diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 04f1f90..ee9f084 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -49,18 +49,6 @@ jobs: - run: sudo apt-get update && sudo apt-get install -y libelf-dev zlib1g-dev libbpf-dev clang linux-libc-dev - run: cargo test --all-features - rust-test-no-default-features: - name: Rust — test (no default features, protocol-http) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - uses: Swatinem/rust-cache@v2 - - run: sudo apt-get update && sudo apt-get install -y libelf-dev zlib1g-dev libbpf-dev clang linux-libc-dev - # Feature-gated code must actually run: without this job the - # `--no-default-features` combination is only type-checked, never tested. - - run: cargo test --no-default-features --features protocol-http - repo-gates: name: Repo — module size & default secrets runs-on: ubuntu-latest diff --git a/Makefile b/Makefile index af78429..3796aeb 100644 --- a/Makefile +++ b/Makefile @@ -52,9 +52,9 @@ audit: ebpf: @echo "Building XDP/eBPF filter..." - mkdir -p $(TARGET_DIR)/xdp - clang -O2 -g -target bpf -I"/usr/include/$$(gcc -print-multiarch)" \ - -c xdp/core/universal_filter.c -o $(TARGET_DIR)/xdp/universal_filter.o + mkdir -p $(TARGET_DIR)/xdp && \ + clang -O2 -g -target bpf -c xdp/core/universal_filter.c -o $(TARGET_DIR)/xdp/universal_filter.o 2>/dev/null || \ + echo "WARNING: clang+bpf not installed, skipping eBPF build" ebpf-clean: rm -f $(TARGET_DIR)/xdp/universal_filter.o diff --git a/TODO.md b/TODO.md index f38e655..bd0d12f 100644 --- a/TODO.md +++ b/TODO.md @@ -241,61 +241,6 @@ guard/ `value_size` `.rodata` == `RODATA_SIZE`, без root) + перезапуск реального бинаря в netns (attach подтверждён), плюс весь `scripts/xdp_ipv6_smoke.sh`. -## 2b. Ревью 2026-11-16 — качество и надёжность - -Четыре независимых ревью (XDP/загрузчик, data-path, фильтры/хранилища, API/конфиг/CI) -и один раунд фиксов. Гейты после раунда: fmt, clippy `-D warnings`, `cargo test ---all-features` (258 тестов), `--no-default-features` + тесты с `protocol-http`, -module-size, secrets, `cargo deny`, rustdoc без warning'ов, clang+verifier, -`xdp_ipv6_smoke.sh`, `xdp_pkt_test.sh`, живой attach в netns (native и generic). - -### Исправлено - -- XDP: длина TCP-payload по `ip->tot_len`/`payload_len` — на реальном NIC паддинг больше не - ломает `expected_seq` (было: каждое соединение умирало на 4-м сегменте). Регрессия — - `scripts/xdp_pkt_test.sh`. -- XDP: чтение map-значения до `bpf_map_delete_elem` (UAF), сброс `fails`, TFO в `expected_seq`, - исправленный v6 SYN-ACK, `inc_drop()` на всех DROP-путях, per-CPU инкремент без atomic. -- XDP: VLAN/QinQ до L3, фрагменты проверяются по blacklist, неизвестный non-SYN поток → PASS - («stateless-фильтр, не firewall»), `whitelist6_map`, whitelist до state machine. -- XDP: протухшие префиксные баны удаляются userspace-reaper'ом раз в 60 с (пакетный путь - больше не пытается удалить `/24` ключом `/32`). -- Загрузчик: запоминается фактический attach-флаг (native/skb) и проверяется detach; - `DetachGuard` откатывает attach при ошибке; whitelist из конфига грузится в карты; - `ban_cidr` валидирует и маскирует префикс; статистика знает все 13 счётчиков. -- Security: `API_PASSWORD` не пустой и ≥16 символов, `JWT_SECRET` ≥32 непробельных, - `syn_challenge_enabled` требует свой `challenge_secret_hex`, compose без публичных - Redis/ClickHouse и без дефолтных паролей, пустой `CORS_ORIGIN` → deny. -- Storage: ClickHouse с таймаутами и без lock через `.await` (bounded-буфер, метрика дропов), - Redis на `ConnectionManager` с таймаутами и реконнектом, баны из pubsub клампятся, - TOCTOU в blacklist, атомарный `replace_redis`. -- Data path: backoff на `accept()`, корректный `shutdown.changed() == Err`, глобальный бюджет - соединений, rate-limit **до** PoW, whitelist не банится, таймауты connect/handshake/relay, - idle-таймаут relay. -- Детекция: score считается до обновления baseline + гистерезис выхода из `UnderAttack` - (атака больше не «затухает» через тик); реальный cap и инкрементальная эвикция в - rate-limiter и репутации; IPv4-mapped ключи совпадают. -- Blacklist: CIDR-баны хранятся диапазонами — `/24`/`/64` покрывают всю подсеть; - нормализация IPv4-mapped на входе и на lookup. -- CI: джоба `cargo test --no-default-features --features protocol-http`, `make ebpf` больше - не глотает ошибки, secrets-гейт ловит слабые compose-дефолты. -- `doctor` не дёргает защищённые ручки без токена и возвращает ненулевой код при провале. -- Инлайн-тесты: 25 → 10 файлов (остальные — в следующих итерациях). - -### Осталось (следующий раунд) - -- [ ] API manager'а: `KEYS` → `SCAN`, batch `MGET` вместо N+1, ошибки Redis → 503 (а не - `200 []`), `DefaultBodyLimit`/`TimeoutLayer`, лимит длины `reason`, graceful shutdown, - эвикция login-лимитера, ключ по `X-Forwarded-For` за доверенным прокси. -- [ ] `trusted_cidrs` + PROXY-header IP как ключ всех политик: банить/лимитировать по - transport-IP, header-IP — только после валидации (ban-amplification через LB). -- [ ] XDP spoof-gate: `unique_sources = 0` на XDP-пути делает `Block` недостижимым — - либо counting в ядре, либо явная документация (сейчас логируется). -- [ ] IPv6 bind в listener (`Domain::IPV4` + строковый парсинг адреса). -- [ ] `relay_idle_timeout_secs` в `[limits]` (сейчас константа 300 с) и семафор бюджета - полем `Gateway` вместо `OnceLock`. -- [ ] Оставшиеся инлайн-тесты (10 файлов) мигрировать в `tests/`. - ## 3. Backlog - [ ] Мигрировать существующие инлайн-тесты (`#[cfg(test)]` в src/) в `tests/` — diff --git a/deploy/config/edge-docker.toml b/deploy/config/edge-docker.toml index d712aed..c0e06b6 100644 --- a/deploy/config/edge-docker.toml +++ b/deploy/config/edge-docker.toml @@ -28,8 +28,6 @@ rate_limit_burst = 10.0 ban_duration_secs = 3600 [store] -# deploy/docker-compose.yml requires REDIS_PASSWORD; add it to the URL when the -# edge uses that stack: redis://:PASSWORD@redis:6379/0 redis_url = "redis://redis:6379/0" blacklist_cache_ttl_secs = 300 clickhouse_url = "" diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index ec66f20..1ad6867 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -1,26 +1,19 @@ services: redis: image: redis:7-alpine - # No published host port: only containers on this network reach Redis, and - # the password is mandatory so an unset variable aborts startup. - environment: - REDIS_PASSWORD: "${REDIS_PASSWORD:?REDIS_PASSWORD must be set (see docs/deployment.md)}" - command: redis-server --requirepass "${REDIS_PASSWORD:?REDIS_PASSWORD must be set (see docs/deployment.md)}" + restart: unless-stopped healthcheck: - test: ["CMD-SHELL", "redis-cli -a \"$$REDIS_PASSWORD\" --no-auth-warning ping | grep -q PONG"] + test: ["CMD", "redis-cli", "ping"] interval: 3s timeout: 1s retries: 5 - restart: unless-stopped clickhouse: image: clickhouse/clickhouse-server:latest container_name: rampart-clickhouse - # ClickHouse has no authentication here: bind it to loopback only and keep - # container-to-container traffic on the Compose network (service name). ports: - - "127.0.0.1:8123:8123" - - "127.0.0.1:9000:9000" + - "8123:8123" + - "9000:9000" volumes: - ./clickhouse/schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro healthcheck: @@ -34,12 +27,12 @@ services: image: grafana/grafana:latest container_name: rampart-grafana ports: - - "127.0.0.1:3000:3000" + - "3000:3000" depends_on: clickhouse: condition: service_started environment: - GF_SECURITY_ADMIN_PASSWORD: "${GRAFANA_PASSWORD:?GRAFANA_PASSWORD must be set (see docs/deployment.md)}" + GF_INSTALL_PLUGINS: grafana-clickhouse-datasource volumes: - ./grafana/datasources:/etc/grafana/provisioning/datasources:ro - ./grafana/dashboards:/etc/grafana/provisioning/dashboards:ro diff --git a/deploy/test/README.md b/deploy/test/README.md index 52db9ad..b7a0023 100644 --- a/deploy/test/README.md +++ b/deploy/test/README.md @@ -70,4 +70,4 @@ rampart_attack_status ``` ClickHouse (опционально): http://localhost:8123 — долгосрочное хранение событий. -Grafana: http://localhost:3000 (логин `admin`, пароль из `GRAFANA_PASSWORD`) — дашборды из `deploy/grafana/`. +Grafana: http://localhost:3000 (admin/admin) — дашборды из `deploy/grafana/`. diff --git a/docker-compose.yml b/docker-compose.yml index 4093dec..3d99ff2 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,17 +2,13 @@ services: redis: image: redis:7-alpine container_name: rampart-redis - # Redis is reachable only from this Compose network and the loopback - # interface; the password is mandatory so an unset variable aborts startup. + command: redis-server --requirepass "${REDIS_PASSWORD:-rampart_dev}" --appendonly yes ports: - - "127.0.0.1:6379:6379" - environment: - REDIS_PASSWORD: "${REDIS_PASSWORD:?REDIS_PASSWORD must be set (see docs/deployment.md)}" - command: redis-server --requirepass "${REDIS_PASSWORD:?REDIS_PASSWORD must be set (see docs/deployment.md)}" --appendonly yes + - "6379:6379" volumes: - redis-data:/data healthcheck: - test: ["CMD-SHELL", "redis-cli -a \"$$REDIS_PASSWORD\" --no-auth-warning ping | grep -q PONG"] + test: ["CMD", "redis-cli", "--raw", "incr", "ping"] interval: 5s timeout: 3s retries: 5 @@ -21,11 +17,9 @@ services: clickhouse: image: clickhouse/clickhouse-server:24-alpine container_name: rampart-clickhouse - # ClickHouse has no authentication here: bind it to loopback only and keep - # container-to-container traffic on the Compose network (service name). ports: - - "127.0.0.1:8123:8123" # HTTP - - "127.0.0.1:9000:9000" # Native TCP + - "8123:8123" # HTTP + - "9000:9000" # Native TCP volumes: - clickhouse-data:/var/lib/clickhouse - ./deploy/clickhouse/schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro @@ -40,9 +34,9 @@ services: image: grafana/grafana:latest container_name: rampart-grafana ports: - - "127.0.0.1:3000:3000" + - "3000:3000" environment: - - GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD:?GRAFANA_PASSWORD must be set (see docs/deployment.md)} + - GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD:-admin} - GF_INSTALL_PLUGINS=grafana-clickhouse-datasource volumes: - grafana-data:/var/lib/grafana diff --git a/docs/configuration.md b/docs/configuration.md index 3ff65c5..23f9aa3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -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`, минимум 16 символов; `changeme` запрещён | -| `CORS_ORIGIN` | нет | — (CORS выключен) | `*` — разрешить все источники; список через запятую; пусто/не задано — запретить cross-origin | +| `API_PASSWORD` | да | — | Пароль для `/api/v1/auth/login`; значение `changeme` запрещено | +| `CORS_ORIGIN` | нет | `http://localhost:5173` | CORS; `*` или пусто — разрешить все | Manager всегда слушает `0.0.0.0:8080`. @@ -136,21 +136,9 @@ 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` | — (обязателен при `syn_challenge_enabled`) | 128-битный hex-секрет, например `openssl rand -hex 8`; встроенный плейсхолдер запрещён | +| `challenge_secret_hex` | плейсхолдер | 128-битный hex-секрет challenge | | `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` diff --git a/docs/deployment.md b/docs/deployment.md index 19db2ee..2009310 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -73,34 +73,24 @@ 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="$(openssl rand -base64 24)" # минимум 16 символов, дефолт запрещён +export JWT_SECRET="$(openssl rand -hex 32)" # минимум 32 байта +export API_PASSWORD="не-changeme" # дефолт запрещён 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 -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). +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. -Инфраструктура (Redis, ClickHouse, Grafana) требует пароли из окружения — -Compose не стартует без них: +Инфраструктура (Redis, ClickHouse, Grafana): ```bash -export REDIS_PASSWORD="$(openssl rand -base64 24)" -export GRAFANA_PASSWORD="$(openssl rand -base64 24)" docker compose up -d redis clickhouse grafana ``` @@ -113,10 +103,6 @@ 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 . @@ -124,15 +110,6 @@ 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 diff --git a/docs/testing.md b/docs/testing.md index 9659e80..b08a62c 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -45,18 +45,8 @@ sudo bash scripts/xdp_ipv6_smoke.sh ``` Поднимает netns + veth, грузит программу через verifier и проверяет: бан IPv6 и IPv4 -(включая короткие UDP-датаграммы), снятие бана, whitelist поверх активного бана, истечение -TTL по монотонным часам и `udp_policy = "rate-limit"` для IPv6 (политика патчится в -`.rodata` до загрузки). - -```bash -sudo bash scripts/xdp_pkt_test.sh -``` - -Проверяет то, что veth-смок поймать не может по построению: Ethernet-паддинг (длина -TCP-payload по `ip->tot_len`), VLAN/QinQ-теги и фрагменты — забаненный источник не должен -проходить ни тегированным, ни фрагментированным. - +(включая короткие UDP-датаграммы), снятие бана, истечение TTL по монотонным часам и +`udp_policy = "rate-limit"` для IPv6 (политика патчится в `.rodata` до загрузки). `scripts/xdp_netns_smoke.sh` дополнительно гоняет реальный бинарь `rampart` end-to-end (требует `hping3`). diff --git a/scripts/check_default_secrets.sh b/scripts/check_default_secrets.sh index cd8e40a..fb54e13 100755 --- a/scripts/check_default_secrets.sh +++ b/scripts/check_default_secrets.sh @@ -1,21 +1,15 @@ #!/usr/bin/env bash # -# check_default_secrets.sh — reject placeholder and weak secrets committed as -# real values in code, deploy configs, or docs. -# -# Catches: -# 1. the literal placeholder "changeme"; -# 2. Compose-style fallbacks to weak defaults, e.g. ${REDIS_PASSWORD:-rampart_dev} -# or ${GRAFANA_PASSWORD:-admin}; -# 3. Redis `requirepass` with a weak or empty password. +# check_default_secrets.sh — reject the placeholder secret "changeme" +# committed as a real value in code, deploy configs, or docs. # # Intentional occurrences are whitelisted in two layers: # 1. File level — the validation code itself: # src/bin/rampart-manager.rs (startup guard rejecting the default) -# src/manager/security.rs (password/secret policy + placeholders) -# src/manager/api/auth.rs (login handler) -# 2. Line level — a matching line is skipped when it contains "must not be" or -# "test" (case-insensitive), states the prohibition ("запр" root: запрет / +# src/manager/api/auth.rs (test constant) +# 2. Line level — only lines that *use* "changeme" as a value are reported. +# A matching line is skipped when it contains "must not be" or "test" +# (case-insensitive), states the prohibition ("запр" root: запрет / # запрещено / запрещён — the project docs are partly Russian), or is a # comment / markdown table row (starts with '#', '//', '*', '|', '--'). # @@ -23,62 +17,47 @@ set -u +PATTERN="changeme" SCAN_DIRS="src deploy docs" -FILE_WHITELIST="src/bin/rampart-manager.rs src/manager/security.rs src/manager/api/auth.rs" - -# "@@" pairs. The `|` inside alternations is -# safe because entries are split on the first `@@`. -PATTERNS=( - 'changeme@@placeholder password "changeme"' - '\$\{[A-Za-z_][A-Za-z0-9_]*:-[[:space:]]*(rampart_dev|admin|password|secret|root)@@fallback to a weak default value' - "requirepass[[:space:]]+[\"']?[[:space:]]*(rampart_dev|admin|password|redis|secret|root)@@requirepass with a weak password" - "requirepass[[:space:]]*([\"']{2})?[[:space:]]*\$@@requirepass without a password" -) +FILE_WHITELIST="src/bin/rampart-manager.rs src/manager/api/auth.rs" cd "$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)" || exit 1 -offenders=$(mktemp) -trap 'rm -f "$offenders"' EXIT - +found=0 for dir in $SCAN_DIRS; do [ -d "$dir" ] || continue - for entry in "${PATTERNS[@]}"; do - pattern="${entry%%@@*}" - description="${entry#*@@}" - while IFS= read -r match; do - [ -n "$match" ] || continue - file="${match%%:*}" - rest="${match#*:}" - lineno="${rest%%:*}" - content="${rest#*:}" + while IFS= read -r match; do + file="${match%%:*}" + rest="${match#*:}" + lineno="${rest%%:*}" + content="${rest#*:}" - skip=0 - for whitelisted in $FILE_WHITELIST; do - [ "$file" = "$whitelisted" ] && skip=1 - done - if printf '%s' "$content" | grep -qiE 'must not be|test|запр'; then - skip=1 - fi - trimmed="${content#"${content%%[![:space:]]*}"}" - if [ "${trimmed:0:2}" = "//" ] || [ "${trimmed:0:2}" = "--" ]; then - skip=1 - fi - case "${trimmed:0:1}" in - '#'|'*'|'|') skip=1 ;; - esac + skip=0 + for whitelisted in $FILE_WHITELIST; do + [ "$file" = "$whitelisted" ] && skip=1 + done + if printf '%s' "$content" | grep -qiE 'must not be|test|запр'; then + skip=1 + fi + trimmed="${content#"${content%%[![:space:]]*}"}" + if [ "${trimmed:0:2}" = "//" ] || [ "${trimmed:0:2}" = "--" ]; then + skip=1 + fi + case "${trimmed:0:1}" in + '#'|'*'|'|') skip=1 ;; + esac - if [ "$skip" -eq 0 ]; then - printf 'FAIL %s:%s: %s [%s]\n' "$file" "$lineno" "$trimmed" "$description" >> "$offenders" - fi - done < <(grep -rnE --binary-files=without-match "$pattern" "$dir" 2>/dev/null) - done + if [ "$skip" -eq 0 ]; then + found=1 + printf 'FAIL %s:%s: %s\n' "$file" "$lineno" "$trimmed" >&2 + fi + done < <(grep -rn --binary-files=without-match "$PATTERN" "$dir" 2>/dev/null) done -if [ -s "$offenders" ]; then - sort -u "$offenders" >&2 - echo "secrets gate: FAIL — placeholder/weak secret used as a value (see lines above)" >&2 +if [ "$found" -ne 0 ]; then + echo "secrets gate: FAIL — 'changeme' used as a value (see lines above)" >&2 exit 1 fi -echo "secrets gate: PASS — no placeholder or weak default secrets in: $SCAN_DIRS" +echo "secrets gate: PASS — no unexpected '$PATTERN' occurrences in: $SCAN_DIRS" exit 0 diff --git a/scripts/xdp_ipv6_smoke.sh b/scripts/xdp_ipv6_smoke.sh index cb01455..eb0ce6e 100755 --- a/scripts/xdp_ipv6_smoke.sh +++ b/scripts/xdp_ipv6_smoke.sh @@ -9,8 +9,7 @@ # to fall through to XDP_PASS past the blacklist because the length check # was sized for TCP; # 4. the same holds for IPv4, through the shared L4 gate; -# 5. a /128 entry in whitelist6_map bypasses an active ban; -# 6. expiry: a ban with a monotonic TTL really expires in the kernel; it +# 5. expiry: a ban with a monotonic TTL really expires in the kernel; it # used to live forever because userspace wrote epoch-ns while the C side # compared against bpf_ktime_get_ns(). # @@ -75,21 +74,19 @@ discover_maps() { IDS=$(bpftool prog show pinned "$PIN" | grep -o 'map_ids [0-9,]*' | cut -d' ' -f2 | tr ',' ' ') B4="" B6="" - W6="" ST="" for id in $IDS; do desc=$(bpftool map show id "$id" 2>/dev/null) case "$desc" in *"name blacklist6_map"*) B6=$id ;; *"name blacklist_map"*) B4=$id ;; - *"name whitelist6_map"*) W6=$id ;; *"name stats_map"*) ST=$id ;; esac done - [ -n "$B4" ] && [ -n "$B6" ] && [ -n "$W6" ] && [ -n "$ST" ] + [ -n "$B4" ] && [ -n "$B6" ] && [ -n "$ST" ] } discover_maps || { echo "карты не найдены"; exit 1; } -ok "blacklist_map id=$B4, blacklist6_map id=$B6, whitelist6_map id=$W6, stats_map id=$ST" +ok "blacklist_map id=$B4, blacklist6_map id=$B6, stats_map id=$ST" # LPM keys: prefixlen (u32 LE) followed by the address in network order. KEY6="80 00 00 00 fd 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02" @@ -117,8 +114,7 @@ stats() { bpftool -j map dump id "$ST" | python3 -c " import json, sys names = {0: 'total', 1: 'tcp', 2: 'whitelist', 3: 'blacklist', 4: 'syn_thr', - 5: 'pass', 6: 'drop', 7: 'udp', 8: 'rate', 9: 'chal_sent', - 12: 'frag_bypass'} + 5: 'pass', 6: 'drop', 7: 'udp', 8: 'rate', 9: 'chal_sent'} out = {} for e in json.load(sys.stdin): k = names.get(e['formatted']['key']) @@ -179,23 +175,6 @@ drop1=$(metric drop) || fail "v4 короткая датаграмма прошла мимо бана ($(stats))" bpftool map delete id "$B4" key hex $KEY4 || fail "v4 map delete" -# Phase 2b: the IPv6 whitelist wins over an active ban and is consulted before -# the port gate and conntrack, so an allowlisted source truly bypasses -# filtering. -WL6_KEY="80 00 00 00 fd 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02" -bpftool map update id "$B6" key hex $KEY6 value hex ff ff ff ff ff ff ff ff || fail "v6 ban for whitelist phase" -bpftool map update id "$W6" key hex $WL6_KEY value hex 01 || fail "whitelist6 map update" -drop0=$(metric drop); total0=$(metric total); wl0=$(metric whitelist) -for _ in 1 2 3; do send6 100; done -sleep 0.5 -drop1=$(metric drop); total1=$(metric total); wl1=$(metric whitelist) -[ "${total1:-0}" -gt "${total0:-0}" ] && [ "${drop1:-0}" -eq "${drop0:-0}" ] \ - && [ "${wl1:-0}" -gt "${wl0:-0}" ] \ - && ok "v6 whitelist обходит активный бан (total $total0 -> $total1, drop $drop0 -> $drop1, whitelist $wl0 -> $wl1)" \ - || fail "v6 whitelist не обходит бан ($(stats))" -bpftool map delete id "$W6" key hex $WL6_KEY || fail "whitelist6 map delete" -bpftool map delete id "$B6" key hex $KEY6 || fail "v6 map delete after whitelist phase" - # Phase 3: ban expiry on the monotonic clock. A TTL written in epoch-ns would # never expire against bpf_ktime_get_ns(), so this phase pins the clock choice. TTL=2 diff --git a/scripts/xdp_pkt_test.sh b/scripts/xdp_pkt_test.sh deleted file mode 100755 index f905a04..0000000 --- a/scripts/xdp_pkt_test.sh +++ /dev/null @@ -1,241 +0,0 @@ -#!/usr/bin/env bash -# Packet-level smoke test for L2/L3 edge cases that ordinary sockets cannot -# produce: VLAN/QinQ tags, IPv4 fragments and Ethernet padding. -# -# What it verifies (each phase is a regression for a fix in universal_filter.c): -# 1. VLAN, QinQ and plain datagrams from a banned source are all dropped — -# tags are peeled before L3 and the blacklist still runs; -# 2. first (MF) and non-first fragments from a banned source are dropped by -# the source blacklist; -# 3. fragments from a clean source pass and bump STAT_FRAGMENT_BYPASS; -# 4. TCP payload length comes from ip->tot_len, not from the frame end: a -# segment followed by 16 bytes of Ethernet padding advances expected_seq -# by the 4 declared payload bytes only (read back from conntrack_map). -# -# Requires root/CAP_BPF+CAP_NET_ADMIN, bpftool, clang, python3. -# Run: sudo bash scripts/xdp_pkt_test.sh - -set -u - -NS=rampart_pkt_smoke -DEV0=rthp0 -DEV1=rtapp0 -HOST4=10.88.0.1 -NS4=10.88.0.2 -PORT=4444 -OBJ=$(mktemp /tmp/rampart_pkt_smoke.XXXXXX.o) -PIN=/sys/fs/bpf/rampart_pkt_smoke -WORK=$(mktemp -d /tmp/rampart_pkt_work.XXXXXX) -PASS=1 - -fail() { echo "FAIL: $1"; PASS=0; } -ok() { echo "ok: $1"; } - -# Detach and remove every artefact, so a rerun starts from a clean state. -cleanup() { - bpftool net detach xdp dev "$DEV0" 2>/dev/null - rm -f "$PIN" "$OBJ" - rm -rf "$WORK" - ip link del "$DEV0" 2>/dev/null - ip netns del "$NS" 2>/dev/null -} -trap cleanup EXIT - -[ "$(id -u)" = 0 ] || { echo "нужен root (CAP_BPF+CAP_NET_ADMIN)"; exit 2; } -cd "$(dirname "$0")/.." || exit 2 - -clang -O2 -g -target bpf -mcpu=v3 -c xdp/core/universal_filter.c -o "$OBJ" \ - -Ixdp -Ixdp/core -Ixdp/hooks -I/usr/include/x86_64-linux-gnu \ - || { echo "clang: не собралось"; exit 1; } -ok "clang: universal_filter.c собран" - -ip netns add "$NS" || { echo "не удалось создать netns"; exit 2; } -ip link add "$DEV0" type veth peer name "$DEV1" || exit 2 -ip link set "$DEV1" netns "$NS" -ip addr add "$HOST4/24" dev "$DEV0" -ip link set "$DEV0" up -ip -n "$NS" addr add "$NS4/24" dev "$DEV1" -ip -n "$NS" link set "$DEV1" up -ip -n "$NS" link set lo up -ok "netns $NS + veth ($HOST4 <-> $NS4)" - -# Loading through the verifier is itself a check. -bpftool prog load "$OBJ" "$PIN" type xdp || { echo "verifier отверг программу"; exit 1; } -bpftool net attach xdp pinned "$PIN" dev "$DEV0" || exit 1 -ok "verifier принял программу, attach на $DEV0" - -discover_maps() { - IDS=$(bpftool prog show pinned "$PIN" | grep -o 'map_ids [0-9,]*' | cut -d' ' -f2 | tr ',' ' ') - B4="" - CT="" - ST="" - for id in $IDS; do - desc=$(bpftool map show id "$id" 2>/dev/null) - case "$desc" in - *"name blacklist_map"*) B4=$id ;; - *"name conntrack_map"*) CT=$id ;; - *"name stats_map"*) ST=$id ;; - esac - done - [ -n "$B4" ] && [ -n "$CT" ] && [ -n "$ST" ] -} -discover_maps || { echo "карты не найдены"; exit 1; } -ok "blacklist_map id=$B4, conntrack_map id=$CT, stats_map id=$ST" - -# Crafted-frame sender. argv: iface src dst kind args... -# The frames are emitted with AF_PACKET from inside the namespace, so they -# arrive on DEV0 exactly as a NIC would deliver them. Checksums of TCP/UDP are -# irrelevant: XDP runs before the stack and only the IP header is inspected. -cat > "$WORK/send.py" <<'PY' -import socket, struct, sys - -iface, src, dst, kind = sys.argv[1:5] -SPORT = 40000 - -DST_MAC = bytes.fromhex("020000000001") -SRC_MAC = bytes.fromhex("020000000002") - - -def ip_checksum(hdr): - if len(hdr) % 2: - hdr += b"\0" - s = 0 - for i in range(0, len(hdr), 2): - s += (hdr[i] << 8) | hdr[i + 1] - while s >> 16: - s = (s & 0xFFFF) + (s >> 16) - return (~s) & 0xFFFF - - -def ip4(proto, payload, frag_off=0): - total = 20 + len(payload) - args = (0x45, 0, total, 0x1234, frag_off, 64, proto, 0, - socket.inet_aton(src), socket.inet_aton(dst)) - hdr = struct.pack("!BBHHHBBH4s4s", *args) - args = args[:7] + (ip_checksum(hdr),) + args[8:] - return struct.pack("!BBHHHBBH4s4s", *args) + payload - - -def l2(eth_type, tags): - hdr = DST_MAC + SRC_MAC - if tags >= 1: - hdr += struct.pack("!HH", 0x8100 if tags == 1 else 0x88A8, 100) - if tags >= 2: - hdr += struct.pack("!HH", 0x8100, 200) - return hdr + struct.pack("!H", eth_type) - - -def emit(eth_type, l3, tags, pad): - frame = l2(eth_type, tags) + l3 - if len(frame) < pad: - frame += b"\0" * (pad - len(frame)) - sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) - sock.bind((iface, 0)) - sock.send(frame) - - -def udp(args): - sport, dport, tags, pad = (int(a, 0) for a in args) - data = b"x" * 8 - hdr = struct.pack("!HHHH", sport, dport, 8 + len(data), 0) - emit(0x0800, ip4(17, hdr + data), tags, pad) - - -def frag(args): - sport, dport, offset8, mf = (int(a, 0) for a in args) - data = b"y" * 8 - hdr = struct.pack("!HHHH", sport, dport, 16, 0) - frag_off = (offset8 & 0x1FFF) | (0x2000 if mf else 0) - emit(0x0800, ip4(17, hdr + data, frag_off), 0, 0) - - -def tcp(args): - sport, dport, seq, ack, flags, data_len, pad = (int(a, 0) for a in args) - data = b"z" * data_len - hdr = struct.pack("!HHIIBBHHH", sport, dport, seq, ack, 0x50, flags, - 0xFFFF, 0, 0) - emit(0x0800, ip4(6, hdr + data), 0, pad) - - -{"udp": udp, "frag": frag, "tcp": tcp}[kind](sys.argv[5:]) -PY - -send() { ip netns exec "$NS" python3 "$WORK/send.py" "$DEV1" "$NS4" "$HOST4" "$@"; } - -# Sum the per-CPU counters and print only the non-zero ones. -stats() { - bpftool -j map dump id "$ST" | python3 -c " -import json, sys -names = {0: 'total', 3: 'blacklist', 5: 'pass', 6: 'drop', 12: 'frag_bypass'} -out = {} -for e in json.load(sys.stdin): - k = names.get(e['formatted']['key']) - if k is not None: - out[k] = sum(v['value'] for v in e['formatted']['values']) -print(' '.join(f'{k}={v}' for k, v in out.items() if v) or 'все нули') -" -} -metric() { stats | tr ' ' '\n' | sed -n "s/^$1=//p" | head -1; } - -# /32 LPM key for $NS4 and a ban that never expires in this run. -KEY4="20 00 00 00 0a 58 00 02" -BAN="ff ff ff ff ff ff ff ff" -bpftool map update id "$B4" key hex $KEY4 value hex $BAN || fail "ban $NS4" - -# Phase 1: tagged traffic from a banned source (plain frame as control). -drop0=$(metric drop) -send udp 5000 $PORT 1 0 -send udp 5000 $PORT 2 0 -send udp 5000 $PORT 0 0 -sleep 0.3 -drop1=$(metric drop) -[ "${drop1:-0}" -ge $((${drop0:-0} + 3)) ] \ - && ok "VLAN/QinQ/plain UDP от забаненного источника дропаются (drop $drop0 -> $drop1)" \ - || fail "tagged traffic прошёл мимо бана (drop $drop0 -> $drop1, $(stats))" - -# Phase 2: fragments from a banned source, first (MF) and later ones. -drop0=$(metric drop) -send frag 5001 $PORT 0 1 -send frag 5002 $PORT 1 0 -send frag 5003 $PORT 1 1 -sleep 0.3 -drop1=$(metric drop) -[ "${drop1:-0}" -ge $((${drop0:-0} + 3)) ] \ - && ok "фрагменты (MF и offset>0) от забаненного источника дропаются (drop $drop0 -> $drop1)" \ - || fail "фрагменты прошли мимо бана (drop $drop0 -> $drop1, $(stats))" - -bpftool map delete id "$B4" key hex $KEY4 || fail "unban $NS4" - -# Phase 3: fragments from a clean source pass and are counted separately. -pass0=$(metric pass) -frag0=$(metric frag_bypass) -send frag 5004 $PORT 0 1 -send frag 5005 $PORT 1 0 -send frag 5006 $PORT 2 0 -sleep 0.3 -pass1=$(metric pass) -frag1=$(metric frag_bypass) -[ "${pass1:-0}" -ge $((${pass0:-0} + 3)) ] && [ "${frag1:-0}" -ge $((${frag0:-0} + 3)) ] \ - && ok "чистые фрагменты проходят и считаются (pass $pass0 -> $pass1, frag $frag0 -> $frag1)" \ - || fail "чистые фрагменты не прошли/не посчитались (pass $pass0 -> $pass1, frag $frag0 -> $frag1, $(stats))" - -# Phase 4: a padded frame must not inflate the TCP payload. ISN=1000, so after -# the handshake expected_seq is 1001; a 4-byte payload must leave 1005, not -# 1001 + 4 + 16 padding = 1021. -send tcp 40000 $PORT 1000 0 0x02 0 0 # SYN -send tcp 40000 $PORT 1001 2000 0x10 0 0 # ACK completes the handshake -send tcp 40000 $PORT 1001 2000 0x18 4 74 # 4 payload bytes, 16 pad bytes -sleep 0.3 -got=$(bpftool -j map dump id "$CT" | python3 -c " -import json, sys -for e in json.load(sys.stdin): - v = bytes(int(x, 0) for x in e['value']) - print(int.from_bytes(v[4:8], 'little')) - break -") -[ "${got:-0}" = "1005" ] \ - && ok "expected_seq учёл 4 байта payload, а не 20 байт кадра (expected_seq=$got)" \ - || fail "expected_seq=$got, ожидалось 1005 (паддинг попал в payload)" - -[ "$PASS" = 1 ] && echo "PASS: VLAN/QinQ, фрагменты и паддинг обрабатываются корректно" || echo "FAIL" -[ "$PASS" = 1 ] diff --git a/src/app/runtime.rs b/src/app/runtime.rs index 91142d2..c576c34 100644 --- a/src/app/runtime.rs +++ b/src/app/runtime.rs @@ -132,9 +132,6 @@ pub async fn run() -> anyhow::Result { let subnet_tracker = start_subnet_tracker(&config); monitor::spawn( &config.detect.prefix, - Duration::from_secs(config.ban.ban_duration_secs), - blacklist.clone(), - !config.proxy_protocol.ingress_enabled, subnet_tracker.clone(), xdp_filter.clone(), shutdown_rx.clone(), @@ -193,9 +190,7 @@ pub async fn run() -> anyhow::Result { tracing::info!("Rampart edge starting on {}:{}", config.bind.address, config.bind.port); tracing::info!("Upstreams: {:?}", config.backend.upstreams); - // The configured difficulty is the floor and the starting point; the - // adjuster only raises it under load. - let adjuster = Arc::new(Mutex::new(DifficultyAdjuster::with_floor(config.pow.difficulty))); + let adjuster = Arc::new(Mutex::new(DifficultyAdjuster::default())); let gateway = Arc::new(Gateway::new( config.clone(), rate_limiter, diff --git a/src/app/services.rs b/src/app/services.rs index 69f39cb..8f75167 100644 --- a/src/app/services.rs +++ b/src/app/services.rs @@ -51,12 +51,11 @@ fn register_http(registry: &mut ProtocolRegistry, config: &Config) { } #[cfg(feature = "xdp")] -pub fn start_xdp( +pub(crate) fn start_xdp( config: &Arc, shutdown_rx: &watch::Receiver, blacklist: &Arc, ) -> anyhow::Result>>> { - use anyhow::Context as _; use std::time::Duration; use crate::xdp::XdpMetrics; @@ -83,28 +82,12 @@ pub fn start_xdp( ); } guard.load()?; - // The kernel filter only honours its LPM whitelist, so a configured - // `whitelist` that fails to load is a startup error: silently dropping - // the entries would expose trusted peers to the XDP rules. - let whitelist = build_whitelist(config)?; - for ip in whitelist.iter() { - guard - .whitelist_add(*ip) - .with_context(|| format!("failed to load XDP whitelist entry {ip}"))?; - } - tracing::info!( - entries = whitelist.len(), - "configured whitelist loaded into the XDP LPM maps" - ); } let xdp_metrics = XdpMetrics::register()?; let sd = shutdown_rx.clone(); let shared_thread = shared.clone(); std::thread::spawn(move || { - // The loop ticks every 5 s; sweep the ban maps once a minute. - const REAP_EVERY_TICKS: u32 = 12; - let mut tick: u32 = 0; while !*sd.borrow() { let guard = match shared_thread.lock() { Ok(g) => g, @@ -114,17 +97,6 @@ pub fn start_xdp( if let Ok(stats) = guard.get_stats() { xdp_metrics.update(&stats); } - tick += 1; - if tick >= REAP_EVERY_TICKS { - tick = 0; - // The packet path only expires the exact /32 or /128 key it - // looked up, so wider prefix bans stay resident until swept. - match guard.reap_expired_bans() { - Ok(0) => {}, - Ok(n) => tracing::info!(reaped = n, "expired XDP prefix bans removed"), - Err(e) => tracing::warn!(error = %e, "XDP expired-ban reaper failed"), - } - } drop(guard); std::thread::sleep(Duration::from_secs(5)); } @@ -136,7 +108,7 @@ pub fn start_xdp( } #[cfg(not(feature = "xdp"))] -pub fn start_xdp( +pub(crate) fn start_xdp( _config: &Arc, _shutdown_rx: &watch::Receiver, _blacklist: &Arc, @@ -181,7 +153,7 @@ fn ensure_store_features(config: &Config) -> anyhow::Result<()> { /// # Errors /// Fails on an invalid entry or when the config requires store features that are /// not compiled in. -pub fn build_whitelist(config: &Config) -> anyhow::Result>> { +pub(crate) fn build_whitelist(config: &Config) -> anyhow::Result>> { ensure_store_features(config)?; let mut set = HashSet::with_capacity(config.whitelist.len()); for entry in &config.whitelist { @@ -192,3 +164,51 @@ pub fn build_whitelist(config: &Config) -> anyhow::Result>> } Ok(Arc::new(set)) } + +#[cfg(test)] +mod tests { + use super::*; + + fn config_with_redis() -> Config { + Config { + store: crate::config::StoreConfig { + redis_url: Some("redis://127.0.0.1:6379/0".to_string()), + ..Default::default() + }, + ..Default::default() + } + } + + #[cfg(not(feature = "store-redis"))] + #[test] + fn redis_config_without_feature_fails_fast() { + let err = ensure_store_features(&config_with_redis()).expect_err("must fail without store-redis"); + assert!(err.to_string().contains("built without store-redis feature")); + } + + #[cfg(not(feature = "store-redis"))] + #[test] + fn empty_store_config_passes_without_feature() { + assert!(ensure_store_features(&Config::default()).is_ok()); + } + + #[cfg(feature = "store-redis")] + #[test] + fn guard_is_noop_with_feature() { + assert!(ensure_store_features(&config_with_redis()).is_ok()); + } + + /// XDP auto-ban wiring: `start_xdp` must accept the `Arc` and, with + /// `[xdp]` disabled, touch neither the kernel nor the blacklist. The + /// `set_autoban` -> `load()` order inside the enabled branch cannot be checked + /// without a kernel. + #[test] + fn start_xdp_accepts_blacklist_and_skips_kernel_when_disabled() { + let (_tx, rx) = watch::channel(false); + let blacklist = Arc::new(Blacklist::new()); + let started = start_xdp(&Arc::new(Config::default()), &rx, &blacklist) + .expect("xdp disabled: no kernel work and no error"); + assert!(started.is_none()); + assert!(blacklist.is_empty()); + } +} diff --git a/src/app/shutdown.rs b/src/app/shutdown.rs index 198a7a4..bcba0fd 100644 --- a/src/app/shutdown.rs +++ b/src/app/shutdown.rs @@ -18,14 +18,11 @@ pub enum RunExit { impl RunExit { /// Process exit code for this outcome. - /// - /// A forced drain timeout loses connections that did not finish in time, so - /// it must not look like a clean shutdown to supervisors and scripts. #[must_use] pub const fn code(self) -> i32 { match self { Self::Ok => 0, - Self::DrainTimeout => 1, + Self::DrainTimeout => 0, } } } @@ -56,3 +53,15 @@ async fn wait_for_signal() { _ = term.recv() => {} } } + +#[cfg(test)] +mod tests { + use super::RunExit; + + #[test] + fn run_exit_codes_match_previous_process_exit() { + // Both the clean path and the former drain timeout (`process::exit(0)`) exited with code 0. + assert_eq!(RunExit::Ok.code(), 0); + assert_eq!(RunExit::DrainTimeout.code(), 0); + } +} diff --git a/src/bin/rampart-manager.rs b/src/bin/rampart-manager.rs index 4f6c6bb..4d04421 100644 --- a/src/bin/rampart-manager.rs +++ b/src/bin/rampart-manager.rs @@ -1,14 +1,17 @@ //! Rampart manager daemon: HTTP API in front of the redis state store. use axum::{ - Router, middleware, + Router, + http::HeaderValue, + middleware, routing::{get, post}, }; use dashmap::DashMap; #[cfg(feature = "store-redis")] use rampart::manager::sync; -use rampart::manager::{AppState, api, auth, security}; +use rampart::manager::{AppState, api, auth}; use std::sync::Arc; +use tower_http::cors::CorsLayer; use tracing_subscriber::EnvFilter; #[tokio::main] @@ -29,7 +32,9 @@ async fn main() -> anyhow::Result<()> { let redis_client = redis::Client::open(redis_url)?; let jwt_secret = std::env::var("JWT_SECRET").map_err(|_| anyhow::anyhow!("JWT_SECRET must be set"))?; - security::validate_jwt_secret(&jwt_secret)?; + if jwt_secret.len() < 32 { + return Err(anyhow::anyhow!("JWT_SECRET must be at least 32 bytes")); + } let jwt_audience = std::env::var("JWT_AUDIENCE").unwrap_or_else(|_| "rampart".to_string()); let jwt_expiration = std::env::var("JWT_EXPIRATION_SECS") .unwrap_or_else(|_| "86400".to_string()) @@ -37,7 +42,9 @@ async fn main() -> anyhow::Result<()> { .map_err(|_| anyhow::anyhow!("JWT_EXPIRATION_SECS must be a valid u64"))?; let api_password = std::env::var("API_PASSWORD").map_err(|_| anyhow::anyhow!("API_PASSWORD must be set"))?; - security::validate_api_password(&api_password)?; + if api_password == "changeme" { + return Err(anyhow::anyhow!("API_PASSWORD must not be the default 'changeme'")); + } let state = Arc::new(AppState { #[cfg(feature = "store-redis")] @@ -71,13 +78,17 @@ async fn main() -> anyhow::Result<()> { .route("/api/v1/nodes", get(api::inventory::nodes::list_nodes)); let protected = protected.route_layer(middleware::from_fn_with_state(state.clone(), auth::auth_middleware)); - let cors_policy = security::CorsPolicy::parse(std::env::var("CORS_ORIGIN").ok().as_deref())?; - tracing::info!("CORS policy: {cors_policy:?}"); + let cors = match std::env::var("CORS_ORIGIN") { + Ok(origin) if origin.is_empty() || origin == "*" => CorsLayer::new().allow_origin(tower_http::cors::Any), + Ok(origin) => CorsLayer::new().allow_origin(HeaderValue::from_str(&origin)?), + Err(_) => CorsLayer::new().allow_origin(HeaderValue::from_static("http://localhost:5173")), + }; - let mut app = Router::new().merge(public).merge(protected).with_state(state); - if let Some(cors) = cors_policy.cors_layer() { - app = app.layer(cors); - } + let app = Router::new() + .merge(public) + .merge(protected) + .layer(cors) + .with_state(state); let addr = "0.0.0.0:8080"; tracing::info!("Manager API listening on {addr}"); diff --git a/src/cli/commands/config.rs b/src/cli/commands/config.rs index 17db4c6..45c716c 100644 --- a/src/cli/commands/config.rs +++ b/src/cli/commands/config.rs @@ -14,7 +14,7 @@ pub async fn run(key: Option, value: Option) -> anyhow::Result<( println!(); println!("Example keys:"); println!(" workers.count"); - println!(" limits.rate_limit_pps"); + println!(" limits.rate_limit_login_pps"); println!(" limits.max_connections_per_ip"); Ok(()) }, diff --git a/src/cli/commands/doctor.rs b/src/cli/commands/doctor.rs index 0836ac5..95e28db 100644 --- a/src/cli/commands/doctor.rs +++ b/src/cli/commands/doctor.rs @@ -2,11 +2,6 @@ use crate::xdp::{EnvironmentReport, FilesystemProbe, SystemProbe}; -/// Environment variable holding a ready-to-use manager bearer token. -const TOKEN_ENV: &str = "RAMPART_TOKEN"; -/// Environment variable holding the manager API password used to log in. -const PASSWORD_ENV: &str = "RAMPART_API_PASSWORD"; - /// Finds the interface that owns the default route in `/proc/net/route` /// (destination `00000000`). Works without root. fn default_route_interface(probe: &impl SystemProbe) -> Option { @@ -17,51 +12,6 @@ fn default_route_interface(probe: &impl SystemProbe) -> Option { }) } -/// Obtains a bearer token for the protected manager endpoints. -/// -/// `RAMPART_TOKEN` is used as is; otherwise `RAMPART_API_PASSWORD` is exchanged -/// for a token via `/api/v1/auth/login`. Protected endpoints are never called -/// anonymously, so `None` means the caller has to be told to provide a -/// credential instead of seeing a misleading failure. -async fn manager_token(client: &reqwest::Client, manager_url: &str) -> Option { - if let Ok(token) = std::env::var(TOKEN_ENV) { - if !token.trim().is_empty() { - return Some(token); - } - } - let password = std::env::var(PASSWORD_ENV).ok().filter(|value| !value.is_empty())?; - let response = client - .post(format!("{manager_url}/api/v1/auth/login")) - .json(&serde_json::json!({"password": password})) - .send() - .await - .ok()?; - if !response.status().is_success() { - println!("[WARN] Manager login rejected ({})", response.status()); - return None; - } - let body = response.json::().await.ok()?; - body["token"].as_str().map(str::to_owned) -} - -/// Probes one protected manager endpoint with a bearer token. -async fn check_protected(client: &reqwest::Client, manager_url: &str, path: &str, label: &str, token: Option<&str>) { - let Some(token) = token else { - println!("[SKIP] {label}: set {TOKEN_ENV} or {PASSWORD_ENV} to check it"); - return; - }; - match client - .get(format!("{manager_url}{path}")) - .bearer_auth(token) - .send() - .await - { - Ok(resp) if resp.status().is_success() => println!("[OK] {label}"), - Ok(resp) => println!("[WARN] {label} unavailable ({})", resp.status()), - Err(e) => println!("[WARN] {label} unavailable: {e}"), - } -} - /// Network/XDP section: what the environment exposes without root. fn print_network_section(all_ok: &mut bool) { println!("\nNetwork / XDP"); @@ -110,10 +60,6 @@ fn print_network_section(all_ok: &mut bool) { } /// Runs every diagnostic and prints the report. -/// -/// # Errors -/// Returns an error when any check failed, so scripts and CI see a non-zero -/// exit status instead of a report that only looks alarming. pub async fn run() -> anyhow::Result<()> { println!("Rampart Diagnostics"); println!("=====================\n"); @@ -121,9 +67,8 @@ pub async fn run() -> anyhow::Result<()> { let mut all_ok = true; let manager_url = std::env::var("RAMPART_MANAGER").unwrap_or_else(|_| "http://localhost:8080".to_string()); - let client = reqwest::Client::new(); - match client.get(format!("{manager_url}/api/v1/health")).send().await { + match reqwest::get(format!("{manager_url}/api/v1/health")).await { Ok(resp) if resp.status().is_success() => { println!("[OK] Manager API"); }, @@ -133,31 +78,32 @@ pub async fn run() -> anyhow::Result<()> { }, } - let token = manager_token(&client, &manager_url).await; - check_protected( - &client, - &manager_url, - "/api/v1/blacklist", - "Blacklist API", - token.as_deref(), - ) - .await; - check_protected( - &client, - &manager_url, - "/api/v1/servers", - "Servers API", - token.as_deref(), - ) - .await; + match reqwest::get(format!("{manager_url}/api/v1/blacklist")).await { + Ok(resp) if resp.status().is_success() => { + println!("[OK] Blacklist API"); + }, + _ => { + println!("[WARN] Blacklist API unavailable"); + }, + } + + match reqwest::get(format!("{manager_url}/api/v1/servers")).await { + Ok(resp) if resp.status().is_success() => { + println!("[OK] Servers API"); + }, + _ => { + println!("[WARN] Servers API unavailable"); + }, + } print_network_section(&mut all_ok); println!(); - if !all_ok { + if all_ok { + println!("All checks passed."); + } else { println!("Some checks failed. Run with --verbose for details."); - anyhow::bail!("doctor: one or more checks failed"); } - println!("All checks passed."); + Ok(()) } diff --git a/src/config/mod.rs b/src/config/mod.rs index 6f9996e..03aa1c2 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -19,14 +19,6 @@ pub use sections::{ use serde::Deserialize; use std::fs; -/// Upper bound of `ban.ban_duration_secs`: one year. -const MAX_BAN_DURATION_SECS: u64 = 31_536_000; -/// Upper bound of `pow.difficulty`. -const MAX_POW_DIFFICULTY: u8 = 10; -/// Placeholder `xdp.challenge_secret_hex` values baked into the XDP defaults -/// (`xdp/core/config.h` and `XdpGlobals::default()`; both spellings exist). -const PLACEHOLDER_CHALLENGE_SECRETS: [&str; 2] = ["a5a5a5a5a5a5a5a5", "a5a55a5a5a5aa5a5"]; - #[derive(Debug, Clone, Default, Deserialize)] pub struct Config { #[serde(default)] @@ -98,38 +90,9 @@ impl Config { if self.detect.prefix.enabled && self.detect.prefix.syn_threshold == 0 { anyhow::bail!("detect.prefix.syn_threshold must be positive when enabled"); } - if self.xdp.syn_challenge_enabled { - let secret = self.xdp.challenge_secret_hex.as_deref().ok_or_else(|| { - anyhow::anyhow!( - "xdp.syn_challenge_enabled requires xdp.challenge_secret_hex; \ - generate one with `openssl rand -hex 8`" - ) - })?; - if is_placeholder_challenge_secret(secret) { - anyhow::bail!( - "xdp.challenge_secret_hex is the built-in placeholder; \ - generate a random secret with `openssl rand -hex 8`" - ); - } - } if self.limits.max_connections_per_ip == 0 { anyhow::bail!("limits.max_connections_per_ip must be positive"); } - if !self.limits.rate_limit_pps.is_finite() || self.limits.rate_limit_pps <= 0.0 { - anyhow::bail!("limits.rate_limit_pps must be a finite number greater than 0"); - } - if !self.limits.rate_limit_burst.is_finite() || self.limits.rate_limit_burst < 1.0 { - anyhow::bail!("limits.rate_limit_burst must be a finite number at least 1"); - } - if self.ban.ban_duration_secs == 0 || self.ban.ban_duration_secs > MAX_BAN_DURATION_SECS { - anyhow::bail!("ban.ban_duration_secs must be between 1 and {MAX_BAN_DURATION_SECS}"); - } - if self.pow.difficulty == 0 || self.pow.difficulty > MAX_POW_DIFFICULTY { - anyhow::bail!("pow.difficulty must be between 1 and {MAX_POW_DIFFICULTY}"); - } - if self.workers.count == 0 { - anyhow::bail!("workers.count must be at least 1: otherwise no accept loops are started"); - } if self.proxy_protocol.ingress_enabled { if self.proxy_protocol.trusted_cidrs.is_empty() { anyhow::bail!("proxy_protocol.ingress_enabled requires at least one trusted_cidrs entry"); @@ -175,17 +138,109 @@ impl Config { } } -/// Returns whether `secret` spells a built-in placeholder challenge secret. -/// -/// Hex digits are compared case-insensitively, with an optional `0x` prefix and -/// `_`, `:` and `-` separators ignored, so every spelling of the placeholder is -/// caught. -fn is_placeholder_challenge_secret(secret: &str) -> bool { - let normalized = secret - .trim() - .trim_start_matches("0x") - .trim_start_matches("0X") - .replace(['_', ':', '-'], "") - .to_ascii_lowercase(); - PLACEHOLDER_CHALLENGE_SECRETS.contains(&normalized.as_str()) +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_config_uses_defaults() { + let config = Config::parse_str("").expect("empty config should parse"); + assert_eq!(config.bind.address, "0.0.0.0"); + assert_eq!(config.bind.port, 25565); + assert_eq!(config.backend.upstreams, vec!["127.0.0.1:25566"]); + assert!(!config.pow.enabled); + assert!(!config.xdp.enabled); + } + + #[test] + fn full_config_parses() { + let config = Config::parse_str( + r#" +[bind] +address = "10.0.0.1" +port = 443 + +[backend] +upstreams = ["192.168.1.10:8080", "192.168.1.11:8080"] + +[pow] +enabled = true +difficulty = 6 + +whitelist = ["203.0.113.7"] +"#, + ) + .expect("config should parse"); + assert_eq!(config.bind.port, 443); + assert_eq!(config.backend.upstreams.len(), 2); + assert!(config.pow.enabled); + assert_eq!(config.pow.difficulty, 6); + } + + #[test] + fn empty_upstreams_rejected() { + let result = Config::parse_str( + r#" +[backend] +upstreams = [] +"#, + ); + assert!(result.is_err()); + } + + #[test] + fn invalid_upstream_rejected() { + let result = Config::parse_str( + r#" +[backend] +upstreams = ["not-an-addr"] +"#, + ); + assert!(result.is_err()); + } + + #[test] + fn invalid_whitelist_entry_rejected() { + let result = Config::parse_str("whitelist = [\"999.999.1.1\"]"); + assert!(result.is_err()); + } + + #[test] + fn prefix_detect_defaults_disabled() { + let config = Config::parse_str("").expect("empty config should parse"); + assert!(!config.detect.prefix.enabled); + assert_eq!(config.detect.prefix.syn_threshold, 500); + assert_eq!(config.detect.prefix.window_secs, 10); + assert_eq!(config.detect.prefix.min_unique_sources, 16); + } + + #[test] + fn prefix_detect_section_parses() { + let config = Config::parse_str( + r#" +[detect.prefix] +enabled = true +syn_threshold = 1000 +window_secs = 5 +min_unique_sources = 8 +"#, + ) + .expect("detect.prefix section should parse"); + assert!(config.detect.prefix.enabled); + assert_eq!(config.detect.prefix.syn_threshold, 1000); + assert_eq!(config.detect.prefix.window_secs, 5); + assert_eq!(config.detect.prefix.min_unique_sources, 8); + } + + #[test] + fn prefix_detect_zero_threshold_rejected_when_enabled() { + let result = Config::parse_str( + r#" +[detect.prefix] +enabled = true +syn_threshold = 0 +"#, + ); + assert!(result.is_err()); + } } diff --git a/src/engine/challenge/difficulty.rs b/src/engine/challenge/difficulty.rs index 47da3d5..26a4bb1 100644 --- a/src/engine/challenge/difficulty.rs +++ b/src/engine/challenge/difficulty.rs @@ -4,20 +4,10 @@ use crate::metrics; use std::collections::VecDeque; use std::time::Instant; -/// Lowest usable difficulty: 0 disables the PoW gate before the adjuster runs. -pub const MIN_DIFFICULTY: u8 = 1; - -/// Highest adaptive difficulty. Every extra hex digit quadruples solver work. -pub const MAX_DIFFICULTY: u8 = 12; - -/// Difficulty the adjuster climbs to under the heaviest observed load. -const DEFAULT_MAX_DIFFICULTY: u8 = 10; - /// Adapts the PoW difficulty to the current connection rate. /// /// The rate is counted over a sliding one-second window and the resulting -/// difficulty is clamped to `[min, max]`. The lower bound is also the floor and -/// the starting difficulty, so a configured value takes effect immediately. +/// difficulty is clamped to `[min, max]`. pub struct DifficultyAdjuster { window: VecDeque, min: u8, @@ -32,36 +22,17 @@ impl Default for DifficultyAdjuster { } impl DifficultyAdjuster { - /// Creates an adjuster with the explicit `[min, max]` range. - /// - /// Inverted bounds are swapped, and both ends are clamped to - /// [`MIN_DIFFICULTY`]..=[`MAX_DIFFICULTY`]. The lower bound doubles as the - /// starting difficulty. + /// Creates an adjuster clamped to `min.max(4)` and `max.min(10)`. #[must_use] pub fn new(min: u8, max: u8) -> Self { - let (min, max) = if min > max { (max, min) } else { (min, max) }; - let min = min.clamp(MIN_DIFFICULTY, MAX_DIFFICULTY); - let max = max.clamp(min, MAX_DIFFICULTY); Self { window: VecDeque::new(), - min, - max, - current: min, + min: min.max(4), + max: max.min(10), + current: min.max(4), } } - /// Creates an adjuster whose floor and starting point is the configured PoW - /// difficulty. - /// - /// The ceiling stays at the default maximum, or rises to the configured - /// value when that value is higher. Values outside - /// [`MIN_DIFFICULTY`]..=[`MAX_DIFFICULTY`] are clamped. - #[must_use] - pub fn with_floor(difficulty: u8) -> Self { - let floor = difficulty.clamp(MIN_DIFFICULTY, MAX_DIFFICULTY); - Self::new(floor, floor.max(DEFAULT_MAX_DIFFICULTY)) - } - /// Records one connection and recomputes the difficulty for the window. pub fn record_connection(&mut self) { let now = Instant::now(); @@ -93,18 +64,33 @@ impl DifficultyAdjuster { self.current } - /// Rate step before it is clamped to the configured range. - fn rate_difficulty(&self) -> u8 { + fn compute_difficulty(&self) -> u8 { match self.window.len() { - cps if cps > 500 => MAX_DIFFICULTY, + cps if cps > 500 => self.max.max(self.min), cps if cps > 200 => 8, cps if cps > 50 => 6, _ => self.min, } } +} - fn compute_difficulty(&self) -> u8 { - // The rate ladder is global; the configured range is authoritative. - self.rate_difficulty().clamp(self.min, self.max) +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn adjuster_raises_difficulty_under_load() { + let mut adjuster = DifficultyAdjuster::new(4, 10); + for _ in 0..600 { + adjuster.record_connection(); + } + assert_eq!(adjuster.current_difficulty(), 10); + } + + #[test] + fn adjuster_stays_minimal_when_idle() { + let mut adjuster = DifficultyAdjuster::new(4, 10); + adjuster.record_connection(); + assert_eq!(adjuster.current_difficulty(), 4); } } diff --git a/src/engine/challenge/mod.rs b/src/engine/challenge/mod.rs index e6bba73..461a3ce 100644 --- a/src/engine/challenge/mod.rs +++ b/src/engine/challenge/mod.rs @@ -4,5 +4,5 @@ mod difficulty; mod pow; -pub use difficulty::{DifficultyAdjuster, MAX_DIFFICULTY, MIN_DIFFICULTY}; +pub use difficulty::DifficultyAdjuster; pub use pow::{Challenge, enforce, solve}; diff --git a/src/engine/challenge/pow.rs b/src/engine/challenge/pow.rs index 79eaaac..057bc7f 100644 --- a/src/engine/challenge/pow.rs +++ b/src/engine/challenge/pow.rs @@ -1,5 +1,3 @@ -//! Universal SHA-256 hashcash challenge generation, solver and verifier. - use rand::Rng; use sha2::{Digest, Sha256}; use std::net::IpAddr; @@ -7,15 +5,11 @@ use std::time::{Duration, Instant}; use subtle::ConstantTimeEq; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; -use tokio::time::timeout; const CHALLENGE_TTL_SECS: u64 = 30; const MAX_NONCE_LEN: usize = 64; const ALLOWED_HEX_PREFIX: [u8; 4] = *b"0123"; -/// Maximum time a peer gets to read the challenge and return a nonce. -const NONCE_TIMEOUT: Duration = Duration::from_secs(10); - /// Active PoW challenge issued to one connection. pub struct Challenge { token: [u8; 32], @@ -38,9 +32,7 @@ impl Challenge { } /// Builds a challenge with an explicit token. - /// /// Intended for deterministic tests, where a random token makes the outcome - /// hard to predict. #[must_use] pub fn with_token(token: [u8; 32], difficulty: u8) -> Self { Self { @@ -112,14 +104,8 @@ pub fn solve(challenge: &str, difficulty: u8) -> Option { /// Runs the textual PoW gate on `stream`: issues a challenge and checks the /// answer. /// -/// Wire format: the server writes the hex challenge followed by `\n`; the -/// client answers with the nonce followed by `\n`. A reply terminated by EOF is -/// also accepted for compatibility with clients that close their write half -/// after sending the nonce. Anything the client sent after the delimiter stays -/// in the socket buffer and is seen by the protocol handshake that runs next. -/// /// # Errors -/// Only I/O failures are reported; a wrong or missing solution is `Ok(false)`. +/// Only I/O failures are reported; a wrong solution is `Ok(false)`. pub async fn enforce(stream: &mut TcpStream, peer_ip: IpAddr, difficulty: u8) -> anyhow::Result { if difficulty == 0 { tracing::debug!("pow: difficulty 0, skipping for {peer_ip}"); @@ -128,21 +114,22 @@ pub async fn enforce(stream: &mut TcpStream, peer_ip: IpAddr, difficulty: u8) -> let mut challenge = Challenge::generate(difficulty); let line = format!("{}\n", challenge.challenge_string()); - timeout(NONCE_TIMEOUT, stream.write_all(line.as_bytes())).await??; + stream.write_all(line.as_bytes()).await?; - let nonce = match timeout(NONCE_TIMEOUT, read_nonce_line(stream)).await { - Ok(result) => result?, - Err(_) => { - tracing::debug!("pow: nonce read timed out for {peer_ip}"); - return Ok(false); - }, - }; - let Some(nonce) = nonce else { - tracing::debug!("pow: invalid or missing nonce from {peer_ip}"); + let mut buf = [0u8; MAX_NONCE_LEN + 1]; + let n = tokio::time::timeout(Duration::from_secs(10), stream.read(&mut buf)).await??; + if n == 0 { + tracing::debug!("pow: no response from {peer_ip}"); return Ok(false); - }; + } - let valid = challenge.verify(&nonce); + let nonce = std::str::from_utf8(&buf[..n.min(MAX_NONCE_LEN)]).unwrap_or("").trim(); + if nonce.is_empty() || nonce.len() > MAX_NONCE_LEN { + tracing::debug!("pow: invalid nonce from {peer_ip}"); + return Ok(false); + } + + let valid = challenge.verify(nonce); tracing::debug!( "pow: verification {} for {peer_ip}", if valid { "passed" } else { "failed" } @@ -150,43 +137,54 @@ pub async fn enforce(stream: &mut TcpStream, peer_ip: IpAddr, difficulty: u8) -> Ok(valid) } -/// Reads a newline-terminated nonce without consuming the bytes that follow the -/// delimiter. -/// -/// `peek` inspects the buffer first; only the nonce and its `\n` are consumed, so -/// a client that coalesces the nonce and the handshake into one TCP segment is -/// not truncated. A nonce split across segments is accumulated until the -/// delimiter arrives or the connection reports EOF. -/// -/// Returns `None` for an empty, oversized or non-UTF-8 reply. -async fn read_nonce_line(stream: &mut TcpStream) -> anyhow::Result> { - let mut buf = [0u8; MAX_NONCE_LEN + 1]; - let mut nonce = Vec::with_capacity(MAX_NONCE_LEN); - loop { - let n = stream.peek(&mut buf).await?; - if n == 0 { - // EOF without a delimiter: accept the bytes received so far. - break; - } - if let Some(pos) = buf[..n].iter().position(|&b| b == b'\n') { - if nonce.len() + pos > MAX_NONCE_LEN { - return Ok(None); - } - nonce.extend_from_slice(&buf[..pos]); - // Consume exactly the nonce line; the handshake bytes stay buffered. - stream.read_exact(&mut buf[..=pos]).await?; - break; - } - if nonce.len() + n > MAX_NONCE_LEN { - return Ok(None); - } - stream.read_exact(&mut buf[..n]).await?; - nonce.extend_from_slice(&buf[..n]); +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn solve_then_verify_roundtrip() { + let mut challenge = Challenge::generate(2); + let nonce = solve(&challenge.challenge_string(), 2).expect("solver should find a nonce"); + assert!(challenge.verify(&nonce), "verifier must accept solver output"); } - let text = std::str::from_utf8(&nonce).unwrap_or("").trim(); - if text.is_empty() || text.len() > MAX_NONCE_LEN { - return Ok(None); + #[test] + fn verify_rejects_wrong_nonce() { + let mut challenge = Challenge::generate(4); + let challenge_str = challenge.challenge_string(); + + // Search for a nonce that an independently computed SHA-256 provably rejects, + // so the test stays deterministic. + let mut wrong_nonce = None; + for i in 0..10_000u32 { + let candidate = format!("bad-{i}"); + let hex_hash = hex::encode(Sha256::digest(format!("{challenge_str}{candidate}").as_bytes())); + if !hex_hash + .as_bytes() + .iter() + .take(4) + .all(|c| ALLOWED_HEX_PREFIX.contains(c)) + { + wrong_nonce = Some(candidate); + break; + } + } + let wrong_nonce = wrong_nonce.expect("a failing nonce must exist among candidates"); + assert!(!challenge.verify(&wrong_nonce)); + } + + #[test] + fn verify_rejects_replay() { + let mut challenge = Challenge::generate(2); + let nonce = solve(&challenge.challenge_string(), 2).expect("solved"); + assert!(challenge.verify(&nonce)); + assert!(!challenge.verify(&nonce), "challenge must be single-use"); + } + + #[test] + fn verify_rejects_oversized_nonce() { + let mut challenge = Challenge::generate(2); + let big_nonce = "0".repeat(MAX_NONCE_LEN + 1); + assert!(!challenge.verify(&big_nonce)); } - Ok(Some(text.to_string())) } diff --git a/src/engine/listener.rs b/src/engine/listener.rs index 7bc85e2..5e1fc2d 100644 --- a/src/engine/listener.rs +++ b/src/engine/listener.rs @@ -4,107 +4,10 @@ use crate::config::Config; use crate::engine::tunnel::Gateway; use crate::traffic::hook::TrafficHook; use socket2::{Domain, Socket, Type}; -use std::io::ErrorKind; use std::sync::Arc; -use std::time::Duration; use tokio::net::TcpListener; use tokio::sync::watch; -const ACCEPT_BACKOFF_MIN: Duration = Duration::from_millis(50); -const ACCEPT_BACKOFF_MAX: Duration = Duration::from_millis(500); -/// Consecutive accept failures between full-rate ERROR logs. -/// -/// Every intervening failure is still reported at `debug`, so the log stays -/// diagnosable without amplifying a spin into a disk-filling storm. -const ACCEPT_ERROR_LOG_EVERY: u32 = 32; - -/// Linux errno values that mean "the listener is temporarily unable to accept". -/// -/// `libc` is an optional dependency of the `xdp` feature, so the values are -/// spelled out here; they are ABI constants on the platforms Rampart targets. -#[cfg(target_os = "linux")] -mod errno { - pub const ENOMEM: i32 = 12; - pub const ENFILE: i32 = 23; - pub const EMFILE: i32 = 24; - pub const ENOBUFS: i32 = 105; -} - -/// Exponential backoff for transient `accept()` failures. -/// -/// File-descriptor exhaustion (`EMFILE`/`ENFILE`) makes `accept()` fail -/// synchronously and forever: a plain `continue` turns every worker into a -/// 100% CPU spin that also floods the log. Each transient failure therefore -/// yields a mandatory sleep, growing from `ACCEPT_BACKOFF_MIN` to -/// `ACCEPT_BACKOFF_MAX` and resetting after the next successful accept. -pub struct AcceptBackoff { - delay: Duration, - failures: u32, -} - -impl Default for AcceptBackoff { - fn default() -> Self { - Self::new() - } -} - -impl AcceptBackoff { - #[must_use] - pub fn new() -> Self { - Self { - delay: Duration::ZERO, - failures: 0, - } - } - - /// Returns how long the accept loop must sleep before retrying `error`. - /// - /// `None` means the error is not a capacity or readiness condition - /// (`ECONNABORTED`, `EPROTO`, ...): the connection was abandoned by the peer - /// or the kernel, so an immediate retry is correct. - pub fn delay(&mut self, error: &std::io::Error) -> Option { - if !is_transient(error) { - return None; - } - self.failures = self.failures.saturating_add(1); - self.delay = if self.delay.is_zero() { - ACCEPT_BACKOFF_MIN - } else { - (self.delay * 2).min(ACCEPT_BACKOFF_MAX) - }; - Some(self.delay) - } - - /// Clears the accumulated backoff after a successful accept. - pub fn reset(&mut self) { - self.delay = Duration::ZERO; - self.failures = 0; - } - - /// Reports whether the current failure deserves a full-rate ERROR log. - #[must_use] - pub fn should_log(&self) -> bool { - self.failures == 1 || self.failures % ACCEPT_ERROR_LOG_EVERY == 0 - } -} - -fn is_transient(error: &std::io::Error) -> bool { - if matches!( - error.kind(), - ErrorKind::WouldBlock | ErrorKind::Interrupted | ErrorKind::OutOfMemory - ) { - return true; - } - #[cfg(target_os = "linux")] - if matches!( - error.raw_os_error(), - Some(errno::EMFILE | errno::ENFILE | errno::ENOBUFS | errno::ENOMEM) - ) { - return true; - } - false -} - /// Starts `workers.count` accept loops on a single address. /// /// Each worker binds its own socket with `SO_REUSEPORT` and `SO_REUSEADDR`, so @@ -155,45 +58,22 @@ async fn accept_loop( hook: Arc, mut shutdown: watch::Receiver, ) { - let mut backoff = AcceptBackoff::new(); loop { tokio::select! { biased; - changed = shutdown.changed() => { - match changed { - Ok(()) if *shutdown.borrow() => { - tracing::info!("shutdown signal received, stopping accept loop"); - return; - }, - // An update that does not raise the flag: keep serving. - Ok(()) => {}, - // The sender is gone. `changed()` would return `Err` immediately - // and forever, so treat it as shutdown instead of spinning. - Err(_) => { - tracing::info!("shutdown channel closed, stopping accept loop"); - return; - }, + _ = shutdown.changed() => { + if *shutdown.borrow() { + tracing::info!("shutdown signal received, stopping accept loop"); + return; } } result = listener.accept() => { let (stream, peer_addr) = match result { - Ok(conn) => { - backoff.reset(); - conn - }, + Ok(conn) => conn, Err(e) => { - if let Some(delay) = backoff.delay(&e) { - if backoff.should_log() { - tracing::error!("accept error, backing off {delay:?}: {e}"); - } else { - tracing::debug!("accept error, backing off {delay:?}: {e}"); - } - tokio::time::sleep(delay).await; - } else { - tracing::debug!("accept error: {e}"); - } + tracing::error!("accept error: {e}"); continue; - }, + } }; let gateway = Arc::clone(&gateway); let hook = Arc::clone(&hook); diff --git a/src/engine/subnet/monitor.rs b/src/engine/subnet/monitor.rs index 00fd93e..e2a0ec2 100644 --- a/src/engine/subnet/monitor.rs +++ b/src/engine/subnet/monitor.rs @@ -6,7 +6,6 @@ use crate::config::DetectPrefixConfig; use crate::engine::subnet_tracker::{SubnetTracker, TrackerSource}; -use crate::filter::blacklist::Blacklist; use crate::metrics; #[cfg(feature = "xdp")] use crate::traffic::prefix::XdpPrefixStats; @@ -31,22 +30,6 @@ impl Source { Source::Tracker(tracker) => tracker.snapshot().await, } } - - /// Whether the source reports distinct source addresses per prefix. - fn counts_unique_sources(&self) -> bool { - match self { - #[cfg(feature = "xdp")] - Source::Xdp(_) => false, - Source::Tracker(_) => true, - } - } -} - -/// Verdict enforcement settings shared by every snapshot tick. -struct BanPolicy { - blacklist: Arc, - ttl: Duration, - trusted: bool, } /// Spawns the background subnet monitor when `[detect.prefix] enabled`. @@ -54,16 +37,8 @@ struct BanPolicy { /// Source priority: the XDP map when a filter is loaded, otherwise the userspace /// aggregator. Without either source the monitor stays disabled and logs a /// warning. -/// -/// `ban_ttl` comes from `[ban].ban_duration_secs`. `trusted_peer` is false when -/// the observed address comes from an unverified ingress path (inbound PROXY -/// protocol), where banning it could punish the transport proxy instead of the -/// real client. pub fn spawn( detect: &DetectPrefixConfig, - ban_ttl: Duration, - blacklist: Arc, - trusted_peer: bool, tracker: Option>, xdp: Option>>, mut shutdown: watch::Receiver, @@ -77,12 +52,6 @@ pub fn spawn( }; let detector = SubnetDetector::from_config(detect); let window = Duration::from_secs(detect.window_secs.max(1)); - let policy = BanPolicy { - blacklist, - ttl: ban_ttl, - trusted: trusted_peer, - }; - let extreme_threshold = detect.syn_threshold.saturating_mul(4); tokio::spawn(async move { let mut tick = tokio::time::interval(window); @@ -97,10 +66,7 @@ pub fn spawn( } _ = tick.tick() => { match source.snapshot().await { - Ok(snaps) => { - let verdicts = detector.evaluate(&snaps); - apply_verdicts(&verdicts, &source, &policy, extreme_threshold); - }, + Ok(snaps) => apply_verdicts(&detector.evaluate(&snaps), &source).await, Err(e) => tracing::debug!("prefix stats unavailable: {e}"), } } @@ -119,7 +85,7 @@ fn build_source(tracker: Option>, xdp: Option= extreme_threshold - { - // XDP does not count distinct sources, so the spoof gate can never - // confirm `Block` on that path; make the cap visible instead of silent. - tracing::info!( - prefix = %pv.prefix, - syn = pv.snapshot.syn_count, - "spoof gate suppressed block: XDP has no source diversity data; escalating at L7 only" - ); + if pv.verdict == SubnetVerdict::Block { + enforce_block(source, pv).await; } } +} + +async fn enforce_block(source: &Source, pv: &PrefixVerdict) { match source { #[cfg(feature = "xdp")] - Source::Xdp(xdp) if policy.trusted => ban_xdp_verdicts(xdp, verdicts, policy.ttl), - #[cfg(feature = "xdp")] - Source::Xdp(_) => { - if verdicts.iter().any(|pv| pv.verdict == SubnetVerdict::Block) { - tracing::warn!("subnet kernel bans suppressed: peer identity comes from an untrusted ingress path"); + Source::Xdp(xdp) => { + let result = { + let guard = xdp.filter_lock(); + guard.ban_cidr(pv.prefix, prefix_len(pv.prefix), 3600) + }; + if let Err(e) = result { + tracing::warn!("subnet block failed for {}: {e}", pv.prefix); } }, Source::Tracker(_) => { - enforce_tracker_verdicts(verdicts, &policy.blacklist, policy.ttl, policy.trusted); - }, - } -} - -/// Applies userspace `Block` verdicts to the shared blacklist. -/// -/// Returns the number of banned prefixes. When `trusted` is false the observed -/// addresses belong to an unverified ingress path, so the verdict is only logged -/// at warn level and no ban is installed. -/// -/// The ban is inserted as a CIDR range, so every address inside the detected -/// `/24` or `/64` is blocked, not just its network address. -pub fn enforce_tracker_verdicts( - verdicts: &[PrefixVerdict], - blacklist: &Blacklist, - ttl: Duration, - trusted: bool, -) -> usize { - let mut banned = 0; - for pv in verdicts.iter().filter(|pv| pv.verdict == SubnetVerdict::Block) { - if !trusted { tracing::warn!( prefix = %pv.prefix, - "subnet block verdict on an untrusted peer path; not adding to the blacklist" + "block verdict without kernel enforcement; escalate at L7" ); - continue; - } - blacklist.add_cidr(pv.prefix, prefix_len(pv.prefix), ttl, "subnet_attack"); - banned += 1; - tracing::warn!( - prefix = %pv.prefix, - ttl_secs = ttl.as_secs(), - "subnet blocked in the userspace blacklist" - ); - } - banned -} - -#[cfg(feature = "xdp")] -fn ban_xdp_verdicts(xdp: &XdpPrefixStats, verdicts: &[PrefixVerdict], ttl: Duration) { - for pv in verdicts.iter().filter(|pv| pv.verdict == SubnetVerdict::Block) { - let result = { - let guard = xdp.filter_lock(); - guard.ban_cidr(pv.prefix, prefix_len(pv.prefix), ttl.as_secs()) - }; - match result { - Ok(()) => tracing::warn!( - prefix = %pv.prefix, - ttl_secs = ttl.as_secs(), - "subnet blocked in XDP" - ), - Err(e) => tracing::warn!("subnet block failed for {}: {e}", pv.prefix), - } + }, } } /// Prefix length matching the detection granularity (v4 /24, v6 /64). +#[cfg(feature = "xdp")] fn prefix_len(prefix: IpAddr) -> u8 { match prefix { IpAddr::V4(_) => 24, diff --git a/src/engine/subnet/tracker.rs b/src/engine/subnet/tracker.rs index 6f3d3b2..817fd76 100644 --- a/src/engine/subnet/tracker.rs +++ b/src/engine/subnet/tracker.rs @@ -4,49 +4,25 @@ //! Fallback path of the subnet detector when XDP is disabled: it feeds //! [`crate::traffic::prefix::SubnetDetector`] with the same snapshot shape the //! kernel map produces. -//! -//! Memory is bounded on purpose. Both the prefix table and the per-prefix -//! source set have hard caps, so a source rotating through a /48 (or a /64 with -//! millions of addresses) cannot grow the tracker without limit during one -//! detection window; over-cap events are counted and reported. use crate::traffic::prefix::{PrefixSnapshot, PrefixStatsSource, prefix_of}; -use std::collections::{HashMap, HashSet}; +use dashmap::DashMap; use std::net::IpAddr; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::time::Instant; -/// Upper bound on tracked prefixes per window. -pub const DEFAULT_MAX_PREFIXES: usize = 4096; - -/// Upper bound on distinct sources remembered per prefix. -/// -/// 256 is well above the default `min_unique_sources = 16` spoof gate while -/// keeping the worst-case table at a few megabytes. -pub const DEFAULT_MAX_SOURCES_PER_PREFIX: usize = 256; - struct WindowState { syn_count: u64, - sources: HashSet, + sources: std::collections::HashSet, started: Instant, } -#[derive(Debug, Clone, Copy)] -struct Limits { - max_prefixes: usize, - max_sources: usize, -} - /// Aggregates new connections per prefix. /// /// `take_snapshot` drains the accumulated state, so every call closes exactly /// one detection window. pub struct SubnetTracker { - windows: Mutex>, - limits: Limits, - dropped_prefixes: AtomicU64, - dropped_sources: AtomicU64, + windows: DashMap, } impl Default for SubnetTracker { @@ -58,108 +34,47 @@ impl Default for SubnetTracker { impl SubnetTracker { #[must_use] pub fn new() -> Self { - Self::with_limits(DEFAULT_MAX_PREFIXES, DEFAULT_MAX_SOURCES_PER_PREFIX) - } - - /// Creates a tracker with explicit caps. - /// - /// Both limits are clamped to at least one entry. The constructor mainly - /// lets tests exercise the caps without building thousands of prefixes. - #[must_use] - pub fn with_limits(max_prefixes: usize, max_sources_per_prefix: usize) -> Self { Self { - windows: Mutex::new(HashMap::new()), - limits: Limits { - max_prefixes: max_prefixes.max(1), - max_sources: max_sources_per_prefix.max(1), - }, - dropped_prefixes: AtomicU64::new(0), - dropped_sources: AtomicU64::new(0), + windows: DashMap::new(), } } /// Records a new inbound connection (userspace equivalent of a SYN). - /// - /// Call it only after the source passed the blacklist check, so banned - /// sources cannot allocate tracker memory. pub fn record_connection(&self, ip: IpAddr) { let prefix = prefix_of(ip); - let mut windows = self.windows.lock().expect("subnet tracker lock poisoned"); - if let Some(state) = windows.get_mut(&prefix) { - state.syn_count = state.syn_count.saturating_add(1); - Self::remember_source(state, ip, self.limits.max_sources, &self.dropped_sources); - return; - } - if windows.len() >= self.limits.max_prefixes { - self.dropped_prefixes.fetch_add(1, Ordering::Relaxed); - return; - } - let mut sources = HashSet::new(); - sources.insert(ip); - windows.insert( - prefix, - WindowState { - syn_count: 1, - sources, - started: Instant::now(), - }, - ); + let mut state = self.windows.entry(prefix).or_insert_with(|| WindowState { + syn_count: 0, + sources: std::collections::HashSet::new(), + started: Instant::now(), + }); + state.syn_count = state.syn_count.saturating_add(1); + state.sources.insert(ip); } /// Takes and resets the aggregates of the current window. #[must_use] pub fn take_snapshot(&self) -> Vec<(IpAddr, PrefixSnapshot)> { - let windows = std::mem::take(&mut *self.windows.lock().expect("subnet tracker lock poisoned")); - let dropped_prefixes = self.dropped_prefixes.load(Ordering::Relaxed); - let dropped_sources = self.dropped_sources.load(Ordering::Relaxed); - if dropped_prefixes > 0 || dropped_sources > 0 { - tracing::debug!( - dropped_prefixes, - dropped_sources, - "subnet tracker caps reached; aggregates are bounded" - ); - } - windows - .into_iter() - .filter(|(_, state)| state.syn_count > 0) - .map(|(prefix, state)| { - ( - prefix, - PrefixSnapshot { - // Userspace only sees established connections, so `pkt_count` mirrors the - // same flow as `syn_count`. - pkt_count: state.syn_count, - syn_count: state.syn_count, - last_seen_ns: state.started.elapsed().as_nanos() as u64, - unique_sources: state.sources.len() as u64, - }, - ) - }) - .collect() - } - - /// Number of connections from new prefixes dropped because the prefix cap - /// was reached. - #[must_use] - pub fn dropped_prefixes(&self) -> u64 { - self.dropped_prefixes.load(Ordering::Relaxed) - } - - /// Number of connections from new source addresses dropped because the - /// per-prefix source cap was reached. - #[must_use] - pub fn dropped_sources(&self) -> u64 { - self.dropped_sources.load(Ordering::Relaxed) - } - - fn remember_source(state: &mut WindowState, ip: IpAddr, cap: usize, dropped: &AtomicU64) { - if state.sources.len() < cap { - state.sources.insert(ip); - return; - } - if !state.sources.contains(&ip) { - dropped.fetch_add(1, Ordering::Relaxed); - } + let mut out = Vec::new(); + // Drain every key: the next window starts from an empty map, so memory does not + // grow when an attacker spoofs many distinct prefixes. + self.windows.retain(|prefix, state| { + if state.syn_count == 0 { + return false; + } + out.push(( + *prefix, + PrefixSnapshot { + // Userspace only sees established connections, so `pkt_count` mirrors the same + // flow as `syn_count`. + pkt_count: state.syn_count, + syn_count: state.syn_count, + last_seen_ns: state.started.elapsed().as_nanos() as u64, + unique_sources: state.sources.len() as u64, + }, + )); + false + }); + out } } @@ -173,3 +88,48 @@ impl PrefixStatsSource for TrackerSource { Ok(self.tracker.take_snapshot()) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::net::{Ipv4Addr, Ipv6Addr}; + + fn v4(octets: [u8; 4]) -> IpAddr { + IpAddr::V4(Ipv4Addr::from(octets)) + } + + #[test] + fn groups_connections_by_prefix() { + let tracker = SubnetTracker::new(); + tracker.record_connection(v4([203, 0, 113, 1])); + tracker.record_connection(v4([203, 0, 113, 2])); + tracker.record_connection(v4([198, 51, 100, 9])); + let snaps = tracker.take_snapshot(); + assert_eq!(snaps.len(), 2); + let by_prefix: std::collections::HashMap = snaps.into_iter().collect(); + assert_eq!(by_prefix[&v4([203, 0, 113, 0])].syn_count, 2); + assert_eq!(by_prefix[&v4([203, 0, 113, 0])].unique_sources, 2); + assert_eq!(by_prefix[&v4([198, 51, 100, 0])].syn_count, 1); + } + + #[test] + fn snapshot_drains_window() { + let tracker = SubnetTracker::new(); + tracker.record_connection(v4([10, 0, 0, 1])); + assert_eq!(tracker.take_snapshot().len(), 1); + assert!(tracker.take_snapshot().is_empty()); + } + + #[test] + fn mapped_addresses_share_v4_prefix() { + let tracker = SubnetTracker::new(); + tracker.record_connection(v4([203, 0, 113, 5])); + // ::ffff:203.0.113.6 + let mapped = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xcb00, 0x7106); + tracker.record_connection(IpAddr::V6(mapped)); + let snaps = tracker.take_snapshot(); + assert_eq!(snaps.len(), 1); + assert_eq!(snaps[0].0, v4([203, 0, 113, 0])); + assert_eq!(snaps[0].1.unique_sources, 2); + } +} diff --git a/src/engine/tunnel/gateway.rs b/src/engine/tunnel/gateway.rs index ebf6d34..670392f 100644 --- a/src/engine/tunnel/gateway.rs +++ b/src/engine/tunnel/gateway.rs @@ -1,16 +1,7 @@ //! Per-connection pipeline of the edge engine: filters, PoW gate, protocol //! handshake and upstream relay. -//! -//! The module root owns gateway construction and the entry point; the stages -//! live in `pipeline` (filters, PoW, handshake, upstream), `admission` -//! (reputation escalation, bans and events) and `relay` (idle-bounded relay). -mod admission; mod challenge; -mod pipeline; -mod relay; - -pub use relay::RELAY_IDLE_TIMEOUT; #[cfg(feature = "protocol-minecraft")] use super::proxy; @@ -21,14 +12,17 @@ use crate::engine::subnet::tracker::SubnetTracker; use crate::filter::blacklist::Blacklist; use crate::filter::connection_limit::ConnectionLimiter; use crate::filter::rate_limit::RateLimiter; +use crate::metrics; use crate::protocol::ProtocolRegistry; -use crate::store::clickhouse::ClickHouseWriter; +use crate::store::clickhouse::{ClickHouseEvent, ClickHouseWriter}; use crate::traffic::reputation::IpReputation; use crate::xdp::XdpFilter; use std::collections::HashSet; use std::net::IpAddr; -use std::sync::atomic::AtomicU64; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::io::AsyncWriteExt; use tokio::net::TcpStream; use tokio::sync::Mutex as TokioMutex; @@ -61,7 +55,7 @@ impl Gateway { allowed_1s, registry, subnet_tracker, - upstream_cursor: std::sync::atomic::AtomicUsize::new(0), + upstream_cursor: AtomicUsize::new(0), } } @@ -75,7 +69,25 @@ impl Gateway { let client_addr = if self.config.proxy_protocol.ingress_enabled { #[cfg(feature = "protocol-minecraft")] { - match proxy::resolve_client_addr(&self.config.proxy_protocol, &mut client, peer_addr).await { + if !self + .config + .proxy_protocol + .trusted_cidrs + .iter() + .any(|cidr| cidr.contains(peer_addr.ip())) + { + return GatewayOutcome { + client_ip: None, + result: Err(anyhow::anyhow!("untrusted peer attempted inbound PROXY protocol")), + }; + } + match proxy::read_v2_header( + &mut client, + Duration::from_millis(self.config.proxy_protocol.ingress_timeout_ms), + self.config.proxy_protocol.max_header_bytes, + ) + .await + { Ok(client_addr) => client_addr, Err(error) => { return GatewayOutcome { @@ -102,4 +114,122 @@ impl Gateway { result, } } + + async fn handle_client( + &self, + mut client: TcpStream, + peer_addr: std::net::SocketAddr, + client_addr: std::net::SocketAddr, + ) -> anyhow::Result<()> { + let peer_ip = client_addr.ip(); + + if let Some(tracker) = &self.subnet_tracker { + tracker.record_connection(peer_ip); + } + + if self.blacklist.is_blocked(peer_ip) { + metrics::CONNECTIONS_TOTAL.with_label_values(&["blocked"]).inc(); + return Ok(()); + } + + let Some(_connection_permit) = self.connection_limiter.try_acquire(peer_ip) else { + self.block_rate_limit(peer_ip).await; + return Ok(()); + }; + + if !self.pass_pow_gate(&mut client, peer_ip).await? { + return Ok(()); + } + + if !self.rate_limiter.check(peer_ip) { + self.block_rate_limit(peer_ip).await; + return Ok(()); + } + + let handler = self.registry.primary()?; + let handshake = match handler.handshake(&mut client).await { + Ok(handshake) => handshake, + Err(e) => { + tracing::debug!("handshake rejected from {peer_addr}: {e}"); + metrics::CONNECTIONS_TOTAL.with_label_values(&["blocked"]).inc(); + return Ok(()); + }, + }; + + metrics::CONNECTIONS_TOTAL.with_label_values(&["allowed"]).inc(); + self.allowed_1s.fetch_add(1, Ordering::Relaxed); + self.reputation.record_good(peer_ip); + + let mut backend = TcpStream::connect(self.next_upstream(&handshake.upstream.addr)).await?; + #[cfg(feature = "protocol-minecraft")] + if self.config.protocol.minecraft.enabled && self.config.protocol.minecraft.send_proxy_protocol { + let source = client_addr; + let destination = client.local_addr()?; + backend.write_all(&proxy::protocol_v2(source, destination)?).await?; + } + if !handshake.initial_backend_data.is_empty() { + backend.write_all(&handshake.initial_backend_data).await?; + } + tokio::io::copy_bidirectional(&mut client, &mut backend).await?; + Ok(()) + } + + fn next_upstream<'a>(&'a self, negotiated: &'a str) -> &'a str { + let upstreams = &self.config.backend.upstreams; + if upstreams.len() > 1 { + let idx = self.upstream_cursor.fetch_add(1, Ordering::Relaxed) % upstreams.len(); + return upstreams[idx].as_str(); + } + if let Some(first) = upstreams.first() { + return first.as_str(); + } + negotiated + } + + async fn block_rate_limit(&self, ip: IpAddr) { + metrics::RATE_LIMIT_HITS.with_label_values(&["hit"]).inc(); + metrics::CONNECTIONS_TOTAL.with_label_values(&["blocked"]).inc(); + self.reputation.record_bad(ip); + if self.reputation.score(ip) < -40 { + let duration_secs = Duration::from_secs(self.config.ban.ban_duration_secs); + self.blacklist.add(ip, duration_secs, "low_reputation"); + if !self.config.proxy_protocol.ingress_enabled { + self.xdp_ban(ip, duration_secs.as_secs()); + } + self.push_event("block", ip, "low_reputation").await; + tracing::info!("low reputation ban {ip}: rate-limit abuse"); + } + } + + fn xdp_ban(&self, ip: IpAddr, duration_secs: u64) { + let Some(xdp) = &self.xdp else { + return; + }; + let prefix_len = if ip.is_ipv4() { 32 } else { 128 }; + match xdp + .lock() + .expect("xdp lock poisoned") + .ban_cidr(ip, prefix_len, duration_secs) + { + Ok(()) => tracing::debug!("xdp ban {ip} for {duration_secs}s"), + Err(e) => tracing::warn!("xdp ban failed for {ip}: {e}"), + } + } + + async fn push_event(&self, event_type: &str, ip: IpAddr, data_string: &str) { + let Some(writer) = &self.clickhouse else { + return; + }; + let event = ClickHouseEvent { + timestamp: chrono::Utc::now(), + event_type: event_type.to_string(), + ip: ip.to_string(), + data_float: 0.0, + data_int: 0, + data_string: data_string.to_string(), + }; + if let Err(e) = writer.lock().await.push(event).await { + tracing::debug!("clickhouse push error: {e}"); + } + } } diff --git a/src/engine/tunnel/gateway/admission.rs b/src/engine/tunnel/gateway/admission.rs deleted file mode 100644 index 92d6227..0000000 --- a/src/engine/tunnel/gateway/admission.rs +++ /dev/null @@ -1,67 +0,0 @@ -//! Reputation escalation, bans and telemetry for dropped connections. - -use super::Gateway; -use crate::metrics; -use crate::store::clickhouse::ClickHouseEvent; -use std::net::IpAddr; -use std::time::Duration; - -impl Gateway { - /// Accounts for a connection dropped by an admission filter and escalates to - /// a ban when the source reputation is exhausted. - /// - /// Whitelisted peers are exempt: a ban is replicated to Redis and XDP on - /// every node, which would lock a trusted operator out of the whole cluster. - pub(super) async fn block_rate_limit(&self, ip: IpAddr) { - if self.whitelist.contains(&ip) { - metrics::RATE_LIMIT_HITS.with_label_values(&["trusted"]).inc(); - return; - } - metrics::RATE_LIMIT_HITS.with_label_values(&["hit"]).inc(); - metrics::CONNECTIONS_TOTAL.with_label_values(&["blocked"]).inc(); - self.reputation.record_bad(ip); - if self.reputation.score(ip) < -40 { - let duration_secs = Duration::from_secs(self.config.ban.ban_duration_secs); - self.blacklist.add(ip, duration_secs, "low_reputation"); - if !self.config.proxy_protocol.ingress_enabled { - self.xdp_ban(ip, duration_secs.as_secs()); - } - self.push_event("block", ip, "low_reputation").await; - tracing::info!("low reputation ban {ip}: rate-limit abuse"); - } - } - - /// Mirrors a ban into the XDP map, if the kernel filter is attached. - fn xdp_ban(&self, ip: IpAddr, duration_secs: u64) { - let Some(xdp) = &self.xdp else { - return; - }; - let prefix_len = if ip.is_ipv4() { 32 } else { 128 }; - match xdp - .lock() - .expect("xdp lock poisoned") - .ban_cidr(ip, prefix_len, duration_secs) - { - Ok(()) => tracing::debug!("xdp ban {ip} for {duration_secs}s"), - Err(e) => tracing::warn!("xdp ban failed for {ip}: {e}"), - } - } - - /// Forwards an event to ClickHouse when the writer is configured. - async fn push_event(&self, event_type: &str, ip: IpAddr, data_string: &str) { - let Some(writer) = &self.clickhouse else { - return; - }; - let event = ClickHouseEvent { - timestamp: chrono::Utc::now(), - event_type: event_type.to_string(), - ip: ip.to_string(), - data_float: 0.0, - data_int: 0, - data_string: data_string.to_string(), - }; - if let Err(e) = writer.lock().await.push(event).await { - tracing::debug!("clickhouse push error: {e}"); - } - } -} diff --git a/src/engine/tunnel/gateway/challenge.rs b/src/engine/tunnel/gateway/challenge.rs index c4f88e0..cc5b159 100644 --- a/src/engine/tunnel/gateway/challenge.rs +++ b/src/engine/tunnel/gateway/challenge.rs @@ -31,10 +31,6 @@ impl Gateway { adjuster.record_connection(); adjuster.current_difficulty() }; - // The configured difficulty is a hard floor even if the adjuster was - // constructed without it; recording the connection above still adapts - // the value for later peers. - let diff = diff.max(pow_config.difficulty); let result = enforce_pow(client, peer_ip, diff).await?; if !result { metrics::POW_CHALLENGES_TOTAL.with_label_values(&["failed"]).inc(); diff --git a/src/engine/tunnel/gateway/pipeline.rs b/src/engine/tunnel/gateway/pipeline.rs deleted file mode 100644 index 2205556..0000000 --- a/src/engine/tunnel/gateway/pipeline.rs +++ /dev/null @@ -1,208 +0,0 @@ -//! Filter order and upstream establishment for one accepted connection. - -use super::Gateway; -use super::RELAY_IDLE_TIMEOUT; -use crate::metrics; -use std::sync::OnceLock; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::time::Duration; -use tokio::io::AsyncWriteExt; -use tokio::net::TcpStream; -use tokio::sync::Semaphore; - -/// Multiplier applied to the per-IP limit when sizing the global connection -/// budget: `4 x workers x max_connections_per_ip` in-flight connections. -const GLOBAL_BUDGET_FACTOR: usize = 4; -/// Ceiling of the global budget, so a large worker count cannot exhaust the -/// file-descriptor table of the host. -const GLOBAL_BUDGET_MAX: usize = 100_000; -/// One in every `BUDGET_LOG_EVERY` budget rejections is logged. -const BUDGET_LOG_EVERY: u64 = 128; - -/// Process-wide in-flight connection budget. -/// -/// Initialised on first use from the worker count and the per-IP limit of the -/// gateway configuration. A process-wide value is intentional: the budget caps -/// descriptors and tasks for the whole edge node, and there is exactly one -/// gateway per process in production. -static GLOBAL_BUDGET: OnceLock = OnceLock::new(); -/// Total connections rejected by the global budget, used for log rate limiting. -static BUDGET_REJECTIONS: AtomicU64 = AtomicU64::new(0); - -impl Gateway { - /// Returns the process-wide in-flight connection budget. - fn global_budget(&self) -> &'static Semaphore { - GLOBAL_BUDGET.get_or_init(|| { - let workers = self.config.workers.count.max(1); - let per_ip = self.config.limits.max_connections_per_ip.max(1) as usize; - let capacity = workers - .saturating_mul(per_ip) - .saturating_mul(GLOBAL_BUDGET_FACTOR) - .clamp(1, GLOBAL_BUDGET_MAX); - Semaphore::new(capacity) - }) - } - - /// Runs the filter stages, PoW gate, protocol handshake and relay. - /// - /// # Errors - /// Only upstream I/O failures are surfaced; every filter drop is `Ok(())`. - pub(super) async fn handle_client( - &self, - mut client: TcpStream, - peer_addr: std::net::SocketAddr, - client_addr: std::net::SocketAddr, - ) -> anyhow::Result<()> { - let peer_ip = client_addr.ip(); - let trusted = self.whitelist.contains(&peer_ip); - - // Trusted peers bypass every ingress filter and are never auto-banned: - // blacklist entries and XDP/Redis bans propagate across all nodes, so a - // whitelisted address must never enter that path. - if !trusted { - if self.blacklist.is_blocked(peer_ip) { - metrics::CONNECTIONS_TOTAL.with_label_values(&["blocked"]).inc(); - return Ok(()); - } - - // Feed the subnet detector only after the ban decision: a source we - // already block must not allocate tracker memory. - if let Some(tracker) = &self.subnet_tracker { - tracker.record_connection(peer_ip); - } - - // The cheap token check runs before the expensive PoW exchange: a - // client that never solves the challenge must still exhaust its own - // rate budget instead of holding a task for the PoW timeout unpaid. - if !self.rate_limiter.check(peer_ip) { - self.block_rate_limit(peer_ip).await; - return Ok(()); - } - } - - // Global budget: `try_acquire` keeps an overloaded node responsive (the - // accept loop never queues unbounded per-connection tasks) and the - // connection is closed immediately on refusal. - let _global_permit = if trusted { - None - } else { - match self.global_budget().try_acquire() { - Ok(permit) => Some(permit), - Err(_) => { - metrics::CONNECTIONS_TOTAL.with_label_values(&["overloaded"]).inc(); - let seen = BUDGET_REJECTIONS.fetch_add(1, Ordering::Relaxed); - if seen % BUDGET_LOG_EVERY == 0 { - tracing::warn!( - "global connection budget exhausted after {seen} rejections, dropping {peer_ip}" - ); - } - return Ok(()); - }, - } - }; - - let Some(_connection_permit) = self.connection_limiter.try_acquire(peer_ip) else { - if trusted { - tracing::debug!("per-IP connection limit reached for trusted {peer_ip}"); - } else { - self.block_rate_limit(peer_ip).await; - } - return Ok(()); - }; - - if !self.pass_pow_gate(&mut client, peer_ip).await? { - return Ok(()); - } - - let handshake_budget = Duration::from_secs(self.config.limits.handshake_timeout_secs.max(1)); - let handler = self.registry.primary()?; - let handshake = match tokio::time::timeout(handshake_budget, handler.handshake(&mut client)).await { - Ok(Ok(handshake)) => handshake, - Ok(Err(e)) => { - tracing::debug!("handshake rejected from {peer_addr}: {e}"); - metrics::CONNECTIONS_TOTAL.with_label_values(&["blocked"]).inc(); - return Ok(()); - }, - Err(_) => { - tracing::debug!("handshake timed out after {handshake_budget:?} from {peer_addr}"); - metrics::CONNECTIONS_TOTAL.with_label_values(&["blocked"]).inc(); - return Ok(()); - }, - }; - - metrics::CONNECTIONS_TOTAL.with_label_values(&["allowed"]).inc(); - self.allowed_1s.fetch_add(1, Ordering::Relaxed); - self.reputation.record_good(peer_ip); - - let mut backend = self - .connect_upstream(&handshake.upstream.addr, handshake_budget) - .await?; - self.send_preamble( - &mut client, - &mut backend, - client_addr, - &handshake.initial_backend_data, - handshake_budget, - ) - .await?; - self.relay_with_idle(client, backend, RELAY_IDLE_TIMEOUT).await - } - - /// Opens the upstream connection under the handshake timeout. - /// - /// # Errors - /// Fails when the connect is refused or exceeds `budget`. - async fn connect_upstream(&self, negotiated: &str, budget: Duration) -> anyhow::Result { - let upstream = self.next_upstream(negotiated); - match tokio::time::timeout(budget, TcpStream::connect(upstream)).await { - Ok(Ok(stream)) => Ok(stream), - Ok(Err(e)) => Err(anyhow::anyhow!("upstream connect to {upstream} failed: {e}")), - Err(_) => Err(anyhow::anyhow!( - "upstream connect to {upstream} timed out after {budget:?}" - )), - } - } - - /// Writes the PROXY protocol header and the protocol's replay bytes to the - /// backend under the handshake timeout. - /// - /// # Errors - /// Fails on address resolution and on a write that exceeds `budget`. - #[allow(unused_variables)] - async fn send_preamble( - &self, - client: &mut TcpStream, - backend: &mut TcpStream, - client_addr: std::net::SocketAddr, - initial_data: &[u8], - budget: Duration, - ) -> anyhow::Result<()> { - let mut preamble = Vec::new(); - #[cfg(feature = "protocol-minecraft")] - if self.config.protocol.minecraft.enabled && self.config.protocol.minecraft.send_proxy_protocol { - let destination = client.local_addr()?; - preamble.extend_from_slice(&super::super::proxy::protocol_v2(client_addr, destination)?); - } - preamble.extend_from_slice(initial_data); - if preamble.is_empty() { - return Ok(()); - } - match tokio::time::timeout(budget, backend.write_all(&preamble)).await { - Ok(Ok(())) => Ok(()), - Ok(Err(e)) => Err(e.into()), - Err(_) => Err(anyhow::anyhow!("upstream preamble write timed out after {budget:?}")), - } - } - - fn next_upstream<'a>(&'a self, negotiated: &'a str) -> &'a str { - let upstreams = &self.config.backend.upstreams; - if upstreams.len() > 1 { - let idx = self.upstream_cursor.fetch_add(1, Ordering::Relaxed) % upstreams.len(); - return upstreams[idx].as_str(); - } - if let Some(first) = upstreams.first() { - return first.as_str(); - } - negotiated - } -} diff --git a/src/engine/tunnel/gateway/relay.rs b/src/engine/tunnel/gateway/relay.rs deleted file mode 100644 index 9ecd994..0000000 --- a/src/engine/tunnel/gateway/relay.rs +++ /dev/null @@ -1,75 +0,0 @@ -//! Idle-aware bidirectional relay between the accepted client and the backend. - -use super::Gateway; -use std::io; -use std::time::Duration; -use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; -use tokio::net::TcpStream; - -const RELAY_BUFFER_BYTES: usize = 16 * 1024; - -/// Idle budget of the client/backend relay. -/// -/// Minecraft keeps one connection alive for a whole session and a legitimately -/// silent gap (menus, chunk loading, AFK timeouts) can last minutes, so 300s is -/// the safe default: it never cuts a real session and still reaps dead peers. -/// The value is a constant because `[limits]` is owned by a parallel change; it -/// is plumbed as a parameter through [`Gateway::relay_with_idle`] so a config -/// field can be wired in without touching the relay itself. -pub const RELAY_IDLE_TIMEOUT: Duration = Duration::from_secs(300); - -impl Gateway { - /// Relays bytes in both directions until either side closes, an I/O error - /// occurs or a direction stays silent for `idle`. - /// - /// The idle budget restarts on every successful read/write, so a long-lived - /// session with steady traffic is never cut, while a dead or half-open peer - /// is reaped instead of pinning two descriptors forever. Both directions run - /// under one `select!`: when one pump finishes the other is dropped and both - /// sockets close, preserving the cancellation semantics of - /// `copy_bidirectional`. - /// - /// `idle` is a parameter rather than a constant so tests can exercise the - /// timeout with a short budget and per-upstream tuning can override it. - /// - /// # Errors - /// Fails on the first I/O error and on an idle timeout; a clean half-close is - /// `Ok`. - pub async fn relay_with_idle(&self, client: TcpStream, backend: TcpStream, idle: Duration) -> anyhow::Result<()> { - let (client_read, mut client_write) = client.into_split(); - let (backend_read, mut backend_write) = backend.into_split(); - tokio::select! { - result = pump(client_read, &mut backend_write, idle) => result?, - result = pump(backend_read, &mut client_write, idle) => result?, - } - Ok(()) - } -} - -/// Copies one direction, bounded by `idle` between chunks. -/// -/// # Errors -/// Fails on a read/write error and when a direction makes no progress within -/// `idle`. -async fn pump(mut source: R, mut sink: W, idle: Duration) -> io::Result<()> -where - R: AsyncRead + Unpin, - W: AsyncWrite + Unpin, -{ - let mut buffer = vec![0u8; RELAY_BUFFER_BYTES]; - loop { - let read = tokio::time::timeout(idle, source.read(&mut buffer)) - .await - .map_err(|_| idle_error())??; - if read == 0 { - return Ok(()); - } - tokio::time::timeout(idle, sink.write_all(&buffer[..read])) - .await - .map_err(|_| idle_error())??; - } -} - -fn idle_error() -> io::Error { - io::Error::new(io::ErrorKind::TimedOut, "relay idle timeout") -} diff --git a/src/engine/tunnel/proxy.rs b/src/engine/tunnel/proxy.rs index d681845..892f0d6 100644 --- a/src/engine/tunnel/proxy.rs +++ b/src/engine/tunnel/proxy.rs @@ -1,38 +1,10 @@ -//! PROXY protocol v2 support: header encoding for the backend and strict -//! parsing of headers injected by trusted ingress peers. +//! Encoding of upstream PROXY protocol v2 headers. -use crate::config::ProxyProtocolConfig; use std::net::SocketAddr; -use std::time::Duration; -use tokio::net::TcpStream; mod inbound; pub(super) use inbound::read_v2_header; -/// Resolves the effective client address from an inbound PROXY v2 header. -/// -/// Only peers inside `config.trusted_cidrs` may inject a header; anyone else -/// is rejected instead of being believed. The whole header must arrive within -/// `config.ingress_timeout_ms` and fit in `config.max_header_bytes`. -/// -/// # Errors -/// Fails when the peer is not trusted, on timeout and on any header parse error. -pub(super) async fn resolve_client_addr( - config: &ProxyProtocolConfig, - client: &mut TcpStream, - peer_addr: SocketAddr, -) -> anyhow::Result { - if !config.trusted_cidrs.iter().any(|cidr| cidr.contains(peer_addr.ip())) { - anyhow::bail!("untrusted peer attempted inbound PROXY protocol"); - } - read_v2_header( - client, - Duration::from_millis(config.ingress_timeout_ms), - config.max_header_bytes, - ) - .await -} - /// Encodes a PROXY protocol v2 TCP header for the backend. /// /// The backend must accept connections only from trusted Rampart nodes, since diff --git a/src/filter/blacklist.rs b/src/filter/blacklist.rs new file mode 100644 index 0000000..e18b533 --- /dev/null +++ b/src/filter/blacklist.rs @@ -0,0 +1,183 @@ +use dashmap::DashMap; +use std::net::IpAddr; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::sync::broadcast; + +const LOCAL_BAN_EVENT_CAPACITY: usize = 4096; + +#[derive(Clone, Debug)] +pub struct LocalBanEvent { + pub ip: IpAddr, + pub expires_at_unix: i64, + pub reason: String, +} + +struct BanEntry { + expires: Instant, + _reason: String, +} + +pub struct Blacklist { + entries: Arc>, + redis_entries: Arc>, + local_ban_events: broadcast::Sender, +} + +impl Default for Blacklist { + fn default() -> Self { + Self::new() + } +} + +impl Blacklist { + pub fn new() -> Self { + let (local_ban_events, _) = broadcast::channel(LOCAL_BAN_EVENT_CAPACITY); + Self { + entries: Arc::new(DashMap::new()), + redis_entries: Arc::new(DashMap::new()), + local_ban_events, + } + } + + pub fn is_blocked(&self, ip: IpAddr) -> bool { + Self::is_blocked_in(&self.entries, ip) || Self::is_blocked_in(&self.redis_entries, ip) + } + + pub fn add(&self, ip: IpAddr, duration: Duration, reason: &str) { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let expires_at_unix = now.saturating_add(duration.as_secs()).min(i64::MAX as u64) as i64; + self.entries.insert( + ip, + BanEntry { + expires: Instant::now() + duration, + _reason: reason.to_string(), + }, + ); + let _ = self.local_ban_events.send(LocalBanEvent { + ip, + expires_at_unix, + reason: reason.to_string(), + }); + } + + pub fn subscribe_local_bans(&self) -> broadcast::Receiver { + self.local_ban_events.subscribe() + } + + pub fn local_snapshot(&self) -> Vec { + self.entries + .iter() + .filter(|entry| entry.expires > Instant::now()) + .map(|entry| LocalBanEvent { + ip: *entry.key(), + expires_at_unix: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs() + .saturating_add(entry.expires.saturating_duration_since(Instant::now()).as_secs()) + .min(i64::MAX as u64) as i64, + reason: entry._reason.clone(), + }) + .collect() + } + + pub fn remove(&self, ip: IpAddr) { + self.entries.remove(&ip); + } + + pub fn add_redis(&self, ip: IpAddr, duration: Duration, reason: &str) { + self.redis_entries.insert( + ip, + BanEntry { + expires: Instant::now() + duration, + _reason: reason.to_string(), + }, + ); + } + + pub fn remove_redis(&self, ip: IpAddr) { + self.redis_entries.remove(&ip); + } + + /// Replaces the Redis-managed ban set, preserving locally detected bans. + /// + /// `redis_entries` is rebuilt from `entries` wholesale, so a ban that + /// disappeared upstream stops applying after this call. + pub fn replace_redis(&self, entries: I) + where + I: IntoIterator, + { + self.redis_entries.clear(); + for (ip, duration, reason) in entries { + self.add_redis(ip, duration, &reason); + } + } + + pub fn len(&self) -> usize { + self.entries.len() + self.redis_entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() && self.redis_entries.is_empty() + } + + pub fn clear_expired(&self) { + self.entries.retain(|_, entry| entry.expires > Instant::now()); + self.redis_entries.retain(|_, entry| entry.expires > Instant::now()); + } + + fn is_blocked_in(entries: &DashMap, ip: IpAddr) -> bool { + if let Some(entry) = entries.get(&ip) { + if entry.expires > Instant::now() { + return true; + } + drop(entry); + entries.remove(&ip); + } + false + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::net::{IpAddr, Ipv4Addr}; + + fn ip(octets: [u8; 4]) -> IpAddr { + IpAddr::V4(Ipv4Addr::from(octets)) + } + + #[test] + fn test_blacklist_block() { + let bl = Blacklist::new(); + bl.add(ip([1, 2, 3, 4]), Duration::from_secs(60), "test"); + assert!(bl.is_blocked(ip([1, 2, 3, 4]))); + } + + #[test] + fn test_blacklist_not_blocked() { + let bl = Blacklist::new(); + bl.add(ip([1, 2, 3, 4]), Duration::from_secs(60), "test"); + assert!(!bl.is_blocked(ip([5, 6, 7, 8]))); + } + + #[test] + fn test_blacklist_expired() { + let bl = Blacklist::new(); + bl.add(ip([1, 2, 3, 4]), Duration::from_millis(1), "test"); + std::thread::sleep(Duration::from_millis(2)); + assert!(!bl.is_blocked(ip([1, 2, 3, 4]))); + } + + #[test] + fn test_blacklist_remove() { + let bl = Blacklist::new(); + bl.add(ip([1, 2, 3, 4]), Duration::from_secs(60), "test"); + bl.remove(ip([1, 2, 3, 4])); + assert!(!bl.is_blocked(ip([1, 2, 3, 4]))); + } +} diff --git a/src/filter/blacklist/mod.rs b/src/filter/blacklist/mod.rs deleted file mode 100644 index aff0ab7..0000000 --- a/src/filter/blacklist/mod.rs +++ /dev/null @@ -1,235 +0,0 @@ -//! In-memory ban tables. -//! -//! Two tables are kept: bans detected locally and bans mirrored from Redis. -//! Expired entries are removed lazily on lookup and periodically by -//! [`Blacklist::clear_expired`]. Deadlines are monotonic and clamped, so a -//! hostile expiry can never overflow or panic. - -mod prefix; - -use self::prefix::PrefixBans; -use dashmap::DashMap; -use std::collections::HashSet; -use std::net::IpAddr; -use std::sync::Arc; -use std::time::{Duration, Instant}; -use tokio::sync::broadcast; - -const LOCAL_BAN_EVENT_CAPACITY: usize = 4096; - -/// Upper bound for a single ban; longer requests are clamped. -pub const MAX_BAN_DURATION_SECS: u64 = 31_536_000; - -/// A locally detected ban, forwarded to the Redis publisher. -#[derive(Clone, Debug)] -pub struct LocalBanEvent { - pub ip: IpAddr, - /// Wall-clock expiry as Unix seconds. - pub expires_at_unix: i64, - pub reason: String, -} - -struct BanEntry { - expires: Instant, - _reason: String, -} - -/// Combined view of local and Redis-mirrored bans. -pub struct Blacklist { - entries: Arc>, - redis_entries: Arc>, - prefixes: PrefixBans, - local_ban_events: broadcast::Sender, -} - -impl Default for Blacklist { - fn default() -> Self { - Self::new() - } -} - -impl Blacklist { - /// Creates an empty blacklist. - pub fn new() -> Self { - let (local_ban_events, _) = broadcast::channel(LOCAL_BAN_EVENT_CAPACITY); - Self { - entries: Arc::new(DashMap::new()), - redis_entries: Arc::new(DashMap::new()), - prefixes: PrefixBans::new(), - local_ban_events, - } - } - - /// Returns whether `ip` is banned: exact match or inside a CIDR ban. - pub fn is_blocked(&self, ip: IpAddr) -> bool { - let ip = normalize(ip); - Self::is_blocked_in(&self.entries, ip) - || Self::is_blocked_in(&self.redis_entries, ip) - || self.prefixes.is_blocked(ip, Instant::now()) - } - - /// Adds a CIDR ban covering `ip/prefix_len` and broadcasts its network - /// address, so other nodes mirror at least that host. - /// - /// Invalid prefix lengths (`0`, `> 32` for IPv4, `> 128` for IPv6) are - /// ignored: a `/0` ban would blackhole the whole address family. - pub fn add_cidr(&self, ip: IpAddr, prefix_len: u8, duration: Duration, reason: &str) { - let duration = clamp_duration(duration); - let Some(start) = self.prefixes.add(ip, prefix_len, deadline(duration)) else { - tracing::warn!(%ip, prefix_len, "ignoring CIDR ban with an invalid prefix length"); - return; - }; - let expires_at_unix = now_unix().saturating_add(duration.as_secs()).min(i64::MAX as u64) as i64; - let _ = self.local_ban_events.send(LocalBanEvent { - ip: start, - expires_at_unix, - reason: reason.to_string(), - }); - } - - /// Adds a local ban and broadcasts it for the Redis publisher. - pub fn add(&self, ip: IpAddr, duration: Duration, reason: &str) { - let ip = normalize(ip); - let duration = clamp_duration(duration); - let expires_at_unix = now_unix().saturating_add(duration.as_secs()).min(i64::MAX as u64) as i64; - self.entries.insert( - ip, - BanEntry { - expires: deadline(duration), - _reason: reason.to_string(), - }, - ); - let _ = self.local_ban_events.send(LocalBanEvent { - ip, - expires_at_unix, - reason: reason.to_string(), - }); - } - - /// Subscribes to locally detected bans. - pub fn subscribe_local_bans(&self) -> broadcast::Receiver { - self.local_ban_events.subscribe() - } - - /// Returns all active local bans. - pub fn local_snapshot(&self) -> Vec { - let now = Instant::now(); - let now_unix = now_unix(); - self.entries - .iter() - .filter(|entry| entry.expires > now) - .map(|entry| LocalBanEvent { - ip: *entry.key(), - expires_at_unix: now_unix - .saturating_add(entry.expires.saturating_duration_since(now).as_secs()) - .min(i64::MAX as u64) as i64, - reason: entry._reason.clone(), - }) - .collect() - } - - /// Removes a local ban. - pub fn remove(&self, ip: IpAddr) { - self.entries.remove(&normalize(ip)); - } - - /// Adds a Redis-mirrored ban. - pub fn add_redis(&self, ip: IpAddr, duration: Duration, reason: &str) { - let ip = normalize(ip); - let duration = clamp_duration(duration); - self.redis_entries.insert( - ip, - BanEntry { - expires: deadline(duration), - _reason: reason.to_string(), - }, - ); - } - - /// Removes a Redis-mirrored ban. - pub fn remove_redis(&self, ip: IpAddr) { - self.redis_entries.remove(&normalize(ip)); - } - - /// Replaces the Redis-managed ban set, preserving locally detected bans. - /// - /// New entries are inserted before stale ones are removed, so a reconnect - /// never exposes a window without bans. A ban that disappeared upstream - /// stops applying after this call. - pub fn replace_redis(&self, entries: I) - where - I: IntoIterator, - { - let mut fresh = HashSet::new(); - for (ip, duration, reason) in entries { - fresh.insert(ip); - self.add_redis(ip, duration, &reason); - } - self.redis_entries.retain(|ip, _| fresh.contains(ip)); - } - - /// Total number of tracked bans. - pub fn len(&self) -> usize { - self.entries.len() + self.redis_entries.len() + self.prefixes.len() - } - - /// Returns whether all ban tables are empty. - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Drops expired entries from all tables. - pub fn clear_expired(&self) { - let now = Instant::now(); - self.entries.retain(|_, entry| entry.expires > now); - self.redis_entries.retain(|_, entry| entry.expires > now); - self.prefixes.clear_expired(now); - } - - /// Checks `entries`, lazily removing `ip` only if it is still expired. - /// - /// The conditional removal avoids a TOCTOU race in which a concurrent - /// re-ban would be deleted right after the expired entry was observed. - fn is_blocked_in(entries: &DashMap, ip: IpAddr) -> bool { - let now = Instant::now(); - if let Some(entry) = entries.get(&ip) - && entry.expires > now - { - return true; - } - entries.remove_if(&ip, |_, entry| entry.expires <= now); - false - } -} - -/// Collapses IPv4-mapped IPv6 addresses to IPv4, so one client never occupies -/// two different keys in the ban tables. -fn normalize(ip: IpAddr) -> IpAddr { - match ip { - IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4), - IpAddr::V4(_) => ip, - } -} - -/// Clamps a requested duration to [`MAX_BAN_DURATION_SECS`]. -fn clamp_duration(duration: Duration) -> Duration { - duration.min(Duration::from_secs(MAX_BAN_DURATION_SECS)) -} - -/// Returns the monotonic deadline for an already clamped duration. -/// -/// Overflow cannot occur for clamped values, but is handled defensively so a -/// malformed duration can never panic the data plane. -fn deadline(duration: Duration) -> Instant { - Instant::now() - .checked_add(duration) - .unwrap_or_else(|| Instant::now() + Duration::from_secs(MAX_BAN_DURATION_SECS)) -} - -/// Current wall-clock time as Unix seconds. -fn now_unix() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_secs() -} diff --git a/src/filter/blacklist/prefix.rs b/src/filter/blacklist/prefix.rs deleted file mode 100644 index a465ac1..0000000 --- a/src/filter/blacklist/prefix.rs +++ /dev/null @@ -1,119 +0,0 @@ -//! CIDR ban table. -//! -//! Exact-address bans live in two `DashMap`s in [`super`]; substrate-wide bans -//! (`/24`, `/64`, ...) are stored here as inclusive address ranges. The table is -//! a plain `RwLock>`: entries are few (the subnet monitor bans at most a -//! handful per tick), so a linear scan is cheaper than a trie, and the hard cap -//! bounds the worst case under abuse. - -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -use std::sync::RwLock; -use std::time::Instant; - -/// Upper bound on distinct CIDR bans kept in memory. -const MAX_PREFIX_BANS: usize = 256; - -/// One CIDR ban, stored as an inclusive address range. -struct PrefixBan { - start: IpAddr, - end: IpAddr, - expires: Instant, -} - -/// Thread-safe set of active CIDR bans. -pub(super) struct PrefixBans { - entries: RwLock>, -} - -impl PrefixBans { - /// Creates an empty table. - pub(super) fn new() -> Self { - Self { - entries: RwLock::new(Vec::new()), - } - } - - /// Inserts `ip/prefix_len` until `expires`. - /// - /// Returns the network address when the ban was inserted, or `None` for an - /// invalid prefix length (`0`, `> 32` for IPv4, `> 128` for IPv6): a `/0` - /// ban would blackhole an entire address family. - pub(super) fn add(&self, ip: IpAddr, prefix_len: u8, expires: Instant) -> Option { - let (start, end) = cidr_range(ip, prefix_len)?; - let now = Instant::now(); - let mut bans = self.entries.write().unwrap_or_else(|poison| poison.into_inner()); - bans.retain(|ban| ban.expires > now); - if bans.len() >= MAX_PREFIX_BANS { - bans.remove(0); - } - bans.push(PrefixBan { start, end, expires }); - Some(start) - } - - /// Returns whether `ip` falls into an active CIDR ban. - pub(super) fn is_blocked(&self, ip: IpAddr, now: Instant) -> bool { - let bans = self.entries.read().unwrap_or_else(|poison| poison.into_inner()); - bans.iter().any(|ban| ban.expires > now && range_contains(ban, ip)) - } - - /// Drops expired CIDR bans. - pub(super) fn clear_expired(&self, now: Instant) { - self.entries - .write() - .unwrap_or_else(|poison| poison.into_inner()) - .retain(|ban| ban.expires > now); - } - - /// Number of tracked CIDR bans (including not-yet-reaped expired ones). - pub(super) fn len(&self) -> usize { - self.entries.read().unwrap_or_else(|poison| poison.into_inner()).len() - } -} - -/// Converts `ip/prefix_len` into an inclusive address range. -/// -/// IPv4-mapped IPv6 addresses are normalised to IPv4 first, matching the prefix -/// keys used by the subnet detector and the XDP prefix stats. -fn cidr_range(ip: IpAddr, prefix_len: u8) -> Option<(IpAddr, IpAddr)> { - let ip = match ip { - IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4), - IpAddr::V4(_) => ip, - }; - match ip { - IpAddr::V4(v4) => { - if prefix_len == 0 || prefix_len > 32 { - return None; - } - let mask = u32::MAX << (32 - prefix_len); - let base = u32::from(v4) & mask; - Some(( - IpAddr::V4(Ipv4Addr::from(base)), - IpAddr::V4(Ipv4Addr::from(base | !mask)), - )) - }, - IpAddr::V6(v6) => { - if prefix_len == 0 || prefix_len > 128 { - return None; - } - let mask = u128::MAX << (128 - prefix_len); - let base = u128::from(v6) & mask; - Some(( - IpAddr::V6(Ipv6Addr::from(base)), - IpAddr::V6(Ipv6Addr::from(base | !mask)), - )) - }, - } -} - -/// Returns whether `ip` is inside `ban`'s inclusive range. -fn range_contains(ban: &PrefixBan, ip: IpAddr) -> bool { - match (ban.start, ban.end, ip) { - (IpAddr::V4(start), IpAddr::V4(end), IpAddr::V4(addr)) => { - u32::from(start) <= u32::from(addr) && u32::from(addr) <= u32::from(end) - }, - (IpAddr::V6(start), IpAddr::V6(end), IpAddr::V6(addr)) => { - u128::from(start) <= u128::from(addr) && u128::from(addr) <= u128::from(end) - }, - _ => false, - } -} diff --git a/src/filter/rate_limit.rs b/src/filter/rate_limit.rs index c857792..76a8305 100644 --- a/src/filter/rate_limit.rs +++ b/src/filter/rate_limit.rs @@ -1,175 +1,155 @@ -//! Per-source token-bucket rate limiter for the accept path. -//! -//! # Capacity policy -//! -//! The bucket table is a hard-bounded sharded hash map: at most `max_buckets` -//! live buckets (one million for [`RateLimiter::new`]). Admission uses an -//! atomic reservation, so concurrent accept loops cannot overshoot the bound -//! the way a plain `len()` check would. -//! -//! # Saturation policy -//! -//! When the table is full, [`RateLimiter::check`] fails closed for a *new* -//! source: the connection is rejected until [`RateLimiter::sweep`] frees a -//! slot. Existing sources keep their token state and are never refused because -//! of the cap. Failing closed is deliberate for a protection device - the -//! alternative (unbounded buckets, or silently allowing everything once the -//! table is full) turns a memory exhaustion vector into a bypass. -//! -//! # Eviction policy -//! -//! [`RateLimiter::sweep`] visits eight of the sixty-four shards and drops -//! buckets idle for longer than `eviction_idle` (ten minutes by default). Work -//! per call is bounded, so the accept path never stalls on a full-table -//! `retain`, and one full cycle takes eight one-minute ticks. - -use std::collections::HashMap; -use std::collections::hash_map::RandomState; -use std::hash::BuildHasher; +use dashmap::DashMap; use std::net::IpAddr; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, Instant}; -/// Default hard bound of the bucket table (one million sources). const MAX_BUCKETS: usize = 1_000_000; -/// Default idle age after which a bucket may be reclaimed. const EVICTION_IDLE: Duration = Duration::from_secs(600); -/// Number of independently locked map shards. -const SHARDS: usize = 64; -/// Shards examined by one [`RateLimiter::sweep`] call. -const SWEEP_SHARDS_PER_TICK: usize = 8; +const SWEEP_INTERVAL: Duration = Duration::from_secs(60); -/// Token-bucket state of one source address. struct Bucket { tokens: f64, last_refill: Instant, last_access: Instant, } -/// Per-source token buckets with a hard capacity bound. pub struct RateLimiter { - shards: Box<[Mutex>]>, - hasher: RandomState, - live: AtomicUsize, - max_buckets: usize, + buckets: Arc>, max_tokens: f64, refill_rate: f64, + _refill_interval: Duration, + epoch: Instant, + last_sweep_elapsed: AtomicU64, eviction_idle: Duration, - sweep_cursor: AtomicUsize, } impl RateLimiter { - /// Builds a limiter with the production capacity policy. - #[must_use] pub fn new(rate_per_sec: f64, burst: f64) -> Self { - Self::with_capacity(rate_per_sec, burst, MAX_BUCKETS, EVICTION_IDLE) + Self::with_eviction(rate_per_sec, burst, EVICTION_IDLE) } - /// Builds a limiter with an explicit capacity policy. - /// - /// `max_buckets` is the hard bound of the table and `eviction_idle` the - /// idle age after which [`Self::sweep`] may reclaim a bucket. [`Self::new`] - /// supplies the production defaults; this constructor exists for tests and - /// for deployments with a tighter memory budget. - #[must_use] - pub fn with_capacity(rate_per_sec: f64, burst: f64, max_buckets: usize, eviction_idle: Duration) -> Self { + fn with_eviction(rate_per_sec: f64, burst: f64, eviction_idle: Duration) -> Self { Self { - shards: (0..SHARDS).map(|_| Mutex::new(HashMap::new())).collect(), - hasher: RandomState::new(), - live: AtomicUsize::new(0), - max_buckets, + buckets: Arc::new(DashMap::new()), max_tokens: burst, refill_rate: rate_per_sec, + _refill_interval: Duration::from_secs(1), + epoch: Instant::now(), + last_sweep_elapsed: AtomicU64::new(0), eviction_idle, - sweep_cursor: AtomicUsize::new(0), } } - /// Consumes one token for `ip`, returning `false` when the source is over - /// its rate or the table is saturated (see the module documentation). pub fn check(&self, ip: IpAddr) -> bool { let now = Instant::now(); - let index = self.shard_index(ip); - let mut shard = self.lock(index); - if let Some(bucket) = shard.get_mut(&ip) { - return refill_and_take(bucket, now, self.max_tokens, self.refill_rate); - } - if !self.reserve() { - return false; - } - let mut bucket = Bucket { + let mut entry = self.buckets.entry(ip).or_insert_with(|| Bucket { tokens: self.max_tokens, last_refill: now, last_access: now, - }; - let allowed = refill_and_take(&mut bucket, now, self.max_tokens, self.refill_rate); - shard.insert(ip, bucket); - allowed + }); + + let elapsed = now.duration_since(entry.last_refill); + let refill = elapsed.as_secs_f64() * self.refill_rate; + entry.tokens = (entry.tokens + refill).min(self.max_tokens); + entry.last_refill = now; + entry.last_access = now; + + if entry.tokens >= 1.0 { + entry.tokens -= 1.0; + true + } else { + false + } } - /// Number of live buckets. - #[must_use] pub fn len(&self) -> usize { - (0..self.shards.len()).map(|index| self.lock(index).len()).sum() + self.buckets.len() } - /// Whether the table is empty. - #[must_use] pub fn is_empty(&self) -> bool { - self.len() == 0 + self.buckets.is_empty() } - /// Evicts idle buckets from the next shard slice and returns how many were - /// removed. See the eviction policy in the module documentation. - pub fn sweep(&self) -> usize { + /// Evicts idle buckets. + /// + /// Runs either when the table grows past `MAX_BUCKETS` (cap enforcement) + /// or once per `SWEEP_INTERVAL`. Buckets touched within `eviction_idle` + /// survive, so active sources keep their token state. + pub fn sweep(&self) { let now = Instant::now(); - let shard_count = self.shards.len(); - let start = self.sweep_cursor.fetch_add(SWEEP_SHARDS_PER_TICK, Ordering::Relaxed); - let mut removed = 0; - for offset in 0..SWEEP_SHARDS_PER_TICK.min(shard_count) { - let index = (start + offset) % shard_count; - let mut shard = self.lock(index); - let before = shard.len(); - shard.retain(|_, bucket| now.duration_since(bucket.last_access) < self.eviction_idle); - removed += before - shard.len(); + let elapsed_secs = now.duration_since(self.epoch).as_secs(); + let last = self.last_sweep_elapsed.load(Ordering::Relaxed); + let due = last == 0 || elapsed_secs.saturating_sub(last) >= SWEEP_INTERVAL.as_secs(); + let over_cap = self.buckets.len() > MAX_BUCKETS; + if !over_cap && !due { + return; } - if removed > 0 { - self.live.fetch_sub(removed, Ordering::AcqRel); - } - removed - } - - /// Reserves one slot in the table, enforcing the hard bound. - fn reserve(&self) -> bool { - let live = self.live.fetch_add(1, Ordering::AcqRel); - if live >= self.max_buckets { - self.live.fetch_sub(1, Ordering::AcqRel); - return false; - } - true - } - - fn shard_index(&self, ip: IpAddr) -> usize { - (self.hasher.hash_one(ip) as usize) % self.shards.len() - } - - fn lock(&self, index: usize) -> MutexGuard<'_, HashMap> { - // A poisoned shard still holds consistent token buckets; keep serving - // instead of taking the whole limiter down. - self.shards[index].lock().unwrap_or_else(|poison| poison.into_inner()) + self.buckets + .retain(|_, b| now.duration_since(b.last_access) < self.eviction_idle); + self.last_sweep_elapsed.store(elapsed_secs, Ordering::Relaxed); } } -fn refill_and_take(bucket: &mut Bucket, now: Instant, max_tokens: f64, refill_rate: f64) -> bool { - let elapsed = now.duration_since(bucket.last_refill); - bucket.tokens = (bucket.tokens + elapsed.as_secs_f64() * refill_rate).min(max_tokens); - bucket.last_refill = now; - bucket.last_access = now; - if bucket.tokens >= 1.0 { - bucket.tokens -= 1.0; - true - } else { - false +#[cfg(test)] +mod tests { + use super::*; + use std::net::{IpAddr, Ipv4Addr}; + + fn test_ip(octet: u8) -> IpAddr { + IpAddr::V4(Ipv4Addr::new(10, 0, 0, octet)) + } + + #[test] + fn test_rate_limit_under() { + let limiter = RateLimiter::new(10.0, 10.0); + assert!(limiter.check(test_ip(1))); + } + + #[test] + fn test_rate_limit_over() { + let limiter = RateLimiter::new(1.0, 1.0); + assert!(limiter.check(test_ip(1))); + assert!(!limiter.check(test_ip(1))); + } + + #[test] + fn test_rate_limit_burst() { + let limiter = RateLimiter::new(1.0, 5.0); + for _ in 0..5 { + assert!(limiter.check(test_ip(2))); + } + assert!(!limiter.check(test_ip(2))); + } + + #[test] + fn test_rate_limit_refill() { + let limiter = RateLimiter::new(100.0, 1.0); + assert!(limiter.check(test_ip(3))); + assert!(!limiter.check(test_ip(3))); + std::thread::sleep(Duration::from_millis(20)); + assert!(limiter.check(test_ip(3))); + } + + #[test] + fn test_sweep_removes_idle_keeps_active() { + let limiter = RateLimiter::with_eviction(1.0, 10.0, Duration::from_millis(20)); + limiter.check(test_ip(1)); + limiter.check(test_ip(2)); + std::thread::sleep(Duration::from_millis(50)); + limiter.check(test_ip(2)); + limiter.sweep(); + assert_eq!(limiter.len(), 1); + assert!(!limiter.buckets.contains_key(&test_ip(1))); + assert!(limiter.buckets.contains_key(&test_ip(2))); + } + + #[test] + fn test_sweep_does_not_remove_active() { + let limiter = RateLimiter::with_eviction(1.0, 10.0, Duration::from_millis(50)); + limiter.check(test_ip(1)); + limiter.sweep(); + assert_eq!(limiter.len(), 1); + assert!(limiter.buckets.contains_key(&test_ip(1))); } } diff --git a/src/manager/api/auth.rs b/src/manager/api/auth.rs index 4d60333..8c0e491 100644 --- a/src/manager/api/auth.rs +++ b/src/manager/api/auth.rs @@ -1,5 +1,3 @@ -//! `POST /api/v1/auth/login`: password check with a per-IP attempt limiter. - use crate::manager::AppState; use axum::{ Json, @@ -13,6 +11,7 @@ use std::{ sync::Arc, time::{Duration, Instant}, }; +use subtle::ConstantTimeEq; const LOGIN_WINDOW: Duration = Duration::from_secs(60); const LOGIN_MAX_ATTEMPTS: u32 = 5; @@ -34,7 +33,7 @@ pub async fn login( )); } - if !crate::manager::security::verify_password(&req.password, &state.api_password) { + if !verify_password(&req.password, &state.api_password) { return Err(( StatusCode::UNAUTHORIZED, Json(serde_json::json!({"error": "invalid password"})), @@ -50,11 +49,16 @@ pub async fn login( } } -/// Records a login attempt for `ip` and reports whether it is within the window. -/// -/// The limiter allows `LOGIN_MAX_ATTEMPTS` attempts per `LOGIN_WINDOW` and -/// resets the counter when the window elapses. -pub fn allow_login_attempt(limiter: &DashMap, ip: IpAddr) -> bool { +fn verify_password(provided: &str, expected: &str) -> bool { + let provided = provided.as_bytes(); + let expected = expected.as_bytes(); + let len_match = (provided.len() as u64).ct_eq(&(expected.len() as u64)); + let min_len = provided.len().min(expected.len()); + let bytes_match = provided[..min_len].ct_eq(&expected[..min_len]); + bool::from(len_match & bytes_match) +} + +fn allow_login_attempt(limiter: &DashMap, ip: IpAddr) -> bool { let now = Instant::now(); let mut slot = limiter.entry(ip).or_insert((now, 0)); let (last_reset, attempts) = &mut *slot; @@ -68,3 +72,33 @@ pub fn allow_login_attempt(limiter: &DashMap, ip: IpAddr } true } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verify_password_matches() { + assert!(verify_password("s3cret-pass", "s3cret-pass")); + } + + #[test] + fn verify_password_rejects_wrong() { + assert!(!verify_password("wrong-pass", "s3cret-pass")); + } + + #[test] + fn verify_password_rejects_different_length() { + assert!(!verify_password("short", "a-longer-password")); + } + + #[test] + fn allow_login_attempt_respects_limit() { + let limiter = DashMap::new(); + let ip = IpAddr::from([127, 0, 0, 1]); + for _ in 0..LOGIN_MAX_ATTEMPTS { + assert!(allow_login_attempt(&limiter, ip)); + } + assert!(!allow_login_attempt(&limiter, ip)); + } +} diff --git a/src/manager/mod.rs b/src/manager/mod.rs index 4ccaf84..0f5b051 100644 --- a/src/manager/mod.rs +++ b/src/manager/mod.rs @@ -3,7 +3,6 @@ //! Owns [`AppState`], the handle shared by every handler through [`SharedState`]. pub mod api; pub mod auth; -pub mod security; pub mod sync; use dashmap::DashMap; diff --git a/src/manager/security.rs b/src/manager/security.rs deleted file mode 100644 index 305b45e..0000000 --- a/src/manager/security.rs +++ /dev/null @@ -1,135 +0,0 @@ -//! Startup security policy of the management plane. -//! -//! Weak credentials turn the control plane API into an authentication bypass: -//! an empty `API_PASSWORD` matches an empty login, and a guessable -//! `JWT_SECRET` lets anyone mint admin tokens. The manager validates both -//! before it binds a socket, and derives its CORS policy from an explicit -//! `CORS_ORIGIN` value instead of silently allowing every origin. - -use anyhow::{Result, bail}; -use subtle::ConstantTimeEq; -use tower_http::cors::{AllowOrigin, Any, CorsLayer}; - -/// Minimum length of `API_PASSWORD` in characters. -const MIN_API_PASSWORD_CHARS: usize = 16; -/// Minimum number of non-whitespace bytes in `JWT_SECRET`. -const MIN_JWT_SECRET_BYTES: usize = 32; -/// Placeholder password shipped in documentation and examples. -const DEFAULT_API_PASSWORD: &str = "changeme"; - -/// Validates `API_PASSWORD` before the manager starts serving. -/// -/// # Errors -/// Rejects an empty or whitespace-only password, a password shorter than -/// `MIN_API_PASSWORD_CHARS` characters, and the `changeme` placeholder. -pub fn validate_api_password(password: &str) -> Result<()> { - let trimmed = password.trim(); - if trimmed.is_empty() { - bail!("API_PASSWORD must not be empty: an empty password would accept an empty login"); - } - if trimmed.chars().count() < MIN_API_PASSWORD_CHARS { - bail!("API_PASSWORD must be at least {MIN_API_PASSWORD_CHARS} characters long"); - } - if trimmed.eq_ignore_ascii_case(DEFAULT_API_PASSWORD) { - bail!("API_PASSWORD must not be the default placeholder '{DEFAULT_API_PASSWORD}'"); - } - Ok(()) -} - -/// Validates `JWT_SECRET` before the manager starts serving. -/// -/// # Errors -/// Rejects a secret with fewer than `MIN_JWT_SECRET_BYTES` non-whitespace -/// bytes, which includes empty and all-whitespace secrets. -pub fn validate_jwt_secret(secret: &str) -> Result<()> { - let significant = secret.bytes().filter(|byte| !byte.is_ascii_whitespace()).count(); - if significant < MIN_JWT_SECRET_BYTES { - bail!("JWT_SECRET must contain at least {MIN_JWT_SECRET_BYTES} non-whitespace bytes, got {significant}"); - } - Ok(()) -} - -/// Compares a login password with the configured one in constant time. -/// -/// An empty stored password never verifies: that is the authentication bypass -/// the startup policy ([`validate_api_password`]) rules out, and the handler -/// keeps the same guarantee for any state built by other code paths. -#[must_use] -pub fn verify_password(provided: &str, expected: &str) -> bool { - if expected.is_empty() { - return false; - } - let provided = provided.as_bytes(); - let expected = expected.as_bytes(); - let len_match = (provided.len() as u64).ct_eq(&(expected.len() as u64)); - let min_len = provided.len().min(expected.len()); - let bytes_match = provided[..min_len].ct_eq(&expected[..min_len]); - bool::from(len_match & bytes_match) -} - -/// Cross-origin resource sharing policy derived from `CORS_ORIGIN`. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum CorsPolicy { - /// No cross-origin layer at all: browsers on other origins are denied. - Deny, - /// Every origin is allowed; requires an explicit `CORS_ORIGIN=*`. - Any, - /// Only the listed origins are allowed. - AllowList(Vec), -} - -impl CorsPolicy { - /// Parses the raw `CORS_ORIGIN` value. - /// - /// An unset or empty variable denies cross-origin access, `*` must be set - /// explicitly to allow any origin, and anything else is a comma-separated - /// list of origins. - /// - /// # Errors - /// Fails on an empty entry, on a wildcard mixed with concrete origins, and - /// on an entry that is not a valid HTTP header value. - pub fn parse(raw: Option<&str>) -> Result { - let Some(raw) = raw else { - return Ok(Self::Deny); - }; - let raw = raw.trim(); - if raw.is_empty() { - return Ok(Self::Deny); - } - if raw == "*" { - return Ok(Self::Any); - } - let mut origins = Vec::new(); - for entry in raw.split(',') { - let origin = entry.trim(); - if origin.is_empty() { - bail!("CORS_ORIGIN contains an empty origin entry"); - } - if origin == "*" { - bail!("CORS_ORIGIN wildcard '*' must be used alone, not inside an origin list"); - } - axum::http::HeaderValue::from_str(origin) - .map_err(|_| anyhow::anyhow!("CORS_ORIGIN entry '{origin}' is not a valid HTTP header value"))?; - origins.push(origin.to_owned()); - } - Ok(Self::AllowList(origins)) - } - - /// Builds the axum CORS layer for this policy. - /// - /// Returns `None` for [`CorsPolicy::Deny`] so the router is served without - /// any cross-origin layer. - #[must_use] - pub fn cors_layer(&self) -> Option { - match self { - Self::Deny => None, - Self::Any => Some(CorsLayer::new().allow_origin(Any)), - Self::AllowList(origins) => { - let allowed = origins - .iter() - .filter_map(|origin| axum::http::HeaderValue::from_str(origin).ok()); - Some(CorsLayer::new().allow_origin(AllowOrigin::list(allowed))) - }, - } - } -} diff --git a/src/store/clickhouse.rs b/src/store/clickhouse.rs index 7c1a753..fd1530b 100644 --- a/src/store/clickhouse.rs +++ b/src/store/clickhouse.rs @@ -1,42 +1,13 @@ -//! ClickHouse event sink. -//! -//! The data plane must never block on the sink: [`ClickHouseWriter::push`] only -//! touches memory, while the background task drains a batch under the writer -//! lock and performs network I/O outside of it. Every request is bounded by a -//! request timeout and every flush by a global timeout, so an unreachable or -//! hung ClickHouse degrades into dropped events instead of a stalled daemon. - use chrono::{DateTime, Utc}; -use prometheus::IntCounter; use serde::Serialize; -use std::sync::{Arc, LazyLock}; +use std::sync::Arc; use std::time::Duration; use tokio::sync::Mutex; use tokio::sync::watch; -/// Maximum number of events sent in one INSERT. -pub const BATCH_SIZE: usize = 1000; -/// Hard cap on buffered events; further pushes are dropped and counted. -pub const MAX_BUFFER_EVENTS: usize = 10_000; - +const BATCH_SIZE: usize = 1000; const FLUSH_INTERVAL: Duration = Duration::from_secs(1); -const FLUSH_TIMEOUT: Duration = Duration::from_secs(5); -const REQUEST_TIMEOUT: Duration = Duration::from_secs(2); -const CONNECT_TIMEOUT: Duration = Duration::from_secs(1); -const ERROR_BODY_LIMIT: usize = 512; -/// Batches drained per tick; keeps sustained event rates from backing up. -const MAX_BATCHES_PER_FLUSH: usize = 4; -/// Events discarded because the buffer was full or a retry could not fit. -pub static CLICKHOUSE_DROPPED: LazyLock = LazyLock::new(|| { - prometheus::register_int_counter!( - "rampart_clickhouse_dropped_total", - "ClickHouse events dropped (buffer overflow or failed flush)" - ) - .expect("CLICKHOUSE_DROPPED") -}); - -/// One row of the `rampart_events` table. #[derive(Debug, Clone, Serialize)] pub struct ClickHouseEvent { pub timestamp: DateTime, @@ -47,186 +18,72 @@ pub struct ClickHouseEvent { pub data_string: String, } -/// Buffered ClickHouse writer shared by the data plane and the flush task. pub struct ClickHouseWriter { url: String, client: reqwest::Client, buffer: Vec, - dropped: u64, } impl ClickHouseWriter { - /// Creates a writer for `url` with bounded request and connect timeouts. pub fn new(url: &str) -> Self { - let client = reqwest::Client::builder() - .timeout(REQUEST_TIMEOUT) - .connect_timeout(CONNECT_TIMEOUT) - .build() - .expect("clickhouse http client"); Self { url: url.to_string(), - client, + client: reqwest::Client::new(), buffer: Vec::with_capacity(BATCH_SIZE), - dropped: 0, } } - /// Queues `event` for the next flush. - /// - /// This never performs I/O and never fails; when the buffer is full the - /// event is dropped and counted instead of blocking the data plane. - /// - /// # Errors - /// Currently infallible; the result is kept for API stability. pub async fn push(&mut self, event: ClickHouseEvent) -> anyhow::Result<()> { - if self.buffer.len() >= MAX_BUFFER_EVENTS { - self.record_drop(1); - return Ok(()); - } self.buffer.push(event); + if self.buffer.len() >= BATCH_SIZE { + self.flush().await?; + } Ok(()) } - /// Sends every buffered event, re-queueing the batch on failure. - /// - /// # Errors - /// Returns an error when the insert fails or exceeds `FLUSH_TIMEOUT`; the - /// batch stays buffered for the next attempt. pub async fn flush(&mut self) -> anyhow::Result<()> { - let batch = std::mem::take(&mut self.buffer); - if batch.is_empty() { + if self.buffer.is_empty() { return Ok(()); } - match tokio::time::timeout(FLUSH_TIMEOUT, send_batch(&self.client, &self.url, &batch)).await { - Ok(Ok(())) => { - tracing::debug!(events = batch.len(), "flushed events to clickhouse"); - Ok(()) - }, - Ok(Err(error)) => { - self.requeue_batch(batch); - Err(error) - }, - Err(_) => { - self.requeue_batch(batch); - anyhow::bail!("clickhouse flush timed out after {FLUSH_TIMEOUT:?}") - }, - } - } - - /// Number of events waiting in the buffer. - pub fn pending(&self) -> usize { - self.buffer.len() - } - - /// Number of events this writer discarded. - pub fn dropped(&self) -> u64 { - self.dropped - } - - fn take_batch(&mut self) -> Vec { - let take = self.buffer.len().min(BATCH_SIZE); - self.buffer.drain(..take).collect() - } - - /// Puts a failed batch back in front of the buffer, keeping it bounded. - fn requeue_batch(&mut self, mut batch: Vec) { - batch.append(&mut self.buffer); - if batch.len() > MAX_BUFFER_EVENTS { - let overflow = batch.len() - MAX_BUFFER_EVENTS; - batch.truncate(MAX_BUFFER_EVENTS); - self.record_drop(overflow); - } - self.buffer = batch; - } - - fn record_drop(&mut self, count: usize) { - let count = u64::try_from(count).unwrap_or(u64::MAX); - let first_drop = self.dropped == 0; - self.dropped = self.dropped.saturating_add(count); - CLICKHOUSE_DROPPED.inc_by(count); - // Log once per writer: further drops are visible in the counter only, - // so a sustained outage cannot flood the log. - if first_drop { - tracing::warn!(count, "clickhouse buffer full; dropping events"); + let events = std::mem::take(&mut self.buffer); + let json = serde_json::to_string(&events)?; + let response = self + .client + .post(&self.url) + .query(&[("query", "INSERT INTO rampart_events FORMAT JSONEachRow")]) + .header("Content-Type", "application/json") + .body(json) + .send() + .await?; + let status = response.status(); + if !status.is_success() { + let text = response.text().await?; + anyhow::bail!("clickhouse insert failed ({}): {}", status, text); } + tracing::debug!("flushed {} events to clickhouse", events.len()); + Ok(()) } } -/// Runs the periodic flush loop until shutdown. -/// -/// A closed shutdown channel is treated as a shutdown request: the final -/// flush runs and the task exits instead of busy-looping on `changed()`. pub fn start_flush_task(writer: Arc>, mut shutdown: watch::Receiver) { tokio::spawn(async move { loop { tokio::select! { _ = tokio::time::sleep(FLUSH_INTERVAL) => { - for _ in 0..MAX_BATCHES_PER_FLUSH { - if !flush_batch(&writer).await { - break; - } + if let Err(e) = writer.lock().await.flush().await { + tracing::error!("clickhouse flush error: {e}"); } - }, - changed = shutdown.changed() => { - if changed.is_err() || *shutdown.borrow_and_update() { + } + _ = shutdown.changed() => { + if *shutdown.borrow() { tracing::info!("flushing clickhouse on shutdown"); - flush_batch(&writer).await; + if let Err(e) = writer.lock().await.flush().await { + tracing::error!("clickhouse final flush error: {e}"); + } return; } - }, + } } } }); } - -/// Drains one batch under the lock and sends it without holding the lock. -/// -/// Returns `false` when there was nothing to send or the send failed. -async fn flush_batch(writer: &Arc>) -> bool { - let (client, url, batch) = { - let mut writer = writer.lock().await; - let batch = writer.take_batch(); - (writer.client.clone(), writer.url.clone(), batch) - }; - if batch.is_empty() { - return false; - } - match tokio::time::timeout(FLUSH_TIMEOUT, send_batch(&client, &url, &batch)).await { - Ok(Ok(())) => { - tracing::debug!(events = batch.len(), "flushed events to clickhouse"); - true - }, - Ok(Err(error)) => { - tracing::warn!(%error, events = batch.len(), "clickhouse flush failed; re-queueing"); - requeue_batch(writer, batch).await; - false - }, - Err(_) => { - tracing::warn!(events = batch.len(), "clickhouse flush timed out; re-queueing"); - requeue_batch(writer, batch).await; - false - }, - } -} - -async fn requeue_batch(writer: &Arc>, batch: Vec) { - writer.lock().await.requeue_batch(batch); -} - -async fn send_batch(client: &reqwest::Client, url: &str, batch: &[ClickHouseEvent]) -> anyhow::Result<()> { - let json = serde_json::to_string(batch)?; - let response = client - .post(url) - .query(&[("query", "INSERT INTO rampart_events FORMAT JSONEachRow")]) - .header("Content-Type", "application/json") - .body(json) - .send() - .await?; - let status = response.status(); - if !status.is_success() { - let mut text = response.text().await.unwrap_or_default(); - text.truncate(ERROR_BODY_LIMIT); - anyhow::bail!("clickhouse insert failed ({status}): {text}"); - } - Ok(()) -} diff --git a/src/store/redis.rs b/src/store/redis.rs index bd892c2..721b912 100644 --- a/src/store/redis.rs +++ b/src/store/redis.rs @@ -1,59 +1,41 @@ -//! Redis-backed [`StateStore`] and blacklist synchronisation. -//! -//! Commands share one reconnecting [`ConnectionManager`] and are bounded by -//! `connection::REDIS_TIMEOUT`; pub/sub connections are acquired and -//! subscribed under the same timeout. - use crate::store::StateStore; use redis::AsyncCommands; -use redis::aio::ConnectionManager; -mod backoff; -mod connection; mod sync; - -pub use backoff::{BACKOFF_MAX, BACKOFF_MIN, next_backoff}; pub use sync::{start_blacklist_sync, start_local_ban_publisher}; -/// Redis-backed state store. pub struct RedisStore { - manager: ConnectionManager, + client: redis::Client, } impl RedisStore { - /// Connects to `url` and establishes a reconnecting manager. - /// - /// # Errors - /// Returns an error for an invalid URL, an unreachable server or an attempt - /// that exceeds `connection::REDIS_TIMEOUT`. - pub async fn new(url: &str) -> anyhow::Result { + pub fn new(url: &str) -> anyhow::Result { let client = redis::Client::open(url)?; - let manager = connection::connection_manager(&client).await?; - Ok(Self { manager }) + Ok(Self { client }) } } impl StateStore for RedisStore { async fn get(&self, key: &str) -> anyhow::Result> { - let mut conn = self.manager.clone(); - connection::command(conn.get(key)).await + let mut conn = self.client.get_multiplexed_async_connection().await?; + Ok(conn.get(key).await?) } async fn set(&self, key: &str, value: &str) -> anyhow::Result<()> { - let mut conn = self.manager.clone(); - let _: () = connection::command(conn.set(key, value)).await?; + let mut conn = self.client.get_multiplexed_async_connection().await?; + let _: () = conn.set(key, value).await?; Ok(()) } async fn del(&self, key: &str) -> anyhow::Result<()> { - let mut conn = self.manager.clone(); - let _: () = connection::command(conn.del(key)).await?; + let mut conn = self.client.get_multiplexed_async_connection().await?; + let _: () = conn.del(key).await?; Ok(()) } async fn publish(&self, channel: &str, message: &str) -> anyhow::Result<()> { - let mut conn = self.manager.clone(); - let _: i64 = connection::command(conn.publish(channel, message)).await?; + let mut conn = self.client.get_multiplexed_async_connection().await?; + let _: () = conn.publish(channel, message).await?; Ok(()) } } diff --git a/src/store/redis/backoff.rs b/src/store/redis/backoff.rs deleted file mode 100644 index 7a95c9e..0000000 --- a/src/store/redis/backoff.rs +++ /dev/null @@ -1,14 +0,0 @@ -//! Exponential reconnect backoff shared by the Redis sync tasks. - -use std::time::Duration; - -/// Initial reconnect delay. -pub const BACKOFF_MIN: Duration = Duration::from_secs(1); -/// Upper bound for the reconnect delay. -pub const BACKOFF_MAX: Duration = Duration::from_secs(30); - -/// Doubles `previous`, capped at `max`; never overflows. -#[must_use] -pub fn next_backoff(previous: Duration, max: Duration) -> Duration { - previous.saturating_mul(2).min(max) -} diff --git a/src/store/redis/connection.rs b/src/store/redis/connection.rs deleted file mode 100644 index bf6089e..0000000 --- a/src/store/redis/connection.rs +++ /dev/null @@ -1,36 +0,0 @@ -//! Timeout-bounded Redis connection helpers. -//! -//! Every connect and command in the store layer goes through this module so a -//! stalled server can never block a data-plane or shutdown path. - -use redis::aio::ConnectionManager; -use std::future::Future; -use std::time::Duration; - -/// Maximum time spent on one Redis connect or command. -pub const REDIS_TIMEOUT: Duration = Duration::from_secs(2); - -/// Opens a reconnecting connection manager, bounded by `REDIS_TIMEOUT`. -/// -/// # Errors -/// Returns an error for an unreachable server or a timed-out attempt. -pub async fn connection_manager(client: &redis::Client) -> anyhow::Result { - match tokio::time::timeout(REDIS_TIMEOUT, client.get_connection_manager()).await { - Ok(result) => Ok(result?), - Err(_) => anyhow::bail!("redis connection timed out after {REDIS_TIMEOUT:?}"), - } -} - -/// Awaits a Redis command future, bounded by `REDIS_TIMEOUT`. -/// -/// # Errors -/// Returns an error when the command fails or exceeds the timeout. -pub async fn command(future: F) -> anyhow::Result -where - F: Future>, -{ - match tokio::time::timeout(REDIS_TIMEOUT, future).await { - Ok(result) => Ok(result?), - Err(_) => anyhow::bail!("redis command timed out after {REDIS_TIMEOUT:?}"), - } -} diff --git a/src/store/redis/sync.rs b/src/store/redis/sync.rs index c4042d9..8c25d4d 100644 --- a/src/store/redis/sync.rs +++ b/src/store/redis/sync.rs @@ -1,18 +1,9 @@ -//! Blacklist synchronisation over a Redis pub/sub channel. -//! -//! The subscriber reconciles the durable snapshot on every (re)connect, then -//! applies events. All connects, subscribes and commands are timeout-bounded; -//! a failed attempt backs off exponentially and a panicking handler is logged -//! instead of killing the task. - mod event; mod publisher; mod snapshot; pub use publisher::start_local_ban_publisher; -use super::backoff::{BACKOFF_MAX, BACKOFF_MIN, next_backoff}; -use super::connection::{REDIS_TIMEOUT, connection_manager}; use crate::filter::blacklist::Blacklist; use futures::StreamExt; use std::sync::Arc; @@ -20,17 +11,19 @@ use std::time::Duration; use tokio::sync::watch; const BLACKLIST_CHANNEL: &str = "rampart:blacklist:events"; +const BACKOFF_MIN: Duration = Duration::from_secs(1); +const BACKOFF_MAX: Duration = Duration::from_secs(30); + +fn next_backoff(prev: Duration, max: Duration) -> Duration { + prev.saturating_mul(2).min(max) +} -/// Why a subscription attempt ended. enum Flow { - /// Shutdown was requested. Stop, - /// The attempt failed; reconnect after a backoff delay. Retry, } -/// Resolves once shutdown is requested or the channel is closed. -pub(super) async fn wait_for_shutdown(shutdown: &mut watch::Receiver) { +async fn wait_for_shutdown(shutdown: &mut watch::Receiver) { loop { if shutdown.changed().await.is_err() || *shutdown.borrow_and_update() { return; @@ -38,7 +31,6 @@ pub(super) async fn wait_for_shutdown(shutdown: &mut watch::Receiver) { } } -/// Runs the blacklist subscriber until shutdown. pub async fn start_blacklist_sync( client: &redis::Client, blacklist: Arc, @@ -71,44 +63,30 @@ async fn subscribe_once( backoff: &mut Duration, ) -> Flow { let mut pubsub = tokio::select! { - connected = tokio::time::timeout(REDIS_TIMEOUT, client.get_async_pubsub()) => match connected { - Ok(Ok(pubsub)) => pubsub, - Ok(Err(e)) => { + connected = client.get_async_pubsub() => match connected { + Ok(pubsub) => pubsub, + Err(e) => { tracing::error!("failed to connect to Redis for blacklist sync: {e}"); return Flow::Retry; }, - Err(_) => { - tracing::error!("timed out connecting to Redis for blacklist sync"); - return Flow::Retry; - }, }, () = wait_for_shutdown(shutdown) => return Flow::Stop, }; tokio::select! { - subscribed = tokio::time::timeout(REDIS_TIMEOUT, pubsub.subscribe(BLACKLIST_CHANNEL)) => match subscribed { - Ok(Ok(())) => { - tracing::info!("subscribed to {BLACKLIST_CHANNEL}"); - *backoff = BACKOFF_MIN; - }, - Ok(Err(e)) => { + subscribed = pubsub.subscribe(BLACKLIST_CHANNEL) => match subscribed { + Ok(()) => tracing::info!("subscribed to {BLACKLIST_CHANNEL}"), + Err(e) => { tracing::error!("failed to subscribe to blacklist events: {e}"); return Flow::Retry; }, - Err(_) => { - tracing::error!("timed out subscribing to blacklist events"); - return Flow::Retry; - }, }, () = wait_for_shutdown(shutdown) => return Flow::Stop, } tokio::select! { - loaded = reconcile(blacklist, client) => match loaded { - Ok(()) => { - tracing::info!("blacklist snapshot reconciled from Redis"); - *backoff = BACKOFF_MIN; - }, + loaded = snapshot::reconcile(client, blacklist) => match loaded { + Ok(()) => tracing::info!("blacklist snapshot reconciled from Redis"), Err(e) => { tracing::error!("failed to reconcile blacklist snapshot: {e}"); return Flow::Retry; @@ -121,7 +99,13 @@ async fn subscribe_once( loop { tokio::select! { maybe_msg = stream.next() => match maybe_msg { - Some(msg) => handle_message(&msg, blacklist, backoff), + Some(msg) => { + if let Err(e) = event::handle(&msg, blacklist) { + tracing::error!("blacklist event error: {e}"); + } else { + *backoff = BACKOFF_MIN; + } + }, None => { tracing::error!("blacklist pubsub stream ended; resubscribing"); return Flow::Retry; @@ -132,18 +116,22 @@ async fn subscribe_once( } } -/// Handles one event without letting a rejected or panicking payload kill the -/// subscriber task. -fn handle_message(msg: &redis::Msg, blacklist: &Blacklist, backoff: &mut Duration) { - let handled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| event::handle(msg, blacklist))); - match handled { - Ok(Ok(())) => *backoff = BACKOFF_MIN, - Ok(Err(error)) => tracing::warn!(%error, "rejected blacklist event"), - Err(_) => tracing::error!("blacklist event handler panicked; continuing"), +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backoff_doubles_until_cap() { + let mut b = BACKOFF_MIN; + for expected_secs in [2, 4, 8, 16, 30, 30] { + b = next_backoff(b, BACKOFF_MAX); + assert_eq!(b, Duration::from_secs(expected_secs)); + } + } + + #[test] + fn backoff_never_exceeds_max_even_with_huge_prev() { + let b = next_backoff(Duration::from_secs(u64::MAX / 2), BACKOFF_MAX); + assert!(b <= BACKOFF_MAX); } } - -async fn reconcile(blacklist: &Blacklist, client: &redis::Client) -> anyhow::Result<()> { - let manager = connection_manager(client).await?; - snapshot::reconcile(&manager, blacklist).await -} diff --git a/src/store/redis/sync/event.rs b/src/store/redis/sync/event.rs index 80f8dae..15befe3 100644 --- a/src/store/redis/sync/event.rs +++ b/src/store/redis/sync/event.rs @@ -1,14 +1,10 @@ -//! Decoding and validation of blacklist events received from Redis. -//! -//! A remote or stale manager must not be able to ban an address for an -//! arbitrary duration, so every ban is range-checked against -//! [`MAX_BAN_DURATION_SECS`] before it reaches the in-memory table. - -use crate::filter::blacklist::{Blacklist, MAX_BAN_DURATION_SECS}; +use crate::filter::blacklist::Blacklist; use redis::Msg; use serde::Deserialize; use std::time::Duration; +const MAX_BAN_DURATION_SECS: u64 = 31_536_000; + #[derive(Deserialize)] struct BlacklistEvent { ip: String, @@ -31,54 +27,31 @@ pub(super) fn handle(msg: &Msg, blacklist: &Blacklist) -> anyhow::Result<()> { match event.action.as_str() { "ban" => { let duration = match event.expires_at_unix { - Some(expires_at) => absolute_duration(expires_at)?, - None => checked_duration(event.duration_secs)?, + Some(expires_at) => { + if chrono::DateTime::from_timestamp(expires_at, 0).is_none() { + anyhow::bail!("invalid blacklist event expiry timestamp"); + } + let remaining = expires_at.saturating_sub(chrono::Utc::now().timestamp()); + if remaining <= 0 { + blacklist.remove_redis(ip); + return Ok(()); + } + let remaining = u64::try_from(remaining)?; + if remaining > MAX_BAN_DURATION_SECS { + anyhow::bail!("blacklist event expiry exceeds maximum duration"); + } + Duration::from_secs(remaining) + }, + None => Duration::from_secs(event.duration_secs), }; - match duration { - Some(duration) => { - blacklist.add_redis(ip, duration, "manager_event"); - tracing::info!(ip = %event.ip, "blacklist add via Redis"); - }, - None => { - blacklist.remove_redis(ip); - tracing::info!(ip = %event.ip, "blacklist expiry already passed"); - }, - } + blacklist.add_redis(ip, duration, "manager_event"); + tracing::info!("blacklist add via Redis: {}", event.ip); }, "unban" => { blacklist.remove_redis(ip); - tracing::info!(ip = %event.ip, "blacklist remove via Redis"); + tracing::info!("blacklist remove via Redis: {}", event.ip); }, - action => anyhow::bail!("unknown blacklist action: {action}"), + action => anyhow::bail!("unknown action: {action}"), } Ok(()) } - -/// Converts an absolute expiry into the remaining ban duration. -/// -/// Returns `Ok(None)` when the expiry is already in the past. -fn absolute_duration(expires_at: i64) -> anyhow::Result> { - if chrono::DateTime::from_timestamp(expires_at, 0).is_none() { - anyhow::bail!("invalid blacklist event expiry timestamp"); - } - let remaining = expires_at.saturating_sub(chrono::Utc::now().timestamp()); - if remaining <= 0 { - return Ok(None); - } - let remaining = u64::try_from(remaining)?; - if remaining > MAX_BAN_DURATION_SECS { - anyhow::bail!("blacklist event expiry exceeds {MAX_BAN_DURATION_SECS}s"); - } - Ok(Some(Duration::from_secs(remaining))) -} - -/// Validates a relative ban duration. -fn checked_duration(secs: u64) -> anyhow::Result> { - if secs > MAX_BAN_DURATION_SECS { - anyhow::bail!("blacklist event duration {secs}s exceeds {MAX_BAN_DURATION_SECS}s"); - } - if secs == 0 { - return Ok(None); - } - Ok(Some(Duration::from_secs(secs))) -} diff --git a/src/store/redis/sync/publisher.rs b/src/store/redis/sync/publisher.rs index f88be07..e1e685c 100644 --- a/src/store/redis/sync/publisher.rs +++ b/src/store/redis/sync/publisher.rs @@ -1,16 +1,6 @@ -//! Publishes locally detected bans to Redis. -//! -//! Each ban is stored atomically (set member, metadata hash, event publish) via -//! a Lua script on a shared reconnecting connection. Failed publishes retry -//! with exponential backoff and abandon the event when shutdown is requested. - -use super::wait_for_shutdown; use crate::filter::blacklist::{Blacklist, LocalBanEvent}; -use crate::store::redis::backoff::{BACKOFF_MAX, BACKOFF_MIN, next_backoff}; -use crate::store::redis::connection::{command, connection_manager}; -use redis::aio::ConnectionManager; use serde::Serialize; -use std::sync::Arc; +use std::time::Duration; use tokio::sync::{broadcast, watch}; const BLACKLIST_KEY: &str = "rampart:blacklist"; @@ -34,16 +24,14 @@ struct BanEvent<'a> { reason: &'a str, } -/// Publishes local bans and the current local snapshot until shutdown. pub async fn start_local_ban_publisher( client: redis::Client, - blacklist: Arc, + blacklist: std::sync::Arc, mut events: broadcast::Receiver, mut shutdown: watch::Receiver, ) { - let mut manager: Option = None; for event in blacklist.local_snapshot() { - if !publish_with_retry(&client, &mut manager, event, &mut shutdown).await { + if !publish_with_retry(&client, event, &mut shutdown).await { return; } } @@ -52,14 +40,14 @@ pub async fn start_local_ban_publisher( tokio::select! { received = events.recv() => match received { Ok(event) => { - if !publish_with_retry(&client, &mut manager, event, &mut shutdown).await { + if !publish_with_retry(&client, event, &mut shutdown).await { return; } }, Err(broadcast::error::RecvError::Lagged(skipped)) => { tracing::warn!(skipped, "local ban publisher lagged; reconciling active local bans"); for event in blacklist.local_snapshot() { - if !publish_with_retry(&client, &mut manager, event, &mut shutdown).await { + if !publish_with_retry(&client, event, &mut shutdown).await { return; } } @@ -75,29 +63,19 @@ pub async fn start_local_ban_publisher( } } -/// Publishes one event, retrying until it succeeds or shutdown is requested. async fn publish_with_retry( client: &redis::Client, - manager: &mut Option, event: LocalBanEvent, shutdown: &mut watch::Receiver, ) -> bool { - let mut delay = BACKOFF_MIN; + let mut delay = Duration::from_secs(1); loop { - let result = tokio::select! { - result = publish_ban(client, manager, &event) => result, - () = wait_for_shutdown(shutdown) => return false, - }; - match result { + match publish_ban(client, &event).await { Ok(()) => return true, - Err(error) => { - // Force a reconnect on the next attempt. - *manager = None; - tracing::warn!(%error, ip = %event.ip, "failed to persist local ban; retrying"); - }, + Err(error) => tracing::warn!(%error, ip = %event.ip, "failed to persist local ban; retrying"), } tokio::select! { - _ = tokio::time::sleep(delay) => delay = next_backoff(delay, BACKOFF_MAX), + _ = tokio::time::sleep(delay) => delay = (delay * 2).min(Duration::from_secs(30)), changed = shutdown.changed() => { if changed.is_err() || *shutdown.borrow_and_update() { return false; @@ -107,11 +85,7 @@ async fn publish_with_retry( } } -async fn publish_ban( - client: &redis::Client, - manager: &mut Option, - event: &LocalBanEvent, -) -> anyhow::Result<()> { +async fn publish_ban(client: &redis::Client, event: &LocalBanEvent) -> anyhow::Result<()> { let now = chrono::Utc::now().timestamp(); let remaining = event.expires_at_unix.saturating_sub(now); if remaining <= 0 { @@ -129,26 +103,17 @@ async fn publish_ban( expires_at_unix: event.expires_at_unix, reason: &event.reason, })?; - let mut conn = match manager { - Some(conn) => conn.clone(), - None => { - let conn = connection_manager(client).await?; - *manager = Some(conn.clone()); - conn - }, - }; - let _: i64 = command( - redis::cmd("EVAL") - .arg(STORE_BAN_SCRIPT) - .arg(3) - .arg(BLACKLIST_KEY) - .arg(BLACKLIST_METADATA_KEY) - .arg(BLACKLIST_CHANNEL) - .arg(event.ip.to_string()) - .arg(metadata) - .arg(payload) - .query_async(&mut conn), - ) - .await?; + let mut conn = client.get_multiplexed_async_connection().await?; + let _: i64 = redis::cmd("EVAL") + .arg(STORE_BAN_SCRIPT) + .arg(3) + .arg(BLACKLIST_KEY) + .arg(BLACKLIST_METADATA_KEY) + .arg(BLACKLIST_CHANNEL) + .arg(event.ip.to_string()) + .arg(metadata) + .arg(payload) + .query_async(&mut conn) + .await?; Ok(()) } diff --git a/src/store/redis/sync/snapshot.rs b/src/store/redis/sync/snapshot.rs index cfbe9b6..70ae343 100644 --- a/src/store/redis/sync/snapshot.rs +++ b/src/store/redis/sync/snapshot.rs @@ -1,13 +1,5 @@ -//! Durable blacklist snapshot reconciliation. -//! -//! The snapshot is rebuilt from `rampart:blacklist` (set) and -//! `rampart:blacklist:metadata` (hash) after every (re)subscribe and then -//! swapped into the mirrored in-memory table. - -use crate::filter::blacklist::{Blacklist, MAX_BAN_DURATION_SECS}; -use crate::store::redis::connection::command; +use crate::filter::blacklist::Blacklist; use redis::AsyncCommands; -use redis::aio::ConnectionManager; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::time::Duration; @@ -15,6 +7,7 @@ use std::time::Duration; const BLACKLIST_KEY: &str = "rampart:blacklist"; const BLACKLIST_METADATA_KEY: &str = "rampart:blacklist:metadata"; const LEGACY_BAN_DURATION_SECS: i64 = 300; +const MAX_BAN_DURATION_SECS: i64 = 31_536_000; #[derive(Deserialize, Serialize)] struct BlacklistMetadata { @@ -23,15 +16,11 @@ struct BlacklistMetadata { reason: String, } -/// Restores current durable bans after subscribing to the event channel. -/// -/// # Errors -/// Returns an error when Redis is unreachable, a command times out or a -/// recorded timestamp is outside the representable range. -pub(super) async fn reconcile(manager: &ConnectionManager, blacklist: &Blacklist) -> anyhow::Result<()> { - let mut conn = manager.clone(); - let members: Vec = command(redis::cmd("SMEMBERS").arg(BLACKLIST_KEY).query_async(&mut conn)).await?; - let metadata: HashMap = command(conn.hgetall(BLACKLIST_METADATA_KEY)).await?; +/// Restore current durable bans after subscribing to the event channel. +pub(super) async fn reconcile(client: &redis::Client, blacklist: &Blacklist) -> anyhow::Result<()> { + let mut conn = client.get_multiplexed_async_connection().await?; + let members: Vec = redis::cmd("SMEMBERS").arg(BLACKLIST_KEY).query_async(&mut conn).await?; + let metadata: HashMap = conn.hgetall(BLACKLIST_METADATA_KEY).await?; let now = chrono::Utc::now().timestamp(); let mut active = Vec::with_capacity(members.len()); @@ -50,28 +39,22 @@ pub(super) async fn reconcile(manager: &ConnectionManager, blacklist: &Blacklist None => continue, }, }; - if chrono::DateTime::from_timestamp(record.created_at_unix, 0).is_none() + if record.expires_at_unix <= now + || chrono::DateTime::from_timestamp(record.created_at_unix, 0).is_none() || chrono::DateTime::from_timestamp(record.expires_at_unix, 0).is_none() + || record.expires_at_unix.saturating_sub(now) > MAX_BAN_DURATION_SECS { continue; } - let remaining = record.expires_at_unix.saturating_sub(now); - if remaining <= 0 { - continue; - } - let remaining = u64::try_from(remaining)?; - if remaining > MAX_BAN_DURATION_SECS { - continue; - } + let remaining = u64::try_from(record.expires_at_unix - now)?; active.push((ip, Duration::from_secs(remaining), record.reason)); } blacklist.replace_redis(active); Ok(()) } -/// Backfills metadata for a ban written by an older manager. async fn legacy_record( - conn: &mut ConnectionManager, + conn: &mut redis::aio::MultiplexedConnection, target: &str, now: i64, ) -> anyhow::Result> { @@ -80,17 +63,15 @@ async fn legacy_record( expires_at_unix: now.saturating_add(LEGACY_BAN_DURATION_SECS), reason: "legacy_unverified".to_string(), }; - let inserted: i64 = command( - redis::cmd("HSETNX") - .arg(BLACKLIST_METADATA_KEY) - .arg(target) - .arg(serde_json::to_string(&legacy)?) - .query_async(conn), - ) - .await?; + let inserted: i64 = redis::cmd("HSETNX") + .arg(BLACKLIST_METADATA_KEY) + .arg(target) + .arg(serde_json::to_string(&legacy)?) + .query_async(conn) + .await?; if inserted == 1 { return Ok(Some(legacy)); } - let current: Option = command(conn.hget(BLACKLIST_METADATA_KEY, target)).await?; + let current: Option = conn.hget(BLACKLIST_METADATA_KEY, target).await?; Ok(current.and_then(|value| serde_json::from_str(&value).ok())) } diff --git a/src/traffic/intel/detector.rs b/src/traffic/intel/detector.rs index 08afd7e..011e67a 100644 --- a/src/traffic/intel/detector.rs +++ b/src/traffic/intel/detector.rs @@ -1,93 +1,16 @@ -//! Attack state machine over the hour-of-week traffic profile. -//! -//! [`AttackDetector`] scores every one-second window against the baselines -//! *before* the window is folded into them. Scoring first is what keeps a -//! sustained flood visible: a detector that learns the attack as normal stops -//! escalating after a few ticks, and anything that depends on -//! [`AttackStatus::UnderAttack`] (for example offender bans) stops working for -//! the rest of the attack. -//! -//! Two baselines are combined: -//! -//! - [`TrafficProfiler`]: the hour-of-week shape, updated from clean windows. -//! - A slow seeded EWMA (1% per window): the global traffic level. It covers -//! the cold start and the first tick of every hour slot, where the -//! hour-of-week baseline is still zero or close to it. -//! -//! A window is scored against the higher of the two, and attack-level windows -//! are not recorded at all. A flood therefore never becomes the baseline it is -//! compared to, while ordinary drift (below [`DetectorThresholds::attack_score`]) -//! keeps both baselines current. -//! -//! Leaving [`AttackStatus::UnderAttack`] requires -//! [`DetectorThresholds::recover_after`] consecutive windows below -//! [`DetectorThresholds::attack_score`]. The exit hysteresis keeps a single -//! calm window in the middle of an attack from restarting the escalation -//! count. - -use crate::traffic::ewma::Ewma; use crate::traffic::profiler::TrafficProfiler; -/// Smoothing factor of the slow global baseline: one percent per window, so a -/// legitimate traffic shift is learned in about a hundred seconds. -const SLOW_ALPHA: f64 = 0.01; -/// Upper bound of a reported score; `10` means "at least ten times the -/// baseline" and keeps the attack state machine from chasing huge ratios. -const MAX_ANOMALY_RATIO: f64 = 10.0; - -/// Classification of the current traffic window. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum AttackStatus { - /// Traffic is within the learned baseline. Normal, - /// A ratio above [`DetectorThresholds::suspicious_score`] was observed, - /// but the escalation count is not reached yet. Suspicious, - /// Consecutive anomalous windows were observed; the edge escalates. UnderAttack, } -/// Tunables of the attack state machine. -/// -/// The scores are ratios to the baseline (a value of `3.0` means "three times -/// the usual rate"). The defaults match the v0.3 policy; a caller that needs a -/// different sensitivity passes its own values to -/// [`AttackDetector::with_thresholds`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct DetectorThresholds { - /// Ratio that marks a window as suspicious. - pub suspicious_score: f64, - /// Ratio that counts a window as anomalous for escalation. - pub attack_score: f64, - /// Consecutive anomalous windows required to enter `UnderAttack`. - pub escalate_after: u32, - /// Consecutive sub-attack windows required to leave `UnderAttack`. - pub recover_after: u32, -} - -impl Default for DetectorThresholds { - fn default() -> Self { - Self { - suspicious_score: 2.0, - attack_score: 3.0, - escalate_after: 3, - recover_after: 5, - } - } -} - -/// Detects floods from the packets-per-second and connections-per-second -/// profiles. pub struct AttackDetector { pps_profiler: TrafficProfiler, cps_profiler: TrafficProfiler, - pps_slow: Ewma, - cps_slow: Ewma, - primed: bool, - thresholds: DetectorThresholds, consecutive_anomalies: u32, - recovery_windows: u32, - under_attack: bool, } impl Default for AttackDetector { @@ -97,99 +20,95 @@ impl Default for AttackDetector { } impl AttackDetector { - /// Builds a detector with the default [`DetectorThresholds`]. - #[must_use] pub fn new() -> Self { - Self::with_thresholds(DetectorThresholds::default()) - } - - /// Builds a detector with explicit thresholds. - #[must_use] - pub fn with_thresholds(thresholds: DetectorThresholds) -> Self { Self { pps_profiler: TrafficProfiler::new(), cps_profiler: TrafficProfiler::new(), - pps_slow: Ewma::new(SLOW_ALPHA), - cps_slow: Ewma::new(SLOW_ALPHA), - primed: false, - thresholds, consecutive_anomalies: 0, - recovery_windows: 0, - under_attack: false, } } - /// Analyses one metrics window (packets/s and new connections/s) and - /// returns the attack classification. + /// Analyses one metrics window (packets/s and new connections/s) against + /// the accumulated profiles. /// - /// A window is anomalous when its ratio to the baseline reaches - /// [`DetectorThresholds::attack_score`]. - /// [`DetectorThresholds::escalate_after`] consecutive anomalous windows - /// enter `UnderAttack`; the status is left only after - /// [`DetectorThresholds::recover_after`] consecutive windows below the - /// attack score. The first window only primes the baselines. + /// A spike in either metric counts as an anomaly. Three consecutive + /// anomalous windows escalate to [`AttackStatus::UnderAttack`]; a single + /// one above the suspicious score yields [`AttackStatus::Suspicious`]. pub fn analyze(&mut self, pps: f64, cps: f64) -> AttackStatus { - if !self.primed { - self.primed = true; - self.pps_slow.seed(pps); - self.cps_slow.seed(cps); - self.pps_profiler.record(pps); - self.cps_profiler.record(cps); - return AttackStatus::Normal; + self.pps_profiler.record(pps); + self.cps_profiler.record(cps); + let score = self + .pps_profiler + .anomaly_score(pps) + .max(self.cps_profiler.anomaly_score(cps)); + + if score > 3.0 { + self.consecutive_anomalies += 1; + } else { + self.consecutive_anomalies = 0; } - // Score against the baselines first: recording first would fold the - // spike into the baseline it is scored against. - let pps_baseline = self.pps_profiler.baseline().max(self.pps_slow.value()); - let cps_baseline = self.cps_profiler.baseline().max(self.cps_slow.value()); - let score = anomaly_ratio(pps, pps_baseline).max(anomaly_ratio(cps, cps_baseline)); - - self.update_state(score); - - // Attack-level windows never enter the baselines (see the module - // documentation); everything else keeps both of them current. - if score < self.thresholds.attack_score { - self.pps_profiler.record(pps); - self.cps_profiler.record(cps); - self.pps_slow.update(pps); - self.cps_slow.update(cps); - } - - if self.under_attack { + if self.consecutive_anomalies >= 3 { AttackStatus::UnderAttack - } else if score >= self.thresholds.suspicious_score { + } else if score > 2.0 { AttackStatus::Suspicious } else { AttackStatus::Normal } } - - fn update_state(&mut self, score: f64) { - if score >= self.thresholds.attack_score { - self.consecutive_anomalies = self.consecutive_anomalies.saturating_add(1); - self.recovery_windows = 0; - } else { - self.consecutive_anomalies = 0; - self.recovery_windows = self.recovery_windows.saturating_add(1); - } - - if self.under_attack { - if self.recovery_windows >= self.thresholds.recover_after { - self.under_attack = false; - } - } else if self.consecutive_anomalies >= self.thresholds.escalate_after { - self.under_attack = true; - } - } } -/// Ratio of a window to its baseline, capped at [`MAX_ANOMALY_RATIO`]. -/// -/// Returns zero for an unset baseline and for non-finite windows, so a broken -/// counter cannot pin the detector in the attack state. -fn anomaly_ratio(sample: f64, baseline: f64) -> f64 { - if !sample.is_finite() || baseline <= 0.0 { - return 0.0; +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_attack_status_normal() { + let mut d = AttackDetector::new(); + for _ in 0..10 { + d.analyze(100.0, 10.0); + } + assert_eq!(d.analyze(100.0, 10.0), AttackStatus::Normal); + } + + #[test] + fn test_attack_status_suspicious_pps_spike() { + let mut d = AttackDetector::new(); + for _ in 0..10 { + d.analyze(1.0, 1.0); + } + assert_eq!(d.analyze(5.0, 1.0), AttackStatus::Suspicious); + } + + #[test] + fn test_attack_status_suspicious_cps_spike() { + let mut d = AttackDetector::new(); + for _ in 0..10 { + d.analyze(1.0, 1.0); + } + assert_eq!(d.analyze(1.0, 5.0), AttackStatus::Suspicious); + } + + #[test] + fn test_attack_status_under_attack() { + let mut d = AttackDetector::new(); + for _ in 0..10 { + d.analyze(1.0, 1.0); + } + d.analyze(10_000.0, 100.0); + d.analyze(10_000.0, 100.0); + assert_eq!(d.analyze(10_000.0, 100.0), AttackStatus::UnderAttack); + } + + #[test] + fn test_consecutive_resets_on_normal() { + let mut d = AttackDetector::new(); + for _ in 0..10 { + d.analyze(1.0, 1.0); + } + d.analyze(100.0, 10.0); + d.analyze(100.0, 10.0); + d.analyze(1.0, 1.0); + assert_eq!(d.analyze(1.0, 1.0), AttackStatus::Normal); } - (sample.max(0.0) / baseline).min(MAX_ANOMALY_RATIO) } diff --git a/src/traffic/intel/ewma.rs b/src/traffic/intel/ewma.rs index 754edb5..74a1b8c 100644 --- a/src/traffic/intel/ewma.rs +++ b/src/traffic/intel/ewma.rs @@ -1,29 +1,5 @@ -//! Time-aware exponential moving average used by the traffic profilers. -//! -//! The average is expressed in samples per unit time and is fed once per -//! metrics window by [`crate::traffic::profiler::TrafficProfiler`]. - use std::time::Instant; -/// Smoothing factor used for `alpha` values outside the valid `(0, 1]` range -/// and for `NaN`, so a malformed configuration cannot freeze the baseline. -const DEFAULT_ALPHA: f64 = 0.125; - -/// Exponential moving average with a wall-clock aware step count. -/// -/// # Formula -/// -/// For a sample `x` that arrives `dt` seconds after the previous update, -/// `steps = max(dt, 1)` and `weight = (1 - alpha)^steps`. The average is then -/// -/// ```text -/// value = value * weight + x * (1 - weight) -/// ``` -/// -/// A larger `alpha` gives more weight to the newest sample; `alpha = 1` makes -/// the average equal to the last finite sample. The step count keeps the -/// smoothing independent of the tick rate: one update after a two-second gap -/// is worth two one-second updates. pub struct Ewma { value: f64, last: Instant, @@ -31,59 +7,51 @@ pub struct Ewma { } impl Ewma { - /// Builds a smoothed average that starts at zero. - /// - /// `alpha` is clamped to `(0, 1]`; `NaN`, infinity and non-positive values - /// fall back to the default 0.125 instead of silently disabling the - /// smoothing or producing a non-finite baseline. - #[must_use] pub fn new(alpha: f64) -> Self { Self { value: 0.0, last: Instant::now(), - alpha: sanitize_alpha(alpha), + alpha, } } - /// Folds `sample` into the average, following the formula in the type - /// documentation. - /// - /// Non-finite samples are ignored (the update timestamp is not advanced - /// either), so one broken counter reading cannot poison the baseline. pub fn update(&mut self, sample: f64) { - if !sample.is_finite() { - return; - } let now = Instant::now(); - let steps = now.duration_since(self.last).as_secs_f64().max(1.0); + let elapsed = now.duration_since(self.last).as_secs_f64(); + let steps = elapsed.max(1.0); let weight = (1.0 - self.alpha).powf(steps); self.value = self.value * weight + sample * (1.0 - weight); self.last = now; } - /// Replaces the average with `value` and restarts the step timer. - /// - /// Used to prime a baseline from the first observed window instead of - /// climbing from zero, which would otherwise read as an anomaly. - pub fn seed(&mut self, value: f64) { - if !value.is_finite() { - return; - } - self.value = value; - self.last = Instant::now(); - } - - /// Current smoothed value. - #[must_use] pub fn value(&self) -> f64 { self.value } } -fn sanitize_alpha(alpha: f64) -> f64 { - if alpha.is_finite() && alpha > 0.0 { - alpha.min(1.0) - } else { - DEFAULT_ALPHA +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_ewma_initial() { + let ewma = Ewma::new(0.125); + assert_eq!(ewma.value(), 0.0); + } + + #[test] + fn test_ewma_update() { + let mut ewma = Ewma::new(1.0); + ewma.update(100.0); + assert!((ewma.value() - 100.0).abs() < 1.0); + } + + #[test] + fn test_ewma_convergence() { + let mut ewma = Ewma::new(0.5); + for _ in 0..10 { + ewma.update(50.0); + } + assert!((ewma.value() - 50.0).abs() < 1.0); } } diff --git a/src/traffic/intel/reputation.rs b/src/traffic/intel/reputation.rs index 570e5e4..554040c 100644 --- a/src/traffic/intel/reputation.rs +++ b/src/traffic/intel/reputation.rs @@ -1,79 +1,9 @@ -//! Per-source reputation with time decay and idle-TTL eviction. -//! -//! A source starts neutral (`0`); [`IpReputation::record_bad`] subtracts ten -//! points and [`IpReputation::record_good`] adds one, clamped to `[-100, 100]`. -//! Scores decay toward neutral on read (half of the magnitude per thirty -//! minutes of inactivity), so one old success cannot keep a source trusted -//! forever and one old failure cannot keep it toxic. -//! -//! State lives in sixty-four locked shards. [`IpReputation::sweep`] visits -//! eight of them per call and drops entries idle for longer than ten minutes; -//! recording advances one step per minute, so the table is reclaimed without -//! an external scheduler and no full-map `retain`. -//! -//! [`IpReputation::offenders_below`] returns at most 64 of the worst sources, -//! so one escalation cannot flood the ban list or the log. - -use std::collections::hash_map::RandomState; -use std::collections::{BinaryHeap, HashMap}; -use std::hash::BuildHasher; +use dashmap::DashMap; use std::net::IpAddr; -use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Mutex, MutexGuard}; -use std::time::{Duration, Instant}; +use std::sync::Arc; -/// Idle age after which a source is forgotten. -const IDLE_TTL: Duration = Duration::from_secs(600); -/// Time after which a dead source's score is halved. -const DECAY_HALF_LIFE: Duration = Duration::from_secs(1800); -/// Minimum interval between two automatic sweep steps. -const SWEEP_INTERVAL: Duration = Duration::from_secs(60); -/// Number of independently locked score shards. -const SHARDS: usize = 64; -/// Shards examined by one [`IpReputation::sweep`] call. -const SWEEP_SHARDS_PER_TICK: usize = 8; -/// Upper bound of a single offender batch. -const MAX_OFFENDERS_PER_CYCLE: usize = 64; -const GOOD_STEP: i32 = 1; -const BAD_STEP: i32 = -10; -const MAX_SCORE: i32 = 100; -const MIN_SCORE: i32 = -100; - -/// Tunables of [`IpReputation`]. -#[derive(Debug, Clone, Copy)] -pub struct ReputationPolicy { - /// Idle age after which a source is forgotten. - pub idle_ttl: Duration, - /// Time after which a dead source's score is halved. - pub decay_half_life: Duration, - /// Upper bound of a single [`IpReputation::offenders_below`] batch. - pub max_offenders: usize, -} - -impl Default for ReputationPolicy { - fn default() -> Self { - Self { - idle_ttl: IDLE_TTL, - decay_half_life: DECAY_HALF_LIFE, - max_offenders: MAX_OFFENDERS_PER_CYCLE, - } - } -} - -/// Reputation entry: the raw score and when it was last touched. -struct Entry { - score: i32, - last_update: Instant, -} - -/// Reputation scores of the sources seen by the edge node. pub struct IpReputation { - shards: Box<[Mutex>]>, - hasher: RandomState, - policy: ReputationPolicy, - epoch: Instant, - last_sweep: AtomicU64, - sweep_cursor: AtomicUsize, + scores: Arc>, } impl Default for IpReputation { @@ -83,166 +13,129 @@ impl Default for IpReputation { } impl IpReputation { - /// Builds a reputation table with the production policy. - #[must_use] pub fn new() -> Self { - Self::with_policy(ReputationPolicy::default()) - } - - /// Builds a reputation table with an explicit policy. - pub fn with_policy(policy: ReputationPolicy) -> Self { Self { - shards: (0..SHARDS).map(|_| Mutex::new(HashMap::new())).collect(), - hasher: RandomState::new(), - policy, - epoch: Instant::now(), - last_sweep: AtomicU64::new(0), - sweep_cursor: AtomicUsize::new(0), + scores: Arc::new(DashMap::new()), } } - /// Records a successful connection. pub fn record_good(&self, ip: IpAddr) { - self.sweep_if_due(); - self.adjust(ip, GOOD_STEP); + let mut entry = self.scores.entry(ip).or_insert(0); + *entry = (*entry + 1).min(100); } - /// Records a failed or abusive connection. pub fn record_bad(&self, ip: IpAddr) { - self.sweep_if_due(); - self.adjust(ip, BAD_STEP); + let mut entry = self.scores.entry(ip).or_insert(0); + *entry = (*entry - 10).max(-100); } - /// Current decayed score of `ip`; `0` for unknown or idle sources. pub fn score(&self, ip: IpAddr) -> i32 { - let now = Instant::now(); - let index = self.shard_index(ip); - let shard = self.lock(index); - let Some(entry) = shard.get(&ip) else { return 0 }; - let idle = now.duration_since(entry.last_update); - if idle > self.policy.idle_ttl { - return 0; - } - decayed_score(entry.score, idle, self.policy.decay_half_life) + self.scores.get(&ip).map(|v| *v).unwrap_or(0) } - /// Returns up to [`ReputationPolicy::max_offenders`] of the worst sources - /// scored at or below `threshold`. + /// Returns the sources scored at or below `threshold` (the offenders). /// - /// The snapshot is safe to ban from while other threads keep recording - /// events. When more offenders exist than the batch cap, exactly one - /// aggregated warning carries the total count. + /// The result is a snapshot copy, so it is safe to ban from it while other + /// threads keep recording events. pub fn offenders_below(&self, threshold: i32) -> Vec { - let now = Instant::now(); - let limit = self.policy.max_offenders; - let mut worst: BinaryHeap<(i32, IpAddr)> = BinaryHeap::new(); - let mut found = 0usize; - for index in 0..self.shards.len() { - let shard = self.lock(index); - for (ip, entry) in shard.iter() { - let idle = now.duration_since(entry.last_update); - if idle > self.policy.idle_ttl { - continue; - } - let score = decayed_score(entry.score, idle, self.policy.decay_half_life); - if score > threshold { - continue; - } - found += 1; - worst.push((score, *ip)); - if worst.len() > limit { - worst.pop(); - } - } - } - let offenders: Vec = worst.into_iter().map(|(_, ip)| ip).collect(); - if found > offenders.len() { - tracing::warn!( - found, - returned = offenders.len(), - "reputation offender batch truncated for this cycle" - ); - } - offenders + self.scores + .iter() + .filter(|entry| *entry.value() <= threshold) + .map(|entry| *entry.key()) + .collect() } - /// Whether the source is above the trusted score. pub fn is_trusted(&self, ip: IpAddr) -> bool { self.score(ip) > 50 } - - /// Number of live entries. - pub fn len(&self) -> usize { - (0..self.shards.len()).map(|index| self.lock(index).len()).sum() - } - - /// Whether the table is empty. - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Evicts idle entries from the next shard slice; returns the count. - pub fn sweep(&self) -> usize { - let now = Instant::now(); - let shard_count = self.shards.len(); - let start = self.sweep_cursor.fetch_add(SWEEP_SHARDS_PER_TICK, Ordering::Relaxed); - let mut removed = 0; - for offset in 0..SWEEP_SHARDS_PER_TICK.min(shard_count) { - let index = (start + offset) % shard_count; - let mut shard = self.lock(index); - let before = shard.len(); - shard.retain(|_, entry| now.duration_since(entry.last_update) <= self.policy.idle_ttl); - removed += before - shard.len(); - } - removed - } - - fn adjust(&self, ip: IpAddr, delta: i32) { - let now = Instant::now(); - let index = self.shard_index(ip); - let mut shard = self.lock(index); - let entry = shard.entry(ip).or_insert(Entry { - score: 0, - last_update: now, - }); - let idle = now.duration_since(entry.last_update); - let decayed = decayed_score(entry.score, idle, self.policy.decay_half_life); - entry.score = (decayed + delta).clamp(MIN_SCORE, MAX_SCORE); - entry.last_update = now; - } - - /// Advances one sweep step when [`SWEEP_INTERVAL`] has elapsed, so eviction - /// does not depend on an external timer. - fn sweep_if_due(&self) { - let elapsed = self.epoch.elapsed().as_secs(); - let last = self.last_sweep.load(Ordering::Relaxed); - if elapsed.saturating_sub(last) < SWEEP_INTERVAL.as_secs() { - return; - } - let advanced = self - .last_sweep - .compare_exchange(last, elapsed, Ordering::AcqRel, Ordering::Relaxed); - if advanced.is_ok() { - self.sweep(); - } - } - - fn shard_index(&self, ip: IpAddr) -> usize { - (self.hasher.hash_one(ip) as usize) % self.shards.len() - } - - fn lock(&self, index: usize) -> MutexGuard<'_, HashMap> { - // A poisoned shard still holds consistent scores; keep serving. - self.shards[index].lock().unwrap_or_else(|poison| poison.into_inner()) - } } -fn decayed_score(score: i32, idle: Duration, half_life: Duration) -> i32 { - if score == 0 || half_life.is_zero() { - return 0; +#[cfg(test)] +mod tests { + use super::*; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + + fn v4(octets: [u8; 4]) -> IpAddr { + IpAddr::V4(Ipv4Addr::from(octets)) + } + + #[test] + fn test_reputation_initial_score() { + let rep = IpReputation::new(); + assert_eq!(rep.score(v4([192, 168, 1, 1])), 0); + } + + #[test] + fn test_reputation_good() { + let rep = IpReputation::new(); + let ip = v4([10, 0, 0, 1]); + rep.record_good(ip); + assert_eq!(rep.score(ip), 1); + } + + #[test] + fn test_reputation_bad() { + let rep = IpReputation::new(); + let ip = v4([10, 0, 0, 2]); + rep.record_bad(ip); + assert_eq!(rep.score(ip), -10); + } + + #[test] + fn test_reputation_cap_positive() { + let rep = IpReputation::new(); + let ip = v4([10, 0, 0, 3]); + for _ in 0..200 { + rep.record_good(ip); + } + assert_eq!(rep.score(ip), 100); + } + + #[test] + fn test_reputation_cap_negative() { + let rep = IpReputation::new(); + let ip = v4([10, 0, 0, 4]); + for _ in 0..20 { + rep.record_bad(ip); + } + assert_eq!(rep.score(ip), -100); + } + + #[test] + fn test_is_trusted() { + let rep = IpReputation::new(); + let ip = v4([10, 0, 0, 5]); + assert!(!rep.is_trusted(ip)); + for _ in 0..51 { + rep.record_good(ip); + } + assert!(rep.is_trusted(ip)); + } + + #[test] + fn test_reputation_v6() { + let rep = IpReputation::new(); + let ip = IpAddr::V6(Ipv6Addr::LOCALHOST); + rep.record_bad(ip); + assert_eq!(rep.score(ip), -10); + } + + #[test] + fn test_offenders_below_threshold() { + let rep = IpReputation::new(); + let bad = v4([10, 0, 0, 1]); + let good = v4([10, 0, 0, 2]); + for _ in 0..6 { + rep.record_bad(bad); + } + rep.record_good(good); + let offenders = rep.offenders_below(-50); + assert_eq!(offenders, vec![bad]); + } + + #[test] + fn test_offenders_empty_when_none_below() { + let rep = IpReputation::new(); + assert!(rep.offenders_below(-50).is_empty()); } - let factor = 0.5f64.powf(idle.as_secs_f64() / half_life.as_secs_f64()); - // Rounding (instead of truncation) keeps an immediate second update from - // decaying a score of `1` back to zero on the microsecond scale. - (f64::from(score) * factor).round() as i32 } diff --git a/src/traffic/prefix/key.rs b/src/traffic/prefix/key.rs index f8055df..13dc9eb 100644 --- a/src/traffic/prefix/key.rs +++ b/src/traffic/prefix/key.rs @@ -17,22 +17,17 @@ pub struct PrefixKey { impl PrefixKey { /// Builds the prefix key for an address (v4 maps to /24 in the first four /// bytes, v6 maps to /64). - /// - /// The address is normalised through [`prefix_of`] first, so an - /// IPv4-mapped IPv6 source (`::ffff:a.b.c.d`) produces exactly the same key - /// as the plain IPv4 address. XDP `prefix_stats` entries and the user-space - /// tracker therefore agree on the bucket of a dual-stack client. #[must_use] pub fn new(ip: IpAddr) -> Self { let mut key = Self::default(); - match prefix_of(ip) { + match ip { IpAddr::V4(v4) => { key.family = PREFIX_FAMILY_V4; - key.addr[..4].copy_from_slice(&v4.octets()); + key.addr[..4].copy_from_slice(&masked_v4(v4).octets()); }, IpAddr::V6(v6) => { key.family = PREFIX_FAMILY_V6; - key.addr.copy_from_slice(&v6.octets()); + key.addr.copy_from_slice(&masked_v6_segments(v6)); }, } key diff --git a/src/xdp/filter/attach.rs b/src/xdp/filter/attach.rs index e51230e..cc7f35d 100644 --- a/src/xdp/filter/attach.rs +++ b/src/xdp/filter/attach.rs @@ -1,25 +1,27 @@ -use std::ffi::CString; -use std::os::unix::io::AsFd; - use anyhow::{Context, Result, bail}; -use libbpf_rs::{Object, OpenObject, Program, Xdp, XdpFlags}; +use libbpf_rs::{MapCore, Object, OpenObject, RingBuffer, RingBufferBuilder}; +use std::ffi::CString; +use std::net::IpAddr; +use std::sync::Arc; +use std::time::Duration; +use crate::filter::blacklist::Blacklist; use crate::xdp::globals::{RODATA_MAP_NAME, XdpGlobals}; +use crate::xdp::metrics::XDP_AUTOBANS_TOTAL; -/// Name of the XDP program inside the compiled object. -const XDP_PROG_NAME: &str = "rampart_universal_filter"; +use super::events::{AutoBanConfig, auto_ban_decision, parse_xdp_event}; /// Builds the NUL-terminated C string libc's `if_nametoindex` requires. /// Rejects interface names containing an interior NUL byte instead of /// silently truncating at it (the `&str`-as-`*const c_char` UB we removed). -pub fn interface_cstr(name: &str) -> Result { +pub(super) fn interface_cstr(name: &str) -> Result { CString::new(name).with_context(|| format!("interface name {name:?} contains an interior NUL byte")) } /// The internal `.rodata` data map is matched by suffix: libbpf names it /// `.rodata`, and with `open_memory` and no explicit `.name()` the object is /// called `memory` — an exact comparison broke on a live kernel (smoke test). -pub fn is_rodata_map(name: &str) -> bool { +pub(super) fn is_rodata_map(name: &str) -> bool { name.ends_with(".rodata") } @@ -55,148 +57,108 @@ pub(super) fn patch_rodata(open_obj: &mut OpenObject, globals: &XdpGlobals) -> R .with_context(|| format!("failed to set initial value of '{RODATA_MAP_NAME}'")) } -/// `XDP_ATTACHED_*` values from `linux/netlink.h` (`IFLA_XDP_ATTACHED`). -/// -/// The order is NONE, DRV, SKB, HW, MULTI — hardware offload is 3, not 2. -const XDP_ATTACHED_DRV: u8 = 1; -const XDP_ATTACHED_SKB: u8 = 2; -const XDP_ATTACHED_HW: u8 = 3; -const XDP_ATTACHED_MULTI: u8 = 4; - /// Honest name of the attach mode, derived from the `attach_mode` field of -/// `bpf_xdp_query_opts` (kernel `enum xdp_attach_mode`). -pub fn xdp_attach_mode_name(mode: u8) -> &'static str { +/// `bpf_xdp_query_opts` (kernel `enum xdp_attached_mode`: NONE=0, DRV=1, OFFLOAD=2, SKB=3). +pub(super) fn xdp_attach_mode_name(mode: u8) -> &'static str { match mode { - XDP_ATTACHED_DRV => "native (drv)", - XDP_ATTACHED_SKB => "generic (skb)", - XDP_ATTACHED_HW => "hardware offload", - XDP_ATTACHED_MULTI => "multiple programs", + 1 => "native (drv)", + 2 => "hardware offload", + 3 => "generic (skb)", _ => "none", } } -/// Detach flags matching the mode the kernel actually attached the program in. +/// Builds the ringbuf callback for `events_ringbuf`. /// -/// The mode is discovered after attach via `bpf_xdp_query`; using the flags -/// that were *requested* is wrong when the kernel picked a different mode -/// (for example generic after a failed native attach). -fn detach_flags_for_mode(mode: u8) -> Option { - match mode { - XDP_ATTACHED_DRV => Some(XdpFlags::DRV_MODE), - XDP_ATTACHED_SKB => Some(XdpFlags::SKB_MODE), - XDP_ATTACHED_HW => Some(XdpFlags::HW_MODE), - XDP_ATTACHED_MULTI => None, - // NONE: the query failed after a successful attach. - _ => None, - } -} - -/// Attaches with the native-first mode ladder and returns the detach flags. -fn attach_with_fallback(xdp: &Xdp<'_>, ifindex: i32, interface: &str) -> Result { - if let Err(e) = xdp.attach(ifindex, XdpFlags::NONE) { - tracing::warn!( - interface = %interface, - error = %e, - "native XDP attach failed, falling back to generic (skb) mode" +/// The callback must be `'static`, so all shared state (`Arc`, a copy of +/// `AutoBanConfig`) is captured by `move` clones. When `blacklist` is `None` (feature not +/// wired) or the policy is disabled, events are only parsed and logged in a structured +/// way; no bans are written. The hot path does no `format!` — only `tracing` fields and +/// `&'static str` reasons. +pub(super) fn build_ringbuf( + obj: &Object, + blacklist: Option>, + cfg: AutoBanConfig, +) -> Result> { + let map = obj + .maps() + .find(|m| m.name() == "events_ringbuf") + .context("events_ringbuf not found")?; + let mut builder = RingBufferBuilder::new(); + builder.add(&map, move |data: &[u8]| { + let Some(event) = parse_xdp_event(data) else { + tracing::debug!( + len = data.len(), + "xdp ringbuf frame ignored (too short or unknown type)" + ); + return 0; + }; + tracing::debug!( + kind = ?event.kind, + src_ip = %event.src_ip, + metadata = event.metadata, + "xdp event" ); - xdp.attach(ifindex, XdpFlags::SKB_MODE) - .context("XDP attach failed in both native and generic modes")?; - Ok(XdpFlags::SKB_MODE) - } else { - Ok(XdpFlags::NONE) - } -} - -/// Finds the loader's XDP program in a loaded object. -fn find_xdp_program<'obj>(obj: &'obj Object) -> Result> { - obj.progs() - .find(|p| p.name() == XDP_PROG_NAME) - .with_context(|| format!("XDP program '{XDP_PROG_NAME}' not found")) -} - -/// Detaches the program if it is dropped while still armed. -/// -/// Any error between a successful attach and the moment `XdpFilter` takes -/// ownership leaves an XDP program attached that drops traffic but has no -/// userspace reader (an orphaned filter). This guard makes that window fail -/// safe: unless [`DetachGuard::disarm`] was called, dropping it detaches. -pub(super) struct DetachGuard<'obj> { - prog: Program<'obj>, - ifindex: i32, - /// Raw `XdpFlags` bits: `XdpFlags` itself is neither `Copy` nor `Clone`. - flags_bits: u32, - armed: bool, -} - -impl<'obj> DetachGuard<'obj> { - fn new(prog: Program<'obj>, ifindex: i32, flags_bits: u32) -> Self { - Self { - prog, - ifindex, - flags_bits, - armed: true, + let Some(blacklist) = &blacklist else { + return 0; + }; + if let Some(ban) = auto_ban_decision(&event, &cfg) { + let addr = IpAddr::V4(ban.ip); + // `Blacklist::add` returns `()` (it ignores `DashMap::insert`) and blacklist.rs is + // out of our edit scope, so "is this a new ban" is decided through the public + // `is_blocked` before the overwrite. This dedups the log line and the metric by + // active ban, not by the fact of insertion. + let already_banned = blacklist.is_blocked(addr); + blacklist.add(addr, Duration::from_secs(ban.duration_secs), ban.reason); + if already_banned { + tracing::debug!(src_ip = %ban.ip, reason = ban.reason, "xdp auto-ban refreshed"); + } else { + XDP_AUTOBANS_TOTAL.inc(); + tracing::info!( + src_ip = %ban.ip, + reason = ban.reason, + duration_secs = ban.duration_secs, + "xdp auto-ban issued" + ); + } } - } - - /// Marks the attach as committed; dropping the guard is then a no-op. - pub(super) fn disarm(mut self) { - self.armed = false; - } + 0 + })?; + Ok(builder.build()?) } -impl Drop for DetachGuard<'_> { - fn drop(&mut self) { - if !self.armed { - return; - } - if let Err(e) = Xdp::new(self.prog.as_fd()).detach(self.ifindex, XdpFlags::from_bits_truncate(self.flags_bits)) - { - tracing::error!( - ifindex = self.ifindex, - error = %e, - "XDP attach rollback failed: the program may still be attached" - ); - } else { - tracing::warn!(ifindex = self.ifindex, "XDP attach rolled back after a setup failure"); - } +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn interface_cstr_accepts_plain_names() { + let c = interface_cstr("eth0").expect("valid interface name"); + assert_eq!(c.as_bytes(), b"eth0"); + assert_eq!(c.as_bytes_with_nul(), b"eth0\0"); + } + + #[test] + fn interface_cstr_rejects_interior_nul() { + assert!(interface_cstr("et\0h0").is_err()); + } + + #[test] + fn rodata_map_matches_libbpf_naming() { + // libbpf builds the name as `
` without rewriting the dot + // (libbpf.c ~1911); with open_memory and no name the object is called "memory": + assert!(is_rodata_map("rampart.rodata")); + assert!(is_rodata_map("memory.rodata")); + assert!(is_rodata_map(".rodata")); + assert!(!is_rodata_map("rampart.bss")); + assert!(!is_rodata_map("stats_map")); + } + + #[test] + fn attach_mode_names_are_honest() { + assert_eq!(xdp_attach_mode_name(1), "native (drv)"); + assert_eq!(xdp_attach_mode_name(3), "generic (skb)"); + assert_eq!(xdp_attach_mode_name(2), "hardware offload"); + assert_eq!(xdp_attach_mode_name(0), "none"); } } - -/// Attaches the program and returns `(detach flags, mode name, rollback guard)`. -/// -/// The returned guard must be disarmed only after every fallible step that -/// follows the attach has succeeded. The attach mode is queried from the -/// kernel (not assumed from the requested flags) so that a generic-mode -/// fallback is detached from the generic slot. -pub(super) fn attach_program<'obj>( - obj: &'obj Object, - ifindex: i32, - interface: &str, -) -> Result<(u32, &'static str, DetachGuard<'obj>)> { - let prog = find_xdp_program(obj)?; - let requested = { - let xdp = Xdp::new(prog.as_fd()); - attach_with_fallback(&xdp, ifindex, interface)? - }; - let mode = match Xdp::new(prog.as_fd()).query(ifindex, XdpFlags::NONE) { - Ok(query) => query.attach_mode, - Err(e) => { - tracing::warn!( - interface = %interface, - error = %e, - "XDP attach-mode query failed; assuming the requested flags" - ); - 0 - }, - }; - // Fall back to the requested flags when the query failed or the interface - // reports several programs (MULTI): that is the best detach handle we have. - let flags_bits = detach_flags_for_mode(mode).unwrap_or(requested).bits(); - let guard = DetachGuard::new(prog, ifindex, flags_bits); - let name = if mode == 0 { - "unknown" - } else { - xdp_attach_mode_name(mode) - }; - Ok((flags_bits, name, guard)) -} diff --git a/src/xdp/filter/events.rs b/src/xdp/filter/events.rs index fca5996..809fe5a 100644 --- a/src/xdp/filter/events.rs +++ b/src/xdp/filter/events.rs @@ -1,19 +1,11 @@ //! Parsing and policy for XDP ringbuf events (`struct xdp_event`). //! -//! Parsing and the auto-ban policy are pure functions covered by -//! `tests/xdp_events.rs`; [`build_ringbuf`] wires the same policy into the libbpf -//! ringbuf callback. +//! Pure functions (no I/O, no libbpf) so that they can be covered by unit tests without +//! a kernel or Redis. The callback wiring lives in [`super::attach`]. -use std::net::{IpAddr, Ipv4Addr}; -use std::sync::Arc; -use std::time::Duration; - -use anyhow::{Context, Result}; -use libbpf_rs::{MapCore, Object, RingBuffer, RingBufferBuilder}; +use std::net::Ipv4Addr; use crate::config::XdpConfig; -use crate::filter::blacklist::Blacklist; -use crate::xdp::metrics::XDP_AUTOBANS_TOTAL; /// Exact size of `struct xdp_event` (see `xdp/core/common.h:61-66`): /// `__u32 type` @0, `__u32 src_ip` @4, `__u32 metadata` @8, @@ -174,64 +166,5 @@ pub fn auto_ban_decision(event: &XdpEvent, config: &AutoBanConfig) -> Option`, a copy of -/// `AutoBanConfig`) is captured by `move` clones. When `blacklist` is `None` (feature not -/// wired) or the policy is disabled, events are only parsed and logged in a structured -/// way; no bans are written. The hot path does no `format!` — only `tracing` fields and -/// `&'static str` reasons. -pub(super) fn build_ringbuf( - obj: &Object, - blacklist: Option>, - cfg: AutoBanConfig, -) -> Result> { - let map = obj - .maps() - .find(|m| m.name() == "events_ringbuf") - .context("events_ringbuf not found")?; - let mut builder = RingBufferBuilder::new(); - builder.add(&map, move |data: &[u8]| { - let Some(event) = parse_xdp_event(data) else { - tracing::debug!( - len = data.len(), - "xdp ringbuf frame ignored (too short or unknown type)" - ); - return 0; - }; - tracing::debug!( - kind = ?event.kind, - src_ip = %event.src_ip, - metadata = event.metadata, - "xdp event" - ); - let Some(blacklist) = &blacklist else { - return 0; - }; - if let Some(ban) = auto_ban_decision(&event, &cfg) { - let addr = IpAddr::V4(ban.ip); - // `Blacklist::add` returns `()` (it ignores `DashMap::insert`) and blacklist.rs is - // out of our edit scope, so "is this a new ban" is decided through the public - // `is_blocked` before the overwrite. This dedups the log line and the metric by - // active ban, not by the fact of insertion. - let already_banned = blacklist.is_blocked(addr); - blacklist.add(addr, Duration::from_secs(ban.duration_secs), ban.reason); - if already_banned { - tracing::debug!(src_ip = %ban.ip, reason = ban.reason, "xdp auto-ban refreshed"); - } else { - XDP_AUTOBANS_TOTAL.inc(); - tracing::info!( - src_ip = %ban.ip, - reason = ban.reason, - duration_secs = ban.duration_secs, - "xdp auto-ban issued" - ); - } - } - 0 - })?; - Ok(builder.build()?) -} - // Parser and policy coverage lives in `tests/xdp_events.rs` (this module is kept under // the 250-line limit; `src/xdp/filter/` already has the maximum of 4 files per directory). diff --git a/src/xdp/filter/maps.rs b/src/xdp/filter/maps.rs index af8cefa..f23432e 100644 --- a/src/xdp/filter/maps.rs +++ b/src/xdp/filter/maps.rs @@ -1,117 +1,58 @@ -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; - -use anyhow::{Result, bail}; -use libbpf_rs::{MapCore, MapFlags}; - use super::XdpFilter; -use crate::xdp::probe::{blacklist_expiry_ns, monotonic_ns}; +use anyhow::Result; +use libbpf_rs::{MapCore, MapFlags}; +use std::net::{IpAddr, Ipv4Addr}; -/// Encodes an LPM-trie key for `blacklist_map` and `whitelist_map`: -/// prefix length as a little-endian u32 in bytes 0..4 and the four IPv4 -/// octets in network order in bytes 4..8 (`struct lpm_key` in `common.h`). +/// Monotonic clock in ns since boot — the same clock as `bpf_ktime_get_ns()`, +/// which is what the XDP program compares ban expiry against. `SystemTime` +/// (epoch ns) is ~50 years larger, so bans written with it never expired. +/// +/// # Panics +/// Never: `clock_gettime(CLOCK_MONOTONIC)` cannot fail on Linux. #[must_use] -pub fn blacklist_key(prefix_len: u8, v4: &[u8; 4]) -> [u8; 8] { - ipv4_lpm_key(prefix_len, v4) +pub fn monotonic_ns() -> u64 { + let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 }; + // SAFETY: `ts` is a valid, writable `timespec` and CLOCK_MONOTONIC is + // always available on Linux (the only target of the `xdp` feature). + unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) }; + let secs = u64::try_from(ts.tv_sec).unwrap_or(0); + secs.saturating_mul(1_000_000_000) + .saturating_add(u64::try_from(ts.tv_nsec).unwrap_or(0)) } -/// Encodes an LPM-trie key for `whitelist_map`; the layout is identical to -/// [`blacklist_key`] because both C maps use `struct lpm_key`. -#[must_use] -pub fn whitelist_key(prefix_len: u8, v4: &[u8; 4]) -> [u8; 8] { - ipv4_lpm_key(prefix_len, v4) +/// Encodes an LPM-trie key for `blacklist_map`: prefix length in byte 0 and the +/// four IPv4 octets in bytes 4..8 (bytes 1..3 are padding the kernel ignores). +pub(super) fn blacklist_key(prefix_len: u8, v4: &[u8; 4]) -> [u8; 8] { + let mut key = [0u8; 8]; + key[0] = prefix_len; + key[4..8].copy_from_slice(v4); + key } /// Encodes an LPM-trie key for `blacklist6_map`: prefix length as a /// little-endian u32 in bytes 0..4 and the 16-byte IPv6 address in network /// order in bytes 4..20 (20 bytes total, matching the C `struct lpm_key6`). -#[must_use] pub fn blacklist6_key(prefix_len: u8, v6: &[u8; 16]) -> [u8; 20] { - ipv6_lpm_key(prefix_len, v6) -} - -/// Encodes an LPM-trie key for `whitelist6_map`; identical to -/// [`blacklist6_key`] because both C maps use `struct lpm_key6`. -#[must_use] -pub fn whitelist6_key(prefix_len: u8, v6: &[u8; 16]) -> [u8; 20] { - ipv6_lpm_key(prefix_len, v6) -} - -fn ipv4_lpm_key(prefix_len: u8, v4: &[u8; 4]) -> [u8; 8] { - let mut key = [0u8; 8]; - key[0..4].copy_from_slice(&u32::from(prefix_len).to_le_bytes()); - key[4..8].copy_from_slice(v4); - key -} - -fn ipv6_lpm_key(prefix_len: u8, v6: &[u8; 16]) -> [u8; 20] { let mut key = [0u8; 20]; - key[0..4].copy_from_slice(&u32::from(prefix_len).to_le_bytes()); + key[0] = prefix_len; key[4..20].copy_from_slice(v6); key } -/// Validates a CIDR prefix length and clears the host bits of `prefix`. -/// -/// The kernel's LPM trie compares keys bit by bit, so `10.1.2.3/24` and -/// `10.1.2.0/24` are different keys for the same range: without masking, two -/// bans of the same subnet never share an entry and expiry bookkeeping falls -/// apart. A zero-length prefix is rejected because "ban the entire address -/// space" is never an intentional operator request. -/// -/// # Errors -/// `prefix_len` is 0 or exceeds 32 for IPv4 / 128 for IPv6. -pub fn normalize_cidr(prefix: IpAddr, prefix_len: u8) -> Result { - match prefix { - IpAddr::V4(addr) => { - ensure_prefix_len(prefix_len, 32, "IPv4")?; - Ok(IpAddr::V4(Ipv4Addr::from(mask_v4(addr, prefix_len)))) - }, - IpAddr::V6(addr) => { - ensure_prefix_len(prefix_len, 128, "IPv6")?; - Ok(IpAddr::V6(Ipv6Addr::from(mask_v6(addr, prefix_len)))) - }, - } -} - -fn ensure_prefix_len(prefix_len: u8, max: u8, family: &str) -> Result<()> { - if prefix_len == 0 || prefix_len > max { - bail!("invalid {family} prefix length {prefix_len}: expected 1..={max}"); - } - Ok(()) -} - -fn mask_v4(addr: Ipv4Addr, prefix_len: u8) -> [u8; 4] { - let bits = u32::from(addr); - let mask = u32::MAX << (32 - u32::from(prefix_len)); - (bits & mask).to_be_bytes() -} - -fn mask_v6(addr: Ipv6Addr, prefix_len: u8) -> [u8; 16] { - let mut octets = addr.octets(); - let full_bytes = usize::from(prefix_len) / 8; - let remainder = prefix_len % 8; - for byte in octets.iter_mut().skip(full_bytes) { - *byte = 0; - } - if remainder != 0 { - // `full_bytes` is always < 16 here: a partial byte follows the full ones. - octets[full_bytes] &= 0xffu8 << (8 - remainder); - } - octets +/// Absolute ban expiry on the monotonic clock, saturating so an absurd duration +/// clamps to `u64::MAX` rather than wrapping into the past. +pub(super) fn blacklist_expiry_ns(now_ns: u64, duration_secs: u64) -> u64 { + now_ns.saturating_add(duration_secs.saturating_mul(1_000_000_000)) } impl XdpFilter { /// Adds a CIDR ban to the matching LPM trie: `blacklist_map` for IPv4, /// `blacklist6_map` for IPv6. /// - /// The prefix is masked first (see [`normalize_cidr`]), so every ban of - /// the same subnet addresses the same kernel key. - /// /// # Errors - /// Invalid prefix length, XDP not loaded, map missing from the object, or - /// a BPF update failure. + /// XDP not loaded, map missing from the object, or a BPF update failure. pub fn ban_cidr(&self, prefix: IpAddr, prefix_len: u8, duration_secs: u64) -> Result<()> { - match normalize_cidr(prefix, prefix_len)? { + match prefix { IpAddr::V4(net) => self.blacklist_update(prefix_len, &net.octets(), duration_secs), IpAddr::V6(net) => self.blacklist6_update(prefix_len, &net.octets(), duration_secs), } @@ -133,113 +74,6 @@ impl XdpFilter { Ok(()) } - /// Adds one address to the kernel whitelist: `/32` for IPv4, `/128` for IPv6. - /// - /// # Errors - /// XDP not loaded, the matching whitelist map is missing, or a BPF update - /// failure. - pub fn whitelist_add(&self, ip: IpAddr) -> Result<()> { - let prefix_len = match ip { - IpAddr::V4(_) => 32, - IpAddr::V6(_) => 128, - }; - self.whitelist_add_cidr(ip, prefix_len) - } - - /// Adds a CIDR to the matching whitelist LPM trie: `whitelist_map` for - /// IPv4, `whitelist6_map` for IPv6. - /// - /// The C filter treats a present key as "trusted" and ignores the value, - /// so the stored `u8` is always `1`. - /// - /// # Errors - /// Invalid prefix length, XDP not loaded, map missing from the object, or - /// a BPF update failure. - pub fn whitelist_add_cidr(&self, prefix: IpAddr, prefix_len: u8) -> Result<()> { - match normalize_cidr(prefix, prefix_len)? { - IpAddr::V4(net) => { - let map = self.find_map("whitelist_map")?; - map.update(&whitelist_key(prefix_len, &net.octets()), &[1u8], MapFlags::ANY)?; - }, - IpAddr::V6(net) => { - let map = self.find_map("whitelist6_map")?; - map.update(&whitelist6_key(prefix_len, &net.octets()), &[1u8], MapFlags::ANY)?; - }, - } - Ok(()) - } - - /// Removes one address from the kernel whitelist. - /// - /// # Errors - /// XDP not loaded, the matching whitelist map is missing, or a BPF delete - /// failure. - pub fn whitelist_remove(&self, ip: IpAddr) -> Result<()> { - match ip { - IpAddr::V4(addr) => { - let map = self.find_map("whitelist_map")?; - map.delete(&whitelist_key(32, &addr.octets()))?; - }, - IpAddr::V6(addr) => { - let map = self.find_map("whitelist6_map")?; - map.delete(&whitelist6_key(128, &addr.octets()))?; - }, - } - Ok(()) - } - - /// Removes expired entries from `blacklist_map` and `blacklist6_map`. - /// - /// The packet path can only expire the exact `/32` or `/128` key it looked - /// up, so a ban on a wider prefix (for example a `/24`) stays resident and - /// keeps blocking sources until it is deleted here. Call periodically. - /// - /// Expiry semantics are the kernel's: an entry is alive while - /// `expiry > bpf_ktime_get_ns()`. There is no "permanent" sentinel; `0` is - /// already expired and is deleted, while a permanent ban is stored as - /// `u64::MAX` and naturally survives every comparison. Keys are collected - /// before deletion because the LPM iterator is not stable across deletes, - /// and the expiry is re-read immediately before the delete so a - /// concurrent refresh wins over the reaper. - /// - /// # Errors - /// XDP not loaded, a blacklist map is missing, or a BPF lookup/delete fails. - pub fn reap_expired_bans(&self) -> Result { - let now = monotonic_ns(); - let reaped = self.reap_map("blacklist_map", now)? + self.reap_map("blacklist6_map", now)?; - Ok(reaped) - } - - fn reap_map(&self, name: &str, now: u64) -> Result { - let map = self.find_map(name)?; - let keys: Vec> = map.keys().collect(); - let mut reaped = 0; - for key in keys { - let Some(value) = map.lookup(&key, MapFlags::ANY)? else { - continue; - }; - let Ok(raw) = <[u8; 8]>::try_from(value.as_slice()) else { - continue; - }; - if u64::from_le_bytes(raw) > now { - continue; - } - // A ban may have been refreshed after the first read; never delete a fresh one. - let Some(value) = map.lookup(&key, MapFlags::ANY)? else { - continue; - }; - let Ok(raw) = <[u8; 8]>::try_from(value.as_slice()) else { - continue; - }; - if u64::from_le_bytes(raw) > monotonic_ns() { - continue; - } - map.delete(&key)?; - reaped += 1; - } - Ok(reaped) - } - pub fn unban_ip(&self, ip: Ipv4Addr) -> Result<()> { let map = self.find_map("blacklist_map")?; let key = blacklist_key(32, &ip.octets()); @@ -247,3 +81,25 @@ impl XdpFilter { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blacklist_key_puts_prefix_len_first_and_octets_last() { + assert_eq!(blacklist_key(24, &[10, 0, 1, 200]), [24, 0, 0, 0, 10, 0, 1, 200]); + assert_eq!(blacklist_key(32, &[127, 0, 0, 1]), [32, 0, 0, 0, 127, 0, 0, 1]); + } + + #[test] + fn blacklist_expiry_converts_secs_to_ns() { + assert_eq!(blacklist_expiry_ns(1_000, 2), 1_000 + 2_000_000_000); + } + + #[test] + fn blacklist_expiry_saturates_instead_of_wrapping() { + assert_eq!(blacklist_expiry_ns(u64::MAX, 1), u64::MAX); + assert_eq!(blacklist_expiry_ns(0, u64::MAX), u64::MAX); + } +} diff --git a/src/xdp/filter/mod.rs b/src/xdp/filter/mod.rs index 7ab1b63..5fe2da3 100644 --- a/src/xdp/filter/mod.rs +++ b/src/xdp/filter/mod.rs @@ -1,32 +1,27 @@ -use anyhow::{Context, Result}; -use libbpf_rs::{MapCore, Object, ObjectBuilder, RingBuffer, Xdp, XdpFlags}; +use anyhow::{Context, Result, bail}; +use libbpf_rs::{MapCore, MapFlags, Object, ObjectBuilder, RingBuffer, Xdp, XdpFlags}; use std::os::unix::io::AsFd; use std::sync::Arc; +use super::XdpStats; use super::globals::XdpGlobals; use crate::config::XdpConfig; use crate::filter::blacklist::Blacklist; +use crate::traffic::prefix::{PrefixKey, PrefixStatsVal}; -use attach::{attach_program, patch_rodata}; -use events::{AutoBanConfig, build_ringbuf}; +use attach::{build_ringbuf, interface_cstr, patch_rodata, xdp_attach_mode_name}; +use events::AutoBanConfig; mod attach; pub(crate) mod events; mod maps; -pub use attach::{interface_cstr, is_rodata_map, xdp_attach_mode_name}; -pub use maps::{blacklist_key, blacklist6_key, normalize_cidr, whitelist_key, whitelist6_key}; +pub use maps::{blacklist6_key, monotonic_ns}; pub struct XdpFilter { obj: Option, ringbuf: Option>, ifindex: i32, - /// Raw `XdpFlags` bits of the slot the program was actually attached to - /// (libbpf-rs's `XdpFlags` is neither `Copy` nor `Clone`, so the bits are - /// stored and rebuilt with `from_bits_truncate`). The kernel may pick - /// generic (skb) mode after a failed native attach; detaching the native - /// slot in that case would leave an orphaned filter behind. - attach_flags: Option, interface: String, globals: XdpGlobals, blacklist: Option>, @@ -39,7 +34,6 @@ impl XdpFilter { obj: None, ringbuf: None, ifindex: 0, - attach_flags: None, interface: interface.to_string(), globals: XdpGlobals::default(), blacklist: None, @@ -62,16 +56,6 @@ impl XdpFilter { self.autoban = AutoBanConfig::from_xdp(config); } - /// Loads the object, attaches it and registers the ringbuf reader. - /// - /// Fallible setup (`build_ringbuf`) runs before the attach, so a failure - /// there cannot leave a filter behind. Everything after the attach is - /// covered by an `attach::DetachGuard`: any early return detaches instead - /// of leaving an orphaned program that drops traffic without a reader. - /// - /// # Errors - /// The environment probe, object load, map setup or attach failed. On an - /// attach failure no program is left installed. pub fn load(&mut self) -> Result<()> { // Diagnostics before loading: fail fast on an unsupported kernel or driver. super::probe::preflight(&self.interface)?; @@ -96,65 +80,68 @@ impl XdpFilter { let ifindex = unsafe { libc::if_nametoindex(c_interface.as_ptr()) }; if ifindex == 0 { let err = std::io::Error::last_os_error(); - anyhow::bail!("interface '{}' not found: {err}", self.interface); + bail!("interface '{}' not found: {err}", self.interface); } - // The ringbuf is the only fallible post-attach step; building it first - // removes the failure mode entirely instead of relying on rollback. + + let prog = obj + .progs() + .find(|p| p.name() == "rampart_universal_filter") + .context("XDP program 'rampart_universal_filter' not found")?; + let xdp = Xdp::new(prog.as_fd()); + // Mode ladder: try native (drv) first; if the driver cannot handle it, fall back to + // generic (skb) with a warning (finding #1 of the competitive analysis: report the + // mode as it is, no window dressing). + let ifindex = ifindex as i32; + if let Err(e) = xdp.attach(ifindex, XdpFlags::NONE) { + tracing::warn!( + interface = %self.interface, + error = %e, + "native XDP attach failed, falling back to generic (skb) mode" + ); + xdp.attach(ifindex, XdpFlags::SKB_MODE) + .context("XDP attach failed in both native and generic modes")?; + } + let mode = xdp + .query(ifindex, XdpFlags::NONE) + .map(|q| xdp_attach_mode_name(q.attach_mode)) + .unwrap_or("unknown"); + super::metrics::init(); let rbuf = build_ringbuf(&obj, self.blacklist.clone(), self.autoban)?; - let (attach_flags, mode, guard) = attach_program(&obj, ifindex as i32, &self.interface)?; - guard.disarm(); - self.obj = Some(obj); self.ringbuf = Some(rbuf); - self.ifindex = ifindex as i32; - self.attach_flags = Some(attach_flags); + self.ifindex = ifindex; tracing::info!("XDP filter attached to {} (mode: {mode})", self.interface); Ok(()) } - /// Detaches the program from the interface and drops the ringbuf. - /// - /// The stored attach flags select the slot the kernel actually used, and - /// the interface is queried afterwards: a detach that silently did - /// nothing (the old `XdpFlags::NONE` on a generic-mode program) must not - /// be reported as success. - /// - /// # Errors - /// The detach failed or the interface still reports an attached program. pub fn unload(&mut self) -> Result<()> { - let Some(obj) = self.obj.as_ref() else { - self.ringbuf = None; - self.ifindex = 0; - self.attach_flags = None; - return Ok(()); - }; - let Some(flags) = self.attach_flags else { - anyhow::bail!("XDP state is inconsistent: object present without attach flags"); - }; - let result = self.detach_program(obj, flags); + let was_attached = self.obj.is_some(); + let mut result = Ok(()); + if let Some(obj) = self.obj.as_ref() { + result = self.detach_program(obj); + } self.ringbuf = None; - if result.is_ok() { - self.obj = None; - self.ifindex = 0; - self.attach_flags = None; + self.obj = None; + self.ifindex = 0; + if was_attached { tracing::info!("XDP filter detached from {}", self.interface); } result } /// Detaches the XDP program using the real program fd owned by the loaded - /// `Object`. A detach failure while a filter is active is surfaced loudly - /// and returned, never swallowed — otherwise the kernel keeps dropping - /// packets we no longer intend to filter. - fn detach_program(&self, obj: &Object, flags: u32) -> Result<()> { + /// `Object` (mirroring `load`'s `Xdp::new(prog.as_fd()).attach(..)`). A + /// detach failure while a filter is active is surfaced loudly and returned, + /// never swallowed — otherwise the kernel keeps dropping packets we no + /// longer intend to filter. + fn detach_program(&self, obj: &Object) -> Result<()> { let prog = obj .progs() .find(|p| p.name() == "rampart_universal_filter") .context("XDP program 'rampart_universal_filter' not found while detaching")?; - let xdp = Xdp::new(prog.as_fd()); - if let Err(e) = xdp.detach(self.ifindex, XdpFlags::from_bits_truncate(flags)) { + if let Err(e) = Xdp::new(prog.as_fd()).detach(self.ifindex, XdpFlags::NONE) { tracing::error!( interface = %self.interface, ifindex = self.ifindex, @@ -163,19 +150,6 @@ impl XdpFilter { ); return Err(e).with_context(|| format!("failed to detach XDP from '{}'", self.interface)); } - // Query every mode (`NONE`), not just the one we detached: only an - // attach mode of NONE proves the interface is clean. - let remaining = xdp - .query(self.ifindex, XdpFlags::NONE) - .context("failed to verify the XDP detach (query)")? - .attach_mode; - if remaining != 0 { - let mode = xdp_attach_mode_name(remaining); - anyhow::bail!( - "XDP program is still attached to '{}' after detach (mode: {mode})", - self.interface - ); - } Ok(()) } @@ -185,7 +159,7 @@ impl XdpFilter { } } - pub(crate) fn find_map<'a>(&'a self, name: &str) -> Result { + fn find_map<'a>(&'a self, name: &str) -> Result { self.obj .as_ref() .context("XDP not loaded")? @@ -193,6 +167,53 @@ impl XdpFilter { .find(|m| m.name() == name) .with_context(|| format!("map '{}' not found", name)) } + + /// Reads the `prefix_stats` map (aggregates per /24 and /64 prefix). + /// + /// # Errors + /// XDP is not loaded, the map is missing from the object, or a BPF read fails. + pub fn read_prefix_stats(&self) -> Result> { + let map = self.find_map("prefix_stats")?; + let mut out = Vec::new(); + for key in map.keys() { + let Ok(kb) = <[u8; 24]>::try_from(key.as_slice()) else { + continue; + }; + let Some(val) = map.lookup(&kb, MapFlags::ANY).context("prefix_stats lookup failed")? else { + continue; + }; + let Ok(vb) = <[u8; 24]>::try_from(val.as_slice()) else { + continue; + }; + out.push((PrefixKey::from_bytes(kb), PrefixStatsVal::from_bytes(vb))); + } + Ok(out) + } + + pub fn get_stats(&self) -> Result { + let map = self.find_map("stats_map")?; + let sum = |idx: u32| -> u64 { + let key = idx.to_le_bytes(); + match map.lookup(&key, MapFlags::ANY) { + Ok(Some(v)) => v + .chunks_exact(8) + .map(|c| u64::from_le_bytes(c.try_into().expect("chunk size 8"))) + .sum(), + _ => 0, + } + }; + Ok(XdpStats { + total: sum(0), + tcp: sum(1), + whitelist: sum(2), + blacklist: sum(3), + syn_throttle: sum(4), + passed: sum(5), + dropped: sum(6), + udp: sum(7), + rate_limit: sum(8), + }) + } } // SAFETY: `XdpFilter` is only ever accessed from the single thread that owns it, diff --git a/src/xdp/mod.rs b/src/xdp/mod.rs index 0909bf2..9bb4b3a 100644 --- a/src/xdp/mod.rs +++ b/src/xdp/mod.rs @@ -6,9 +6,7 @@ mod probe; pub use probe::{ - AttachMode, EnvironmentReport, FilesystemProbe, KernelVersion, MIN_KERNEL, STAT_BLACKLIST, STAT_CHALLENGE_FAILED, - STAT_CHALLENGE_SENT, STAT_CHALLENGE_VERIFIED, STAT_DROP, STAT_FRAGMENT_BYPASS, STAT_PASS, STAT_RATE_LIMIT, - STAT_SYN_THROTTLE, STAT_TCP, STAT_TOTAL, STAT_UDP, STAT_WHITELIST, SystemProbe, XdpStats, + AttachMode, EnvironmentReport, FilesystemProbe, KernelVersion, MIN_KERNEL, SystemProbe, XdpStats, driver_supports_native_xdp, }; @@ -23,17 +21,18 @@ mod metrics; #[cfg(feature = "xdp")] mod filter; #[cfg(feature = "xdp")] +pub use filter::XdpFilter; +#[cfg(feature = "xdp")] +pub use filter::blacklist6_key; +#[cfg(feature = "xdp")] pub use filter::events::{ AutoBanConfig, BanAction, XDP_EVENT_LEN, XdpEvent, XdpEventKind, auto_ban_decision, parse_xdp_event, }; #[cfg(feature = "xdp")] -pub use filter::{ - XdpFilter, blacklist_key, blacklist6_key, interface_cstr, is_rodata_map, normalize_cidr, whitelist_key, - whitelist6_key, xdp_attach_mode_name, -}; +pub use filter::monotonic_ns; #[cfg(feature = "xdp")] -pub use probe::{XdpMetrics, blacklist_expiry_ns, monotonic_ns}; +pub use probe::XdpMetrics; #[cfg(not(feature = "xdp"))] mod noop; diff --git a/src/xdp/noop.rs b/src/xdp/noop.rs index 97e06f5..37c6be0 100644 --- a/src/xdp/noop.rs +++ b/src/xdp/noop.rs @@ -23,12 +23,6 @@ impl XdpFilter { Ok(()) } - /// Nothing to reap without the kernel filter; the maintenance loop can call - /// this unconditionally. - pub fn reap_expired_bans(&self) -> Result { - Ok(0) - } - /// Honest failure: reading `prefix_stats` is not wired up without the `xdp` feature. /// /// # Errors diff --git a/src/xdp/probe/clock.rs b/src/xdp/probe/clock.rs deleted file mode 100644 index beeca51..0000000 --- a/src/xdp/probe/clock.rs +++ /dev/null @@ -1,30 +0,0 @@ -//! Monotonic clock shared by the XDP userspace path. -//! -//! The kernel writes `bpf_ktime_get_ns()` values (CLOCK_MONOTONIC nanoseconds -//! since boot) into the ban maps, and the packet path compares expiry -//! against the same clock. Userspace must therefore never use `SystemTime` -//! (epoch nanoseconds, about 50 years larger) for bans. - -/// Monotonic clock in ns since boot — the same clock as `bpf_ktime_get_ns()`, -/// which is what the XDP program compares ban expiry against. `SystemTime` -/// (epoch ns) is ~50 years larger, so bans written with it never expired. -/// -/// # Panics -/// Never: `clock_gettime(CLOCK_MONOTONIC)` cannot fail on Linux. -#[must_use] -pub fn monotonic_ns() -> u64 { - let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 }; - // SAFETY: `ts` is a valid, writable `timespec` and CLOCK_MONOTONIC is - // always available on Linux (the only target of the `xdp` feature). - unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) }; - let secs = u64::try_from(ts.tv_sec).unwrap_or(0); - secs.saturating_mul(1_000_000_000) - .saturating_add(u64::try_from(ts.tv_nsec).unwrap_or(0)) -} - -/// Absolute ban expiry on the monotonic clock, saturating so an absurd duration -/// clamps to `u64::MAX` rather than wrapping into the past. -#[must_use] -pub fn blacklist_expiry_ns(now_ns: u64, duration_secs: u64) -> u64 { - now_ns.saturating_add(duration_secs.saturating_mul(1_000_000_000)) -} diff --git a/src/xdp/probe/metrics.rs b/src/xdp/probe/metrics.rs index 952d0c7..99bd70f 100644 --- a/src/xdp/probe/metrics.rs +++ b/src/xdp/probe/metrics.rs @@ -13,10 +13,6 @@ pub struct XdpMetrics { dropped: IntGauge, udp: IntGauge, rate_limit: IntGauge, - challenge_sent: IntGauge, - challenge_verified: IntGauge, - challenge_failed: IntGauge, - fragment_bypass: IntGauge, } impl XdpMetrics { @@ -37,13 +33,6 @@ impl XdpMetrics { dropped: Self::new_gauge("rampart_xdp_dropped", "Packets dropped by filter")?, udp: Self::new_gauge("rampart_xdp_udp", "UDP packets processed")?, rate_limit: Self::new_gauge("rampart_xdp_rate_limit", "Packets rate-limited by window counter")?, - challenge_sent: Self::new_gauge("rampart_xdp_challenge_sent", "RST challenges sent")?, - challenge_verified: Self::new_gauge("rampart_xdp_challenge_verified", "RST challenges verified")?, - challenge_failed: Self::new_gauge("rampart_xdp_challenge_failed", "RST challenges failed")?, - fragment_bypass: Self::new_gauge( - "rampart_xdp_fragment_bypass", - "Packets bypassing L4 checks as fragments", - )?, }; tracing::info!("XDP Prometheus metrics registered"); Ok(m) @@ -59,10 +48,6 @@ impl XdpMetrics { self.dropped.set(stats.dropped as i64); self.udp.set(stats.udp as i64); self.rate_limit.set(stats.rate_limit as i64); - self.challenge_sent.set(stats.challenge_sent as i64); - self.challenge_verified.set(stats.challenge_verified as i64); - self.challenge_failed.set(stats.challenge_failed as i64); - self.fragment_bypass.set(stats.fragment_bypass as i64); tracing::debug!("XDP metrics updated"); } } diff --git a/src/xdp/probe/mod.rs b/src/xdp/probe/mod.rs index bd70e2b..4f5ad7a 100644 --- a/src/xdp/probe/mod.rs +++ b/src/xdp/probe/mod.rs @@ -1,4 +1,4 @@ -//! XDP environment probing: diagnostics, statistics, metrics and the shared clock. +//! XDP environment probing: diagnostics, statistics and metrics. mod diagnostics; #[cfg(feature = "xdp")] @@ -7,17 +7,8 @@ pub use diagnostics::{ AttachMode, EnvironmentReport, FilesystemProbe, KernelVersion, MIN_KERNEL, SystemProbe, driver_supports_native_xdp, }; -#[cfg(feature = "xdp")] -mod clock; -#[cfg(feature = "xdp")] -pub use clock::{blacklist_expiry_ns, monotonic_ns}; - mod stats; -pub use stats::{ - STAT_BLACKLIST, STAT_CHALLENGE_FAILED, STAT_CHALLENGE_SENT, STAT_CHALLENGE_VERIFIED, STAT_DROP, - STAT_FRAGMENT_BYPASS, STAT_PASS, STAT_RATE_LIMIT, STAT_SYN_THROTTLE, STAT_TCP, STAT_TOTAL, STAT_UDP, - STAT_WHITELIST, XdpStats, -}; +pub use stats::XdpStats; #[cfg(feature = "xdp")] mod metrics; diff --git a/src/xdp/probe/stats.rs b/src/xdp/probe/stats.rs index 449e047..34d4845 100644 --- a/src/xdp/probe/stats.rs +++ b/src/xdp/probe/stats.rs @@ -1,47 +1,3 @@ -//! XDP program counters and the readers for the kernel statistics maps. -//! -//! `stats_map` is a `BPF_MAP_TYPE_PERCPU_ARRAY` keyed by the `STAT_*` indices -//! from `xdp/core/maps.h`; every element holds one `__u64` per CPU, so a -//! lookup returns a blob whose 8-byte chunks must be summed. -//! `prefix_stats` is a plain LRU hash read as whole key/value records. - -#[cfg(feature = "xdp")] -use anyhow::{Context, Result}; -#[cfg(feature = "xdp")] -use libbpf_rs::{MapCore, MapFlags}; - -#[cfg(feature = "xdp")] -use crate::traffic::prefix::{PrefixKey, PrefixStatsVal}; -#[cfg(feature = "xdp")] -use crate::xdp::XdpFilter; - -/// `STAT_TOTAL`: every packet that reached the filter. -pub const STAT_TOTAL: u32 = 0; -/// `STAT_TCP`: TCP packets seen. -pub const STAT_TCP: u32 = 1; -/// `STAT_WHITELIST`: packets passed by the whitelist check. -pub const STAT_WHITELIST: u32 = 2; -/// `STAT_BLACKLIST`: packets dropped by the blacklist check. -pub const STAT_BLACKLIST: u32 = 3; -/// `STAT_SYN_THROTTLE`: SYNs dropped by the per-source throttle. -pub const STAT_SYN_THROTTLE: u32 = 4; -/// `STAT_PASS`: packets passed to the kernel stack. -pub const STAT_PASS: u32 = 5; -/// `STAT_DROP`: packets dropped by any rule. -pub const STAT_DROP: u32 = 6; -/// `STAT_UDP`: UDP packets seen. -pub const STAT_UDP: u32 = 7; -/// `STAT_RATE_LIMIT`: packets dropped by a rate limiter. -pub const STAT_RATE_LIMIT: u32 = 8; -/// `STAT_CHALLENGE_SENT`: RST challenges sent to suspicious sources. -pub const STAT_CHALLENGE_SENT: u32 = 9; -/// `STAT_CHALLENGE_VERIFIED`: sources that answered a challenge correctly. -pub const STAT_CHALLENGE_VERIFIED: u32 = 10; -/// `STAT_CHALLENGE_FAILED`: sources that failed a challenge. -pub const STAT_CHALLENGE_FAILED: u32 = 11; -/// `STAT_FRAGMENT_BYPASS`: packets passed because their L4 header is unavailable (fragments). -pub const STAT_FRAGMENT_BYPASS: u32 = 12; - /// XDP program counters; the indices follow `STAT_*` from `xdp/core/maps.h`. #[derive(Debug, Clone, Copy, Default)] pub struct XdpStats { @@ -54,67 +10,4 @@ pub struct XdpStats { pub dropped: u64, pub udp: u64, pub rate_limit: u64, - pub challenge_sent: u64, - pub challenge_verified: u64, - pub challenge_failed: u64, - pub fragment_bypass: u64, -} - -#[cfg(feature = "xdp")] -impl XdpFilter { - /// Reads `stats_map` and sums the per-CPU values. - /// - /// # Errors - /// XDP is not loaded, or the map is missing from the object (individual - /// lookup failures are reported as zero rather than aborting the report). - pub fn get_stats(&self) -> Result { - let map = self.find_map("stats_map")?; - let sum = |idx: u32| -> u64 { - let key = idx.to_le_bytes(); - match map.lookup(&key, MapFlags::ANY) { - Ok(Some(v)) => v - .chunks_exact(8) - .map(|c| u64::from_le_bytes(c.try_into().expect("chunk size 8"))) - .sum(), - _ => 0, - } - }; - Ok(XdpStats { - total: sum(STAT_TOTAL), - tcp: sum(STAT_TCP), - whitelist: sum(STAT_WHITELIST), - blacklist: sum(STAT_BLACKLIST), - syn_throttle: sum(STAT_SYN_THROTTLE), - passed: sum(STAT_PASS), - dropped: sum(STAT_DROP), - udp: sum(STAT_UDP), - rate_limit: sum(STAT_RATE_LIMIT), - challenge_sent: sum(STAT_CHALLENGE_SENT), - challenge_verified: sum(STAT_CHALLENGE_VERIFIED), - challenge_failed: sum(STAT_CHALLENGE_FAILED), - fragment_bypass: sum(STAT_FRAGMENT_BYPASS), - }) - } - - /// Reads the `prefix_stats` map (aggregates per /24 and /64 prefix). - /// - /// # Errors - /// XDP is not loaded, the map is missing from the object, or a BPF read fails. - pub fn read_prefix_stats(&self) -> Result> { - let map = self.find_map("prefix_stats")?; - let mut out = Vec::new(); - for key in map.keys() { - let Ok(kb) = <[u8; 24]>::try_from(key.as_slice()) else { - continue; - }; - let Some(val) = map.lookup(&kb, MapFlags::ANY).context("prefix_stats lookup failed")? else { - continue; - }; - let Ok(vb) = <[u8; 24]>::try_from(val.as_slice()) else { - continue; - }; - out.push((PrefixKey::from_bytes(kb), PrefixStatsVal::from_bytes(vb))); - } - Ok(out) - } } diff --git a/tests/app_shutdown.rs b/tests/app_shutdown.rs deleted file mode 100644 index 97b54cb..0000000 --- a/tests/app_shutdown.rs +++ /dev/null @@ -1,15 +0,0 @@ -//! Edge daemon exit codes: a forced drain timeout must not look like success. - -use rampart::app::RunExit; - -#[test] -fn clean_shutdown_exits_zero() { - assert_eq!(RunExit::Ok.code(), 0); -} - -#[test] -fn forced_drain_timeout_exits_nonzero() { - // Connections were cut before finishing: supervisors and scripts must see a - // failure, not a clean exit. - assert_eq!(RunExit::DrainTimeout.code(), 1); -} diff --git a/tests/clickhouse_writer.rs b/tests/clickhouse_writer.rs deleted file mode 100644 index 0ce466b..0000000 --- a/tests/clickhouse_writer.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! Integration tests for the ClickHouse sink: buffering, bounded flush and -//! retry on failure. - -use std::time::{Duration, Instant}; - -use rampart::store::clickhouse::{ClickHouseEvent, ClickHouseWriter, MAX_BUFFER_EVENTS}; - -fn event(seq: usize) -> ClickHouseEvent { - ClickHouseEvent { - timestamp: chrono::Utc::now(), - event_type: "test".to_string(), - ip: format!("192.0.2.{}", seq % 250), - data_float: 0.0, - data_int: 0, - data_string: String::new(), - } -} - -#[tokio::test] -async fn push_only_buffers_events() { - let mut writer = ClickHouseWriter::new("http://127.0.0.1:1"); - writer.push(event(0)).await.expect("push must succeed"); - - assert_eq!(writer.pending(), 1, "push must not flush eagerly"); - assert_eq!(writer.dropped(), 0); -} - -#[tokio::test] -async fn empty_flush_is_a_noop() { - let mut writer = ClickHouseWriter::new("http://127.0.0.1:1"); - writer.flush().await.expect("empty flush must not touch the network"); -} - -#[tokio::test] -async fn failed_flush_requeues_the_batch() { - let mut writer = ClickHouseWriter::new("http://127.0.0.1:1"); - writer.push(event(1)).await.expect("push must succeed"); - - let result = writer.flush().await; - - assert!(result.is_err(), "connection refused must surface as an error"); - assert_eq!(writer.pending(), 1, "failed batch must be re-queued"); - assert_eq!(writer.dropped(), 0, "a single failed batch is not a drop"); -} - -#[tokio::test] -async fn stalled_server_flush_is_bounded() { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind"); - let addr = listener.local_addr().expect("local addr"); - let server = tokio::spawn(async move { - let (_stream, _) = listener.accept().await.expect("accept"); - // Keep the connection open without ever answering. - std::future::pending::<()>().await; - }); - - let mut writer = ClickHouseWriter::new(&format!("http://{addr}/")); - writer.push(event(2)).await.expect("push must succeed"); - - let started = Instant::now(); - let result = writer.flush().await; - let elapsed = started.elapsed(); - server.abort(); - - assert!(result.is_err(), "a stalled server must fail the flush"); - assert!( - elapsed < Duration::from_secs(5), - "flush must be bounded, took {elapsed:?}" - ); - assert_eq!(writer.pending(), 1, "timed-out batch must be re-queued"); -} - -#[tokio::test] -async fn buffer_is_bounded_and_overflow_is_counted() { - let mut writer = ClickHouseWriter::new("http://127.0.0.1:1"); - for seq in 0..MAX_BUFFER_EVENTS + 7 { - writer.push(event(seq)).await.expect("push must succeed"); - } - - assert_eq!(writer.pending(), MAX_BUFFER_EVENTS, "buffer must stay bounded"); - assert_eq!(writer.dropped(), 7, "overflow must be counted"); -} diff --git a/tests/config_parse.rs b/tests/config_parse.rs index 74b2b4a..230c25d 100644 --- a/tests/config_parse.rs +++ b/tests/config_parse.rs @@ -142,127 +142,3 @@ events_enabled = false assert!(!xdp.throttle_enabled); assert!(!xdp.events_enabled); } - -#[test] -fn prefix_detect_defaults_disabled() { - let config = Config::parse_str("").expect("empty config must parse"); - assert!(!config.detect.prefix.enabled); - assert_eq!(config.detect.prefix.syn_threshold, 500); - assert_eq!(config.detect.prefix.window_secs, 10); - assert_eq!(config.detect.prefix.min_unique_sources, 16); -} - -#[test] -fn prefix_detect_section_parses() { - let config = Config::parse_str( - r#" -[detect.prefix] -enabled = true -syn_threshold = 1000 -window_secs = 5 -min_unique_sources = 8 -"#, - ) - .expect("detect.prefix section must parse"); - assert!(config.detect.prefix.enabled); - assert_eq!(config.detect.prefix.syn_threshold, 1000); - assert_eq!(config.detect.prefix.window_secs, 5); - assert_eq!(config.detect.prefix.min_unique_sources, 8); -} - -#[test] -fn prefix_detect_zero_threshold_rejected_when_enabled() { - let err = Config::parse_str("[detect.prefix]\nenabled = true\nsyn_threshold = 0\n") - .expect_err("zero threshold must be rejected"); - assert!(err.to_string().contains("detect.prefix.syn_threshold")); -} - -#[test] -fn syn_challenge_requires_a_secret() { - let err = Config::parse_str("[xdp]\nsyn_challenge_enabled = true\n") - .expect_err("missing challenge secret must be rejected"); - let message = err.to_string(); - assert!(message.contains("challenge_secret_hex")); - assert!(message.contains("openssl rand -hex 8")); -} - -#[test] -fn syn_challenge_rejects_every_placeholder_spelling() { - for secret in [ - "a5a5a5a5a5a5a5a5", - "A5A5A5A5A5A5A5A5", - "0xA5A5A5A5A5A5A5A5", - "a5a5-5a5a-5a5a-a5a5", - "a5a55a5a5a5aa5a5", - "A5A5_5A5A_5A5A_A5A5", - "0xa5a55a5a5a5aa5a5", - ] { - let toml = format!("[xdp]\nsyn_challenge_enabled = true\nchallenge_secret_hex = \"{secret}\"\n"); - let err = Config::parse_str(&toml).expect_err("placeholder secret must be rejected"); - assert!( - err.to_string().contains("placeholder"), - "secret '{secret}' must be rejected" - ); - } -} - -#[test] -fn syn_challenge_accepts_a_generated_secret() { - let config = - Config::parse_str("[xdp]\nsyn_challenge_enabled = true\nchallenge_secret_hex = \"9f3c71a0b2d84e65\"\n") - .expect("random challenge secret must be accepted"); - assert_eq!(config.xdp.challenge_secret_hex.as_deref(), Some("9f3c71a0b2d84e65")); -} - -#[test] -fn rejects_non_positive_rate_limit() { - for pps in ["0.0", "-1.0", "nan", "inf"] { - let toml = format!("[limits]\nrate_limit_pps = {pps}\n"); - let err = Config::parse_str(&toml).expect_err("rate_limit_pps must be positive and finite"); - assert!( - err.to_string().contains("limits.rate_limit_pps"), - "pps '{pps}' must be rejected" - ); - } -} - -#[test] -fn rejects_rate_limit_burst_below_one() { - for burst in ["0.0", "0.5", "nan"] { - let toml = format!("[limits]\nrate_limit_burst = {burst}\n"); - let err = Config::parse_str(&toml).expect_err("rate_limit_burst must be at least 1"); - assert!( - err.to_string().contains("limits.rate_limit_burst"), - "burst '{burst}' must be rejected" - ); - } -} - -#[test] -fn rejects_out_of_range_ban_duration() { - let err = Config::parse_str("[ban]\nban_duration_secs = 0\n").expect_err("zero ban duration must be rejected"); - assert!(err.to_string().contains("ban.ban_duration_secs")); - let err = Config::parse_str("[ban]\nban_duration_secs = 31536001\n") - .expect_err("ban duration above one year must be rejected"); - assert!(err.to_string().contains("ban.ban_duration_secs")); - assert!(Config::parse_str("[ban]\nban_duration_secs = 31536000\n").is_ok()); -} - -#[test] -fn rejects_out_of_range_pow_difficulty() { - for difficulty in ["0", "11"] { - let toml = format!("[pow]\nenabled = true\ndifficulty = {difficulty}\n"); - let err = Config::parse_str(&toml).expect_err("pow.difficulty must stay in 1..=10"); - assert!( - err.to_string().contains("pow.difficulty"), - "difficulty '{difficulty}' must be rejected" - ); - } - assert!(Config::parse_str("[pow]\ndifficulty = 10\n").is_ok()); -} - -#[test] -fn rejects_zero_workers() { - let err = Config::parse_str("[workers]\ncount = 0\n").expect_err("zero workers must be rejected"); - assert!(err.to_string().contains("workers.count")); -} diff --git a/tests/connection_limits.rs b/tests/connection_limits.rs deleted file mode 100644 index 33601dd..0000000 --- a/tests/connection_limits.rs +++ /dev/null @@ -1,313 +0,0 @@ -//! Connection-path limits: filter order around the PoW gate, the whitelist -//! exemption from bans, accept-loop backoff and the idle relay timeout. - -use rampart::config::Config; -use rampart::engine::challenge::DifficultyAdjuster; -use rampart::engine::listener::AcceptBackoff; -use rampart::engine::tunnel::Gateway; -use rampart::filter::blacklist::Blacklist; -use rampart::filter::rate_limit::RateLimiter; -use rampart::protocol::ProtocolRegistry; -use rampart::traffic::reputation::IpReputation; -use std::collections::HashSet; -use std::io; -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use std::sync::Arc; -use std::sync::Mutex; -use std::sync::atomic::AtomicU64; -use std::time::Duration; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::net::{TcpListener, TcpStream}; - -/// Linux `EMFILE` (too many open files), the errno behind the accept spin. -#[cfg(target_os = "linux")] -const EMFILE: i32 = 24; - -/// Builds a gateway with the cheap collaborators and no XDP/ClickHouse/protocol -/// handler, so every stage past the filters fails fast. -fn test_gateway(config: Config, whitelist: HashSet) -> Arc { - Arc::new(Gateway::new( - Arc::new(config.clone()), - Arc::new(RateLimiter::new( - config.limits.rate_limit_pps, - config.limits.rate_limit_burst, - )), - Arc::new(Blacklist::new()), - Arc::new(Mutex::new(DifficultyAdjuster::default())), - Arc::new(whitelist), - Arc::new(IpReputation::new()), - None, - None, - Arc::new(AtomicU64::new(0)), - Arc::new(ProtocolRegistry::new()), - None, - )) -} - -/// Returns a connected client/server pair over loopback. -async fn loopback() -> (TcpStream, TcpStream) { - let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind loopback"); - let addr = listener.local_addr().expect("local addr"); - let (client, accepted) = tokio::join!(TcpStream::connect(addr), listener.accept()); - (client.expect("connect"), accepted.expect("accept").0) -} - -/// Reads one newline-terminated line without blocking past `limit`. -async fn read_line(stream: &mut TcpStream, limit: Duration) -> io::Result> { - let mut line = Vec::new(); - let mut byte = [0u8; 1]; - loop { - let read = tokio::time::timeout(limit, stream.read(&mut byte)).await??; - if read == 0 || byte[0] == b'\n' { - return Ok(line); - } - line.push(byte[0]); - } -} - -/// A rate-limited client must be rejected before the PoW exchange starts, so -/// no challenge is written and the task never waits for a solver. -#[tokio::test] -async fn rate_limit_runs_before_pow() { - let mut config = Config::default(); - config.limits.rate_limit_pps = 0.0; - config.limits.rate_limit_burst = 0.0; - config.pow.enabled = true; - config.pow.difficulty = 1; - let gateway = test_gateway(config, HashSet::new()); - - let (mut client, server) = loopback().await; - let peer = SocketAddr::from(([203, 0, 113, 7], 51_000)); - let started = tokio::time::Instant::now(); - let outcome = gateway.handle(server, peer).await; - assert!(outcome.result.is_ok(), "a rate-limited connection is dropped silently"); - assert!( - started.elapsed() < Duration::from_millis(500), - "rate limit must short-circuit the PoW gate" - ); - - let mut scratch = [0u8; 64]; - let read = tokio::time::timeout(Duration::from_secs(1), client.read(&mut scratch)) - .await - .expect("read must not hang") - .expect("read must succeed"); - assert_eq!(read, 0, "a rate-limited client must not receive a PoW challenge"); -} - -/// A client that never answers PoW must still burn its own token, so the next -/// attempt from the same source is rate limited instead of parked in PoW. -#[tokio::test] -async fn silent_pow_client_exhausts_budget_for_next_attempt() { - let mut config = Config::default(); - config.limits.rate_limit_pps = 0.0; - config.limits.rate_limit_burst = 1.0; - config.pow.enabled = true; - config.pow.difficulty = 1; - let gateway = test_gateway(config, HashSet::new()); - let peer = SocketAddr::from(([203, 0, 113, 8], 51_001)); - - let (mut first_client, first_server) = loopback().await; - let first_gateway = Arc::clone(&gateway); - let first = tokio::spawn(async move { first_gateway.handle(first_server, peer).await.result }); - - let challenge = read_line(&mut first_client, Duration::from_secs(2)) - .await - .expect("first attempt must reach the PoW gate"); - assert!(!challenge.is_empty(), "PoW gate issues a challenge line"); - - let (mut second_client, second_server) = loopback().await; - let started = tokio::time::Instant::now(); - let outcome = gateway.handle(second_server, peer).await; - assert!(outcome.result.is_ok()); - assert!( - started.elapsed() < Duration::from_millis(500), - "second attempt must be rejected by the rate limiter, not queued behind PoW" - ); - let mut scratch = [0u8; 1]; - let read = second_client.read(&mut scratch).await.expect("read must succeed"); - assert_eq!(read, 0, "second attempt is closed without a challenge"); - - first.abort(); -} - -/// A whitelisted source stays exempt from the rate limiter and is never -/// auto-banned, even after enough abuse to drive reputation below the ban -/// threshold, and an existing ban entry is ignored for it. -#[tokio::test] -async fn whitelisted_peer_is_exempt_from_rate_limit_and_ban() { - let mut config = Config::default(); - config.limits.rate_limit_pps = 0.0; - config.limits.rate_limit_burst = 0.0; - let trusted = IpAddr::V4(Ipv4Addr::new(198, 51, 100, 10)); - let gateway = test_gateway(config, HashSet::from([trusted])); - let peer = SocketAddr::new(trusted, 51_002); - - for _ in 0..8 { - let (_client, server) = loopback().await; - let outcome = gateway.handle(server, peer).await; - assert!( - outcome.result.is_err(), - "a trusted peer must pass every filter and reach the (empty) registry" - ); - } - assert!( - !gateway.blacklist.is_blocked(trusted), - "a trusted peer must never be banned" - ); - assert_eq!( - gateway.reputation.score(trusted), - 0, - "trusted traffic is not scored as abusive" - ); - - gateway - .blacklist - .add(trusted, Duration::from_secs(60), "stale-test-ban"); - let (_client, server) = loopback().await; - assert!( - gateway.handle(server, peer).await.result.is_err(), - "the whitelist overrides an existing blacklist entry" - ); -} - -/// The untrusted counterpart: repeated rate-limit hits drive reputation below -/// the threshold and the peer is banned. -#[tokio::test] -async fn repeated_rate_limit_hits_auto_ban_untrusted_peer() { - let mut config = Config::default(); - config.limits.rate_limit_pps = 0.0; - config.limits.rate_limit_burst = 0.0; - let gateway = test_gateway(config, HashSet::new()); - let peer_ip = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 9)); - let peer = SocketAddr::new(peer_ip, 51_003); - - for _ in 0..5 { - let (_client, server) = loopback().await; - assert!( - gateway.handle(server, peer).await.result.is_ok(), - "a rate-limited connection is dropped silently" - ); - } - assert!( - gateway.blacklist.is_blocked(peer_ip), - "reputation below -40 must ban the peer" - ); -} - -/// Backoff doubles from 50ms to a 500ms cap and restarts after a successful -/// accept. -#[cfg(target_os = "linux")] -#[test] -fn accept_backoff_grows_caps_and_resets() { - let mut backoff = AcceptBackoff::new(); - let error = io::Error::from_raw_os_error(EMFILE); - let expected = [50u64, 100, 200, 400, 500, 500]; - for milliseconds in expected { - assert_eq!(backoff.delay(&error), Some(Duration::from_millis(milliseconds))); - } - backoff.reset(); - assert_eq!( - backoff.delay(&error), - Some(Duration::from_millis(50)), - "reset after a successful accept restarts at the minimum" - ); -} - -/// Peer-abort errors need no delay: retrying immediately is correct there. -#[test] -fn accept_backoff_skips_non_transient_errors() { - let mut backoff = AcceptBackoff::new(); - assert_eq!(backoff.delay(&io::Error::from(io::ErrorKind::ConnectionAborted)), None); - assert_eq!(backoff.delay(&io::Error::from(io::ErrorKind::InvalidInput)), None); -} - -/// Error logging is rate limited: first failure and then one per window. -#[cfg(target_os = "linux")] -#[test] -fn accept_backoff_rate_limits_error_logs() { - let mut backoff = AcceptBackoff::new(); - let error = io::Error::from_raw_os_error(EMFILE); - assert!(backoff.delay(&error).is_some()); - assert!( - backoff.should_log(), - "the first failure is always logged at error level" - ); - assert!(backoff.delay(&error).is_some()); - assert!(!backoff.should_log(), "repeated failures stay at debug level"); - for _ in 2..32 { - assert!(backoff.delay(&error).is_some()); - } - assert!(backoff.should_log(), "a periodic reminder keeps the condition visible"); -} - -/// The loop must spend real time sleeping instead of spinning. `tokio`'s -/// `test-util` feature is not compiled in, so this uses the real minimum -/// backoff (50ms) with a short iteration count. -#[cfg(target_os = "linux")] -#[tokio::test] -async fn accept_backoff_sleeps_instead_of_spinning() { - let mut backoff = AcceptBackoff::new(); - let error = io::Error::from_raw_os_error(EMFILE); - let started = tokio::time::Instant::now(); - let mut slept = Duration::ZERO; - for _ in 0..3 { - let delay = backoff.delay(&error).expect("transient error must back off"); - assert!(!delay.is_zero(), "a failed accept must yield a non-zero delay"); - tokio::time::sleep(delay).await; - slept += delay; - } - assert!(slept >= Duration::from_millis(350), "50+100+200ms of mandatory backoff"); - assert!( - started.elapsed() >= slept, - "the loop cannot advance faster than its backoff" - ); -} - -/// A silent pair is closed by the relay idle timeout instead of pinning two -/// descriptors forever. -#[tokio::test] -async fn relay_idle_timeout_closes_silent_pair() { - let gateway = test_gateway(Config::default(), HashSet::new()); - let (_client_peer, gateway_side) = loopback().await; - let (backend_gateway_side, _backend_peer) = loopback().await; - - let idle = Duration::from_millis(60); - let started = tokio::time::Instant::now(); - let result = tokio::time::timeout( - Duration::from_secs(2), - gateway.relay_with_idle(gateway_side, backend_gateway_side, idle), - ) - .await - .expect("relay must be cut by the idle timeout, not hang"); - assert!(result.is_err(), "silent relay must be cut by the idle timeout"); - assert!(started.elapsed() >= idle, "the idle budget must actually elapse"); -} - -/// The idle budget must not break normal forwarding in either direction. -#[tokio::test] -async fn relay_forwards_bytes_in_both_directions() { - let gateway = test_gateway(Config::default(), HashSet::new()); - let (mut client_peer, client_side) = loopback().await; - let (backend_side, mut backend_peer) = loopback().await; - - let relay = tokio::spawn(async move { - gateway - .relay_with_idle(client_side, backend_side, Duration::from_secs(5)) - .await - }); - - client_peer.write_all(b"ping").await.expect("write to relay"); - let mut buffer = [0u8; 4]; - backend_peer.read_exact(&mut buffer).await.expect("backend read"); - assert_eq!(&buffer, b"ping"); - - backend_peer.write_all(b"pong").await.expect("write from backend"); - client_peer.read_exact(&mut buffer).await.expect("client read"); - assert_eq!(&buffer, b"pong"); - - drop(client_peer); - assert!( - relay.await.expect("relay task").is_ok(), - "clean half-close is not an error" - ); -} diff --git a/tests/filter_logic.rs b/tests/filter_logic.rs index 2180439..59f6df3 100644 --- a/tests/filter_logic.rs +++ b/tests/filter_logic.rs @@ -57,201 +57,3 @@ fn blacklist_remove_clears_ban() { blacklist.remove(ip(7)); assert!(!blacklist.is_blocked(ip(7))); } - -#[test] -fn blacklist_expired_cleanup_keeps_fresh_reban() { - let blacklist = Blacklist::new(); - blacklist.add(ip(8), Duration::ZERO, "stale"); - assert!(!blacklist.is_blocked(ip(8)), "zero-duration ban is already expired"); - - blacklist.add(ip(8), Duration::from_secs(60), "fresh"); - assert!( - blacklist.is_blocked(ip(8)), - "expired-entry cleanup must not delete a fresh ban" - ); - assert_eq!(blacklist.len(), 1); -} - -#[test] -fn blacklist_expired_cleanup_does_not_race_with_reban() { - let blacklist = std::sync::Arc::new(Blacklist::new()); - let reader = blacklist.clone(); - let handle = std::thread::spawn(move || { - for _ in 0..2000 { - let _ = reader.is_blocked(ip(9)); - std::thread::yield_now(); - } - }); - for _ in 0..2000 { - blacklist.add(ip(9), Duration::ZERO, "stale"); - blacklist.add(ip(9), Duration::from_secs(60), "fresh"); - } - handle.join().expect("reader thread must not panic"); - assert!( - blacklist.is_blocked(ip(9)), - "a concurrently refreshed ban must survive stale cleanup" - ); -} - -#[test] -fn blacklist_clamps_huge_durations_without_panicking() { - let blacklist = Blacklist::new(); - blacklist.add(ip(10), Duration::from_secs(u64::MAX), "hostile"); - blacklist.add_redis(ip(11), Duration::from_secs(u64::MAX), "hostile"); - - assert!(blacklist.is_blocked(ip(10)), "local ban must be clamped, not dropped"); - assert!(blacklist.is_blocked(ip(11)), "redis ban must be clamped, not dropped"); -} - -#[test] -fn replace_redis_keeps_new_bans_and_local_entries() { - let blacklist = Blacklist::new(); - blacklist.add(ip(12), Duration::from_secs(60), "local"); - blacklist.add_redis(ip(13), Duration::from_secs(60), "stale-upstream"); - - blacklist.replace_redis([ - (ip(14), Duration::from_secs(60), "upstream".to_string()), - (ip(15), Duration::from_secs(60), "upstream".to_string()), - ]); - - assert!(blacklist.is_blocked(ip(14)), "new upstream ban must apply immediately"); - assert!(blacklist.is_blocked(ip(15)), "new upstream ban must apply immediately"); - assert!(!blacklist.is_blocked(ip(13)), "ban removed upstream must stop applying"); - assert!( - blacklist.is_blocked(ip(12)), - "local bans must survive a Redis reconcile" - ); -} - -#[test] -fn replace_redis_can_clear_every_mirrored_ban() { - let blacklist = Blacklist::new(); - blacklist.add_redis(ip(16), Duration::from_secs(60), "stale-upstream"); - - blacklist.replace_redis(std::iter::empty()); - - assert!(!blacklist.is_blocked(ip(16))); - assert!(blacklist.is_empty()); -} - -fn numbered(index: u32) -> IpAddr { - IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + index)) -} - -#[test] -fn rate_limiter_enforces_a_hard_bucket_cap() { - let limiter = RateLimiter::with_capacity(1.0, 1.0, 4, Duration::from_secs(600)); - let admitted = (0..100).filter(|index| limiter.check(numbered(*index))).count(); - assert_eq!(admitted, 4, "only max_buckets new sources may be admitted"); - assert_eq!(limiter.len(), 4); - assert!( - !limiter.check(numbered(500)), - "a new source fails closed once the table is saturated" - ); - assert_eq!(limiter.len(), 4, "a refused source must not allocate a bucket"); -} - -#[test] -fn rate_limiter_sweep_frees_capacity_and_keeps_active() { - let limiter = RateLimiter::with_capacity(1.0, 10.0, 2, Duration::from_millis(100)); - assert!(limiter.check(ip(1))); - assert!(limiter.check(ip(2))); - std::thread::sleep(Duration::from_millis(200)); - assert!(limiter.check(ip(2)), "the active source still has tokens"); - - for _ in 0..8 { - limiter.sweep(); - } - assert_eq!(limiter.len(), 1, "idle bucket evicted, active bucket kept"); - assert!(limiter.check(ip(3)), "eviction must free a slot for a new source"); -} - -#[test] -fn rate_limiter_sweep_is_incremental() { - let limiter = RateLimiter::with_capacity(1000.0, 1.0, 4096, Duration::from_millis(10)); - for index in 0..4096 { - assert!(limiter.check(numbered(index))); - } - std::thread::sleep(Duration::from_millis(20)); - - let first = limiter.sweep(); - assert!(first > 0, "the first sweep must reclaim idle buckets"); - assert!(first < 4096, "one sweep must not scan the whole table"); - assert!(!limiter.is_empty(), "a single sweep leaves work for the next tick"); - - for _ in 0..8 { - limiter.sweep(); - } - assert!(limiter.is_empty(), "a full shard cycle reclaims every idle bucket"); -} - -#[test] -fn cidr_ban_covers_the_whole_range() { - let blacklist = Blacklist::new(); - blacklist.add_cidr( - IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3)), - 24, - Duration::from_secs(60), - "subnet", - ); - assert!(blacklist.is_blocked(IpAddr::V4(Ipv4Addr::new(10, 1, 2, 1)))); - assert!(blacklist.is_blocked(IpAddr::V4(Ipv4Addr::new(10, 1, 2, 255)))); - assert!(!blacklist.is_blocked(IpAddr::V4(Ipv4Addr::new(10, 1, 3, 1)))); -} - -#[test] -fn cidr_ban_normalises_host_bits_and_v4_mapped_addresses() { - let blacklist = Blacklist::new(); - blacklist.add_cidr( - IpAddr::V4(Ipv4Addr::new(10, 7, 9, 200)), - 24, - Duration::from_secs(60), - "subnet", - ); - let mapped: IpAddr = "::ffff:10.7.9.1".parse().expect("mapped ipv4"); - assert!(blacklist.is_blocked(mapped), "/24 ban must cover the mapped form too"); -} - -#[test] -fn cidr_ban_expires() { - let blacklist = Blacklist::new(); - blacklist.add_cidr( - IpAddr::V4(Ipv4Addr::new(10, 8, 0, 0)), - 16, - Duration::from_millis(1), - "subnet", - ); - std::thread::sleep(Duration::from_millis(5)); - assert!(!blacklist.is_blocked(IpAddr::V4(Ipv4Addr::new(10, 8, 0, 1)))); - blacklist.clear_expired(); - assert!(blacklist.is_empty()); -} - -#[test] -fn invalid_cidr_prefix_is_ignored() { - let blacklist = Blacklist::new(); - blacklist.add_cidr( - IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)), - 0, - Duration::from_secs(60), - "subnet", - ); - blacklist.add_cidr( - IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)), - 33, - Duration::from_secs(60), - "subnet", - ); - assert!(blacklist.is_empty(), "a /0 or /33 ban must not be installed"); -} - -#[test] -fn ipv6_cidr_ban_covers_the_range() { - let blacklist = Blacklist::new(); - let prefix: IpAddr = "fd00:1234:5678:9abc::".parse().expect("ipv6 prefix"); - blacklist.add_cidr(prefix, 64, Duration::from_secs(60), "subnet"); - let inside: IpAddr = "fd00:1234:5678:9abc::42".parse().expect("ipv6 inside"); - let outside: IpAddr = "fd00:1234:5678:9abd::1".parse().expect("ipv6 outside"); - assert!(blacklist.is_blocked(inside)); - assert!(!blacklist.is_blocked(outside)); -} diff --git a/tests/manager_security.rs b/tests/manager_security.rs deleted file mode 100644 index 2d9d3e6..0000000 --- a/tests/manager_security.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! Management-plane security: API password/JWT policy and the CORS downgrade. -//! -//! Regression tests for the authentication bypass where an empty -//! `API_PASSWORD` matched an empty login (`verify_password("", "")`). - -use dashmap::DashMap; -use rampart::manager::api::auth::allow_login_attempt; -use rampart::manager::security::{CorsPolicy, validate_api_password, validate_jwt_secret, verify_password}; -use std::net::IpAddr; - -const STRONG_PASSWORD: &str = "correct-horse-battery-staple"; -const STRONG_SECRET: &str = "0123456789abcdef0123456789abcdef"; - -#[test] -fn rejects_empty_api_password() { - let err = validate_api_password("").expect_err("empty password must be rejected"); - assert!(err.to_string().contains("must not be empty")); -} - -#[test] -fn rejects_whitespace_only_api_password() { - assert!(validate_api_password(" ").is_err()); -} - -#[test] -fn rejects_short_api_password() { - let short = "a".repeat(15); - let err = validate_api_password(&short).expect_err("15 characters must be rejected"); - assert!(err.to_string().contains("at least 16")); - assert!(validate_api_password(&"a".repeat(16)).is_ok()); -} - -#[test] -fn rejects_placeholder_api_password() { - assert!(validate_api_password("changeme").is_err()); - assert!(validate_api_password("ChangeMe").is_err()); - assert!(validate_api_password(" changeme ").is_err()); -} - -#[test] -fn accepts_strong_api_password() { - assert!(validate_api_password(STRONG_PASSWORD).is_ok()); -} - -#[test] -fn empty_stored_password_never_verifies() { - assert!(!verify_password("", "")); - assert!(!verify_password("anything", "")); -} - -#[test] -fn verify_password_matches_exact_value_only() { - assert!(verify_password(STRONG_PASSWORD, STRONG_PASSWORD)); - assert!(!verify_password("wrong-password", STRONG_PASSWORD)); - assert!(!verify_password("short", STRONG_PASSWORD)); -} - -#[test] -fn rejects_empty_or_short_jwt_secret() { - assert!(validate_jwt_secret("").is_err()); - assert!(validate_jwt_secret(&" ".repeat(64)).is_err()); - assert!(validate_jwt_secret(&"a".repeat(31)).is_err()); - let err = validate_jwt_secret(" \t\n").expect_err("whitespace must be rejected"); - assert!(err.to_string().contains("non-whitespace")); -} - -#[test] -fn accepts_strong_jwt_secret() { - assert!(validate_jwt_secret(STRONG_SECRET).is_ok()); - assert!(validate_jwt_secret(&format!(" {STRONG_SECRET} ")).is_ok()); -} - -#[test] -fn cors_without_explicit_origin_is_denied() { - assert_eq!(CorsPolicy::parse(None).expect("unset is valid"), CorsPolicy::Deny); - assert_eq!(CorsPolicy::parse(Some("")).expect("empty is valid"), CorsPolicy::Deny); - assert_eq!( - CorsPolicy::parse(Some(" ")).expect("blank is valid"), - CorsPolicy::Deny - ); - assert!(CorsPolicy::Deny.cors_layer().is_none()); -} - -#[test] -fn cors_wildcard_requires_explicit_flag() { - assert_eq!( - CorsPolicy::parse(Some("*")).expect("wildcard is valid"), - CorsPolicy::Any - ); - assert!(CorsPolicy::Any.cors_layer().is_some()); -} - -#[test] -fn cors_origin_list_is_trimmed() { - let policy = CorsPolicy::parse(Some("https://a.example, https://b.example")).expect("list must parse"); - assert_eq!( - policy, - CorsPolicy::AllowList(vec!["https://a.example".to_owned(), "https://b.example".to_owned()]) - ); - assert!(policy.cors_layer().is_some()); -} - -#[test] -fn cors_rejects_empty_entries_and_mixed_wildcard() { - assert!(CorsPolicy::parse(Some("https://a.example,")).is_err()); - assert!(CorsPolicy::parse(Some("https://a.example,*")).is_err()); -} - -#[test] -fn cors_rejects_invalid_header_value() { - // A newline inside an origin is a header-injection attempt, not a valid value. - assert!(CorsPolicy::parse(Some("https://evil.example\nSet-Cookie: x")).is_err()); - assert!(CorsPolicy::parse(Some("https://evil.example/\u{7f}")).is_err()); -} - -#[test] -fn login_limiter_blocks_after_five_attempts() { - let limiter = DashMap::new(); - let ip = IpAddr::from([127, 0, 0, 1]); - for _ in 0..5 { - assert!(allow_login_attempt(&limiter, ip)); - } - assert!(!allow_login_attempt(&limiter, ip)); -} diff --git a/tests/pow_difficulty.rs b/tests/pow_difficulty.rs deleted file mode 100644 index 78d06db..0000000 --- a/tests/pow_difficulty.rs +++ /dev/null @@ -1,80 +0,0 @@ -//! Adaptive PoW difficulty: configured floor, range clamping and the rate -//! ladder. The adjuster lives in `src/engine/challenge/difficulty.rs`; these -//! tests are the only consumer of the range constants. - -use rampart::engine::challenge::{DifficultyAdjuster, MAX_DIFFICULTY, MIN_DIFFICULTY}; - -#[test] -fn idle_uses_the_configured_floor() { - let adjuster = DifficultyAdjuster::new(4, 10); - assert_eq!(adjuster.current_difficulty(), 4); -} - -#[test] -fn configured_pow_difficulty_is_the_starting_point() { - // `[pow].difficulty = 7` must not be ignored until the first connection. - assert_eq!(DifficultyAdjuster::with_floor(7).current_difficulty(), 7); -} - -#[test] -fn configured_floor_can_be_lower_than_the_old_hardcoded_minimum() { - assert_eq!(DifficultyAdjuster::with_floor(2).current_difficulty(), 2); -} - -#[test] -fn configured_floor_is_clamped_to_the_supported_range() { - assert_eq!(DifficultyAdjuster::with_floor(0).current_difficulty(), MIN_DIFFICULTY); - assert_eq!(DifficultyAdjuster::with_floor(250).current_difficulty(), MAX_DIFFICULTY); -} - -#[test] -fn inverted_range_is_swapped_instead_of_breaking_the_clamp() { - let mut adjuster = DifficultyAdjuster::new(9, 5); - assert_eq!(adjuster.current_difficulty(), 5, "lower end is the starting point"); - for _ in 0..600 { - adjuster.record_connection(); - } - assert_eq!( - adjuster.current_difficulty(), - 9, - "under load the swapped upper end applies" - ); -} - -#[test] -fn pinned_range_never_moves() { - let mut adjuster = DifficultyAdjuster::new(6, 6); - for _ in 0..600 { - adjuster.record_connection(); - } - assert_eq!(adjuster.current_difficulty(), 6); -} - -#[test] -fn rate_ladder_is_clamped_to_the_configured_range() { - let mut adjuster = DifficultyAdjuster::new(7, 8); - for _ in 0..60 { - adjuster.record_connection(); - } - // Raw ladder step is 6, below the configured floor. - assert_eq!(adjuster.current_difficulty(), 7); - for _ in 60..201 { - adjuster.record_connection(); - } - // Raw ladder step is 8 and fits the range. - assert_eq!(adjuster.current_difficulty(), 8); - for _ in 201..600 { - adjuster.record_connection(); - } - // Raw ladder step is MAX_DIFFICULTY, above the configured ceiling. - assert_eq!(adjuster.current_difficulty(), 8); -} - -#[test] -fn default_range_rises_to_ten_under_load() { - let mut adjuster = DifficultyAdjuster::default(); - for _ in 0..600 { - adjuster.record_connection(); - } - assert_eq!(adjuster.current_difficulty(), 10); -} diff --git a/tests/pow_roundtrip.rs b/tests/pow_roundtrip.rs index 7c3e9d0..ba7a660 100644 --- a/tests/pow_roundtrip.rs +++ b/tests/pow_roundtrip.rs @@ -1,11 +1,7 @@ //! PoW roundtrip tests: solver output must satisfy the verifier, replays and -//! garbage must not, and the nonce exchange must survive TCP framing quirks. +//! garbage must not. -use rampart::engine::challenge::{Challenge, enforce, solve}; -use std::net::IpAddr; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::net::{TcpListener, TcpStream}; -use tokio::time::{Duration, sleep}; +use rampart::engine::challenge::{Challenge, solve}; /// Fixed 32-byte token: sha256(hex(token) || "garbage") starts with "ebc1", /// so "garbage" provably fails the difficulty-2 check (first two hex chars @@ -13,8 +9,6 @@ use tokio::time::{Duration, sleep}; /// per run, since any digest lands in the accepted prefix with p=(4/16)^2. const FIXED_TOKEN: [u8; 32] = *b"rampart-pow-fixed-token-test-v1!"; -const PEER: IpAddr = IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 1)); - #[test] fn solver_output_passes_verifier() { let mut challenge = Challenge::generate(3); @@ -31,104 +25,3 @@ fn verifier_rejects_garbage_and_replay() { assert!(challenge.verify(&nonce), "first use passes"); assert!(!challenge.verify(&nonce), "replay is rejected"); } - -#[test] -fn verifier_rejects_oversized_nonce() { - let mut challenge = Challenge::with_token(FIXED_TOKEN, 2); - let big_nonce = "0".repeat(65); - assert!(!challenge.verify(&big_nonce)); -} - -/// Connects a server/client loopback pair; the first value is the server side. -async fn pair() -> (TcpStream, TcpStream) { - let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind loopback"); - let addr = listener.local_addr().expect("local address"); - let accept = tokio::spawn(async move { listener.accept().await.expect("accept").0 }); - let client = TcpStream::connect(addr).await.expect("connect loopback"); - let server = accept.await.expect("accept task"); - (server, client) -} - -/// Reads one newline-terminated server line byte by byte. -async fn read_line(stream: &mut TcpStream) -> String { - let mut line = Vec::new(); - loop { - let mut byte = [0u8; 1]; - let n = stream.read(&mut byte).await.expect("read line"); - if n == 0 || byte[0] == b'\n' { - break; - } - line.push(byte[0]); - } - String::from_utf8(line).expect("challenge is hex") -} - -#[tokio::test] -async fn nonce_coalesced_with_handshake_is_preserved() { - let (mut server, mut client) = pair().await; - let server_task = tokio::spawn(async move { - let passed = enforce(&mut server, PEER, 2).await.expect("enforce"); - let mut tail = [0u8; 5]; - server - .read_exact(&mut tail) - .await - .expect("handshake bytes after the nonce"); - (passed, tail) - }); - - let challenge = read_line(&mut client).await; - let nonce = solve(&challenge, 2).expect("solved"); - // One write: nonce delimiter and the first handshake bytes in one segment. - client - .write_all(format!("{nonce}\nHELLO").as_bytes()) - .await - .expect("write nonce and handshake"); - let (passed, tail) = server_task.await.expect("server task"); - assert!(passed); - assert_eq!(&tail, b"HELLO", "bytes after the delimiter must reach the handshake"); -} - -#[tokio::test] -async fn nonce_split_across_segments_is_accepted() { - let (mut server, mut client) = pair().await; - let server_task = tokio::spawn(async move { enforce(&mut server, PEER, 2).await.expect("enforce") }); - - let challenge = read_line(&mut client).await; - let nonce = solve(&challenge, 2).expect("solved"); - let split = nonce.len() / 2; - client - .write_all(&nonce.as_bytes()[..split]) - .await - .expect("first segment"); - sleep(Duration::from_millis(20)).await; - client - .write_all(&nonce.as_bytes()[split..]) - .await - .expect("second segment"); - client.write_all(b"\n").await.expect("delimiter"); - - assert!(server_task.await.expect("server task")); -} - -#[tokio::test] -async fn eof_terminated_nonce_is_still_accepted() { - let (mut server, mut client) = pair().await; - let server_task = tokio::spawn(async move { enforce(&mut server, PEER, 2).await.expect("enforce") }); - - let challenge = read_line(&mut client).await; - let nonce = solve(&challenge, 2).expect("solved"); - client.write_all(nonce.as_bytes()).await.expect("write nonce"); - client.shutdown().await.expect("close write half"); - - assert!(server_task.await.expect("server task")); -} - -#[tokio::test] -async fn oversized_nonce_without_delimiter_is_rejected() { - let (mut server, mut client) = pair().await; - let server_task = tokio::spawn(async move { enforce(&mut server, PEER, 2).await.expect("enforce") }); - - let _challenge = read_line(&mut client).await; - client.write_all(&[b'0'; 65]).await.expect("oversized nonce"); - assert!(!server_task.await.expect("server task")); -} diff --git a/tests/redis_backoff.rs b/tests/redis_backoff.rs deleted file mode 100644 index 5e03f77..0000000 --- a/tests/redis_backoff.rs +++ /dev/null @@ -1,25 +0,0 @@ -//! Integration tests for the Redis reconnect backoff policy. - -// The backoff helpers live behind the optional `store-redis` feature, so this -// test target must be skipped when that feature is off (`cargo check -// --no-default-features --all-targets`, CI protocol-http job). -#![cfg(feature = "store-redis")] - -use std::time::Duration; - -use rampart::store::redis::{BACKOFF_MAX, BACKOFF_MIN, next_backoff}; - -#[test] -fn backoff_doubles_until_cap() { - let mut backoff = BACKOFF_MIN; - for expected_secs in [2, 4, 8, 16, 30, 30] { - backoff = next_backoff(backoff, BACKOFF_MAX); - assert_eq!(backoff, Duration::from_secs(expected_secs)); - } -} - -#[test] -fn backoff_never_exceeds_max() { - let backoff = next_backoff(Duration::from_secs(u64::MAX / 2), BACKOFF_MAX); - assert!(backoff <= BACKOFF_MAX); -} diff --git a/tests/subnet_detection.rs b/tests/subnet_detection.rs index e635118..64b373a 100644 --- a/tests/subnet_detection.rs +++ b/tests/subnet_detection.rs @@ -1,16 +1,12 @@ //! Integration tests for subnet-level detection: tracker, detector and verdicts. use rampart::config::Config; -use rampart::engine::subnet::monitor::enforce_tracker_verdicts; use rampart::engine::subnet_tracker::SubnetTracker; -use rampart::filter::blacklist::Blacklist; use rampart::traffic::prefix::{ - PrefixKey, PrefixSnapshot, PrefixStatsSource, PrefixStatsVal, PrefixVerdict, SubnetDetector, SubnetVerdict, - prefix_of, + PrefixKey, PrefixSnapshot, PrefixStatsSource, PrefixStatsVal, SubnetDetector, SubnetVerdict, prefix_of, }; use std::collections::HashMap; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -use std::time::Duration; fn v4(octets: [u8; 4]) -> IpAddr { IpAddr::V4(Ipv4Addr::from(octets)) @@ -198,145 +194,6 @@ fn spoof_gate_downgrades_block_to_challenge() { assert_eq!(verdict_for(&detector, &unknown), SubnetVerdict::Challenge); } -#[test] -fn tracker_groups_connections_by_prefix() { - let tracker = SubnetTracker::new(); - tracker.record_connection(v4([203, 0, 113, 1])); - tracker.record_connection(v4([203, 0, 113, 2])); - tracker.record_connection(v4([198, 51, 100, 9])); - let by_prefix: HashMap = tracker.take_snapshot().into_iter().collect(); - assert_eq!(by_prefix.len(), 2); - assert_eq!(by_prefix[&v4([203, 0, 113, 0])].syn_count, 2); - assert_eq!(by_prefix[&v4([203, 0, 113, 0])].unique_sources, 2); - assert_eq!(by_prefix[&v4([198, 51, 100, 0])].syn_count, 1); -} - -#[test] -fn tracker_snapshot_drains_window() { - let tracker = SubnetTracker::new(); - tracker.record_connection(v4([10, 0, 0, 1])); - assert_eq!(tracker.take_snapshot().len(), 1); - assert!(tracker.take_snapshot().is_empty()); -} - -#[test] -fn tracker_mapped_addresses_share_v4_prefix() { - let tracker = SubnetTracker::new(); - tracker.record_connection(v4([203, 0, 113, 5])); - // ::ffff:203.0.113.6 - let mapped = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xcb00, 0x7106); - tracker.record_connection(IpAddr::V6(mapped)); - let snaps = tracker.take_snapshot(); - assert_eq!(snaps.len(), 1); - assert_eq!(snaps[0].0, v4([203, 0, 113, 0])); - assert_eq!(snaps[0].1.unique_sources, 2); -} - -#[test] -fn tracker_prefix_cap_drops_new_prefixes_and_counts_them() { - let tracker = SubnetTracker::with_limits(2, 8); - tracker.record_connection(v4([10, 0, 0, 1])); - tracker.record_connection(v4([10, 0, 1, 1])); - tracker.record_connection(v4([10, 0, 2, 1])); - assert_eq!(tracker.dropped_prefixes(), 1); - // Existing prefixes keep accumulating even while the table is full. - tracker.record_connection(v4([10, 0, 0, 2])); - - let snaps: HashMap = tracker.take_snapshot().into_iter().collect(); - assert_eq!(snaps.len(), 2); - assert_eq!(snaps[&v4([10, 0, 0, 0])].syn_count, 2); - assert!( - !snaps.contains_key(&v4([10, 0, 2, 0])), - "over-cap prefix was not stored" - ); -} - -#[test] -fn tracker_source_cap_bounds_per_prefix_memory() { - let tracker = SubnetTracker::with_limits(8, 3); - for last in 1..=100u8 { - tracker.record_connection(v4([203, 0, 113, last])); - } - assert_eq!( - tracker.dropped_sources(), - 97, - "only the first three distinct sources are stored" - ); - - let snaps = tracker.take_snapshot(); - assert_eq!(snaps.len(), 1); - assert_eq!(snaps[0].1.syn_count, 100, "the aggregate counter is not capped"); - assert_eq!(snaps[0].1.unique_sources, 3); -} - -#[test] -fn tracker_source_cap_counts_only_new_addresses() { - let tracker = SubnetTracker::with_limits(1, 2); - tracker.record_connection(v4([198, 51, 100, 1])); - tracker.record_connection(v4([198, 51, 100, 2])); - tracker.record_connection(v4([198, 51, 100, 3])); - assert_eq!(tracker.dropped_sources(), 1); - // Repeated traffic from a remembered source is not a dropped new source. - tracker.record_connection(v4([198, 51, 100, 1])); - assert_eq!(tracker.dropped_sources(), 1); - tracker.record_connection(v4([198, 51, 100, 4])); - assert_eq!(tracker.dropped_sources(), 2); -} - -fn block_verdict(prefix: IpAddr) -> PrefixVerdict { - PrefixVerdict { - prefix, - verdict: SubnetVerdict::Block, - snapshot: PrefixSnapshot { - syn_count: 4000, - unique_sources: 64, - ..PrefixSnapshot::default() - }, - } -} - -#[test] -fn trusted_tracker_block_reaches_the_blacklist_with_the_configured_ttl() { - let blacklist = Blacklist::new(); - let verdicts = [block_verdict(v4([203, 0, 113, 0]))]; - let banned = enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_secs(120), true); - assert_eq!(banned, 1); - assert!(blacklist.is_blocked(v4([203, 0, 113, 0]))); -} - -#[test] -fn untrusted_tracker_block_only_warns() { - let blacklist = Blacklist::new(); - let verdicts = [block_verdict(v4([198, 51, 100, 0]))]; - let banned = enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_secs(120), false); - assert_eq!(banned, 0); - assert!(blacklist.is_empty()); -} - -#[test] -fn tracker_ban_uses_the_given_duration() { - let blacklist = Blacklist::new(); - let verdicts = [block_verdict(v4([192, 0, 2, 0]))]; - enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_millis(1), true); - std::thread::sleep(Duration::from_millis(2)); - assert!( - !blacklist.is_blocked(v4([192, 0, 2, 0])), - "ban must expire with its TTL" - ); -} - -#[test] -fn non_block_verdicts_do_not_ban() { - let blacklist = Blacklist::new(); - let mut verdict = block_verdict(v4([203, 0, 113, 0])); - verdict.verdict = SubnetVerdict::Challenge; - assert_eq!( - enforce_tracker_verdicts(&[verdict], &blacklist, Duration::from_secs(60), true), - 0 - ); - assert!(blacklist.is_empty()); -} - #[test] fn evaluate_skips_empty_prefixes() { let detector = SubnetDetector::new(100, 0); @@ -356,22 +213,3 @@ fn evaluate_skips_empty_prefixes() { assert_eq!(verdicts[0].prefix, v4([10, 0, 1, 0])); assert_eq!(verdicts[0].verdict, SubnetVerdict::Block); } - -#[test] -fn prefix_key_normalises_ipv4_mapped_addresses() { - // ::ffff:1.2.3.4 - let mapped = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x0102, 0x0304)); - let plain = v4([1, 2, 3, 4]); - - assert_eq!( - PrefixKey::new(mapped), - PrefixKey::new(plain), - "a mapped client must produce one key in XDP prefix stats and the user-space tracker" - ); - assert_eq!( - PrefixKey::new(mapped).family, - rampart::traffic::prefix::PREFIX_FAMILY_V4 - ); - assert_eq!(PrefixKey::new(mapped).to_prefix(), Some(prefix_of(mapped))); - assert_eq!(PrefixKey::new(mapped).to_prefix(), Some(v4([1, 2, 3, 0]))); -} diff --git a/tests/traffic_intel.rs b/tests/traffic_intel.rs index 7f73248..1156bcb 100644 --- a/tests/traffic_intel.rs +++ b/tests/traffic_intel.rs @@ -1,15 +1,14 @@ -//! Integration tests for Traffic Intelligence on the hot path: EWMA sanity, -//! attack detection across a sustained flood, reputation decay/eviction and -//! auto-ban driven by reputation. +//! Integration tests for Traffic Intelligence on the hot path: auto-ban driven +//! by reputation, attack detection on a synthetic spike and alerts on state +//! transitions. use rampart::config::DetectAutobanConfig; use rampart::filter::blacklist::Blacklist; use rampart::traffic::alert::AlertDispatcher; -use rampart::traffic::detector::{AttackDetector, AttackStatus, DetectorThresholds}; -use rampart::traffic::ewma::Ewma; +use rampart::traffic::detector::{AttackDetector, AttackStatus}; use rampart::traffic::hook::TrafficHook; -use rampart::traffic::reputation::{IpReputation, ReputationPolicy}; -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +use rampart::traffic::reputation::IpReputation; +use std::net::{IpAddr, Ipv4Addr}; use std::sync::Arc; use std::time::Duration; @@ -24,363 +23,6 @@ fn autoban_cfg(enabled: bool) -> DetectAutobanConfig { } } -fn quiet(detector: &mut AttackDetector) { - for _ in 0..12 { - detector.analyze(500.0, 50.0); - } -} - -// EWMA - -#[test] -fn ewma_starts_at_zero() { - assert_eq!(Ewma::new(0.125).value(), 0.0); -} - -#[test] -fn ewma_alpha_one_follows_the_sample() { - let mut ewma = Ewma::new(1.0); - ewma.update(100.0); - assert!((ewma.value() - 100.0).abs() < 1.0); -} - -#[test] -fn ewma_converges_to_a_constant_sample() { - let mut ewma = Ewma::new(0.5); - for _ in 0..10 { - ewma.update(50.0); - } - assert!((ewma.value() - 50.0).abs() < 1.0); -} - -#[test] -fn ewma_falls_back_on_invalid_alpha() { - for alpha in [f64::NAN, f64::INFINITY, 0.0, -0.5] { - let mut ewma = Ewma::new(alpha); - ewma.update(100.0); - assert!(ewma.value().is_finite(), "alpha={alpha} must keep the average finite"); - assert!( - ewma.value() > 0.0 && ewma.value() < 100.0, - "alpha={alpha} must fall back to the default smoothing" - ); - } -} - -#[test] -fn ewma_seed_primes_the_baseline() { - let mut ewma = Ewma::new(0.01); - ewma.seed(500.0); - assert_eq!(ewma.value(), 500.0, "a seeded baseline starts at the observed value"); - ewma.update(500.0); - assert_eq!(ewma.value(), 500.0); - assert!(!ewma.value().is_nan()); -} - -#[test] -fn ewma_ignores_non_finite_samples() { - let mut ewma = Ewma::new(0.5); - ewma.update(10.0); - let before = ewma.value(); - ewma.update(f64::NAN); - ewma.update(f64::INFINITY); - assert_eq!(ewma.value(), before, "non-finite samples must not move the average"); -} - -// Attack detector - -#[test] -fn attack_detector_reports_normal_traffic() { - let mut detector = AttackDetector::new(); - quiet(&mut detector); - assert_eq!(detector.analyze(500.0, 50.0), AttackStatus::Normal); -} - -#[test] -fn attack_detector_flags_pps_spike_as_suspicious() { - let mut detector = AttackDetector::new(); - for _ in 0..10 { - detector.analyze(1.0, 1.0); - } - assert_eq!(detector.analyze(5.0, 1.0), AttackStatus::Suspicious); -} - -#[test] -fn attack_detector_flags_cps_spike_as_suspicious() { - let mut detector = AttackDetector::new(); - for _ in 0..10 { - detector.analyze(1.0, 1.0); - } - assert_eq!(detector.analyze(1.0, 5.0), AttackStatus::Suspicious); -} - -#[test] -fn attack_detector_escalates_after_three_anomalies() { - let mut detector = AttackDetector::new(); - for _ in 0..10 { - detector.analyze(1.0, 1.0); - } - detector.analyze(10_000.0, 100.0); - detector.analyze(10_000.0, 100.0); - assert_eq!(detector.analyze(10_000.0, 100.0), AttackStatus::UnderAttack); -} - -#[test] -fn attack_detector_resets_on_a_normal_window() { - let mut detector = AttackDetector::new(); - for _ in 0..10 { - detector.analyze(1.0, 1.0); - } - detector.analyze(100.0, 10.0); - detector.analyze(100.0, 10.0); - detector.analyze(1.0, 1.0); - assert_eq!(detector.analyze(1.0, 1.0), AttackStatus::Normal); -} - -#[test] -fn detector_flags_synthetic_traffic_spike() { - let mut detector = AttackDetector::new(); - - // Baseline: a quiet profile. - for _ in 0..12 { - detector.analyze(500.0, 50.0); - } - - // Synthetic spike: 200x pps and cps for three consecutive windows. - assert_eq!( - detector.analyze(100_000.0, 10_000.0), - AttackStatus::Suspicious, - "first anomalous window is suspicious" - ); - assert_eq!(detector.analyze(100_000.0, 10_000.0), AttackStatus::Suspicious); - assert_eq!( - detector.analyze(100_000.0, 10_000.0), - AttackStatus::UnderAttack, - "three anomalous windows in a row must escalate to UnderAttack" - ); -} - -#[test] -fn sustained_flood_stays_under_attack_and_keeps_banning_offenders() { - let reputation = Arc::new(IpReputation::new()); - let blacklist = Arc::new(Blacklist::new()); - let hook = TrafficHook::new(Arc::clone(&reputation), Arc::clone(&blacklist), autoban_cfg(true), 60); - let mut detector = AttackDetector::new(); - quiet(&mut detector); - - for tick in 0..10u8 { - let status = detector.analyze(100_000.0, 10_000.0); - if tick < 2 { - assert_eq!(status, AttackStatus::Suspicious, "flood tick {tick}"); - } else { - assert_eq!( - status, - AttackStatus::UnderAttack, - "flood tick {tick}: the detector must not learn the attack as normal" - ); - } - - // A fresh offender joins on every tick of the attack. The edge keeps - // banning them only while the detector stays in UnderAttack. - let offender = ip([203, 0, 113, tick + 1]); - for _ in 0..6 { - reputation.record_bad(offender); - } - assert!(hook.ban_offenders() >= 1, "flood tick {tick} must produce a ban"); - assert!( - blacklist.is_blocked(offender), - "flood tick {tick}: offender must be banned" - ); - } -} - -#[test] -fn under_attack_exits_only_after_the_recovery_window() { - let mut detector = AttackDetector::new(); - quiet(&mut detector); - for _ in 0..3 { - detector.analyze(100_000.0, 10_000.0); - } - assert_eq!(detector.analyze(100_000.0, 10_000.0), AttackStatus::UnderAttack); - - // Four calm windows are not enough: the exit hysteresis is five ticks. - for tick in 0..4 { - assert_eq!( - detector.analyze(500.0, 50.0), - AttackStatus::UnderAttack, - "calm tick {tick} must not end the attack" - ); - } - assert_eq!( - detector.analyze(500.0, 50.0), - AttackStatus::Normal, - "the fifth calm tick ends the attack" - ); -} - -#[test] -fn detector_thresholds_are_configurable() { - let thresholds = DetectorThresholds { - suspicious_score: 1.5, - attack_score: 2.0, - escalate_after: 1, - recover_after: 2, - }; - let mut detector = AttackDetector::with_thresholds(thresholds); - for _ in 0..10 { - detector.analyze(100.0, 10.0); - } - assert_eq!( - detector.analyze(1_000.0, 100.0), - AttackStatus::UnderAttack, - "escalate_after = 1 must escalate on the first anomalous window" - ); - assert_eq!(detector.analyze(100.0, 10.0), AttackStatus::UnderAttack); - assert_ne!( - detector.analyze(100.0, 10.0), - AttackStatus::UnderAttack, - "recover_after = 2 must end the attack" - ); -} - -// Reputation - -#[test] -fn reputation_initial_score_is_neutral() { - let rep = IpReputation::new(); - assert_eq!(rep.score(ip([192, 168, 1, 1])), 0); -} - -#[test] -fn reputation_good_and_bad_steps() { - let rep = IpReputation::new(); - let good = ip([10, 0, 0, 1]); - let bad = ip([10, 0, 0, 2]); - rep.record_good(good); - rep.record_bad(bad); - assert_eq!(rep.score(good), 1); - assert_eq!(rep.score(bad), -10); -} - -#[test] -fn reputation_scores_are_clamped() { - let rep = IpReputation::new(); - let good = ip([10, 0, 0, 3]); - let bad = ip([10, 0, 0, 4]); - for _ in 0..200 { - rep.record_good(good); - } - for _ in 0..20 { - rep.record_bad(bad); - } - assert_eq!(rep.score(good), 100); - assert_eq!(rep.score(bad), -100); -} - -#[test] -fn reputation_trusts_after_enough_good_connections() { - let rep = IpReputation::new(); - let ip = ip([10, 0, 0, 5]); - assert!(!rep.is_trusted(ip)); - for _ in 0..51 { - rep.record_good(ip); - } - assert!(rep.is_trusted(ip)); -} - -#[test] -fn reputation_tracks_ipv6() { - let rep = IpReputation::new(); - let ip = IpAddr::V6(Ipv6Addr::LOCALHOST); - rep.record_bad(ip); - assert_eq!(rep.score(ip), -10); -} - -#[test] -fn reputation_decays_toward_neutral() { - let policy = ReputationPolicy { - idle_ttl: Duration::from_secs(10), - decay_half_life: Duration::from_millis(20), - max_offenders: 64, - }; - let rep = IpReputation::with_policy(policy); - let bad = ip([10, 0, 0, 6]); - for _ in 0..20 { - rep.record_bad(bad); - } - assert_eq!(rep.score(bad), -100); - std::thread::sleep(Duration::from_millis(40)); - let decayed = rep.score(bad); - assert!( - decayed > -100 && decayed < 0, - "two half-lives must move the score toward neutral, got {decayed}" - ); -} - -#[test] -fn reputation_sweep_evicts_idle_and_keeps_active() { - let policy = ReputationPolicy { - idle_ttl: Duration::from_millis(20), - decay_half_life: Duration::from_secs(1800), - max_offenders: 64, - }; - let rep = IpReputation::with_policy(policy); - let idle = ip([10, 0, 0, 7]); - let active = ip([10, 0, 0, 8]); - rep.record_bad(idle); - rep.record_bad(active); - - std::thread::sleep(Duration::from_millis(40)); - rep.record_bad(active); - for _ in 0..8 { - rep.sweep(); - } - - assert_eq!(rep.len(), 1, "only the idle source may be evicted"); - assert_eq!(rep.score(idle), 0, "evicted source is neutral again"); - assert!(rep.score(active) < 0, "active source keeps its score"); -} - -#[test] -fn offenders_are_capped_per_cycle() { - let policy = ReputationPolicy { - idle_ttl: Duration::from_secs(600), - decay_half_life: Duration::from_secs(1800), - max_offenders: 3, - }; - let rep = IpReputation::with_policy(policy); - for last in 1..=20u8 { - let source = ip([198, 51, 100, last]); - for _ in 0..6 { - rep.record_bad(source); - } - } - assert_eq!( - rep.offenders_below(-50).len(), - 3, - "one cycle must not return the whole offender table" - ); -} - -#[test] -fn offenders_below_returns_worst_sources() { - let rep = IpReputation::new(); - let bad = ip([10, 0, 0, 1]); - let good = ip([10, 0, 0, 2]); - for _ in 0..6 { - rep.record_bad(bad); - } - rep.record_good(good); - assert_eq!(rep.offenders_below(-50), vec![bad]); -} - -#[test] -fn offenders_below_is_empty_without_offenders() { - let rep = IpReputation::new(); - assert!(rep.offenders_below(-50).is_empty()); -} - -// Traffic hook auto-ban - #[test] fn reputation_fall_after_drops_triggers_autoban() { let reputation = Arc::new(IpReputation::new()); @@ -427,6 +69,29 @@ fn autoban_ttl_expires_ban() { ); } +#[test] +fn detector_flags_synthetic_traffic_spike() { + let mut detector = AttackDetector::new(); + + // Baseline: a quiet profile. + for _ in 0..12 { + detector.analyze(500.0, 50.0); + } + + // Synthetic spike: 200x pps and cps for three consecutive windows. + assert_eq!( + detector.analyze(100_000.0, 10_000.0), + AttackStatus::Suspicious, + "first anomalous window is suspicious" + ); + assert_eq!(detector.analyze(100_000.0, 10_000.0), AttackStatus::Suspicious); + assert_eq!( + detector.analyze(100_000.0, 10_000.0), + AttackStatus::UnderAttack, + "three anomalous windows in a row must escalate to UnderAttack" + ); +} + #[test] fn alerts_fire_only_on_state_transitions() { let dispatcher = AlertDispatcher::new(); diff --git a/tests/xdp_attach_smoke.rs b/tests/xdp_attach_smoke.rs deleted file mode 100644 index e7cd873..0000000 --- a/tests/xdp_attach_smoke.rs +++ /dev/null @@ -1,72 +0,0 @@ -//! Opt-in live attach check for the XDP loader. -//! -//! Ignored by default: it needs root (CAP_BPF/CAP_NET_ADMIN) and a disposable -//! interface, best inside a throwaway network namespace. Run it through -//! `/tmp/opencode/loaderchk.sh` (creates a veth pair in a netns) or manually: -//! -//! ```text -//! sudo ip netns exec env RAMPART_XDP_TEST_IFACE=veth-test \ -//! target/debug/deps/xdp_attach_smoke- --ignored --nocapture -//! ``` -//! -//! It covers the regressions this suite is about: the attach mode is -//! remembered for detach (a generic-mode attach must not leave an orphaned -//! filter behind), whitelist entries load into both LPM tries, a live ban -//! survives the reaper, an expired prefix ban is reaped, and `unload` reports -//! a clean interface. -#![cfg(feature = "xdp")] - -use std::net::IpAddr; - -use rampart::xdp::XdpFilter; - -fn ip(text: &str) -> IpAddr { - text.parse().expect("test literal must be a valid address") -} - -#[test] -#[ignore = "needs root/CAP_NET_ADMIN and a disposable interface in a network namespace"] -fn attach_ban_whitelist_reap_and_detach() { - let interface = std::env::var("RAMPART_XDP_TEST_IFACE") - .expect("set RAMPART_XDP_TEST_IFACE to a disposable interface (inside a netns)"); - - let mut filter = XdpFilter::new(&interface); - filter.load().expect("XDP load and attach must succeed"); - - filter - .whitelist_add(ip("192.0.2.7")) - .expect("IPv4 whitelist entry must load into whitelist_map"); - filter - .whitelist_add(ip("2001:db8::7")) - .expect("IPv6 whitelist entry must load into whitelist6_map"); - - // A live prefix ban must not be removed by the periodic reaper. - filter - .ban_cidr(ip("10.1.2.3"), 24, 600) - .expect("CIDR ban must be accepted"); - assert_eq!( - filter.reap_expired_bans().expect("reaper must run"), - 0, - "a ban that expires in 10 minutes must survive the reaper" - ); - - // A zero-duration ban is already expired on the monotonic clock. - filter - .ban_cidr(ip("10.9.8.7"), 24, 0) - .expect("zero-duration ban must be accepted"); - assert!( - filter.reap_expired_bans().expect("reaper must run") >= 1, - "the expired prefix ban must be removed" - ); - - // unload() uses the remembered attach flags and verifies mode NONE. - filter - .unload() - .expect("detach must succeed and leave the interface clean"); - drop(filter); - - // A second attach proves no orphaned program remained on the interface. - let mut again = XdpFilter::new(&interface); - again.load().expect("re-attach on the same interface must succeed"); - again.unload().expect("second detach must succeed"); -} diff --git a/tests/xdp_ban_keys.rs b/tests/xdp_ban_keys.rs deleted file mode 100644 index ef42858..0000000 --- a/tests/xdp_ban_keys.rs +++ /dev/null @@ -1,100 +0,0 @@ -//! Ban-key encoding for the IPv4 LPM trie and CIDR normalization. -//! -//! No kernel needed: these exercise the pure functions the loader uses before -//! touching `blacklist_map`. Regression class: two bans of the same /24 with -//! different host bits used to produce distinct LPM keys, and a prefix length -//! of 0 or above the address width was accepted silently. -#![cfg(feature = "xdp")] - -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; - -use rampart::xdp::{blacklist_expiry_ns, blacklist_key, normalize_cidr}; - -#[test] -fn blacklist_key_puts_prefix_len_first_and_octets_last() { - assert_eq!(blacklist_key(24, &[10, 0, 1, 200]), [24, 0, 0, 0, 10, 0, 1, 200]); - assert_eq!(blacklist_key(32, &[127, 0, 0, 1]), [32, 0, 0, 0, 127, 0, 0, 1]); -} - -#[test] -fn blacklist_key_encodes_prefix_len_as_little_endian_u32() { - let key = blacklist_key(8, &[10, 1, 2, 3]); - assert_eq!(u32::from_le_bytes(key[0..4].try_into().expect("4 bytes")), 8); -} - -#[test] -fn blacklist_expiry_converts_secs_to_ns() { - assert_eq!(blacklist_expiry_ns(1_000, 2), 1_000 + 2_000_000_000); -} - -#[test] -fn blacklist_expiry_saturates_instead_of_wrapping() { - assert_eq!(blacklist_expiry_ns(u64::MAX, 1), u64::MAX); - assert_eq!(blacklist_expiry_ns(0, u64::MAX), u64::MAX); -} - -#[test] -fn normalize_cidr_masks_host_bits_for_a_slash_24() { - let net = normalize_cidr(IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3)), 24).expect("valid /24"); - assert_eq!(net, IpAddr::V4(Ipv4Addr::new(10, 1, 2, 0))); -} - -#[test] -fn without_masking_host_bits_would_produce_different_ban_keys() { - // This is the regression: these two keys denote the same /24 but differ. - assert_ne!(blacklist_key(24, &[10, 1, 2, 3]), blacklist_key(24, &[10, 1, 2, 0])); -} - -#[test] -fn a_whole_subnet_shares_one_ban_key_after_normalization() { - let first = normalize_cidr(IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3)), 24).expect("valid /24"); - let second = normalize_cidr(IpAddr::V4(Ipv4Addr::new(10, 1, 2, 99)), 24).expect("valid /24"); - let (IpAddr::V4(first), IpAddr::V4(second)) = (first, second) else { - return; - }; - assert_eq!(blacklist_key(24, &first.octets()), blacklist_key(24, &second.octets())); -} - -#[test] -fn normalize_cidr_keeps_slash_32_unchanged() { - let addr = IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3)); - assert_eq!(normalize_cidr(addr, 32).expect("valid /32"), addr); -} - -#[test] -fn normalize_cidr_masks_host_bits_for_ipv6() { - let addr = IpAddr::V6("2001:db8:1:2:3:4:5:6".parse::().expect("literal")); - let net = normalize_cidr(addr, 64).expect("valid /64"); - assert_eq!(net, IpAddr::V6("2001:db8:1:2::".parse::().expect("literal"))); -} - -#[test] -fn normalize_cidr_masks_partial_bytes() { - let net = normalize_cidr(IpAddr::V4(Ipv4Addr::new(10, 1, 2, 255)), 20).expect("valid /20"); - assert_eq!(net, IpAddr::V4(Ipv4Addr::new(10, 1, 0, 0))); -} - -#[test] -fn normalize_cidr_keeps_slash_128_unchanged() { - let addr = IpAddr::V6("2001:db8::1".parse::().expect("literal")); - assert_eq!(normalize_cidr(addr, 128).expect("valid /128"), addr); -} - -#[test] -fn normalize_cidr_rejects_prefix_zero() { - let err = normalize_cidr(IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3)), 0).expect_err("prefix 0 is invalid"); - assert!(err.to_string().contains("invalid IPv4 prefix length 0")); -} - -#[test] -fn normalize_cidr_rejects_ipv4_prefix_above_32() { - let err = normalize_cidr(IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3)), 33).expect_err("prefix 33 is invalid"); - assert!(err.to_string().contains("invalid IPv4 prefix length 33")); -} - -#[test] -fn normalize_cidr_rejects_ipv6_prefix_above_128() { - let addr = IpAddr::V6("2001:db8::1".parse::().expect("literal")); - let err = normalize_cidr(addr, 129).expect_err("prefix 129 is invalid"); - assert!(err.to_string().contains("invalid IPv6 prefix length 129")); -} diff --git a/tests/xdp_loader.rs b/tests/xdp_loader.rs deleted file mode 100644 index ac22ac1..0000000 --- a/tests/xdp_loader.rs +++ /dev/null @@ -1,41 +0,0 @@ -//! Pure helpers of the XDP loader: interface-name conversion, `.rodata` map -//! naming and the honest attach-mode names. -//! -//! These used to be inline tests in `src/xdp/filter/attach.rs`. They need no -//! kernel; the real attach path is exercised by the netns smoke scripts. -#![cfg(feature = "xdp")] - -use rampart::xdp::{interface_cstr, is_rodata_map, xdp_attach_mode_name}; - -#[test] -fn interface_cstr_accepts_plain_names() { - let c = interface_cstr("eth0").expect("valid interface name"); - assert_eq!(c.as_bytes(), b"eth0"); - assert_eq!(c.as_bytes_with_nul(), b"eth0\0"); -} - -#[test] -fn interface_cstr_rejects_interior_nul() { - assert!(interface_cstr("et\0h0").is_err()); -} - -#[test] -fn rodata_map_matches_libbpf_naming() { - // libbpf builds the name as `
` without rewriting the dot - // (libbpf.c ~1911); with open_memory and no name the object is called "memory": - assert!(is_rodata_map("rampart.rodata")); - assert!(is_rodata_map("memory.rodata")); - assert!(is_rodata_map(".rodata")); - assert!(!is_rodata_map("rampart.bss")); - assert!(!is_rodata_map("stats_map")); -} - -#[test] -fn attach_mode_names_are_honest() { - // Kernel order (linux/netlink.h): NONE=0, DRV=1, SKB=2, HW=3, MULTI=4. - assert_eq!(xdp_attach_mode_name(1), "native (drv)"); - assert_eq!(xdp_attach_mode_name(2), "generic (skb)"); - assert_eq!(xdp_attach_mode_name(3), "hardware offload"); - assert_eq!(xdp_attach_mode_name(0), "none"); - assert_eq!(xdp_attach_mode_name(4), "multiple programs"); -} diff --git a/tests/xdp_object_maps.rs b/tests/xdp_object_maps.rs index 8abc0ad..a075fc6 100644 --- a/tests/xdp_object_maps.rs +++ b/tests/xdp_object_maps.rs @@ -29,7 +29,6 @@ fn every_map_the_loader_uses_exists_in_the_object() { "blacklist_map", "blacklist6_map", "whitelist_map", - "whitelist6_map", "udp_rate_limit", "udp_rate_limit6", ] { @@ -57,34 +56,3 @@ fn rodata_map_value_size_matches_loader_image() { "sizeof(struct rampart_config) in config.h must equal sizeof(XdpGlobals)" ); } - -#[test] -fn map_key_and_value_sizes_match_the_rust_encoding() { - let obj = open_object(); - // (map, key size, value size) as encoded by src/xdp/filter/maps.rs and - // src/xdp/probe/stats.rs. The C structs come from xdp/core/common.h, - // xdp/core/prefix_stats.h and xdp/core/maps.h. - let expected = [ - ("blacklist_map", 8, 8), - ("blacklist6_map", 20, 8), - ("whitelist_map", 8, 1), - ("whitelist6_map", 20, 1), - ("prefix_stats", 24, 24), - ("stats_map", 4, 8), - ]; - for (name, key_size, value_size) in expected { - let map = obj.maps().find(|m| m.name().to_string_lossy() == name); - assert!(map.is_some(), "map '{name}' is missing from the XDP object"); - let map = map.expect("map existence asserted above"); - assert_eq!( - map.key_size(), - key_size, - "map '{name}' key size drifted from the Rust encoding" - ); - assert_eq!( - map.value_size(), - value_size, - "map '{name}' value size drifted from the Rust encoding" - ); - } -} diff --git a/tests/xdp_services.rs b/tests/xdp_services.rs deleted file mode 100644 index 8518dfc..0000000 --- a/tests/xdp_services.rs +++ /dev/null @@ -1,79 +0,0 @@ -//! Edge service wiring: whitelist parsing and the XDP startup path. -//! -//! These used to be inline `#[cfg(test)]` tests in `src/app/services.rs`; the -//! project keeps tests out of source files (TODO.md §4). Kernel-touching -//! behaviour is not exercised here: `start_xdp` is called with `[xdp]` -//! disabled, and the whitelist-map load needs a live interface. - -use std::net::IpAddr; -use std::sync::Arc; - -use rampart::app::services::{build_whitelist, start_xdp}; -use rampart::config::{Config, StoreConfig}; -use rampart::filter::blacklist::Blacklist; -use tokio::sync::watch; - -fn config_with_redis() -> Config { - Config { - store: StoreConfig { - redis_url: Some("redis://127.0.0.1:6379/0".to_string()), - ..Default::default() - }, - ..Default::default() - } -} - -#[cfg(not(feature = "store-redis"))] -#[test] -fn redis_config_without_feature_fails_fast() { - let err = build_whitelist(&config_with_redis()).expect_err("must fail without store-redis"); - assert!(err.to_string().contains("built without store-redis feature")); -} - -#[cfg(not(feature = "store-redis"))] -#[test] -fn empty_store_config_passes_without_feature() { - assert!(build_whitelist(&Config::default()).is_ok()); -} - -#[cfg(feature = "store-redis")] -#[test] -fn redis_config_passes_with_store_feature() { - assert!(build_whitelist(&config_with_redis()).is_ok()); -} - -#[test] -fn build_whitelist_parses_both_address_families() { - let config = Config { - whitelist: vec!["192.0.2.10".to_string(), "2001:db8::1".to_string()], - ..Default::default() - }; - let set = build_whitelist(&config).expect("valid whitelist entries"); - assert!(set.contains(&"192.0.2.10".parse::().expect("ipv4 literal"))); - assert!(set.contains(&"2001:db8::1".parse::().expect("ipv6 literal"))); - assert_eq!(set.len(), 2); -} - -#[test] -fn build_whitelist_rejects_a_malformed_entry() { - let config = Config { - whitelist: vec!["definitely-not-an-ip".to_string()], - ..Default::default() - }; - let err = build_whitelist(&config).expect_err("malformed entry must fail"); - assert!(err.to_string().contains("invalid whitelist entry")); -} - -/// XDP auto-ban wiring: `start_xdp` must accept the `Arc` and, with -/// `[xdp]` disabled, touch neither the kernel nor the blacklist. The -/// `set_autoban` -> `load()` order inside the enabled branch cannot be checked -/// without a kernel. -#[test] -fn start_xdp_accepts_blacklist_and_skips_kernel_when_disabled() { - let (_tx, rx) = watch::channel(false); - let blacklist = Arc::new(Blacklist::new()); - let started = - start_xdp(&Arc::new(Config::default()), &rx, &blacklist).expect("xdp disabled: no kernel work and no error"); - assert!(started.is_none()); - assert!(blacklist.is_empty()); -} diff --git a/tests/xdp_whitelist_keys.rs b/tests/xdp_whitelist_keys.rs deleted file mode 100644 index cf00dfe..0000000 --- a/tests/xdp_whitelist_keys.rs +++ /dev/null @@ -1,42 +0,0 @@ -//! Whitelist LPM key layouts (`whitelist_map` / `whitelist6_map`). -//! -//! The kernel keys are `struct lpm_key` (8 bytes) and `struct lpm_key6` -//! (20 bytes): a little-endian u32 prefix length followed by the address in -//! network order. A drift here silently whitelists the wrong range. -#![cfg(feature = "xdp")] - -use rampart::xdp::{whitelist_key, whitelist6_key}; - -const ADDR_V4: [u8; 4] = [10, 1, 2, 0]; -const ADDR_V6_2001_DB8: [u8; 16] = [0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]; - -#[test] -fn whitelist_key_is_prefix_len_then_address() { - let key = whitelist_key(24, &ADDR_V4); - - assert_eq!(key.len(), 8); - assert_eq!(u32::from_le_bytes(key[0..4].try_into().expect("4 bytes")), 24); - assert_eq!(key[4..8], ADDR_V4, "address kept in network order"); -} - -#[test] -fn whitelist_key_matches_the_blacklist_layout() { - assert_eq!(whitelist_key(32, &ADDR_V4), rampart::xdp::blacklist_key(32, &ADDR_V4)); -} - -#[test] -fn whitelist6_key_is_u32_prefix_len_then_16_address_bytes() { - let key = whitelist6_key(64, &ADDR_V6_2001_DB8); - - assert_eq!(key.len(), 20); - assert_eq!(u32::from_le_bytes(key[0..4].try_into().expect("4 bytes")), 64); - assert_eq!(key[4..20], ADDR_V6_2001_DB8, "address kept in network order"); -} - -#[test] -fn whitelist6_key_does_not_confuse_leading_zeros_with_the_prefix_len() { - let key = whitelist6_key(128, &[0u8; 16]); - - assert_eq!(u32::from_le_bytes(key[0..4].try_into().expect("4 bytes")), 128); - assert_eq!(key[4..20], [0u8; 16]); -} diff --git a/xdp/core/common.h b/xdp/core/common.h index e0ad622..7a4361d 100644 --- a/xdp/core/common.h +++ b/xdp/core/common.h @@ -7,25 +7,11 @@ #define ETH_P_IP 0x0800 #define ETH_P_IPV6 0x86DD -#define ETH_P_8021Q 0x8100 -#define ETH_P_8021AD 0x88A8 #define IPPROTO_TCP 6 #define IPPROTO_UDP 17 -#define IPPROTO_FRAGMENT 44 #define IP_OFFSET 0x1FFF #define IP_MF 0x2000 -/** - * One 802.1Q / 802.1ad tag. - * - * The filter only needs the encapsulated EtherType to skip up to two tags - * before L3; the TCI (PCP/DEI/VID) has no bearing on L3/L4 policy. - */ -struct rampart_vlan_hdr { - __u16 tci; // PCP/DEI/VID, unused - __u16 encap_proto; // EtherType of the next header -}; - /** * Protocol-agnostic TCP connection states. * diff --git a/xdp/core/maps.h b/xdp/core/maps.h index 3644d57..9f1953b 100644 --- a/xdp/core/maps.h +++ b/xdp/core/maps.h @@ -6,9 +6,8 @@ * * An LPM trie so operators can ban a CIDR range rather than single hosts. * The value is the ban expiry as a bpf_ktime_get_ns() timestamp; expired - * entries are ignored by the packet path and reaped from userspace, which - * knows the prefix length. BPF_F_NO_PREALLOC is required by the LPM trie - * type. + * entries are removed lazily by the lookup helpers. BPF_F_NO_PREALLOC is + * required by the LPM trie type. */ struct { __uint(type, BPF_MAP_TYPE_LPM_TRIE); @@ -35,9 +34,8 @@ struct { /** * Whitelist. * - * LPM trie of trusted CIDRs; the filter consults it before the port gate, - * conntrack and blacklists so allowlisted traffic can never be throttled or - * banned away. + * LPM trie of trusted CIDRs; the filter consults it before any other check + * so allowlisted traffic can never be throttled or banned away. */ struct { __uint(type, BPF_MAP_TYPE_LPM_TRIE); @@ -47,28 +45,11 @@ struct { __uint(map_flags, BPF_F_NO_PREALLOC); } whitelist_map SEC(".maps"); -/** - * IPv6 whitelist. - * - * IPv6 twin of whitelist_map: a 20-byte LPM key (host-order prefixlen - * followed by 16 address bytes) and the same early position in the packet - * path. Lookups use prefixlen 128 for the exact source address. - */ -struct { - __uint(type, BPF_MAP_TYPE_LPM_TRIE); - __uint(max_entries, 1000); - __type(key, struct lpm_key6); - __type(value, __u8); - __uint(map_flags, BPF_F_NO_PREALLOC); -} whitelist6_map SEC(".maps"); - /** * Connection tracking table (SYN_RECEIVED to ESTABLISHED). * * LRU so a flood of half-open flows evicts old entries instead of failing - * map updates; RST/FIN removes entries explicitly on the normal path. Only - * new connections are policed: a non-SYN segment whose entry was evicted - * passes, because this is a stateless filter, not a firewall. + * map updates; RST/FIN removes entries explicitly on the normal path. */ struct { __uint(type, BPF_MAP_TYPE_LRU_HASH); @@ -174,7 +155,6 @@ struct { #define STAT_CHALLENGE_SENT 9 #define STAT_CHALLENGE_VERIFIED 10 #define STAT_CHALLENGE_FAILED 11 -#define STAT_FRAGMENT_BYPASS 12 /** * Per-CPU counter storage. diff --git a/xdp/core/stats.h b/xdp/core/stats.h index b40f13b..af0f390 100644 --- a/xdp/core/stats.h +++ b/xdp/core/stats.h @@ -8,9 +8,7 @@ * Increment one per-CPU counter. * * A missing slot (never updated, or an index past max_entries) is ignored so - * accounting can never change a packet verdict. The slot is private to the - * current CPU, so a plain read-modify-write is enough: an atomic would only - * add contention on the hottest path. + * accounting can never change a packet verdict. * * @param idx STAT_* index into stats_map */ @@ -18,7 +16,7 @@ static __always_inline void inc_stat(__u32 idx) { __u64 *val = bpf_map_lookup_elem(&stats_map, &idx); if (val) - (*val)++; + __sync_fetch_and_add(val, 1); } /** @@ -37,7 +35,6 @@ static __always_inline void inc_rate_limit(void) { inc_stat(STAT_RATE_LIMIT); static __always_inline void inc_chal_sent(void) { inc_stat(STAT_CHALLENGE_SENT); } static __always_inline void inc_chal_verified(void) { inc_stat(STAT_CHALLENGE_VERIFIED); } static __always_inline void inc_chal_failed(void) { inc_stat(STAT_CHALLENGE_FAILED); } -static __always_inline void inc_fragment_bypass(void) { inc_stat(STAT_FRAGMENT_BYPASS); } static __always_inline void inc_pass(void) { inc_stat(STAT_PASS); } static __always_inline void inc_drop(void) { inc_stat(STAT_DROP); } diff --git a/xdp/core/syn_challenge.h b/xdp/core/syn_challenge.h index 1b3c53f..4fb6463 100644 --- a/xdp/core/syn_challenge.h +++ b/xdp/core/syn_challenge.h @@ -129,10 +129,7 @@ static __always_inline void chal_build_synack(struct xdp_md *ctx, __builtin_memcpy(tcpw, tcp, 20); if (is_ipv6) { - // saddr/daddr hold the addresses of the reply: the new source is the - // original destination and the new destination is the original - // source. The checksum below is computed over exactly these values. - __builtin_memcpy(saddr, &((struct ipv6hdr *)l3)->daddr, 16); + __builtin_memcpy(saddr, &((struct ipv6hdr *)l3)->daddr, 16); // swapped __builtin_memcpy(daddr, &((struct ipv6hdr *)l3)->saddr, 16); } else { saddr[0] = ((struct iphdr *)l3)->daddr; @@ -194,11 +191,8 @@ static __always_inline void chal_build_synack(struct xdp_md *ctx, __builtin_memcpy(eth->h_source, md, ETH_ALEN); if (is_ipv6) { struct ipv6hdr *ip6 = l3; - // Write the header with the same orientation the checksum was built - // from: saddr is the new source (original destination), daddr the - // new destination (original source). - __builtin_memcpy(&ip6->saddr, saddr, 16); - __builtin_memcpy(&ip6->daddr, daddr, 16); + __builtin_memcpy(&ip6->saddr, daddr, 16); + __builtin_memcpy(&ip6->daddr, saddr, 16); ip6->hop_limit = 64; } else { __builtin_memcpy(l3, ipw, 20); @@ -289,13 +283,10 @@ static __always_inline int chal_on_rst(struct tcphdr *tcp, __u32 ack = bpf_ntohl(tcp->ack_seq); __u8 ok = (seq == p->bad_ack) || (tcp->ack && ack == p->marker + 1); - __u64 sent_at = p->sent_at; - // Copy every field needed before deleting: an LRU element may be freed - // as soon as it is removed, so p must never be dereferenced afterwards. bpf_map_delete_elem(&challenge_pending, flow); - if (!ok || now - sent_at > timeout_ns) { + if (!ok || now - p->sent_at > timeout_ns) { inc_chal_failed(); return XDP_DROP; } diff --git a/xdp/core/universal_filter.c b/xdp/core/universal_filter.c index 7dd7f9e..9852428 100644 --- a/xdp/core/universal_filter.c +++ b/xdp/core/universal_filter.c @@ -5,20 +5,13 @@ * owns, in this order: * * 1. No pure-ACK drop (prevents TCP handshake deadlock). - * 2. LRU conntrack, consulted only for new (SYN) connections. A non-SYN - * segment with no tracked state passes: this is a stateless filter, not - * a firewall, so spoofed SYNs cannot black-hole established flows and - * ordinary replies are never dropped for lack of state. + * 2. LRU conntrack: SYN_RECEIVED to ESTABLISHED, with sequence tracking. * 3. RST/FIN removes the conntrack entry, so no stale state survives. * 4. IPv6 support alongside IPv4. - * 5. IP/CIDR blacklist and whitelist (LPM trie, IPv4 and IPv6). + * 5. IP/CIDR blacklist and whitelist (LPM trie). * 6. Per-IP SYN throttle, with invalid TCP flag combinations dropped. * 7. UDP policy from config.h: pass, drop or rate-limit. * - * L2 decapsulation peels up to two VLAN tags before L3. IP fragments carry - * no inspectable ports, so they only get the source blacklist and then pass - * (dropping first fragments would break legitimate large datagrams). - * * Deep payload inspection is delegated to an optional protocol hook (see * ../hooks/hook_api.h). Without a hook, established connections pass. */ @@ -77,12 +70,7 @@ static __always_inline __u8 detect_tcp_bypass(struct tcphdr *tcp) } /** - * Check the IPv4 blacklist. - * - * The /32 lookup cannot address a wider /24 (or any other prefix) stored in - * the trie, so an expired entry is only ignored here; userspace reaps it - * with the prefix length it was created with. Deleting by /32 from the - * packet path used to leak every prefix ban until the trie filled up. + * Check the IPv4 blacklist and expire the entry on the way out. * * @param src_ip source address, network byte order * @param now current bpf_ktime_get_ns() timestamp @@ -94,15 +82,17 @@ static __always_inline __u8 is_blacklisted(__u32 src_ip, __u64 now) __u64 *ban_until = bpf_map_lookup_elem(&blacklist_map, &key); if (!ban_until) return 0; - return *ban_until > now; + if (*ban_until > now) + return 1; + bpf_map_delete_elem(&blacklist_map, &key); // expired — clean up + return 0; } /** - * Check the IPv6 blacklist. + * Check the IPv6 blacklist and expire the entry on the way out. * * Key layout mirrors bpf_lpm_trie_key: prefixlen in host order followed by - * 16 address bytes. Expired entries are ignored, never deleted here, for the - * same reason as in is_blacklisted(). + * 16 address bytes. * * @param addr 16-byte source address, network byte order * @param now current bpf_ktime_get_ns() timestamp @@ -116,7 +106,10 @@ static __always_inline __u8 is_blacklisted6(const __u8 addr[16], __u64 now) __u64 *ban_until = bpf_map_lookup_elem(&blacklist6_map, &key); if (!ban_until) return 0; - return *ban_until > now; + if (*ban_until > now) + return 1; + bpf_map_delete_elem(&blacklist6_map, &key); // expired — clean up + return 0; } /** @@ -225,25 +218,8 @@ int rampart_universal_filter(struct xdp_md *ctx) if ((void *)(eth + 1) > data_end) return XDP_PASS; - // Strip up to two VLAN tags (802.1Q / 802.1ad). Tagged frames used to hit - // the non-IP early return, which let a banned source bypass the blacklist - // with VLAN/QinQ encapsulation. - void *l3 = (void *)(eth + 1); - __u16 eth_proto = eth->h_proto; -#pragma unroll - for (int i = 0; i < 2; i++) { - if (eth_proto != bpf_htons(ETH_P_8021Q) && - eth_proto != bpf_htons(ETH_P_8021AD)) - break; - struct rampart_vlan_hdr *vh = l3; - if ((void *)(vh + 1) > data_end) - return XDP_PASS; - eth_proto = vh->encap_proto; - l3 = (void *)(vh + 1); - } - // Non-IP traffic: pass (ARP, etc.) - if (eth_proto != bpf_htons(ETH_P_IP) && eth_proto != bpf_htons(ETH_P_IPV6)) + if (eth->h_proto != bpf_htons(ETH_P_IP) && eth->h_proto != bpf_htons(ETH_P_IPV6)) return XDP_PASS; // Parse the IP header. @@ -252,48 +228,36 @@ int rampart_universal_filter(struct xdp_md *ctx) __u8 l4_proto = 0; __u8 is_ipv6 = 0; __u8 native_v6 = 0; - __u8 is_fragment = 0; __u8 src6[16]; - if (eth_proto == bpf_htons(ETH_P_IP)) { - struct iphdr *ip = l3; + if (eth->h_proto == bpf_htons(ETH_P_IP)) { + struct iphdr *ip = (void *)(eth + 1); if ((void *)(ip + 1) > data_end) return XDP_PASS; - if (ip->ihl < 5) { - inc_drop(); + if (ip->ihl < 5) + return XDP_DROP; + + if (ip->protocol != IPPROTO_TCP && ip->protocol != IPPROTO_UDP) + return XDP_PASS; + + // Non-sequential fragment: pass (can't inspect ports safely) + if (ip->frag_off & bpf_htons(IP_OFFSET)) + return XDP_PASS; + + // First fragment with MF: drop (can't reassemble) + if (ip->frag_off & bpf_htons(IP_MF)) return XDP_DROP; - } src_ip = ip->saddr; dst_ip = ip->daddr; l4_proto = ip->protocol; - - // MF or a non-zero offset: this packet has no reliable L4 header. - // Both first and later fragments are handled by the source blacklist - // below and then passed; dropping first fragments would break - // legitimate large datagrams. - if (ip->frag_off & bpf_htons(IP_OFFSET | IP_MF)) { - is_fragment = 1; - } else if (ip->protocol != IPPROTO_TCP && ip->protocol != IPPROTO_UDP) { - return XDP_PASS; - } } else { - struct ipv6hdr *ip6 = l3; + struct ipv6hdr *ip6 = (void *)(eth + 1); if ((void *)(ip6 + 1) > data_end) return XDP_PASS; - // Keep the full address for the IPv6 whitelist and blacklist even - // when it is IPv4-mapped; the low 32 bits are used for flow keys. - __builtin_memcpy(src6, &ip6->saddr, 16); - is_ipv6 = 1; - l4_proto = ip6->nexthdr; - - // A fragment header hides the L4 header; same policy as IPv4. - if (ip6->nexthdr == IPPROTO_FRAGMENT) { - is_fragment = 1; - } else if (ip6->nexthdr != IPPROTO_TCP && ip6->nexthdr != IPPROTO_UDP) { + if (ip6->nexthdr != IPPROTO_TCP && ip6->nexthdr != IPPROTO_UDP) return XDP_PASS; // extension headers not walked - } // Use IPv4-mapped IPv6 address for flow key (::ffff:0:0/96) if (ip6->saddr.in6_u.u6_addr32[0] != 0 || @@ -306,70 +270,37 @@ int rampart_universal_filter(struct xdp_md *ctx) // separately after the generic L4/port gates and must never // touch the IPv4 maps. native_v6 = 1; + is_ipv6 = 1; + l4_proto = ip6->nexthdr; + __builtin_memcpy(src6, &ip6->saddr, 16); } else { // Source address must come from saddr, never daddr, or the // filter would track the server instead of the client. src_ip = ip6->saddr.in6_u.u6_addr32[3]; dst_ip = ip6->daddr.in6_u.u6_addr32[3]; + l4_proto = ip6->nexthdr; + is_ipv6 = 1; } } - __u64 now = bpf_ktime_get_ns(); - - // Whitelist check (LPM trie), before the port gate, conntrack and both - // blacklists: a whitelisted source must truly bypass the state machine. - if (is_ipv6) { - struct lpm_key6 wl6 = {}; - wl6.prefixlen = 128; - __builtin_memcpy(wl6.addr, src6, 16); - if (bpf_map_lookup_elem(&whitelist6_map, &wl6)) { - inc_whitelist(); - return XDP_PASS; - } - } else { - struct lpm_key wl = { .prefixlen = 32, .ip = src_ip }; - if (bpf_map_lookup_elem(&whitelist_map, &wl)) { - inc_whitelist(); - return XDP_PASS; - } - } - - // Fragments: the L4 ports are missing or incomplete, so the stateful and - // throttle logic cannot run. Apply the source blacklist and pass; the - // dedicated counter keeps this deliberate bypass observable. - if (is_fragment) { - __u8 banned = native_v6 ? is_blacklisted6(src6, now) - : is_blacklisted(src_ip, now); - if (banned) { - inc_blacklist(); - inc_drop(); - if (!native_v6 && G_FEATURE_EVENTS) - push_event(EVENT_BAN, src_ip, 0); - return XDP_DROP; - } - inc_fragment_bypass(); - inc_pass(); - return XDP_PASS; - } - // Parse the L4 header. __u8 ip_hdr_len; void *l4; if (is_ipv6) { - struct ipv6hdr *ip6 = l3; + struct ipv6hdr *ip6 = (void *)(eth + 1); l4 = (void *)(ip6 + 1); ip_hdr_len = sizeof(struct ipv6hdr); } else { - struct iphdr *ip = l3; + struct iphdr *ip = (void *)(eth + 1); l4 = (void *)ip + (ip->ihl * 4); ip_hdr_len = ip->ihl * 4; } // Minimum L4 header per protocol: a short UDP datagram used to fall through // to XDP_PASS because the check was sized for TCP, letting it bypass the - // blacklist entirely. Fragments were already handled above (source - // blacklist only), so a short UDP header here is a real datagram. + // blacklist entirely. IPv6 native fragmentation is already filtered above + // (nexthdr must be TCP/UDP), so a short UDP header here is a real datagram. __u32 min_l4 = (l4_proto == IPPROTO_TCP) ? sizeof(struct tcphdr) : sizeof(struct udphdr); if ((void *)l4 + min_l4 > data_end) @@ -390,6 +321,8 @@ int rampart_universal_filter(struct xdp_md *ctx) else inc_udp(); + __u64 now = bpf_ktime_get_ns(); + // Native IPv6: blacklist plus cheap L4 policy (no stateful v6 yet). if (native_v6) { if (is_blacklisted6(src6, now)) { @@ -430,6 +363,13 @@ int rampart_universal_filter(struct xdp_md *ctx) return XDP_PASS; } + // Whitelist check (CIDR), before any filtering. + struct lpm_key wl_key = { .prefixlen = 32, .ip = src_ip }; + if (bpf_map_lookup_elem(&whitelist_map, &wl_key)) { + inc_whitelist(); + return XDP_PASS; + } + // Blacklist check (CIDR with expiry). if (is_blacklisted(src_ip, now)) { inc_blacklist(); @@ -474,52 +414,23 @@ int rampart_universal_filter(struct xdp_md *ctx) return XDP_DROP; } - // TCP header length check. - if (tcp->doff < 5) { - inc_drop(); + // TCP header length check + if (tcp->doff < 5) return XDP_DROP; - } __u8 tcp_hdr_len = tcp->doff * 4; - if ((void *)l4 + tcp_hdr_len > data_end) { - inc_drop(); + if ((void *)data + sizeof(struct ethhdr) + ip_hdr_len + tcp_hdr_len > data_end) return XDP_DROP; - } // Per-prefix stats key (/24), built once after blacklist and bypass drops. struct prefix_key pkey; prefix_key_from_v4(&pkey, src_ip); - // The payload window is bounded by the IP header length field, not by - // data_end: a real NIC pads the last frame to the 60-byte Ethernet - // minimum, so counting to data_end would treat the padding as payload, - // drift expected_seq and drop the connection after a few segments. The - // frame can still be shorter than the IP header claims, so cap at - // data_end as well. - __u32 l4_len; - if (is_ipv6) { - struct ipv6hdr *ip6 = l3; - l4_len = sizeof(struct ipv6hdr) + bpf_ntohs(ip6->payload_len); - } else { - struct iphdr *ip = l3; - __u16 tot_len = bpf_ntohs(ip->tot_len); - if (tot_len < ip_hdr_len) { - inc_drop(); - return XDP_DROP; - } - l4_len = (__u32)(tot_len - ip_hdr_len); - } - - __u32 frame_l4 = (__u32)((__u8 *)data_end - (__u8 *)l4); - if (l4_len > frame_l4) - l4_len = frame_l4; - if (l4_len < tcp_hdr_len) { - inc_drop(); - return XDP_DROP; - } - - __u32 tcp_payload_len = l4_len - tcp_hdr_len; + // Compute payload pointers __u8 *tcp_payload = (__u8 *)tcp + tcp_hdr_len; - __u8 *tcp_payload_end = tcp_payload + tcp_payload_len; + __u8 *tcp_payload_end = (__u8 *)data_end; + __s32 tcp_payload_len = (__s32)(tcp_payload_end - tcp_payload); + if (tcp_payload_len < 0) + tcp_payload_len = 0; // Build the flow key. struct flow_key flow = { @@ -547,14 +458,8 @@ int rampart_universal_filter(struct xdp_md *ctx) // Placed after throttle and blacklist so abusive sources never get a // reply, mirroring the prefix_stats ordering. if (G_SYN_CHALLENGE_ENABLED) { - // The challenge reply is rebuilt as a bare 20-byte IPv4 header, - // so an IPv4 SYN with options cannot be answered without shipping - // a malformed SYN-ACK. Drop it (counted) instead. - if (!is_ipv6 && ((struct iphdr *)l3)->ihl != 5) { - inc_drop(); - return XDP_DROP; - } - int cv = chal_on_syn(ctx, eth, l3, is_ipv6, tcp, &flow, now); + int cv = chal_on_syn(ctx, eth, (void *)(eth + 1), is_ipv6, + tcp, &flow, now); if (cv != CHAL_CONTINUE) return cv; } @@ -562,12 +467,10 @@ int rampart_universal_filter(struct xdp_md *ctx) // Count SYN only after throttle passed (don't count throttled SYNs) update_prefix_stats(&pkey, 1, now); - // Create conntrack entry for new connection. A SYN may carry data - // (TCP Fast Open), which is acknowledged as part of the handshake; - // expected_seq must advance past it or the completing ACK is dropped. + // Create conntrack entry for new connection struct conntrack_entry ce = {}; ce.state = STATE_SYN_RECEIVED; - ce.expected_seq = bpf_ntohl(tcp->seq) + 1 + tcp_payload_len; + ce.expected_seq = bpf_ntohl(tcp->seq) + 1; // expect ACK seq ce.src_ip = src_ip; ce.src_port = tcp->source; ce.last_seen = now; @@ -596,12 +499,9 @@ int rampart_universal_filter(struct xdp_md *ctx) struct conntrack_entry *conn = bpf_map_lookup_elem(&conntrack_map, &flow); if (!conn) { - // Stateless filter, not a firewall: only new connections (SYN) are - // policed. An untracked non-SYN segment — a flow evicted under SYN - // pressure, a connection opened before attach, or the reply to the - // daemon's own outbound connection — passes instead of being dropped. - inc_pass(); - return XDP_PASS; + // Unknown connection — drop + inc_drop(); + return XDP_DROP; } conn->last_seen = now; @@ -614,28 +514,19 @@ int rampart_universal_filter(struct xdp_md *ctx) // Sequence number tracking, established connections only. __u32 seq = bpf_ntohl(tcp->seq); - if (conn->state == STATE_ESTABLISHED && tcp_payload_len > 0) { - if (seq != conn->expected_seq) { - conn->fails++; - if (conn->fails >= G_MAX_OUT_OF_ORDER) { - // Copy the counter before deleting: the LRU element may be - // freed by bpf_map_delete_elem, so conn must not be read - // afterwards. - __u8 fails = conn->fails; - bpf_map_delete_elem(&conntrack_map, &flow); - inc_drop(); - if (G_FEATURE_EVENTS) - push_event(EVENT_CONN_DROP, src_ip, fails); - return XDP_DROP; - } - // Allow retransmission (don't update expected_seq) - inc_pass(); - return XDP_PASS; + if (conn->state == STATE_ESTABLISHED && tcp_payload_len > 0 && + seq != conn->expected_seq) { + conn->fails++; + if (conn->fails >= G_MAX_OUT_OF_ORDER) { + bpf_map_delete_elem(&conntrack_map, &flow); + inc_drop(); + if (G_FEATURE_EVENTS) + push_event(EVENT_CONN_DROP, src_ip, conn->fails); + return XDP_DROP; } - // In-order segment: reset the reordering counter, so isolated - // reordered/retransmitted segments over the connection lifetime can - // never accumulate into a false positive. - conn->fails = 0; + // Allow retransmission (don't update expected_seq) + inc_pass(); + return XDP_PASS; } // State machine. diff --git a/xdp/hooks/hook_api.h b/xdp/hooks/hook_api.h index 18db94a..9038e86 100644 --- a/xdp/hooks/hook_api.h +++ b/xdp/hooks/hook_api.h @@ -28,8 +28,7 @@ * * struct cursor bounds-checked window over the TCP payload, where pos is * the first payload byte and end is one past the last byte - * of the payload as declared by the IP header, capped by - * data_end (Ethernet padding is never part of the window). + * of the packet (validated against data_end). * struct pkt_meta read-only metadata: the 4-tuple (ports in host byte * order), payload length, the full TCP flags byte and the * L3 family. @@ -99,7 +98,7 @@ */ struct cursor { __u8 *pos; // next unparsed byte - __u8 *end; // one past the last payload byte (IP length capped by data_end) + __u8 *end; // one past last valid byte (== data_end) }; /**