lighthouse: add local fixes and exploit tooling

This commit is contained in:
shira committed 2026-10-25 10:56:50 +03:00
1 parent 21a8646fd9
commit 8987f08ee1
11 files changed
+935 -30

No files matched your search

+1 -1
View File
@@ -29,7 +29,7 @@ RUN /bin/sh ./server/build.sh
COPY --from=web /web/dist ./public/
RUN mkdir -p /data /var/log/lighthouse /srv/lighthouse/work \
&& chmod 0700 /data \
&& chmod 0755 /var/log/lighthouse \
&& chmod 0700 /var/log/lighthouse \
&& chmod 0711 /srv/lighthouse/work
EXPOSE 8080
CMD ["/srv/lighthouse/server/lighthouse"]
+15
View File
@@ -0,0 +1,15 @@
# Lighthouse: статус кандидата на 25.10.2026
Исходный сервис: `takuya/go-ctf`, `main`, commit `4f70df55dd822880f4759d553f7ed249166cad86`. Этот каталог содержит локально проверенный кандидат исправлений; push исходников **не является выкладкой** на игровую vulnbox.
- L-02: загрузка фильтра требует `X-Queue-Key`; браузер передаёт ключ.
- L-03: чтение сообщений выдаёт страницы по 128 и помечает прочитанными только выданные записи.
- L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище.
- L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его.
- L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными.
На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Официальный checker и игровой том не проверены. Изменения контракта `POST /filter` и чтения более 128 сообщений требуют отдельной проверки CHECK/PUT/GET перед выкладкой.
**Известный риск DOWN:** Dockerfile устанавливает Debian bookworm `libcpp-httplib-dev` / `libcpp-httplib0.11` версии `0.11.4+ds-1+deb12u1`. [Debian Security Tracker](https://security-tracker.debian.org/tracker/CVE-2026-45352) отмечает эту версию уязвимой к CVE-2026-45352 (отказ в обслуживании при некорректном chunked-запросе); [описание разработчика](https://github.com/yhirose/cpp-httplib/security/advisories/GHSA-h6wq-j5mv-f3q8) указывает исправление в 0.43.4. Кроме того, [Debian Security Tracker](https://security-tracker.debian.org/tracker/CVE-2025-53628) помечает ту же bookworm-сборку уязвимой к CVE-2025-53628: неограниченная длина строки HTTP-запроса может вызвать расход памяти и отказ в обслуживании до обработки запроса приложением. Лимит `set_payload_max_length(32768)` ограничивает тело, а не эту строку; более того, [CVE-2025-46728](https://security-tracker.debian.org/tracker/CVE-2025-46728) позволяет обойти и сам лимит тела через chunked-запрос в этой версии `cpp-httplib`. Данный кандидат эти риски не устраняет. Перед игровым переключением нужна отдельная проверенная замена зависимости и тесты совместимости; простой `apt upgrade` внутри bookworm не подтверждает исправление.
В этом же приватном репозитории находится `sploits/lighthouse/`. Полный clone/pull на vulnbox принесёт и атакующий код. При подготовке выкладки переносите только нужный каталог сервиса; не монтируйте `sploits/` в контейнер и не помещайте его в web root. Для отката сохраняйте тома данных: не используйте `compose down -v`.
+26 -5
View File
@@ -12,7 +12,7 @@ createApp({
const source = ref('int filter(int length) {\n return length <= 4096;\n}');
const filterLabel = ref('unnamed'), revision = ref('');
const selectedFilter = ref(null);
const received = ref([]), filters = ref([]);
const received = ref([]), filters = ref([]), nextAfter = ref(0), pageShowRead = ref(false);
const state = ref(null), view = ref('messages'), showRead = ref(false);
const feedback = ref({}), compiler = ref(''), listing = ref('');
const path = suffix => '/api/queues/' + queue.value + suffix;
@@ -52,6 +52,7 @@ createApp({
state.value = created;
recipient.value = created.id;
received.value = [];
nextAfter.value = 0;
filters.value = [];
selectedFilter.value = null;
view.value = 'messages';
@@ -67,6 +68,7 @@ createApp({
state.value = info;
recipient.value = id;
received.value = [];
nextAfter.value = 0;
filters.value = [];
selectedFilter.value = null;
view.value = 'messages';
@@ -78,6 +80,7 @@ createApp({
pass.value = '';
state.value = null;
received.value = [];
nextAfter.value = 0;
filters.value = [];
selectedFilter.value = null;
compiler.value = '';
@@ -105,6 +108,8 @@ createApp({
const receive = () => action('receive', async () => {
await refresh();
const result = await api(path('/messages' + (showRead.value ? '?show_read=true' : '')), { headers: headers() });
pageShowRead.value = showRead.value;
nextAfter.value = result.has_more ? result.next_after : 0;
received.value = result.messages.map(message => {
try {
return { id: message.id, topic: message.topic, text: decrypt(key.value, message.ciphertext) };
@@ -115,6 +120,21 @@ createApp({
await refresh();
return result.messages.length ? result.messages.length + ' message(s) displayed.' : 'No messages to display.';
});
const loadMore = () => action('receive', async () => {
if (!nextAfter.value) return 'No more messages.';
const suffix = '/messages?after_id=' + nextAfter.value + (pageShowRead.value ? '&show_read=true' : '');
const result = await api(path(suffix), { headers: headers() });
nextAfter.value = result.has_more ? result.next_after : 0;
received.value.push(...result.messages.map(message => {
try {
return { id: message.id, topic: message.topic, text: decrypt(key.value, message.ciphertext) };
} catch {
return { id: message.id, topic: message.topic, text: 'Cannot open this message.' };
}
}));
await refresh();
return result.messages.length + ' more message(s) displayed.';
});
const loadFilters = () => action('refreshFilters', async () => {
filters.value = (await api(path('/filters'))).filters;
return 'Revision list updated.';
@@ -137,7 +157,7 @@ createApp({
compiler.value = '';
listing.value = '';
const result = await api(path('/filter'), {
method: 'POST', body: JSON.stringify({ source: source.value, label: filterLabel.value })
method: 'POST', headers: headers(), body: JSON.stringify({ source: source.value, label: filterLabel.value })
}, [422]);
compiler.value = result.compiler || '';
listing.value = result.listing || '';
@@ -165,9 +185,9 @@ createApp({
return {
queue, pass, recipient, queueLabel, retention, topic, delay, text,
source, filterLabel, revision, selectedFilter, received, filters, state, view, showRead,
source, filterLabel, revision, selectedFilter, received, filters, state, view, showRead, nextAfter,
feedback, compiler, listing, credentials,
create, open, leave, send, receive, loadFilters, selectFilter, newDraft, draftFrom, install, activate
create, open, leave, send, receive, loadMore, loadFilters, selectFilter, newDraft, draftFrom, install, activate
};
},
template: `
@@ -218,7 +238,8 @@ createApp({
<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="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 class="panel">
<p class="eyebrow">OUTBOX</p><h2>Send a message</h2>
+9 -3
View File
@@ -1,5 +1,6 @@
#pragma once
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <mutex>
@@ -15,13 +16,18 @@ inline void append(const std::string& created_at, const std::string& queue,
std::lock_guard guard(lock);
auto directory = std::filesystem::path("/var/log/lighthouse") / created_at.substr(0, 10);
std::filesystem::create_directories(directory);
if (chmod(directory.c_str(), 0755) != 0)
if (chmod(directory.c_str(), 0700) != 0)
throw std::runtime_error("cannot secure journal directory");
auto path = directory / (queue + ".log");
std::ofstream file(path, std::ios::app);
if (!file || chmod(path.c_str(), 0644) != 0)
if (!file || chmod(path.c_str(), 0600) != 0)
throw std::runtime_error("cannot open journal");
file << instant << " queue=" << queue << " topic=" << topic << " ciphertext=" << cipher << "\n";
const auto line = instant + " queue=" + queue + " topic=" + topic + " ciphertext=" + cipher + "\n";
const auto position = file.tellp();
if (position < 0) throw std::runtime_error("cannot size journal");
constexpr std::uintmax_t max_journal_bytes = 512 * 1024;
if (static_cast<std::uintmax_t>(position) + line.size() > max_journal_bytes) return;
file << line;
file.close();
if (!file) throw std::runtime_error("cannot write journal");
}
+60 -21
View File
@@ -9,6 +9,7 @@
#include <filesystem>
#include <iostream>
#include <charconv>
#include <mutex>
#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)}};
}
// Expired rows are already invisible to readers. Reclaim a bounded batch on
// each public write so cleanup cannot hold the shared database lock for long.
static void prune_expired() {
Statement prune(db, R"SQL(
DELETE FROM messages WHERE id IN (
SELECT id FROM messages WHERE expires_at<=? ORDER BY expires_at LIMIT 256
)
)SQL");
prune.bind(1, epoch_now()).next();
}
static long long after_id(const httplib::Request& request) {
if (!request.has_param("after_id")) return 0;
const auto value = request.get_param_value("after_id");
long long parsed = 0;
const auto result = std::from_chars(value.data(), value.data() + value.size(), parsed);
if (value.empty() || result.ec != std::errc{} || result.ptr != value.data() + value.size() || parsed < 0)
throw HttpError(400, "bad after_id");
return parsed;
}
static void initialize() {
fs::create_directories("/data");
fs::create_directories("/var/log/lighthouse");
fs::create_directories(filters::work_root);
if (chmod("/data", 0700) || chmod("/var/log/lighthouse", 0755) ||
if (chmod("/data", 0700) || chmod("/var/log/lighthouse", 0700) ||
chmod(filters::work_root, 0711))
throw std::runtime_error("cannot set storage permissions");
if (sqlite3_open("/data/lighthouse.db", &db) != SQLITE_OK)
@@ -84,6 +106,7 @@ static void initialize() {
listing TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS messages_by_queue ON messages(queue_id,id);
CREATE INDEX IF NOT EXISTS messages_by_expiry ON messages(expires_at);
CREATE INDEX IF NOT EXISTS revisions_by_queue ON filter_revisions(queue_id,id DESC);
)SQL");
bool has_read_at = false;
@@ -112,6 +135,7 @@ static void queue_routes(httplib::Server& server) {
auto retention = number_field(body, "retention_seconds", 3600, 60, 604800);
auto id = uuid(), key = random_hex(48), created = utc_now();
std::lock_guard guard(db_lock);
prune_expired();
Statement insert(db, "INSERT INTO queues(id,read_key,label,retention_seconds,created_at) VALUES(?,?,?,?,?)");
insert.bind(1, id).bind(2, key).bind(3, label).bind(4, retention).bind(5, created).next();
reply(response, 201, {{"id", id}, {"read_key", key}, {"label", label},
@@ -146,6 +170,7 @@ static void filter_routes(httplib::Server& server) {
{
std::lock_guard guard(db_lock);
require_queue(id);
require_key(request);
}
auto artifact = filters::compile(source);
auto state = artifact.ready ? "ready" : "rejected";
@@ -153,6 +178,8 @@ static void filter_routes(httplib::Server& server) {
{
std::lock_guard guard(db_lock);
Transaction transaction(db);
require_queue(id);
require_key(request);
Statement insert(db, R"SQL(
INSERT INTO filter_revisions(queue_id,label,state,wasm_path,compiler_output,source,listing,created_at)
VALUES(?,?,?,?,?,?,?,?)
@@ -263,8 +290,7 @@ static void message_routes(httplib::Server& server) {
{
std::lock_guard guard(db_lock);
Transaction transaction(db);
Statement prune(db, "DELETE FROM messages WHERE queue_id=? AND expires_at<=?");
prune.bind(1, id).bind(2, epoch_now()).next();
prune_expired();
Statement insert(db, R"SQL(
INSERT INTO messages(queue_id,ciphertext,topic,not_before,expires_at,created_at) VALUES(?,?,?,?,?,?)
)SQL");
@@ -279,27 +305,40 @@ static void message_routes(httplib::Server& server) {
server.Get(R"(/api/queues/([0-9a-f-]{36})/messages)", endpoint([](const auto& request, auto& response) {
auto show_read = request.has_param("show_read") && request.get_param_value("show_read") == "true";
std::lock_guard guard(db_lock);
require_key(request);
auto moment = epoch_now();
Transaction transaction(db);
Statement query(db, R"SQL(
SELECT id,topic,ciphertext FROM messages
WHERE queue_id=? AND not_before<=? AND expires_at>?
AND (? OR read_at IS NULL) ORDER BY id
)SQL");
query.bind(1, request.matches[1].str()).bind(2, moment).bind(3, moment).bind(4, show_read ? 1LL : 0LL);
auto after = after_id(request);
constexpr long long page_size = 128;
auto messages = json::array();
while (query.next()) messages.push_back(message_row(query));
if (!show_read) {
Statement mark(db, R"SQL(
UPDATE messages SET read_at=? WHERE queue_id=? AND not_before<=?
AND expires_at>? AND read_at IS NULL
bool has_more = false;
long long last = after;
{
std::lock_guard guard(db_lock);
require_key(request);
auto moment = epoch_now();
Transaction transaction(db);
Statement query(db, R"SQL(
SELECT id,topic,ciphertext FROM messages
WHERE queue_id=? AND id>? AND not_before<=? AND expires_at>?
AND (? OR read_at IS NULL) ORDER BY id LIMIT ?
)SQL");
mark.bind(1, moment).bind(2, request.matches[1].str()).bind(3, moment).bind(4, moment).next();
query.bind(1, request.matches[1].str()).bind(2, after).bind(3, moment)
.bind(4, moment).bind(5, show_read ? 1LL : 0LL).bind(6, page_size + 1);
while (query.next()) {
if (messages.size() == page_size) { has_more = true; break; }
last = query.number(0);
messages.push_back(message_row(query));
}
if (!show_read && !messages.empty()) {
Statement mark(db, R"SQL(
UPDATE messages SET read_at=? WHERE queue_id=? AND id>? AND id<=?
AND not_before<=? AND expires_at>? AND read_at IS NULL
)SQL");
mark.bind(1, moment).bind(2, request.matches[1].str()).bind(3, after)
.bind(4, last).bind(5, moment).bind(6, moment).next();
}
transaction.commit();
}
transaction.commit();
reply(response, 200, {{"messages", messages}});
reply(response, 200, {{"messages", messages}, {"has_more", has_more},
{"next_after", has_more ? last : 0}});
}));
}
+209
View File
@@ -0,0 +1,209 @@
#!/usr/bin/env python3
"""Loopback-only smoke tests using disposable containers and synthetic records."""
import argparse
import base64
import json
import os
from pathlib import Path
import re
import subprocess
import urllib.error
import urllib.parse
import urllib.request
SOURCE = "int filter(int length) { return length <= 8192; }"
OLD_JOURNAL = "/var/log/lighthouse/1999-12-31/synthetic-legacy.log"
OLD_CONTENT = "synthetic legacy journal; retain these bytes\n"
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("seed", "verify"))
parser.add_argument("--url", required=True)
parser.add_argument("--container", required=True)
parser.add_argument("--state", type=Path, required=True)
parser.add_argument("--journal", choices=("baseline", "private"), required=True)
args = parser.parse_args()
parsed = urllib.parse.urlsplit(args.url)
if (parsed.scheme != "http" or parsed.hostname not in ("127.0.0.1", "localhost", "::1")
or parsed.username or parsed.password or parsed.query or parsed.fragment):
parser.error("tests only accept an explicit loopback HTTP URL")
if not re.fullmatch(r"goctf-lighthouse-lab-[a-z0-9-]+", args.container):
parser.error("use a disposable container named goctf-lighthouse-lab-...")
origin = args.url.rstrip("/")
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
checks = 0
def check(condition, message):
nonlocal checks
if not condition:
raise AssertionError(message)
checks += 1
def api(method, path, body=None, key=None, expected=200):
headers = {"Content-Type": "application/json"}
if key is not None:
headers["X-Queue-Key"] = key
request = urllib.request.Request(origin + path, method=method, headers=headers,
data=None if body is None else json.dumps(body).encode())
try:
response = opener.open(request, timeout=12)
except urllib.error.HTTPError as error:
response = error
with response:
status = response.status
result = json.loads(response.read())
check(status == expected, f"unexpected HTTP status for {method} {path}: {status}")
return result
def inside(*command, user=None):
command_line = ["docker", "exec"]
if user:
command_line.extend(("--user", user))
return subprocess.run(command_line + [args.container, *command],
capture_output=True, text=True, timeout=15)
def mode(path):
result = inside("stat", "-c", "%a", path)
check(result.returncode == 0, "cannot inspect synthetic journal permissions")
return result.stdout.strip()
check(api("GET", "/api/health")["status"] == "ok", "health response changed")
if args.action == "seed":
check(not args.state.exists(), "refusing to overwrite a previous test state")
queue = api("POST", "/api/queues", {"label": "regression mailbox", "retention_seconds": 3600},
expected=201)
check(bool(re.fullmatch(r"[0-9a-f-]{36}", queue["id"])), "invalid generated queue ID")
check(bool(re.fullmatch(r"[0-9a-f]{48}", queue["read_key"])), "invalid generated read key")
path = "/api/queues/" + queue["id"]
other = api("POST", "/api/queues", {"label": "other mailbox"}, expected=201)
api("GET", path + "/messages", expected=403)
api("GET", path + "/messages", key=other["read_key"], expected=403)
api("POST", path + "/messages", {"message": "not-base64"}, expected=400)
api("POST", path + "/messages", {"message": "eA==", "topic": "invalid/topic"}, expected=400)
compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "length filter"})
check(compiled["ok"] is True, "ordinary C filter did not compile")
api("POST", path + f"/filters/{compiled['revision']}/activate", {}, expected=403)
api("POST", path + f"/filters/{compiled['revision']}/activate", {}, key=queue["read_key"])
api("GET", path + f"/filters/{compiled['revision']}", expected=403)
rejected = api("POST", path + "/filter", {"source": "int filter(int x) { return ; broken }"},
expected=422)
check(rejected["ok"] is False and bool(rejected["compiler"]), "compiler diagnostics missing")
raw = b"synthetic regression message\x00with binary data"
api("POST", path + "/messages", {"message": base64.b64encode(raw).decode(), "topic": "regression"},
expected=201)
received = api("GET", path + "/messages", key=queue["read_key"])["messages"]
check(len(received) == 1 and received[0]["topic"] == "regression", "normal delivery failed")
check(bool(re.fullmatch(r"[0-9a-f]+", received[0]["ciphertext"])), "ciphertext encoding changed")
check(api("GET", path + "/messages", key=queue["read_key"])["messages"] == [],
"reading did not mark the message")
journal = f"/var/log/lighthouse/{queue['created_at'][:10]}/{queue['id']}.log"
create_old = inside("sh", "-c", 'mkdir -p /var/log/lighthouse/1999-12-31 && '
'printf "%s\\n" "synthetic legacy journal; retain these bytes" '
'> /var/log/lighthouse/1999-12-31/synthetic-legacy.log && '
'chmod 755 /var/log/lighthouse/1999-12-31 && '
'chmod 644 /var/log/lighthouse/1999-12-31/synthetic-legacy.log')
check(create_old.returncode == 0, "cannot prepare synthetic legacy journal")
state = {"queue": queue, "revision": compiled["revision"], "message": received[0], "journal": journal}
args.state.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
descriptor = os.open(args.state, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, "w") as stream:
json.dump(state, stream)
else:
state = json.loads(args.state.read_text())
queue = state["queue"]
path = "/api/queues/" + queue["id"]
metadata = api("GET", path)
check(metadata["label"] == "regression mailbox" and metadata["filter_installed"],
"queue metadata or active filter was lost")
messages = api("GET", path + "/messages?show_read=true", key=queue["read_key"])["messages"]
check(state["message"] in messages, "old message or ciphertext changed across restart")
check(api("GET", path + "/messages", key=queue["read_key"])["messages"] == [],
"old read_at state was not retained")
details = api("GET", path + f"/filters/{state['revision']}", key=queue["read_key"])
check(details["source"] == SOURCE and details["active"], "old filter was not retained")
api("GET", path + "/messages?show_read=true", key="0" * 48, expected=403)
api("POST", path + "/messages", {"message": "bmV3IHN5bnRoZXRpYyBtZXNzYWdl"}, expected=201)
check(len(api("GET", path + "/messages", key=queue["read_key"])["messages"]) == 1,
"old active filter rejected a normal new message")
api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"}, expected=403)
api("POST", "/api/queues/00000000-0000-0000-0000-000000000000/filter",
{"source": SOURCE, "label": "missing queue"}, expected=404)
api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"},
key="0" * 48, expected=403)
compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"},
key=queue["read_key"])
check(compiled["ok"] is True, "compilation contract changed after restart")
paging = api("POST", "/api/queues", {"label": "pagination regression"}, expected=201)
paging_path = "/api/queues/" + paging["id"] + "/messages"
for index in range(130):
api("POST", paging_path, {"message": "eA==", "topic": "page"}, expected=201)
first = api("GET", paging_path, key=paging["read_key"])
check(len(first["messages"]) == 128 and first["has_more"], "first page boundary changed")
check(first["next_after"] == first["messages"][-1]["id"], "first page cursor changed")
second = api("GET", paging_path + "?after_id=" + str(first["next_after"]),
key=paging["read_key"])
check(len(second["messages"]) == 2 and not second["has_more"],
"unread messages beyond first page were lost")
check(second["messages"][0]["id"] > first["messages"][-1]["id"],
"page order changed")
check(api("GET", paging_path, key=paging["read_key"])["messages"] == [],
"paged read did not mark exactly the delivered messages")
check(len(api("GET", paging_path + "?show_read=true", key=paging["read_key"])["messages"]) == 128,
"history page changed")
api("GET", paging_path + "?after_id=-1", key=paging["read_key"], expected=400)
api("GET", paging_path + "?after_id=9223372036854775808", key=paging["read_key"], expected=400)
expiring = api("POST", "/api/queues", {"label": "expired cleanup"}, expected=201)
expiring_path = "/api/queues/" + expiring["id"]
api("POST", expiring_path + "/messages", {"message": "eA=="}, expected=201)
updated = inside("sqlite3", "/data/lighthouse.db",
"UPDATE messages SET expires_at=0 WHERE queue_id='" + expiring["id"] + "'")
check(updated.returncode == 0, "cannot prepare synthetic expired row")
api("POST", "/api/queues", {"label": "cleanup trigger"}, expected=201)
check(api("GET", expiring_path)["stored_count"] == 0,
"expired rows were not reclaimed by a public write")
capped = api("POST", "/api/queues", {"label": "bounded journal"}, expected=201)
capped_path = "/api/queues/" + capped["id"]
encoded = base64.b64encode(b"x" * 4096).decode()
for index in range(68):
api("POST", capped_path + "/messages", {"message": encoded}, expected=201)
journal_path = f"/var/log/lighthouse/{capped['created_at'][:10]}/{capped['id']}.log"
journal_size = inside("stat", "-c", "%s", journal_path)
check(journal_size.returncode == 0 and 0 < int(journal_size.stdout) <= 512 * 1024,
"journal exceeded the per-queue cap")
check(api("GET", capped_path)["stored_count"] == 68,
"journal cap dropped messages from SQLite")
old = inside("cat", OLD_JOURNAL)
check(old.returncode == 0 and old.stdout == OLD_CONTENT, "legacy journal bytes were altered")
diagnostic = api("POST", path + "/filter", {
"source": '#include "' + OLD_JOURNAL + '"\nint filter(int length) { return 1; }',
"label": "synthetic journal regression",
}, key=queue["read_key"] if args.action == "verify" else None, expected=422)["compiler"]
check((OLD_CONTENT.strip() in diagnostic) == (args.journal == "baseline"),
"unexpected disclosure of the synthetic journal through compiler diagnostics")
incbin = '__asm__(".incbin \\"' + OLD_JOURNAL + '\\",0,32");\nint filter(int length) { return 1; }'
compiled_bytes = api("POST", path + "/filter", {
"source": incbin, "label": "synthetic incbin regression",
}, key=queue["read_key"] if args.action == "verify" else None,
expected=422 if args.journal == "private" else 200)
check(compiled_bytes["ok"] == (args.journal == "baseline"),
"unexpected journal embedding result")
expected = "700" if args.journal == "private" else "755"
check(mode("/var/log/lighthouse") == expected, "unexpected journal root permissions")
for journal in (state["journal"], OLD_JOURNAL):
result = inside("test", "-r", journal, user="nobody")
check((result.returncode != 0) == (args.journal == "private"),
"unexpected unprivileged access to a synthetic journal")
if args.journal == "private":
check(mode(str(Path(state["journal"]).parent)) == "700", "new journal directory is not private")
check(mode(state["journal"]) == "600", "new journal file is not private")
print(f"PASS: {checks} checks ({args.action}, journal={args.journal}); no record values printed")
if __name__ == "__main__":
main()