feat(xdp): IPv6 UDP rate limit, working loader; English JavaDoc comments

XDP behaviour:
- udp_rate_limit6 (LRU, 128-bit source key) + throttle_hit6, so
  udp_policy = "rate-limit" now applies to native IPv6 as well.
- scripts/xdp_ipv6_smoke.sh: phase 4 patches .rodata before load and
  verifies policy=2 on a real kernel (3 pass / 3 rate-limited).

XDP loader (was completely broken, never reached the verifier):
- .rodata is now one struct rampart_config with frozen offsets enforced by
  _Static_assert; XdpGlobals is #[repr(C)] and the image is built with
  offset_of!. Previously a 96-byte image was written into a 76-byte map at
  offsets clang had reordered, so load() failed with EINVAL.
- patch_rodata fails loudly when the map size and the image size diverge.
- build.rs tracks xdp/core and xdp/hooks, not just universal_filter.c.
- build_ringbuf looked for "events_map"; the map is "events_ringbuf".
- tests/xdp_object_maps.rs: verifies map names and .rodata size without root;
  the real binary was confirmed to attach in a netns.

Docs and style:
- Code comments are English, JavaDoc/Rustdoc style, without emoji or
  decorative banners (new project rule, TODO §0.8).
- README rewritten bilingual: Russian first, English below, TOC and
  copy-paste quick start.
- docs/README.md: documentation index and maintenance rules;
  configuration.md documents the whole [xdp] section and IPv4/IPv6 coverage;
  testing.md describes the real-kernel smoke; stale research links removed.
This commit is contained in:
Loki 2026-11-15 23:44:07 +01:00
parent 295ab81fb4
commit 918e561a61
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
104 changed files with 2129 additions and 1021 deletions

463
README.md
View file

