fix(core): close auth bypass, hangs and memory leaks found by review

Security:
- An empty API_PASSWORD passed validation (only the literal "changeme" was
  rejected) and verify_password("", "") returned true, so a login with an
  empty password minted an admin token. Require >= 16 characters and >= 32
  non-whitespace bytes for JWT_SECRET; verify rejects an empty stored secret.
- syn_challenge_enabled required a real challenge_secret_hex: the public
  placeholder from config.h is now rejected in every spelling.
- docker-compose: Redis/ClickHouse/Grafana are loopback-only and every
  password uses ${VAR:?} instead of a default. An exposed Redis was a way to
  lift bans and publish unbans to the whole fleet with one redis-cli.
- Empty CORS_ORIGIN no longer means "allow any origin".
- ban_cidr / userspace blacklist validate and mask prefixes; CIDR bans are
  stored as ranges, so a /24 or /64 ban actually covers the subnet (before,
  only the network address was blocked).

Availability:
- ClickHouse client has connect/request timeouts and no mutex held across
  await: a hung analytics backend can no longer freeze the ban path. Events
  go through a bounded buffer with a drop counter.
- Redis uses a ConnectionManager with per-command timeouts; pubsub and
  reconcile reset the backoff after success; publish cannot block shutdown.
- Ban durations from pubsub are clamped and use checked_add; the sync task
  survives panics instead of silently dying.
- Blacklist TOCTOU (remove_if) and replace_redis no longer empties the table
  during a Redis reconnect.
- RateLimiter and reputation have hard caps with incremental eviction instead
  of an unbounded DashMap and a stop-the-world retain.
- The attack detector scores before updating its baseline and needs several
  quiet windows to leave UnderAttack, so a sustained flood keeps banning new
  offenders instead of ending after one tick.
- accept() backs off on EMFILE/ENFILE, shutdown Err is treated as shutdown,
  a global semaphore bounds in-flight connections, rate limiting runs before
  PoW, whitelisted IPs are never banned, and connect/handshake/relay have
  timeouts with an idle budget.
- PoW uses the configured difficulty as a floor, the clamp is enforced, and
  nonce framing survives split segments and coalesced handshake bytes.
- Subnet tracker memory is capped (prefixes and per-prefix sources) and the
  monitor bans with the configured TTL.

CI and docs:
- CI runs the test suite with --no-default-features --features protocol-http;
  make ebpf fails on errors; the secrets gate catches weak compose defaults.
- doctor skips protected endpoints without a token and exits non-zero on
  failure; a drain timeout returns exit code 1.
- TODO §2b records the review findings, what is fixed and what is deferred;
  configuration/testing docs describe the new XDP and secret semantics.
This commit is contained in:
Loki 2026-11-16 12:06:23 +01:00
parent 14dcaccdbf
commit c1a076a4a3
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
57 changed files with 4193 additions and 1171 deletions

View file

@ -92,11 +92,11 @@ max_header_bytes = 512
| Переменная | Обязательна | По умолчанию | Описание |
|------------|-------------|--------------|----------|
| `REDIS_URL` | нет | `redis://127.0.0.1:6379/0` | Хранилище состояния |
| `JWT_SECRET` | да | — | Минимум 32 байта |
| `JWT_SECRET` | да | — | Минимум 32 непробельных байта |
| `JWT_AUDIENCE` | нет | `rampart` | Audience JWT |
| `JWT_EXPIRATION_SECS` | нет | `86400` | Время жизни токена |
| `API_PASSWORD` | да | — | Пароль для `/api/v1/auth/login`; значение `changeme` запрещено |
| `CORS_ORIGIN` | нет | `http://localhost:5173` | CORS; `*` или пусто — разрешить все |
| `API_PASSWORD` | да | — | Пароль для `/api/v1/auth/login`, минимум 16 символов; `changeme` запрещён |
| `CORS_ORIGIN` | нет | — (CORS выключен) | `*` — разрешить все источники; список через запятую; пусто/не задано — запретить cross-origin |
Manager всегда слушает `0.0.0.0:8080`.
@ -136,9 +136,21 @@ clang -O2 -g -target bpf -c xdp/core/universal_filter.c -o /tmp/universal_filter
| `auto_ban_duration_secs` | `300` | Длительность авто-бана |
| `auto_ban_conn_drop_fails` | `3` | Порог `conn->fails` для бана по `EVENT_CONN_DROP` |
| `syn_challenge_enabled` | `false` | RST-challenge (Oubliette liveness proof) |
| `challenge_secret_hex` | плейсхолдер | 128-битный hex-секрет challenge |
| `challenge_secret_hex` | — (обязателен при `syn_challenge_enabled`) | 128-битный hex-секрет, например `openssl rand -hex 8`; встроенный плейсхолдер запрещён |
| `challenge_timeout_ms` | `3000` | TTL pending-challenge |
Поведение XDP-фильтра:
- **Stateless-фильтр, не firewall.** Состояние conntrack ведётся только для TCP-соединений,
начатых с SYN. Пакет без состояния (non-SYN) пропускается: включение фильтра не рвёт
ответы на исходящие соединения самого демона и keep-alive от health-check'ов.
- **VLAN/QinQ** (802.1Q и 802.1ad, до двух тегов) разбираются; **фрагменты** проверяются по
source-IP в blacklist и пропускаются (не дропаются), счётчик — `frag` в `stats_map`.
- **Whitelist** из корневого `whitelist = [...]` загружается в XDP-карты (`whitelist_map`,
`whitelist6_map`) при attach и обходит state machine, throttle и баны.
- **CIDR-баны**: XDP матчит по LPM-трие, userspace — по диапазонам адресов, поэтому бан
`/24` или `/64` покрывает всю подсеть.
Покрытие семейств адресов:
- **IPv4**: blacklist, SYN-throttle, conntrack, RST-challenge, ringbuf-события, `udp_policy`

