Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb9d98e0a3 | ||
|
|
3a8c7dac2e | ||
|
|
c2611ca8a6 | ||
|
|
ac759c5ba5 |
No files matched your search
@@ -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` проходит.
|
||||
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
|
||||
@@ -57,9 +57,11 @@ private review и чтение старого заказа после перез
|
||||
контракту: каждый доставленный заказ получает cargo. Схема и данные БД не
|
||||
изменялись, поэтому для отката достаточно пересобрать только `api`.
|
||||
|
||||
В `main` остаётся `f09895d`: покупка и checkout требуют
|
||||
`POST /api/promo/invalidate` после начисления promo. Наблюдаемый checker
|
||||
выполняет `credit -> invalidate -> buy/checkout`, поэтому этот gate сохраняется.
|
||||
Требование обязательного `POST /api/promo/invalidate` перед покупкой удалено
|
||||
после ошибки checker `Unexpected HTTP status from /api/products/{id}/buy`.
|
||||
Оно не останавливало адаптивный сплойт, который мог вызвать публичный invalidate,
|
||||
но добавляло несовместимый HTTP 409 в штатный путь. Однократность начисления
|
||||
promo через `credited_at` сохранена.
|
||||
|
||||
## Эксплойт и дальнейшая проверка
|
||||
|
||||
|
||||
@@ -530,9 +530,6 @@ def order_product(product_id):
|
||||
return None, error("product not found", 404)
|
||||
if row["seller_id"] == session["user_id"]:
|
||||
return None, error("cannot buy your own product")
|
||||
cur.execute("SELECT 1 FROM promo_codes WHERE user_id=%s", (session["user_id"],))
|
||||
if cur.fetchone():
|
||||
return None, error("promo code must be invalidated", 409)
|
||||
if row["balance"] < row["price"]:
|
||||
return None, error("insufficient balance", 409)
|
||||
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"]))
|
||||
@@ -558,9 +555,6 @@ def checkout():
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
|
||||
buyer = cur.fetchone()
|
||||
cur.execute("SELECT 1 FROM promo_codes WHERE user_id=%s", (session["user_id"],))
|
||||
if cur.fetchone():
|
||||
return error("promo code must be invalidated", 409)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity
|
||||
|
||||
+6
-4
@@ -8,9 +8,9 @@ The checker creates flag-bearing products priced within the 200-credit budget of
|
||||
|
||||
Incident logs and aggregate database checks confirmed this exact path. The observed attacker used `register -> account -> promo/credit -> direct buy -> orders`, while the checker uses `promo/credit -> promo/invalidate -> cart -> checkout -> orders`.
|
||||
|
||||
The emergency patch requires the buyer to finish the existing promo lifecycle before either direct purchase or checkout. `promo/invalidate` now succeeds only after credit, and both purchase paths return 409 while a promo row remains. Routes, successful response bodies, prices, delivery, existing orders, and cargo retrieval are unchanged. A synthetic route-level regression confirmed that purchase before invalidation is blocked, credit followed by invalidation preserves direct buy and checkout, and an uncredited promo cannot be deleted to bypass the gate.
|
||||
The temporary purchase gate that returned 409 while a promo row remained was removed after the checker reported an unexpected status from `POST /api/products/{id}/buy`. It was not an effective confidentiality boundary because an attacker could call the public invalidate endpoint and reproduce the checker flow. Direct buy and checkout again accept buyers with an uncredited or credited promo row when their balance is sufficient; atomic one-time promo credit remains enforced.
|
||||
|
||||
This is containment for the observed exploit, not a durable confidentiality boundary. An adaptive attacker can call the public invalidate endpoint and reproduce the checker workflow. A permanent fix requires a checker-compatible non-public purchase capability or moving flags out of buyer-deliverable cargo.
|
||||
The cargo disclosure remains open because attacker and checker use the same public purchase workflow. One-time promo credit prevents balance replay but is not a confidentiality boundary. A permanent fix requires a checker-compatible non-public purchase capability or moving flags out of buyer-deliverable cargo.
|
||||
|
||||
### Cross-seller review cursor BOLA
|
||||
|
||||
@@ -38,7 +38,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
|
||||
|
||||
## Affected code before the patch
|
||||
|
||||
- `api/app.py`: `seller_reviews`, `get_contract`, and `credit_promo`.
|
||||
- `api/app.py`: `seller_reviews`, `get_contract`, `credit_promo`, `order_product`, and `checkout`.
|
||||
- `api/database.py`: startup migration removed promo consumption state.
|
||||
- `db/init.sql`: `promo_codes` had no consumption field.
|
||||
|
||||
@@ -47,6 +47,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
|
||||
- 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.
|
||||
- `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.
|
||||
- Direct buy and checkout no longer require deletion of the promo row. This restores the original purchase contract while retaining the one-time credit transition.
|
||||
- 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
|
||||
@@ -54,7 +55,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
|
||||
- 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.
|
||||
- Both `credit -> invalidate -> purchase` and purchase with a remaining promo row are accepted when the buyer has sufficient balance.
|
||||
- No neighboring-service configuration is changed. Secret rotation is isolated to Starpost and keeps the existing variable names consumed by the containers.
|
||||
|
||||
## Verification
|
||||
@@ -65,6 +66,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
|
||||
- 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.
|
||||
- Purchase SLA regression: current `main` reproduced HTTP 409 with an uncredited promo row; the patched PostgreSQL route matrix passed direct buy before credit, direct buy after credit without invalidate, checkout after credit without invalidate, the existing invalidate flow, and preserved insufficient-balance and archived-product errors.
|
||||
- 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.
|
||||
|
||||
Reference in new issue
Block a user