@ -1,256 +1,321 @@
<div align="center"> <div align="center">
> **⚠️ UNDER DEVELOPMENT** — All performance data, benchmarks, and specifications shown are approximate and subject to change.
>
> **⚠️ В РАЗРАБОТКЕ** — Все показатели производительности, тесты и характеристики являются примерными и могут измениться.
</div>
<div align="center">
# Rampart # Rampart
Universal network protection platform (L3/L4/L7 DDoS filtering framework) **Универсальная платформа сетевой защиты: L3/L4/L7-фильтрация DDoS для VDS, веб-сервисов и игровых серверов.**
![Rust](https://img.shields.io/badge/Rust-000000?style=flat-square&logo=rust&logoColor=white) ![Rust](https://img.shields.io/badge/Rust-000000?style=flat-square&logo=rust&logoColor=white)
![eBPF](https://img.shields.io/badge/C/eBPF%20XDP-FF6C37?style=flat-square&logo=linux&logoColor=white) ![eBPF](https://img.shields.io/badge/C%2FeBPF%20XDP-FF6C37?style=flat-square&logo=linux&logoColor=white)
![License](https://img.shields.io/badge/license-GPLv3-blue?style=flat-square&logo=gnu&logoColor=white) ![License](https://img.shields.io/badge/license-GPLv3-blue?style=flat-square&logo=gnu&logoColor=white)
![Version](https://img.shields.io/badge/version-0.3.0--dev-green?style=flat-square) ![Version](https://img.shields.io/badge/version-0.3.0--dev-green?style=flat-square)
![Status](https://img.shields.io/badge/status-development-yellow?style=flat-square) ![Status](https://img.shields.io/badge/status-development-yellow?style=flat-square)
[English](#english) | [Русский](#russian) [Русский](#русский) · [English](#english)
</div> </div>
--- > [!WARNING]
> Проект в активной разработке. Числа производительности и API могут меняться.
<a name="english"></a>
## English
### Overview
Rampart filters traffic at three levels before it reaches your service:
- **Kernel level** — XDP/eBPF drops unwanted packets before they reach the Linux TCP stack;
- **Network level** — PoW challenge raises the cost of connection floods for any TCP protocol;
- **Application level** — Rust userspace core performs L7 handshake analysis, rate limiting and reputation checks.
Protocol-specific logic lives in **modular protocol plugins**, so the same platform protects VDS, web services, and game servers alike.
### Architecture
```
┌────────────────────────────────────────────────────────────────────┐
│ Layer 1: Kernel / XDP (C) │
│ universal TCP state machine · SYN throttle · CIDR black/white │
│ lists · UDP policy · pluggable BPF protocol hooks │
├────────────────────────────────────────────────────────────────────┤
│ Layer 2: Universal PoW Challenge (Rust) │
│ SHA256 hashcash · dynamic difficulty │
│ works over any TCP protocol ⚠️ OFF by default │
├────────────────────────────────────────────────────────────────────┤
│ Layer 3: Userspace Core (Rust) │
│ L7 handshake analysis · rate limit · HMAC · death-code patterns │
├────────────────────────────────────────────────────────────────────┤
│ Layer 4: Protocol Plugins (feature crates) │
│ http (protocol-http) · Minecraft Java (protocol-minecraft) · grpc (planned) │
└────────────────────────────────────────────────────────────────────┘
Traffic Intel (EWMA thresholds, profiling, reputation)
runs across all layers
```
```
Attacker → [XDP/eBPF] → [PoW] → [Userspace Core] → [Plugin] → Your Service
1 2 3 4
```
### Components
| Component | Role | Stack |
|-----------|------|-------|
| **rampart** | Edge engine: XDP loader, PoW challenge, L7 filtering, traffic intel | Rust (tokio, libbpf) + C (XDP) |
| **rampart-manager** | Management API + Redis sync | Rust (axum, redis) |
| **rampart-cli** | CLI tool for operators | Rust (clap) |
| **rampart-tui** | Live metrics terminal dashboard, polls the Prometheus `/metrics` endpoint | Rust (ratatui) |
| **protocol plugins** | Protocol-aware filtering as feature crates | Rust |
| ↳ `http` | HTTP/1.1 handler, compiled with the `protocol-http` feature | Rust |
| ↳ `minecraft` | Minecraft Java TCP handshake and tunnel, compiled with `protocol-minecraft` | Rust |
| ↳ `grpc` | Planned | Rust |
| **docs/kb** | Bilingual knowledge base: attack anatomy, defense levels, practice guides | Markdown |
### Performance
Confirmed numbers only — VDS stress test ([load-test-report.md](docs/research/load-test-report.md)), edge-only setup on loopback, 2 vCPU:
| Scenario | Result |
|----------|--------|
| Raw L7 throughput | ~4k conn/s proxied |
| Masked 100-IP handshake flood (default 5 pps/IP) | **99.6% blocked**, legit clients OK |
| SYN flood without XDP | 0 impact — handled by the kernel |
Full benchmark suite in progress.
### Quick Start
```bash
# Build the HTTP edge handler
cargo build --release --features protocol-http
# Install the default config
sudo mkdir -p /etc/rampart
sudo cp deploy/config/edge-http.toml /etc/rampart/config.toml
# Run edge node (config path comes from $RAMPART_CONFIG, default /etc/rampart/config.toml)
RAMPART_CONFIG=/etc/rampart/config.toml ./target/release/rampart
```
### Minecraft Java Edge
Rampart also has an early Minecraft Java TCP handler. Build it with
`cargo build --release --features protocol-minecraft --bin rampart`, copy
`deploy/config/edge.toml` as its config, and follow
[docs/minecraft-java.md](docs/minecraft-java.md) for Paper PROXY-protocol and
private-backend setup. This handler does not protect an already-saturated home
uplink; use a DDoS-filtering game proxy/provider in front of the edge.
### Documentation
| Path | Description |
|------|-------------|
| [docs/kb/](docs/kb/) | Knowledge base: attack anatomy, defense levels, practice guides |
| [docs/research/architecture.md](docs/research/architecture.md) | Layered architecture, ADRs, migration notes |
| [docs/research/load-test-report.md](docs/research/load-test-report.md) | VDS stress test report (2026-08-04) |
| [docs/research/](docs/research/) | Research notes: eBPF, anti-bot, DDoS vectors, networking |
| [docs/deployment.md](docs/deployment.md) | Deployment guide |
| [docs/minecraft-java.md](docs/minecraft-java.md) | Minecraft Java edge and Paper setup |
| [docs/configuration.md](docs/configuration.md) | Configuration reference |
| [docs/runbook.md](docs/runbook.md) | Operations runbook |
### Roadmap
- Stabilize the protocol plugin API
- BPF hook modules for deep protocol parsing in XDP
--- ---
<a name="russian"></a> <a id="русский"></a>
## Русский ## Русский
### Обзор ### Содержание
Rampart фильтрует трафик на трёх уровнях до того, как он дойдёт до вашего сервиса: - [Что это](#что-это)
- [Как это работает](#как-это-работает)
- [Возможности](#возможности)
- [Требования](#требования)
- [Быстрый старт](#быстрый-старт)
- [Конфигурация](#конфигурация)
- [Протокол-плагины](#протокол-плагины)
- [Производительность](#производительность)
- [Документация](#документация)
- [Разработка](#разработка)
- [Лицензия](#лицензия)
- **Уровень ядра** — XDP/eBPF отбрасывает нежелательные пакеты до того, как они попадут в TCP-стек Linux; ### Что это
- **Сетевой уровень** — PoW-challenge повышает стоимость флуда соединений для любого TCP-протокола;
- **Прикладной уровень** — userspace-ядро на Rust выполняет анализ L7-handshake, rate limiting и проверку репутации.
Логика, специфичная для протоколов, вынесена в **модульные протокол-плагины** — одна платформа защищает VDS, веб-сервисы и игровые серверы. Rampart отбрасывает атакующий трафик до того, как он дойдёт до вашего сервиса.
Фильтрация идёт в три уровня: XDP/eBPF в ядре, PoW-challenge в userspace и
L7-анализ протокола. Логика конкретного протокола вынесена в плагины, поэтому
одна и та же платформа защищает и веб-сервис, и игровой сервер.
### Архитектура ### Как это работает
```
┌────────────────────────────────────────────────────────────────────┐
│ Слой 1: Ядро / XDP (C) │
│ универсальный TCP state machine · SYN throttle · CIDR black/ │
│ white списки · UDP policy · подключаемые BPF протокол-хуки │
├────────────────────────────────────────────────────────────────────┤
│ Слой 2: Универсальный PoW Challenge (Rust) │
│ SHA256 hashcash · dynamic difficulty │
│ работает поверх любого TCP-протокола ⚠️ ВЫКЛЮЧЕН по умолчанию │
├────────────────────────────────────────────────────────────────────┤
│ Слой 3: Userspace Core (Rust) │
│ L7 handshake analysis · rate limit · HMAC · death-code паттерны │
├────────────────────────────────────────────────────────────────────┤
│ Слой 4: Протокол-плагины (feature crates) │
│ http (protocol-http) · Minecraft Java (protocol-minecraft) · grpc (в планах) │
└────────────────────────────────────────────────────────────────────┘
Traffic Intel (EWMA thresholds, профилирование, репутация)
работает поперёк всех слоёв
```
``` ```
Атакующий → [XDP/eBPF] → [PoW] → [Userspace Core] → [Плагин] → Ваш сервис Атакующий → [XDP/eBPF] → [PoW] → [Userspace Core] → [Плагин] → Ваш сервис
1 2 3 4 1 2 3 4
``` ```
### Компоненты | Уровень | Что делает | Стек |
|---------|------------|------|
| **1. Ядро / XDP** | Дроп пакетов до стека Linux: TCP state machine, SYN-throttle, CIDR blacklist/whitelist, UDP policy, IPv4 + IPv6 | C, eBPF |
| **2. PoW challenge** | Повышает цену флуда соединений для любого TCP-протокола (по умолчанию выключен) | Rust, SHA-256 hashcash |
| **3. Userspace core** | L7-handshake, rate limit, репутация, профилирование трафика | Rust, tokio |
| **4. Протокол-плагины** | Разбор и фильтрация конкретного протокола | Rust (feature crates) |
| Компонент | Роль | Технологии | ### Возможности
|-----------|------|------------|
| **rampart** | Edge-движок: XDP loader, PoW challenge, L7-фильтрация, traffic intel | Rust (tokio, libbpf) + C (XDP) |
| **rampart-manager** | Management API + Redis sync | Rust (axum, redis) |
| **rampart-cli** | CLI для операторов | Rust (clap) |
| **rampart-tui** | Терминальный дашборд live-метрик, опрашивает Prometheus `/metrics` | Rust (ratatui) |
| **Протокол-плагины** | Протоколозависимая фильтрация в виде feature crates | Rust |
| ↳ `http` | HTTP/1.1-обработчик, собирается с фичей `protocol-http` | Rust |
| ↳ `minecraft` | TCP-handshake и туннель Minecraft Java, фича `protocol-minecraft` | Rust |
| ↳ `grpc` | В планах | Rust |
| **docs/kb** | Двуязычная база знаний: анатомия атак, уровни защиты, практические руководства | Markdown |
### Производительность - **XDP-фильтр в ядре** — blacklist/whitelist CIDR, SYN-throttle, детект поддельных
TCP-флагов, UDP policy (`pass` / `drop` / `rate-limit`), prefix-статистика.
- **IPv4 и IPv6** — отдельные LPM-таблицы для обоих семейств: баны по `/32` и `/128`,
UDP rate-limit с 128-битным ключом, детект TCP-bypass, статистика по `/24` и `/64`.
- **PoW-challenge** — hashcash с динамической сложностью, работает поверх любого TCP.
- **Протокол-плагины** — HTTP/1.1 и Minecraft Java, API плагинов стабилизируется.
- **Ringbuf-события и авто-бан** — события из ядра в userspace, opt-in авто-бан по
rate-limit и обрывам соединений.
- **Управление и наблюдаемость** — Prometheus-метрики, management API + Redis-синхронизация,
CLI и TUI-дашборд.
- **Traffic Intel** — EWMA-пороги, профилирование и репутация поверх всех уровней.
Только подтверждённые числа — VDS stress test ([load-test-report.md](docs/research/load-test-report.md)), edge-only на loopback, 2 vCPU: ### Требования
| Сценарий | Результат | | Компонент | Требование |
|----------|-----------| |-----------|------------|
| Raw L7 пропускная способность | ~4k conn/s проксировано | | Rust | 1.85+ (edition 2024) |
| Маскированный flood с 100 IP (default 5 pps/IP) | **99.6% заблокировано**, легитимные клиенты в порядке | | XDP | Linux 5.10+, `clang` с `-target bpf`, `libbpf`/`libelf` |
| SYN flood без XDP | 0 влияния — обрабатывается ядром | | Опционально | Redis (синхронизация блэклиста), ClickHouse (события), GeoIP-база |
Полный набор бенчмарков в процессе подготовки.
### Быстрый старт ### Быстрый старт
```bash ```bash
# Сборка HTTP-обработчика # 1. Сборка edge-ноды с HTTP-обработчиком
cargo build --release --features protocol-http cargo build --release --features protocol-http
# Установка дефолтного конфига # 2. Конфиг (путь по умолчанию /etc/rampart/config.toml, переопределяется $RAMPART_CONFIG)
sudo mkdir -p /etc/rampart sudo mkdir -p /etc/rampart
sudo cp deploy/config/edge-http.toml /etc/rampart/config.toml sudo cp deploy/config/edge-http.toml /etc/rampart/config.toml
# Запуск edge ноды (путь конфига берётся из $RAMPART_CONFIG, по умолчанию /etc/rampart/config.toml) # 3. Запуск
RAMPART_CONFIG=/etc/rampart/config.toml ./target/release/rampart RAMPART_CONFIG=/etc/rampart/config.toml ./target/release/rampart
``` ```
### Minecraft Java Edge С XDP (нужен root либо `CAP_BPF` + `CAP_NET_ADMIN`):
В проекте появился ранний TCP-обработчик Minecraft Java. Соберите его командой ```bash
`cargo build --release --features protocol-minecraft --bin rampart`, скопируйте cargo build --release --features protocol-http,xdp
`deploy/config/edge.toml` как конфиг и настройте # в конфиге: [xdp] enabled = true, interface = "eth0"
Paper и закрытый backend по инструкции ```
[docs/minecraft-java.md](docs/minecraft-java.md). Сам Rampart не спасёт домашний
канал, если атака уже забила его: перед edge нужен игровой прокси или провайдер Проверить, что всё собрано и работает:
с фильтрацией DDoS.
```bash
cargo fmt --all --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-features
```
### Конфигурация
Полный справочник — [docs/configuration.md](docs/configuration.md). Минимальный конфиг:
bind-адрес и порт, список upstream'ов, `[limits]`, опционально `[store]` и `[xdp]`.
### Протокол-плагины
| Плагин | Feature | Что даёт |
|--------|---------|----------|
| HTTP/1.1 | `protocol-http` | Парсинг request-head, вердикт Allow/Reject, туннель на upstream |
| Minecraft Java | `protocol-minecraft` | TCP-handshake, туннель на Paper (включая PROXY protocol) |
| gRPC | план | — |
Minecraft-edge: `cargo build --release --features protocol-minecraft --bin rampart`,
конфиг — `deploy/config/edge.toml`, инструкция — [docs/minecraft-java.md](docs/minecraft-java.md).
Rampart не спасёт уже забитый домашний канал: перед edge нужен игровой прокси или
провайдер с фильтрацией DDoS.
### Производительность
Только подтверждённые замеры — VDS stress test, edge-only на loopback, 2 vCPU
([отчёт](docs/research/load-test-report.md)):
| Сценарий | Результат |
|----------|-----------|
| Пропускная способность L7 | ~4k conn/s |
| Маскированный flood с 100 IP (5 pps/IP) | **99.6% заблокировано**, легитимные клиенты работают |
| SYN flood без XDP | обрабатывается ядром |
Полный набор бенчмарков — в работе.
### Документация ### Документация
| Путь | Описание | | Раздел | Где |
|------|----------| |--------|-----|
| [docs/kb/](docs/kb/) | База знаний: анатомия атак, уровни защиты, практические руководства | | Индекс всей документации | [docs/README.md](docs/README.md) |
| [docs/research/architecture.md](docs/research/architecture.md) | Слоистая архитектура, ADR, миграционные заметки | | Деплой | [docs/deployment.md](docs/deployment.md) |
| [docs/research/load-test-report.md](docs/research/load-test-report.md) | Отчёт по VDS stress test (2026-08-04) | | Конфигурация | [docs/configuration.md](docs/configuration.md) |
| [docs/research/](docs/research/) | Research-заметки: eBPF, антибот, векторы DDoS, сети | | Эксплуатация (runbook) | [docs/runbook.md](docs/runbook.md) |
| [docs/deployment.md](docs/deployment.md) | Руководство по деплою | | Диагностика | [docs/troubleshooting.md](docs/troubleshooting.md) |
| [docs/minecraft-java.md](docs/minecraft-java.md) | Minecraft Java edge и настройка Paper | | Тестирование | [docs/testing.md](docs/testing.md) |
| [docs/configuration.md](docs/configuration.md) | Справочник конфигурации | | API manager'а | [docs/api.md](docs/api.md) |
| [docs/runbook.md](docs/runbook.md) | Операционный runbook | | База знаний (атаки, защита, практика) | [docs/kb/](docs/kb/) |
| Research: архитектура, eBPF, DDoS | [docs/research/](docs/research/) |
### Roadmap ### Разработка
- Стабилизация API протокол-плагинов - Правила кода и Definition of Done — [TODO.md](TODO.md) (§0).
- BPF hook модули для глубокого парсинга протоколов в XDP - Комментарии в коде — только по-английски, JavaDoc/Rustdoc-стиль (§0.8).
- Тесты живут в `tests/`, без `#[cfg(test)]` в файлах с кодом.
- Перед PR: `cargo fmt`, `cargo clippy -D warnings`, `cargo test --all-features`.
Трекер идей и статус задач — [TODO.md](TODO.md), issues и PR — во вкладках репозитория.
### Лицензия
GNU General Public License v3.0 — [LICENSE](LICENSE).
--- ---
### Links <a id="english"></a>
- [Releases](../../releases) ## English
- [Issues](../../issues)
- [License](LICENSE) ### Contents
- [What it is](#what-it-is)
- [How it works](#how-it-works)
- [Features](#features)
- [Requirements](#requirements)
- [Quick start](#quick-start)
- [Configuration](#configuration)
- [Protocol plugins](#protocol-plugins)
- [Performance](#performance)
- [Documentation](#documentation)
- [Development](#development)
- [License](#license)
### What it is
Rampart drops malicious traffic before it reaches your service. Filtering happens
at three levels: XDP/eBPF in the kernel, a proof-of-work challenge in userspace,
and L7 protocol analysis. Protocol-specific logic lives in plugins, so the same
platform protects a web service and a game server alike.
### How it works
```
Attacker → [XDP/eBPF] → [PoW] → [Userspace Core] → [Plugin] → Your service
1 2 3 4
```
| Layer | Responsibility | Stack |
|-------|----------------|-------|
| **1. Kernel / XDP** | Drop packets before the Linux stack: TCP state machine, SYN throttle, CIDR black/white lists, UDP policy, IPv4 + IPv6 | C, eBPF |
| **2. PoW challenge** | Raises the cost of connection floods for any TCP protocol (off by default) | Rust, SHA-256 hashcash |
| **3. Userspace core** | L7 handshake analysis, rate limiting, reputation, traffic profiling | Rust, tokio |
| **4. Protocol plugins** | Protocol-aware parsing and filtering | Rust (feature crates) |
### Features
- **Kernel XDP filter** — CIDR blacklist/whitelist, SYN throttle, forged TCP flag
detection, UDP policy (`pass` / `drop` / `rate-limit`), per-prefix statistics.
- **IPv4 and IPv6** — separate LPM tables for both families: `/32` and `/128` bans,
UDP rate limiting keyed by the full 128-bit address, TCP bypass detection,
`/24` and `/64` prefix stats.
- **PoW challenge** — hashcash with dynamic difficulty over any TCP protocol.
- **Protocol plugins** — HTTP/1.1 and Minecraft Java; the plugin API is stabilizing.
- **Ringbuf events and auto-ban** — kernel events delivered to userspace, with
opt-in auto-ban on rate limits and connection drops.
- **Operations** — Prometheus metrics, management API with Redis sync, CLI and a
terminal dashboard.
- **Traffic Intel** — EWMA thresholds, profiling and reputation across all layers.
### Requirements
| Component | Requirement |
|-----------|-------------|
| Rust | 1.85+ (edition 2024) |
| XDP | Linux 5.10+, `clang` with `-target bpf`, `libbpf`/`libelf` |
| Optional | Redis (blacklist sync), ClickHouse (events), GeoIP database |
### Quick start
```bash
# 1. Build the edge node with the HTTP handler
cargo build --release --features protocol-http
# 2. Install the config (default is /etc/rampart/config.toml, override with $RAMPART_CONFIG)
sudo mkdir -p /etc/rampart
sudo cp deploy/config/edge-http.toml /etc/rampart/config.toml
# 3. Run
RAMPART_CONFIG=/etc/rampart/config.toml ./target/release/rampart
```
With XDP (root or `CAP_BPF` + `CAP_NET_ADMIN`):
```bash
cargo build --release --features protocol-http,xdp
# config: [xdp] enabled = true, interface = "eth0"
```
Verify the checkout:
```bash
cargo fmt --all --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-features
```
### Configuration
Full reference: [docs/configuration.md](docs/configuration.md). The minimal config
needs a bind address and port, upstreams, and `[limits]`; `[store]` and `[xdp]`
are optional.
### Protocol plugins
| Plugin | Feature | Provides |
|--------|---------|----------|
| HTTP/1.1 | `protocol-http` | Request-head parsing, Allow/Reject verdict, upstream tunnel |
| Minecraft Java | `protocol-minecraft` | TCP handshake, tunnel to Paper (PROXY protocol supported) |
| gRPC | planned | — |
Minecraft edge: `cargo build --release --features protocol-minecraft --bin rampart`,
config in `deploy/config/edge.toml`, guide in
[docs/minecraft-java.md](docs/minecraft-java.md). Rampart cannot rescue an already
saturated home uplink: put a game proxy or a DDoS-filtering provider in front.
### Performance
Confirmed numbers only — VDS stress test, edge-only on loopback, 2 vCPU
([report](docs/research/load-test-report.md)):
| Scenario | Result |
|----------|--------|
| L7 throughput | ~4k conn/s |
| Masked 100-IP handshake flood (5 pps/IP) | **99.6% blocked**, legitimate clients unaffected |
| SYN flood without XDP | handled by the kernel |
The full benchmark suite is in progress.
### Documentation
| Topic | Where |
|-------|-------|
| Documentation index | [docs/README.md](docs/README.md) |
| Deployment | [docs/deployment.md](docs/deployment.md) |
| Configuration | [docs/configuration.md](docs/configuration.md) |
| Operations runbook | [docs/runbook.md](docs/runbook.md) |
| Troubleshooting | [docs/troubleshooting.md](docs/troubleshooting.md) |
| Testing | [docs/testing.md](docs/testing.md) |
| Manager API | [docs/api.md](docs/api.md) |
| Knowledge base | [docs/kb/](docs/kb/) |
| Research notes | [docs/research/](docs/research/) |
### Development
- Coding rules and Definition of Done: [TODO.md](TODO.md) (§0).
- Code comments are English only, JavaDoc/Rustdoc style (§0.8).
- Tests live in `tests/`; no `#[cfg(test)]` modules in code files.
- Before a PR: `cargo fmt`, `cargo clippy -D warnings`, `cargo test --all-features`.
Roadmap and task status live in [TODO.md](TODO.md); issues and PRs are in the
repository tabs.
### License ### License
GNU General Public License v3.0 GNU General Public License v3.0 — [LICENSE](LICENSE).

47
TODO.md
View file

@ -43,6 +43,19 @@
тесты живут в `tests/` (нужный хелпер делай `pub` с реальным вызовом-потребителем). тесты живут в `tests/` (нужный хелпер делай `pub` с реальным вызовом-потребителем).
Существующие инлайн-тесты — легаси, мигрировать постепенно (см. бэклог). Существующие инлайн-тесты — легаси, мигрировать постепенно (см. бэклог).
### §0.8 Комментарии в коде (все языки)
- **Все комментарии и doc-комментарии — на английском.** Русский остаётся только в
пользовательских текстах: `docs/`, README, TODO, логи (`tracing::*!`), сообщения CLI/ошибок.
- **JavaDoc/Rustdoc-стиль.** C: `/** ... */` над функцией/структурой/картой/глобалом с
`@param`/`@return`, когда они есть. Rust: `//!` для модуля (что он владеет), `///` для
элемента; сохраняй секции `# Errors` / `# Panics` / `# Safety`.
- **Без эмодзи, ASCII-баннеров (`═══`, `───`), CAPS-акцентов** и декоративных разделителей.
Для группировки — обычный короткий комментарий.
- Инлайн-комментарий объясняет **почему**, а не пересказывает код. Комментарий-шум удаляй.
- Правишь файл — переводи комментарии в нём целиком (смесь языков запрещена), но **не трогай
строковые литералы, идентификаторы и логику**.
- `// SAFETY:` — префикс обязателен, текст по-английски.
--- ---
## 1. Целевая структура (v0.3) ## 1. Целевая структура (v0.3)
@ -136,6 +149,15 @@ guard/
### Документация ### Документация
- [x] docs/deployment.md, configuration.md, runbook.md — старых крейтов/MC не упоминают (grep чисто). - [x] docs/deployment.md, configuration.md, runbook.md — старых крейтов/MC не упоминают (grep чисто).
- [x] docs/kb/README.md — индекс KB со ссылками. - [x] docs/kb/README.md — индекс KB со ссылками.
- [x] `docs/README.md` — единый индекс документации (начало работы, how-to, reference,
протоколы, теория/research) + правила ведения: русский язык, один документ = одна
задача, reference правится в том же PR, что и код, плоская структура, kebab-case.
- [x] `README.md` — двуязычный: русская часть сверху, английская снизу, общий шапка/бейджи/
переключатель языка; структура по практике (что это → как работает → возможности →
требования → quick start → конфиг → плагины → производительность → документация →
разработка → лицензия); TOC, копируемые команды, ссылки на docs/README.md.
- [x] `docs/configuration.md` — полная таблица `[xdp]` (включая `udp_policy`) и покрытие IPv4/IPv6;
`docs/testing.md` — реальные XDP-smoke'и, а не только clang-проверка.
- [x] TUI (ratatui): live-метрики из Prometheus endpoint — готово (src/tui/, 564613b). - [x] TUI (ratatui): live-метрики из Prometheus endpoint — готово (src/tui/, 564613b).
## 2a. Раунд 2026-09-15 — исправлено по итогам ревью ## 2a. Раунд 2026-09-15 — исправлено по итогам ревью
@ -180,7 +202,14 @@ guard/
- [x] **Тесты**: `tests/xdp_ban_v6.rs` (layout ключа `/64` и `/128`, network order); - [x] **Тесты**: `tests/xdp_ban_v6.rs` (layout ключа `/64` и `/128`, network order);
`scripts/xdp_ipv6_smoke.sh` — реальный netns+verifier smoke (без бана pass → с баном `scripts/xdp_ipv6_smoke.sh` — реальный netns+verifier smoke (без бана pass → с баном
blacklist+drop → после снятия снова pass), проверен на ядре 7.3.4. blacklist+drop → после снятия снова pass), проверен на ядре 7.3.4.
- Non-goals (позже): conntrack/throttle/UDP rate-limit (`policy==2`)/RST-challenge для нативного v6 - [x] **UDP rate-limit (`policy==2`) для native v6** (2026-11-15): `udp_rate_limit6` (LRU_HASH,
16-байтный ключ `struct in6_addr`, value `struct throttle_entry`) + `throttle_hit6` в
`universal_filter.c` (та же семантика окна/порога, что у v4); ветка UDP в `native_v6`
теперь `switch (G_UDP_POLICY)`: 1 → DROP, 2 → `throttle_hit6` → DROP при превышении,
иначе PASS. Ringbuf-события для v6 по-прежнему не шлём (ABI `src_ip` u32) — только счётчики.
Проверка: фаза 4 в `scripts/xdp_ipv6_smoke.sh` (патч `.rodata` до загрузки: policy=2,
hits=3 → 3 pass, 3 rate-limit).
- Non-goals (позже): conntrack/throttle/RST-challenge для нативного v6
(нужны 128-битные flow/throttle-ключи); whitelist6 (у `whitelist_map` нет писателя даже для v4); (нужны 128-битные flow/throttle-ключи); whitelist6 (у `whitelist_map` нет писателя даже для v4);
ringbuf-события для v6; unban v6. ringbuf-события для v6; unban v6.
- [x] **Expiry бана из userspace не работал в ядре** (найден и починен 2026-11-15, касался v4 и v6): - [x] **Expiry бана из userspace не работал в ядре** (найден и починен 2026-11-15, касался v4 и v6):
@ -194,6 +223,22 @@ guard/
Теперь минимум считается по протоколу (`sizeof(struct udphdr)` для UDP); регрессия — Теперь минимум считается по протоколу (`sizeof(struct udphdr)` для UDP); регрессия —
«короткая датаграмма» в `scripts/xdp_ipv6_smoke.sh`. TCP-путь не изменился: там по-прежнему «короткая датаграмма» в `scripts/xdp_ipv6_smoke.sh`. TCP-путь не изменился: там по-прежнему
требуется полный `struct tcphdr`. требуется полный `struct tcphdr`.
- [x] **XDP-загрузчик не мог загрузить программу вообще** (найден и починен 2026-11-15).
Три независимых бага, каждый из которых валил `load()` до verifier'а:
1. `.rodata`-раскладка: `build_rodata_image` писал 96-байтный образ в 76-байтную карту
(`EINVAL`) и по неверным смещениям — clang переставляет отдельные `static volatile const`
глобалы (UDP-политика лежала в 4, а не в 49). Теперь в `config.h` один
`struct rampart_config` (layout фиксирован C-структурой + `_Static_assert` на каждый
offset и размер), `XdpGlobals` получил `#[repr(C)]`, образ строится через `offset_of!`,
а `patch_rodata` падает с внятным сообщением при расхождении размера.
2. `build.rs` отслеживал только `universal_filter.c` — правка `config.h`/`common.h` оставляла
стухший объект в `OUT_DIR` (и старое `.rodata`). Теперь `rerun-if-changed` на `xdp/core`
и `xdp/hooks`.
3. `build_ringbuf` искал карту `events_map`, а в C она `events_ringbuf` —
`load()` падал после успешного verifier'а.
Регрессии: `tests/xdp_object_maps.rs` (имена всех карт, которые ищет загрузчик, и
`value_size` `.rodata` == `RODATA_SIZE`, без root) + перезапуск реального бинаря в netns
(attach подтверждён), плюс весь `scripts/xdp_ipv6_smoke.sh`.
## 3. Backlog ## 3. Backlog

View file

@ -15,6 +15,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let dst = out_dir.join("universal_filter.o"); let dst = out_dir.join("universal_filter.o");
println!("cargo:rerun-if-changed={}", src.display()); println!("cargo:rerun-if-changed={}", src.display());
// config.h/common.h/etc. live in these dirs: without tracking them a header
// edit silently keeps a stale object (and a stale .rodata layout).
println!("cargo:rerun-if-changed={}", xdp_dir.join("core").display());
println!("cargo:rerun-if-changed={}", xdp_dir.join("hooks").display());
let host_triple = std::env::var("HOST").unwrap_or_default(); let host_triple = std::env::var("HOST").unwrap_or_default();
let arch = host_triple.split('-').next().unwrap_or(&host_triple); let arch = host_triple.split('-').next().unwrap_or(&host_triple);

66
docs/README.md Normal file
View file

@ -0,0 +1,66 @@
# Документация Rampart
> Индекс всей документации проекта и правила её ведения.
> Точка входа — [README.md](../README.md); текущий статус и планы — [TODO.md](../TODO.md).
---
## 1. С чего начать
| Документ | Когда читать |
|----------|--------------|
| [deployment.md](deployment.md) | Первый деплой edge-ноды и manager'а |
| [configuration.md](configuration.md) | Настройка `config.toml`, секция `[xdp]`, переменные manager'а |
| [runbook.md](runbook.md) | Ежедневная эксплуатация и типовые операции |
## 2. Эксплуатация (how-to)
| Документ | О чём |
|----------|-------|
| [runbook.md](runbook.md) | Метрики, рестарты, снятие банов, аварийные процедуры |
| [troubleshooting.md](troubleshooting.md) | Диагностика типовых проблем |
| [disaster_recovery.md](disaster_recovery.md) | Восстановление после отказа Redis/ноды |
| [testing.md](testing.md) | Гейты, тесты, XDP-smoke на реальном ядре |
## 3. Справочник (reference)
| Документ | О чём |
|----------|-------|
| [configuration.md](configuration.md) | Все поля конфига и значения по умолчанию |
| [api.md](api.md) | HTTP API manager'а: аутентификация, эндпоинты |
| [vds_compatibility.md](vds_compatibility.md) | Ограничения окружений и ядер |
## 4. Протоколы
| Документ | О чём |
|----------|-------|
| [minecraft-java.md](minecraft-java.md) | Minecraft-edge: Paper, PROXY protocol, закрытый backend |
## 5. Теория и исследования
| Раздел | О чём |
|--------|-------|
| [kb/](kb/README.md) | База знаний: анатомия атак, уровни защиты, практика (двуязычная) |
| [research/](research/README.md) | Глубокие разборы: архитектура, eBPF, DDoS, Rust-производительность, конкуренты |
`kb/` отвечает на вопрос «как это работает и как защищаться», `research/` — на вопрос
«какое решение выбрать и почему». Статус проекта не живёт ни там, ни там — только в
[TODO.md](../TODO.md).
---
## 6. Как вести документацию
1. **Язык.** `docs/` — русский. Исключение: [docs/kb/](kb/README.md), где статьи
двуязычные (`## English` / `## Русский`). Комментарии в коде — английский (TODO §0.8).
2. **Один документ = одна задача.** How-to начинается с цели («что получится в конце»),
содержит копируемые команды и заканчивается проверкой результата.
3. **Reference синхронизируется с кодом в том же PR.** Меняешь поле конфига, флаг CLI
или эндпоинт — правишь `configuration.md` / `api.md` там же. Расхождение = баг.
4. **Новый документ** кладётся в подходящую категорию (2–4) и сразу добавляется в эту
таблицу; если он является точкой входа — ссылка добавляется и в корневой README.
5. **Не размножай папки.** Плоская структура `docs/*.md` — норма; подпапка нужна только
для серии документов (`kb/`, `research/`).
6. **Имена файлов** — kebab-case, `.md`, без дат в имени; дата и версия — внутри документа.
7. **Никаких битых ссылок.** Перед коммитом: `grep -o '](\.\?[^)]*)' docs/*.md` и проверь,
что цели существуют.

View file

@ -43,6 +43,18 @@ clickhouse_url = "" # пусто = запись событий вы
[xdp] [xdp]
enabled = false # требует сборки --features xdp, kernel 5.10+ enabled = false # требует сборки --features xdp, kernel 5.10+
interface = "eth0" interface = "eth0"
protected_port_start = 1 # пакеты вне диапазона уходят в XDP_PASS до фильтра
protected_port_end = 65535
udp_policy = "pass" # pass | drop | rate-limit (для IPv4 и IPv6)
udp_rate_hit_count = 100 # порог пакетов в окне при rate-limit
udp_rate_window_ms = 1000 # окно rate-limit
throttle_enabled = true # SYN-throttle (только IPv4)
events_enabled = true # ringbuf-события в userspace (только IPv4)
auto_ban_enabled = false # OPT-IN: баны по событиям ringbuf
auto_ban_duration_secs = 300
auto_ban_conn_drop_fails = 3
syn_challenge_enabled = false # RST-challenge (только IPv4)
challenge_timeout_ms = 3000
[logging] [logging]
level = "info" # trace, debug, info, warn, error level = "info" # trace, debug, info, warn, error
@ -109,6 +121,33 @@ Manager всегда слушает `0.0.0.0:8080`.
clang -O2 -g -target bpf -c xdp/core/universal_filter.c -o /tmp/universal_filter.o clang -O2 -g -target bpf -c xdp/core/universal_filter.c -o /tmp/universal_filter.o
``` ```
Параметры `[xdp]` (значения по умолчанию — в `src/config/sections/platform.rs`):
| Поле | По умолчанию | Что делает |
|------|--------------|------------|
| `enabled` | `false` | Загрузить и приаттачить XDP-программу при старте |
| `interface` | `eth0` | Интерфейс; native XDP, при отказе драйвера — generic (skb) |
| `protected_port_start` / `_end` | `1` / `65535` | Порт-гейт: трафик вне диапазона не фильтруется |
| `udp_policy` | `pass` | `drop` — дропать весь UDP; `rate-limit` — окно на source-IP |
| `udp_rate_hit_count` / `udp_rate_window_ms` | `100` / `1000` | Порог и окно для `rate-limit` |
| `throttle_enabled` | `true` | SYN-throttle + авто-бан по `connection_throttle` |
| `events_enabled` | `true` | Ringbuf-события (rate-limit/conn-drop) в userspace |
| `auto_ban_enabled` | `false` | OPT-IN: баны по событиям ringbuf |
| `auto_ban_duration_secs` | `300` | Длительность авто-бана |
| `auto_ban_conn_drop_fails` | `3` | Порог `conn->fails` для бана по `EVENT_CONN_DROP` |
| `syn_challenge_enabled` | `false` | RST-challenge (Oubliette liveness proof) |
| `challenge_secret_hex` | плейсхолдер | 128-битный hex-секрет challenge |
| `challenge_timeout_ms` | `3000` | TTL pending-challenge |
Покрытие семейств адресов:
- **IPv4**: blacklist, SYN-throttle, conntrack, RST-challenge, ringbuf-события, `udp_policy`
(включая `rate-limit`), prefix-статистика.
- **IPv6**: blacklist (`blacklist6_map`, LPM по `/128` и префиксам), `udp_policy`
(включая `rate-limit` с 128-битным ключом), детект TCP-bypass, prefix-статистика.
Пока нет: conntrack, SYN-throttle, RST-challenge, ringbuf-события и unban для v6 —
для v6 события видны только в счётчиках `stats_map`.
--- ---
*Версия: 2.1 | Октябрь 2026* *Версия: 2.1 | Октябрь 2026*

View file

@ -19,7 +19,6 @@
| [haproxy.md](./haproxy.md) | HAProxy конфиг, mTLS, замена на Rust LB | v0.2 | | [haproxy.md](./haproxy.md) | HAProxy конфиг, mTLS, замена на Rust LB | v0.2 |
| [envoy.md](./envoy.md) | EWMA балансировка, Circuit Breaker, xDS API | v0.5 | | [envoy.md](./envoy.md) | EWMA балансировка, Circuit Breaker, xDS API | v0.5 |
| [observability.md](./observability.md) | Prometheus, OpenTelemetry, ClickHouse, Parca | v0.3 | | [observability.md](./observability.md) | Prometheus, OpenTelemetry, ClickHouse, Parca | v0.3 |
| [minecraft-protocol.md](./minecraft-protocol.md) | Handshake парсинг, VarInt, Forge, fingerprinting | v0.1 |
| [anti-bot.md](./anti-bot.md) | Sonar, challenge системы, AI-обходы, fingerprint | v0.2 | | [anti-bot.md](./anti-bot.md) | Sonar, challenge системы, AI-обходы, fingerprint | v0.2 |
| [benchmark.md](./benchmark.md) | Инструменты, методология, ожидаемые результаты | v0.3 | | [benchmark.md](./benchmark.md) | Инструменты, методология, ожидаемые результаты | v0.3 |
| [security.md](./security.md) | STRIDE, mTLS, Zero Trust, supply chain | v0.2 | | [security.md](./security.md) | STRIDE, mTLS, Zero Trust, supply chain | v0.2 |
@ -32,8 +31,7 @@
``` ```
Хочу написать первую версию (v0.1) Хочу написать первую версию (v0.1)
→ architecture.md + minecraft-protocol.md + ddos.md → architecture.md + ddos.md
Хочу добавить защиту от ботов Хочу добавить защиту от ботов
→ anti-bot.md → anti-bot.md
@ -61,7 +59,6 @@
| [api.md](../api.md) | REST API спецификация | | [api.md](../api.md) | REST API спецификация |
| [testing.md](../testing.md) | Методология тестирования | | [testing.md](../testing.md) | Методология тестирования |
| [troubleshooting.md](../troubleshooting.md) | FAQ | | [troubleshooting.md](../troubleshooting.md) | FAQ |
| [migration.md](../migration.md) | Обновление версий |
--- ---

View file

@ -37,6 +37,19 @@ XDP: smoke-check компиляции BPF-программы:
clang -O2 -g -target bpf -c xdp/core/universal_filter.c -o /tmp/universal_filter.o 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`):
```bash
sudo bash scripts/xdp_ipv6_smoke.sh
```
Поднимает netns + veth, грузит программу через verifier и проверяет: бан IPv6 и IPv4
(включая короткие UDP-датаграммы), снятие бана, истечение TTL по монотонным часам и
`udp_policy = "rate-limit"` для IPv6 (политика патчится в `.rodata` до загрузки).
`scripts/xdp_netns_smoke.sh` дополнительно гоняет реальный бинарь `rampart` end-to-end
(требует `hping3`).
--- ---
## 3. Локальный integration-стенд (Docker) ## 3. Локальный integration-стенд (Docker)

View file

@ -1,17 +1,20 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Функциональный smoke XDP-банов на РЕАЛЬНОМ ядре (netns + veth + verifier). # Functional smoke test of XDP bans on a real kernel (netns + veth + verifier).
# #
# Что проверяет: # What it verifies:
# 1. verifier принимает universal_filter.o; # 1. the verifier accepts universal_filter.o;
# 2. native-IPv6 без бана проходит, с записью /128 в blacklist6_map — дропается; # 2. native IPv6 traffic passes without a ban and is dropped once a /128
# 3. короткая UDP-датаграмма (<20 байт L4) тоже дропается — раньше она уходила # entry exists in blacklist6_map;
# в XDP_PASS мимо blacklist (проверка длины была рассчитана на TCP); # 3. a short UDP datagram (under 20 bytes of L4) is dropped as well; it used
# 4. то же для IPv4 (общий L4-гейт); # to fall through to XDP_PASS past the blacklist because the length check
# 5. expiry: бан с монотонным TTL реально истекает в ядре (раньше userspace # was sized for TCP;
# писал epoch-ns, а C сравнивал с bpf_ktime_get_ns() — бан жил вечно). # 4. the same holds for IPv4, through the shared L4 gate;
# 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().
# #
# Требует root/CAP_BPF+CAP_NET_ADMIN, bpftool, clang, python3. # Requires root/CAP_BPF+CAP_NET_ADMIN, bpftool, clang, python3.
# Запуск: sudo bash scripts/xdp_ipv6_smoke.sh # Run: sudo bash scripts/xdp_ipv6_smoke.sh
set -u set -u
@ -30,6 +33,7 @@ PASS=1
fail() { echo "FAIL: $1"; PASS=0; } fail() { echo "FAIL: $1"; PASS=0; }
ok() { echo "ok: $1"; } ok() { echo "ok: $1"; }
# Detach and remove every artefact, so a rerun starts from a clean state.
cleanup() { cleanup() {
bpftool net detach xdp dev "$DEV0" 2>/dev/null bpftool net detach xdp dev "$DEV0" 2>/dev/null
rm -f "$PIN" "$OBJ" rm -f "$PIN" "$OBJ"
@ -41,11 +45,13 @@ trap cleanup EXIT
[ "$(id -u)" = 0 ] || { echo "нужен root (CAP_BPF+CAP_NET_ADMIN)"; exit 2; } [ "$(id -u)" = 0 ] || { echo "нужен root (CAP_BPF+CAP_NET_ADMIN)"; exit 2; }
cd "$(dirname "$0")/.." || exit 2 cd "$(dirname "$0")/.." || exit 2
# Build the object once; the same binary is reused for every phase below.
clang -O2 -g -target bpf -mcpu=v3 -c xdp/core/universal_filter.c -o "$OBJ" \ 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 \ -Ixdp -Ixdp/core -Ixdp/hooks -I/usr/include/x86_64-linux-gnu \
|| { echo "clang: не собралось"; exit 1; } || { echo "clang: не собралось"; exit 1; }
ok "clang: universal_filter.c собран" ok "clang: universal_filter.c собран"
# Isolated namespace with one veth pair: host side is DEV0, peer is DEV1.
ip netns add "$NS" || { echo "не удалось создать netns"; exit 2; } ip netns add "$NS" || { echo "не удалось создать netns"; exit 2; }
ip link add "$DEV0" type veth peer name "$DEV1" || exit 2 ip link add "$DEV0" type veth peer name "$DEV1" || exit 2
ip link set "$DEV1" netns "$NS" ip link set "$DEV1" netns "$NS"
@ -58,36 +64,43 @@ ip -n "$NS" link set "$DEV1" up
ip -n "$NS" link set lo up ip -n "$NS" link set lo up
ok "netns $NS + veth ($HOST6/$HOST4 <-> $NS6/$NS4)" ok "netns $NS + veth ($HOST6/$HOST4 <-> $NS6/$NS4)"
# Loading through the verifier is itself a check: a rejected program exits here.
bpftool prog load "$OBJ" "$PIN" type xdp || { echo "verifier отверг программу"; exit 1; } bpftool prog load "$OBJ" "$PIN" type xdp || { echo "verifier отверг программу"; exit 1; }
bpftool net attach xdp pinned "$PIN" dev "$DEV0" || exit 1 bpftool net attach xdp pinned "$PIN" dev "$DEV0" || exit 1
ok "verifier принял программу, attach на $DEV0" ok "verifier принял программу, attach на $DEV0"
IDS=$(bpftool prog show pinned "$PIN" | grep -o 'map_ids [0-9,]*' | cut -d' ' -f2 | tr ',' ' ') # Resolve map ids from the pinned program; ids change on every load.
B4="" discover_maps() {
B6="" IDS=$(bpftool prog show pinned "$PIN" | grep -o 'map_ids [0-9,]*' | cut -d' ' -f2 | tr ',' ' ')
ST="" B4=""
for id in $IDS; do B6=""
desc=$(bpftool map show id "$id" 2>/dev/null) ST=""
case "$desc" in for id in $IDS; do
*"name blacklist6_map"*) B6=$id ;; desc=$(bpftool map show id "$id" 2>/dev/null)
*"name blacklist_map"*) B4=$id ;; case "$desc" in
*"name stats_map"*) ST=$id ;; *"name blacklist6_map"*) B6=$id ;;
esac *"name blacklist_map"*) B4=$id ;;
done *"name stats_map"*) ST=$id ;;
[ -n "$B4" ] && [ -n "$B6" ] && [ -n "$ST" ] || { echo "карты не найдены"; exit 1; } esac
done
[ -n "$B4" ] && [ -n "$B6" ] && [ -n "$ST" ]
}
discover_maps || { echo "карты не найдены"; exit 1; }
ok "blacklist_map id=$B4, blacklist6_map id=$B6, stats_map id=$ST" ok "blacklist_map id=$B4, blacklist6_map id=$B6, stats_map id=$ST"
# Ключи LPM: prefixlen (u32 LE) + адрес в network order. # 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" KEY6="80 00 00 00 fd 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02"
KEY4="20 00 00 00 0a 63 00 02" KEY4="20 00 00 00 0a 63 00 02"
send6() { # $1 = размер payload # Send one IPv6 UDP datagram of $1 payload bytes from inside the namespace.
send6() {
ip netns exec "$NS" python3 -c " ip netns exec "$NS" python3 -c "
import socket import socket
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
s.sendto(b'x' * $1, ('$HOST6', $PORT)) s.sendto(b'x' * $1, ('$HOST6', $PORT))
" "
} }
# Same for IPv4.
send4() { send4() {
ip netns exec "$NS" python3 -c " ip netns exec "$NS" python3 -c "
import socket import socket
@ -96,7 +109,7 @@ s.sendto(b'x' * $1, ('$HOST4', $PORT))
" "
} }
# Суммы per-CPU счётчиков (только ненулевые). # Sum the per-CPU counters and print only the non-zero ones.
stats() { stats() {
bpftool -j map dump id "$ST" | python3 -c " bpftool -j map dump id "$ST" | python3 -c "
import json, sys import json, sys
@ -110,9 +123,11 @@ for e in json.load(sys.stdin):
print(' '.join(f'{k}={v}' for k, v in out.items() if v) or 'все нули') print(' '.join(f'{k}={v}' for k, v in out.items() if v) or 'все нули')
" "
} }
# Read a single counter value; empty output means the counter is zero.
metric() { stats | tr ' ' '\n' | sed -n "s/^$1=//p" | head -1; } metric() { stats | tr ' ' '\n' | sed -n "s/^$1=//p" | head -1; }
mono_ns_hex() { # монотонные ns + $1 секунд, 8 байт little-endian # Monotonic now + $1 seconds as 8 little-endian bytes, the kernel's ban TTL format.
mono_ns_hex() {
python3 -c " python3 -c "
import time import time
ns = time.clock_gettime_ns(time.CLOCK_MONOTONIC) + $1 * 1_000_000_000 ns = time.clock_gettime_ns(time.CLOCK_MONOTONIC) + $1 * 1_000_000_000
@ -120,7 +135,7 @@ print(' '.join(f'{b:02x}' for b in ns.to_bytes(8, 'little')))
" "
} }
# ── Фаза 1: IPv6 ── # Phase 1: IPv6 — traffic passes, a ban drops it, removing the ban restores it.
pass0=$(metric pass) pass0=$(metric pass)
for _ in 1 2 3; do send6 100; done for _ in 1 2 3; do send6 100; done
sleep 0.5 sleep 0.5
@ -132,7 +147,7 @@ pass1=$(metric pass)
drop0=$(metric drop) drop0=$(metric drop)
bpftool map update id "$B6" key hex $KEY6 value hex ff ff ff ff ff ff ff ff || fail "v6 map update" bpftool map update id "$B6" key hex $KEY6 value hex ff ff ff ff ff ff ff ff || fail "v6 map update"
for _ in 1 2 3; do send6 100; done for _ in 1 2 3; do send6 100; done
for _ in 1 2 3; do send6 1; done # короткая датаграмма for _ in 1 2 3; do send6 1; done # short datagram
sleep 0.5 sleep 0.5
drop1=$(metric drop) drop1=$(metric drop)
[ "${drop1:-0}" -ge $((${drop0:-0} + 6)) ] \ [ "${drop1:-0}" -ge $((${drop0:-0} + 6)) ] \
@ -148,10 +163,11 @@ pass3=$(metric pass)
&& ok "v6 после снятия бана проходит (pass $pass2 -> $pass3)" \ && ok "v6 после снятия бана проходит (pass $pass2 -> $pass3)" \
|| fail "v6 после снятия бана не проходит ($(stats))" || fail "v6 после снятия бана не проходит ($(stats))"
# ── Фаза 2: IPv4 (общий L4-гейт) ── # Phase 2: IPv4 through the shared L4 gate — only short datagrams, which is
# the min_l4 regression.
drop0=$(metric drop) drop0=$(metric drop)
bpftool map update id "$B4" key hex $KEY4 value hex ff ff ff ff ff ff ff ff || fail "v4 map update" bpftool map update id "$B4" key hex $KEY4 value hex ff ff ff ff ff ff ff ff || fail "v4 map update"
for _ in 1 2 3; do send4 1; done # только короткие — регрессия на min_l4 for _ in 1 2 3; do send4 1; done # short datagrams only — the min_l4 regression
sleep 0.5 sleep 0.5
drop1=$(metric drop) drop1=$(metric drop)
[ "${drop1:-0}" -ge $((${drop0:-0} + 3)) ] \ [ "${drop1:-0}" -ge $((${drop0:-0} + 3)) ] \
@ -159,7 +175,8 @@ drop1=$(metric drop)
|| fail "v4 короткая датаграмма прошла мимо бана ($(stats))" || fail "v4 короткая датаграмма прошла мимо бана ($(stats))"
bpftool map delete id "$B4" key hex $KEY4 || fail "v4 map delete" bpftool map delete id "$B4" key hex $KEY4 || fail "v4 map delete"
# ── Фаза 3: expiry бана (монотонные часы) ── # 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 TTL=2
bpftool map update id "$B6" key hex $KEY6 value hex $(mono_ns_hex $TTL) || fail "expiry update" bpftool map update id "$B6" key hex $KEY6 value hex $(mono_ns_hex $TTL) || fail "expiry update"
drop0=$(metric drop) drop0=$(metric drop)
@ -179,5 +196,47 @@ drop3=$(metric drop); pass3=$(metric pass)
&& ok "бан истёк по монотонным часам (pass $pass2 -> $pass3, drop $drop2 -> $drop3)" \ && ok "бан истёк по монотонным часам (pass $pass2 -> $pass3, drop $drop2 -> $drop3)" \
|| fail "бан не истёк (pass $pass2 -> $pass3, drop $drop2 -> $drop3)" || fail "бан не истёк (pass $pass2 -> $pass3, drop $drop2 -> $drop3)"
[ "$PASS" = 1 ] && echo "PASS: XDP-баны (v4/v6, короткий L4, expiry) работают на живом ядре" || echo "FAIL" # Phase 4: UDP rate-limit (policy=2) for native IPv6.
[ "$PASS" = 1 ] # Policy is a .rodata global and libbpf freezes .rodata after load, so the
# object section is patched before loading. The offsets are pinned by the
# _Static_asserts in xdp/core/config.h: udp_policy @49, udp_hit_count @52.
POBJ="$OBJ.rl"
cp "$OBJ" "$POBJ"
if llvm-objcopy --dump-section .rodata="$POBJ.rodata" "$POBJ" \
&& python3 - "$POBJ.rodata" <<'PY' \
&& llvm-objcopy --update-section .rodata="$POBJ.rodata" "$POBJ"
import sys
path = sys.argv[1]
img = bytearray(open(path, "rb").read())
assert len(img) >= 56, f"unexpected .rodata size {len(img)}"
img[49] = 2 # G_UDP_POLICY = rate-limit
img[52:56] = (3).to_bytes(4, "little") # G_UDP_HIT_COUNT = 3 (fast trigger)
open(path, "wb").write(img)
PY
then
# Reload with the patched policy; map ids are invalidated by the reload.
ip link set "$DEV0" xdp off 2>/dev/null
rm -f "$PIN"
if bpftool prog load "$POBJ" "$PIN" type xdp \
&& bpftool net attach xdp pinned "$PIN" dev "$DEV0"; then
if discover_maps; then
rl0=$(metric rate); pass0=$(metric pass)
for _ in 1 2 3 4 5 6; do send6 100; done
sleep 0.3
rl1=$(metric rate); pass1=$(metric pass)
[ "${rl1:-0}" -gt "${rl0:-0}" ] && [ "${pass1:-0}" -gt "${pass0:-0}" ] \
&& ok "v6 UDP rate-limit policy=2 (rate $rl0 -> $rl1, pass $pass0 -> $pass1)" \
|| fail "v6 UDP rate-limit не срабатывает ($(stats))"
else
fail "карты не найдены после перезагрузки с policy=2"
fi
else
fail "объект с policy=2 не загрузился"
fi
rm -f "$POBJ" "$POBJ.rodata"
else
fail "не удалось пропатчить .rodata (policy=2)"
fi
[ "$PASS" = 1 ] && echo "PASS: XDP-баны и UDP rate-limit (v4/v6) работают на живом ядре" || echo "FAIL"
[ "$PASS" = 1 ]

View file

@ -1,18 +1,20 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# netns+veth smoke-тест XDP-пути на РЕАЛЬНОМ ядре (вывод №7 конкурентного анализа). # netns + veth smoke test of the XDP path on a real kernel (finding #7 of the
# concurrency analysis).
# #
# Проверяет то, что невозможно проверить в контейнере CI без CAP_BPF: # Covers what cannot be checked in a CI container without CAP_BPF:
# 1. verifier принимает universal_filter.o (загрузка через libbpf); # 1. the verifier accepts universal_filter.o (loaded through libbpf);
# 2. attach на живом интерфейсе в netns, native-режим; # 2. attach on a live interface inside a netns, native mode;
# 3. легитимный HTTP проксируется; # 3. legitimate HTTP is proxied;
# 4. SYN-флуд порождает ringbuf-события -> opt-in auto-ban работает; # 4. a SYN flood produces ringbuf events, so opt-in auto-ban works;
# 5. по завершении бана трафик восстанавливается (expiry); # 5. traffic recovers once the ban expires;
# 6. после SIGTERM XDP-ПРОГРАММА РЕАЛЬНО ОТВЯЗАНА (регрессия на bug fd=-1). # 6. after SIGTERM the XDP program is really detached (regression on the
# fd=-1 bug).
# #
# Запуск: на хосте с root/CAP_BPF (VDS или VM-раннер CI), не в контейнере: # Run: on a host with root/CAP_BPF (VDS or a VM CI runner), not in a container:
# BIN=./target/release/rampart bash scripts/xdp_netns_smoke.sh # BIN=./target/release/rampart bash scripts/xdp_netns_smoke.sh
# #
# Требования: iproute2, bpftool, hping3, python3 (http.server), curl. # Requires: iproute2, bpftool, hping3, python3 (http.server), curl.
set -u set -u
@ -32,6 +34,7 @@ PASS=1
fail() { echo "FAIL: $1"; PASS=0; } fail() { echo "FAIL: $1"; PASS=0; }
ok() { echo "ok: $1"; } ok() { echo "ok: $1"; }
# Kill both processes and drop the namespace, whatever the exit path was.
cleanup() { cleanup() {
[ -n "$RAMPID" ] && kill -9 "$RAMPID" 2>/dev/null [ -n "$RAMPID" ] && kill -9 "$RAMPID" 2>/dev/null
[ -n "$SRVPID" ] && kill -9 "$SRVPID" 2>/dev/null [ -n "$SRVPID" ] && kill -9 "$SRVPID" 2>/dev/null
@ -43,7 +46,8 @@ trap cleanup EXIT
[ "$(id -u)" = 0 ] || { echo "нужен root (CAP_BPF+CAP_NET_ADMIN)"; exit 2; } [ "$(id -u)" = 0 ] || { echo "нужен root (CAP_BPF+CAP_NET_ADMIN)"; exit 2; }
[ -x "$BIN" ] || { echo "бинарь не найден: $BIN"; exit 2; } [ -x "$BIN" ] || { echo "бинарь не найден: $BIN"; exit 2; }
# --- 1. netns + veth: весь тест изолирован, прод-трафик не затрагивается --- # Phase 1: netns plus veth, so the whole test is isolated and production
# traffic is never touched.
ip netns del "$NS" 2>/dev/null ip netns del "$NS" 2>/dev/null
ip netns add "$NS" || { echo "не удалось создать netns"; exit 2; } ip netns add "$NS" || { echo "не удалось создать netns"; exit 2; }
ip link add rth0 type veth peer name rtap ip link add rth0 type veth peer name rtap
@ -54,7 +58,8 @@ ip -n "$NS" link set rtap up
ip -n "$NS" link set lo up ip -n "$NS" link set lo up
ok "netns $NS + veth подняты" ok "netns $NS + veth подняты"
# --- 2. конфиг edge: узкий защищённый диапазон, автобан включён (иначе нечего тестить) --- # Phase 2: edge config. The protected range is a single port and auto-ban is
# on, otherwise there is nothing to observe.
cat > "$WORK/edge.toml" <<EOF cat > "$WORK/edge.toml" <<EOF
[bind] [bind]
address = "$EDGE_IP" address = "$EDGE_IP"
@ -94,13 +99,13 @@ format = "text"
enabled = false enabled = false
EOF EOF
# --- 3. origin на host-половине veth --- # Phase 3: origin server on the host half of the veth pair.
echo "<html><body>rampart-smoke-origin</body></html>" > "$WORK/index.html" echo "<html><body>rampart-smoke-origin</body></html>" > "$WORK/index.html"
python3 -m http.server "$ORIGIN_PORT" --bind "$HOST_IP" -d "$WORK" >/dev/null 2>&1 & python3 -m http.server "$ORIGIN_PORT" --bind "$HOST_IP" -d "$WORK" >/dev/null 2>&1 &
SRVPID=$! SRVPID=$!
sleep 0.5 sleep 0.5
# --- 4. старт edge внутри netns, ожидание attach --- # Phase 4: start edge inside the namespace and wait for the attach log line.
RUST_LOG=rampart=debug RAMPART_CONFIG="$WORK/edge.toml" \ RUST_LOG=rampart=debug RAMPART_CONFIG="$WORK/edge.toml" \
ip netns exec "$NS" "$BIN" > "$WORK/rampart.log" 2>&1 & ip netns exec "$NS" "$BIN" > "$WORK/rampart.log" 2>&1 &
RAMPID=$! RAMPID=$!
@ -116,8 +121,8 @@ else
fail "XDP не аттачнулся; лог:"; sed -n '1,30p' "$WORK/rampart.log"; exit 1 fail "XDP не аттачнулся; лог:"; sed -n '1,30p' "$WORK/rampart.log"; exit 1
fi fi
# Режим attach: native ожидаем на veth, но fallback на generic — штатный # Attach mode: native is expected on veth, but generic is a normal fallback in
# путь лестницы в load(); сверяем с честным логом режима от rampart. # the load() ladder, so compare against the mode rampart actually reports.
if ip -n "$NS" link show rtap | grep -qE "xdp( |$)"; then if ip -n "$NS" link show rtap | grep -qE "xdp( |$)"; then
ok "attach native (ip link: xdp)" ok "attach native (ip link: xdp)"
elif ip -n "$NS" link show rtap | grep -q "xdpgeneric"; then elif ip -n "$NS" link show rtap | grep -q "xdpgeneric"; then
@ -127,13 +132,13 @@ else
fi fi
grep -oE "mode: [a-z ()]+" "$WORK/rampart.log" | tail -1 grep -oE "mode: [a-z ()]+" "$WORK/rampart.log" | tail -1
# --- 5. легитимный HTTP проходит прокси --- # Phase 5: a legitimate HTTP request must reach the origin through the proxy.
BODY=$(curl -s --max-time 5 "http://$EDGE_IP:$EDGE_PORT/" || true) BODY=$(curl -s --max-time 5 "http://$EDGE_IP:$EDGE_PORT/" || true)
echo "$BODY" | grep -q "rampart-smoke-origin" \ echo "$BODY" | grep -q "rampart-smoke-origin" \
&& ok "легитимный HTTP проксируется" \ && ok "легитимный HTTP проксируется" \
|| fail "легитимный HTTP не дошёл до origin" || fail "легитимный HTTP не дошёл до origin"
# --- 6. SYN-флуд -> throttle -> ringbuf events -> auto-ban --- # Phase 6: SYN flood, then throttle, ringbuf events and auto-ban.
hping3 -S -p "$EDGE_PORT" -c 4000 -i u200 "$EDGE_IP" >/dev/null 2>&1 || true hping3 -S -p "$EDGE_PORT" -c 4000 -i u200 "$EDGE_IP" >/dev/null 2>&1 || true
sleep 3 sleep 3
grep -q "xdp event" "$WORK/rampart.log" \ grep -q "xdp event" "$WORK/rampart.log" \
@ -149,20 +154,21 @@ BANS=$(ip netns exec "$NS" curl -s --max-time 2 "http://127.0.0.1:$METRICS_PORT/
[ "${BANS:-0}" != "0" ] && ok "метрика rampart_xdp_autobans_total=$BANS" \ [ "${BANS:-0}" != "0" ] && ok "метрика rampart_xdp_autobans_total=$BANS" \
|| fail "метрика autobans пуста" || fail "метрика autobans пуста"
# забаненный источник отклоняется до истечения 5с # A banned source is refused while the ban is active.
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 2 "http://$EDGE_IP:$EDGE_PORT/" || echo "err") HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 2 "http://$EDGE_IP:$EDGE_PORT/" || echo "err")
[ "$HTTP_CODE" = "err" ] || [ "$HTTP_CODE" = "000" ] \ [ "$HTTP_CODE" = "err" ] || [ "$HTTP_CODE" = "000" ] \
&& ok "забаненный клиент отклонён (http=$HTTP_CODE)" \ && ok "забаненный клиент отклонён (http=$HTTP_CODE)" \
|| fail "забаненный клиент получил ответ ($HTTP_CODE)" || fail "забаненный клиент получил ответ ($HTTP_CODE)"
# --- 7. expiry: через 7с (> ban 5s) трафик возвращается --- # Phase 7: expiry. After 7s (ban is 5s) traffic must come back on its own.
sleep 7 sleep 7
BODY=$(curl -s --max-time 5 "http://$EDGE_IP:$EDGE_PORT/" || true) BODY=$(curl -s --max-time 5 "http://$EDGE_IP:$EDGE_PORT/" || true)
echo "$BODY" | grep -q "rampart-smoke-origin" \ echo "$BODY" | grep -q "rampart-smoke-origin" \
&& ok "бан истёк, легитимный трафик восстановлен" \ && ok "бан истёк, легитимный трафик восстановлен" \
|| fail "после expiry трафик не восстановился" || fail "после expiry трафик не восстановился"
# --- 8. ГРЕЙСФУЛ СТОП -> ПРОГРАММА ОТВЯЗАНА (регрессия на borrow_raw(-1)) --- # Phase 8: graceful stop must leave no program behind (regression on
# borrow_raw(-1) during detach).
kill -TERM "$RAMPID" kill -TERM "$RAMPID"
wait "$RAMPID"; RC=$? wait "$RAMPID"; RC=$?
RAMPID="" RAMPID=""
@ -176,7 +182,7 @@ else
ok "XDP-программа реально отвязана после SIGTERM" ok "XDP-программа реально отвязана после SIGTERM"
fi fi
# --- итог --- # Summary: exit code drives CI, the log excerpt makes a failure diagnosable.
echo echo
if [ "$PASS" = 1 ]; then if [ "$PASS" = 1 ]; then
echo "PASS — xdp netns smoke ($(uname -r))" echo "PASS — xdp netns smoke ($(uname -r))"

View file

@ -1,4 +1,4 @@
//! Wiring-логика edge-демона: сборка сервисов и главный цикл запуска. //! Edge daemon wiring: service construction and the main run loop.
pub mod runtime; pub mod runtime;
pub mod services; pub mod services;

View file

@ -1,4 +1,5 @@
//! Runtime edge-демона: сборка компонентов, фоновые задачи и запуск listener. //! Edge daemon runtime: component assembly, background tasks and listener
//! startup.
use crate::config::Config; use crate::config::Config;
use crate::engine::challenge::DifficultyAdjuster; use crate::engine::challenge::DifficultyAdjuster;
@ -32,12 +33,12 @@ fn attack_status_value(status: AttackStatus) -> i64 {
} }
} }
/// Точка входа edge-демона (`rampart`): то, что делал `main` бинаря. /// Entry point of the edge daemon (`rampart`).
/// ///
/// Возвращает [`RunExit`] — выбор кода и самого завершения делает бинарь. /// Returns [`RunExit`]; the binary decides whether and how the process ends.
/// ///
/// # Errors /// # Errors
/// Ошибки старта: нечитаемый конфиг, пустой реестр протоколов, сбой listener. /// Startup failures: unreadable config, empty protocol registry, listener error.
pub async fn run() -> anyhow::Result<RunExit> { pub async fn run() -> anyhow::Result<RunExit> {
tracing_subscriber::fmt() tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env().add_directive("rampart=info".parse()?)) .with_env_filter(EnvFilter::from_default_env().add_directive("rampart=info".parse()?))
@ -163,7 +164,7 @@ pub async fn run() -> anyhow::Result<RunExit> {
let status = det.lock().expect("detector lock poisoned").analyze(pps, cps); let status = det.lock().expect("detector lock poisoned").analyze(pps, cps);
metrics::ATTACK_STATUS.set(attack_status_value(status)); metrics::ATTACK_STATUS.set(attack_status_value(status));
if let Some(alert) = alert_dispatcher.on_status(status) { if let Some(alert) = alert_dispatcher.on_status(status) {
// Дедупликация: алерт только на переходе состояния атаки. // Deduplication: an alert is emitted only on an attack state transition.
metrics::INTEL_ALERTS_TOTAL.inc(); metrics::INTEL_ALERTS_TOTAL.inc();
tracing::warn!(pps, cps, "{alert}"); tracing::warn!(pps, cps, "{alert}");
push_attack_event(&ch, pps).await; push_attack_event(&ch, pps).await;
@ -208,8 +209,8 @@ pub async fn run() -> anyhow::Result<RunExit> {
result?; result?;
Ok(RunExit::Ok) Ok(RunExit::Ok)
} }
// Drain-таймаут сработал: возвращаем сигнал бинарю завершить процесс // The drain timeout fired: hand the signal back so the binary can end the
// немедленно, как это делал прежний `process::exit(0)`. // process immediately, replacing the former `process::exit(0)`.
_ = drain_rx => Ok(RunExit::DrainTimeout), _ = drain_rx => Ok(RunExit::DrainTimeout),
} }
} }

View file

@ -1,4 +1,5 @@
//! Сервисы edge-демона: реестр протоколов, whitelist, XDP и subnet-трекер. //! Edge daemon services: protocol registry, whitelist, XDP and the subnet
//! tracker.
use crate::config::Config; use crate::config::Config;
use crate::engine::subnet::tracker::SubnetTracker; use crate::engine::subnet::tracker::SubnetTracker;
@ -13,11 +14,11 @@ use std::sync::Arc;
use std::sync::Mutex; use std::sync::Mutex;
use tokio::sync::watch; use tokio::sync::watch;
/// Собирает реестр протоколов из скомпилированных реализаций. /// Builds the protocol registry from the compiled handlers.
/// ///
/// Обработчики поставляются фичами: `protocol-http` регистрирует /// Handlers are supplied by features: `protocol-http` registers the HTTP/1.1
/// HTTP/1.1-обработчик с политикой из секции `[protocol.http]`. /// handler with the policy from `[protocol.http]`. External crates register
/// Внешние крейты регистрируют свои обработчики в этом же месте. /// their handlers at the same point.
pub(crate) fn build_registry(config: &Config) -> ProtocolRegistry { pub(crate) fn build_registry(config: &Config) -> ProtocolRegistry {
#[cfg(feature = "protocol-minecraft")] #[cfg(feature = "protocol-minecraft")]
if config.protocol.minecraft.enabled { if config.protocol.minecraft.enabled {
@ -115,8 +116,8 @@ pub(crate) fn start_xdp(
Ok(None) Ok(None)
} }
/// Юзерспейс-агрегатор префиксов: активен, когда detect.prefix включён, /// Userspace prefix aggregator: active when `detect.prefix` is enabled and the
/// а XDP-путь не работает (не собран или выключен в конфиге). /// XDP path does not run (not compiled in or disabled in the config).
pub(crate) fn start_subnet_tracker(config: &Config) -> Option<Arc<SubnetTracker>> { pub(crate) fn start_subnet_tracker(config: &Config) -> Option<Arc<SubnetTracker>> {
let xdp_active = cfg!(feature = "xdp") && config.xdp.enabled; let xdp_active = cfg!(feature = "xdp") && config.xdp.enabled;
if config.detect.prefix.enabled && !xdp_active { if config.detect.prefix.enabled && !xdp_active {
@ -131,11 +132,12 @@ pub(crate) fn start_subnet_tracker(config: &Config) -> Option<Arc<SubnetTracker>
} }
} }
/// Store-фичи проверяются на старте edge-демона: конфиг, запрашивающий redis, /// Validates store features at edge startup: a config that asks for redis in a
/// в бинаре без `store-redis` должен упасть сразу, а не молча потерять /// binary without `store-redis` must fail immediately instead of silently losing
/// blacklist-sync (sync-задача в runtime.rs живёт под тем же cfg). /// blacklist sync (the sync task in `runtime.rs` lives behind the same cfg).
/// Точка вызова — `build_whitelist`: ближайший `?`-хук, принимающий конфиг ///
/// до бинда listener'а (сам runtime.rs вне правок этой задачи). /// Called from `build_whitelist`, the closest `?` hook that receives the config
/// before the listener binds.
fn ensure_store_features(config: &Config) -> anyhow::Result<()> { fn ensure_store_features(config: &Config) -> anyhow::Result<()> {
#[cfg(not(feature = "store-redis"))] #[cfg(not(feature = "store-redis"))]
if config.store.redis_url.as_deref().is_some_and(|url| !url.is_empty()) { if config.store.redis_url.as_deref().is_some_and(|url| !url.is_empty()) {
@ -146,6 +148,11 @@ fn ensure_store_features(config: &Config) -> anyhow::Result<()> {
Ok(()) Ok(())
} }
/// Parses `whitelist` entries into a shared address set.
///
/// # Errors
/// Fails on an invalid entry or when the config requires store features that are
/// not compiled in.
pub(crate) fn build_whitelist(config: &Config) -> anyhow::Result<Arc<HashSet<IpAddr>>> { pub(crate) fn build_whitelist(config: &Config) -> anyhow::Result<Arc<HashSet<IpAddr>>> {
ensure_store_features(config)?; ensure_store_features(config)?;
let mut set = HashSet::with_capacity(config.whitelist.len()); let mut set = HashSet::with_capacity(config.whitelist.len());
@ -191,10 +198,10 @@ mod tests {
assert!(ensure_store_features(&config_with_redis()).is_ok()); assert!(ensure_store_features(&config_with_redis()).is_ok());
} }
/// Wiring-тасовка XDP auto-ban: `start_xdp` обязан принимать `Arc<Blacklist>` /// XDP auto-ban wiring: `start_xdp` must accept the `Arc<Blacklist>` and, with
/// (т.е. существовать в сигнатуре с blacklist) и при выключенном `[xdp]` /// `[xdp]` disabled, touch neither the kernel nor the blacklist. The
/// не трогать ни ядро, ни blacklist. Порядок `set_autoban` -> `load()` /// `set_autoban` -> `load()` order inside the enabled branch cannot be checked
/// внутри enabled-ветки без ядра непроверяем — см. комментарий на месте вызова. /// without a kernel.
#[test] #[test]
fn start_xdp_accepts_blacklist_and_skips_kernel_when_disabled() { fn start_xdp_accepts_blacklist_and_skips_kernel_when_disabled() {
let (_tx, rx) = watch::channel(false); let (_tx, rx) = watch::channel(false);

View file

@ -1,23 +1,23 @@
//! Shutdown-drain машина edge-демона: сигнал, drain-таймер и код завершения. //! Edge daemon shutdown drain: signal handling, drain timer and exit code.
use std::time::Duration; use std::time::Duration;
use tokio::sync::oneshot; use tokio::sync::oneshot;
use tokio::sync::watch; use tokio::sync::watch;
/// Результат завершения демона. Код выхода вычисляется здесь, но сам /// Daemon exit outcome. The exit code is computed here, but `process::exit` is
/// `process::exit` вызывается только в точке входа бинаря (`src/bin/rampart.rs`), /// only called from the binary entry point (`src/bin/rampart.rs`), which keeps
/// поэтому библиотечный код остаётся свободным от lint `exit`. /// the library free of the `exit` lint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunExit { pub enum RunExit {
/// Listener отработал штатно: drain уложился в таймаут. /// The listener finished cleanly: the drain fit into the timeout.
Ok, Ok,
/// Истёк drain-таймаут: бинарь обязан завершить процесс немедленно /// The drain timeout expired: the binary must terminate the process immediately
/// (замена прежнему `process::exit(0)` внутри shutdown-таймера). /// (replaces the former `process::exit(0)` inside the shutdown timer).
DrainTimeout, DrainTimeout,
} }
impl RunExit { impl RunExit {
/// Код завершения процесса для данного результата. /// Process exit code for this outcome.
#[must_use] #[must_use]
pub const fn code(self) -> i32 { pub const fn code(self) -> i32 {
match self { match self {
@ -27,11 +27,11 @@ impl RunExit {
} }
} }
/// Ставит фоновую shutdown-задачу. /// Spawns the background shutdown task.
/// ///
/// shutdown-таймер обязан завершить процесс: сам `process::exit` вынесен в /// The timer must end the process, but `process::exit` now lives in the binary,
/// бинарь, а здесь мы лишь уведомляем `run` об истечении drain-таймаута через /// so this only reports the drain timeout to `run` over a oneshot channel. The
/// oneshot-канал. Логи и тайминг (5s после сигнала) сохранены без изменений. /// process is given five seconds to drain after the signal.
pub(crate) fn spawn_shutdown_drain(shutdown_tx: watch::Sender<bool>, drain_tx: oneshot::Sender<()>) { pub(crate) fn spawn_shutdown_drain(shutdown_tx: watch::Sender<bool>, drain_tx: oneshot::Sender<()>) {
tokio::spawn(async move { tokio::spawn(async move {
wait_for_signal().await; wait_for_signal().await;
@ -60,7 +60,7 @@ mod tests {
#[test] #[test]
fn run_exit_codes_match_previous_process_exit() { fn run_exit_codes_match_previous_process_exit() {
// Штатный путь и прежний drain-timeout (`process::exit(0)`) завершались с кодом 0. // 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::Ok.code(), 0);
assert_eq!(RunExit::DrainTimeout.code(), 0); assert_eq!(RunExit::DrainTimeout.code(), 0);
} }

View file

@ -1,3 +1,5 @@
//! Command-line client for the Rampart manager API.
#![allow(clippy::print_stdout, clippy::print_stderr)] #![allow(clippy::print_stdout, clippy::print_stderr)]
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};

View file

@ -1,3 +1,5 @@
//! Rampart manager daemon: HTTP API in front of the redis state store.
use axum::{ use axum::{
Router, Router,
http::HeaderValue, http::HeaderValue,
@ -18,8 +20,8 @@ async fn main() -> anyhow::Result<()> {
.with_env_filter(EnvFilter::from_default_env().add_directive("rampart=info".parse()?)) .with_env_filter(EnvFilter::from_default_env().add_directive("rampart=info".parse()?))
.init(); .init();
// Manager живёт исключительно на redis-хранилище: без фичи стартовать // The manager lives exclusively on the redis store: without the feature there
// нечего — fail-fast вместо полумёртвого API (features additive, TODO SOLID D). // is nothing to start, so fail fast instead of serving a half-dead API.
if !cfg!(feature = "store-redis") { if !cfg!(feature = "store-redis") {
anyhow::bail!("rampart-manager requires a redis state store: built without store-redis feature"); anyhow::bail!("rampart-manager requires a redis state store: built without store-redis feature");
} }
@ -61,8 +63,8 @@ async fn main() -> anyhow::Result<()> {
.route("/api/v1/health", get(api::inventory::health::health_check)) .route("/api/v1/health", get(api::inventory::health::health_check))
.route("/api/v1/auth/login", post(api::auth::login)); .route("/api/v1/auth/login", post(api::auth::login));
// Redis-зависимые маршруты существуют только вместе с фичей; сам manager // Redis-backed routes only exist together with the feature; the manager bails
// без неё bail'ит выше, поэтому 501-заглушки были бы недостижимым кодом. // out above without it, so 501 stubs here would be unreachable code.
let protected = Router::new(); let protected = Router::new();
#[cfg(feature = "store-redis")] #[cfg(feature = "store-redis")]
let protected = protected let protected = protected

View file

@ -1,4 +1,4 @@
//! `rampart-tui` — интерактивный терминальный дашборд live-метрик Rampart. //! `rampart-tui` is an interactive terminal dashboard for live Rampart metrics.
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
@ -21,7 +21,7 @@ struct Cli {
/// URL Prometheus metrics endpoint /// URL Prometheus metrics endpoint
#[arg(long, default_value = "http://127.0.0.1:9090/metrics")] #[arg(long, default_value = "http://127.0.0.1:9090/metrics")]
url: String, url: String,
/// Период опроса, секунды /// Scrape interval in seconds
#[arg(long, default_value_t = 1)] #[arg(long, default_value_t = 1)]
refresh_secs: u64, refresh_secs: u64,
} }

View file

@ -1,11 +1,13 @@
//! Edge daemon entry point; all work is delegated to [`rampart::app::run`].
use rampart::app::{self, RunExit}; use rampart::app::{self, RunExit};
#[tokio::main] #[tokio::main]
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
match app::run().await? { match app::run().await? {
// Штатное завершение listener: управление возвращается tokio-рантайму. // Clean listener shutdown: control returns to the tokio runtime.
RunExit::Ok => Ok(()), RunExit::Ok => Ok(()),
// Drain-таймаут: бинарь — единственное место, где допустим process::exit. // Drain timeout: the binary is the only place where process::exit is allowed.
exit => std::process::exit(exit.code()), exit => std::process::exit(exit.code()),
} }
} }

View file

@ -1,3 +1,5 @@
//! `blacklist` subcommands: manage the manager blacklist over its HTTP API.
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize; use serde::Serialize;

View file

@ -1,3 +1,6 @@
//! `config` subcommand: prints configuration usage; lookups and updates are not
//! implemented yet.
pub async fn run(key: Option<String>, value: Option<String>) -> anyhow::Result<()> { pub async fn run(key: Option<String>, value: Option<String>) -> anyhow::Result<()> {
match (key, value) { match (key, value) {
(Some(_), Some(_)) => { (Some(_), Some(_)) => {

View file

@ -1,7 +1,9 @@
//! `doctor` subcommand: environment, manager API and XDP diagnostics.
use crate::xdp::{EnvironmentReport, FilesystemProbe, SystemProbe}; use crate::xdp::{EnvironmentReport, FilesystemProbe, SystemProbe};
/// Ищет интерфейс с маршрутом по умолчанию в /proc/net/route /// Finds the interface that owns the default route in `/proc/net/route`
/// (destination == 00000000). Работает без root. /// (destination `00000000`). Works without root.
fn default_route_interface(probe: &impl SystemProbe) -> Option<String> { fn default_route_interface(probe: &impl SystemProbe) -> Option<String> {
let routes = probe.read_file("/proc/net/route").ok()?; let routes = probe.read_file("/proc/net/route").ok()?;
routes.lines().skip(1).find_map(|line| { routes.lines().skip(1).find_map(|line| {
@ -10,7 +12,7 @@ fn default_route_interface(probe: &impl SystemProbe) -> Option<String> {
}) })
} }
/// Подсекция network/XDP: что видно окружению без root. /// Network/XDP section: what the environment exposes without root.
fn print_network_section(all_ok: &mut bool) { fn print_network_section(all_ok: &mut bool) {
println!("\nNetwork / XDP"); println!("\nNetwork / XDP");
println!("-------------"); println!("-------------");
@ -57,6 +59,7 @@ fn print_network_section(all_ok: &mut bool) {
} }
} }
/// Runs every diagnostic and prints the report.
pub async fn run() -> anyhow::Result<()> { pub async fn run() -> anyhow::Result<()> {
println!("Rampart Diagnostics"); println!("Rampart Diagnostics");
println!("=====================\n"); println!("=====================\n");

View file

@ -1,3 +1,5 @@
//! Subcommand implementations for the Rampart CLI.
pub mod blacklist; pub mod blacklist;
pub mod config; pub mod config;
pub mod doctor; pub mod doctor;

View file

@ -1,3 +1,9 @@
//! `drain` subcommand: gracefully drain a node.
/// Drains `node` gracefully.
///
/// # Errors
/// Always fails: draining is not implemented yet.
pub async fn run(node: &str) -> anyhow::Result<()> { pub async fn run(node: &str) -> anyhow::Result<()> {
anyhow::bail!("graceful drain is not implemented for node {node}") anyhow::bail!("graceful drain is not implemented for node {node}")
} }

View file

@ -1,7 +1,17 @@
//! `emergency` subcommand: switch the edge policy into or out of emergency mode.
/// Switches emergency mode on.
///
/// # Errors
/// Always fails: emergency mode is not implemented yet.
pub async fn enable() -> anyhow::Result<()> { pub async fn enable() -> anyhow::Result<()> {
anyhow::bail!("emergency mode is not implemented; change the edge policy and restart Rampart") anyhow::bail!("emergency mode is not implemented; change the edge policy and restart Rampart")
} }
/// Switches emergency mode off.
///
/// # Errors
/// Always fails: emergency mode is not implemented yet.
pub async fn disable() -> anyhow::Result<()> { pub async fn disable() -> anyhow::Result<()> {
anyhow::bail!("emergency mode is not implemented; change the edge policy and restart Rampart") anyhow::bail!("emergency mode is not implemented; change the edge policy and restart Rampart")
} }

View file

@ -1,4 +1,4 @@
//! CLI-команды управления edge-узлами: статус, drain, аварийный режим. //! Edge node management commands: status, drain and emergency mode.
pub mod drain; pub mod drain;
pub mod emergency; pub mod emergency;
pub mod status; pub mod status;

View file

@ -1,3 +1,5 @@
//! `status` subcommand: print the manager health summary.
pub async fn run() -> anyhow::Result<()> { pub async fn run() -> anyhow::Result<()> {
println!("Rampart Status"); println!("Rampart Status");
println!("================\n"); println!("================\n");

View file

@ -1,3 +1,3 @@
//! CLI-команды для bin/rampart-cli. //! CLI commands used by `bin/rampart-cli`.
#[allow(clippy::print_stdout, clippy::print_stderr)] #[allow(clippy::print_stdout, clippy::print_stderr)]
pub mod commands; pub mod commands;

View file

@ -1,4 +1,7 @@
//! Единый конфиг платформы Rampart. //! Single configuration of the Rampart platform.
//!
//! Owns the [`Config`] root type, its serde defaults and the semantic validation
//! that runs before the daemon binds a socket.
mod sections; mod sections;
#[cfg(feature = "protocol-http")] #[cfg(feature = "protocol-http")]
@ -50,21 +53,21 @@ pub struct Config {
} }
impl Config { impl Config {
/// Парсит конфиг из TOML-строки и валидирует семантику. /// Parses the config from a TOML string and validates its semantics.
/// ///
/// # Errors /// # Errors
/// Возвращает ошибку при невалидном TOML или нарушении инвариантов /// Fails on invalid TOML or on a violated invariant (empty upstream list,
/// (пустой список upstream-бэкендов, некорректные адреса). /// malformed addresses, unsafe PROXY protocol settings).
pub fn parse_str(contents: &str) -> anyhow::Result<Self> { pub fn parse_str(contents: &str) -> anyhow::Result<Self> {
let config: Config = toml::from_str(contents)?; let config: Config = toml::from_str(contents)?;
config.validate()?; config.validate()?;
Ok(config) Ok(config)
} }
/// Читает и парсит конфиг из файла. /// Reads and parses the config from a file.
/// ///
/// # Errors /// # Errors
/// Возвращает ошибку при невозможности прочитать файл или невалидном содержимом. /// Fails when the file cannot be read or its contents are invalid.
pub fn from_file(path: &str) -> anyhow::Result<Self> { pub fn from_file(path: &str) -> anyhow::Result<Self> {
let contents = fs::read_to_string(path)?; let contents = fs::read_to_string(path)?;
Self::parse_str(&contents) Self::parse_str(&contents)

View file

@ -1,6 +1,8 @@
//! Detection sections (`[detect*]`) and the per-protocol handler policy.
use serde::Deserialize; use serde::Deserialize;
/// Секция `[detect]`: детекторы распределённых атак. /// `[detect]` section: distributed attack detectors.
#[derive(Debug, Clone, Default, Deserialize)] #[derive(Debug, Clone, Default, Deserialize)]
pub struct DetectConfig { pub struct DetectConfig {
#[serde(default)] #[serde(default)]
@ -11,9 +13,10 @@ pub struct DetectConfig {
pub alert: DetectAlertConfig, pub alert: DetectAlertConfig,
} }
/// Секция `[detect.autoban]`: авто-бан источников по репутации и сигналам /// `[detect.autoban]` section: auto-ban sources based on reputation and attack
/// детектора атак. Порог сравнивается со скором [`crate::traffic::reputation::IpReputation`], /// detector signals. The threshold is compared against the
/// TTL берётся из `ban.ban_duration_secs`. /// [`crate::traffic::reputation::IpReputation`] score, the TTL comes from
/// `ban.ban_duration_secs`.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct DetectAutobanConfig { pub struct DetectAutobanConfig {
#[serde(default)] #[serde(default)]
@ -35,15 +38,15 @@ fn default_autoban_reputation_threshold() -> i32 {
-50 -50
} }
/// Секция `[detect.alert]`: webhook-алерты на переходах состояния атаки /// `[detect.alert]` section: webhook alerts on attack state transitions
/// («атака началась» / «атака закончилась»). /// (attack started, attack ended).
#[derive(Debug, Clone, Default, Deserialize)] #[derive(Debug, Clone, Default, Deserialize)]
pub struct DetectAlertConfig { pub struct DetectAlertConfig {
#[serde(default)] #[serde(default)]
pub webhook_url: Option<String>, pub webhook_url: Option<String>,
} }
/// Секция `[detect.prefix]`: subnet-level детектор распределённых атак. /// `[detect.prefix]` section: subnet-level detector for distributed attacks.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct DetectPrefixConfig { pub struct DetectPrefixConfig {
#[serde(default)] #[serde(default)]
@ -77,7 +80,7 @@ fn default_prefix_min_unique_sources() -> u64 {
16 16
} }
/// Секция `[protocol]`: протокольные обработчики (plugin-by-feature). /// `[protocol]` section: protocol handlers, enabled one plugin per feature.
#[cfg(any(feature = "protocol-http", feature = "protocol-minecraft"))] #[cfg(any(feature = "protocol-http", feature = "protocol-minecraft"))]
#[derive(Debug, Clone, Default, Deserialize)] #[derive(Debug, Clone, Default, Deserialize)]
pub struct ProtocolConfig { pub struct ProtocolConfig {
@ -89,6 +92,7 @@ pub struct ProtocolConfig {
pub minecraft: MinecraftProtocolConfig, pub minecraft: MinecraftProtocolConfig,
} }
/// `[protocol.minecraft]` section: Minecraft handshake handler policy.
#[cfg(feature = "protocol-minecraft")] #[cfg(feature = "protocol-minecraft")]
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct MinecraftProtocolConfig { pub struct MinecraftProtocolConfig {
@ -129,7 +133,7 @@ fn default_minecraft_timeout_secs() -> u64 {
5 5
} }
/// Секция `[protocol.http]`: политика HTTP/1.1-обработчика на edge-ноде. /// `[protocol.http]` section: HTTP/1.1 handler policy on the edge node.
#[cfg(feature = "protocol-http")] #[cfg(feature = "protocol-http")]
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct HttpProtocolConfig { pub struct HttpProtocolConfig {

View file

@ -1,7 +1,10 @@
//! Edge sections: bind, backend, workers, limits, ban, PoW and PROXY protocol.
use serde::{Deserialize, Deserializer}; use serde::{Deserialize, Deserializer};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr; use std::str::FromStr;
/// `[bind]` section: listen address and port of the edge node.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct BindConfig { pub struct BindConfig {
#[serde(default = "default_bind_address")] #[serde(default = "default_bind_address")]
@ -26,7 +29,7 @@ fn default_bind_port() -> u16 {
25565 25565
} }
/// Generic upstream-бэкенды (список addr:port) за edge-нодой. /// `[backend]` section: upstream backends (`addr:port`) behind the edge node.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct BackendConfig { pub struct BackendConfig {
#[serde(default = "default_upstreams")] #[serde(default = "default_upstreams")]
@ -45,6 +48,7 @@ fn default_upstreams() -> Vec<String> {
vec!["127.0.0.1:25566".to_string()] vec!["127.0.0.1:25566".to_string()]
} }
/// `[workers]` section: number of accept loops sharing the listen address.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct WorkerConfig { pub struct WorkerConfig {
#[serde(default = "default_worker_count")] #[serde(default = "default_worker_count")]
@ -61,6 +65,7 @@ fn default_worker_count() -> usize {
4 4
} }
/// `[limits]` section: per-IP connection and rate limits.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct LimitsConfig { pub struct LimitsConfig {
#[serde(default = "default_handshake_timeout")] #[serde(default = "default_handshake_timeout")]
@ -97,6 +102,7 @@ fn default_rate_limit_burst() -> f64 {
10.0 10.0
} }
/// `[ban]` section: default ban duration.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct BanConfig { pub struct BanConfig {
#[serde(default = "default_ban_duration")] #[serde(default = "default_ban_duration")]
@ -115,6 +121,7 @@ fn default_ban_duration() -> u64 {
3600 3600
} }
/// `[pow]` section: proof-of-work gate.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct PowConfig { pub struct PowConfig {
#[serde(default)] #[serde(default)]
@ -131,7 +138,6 @@ impl Default for PowConfig {
} }
} }
} }
fn default_pow_difficulty() -> u8 { fn default_pow_difficulty() -> u8 {
4 4
} }
@ -144,25 +150,14 @@ pub struct TrustedProxyCidr {
} }
impl TrustedProxyCidr { impl TrustedProxyCidr {
/// Returns whether `ip` belongs to this network.
#[must_use] #[must_use]
pub fn contains(&self, ip: IpAddr) -> bool { pub fn contains(&self, ip: IpAddr) -> bool {
let mask4 = mask_v4(self.prefix_len);
let mask6 = mask_v6(self.prefix_len);
match (self.network, ip) { match (self.network, ip) {
(IpAddr::V4(network), IpAddr::V4(ip)) => { (IpAddr::V4(network), IpAddr::V4(ip)) => u32::from(network) & mask4 == u32::from(ip) & mask4,
let mask = if self.prefix_len == 0 { (IpAddr::V6(network), IpAddr::V6(ip)) => u128::from(network) & mask6 == u128::from(ip) & mask6,
0
} else {
u32::MAX << (32 - self.prefix_len)
};
u32::from(network) & mask == u32::from(ip) & mask
},
(IpAddr::V6(network), IpAddr::V6(ip)) => {
let mask = if self.prefix_len == 0 {
0
} else {
u128::MAX << (128 - self.prefix_len)
};
u128::from(network) & mask == u128::from(ip) & mask
},
_ => false, _ => false,
} }
} }
@ -213,6 +208,7 @@ fn mask_v6(prefix: u8) -> u128 {
if prefix == 0 { 0 } else { u128::MAX << (128 - prefix) } if prefix == 0 { 0 } else { u128::MAX << (128 - prefix) }
} }
/// `[proxy_protocol]` section: inbound PROXY protocol ingestion.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct ProxyProtocolConfig { pub struct ProxyProtocolConfig {
#[serde(default)] #[serde(default)]

View file

@ -1,4 +1,4 @@
//! Секции единого конфига платформы. //! Sections of the platform config.
mod detect; mod detect;
mod edge; mod edge;

View file

@ -1,5 +1,8 @@
//! Platform sections: store backends, XDP, logging and metrics.
use serde::Deserialize; use serde::Deserialize;
/// `[store]` section: redis and ClickHouse backends.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct StoreConfig { pub struct StoreConfig {
pub redis_url: Option<String>, pub redis_url: Option<String>,
@ -22,6 +25,7 @@ fn default_blacklist_cache_ttl() -> u64 {
300 300
} }
/// `[xdp]` section: kernel-side filter configuration and auto-ban policy.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct XdpConfig { pub struct XdpConfig {
#[serde(default)] #[serde(default)]
@ -32,7 +36,7 @@ pub struct XdpConfig {
pub protected_port_start: u16, pub protected_port_start: u16,
#[serde(default = "default_xdp_port_end")] #[serde(default = "default_xdp_port_end")]
pub protected_port_end: u16, pub protected_port_end: u16,
/// "pass" | "drop" | "rate-limit" → G_UDP_POLICY. /// UDP policy: "pass", "drop" or "rate-limit", mapped to `G_UDP_POLICY`.
#[serde(default = "default_xdp_udp_policy")] #[serde(default = "default_xdp_udp_policy")]
pub udp_policy: String, pub udp_policy: String,
#[serde(default = "default_xdp_udp_hit_count")] #[serde(default = "default_xdp_udp_hit_count")]
@ -41,7 +45,8 @@ pub struct XdpConfig {
pub udp_rate_window_ms: u64, pub udp_rate_window_ms: u64,
#[serde(default)] #[serde(default)]
pub syn_challenge_enabled: bool, pub syn_challenge_enabled: bool,
/// 128-битный hex (16 символов) для G_CHALLENGE_SECRET; None = плейсхолдер из config.h. /// 128-bit hex (16 characters) for `G_CHALLENGE_SECRET`; `None` keeps the
/// placeholder from `config.h`.
#[serde(default)] #[serde(default)]
pub challenge_secret_hex: Option<String>, pub challenge_secret_hex: Option<String>,
#[serde(default = "default_xdp_challenge_timeout_ms")] #[serde(default = "default_xdp_challenge_timeout_ms")]
@ -50,14 +55,15 @@ pub struct XdpConfig {
pub throttle_enabled: bool, pub throttle_enabled: bool,
#[serde(default = "default_xdp_events_enabled")] #[serde(default = "default_xdp_events_enabled")]
pub events_enabled: bool, pub events_enabled: bool,
/// OPT-IN: авто-бан по ringbuf-событиям XDP. По умолчанию выключен /// Opt-in auto-ban driven by XDP ringbuf events. Disabled by default (secure
/// («по умолчанию безопасно»): без него события только логируются. /// by default): without it events are only logged.
#[serde(default)] #[serde(default)]
pub auto_ban_enabled: bool, pub auto_ban_enabled: bool,
/// Длительность авто-бана в секундах (для RATE_LIMIT/CONN_DROP). /// Auto-ban duration in seconds (`RATE_LIMIT` / `CONN_DROP` events).
#[serde(default = "default_xdp_auto_ban_duration_secs")] #[serde(default = "default_xdp_auto_ban_duration_secs")]
pub auto_ban_duration_secs: u64, pub auto_ban_duration_secs: u64,
/// Порог `conn->fails` для авто-бана по EVENT_CONN_DROP (см. universal_filter.c:368). /// `conn->fails` threshold for auto-ban on `EVENT_CONN_DROP`
/// (see `universal_filter.c:368`).
#[serde(default = "default_xdp_auto_ban_conn_drop_fails")] #[serde(default = "default_xdp_auto_ban_conn_drop_fails")]
pub auto_ban_conn_drop_fails: u8, pub auto_ban_conn_drop_fails: u8,
} }
@ -118,6 +124,7 @@ fn default_xdp_auto_ban_conn_drop_fails() -> u8 {
3 3
} }
/// `[logging]` section: log level and format.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct LoggingConfig { pub struct LoggingConfig {
#[serde(default = "default_log_level")] #[serde(default = "default_log_level")]
@ -142,6 +149,7 @@ fn default_log_format() -> String {
"text".to_string() "text".to_string()
} }
/// `[metrics]` section: Prometheus scrape endpoint.
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
pub struct MetricsConfig { pub struct MetricsConfig {
#[serde(default = "default_metrics_enabled")] #[serde(default = "default_metrics_enabled")]

View file

@ -1,8 +1,13 @@
//! Adaptive proof-of-work difficulty driven by the observed connection rate.
use crate::metrics; use crate::metrics;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::time::Instant; use std::time::Instant;
/// Адаптирует сложность PoW к текущему темпу подключений. /// 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]`.
pub struct DifficultyAdjuster { pub struct DifficultyAdjuster {
window: VecDeque<Instant>, window: VecDeque<Instant>,
min: u8, min: u8,
@ -17,6 +22,7 @@ impl Default for DifficultyAdjuster {
} }
impl DifficultyAdjuster { impl DifficultyAdjuster {
/// Creates an adjuster clamped to `min.max(4)` and `max.min(10)`.
#[must_use] #[must_use]
pub fn new(min: u8, max: u8) -> Self { pub fn new(min: u8, max: u8) -> Self {
Self { Self {
@ -27,6 +33,7 @@ impl DifficultyAdjuster {
} }
} }
/// Records one connection and recomputes the difficulty for the window.
pub fn record_connection(&mut self) { pub fn record_connection(&mut self) {
let now = Instant::now(); let now = Instant::now();
self.window.push_back(now); self.window.push_back(now);
@ -50,6 +57,7 @@ impl DifficultyAdjuster {
} }
} }
/// Returns the current difficulty and publishes it to the metrics gauge.
#[must_use] #[must_use]
pub fn current_difficulty(&self) -> u8 { pub fn current_difficulty(&self) -> u8 {
metrics::POW_CURRENT_DIFFICULTY.set(self.current as i64); metrics::POW_CURRENT_DIFFICULTY.set(self.current as i64);

View file

@ -1,5 +1,5 @@
//! Универсальный SHA-256 hashcash: генерация challenge, решатель, //! Universal SHA-256 hashcash: challenge generation, solver, verifier and
//! верификатор и адаптивная сложность. //! adaptive difficulty.
mod difficulty; mod difficulty;
mod pow; mod pow;

View file

@ -10,7 +10,7 @@ const CHALLENGE_TTL_SECS: u64 = 30;
const MAX_NONCE_LEN: usize = 64; const MAX_NONCE_LEN: usize = 64;
const ALLOWED_HEX_PREFIX: [u8; 4] = *b"0123"; const ALLOWED_HEX_PREFIX: [u8; 4] = *b"0123";
/// Активная PoW-задача, выданная одному соединению. /// Active PoW challenge issued to one connection.
pub struct Challenge { pub struct Challenge {
token: [u8; 32], token: [u8; 32],
created_at: Instant, created_at: Instant,
@ -31,8 +31,8 @@ impl Challenge {
} }
} }
/// Challenge с явным токеном — для детерминированных тестов, где /// Builds a challenge with an explicit token.
/// случайный дайджест даёт flaky-исход. /// Intended for deterministic tests, where a random token makes the outcome
#[must_use] #[must_use]
pub fn with_token(token: [u8; 32], difficulty: u8) -> Self { pub fn with_token(token: [u8; 32], difficulty: u8) -> Self {
Self { Self {
@ -53,7 +53,9 @@ impl Challenge {
hex::encode(self.token) hex::encode(self.token)
} }
/// Проверяет nonce и помечает challenge использованным при успехе. /// Verifies `nonce` and marks the challenge as used on success.
///
/// A challenge is single-use and expires after `CHALLENGE_TTL_SECS`.
#[must_use] #[must_use]
pub fn verify(&mut self, nonce: &str) -> bool { pub fn verify(&mut self, nonce: &str) -> bool {
if self.used || self.is_expired() || nonce.len() > MAX_NONCE_LEN { if self.used || self.is_expired() || nonce.len() > MAX_NONCE_LEN {
@ -78,7 +80,7 @@ impl Challenge {
} }
} }
/// Переборный решатель hashcash (для клиентов и тестов). /// Brute-force hashcash solver used by clients and tests.
#[must_use] #[must_use]
pub fn solve(challenge: &str, difficulty: u8) -> Option<String> { pub fn solve(challenge: &str, difficulty: u8) -> Option<String> {
let d = difficulty as usize; let d = difficulty as usize;
@ -99,10 +101,11 @@ pub fn solve(challenge: &str, difficulty: u8) -> Option<String> {
None None
} }
/// Проводит текстовый PoW-gate в потоке: выдаёт challenge и проверяет ответ. /// Runs the textual PoW gate on `stream`: issues a challenge and checks the
/// answer.
/// ///
/// # Errors /// # Errors
/// Возвращает ошибку только при сбое ввода-вывода; неверное решение — `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<bool> { pub async fn enforce(stream: &mut TcpStream, peer_ip: IpAddr, difficulty: u8) -> anyhow::Result<bool> {
if difficulty == 0 { if difficulty == 0 {
tracing::debug!("pow: difficulty 0, skipping for {peer_ip}"); tracing::debug!("pow: difficulty 0, skipping for {peer_ip}");
@ -150,8 +153,8 @@ mod tests {
let mut challenge = Challenge::generate(4); let mut challenge = Challenge::generate(4);
let challenge_str = challenge.challenge_string(); let challenge_str = challenge.challenge_string();
// Подбираем nonce, который независимо рассчитанный SHA-256 // Search for a nonce that an independently computed SHA-256 provably rejects,
// заведомо отклоняет — тест детерминирован. // so the test stays deterministic.
let mut wrong_nonce = None; let mut wrong_nonce = None;
for i in 0..10_000u32 { for i in 0..10_000u32 {
let candidate = format!("bad-{i}"); let candidate = format!("bad-{i}");

View file

@ -1,4 +1,4 @@
//! Multi-worker TCP accept-loop с SO_REUSEPORT и graceful shutdown. //! Multi-worker TCP accept loop with `SO_REUSEPORT` and graceful shutdown.
use crate::config::Config; use crate::config::Config;
use crate::engine::tunnel::Gateway; use crate::engine::tunnel::Gateway;
@ -8,11 +8,14 @@ use std::sync::Arc;
use tokio::net::TcpListener; use tokio::net::TcpListener;
use tokio::sync::watch; use tokio::sync::watch;
/// Запускает `workers.count` accept-loop'ов на одном адресе. /// Starts `workers.count` accept loops on a single address.
///
/// Each worker binds its own socket with `SO_REUSEPORT` and `SO_REUSEADDR`, so
/// the kernel distributes incoming connections across them and a restart does
/// not fail on `TIME_WAIT` sockets.
/// ///
/// # Errors /// # Errors
/// Возвращает ошибку при невозможности забиндить адрес или падении одного /// Fails when the address cannot be bound or when one of the accept loops dies.
/// из accept-loop'ов.
pub async fn run( pub async fn run(
config: Arc<Config>, config: Arc<Config>,
gateway: Arc<Gateway>, gateway: Arc<Gateway>,
@ -75,7 +78,7 @@ async fn accept_loop(
let gateway = Arc::clone(&gateway); let gateway = Arc::clone(&gateway);
let hook = Arc::clone(&hook); let hook = Arc::clone(&hook);
tokio::spawn(async move { tokio::spawn(async move {
// Hot path Traffic Intelligence: только атомики и DashMap. // Traffic intelligence hot path: atomics and `DashMap` only.
hook.on_accept(); hook.on_accept();
let outcome = gateway.handle(stream, peer_addr).await; let outcome = gateway.handle(stream, peer_addr).await;
if let Err(e) = outcome.result { if let Err(e) = outcome.result {

View file

@ -1,10 +1,13 @@
//! Edge-движок: listener, generic TCP tunnel, PoW gate. //! Edge engine: multi-worker listener, generic TCP tunnel and the PoW gate.
//!
//! Owns the per-connection pipeline and the subnet-level detection wiring that
//! sits between the kernel filter and the traffic intelligence layer.
pub mod challenge; pub mod challenge;
pub mod listener; pub mod listener;
pub mod subnet; pub mod subnet;
pub mod tunnel; pub mod tunnel;
// Совместимость путей после переезда в subnet/: `engine::subnet_tracker` / // Path compatibility after the move into `subnet/`: `engine::subnet_tracker` and
// `engine::subnet_monitor` остаются валидными алиасами модулей. // `engine::subnet_monitor` stay valid module paths.
pub use subnet::{monitor as subnet_monitor, tracker as subnet_tracker}; pub use subnet::{monitor as subnet_monitor, tracker as subnet_tracker};

View file

@ -1,3 +1,3 @@
//! Subnet-level детектор: юзерспейс-агрегатор префиксов и монитор вердиктов. //! Subnet-level detector: userspace prefix aggregator and verdict monitor.
pub mod monitor; pub mod monitor;
pub mod tracker; pub mod tracker;

View file

@ -1,7 +1,7 @@
//! Периодический subnet-монитор: источник снапшотов → детектор → эскалация. //! Periodic subnet monitor: snapshot source, detector and verdict escalation.
//! //!
//! Источник выбирается по сборке и конфигу: XDP-карта `prefix_stats` //! The source is chosen by build features and config: the XDP `prefix_stats` map
//! (feature `xdp` + загруженный фильтр) либо юзерспейс-агрегатор //! (feature `xdp` with a loaded filter) or the userspace aggregator
//! [`SubnetTracker`]. //! [`SubnetTracker`].
use crate::config::DetectPrefixConfig; use crate::config::DetectPrefixConfig;
@ -32,10 +32,11 @@ impl Source {
} }
} }
/// Запускает фоновый subnet-монитор, если `[detect.prefix] enabled`. /// Spawns the background subnet monitor when `[detect.prefix] enabled`.
/// ///
/// Приоритет источника: XDP-карта при загруженном фильтре, иначе /// 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.
pub fn spawn( pub fn spawn(
detect: &DetectPrefixConfig, detect: &DetectPrefixConfig,
tracker: Option<Arc<SubnetTracker>>, tracker: Option<Arc<SubnetTracker>>,
@ -123,7 +124,7 @@ async fn enforce_block(source: &Source, pv: &PrefixVerdict) {
} }
} }
/// Длина префикса, соответствующая гранулярности детекции (v4 /24, v6 /64). /// Prefix length matching the detection granularity (v4 /24, v6 /64).
#[cfg(feature = "xdp")] #[cfg(feature = "xdp")]
fn prefix_len(prefix: IpAddr) -> u8 { fn prefix_len(prefix: IpAddr) -> u8 {
match prefix { match prefix {

View file

@ -1,7 +1,9 @@
//! Юзерспейс-агрегатор новых соединений по префиксам (/24, /64). //! Userspace aggregator of new connections per prefix (/24 for IPv4, /64 for
//! IPv6).
//! //!
//! Fallback-путь subnet-детектора, когда XDP выключен: питает //! Fallback path of the subnet detector when XDP is disabled: it feeds
//! [`crate::traffic::prefix::SubnetDetector`] теми же снапшотами. //! [`crate::traffic::prefix::SubnetDetector`] with the same snapshot shape the
//! kernel map produces.
use crate::traffic::prefix::{PrefixSnapshot, PrefixStatsSource, prefix_of}; use crate::traffic::prefix::{PrefixSnapshot, PrefixStatsSource, prefix_of};
use dashmap::DashMap; use dashmap::DashMap;
@ -15,8 +17,10 @@ struct WindowState {
started: Instant, started: Instant,
} }
/// Агрегатор новых соединений по префиксам. `take_snapshot` дренирует /// Aggregates new connections per prefix.
/// накопленное: каждый вызов закрывает одно окно детекции. ///
/// `take_snapshot` drains the accumulated state, so every call closes exactly
/// one detection window.
pub struct SubnetTracker { pub struct SubnetTracker {
windows: DashMap<IpAddr, WindowState>, windows: DashMap<IpAddr, WindowState>,
} }
@ -35,7 +39,7 @@ impl SubnetTracker {
} }
} }
/// Регистрирует новое входящее соединение (юзерспейс-аналог SYN). /// Records a new inbound connection (userspace equivalent of a SYN).
pub fn record_connection(&self, ip: IpAddr) { pub fn record_connection(&self, ip: IpAddr) {
let prefix = prefix_of(ip); let prefix = prefix_of(ip);
let mut state = self.windows.entry(prefix).or_insert_with(|| WindowState { let mut state = self.windows.entry(prefix).or_insert_with(|| WindowState {
@ -47,12 +51,12 @@ impl SubnetTracker {
state.sources.insert(ip); state.sources.insert(ip);
} }
/// Забирает и сбрасывает агрегаты текущего окна. /// Takes and resets the aggregates of the current window.
#[must_use] #[must_use]
pub fn take_snapshot(&self) -> Vec<(IpAddr, PrefixSnapshot)> { pub fn take_snapshot(&self) -> Vec<(IpAddr, PrefixSnapshot)> {
let mut out = Vec::new(); 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| { self.windows.retain(|prefix, state| {
if state.syn_count == 0 { if state.syn_count == 0 {
return false; return false;
@ -60,8 +64,8 @@ impl SubnetTracker {
out.push(( out.push((
*prefix, *prefix,
PrefixSnapshot { PrefixSnapshot {
// Юзерспейс видит только установленные соединения; // Userspace only sees established connections, so `pkt_count` mirrors the same
// pkt_count отражает тот же поток. // flow as `syn_count`.
pkt_count: state.syn_count, pkt_count: state.syn_count,
syn_count: state.syn_count, syn_count: state.syn_count,
last_seen_ns: state.started.elapsed().as_nanos() as u64, last_seen_ns: state.started.elapsed().as_nanos() as u64,
@ -74,7 +78,7 @@ impl SubnetTracker {
} }
} }
/// Адаптер [`SubnetTracker`] под трейт [`PrefixStatsSource`]. /// Adapts [`SubnetTracker`] to the [`PrefixStatsSource`] trait.
pub struct TrackerSource { pub struct TrackerSource {
pub tracker: Arc<SubnetTracker>, pub tracker: Arc<SubnetTracker>,
} }

View file

@ -1,4 +1,5 @@
//! Generic TCP proxy: фильтры входа → protocol handshake → upstream. //! Generic TCP proxy pipeline: ingress filters, protocol handshake, upstream
//! relay.
use crate::config::Config; use crate::config::Config;
use crate::engine::challenge::DifficultyAdjuster; use crate::engine::challenge::DifficultyAdjuster;
@ -20,7 +21,7 @@ mod gateway;
#[cfg(feature = "protocol-minecraft")] #[cfg(feature = "protocol-minecraft")]
mod proxy; mod proxy;
/// Общее состояние edge-движка, разделяемое между accept-loop'ами. /// Shared edge engine state handed to every accept loop by [`Arc`].
pub struct Gateway { pub struct Gateway {
pub config: Arc<Config>, pub config: Arc<Config>,
pub rate_limiter: Arc<RateLimiter>, pub rate_limiter: Arc<RateLimiter>,

View file

@ -1,3 +1,6 @@
//! Per-connection pipeline of the edge engine: filters, PoW gate, protocol
//! handshake and upstream relay.
mod challenge; mod challenge;
#[cfg(feature = "protocol-minecraft")] #[cfg(feature = "protocol-minecraft")]
@ -56,11 +59,11 @@ impl Gateway {
} }
} }
/// Полный конвейер обработки входящего соединения. /// Runs the full pipeline for one inbound connection.
/// ///
/// # Errors /// # Errors
/// Возвращает ошибку только при сбое ввода-вывода апстрима; блокировки /// Only upstream I/O failures are surfaced; a connection dropped by a filter or
/// клиента ошибкой не считаются. /// by the challenge gate is not an error.
#[allow(unused_mut)] #[allow(unused_mut)]
pub async fn handle(&self, mut client: TcpStream, peer_addr: std::net::SocketAddr) -> GatewayOutcome { pub async fn handle(&self, mut client: TcpStream, peer_addr: std::net::SocketAddr) -> GatewayOutcome {
let client_addr = if self.config.proxy_protocol.ingress_enabled { let client_addr = if self.config.proxy_protocol.ingress_enabled {

View file

@ -1,3 +1,5 @@
//! Proof-of-work gate step of the connection pipeline.
use super::Gateway; use super::Gateway;
use crate::engine::challenge::enforce as enforce_pow; use crate::engine::challenge::enforce as enforce_pow;
use crate::metrics; use crate::metrics;
@ -5,6 +7,14 @@ use std::net::IpAddr;
use tokio::net::TcpStream; use tokio::net::TcpStream;
impl Gateway { impl Gateway {
/// Runs the proof-of-work gate for `peer_ip` and reports whether the
/// connection may continue.
///
/// Whitelisted peers skip the challenge but still publish the current
/// difficulty to the metrics gauge.
///
/// # Errors
/// Propagates I/O failures from the challenge exchange.
pub(super) async fn pass_pow_gate(&self, client: &mut TcpStream, peer_ip: IpAddr) -> anyhow::Result<bool> { pub(super) async fn pass_pow_gate(&self, client: &mut TcpStream, peer_ip: IpAddr) -> anyhow::Result<bool> {
let pow_config = &self.config.pow; let pow_config = &self.config.pow;
if !(pow_config.enabled && pow_config.difficulty > 0) { if !(pow_config.enabled && pow_config.difficulty > 0) {

View file

@ -1,10 +1,17 @@
//! Encoding of upstream PROXY protocol v2 headers.
use std::net::SocketAddr; use std::net::SocketAddr;
mod inbound; mod inbound;
pub(super) use inbound::read_v2_header; pub(super) use inbound::read_v2_header;
/// Encodes a PROXY protocol v2 TCP header for the backend. /// Encodes a PROXY protocol v2 TCP header for the backend.
/// The backend must accept connections only from trusted Rampart nodes. ///
/// The backend must accept connections only from trusted Rampart nodes, since
/// anyone able to reach it could otherwise forge the source address.
///
/// # Errors
/// Fails when the source and destination address families differ.
pub(super) fn protocol_v2(source: SocketAddr, destination: SocketAddr) -> anyhow::Result<Vec<u8>> { pub(super) fn protocol_v2(source: SocketAddr, destination: SocketAddr) -> anyhow::Result<Vec<u8>> {
const SIGNATURE: [u8; 12] = *b"\r\n\r\n\0\r\nQUIT\n"; const SIGNATURE: [u8; 12] = *b"\r\n\r\n\0\r\nQUIT\n";
if source.is_ipv4() != destination.is_ipv4() { if source.is_ipv4() != destination.is_ipv4() {

View file

@ -8,6 +8,13 @@ use tokio::net::TcpStream;
const SIGNATURE: [u8; 12] = *b"\r\n\r\n\0\r\nQUIT\n"; const SIGNATURE: [u8; 12] = *b"\r\n\r\n\0\r\nQUIT\n";
const FIXED_HEADER_BYTES: usize = 16; const FIXED_HEADER_BYTES: usize = 16;
/// Reads and validates an inbound PROXY protocol v2 header.
///
/// The whole header must arrive within `timeout`.
///
/// # Errors
/// Fails on timeout, on a bad signature or command, on an unsupported address
/// family, on TLVs, and on a header larger than `max_header_bytes`.
pub(crate) async fn read_v2_header( pub(crate) async fn read_v2_header(
stream: &mut TcpStream, stream: &mut TcpStream,
timeout: Duration, timeout: Duration,

View file

@ -103,7 +103,10 @@ impl Blacklist {
self.redis_entries.remove(&ip); self.redis_entries.remove(&ip);
} }
/// Replace Redis-managed bans while preserving local detector bans. /// 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<I>(&self, entries: I) pub fn replace_redis<I>(&self, entries: I)
where where
I: IntoIterator<Item = (IpAddr, Duration, String)>, I: IntoIterator<Item = (IpAddr, Duration, String)>,

View file

@ -1,4 +1,7 @@
//! Фильтры входящего трафика. //! Inbound traffic filters.
//!
//! Owns the per-source guards applied on the accept path: blacklist,
//! per-IP connection limit, geo policy and token-bucket rate limiting.
pub mod blacklist; pub mod blacklist;
pub mod connection_limit; pub mod connection_limit;

View file

@ -71,8 +71,11 @@ impl RateLimiter {
self.buckets.is_empty() self.buckets.is_empty()
} }
/// Эвиктит простаивающие бакеты. Запускается, когда бакетов больше /// Evicts idle buckets.
/// MAX_BUCKETS либо по расписанию (раз в SWEEP_INTERVAL). ///
/// 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) { pub fn sweep(&self) {
let now = Instant::now(); let now = Instant::now();
let elapsed_secs = now.duration_since(self.epoch).as_secs(); let elapsed_secs = now.duration_since(self.epoch).as_secs();

View file

@ -1,4 +1,6 @@
//! Rampart — универсальная платформа сетевой защиты (L3/L4/L7). //! Rampart is a universal L3/L4/L7 network protection platform.
//!
//! The crate root owns the module tree; each module documents what it owns.
pub mod app; pub mod app;
pub mod cli; pub mod cli;
pub mod config; pub mod config;

View file

@ -1,4 +1,6 @@
//! Инвентарь manager-API: health, узлы и серверы. //! Manager API inventory: health, nodes and servers.
//!
//! Owns the read-side endpoints that describe the fleet as the manager sees it.
pub mod health; pub mod health;
pub mod nodes; pub mod nodes;
pub mod servers; pub mod servers;

View file

@ -1,4 +1,6 @@
//! Management-плоскость Rampart: REST API, аутентификация, синхронизация узлов. //! Rampart management plane: REST API, authentication and node synchronisation.
//!
//! Owns [`AppState`], the handle shared by every handler through [`SharedState`].
pub mod api; pub mod api;
pub mod auth; pub mod auth;
pub mod sync; pub mod sync;
@ -8,10 +10,11 @@ use std::net::IpAddr;
use std::sync::Arc; use std::sync::Arc;
use std::time::Instant; use std::time::Instant;
/// Общее состояние management-API. /// Shared state of the management API.
pub struct AppState { pub struct AppState {
/// Redis-клиент управления состоянием; присутствует только при собранной /// Redis client for state management; present only when the `store-redis`
/// фиче `store-redis` (manager требует её на старте — см. bin/rampart-manager). /// feature is compiled in (the manager requires it at startup, see
/// bin/rampart-manager).
#[cfg(feature = "store-redis")] #[cfg(feature = "store-redis")]
pub redis_client: redis::Client, pub redis_client: redis::Client,
pub jwt_secret: String, pub jwt_secret: String,

View file

@ -1,3 +1,9 @@
//! Prometheus registry for the edge process: metric handles and the scrape
//! endpoint.
//!
//! Metric names and help strings are part of the public monitoring contract and
//! must stay stable across releases.
use prometheus::{ use prometheus::{
Encoder, IntCounter, IntCounterVec, IntGauge, register_int_counter, register_int_counter_vec, register_int_gauge, Encoder, IntCounter, IntCounterVec, IntGauge, register_int_counter, register_int_counter_vec, register_int_gauge,
}; };
@ -65,7 +71,13 @@ pub static INTEL_ALERTS_TOTAL: LazyLock<IntCounter> = LazyLock::new(|| {
.expect("INTEL_ALERTS_TOTAL") .expect("INTEL_ALERTS_TOTAL")
}); });
/// Отдаёт Prometheus-метрики по голому HTTP/0.9-совместимому ответу. /// Serves the Prometheus registry over a minimal HTTP endpoint.
///
/// Runs until the task is dropped; a failed connection is logged and never
/// aborts the loop.
///
/// The request line is not parsed: every connection receives the current
/// registry snapshot with `Content-Length` and is then closed.
pub async fn run_metrics_server(addr: &str) { pub async fn run_metrics_server(addr: &str) {
let listener = match TcpListener::bind(addr).await { let listener = match TcpListener::bind(addr).await {
Ok(l) => l, Ok(l) => l,

View file

@ -1,9 +1,12 @@
//! HTTP/1.1 protocol handler (feature `protocol-http`). //! HTTP/1.1 protocol handler (feature `protocol-http`).
//! //!
//! Первый plugin-реализаций [`ProtocolHandler`]: читает request-head //! Owns the first plugin implementation of [`ProtocolHandler`]: it reads the
//! постепенно (TCP приходит фрагментами), проверяет его по политике из //! request head incrementally (TCP arrives in fragments), evaluates it against
//! секции `[protocol.http]` и возвращает upstream для туннелирования. //! the policy from the `[protocol.http]` section and returns the upstream to
//! Прочитанная голова передаётся upstream как начальные байты туннеля. //! tunnel to.
//!
//! The bytes already consumed for the head are forwarded to the upstream as the
//! initial tunnel payload, so the request is not lost.
mod parser; mod parser;
@ -15,7 +18,7 @@ use std::time::Duration;
use tokio::io::AsyncReadExt; use tokio::io::AsyncReadExt;
use tokio::net::TcpStream; use tokio::net::TcpStream;
/// Обработчик HTTP/1.1: verdict Allow → tunnel на upstream, Reject → drop. /// HTTP/1.1 handler: verdict `Allow` tunnels to the upstream, `Reject` drops.
pub struct HttpProtocolHandler { pub struct HttpProtocolHandler {
policy: parser::Policy, policy: parser::Policy,
timeout: Duration, timeout: Duration,
@ -23,7 +26,10 @@ pub struct HttpProtocolHandler {
} }
impl HttpProtocolHandler { impl HttpProtocolHandler {
/// Собирает обработчик из конфига `[protocol.http]` и списка upstream'ов. /// Builds the handler from the `[protocol.http]` config and the upstream list.
///
/// The first upstream wins; falling back to `127.0.0.1:80` keeps the handler
/// usable in tests where the list is empty.
#[must_use] #[must_use]
pub fn new(http: &HttpProtocolConfig, upstreams: &[String]) -> Self { pub fn new(http: &HttpProtocolConfig, upstreams: &[String]) -> Self {
Self { Self {
@ -37,10 +43,11 @@ impl HttpProtocolHandler {
} }
} }
/// Накапливает request-head без повторного чтения одного и того же префикса. /// Accumulates the request head without re-reading an already scanned prefix.
/// ///
/// # Errors /// # Errors
/// Таймаут, закрытие клиента, превышение `max_header_bytes` или ошибка I/O. /// Times out, the client closes, `max_header_bytes` is exceeded, or the
/// socket reports an I/O error.
async fn read_head(&self, stream: &mut TcpStream) -> anyhow::Result<Vec<u8>> { async fn read_head(&self, stream: &mut TcpStream) -> anyhow::Result<Vec<u8>> {
let limit = self.policy.max_header_bytes; let limit = self.policy.max_header_bytes;
if limit == 0 { if limit == 0 {

View file

@ -1,9 +1,10 @@
//! Чистый парсер и валидатор HTTP/1.x request-head для edge-фильтра. //! Pure HTTP/1.x request-head parser and validator for the edge filter.
//! //!
//! Модуль не знает про I/O: на вход — накопленный заголовок, на выходе — //! Owns the parsing policy and verdicts only: the module knows nothing about
//! [`Verdict`]. Это позволяет покрывать логику юнит-тестами без сокетов. //! I/O. Input is the accumulated head, output is a [`Verdict`], which keeps the
//! logic unit-testable without sockets.
/// Политика проверки, снятая с секции `[protocol.http]`. /// Validation policy derived from the `[protocol.http]` section.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Policy { pub struct Policy {
pub max_header_bytes: usize, pub max_header_bytes: usize,
@ -11,7 +12,7 @@ pub struct Policy {
pub require_user_agent: bool, pub require_user_agent: bool,
} }
/// Результат проверки головы запроса. /// Outcome of validating a request head.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict { pub enum Verdict {
Allow { method: String, path: String, host: String }, Allow { method: String, path: String, host: String },
@ -21,7 +22,7 @@ pub enum Verdict {
const ALLOWED_METHODS: [&str; 7] = ["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"]; const ALLOWED_METHODS: [&str; 7] = ["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"];
const HEADER_TERMINATOR: &[u8] = b"\r\n\r\n"; const HEADER_TERMINATOR: &[u8] = b"\r\n\r\n";
/// Ищет конец головы запроса (`\r\n\r\n`) и возвращает её полную длину. /// Looks for the end of the request head (`\r\n\r\n`) and returns its full length.
#[must_use] #[must_use]
pub fn scan_head(buf: &[u8]) -> Option<usize> { pub fn scan_head(buf: &[u8]) -> Option<usize> {
buf.windows(HEADER_TERMINATOR.len()) buf.windows(HEADER_TERMINATOR.len())
@ -29,7 +30,7 @@ pub fn scan_head(buf: &[u8]) -> Option<usize> {
.map(|pos| pos + HEADER_TERMINATOR.len()) .map(|pos| pos + HEADER_TERMINATOR.len())
} }
/// Разбирает и валидирует голову запроса согласно политике. /// Parses and validates a request head against the policy.
#[must_use] #[must_use]
pub fn evaluate(head: &[u8], policy: &Policy) -> Verdict { pub fn evaluate(head: &[u8], policy: &Policy) -> Verdict {
let Ok(text) = std::str::from_utf8(head) else { let Ok(text) = std::str::from_utf8(head) else {

View file

@ -1,3 +1,9 @@
//! Protocol handler contracts.
//!
//! Owns the [`ProtocolHandler`] trait implemented by L7 plugins and the
//! [`ProtocolRegistry`] that selects the active handler at startup. Concrete
//! handlers live behind features (`protocol-http`, `protocol-minecraft`).
#[cfg(feature = "protocol-http")] #[cfg(feature = "protocol-http")]
pub mod http; pub mod http;
#[cfg(feature = "protocol-minecraft")] #[cfg(feature = "protocol-minecraft")]
@ -7,8 +13,8 @@ use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
use tokio::net::TcpStream; use tokio::net::TcpStream;
/// Результат успешного protocol-handshake: адрес upstream-бэкенда, /// Result of a successful protocol handshake: the upstream backend address the
/// на который нужно проксировать соединение. /// connection must be proxied to.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct Upstream { pub struct Upstream {
pub addr: String, pub addr: String,
@ -45,30 +51,31 @@ impl HandshakeResult {
} }
} }
/// Точка расширения платформы: реализация для конкретного L7-протокола. /// Platform extension point: one implementation per L7 protocol.
/// ///
/// Контракт минимальный: обработчик проводит handshake с клиентом /// The contract is deliberately small. A handler drives the handshake with the
/// (чтение/запись в поток до момента, когда можно проксировать) и /// client (reading and writing on the stream up to the point where proxying is
/// возвращает целевой [`Upstream`]. Реализации поставляются фичами /// possible) and returns the target [`Upstream`]. Implementations ship as
/// (`--features protocol-http`, внешние plugin-крейты) — в ядре их нет. /// features (`--features protocol-http`, external plugin crates); the core
/// itself contains none.
/// ///
/// Метод асинхронен через boxed future, чтобы трейт оставался /// The method is async through a boxed future so the trait stays
/// dyn-совместимым (`ProtocolRegistry` хранит `Box<dyn ProtocolHandler>`). /// dyn-compatible (`ProtocolRegistry` stores `Box<dyn ProtocolHandler>`).
pub trait ProtocolHandler: Send + Sync { pub trait ProtocolHandler: Send + Sync {
/// Имя протокола (для метрик, логов и реестра). /// Protocol name, used in metrics, logs and the registry.
fn name(&self) -> &'static str; fn name(&self) -> &'static str;
/// Проводит handshake с клиентом и определяет upstream. /// Drives the client handshake and resolves the upstream.
/// ///
/// # Errors /// # Errors
/// Возвращает ошибку при невалидном клиентском потоке или отказе в доступе. /// Returns an error when the client stream is invalid or access is denied.
fn handshake<'a>( fn handshake<'a>(
&'a self, &'a self,
stream: &'a mut TcpStream, stream: &'a mut TcpStream,
) -> Pin<Box<dyn Future<Output = anyhow::Result<HandshakeResult>> + Send + 'a>>; ) -> Pin<Box<dyn Future<Output = anyhow::Result<HandshakeResult>> + Send + 'a>>;
} }
/// Реестр скомпилированных протокольных обработчиков. /// Registry of the protocol handlers compiled into this binary.
#[derive(Default)] #[derive(Default)]
pub struct ProtocolRegistry { pub struct ProtocolRegistry {
handlers: Vec<Box<dyn ProtocolHandler>>, handlers: Vec<Box<dyn ProtocolHandler>>,
@ -104,11 +111,11 @@ impl ProtocolRegistry {
self.handlers.iter().find(|h| h.name() == name).map(|h| h.as_ref()) self.handlers.iter().find(|h| h.name() == name).map(|h| h.as_ref())
} }
/// Возвращает основной обработчик. /// Returns the primary handler, the first one registered.
/// ///
/// # Errors /// # Errors
/// Возвращает ошибку, если ни один протокол не скомпилирован — /// Returns an error when no protocol is compiled in; an edge node must
/// edge-нода обязана fail-fast на старте в этом случае. /// fail fast at startup in that case.
pub fn primary(&self) -> anyhow::Result<&dyn ProtocolHandler> { pub fn primary(&self) -> anyhow::Result<&dyn ProtocolHandler> {
let Some(handler) = self.handlers.first() else { let Some(handler) = self.handlers.first() else {
anyhow::bail!( anyhow::bail!(

View file

@ -1,3 +1,8 @@
//! External state backends.
//!
//! Owns the [`StateStore`] contract plus the Redis implementation (blacklist
//! sync between nodes) and the ClickHouse event sink.
#[cfg(feature = "store-redis")] #[cfg(feature = "store-redis")]
pub mod redis; pub mod redis;
#[cfg(feature = "store-redis")] #[cfg(feature = "store-redis")]
@ -5,22 +10,30 @@ pub use redis::{start_blacklist_sync, start_local_ban_publisher};
pub mod clickhouse; pub mod clickhouse;
/// Общий контракт внешнего хранилища состояния. /// Common contract for an external state store.
#[allow(async_fn_in_trait)] #[allow(async_fn_in_trait)]
pub trait StateStore: Send + Sync { pub trait StateStore: Send + Sync {
/// Reads `key`, returning `None` when it is absent.
///
/// # Errors /// # Errors
/// Возвращает ошибку при недоступности хранилища. /// Returns an error when the store is unreachable.
async fn get(&self, key: &str) -> anyhow::Result<Option<String>>; async fn get(&self, key: &str) -> anyhow::Result<Option<String>>;
/// Writes `value` under `key`, overwriting any previous value.
///
/// # Errors /// # Errors
/// Возвращает ошибку при недоступности хранилища. /// Returns an error when the store is unreachable.
async fn set(&self, key: &str, value: &str) -> anyhow::Result<()>; async fn set(&self, key: &str, value: &str) -> anyhow::Result<()>;
/// Deletes `key`; deleting a missing key is not an error.
///
/// # Errors /// # Errors
/// Возвращает ошибку при недоступности хранилища. /// Returns an error when the store is unreachable.
async fn del(&self, key: &str) -> anyhow::Result<()>; async fn del(&self, key: &str) -> anyhow::Result<()>;
/// Publishes `message` to `channel` for subscribers to consume.
///
/// # Errors /// # Errors
/// Возвращает ошибку при недоступности хранилища. /// Returns an error when the store is unreachable.
async fn publish(&self, channel: &str, message: &str) -> anyhow::Result<()>; async fn publish(&self, channel: &str, message: &str) -> anyhow::Result<()>;
} }

View file

@ -1,7 +1,7 @@
//! Traffic Intelligence в hot path: репутация → авто-бан → метрики окна. //! Traffic Intelligence in the hot path: reputation, auto-ban and window metrics.
//! //!
//! Все вызовы из accept-пути дешёвые (DashMap/атомики), блокирующего //! Every call reachable from the accept path is cheap (DashMap/atomics) and
//! ввода-вывода нет. //! performs no blocking I/O.
use crate::config::DetectAutobanConfig; use crate::config::DetectAutobanConfig;
use crate::filter::blacklist::Blacklist; use crate::filter::blacklist::Blacklist;
@ -15,10 +15,10 @@ use std::time::Duration;
const BAN_REASON_LOW_REPUTATION: &str = "low_reputation"; const BAN_REASON_LOW_REPUTATION: &str = "low_reputation";
const BAN_REASON_ATTACK: &str = "attack_detector"; const BAN_REASON_ATTACK: &str = "attack_detector";
/// Точка входа Traffic Intelligence для сетевого пути. /// Entry point of Traffic Intelligence on the network path.
/// ///
/// События: новое соединение (`on_accept`), завершение обработки соединения /// Events: a new connection (`on_accept`), a finished connection
/// (`on_connection_end`), эскалация детектора атак (`ban_offenders`). /// (`on_connection_end`) and attack-detector escalation (`ban_offenders`).
pub struct TrafficHook { pub struct TrafficHook {
reputation: Arc<IpReputation>, reputation: Arc<IpReputation>,
blacklist: Arc<Blacklist>, blacklist: Arc<Blacklist>,
@ -43,13 +43,18 @@ impl TrafficHook {
} }
} }
/// Новое соединение принято accept-loop'ом. Только счётчик окна cps. /// A new connection was accepted by the accept loop.
///
/// Only bumps the cps window counter; the counter is drained by
/// [`Self::take_cps`] once per second.
pub fn on_accept(&self) { pub fn on_accept(&self) {
self.conn_window.fetch_add(1, Ordering::Relaxed); self.conn_window.fetch_add(1, Ordering::Relaxed);
} }
/// Соединение обработано. Если источник попал под rate-limit (репутация /// A connection finished processing.
/// упала до порога) — авто-бан с TTL из конфига. ///
/// If the source was pushed down to the reputation threshold, it is banned
/// with the TTL taken from the config.
pub fn on_connection_end(&self, ip: IpAddr) { pub fn on_connection_end(&self, ip: IpAddr) {
if !self.autoban.enabled || self.blacklist.is_blocked(ip) { if !self.autoban.enabled || self.blacklist.is_blocked(ip) {
return; return;
@ -57,8 +62,10 @@ impl TrafficHook {
self.autoban_if_toxic(ip, BAN_REASON_LOW_REPUTATION); self.autoban_if_toxic(ip, BAN_REASON_LOW_REPUTATION);
} }
/// Эскалация детектора атак: бан всех источников ниже порога репутации. /// Attack-detector escalation: bans every source below the reputation
/// Вызывается один раз на переход в `UnderAttack`, не на каждый тик. /// threshold and returns how many bans were issued.
///
/// Called once on the transition into `UnderAttack`, not on every tick.
pub fn ban_offenders(&self) -> usize { pub fn ban_offenders(&self) -> usize {
if !self.autoban.enabled { if !self.autoban.enabled {
return 0; return 0;
@ -75,7 +82,7 @@ impl TrafficHook {
banned banned
} }
/// Забирает накопленное окно новых соединений за секунду (cps). /// Takes the accumulated one-second window of new connections (cps).
pub fn take_cps(&self) -> u64 { pub fn take_cps(&self) -> u64 {
self.conn_window.swap(0, Ordering::Relaxed) self.conn_window.swap(0, Ordering::Relaxed)
} }
@ -206,7 +213,7 @@ mod tests {
enabled: true, enabled: true,
reputation_threshold: -50, reputation_threshold: -50,
}, },
// Короткий TTL как мок времени: бан жив, потом истекает. // Zero TTL as a time mock: the ban must be dead on arrival.
0, 0,
); );
let target = ip([10, 3, 0, 1]); let target = ip([10, 3, 0, 1]);

View file

@ -28,8 +28,12 @@ impl AttackDetector {
} }
} }
/// Анализирует окно метрик (пакеты/с и новые соединения/с) относительно /// Analyses one metrics window (packets/s and new connections/s) against
/// накопленных профилей. Аномалией считается всплеск любой из метрик. /// the accumulated profiles.
///
/// 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 { pub fn analyze(&mut self, pps: f64, cps: f64) -> AttackStatus {
self.pps_profiler.record(pps); self.pps_profiler.record(pps);
self.cps_profiler.record(cps); self.cps_profiler.record(cps);

View file

@ -1,4 +1,7 @@
//! Интеллект трафика: EWMA-сглаживание, детектор атак и репутация IP. //! Traffic intelligence: EWMA smoothing, attack detector and per-IP reputation.
//!
//! Owns the scoring primitives consumed by [`crate::traffic::hook`]; the
//! modules are also re-exported at `traffic::{ewma, detector, reputation}`.
pub mod detector; pub mod detector;
pub mod ewma; pub mod ewma;
pub mod reputation; pub mod reputation;

View file

@ -33,7 +33,10 @@ impl IpReputation {
self.scores.get(&ip).map(|v| *v).unwrap_or(0) self.scores.get(&ip).map(|v| *v).unwrap_or(0)
} }
/// Возвращает источники со скором не выше `threshold` (нарушители). /// Returns the sources scored at or below `threshold` (the offenders).
///
/// 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<IpAddr> { pub fn offenders_below(&self, threshold: i32) -> Vec<IpAddr> {
self.scores self.scores
.iter() .iter()

View file

@ -1,11 +1,15 @@
//! Профилирование трафика, детектор атак и репутация IP. //! Traffic profiling, attack detection and per-IP reputation.
//!
//! Owns the state the edge node feeds from the accept path: [`hook::TrafficHook`]
//! wires reputation, auto-ban and window metrics together, while the `intel`,
//! `prefix` and `profile` submodules hold the detectors themselves.
pub mod hook; pub mod hook;
pub mod intel; pub mod intel;
pub mod prefix; pub mod prefix;
pub mod profile; pub mod profile;
// Совместимость путей после группировки: домены `intel/` и `profile/` // Re-exported under the old paths (`traffic::{detector, ewma, ...}`) so the
// остаются доступны по прежним путям `traffic::{detector, ewma, ...}`. // grouping into `intel/` and `profile/` stays source-compatible.
pub use intel::{detector, ewma, reputation}; pub use intel::{detector, ewma, reputation};
pub use profile::{alert, profiler}; pub use profile::{alert, profiler};

View file

@ -1,11 +1,11 @@
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
/// `family` для IPv4-префиксов (/24). /// `family` tag for IPv4 prefixes (/24).
pub const PREFIX_FAMILY_V4: u8 = 4; pub const PREFIX_FAMILY_V4: u8 = 4;
/// `family` для IPv6-префиксов (/64). /// `family` tag for IPv6 prefixes (/64).
pub const PREFIX_FAMILY_V6: u8 = 6; pub const PREFIX_FAMILY_V6: u8 = 6;
/// Ключ карты `prefix_stats` (`BPF_MAP_TYPE_LRU_HASH`, max_entries 65536). /// Key of the `prefix_stats` map (`BPF_MAP_TYPE_LRU_HASH`, 65536 entries).
#[repr(C)] #[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PrefixKey { pub struct PrefixKey {
@ -15,7 +15,8 @@ pub struct PrefixKey {
} }
impl PrefixKey { impl PrefixKey {
/// Строит ключ префикса для адреса (v4 → /24 в первых 4 байтах, v6 → /64). /// Builds the prefix key for an address (v4 maps to /24 in the first four
/// bytes, v6 maps to /64).
#[must_use] #[must_use]
pub fn new(ip: IpAddr) -> Self { pub fn new(ip: IpAddr) -> Self {
let mut key = Self::default(); let mut key = Self::default();
@ -32,7 +33,7 @@ impl PrefixKey {
key key
} }
/// Префикс как IP-адрес (маскированный). /// The prefix as a masked IP address; `None` for an unknown `family` tag.
#[must_use] #[must_use]
pub fn to_prefix(self) -> Option<IpAddr> { pub fn to_prefix(self) -> Option<IpAddr> {
match self.family { match self.family {
@ -66,13 +67,14 @@ impl PrefixKey {
} }
} }
/// Возвращает префикс адреса: IPv4 и IPv4-mapped → /24, IPv6 → /64. /// Returns the prefix of an address: IPv4 and IPv4-mapped share /24, IPv6 uses /64.
#[must_use] #[must_use]
pub fn prefix_of(ip: IpAddr) -> IpAddr { pub fn prefix_of(ip: IpAddr) -> IpAddr {
match ip { match ip {
IpAddr::V4(v4) => IpAddr::V4(masked_v4(v4)), IpAddr::V4(v4) => IpAddr::V4(masked_v4(v4)),
IpAddr::V6(v6) => match v6.to_ipv4_mapped() { IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
// ::ffff:a.b.c.d живёт в том же /24-пространстве, что и a.b.c.d. // ::ffff:a.b.c.d must land in the same /24 bucket as a.b.c.d,
// otherwise a dual-stack client could escape its own ban.
Some(v4) => IpAddr::V4(masked_v4(v4)), Some(v4) => IpAddr::V4(masked_v4(v4)),
None => IpAddr::V6(Ipv6Addr::from(masked_v6_segments(v6))), None => IpAddr::V6(Ipv6Addr::from(masked_v6_segments(v6))),
}, },

View file

@ -1,9 +1,9 @@
//! Subnet-level (prefix) детектор распределённых атак. //! Subnet-level (prefix) distributed attack detector.
//! //!
//! Источник данных — трейт [`PrefixStatsSource`]: карта XDP `prefix_stats` //! Data arrives through the [`PrefixStatsSource`] trait: either the XDP
//! (feature `xdp`) либо юзерспейс-агрегатор [`crate::engine::subnet_tracker`]. //! `prefix_stats` map (feature `xdp`) or the user-space aggregator in
//! Контракт с XDP-агентом: [`PrefixKey`] / [`PrefixStatsVal`] должны совпадать //! [`crate::engine::subnet_tracker`]. [`PrefixKey`] and [`PrefixStatsVal`] must
//! побайтово со структурами ядра. //! match the kernel structs byte for byte, hence the `repr(C)` layout.
mod key; mod key;
mod stats; mod stats;

View file

@ -2,7 +2,7 @@ use anyhow::Result;
use std::future::Future; use std::future::Future;
use std::net::IpAddr; use std::net::IpAddr;
/// Значение карты `prefix_stats`. /// Value of the `prefix_stats` map.
#[repr(C)] #[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PrefixStatsVal { pub struct PrefixStatsVal {
@ -12,7 +12,7 @@ pub struct PrefixStatsVal {
} }
impl PrefixStatsVal { impl PrefixStatsVal {
/// Разбирает сырые 24 байта значения карты. /// Parses the raw 24-byte map value.
#[must_use] #[must_use]
pub fn from_bytes(bytes: [u8; 24]) -> Self { pub fn from_bytes(bytes: [u8; 24]) -> Self {
let read_u64 = let read_u64 =
@ -24,7 +24,7 @@ impl PrefixStatsVal {
} }
} }
/// Сериализует значение в сырые 24 байта карты. /// Serialises the value into the raw 24-byte map layout.
#[must_use] #[must_use]
pub fn to_bytes(self) -> [u8; 24] { pub fn to_bytes(self) -> [u8; 24] {
let mut out = [0u8; 24]; let mut out = [0u8; 24];
@ -35,10 +35,10 @@ impl PrefixStatsVal {
} }
} }
/// Агрегат по одному префиксу за окно детекции. /// Aggregated counters for one prefix over a detection window.
/// ///
/// `unique_sources == 0` означает, что источник не считает уникальные адреса /// `unique_sources == 0` means the source does not count distinct addresses
/// (XDP-путь); spoof-gate в этом случае Block не подтверждает. /// (the XDP path), and the spoof gate then never confirms `Block`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PrefixSnapshot { pub struct PrefixSnapshot {
pub syn_count: u64, pub syn_count: u64,
@ -47,16 +47,17 @@ pub struct PrefixSnapshot {
pub unique_sources: u64, pub unique_sources: u64,
} }
/// Источник агрегатов по префиксам. Позволяет тестам работать без ядра. /// Source of per-prefix aggregates; keeps tests independent of the kernel.
pub trait PrefixStatsSource { pub trait PrefixStatsSource {
/// Снимок агрегатов за текущее окно. /// Snapshot of the aggregates for the current window.
/// ///
/// # Errors /// # Errors
/// Ошибка чтения источника (карта не загружена, BPF-сбой и т.п.). /// Returns an error when the source cannot be read (map not loaded, BPF
/// failure and similar).
fn snapshot(&self) -> impl Future<Output = Result<Vec<(IpAddr, PrefixSnapshot)>>> + Send; fn snapshot(&self) -> impl Future<Output = Result<Vec<(IpAddr, PrefixSnapshot)>>> + Send;
} }
/// Эскалация вердиктов subnet-level детектора. /// Verdict escalation ladder of the subnet-level detector.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubnetVerdict { pub enum SubnetVerdict {
Monitor, Monitor,
@ -65,7 +66,7 @@ pub enum SubnetVerdict {
Block, Block,
} }
/// Вердикт по одному префиксу. /// Verdict for a single prefix.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrefixVerdict { pub struct PrefixVerdict {
pub prefix: IpAddr, pub prefix: IpAddr,
@ -73,12 +74,13 @@ pub struct PrefixVerdict {
pub snapshot: PrefixSnapshot, pub snapshot: PrefixSnapshot,
} }
/// Детектор распределённых атак по префиксам. /// Detector for distributed attacks at prefix granularity.
/// ///
/// Лестница эскалации по `syn_count` за окно: `< threshold` → Monitor, /// Escalation ladder over the `syn_count` of one window: below `threshold` is
/// `< 2×threshold` → StrictLimit, иначе Challenge; Block только при /// `Monitor`, below `2 x threshold` is `StrictLimit`, anything higher is
/// `≥ 4×threshold` И прохождении spoof-gate (≥ `min_unique_sources` /// `Challenge`. `Block` requires at least `4 x threshold` *and* a passed spoof
/// уникальных IP — защита от ложного бана CGNAT/спуфинга). /// gate (at least `min_unique_sources` distinct IPs), which guards against
/// false bans of CGNAT ranges and spoofed sources.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct SubnetDetector { pub struct SubnetDetector {
syn_threshold: u64, syn_threshold: u64,
@ -99,7 +101,7 @@ impl SubnetDetector {
Self::new(config.syn_threshold, config.min_unique_sources) Self::new(config.syn_threshold, config.min_unique_sources)
} }
/// Оценивает снимок и возвращает вердикты по активным префиксам. /// Evaluates a snapshot and returns verdicts for all active prefixes.
#[must_use] #[must_use]
pub fn evaluate(&self, snapshots: &[(IpAddr, PrefixSnapshot)]) -> Vec<PrefixVerdict> { pub fn evaluate(&self, snapshots: &[(IpAddr, PrefixSnapshot)]) -> Vec<PrefixVerdict> {
snapshots snapshots
@ -131,14 +133,15 @@ impl SubnetDetector {
#[must_use] #[must_use]
fn spoof_gate_passed(&self, snap: &PrefixSnapshot) -> bool { fn spoof_gate_passed(&self, snap: &PrefixSnapshot) -> bool {
// gate отключён (min_unique_sources == 0) либо подтверждено разнообразие. // The gate is disabled (min_unique_sources == 0) or diversity is confirmed.
self.min_unique_sources == 0 || snap.unique_sources >= self.min_unique_sources self.min_unique_sources == 0 || snap.unique_sources >= self.min_unique_sources
} }
} }
/// Реализация [`PrefixStatsSource`] поверх XDP-фильтра (feature `xdp`). /// [`PrefixStatsSource`] backed by the XDP filter (feature `xdp`).
/// Читает карту `prefix_stats`; уникальные источники ядро не считает, ///
/// поэтому spoof-gate на этом пути Block не подтверждает. /// Reads the `prefix_stats` map. The kernel does not track distinct source
/// addresses, so the spoof gate never confirms `Block` on this path.
#[cfg(feature = "xdp")] #[cfg(feature = "xdp")]
pub struct XdpPrefixStats { pub struct XdpPrefixStats {
filter: std::sync::Arc<std::sync::Mutex<crate::xdp::XdpFilter>>, filter: std::sync::Arc<std::sync::Mutex<crate::xdp::XdpFilter>>,
@ -151,10 +154,11 @@ impl XdpPrefixStats {
Self { filter } Self { filter }
} }
/// Блокирует мьютекс фильтра (для kernel-enforcement вердиктов). /// Locks the filter mutex (needed for kernel enforcement of verdicts).
/// ///
/// # Panics /// # Panics
/// Если мьютекс отравлен (паника в другом потоке во время удержания). /// Panics if the mutex is poisoned, that is, if another thread panicked
/// while holding it.
pub fn filter_lock(&self) -> std::sync::MutexGuard<'_, crate::xdp::XdpFilter> { pub fn filter_lock(&self) -> std::sync::MutexGuard<'_, crate::xdp::XdpFilter> {
self.filter.lock().expect("xdp lock poisoned") self.filter.lock().expect("xdp lock poisoned")
} }

View file

@ -56,9 +56,11 @@ impl fmt::Display for Alert {
} }
} }
/// Дедуплицирующий диспетчер алертов: алерт выдаётся только на переходе /// Deduplicating alert dispatcher.
/// состояния детектора (вход в `UnderAttack` и выход из него), не на каждом ///
/// тике. Логика — poll-and-persist (LNVPS issue #331). /// An alert is emitted only on a detector state transition (entering
/// `UnderAttack` and leaving it), never on every tick. The behaviour is
/// poll-and-persist: the previous status is kept as the baseline.
#[derive(Default)] #[derive(Default)]
pub struct AlertDispatcher { pub struct AlertDispatcher {
previous: Mutex<Option<AttackStatus>>, previous: Mutex<Option<AttackStatus>>,
@ -69,9 +71,11 @@ impl AlertDispatcher {
Self::default() Self::default()
} }
/// Возвращает `Some(Alert)` только при переходе через границу атаки: /// Returns `Some(Alert)` only when the attack boundary is crossed: entering
/// вход в `UnderAttack` («attack started») или выход из него /// `UnderAttack` ("attack started") or leaving it ("attack ended").
/// («attack ended»). Первое наблюдение алерта не порождает. ///
/// The first observation never produces an alert, so a node that starts up
/// during an attack does not report a transition it never saw.
pub fn on_status(&self, status: AttackStatus) -> Option<Alert> { pub fn on_status(&self, status: AttackStatus) -> Option<Alert> {
let mut previous = self.previous.lock().expect("alert dispatcher lock poisoned"); let mut previous = self.previous.lock().expect("alert dispatcher lock poisoned");
if *previous == Some(status) { if *previous == Some(status) {
@ -89,9 +93,10 @@ impl AlertDispatcher {
} }
} }
/// Отправляет алерт на webhook (fire-and-forget, с таймаутом). /// Delivers an alert to a webhook (fire-and-forget, with a timeout).
/// ///
/// Вызывать следует из фоновых задач: сетевой ввод-вывод недопустим в hot path. /// Call it from background tasks only: network I/O is not allowed on the hot
/// path.
pub async fn send_webhook(url: String, alert: Alert) { pub async fn send_webhook(url: String, alert: Alert) {
let payload = serde_json::json!({ let payload = serde_json::json!({
"level": alert.level.to_string(), "level": alert.level.to_string(),

View file

@ -1,3 +1,6 @@
//! Профилирование трафика edge-ноды и алерты детектора атак. //! Edge-node traffic profiling and attack-detector alerts.
//!
//! Owns the sliding EWMA profiler and the deduplicating alert dispatcher;
//! both are re-exported at `traffic::{profiler, alert}`.
pub mod alert; pub mod alert;
pub mod profiler; pub mod profiler;

View file

@ -1,4 +1,8 @@
//! Циклы приложения: fetch-таска (tokio) и UI-цикл (tick + события клавиатуры). //! Application loops: the fetch task (tokio) and the UI loop (tick plus
//! keyboard events).
//!
//! Owns the wiring between a [`Fetcher`] and the terminal: the fetch task never
//! draws and the UI loop never performs I/O beyond the terminal itself.
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
@ -10,14 +14,14 @@ use crate::tui::prometheus::parse;
use crate::tui::state::AppState; use crate::tui::state::AppState;
use crate::tui::ui; use crate::tui::ui;
/// Управляемые пользователем команды (клавиши). /// Commands the user can trigger from the keyboard.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command { pub enum Command {
Quit, Quit,
Refresh, Refresh,
} }
/// Маппинг клавиш: `q`/`Esc` — выход, `r` — обновить немедленно. /// Key mapping: `q`/`Esc` quit, `r` refreshes immediately.
#[must_use] #[must_use]
pub fn handle_key(code: crossterm::event::KeyCode) -> Option<Command> { pub fn handle_key(code: crossterm::event::KeyCode) -> Option<Command> {
match code { match code {
@ -27,7 +31,7 @@ pub fn handle_key(code: crossterm::event::KeyCode) -> Option<Command> {
} }
} }
/// Приводит результат fetch к виду для [`AppState::apply_fetch`]. /// Converts a fetch result into the shape expected by [`AppState::apply_fetch`].
pub fn normalize(result: Result<String, FetchError>) -> Result<crate::tui::prometheus::MetricSet, String> { pub fn normalize(result: Result<String, FetchError>) -> Result<crate::tui::prometheus::MetricSet, String> {
match result { match result {
Ok(body) => Ok(parse(&body)), Ok(body) => Ok(parse(&body)),
@ -36,7 +40,10 @@ pub fn normalize(result: Result<String, FetchError>) -> Result<crate::tui::prome
} }
} }
/// Фоновая задача: fetch → [`AppState`]. Ошибки сети пишутся в снапшот баннером. /// Background task: fetch into [`AppState`].
///
/// Network failures are stored in the snapshot and rendered as an error banner,
/// so a dead endpoint degrades the view instead of ending the session.
pub async fn spawn_fetch_loop(fetcher: Arc<dyn Fetcher>, state: Arc<AppState>, refresh: Duration, notify: Arc<Notify>) { pub async fn spawn_fetch_loop(fetcher: Arc<dyn Fetcher>, state: Arc<AppState>, refresh: Duration, notify: Arc<Notify>) {
loop { loop {
let started = std::time::Instant::now(); let started = std::time::Instant::now();
@ -51,10 +58,11 @@ pub async fn spawn_fetch_loop(fetcher: Arc<dyn Fetcher>, state: Arc<AppState>, r
} }
} }
/// UI-цикл: рисует кадр каждые ~100 мс, обрабатывает клавиши. /// UI loop: draws a frame roughly every 100 ms and handles key presses.
/// ///
/// # Errors /// # Errors
/// Возвращает ошибку терминала (draw/poll) — вызывающий восстанавливает TTY. /// Returns the terminal error from draw/poll; the caller is responsible for
/// restoring the TTY.
pub async fn run_ui( pub async fn run_ui(
terminal: &mut ratatui::Terminal<impl ratatui::backend::Backend<Error = std::io::Error>>, terminal: &mut ratatui::Terminal<impl ratatui::backend::Backend<Error = std::io::Error>>,
state: Arc<AppState>, state: Arc<AppState>,
@ -71,13 +79,13 @@ pub async fn run_ui(
} }
} }
/// Неблокирующее ожидание клавиши в течение `timeout`. /// Non-blocking wait for a key press within `timeout`.
fn poll_command(timeout: Duration) -> std::io::Result<Option<Command>> { fn poll_command(timeout: Duration) -> std::io::Result<Option<Command>> {
if !crossterm::event::poll(timeout)? { if !crossterm::event::poll(timeout)? {
return Ok(None); return Ok(None);
} }
if let crossterm::event::Event::Key(key) = crossterm::event::read()? { if let crossterm::event::Event::Key(key) = crossterm::event::read()? {
// Реагируем только на нажатие (не автоповтор/отпускание). // React to presses only, ignoring auto-repeat and key releases.
if key.kind == crossterm::event::KeyEventKind::Press { if key.kind == crossterm::event::KeyEventKind::Press {
return Ok(handle_key(key.code)); return Ok(handle_key(key.code));
} }

View file

@ -1,38 +1,44 @@
//! Получение тела `/metrics`: трейт [`Fetcher`] для мока в тестах и HTTP-реализация. //! Fetching of the `/metrics` body: the [`Fetcher`] trait for test mocks plus
//! the HTTP implementation.
//!
//! Owns the transport boundary of the TUI; parsing lives in
//! [`crate::tui::prometheus`].
use std::time::Duration; use std::time::Duration;
use futures::future::BoxFuture; use futures::future::BoxFuture;
use thiserror::Error; use thiserror::Error;
/// Ошибка загрузки метрик. /// Metrics fetch failure.
#[derive(Debug, Error, Clone)] #[derive(Debug, Error, Clone)]
pub enum FetchError { pub enum FetchError {
/// Сетевая ошибка / DNS / таймаут. /// Network error, DNS failure or timeout.
#[error("network error: {0}")] #[error("network error: {0}")]
Network(String), Network(String),
/// Endpoint ответил не-200 статусом. /// The endpoint answered with a non-200 status.
#[error("http status {0}")] #[error("http status {0}")]
Status(u16), Status(u16),
} }
/// Абстракция источника exposition-текста Prometheus. /// Abstraction over a source of Prometheus exposition text.
pub trait Fetcher: Send + Sync { pub trait Fetcher: Send + Sync {
/// Загружает текущий срез метрик. /// Fetches the current metrics snapshot.
/// ///
/// # Errors /// # Errors
/// Возвращает [`FetchError`] при сетевом сбое или плохом HTTP-статусе. /// Returns [`FetchError`] on a network failure or a bad HTTP status.
fn fetch(&self) -> BoxFuture<'_, Result<String, FetchError>>; fn fetch(&self) -> BoxFuture<'_, Result<String, FetchError>>;
} }
/// Реализация [`Fetcher`] поверх reqwest GET. /// [`Fetcher`] implementation on top of a reqwest GET.
pub struct HttpFetcher { pub struct HttpFetcher {
url: String, url: String,
client: reqwest::Client, client: reqwest::Client,
} }
impl HttpFetcher { impl HttpFetcher {
/// Создаёт fetcher с таймаутом запроса 5 секунд. /// Creates a fetcher with a 5 second request timeout.
///
/// Returns `None` when the HTTP client cannot be built.
pub fn new(url: impl Into<String>) -> Option<Self> { pub fn new(url: impl Into<String>) -> Option<Self> {
let client = reqwest::Client::builder() let client = reqwest::Client::builder()
.timeout(Duration::from_secs(5)) .timeout(Duration::from_secs(5))

View file

@ -1,3 +1,6 @@
//! Метрики TUI: парсер Prometheus-exposition и fetcher эндпоинтов. //! TUI metrics: the Prometheus exposition parser and the endpoint fetchers.
//!
//! Owns the read-only side of the TUI: turning `/metrics` text into a
//! [`prometheus::MetricSet`] and pulling the body over HTTP (or a test mock).
pub mod fetch; pub mod fetch;
pub mod prometheus; pub mod prometheus;

View file

@ -1,12 +1,13 @@
//! Минималистичный парсер текстового формата Prometheus (version=0.0.4). //! Minimal parser for the Prometheus text exposition format (version 0.0.4).
//! //!
//! Поддерживает: комментарии (`# HELP`, `# TYPE`, `#`), строки вида //! Owns the parsing rules for `/metrics` bodies. Accepts comment lines
//! `metric{label="value",...} value [timestamp]` и `metric value [timestamp]`. //! (`# HELP`, `# TYPE`, `#`), `metric{label="value",...} value [timestamp]` and
//! Значения `NaN`/`+Inf`/`-Inf` парсятся штатно через `f64::from_str`. //! `metric value [timestamp]`. `NaN`/`+Inf`/`-Inf` are parsed through
//! `f64::from_str`.
use std::collections::BTreeMap; use std::collections::BTreeMap;
/// Один сэмпл из exposition-формата Prometheus. /// One sample from the Prometheus exposition format.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct MetricSample { pub struct MetricSample {
pub name: String, pub name: String,
@ -14,21 +15,23 @@ pub struct MetricSample {
pub value: f64, pub value: f64,
} }
/// Набор сэмплов одного ответа `/metrics`. /// All samples of a single `/metrics` response.
#[derive(Debug, Default, Clone, PartialEq)] #[derive(Debug, Default, Clone, PartialEq)]
pub struct MetricSet { pub struct MetricSet {
samples: Vec<MetricSample>, samples: Vec<MetricSample>,
} }
impl MetricSet { impl MetricSet {
/// Сумма значений всех серий с данным именем (для counter/gauge vec). /// Sums the values of every series with this name (for counter/gauge vecs).
/// Отсутствующая метрика даёт `0.0`. ///
/// A missing metric yields `0.0`.
#[must_use] #[must_use]
pub fn sum(&self, name: &str) -> f64 { pub fn sum(&self, name: &str) -> f64 {
self.samples.iter().filter(|s| s.name == name).map(|s| s.value).sum() self.samples.iter().filter(|s| s.name == name).map(|s| s.value).sum()
} }
/// Значение серии с именем и одной меткой; `None`, если не найдено. /// Value of the series with this name carrying `label == value`, or `None`
/// when no such series exists.
#[must_use] #[must_use]
pub fn labeled(&self, name: &str, label: &str, value: &str) -> Option<f64> { pub fn labeled(&self, name: &str, label: &str, value: &str) -> Option<f64> {
self.samples self.samples
@ -37,17 +40,17 @@ impl MetricSet {
.map(|s| s.value) .map(|s| s.value)
} }
/// Все сэмплы (для тестов и отладки). /// All samples (for tests and debugging).
#[must_use] #[must_use]
pub fn samples(&self) -> &[MetricSample] { pub fn samples(&self) -> &[MetricSample] {
&self.samples &self.samples
} }
} }
/// Парсит тело ответа `/metrics`. /// Parses a `/metrics` response body.
/// ///
/// Строки с ошибкой формата пропускаются (exposition-поток может быть частично /// Lines with a malformed format are skipped: an exposition stream may be
/// повреждён — TUI не должен падать на этом). /// partially corrupted and the TUI must not die because of it.
#[must_use] #[must_use]
pub fn parse(input: &str) -> MetricSet { pub fn parse(input: &str) -> MetricSet {
let mut samples = Vec::new(); let mut samples = Vec::new();
@ -64,18 +67,18 @@ fn parse_line(line: &str) -> Option<MetricSample> {
if line.is_empty() || line.starts_with('#') { if line.is_empty() || line.starts_with('#') {
return None; return None;
} }
// Формат: metric[{labels}] value [timestamp]; значения меток могут // Format: metric[{labels}] value [timestamp]. Label values may contain
// содержать пробелы, поэтому голову отрезаем с учётом кавычек. // spaces, so the head has to be cut with quote awareness.
let (head, rest) = split_head_and_rest(line); let (head, rest) = split_head_and_rest(line);
let value_str = rest.split_whitespace().next()?; let value_str = rest.split_whitespace().next()?;
// Timestamp после value игнорируем. // A timestamp after the value is irrelevant for the TUI and dropped.
let (name, labels) = split_metric(head)?; let (name, labels) = split_metric(head)?;
let value = parse_value(value_str)?; let value = parse_value(value_str)?;
Some(MetricSample { name, labels, value }) Some(MetricSample { name, labels, value })
} }
/// Отделяет `metric{...}` от хвоста `value [timestamp]`. /// Splits `metric{...}` from the trailing `value [timestamp]`.
fn split_head_and_rest(line: &str) -> (&str, &str) { fn split_head_and_rest(line: &str) -> (&str, &str) {
let Some(open) = line.find('{') else { let Some(open) = line.find('{') else {
return match line.find(char::is_whitespace) { return match line.find(char::is_whitespace) {
@ -92,7 +95,7 @@ fn split_head_and_rest(line: &str) -> (&str, &str) {
} }
} }
/// Индекс `}` вне кавычек, начиная с позиции `from`. /// Index of the `}` outside quotes, starting at `from`.
fn find_closing_brace(line: &str, from: usize) -> Option<usize> { fn find_closing_brace(line: &str, from: usize) -> Option<usize> {
let mut in_quotes = false; let mut in_quotes = false;
let mut escaped = false; let mut escaped = false;
@ -138,7 +141,7 @@ fn parse_labels(inner: &str) -> BTreeMap<String, String> {
labels labels
} }
/// Разбивает `a="1", b="2"` по запятым вне кавычек. /// Splits `a="1", b="2"` on commas outside quotes.
fn split_label_pairs(inner: &str) -> Vec<&str> { fn split_label_pairs(inner: &str) -> Vec<&str> {
let mut parts = Vec::new(); let mut parts = Vec::new();
let mut in_quotes = false; let mut in_quotes = false;

View file

@ -1,7 +1,10 @@
//! TUI-модуль Rampart: live-метрики edge-ноды/manager в терминале (ratatui). //! Rampart TUI: live edge-node and manager metrics in the terminal (ratatui).
//! //!
//! Используется бинарём `rampart-tui`; источник данных — Prometheus //! Owns the terminal front end used by the `rampart-tui` binary; the data
//! exposition endpoint (`/metrics`). //! source is the Prometheus exposition endpoint (`/metrics`).
//!
//! The fetch task and the render loop communicate only through
//! [`state::AppState`], so a slow or failing endpoint never blocks the UI.
pub mod app; pub mod app;
pub mod metrics; pub mod metrics;

View file

@ -1,4 +1,8 @@
//! Общее состояние TUI: последний срез метрик, история pps/drops, расчёт rate. //! Shared TUI state: the last metrics snapshot, the pps/drops history and the
//! rate calculation.
//!
//! Owns the only hand-off point between the fetch task and the UI loop; every
//! accessor is mutex-guarded and tolerates a poisoned lock.
use std::collections::VecDeque; use std::collections::VecDeque;
use std::sync::Mutex; use std::sync::Mutex;
@ -6,17 +10,17 @@ use std::time::Instant;
use crate::tui::prometheus::MetricSet; use crate::tui::prometheus::MetricSet;
/// Максимальная длина скользящего окна графика. /// Maximum length of the chart's sliding window.
pub const HISTORY_CAPACITY: usize = 120; pub const HISTORY_CAPACITY: usize = 120;
/// Один сэмпл истории (значения — rates, единиц/сек). /// A single history sample; the values are rates in units per second.
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
pub struct HistoryPoint { pub struct HistoryPoint {
pub packets_per_sec: f64, pub packets_per_sec: f64,
pub drops_per_sec: f64, pub drops_per_sec: f64,
} }
/// Скользящее окно истории фиксированной ёмкости. /// Fixed-capacity sliding window of history samples.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct History { pub struct History {
points: VecDeque<HistoryPoint>, points: VecDeque<HistoryPoint>,
@ -31,7 +35,7 @@ impl Default for History {
} }
impl History { impl History {
/// Добавляет точку, вытесняя старейшую при переполнении окна. /// Appends a point, evicting the oldest one once the window is full.
pub fn push(&mut self, point: HistoryPoint) { pub fn push(&mut self, point: HistoryPoint) {
if self.points.len() == HISTORY_CAPACITY { if self.points.len() == HISTORY_CAPACITY {
self.points.pop_front(); self.points.pop_front();
@ -39,14 +43,14 @@ impl History {
self.points.push_back(point); self.points.push_back(point);
} }
/// Точки в хронологическом порядке. /// Points in chronological order.
#[must_use] #[must_use]
pub fn points(&self) -> &VecDeque<HistoryPoint> { pub fn points(&self) -> &VecDeque<HistoryPoint> {
&self.points &self.points
} }
} }
/// Состояние приложения, общее между fetch-потоком и UI-циклом. /// Application state shared between the fetch task and the UI loop.
#[derive(Debug)] #[derive(Debug)]
pub struct AppState { pub struct AppState {
url: String, url: String,
@ -56,7 +60,7 @@ pub struct AppState {
} }
impl AppState { impl AppState {
/// Создаёт состояние с URL источника метрик (для статус-панели). /// Creates the state for a metrics source URL (shown in the status panel).
#[must_use] #[must_use]
pub fn new(url: impl Into<String>) -> Self { pub fn new(url: impl Into<String>) -> Self {
Self { Self {
@ -67,14 +71,14 @@ impl AppState {
} }
} }
/// URL источника метрик. /// URL of the metrics source.
#[must_use] #[must_use]
pub fn url(&self) -> &str { pub fn url(&self) -> &str {
&self.url &self.url
} }
} }
/// Последний успешный/неуспешный результат fetch. /// Result of the latest successful or failed fetch.
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
pub struct Snapshot { pub struct Snapshot {
pub metrics: Option<MetricSet>, pub metrics: Option<MetricSet>,
@ -83,7 +87,7 @@ pub struct Snapshot {
} }
impl AppState { impl AppState {
/// Записывает результат очередного fetch и обновляет историю rate. /// Records the result of the latest fetch and extends the rate history.
pub fn apply_fetch(&self, result: Result<MetricSet, String>, elapsed_secs: f64) { pub fn apply_fetch(&self, result: Result<MetricSet, String>, elapsed_secs: f64) {
let mut snapshot = match self.snapshot.lock() { let mut snapshot = match self.snapshot.lock() {
Ok(guard) => guard, Ok(guard) => guard,
@ -119,9 +123,9 @@ impl AppState {
} }
} }
/// Копия среза метрик + истории для отрисовки кадра. /// Copy of the metrics snapshot plus history for rendering one frame.
/// ///
/// UI не держит лок — рисуем по снимку. /// The UI never holds a lock: it draws from the copy.
#[must_use] #[must_use]
pub fn frame_data(&self) -> FrameData { pub fn frame_data(&self) -> FrameData {
let snapshot = self.snapshot.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let snapshot = self.snapshot.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
@ -139,21 +143,21 @@ impl AppState {
} }
} }
/// Снимок для одного кадра UI. /// Snapshot consumed by a single UI frame.
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
pub struct FrameData { pub struct FrameData {
/// URL источника метрик. /// URL of the metrics source.
pub url: String, pub url: String,
pub snapshot: Snapshot, pub snapshot: Snapshot,
pub history: History, pub history: History,
/// Время работы TUI (сек). /// TUI uptime in seconds.
pub uptime_secs: u64, pub uptime_secs: u64,
} }
/// Rate счётчика из двух сэмплов: `(current - previous) / dt`. /// Counter rate from two samples: `(current - previous) / dt`.
/// ///
/// `None` у предыдущего значения (первый сэмпл) даёт 0.0. Сброс счётчика /// A `None` previous value (first sample) yields 0.0. A counter reset
/// (`current < previous`) трактуетcя как рестарт процесса → 0.0. /// (`current < previous`) is treated as a process restart and also yields 0.0.
#[must_use] #[must_use]
pub fn counter_rate(previous: Option<f64>, current: Option<f64>, elapsed_secs: f64) -> f64 { pub fn counter_rate(previous: Option<f64>, current: Option<f64>, elapsed_secs: f64) -> f64 {
let (Some(previous), Some(current)) = (previous, current) else { let (Some(previous), Some(current)) = (previous, current) else {

View file

@ -1,4 +1,7 @@
//! Отрисовка кадра ratatui: статус-панель, таблица счётчиков, график pps/drops, помощь. //! ratatui frame rendering: status panel, counters table, pps/drops chart and
//! the key help line.
//!
//! Owns the visual layout only; all values come from [`FrameData`].
use ratatui::Frame; use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::layout::{Constraint, Layout, Rect};
@ -9,7 +12,7 @@ use ratatui::widgets::{Axis, Block, Borders, Chart, Dataset, GraphType, Paragrap
use crate::tui::state::{FrameData, HistoryPoint}; use crate::tui::state::{FrameData, HistoryPoint};
/// Имена метрик edge/manager (см. src/metrics.rs и src/xdp/metrics.rs). /// Edge/manager metric names (see src/metrics.rs and src/xdp/metrics.rs).
mod names { mod names {
pub const XDP_TOTAL: &str = "rampart_xdp_total"; pub const XDP_TOTAL: &str = "rampart_xdp_total";
pub const XDP_TCP: &str = "rampart_xdp_tcp"; pub const XDP_TCP: &str = "rampart_xdp_tcp";
@ -27,7 +30,7 @@ mod names {
pub const ATTACK_STATUS: &str = "rampart_attack_status"; pub const ATTACK_STATUS: &str = "rampart_attack_status";
} }
/// Рисует весь кадр. /// Draws the whole frame.
pub fn render(frame: &mut Frame, data: &FrameData) { pub fn render(frame: &mut Frame, data: &FrameData) {
let [header, body, help] = let [header, body, help] =
Layout::vertical([Constraint::Length(3), Constraint::Min(3), Constraint::Length(1)]).areas(frame.area()); Layout::vertical([Constraint::Length(3), Constraint::Min(3), Constraint::Length(1)]).areas(frame.area());
@ -69,7 +72,7 @@ fn render_header(frame: &mut Frame, area: Rect, data: &FrameData) {
frame.render_widget(Paragraph::new(line).block(Block::new().borders(Borders::ALL)), area); frame.render_widget(Paragraph::new(line).block(Block::new().borders(Borders::ALL)), area);
} }
/// Пары «подпись → имя метрики» для таблицы. /// Counter label to metric name pairs for the table.
const COUNTER_ROWS: &[(&str, &str)] = &[ const COUNTER_ROWS: &[(&str, &str)] = &[
("XDP total", names::XDP_TOTAL), ("XDP total", names::XDP_TOTAL),
("XDP tcp", names::XDP_TCP), ("XDP tcp", names::XDP_TCP),

View file

@ -18,14 +18,14 @@ pub(super) fn interface_cstr(name: &str) -> Result<CString> {
CString::new(name).with_context(|| format!("interface name {name:?} contains an interior NUL byte")) CString::new(name).with_context(|| format!("interface name {name:?} contains an interior NUL byte"))
} }
/// Внутренний data-map `.rodata` ищется по суффиксу: libbpf именует его /// The internal `.rodata` data map is matched by suffix: libbpf names it
/// `<obj_name>.rodata`, а имя объекта при `open_memory` без явного `.name()` /// `<obj_name>.rodata`, and with `open_memory` and no explicit `.name()` the object is
/// вообще `memory` — точное сравнение ломалось на живом ядре (smoke-тест). /// called `memory` — an exact comparison broke on a live kernel (smoke test).
pub(super) fn is_rodata_map(name: &str) -> bool { pub(super) fn is_rodata_map(name: &str) -> bool {
name.ends_with(".rodata") name.ends_with(".rodata")
} }
/// Патчит карту `*.rodata` (volatile const глобалы) ДО загрузки объекта. /// Patches the `*.rodata` map (volatile-const globals) before the object is loaded.
pub(super) fn patch_rodata(open_obj: &mut OpenObject, globals: &XdpGlobals) -> Result<()> { pub(super) fn patch_rodata(open_obj: &mut OpenObject, globals: &XdpGlobals) -> Result<()> {
let image = globals.build_rodata_image(); let image = globals.build_rodata_image();
if !open_obj if !open_obj
@ -42,12 +42,23 @@ pub(super) fn patch_rodata(open_obj: &mut OpenObject, globals: &XdpGlobals) -> R
.maps_mut() .maps_mut()
.find(|m| m.name().to_str().is_some_and(is_rodata_map)) .find(|m| m.name().to_str().is_some_and(is_rodata_map))
.context("rodata map vanished between passes")?; .context("rodata map vanished between passes")?;
// libbpf rejects a value whose size differs from the map's (EINVAL, and the
// error message says nothing useful). Fail loudly here instead: a mismatch
// means `struct rampart_config` in config.h and `XdpGlobals` drifted apart.
let expected = map.value_size() as usize;
if image.len() != expected {
bail!(
"XDP .rodata map expects {expected} bytes, loader image has {} — \
struct rampart_config (xdp/core/config.h) and XdpGlobals (src/xdp/globals.rs) diverged",
image.len()
);
}
map.set_initial_value(&image) map.set_initial_value(&image)
.with_context(|| format!("failed to set initial value of '{RODATA_MAP_NAME}'")) .with_context(|| format!("failed to set initial value of '{RODATA_MAP_NAME}'"))
} }
/// Честное имя режима attach по `attach_mode` из `bpf_xdp_query_opts` /// Honest name of the attach mode, derived from the `attach_mode` field of
/// (kernel `enum xdp_attached_mode`: NONE=0, DRV=1, OFFLOAD=2, SKB=3). /// `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 { pub(super) fn xdp_attach_mode_name(mode: u8) -> &'static str {
match mode { match mode {
1 => "native (drv)", 1 => "native (drv)",
@ -57,13 +68,13 @@ pub(super) fn xdp_attach_mode_name(mode: u8) -> &'static str {
} }
} }
/// Собирает ringbuf-колбэк для `events_map`. /// Builds the ringbuf callback for `events_ringbuf`.
/// ///
/// Колбэк обязан быть `'static`, поэтому всё разделяемое состояние (`Arc<Blacklist>`, /// The callback must be `'static`, so all shared state (`Arc<Blacklist>`, a copy of
/// копия `AutoBanConfig`) захватывается `move`-клонами. Когда `blacklist` — `None` /// `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
/// логируются структурированно; баны не пишутся. В горячем пути нет `format!` — /// way; no bans are written. The hot path does no `format!` — only `tracing` fields and
/// `tracing`-поля и `&'static str` причины. /// `&'static str` reasons.
pub(super) fn build_ringbuf( pub(super) fn build_ringbuf(
obj: &Object, obj: &Object,
blacklist: Option<Arc<Blacklist>>, blacklist: Option<Arc<Blacklist>>,
@ -71,8 +82,8 @@ pub(super) fn build_ringbuf(
) -> Result<RingBuffer<'static>> { ) -> Result<RingBuffer<'static>> {
let map = obj let map = obj
.maps() .maps()
.find(|m| m.name() == "events_map") .find(|m| m.name() == "events_ringbuf")
.context("events_map not found")?; .context("events_ringbuf not found")?;
let mut builder = RingBufferBuilder::new(); let mut builder = RingBufferBuilder::new();
builder.add(&map, move |data: &[u8]| { builder.add(&map, move |data: &[u8]| {
let Some(event) = parse_xdp_event(data) else { let Some(event) = parse_xdp_event(data) else {
@ -93,10 +104,10 @@ pub(super) fn build_ringbuf(
}; };
if let Some(ban) = auto_ban_decision(&event, &cfg) { if let Some(ban) = auto_ban_decision(&event, &cfg) {
let addr = IpAddr::V4(ban.ip); let addr = IpAddr::V4(ban.ip);
// `Blacklist::add` возвращает `()` (DashMap::insert игнорируется), а // `Blacklist::add` returns `()` (it ignores `DashMap::insert`) and blacklist.rs is
// править blacklist.rs вне нашей зоны нельзя — поэтому «новый ли бан» // out of our edit scope, so "is this a new ban" is decided through the public
// определяем через публичный `is_blocked` ДО перезаписи. Это дедуп // `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); let already_banned = blacklist.is_blocked(addr);
blacklist.add(addr, Duration::from_secs(ban.duration_secs), ban.reason); blacklist.add(addr, Duration::from_secs(ban.duration_secs), ban.reason);
if already_banned { if already_banned {
@ -134,8 +145,8 @@ mod tests {
#[test] #[test]
fn rodata_map_matches_libbpf_naming() { fn rodata_map_matches_libbpf_naming() {
// libbpf строит имя `<obj><section>` без замены точки (libbpf.c ~1911), // libbpf builds the name as `<obj><section>` without rewriting the dot
// при open_memory без name объект называется "memory": // (libbpf.c ~1911); with open_memory and no name the object is called "memory":
assert!(is_rodata_map("rampart.rodata")); assert!(is_rodata_map("rampart.rodata"));
assert!(is_rodata_map("memory.rodata")); assert!(is_rodata_map("memory.rodata"));
assert!(is_rodata_map(".rodata")); assert!(is_rodata_map(".rodata"));

View file

@ -1,32 +1,32 @@
//! Разбор и политика для событий XDP-ringbuf (`struct xdp_event`). //! Parsing and policy for XDP ringbuf events (`struct xdp_event`).
//! //!
//! Чистые (без I/O, без libbpf) функции, чтобы их можно было покрыть //! Pure functions (no I/O, no libbpf) so that they can be covered by unit tests without
//! юнит-тестами без ядра/Redis. Wiring колбэка — в [`super::attach`]. //! a kernel or Redis. The callback wiring lives in [`super::attach`].
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use crate::config::XdpConfig; use crate::config::XdpConfig;
/// Точный размер `struct xdp_event` (см. `xdp/core/common.h:61-66`): /// Exact size of `struct xdp_event` (see `xdp/core/common.h:61-66`):
/// `__u32 type` @0, `__u32 src_ip` @4, `__u32 metadata` @8, /// `__u32 type` @0, `__u32 src_ip` @4, `__u32 metadata` @8,
/// 4 байта padding @12 (выравнивание `__u64`), `__u64 timestamp` @16 → 24. /// 4 bytes of padding @12 (to align `__u64`), `__u64 timestamp` @16 -> 24.
pub const XDP_EVENT_LEN: usize = 24; pub const XDP_EVENT_LEN: usize = 24;
/// Тип события из `enum event_type` (`common.h:54-59`). /// Event type from `enum event_type` (`common.h:54-59`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XdpEventKind { pub enum XdpEventKind {
/// `EVENT_BAN` — пакет уже был в blacklist_map и сброшен ядром. /// `EVENT_BAN` — the packet was already in `blacklist_map` and was dropped by the kernel.
Ban, Ban,
/// `EVENT_RATE_LIMIT` — превышен порог троттлинга (SYN/UDP). /// `EVENT_RATE_LIMIT` — the throttling threshold was exceeded (SYN/UDP).
RateLimit, RateLimit,
/// `EVENT_POLICY_DROP` — статичная политика (UDP drop / вредоносные TCP-флаги). /// `EVENT_POLICY_DROP` — a static policy match (UDP drop / malicious TCP flags).
PolicyDrop, PolicyDrop,
/// `EVENT_CONN_DROP` — flow сброшен (несоответствие seq или verdict хука). /// `EVENT_CONN_DROP` — the flow was dropped (sequence mismatch or a hook verdict).
ConnDrop, ConnDrop,
} }
impl XdpEventKind { impl XdpEventKind {
/// Декодирует числовое значение из C-enum. Неизвестный тип → `None` + debug. /// Decodes the numeric value of the C enum. An unknown type yields `None` plus a debug log.
fn from_u32(raw: u32) -> Option<Self> { fn from_u32(raw: u32) -> Option<Self> {
match raw { match raw {
0 => Some(Self::Ban), 0 => Some(Self::Ban),
@ -41,41 +41,43 @@ impl XdpEventKind {
} }
} }
/// Разобранное событие ringbuf. /// A parsed ringbuf event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct XdpEvent { pub struct XdpEvent {
pub kind: XdpEventKind, pub kind: XdpEventKind,
/// IPv4 источника (для IPv4-mapped IPv6 ядро кладёт в `src_ip` младший u32). /// Source IPv4 address (for IPv4-mapped IPv6 the kernel stores the low u32 in `src_ip`).
pub src_ip: Ipv4Addr, pub src_ip: Ipv4Addr,
/// Поле `__u32 metadata`: для `RateLimit` — порог срабатывания троттлинга, /// The `__u32 metadata` field: for `RateLimit` the throttling threshold that fired, for
/// для `ConnDrop` — счётчик `conn->fails`, иначе `0`. /// `ConnDrop` the `conn->fails` counter, `0` otherwise.
pub metadata: u32, pub metadata: u32,
/// `bpf_ktime_get_ns()` на момент генерации (monotonic, не wall-clock). /// `bpf_ktime_get_ns()` at generation time (monotonic, not wall clock).
pub timestamp_ns: u64, pub timestamp_ns: u64,
} }
/// Разбирает 24-байтовый кадр `struct xdp_event`. /// Parses a 24-byte `struct xdp_event` frame.
/// ///
/// # Byte order (проверено по C-источнику) /// # Byte order (verified against the C source)
/// Скалярные поля (`type`, `metadata`, `timestamp`) пишутся ядром в ПОРЯДКЕ ХОСТА /// The scalar fields (`type`, `metadata`, `timestamp`) are written by the kernel in host
/// без конверсии: `push_event` присваивает их как есть — `e->type = type`, /// order without conversion: `push_event` assigns them as they are — `e->type = type`,
/// `e->metadata = meta`, `e->timestamp = bpf_ktime_get_ns()` /// `e->metadata = meta`, `e->timestamp = bpf_ktime_get_ns()` (`common.h:92-95`; no
/// (`common.h:92-95`, `bpf_htonl`/`bpf_ntohl` к ним НЕ применяется). Userspace /// `bpf_htonl`/`bpf_ntohl` is applied). Userspace reads the same bytes on the same
/// читает те же байты на той же машине → `from_ne_bytes` корректно. /// machine, so `from_ne_bytes` is correct.
/// ///
/// А вот `src_ip` — сетевой порядок (big-endian octets): он приходит прямо из /// `src_ip` is different: it is in network order (big-endian octets) because it comes
/// заголовка пакета `src_ip = ip->saddr` (`universal_filter.c:149`) и пишется в /// straight from the packet header as `src_ip = ip->saddr` (`universal_filter.c:149`)
/// событие без `bpf_htonl` (`common.h:93`). Значит байты `data[4..8]` — это октеты /// and is copied into the event without `bpf_htonl` (`common.h:93`). Bytes `data[4..8]`
/// адреса в точковом порядке, и читать их надо как `Ipv4Addr::new(octets...)`, а НЕ /// are therefore the address octets in dotted order and must be read as
/// как `from_ne_bytes(u32)` (прежний баг: на LE-хосте давал перевернутый IP). /// `Ipv4Addr::new(octets...)`, not as `from_ne_bytes(u32)` (the old bug produced a
/// reversed IP on little-endian hosts).
/// ///
/// Возвращает `None`, если кадр короче `XDP_EVENT_LEN` или тип неизвестен. /// Returns `None` if the frame is shorter than `XDP_EVENT_LEN` or the type is unknown.
pub fn parse_xdp_event(bytes: &[u8]) -> Option<XdpEvent> { pub fn parse_xdp_event(bytes: &[u8]) -> Option<XdpEvent> {
let raw: &[u8; XDP_EVENT_LEN] = bytes.get(..XDP_EVENT_LEN)?.try_into().ok()?; let raw: &[u8; XDP_EVENT_LEN] = bytes.get(..XDP_EVENT_LEN)?.try_into().ok()?;
let kind = XdpEventKind::from_u32(u32::from_ne_bytes(raw[0..4].try_into().ok()?))?; let kind = XdpEventKind::from_u32(u32::from_ne_bytes(raw[0..4].try_into().ok()?))?;
let src_ip = Ipv4Addr::new(raw[4], raw[5], raw[6], raw[7]); let src_ip = Ipv4Addr::new(raw[4], raw[5], raw[6], raw[7]);
let metadata = u32::from_ne_bytes(raw[8..12].try_into().ok()?); let metadata = u32::from_ne_bytes(raw[8..12].try_into().ok()?);
// raw[12..16] — выравнивающий padding под __u64, не читаем (он не инициализирован). // `raw[12..16]` is alignment padding for `__u64`; it is not read because the kernel
// never initialises it.
let timestamp_ns = u64::from_ne_bytes(raw[16..24].try_into().ok()?); let timestamp_ns = u64::from_ne_bytes(raw[16..24].try_into().ok()?);
Some(XdpEvent { Some(XdpEvent {
kind, kind,
@ -85,7 +87,7 @@ pub fn parse_xdp_event(bytes: &[u8]) -> Option<XdpEvent> {
}) })
} }
/// Параметры авто-бана, резолвинг из секции `[xdp]`. /// Auto-ban parameters, resolved from the `[xdp]` section.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AutoBanConfig { pub struct AutoBanConfig {
pub enabled: bool, pub enabled: bool,
@ -104,7 +106,7 @@ impl Default for AutoBanConfig {
} }
impl AutoBanConfig { impl AutoBanConfig {
/// Берёт значения из `[xdp]`-секции конфига (единственный источник истины). /// Takes the values from the `[xdp]` config section (the single source of truth).
pub fn from_xdp(cfg: &XdpConfig) -> Self { pub fn from_xdp(cfg: &XdpConfig) -> Self {
Self { Self {
enabled: cfg.auto_ban_enabled, enabled: cfg.auto_ban_enabled,
@ -114,33 +116,35 @@ impl AutoBanConfig {
} }
} }
/// Готовый бан для применения к userspace-`Blacklist`. /// A ready-to-apply ban for the userspace `Blacklist`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BanAction { pub struct BanAction {
pub ip: Ipv4Addr, pub ip: Ipv4Addr,
pub duration_secs: u64, pub duration_secs: u64,
/// Статичная причина (без аллокаций в горячем пути). /// Static reason (no allocation on the hot path).
pub reason: &'static str, pub reason: &'static str,
} }
/// Чистое решение: банить ли источник события и на сколько. /// Pure decision: whether the event source should be banned and for how long.
/// ///
/// Возвращает `None`, если фича выключена или тип события не банится. /// Returns `None` when the feature is disabled or the event type is not bannable. The
/// Разбор по типам обоснован C-кодом: /// per-type split follows the C code:
/// ///
/// * [`XdpEventKind::Ban`] — НЕ баним. Событие эмитится уже ПОСЛЕ того, как /// * [`XdpEventKind::Ban`] — not banned. The event is emitted only after the kernel has
/// ядро нашло IP в `blacklist_map` и дропнуло пакет (`universal_filter.c:220-225`); /// already found the IP in `blacklist_map` and dropped the packet
/// повторный userspace-бан бессмысленен и мог бы скрыть штатный expiry. /// (`universal_filter.c:220-225`), so a second userspace ban is pointless and could
/// * [`XdpEventKind::PolicyDrop`] — НЕ баним по умолчанию. Это статичная /// mask the regular expiry.
/// политика на каждый пакет: UDP-drop-политика (`:234`) и вредоносные TCP-флаги /// * [`XdpEventKind::PolicyDrop`] — not banned by default. This is a static per-packet
/// (`:259`). Бан по одному malformed-пакету перебанит легитимных, но глючных /// policy: the UDP drop policy (`:234`) and malicious TCP flags (`:259`). Banning on a
/// клиентов — порог аккумулирования здесь отсутствует по смыслу. /// single malformed packet would re-ban legitimate but buggy clients, and there is no
/// * [`XdpEventKind::RateLimit`] — банیم. Порог троттлинга уже фактически превышен; /// accumulation threshold here by design.
/// при этом UDP-путь (`:237-243`) только дропает и НЕ заносит в blacklist (в /// * [`XdpEventKind::RateLimit`] — banned. The throttling threshold has already been
/// отличие от SYN-пути `:295`) — userspace-бан добавляет реальную защиту. /// exceeded; the UDP path (`:237-243`) only drops and does not insert into the
/// * [`XdpEventKind::ConnDrop`] — баним, только если `metadata` (=`conn->fails`) /// blacklist (unlike the SYN path at `:295`), so the userspace ban adds real
/// достиг порога (`:364-368`). Дроп по протокольному хуку приходит с `fails = 0` /// protection.
/// (`:418`) и ниже порога, т.е. не банится. /// * [`XdpEventKind::ConnDrop`] — banned only when `metadata` (= `conn->fails`) reached
/// the threshold (`:364-368`). A protocol-hook drop arrives with `fails = 0` (`:418`),
/// below the threshold, so it is not banned.
#[must_use] #[must_use]
pub fn auto_ban_decision(event: &XdpEvent, config: &AutoBanConfig) -> Option<BanAction> { pub fn auto_ban_decision(event: &XdpEvent, config: &AutoBanConfig) -> Option<BanAction> {
if !config.enabled { if !config.enabled {
@ -162,5 +166,5 @@ pub fn auto_ban_decision(event: &XdpEvent, config: &AutoBanConfig) -> Option<Ban
} }
} }
// Покрытие парсера и политики — в `tests/xdp_events.rs` (держим модуль под // Parser and policy coverage lives in `tests/xdp_events.rs` (this module is kept under
// лимитом 250 строк; `src/xdp/filter/` уже на пределе в 4 файла на каталог). // the 250-line limit; `src/xdp/filter/` already has the maximum of 4 files per directory).

View file

@ -41,28 +41,29 @@ impl XdpFilter {
} }
} }
/// Задаёт глобалы для патчинга `.rodata` при следующем `load()`. /// Sets the globals used to patch `.rodata` on the next `load()`.
pub fn set_globals(&mut self, globals: XdpGlobals) { pub fn set_globals(&mut self, globals: XdpGlobals) {
self.globals = globals; self.globals = globals;
} }
/// Подключает OPT-IN авто-бан по ringbuf-событиям к userspace-`Blacklist`. /// Wires the opt-in auto-ban from ringbuf events into the userspace `Blacklist`.
/// ///
/// До вызова `load()`. Политика читается из `[xdp]`-секции; если /// Must be called before `load()`. The policy is read from the `[xdp]` section; when
/// `auto_ban_enabled = false` (по умолчанию), колбэк лишь логирует события и /// `auto_ban_enabled = false` (the default) the callback only logs events and never
/// не трогает blacklist. /// touches the blacklist.
pub fn set_autoban(&mut self, blacklist: Arc<Blacklist>, config: &XdpConfig) { pub fn set_autoban(&mut self, blacklist: Arc<Blacklist>, config: &XdpConfig) {
self.blacklist = Some(blacklist); self.blacklist = Some(blacklist);
self.autoban = AutoBanConfig::from_xdp(config); self.autoban = AutoBanConfig::from_xdp(config);
} }
pub fn load(&mut self) -> Result<()> { pub fn load(&mut self) -> Result<()> {
// Диагностика ДО загрузки: fail-fast на неподдерживаемом ядре/драйвере. // Diagnostics before loading: fail fast on an unsupported kernel or driver.
super::probe::preflight(&self.interface)?; super::probe::preflight(&self.interface)?;
let bpf_obj = include_bytes!(concat!(env!("OUT_DIR"), "/universal_filter.o")); let bpf_obj = include_bytes!(concat!(env!("OUT_DIR"), "/universal_filter.o"));
// Имя объекта задаётся ЯВНО: при open_memory libbpf не знает имени файла, // The object name is set explicitly: with `open_memory` libbpf does not know the
// а по нему именуются внутренние maps ("rampart_.rodata" в patch_rodata). // file name, yet the internal maps are named after it (`rampart_.rodata`, see
// `patch_rodata`).
let mut open_obj = ObjectBuilder::default() let mut open_obj = ObjectBuilder::default()
.name("rampart") .name("rampart")
.context("failed to set BPF object name")? .context("failed to set BPF object name")?
@ -87,9 +88,9 @@ impl XdpFilter {
.find(|p| p.name() == "rampart_universal_filter") .find(|p| p.name() == "rampart_universal_filter")
.context("XDP program 'rampart_universal_filter' not found")?; .context("XDP program 'rampart_universal_filter' not found")?;
let xdp = Xdp::new(prog.as_fd()); let xdp = Xdp::new(prog.as_fd());
// Лестница режимов: пробуем native (drv); если драйвер не тянет — // Mode ladder: try native (drv) first; if the driver cannot handle it, fall back to
// честный fallback в generic (skb) с предупреждением (вывод №1 из // 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; let ifindex = ifindex as i32;
if let Err(e) = xdp.attach(ifindex, XdpFlags::NONE) { if let Err(e) = xdp.attach(ifindex, XdpFlags::NONE) {
tracing::warn!( tracing::warn!(
@ -167,10 +168,10 @@ impl XdpFilter {
.with_context(|| format!("map '{}' not found", name)) .with_context(|| format!("map '{}' not found", name))
} }
/// Читает карту `prefix_stats` (агрегаты по префиксам /24 и /64). /// Reads the `prefix_stats` map (aggregates per /24 and /64 prefix).
/// ///
/// # Errors /// # Errors
/// XDP не загружен, карта отсутствует в объекте или ошибка BPF-чтения. /// XDP is not loaded, the map is missing from the object, or a BPF read fails.
pub fn read_prefix_stats(&self) -> Result<Vec<(PrefixKey, PrefixStatsVal)>> { pub fn read_prefix_stats(&self) -> Result<Vec<(PrefixKey, PrefixStatsVal)>> {
let map = self.find_map("prefix_stats")?; let map = self.find_map("prefix_stats")?;
let mut out = Vec::new(); let mut out = Vec::new();

View file

@ -1,53 +1,58 @@
//! Патчинг volatile const глобалов XDP-программы (`xdp/core/config.h`) из TOML-конфига. //! Patches the XDP program's volatile-const globals (`xdp/core/config.h`) from the TOML config.
//! //!
//! Глобалы живут в секции `.rodata`, которая при загрузке превращается в карту //! The globals live in the `.rodata` section, which libbpf turns into a map named
//! с именем `rampart_.rodata`. Образ патчится до `load()` через //! `rampart_.rodata` on load. The image is patched before `load()` via
//! `OpenMapMut::set_initial_value()` (см. [`crate::xdp::filter`]). //! `OpenMapMut::set_initial_value()` (see [`crate::xdp::filter`]).
//! //!
//! # Схема маппинга `[xdp]` → G_* (единственный источник истины) //! # `[xdp]` -> `G_*` mapping (single source of truth)
//! //!
//! | Конфиг | Глобал | Тип | //! | Config key | Global | Type |
//! |-------------------------|------------------------------|-----| //! |-------------------------|------------------------------|-----|
//! | `protected_port_start` | `G_START_PORT` | u16 | //! | `protected_port_start` | `G_START_PORT` | u16 |
//! | `protected_port_end` | `G_END_PORT` | u16 | //! | `protected_port_end` | `G_END_PORT` | u16 |
//! | `udp_policy` | `G_UDP_POLICY` | u8 ("pass"=0, "drop"=1, "rate-limit"=2) | //! | `udp_policy` | `G_UDP_POLICY` | u8 ("pass"=0, "drop"=1, "rate-limit"=2) |
//! | `udp_rate_hit_count` | `G_UDP_HIT_COUNT` | u32 | //! | `udp_rate_hit_count` | `G_UDP_HIT_COUNT` | u32 |
//! | `udp_rate_window_ms` | `G_UDP_WINDOW_NS` | u64 (мс → нс) | //! | `udp_rate_window_ms` | `G_UDP_WINDOW_NS` | u64 (ms -> ns) |
//! | `throttle_enabled` | `G_FEATURE_SYN_THROTTLE` | u8 (bool → 0/1) | //! | `throttle_enabled` | `G_FEATURE_SYN_THROTTLE` | u8 (bool -> 0/1) |
//! | `events_enabled` | `G_FEATURE_EVENTS` | u8 (bool → 0/1) | //! | `events_enabled` | `G_FEATURE_EVENTS` | u8 (bool -> 0/1) |
//! | `syn_challenge_enabled` | `G_SYN_CHALLENGE_ENABLED` | u8 (bool → 0/1) | //! | `syn_challenge_enabled` | `G_SYN_CHALLENGE_ENABLED` | u8 (bool -> 0/1) |
//! | `challenge_secret_hex` | `G_CHALLENGE_SECRET` | u64 (hex, big-endian) | //! | `challenge_secret_hex` | `G_CHALLENGE_SECRET` | u64 (hex, big-endian) |
//! | `challenge_timeout_ms` | `G_CHALLENGE_TIMEOUT_MS` | u32 | //! | `challenge_timeout_ms` | `G_CHALLENGE_TIMEOUT_MS` | u32 |
//! //!
//! Остальные глобалы (`G_SYN_*`, `G_CONNTRACK_IDLE_NS`, `G_PLAYER_IDLE_NS`, //! The remaining globals (`G_SYN_*`, `G_CONNTRACK_IDLE_NS`, `G_PLAYER_IDLE_NS`,
//! `G_BAN_DURATION_NS`, `G_MAX_OUT_OF_ORDER`, `G_CHALLENGE_VERIFIED_TTL_NS`) //! `G_BAN_DURATION_NS`, `G_MAX_OUT_OF_ORDER`, `G_CHALLENGE_VERIFIED_TTL_NS`) are not
//! конфигом пока не управляются и патчатся значениями по умолчанию из config.h. //! configurable yet; they are patched with the defaults from config.h.
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use std::mem::offset_of;
use crate::config::XdpConfig; use crate::config::XdpConfig;
/// Имя карты с образом `.rodata` загруженного BPF-объекта. /// Name of the map holding the loaded BPF object's `.rodata` image.
/// Имя внутренней `.rodata`-карты при `ObjectBuilder::name("rampart")`: ///
/// libbpf конструирует `<obj_name><section>` без замены точки (sanitizer /// This is the name of libbpf's internal `.rodata` map when the object is built with
/// пропускаёт `.`; libbpf.c, map name logic) → `rampart.rodata`. /// `ObjectBuilder::name("rampart")`: libbpf concatenates `<obj_name><section>` without
/// Поиск в `patch_rodata` всё равно по суффиксу — имя здесь для диагностики. /// rewriting the dot (the sanitizer passes `.` through; see libbpf.c map naming), so the
/// result is `rampart.rodata`. `patch_rodata` matches by suffix anyway, so the name is
/// only used for diagnostics.
pub(crate) const RODATA_MAP_NAME: &str = "rampart.rodata"; pub(crate) const RODATA_MAP_NAME: &str = "rampart.rodata";
/// Размер образа `.rodata` в байтах (см. `build_rodata_image`). /// Size of the `.rodata` image in bytes: exactly `sizeof(struct rampart_config)` from
pub const RODATA_SIZE: usize = 96; /// `xdp/core/config.h`, which `XdpGlobals` (`#[repr(C)]`) mirrors field for field.
pub const RODATA_SIZE: usize = std::mem::size_of::<XdpGlobals>();
/// Значение `G_UDP_POLICY`: пропускать UDP. /// `G_UDP_POLICY` value: pass UDP through.
pub const UDP_POLICY_PASS: u8 = 0; pub const UDP_POLICY_PASS: u8 = 0;
/// Значение `G_UDP_POLICY`: дропать весь UDP. /// `G_UDP_POLICY` value: drop all UDP.
pub const UDP_POLICY_DROP: u8 = 1; pub const UDP_POLICY_DROP: u8 = 1;
/// Значение `G_UDP_POLICY`: rate-limit по окну/порогу. /// `G_UDP_POLICY` value: rate-limit per window/threshold.
pub const UDP_POLICY_RATE_LIMIT: u8 = 2; pub const UDP_POLICY_RATE_LIMIT: u8 = 2;
/// Дефолт-плейсхолдер `G_CHALLENGE_SECRET` из config.h. /// Default placeholder for `G_CHALLENGE_SECRET` from config.h.
const DEFAULT_CHALLENGE_SECRET: u64 = 0xA5A5_A5A5_A5A5_A5A5; const DEFAULT_CHALLENGE_SECRET: u64 = 0xA5A5_A5A5_A5A5_A5A5;
/// Runtime-значения глобалов XDP-программы; `Default` совпадает с config.h. /// Runtime values of the XDP program globals; `Default` matches config.h.
#[repr(C)]
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct XdpGlobals { pub struct XdpGlobals {
pub start_port: u16, pub start_port: u16,
@ -96,53 +101,55 @@ impl Default for XdpGlobals {
} }
impl XdpGlobals { impl XdpGlobals {
/// Собирает байтовый образ `.rodata` в порядке объявления глобалов /// Builds the byte image of `.rodata`: a mirror of `struct rampart_config` from
/// в `xdp/core/config.h` с естественным выравниванием каждого поля. /// `xdp/core/config.h`.
/// ///
/// RISK: раскладка предполагает, что линкер кладёт статические переменные /// Offsets come from the `#[repr(C)]` type itself (`offset_of!`) instead of being
/// в секцию `.rodata` в порядке объявления с natural alignment — на /// hardcoded, because the layout is defined by the C struct — not by the symbol order
/// практике это так (каждая `static volatile const` получает своё /// the linker happens to pick.
/// выравнивание, padding виден в смещениях ниже), но стандарт C этого не
/// гарантирует. TODO: верифицировать смещения на сервере через BTF-dump
/// карты `rampart_.rodata` (`bpftool btf dump`) и зафиксировать их здесь.
pub fn build_rodata_image(&self) -> Vec<u8> { pub fn build_rodata_image(&self) -> Vec<u8> {
let mut img = vec![0u8; RODATA_SIZE]; let mut img = vec![0u8; RODATA_SIZE];
// u16 ×2 без padding: смещения 0..4. let put16 = |img: &mut [u8], off: usize, v: u16| img[off..off + 2].copy_from_slice(&v.to_le_bytes());
img[0..2].copy_from_slice(&self.start_port.to_le_bytes()); let put32 = |img: &mut [u8], off: usize, v: u32| img[off..off + 4].copy_from_slice(&v.to_le_bytes());
img[2..4].copy_from_slice(&self.end_port.to_le_bytes()); let put64 = |img: &mut [u8], off: usize, v: u64| img[off..off + 8].copy_from_slice(&v.to_le_bytes());
// u32, align 4: 4..8. put16(&mut img, offset_of!(Self, start_port), self.start_port);
img[4..8].copy_from_slice(&self.syn_hit_count.to_le_bytes()); put16(&mut img, offset_of!(Self, end_port), self.end_port);
// u64, align 8: 8..48 (SYN throttle + idle timeouts + ban duration). put32(&mut img, offset_of!(Self, syn_hit_count), self.syn_hit_count);
img[8..16].copy_from_slice(&self.syn_window_ns.to_le_bytes()); put64(&mut img, offset_of!(Self, syn_window_ns), self.syn_window_ns);
img[16..24].copy_from_slice(&self.syn_ban_duration_ns.to_le_bytes()); put64(
img[24..32].copy_from_slice(&self.conntrack_idle_ns.to_le_bytes()); &mut img,
img[32..40].copy_from_slice(&self.player_idle_ns.to_le_bytes()); offset_of!(Self, syn_ban_duration_ns),
img[40..48].copy_from_slice(&self.ban_duration_ns.to_le_bytes()); self.syn_ban_duration_ns,
// u8 ×3 подряд: 48, 49, 50 (max_out_of_order, udp_policy, —). );
img[48] = self.max_out_of_order; put64(&mut img, offset_of!(Self, conntrack_idle_ns), self.conntrack_idle_ns);
img[49] = self.udp_policy; put64(&mut img, offset_of!(Self, player_idle_ns), self.player_idle_ns);
// u32 после u8: padding 50..52, значение 52..56. put64(&mut img, offset_of!(Self, ban_duration_ns), self.ban_duration_ns);
img[52..56].copy_from_slice(&self.udp_hit_count.to_le_bytes()); img[offset_of!(Self, max_out_of_order)] = self.max_out_of_order;
// u64, align 8: 56..64. img[offset_of!(Self, udp_policy)] = self.udp_policy;
img[56..64].copy_from_slice(&self.udp_window_ns.to_le_bytes()); put32(&mut img, offset_of!(Self, udp_hit_count), self.udp_hit_count);
// u8 ×3 (feature flags + challenge flag): 64, 65, 66. put64(&mut img, offset_of!(Self, udp_window_ns), self.udp_window_ns);
img[64] = u8::from(self.feature_syn_throttle); img[offset_of!(Self, feature_syn_throttle)] = u8::from(self.feature_syn_throttle);
img[65] = u8::from(self.feature_events); img[offset_of!(Self, feature_events)] = u8::from(self.feature_events);
img[66] = u8::from(self.syn_challenge_enabled); img[offset_of!(Self, syn_challenge_enabled)] = u8::from(self.syn_challenge_enabled);
// u64 после u8: padding 67..72, значение 72..80. put64(&mut img, offset_of!(Self, challenge_secret), self.challenge_secret);
img[72..80].copy_from_slice(&self.challenge_secret.to_le_bytes()); put32(
// u32: 80..84. &mut img,
img[80..84].copy_from_slice(&self.challenge_timeout_ms.to_le_bytes()); offset_of!(Self, challenge_timeout_ms),
// u64 после u32: padding 84..88, значение 88..96. self.challenge_timeout_ms,
img[88..96].copy_from_slice(&self.challenge_verified_ttl_ns.to_le_bytes()); );
put64(
&mut img,
offset_of!(Self, challenge_verified_ttl_ns),
self.challenge_verified_ttl_ns,
);
img img
} }
/// Строит глобалы из секции `[xdp]` конфига. /// Builds the globals from the `[xdp]` section of the config.
/// ///
/// # Errors /// # Errors
/// Неизвестное значение `udp_policy`; некорректный `challenge_secret_hex` /// Unknown `udp_policy` value; malformed `challenge_secret_hex` (not hex, or not
/// (не hex или не 8 байт); `protected_port_end < protected_port_start`. /// 8 bytes); `protected_port_end < protected_port_start`.
pub fn from_config(cfg: &XdpConfig) -> Result<Self> { pub fn from_config(cfg: &XdpConfig) -> Result<Self> {
let mut g = Self { let mut g = Self {
start_port: cfg.protected_port_start, start_port: cfg.protected_port_start,
@ -175,7 +182,8 @@ impl XdpGlobals {
} }
} }
/// Парсит 128-битный hex (16 символов, опциональный префикс `0x`) в u64 (big-endian). /// Parses a 16-hex-digit secret (8 bytes, optional `0x` prefix) into a big-endian u64.
/// `_`, `:` and `-` separators are ignored.
fn parse_secret_hex(s: &str) -> Result<u64> { fn parse_secret_hex(s: &str) -> Result<u64> {
let cleaned = s.trim().trim_start_matches("0x").replace(['_', ':', '-'], ""); let cleaned = s.trim().trim_start_matches("0x").replace(['_', ':', '-'], "");
let bytes = hex::decode(&cleaned).with_context(|| format!("invalid xdp.challenge_secret_hex '{s}'"))?; let bytes = hex::decode(&cleaned).with_context(|| format!("invalid xdp.challenge_secret_hex '{s}'"))?;

View file

@ -1,20 +1,21 @@
//! Prometheus-метрики загрузчика XDP. //! Prometheus metrics of the XDP loader.
//! //!
//! Регистрируются в глобальный реестр `prometheus` (тот же, что собирает //! They register into the global `prometheus` registry — the same one that
//! `prometheus::gather()` в `crate::metrics::run_metrics_server`), поэтому //! `prometheus::gather()` in `crate::metrics::run_metrics_server` scrapes — so the
//! endpoint `/metrics` подхватывает их без правок вне `src/xdp/`. //! `/metrics` endpoint picks them up without changes outside `src/xdp/`.
use prometheus::{IntCounter, register_int_counter}; use prometheus::{IntCounter, register_int_counter};
use std::sync::LazyLock; use std::sync::LazyLock;
/// Сколько раз событие XDP-ringbuf привело к userspace-авто-бану /// How many times an XDP ringbuf event resulted in a userspace auto-ban.
/// (счётчик инкрементится только на НОВЫЙ бан, не на продление). ///
/// The counter is incremented only for a new ban, never for a refresh of an active one.
pub static XDP_AUTOBANS_TOTAL: LazyLock<IntCounter> = LazyLock::new(|| { pub static XDP_AUTOBANS_TOTAL: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!("rampart_xdp_autobans_total", "Auto-bans issued from XDP ringbuf events") register_int_counter!("rampart_xdp_autobans_total", "Auto-bans issued from XDP ringbuf events")
.expect("XDP_AUTOBANS_TOTAL") .expect("XDP_AUTOBANS_TOTAL")
}); });
/// Форсирует регистрацию счётчика (для вызова на старте загрузки XDP). /// Forces registration of the counter (called at the start of the XDP load).
pub fn init() { pub fn init() {
LazyLock::force(&XDP_AUTOBANS_TOTAL); LazyLock::force(&XDP_AUTOBANS_TOTAL);
} }

View file

@ -1,4 +1,8 @@
//! Загрузчик XDP-программы (L3/L4-уровень защиты). //! Loader for the XDP program (L3/L4 protection layer).
//!
//! Owns the filter lifecycle (`XdpFilter`), the `.rodata` globals image (`XdpGlobals`),
//! ringbuf event parsing, XDP metrics and the pre-attach environment probe. Without the
//! `xdp` feature a no-op filter is exported instead.
mod probe; mod probe;
pub use probe::{ pub use probe::{
@ -9,7 +13,7 @@ pub use probe::{
#[cfg(feature = "xdp")] #[cfg(feature = "xdp")]
mod globals; mod globals;
#[cfg(feature = "xdp")] #[cfg(feature = "xdp")]
pub use globals::XdpGlobals; pub use globals::{RODATA_SIZE, XdpGlobals};
#[cfg(feature = "xdp")] #[cfg(feature = "xdp")]
mod metrics; mod metrics;

View file

@ -23,10 +23,10 @@ impl XdpFilter {
Ok(()) Ok(())
} }
/// Честная ошибка: чтение `prefix_stats` не подключено без feature `xdp`. /// Honest failure: reading `prefix_stats` is not wired up without the `xdp` feature.
/// ///
/// # Errors /// # Errors
/// Всегда — сборка без XDP не имеет доступа к картам ядра. /// Always: a build without XDP has no access to the kernel maps.
pub fn read_prefix_stats(&self) -> Result<Vec<(PrefixKey, PrefixStatsVal)>> { pub fn read_prefix_stats(&self) -> Result<Vec<(PrefixKey, PrefixStatsVal)>> {
anyhow::bail!("prefix_stats reading not wired yet: built without xdp feature") anyhow::bail!("prefix_stats reading not wired yet: built without xdp feature")
} }

View file

@ -1,8 +1,8 @@
//! Диагностика окружения перед XDP-attach: ядро, BTF, драйвер NIC, привилегии. //! Environment diagnostics before XDP attach: kernel, BTF, NIC driver, privileges.
//! //!
//! Основной источник боли при XDP — непонятные ошибки attach на неподдерживаемых //! The main source of pain with XDP is opaque attach failures on unsupported kernels and
//! ядрах и драйверах. Модуль собирает [`EnvironmentReport`] ДО загрузки BPF-программы //! drivers. This module collects an [`EnvironmentReport`] before the BPF program is
//! и даёт человекочитаемый вердикт с предупреждениями. //! loaded and produces a human-readable verdict with warnings.
mod report; mod report;
mod types; mod types;

View file

@ -5,7 +5,7 @@ use super::types::{
driver_supports_native_xdp, driver_supports_native_xdp,
}; };
/// Структурированный отчёт о пригодности окружения для XDP. /// Structured report on how suitable the environment is for XDP.
pub struct EnvironmentReport { pub struct EnvironmentReport {
pub kernel_version: Option<KernelVersion>, pub kernel_version: Option<KernelVersion>,
pub btf_available: bool, pub btf_available: bool,
@ -15,7 +15,7 @@ pub struct EnvironmentReport {
} }
impl EnvironmentReport { impl EnvironmentReport {
/// Собирает отчёт через произвольную реализацию [`SystemProbe`]. /// Collects the report through any [`SystemProbe`] implementation.
#[must_use] #[must_use]
pub fn collect(probe: &dyn SystemProbe, interface: &str) -> Self { pub fn collect(probe: &dyn SystemProbe, interface: &str) -> Self {
let kernel_version = probe let kernel_version = probe
@ -61,7 +61,7 @@ impl EnvironmentReport {
} }
} }
/// Ожидаемый режим attach по таблице драйверов. /// Expected attach mode according to the driver table.
#[must_use] #[must_use]
pub fn attach_mode(&self) -> AttachMode { pub fn attach_mode(&self) -> AttachMode {
match self.driver_name.as_deref() { match self.driver_name.as_deref() {
@ -70,7 +70,7 @@ impl EnvironmentReport {
} }
} }
/// Человекочитаемое объяснение вердикта. /// Human-readable explanation of the verdict.
#[must_use] #[must_use]
pub fn verdict(&self) -> String { pub fn verdict(&self) -> String {
let kernel = self let kernel = self
@ -87,10 +87,10 @@ impl EnvironmentReport {
} }
} }
/// Fail-fast проверка минимальной версии ядра. /// Fail-fast check of the minimum kernel version.
/// ///
/// # Errors /// # Errors
/// Версия ядра не определена или ниже [`MIN_KERNEL`]. /// The kernel version is unknown or below [`MIN_KERNEL`].
pub fn validate(&self) -> Result<()> { pub fn validate(&self) -> Result<()> {
let Some(version) = self.kernel_version else { let Some(version) = self.kernel_version else {
bail!("не удалось определить версию ядра ({OSRELEASE_PATH}) — XDP attach отклонён"); bail!("не удалось определить версию ядра ({OSRELEASE_PATH}) — XDP attach отклонён");
@ -102,11 +102,11 @@ impl EnvironmentReport {
} }
} }
/// Предстартовая диагностика перед загрузкой XDP-программы: /// Pre-attach diagnostics before the XDP program is loaded: a structured report in the
/// структурный отчёт в лог, предупреждения, fail-fast на старом ядре. /// log, warnings, and a fail-fast check for an old kernel.
/// ///
/// # Errors /// # Errors
/// См. [`EnvironmentReport::validate`]. /// See [`EnvironmentReport::validate`].
#[cfg(feature = "xdp")] #[cfg(feature = "xdp")]
pub(crate) fn preflight(interface: &str) -> Result<()> { pub(crate) fn preflight(interface: &str) -> Result<()> {
use super::types::FilesystemProbe; use super::types::FilesystemProbe;

View file

@ -1,15 +1,15 @@
use std::fmt; use std::fmt;
/// Минимально поддерживаемая версия ядра: 5.15 LTS. /// Minimum supported kernel version: 5.15 LTS.
pub const MIN_KERNEL: KernelVersion = KernelVersion::new(5, 15, 0); pub const MIN_KERNEL: KernelVersion = KernelVersion::new(5, 15, 0);
pub(super) const OSRELEASE_PATH: &str = "/proc/sys/kernel/osrelease"; pub(super) const OSRELEASE_PATH: &str = "/proc/sys/kernel/osrelease";
pub(super) const BTF_PATH: &str = "/sys/kernel/btf/vmlinux"; pub(super) const BTF_PATH: &str = "/sys/kernel/btf/vmlinux";
const STATUS_PATH: &str = "/proc/self/status"; const STATUS_PATH: &str = "/proc/self/status";
/// Драйверы с известной поддержкой native XDP (по данным xdpgeneric/native /// Drivers with known native XDP support (from the upstream kernel's native/generic
/// матриц upstream-ядра). Отсутствие в списке не означает отсутствие поддержки, /// matrices). Absence from this list does not mean support is missing, but for such
/// но для таких драйверов предсказываем generic mode. /// drivers generic mode is predicted.
const NATIVE_XDP_DRIVERS: &[&str] = &[ const NATIVE_XDP_DRIVERS: &[&str] = &[
"virtio_net", "virtio_net",
"ixgbe", "ixgbe",
@ -31,7 +31,7 @@ const NATIVE_XDP_DRIVERS: &[&str] = &[
"macvlan", "macvlan",
]; ];
/// Версия ядра Linux, пригодная для сравнения (`major.minor.patch`). /// Linux kernel version, suitable for comparison (`major.minor.patch`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct KernelVersion { pub struct KernelVersion {
pub major: u16, pub major: u16,
@ -45,9 +45,9 @@ impl KernelVersion {
Self { major, minor, patch } Self { major, minor, patch }
} }
/// Парсит строку формата `uname -r`. Берёт первые три числовых компонента, /// Parses a `uname -r` style string. Takes the first three numeric components and
/// дистрибутивные суффиксы (`6.8.0-45-generic`, `5.15.0-rc2`) отбрасываются. /// discards distribution suffixes (`6.8.0-45-generic`, `5.15.0-rc2`). A string without
/// Строка без цифр не парсится. /// digits does not parse.
#[must_use] #[must_use]
pub fn parse(release: &str) -> Option<Self> { pub fn parse(release: &str) -> Option<Self> {
let mut nums = release let mut nums = release
@ -66,15 +66,16 @@ impl fmt::Display for KernelVersion {
} }
} }
/// Режим присоединения XDP-программы к интерфейсу. /// Mode in which the XDP program is attached to the interface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttachMode { pub enum AttachMode {
/// Программа исполняется в контексте драйвера NIC — минимальные накладные расходы. /// The program runs in the NIC driver context: lowest overhead.
Native, Native,
/// Программа вызывается из сетевого стека после ingress — работает везде, дороже по CPU. /// The program is invoked from the network stack after ingress: works everywhere, but
/// costs more CPU.
Generic, Generic,
/// Аппаратная разгрузка в NIC — требует явного включения и поддержки железа, /// Hardware offload into the NIC: requires explicit enablement and hardware support,
/// автоматически не выбирается. /// never selected automatically.
Offload, Offload,
} }
@ -88,13 +89,13 @@ impl fmt::Display for AttachMode {
} }
} }
/// Абстракция над procfs/sysfs: реальная реализация — [`FilesystemProbe`], /// Abstraction over procfs/sysfs: the real implementation is [`FilesystemProbe`], tests
/// в тестах — мок. Изолирует диагностику от реального ядра. /// supply a mock. Keeps the diagnostics independent of the real kernel.
pub trait SystemProbe { pub trait SystemProbe {
/// Читает файл целиком. /// Reads a file in full.
/// ///
/// # Errors /// # Errors
/// Проксирует ошибку чтения файла. /// Proxies the file read error.
fn read_file(&self, path: &str) -> std::io::Result<String>; fn read_file(&self, path: &str) -> std::io::Result<String>;
#[must_use] #[must_use]
@ -107,7 +108,7 @@ pub trait SystemProbe {
fn effective_uid(&self) -> u32; fn effective_uid(&self) -> u32;
} }
/// Реальная реализация [`SystemProbe`] поверх `std::fs`. /// Real [`SystemProbe`] implementation on top of `std::fs`.
pub struct FilesystemProbe; pub struct FilesystemProbe;
impl SystemProbe for FilesystemProbe { impl SystemProbe for FilesystemProbe {
@ -123,10 +124,10 @@ impl SystemProbe for FilesystemProbe {
Some(std::fs::read_link(path).ok()?.to_string_lossy().into_owned()) Some(std::fs::read_link(path).ok()?.to_string_lossy().into_owned())
} }
/// Эвристика: эффективный uid берётся из `/proc/self/status`. /// Heuristic: the effective uid is taken from `/proc/self/status`. root almost always
/// root почти всегда имеет CAP_BPF/CAP_NET_ADMIN (если явно не урезаны); /// holds CAP_BPF/CAP_NET_ADMIN (unless explicitly dropped); for non-root the only
/// для не-root подтверждение возможно только попыткой attach. /// confirmation is an actual attach attempt. An unreadable status is treated as an
/// Нечитаемый статус трактуем как непривилегированный процесс. /// unprivileged process.
fn effective_uid(&self) -> u32 { fn effective_uid(&self) -> u32 {
std::fs::read_to_string(STATUS_PATH) std::fs::read_to_string(STATUS_PATH)
.ok() .ok()
@ -147,7 +148,7 @@ pub(super) fn driver_from_link(target: &str) -> Option<String> {
(!name.is_empty()).then(|| name.to_owned()) (!name.is_empty()).then(|| name.to_owned())
} }
/// Поддерживает ли драйвер native XDP (по таблице известных драйверов). /// Whether the driver supports native XDP (per the table of known drivers).
#[must_use] #[must_use]
pub fn driver_supports_native_xdp(driver: &str) -> bool { pub fn driver_supports_native_xdp(driver: &str) -> bool {
NATIVE_XDP_DRIVERS.contains(&driver) NATIVE_XDP_DRIVERS.contains(&driver)

View file

@ -1,4 +1,4 @@
//! Зондирование XDP-окружения: диагностика, статистика и метрики. //! XDP environment probing: diagnostics, statistics and metrics.
mod diagnostics; mod diagnostics;
#[cfg(feature = "xdp")] #[cfg(feature = "xdp")]

View file

@ -1,4 +1,4 @@
/// Счётчики XDP-программы; индексы соответствуют STAT_* из xdp/core/maps.h. /// XDP program counters; the indices follow `STAT_*` from `xdp/core/maps.h`.
#[derive(Debug, Clone, Copy, Default)] #[derive(Debug, Clone, Copy, Default)]
pub struct XdpStats { pub struct XdpStats {
pub total: u64, pub total: u64,

View file

@ -1,3 +1,5 @@
//! Config parsing tests: defaults, section parsing and rejected invariants.
use rampart::config::Config; use rampart::config::Config;
#[test] #[test]

View file

@ -1,3 +1,6 @@
//! Integration tests for the accept-path filters: token-bucket rate limiting
//! and blacklist TTL handling.
use std::net::{IpAddr, Ipv4Addr}; use std::net::{IpAddr, Ipv4Addr};
use std::time::Duration; use std::time::Duration;

View file

@ -1,3 +1,5 @@
//! Integration tests for the HTTP/1.1 protocol handler: request-head
//! accumulation across fragmented writes and policy rejection paths.
#![cfg(feature = "protocol-http")] #![cfg(feature = "protocol-http")]
use rampart::config::HttpProtocolConfig; use rampart::config::HttpProtocolConfig;

View file

@ -1,3 +1,6 @@
//! PoW roundtrip tests: solver output must satisfy the verifier, replays and
//! garbage must not.
use rampart::engine::challenge::{Challenge, solve}; use rampart::engine::challenge::{Challenge, solve};
/// Fixed 32-byte token: sha256(hex(token) || "garbage") starts with "ebc1", /// Fixed 32-byte token: sha256(hex(token) || "garbage") starts with "ebc1",

View file

@ -1,3 +1,6 @@
//! Protocol registry tests: empty registries fail fast, registered handlers
//! resolve by name.
use std::future::Future; use std::future::Future;
use std::pin::Pin; use std::pin::Pin;

View file

@ -1,4 +1,4 @@
//! Интеграционные тесты subnet-level детекции: трекер → детектор → вердикты. //! Integration tests for subnet-level detection: tracker, detector and verdicts.
use rampart::config::Config; use rampart::config::Config;
use rampart::engine::subnet_tracker::SubnetTracker; use rampart::engine::subnet_tracker::SubnetTracker;
@ -12,7 +12,7 @@ fn v4(octets: [u8; 4]) -> IpAddr {
IpAddr::V4(Ipv4Addr::from(octets)) IpAddr::V4(Ipv4Addr::from(octets))
} }
/// Фиксированный источник снапшотов — имитирует XDP-карту без ядра. /// Fixed snapshot source that imitates the XDP map without a kernel.
struct FixedSource(Vec<(IpAddr, PrefixSnapshot)>); struct FixedSource(Vec<(IpAddr, PrefixSnapshot)>);
impl PrefixStatsSource for FixedSource { impl PrefixStatsSource for FixedSource {
@ -24,8 +24,8 @@ impl PrefixStatsSource for FixedSource {
#[tokio::test] #[tokio::test]
async fn tracker_feeds_detector_and_blocks_distributed_attack() { async fn tracker_feeds_detector_and_blocks_distributed_attack() {
let tracker = SubnetTracker::new(); let tracker = SubnetTracker::new();
// 40 уникальных источников из одного /24 — распределённая атака // 40 unique sources from one /24 is a distributed attack: 6 SYNs each,
// (6 SYN от каждого: 240 >= 4 × threshold(50)). // i.e. 240 >= 4 x threshold(50).
for _ in 0..6 { for _ in 0..6 {
for last in 1..=40u8 { for last in 1..=40u8 {
tracker.record_connection(v4([203, 0, 113, last])); tracker.record_connection(v4([203, 0, 113, last]));
@ -41,7 +41,7 @@ async fn tracker_feeds_detector_and_blocks_distributed_attack() {
assert_eq!(verdicts[0].snapshot.syn_count, 240); assert_eq!(verdicts[0].snapshot.syn_count, 240);
assert_eq!(verdicts[0].snapshot.unique_sources, 40); assert_eq!(verdicts[0].snapshot.unique_sources, 40);
// Полный конвейер через трейт-источник (как в бинарнике). // Full pipeline through the trait source, the way the binary drives it.
let source_snaps = FixedSource(snaps).snapshot().await.expect("source snapshot"); let source_snaps = FixedSource(snaps).snapshot().await.expect("source snapshot");
assert_eq!(detector.evaluate(&source_snaps)[0].verdict, SubnetVerdict::Block); assert_eq!(detector.evaluate(&source_snaps)[0].verdict, SubnetVerdict::Block);
} }
@ -49,7 +49,7 @@ async fn tracker_feeds_detector_and_blocks_distributed_attack() {
#[tokio::test] #[tokio::test]
async fn spoof_gate_many_syn_few_sources_no_block() { async fn spoof_gate_many_syn_few_sources_no_block() {
let tracker = SubnetTracker::new(); let tracker = SubnetTracker::new();
// 500 SYN всего из 3 адресов — всплеск, но не распределённый. // 500 SYNs from only 3 addresses: a burst, but not distributed.
for _ in 0..167 { for _ in 0..167 {
for ip in [v4([198, 51, 100, 1]), v4([198, 51, 100, 2]), v4([198, 51, 100, 3])] { for ip in [v4([198, 51, 100, 1]), v4([198, 51, 100, 2]), v4([198, 51, 100, 3])] {
tracker.record_connection(ip); tracker.record_connection(ip);
@ -180,7 +180,7 @@ fn escalation_ladder_monitor_to_block() {
#[test] #[test]
fn spoof_gate_downgrades_block_to_challenge() { fn spoof_gate_downgrades_block_to_challenge() {
let detector = SubnetDetector::new(100, 16); let detector = SubnetDetector::new(100, 16);
// Много SYN из одного источника (или неизвестное разнообразие) → нет Block. // Many SYNs from one source (or unknown diversity) must not yield Block.
let few = PrefixSnapshot { let few = PrefixSnapshot {
syn_count: 1000, syn_count: 1000,
unique_sources: 3, unique_sources: 3,

View file

@ -1,5 +1,6 @@
//! Интеграционные тесты Traffic Intelligence в hot path: авто-бан по //! 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::config::DetectAutobanConfig;
use rampart::filter::blacklist::Blacklist; use rampart::filter::blacklist::Blacklist;
@ -30,7 +31,7 @@ fn reputation_fall_after_drops_triggers_autoban() {
let attacker = ip([198, 51, 100, 7]); let attacker = ip([198, 51, 100, 7]);
for _ in 0..6 { for _ in 0..6 {
// Шесть дропов rate-limit'ом: -10 за каждый, порог auto-ban = -50. // Six drops through the rate limiter: -10 each, auto-ban threshold is -50.
reputation.record_bad(attacker); reputation.record_bad(attacker);
hook.on_connection_end(attacker); hook.on_connection_end(attacker);
} }
@ -53,7 +54,7 @@ fn autoban_ttl_expires_ban() {
Arc::clone(&reputation), Arc::clone(&reputation),
Arc::clone(&blacklist), Arc::clone(&blacklist),
autoban_cfg(true), autoban_cfg(true),
// Короткий TTL из «конфига» как мок времени. // Zero TTL taken from the config as a time mock.
0, 0,
); );
let attacker = ip([198, 51, 100, 8]); let attacker = ip([198, 51, 100, 8]);
@ -72,12 +73,12 @@ fn autoban_ttl_expires_ban() {
fn detector_flags_synthetic_traffic_spike() { fn detector_flags_synthetic_traffic_spike() {
let mut detector = AttackDetector::new(); let mut detector = AttackDetector::new();
// Базовая линия: тихий профиль. // Baseline: a quiet profile.
for _ in 0..12 { for _ in 0..12 {
detector.analyze(500.0, 50.0); detector.analyze(500.0, 50.0);
} }
// Синтетический всплеск: x200 pps и cps три окна подряд. // Synthetic spike: 200x pps and cps for three consecutive windows.
assert_eq!( assert_eq!(
detector.analyze(100_000.0, 10_000.0), detector.analyze(100_000.0, 10_000.0),
AttackStatus::Suspicious, AttackStatus::Suspicious,

View file

@ -1,12 +1,11 @@
//! Тесты TUI-модуля: парсер Prometheus, расчёт rate, поведение при ошибках fetch. //! Tests for the TUI module: Prometheus parser, rate calculation and fetch
//! error handling.
use futures::future::BoxFuture; use futures::future::BoxFuture;
use rampart::tui::fetch::{FetchError, Fetcher, HttpFetcher}; use rampart::tui::fetch::{FetchError, Fetcher, HttpFetcher};
use rampart::tui::prometheus::{MetricSample, parse}; use rampart::tui::prometheus::{MetricSample, parse};
use rampart::tui::state::{AppState, counter_rate}; use rampart::tui::state::{AppState, counter_rate};
// ---------- парсер ----------
#[test] #[test]
fn parses_metric_with_labels_value_and_timestamp() { fn parses_metric_with_labels_value_and_timestamp() {
let set = parse("rampart_xdp_total{iface=\"eth0\",core=\"0\"} 123 1700000000000\n"); let set = parse("rampart_xdp_total{iface=\"eth0\",core=\"0\"} 123 1700000000000\n");
@ -53,11 +52,9 @@ fn parser_tolerates_malformed_lines() {
assert_eq!(set.samples().len(), 1); assert_eq!(set.samples().len(), 1);
} }
// ---------- rate ----------
#[test] #[test]
fn rate_from_two_samples_divides_by_elapsed() { fn rate_from_two_samples_divides_by_elapsed() {
// 1200 - 1100 = 100 пакетов за 2 сек // 1200 - 1100 = 100 packets over 2 seconds.
assert_eq!(counter_rate(Some(1100.0), Some(1200.0), 2.0), 50.0); assert_eq!(counter_rate(Some(1100.0), Some(1200.0), 2.0), 50.0);
} }
@ -79,8 +76,6 @@ fn state_accumulates_history_rates() {
assert!(frame.snapshot.error.is_none()); assert!(frame.snapshot.error.is_none());
} }
// ---------- ошибки fetch (мок Fetcher + локальный HTTP-сервер) ----------
struct FailingFetcher { struct FailingFetcher {
error: FetchError, error: FetchError,
} }
@ -99,7 +94,7 @@ fn network_error_sets_error_banner_not_panic() {
error: FetchError::Network("connection refused".to_owned()), error: FetchError::Network("connection refused".to_owned()),
}; };
// Тот же путь, что и в spawn_fetch_loop: normalize → apply_fetch. // Same path as in spawn_fetch_loop: normalize, then apply_fetch.
let normalized = rampart::tui::app::normalize(Err(fetcher.error)); let normalized = rampart::tui::app::normalize(Err(fetcher.error));
assert!(normalized.is_err()); assert!(normalized.is_err());
let message = match normalized { let message = match normalized {

View file

@ -1,14 +1,14 @@
//! Часы бана: XDP сравнивает expiry с `bpf_ktime_get_ns()` (монотонные ns //! Ban clock: XDP compares expiry against `bpf_ktime_get_ns()` (monotonic nanoseconds
//! с загрузки), поэтому userspace обязан писать то же самое. Регрессия: //! since boot), so userspace must write the same clock. Regression: `SystemTime` (epoch
//! раньше писался `SystemTime` (epoch ns ≈ 1.7e18), и бан не истекал никогда. //! nanoseconds, about 1.7e18) used to be written, and bans never expired.
#![cfg(feature = "xdp")] #![cfg(feature = "xdp")]
use rampart::xdp::monotonic_ns; use rampart::xdp::monotonic_ns;
fn clock_monotonic_ns() -> u64 { fn clock_monotonic_ns() -> u64 {
let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 }; let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
// SAFETY: `ts` — валидный writable `timespec`; CLOCK_MONOTONIC на Linux // SAFETY: `ts` is a valid, writable `timespec`, and CLOCK_MONOTONIC is always
// поддерживается всегда (xdp-фича собирается только под Linux). // supported on Linux (the xdp feature only builds on Linux).
let rc = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) }; let rc = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
assert_eq!(rc, 0, "clock_gettime(CLOCK_MONOTONIC) failed"); assert_eq!(rc, 0, "clock_gettime(CLOCK_MONOTONIC) failed");
let secs = u64::try_from(ts.tv_sec).expect("tv_sec fits u64"); let secs = u64::try_from(ts.tv_sec).expect("tv_sec fits u64");

View file

@ -1,6 +1,6 @@
//! Раскладка ключа `blacklist6_map` (LPM-trie): префикс-длина в байтах 0..4 //! Layout of the `blacklist6_map` key (LPM trie): the prefix length as a little-endian
//! little-endian + 16 байт адреса в network order (байты 4..20). //! u32 in bytes 0..4 plus the 16-byte address in network order (bytes 4..20).
//! Ядро не нужно: проверяется чистая функция кодирования ключа. //! No kernel needed: this exercises the pure key encoding function.
#![cfg(feature = "xdp")] #![cfg(feature = "xdp")]
use rampart::xdp::blacklist6_key; use rampart::xdp::blacklist6_key;
@ -28,7 +28,7 @@ fn key_layout_for_64_prefix() {
#[test] #[test]
fn leading_zero_address_is_not_confused_with_prefix_len() { fn leading_zero_address_is_not_confused_with_prefix_len() {
// ::1 — 15 нулевых байт перед единицей: ключ не должен «съесть» ни одного. // ::1 has fifteen zero bytes before the final one: the key must not consume any of them.
let key = blacklist6_key(128, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); let key = blacklist6_key(128, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
assert_eq!(key[0], 128, "prefixlen is not overwritten by the address"); assert_eq!(key[0], 128, "prefixlen is not overwritten by the address");

View file

@ -1,5 +1,5 @@
//! Интеграционные тесты wire-формата и политики авто-бана XDP-событий. //! Integration tests for the wire format and the auto-ban policy of XDP events.
//! Ядро/Redis не нужны: проверяем чистые парсер и решение + дефолты конфига. //! No kernel or Redis needed: the pure parser and decision are covered, plus config defaults.
#![cfg(feature = "xdp")] #![cfg(feature = "xdp")]
use rampart::config::Config; use rampart::config::Config;
@ -8,21 +8,21 @@ use std::net::Ipv4Addr;
const IP: [u8; 4] = [203, 0, 113, 7]; const IP: [u8; 4] = [203, 0, 113, 7];
/// Собирает кадр ровно как ядро (`push_event`, common.h:87-97): скаляры — native /// Builds a frame exactly as the kernel does (`push_event`, common.h:87-97): scalars in
/// (host) order, `src_ip` — сетевой порядок октетов (raw из заголовка пакета). /// native (host) order, `src_ip` in network octet order (raw from the packet header).
fn frame(kind: u32, octets: [u8; 4], metadata: u32, ts: u64) -> [u8; XDP_EVENT_LEN] { fn frame(kind: u32, octets: [u8; 4], metadata: u32, ts: u64) -> [u8; XDP_EVENT_LEN] {
let mut b = [0u8; XDP_EVENT_LEN]; let mut b = [0u8; XDP_EVENT_LEN];
b[0..4].copy_from_slice(&kind.to_ne_bytes()); b[0..4].copy_from_slice(&kind.to_ne_bytes());
b[4..8].copy_from_slice(&octets); b[4..8].copy_from_slice(&octets);
b[8..12].copy_from_slice(&metadata.to_ne_bytes()); b[8..12].copy_from_slice(&metadata.to_ne_bytes());
// b[12..16] — выравнивающий padding под __u64: ядро его не инициализирует. // b[12..16] is padding for `__u64`; the kernel does not initialise it.
b[16..24].copy_from_slice(&ts.to_ne_bytes()); b[16..24].copy_from_slice(&ts.to_ne_bytes());
b b
} }
#[test] #[test]
fn struct_size_is_24_bytes() { fn struct_size_is_24_bytes() {
// Раскладка common.h: __u32×3 + pad(4) + __u64 = 24, НЕ 16 как парсил код ранее. // common.h layout: __u32 x3 + pad(4) + __u64 = 24, not 16 as the code parsed before.
assert_eq!(XDP_EVENT_LEN, 24); assert_eq!(XDP_EVENT_LEN, 24);
} }
@ -47,12 +47,12 @@ fn dirty_padding_does_not_corrupt_parse() {
#[test] #[test]
fn src_ip_is_network_order_octets_not_native_u32() { fn src_ip_is_network_order_octets_not_native_u32() {
// КЛЮЧЕВОЙ вывод по endianness: октеты лежат в точковом порядке напрямую. // Key endianness insight: the octets sit in dotted order directly.
let f = frame(2, [198, 51, 100, 23], 0, 0); let f = frame(2, [198, 51, 100, 23], 0, 0);
let ev = parse_xdp_event(&f).expect("parses"); let ev = parse_xdp_event(&f).expect("parses");
assert_eq!(ev.src_ip, Ipv4Addr::new(198, 51, 100, 23)); assert_eq!(ev.src_ip, Ipv4Addr::new(198, 51, 100, 23));
// Старый баг (`u32::from_ne_bytes` → Ipv4Addr::from(u32)) на little-endian // The old bug (`u32::from_ne_bytes` -> `Ipv4Addr::from(u32)`) produced a reversed
// давал бы переёрнутый адрес — фиксируем, что мы так НЕ делаем. // address on little-endian; this pins down that we do not do that.
if cfg!(target_endian = "little") { if cfg!(target_endian = "little") {
let naive = u32::from_ne_bytes(<[u8; 4]>::try_from(&f[4..8]).expect("4 octets")); let naive = u32::from_ne_bytes(<[u8; 4]>::try_from(&f[4..8]).expect("4 octets"));
assert_eq!(Ipv4Addr::from(naive), Ipv4Addr::new(23, 100, 51, 198)); assert_eq!(Ipv4Addr::from(naive), Ipv4Addr::new(23, 100, 51, 198));
@ -86,14 +86,14 @@ fn decision_matrix_by_type_and_enablement() {
enabled: false, enabled: false,
..AutoBanConfig::default() ..AutoBanConfig::default()
}; };
// (kind, metadata=fails/хиты, банить ли при enabled) // (kind, metadata=fails/hits, whether to ban when enabled)
let rows = [ let rows = [
(0u32, 255u32, false), // EVENT_BAN — ядро уже забанило: никогда (0u32, 255u32, false), // EVENT_BAN: already banned by the kernel, never
(1, 100, true), // EVENT_RATE_LIMIT — всегда баним (1, 100, true), // EVENT_RATE_LIMIT: always ban
(2, 0, false), // EVENT_POLICY_DROP — политика по дефолту не банит (2, 0, false), // EVENT_POLICY_DROP: the policy does not ban by default
(3, 10, true), // EVENT_CONN_DROP fails=10 >= 3 — баним (3, 10, true), // EVENT_CONN_DROP fails=10 >= 3: ban
(3, 0, false), // EVENT_CONN_DROP fails=0 (hook-drop) — не баним (3, 0, false), // EVENT_CONN_DROP fails=0 (hook drop): no ban
(3, 2, false), // EVENT_CONN_DROP fails=2 < 3 — не баним (3, 2, false), // EVENT_CONN_DROP fails=2 < 3: no ban
]; ];
for (kind, meta, should_ban_when_on) in rows { for (kind, meta, should_ban_when_on) in rows {
let ev = parse_xdp_event(&frame(kind, IP, meta, 0)).expect("known type"); let ev = parse_xdp_event(&frame(kind, IP, meta, 0)).expect("known type");
@ -160,7 +160,7 @@ auto_ban_conn_drop_fails = 5
assert_eq!(policy.duration_secs, 45); assert_eq!(policy.duration_secs, 45);
assert_eq!(policy.conn_drop_fails, 5); assert_eq!(policy.conn_drop_fails, 5);
// fails=4 ниже нового порога 5 — не бан; fails=5 — бан. // fails=4 is below the new threshold of 5 (no ban); fails=5 reaches it (ban).
let below = parse_xdp_event(&frame(3, IP, 4, 0)).expect("frame parses"); let below = parse_xdp_event(&frame(3, IP, 4, 0)).expect("frame parses");
assert!(auto_ban_decision(&below, &policy).is_none()); assert!(auto_ban_decision(&below, &policy).is_none());
let at = parse_xdp_event(&frame(3, IP, 5, 0)).expect("frame parses"); let at = parse_xdp_event(&frame(3, IP, 5, 0)).expect("frame parses");

58
tests/xdp_object_maps.rs Normal file
View file

@ -0,0 +1,58 @@
#![cfg(feature = "xdp")]
//! Contract between the loader (`src/xdp/filter/*`) and the C object: map names and the
//! `.rodata` size. Catches drift without root and without loading the program into the
//! kernel — exactly the class of bug that made XDP fail silently ("events_map not found",
//! "Invalid argument" on `.rodata`).
use libbpf_rs::ObjectBuilder;
use rampart::xdp::RODATA_SIZE;
fn open_object() -> libbpf_rs::OpenObject {
let bytes = include_bytes!(concat!(env!("OUT_DIR"), "/universal_filter.o"));
ObjectBuilder::default()
.name("rampart")
.expect("object name")
.open_memory(bytes)
.expect("open XDP object (ELF/BTF parse must not need privileges)")
}
#[test]
fn every_map_the_loader_uses_exists_in_the_object() {
let obj = open_object();
let names: Vec<String> = obj.maps().map(|m| m.name().to_string_lossy().into_owned()).collect();
// Names come from `find_map`, `build_ringbuf` and `patch_rodata`.
for expected in [
"stats_map",
"prefix_stats",
"events_ringbuf",
"blacklist_map",
"blacklist6_map",
"whitelist_map",
"udp_rate_limit",
"udp_rate_limit6",
] {
assert!(
names.iter().any(|n| n == expected),
"loader expects map '{expected}', object has {names:?}"
);
}
assert!(
names.iter().any(|n| n.ends_with(".rodata")),
"loader expects a '.rodata' map, object has {names:?}"
);
}
#[test]
fn rodata_map_value_size_matches_loader_image() {
let obj = open_object();
let map = obj
.maps()
.find(|m| m.name().to_string_lossy().ends_with(".rodata"))
.expect("rodata map");
assert_eq!(
map.value_size() as usize,
RODATA_SIZE,
"sizeof(struct rampart_config) in config.h must equal sizeof(XdpGlobals)"
);
}

View file

@ -12,13 +12,24 @@
#define IP_OFFSET 0x1FFF #define IP_OFFSET 0x1FFF
#define IP_MF 0x2000 #define IP_MF 0x2000
// ── Protocol-agnostic TCP state machine ── /**
* Protocol-agnostic TCP connection states.
*
* A connection enters the map on the first bare SYN and advances only when
* the handshake completes; payload inspection is reachable from ESTABLISHED
* only, so no state can be skipped.
*/
enum connection_state { enum connection_state {
STATE_SYN_RECEIVED = 0, // SYN seen, waiting for ACK (handshake completing) STATE_SYN_RECEIVED = 0, // SYN seen, waiting for ACK (handshake completing)
STATE_ESTABLISHED = 1, // handshake done; payload handed to proto_hook() STATE_ESTABLISHED = 1, // handshake done; payload handed to proto_hook()
}; };
// ── Flow key (4-tuple for connection tracking) ── /**
* Flow key identifying one connection: the classic 4-tuple.
*
* Addresses and ports stay in network byte order; this key is only ever
* built and compared inside the BPF program.
*/
struct flow_key { struct flow_key {
__u32 src_ip; __u32 src_ip;
__u32 dst_ip; __u32 dst_ip;
@ -26,9 +37,14 @@ struct flow_key {
__u16 dst_port; __u16 dst_port;
}; };
// ── Connection tracking entry ── /**
// LRU maps evict stale entries automatically when full; RST/FIN removes * Connection tracking entry.
// entries explicitly. last_seen supports future timer-based idle cleanup. *
* LRU maps evict stale entries automatically when full; RST/FIN removes
* entries explicitly. last_seen supports future timer-based idle cleanup.
* expected_seq is the next in-order sequence number we accept on the
* server-to-client direction.
*/
struct conntrack_entry { struct conntrack_entry {
__u32 state; __u32 state;
__u32 expected_seq; __u32 expected_seq;
@ -38,25 +54,42 @@ struct conntrack_entry {
__u8 fails; __u8 fails;
}; };
// ── SYN / UDP throttle entry ── /**
* Fixed-window throttle state for one source address.
*
* window_start is a bpf_ktime_get_ns() timestamp, so windows survive
* wall-clock jumps; hits resets whenever the window rolls over.
*/
struct throttle_entry { struct throttle_entry {
__u64 window_start; __u64 window_start;
__u32 hits; __u32 hits;
}; };
// ── LPM key for blacklist/whitelist ── /**
* LPM trie key for IPv4 blacklist and whitelist entries.
*
* prefixlen is in host byte order, the address in network byte order, which
* is the layout the kernel expects for BPF_MAP_TYPE_LPM_TRIE.
*/
struct lpm_key { struct lpm_key {
__u32 prefixlen; __u32 prefixlen;
__u32 ip; __u32 ip;
}; };
// ── LPM key for IPv6 blacklist (format of bpf_lpm_trie_key, 20 bytes) ── /**
* LPM trie key for IPv6 blacklist entries.
*
* Same layout as bpf_lpm_trie_key: host-order prefix length followed by 16
* address bytes, 20 bytes in total.
*/
struct lpm_key6 { struct lpm_key6 {
__u32 prefixlen; __u32 prefixlen;
__u8 addr[16]; __u8 addr[16];
}; };
// ── Ringbuf event (userspace receives these) ── /**
* Event kinds that userspace can receive and react to.
*/
enum event_type { enum event_type {
EVENT_BAN = 0, EVENT_BAN = 0,
EVENT_RATE_LIMIT = 1, EVENT_RATE_LIMIT = 1,
@ -64,6 +97,13 @@ enum event_type {
EVENT_CONN_DROP = 3, EVENT_CONN_DROP = 3,
}; };
/**
* Ring buffer event record handed to userspace.
*
* src_ip is always IPv4 (or the low 32 bits of an IPv4-mapped address)
* because the record format is part of the userspace ABI; native IPv6
* drops are therefore not reported.
*/
struct xdp_event { struct xdp_event {
__u32 type; __u32 type;
__u32 src_ip; __u32 src_ip;
@ -71,7 +111,14 @@ struct xdp_event {
__u64 timestamp; __u64 timestamp;
}; };
// ── Bounds check macros (dual-bounds для verifier) ── /**
* Dual bounds check for the verifier.
*
* A read of sz bytes at ptr is rejected unless it fits inside both the
* provisional end pointer (pend) and the packet tail (dend). barrier_var()
* keeps ptr in a register so the verifier does not lose the narrowed range
* on the second comparison. The caller must provide an error: label.
*/
#define CHECK_BOUNDS_OR_RETURN(ptr, sz, pend, dend) \ #define CHECK_BOUNDS_OR_RETURN(ptr, sz, pend, dend) \
do { \ do { \
if ((void *)(ptr) + (sz) > (void *)(dend)) \ if ((void *)(ptr) + (sz) > (void *)(dend)) \
@ -81,15 +128,35 @@ struct xdp_event {
goto error; \ goto error; \
} while (0) } while (0)
/**
* Pin a pointer in a register.
*
* The empty asm block gives the value a register home, which stops the
* verifier from widening a range it already proved.
*/
#define barrier_var(var) asm volatile("" : "+r"(var)) #define barrier_var(var) asm volatile("" : "+r"(var))
// ── Ringbuf for events → userspace (declared here for push_event) ── /**
* Ring buffer carrying events to userspace.
*
* Declared next to push_event() rather than in maps.h so every program that
* includes this header gets the producer side without extra wiring.
*/
struct { struct {
__uint(type, BPF_MAP_TYPE_RINGBUF); __uint(type, BPF_MAP_TYPE_RINGBUF);
__uint(max_entries, 1 << 24); __uint(max_entries, 1 << 24);
} events_ringbuf SEC(".maps"); } events_ringbuf SEC(".maps");
// ── Event push to ringbuf ── /**
* Publish one event to userspace.
*
* Fire-and-forget: a full or missing ring buffer silently drops the record
* because event reporting must never change the packet verdict.
*
* @param type event kind stored in the record
* @param src_ip source address, network byte order
* @param meta event-specific value, e.g. the threshold that fired
*/
static __always_inline void push_event(enum event_type type, __u32 src_ip, __u32 meta) static __always_inline void push_event(enum event_type type, __u32 src_ip, __u32 meta)
{ {
struct xdp_event *e = bpf_ringbuf_reserve(&events_ringbuf, sizeof(struct xdp_event), 0); struct xdp_event *e = bpf_ringbuf_reserve(&events_ringbuf, sizeof(struct xdp_event), 0);

View file

@ -1,47 +1,138 @@
#ifndef RAMPART_CONFIG_H #ifndef RAMPART_CONFIG_H
#define RAMPART_CONFIG_H #define RAMPART_CONFIG_H
// ⚙️ Runtime configurable globals (patched by Rust loader) /**
// These are volatile const — compiler replaces reads with immediate values * Runtime-tunable filter configuration.
// after loader writes to .rodata section *
* The whole configuration lives in one aggregate in .rodata so that its
* layout is fixed by this C declaration and by the mirrored #[repr(C)]
* XdpGlobals in Rust, not by the linker's choice of symbol order. Separate
* globals used to be reordered by clang, which silently broke hardcoded
* offsets; a single aggregated object is emitted whole and stays stable.
*
* The object is volatile const: the loader patches the .rodata map before
* the program is loaded, so the compiler must not constant-fold reads.
*/
struct rampart_config {
// Protected port range: packets to ports outside it bypass the filter
// entirely (XDP_PASS before any counting). Default protects every
// TCP/UDP port; narrow it via loader patching for dedicated-edge setups.
__u16 start_port; // 1
__u16 end_port; // 65535
// ── Port range ── // SYN throttle window: hit count per source, window length, ban length.
// Protected port range: packets to ports OUTSIDE this range bypass the __u32 syn_hit_count; // 10 max SYNs / window
// filter (XDP_PASS before any counting/filtering). Default protects all __u64 syn_window_ns; // 3 sec
// TCP/UDP ports; narrow it via loader patching for dedicated-edge setups. __u64 syn_ban_duration_ns; // 60 sec
static volatile const __u16 G_START_PORT = 1;
static volatile const __u16 G_END_PORT = 65535;
// ── SYN throttle ── // Idle timeouts. The XDP path does not read them yet; they are part of
static volatile const __u32 G_SYN_HIT_COUNT = 10; // max SYNs / window // the loader ABI so userspace can drive timer-based cleanup.
static volatile const __u64 G_SYN_WINDOW_NS = 3000000000ULL; // 3 sec __u64 conntrack_idle_ns; // 30 sec
static volatile const __u64 G_SYN_BAN_DURATION_NS = 60000000000ULL; // 60 sec __u64 player_idle_ns; // 120 sec
// ── Idle timeouts ── // Default ban duration userspace applies to new blacklist entries.
static volatile const __u64 G_CONNTRACK_IDLE_NS = 30000000000ULL; // 30 sec __u64 ban_duration_ns; // 5 min
static volatile const __u64 G_PLAYER_IDLE_NS = 120000000000ULL; // 120 sec
// ── Blacklist default ban duration ── // Out-of-order payload packets tolerated before the connection is cut.
static volatile const __u64 G_BAN_DURATION_NS = 300000000000ULL; // 5 min __u8 max_out_of_order; // 4
// ── Max out-of-order packets before dropping connection ── // UDP policy and its rate-limit window.
static volatile const __u8 G_MAX_OUT_OF_ORDER = 4; __u8 udp_policy; // 0 = pass, 1 = drop, 2 = rate-limit
__u32 udp_hit_count; // 100 max packets / window
__u64 udp_window_ns; // 1 sec
// ── UDP policy ── // Feature switches read on the hot path.
static volatile const __u8 G_UDP_POLICY = 0; // 0 = pass, 1 = drop, 2 = rate-limit __u8 feature_syn_throttle; // 1
static volatile const __u32 G_UDP_HIT_COUNT = 100; // max packets / window __u8 feature_events; // 1
static volatile const __u64 G_UDP_WINDOW_NS = 1000000000ULL; // 1 sec
// ── Feature flags ── // RST-challenge (Oubliette-style liveness proof). 0 disables it, leaving
static volatile const __u8 G_FEATURE_SYN_THROTTLE = 1; // a single branch and zero cost for legitimate traffic. The secret is
static volatile const __u8 G_FEATURE_EVENTS = 1; // patched by the loader at attach time; the value below is a placeholder.
__u8 syn_challenge_enabled; // 0
__u64 challenge_secret; // 0xA5A55A5A5A5AA5A5
__u32 challenge_timeout_ms; // 3000 pending TTL
__u64 challenge_verified_ttl_ns; // 5 min
};
// ── RST-challenge (Oubliette liveness proof) ── /**
// 0 = disabled: single branch, zero cost for legitimate traffic. * Default configuration image shipped inside the object file.
// Secret is patched by the loader at attach time (default is a placeholder). *
static volatile const __u8 G_SYN_CHALLENGE_ENABLED = 0; * volatile const keeps every read tied to the patched .rodata map instead of
static volatile const __u64 G_CHALLENGE_SECRET = 0xA5A55A5A5A5AA5A5ULL; * being folded into a constant at compile time.
static volatile const __u32 G_CHALLENGE_TIMEOUT_MS = 3000; // pending TTL */
static volatile const __u64 G_CHALLENGE_VERIFIED_TTL_NS = 300000000000ULL; // 5 min static volatile const struct rampart_config G = {
.start_port = 1,
.end_port = 65535,
.syn_hit_count = 10,
.syn_window_ns = 3000000000ULL,
.syn_ban_duration_ns = 60000000000ULL,
.conntrack_idle_ns = 30000000000ULL,
.player_idle_ns = 120000000000ULL,
.ban_duration_ns = 300000000000ULL,
.max_out_of_order = 4,
.udp_policy = 0,
.udp_hit_count = 100,
.udp_window_ns = 1000000000ULL,
.feature_syn_throttle = 1,
.feature_events = 1,
.syn_challenge_enabled = 0,
.challenge_secret = 0xA5A55A5A5A5AA5A5ULL,
.challenge_timeout_ms = 3000,
.challenge_verified_ttl_ns = 300000000000ULL,
};
/**
* ABI guard for the configuration struct.
*
* The byte layout is part of the loader contract: src/xdp/globals.rs writes
* fields at offset_of!(XdpGlobals, ..), and the real-kernel smoke patches
* udp_policy and udp_hit_count by raw offset. Reordering or resizing a field
* must break the build instead of silently misconfiguring the filter.
*/
_Static_assert(sizeof(struct rampart_config) == 96,
"sizeof(struct rampart_config) must match XdpGlobals");
_Static_assert(__builtin_offsetof(struct rampart_config, start_port) == 0, "start_port");
_Static_assert(__builtin_offsetof(struct rampart_config, end_port) == 2, "end_port");
_Static_assert(__builtin_offsetof(struct rampart_config, syn_hit_count) == 4, "syn_hit_count");
_Static_assert(__builtin_offsetof(struct rampart_config, syn_window_ns) == 8, "syn_window_ns");
_Static_assert(__builtin_offsetof(struct rampart_config, syn_ban_duration_ns) == 16, "syn_ban_duration_ns");
_Static_assert(__builtin_offsetof(struct rampart_config, conntrack_idle_ns) == 24, "conntrack_idle_ns");
_Static_assert(__builtin_offsetof(struct rampart_config, player_idle_ns) == 32, "player_idle_ns");
_Static_assert(__builtin_offsetof(struct rampart_config, ban_duration_ns) == 40, "ban_duration_ns");
_Static_assert(__builtin_offsetof(struct rampart_config, max_out_of_order) == 48, "max_out_of_order");
_Static_assert(__builtin_offsetof(struct rampart_config, udp_policy) == 49, "udp_policy");
_Static_assert(__builtin_offsetof(struct rampart_config, udp_hit_count) == 52, "udp_hit_count");
_Static_assert(__builtin_offsetof(struct rampart_config, udp_window_ns) == 56, "udp_window_ns");
_Static_assert(__builtin_offsetof(struct rampart_config, feature_syn_throttle) == 64, "feature_syn_throttle");
_Static_assert(__builtin_offsetof(struct rampart_config, feature_events) == 65, "feature_events");
_Static_assert(__builtin_offsetof(struct rampart_config, syn_challenge_enabled) == 66, "syn_challenge_enabled");
_Static_assert(__builtin_offsetof(struct rampart_config, challenge_secret) == 72, "challenge_secret");
_Static_assert(__builtin_offsetof(struct rampart_config, challenge_timeout_ms) == 80, "challenge_timeout_ms");
_Static_assert(__builtin_offsetof(struct rampart_config, challenge_verified_ttl_ns) == 88, "challenge_verified_ttl_ns");
/**
* Read-only aliases that keep the hot path short.
*
* They expand to field accesses on G, so they remain live reads of the
* patched .rodata and cost nothing at runtime.
*/
#define G_START_PORT G.start_port
#define G_END_PORT G.end_port
#define G_SYN_HIT_COUNT G.syn_hit_count
#define G_SYN_WINDOW_NS G.syn_window_ns
#define G_SYN_BAN_DURATION_NS G.syn_ban_duration_ns
#define G_CONNTRACK_IDLE_NS G.conntrack_idle_ns
#define G_PLAYER_IDLE_NS G.player_idle_ns
#define G_BAN_DURATION_NS G.ban_duration_ns
#define G_MAX_OUT_OF_ORDER G.max_out_of_order
#define G_UDP_POLICY G.udp_policy
#define G_UDP_HIT_COUNT G.udp_hit_count
#define G_UDP_WINDOW_NS G.udp_window_ns
#define G_FEATURE_SYN_THROTTLE G.feature_syn_throttle
#define G_FEATURE_EVENTS G.feature_events
#define G_SYN_CHALLENGE_ENABLED G.syn_challenge_enabled
#define G_CHALLENGE_SECRET G.challenge_secret
#define G_CHALLENGE_TIMEOUT_MS G.challenge_timeout_ms
#define G_CHALLENGE_VERIFIED_TTL_NS G.challenge_verified_ttl_ns
#endif /* RAMPART_CONFIG_H */ #endif /* RAMPART_CONFIG_H */

View file

@ -1,8 +1,14 @@
#ifndef RAMPART_MAPS_H #ifndef RAMPART_MAPS_H
#define RAMPART_MAPS_H #define RAMPART_MAPS_H
// 🔗 Blacklist (LPM_TRIE for CIDR support) /**
// Cleared by Rust userspace or per-entry expiry via ringbuf * IPv4 blacklist.
*
* 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 removed lazily by the lookup helpers. BPF_F_NO_PREALLOC is
* required by the LPM trie type.
*/
struct { struct {
__uint(type, BPF_MAP_TYPE_LPM_TRIE); __uint(type, BPF_MAP_TYPE_LPM_TRIE);
__uint(max_entries, 100000); __uint(max_entries, 100000);
@ -11,8 +17,12 @@ struct {
__uint(map_flags, BPF_F_NO_PREALLOC); __uint(map_flags, BPF_F_NO_PREALLOC);
} blacklist_map SEC(".maps"); } blacklist_map SEC(".maps");
// 🔗 IPv6 blacklist (LPM_TRIE, 128-bit prefix keys) /**
// Same value/expiry contract as blacklist_map * IPv6 blacklist.
*
* LPM trie over 128-bit prefix keys, the exact analogue of blacklist_map:
* same expiry semantics, same required map flags.
*/
struct { struct {
__uint(type, BPF_MAP_TYPE_LPM_TRIE); __uint(type, BPF_MAP_TYPE_LPM_TRIE);
__uint(max_entries, 100000); __uint(max_entries, 100000);
@ -21,7 +31,12 @@ struct {
__uint(map_flags, BPF_F_NO_PREALLOC); __uint(map_flags, BPF_F_NO_PREALLOC);
} blacklist6_map SEC(".maps"); } blacklist6_map SEC(".maps");
// 🔗 Whitelist (LPM_TRIE for CIDR) — checked before any filter /**
* Whitelist.
*
* LPM trie of trusted CIDRs; the filter consults it before any other check
* so allowlisted traffic can never be throttled or banned away.
*/
struct { struct {
__uint(type, BPF_MAP_TYPE_LPM_TRIE); __uint(type, BPF_MAP_TYPE_LPM_TRIE);
__uint(max_entries, 1000); __uint(max_entries, 1000);
@ -30,8 +45,12 @@ struct {
__uint(map_flags, BPF_F_NO_PREALLOC); __uint(map_flags, BPF_F_NO_PREALLOC);
} whitelist_map SEC(".maps"); } whitelist_map SEC(".maps");
// 🔗 Connection tracking (SYN_RECEIVED → ESTABLISHED) /**
// LRU — автоматическое вытеснение старых записей * 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.
*/
struct { struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 16384); __uint(max_entries, 16384);
@ -39,7 +58,12 @@ struct {
__type(value, struct conntrack_entry); __type(value, struct conntrack_entry);
} conntrack_map SEC(".maps"); } conntrack_map SEC(".maps");
// 🔗 SYN throttle per-source-IP (LRU) /**
* Per-source SYN throttle state.
*
* LRU keeps memory bounded under spoofed-source floods, where the number of
* distinct keys is unbounded and an exact table would simply fill up.
*/
struct { struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 65535); __uint(max_entries, 65535);
@ -47,7 +71,12 @@ struct {
__type(value, struct throttle_entry); __type(value, struct throttle_entry);
} connection_throttle SEC(".maps"); } connection_throttle SEC(".maps");
// 🔗 UDP rate limit per-source-IP (LRU) — policy from config.h /**
* Per-source UDP rate-limit state.
*
* The window and threshold come from G_UDP_POLICY / G_UDP_HIT_COUNT, so the
* same map serves pass, drop and rate-limit modes without reloading.
*/
struct { struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 65535); __uint(max_entries, 65535);
@ -55,15 +84,39 @@ struct {
__type(value, struct throttle_entry); __type(value, struct throttle_entry);
} udp_rate_limit SEC(".maps"); } udp_rate_limit SEC(".maps");
// ── RST-challenge pending state (challenge reflected, awaiting proof) ── /**
* IPv6 twin of udp_rate_limit.
*
* Native IPv6 has no 32-bit source address to key on, so the key is the full
* 128-bit address; the value and window contract are identical.
*/
struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 65535);
__type(key, struct in6_addr); // src6
__type(value, struct throttle_entry);
} udp_rate_limit6 SEC(".maps");
/**
* RST-challenge pending state, one record per challenged flow.
*
* marker is our chosen ISN and bad_ack is the deliberately unacceptable
* acknowledgement we sent; either one echoed back proves the source saw the
* challenge, so both are kept until the proof arrives or the TTL expires.
*/
struct challenge_pending { struct challenge_pending {
__u64 sent_at; // ktime_ns of the reflected SYN-ACK __u64 sent_at; // ktime_ns of the reflected SYN-ACK
__u32 marker; // our ISN (client may echo it as ack) __u32 marker; // our ISN (client may echo it as ack)
__u32 bad_ack; // bogus ack sent (live client echoes it as RST seq) __u32 bad_ack; // bogus ack sent (live client echoes it as RST seq)
}; };
// 🔗 RST-challenge: verified sources (liveness proven) — sliding TTL via /**
// last_seen, LRU eviction as the hard cap * Sources that already passed the RST challenge.
*
* The value is the last time the source proved liveness: the TTL is slid
* forward on each verified SYN, and LRU eviction is the hard cap when more
* sources are active than the table holds.
*/
struct { struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 65536); __uint(max_entries, 65536);
@ -71,7 +124,12 @@ struct {
__type(value, __u64); // last_seen (ktime_ns) __type(value, __u64); // last_seen (ktime_ns)
} challenge_verified SEC(".maps"); } challenge_verified SEC(".maps");
// 🔗 RST-challenge: outstanding challenges keyed by flow 4-tuple /**
* Outstanding challenges, keyed by the flow 4-tuple.
*
* Keyed per flow rather than per source so two concurrent connections from
* the same host cannot overwrite each other's expected proof.
*/
struct { struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 16384); __uint(max_entries, 16384);
@ -79,7 +137,12 @@ struct {
__type(value, struct challenge_pending); __type(value, struct challenge_pending);
} challenge_pending SEC(".maps"); } challenge_pending SEC(".maps");
// 🔗 Statistics (per-CPU, атомарные инкременты) /**
* Statistics counters, indexed by the STAT_* constants below.
*
* Per-CPU array: increments need no atomics between CPUs, userspace sums the
* per-CPU values when it reads the map.
*/
#define STAT_TOTAL 0 #define STAT_TOTAL 0
#define STAT_TCP 1 #define STAT_TCP 1
#define STAT_WHITELIST 2 #define STAT_WHITELIST 2
@ -93,6 +156,12 @@ struct {
#define STAT_CHALLENGE_VERIFIED 10 #define STAT_CHALLENGE_VERIFIED 10
#define STAT_CHALLENGE_FAILED 11 #define STAT_CHALLENGE_FAILED 11
/**
* Per-CPU counter storage.
*
* max_entries is rounded up past the highest STAT_* index so slots can be
* added without touching the map definition.
*/
struct { struct {
__uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
__uint(max_entries, 16); __uint(max_entries, 16);

View file

@ -3,23 +3,45 @@
#include "common.h" #include "common.h"
// ── Per-prefix traffic statistics (shared ABI with Rust userspace) ── /**
// Layout is part of the userspace contract — do not reorder fields. * Per-prefix traffic statistics.
*
* The key layout is shared with the Rust userspace, which reads and resets
* these counters, so the fields must not be reordered. Coarse prefixes rather
* than single hosts keep the table small while still exposing a source
* subnet that floods.
*/
// family: 4 = IPv4 /24 префикс, 6 = IPv6 /64 префикс /**
* Prefix key.
*
* family selects the prefix width (see PREFIX_FAMILY_V4 / PREFIX_FAMILY_V6);
* addr holds network-order prefix bytes, zero-padded to 16.
*/
struct prefix_key { struct prefix_key {
__u8 family; __u8 family;
__u8 pad[7]; __u8 pad[7];
__u8 addr[16]; // network-order байты префикса, zero-padded __u8 addr[16]; // network-order prefix bytes, zero-padded
}; };
/**
* Counters accumulated for one prefix.
*
* last_seen_ns is a bpf_ktime_get_ns() timestamp, so userspace can ignore
* prefixes that went quiet without keeping its own clock.
*/
struct prefix_stats_val { struct prefix_stats_val {
__u64 syn_count; __u64 syn_count;
__u64 pkt_count; __u64 pkt_count;
__u64 last_seen_ns; // bpf_ktime_get_ns() __u64 last_seen_ns; // bpf_ktime_get_ns()
}; };
// 🔗 Prefix statistics (LRU) — читается и сбрасывается юзерспейсом /**
* Prefix statistics table.
*
* LRU because the number of distinct sources is attacker-controlled; the
* userspace detector reads and resets the entries on its own schedule.
*/
struct { struct {
__uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 65536); __uint(max_entries, 65536);
@ -30,17 +52,33 @@ struct {
#define PREFIX_FAMILY_V4 4 #define PREFIX_FAMILY_V4 4
#define PREFIX_FAMILY_V6 6 #define PREFIX_FAMILY_V6 6
// ── Build /24 IPv4 prefix key (network-order, low 8 bits masked out) ── /**
* Build a /24 IPv4 prefix key.
*
* Copies the address in network order and clears the low octet, which is
* exactly a /24 mask without an arithmetic round trip.
*
* @param key key to initialise
* @param src_ip_net_order source address, network byte order
*/
static __always_inline void prefix_key_from_v4(struct prefix_key *key, static __always_inline void prefix_key_from_v4(struct prefix_key *key,
__u32 src_ip_net_order) __u32 src_ip_net_order)
{ {
__builtin_memset(key, 0, sizeof(*key)); __builtin_memset(key, 0, sizeof(*key));
key->family = PREFIX_FAMILY_V4; key->family = PREFIX_FAMILY_V4;
__builtin_memcpy(key->addr, &src_ip_net_order, 4); __builtin_memcpy(key->addr, &src_ip_net_order, 4);
key->addr[3] = 0; // обнулить младшие 8 бит адреса key->addr[3] = 0; // mask the low octet to get a /24
} }
// ── Build /64 IPv6 prefix key (network-order, low 64 bits masked out) ── /**
* Build a /64 IPv6 prefix key.
*
* Only the high 64 bits are copied; the remainder stays zero from the
* memset, giving a /64 mask in network order.
*
* @param key key to initialise
* @param src_addr 16-byte source address, network byte order
*/
static __always_inline void prefix_key_from_v6(struct prefix_key *key, static __always_inline void prefix_key_from_v6(struct prefix_key *key,
const __u8 src_addr[16]) const __u8 src_addr[16])
{ {
@ -49,8 +87,17 @@ static __always_inline void prefix_key_from_v6(struct prefix_key *key,
__builtin_memcpy(key->addr, src_addr, 8); __builtin_memcpy(key->addr, src_addr, 8);
} }
// ── Increment per-prefix counters (sliding window handled in userspace) ── /**
// is_syn: 1 → syn_count++, 0 → pkt_count++; last_seen_ns updated всегда. * Increment the counters for one prefix.
*
* Creates the entry on first sight. is_syn selects the counter to bump, so a
* SYN flood and a payload flood stay distinguishable downstream; last_seen_ns
* is refreshed on every call. The rate window itself lives in userspace.
*
* @param key prefix key, already built
* @param is_syn 1 counts a SYN, 0 counts any other packet
* @param now current bpf_ktime_get_ns() timestamp
*/
static __always_inline void update_prefix_stats(struct prefix_key *key, static __always_inline void update_prefix_stats(struct prefix_key *key,
__u8 is_syn, __u64 now) __u8 is_syn, __u64 now)
{ {

Some files were not shown because too many files have changed in this diff Show more