BPF program (the first two made the filter wrong on real hardware): - Compute the TCP payload length from ip->tot_len (IPv4) / payload_len (IPv6) instead of data_end. Ethernet padding on a real NIC added 6 bogus payload bytes, broke expected_seq and dropped every connection after the fourth segment. scripts/xdp_pkt_test.sh reproduces it on synthetic frames and fails against the old code. - Read map values (conn->fails, sent_at) before bpf_map_delete_elem; the LRU element is freed by the delete. - Parse up to two VLAN/QinQ tags before L3; fragments are checked against the blacklist and passed instead of bypassing all filtering; first fragments are no longer dropped. - Unknown non-SYN flows PASS: the program is a stateless filter fed by the conntrack state machine, not a firewall, so spoofed SYNs cannot evict established flows into a drop and replies to the daemon's own outbound TCP keep working. - Reset conn->fails on in-order segments, honour SYN payload (TFO), fix the IPv6 SYN-ACK address swap, count every DROP path, drop SYN with IP options. - Expired prefix bans are no longer deleted with the wrong LPM key; userspace reaps them with the exact key. Loader: - Remember the effective attach flags (native vs generic) and use them for detach/query, verifying the interface is clean afterwards. The old code always detached the native slot, leaving a generic program attached after shutdown. - DetachGuard rolls back the attach if anything after it fails. - ban_cidr validates the prefix length and masks host bits. - Whitelist maps (v4 and the new v6 LPM trie) are populated from the config at startup and fail fast on error. - Stats read all 13 counters, and a test asserts every map's key/value size against the Rust encodings. Tests: xdp_pkt_test (padding, VLAN/QinQ, fragments), xdp_loader (attach flags, rollback, detach), xdp_ban_keys, xdp_whitelist_keys, xdp_services, live xdp_attach_smoke (ignored, needs root).
3.9 KiB
Testing - Rampart
Как тестировать: unit, integration, нагрузочное, DDoS simulation.
1. Unit и integration тесты (Rust)
cargo test # все тесты
cargo test --test config_parse
cargo test -- --nocapture # с выводом
Существующие наборы (tests/):
| Тест | Что покрывает |
|---|---|
config_parse |
Парсинг и валидация единого конфига (src/config) |
filter_logic |
Blacklist, rate limit, geo-фильтры |
pow_roundtrip |
Выдача/решение/проверка PoW challenge |
protocol_registry |
Реестр протокольных плагинов |
2. Статический анализ
cargo fmt --all --check
cargo clippy --all-targets --all-features -- -D warnings
cargo deny check
XDP: smoke-check компиляции BPF-программы:
clang -O2 -g -target bpf -c xdp/core/universal_filter.c -o /tmp/universal_filter.o
Функциональные проверки на реальном ядре (нужен root: CAP_BPF + CAP_NET_ADMIN,
bpftool, clang, python3):
sudo bash scripts/xdp_ipv6_smoke.sh
Поднимает netns + veth, грузит программу через verifier и проверяет: бан IPv6 и IPv4
(включая короткие UDP-датаграммы), снятие бана, whitelist поверх активного бана, истечение
TTL по монотонным часам и udp_policy = "rate-limit" для IPv6 (политика патчится в
.rodata до загрузки).
sudo bash scripts/xdp_pkt_test.sh
Проверяет то, что veth-смок поймать не может по построению: Ethernet-паддинг (длина
TCP-payload по ip->tot_len), VLAN/QinQ-теги и фрагменты — забаненный источник не должен
проходить ни тегированным, ни фрагментированным.
scripts/xdp_netns_smoke.sh дополнительно гоняет реальный бинарь rampart end-to-end
(требует hping3).
3. Локальный integration-стенд (Docker)
bash deploy/test/run_test.sh
Поднимает backend-stub (TCP echo), edge (rampart с config.test.toml) и
attacker-контейнер. Сценарии — в deploy/test/README.md.
4. Нагрузочное тестирование
Много-IP TCP flood на VDS (edge-only)
deploy/test/stress/ — полный цикл без Redis/ClickHouse: edge-контейнер с
stub-бэкендом (socat echo) + attacker-контейнер со 100 source IP.
flood.py шлёт чистые TCP-соединения (connect / slowloris / keepalive),
во время флуда параллельно подключаются generic TCP-клиенты (legit.py),
замеряющие RTT.
git clone https://github.com/loki5512344ss/guard.git && cd guard
cargo build --release --bin rampart
cd deploy/test/stress && bash run-stress.sh
Фазы: A — сырая пропускная способность (лимиты сняты), B — защита (per-IP rate limit + reputation bans), C — SYN flood hping3, D — активные соединения.
tcpkali / hping3
tcpkali --connections 1000 --connect-rate 5000 --duration 60s EDGE_IP:25565
hping3 -S --flood -p 25565 --rand-source EDGE_IP # только на свои серверы!
5. Метрики для проверки во время теста
curl -s http://localhost:9090/metrics | grep rampart_
# rampart_connections_total{result="allowed|blocked"}
# rampart_rate_limit_hits
# rampart_pow_challenges_total{result=...}
# rampart_attack_status
Версия: 2.0 | Август 2026