View file

@ -73,24 +73,34 @@ Paper и закрой backend-порт firewall-ом от всех, кроме R
```bash
export REDIS_URL="redis://127.0.0.1:6379/0"
export JWT_SECRET="$(openssl rand -hex 32)" # минимум 32 байта
export API_PASSWORD="не-changeme" # дефолт запрещён
export JWT_SECRET="$(openssl rand -hex 32)" # минимум 32 байта без пробелов
export API_PASSWORD="$(openssl rand -base64 24)" # минимум 16 символов, дефолт запрещён
cargo run --release --bin rampart-manager
# API на 0.0.0.0:8080
```
Manager refuses to start with an empty `API_PASSWORD`, a password shorter than
16 characters, the default placeholder (which must not be `changeme`), or a
`JWT_SECRET` with fewer than 32 non-whitespace bytes.
Manager listens on all interfaces by default. Permit `8080` only from an admin
VPN or specific admin addresses; do not expose the API to the public Internet.
The same applies to Redis (`6379`) and monitoring endpoints such as Prometheus
(`9090`), ClickHouse (`8123`/`9000`) and Grafana (`3000`). The sample Compose
file publishes ClickHouse and Grafana ports on the host, so restrict them with
the host firewall or change their port bindings before deploying on a public
VDS. Redis has no published host port in that Compose file and is reachable
only by containers on its Docker network unless you deliberately expose it.
files bind published ClickHouse and Grafana ports to `127.0.0.1` only, so reach
them through an SSH tunnel or a local admin session, never through the public
interface. `deploy/docker-compose.yml` publishes no Redis port at all and the
root `docker-compose.yml` binds it to loopback; both refuse to start unless
`REDIS_PASSWORD` and `GRAFANA_PASSWORD` are set. Cross-origin access to the
manager API is disabled unless `CORS_ORIGIN` is set explicitly (`*` or a
comma-separated origin list).
Инфраструктура (Redis, ClickHouse, Grafana):
Инфраструктура (Redis, ClickHouse, Grafana) требует пароли из окружения —
Compose не стартует без них:
```bash
export REDIS_PASSWORD="$(openssl rand -base64 24)"
export GRAFANA_PASSWORD="$(openssl rand -base64 24)"
docker compose up -d redis clickhouse grafana
```
@ -103,6 +113,10 @@ Redis только через private network/VPN; при пустом `redis_ur
## 5. Docker
```bash
# Пароли обязательны: без REDIS_PASSWORD/GRAFANA_PASSWORD Compose падает
export REDIS_PASSWORD="$(openssl rand -base64 24)"
export GRAFANA_PASSWORD="$(openssl rand -base64 24)"
# Образ edge
docker build -f deploy/docker/Dockerfile.edge -t rampart-edge .
@ -110,6 +124,15 @@ docker build -f deploy/docker/Dockerfile.edge -t rampart-edge .
docker compose -f deploy/docker-compose.yml up -d
```
Edge подключается к Redis по имени сервиса. Поскольку Redis в Compose требует
пароль, впиши его в URL конфига edge (`deploy/config/edge-docker.toml`) — тот
же пароль, что в `REDIS_PASSWORD`:
```toml
[store]
redis_url = "redis://:PASSWORD@redis:6379/0"
```
## 6. Проверка после деплоя
```bash