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`