Compare commits

..
Author SHA1 Message Date
scandalist-trash ac759c5ba5 orbital-navigation: block mapped loopback SSRF 2026-10-25 07:07:47 -04:00
4 changed files with 20 additions and 50 deletions

No files matched your search

+3 -2
View File
@@ -10,7 +10,7 @@
- `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.
- Внутренний маршрут `/internal/summaries/{id}` защищался только статическим importer key, который сам сервис добавлял при `import_bulletin`. Проверка URL отбрасывала лишь строковые `localhost`/`127.0.0.1`; loopback-алиас `127.1` разрешал SSRF и чтение чужой summary. После первого исправления оставался обход через IPv4-mapped IPv6: разрешённый резолвером `::ffff:127.0.0.1` не считался IPv6 loopback, но подключался к IPv4 loopback. Прямой запрос с известным ключом также не ограничивался loopback peer.
- После `approve_package` содержимое пакета можно было заменить через повторный `PUT`, не сбрасывая approval. `generate_report` распаковывал уже заменённый TAR без повторной безопасной проверки и разрешал canonical target внутри общего `navigation`, поэтому symlink-entry мог прочитать файл навигации другого пользователя.
Ожидаемые источники флагов до исправления: сообщения корабля, manifest полёта, content summary и файлы `navigation/{flight_id}.txt`. Для воспроизведения нужны только публичные маршруты сервиса, обычные учётные записи и идентификаторы объектов; реальные флаги, игровые токены и чужие адреса здесь не используются.
@@ -24,7 +24,7 @@
- Проверка владельца добавлена при привязке и чтении источника, смене корабля профиля и выполнении export job. При загрузке состояния удаляются cross-owner source aliases, а результаты export jobs с нарушенной цепочкой владения очищаются.
- В cache key добавлен владелец; при загрузке состояния кэш безопасно перестраивается для существующих полётов.
- Делегируемые права теперь обязаны быть подмножеством родительских; оба срока должны быть действующими, а дочерний срок не может превышать родительский. `read_manifest` проверяет expiry. При загрузке удаляются просроченные и legacy grants с правами, которые нельзя получить через штатный `grant_geometry`.
- Internal summary требует одновременно loopback peer и importer key. `fetch_bulletin` запрещает любой адрес, который после DNS-разрешения является loopback или unspecified, включая `0.0.0.0` и каждый redirect.
- Internal summary требует одновременно loopback peer и importer key. `fetch_bulletin` канонизирует IPv4-mapped IPv6 после DNS-разрешения и запрещает loopback или unspecified адрес перед каждым соединением, включая redirects.
- Любая повторная загрузка package сбрасывает approval. Перед распаковкой пакет снова проходит `validate_safe_tar`, а attachment обязан оставаться внутри индивидуального work-каталога.
## Проверки
@@ -33,6 +33,7 @@
- На исходной версии все шесть классов проблем воспроизведены с синтетическими данными; 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.
- Дополнительная baseline-vs-patch проверка настоящих бинарников воспроизвела на `f09895d` SSRF через `0.0.0.0`, чтение через сохранённый cross-owner alias, legacy `manifest.read` grant и poisoned export result. Исправленная версия блокирует все четыре пути, сохраняя owner reads, легитимный alias, subset-delegation и корректный завершённый export job.
- Отдельная synthetic runtime-проверка воспроизвела обход через IPv4-mapped IPv6 на `5d2407b`. После канонизации блокируются dotted/hex mapped loopback и mapped unspecified, включая переход через разрешённый redirect; обычный import с non-loopback HTTP endpoint сохраняет исходное содержимое.
- `cargo check --locked` и `cargo test --locked` проходят; проект не содержит встроенных unit-тестов.
- `git diff --check` проходит.
+2 -1
View File
@@ -841,7 +841,8 @@ impl Server {
.map_err(|e| format!("resolve {host}:{port}: {e}"))?
.next()
.ok_or("no address")?;
if addr.ip().is_loopback() || addr.ip().is_unspecified() {
let ip = addr.ip().to_canonical();
if ip.is_loopback() || ip.is_unspecified() {
return Err("internal source forbidden".into());
}
+13 -37
View File
@@ -3,10 +3,9 @@ import hashlib
import hmac
import json as _json
import os
import re
import secrets
from datetime import datetime, timezone
from functools import lru_cache, wraps
from functools import wraps
import psycopg
from flask import Flask, jsonify, request, send_file, session
@@ -28,8 +27,6 @@ app.config.update(
MAX_CONTENT_LENGTH=32 * 1024,
)
CONTRACT_FILENAME_RE = re.compile(r"contract-([0-9]+)-[0-9a-f]{16}\.pdf")
migrate()
@@ -53,21 +50,6 @@ def text(value, field, minimum=1, maximum=200):
return value.strip()
def own_contract_filename(filename, user_id):
match = CONTRACT_FILENAME_RE.fullmatch(filename)
return match is not None and match.group(1) == str(user_id)
@lru_cache(maxsize=4096)
def contract_owner(user_id):
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT id,contract_file FROM users WHERE id=%s", (user_id,))
owner = cur.fetchone()
if not owner:
return None
return owner["id"], owner["contract_file"]
def auth(role=None):
def decorator(handler):
@wraps(handler)
@@ -718,31 +700,23 @@ def seller_reviews():
@app.route("/api/contract", methods=["GET", "POST"])
@auth("seller")
def get_contract():
requested = request.args.get("file")
if request.method == "GET" and requested:
requested = requested.strip()
own_alias = f"contract-{session['user_id']}"
if requested != own_alias and not own_contract_filename(requested, session["user_id"]):
return error("contract not found", 404)
contract_id = None
if request.method == "POST":
contract_id = request.headers.get("X-Contract-Id", "").strip()
if not re.fullmatch(r"\d+", contract_id) or contract_id != str(session["user_id"]):
return error("invalid contract id", 400)
owner = contract_owner(session["user_id"])
if not owner or not owner[1]:
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)
owner_id, filename = owner
if not own_contract_filename(filename, owner_id):
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":
import re
contract_id = request.headers.get("X-Contract-Id", "").strip()
if not re.fullmatch(r"\d+", contract_id) or contract_id != str(owner["id"]):
return error("invalid contract id", 400)
try:
path.unlink()
except FileNotFoundError:
@@ -751,8 +725,10 @@ def get_contract():
return error("contract deletion failed", 500)
return jsonify(status="deleted", deleted=1)
requested = request.args.get("file")
if requested:
if requested not in {filename, f"contract-{owner_id}"}:
raw = requested.strip()
if raw not in {filename, f"contract-{owner['id']}"}:
return error("contract not found", 404)
if not path.is_file():
return error("contract not found", 404)
+2 -10
View File
@@ -24,12 +24,6 @@ Before the patch, a seller could request `GET /api/contract?file=contract-<other
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.
### Contract probe worker and database exhaustion
The provided capture showed sustained authenticated `GET /api/contract` probes at modest bandwidth. Before this patch, each foreign alias reached a new PostgreSQL connection and owner query before returning the existing 404 response. Concurrent probes could therefore occupy all synchronous API threads and delay normal registration and health requests.
The route now rejects foreign aliases, malformed filenames, and foreign deletion IDs before opening PostgreSQL. Repeated legitimate reads use a bounded process-local cache for the seller's immutable contract metadata. Existing routes, response formats, no-query reads, empty `file` reads, exact stored filenames, the own-ID alias, and own-contract deletion are preserved. No nginx, IP, URI, rate-limit, or other traffic filter was added, and no DoS sploit was created.
### 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.
@@ -45,7 +39,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## 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 validates ownership-shaped input before database access, 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. A bounded cache avoids repeated owner lookups for immutable contract metadata. GET without `file`, GET with an empty `file`, GET with the exact stored filename, and the own-ID alias remain supported.
- 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.
@@ -63,7 +57,6 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
- 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.
- Contract exhaustion regression: the pinned baseline-versus-patch matrix confirmed that foreign GET and POST probes no longer touch the database, repeated valid reads perform at most one owner lookup per process, and all preserved GET forms remain byte-identical. A separate PostgreSQL 16 integration run passed registration, login, current/get-old reads, foreign rejection, and own deletion.
- 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.
@@ -92,7 +85,6 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## 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 service-container rebuild, persistent-volume get-old, and checker status were not tested. The PostgreSQL route integration used a temporary database initialized from `db/init.sql` and synthetic contract files.
- The contract metadata cache is process-local. If an operator manually changes or restores `users.contract_file`, restart the API workers before verification so they reload that metadata.
- 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.