Repository navigation
feat(node,api,web): native kernel-level anti-scanner and advanced network protection - #3
Open
reelsmaker2026 wants to merge 1 commit into
Open
reelsmaker2026 wants to merge 1 commit into
reelsmaker2026 wants to merge 1 commit into
Conversation
…work protection - Netfilter (nftables) integration for malicious scanner and probe mitigation - Automated threat feed synchronization (FireHOL, AlienVault, CINS) - Interval collapsing algorithm for CIDR prefixes to avoid netfilter overlaps - TCP MSS clamping in forward/output chains to eliminate PMTU blackholes - Conntrack fast-path in input chain for established/related proxy traffic - Dynamic SYN-flood rate-limiting meter (150/s per source IP) - Self-IP and RFC 1918/loopback safety auto-whitelisting - Web UI drawer with real-time dropped packet and byte statistics - Graceful fallback on environments without netfilter/nftables support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR introduces native kernel-level netfilter (
nftables) network protection and anti-scanner capabilities for StealthNet nodes. It protects edge nodes against automated internet scanning engines, regulatory/censorship probe crawlers, SYN-flood denial of service, and mobile PMTU blackholes, while offloading established proxy traffic through the kernel connection tracker.All changes are strictly backward-compatible, operate without restarting the proxy engine, and gracefully fall back to a no-op state on environments where
nftablesor kernel network permissions (CAP_NET_ADMIN) are unavailable.Key Features & Architectural Changes
1. In-Kernel Scanner and Probe Dropping (
crates/node/src/plugins.rs)inet stealthnetwith dedicated IPv4 (@scanners4) and IPv6 (@scanners6) sets configured withflags interval; counter;.inputchain (priority filter; policy accept;) prior to hitting socket buffers or proxy engine handlers (e.g. Xray/Sing-box), preserving CPU cycles and preventing TLS probing./var/lib/stealthnet/antiscanner_ips.txt).collapse_cidrs_v4andcollapse_cidrs_v6interval deduplication and sorting (RFC-compliant interval tree semantics). Overlapping subnets across different threat feeds (e.g., a/16containing multiple/24or/32entries) are automatically collapsed into the most encompassing supernet before feeding to nftables, eliminating the netfilterconflicting intervals specifiederror.2. Advanced Network Defense & Optimization (
crates/node/src/plugins.rs)rt_pmtu): Automatically clamps TCP Maximum Segment Size in bothforwardandoutputchains (tcp flags syn / syn,rst tcp option maxseg size set rt mtu). This eliminates Path MTU Discovery (PMTU) blackholes commonly experienced by clients on cellular/mobile 3G/4G/5G carriers and PPPoE/encapsulated networks.ct state established,related acceptare accepted immediately at the top of theinputchain, skipping scanner set lookups and rate limiting for established proxy flows to ensure maximum throughput and sub-millisecond latency.meter synlimit4 { ip saddr limit rate over 150/second burst 200 packets } drop) for both IPv4 and IPv6 to mitigate distributed SYN-flood probing.get_local_node_ips) and excludes any CIDR containing the node's own address (cidr_contains_ip), preventing accidental self-isolation.0.0.0.0/0,::/0, loopback (127.0.0.0/8,::1), private RFC 1918 subnets, and overly broad prefixes (< /8for IPv4,< /16for IPv6).3. Node Sync & Heartbeat Reporting (
crates/node/src/main.rs)NodeState.antiscanner_rules_count,antiscanner_dropped_packets,antiscanner_dropped_bytes) are collected and reported in the node heartbeat payload (plugins_status).4. Admin API Validation (
crates/api/src/node_admin.rs)antiScannersettings:http://orhttps://).plugin_validation_tests.5. Web UI Integration (
web/p-nodes.js)fmtBytes).Modified Files
crates/node/src/plugins.rscrates/node/src/main.rscrates/api/src/node_admin.rsantiScanner, unit testsweb/p-nodes.jsTotal: 4 files changed, +700 / -14 lines.
Database Migrations
None required. The feature utilizes existing
pluginsandplugins_statusJSONB fields in thenodestable.Verification & Testing
crates/node/src/plugins.rs: Added comprehensive unit tests covering config deserialization, protected CIDR filtering, CIDR containment checking (cidr_contains_ip), counter parsing from nftables output, and overlapping CIDR interval collapsing (collapse_cidrs_v4,collapse_cidrs_v6). All 24 node unit tests pass.crates/api/src/node_admin.rs: Added test coverage inplugin_validation_testsfor valid and invalid plugin payloads. All 50 API unit tests pass.nftables.Checklist
nftablesorCAP_NET_ADMINis not available on host🇷🇺 Описание изменений (на русском языке)
Данный PR добавляет нативную защиту сетевого уровня ядра Linux через
nftables(Anti-Scanner) для нод StealthNet. Он защищает пограничные ноды от сканеров портов, сетевых пауков надзорных органов и активного зондирования TLS/Reality, подавляет атаки типа SYN-flood и устраняет «чёрные дыры» PMTU на мобильных операторах, пропуская трафик активных клиентов через conntrack fast-path ядра.Все изменения полностью обратно совместимы, не требуют перезапуска движка прокси (Xray/Sing-box) и корректно переходят в режим no-op на системах без
nftablesили сетевых прав ядра (CAP_NET_ADMIN).Основные компоненты и архитектура:
Сброс пакетов сканеров в ядре Linux (
crates/node/src/plugins.rs):inet stealthnet, сеты@scanners4и@scanners6с флагамиinterval; counter;.inputядра до попадания в буферы сокетов и Xray, экономя CPU и блокируя активное TLS-зондирование./var/lib/stealthnet/antiscanner_ips.txt).collapse_cidrs_v4иcollapse_cidrs_v6. При наличии пересекающихся подсетей из разных фидов (например,/16и вложенные/24или/32), они автоматически схлопываются в объемлющую суперсеть перед передачей в nftables. Это полностью исключает ошибку ядраconflicting intervals specified.Расширенная сетевая защита и оптимизация (
crates/node/src/plugins.rs):rt mtu): Автоматическое согласование максимального размера TCP-сегмента в цепочкахforwardиoutput(tcp flags syn / syn,rst tcp option maxseg size set rt mtu). Устраняет зависания соединений и проблемы PMTU Blackhole у клиентов на мобильных сетях 3G/4G/5G и PPPoE.ct state established,related accept) мгновенно принимаются в начале цепочкиinput, минуя поиск по наборам сканеров и лимитеры, гарантируя максимальную пропускную способность и минимальный пинг для клиентов.meter synlimit4 { ip saddr limit rate over 150/second burst 200 packets } drop) для IPv4 и IPv6.get_local_node_ips) и исключает любые подсети, содержащие её адрес (cidr_contains_ip), предотвращая случайную самоизоляцию.0.0.0.0/0,::/0, loopback (127.0.0.0/8,::1), приватных подсетей RFC 1918 и слишком широких масок (< /8для IPv4,< /16для IPv6).Синхронизация и метрики в Heartbeat (
crates/node/src/main.rs):NodeState.antiscanner_rules_count,antiscanner_dropped_packets,antiscanner_dropped_bytes) считываются и передаются в heartbeat (plugins_status).Валидация в API панели (
crates/api/src/node_admin.rs):antiScanner: протоколы (http/https), интервал (от 5 мин до 7 дней), синтаксис кастомных CIDR/IP и списков. Unit-тесты покрывают корректные и некорректные сценарии.Интерфейс веб-панели (
web/p-nodes.js):