Skip to content

feat(node,api,web): native kernel-level anti-scanner and advanced network protection - #3

Open
reelsmaker2026 wants to merge 1 commit into
STEALTHNET-APP:mainfrom
reelsmaker2026:feat/upstream-antiscanner
Open

reelsmaker2026 wants to merge 1 commit into
STEALTHNET-APP:mainfrom
reelsmaker2026:feat/upstream-antiscanner

Conversation

@reelsmaker2026

@reelsmaker2026 reelsmaker2026 commented Sep 26, 2026 •

Copy link
Copy Markdown

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 nftables or kernel network permissions (CAP_NET_ADMIN) are unavailable.


Key Features & Architectural Changes

1. In-Kernel Scanner and Probe Dropping (crates/node/src/plugins.rs)

  • Netfilter Table & Interval Sets: Operates under table inet stealthnet with dedicated IPv4 (@scanners4) and IPv6 (@scanners6) sets configured with flags interval; counter;.
  • Early Input Drop: Inbound packets matching active scanner CIDR sets are dropped in the netfilter input chain (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.
  • Zero-Downtime Feed Synchronization: Threat feeds are fetched asynchronously in the background and atomically re-applied to nftables without restarting or interrupting active proxy connections. Local lists are cached on disk (/var/lib/stealthnet/antiscanner_ips.txt).
  • Interval Collapsing Algorithm: Implements collapse_cidrs_v4 and collapse_cidrs_v6 interval deduplication and sorting (RFC-compliant interval tree semantics). Overlapping subnets across different threat feeds (e.g., a /16 containing multiple /24 or /32 entries) are automatically collapsed into the most encompassing supernet before feeding to nftables, eliminating the netfilter conflicting intervals specified error.

2. Advanced Network Defense & Optimization (crates/node/src/plugins.rs)

  • TCP MSS Clamping (rt_pmtu): Automatically clamps TCP Maximum Segment Size in both forward and output chains (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.
  • Conntrack Fast-Path: Packets with ct state established,related accept are accepted immediately at the top of the input chain, skipping scanner set lookups and rate limiting for established proxy flows to ensure maximum throughput and sub-millisecond latency.
  • Dynamic SYN-Flood Rate Limiting: Employs an in-kernel nftables meter (meter synlimit4 { ip saddr limit rate over 150/second burst 200 packets } drop) for both IPv4 and IPv6 to mitigate distributed SYN-flood probing.
  • Multi-Layer Whitelisting & Safety Filters:
    • Self-IP Auto-Detection: Dynamically detects the node's local network interface IP addresses (get_local_node_ips) and excludes any CIDR containing the node's own address (cidr_contains_ip), preventing accidental self-isolation.
    • Reserved & Wide Prefix Guard: Disallows blocking 0.0.0.0/0, ::/0, loopback (127.0.0.0/8, ::1), private RFC 1918 subnets, and overly broad prefixes (< /8 for IPv4, < /16 for IPv6).

3. Node Sync & Heartbeat Reporting (crates/node/src/main.rs)

  • Node agent tracks anti-scanner sync intervals autonomously in NodeState.
  • Real-time kernel counter metrics (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)

  • Added strict schema and boundary validation for antiScanner settings:
    • Protocol check (URLs must start with http:// or https://).
    • Interval range check (300s to 604,800s / 7 days).
    • Validation of custom CIDR/IP inputs and shared list references.
  • Added comprehensive unit tests in plugin_validation_tests.

5. Web UI Integration (web/p-nodes.js)

  • Integrated an intuitive configuration section into the node plugins drawer with toggles, source feeds textarea, update intervals, and custom subnet inputs.
  • Displays live statistics directly in the drawer and node list: active protected subnets count, dropped packets count, and formatted dropped traffic volume (fmtBytes).

Modified Files

File Changes Description
crates/node/src/plugins.rs +582 / -1 Netfilter table/chains, interval set collapsing, TCP MSS clamping, conntrack fastpath, SYN limit meter, self-IP guard, counter parser, unit tests
crates/node/src/main.rs +33 / -0 Autonomous background sync timer, heartbeat status population
crates/api/src/node_admin.rs +41 / -1 Schema validation for antiScanner, unit tests
web/p-nodes.js +58 / -2 UI drawer controls, rule count, dropped packet & byte badges

Total: 4 files changed, +700 / -14 lines.


Database Migrations

None required. The feature utilizes existing plugins and plugins_status JSONB fields in the nodes table.


Verification & Testing

  • Unit Tests:
    • 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 in plugin_validation_tests for valid and invalid plugin payloads. All 50 API unit tests pass.
  • Live Netfilter & Kernel Verification:
    • Verified on live Linux kernel 6.x environment with nftables.
    • Confirmed synthetic probe packet dropping in isolated netns environment (packets dropped at kernel boundary, counter incremented).
    • Confirmed SYN-flood burst threshold triggering and rate-limiting meter action.
    • Confirmed end-to-end client connectivity (VLESS Reality via real mobile client), passing high-bandwidth traffic through the conntrack fast-path without degradation.

Checklist

  • Code compiles cleanly with zero warnings
  • Unit test suites pass
  • Zero sensitive data, internal IP addresses, or secrets committed (RFC 5737 test addresses used in tests)
  • No breaking API changes or database schema modifications
  • Graceful fallback when nftables or CAP_NET_ADMIN is 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).

Основные компоненты и архитектура:

  1. Сброс пакетов сканеров в ядре Linux (crates/node/src/plugins.rs):

    • Таблица и наборы интервалов: Таблица inet stealthnet, сеты @scanners4 и @scanners6 с флагами interval; counter;.
    • Ранний сброс (Early Drop): Входящие пакеты из подсетей сканеров сбрасываются цепочкой input ядра до попадания в буферы сокетов и Xray, экономя CPU и блокируя активное TLS-зондирование.
    • Обновление списков без простоя: Списки загружаются асинхронно в фоне и атомарно применяются в nftables без разрыва активных соединений клиентов. Списки кэшируются на диске (/var/lib/stealthnet/antiscanner_ips.txt).
    • Алгоритм схлопывания интервалов (Interval Collapsing): Реализованы алгоритмы collapse_cidrs_v4 и collapse_cidrs_v6. При наличии пересекающихся подсетей из разных фидов (например, /16 и вложенные /24 или /32), они автоматически схлопываются в объемлющую суперсеть перед передачей в nftables. Это полностью исключает ошибку ядра conflicting intervals specified.
  2. Расширенная сетевая защита и оптимизация (crates/node/src/plugins.rs):

    • TCP MSS Clamping (rt mtu): Автоматическое согласование максимального размера TCP-сегмента в цепочках forward и output (tcp flags syn / syn,rst tcp option maxseg size set rt mtu). Устраняет зависания соединений и проблемы PMTU Blackhole у клиентов на мобильных сетях 3G/4G/5G и PPPoE.
    • Conntrack Fast-Path: Пакеты установленных сессий (ct state established,related accept) мгновенно принимаются в начале цепочки input, минуя поиск по наборам сканеров и лимитеры, гарантируя максимальную пропускную способность и минимальный пинг для клиентов.
    • Динамический SYN-Flood Rate Limiter: В ядре задействован dynamic meter (meter synlimit4 { ip saddr limit rate over 150/second burst 200 packets } drop) для IPv4 и IPv6.
    • Многоуровневая защита и авто-вайтлинг:
      • Self-IP автоопределение: Нода определяет собственные IP-адреса на сетевых интерфейсах (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).
  3. Синхронизация и метрики в Heartbeat (crates/node/src/main.rs):

    • Агент ноды отслеживает интервалы синхронизации в NodeState.
    • Метрики счетчиков ядра (antiscanner_rules_count, antiscanner_dropped_packets, antiscanner_dropped_bytes) считываются и передаются в heartbeat (plugins_status).
  4. Валидация в API панели (crates/api/src/node_admin.rs):

    • Строгая валидация настроек antiScanner: протоколы (http/https), интервал (от 5 мин до 7 дней), синтаксис кастомных CIDR/IP и списков. Unit-тесты покрывают корректные и некорректные сценарии.
  5. Интерфейс веб-панели (web/p-nodes.js):

    • Блок настроек в шторке плагинов: переключатель, URL источников, интервал обновления, дополнительные подсети.
    • Живые счетчики в карточке и списке нод: количество активных правил, сброшенные пакеты и объём сброшенного трафика.

…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant