feat(xdp): IPv6 UDP rate limit, working loader; English comments and docs
XDP behaviour: - udp_rate_limit6 (LRU, full 128-bit source key) plus throttle_hit6, so udp_policy = "rate-limit" 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). Loader (XDP could never load before this): - .rodata is one struct rampart_config with frozen offsets enforced by _Static_assert; XdpGlobals is #[repr(C)] and the image is built with offset_of!. Before, 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 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 checks map names and .rodata size without root. Docs and style: - Code comments are English, JavaDoc/Rustdoc style, without emoji or banners (new project rule, TODO §0.8). - README rewritten bilingual: Russian first, English below, nav buttons, compact 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 covers the real-kernel smoke; stale links removed.
This commit is contained in:
parent
b64c329125
commit
a8a3057719
104 changed files with 2155 additions and 1030 deletions
497
README.md
497
README.md
|
|
@ -1,256 +1,337 @@
|
|||
<div align="center">
|
||||
|
||||
> **⚠️ UNDER DEVELOPMENT** — All performance data, benchmarks, and specifications shown are approximate and subject to change.
|
||||
>
|
||||
> **⚠️ В РАЗРАБОТКЕ** — Все показатели производительности, тесты и характеристики являются примерными и могут измениться.
|
||||
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
|
||||
# Rampart
|
||||
|
||||
Universal network protection platform (L3/L4/L7 DDoS filtering framework)
|
||||
**Универсальная платформа сетевой защиты: L3/L4/L7-фильтрация DDoS для VDS, веб-сервисов и игровых серверов.**
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
[English](#english) | [Русский](#russian)
|
||||
[](docs/README.md)
|
||||
[](#быстрый-старт)
|
||||
[](docs/configuration.md)
|
||||
[](docs/api.md)
|
||||
[](LICENSE)
|
||||
|
||||
</div>
|
||||
[Русский](#русский) · [English](#english)
|
||||
|
||||
> **Статус:** проект в активной разработке — 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>
|
||||
|
||||
## Русский
|
||||
|
||||
[Обзор](#обзор) · [Возможности](#возможности) · [Требования](#требования) · [Установка](#установка) · [Быстрый старт](#быстрый-старт) · [Конфигурация](#конфигурация) · [Плагины](#протокол-плагины) · [Производительность](#производительность) · [Документация](#документация) · [Разработка](#разработка) · [Лицензия](#лицензия)
|
||||
|
||||
### Обзор
|
||||
|
||||
Rampart фильтрует трафик на трёх уровнях до того, как он дойдёт до вашего сервиса:
|
||||
Rampart отбрасывает атакующий трафик до того, как он дойдёт до вашего сервиса.
|
||||
Фильтрация идёт в три уровня: XDP/eBPF в ядре, PoW-challenge в userspace и
|
||||
L7-анализ протокола. Логика конкретного протокола вынесена в плагины, поэтому
|
||||
одна платформа защищает и веб-сервис, и игровой сервер.
|
||||
|
||||
- **Уровень ядра** — XDP/eBPF отбрасывает нежелательные пакеты до того, как они попадут в TCP-стек Linux;
|
||||
- **Сетевой уровень** — PoW-challenge повышает стоимость флуда соединений для любого TCP-протокола;
|
||||
- **Прикладной уровень** — userspace-ядро на Rust выполняет анализ L7-handshake, rate limiting и проверку репутации.
|
||||
Подходит, если нужен свой edge-фильтр на VDS: без покупки «коробки», с
|
||||
конфигом в TOML и метриками в Prometheus.
|
||||
|
||||
Логика, специфичная для протоколов, вынесена в **модульные протокол-плагины** — одна платформа защищает VDS, веб-сервисы и игровые серверы.
|
||||
|
||||
### Архитектура
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────────┐
|
||||
│ Слой 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] → [Плагин] → Ваш сервис
|
||||
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 проксировано |
|
||||
| Маскированный flood с 100 IP (default 5 pps/IP) | **99.6% заблокировано**, легитимные клиенты в порядке |
|
||||
| SYN flood без XDP | 0 влияния — обрабатывается ядром |
|
||||
| Компонент | Требование |
|
||||
|-----------|------------|
|
||||
| Rust | 1.85+ (edition 2024) |
|
||||
| XDP | Linux 5.10+, `clang` с `-target bpf`, `libbpf`/`libelf` |
|
||||
| Опционально | Redis (синхронизация блэклиста), ClickHouse (события), GeoIP-база |
|
||||
|
||||
Полный набор бенчмарков в процессе подготовки.
|
||||
### Установка
|
||||
|
||||
```bash
|
||||
# Сборка edge-ноды с HTTP-обработчиком
|
||||
cargo build --release --features protocol-http
|
||||
|
||||
# Конфиг: путь по умолчанию /etc/rampart/config.toml,
|
||||
# переопределяется переменной $RAMPART_CONFIG
|
||||
sudo mkdir -p /etc/rampart
|
||||
sudo cp deploy/config/edge-http.toml /etc/rampart/config.toml
|
||||
```
|
||||
|
||||
С XDP-фильтром (нужен root либо `CAP_BPF` + `CAP_NET_ADMIN`):
|
||||
|
||||
```bash
|
||||
cargo build --release --features protocol-http,xdp
|
||||
```
|
||||
|
||||
### Быстрый старт
|
||||
|
||||
```bash
|
||||
# Сборка HTTP-обработчика
|
||||
cargo build --release --features protocol-http
|
||||
|
||||
# Установка дефолтного конфига
|
||||
sudo mkdir -p /etc/rampart
|
||||
sudo cp deploy/config/edge-http.toml /etc/rampart/config.toml
|
||||
|
||||
# Запуск edge ноды (путь конфига берётся из $RAMPART_CONFIG, по умолчанию /etc/rampart/config.toml)
|
||||
RAMPART_CONFIG=/etc/rampart/config.toml ./target/release/rampart
|
||||
```
|
||||
|
||||
### Minecraft Java Edge
|
||||
В конфиге для XDP: `[xdp] enabled = true`, `interface = "eth0"`. Метрики —
|
||||
`http://127.0.0.1:9090/metrics`.
|
||||
|
||||
В проекте появился ранний TCP-обработчик Minecraft Java. Соберите его командой
|
||||
`cargo build --release --features protocol-minecraft --bin rampart`, скопируйте
|
||||
`deploy/config/edge.toml` как конфиг и настройте
|
||||
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
|
||||
```
|
||||
|
||||
### Конфигурация
|
||||
|
||||
```toml
|
||||
[bind]
|
||||
address = "0.0.0.0"
|
||||
port = 25565
|
||||
|
||||
[backend]
|
||||
upstreams = ["127.0.0.1:25566"]
|
||||
|
||||
[xdp]
|
||||
enabled = false # требует сборки с feature `xdp`
|
||||
interface = "eth0"
|
||||
udp_policy = "pass" # pass | drop | rate-limit
|
||||
```
|
||||
|
||||
Все поля и значения по умолчанию — [docs/configuration.md](docs/configuration.md).
|
||||
|
||||
### Протокол-плагины
|
||||
|
||||
| Плагин | 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/research/architecture.md](docs/research/architecture.md) | Слоистая архитектура, ADR, миграционные заметки |
|
||||
| [docs/research/load-test-report.md](docs/research/load-test-report.md) | Отчёт по VDS stress test (2026-08-04) |
|
||||
| [docs/research/](docs/research/) | Research-заметки: eBPF, антибот, векторы DDoS, сети |
|
||||
| [docs/deployment.md](docs/deployment.md) | Руководство по деплою |
|
||||
| [docs/minecraft-java.md](docs/minecraft-java.md) | Minecraft Java edge и настройка Paper |
|
||||
| [docs/configuration.md](docs/configuration.md) | Справочник конфигурации |
|
||||
| [docs/runbook.md](docs/runbook.md) | Операционный runbook |
|
||||
| Раздел | Где |
|
||||
|--------|-----|
|
||||
| Индекс всей документации | [docs/README.md](docs/README.md) |
|
||||
| Деплой | [docs/deployment.md](docs/deployment.md) |
|
||||
| Конфигурация | [docs/configuration.md](docs/configuration.md) |
|
||||
| Эксплуатация (runbook) | [docs/runbook.md](docs/runbook.md) |
|
||||
| Диагностика | [docs/troubleshooting.md](docs/troubleshooting.md) |
|
||||
| Тестирование | [docs/testing.md](docs/testing.md) |
|
||||
| API manager'а | [docs/api.md](docs/api.md) |
|
||||
| База знаний (атаки, защита, практика) | [docs/kb/](docs/kb/) |
|
||||
| Research: архитектура, eBPF, DDoS | [docs/research/](docs/research/) |
|
||||
|
||||
### Roadmap
|
||||
### Разработка
|
||||
|
||||
- Стабилизация API протокол-плагинов
|
||||
- BPF hook модули для глубокого парсинга протоколов в XDP
|
||||
- Правила кода и Definition of Done — [TODO.md](TODO.md) (§0).
|
||||
- Комментарии в коде — только по-английски, 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
|
||||
## English
|
||||
|
||||
- [Releases](../../releases)
|
||||
- [Issues](../../issues)
|
||||
- [License](LICENSE)
|
||||
[Overview](#overview) · [Features](#features) · [Requirements](#requirements) · [Installation](#installation) · [Quick start](#quick-start) · [Configuration](#configuration) · [Plugins](#protocol-plugins) · [Performance](#performance) · [Documentation](#documentation) · [Development](#development) · [License](#license)
|
||||
|
||||
### Overview
|
||||
|
||||
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.
|
||||
|
||||
It fits teams that need their own edge filter on a VDS: no appliance to buy, a
|
||||
TOML config, and Prometheus metrics out of the box.
|
||||
|
||||
**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 |
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Build the edge node with the HTTP handler
|
||||
cargo build --release --features protocol-http
|
||||
|
||||
# Config: default path is /etc/rampart/config.toml,
|
||||
# override it with $RAMPART_CONFIG
|
||||
sudo mkdir -p /etc/rampart
|
||||
sudo cp deploy/config/edge-http.toml /etc/rampart/config.toml
|
||||
```
|
||||
|
||||
With the XDP filter (root or `CAP_BPF` + `CAP_NET_ADMIN`):
|
||||
|
||||
```bash
|
||||
cargo build --release --features protocol-http,xdp
|
||||
```
|
||||
|
||||
### Quick start
|
||||
|
||||
```bash
|
||||
RAMPART_CONFIG=/etc/rampart/config.toml ./target/release/rampart
|
||||
```
|
||||
|
||||
For XDP set `[xdp] enabled = true` and `interface = "eth0"`. Metrics are served
|
||||
at `http://127.0.0.1:9090/metrics`.
|
||||
|
||||
Verify the checkout before making changes:
|
||||
|
||||
```bash
|
||||
cargo fmt --all --check
|
||||
cargo clippy --all-targets --all-features -- -D warnings
|
||||
cargo test --all-features
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
```toml
|
||||
[bind]
|
||||
address = "0.0.0.0"
|
||||
port = 25565
|
||||
|
||||
[backend]
|
||||
upstreams = ["127.0.0.1:25566"]
|
||||
|
||||
[xdp]
|
||||
enabled = false # requires the `xdp` feature
|
||||
interface = "eth0"
|
||||
udp_policy = "pass" # pass | drop | rate-limit
|
||||
```
|
||||
|
||||
Every field and its default: [docs/configuration.md](docs/configuration.md).
|
||||
|
||||
### 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
|
||||
|
||||
GNU General Public License v3.0
|
||||
GNU General Public License v3.0 — [LICENSE](LICENSE).
|
||||
|
|
|
|||
48
TODO.md
48
TODO.md
|
|
@ -43,6 +43,19 @@
|
|||
тесты живут в `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)
|
||||
|
|
@ -136,6 +149,16 @@ guard/
|
|||
### Документация
|
||||
- [x] docs/deployment.md, configuration.md, runbook.md — старых крейтов/MC не упоминают (grep чисто).
|
||||
- [x] docs/kb/README.md — индекс KB со ссылками.
|
||||
- [x] `docs/README.md` — единый индекс документации (начало работы, how-to, reference,
|
||||
протоколы, теория/research) + правила ведения: русский язык, один документ = одна
|
||||
задача, reference правится в том же PR, что и код, плоская структура, kebab-case.
|
||||
- [x] `README.md` — двуязычный: русская часть сверху, английская снизу, общая шапка/бейджи/
|
||||
переключатель языка, ряд кнопок-навигации (docs, quick start, config, API, license);
|
||||
секции по конвенции (обзор → возможности → требования → установка → быстрый старт →
|
||||
конфигурация → плагины → производительность → документация → разработка → лицензия),
|
||||
компактный 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).
|
||||
|
||||
## 2a. Раунд 2026-09-15 — исправлено по итогам ревью
|
||||
|
|
@ -180,7 +203,14 @@ guard/
|
|||
- [x] **Тесты**: `tests/xdp_ban_v6.rs` (layout ключа `/64` и `/128`, network order);
|
||||
`scripts/xdp_ipv6_smoke.sh` — реальный netns+verifier smoke (без бана pass → с баном
|
||||
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);
|
||||
ringbuf-события для v6; unban v6.
|
||||
- [x] **Expiry бана из userspace не работал в ядре** (найден и починен 2026-11-15, касался v4 и v6):
|
||||
|
|
@ -194,6 +224,22 @@ guard/
|
|||
Теперь минимум считается по протоколу (`sizeof(struct udphdr)` для UDP); регрессия —
|
||||
«короткая датаграмма» в `scripts/xdp_ipv6_smoke.sh`. TCP-путь не изменился: там по-прежнему
|
||||
требуется полный `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
|
||||
|
||||
|
|
|
|||
4
build.rs
4
build.rs
|
|
@ -15,6 +15,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
let dst = out_dir.join("universal_filter.o");
|
||||
|
||||
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 arch = host_triple.split('-').next().unwrap_or(&host_triple);
|
||||
|
|
|
|||
66
docs/README.md
Normal file
66
docs/README.md
Normal 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` и проверь,
|
||||
что цели существуют.
|
||||
|
|
@ -43,6 +43,18 @@ clickhouse_url = "" # пусто = запись событий вы
|
|||
[xdp]
|
||||
enabled = false # требует сборки --features xdp, kernel 5.10+
|
||||
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]
|
||||
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
|
||||
```
|
||||
|
||||
Параметры `[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*
|
||||
|
|
|
|||
|
|
@ -19,7 +19,6 @@
|
|||
| [haproxy.md](./haproxy.md) | HAProxy конфиг, mTLS, замена на Rust LB | v0.2 |
|
||||
| [envoy.md](./envoy.md) | EWMA балансировка, Circuit Breaker, xDS API | v0.5 |
|
||||
| [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 |
|
||||
| [benchmark.md](./benchmark.md) | Инструменты, методология, ожидаемые результаты | v0.3 |
|
||||
| [security.md](./security.md) | STRIDE, mTLS, Zero Trust, supply chain | v0.2 |
|
||||
|
|
@ -32,8 +31,7 @@
|
|||
|
||||
```
|
||||
Хочу написать первую версию (v0.1)
|
||||
→ architecture.md + minecraft-protocol.md + ddos.md
|
||||
|
||||
→ architecture.md + ddos.md
|
||||
Хочу добавить защиту от ботов
|
||||
→ anti-bot.md
|
||||
|
||||
|
|
@ -61,7 +59,6 @@
|
|||
| [api.md](../api.md) | REST API спецификация |
|
||||
| [testing.md](../testing.md) | Методология тестирования |
|
||||
| [troubleshooting.md](../troubleshooting.md) | FAQ |
|
||||
| [migration.md](../migration.md) | Обновление версий |
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -37,6 +37,19 @@ XDP: smoke-check компиляции BPF-программы:
|
|||
clang -O2 -g -target bpf -c xdp/core/universal_filter.c -o /tmp/universal_filter.o
|
||||
```
|
||||
|
||||
Функциональные проверки на реальном ядре (нужен root: CAP_BPF + CAP_NET_ADMIN,
|
||||
`bpftool`, `clang`, `python3`):
|
||||
|
||||
```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)
|
||||
|
|
|
|||
|
|
@ -1,17 +1,20 @@
|
|||
#!/usr/bin/env bash
|
||||
# Функциональный smoke XDP-банов на РЕАЛЬНОМ ядре (netns + veth + verifier).
|
||||
# Functional smoke test of XDP bans on a real kernel (netns + veth + verifier).
|
||||
#
|
||||
# Что проверяет:
|
||||
# 1. verifier принимает universal_filter.o;
|
||||
# 2. native-IPv6 без бана проходит, с записью /128 в blacklist6_map — дропается;
|
||||
# 3. короткая UDP-датаграмма (<20 байт L4) тоже дропается — раньше она уходила
|
||||
# в XDP_PASS мимо blacklist (проверка длины была рассчитана на TCP);
|
||||
# 4. то же для IPv4 (общий L4-гейт);
|
||||
# 5. expiry: бан с монотонным TTL реально истекает в ядре (раньше userspace
|
||||
# писал epoch-ns, а C сравнивал с bpf_ktime_get_ns() — бан жил вечно).
|
||||
# What it verifies:
|
||||
# 1. the verifier accepts universal_filter.o;
|
||||
# 2. native IPv6 traffic passes without a ban and is dropped once a /128
|
||||
# entry exists in blacklist6_map;
|
||||
# 3. a short UDP datagram (under 20 bytes of L4) is dropped as well; it used
|
||||
# to fall through to XDP_PASS past the blacklist because the length check
|
||||
# was sized for TCP;
|
||||
# 4. the same holds for IPv4, through the shared L4 gate;
|
||||
# 5. 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.
|
||||
# Запуск: sudo bash scripts/xdp_ipv6_smoke.sh
|
||||
# Requires root/CAP_BPF+CAP_NET_ADMIN, bpftool, clang, python3.
|
||||
# Run: sudo bash scripts/xdp_ipv6_smoke.sh
|
||||
|
||||
set -u
|
||||
|
||||
|
|
@ -30,6 +33,7 @@ PASS=1
|
|||
fail() { echo "FAIL: $1"; PASS=0; }
|
||||
ok() { echo "ok: $1"; }
|
||||
|
||||
# Detach and remove every artefact, so a rerun starts from a clean state.
|
||||
cleanup() {
|
||||
bpftool net detach xdp dev "$DEV0" 2>/dev/null
|
||||
rm -f "$PIN" "$OBJ"
|
||||
|
|
@ -41,11 +45,13 @@ trap cleanup EXIT
|
|||
[ "$(id -u)" = 0 ] || { echo "нужен root (CAP_BPF+CAP_NET_ADMIN)"; 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" \
|
||||
-Ixdp -Ixdp/core -Ixdp/hooks -I/usr/include/x86_64-linux-gnu \
|
||||
|| { echo "clang: не собралось"; exit 1; }
|
||||
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 link add "$DEV0" type veth peer name "$DEV1" || exit 2
|
||||
ip link set "$DEV1" netns "$NS"
|
||||
|
|
@ -58,36 +64,43 @@ ip -n "$NS" link set "$DEV1" up
|
|||
ip -n "$NS" link set lo up
|
||||
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 net attach xdp pinned "$PIN" dev "$DEV0" || exit 1
|
||||
ok "verifier принял программу, attach на $DEV0"
|
||||
|
||||
IDS=$(bpftool prog show pinned "$PIN" | grep -o 'map_ids [0-9,]*' | cut -d' ' -f2 | tr ',' ' ')
|
||||
B4=""
|
||||
B6=""
|
||||
ST=""
|
||||
for id in $IDS; do
|
||||
desc=$(bpftool map show id "$id" 2>/dev/null)
|
||||
case "$desc" in
|
||||
*"name blacklist6_map"*) B6=$id ;;
|
||||
*"name blacklist_map"*) B4=$id ;;
|
||||
*"name stats_map"*) ST=$id ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$B4" ] && [ -n "$B6" ] && [ -n "$ST" ] || { echo "карты не найдены"; exit 1; }
|
||||
# Resolve map ids from the pinned program; ids change on every load.
|
||||
discover_maps() {
|
||||
IDS=$(bpftool prog show pinned "$PIN" | grep -o 'map_ids [0-9,]*' | cut -d' ' -f2 | tr ',' ' ')
|
||||
B4=""
|
||||
B6=""
|
||||
ST=""
|
||||
for id in $IDS; do
|
||||
desc=$(bpftool map show id "$id" 2>/dev/null)
|
||||
case "$desc" in
|
||||
*"name blacklist6_map"*) B6=$id ;;
|
||||
*"name blacklist_map"*) B4=$id ;;
|
||||
*"name stats_map"*) ST=$id ;;
|
||||
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"
|
||||
|
||||
# Ключи 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"
|
||||
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 "
|
||||
import socket
|
||||
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
|
||||
s.sendto(b'x' * $1, ('$HOST6', $PORT))
|
||||
"
|
||||
}
|
||||
# Same for IPv4.
|
||||
send4() {
|
||||
ip netns exec "$NS" python3 -c "
|
||||
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() {
|
||||
bpftool -j map dump id "$ST" | python3 -c "
|
||||
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 'все нули')
|
||||
"
|
||||
}
|
||||
# Read a single counter value; empty output means the counter is zero.
|
||||
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 "
|
||||
import time
|
||||
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)
|
||||
for _ in 1 2 3; do send6 100; done
|
||||
sleep 0.5
|
||||
|
|
@ -132,7 +147,7 @@ pass1=$(metric pass)
|
|||
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"
|
||||
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
|
||||
drop1=$(metric drop)
|
||||
[ "${drop1:-0}" -ge $((${drop0:-0} + 6)) ] \
|
||||
|
|
@ -148,10 +163,11 @@ pass3=$(metric pass)
|
|||
&& ok "v6 после снятия бана проходит (pass $pass2 -> $pass3)" \
|
||||
|| 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)
|
||||
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
|
||||
drop1=$(metric drop)
|
||||
[ "${drop1:-0}" -ge $((${drop0:-0} + 3)) ] \
|
||||
|
|
@ -159,7 +175,8 @@ drop1=$(metric drop)
|
|||
|| fail "v4 короткая датаграмма прошла мимо бана ($(stats))"
|
||||
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
|
||||
bpftool map update id "$B6" key hex $KEY6 value hex $(mono_ns_hex $TTL) || fail "expiry update"
|
||||
drop0=$(metric drop)
|
||||
|
|
@ -179,5 +196,47 @@ drop3=$(metric drop); pass3=$(metric pass)
|
|||
&& ok "бан истёк по монотонным часам (pass $pass2 -> $pass3, drop $drop2 -> $drop3)" \
|
||||
|| fail "бан не истёк (pass $pass2 -> $pass3, drop $drop2 -> $drop3)"
|
||||
|
||||
[ "$PASS" = 1 ] && echo "PASS: XDP-баны (v4/v6, короткий L4, expiry) работают на живом ядре" || echo "FAIL"
|
||||
[ "$PASS" = 1 ]
|
||||
# Phase 4: UDP rate-limit (policy=2) for native IPv6.
|
||||
# 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 ]
|
||||
|
|
@ -1,18 +1,20 @@
|
|||
#!/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:
|
||||
# 1. verifier принимает universal_filter.o (загрузка через libbpf);
|
||||
# 2. attach на живом интерфейсе в netns, native-режим;
|
||||
# 3. легитимный HTTP проксируется;
|
||||
# 4. SYN-флуд порождает ringbuf-события -> opt-in auto-ban работает;
|
||||
# 5. по завершении бана трафик восстанавливается (expiry);
|
||||
# 6. после SIGTERM XDP-ПРОГРАММА РЕАЛЬНО ОТВЯЗАНА (регрессия на bug fd=-1).
|
||||
# Covers what cannot be checked in a CI container without CAP_BPF:
|
||||
# 1. the verifier accepts universal_filter.o (loaded through libbpf);
|
||||
# 2. attach on a live interface inside a netns, native mode;
|
||||
# 3. legitimate HTTP is proxied;
|
||||
# 4. a SYN flood produces ringbuf events, so opt-in auto-ban works;
|
||||
# 5. traffic recovers once the ban expires;
|
||||
# 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
|
||||
#
|
||||
# Требования: iproute2, bpftool, hping3, python3 (http.server), curl.
|
||||
# Requires: iproute2, bpftool, hping3, python3 (http.server), curl.
|
||||
|
||||
set -u
|
||||
|
||||
|
|
@ -32,6 +34,7 @@ PASS=1
|
|||
fail() { echo "FAIL: $1"; PASS=0; }
|
||||
ok() { echo "ok: $1"; }
|
||||
|
||||
# Kill both processes and drop the namespace, whatever the exit path was.
|
||||
cleanup() {
|
||||
[ -n "$RAMPID" ] && kill -9 "$RAMPID" 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; }
|
||||
[ -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 add "$NS" || { echo "не удалось создать netns"; exit 2; }
|
||||
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
|
||||
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
|
||||
[bind]
|
||||
address = "$EDGE_IP"
|
||||
|
|
@ -94,13 +99,13 @@ format = "text"
|
|||
enabled = false
|
||||
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"
|
||||
python3 -m http.server "$ORIGIN_PORT" --bind "$HOST_IP" -d "$WORK" >/dev/null 2>&1 &
|
||||
SRVPID=$!
|
||||
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" \
|
||||
ip netns exec "$NS" "$BIN" > "$WORK/rampart.log" 2>&1 &
|
||||
RAMPID=$!
|
||||
|
|
@ -116,8 +121,8 @@ else
|
|||
fail "XDP не аттачнулся; лог:"; sed -n '1,30p' "$WORK/rampart.log"; exit 1
|
||||
fi
|
||||
|
||||
# Режим attach: native ожидаем на veth, но fallback на generic — штатный
|
||||
# путь лестницы в load(); сверяем с честным логом режима от rampart.
|
||||
# Attach mode: native is expected on veth, but generic is a normal fallback in
|
||||
# the load() ladder, so compare against the mode rampart actually reports.
|
||||
if ip -n "$NS" link show rtap | grep -qE "xdp( |$)"; then
|
||||
ok "attach native (ip link: xdp)"
|
||||
elif ip -n "$NS" link show rtap | grep -q "xdpgeneric"; then
|
||||
|
|
@ -127,13 +132,13 @@ else
|
|||
fi
|
||||
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)
|
||||
echo "$BODY" | grep -q "rampart-smoke-origin" \
|
||||
&& ok "легитимный HTTP проксируется" \
|
||||
|| 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
|
||||
sleep 3
|
||||
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" \
|
||||
|| 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" = "err" ] || [ "$HTTP_CODE" = "000" ] \
|
||||
&& ok "забаненный клиент отклонён (http=$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
|
||||
BODY=$(curl -s --max-time 5 "http://$EDGE_IP:$EDGE_PORT/" || true)
|
||||
echo "$BODY" | grep -q "rampart-smoke-origin" \
|
||||
&& ok "бан истёк, легитимный трафик восстановлен" \
|
||||
|| 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"
|
||||
wait "$RAMPID"; RC=$?
|
||||
RAMPID=""
|
||||
|
|
@ -176,7 +182,7 @@ else
|
|||
ok "XDP-программа реально отвязана после SIGTERM"
|
||||
fi
|
||||
|
||||
# --- итог ---
|
||||
# Summary: exit code drives CI, the log excerpt makes a failure diagnosable.
|
||||
echo
|
||||
if [ "$PASS" = 1 ]; then
|
||||
echo "PASS — xdp netns smoke ($(uname -r))"
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! Wiring-логика edge-демона: сборка сервисов и главный цикл запуска.
|
||||
//! Edge daemon wiring: service construction and the main run loop.
|
||||
|
||||
pub mod runtime;
|
||||
pub mod services;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
//! Runtime edge-демона: сборка компонентов, фоновые задачи и запуск listener.
|
||||
//! Edge daemon runtime: component assembly, background tasks and listener
|
||||
//! startup.
|
||||
|
||||
use crate::config::Config;
|
||||
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
|
||||
/// Ошибки старта: нечитаемый конфиг, пустой реестр протоколов, сбой listener.
|
||||
/// Startup failures: unreadable config, empty protocol registry, listener error.
|
||||
pub async fn run() -> anyhow::Result<RunExit> {
|
||||
tracing_subscriber::fmt()
|
||||
.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);
|
||||
metrics::ATTACK_STATUS.set(attack_status_value(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();
|
||||
tracing::warn!(pps, cps, "{alert}");
|
||||
push_attack_event(&ch, pps).await;
|
||||
|
|
@ -208,8 +209,8 @@ pub async fn run() -> anyhow::Result<RunExit> {
|
|||
result?;
|
||||
Ok(RunExit::Ok)
|
||||
}
|
||||
// Drain-таймаут сработал: возвращаем сигнал бинарю завершить процесс
|
||||
// немедленно, как это делал прежний `process::exit(0)`.
|
||||
// The drain timeout fired: hand the signal back so the binary can end the
|
||||
// process immediately, replacing the former `process::exit(0)`.
|
||||
_ = drain_rx => Ok(RunExit::DrainTimeout),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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::engine::subnet::tracker::SubnetTracker;
|
||||
|
|
@ -13,11 +14,11 @@ use std::sync::Arc;
|
|||
use std::sync::Mutex;
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// Собирает реестр протоколов из скомпилированных реализаций.
|
||||
/// Builds the protocol registry from the compiled handlers.
|
||||
///
|
||||
/// Обработчики поставляются фичами: `protocol-http` регистрирует
|
||||
/// HTTP/1.1-обработчик с политикой из секции `[protocol.http]`.
|
||||
/// Внешние крейты регистрируют свои обработчики в этом же месте.
|
||||
/// Handlers are supplied by features: `protocol-http` registers the HTTP/1.1
|
||||
/// handler with the policy from `[protocol.http]`. External crates register
|
||||
/// their handlers at the same point.
|
||||
pub(crate) fn build_registry(config: &Config) -> ProtocolRegistry {
|
||||
#[cfg(feature = "protocol-minecraft")]
|
||||
if config.protocol.minecraft.enabled {
|
||||
|
|
@ -115,8 +116,8 @@ pub(crate) fn start_xdp(
|
|||
Ok(None)
|
||||
}
|
||||
|
||||
/// Юзерспейс-агрегатор префиксов: активен, когда detect.prefix включён,
|
||||
/// а XDP-путь не работает (не собран или выключен в конфиге).
|
||||
/// Userspace prefix aggregator: active when `detect.prefix` is enabled and the
|
||||
/// XDP path does not run (not compiled in or disabled in the config).
|
||||
pub(crate) fn start_subnet_tracker(config: &Config) -> Option<Arc<SubnetTracker>> {
|
||||
let xdp_active = cfg!(feature = "xdp") && config.xdp.enabled;
|
||||
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,
|
||||
/// в бинаре без `store-redis` должен упасть сразу, а не молча потерять
|
||||
/// blacklist-sync (sync-задача в runtime.rs живёт под тем же cfg).
|
||||
/// Точка вызова — `build_whitelist`: ближайший `?`-хук, принимающий конфиг
|
||||
/// до бинда listener'а (сам runtime.rs вне правок этой задачи).
|
||||
/// Validates store features at edge startup: a config that asks for redis in a
|
||||
/// binary without `store-redis` must fail immediately instead of silently losing
|
||||
/// blacklist sync (the sync task in `runtime.rs` lives behind the same cfg).
|
||||
///
|
||||
/// Called from `build_whitelist`, the closest `?` hook that receives the config
|
||||
/// before the listener binds.
|
||||
fn ensure_store_features(config: &Config) -> anyhow::Result<()> {
|
||||
#[cfg(not(feature = "store-redis"))]
|
||||
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(())
|
||||
}
|
||||
|
||||
/// 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>>> {
|
||||
ensure_store_features(config)?;
|
||||
let mut set = HashSet::with_capacity(config.whitelist.len());
|
||||
|
|
@ -191,10 +198,10 @@ mod tests {
|
|||
assert!(ensure_store_features(&config_with_redis()).is_ok());
|
||||
}
|
||||
|
||||
/// Wiring-тасовка XDP auto-ban: `start_xdp` обязан принимать `Arc<Blacklist>`
|
||||
/// (т.е. существовать в сигнатуре с blacklist) и при выключенном `[xdp]`
|
||||
/// не трогать ни ядро, ни blacklist. Порядок `set_autoban` -> `load()`
|
||||
/// внутри enabled-ветки без ядра непроверяем — см. комментарий на месте вызова.
|
||||
/// XDP auto-ban wiring: `start_xdp` must accept the `Arc<Blacklist>` and, with
|
||||
/// `[xdp]` disabled, touch neither the kernel nor the blacklist. The
|
||||
/// `set_autoban` -> `load()` order inside the enabled branch cannot be checked
|
||||
/// without a kernel.
|
||||
#[test]
|
||||
fn start_xdp_accepts_blacklist_and_skips_kernel_when_disabled() {
|
||||
let (_tx, rx) = watch::channel(false);
|
||||
|
|
|
|||
|
|
@ -1,23 +1,23 @@
|
|||
//! Shutdown-drain машина edge-демона: сигнал, drain-таймер и код завершения.
|
||||
//! Edge daemon shutdown drain: signal handling, drain timer and exit code.
|
||||
|
||||
use std::time::Duration;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// Результат завершения демона. Код выхода вычисляется здесь, но сам
|
||||
/// `process::exit` вызывается только в точке входа бинаря (`src/bin/rampart.rs`),
|
||||
/// поэтому библиотечный код остаётся свободным от lint `exit`.
|
||||
/// Daemon exit outcome. The exit code is computed here, but `process::exit` is
|
||||
/// only called from the binary entry point (`src/bin/rampart.rs`), which keeps
|
||||
/// the library free of the `exit` lint.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunExit {
|
||||
/// Listener отработал штатно: drain уложился в таймаут.
|
||||
/// The listener finished cleanly: the drain fit into the timeout.
|
||||
Ok,
|
||||
/// Истёк drain-таймаут: бинарь обязан завершить процесс немедленно
|
||||
/// (замена прежнему `process::exit(0)` внутри shutdown-таймера).
|
||||
/// The drain timeout expired: the binary must terminate the process immediately
|
||||
/// (replaces the former `process::exit(0)` inside the shutdown timer).
|
||||
DrainTimeout,
|
||||
}
|
||||
|
||||
impl RunExit {
|
||||
/// Код завершения процесса для данного результата.
|
||||
/// Process exit code for this outcome.
|
||||
#[must_use]
|
||||
pub const fn code(self) -> i32 {
|
||||
match self {
|
||||
|
|
@ -27,11 +27,11 @@ impl RunExit {
|
|||
}
|
||||
}
|
||||
|
||||
/// Ставит фоновую shutdown-задачу.
|
||||
/// Spawns the background shutdown task.
|
||||
///
|
||||
/// shutdown-таймер обязан завершить процесс: сам `process::exit` вынесен в
|
||||
/// бинарь, а здесь мы лишь уведомляем `run` об истечении drain-таймаута через
|
||||
/// oneshot-канал. Логи и тайминг (5s после сигнала) сохранены без изменений.
|
||||
/// The timer must end the process, but `process::exit` now lives in the binary,
|
||||
/// so this only reports the drain timeout to `run` over a oneshot channel. The
|
||||
/// 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<()>) {
|
||||
tokio::spawn(async move {
|
||||
wait_for_signal().await;
|
||||
|
|
@ -60,7 +60,7 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
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::DrainTimeout.code(), 0);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! Command-line client for the Rampart manager API.
|
||||
|
||||
#![allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! Rampart manager daemon: HTTP API in front of the redis state store.
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
http::HeaderValue,
|
||||
|
|
@ -18,8 +20,8 @@ async fn main() -> anyhow::Result<()> {
|
|||
.with_env_filter(EnvFilter::from_default_env().add_directive("rampart=info".parse()?))
|
||||
.init();
|
||||
|
||||
// Manager живёт исключительно на redis-хранилище: без фичи стартовать
|
||||
// нечего — fail-fast вместо полумёртвого API (features additive, TODO SOLID D).
|
||||
// The manager lives exclusively on the redis store: without the feature there
|
||||
// is nothing to start, so fail fast instead of serving a half-dead API.
|
||||
if !cfg!(feature = "store-redis") {
|
||||
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/auth/login", post(api::auth::login));
|
||||
|
||||
// Redis-зависимые маршруты существуют только вместе с фичей; сам manager
|
||||
// без неё bail'ит выше, поэтому 501-заглушки были бы недостижимым кодом.
|
||||
// Redis-backed routes only exist together with the feature; the manager bails
|
||||
// out above without it, so 501 stubs here would be unreachable code.
|
||||
let protected = Router::new();
|
||||
#[cfg(feature = "store-redis")]
|
||||
let protected = protected
|
||||
|
|
|
|||
|
|
@ -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::time::Duration;
|
||||
|
|
@ -21,7 +21,7 @@ struct Cli {
|
|||
/// URL Prometheus metrics endpoint
|
||||
#[arg(long, default_value = "http://127.0.0.1:9090/metrics")]
|
||||
url: String,
|
||||
/// Период опроса, секунды
|
||||
/// Scrape interval in seconds
|
||||
#[arg(long, default_value_t = 1)]
|
||||
refresh_secs: u64,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
//! Edge daemon entry point; all work is delegated to [`rampart::app::run`].
|
||||
|
||||
use rampart::app::{self, RunExit};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
match app::run().await? {
|
||||
// Штатное завершение listener: управление возвращается tokio-рантайму.
|
||||
// Clean listener shutdown: control returns to the tokio runtime.
|
||||
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()),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! `blacklist` subcommands: manage the manager blacklist over its HTTP API.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
|
|
|
|||
|
|
@ -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<()> {
|
||||
match (key, value) {
|
||||
(Some(_), Some(_)) => {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
//! `doctor` subcommand: environment, manager API and XDP diagnostics.
|
||||
|
||||
use crate::xdp::{EnvironmentReport, FilesystemProbe, SystemProbe};
|
||||
|
||||
/// Ищет интерфейс с маршрутом по умолчанию в /proc/net/route
|
||||
/// (destination == 00000000). Работает без root.
|
||||
/// Finds the interface that owns the default route in `/proc/net/route`
|
||||
/// (destination `00000000`). Works without root.
|
||||
fn default_route_interface(probe: &impl SystemProbe) -> Option<String> {
|
||||
let routes = probe.read_file("/proc/net/route").ok()?;
|
||||
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) {
|
||||
println!("\nNetwork / XDP");
|
||||
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<()> {
|
||||
println!("Rampart Diagnostics");
|
||||
println!("=====================\n");
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! Subcommand implementations for the Rampart CLI.
|
||||
|
||||
pub mod blacklist;
|
||||
pub mod config;
|
||||
pub mod doctor;
|
||||
|
|
|
|||
|
|
@ -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<()> {
|
||||
anyhow::bail!("graceful drain is not implemented for node {node}")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<()> {
|
||||
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<()> {
|
||||
anyhow::bail!("emergency mode is not implemented; change the edge policy and restart Rampart")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! CLI-команды управления edge-узлами: статус, drain, аварийный режим.
|
||||
//! Edge node management commands: status, drain and emergency mode.
|
||||
pub mod drain;
|
||||
pub mod emergency;
|
||||
pub mod status;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! `status` subcommand: print the manager health summary.
|
||||
|
||||
pub async fn run() -> anyhow::Result<()> {
|
||||
println!("Rampart Status");
|
||||
println!("================\n");
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
//! CLI-команды для bin/rampart-cli.
|
||||
//! CLI commands used by `bin/rampart-cli`.
|
||||
#[allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
pub mod commands;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
#[cfg(feature = "protocol-http")]
|
||||
|
|
@ -50,21 +53,21 @@ pub struct Config {
|
|||
}
|
||||
|
||||
impl Config {
|
||||
/// Парсит конфиг из TOML-строки и валидирует семантику.
|
||||
/// Parses the config from a TOML string and validates its semantics.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при невалидном TOML или нарушении инвариантов
|
||||
/// (пустой список upstream-бэкендов, некорректные адреса).
|
||||
/// Fails on invalid TOML or on a violated invariant (empty upstream list,
|
||||
/// malformed addresses, unsafe PROXY protocol settings).
|
||||
pub fn parse_str(contents: &str) -> anyhow::Result<Self> {
|
||||
let config: Config = toml::from_str(contents)?;
|
||||
config.validate()?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Читает и парсит конфиг из файла.
|
||||
/// Reads and parses the config from a file.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при невозможности прочитать файл или невалидном содержимом.
|
||||
/// Fails when the file cannot be read or its contents are invalid.
|
||||
pub fn from_file(path: &str) -> anyhow::Result<Self> {
|
||||
let contents = fs::read_to_string(path)?;
|
||||
Self::parse_str(&contents)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
//! Detection sections (`[detect*]`) and the per-protocol handler policy.
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Секция `[detect]`: детекторы распределённых атак.
|
||||
/// `[detect]` section: distributed attack detectors.
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
pub struct DetectConfig {
|
||||
#[serde(default)]
|
||||
|
|
@ -11,9 +13,10 @@ pub struct DetectConfig {
|
|||
pub alert: DetectAlertConfig,
|
||||
}
|
||||
|
||||
/// Секция `[detect.autoban]`: авто-бан источников по репутации и сигналам
|
||||
/// детектора атак. Порог сравнивается со скором [`crate::traffic::reputation::IpReputation`],
|
||||
/// TTL берётся из `ban.ban_duration_secs`.
|
||||
/// `[detect.autoban]` section: auto-ban sources based on reputation and attack
|
||||
/// detector signals. The threshold is compared against the
|
||||
/// [`crate::traffic::reputation::IpReputation`] score, the TTL comes from
|
||||
/// `ban.ban_duration_secs`.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct DetectAutobanConfig {
|
||||
#[serde(default)]
|
||||
|
|
@ -35,15 +38,15 @@ fn default_autoban_reputation_threshold() -> i32 {
|
|||
-50
|
||||
}
|
||||
|
||||
/// Секция `[detect.alert]`: webhook-алерты на переходах состояния атаки
|
||||
/// («атака началась» / «атака закончилась»).
|
||||
/// `[detect.alert]` section: webhook alerts on attack state transitions
|
||||
/// (attack started, attack ended).
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
pub struct DetectAlertConfig {
|
||||
#[serde(default)]
|
||||
pub webhook_url: Option<String>,
|
||||
}
|
||||
|
||||
/// Секция `[detect.prefix]`: subnet-level детектор распределённых атак.
|
||||
/// `[detect.prefix]` section: subnet-level detector for distributed attacks.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct DetectPrefixConfig {
|
||||
#[serde(default)]
|
||||
|
|
@ -77,7 +80,7 @@ fn default_prefix_min_unique_sources() -> u64 {
|
|||
16
|
||||
}
|
||||
|
||||
/// Секция `[protocol]`: протокольные обработчики (plugin-by-feature).
|
||||
/// `[protocol]` section: protocol handlers, enabled one plugin per feature.
|
||||
#[cfg(any(feature = "protocol-http", feature = "protocol-minecraft"))]
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
pub struct ProtocolConfig {
|
||||
|
|
@ -89,6 +92,7 @@ pub struct ProtocolConfig {
|
|||
pub minecraft: MinecraftProtocolConfig,
|
||||
}
|
||||
|
||||
/// `[protocol.minecraft]` section: Minecraft handshake handler policy.
|
||||
#[cfg(feature = "protocol-minecraft")]
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct MinecraftProtocolConfig {
|
||||
|
|
@ -129,7 +133,7 @@ fn default_minecraft_timeout_secs() -> u64 {
|
|||
5
|
||||
}
|
||||
|
||||
/// Секция `[protocol.http]`: политика HTTP/1.1-обработчика на edge-ноде.
|
||||
/// `[protocol.http]` section: HTTP/1.1 handler policy on the edge node.
|
||||
#[cfg(feature = "protocol-http")]
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct HttpProtocolConfig {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
//! Edge sections: bind, backend, workers, limits, ban, PoW and PROXY protocol.
|
||||
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
use std::str::FromStr;
|
||||
|
||||
/// `[bind]` section: listen address and port of the edge node.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct BindConfig {
|
||||
#[serde(default = "default_bind_address")]
|
||||
|
|
@ -26,7 +29,7 @@ fn default_bind_port() -> u16 {
|
|||
25565
|
||||
}
|
||||
|
||||
/// Generic upstream-бэкенды (список addr:port) за edge-нодой.
|
||||
/// `[backend]` section: upstream backends (`addr:port`) behind the edge node.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct BackendConfig {
|
||||
#[serde(default = "default_upstreams")]
|
||||
|
|
@ -45,6 +48,7 @@ fn default_upstreams() -> Vec<String> {
|
|||
vec!["127.0.0.1:25566".to_string()]
|
||||
}
|
||||
|
||||
/// `[workers]` section: number of accept loops sharing the listen address.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct WorkerConfig {
|
||||
#[serde(default = "default_worker_count")]
|
||||
|
|
@ -61,6 +65,7 @@ fn default_worker_count() -> usize {
|
|||
4
|
||||
}
|
||||
|
||||
/// `[limits]` section: per-IP connection and rate limits.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct LimitsConfig {
|
||||
#[serde(default = "default_handshake_timeout")]
|
||||
|
|
@ -97,6 +102,7 @@ fn default_rate_limit_burst() -> f64 {
|
|||
10.0
|
||||
}
|
||||
|
||||
/// `[ban]` section: default ban duration.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct BanConfig {
|
||||
#[serde(default = "default_ban_duration")]
|
||||
|
|
@ -115,6 +121,7 @@ fn default_ban_duration() -> u64 {
|
|||
3600
|
||||
}
|
||||
|
||||
/// `[pow]` section: proof-of-work gate.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct PowConfig {
|
||||
#[serde(default)]
|
||||
|
|
@ -131,7 +138,6 @@ impl Default for PowConfig {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_pow_difficulty() -> u8 {
|
||||
4
|
||||
}
|
||||
|
|
@ -144,25 +150,14 @@ pub struct TrustedProxyCidr {
|
|||
}
|
||||
|
||||
impl TrustedProxyCidr {
|
||||
/// Returns whether `ip` belongs to this network.
|
||||
#[must_use]
|
||||
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) {
|
||||
(IpAddr::V4(network), IpAddr::V4(ip)) => {
|
||||
let mask = if self.prefix_len == 0 {
|
||||
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
|
||||
},
|
||||
(IpAddr::V4(network), IpAddr::V4(ip)) => u32::from(network) & mask4 == u32::from(ip) & mask4,
|
||||
(IpAddr::V6(network), IpAddr::V6(ip)) => u128::from(network) & mask6 == u128::from(ip) & mask6,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
|
@ -213,6 +208,7 @@ fn mask_v6(prefix: u8) -> u128 {
|
|||
if prefix == 0 { 0 } else { u128::MAX << (128 - prefix) }
|
||||
}
|
||||
|
||||
/// `[proxy_protocol]` section: inbound PROXY protocol ingestion.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ProxyProtocolConfig {
|
||||
#[serde(default)]
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! Секции единого конфига платформы.
|
||||
//! Sections of the platform config.
|
||||
|
||||
mod detect;
|
||||
mod edge;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
//! Platform sections: store backends, XDP, logging and metrics.
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
/// `[store]` section: redis and ClickHouse backends.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct StoreConfig {
|
||||
pub redis_url: Option<String>,
|
||||
|
|
@ -22,6 +25,7 @@ fn default_blacklist_cache_ttl() -> u64 {
|
|||
300
|
||||
}
|
||||
|
||||
/// `[xdp]` section: kernel-side filter configuration and auto-ban policy.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct XdpConfig {
|
||||
#[serde(default)]
|
||||
|
|
@ -32,7 +36,7 @@ pub struct XdpConfig {
|
|||
pub protected_port_start: u16,
|
||||
#[serde(default = "default_xdp_port_end")]
|
||||
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")]
|
||||
pub udp_policy: String,
|
||||
#[serde(default = "default_xdp_udp_hit_count")]
|
||||
|
|
@ -41,7 +45,8 @@ pub struct XdpConfig {
|
|||
pub udp_rate_window_ms: u64,
|
||||
#[serde(default)]
|
||||
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)]
|
||||
pub challenge_secret_hex: Option<String>,
|
||||
#[serde(default = "default_xdp_challenge_timeout_ms")]
|
||||
|
|
@ -50,14 +55,15 @@ pub struct XdpConfig {
|
|||
pub throttle_enabled: bool,
|
||||
#[serde(default = "default_xdp_events_enabled")]
|
||||
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)]
|
||||
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")]
|
||||
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")]
|
||||
pub auto_ban_conn_drop_fails: u8,
|
||||
}
|
||||
|
|
@ -118,6 +124,7 @@ fn default_xdp_auto_ban_conn_drop_fails() -> u8 {
|
|||
3
|
||||
}
|
||||
|
||||
/// `[logging]` section: log level and format.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct LoggingConfig {
|
||||
#[serde(default = "default_log_level")]
|
||||
|
|
@ -142,6 +149,7 @@ fn default_log_format() -> String {
|
|||
"text".to_string()
|
||||
}
|
||||
|
||||
/// `[metrics]` section: Prometheus scrape endpoint.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct MetricsConfig {
|
||||
#[serde(default = "default_metrics_enabled")]
|
||||
|
|
|
|||
|
|
@ -1,8 +1,13 @@
|
|||
//! Adaptive proof-of-work difficulty driven by the observed connection rate.
|
||||
|
||||
use crate::metrics;
|
||||
use std::collections::VecDeque;
|
||||
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 {
|
||||
window: VecDeque<Instant>,
|
||||
min: u8,
|
||||
|
|
@ -17,6 +22,7 @@ impl Default for DifficultyAdjuster {
|
|||
}
|
||||
|
||||
impl DifficultyAdjuster {
|
||||
/// Creates an adjuster clamped to `min.max(4)` and `max.min(10)`.
|
||||
#[must_use]
|
||||
pub fn new(min: u8, max: u8) -> Self {
|
||||
Self {
|
||||
|
|
@ -27,6 +33,7 @@ impl DifficultyAdjuster {
|
|||
}
|
||||
}
|
||||
|
||||
/// Records one connection and recomputes the difficulty for the window.
|
||||
pub fn record_connection(&mut self) {
|
||||
let now = Instant::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]
|
||||
pub fn current_difficulty(&self) -> u8 {
|
||||
metrics::POW_CURRENT_DIFFICULTY.set(self.current as i64);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! Универсальный SHA-256 hashcash: генерация challenge, решатель,
|
||||
//! верификатор и адаптивная сложность.
|
||||
//! Universal SHA-256 hashcash: challenge generation, solver, verifier and
|
||||
//! adaptive difficulty.
|
||||
|
||||
mod difficulty;
|
||||
mod pow;
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ const CHALLENGE_TTL_SECS: u64 = 30;
|
|||
const MAX_NONCE_LEN: usize = 64;
|
||||
const ALLOWED_HEX_PREFIX: [u8; 4] = *b"0123";
|
||||
|
||||
/// Активная PoW-задача, выданная одному соединению.
|
||||
/// Active PoW challenge issued to one connection.
|
||||
pub struct Challenge {
|
||||
token: [u8; 32],
|
||||
created_at: Instant,
|
||||
|
|
@ -31,8 +31,8 @@ impl Challenge {
|
|||
}
|
||||
}
|
||||
|
||||
/// Challenge с явным токеном — для детерминированных тестов, где
|
||||
/// случайный дайджест даёт flaky-исход.
|
||||
/// Builds a challenge with an explicit token.
|
||||
/// Intended for deterministic tests, where a random token makes the outcome
|
||||
#[must_use]
|
||||
pub fn with_token(token: [u8; 32], difficulty: u8) -> Self {
|
||||
Self {
|
||||
|
|
@ -53,7 +53,9 @@ impl Challenge {
|
|||
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]
|
||||
pub fn verify(&mut self, nonce: &str) -> bool {
|
||||
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]
|
||||
pub fn solve(challenge: &str, difficulty: u8) -> Option<String> {
|
||||
let d = difficulty as usize;
|
||||
|
|
@ -99,10 +101,11 @@ pub fn solve(challenge: &str, difficulty: u8) -> Option<String> {
|
|||
None
|
||||
}
|
||||
|
||||
/// Проводит текстовый PoW-gate в потоке: выдаёт challenge и проверяет ответ.
|
||||
/// Runs the textual PoW gate on `stream`: issues a challenge and checks the
|
||||
/// answer.
|
||||
///
|
||||
/// # 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> {
|
||||
if difficulty == 0 {
|
||||
tracing::debug!("pow: difficulty 0, skipping for {peer_ip}");
|
||||
|
|
@ -150,8 +153,8 @@ mod tests {
|
|||
let mut challenge = Challenge::generate(4);
|
||||
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;
|
||||
for i in 0..10_000u32 {
|
||||
let candidate = format!("bad-{i}");
|
||||
|
|
|
|||
|
|
@ -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::engine::tunnel::Gateway;
|
||||
|
|
@ -8,11 +8,14 @@ use std::sync::Arc;
|
|||
use tokio::net::TcpListener;
|
||||
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
|
||||
/// Возвращает ошибку при невозможности забиндить адрес или падении одного
|
||||
/// из accept-loop'ов.
|
||||
/// Fails when the address cannot be bound or when one of the accept loops dies.
|
||||
pub async fn run(
|
||||
config: Arc<Config>,
|
||||
gateway: Arc<Gateway>,
|
||||
|
|
@ -75,7 +78,7 @@ async fn accept_loop(
|
|||
let gateway = Arc::clone(&gateway);
|
||||
let hook = Arc::clone(&hook);
|
||||
tokio::spawn(async move {
|
||||
// Hot path Traffic Intelligence: только атомики и DashMap.
|
||||
// Traffic intelligence hot path: atomics and `DashMap` only.
|
||||
hook.on_accept();
|
||||
let outcome = gateway.handle(stream, peer_addr).await;
|
||||
if let Err(e) = outcome.result {
|
||||
|
|
|
|||
|
|
@ -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 listener;
|
||||
pub mod subnet;
|
||||
pub mod tunnel;
|
||||
|
||||
// Совместимость путей после переезда в subnet/: `engine::subnet_tracker` /
|
||||
// `engine::subnet_monitor` остаются валидными алиасами модулей.
|
||||
// Path compatibility after the move into `subnet/`: `engine::subnet_tracker` and
|
||||
// `engine::subnet_monitor` stay valid module paths.
|
||||
pub use subnet::{monitor as subnet_monitor, tracker as subnet_tracker};
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
//! Subnet-level детектор: юзерспейс-агрегатор префиксов и монитор вердиктов.
|
||||
//! Subnet-level detector: userspace prefix aggregator and verdict monitor.
|
||||
pub mod monitor;
|
||||
pub mod tracker;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
//! Периодический subnet-монитор: источник снапшотов → детектор → эскалация.
|
||||
//! Periodic subnet monitor: snapshot source, detector and verdict escalation.
|
||||
//!
|
||||
//! Источник выбирается по сборке и конфигу: XDP-карта `prefix_stats`
|
||||
//! (feature `xdp` + загруженный фильтр) либо юзерспейс-агрегатор
|
||||
//! The source is chosen by build features and config: the XDP `prefix_stats` map
|
||||
//! (feature `xdp` with a loaded filter) or the userspace aggregator
|
||||
//! [`SubnetTracker`].
|
||||
|
||||
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(
|
||||
detect: &DetectPrefixConfig,
|
||||
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")]
|
||||
fn prefix_len(prefix: IpAddr) -> u8 {
|
||||
match prefix {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
//! Юзерспейс-агрегатор новых соединений по префиксам (/24, /64).
|
||||
//! Userspace aggregator of new connections per prefix (/24 for IPv4, /64 for
|
||||
//! IPv6).
|
||||
//!
|
||||
//! Fallback-путь subnet-детектора, когда XDP выключен: питает
|
||||
//! [`crate::traffic::prefix::SubnetDetector`] теми же снапшотами.
|
||||
//! Fallback path of the subnet detector when XDP is disabled: it feeds
|
||||
//! [`crate::traffic::prefix::SubnetDetector`] with the same snapshot shape the
|
||||
//! kernel map produces.
|
||||
|
||||
use crate::traffic::prefix::{PrefixSnapshot, PrefixStatsSource, prefix_of};
|
||||
use dashmap::DashMap;
|
||||
|
|
@ -15,8 +17,10 @@ struct WindowState {
|
|||
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 {
|
||||
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) {
|
||||
let prefix = prefix_of(ip);
|
||||
let mut state = self.windows.entry(prefix).or_insert_with(|| WindowState {
|
||||
|
|
@ -47,12 +51,12 @@ impl SubnetTracker {
|
|||
state.sources.insert(ip);
|
||||
}
|
||||
|
||||
/// Забирает и сбрасывает агрегаты текущего окна.
|
||||
/// Takes and resets the aggregates of the current window.
|
||||
#[must_use]
|
||||
pub fn take_snapshot(&self) -> Vec<(IpAddr, PrefixSnapshot)> {
|
||||
let mut out = Vec::new();
|
||||
// Дренируем все ключи: каждое окно начинается с чистой карты,
|
||||
// память не растёт при спуфинге множества префиксов.
|
||||
// Drain every key: the next window starts from an empty map, so memory does not
|
||||
// grow when an attacker spoofs many distinct prefixes.
|
||||
self.windows.retain(|prefix, state| {
|
||||
if state.syn_count == 0 {
|
||||
return false;
|
||||
|
|
@ -60,8 +64,8 @@ impl SubnetTracker {
|
|||
out.push((
|
||||
*prefix,
|
||||
PrefixSnapshot {
|
||||
// Юзерспейс видит только установленные соединения;
|
||||
// pkt_count отражает тот же поток.
|
||||
// Userspace only sees established connections, so `pkt_count` mirrors the same
|
||||
// flow as `syn_count`.
|
||||
pkt_count: state.syn_count,
|
||||
syn_count: state.syn_count,
|
||||
last_seen_ns: state.started.elapsed().as_nanos() as u64,
|
||||
|
|
@ -74,7 +78,7 @@ impl SubnetTracker {
|
|||
}
|
||||
}
|
||||
|
||||
/// Адаптер [`SubnetTracker`] под трейт [`PrefixStatsSource`].
|
||||
/// Adapts [`SubnetTracker`] to the [`PrefixStatsSource`] trait.
|
||||
pub struct TrackerSource {
|
||||
pub tracker: Arc<SubnetTracker>,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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::engine::challenge::DifficultyAdjuster;
|
||||
|
|
@ -20,7 +21,7 @@ mod gateway;
|
|||
#[cfg(feature = "protocol-minecraft")]
|
||||
mod proxy;
|
||||
|
||||
/// Общее состояние edge-движка, разделяемое между accept-loop'ами.
|
||||
/// Shared edge engine state handed to every accept loop by [`Arc`].
|
||||
pub struct Gateway {
|
||||
pub config: Arc<Config>,
|
||||
pub rate_limiter: Arc<RateLimiter>,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
//! Per-connection pipeline of the edge engine: filters, PoW gate, protocol
|
||||
//! handshake and upstream relay.
|
||||
|
||||
mod challenge;
|
||||
|
||||
#[cfg(feature = "protocol-minecraft")]
|
||||
|
|
@ -56,11 +59,11 @@ impl Gateway {
|
|||
}
|
||||
}
|
||||
|
||||
/// Полный конвейер обработки входящего соединения.
|
||||
/// Runs the full pipeline for one inbound connection.
|
||||
///
|
||||
/// # 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)]
|
||||
pub async fn handle(&self, mut client: TcpStream, peer_addr: std::net::SocketAddr) -> GatewayOutcome {
|
||||
let client_addr = if self.config.proxy_protocol.ingress_enabled {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! Proof-of-work gate step of the connection pipeline.
|
||||
|
||||
use super::Gateway;
|
||||
use crate::engine::challenge::enforce as enforce_pow;
|
||||
use crate::metrics;
|
||||
|
|
@ -5,6 +7,14 @@ use std::net::IpAddr;
|
|||
use tokio::net::TcpStream;
|
||||
|
||||
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> {
|
||||
let pow_config = &self.config.pow;
|
||||
if !(pow_config.enabled && pow_config.difficulty > 0) {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,17 @@
|
|||
//! Encoding of upstream PROXY protocol v2 headers.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
|
||||
mod inbound;
|
||||
pub(super) use inbound::read_v2_header;
|
||||
|
||||
/// 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>> {
|
||||
const SIGNATURE: [u8; 12] = *b"\r\n\r\n\0\r\nQUIT\n";
|
||||
if source.is_ipv4() != destination.is_ipv4() {
|
||||
|
|
|
|||
|
|
@ -8,6 +8,13 @@ use tokio::net::TcpStream;
|
|||
const SIGNATURE: [u8; 12] = *b"\r\n\r\n\0\r\nQUIT\n";
|
||||
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(
|
||||
stream: &mut TcpStream,
|
||||
timeout: Duration,
|
||||
|
|
|
|||
|
|
@ -103,7 +103,10 @@ impl Blacklist {
|
|||
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)
|
||||
where
|
||||
I: IntoIterator<Item = (IpAddr, Duration, String)>,
|
||||
|
|
|
|||
|
|
@ -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 connection_limit;
|
||||
|
|
|
|||
|
|
@ -71,8 +71,11 @@ impl RateLimiter {
|
|||
self.buckets.is_empty()
|
||||
}
|
||||
|
||||
/// Эвиктит простаивающие бакеты. Запускается, когда бакетов больше
|
||||
/// MAX_BUCKETS либо по расписанию (раз в SWEEP_INTERVAL).
|
||||
/// Evicts idle buckets.
|
||||
///
|
||||
/// Runs either when the table grows past `MAX_BUCKETS` (cap enforcement)
|
||||
/// or once per `SWEEP_INTERVAL`. Buckets touched within `eviction_idle`
|
||||
/// survive, so active sources keep their token state.
|
||||
pub fn sweep(&self) {
|
||||
let now = Instant::now();
|
||||
let elapsed_secs = now.duration_since(self.epoch).as_secs();
|
||||
|
|
|
|||
|
|
@ -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 cli;
|
||||
pub mod config;
|
||||
|
|
|
|||
|
|
@ -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 nodes;
|
||||
pub mod servers;
|
||||
|
|
|
|||
|
|
@ -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 auth;
|
||||
pub mod sync;
|
||||
|
|
@ -8,10 +10,11 @@ use std::net::IpAddr;
|
|||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Общее состояние management-API.
|
||||
/// Shared state of the management API.
|
||||
pub struct AppState {
|
||||
/// Redis-клиент управления состоянием; присутствует только при собранной
|
||||
/// фиче `store-redis` (manager требует её на старте — см. bin/rampart-manager).
|
||||
/// Redis client for state management; present only when the `store-redis`
|
||||
/// feature is compiled in (the manager requires it at startup, see
|
||||
/// bin/rampart-manager).
|
||||
#[cfg(feature = "store-redis")]
|
||||
pub redis_client: redis::Client,
|
||||
pub jwt_secret: String,
|
||||
|
|
|
|||
|
|
@ -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::{
|
||||
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")
|
||||
});
|
||||
|
||||
/// Отдаёт 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) {
|
||||
let listener = match TcpListener::bind(addr).await {
|
||||
Ok(l) => l,
|
||||
|
|
|
|||
|
|
@ -1,9 +1,12 @@
|
|||
//! HTTP/1.1 protocol handler (feature `protocol-http`).
|
||||
//!
|
||||
//! Первый plugin-реализаций [`ProtocolHandler`]: читает request-head
|
||||
//! постепенно (TCP приходит фрагментами), проверяет его по политике из
|
||||
//! секции `[protocol.http]` и возвращает upstream для туннелирования.
|
||||
//! Прочитанная голова передаётся upstream как начальные байты туннеля.
|
||||
//! Owns the first plugin implementation of [`ProtocolHandler`]: it reads the
|
||||
//! request head incrementally (TCP arrives in fragments), evaluates it against
|
||||
//! the policy from the `[protocol.http]` section and returns the upstream to
|
||||
//! 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;
|
||||
|
||||
|
|
@ -15,7 +18,7 @@ use std::time::Duration;
|
|||
use tokio::io::AsyncReadExt;
|
||||
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 {
|
||||
policy: parser::Policy,
|
||||
timeout: Duration,
|
||||
|
|
@ -23,7 +26,10 @@ pub struct 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]
|
||||
pub fn new(http: &HttpProtocolConfig, upstreams: &[String]) -> Self {
|
||||
Self {
|
||||
|
|
@ -37,10 +43,11 @@ impl HttpProtocolHandler {
|
|||
}
|
||||
}
|
||||
|
||||
/// Накапливает request-head без повторного чтения одного и того же префикса.
|
||||
/// Accumulates the request head without re-reading an already scanned prefix.
|
||||
///
|
||||
/// # 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>> {
|
||||
let limit = self.policy.max_header_bytes;
|
||||
if limit == 0 {
|
||||
|
|
|
|||
|
|
@ -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: на вход — накопленный заголовок, на выходе —
|
||||
//! [`Verdict`]. Это позволяет покрывать логику юнит-тестами без сокетов.
|
||||
//! Owns the parsing policy and verdicts only: the module knows nothing about
|
||||
//! 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)]
|
||||
pub struct Policy {
|
||||
pub max_header_bytes: usize,
|
||||
|
|
@ -11,7 +12,7 @@ pub struct Policy {
|
|||
pub require_user_agent: bool,
|
||||
}
|
||||
|
||||
/// Результат проверки головы запроса.
|
||||
/// Outcome of validating a request head.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
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 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]
|
||||
pub fn scan_head(buf: &[u8]) -> Option<usize> {
|
||||
buf.windows(HEADER_TERMINATOR.len())
|
||||
|
|
@ -29,7 +30,7 @@ pub fn scan_head(buf: &[u8]) -> Option<usize> {
|
|||
.map(|pos| pos + HEADER_TERMINATOR.len())
|
||||
}
|
||||
|
||||
/// Разбирает и валидирует голову запроса согласно политике.
|
||||
/// Parses and validates a request head against the policy.
|
||||
#[must_use]
|
||||
pub fn evaluate(head: &[u8], policy: &Policy) -> Verdict {
|
||||
let Ok(text) = std::str::from_utf8(head) else {
|
||||
|
|
|
|||
|
|
@ -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")]
|
||||
pub mod http;
|
||||
#[cfg(feature = "protocol-minecraft")]
|
||||
|
|
@ -7,8 +13,8 @@ use std::future::Future;
|
|||
use std::pin::Pin;
|
||||
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)]
|
||||
pub struct Upstream {
|
||||
pub addr: String,
|
||||
|
|
@ -45,30 +51,31 @@ impl HandshakeResult {
|
|||
}
|
||||
}
|
||||
|
||||
/// Точка расширения платформы: реализация для конкретного L7-протокола.
|
||||
/// Platform extension point: one implementation per L7 protocol.
|
||||
///
|
||||
/// Контракт минимальный: обработчик проводит handshake с клиентом
|
||||
/// (чтение/запись в поток до момента, когда можно проксировать) и
|
||||
/// возвращает целевой [`Upstream`]. Реализации поставляются фичами
|
||||
/// (`--features protocol-http`, внешние plugin-крейты) — в ядре их нет.
|
||||
/// 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
|
||||
/// possible) and returns the target [`Upstream`]. Implementations ship as
|
||||
/// features (`--features protocol-http`, external plugin crates); the core
|
||||
/// itself contains none.
|
||||
///
|
||||
/// Метод асинхронен через boxed future, чтобы трейт оставался
|
||||
/// dyn-совместимым (`ProtocolRegistry` хранит `Box<dyn ProtocolHandler>`).
|
||||
/// The method is async through a boxed future so the trait stays
|
||||
/// dyn-compatible (`ProtocolRegistry` stores `Box<dyn ProtocolHandler>`).
|
||||
pub trait ProtocolHandler: Send + Sync {
|
||||
/// Имя протокола (для метрик, логов и реестра).
|
||||
/// Protocol name, used in metrics, logs and the registry.
|
||||
fn name(&self) -> &'static str;
|
||||
|
||||
/// Проводит handshake с клиентом и определяет upstream.
|
||||
/// Drives the client handshake and resolves the upstream.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при невалидном клиентском потоке или отказе в доступе.
|
||||
/// Returns an error when the client stream is invalid or access is denied.
|
||||
fn handshake<'a>(
|
||||
&'a self,
|
||||
stream: &'a mut TcpStream,
|
||||
) -> Pin<Box<dyn Future<Output = anyhow::Result<HandshakeResult>> + Send + 'a>>;
|
||||
}
|
||||
|
||||
/// Реестр скомпилированных протокольных обработчиков.
|
||||
/// Registry of the protocol handlers compiled into this binary.
|
||||
#[derive(Default)]
|
||||
pub struct ProtocolRegistry {
|
||||
handlers: Vec<Box<dyn ProtocolHandler>>,
|
||||
|
|
@ -104,11 +111,11 @@ impl ProtocolRegistry {
|
|||
self.handlers.iter().find(|h| h.name() == name).map(|h| h.as_ref())
|
||||
}
|
||||
|
||||
/// Возвращает основной обработчик.
|
||||
/// Returns the primary handler, the first one registered.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку, если ни один протокол не скомпилирован —
|
||||
/// edge-нода обязана fail-fast на старте в этом случае.
|
||||
/// Returns an error when no protocol is compiled in; an edge node must
|
||||
/// fail fast at startup in that case.
|
||||
pub fn primary(&self) -> anyhow::Result<&dyn ProtocolHandler> {
|
||||
let Some(handler) = self.handlers.first() else {
|
||||
anyhow::bail!(
|
||||
|
|
|
|||
|
|
@ -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")]
|
||||
pub mod redis;
|
||||
#[cfg(feature = "store-redis")]
|
||||
|
|
@ -5,22 +10,30 @@ pub use redis::{start_blacklist_sync, start_local_ban_publisher};
|
|||
|
||||
pub mod clickhouse;
|
||||
|
||||
/// Общий контракт внешнего хранилища состояния.
|
||||
/// Common contract for an external state store.
|
||||
#[allow(async_fn_in_trait)]
|
||||
pub trait StateStore: Send + Sync {
|
||||
/// Reads `key`, returning `None` when it is absent.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при недоступности хранилища.
|
||||
/// Returns an error when the store is unreachable.
|
||||
async fn get(&self, key: &str) -> anyhow::Result<Option<String>>;
|
||||
|
||||
/// Writes `value` under `key`, overwriting any previous value.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при недоступности хранилища.
|
||||
/// Returns an error when the store is unreachable.
|
||||
async fn set(&self, key: &str, value: &str) -> anyhow::Result<()>;
|
||||
|
||||
/// Deletes `key`; deleting a missing key is not an error.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при недоступности хранилища.
|
||||
/// Returns an error when the store is unreachable.
|
||||
async fn del(&self, key: &str) -> anyhow::Result<()>;
|
||||
|
||||
/// Publishes `message` to `channel` for subscribers to consume.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает ошибку при недоступности хранилища.
|
||||
/// Returns an error when the store is unreachable.
|
||||
async fn publish(&self, channel: &str, message: &str) -> anyhow::Result<()>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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::filter::blacklist::Blacklist;
|
||||
|
|
@ -15,10 +15,10 @@ use std::time::Duration;
|
|||
const BAN_REASON_LOW_REPUTATION: &str = "low_reputation";
|
||||
const BAN_REASON_ATTACK: &str = "attack_detector";
|
||||
|
||||
/// Точка входа Traffic Intelligence для сетевого пути.
|
||||
/// Entry point of Traffic Intelligence on the network path.
|
||||
///
|
||||
/// События: новое соединение (`on_accept`), завершение обработки соединения
|
||||
/// (`on_connection_end`), эскалация детектора атак (`ban_offenders`).
|
||||
/// Events: a new connection (`on_accept`), a finished connection
|
||||
/// (`on_connection_end`) and attack-detector escalation (`ban_offenders`).
|
||||
pub struct TrafficHook {
|
||||
reputation: Arc<IpReputation>,
|
||||
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) {
|
||||
self.conn_window.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Соединение обработано. Если источник попал под rate-limit (репутация
|
||||
/// упала до порога) — авто-бан с TTL из конфига.
|
||||
/// A connection finished processing.
|
||||
///
|
||||
/// 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) {
|
||||
if !self.autoban.enabled || self.blacklist.is_blocked(ip) {
|
||||
return;
|
||||
|
|
@ -57,8 +62,10 @@ impl TrafficHook {
|
|||
self.autoban_if_toxic(ip, BAN_REASON_LOW_REPUTATION);
|
||||
}
|
||||
|
||||
/// Эскалация детектора атак: бан всех источников ниже порога репутации.
|
||||
/// Вызывается один раз на переход в `UnderAttack`, не на каждый тик.
|
||||
/// Attack-detector escalation: bans every source below the reputation
|
||||
/// 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 {
|
||||
if !self.autoban.enabled {
|
||||
return 0;
|
||||
|
|
@ -75,7 +82,7 @@ impl TrafficHook {
|
|||
banned
|
||||
}
|
||||
|
||||
/// Забирает накопленное окно новых соединений за секунду (cps).
|
||||
/// Takes the accumulated one-second window of new connections (cps).
|
||||
pub fn take_cps(&self) -> u64 {
|
||||
self.conn_window.swap(0, Ordering::Relaxed)
|
||||
}
|
||||
|
|
@ -206,7 +213,7 @@ mod tests {
|
|||
enabled: true,
|
||||
reputation_threshold: -50,
|
||||
},
|
||||
// Короткий TTL как мок времени: бан жив, потом истекает.
|
||||
// Zero TTL as a time mock: the ban must be dead on arrival.
|
||||
0,
|
||||
);
|
||||
let target = ip([10, 3, 0, 1]);
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
self.pps_profiler.record(pps);
|
||||
self.cps_profiler.record(cps);
|
||||
|
|
|
|||
|
|
@ -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 ewma;
|
||||
pub mod reputation;
|
||||
|
|
|
|||
|
|
@ -33,7 +33,10 @@ impl IpReputation {
|
|||
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> {
|
||||
self.scores
|
||||
.iter()
|
||||
|
|
|
|||
|
|
@ -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 intel;
|
||||
pub mod prefix;
|
||||
pub mod profile;
|
||||
|
||||
// Совместимость путей после группировки: домены `intel/` и `profile/`
|
||||
// остаются доступны по прежним путям `traffic::{detector, ewma, ...}`.
|
||||
// Re-exported under the old paths (`traffic::{detector, ewma, ...}`) so the
|
||||
// grouping into `intel/` and `profile/` stays source-compatible.
|
||||
pub use intel::{detector, ewma, reputation};
|
||||
pub use profile::{alert, profiler};
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
/// `family` для IPv4-префиксов (/24).
|
||||
/// `family` tag for IPv4 prefixes (/24).
|
||||
pub const PREFIX_FAMILY_V4: u8 = 4;
|
||||
/// `family` для IPv6-префиксов (/64).
|
||||
/// `family` tag for IPv6 prefixes (/64).
|
||||
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)]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct PrefixKey {
|
||||
|
|
@ -15,7 +15,8 @@ pub struct 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]
|
||||
pub fn new(ip: IpAddr) -> Self {
|
||||
let mut key = Self::default();
|
||||
|
|
@ -32,7 +33,7 @@ impl PrefixKey {
|
|||
key
|
||||
}
|
||||
|
||||
/// Префикс как IP-адрес (маскированный).
|
||||
/// The prefix as a masked IP address; `None` for an unknown `family` tag.
|
||||
#[must_use]
|
||||
pub fn to_prefix(self) -> Option<IpAddr> {
|
||||
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]
|
||||
pub fn prefix_of(ip: IpAddr) -> IpAddr {
|
||||
match ip {
|
||||
IpAddr::V4(v4) => IpAddr::V4(masked_v4(v4)),
|
||||
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)),
|
||||
None => IpAddr::V6(Ipv6Addr::from(masked_v6_segments(v6))),
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
//! Subnet-level (prefix) детектор распределённых атак.
|
||||
//! Subnet-level (prefix) distributed attack detector.
|
||||
//!
|
||||
//! Источник данных — трейт [`PrefixStatsSource`]: карта XDP `prefix_stats`
|
||||
//! (feature `xdp`) либо юзерспейс-агрегатор [`crate::engine::subnet_tracker`].
|
||||
//! Контракт с XDP-агентом: [`PrefixKey`] / [`PrefixStatsVal`] должны совпадать
|
||||
//! побайтово со структурами ядра.
|
||||
//! Data arrives through the [`PrefixStatsSource`] trait: either the XDP
|
||||
//! `prefix_stats` map (feature `xdp`) or the user-space aggregator in
|
||||
//! [`crate::engine::subnet_tracker`]. [`PrefixKey`] and [`PrefixStatsVal`] must
|
||||
//! match the kernel structs byte for byte, hence the `repr(C)` layout.
|
||||
|
||||
mod key;
|
||||
mod stats;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ use anyhow::Result;
|
|||
use std::future::Future;
|
||||
use std::net::IpAddr;
|
||||
|
||||
/// Значение карты `prefix_stats`.
|
||||
/// Value of the `prefix_stats` map.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct PrefixStatsVal {
|
||||
|
|
@ -12,7 +12,7 @@ pub struct PrefixStatsVal {
|
|||
}
|
||||
|
||||
impl PrefixStatsVal {
|
||||
/// Разбирает сырые 24 байта значения карты.
|
||||
/// Parses the raw 24-byte map value.
|
||||
#[must_use]
|
||||
pub fn from_bytes(bytes: [u8; 24]) -> Self {
|
||||
let read_u64 =
|
||||
|
|
@ -24,7 +24,7 @@ impl PrefixStatsVal {
|
|||
}
|
||||
}
|
||||
|
||||
/// Сериализует значение в сырые 24 байта карты.
|
||||
/// Serialises the value into the raw 24-byte map layout.
|
||||
#[must_use]
|
||||
pub fn to_bytes(self) -> [u8; 24] {
|
||||
let mut out = [0u8; 24];
|
||||
|
|
@ -35,10 +35,10 @@ impl PrefixStatsVal {
|
|||
}
|
||||
}
|
||||
|
||||
/// Агрегат по одному префиксу за окно детекции.
|
||||
/// Aggregated counters for one prefix over a detection window.
|
||||
///
|
||||
/// `unique_sources == 0` означает, что источник не считает уникальные адреса
|
||||
/// (XDP-путь); spoof-gate в этом случае Block не подтверждает.
|
||||
/// `unique_sources == 0` means the source does not count distinct addresses
|
||||
/// (the XDP path), and the spoof gate then never confirms `Block`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct PrefixSnapshot {
|
||||
pub syn_count: u64,
|
||||
|
|
@ -47,16 +47,17 @@ pub struct PrefixSnapshot {
|
|||
pub unique_sources: u64,
|
||||
}
|
||||
|
||||
/// Источник агрегатов по префиксам. Позволяет тестам работать без ядра.
|
||||
/// Source of per-prefix aggregates; keeps tests independent of the kernel.
|
||||
pub trait PrefixStatsSource {
|
||||
/// Снимок агрегатов за текущее окно.
|
||||
/// Snapshot of the aggregates for the current window.
|
||||
///
|
||||
/// # 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;
|
||||
}
|
||||
|
||||
/// Эскалация вердиктов subnet-level детектора.
|
||||
/// Verdict escalation ladder of the subnet-level detector.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SubnetVerdict {
|
||||
Monitor,
|
||||
|
|
@ -65,7 +66,7 @@ pub enum SubnetVerdict {
|
|||
Block,
|
||||
}
|
||||
|
||||
/// Вердикт по одному префиксу.
|
||||
/// Verdict for a single prefix.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PrefixVerdict {
|
||||
pub prefix: IpAddr,
|
||||
|
|
@ -73,12 +74,13 @@ pub struct PrefixVerdict {
|
|||
pub snapshot: PrefixSnapshot,
|
||||
}
|
||||
|
||||
/// Детектор распределённых атак по префиксам.
|
||||
/// Detector for distributed attacks at prefix granularity.
|
||||
///
|
||||
/// Лестница эскалации по `syn_count` за окно: `< threshold` → Monitor,
|
||||
/// `< 2×threshold` → StrictLimit, иначе Challenge; Block только при
|
||||
/// `≥ 4×threshold` И прохождении spoof-gate (≥ `min_unique_sources`
|
||||
/// уникальных IP — защита от ложного бана CGNAT/спуфинга).
|
||||
/// Escalation ladder over the `syn_count` of one window: below `threshold` is
|
||||
/// `Monitor`, below `2 x threshold` is `StrictLimit`, anything higher is
|
||||
/// `Challenge`. `Block` requires at least `4 x threshold` *and* a passed spoof
|
||||
/// gate (at least `min_unique_sources` distinct IPs), which guards against
|
||||
/// false bans of CGNAT ranges and spoofed sources.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SubnetDetector {
|
||||
syn_threshold: u64,
|
||||
|
|
@ -99,7 +101,7 @@ impl SubnetDetector {
|
|||
Self::new(config.syn_threshold, config.min_unique_sources)
|
||||
}
|
||||
|
||||
/// Оценивает снимок и возвращает вердикты по активным префиксам.
|
||||
/// Evaluates a snapshot and returns verdicts for all active prefixes.
|
||||
#[must_use]
|
||||
pub fn evaluate(&self, snapshots: &[(IpAddr, PrefixSnapshot)]) -> Vec<PrefixVerdict> {
|
||||
snapshots
|
||||
|
|
@ -131,14 +133,15 @@ impl SubnetDetector {
|
|||
|
||||
#[must_use]
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// Реализация [`PrefixStatsSource`] поверх XDP-фильтра (feature `xdp`).
|
||||
/// Читает карту `prefix_stats`; уникальные источники ядро не считает,
|
||||
/// поэтому spoof-gate на этом пути Block не подтверждает.
|
||||
/// [`PrefixStatsSource`] backed by the XDP filter (feature `xdp`).
|
||||
///
|
||||
/// 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")]
|
||||
pub struct XdpPrefixStats {
|
||||
filter: std::sync::Arc<std::sync::Mutex<crate::xdp::XdpFilter>>,
|
||||
|
|
@ -151,10 +154,11 @@ impl XdpPrefixStats {
|
|||
Self { filter }
|
||||
}
|
||||
|
||||
/// Блокирует мьютекс фильтра (для kernel-enforcement вердиктов).
|
||||
/// Locks the filter mutex (needed for kernel enforcement of verdicts).
|
||||
///
|
||||
/// # 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> {
|
||||
self.filter.lock().expect("xdp lock poisoned")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,9 +56,11 @@ impl fmt::Display for Alert {
|
|||
}
|
||||
}
|
||||
|
||||
/// Дедуплицирующий диспетчер алертов: алерт выдаётся только на переходе
|
||||
/// состояния детектора (вход в `UnderAttack` и выход из него), не на каждом
|
||||
/// тике. Логика — poll-and-persist (LNVPS issue #331).
|
||||
/// Deduplicating alert dispatcher.
|
||||
///
|
||||
/// 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)]
|
||||
pub struct AlertDispatcher {
|
||||
previous: Mutex<Option<AttackStatus>>,
|
||||
|
|
@ -69,9 +71,11 @@ impl AlertDispatcher {
|
|||
Self::default()
|
||||
}
|
||||
|
||||
/// Возвращает `Some(Alert)` только при переходе через границу атаки:
|
||||
/// вход в `UnderAttack` («attack started») или выход из него
|
||||
/// («attack ended»). Первое наблюдение алерта не порождает.
|
||||
/// Returns `Some(Alert)` only when the attack boundary is crossed: entering
|
||||
/// `UnderAttack` ("attack started") or leaving it ("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> {
|
||||
let mut previous = self.previous.lock().expect("alert dispatcher lock poisoned");
|
||||
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) {
|
||||
let payload = serde_json::json!({
|
||||
"level": alert.level.to_string(),
|
||||
|
|
|
|||
|
|
@ -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 profiler;
|
||||
|
|
|
|||
|
|
@ -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::time::Duration;
|
||||
|
|
@ -10,14 +14,14 @@ use crate::tui::prometheus::parse;
|
|||
use crate::tui::state::AppState;
|
||||
use crate::tui::ui;
|
||||
|
||||
/// Управляемые пользователем команды (клавиши).
|
||||
/// Commands the user can trigger from the keyboard.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Command {
|
||||
Quit,
|
||||
Refresh,
|
||||
}
|
||||
|
||||
/// Маппинг клавиш: `q`/`Esc` — выход, `r` — обновить немедленно.
|
||||
/// Key mapping: `q`/`Esc` quit, `r` refreshes immediately.
|
||||
#[must_use]
|
||||
pub fn handle_key(code: crossterm::event::KeyCode) -> Option<Command> {
|
||||
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> {
|
||||
match result {
|
||||
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>) {
|
||||
loop {
|
||||
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
|
||||
/// Возвращает ошибку терминала (draw/poll) — вызывающий восстанавливает TTY.
|
||||
/// Returns the terminal error from draw/poll; the caller is responsible for
|
||||
/// restoring the TTY.
|
||||
pub async fn run_ui(
|
||||
terminal: &mut ratatui::Terminal<impl ratatui::backend::Backend<Error = std::io::Error>>,
|
||||
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>> {
|
||||
if !crossterm::event::poll(timeout)? {
|
||||
return Ok(None);
|
||||
}
|
||||
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 {
|
||||
return Ok(handle_key(key.code));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 futures::future::BoxFuture;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Ошибка загрузки метрик.
|
||||
/// Metrics fetch failure.
|
||||
#[derive(Debug, Error, Clone)]
|
||||
pub enum FetchError {
|
||||
/// Сетевая ошибка / DNS / таймаут.
|
||||
/// Network error, DNS failure or timeout.
|
||||
#[error("network error: {0}")]
|
||||
Network(String),
|
||||
/// Endpoint ответил не-200 статусом.
|
||||
/// The endpoint answered with a non-200 status.
|
||||
#[error("http status {0}")]
|
||||
Status(u16),
|
||||
}
|
||||
|
||||
/// Абстракция источника exposition-текста Prometheus.
|
||||
/// Abstraction over a source of Prometheus exposition text.
|
||||
pub trait Fetcher: Send + Sync {
|
||||
/// Загружает текущий срез метрик.
|
||||
/// Fetches the current metrics snapshot.
|
||||
///
|
||||
/// # Errors
|
||||
/// Возвращает [`FetchError`] при сетевом сбое или плохом HTTP-статусе.
|
||||
/// Returns [`FetchError`] on a network failure or a bad HTTP status.
|
||||
fn fetch(&self) -> BoxFuture<'_, Result<String, FetchError>>;
|
||||
}
|
||||
|
||||
/// Реализация [`Fetcher`] поверх reqwest GET.
|
||||
/// [`Fetcher`] implementation on top of a reqwest GET.
|
||||
pub struct HttpFetcher {
|
||||
url: String,
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
||||
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> {
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(5))
|
||||
|
|
|
|||
|
|
@ -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 prometheus;
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
//! Минималистичный парсер текстового формата Prometheus (version=0.0.4).
|
||||
//! Minimal parser for the Prometheus text exposition format (version 0.0.4).
|
||||
//!
|
||||
//! Поддерживает: комментарии (`# HELP`, `# TYPE`, `#`), строки вида
|
||||
//! `metric{label="value",...} value [timestamp]` и `metric value [timestamp]`.
|
||||
//! Значения `NaN`/`+Inf`/`-Inf` парсятся штатно через `f64::from_str`.
|
||||
//! Owns the parsing rules for `/metrics` bodies. Accepts comment lines
|
||||
//! (`# HELP`, `# TYPE`, `#`), `metric{label="value",...} value [timestamp]` and
|
||||
//! `metric value [timestamp]`. `NaN`/`+Inf`/`-Inf` are parsed through
|
||||
//! `f64::from_str`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Один сэмпл из exposition-формата Prometheus.
|
||||
/// One sample from the Prometheus exposition format.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct MetricSample {
|
||||
pub name: String,
|
||||
|
|
@ -14,21 +15,23 @@ pub struct MetricSample {
|
|||
pub value: f64,
|
||||
}
|
||||
|
||||
/// Набор сэмплов одного ответа `/metrics`.
|
||||
/// All samples of a single `/metrics` response.
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct MetricSet {
|
||||
samples: Vec<MetricSample>,
|
||||
}
|
||||
|
||||
impl MetricSet {
|
||||
/// Сумма значений всех серий с данным именем (для counter/gauge vec).
|
||||
/// Отсутствующая метрика даёт `0.0`.
|
||||
/// Sums the values of every series with this name (for counter/gauge vecs).
|
||||
///
|
||||
/// A missing metric yields `0.0`.
|
||||
#[must_use]
|
||||
pub fn sum(&self, name: &str) -> f64 {
|
||||
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]
|
||||
pub fn labeled(&self, name: &str, label: &str, value: &str) -> Option<f64> {
|
||||
self.samples
|
||||
|
|
@ -37,17 +40,17 @@ impl MetricSet {
|
|||
.map(|s| s.value)
|
||||
}
|
||||
|
||||
/// Все сэмплы (для тестов и отладки).
|
||||
/// All samples (for tests and debugging).
|
||||
#[must_use]
|
||||
pub fn samples(&self) -> &[MetricSample] {
|
||||
&self.samples
|
||||
}
|
||||
}
|
||||
|
||||
/// Парсит тело ответа `/metrics`.
|
||||
/// Parses a `/metrics` response body.
|
||||
///
|
||||
/// Строки с ошибкой формата пропускаются (exposition-поток может быть частично
|
||||
/// повреждён — TUI не должен падать на этом).
|
||||
/// Lines with a malformed format are skipped: an exposition stream may be
|
||||
/// partially corrupted and the TUI must not die because of it.
|
||||
#[must_use]
|
||||
pub fn parse(input: &str) -> MetricSet {
|
||||
let mut samples = Vec::new();
|
||||
|
|
@ -64,18 +67,18 @@ fn parse_line(line: &str) -> Option<MetricSample> {
|
|||
if line.is_empty() || line.starts_with('#') {
|
||||
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 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 value = parse_value(value_str)?;
|
||||
Some(MetricSample { name, labels, value })
|
||||
}
|
||||
|
||||
/// Отделяет `metric{...}` от хвоста `value [timestamp]`.
|
||||
/// Splits `metric{...}` from the trailing `value [timestamp]`.
|
||||
fn split_head_and_rest(line: &str) -> (&str, &str) {
|
||||
let Some(open) = line.find('{') else {
|
||||
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> {
|
||||
let mut in_quotes = false;
|
||||
let mut escaped = false;
|
||||
|
|
@ -138,7 +141,7 @@ fn parse_labels(inner: &str) -> BTreeMap<String, String> {
|
|||
labels
|
||||
}
|
||||
|
||||
/// Разбивает `a="1", b="2"` по запятым вне кавычек.
|
||||
/// Splits `a="1", b="2"` on commas outside quotes.
|
||||
fn split_label_pairs(inner: &str) -> Vec<&str> {
|
||||
let mut parts = Vec::new();
|
||||
let mut in_quotes = false;
|
||||
|
|
|
|||
|
|
@ -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
|
||||
//! exposition endpoint (`/metrics`).
|
||||
//! Owns the terminal front end used by the `rampart-tui` binary; the data
|
||||
//! 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 metrics;
|
||||
|
|
|
|||
|
|
@ -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::sync::Mutex;
|
||||
|
|
@ -6,17 +10,17 @@ use std::time::Instant;
|
|||
|
||||
use crate::tui::prometheus::MetricSet;
|
||||
|
||||
/// Максимальная длина скользящего окна графика.
|
||||
/// Maximum length of the chart's sliding window.
|
||||
pub const HISTORY_CAPACITY: usize = 120;
|
||||
|
||||
/// Один сэмпл истории (значения — rates, единиц/сек).
|
||||
/// A single history sample; the values are rates in units per second.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct HistoryPoint {
|
||||
pub packets_per_sec: f64,
|
||||
pub drops_per_sec: f64,
|
||||
}
|
||||
|
||||
/// Скользящее окно истории фиксированной ёмкости.
|
||||
/// Fixed-capacity sliding window of history samples.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct History {
|
||||
points: VecDeque<HistoryPoint>,
|
||||
|
|
@ -31,7 +35,7 @@ impl Default for History {
|
|||
}
|
||||
|
||||
impl History {
|
||||
/// Добавляет точку, вытесняя старейшую при переполнении окна.
|
||||
/// Appends a point, evicting the oldest one once the window is full.
|
||||
pub fn push(&mut self, point: HistoryPoint) {
|
||||
if self.points.len() == HISTORY_CAPACITY {
|
||||
self.points.pop_front();
|
||||
|
|
@ -39,14 +43,14 @@ impl History {
|
|||
self.points.push_back(point);
|
||||
}
|
||||
|
||||
/// Точки в хронологическом порядке.
|
||||
/// Points in chronological order.
|
||||
#[must_use]
|
||||
pub fn points(&self) -> &VecDeque<HistoryPoint> {
|
||||
&self.points
|
||||
}
|
||||
}
|
||||
|
||||
/// Состояние приложения, общее между fetch-потоком и UI-циклом.
|
||||
/// Application state shared between the fetch task and the UI loop.
|
||||
#[derive(Debug)]
|
||||
pub struct AppState {
|
||||
url: String,
|
||||
|
|
@ -56,7 +60,7 @@ pub struct AppState {
|
|||
}
|
||||
|
||||
impl AppState {
|
||||
/// Создаёт состояние с URL источника метрик (для статус-панели).
|
||||
/// Creates the state for a metrics source URL (shown in the status panel).
|
||||
#[must_use]
|
||||
pub fn new(url: impl Into<String>) -> Self {
|
||||
Self {
|
||||
|
|
@ -67,14 +71,14 @@ impl AppState {
|
|||
}
|
||||
}
|
||||
|
||||
/// URL источника метрик.
|
||||
/// URL of the metrics source.
|
||||
#[must_use]
|
||||
pub fn url(&self) -> &str {
|
||||
&self.url
|
||||
}
|
||||
}
|
||||
|
||||
/// Последний успешный/неуспешный результат fetch.
|
||||
/// Result of the latest successful or failed fetch.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Snapshot {
|
||||
pub metrics: Option<MetricSet>,
|
||||
|
|
@ -83,7 +87,7 @@ pub struct Snapshot {
|
|||
}
|
||||
|
||||
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) {
|
||||
let mut snapshot = match self.snapshot.lock() {
|
||||
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]
|
||||
pub fn frame_data(&self) -> FrameData {
|
||||
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)]
|
||||
pub struct FrameData {
|
||||
/// URL источника метрик.
|
||||
/// URL of the metrics source.
|
||||
pub url: String,
|
||||
pub snapshot: Snapshot,
|
||||
pub history: History,
|
||||
/// Время работы TUI (сек).
|
||||
/// TUI uptime in seconds.
|
||||
pub uptime_secs: u64,
|
||||
}
|
||||
|
||||
/// Rate счётчика из двух сэмплов: `(current - previous) / dt`.
|
||||
/// Counter rate from two samples: `(current - previous) / dt`.
|
||||
///
|
||||
/// `None` у предыдущего значения (первый сэмпл) даёт 0.0. Сброс счётчика
|
||||
/// (`current < previous`) трактуетcя как рестарт процесса → 0.0.
|
||||
/// A `None` previous value (first sample) yields 0.0. A counter reset
|
||||
/// (`current < previous`) is treated as a process restart and also yields 0.0.
|
||||
#[must_use]
|
||||
pub fn counter_rate(previous: Option<f64>, current: Option<f64>, elapsed_secs: f64) -> f64 {
|
||||
let (Some(previous), Some(current)) = (previous, current) else {
|
||||
|
|
|
|||
|
|
@ -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::layout::{Constraint, Layout, Rect};
|
||||
|
|
@ -9,7 +12,7 @@ use ratatui::widgets::{Axis, Block, Borders, Chart, Dataset, GraphType, Paragrap
|
|||
|
||||
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 {
|
||||
pub const XDP_TOTAL: &str = "rampart_xdp_total";
|
||||
pub const XDP_TCP: &str = "rampart_xdp_tcp";
|
||||
|
|
@ -27,7 +30,7 @@ mod names {
|
|||
pub const ATTACK_STATUS: &str = "rampart_attack_status";
|
||||
}
|
||||
|
||||
/// Рисует весь кадр.
|
||||
/// Draws the whole frame.
|
||||
pub fn render(frame: &mut Frame, data: &FrameData) {
|
||||
let [header, body, help] =
|
||||
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);
|
||||
}
|
||||
|
||||
/// Пары «подпись → имя метрики» для таблицы.
|
||||
/// Counter label to metric name pairs for the table.
|
||||
const COUNTER_ROWS: &[(&str, &str)] = &[
|
||||
("XDP total", names::XDP_TOTAL),
|
||||
("XDP tcp", names::XDP_TCP),
|
||||
|
|
|
|||
|
|
@ -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"))
|
||||
}
|
||||
|
||||
/// Внутренний data-map `.rodata` ищется по суффиксу: libbpf именует его
|
||||
/// `<obj_name>.rodata`, а имя объекта при `open_memory` без явного `.name()`
|
||||
/// вообще `memory` — точное сравнение ломалось на живом ядре (smoke-тест).
|
||||
/// The internal `.rodata` data map is matched by suffix: libbpf names it
|
||||
/// `<obj_name>.rodata`, and with `open_memory` and no explicit `.name()` the object is
|
||||
/// called `memory` — an exact comparison broke on a live kernel (smoke test).
|
||||
pub(super) fn is_rodata_map(name: &str) -> bool {
|
||||
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<()> {
|
||||
let image = globals.build_rodata_image();
|
||||
if !open_obj
|
||||
|
|
@ -42,12 +42,23 @@ pub(super) fn patch_rodata(open_obj: &mut OpenObject, globals: &XdpGlobals) -> R
|
|||
.maps_mut()
|
||||
.find(|m| m.name().to_str().is_some_and(is_rodata_map))
|
||||
.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)
|
||||
.with_context(|| format!("failed to set initial value of '{RODATA_MAP_NAME}'"))
|
||||
}
|
||||
|
||||
/// Честное имя режима attach по `attach_mode` из `bpf_xdp_query_opts`
|
||||
/// (kernel `enum xdp_attached_mode`: NONE=0, DRV=1, OFFLOAD=2, SKB=3).
|
||||
/// Honest name of the attach mode, derived from the `attach_mode` field of
|
||||
/// `bpf_xdp_query_opts` (kernel `enum xdp_attached_mode`: NONE=0, DRV=1, OFFLOAD=2, SKB=3).
|
||||
pub(super) fn xdp_attach_mode_name(mode: u8) -> &'static str {
|
||||
match mode {
|
||||
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>`,
|
||||
/// копия `AutoBanConfig`) захватывается `move`-клонами. Когда `blacklist` — `None`
|
||||
/// (фича не подключена) или политика выключена, события только парсятся и
|
||||
/// логируются структурированно; баны не пишутся. В горячем пути нет `format!` —
|
||||
/// `tracing`-поля и `&'static str` причины.
|
||||
/// The callback must be `'static`, so all shared state (`Arc<Blacklist>`, a copy of
|
||||
/// `AutoBanConfig`) is captured by `move` clones. When `blacklist` is `None` (feature not
|
||||
/// wired) or the policy is disabled, events are only parsed and logged in a structured
|
||||
/// way; no bans are written. The hot path does no `format!` — only `tracing` fields and
|
||||
/// `&'static str` reasons.
|
||||
pub(super) fn build_ringbuf(
|
||||
obj: &Object,
|
||||
blacklist: Option<Arc<Blacklist>>,
|
||||
|
|
@ -71,8 +82,8 @@ pub(super) fn build_ringbuf(
|
|||
) -> Result<RingBuffer<'static>> {
|
||||
let map = obj
|
||||
.maps()
|
||||
.find(|m| m.name() == "events_map")
|
||||
.context("events_map not found")?;
|
||||
.find(|m| m.name() == "events_ringbuf")
|
||||
.context("events_ringbuf not found")?;
|
||||
let mut builder = RingBufferBuilder::new();
|
||||
builder.add(&map, move |data: &[u8]| {
|
||||
let Some(event) = parse_xdp_event(data) else {
|
||||
|
|
@ -93,10 +104,10 @@ pub(super) fn build_ringbuf(
|
|||
};
|
||||
if let Some(ban) = auto_ban_decision(&event, &cfg) {
|
||||
let addr = IpAddr::V4(ban.ip);
|
||||
// `Blacklist::add` возвращает `()` (DashMap::insert игнорируется), а
|
||||
// править blacklist.rs вне нашей зоны нельзя — поэтому «новый ли бан»
|
||||
// определяем через публичный `is_blocked` ДО перезаписи. Это дедуп
|
||||
// лога/метрики по активному бану, а не по факту вставки.
|
||||
// `Blacklist::add` returns `()` (it ignores `DashMap::insert`) and blacklist.rs is
|
||||
// out of our edit scope, so "is this a new ban" is decided through the public
|
||||
// `is_blocked` before the overwrite. This dedups the log line and the metric by
|
||||
// active ban, not by the fact of insertion.
|
||||
let already_banned = blacklist.is_blocked(addr);
|
||||
blacklist.add(addr, Duration::from_secs(ban.duration_secs), ban.reason);
|
||||
if already_banned {
|
||||
|
|
@ -134,8 +145,8 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn rodata_map_matches_libbpf_naming() {
|
||||
// libbpf строит имя `<obj><section>` без замены точки (libbpf.c ~1911),
|
||||
// при open_memory без name объект называется "memory":
|
||||
// libbpf builds the name as `<obj><section>` without rewriting the dot
|
||||
// (libbpf.c ~1911); with open_memory and no name the object is called "memory":
|
||||
assert!(is_rodata_map("rampart.rodata"));
|
||||
assert!(is_rodata_map("memory.rodata"));
|
||||
assert!(is_rodata_map(".rodata"));
|
||||
|
|
|
|||
|
|
@ -1,32 +1,32 @@
|
|||
//! Разбор и политика для событий XDP-ringbuf (`struct xdp_event`).
|
||||
//! Parsing and policy for XDP ringbuf events (`struct xdp_event`).
|
||||
//!
|
||||
//! Чистые (без I/O, без libbpf) функции, чтобы их можно было покрыть
|
||||
//! юнит-тестами без ядра/Redis. Wiring колбэка — в [`super::attach`].
|
||||
//! Pure functions (no I/O, no libbpf) so that they can be covered by unit tests without
|
||||
//! a kernel or Redis. The callback wiring lives in [`super::attach`].
|
||||
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
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,
|
||||
/// 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;
|
||||
|
||||
/// Тип события из `enum event_type` (`common.h:54-59`).
|
||||
/// Event type from `enum event_type` (`common.h:54-59`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum XdpEventKind {
|
||||
/// `EVENT_BAN` — пакет уже был в blacklist_map и сброшен ядром.
|
||||
/// `EVENT_BAN` — the packet was already in `blacklist_map` and was dropped by the kernel.
|
||||
Ban,
|
||||
/// `EVENT_RATE_LIMIT` — превышен порог троттлинга (SYN/UDP).
|
||||
/// `EVENT_RATE_LIMIT` — the throttling threshold was exceeded (SYN/UDP).
|
||||
RateLimit,
|
||||
/// `EVENT_POLICY_DROP` — статичная политика (UDP drop / вредоносные TCP-флаги).
|
||||
/// `EVENT_POLICY_DROP` — a static policy match (UDP drop / malicious TCP flags).
|
||||
PolicyDrop,
|
||||
/// `EVENT_CONN_DROP` — flow сброшен (несоответствие seq или verdict хука).
|
||||
/// `EVENT_CONN_DROP` — the flow was dropped (sequence mismatch or a hook verdict).
|
||||
ConnDrop,
|
||||
}
|
||||
|
||||
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> {
|
||||
match raw {
|
||||
0 => Some(Self::Ban),
|
||||
|
|
@ -41,41 +41,43 @@ impl XdpEventKind {
|
|||
}
|
||||
}
|
||||
|
||||
/// Разобранное событие ringbuf.
|
||||
/// A parsed ringbuf event.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct XdpEvent {
|
||||
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,
|
||||
/// Поле `__u32 metadata`: для `RateLimit` — порог срабатывания троттлинга,
|
||||
/// для `ConnDrop` — счётчик `conn->fails`, иначе `0`.
|
||||
/// The `__u32 metadata` field: for `RateLimit` the throttling threshold that fired, for
|
||||
/// `ConnDrop` the `conn->fails` counter, `0` otherwise.
|
||||
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,
|
||||
}
|
||||
|
||||
/// Разбирает 24-байтовый кадр `struct xdp_event`.
|
||||
/// Parses a 24-byte `struct xdp_event` frame.
|
||||
///
|
||||
/// # Byte order (проверено по C-источнику)
|
||||
/// Скалярные поля (`type`, `metadata`, `timestamp`) пишутся ядром в ПОРЯДКЕ ХОСТА
|
||||
/// без конверсии: `push_event` присваивает их как есть — `e->type = type`,
|
||||
/// `e->metadata = meta`, `e->timestamp = bpf_ktime_get_ns()`
|
||||
/// (`common.h:92-95`, `bpf_htonl`/`bpf_ntohl` к ним НЕ применяется). Userspace
|
||||
/// читает те же байты на той же машине → `from_ne_bytes` корректно.
|
||||
/// # Byte order (verified against the C source)
|
||||
/// The scalar fields (`type`, `metadata`, `timestamp`) are written by the kernel in host
|
||||
/// order without conversion: `push_event` assigns them as they are — `e->type = type`,
|
||||
/// `e->metadata = meta`, `e->timestamp = bpf_ktime_get_ns()` (`common.h:92-95`; no
|
||||
/// `bpf_htonl`/`bpf_ntohl` is applied). Userspace reads the same bytes on the same
|
||||
/// machine, so `from_ne_bytes` is correct.
|
||||
///
|
||||
/// А вот `src_ip` — сетевой порядок (big-endian octets): он приходит прямо из
|
||||
/// заголовка пакета `src_ip = ip->saddr` (`universal_filter.c:149`) и пишется в
|
||||
/// событие без `bpf_htonl` (`common.h:93`). Значит байты `data[4..8]` — это октеты
|
||||
/// адреса в точковом порядке, и читать их надо как `Ipv4Addr::new(octets...)`, а НЕ
|
||||
/// как `from_ne_bytes(u32)` (прежний баг: на LE-хосте давал перевернутый IP).
|
||||
/// `src_ip` is different: it is in network order (big-endian octets) because it comes
|
||||
/// straight from the packet header as `src_ip = ip->saddr` (`universal_filter.c:149`)
|
||||
/// and is copied into the event without `bpf_htonl` (`common.h:93`). Bytes `data[4..8]`
|
||||
/// are therefore the address octets in dotted order and must be read as
|
||||
/// `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> {
|
||||
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 src_ip = Ipv4Addr::new(raw[4], raw[5], raw[6], raw[7]);
|
||||
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()?);
|
||||
Some(XdpEvent {
|
||||
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)]
|
||||
pub struct AutoBanConfig {
|
||||
pub enabled: bool,
|
||||
|
|
@ -104,7 +106,7 @@ impl Default for AutoBanConfig {
|
|||
}
|
||||
|
||||
impl AutoBanConfig {
|
||||
/// Берёт значения из `[xdp]`-секции конфига (единственный источник истины).
|
||||
/// Takes the values from the `[xdp]` config section (the single source of truth).
|
||||
pub fn from_xdp(cfg: &XdpConfig) -> Self {
|
||||
Self {
|
||||
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)]
|
||||
pub struct BanAction {
|
||||
pub ip: Ipv4Addr,
|
||||
pub duration_secs: u64,
|
||||
/// Статичная причина (без аллокаций в горячем пути).
|
||||
/// Static reason (no allocation on the hot path).
|
||||
pub reason: &'static str,
|
||||
}
|
||||
|
||||
/// Чистое решение: банить ли источник события и на сколько.
|
||||
/// Pure decision: whether the event source should be banned and for how long.
|
||||
///
|
||||
/// Возвращает `None`, если фича выключена или тип события не банится.
|
||||
/// Разбор по типам обоснован C-кодом:
|
||||
/// Returns `None` when the feature is disabled or the event type is not bannable. The
|
||||
/// per-type split follows the C code:
|
||||
///
|
||||
/// * [`XdpEventKind::Ban`] — НЕ баним. Событие эмитится уже ПОСЛЕ того, как
|
||||
/// ядро нашло IP в `blacklist_map` и дропнуло пакет (`universal_filter.c:220-225`);
|
||||
/// повторный userspace-бан бессмысленен и мог бы скрыть штатный expiry.
|
||||
/// * [`XdpEventKind::PolicyDrop`] — НЕ баним по умолчанию. Это статичная
|
||||
/// политика на каждый пакет: UDP-drop-политика (`:234`) и вредоносные TCP-флаги
|
||||
/// (`:259`). Бан по одному malformed-пакету перебанит легитимных, но глючных
|
||||
/// клиентов — порог аккумулирования здесь отсутствует по смыслу.
|
||||
/// * [`XdpEventKind::RateLimit`] — банیم. Порог троттлинга уже фактически превышен;
|
||||
/// при этом UDP-путь (`:237-243`) только дропает и НЕ заносит в blacklist (в
|
||||
/// отличие от SYN-пути `:295`) — userspace-бан добавляет реальную защиту.
|
||||
/// * [`XdpEventKind::ConnDrop`] — баним, только если `metadata` (=`conn->fails`)
|
||||
/// достиг порога (`:364-368`). Дроп по протокольному хуку приходит с `fails = 0`
|
||||
/// (`:418`) и ниже порога, т.е. не банится.
|
||||
/// * [`XdpEventKind::Ban`] — not banned. The event is emitted only after the kernel has
|
||||
/// already found the IP in `blacklist_map` and dropped the packet
|
||||
/// (`universal_filter.c:220-225`), so a second userspace ban is pointless and could
|
||||
/// mask the regular expiry.
|
||||
/// * [`XdpEventKind::PolicyDrop`] — not banned by default. This is a static per-packet
|
||||
/// 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
|
||||
/// accumulation threshold here by design.
|
||||
/// * [`XdpEventKind::RateLimit`] — banned. The throttling threshold has already been
|
||||
/// exceeded; the UDP path (`:237-243`) only drops and does not insert into the
|
||||
/// blacklist (unlike the SYN path at `:295`), so the userspace ban adds real
|
||||
/// protection.
|
||||
/// * [`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]
|
||||
pub fn auto_ban_decision(event: &XdpEvent, config: &AutoBanConfig) -> Option<BanAction> {
|
||||
if !config.enabled {
|
||||
|
|
@ -162,5 +166,5 @@ pub fn auto_ban_decision(event: &XdpEvent, config: &AutoBanConfig) -> Option<Ban
|
|||
}
|
||||
}
|
||||
|
||||
// Покрытие парсера и политики — в `tests/xdp_events.rs` (держим модуль под
|
||||
// лимитом 250 строк; `src/xdp/filter/` уже на пределе в 4 файла на каталог).
|
||||
// Parser and policy coverage lives in `tests/xdp_events.rs` (this module is kept under
|
||||
// the 250-line limit; `src/xdp/filter/` already has the maximum of 4 files per directory).
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
self.globals = globals;
|
||||
}
|
||||
|
||||
/// Подключает OPT-IN авто-бан по ringbuf-событиям к userspace-`Blacklist`.
|
||||
/// Wires the opt-in auto-ban from ringbuf events into the userspace `Blacklist`.
|
||||
///
|
||||
/// До вызова `load()`. Политика читается из `[xdp]`-секции; если
|
||||
/// `auto_ban_enabled = false` (по умолчанию), колбэк лишь логирует события и
|
||||
/// не трогает blacklist.
|
||||
/// Must be called before `load()`. The policy is read from the `[xdp]` section; when
|
||||
/// `auto_ban_enabled = false` (the default) the callback only logs events and never
|
||||
/// touches the blacklist.
|
||||
pub fn set_autoban(&mut self, blacklist: Arc<Blacklist>, config: &XdpConfig) {
|
||||
self.blacklist = Some(blacklist);
|
||||
self.autoban = AutoBanConfig::from_xdp(config);
|
||||
}
|
||||
|
||||
pub fn load(&mut self) -> Result<()> {
|
||||
// Диагностика ДО загрузки: fail-fast на неподдерживаемом ядре/драйвере.
|
||||
// Diagnostics before loading: fail fast on an unsupported kernel or driver.
|
||||
super::probe::preflight(&self.interface)?;
|
||||
|
||||
let bpf_obj = include_bytes!(concat!(env!("OUT_DIR"), "/universal_filter.o"));
|
||||
// Имя объекта задаётся ЯВНО: при open_memory libbpf не знает имени файла,
|
||||
// а по нему именуются внутренние maps ("rampart_.rodata" в patch_rodata).
|
||||
// The object name is set explicitly: with `open_memory` libbpf does not know the
|
||||
// file name, yet the internal maps are named after it (`rampart_.rodata`, see
|
||||
// `patch_rodata`).
|
||||
let mut open_obj = ObjectBuilder::default()
|
||||
.name("rampart")
|
||||
.context("failed to set BPF object name")?
|
||||
|
|
@ -87,9 +88,9 @@ impl XdpFilter {
|
|||
.find(|p| p.name() == "rampart_universal_filter")
|
||||
.context("XDP program 'rampart_universal_filter' not found")?;
|
||||
let xdp = Xdp::new(prog.as_fd());
|
||||
// Лестница режимов: пробуем native (drv); если драйвер не тянет —
|
||||
// честный fallback в generic (skb) с предупреждением (вывод №1 из
|
||||
// конкурентного анализа: печатать режим как есть, без вранья).
|
||||
// Mode ladder: try native (drv) first; if the driver cannot handle it, fall back to
|
||||
// generic (skb) with a warning (finding #1 of the competitive analysis: report the
|
||||
// mode as it is, no window dressing).
|
||||
let ifindex = ifindex as i32;
|
||||
if let Err(e) = xdp.attach(ifindex, XdpFlags::NONE) {
|
||||
tracing::warn!(
|
||||
|
|
@ -167,10 +168,10 @@ impl XdpFilter {
|
|||
.with_context(|| format!("map '{}' not found", name))
|
||||
}
|
||||
|
||||
/// Читает карту `prefix_stats` (агрегаты по префиксам /24 и /64).
|
||||
/// Reads the `prefix_stats` map (aggregates per /24 and /64 prefix).
|
||||
///
|
||||
/// # 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)>> {
|
||||
let map = self.find_map("prefix_stats")?;
|
||||
let mut out = Vec::new();
|
||||
|
|
|
|||
|
|
@ -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`, которая при загрузке превращается в карту
|
||||
//! с именем `rampart_.rodata`. Образ патчится до `load()` через
|
||||
//! `OpenMapMut::set_initial_value()` (см. [`crate::xdp::filter`]).
|
||||
//! The globals live in the `.rodata` section, which libbpf turns into a map named
|
||||
//! `rampart_.rodata` on load. The image is patched before `load()` via
|
||||
//! `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_end` | `G_END_PORT` | u16 |
|
||||
//! | `udp_policy` | `G_UDP_POLICY` | u8 ("pass"=0, "drop"=1, "rate-limit"=2) |
|
||||
//! | `udp_rate_hit_count` | `G_UDP_HIT_COUNT` | u32 |
|
||||
//! | `udp_rate_window_ms` | `G_UDP_WINDOW_NS` | u64 (мс → нс) |
|
||||
//! | `throttle_enabled` | `G_FEATURE_SYN_THROTTLE` | u8 (bool → 0/1) |
|
||||
//! | `events_enabled` | `G_FEATURE_EVENTS` | u8 (bool → 0/1) |
|
||||
//! | `syn_challenge_enabled` | `G_SYN_CHALLENGE_ENABLED` | u8 (bool → 0/1) |
|
||||
//! | `udp_rate_window_ms` | `G_UDP_WINDOW_NS` | u64 (ms -> ns) |
|
||||
//! | `throttle_enabled` | `G_FEATURE_SYN_THROTTLE` | u8 (bool -> 0/1) |
|
||||
//! | `events_enabled` | `G_FEATURE_EVENTS` | 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_timeout_ms` | `G_CHALLENGE_TIMEOUT_MS` | u32 |
|
||||
//!
|
||||
//! Остальные глобалы (`G_SYN_*`, `G_CONNTRACK_IDLE_NS`, `G_PLAYER_IDLE_NS`,
|
||||
//! `G_BAN_DURATION_NS`, `G_MAX_OUT_OF_ORDER`, `G_CHALLENGE_VERIFIED_TTL_NS`)
|
||||
//! конфигом пока не управляются и патчатся значениями по умолчанию из config.h.
|
||||
//! 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`) are not
|
||||
//! configurable yet; they are patched with the defaults from config.h.
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use std::mem::offset_of;
|
||||
|
||||
use crate::config::XdpConfig;
|
||||
|
||||
/// Имя карты с образом `.rodata` загруженного BPF-объекта.
|
||||
/// Имя внутренней `.rodata`-карты при `ObjectBuilder::name("rampart")`:
|
||||
/// libbpf конструирует `<obj_name><section>` без замены точки (sanitizer
|
||||
/// пропускаёт `.`; libbpf.c, map name logic) → `rampart.rodata`.
|
||||
/// Поиск в `patch_rodata` всё равно по суффиксу — имя здесь для диагностики.
|
||||
/// Name of the map holding the loaded BPF object's `.rodata` image.
|
||||
///
|
||||
/// This is the name of libbpf's internal `.rodata` map when the object is built with
|
||||
/// `ObjectBuilder::name("rampart")`: libbpf concatenates `<obj_name><section>` without
|
||||
/// 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";
|
||||
|
||||
/// Размер образа `.rodata` в байтах (см. `build_rodata_image`).
|
||||
pub const RODATA_SIZE: usize = 96;
|
||||
/// Size of the `.rodata` image in bytes: exactly `sizeof(struct rampart_config)` from
|
||||
/// `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;
|
||||
/// Значение `G_UDP_POLICY`: дропать весь UDP.
|
||||
/// `G_UDP_POLICY` value: drop all UDP.
|
||||
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;
|
||||
|
||||
/// Дефолт-плейсхолдер `G_CHALLENGE_SECRET` из config.h.
|
||||
/// Default placeholder for `G_CHALLENGE_SECRET` from config.h.
|
||||
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)]
|
||||
pub struct XdpGlobals {
|
||||
pub start_port: u16,
|
||||
|
|
@ -96,53 +101,55 @@ impl Default for XdpGlobals {
|
|||
}
|
||||
|
||||
impl XdpGlobals {
|
||||
/// Собирает байтовый образ `.rodata` в порядке объявления глобалов
|
||||
/// в `xdp/core/config.h` с естественным выравниванием каждого поля.
|
||||
/// Builds the byte image of `.rodata`: a mirror of `struct rampart_config` from
|
||||
/// `xdp/core/config.h`.
|
||||
///
|
||||
/// RISK: раскладка предполагает, что линкер кладёт статические переменные
|
||||
/// в секцию `.rodata` в порядке объявления с natural alignment — на
|
||||
/// практике это так (каждая `static volatile const` получает своё
|
||||
/// выравнивание, padding виден в смещениях ниже), но стандарт C этого не
|
||||
/// гарантирует. TODO: верифицировать смещения на сервере через BTF-dump
|
||||
/// карты `rampart_.rodata` (`bpftool btf dump`) и зафиксировать их здесь.
|
||||
/// Offsets come from the `#[repr(C)]` type itself (`offset_of!`) instead of being
|
||||
/// hardcoded, because the layout is defined by the C struct — not by the symbol order
|
||||
/// the linker happens to pick.
|
||||
pub fn build_rodata_image(&self) -> Vec<u8> {
|
||||
let mut img = vec![0u8; RODATA_SIZE];
|
||||
// u16 ×2 без padding: смещения 0..4.
|
||||
img[0..2].copy_from_slice(&self.start_port.to_le_bytes());
|
||||
img[2..4].copy_from_slice(&self.end_port.to_le_bytes());
|
||||
// u32, align 4: 4..8.
|
||||
img[4..8].copy_from_slice(&self.syn_hit_count.to_le_bytes());
|
||||
// u64, align 8: 8..48 (SYN throttle + idle timeouts + ban duration).
|
||||
img[8..16].copy_from_slice(&self.syn_window_ns.to_le_bytes());
|
||||
img[16..24].copy_from_slice(&self.syn_ban_duration_ns.to_le_bytes());
|
||||
img[24..32].copy_from_slice(&self.conntrack_idle_ns.to_le_bytes());
|
||||
img[32..40].copy_from_slice(&self.player_idle_ns.to_le_bytes());
|
||||
img[40..48].copy_from_slice(&self.ban_duration_ns.to_le_bytes());
|
||||
// u8 ×3 подряд: 48, 49, 50 (max_out_of_order, udp_policy, —).
|
||||
img[48] = self.max_out_of_order;
|
||||
img[49] = self.udp_policy;
|
||||
// u32 после u8: padding 50..52, значение 52..56.
|
||||
img[52..56].copy_from_slice(&self.udp_hit_count.to_le_bytes());
|
||||
// u64, align 8: 56..64.
|
||||
img[56..64].copy_from_slice(&self.udp_window_ns.to_le_bytes());
|
||||
// u8 ×3 (feature flags + challenge flag): 64, 65, 66.
|
||||
img[64] = u8::from(self.feature_syn_throttle);
|
||||
img[65] = u8::from(self.feature_events);
|
||||
img[66] = u8::from(self.syn_challenge_enabled);
|
||||
// u64 после u8: padding 67..72, значение 72..80.
|
||||
img[72..80].copy_from_slice(&self.challenge_secret.to_le_bytes());
|
||||
// u32: 80..84.
|
||||
img[80..84].copy_from_slice(&self.challenge_timeout_ms.to_le_bytes());
|
||||
// u64 после u32: padding 84..88, значение 88..96.
|
||||
img[88..96].copy_from_slice(&self.challenge_verified_ttl_ns.to_le_bytes());
|
||||
let put16 = |img: &mut [u8], off: usize, v: u16| img[off..off + 2].copy_from_slice(&v.to_le_bytes());
|
||||
let put32 = |img: &mut [u8], off: usize, v: u32| img[off..off + 4].copy_from_slice(&v.to_le_bytes());
|
||||
let put64 = |img: &mut [u8], off: usize, v: u64| img[off..off + 8].copy_from_slice(&v.to_le_bytes());
|
||||
put16(&mut img, offset_of!(Self, start_port), self.start_port);
|
||||
put16(&mut img, offset_of!(Self, end_port), self.end_port);
|
||||
put32(&mut img, offset_of!(Self, syn_hit_count), self.syn_hit_count);
|
||||
put64(&mut img, offset_of!(Self, syn_window_ns), self.syn_window_ns);
|
||||
put64(
|
||||
&mut img,
|
||||
offset_of!(Self, syn_ban_duration_ns),
|
||||
self.syn_ban_duration_ns,
|
||||
);
|
||||
put64(&mut img, offset_of!(Self, conntrack_idle_ns), self.conntrack_idle_ns);
|
||||
put64(&mut img, offset_of!(Self, player_idle_ns), self.player_idle_ns);
|
||||
put64(&mut img, offset_of!(Self, ban_duration_ns), self.ban_duration_ns);
|
||||
img[offset_of!(Self, max_out_of_order)] = self.max_out_of_order;
|
||||
img[offset_of!(Self, udp_policy)] = self.udp_policy;
|
||||
put32(&mut img, offset_of!(Self, udp_hit_count), self.udp_hit_count);
|
||||
put64(&mut img, offset_of!(Self, udp_window_ns), self.udp_window_ns);
|
||||
img[offset_of!(Self, feature_syn_throttle)] = u8::from(self.feature_syn_throttle);
|
||||
img[offset_of!(Self, feature_events)] = u8::from(self.feature_events);
|
||||
img[offset_of!(Self, syn_challenge_enabled)] = u8::from(self.syn_challenge_enabled);
|
||||
put64(&mut img, offset_of!(Self, challenge_secret), self.challenge_secret);
|
||||
put32(
|
||||
&mut img,
|
||||
offset_of!(Self, challenge_timeout_ms),
|
||||
self.challenge_timeout_ms,
|
||||
);
|
||||
put64(
|
||||
&mut img,
|
||||
offset_of!(Self, challenge_verified_ttl_ns),
|
||||
self.challenge_verified_ttl_ns,
|
||||
);
|
||||
img
|
||||
}
|
||||
|
||||
/// Строит глобалы из секции `[xdp]` конфига.
|
||||
/// Builds the globals from the `[xdp]` section of the config.
|
||||
///
|
||||
/// # Errors
|
||||
/// Неизвестное значение `udp_policy`; некорректный `challenge_secret_hex`
|
||||
/// (не hex или не 8 байт); `protected_port_end < protected_port_start`.
|
||||
/// Unknown `udp_policy` value; malformed `challenge_secret_hex` (not hex, or not
|
||||
/// 8 bytes); `protected_port_end < protected_port_start`.
|
||||
pub fn from_config(cfg: &XdpConfig) -> Result<Self> {
|
||||
let mut g = Self {
|
||||
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> {
|
||||
let cleaned = s.trim().trim_start_matches("0x").replace(['_', ':', '-'], "");
|
||||
let bytes = hex::decode(&cleaned).with_context(|| format!("invalid xdp.challenge_secret_hex '{s}'"))?;
|
||||
|
|
|
|||
|
|
@ -1,20 +1,21 @@
|
|||
//! Prometheus-метрики загрузчика XDP.
|
||||
//! Prometheus metrics of the XDP loader.
|
||||
//!
|
||||
//! Регистрируются в глобальный реестр `prometheus` (тот же, что собирает
|
||||
//! `prometheus::gather()` в `crate::metrics::run_metrics_server`), поэтому
|
||||
//! endpoint `/metrics` подхватывает их без правок вне `src/xdp/`.
|
||||
//! They register into the global `prometheus` registry — the same one that
|
||||
//! `prometheus::gather()` in `crate::metrics::run_metrics_server` scrapes — so the
|
||||
//! `/metrics` endpoint picks them up without changes outside `src/xdp/`.
|
||||
|
||||
use prometheus::{IntCounter, register_int_counter};
|
||||
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(|| {
|
||||
register_int_counter!("rampart_xdp_autobans_total", "Auto-bans issued from XDP ringbuf events")
|
||||
.expect("XDP_AUTOBANS_TOTAL")
|
||||
});
|
||||
|
||||
/// Форсирует регистрацию счётчика (для вызова на старте загрузки XDP).
|
||||
/// Forces registration of the counter (called at the start of the XDP load).
|
||||
pub fn init() {
|
||||
LazyLock::force(&XDP_AUTOBANS_TOTAL);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
pub use probe::{
|
||||
|
|
@ -9,7 +13,7 @@ pub use probe::{
|
|||
#[cfg(feature = "xdp")]
|
||||
mod globals;
|
||||
#[cfg(feature = "xdp")]
|
||||
pub use globals::XdpGlobals;
|
||||
pub use globals::{RODATA_SIZE, XdpGlobals};
|
||||
|
||||
#[cfg(feature = "xdp")]
|
||||
mod metrics;
|
||||
|
|
|
|||
|
|
@ -23,10 +23,10 @@ impl XdpFilter {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Честная ошибка: чтение `prefix_stats` не подключено без feature `xdp`.
|
||||
/// Honest failure: reading `prefix_stats` is not wired up without the `xdp` feature.
|
||||
///
|
||||
/// # Errors
|
||||
/// Всегда — сборка без XDP не имеет доступа к картам ядра.
|
||||
/// Always: a build without XDP has no access to the kernel maps.
|
||||
pub fn read_prefix_stats(&self) -> Result<Vec<(PrefixKey, PrefixStatsVal)>> {
|
||||
anyhow::bail!("prefix_stats reading not wired yet: built without xdp feature")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
//! Диагностика окружения перед XDP-attach: ядро, BTF, драйвер NIC, привилегии.
|
||||
//! Environment diagnostics before XDP attach: kernel, BTF, NIC driver, privileges.
|
||||
//!
|
||||
//! Основной источник боли при XDP — непонятные ошибки attach на неподдерживаемых
|
||||
//! ядрах и драйверах. Модуль собирает [`EnvironmentReport`] ДО загрузки BPF-программы
|
||||
//! и даёт человекочитаемый вердикт с предупреждениями.
|
||||
//! The main source of pain with XDP is opaque attach failures on unsupported kernels and
|
||||
//! drivers. This module collects an [`EnvironmentReport`] before the BPF program is
|
||||
//! loaded and produces a human-readable verdict with warnings.
|
||||
|
||||
mod report;
|
||||
mod types;
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ use super::types::{
|
|||
driver_supports_native_xdp,
|
||||
};
|
||||
|
||||
/// Структурированный отчёт о пригодности окружения для XDP.
|
||||
/// Structured report on how suitable the environment is for XDP.
|
||||
pub struct EnvironmentReport {
|
||||
pub kernel_version: Option<KernelVersion>,
|
||||
pub btf_available: bool,
|
||||
|
|
@ -15,7 +15,7 @@ pub struct EnvironmentReport {
|
|||
}
|
||||
|
||||
impl EnvironmentReport {
|
||||
/// Собирает отчёт через произвольную реализацию [`SystemProbe`].
|
||||
/// Collects the report through any [`SystemProbe`] implementation.
|
||||
#[must_use]
|
||||
pub fn collect(probe: &dyn SystemProbe, interface: &str) -> Self {
|
||||
let kernel_version = probe
|
||||
|
|
@ -61,7 +61,7 @@ impl EnvironmentReport {
|
|||
}
|
||||
}
|
||||
|
||||
/// Ожидаемый режим attach по таблице драйверов.
|
||||
/// Expected attach mode according to the driver table.
|
||||
#[must_use]
|
||||
pub fn attach_mode(&self) -> AttachMode {
|
||||
match self.driver_name.as_deref() {
|
||||
|
|
@ -70,7 +70,7 @@ impl EnvironmentReport {
|
|||
}
|
||||
}
|
||||
|
||||
/// Человекочитаемое объяснение вердикта.
|
||||
/// Human-readable explanation of the verdict.
|
||||
#[must_use]
|
||||
pub fn verdict(&self) -> String {
|
||||
let kernel = self
|
||||
|
|
@ -87,10 +87,10 @@ impl EnvironmentReport {
|
|||
}
|
||||
}
|
||||
|
||||
/// Fail-fast проверка минимальной версии ядра.
|
||||
/// Fail-fast check of the minimum kernel version.
|
||||
///
|
||||
/// # Errors
|
||||
/// Версия ядра не определена или ниже [`MIN_KERNEL`].
|
||||
/// The kernel version is unknown or below [`MIN_KERNEL`].
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
let Some(version) = self.kernel_version else {
|
||||
bail!("не удалось определить версию ядра ({OSRELEASE_PATH}) — XDP attach отклонён");
|
||||
|
|
@ -102,11 +102,11 @@ impl EnvironmentReport {
|
|||
}
|
||||
}
|
||||
|
||||
/// Предстартовая диагностика перед загрузкой XDP-программы:
|
||||
/// структурный отчёт в лог, предупреждения, fail-fast на старом ядре.
|
||||
/// Pre-attach diagnostics before the XDP program is loaded: a structured report in the
|
||||
/// log, warnings, and a fail-fast check for an old kernel.
|
||||
///
|
||||
/// # Errors
|
||||
/// См. [`EnvironmentReport::validate`].
|
||||
/// See [`EnvironmentReport::validate`].
|
||||
#[cfg(feature = "xdp")]
|
||||
pub(crate) fn preflight(interface: &str) -> Result<()> {
|
||||
use super::types::FilesystemProbe;
|
||||
|
|
|
|||
|
|
@ -1,15 +1,15 @@
|
|||
use std::fmt;
|
||||
|
||||
/// Минимально поддерживаемая версия ядра: 5.15 LTS.
|
||||
/// Minimum supported kernel version: 5.15 LTS.
|
||||
pub const MIN_KERNEL: KernelVersion = KernelVersion::new(5, 15, 0);
|
||||
|
||||
pub(super) const OSRELEASE_PATH: &str = "/proc/sys/kernel/osrelease";
|
||||
pub(super) const BTF_PATH: &str = "/sys/kernel/btf/vmlinux";
|
||||
const STATUS_PATH: &str = "/proc/self/status";
|
||||
|
||||
/// Драйверы с известной поддержкой native XDP (по данным xdpgeneric/native
|
||||
/// матриц upstream-ядра). Отсутствие в списке не означает отсутствие поддержки,
|
||||
/// но для таких драйверов предсказываем generic mode.
|
||||
/// Drivers with known native XDP support (from the upstream kernel's native/generic
|
||||
/// matrices). Absence from this list does not mean support is missing, but for such
|
||||
/// drivers generic mode is predicted.
|
||||
const NATIVE_XDP_DRIVERS: &[&str] = &[
|
||||
"virtio_net",
|
||||
"ixgbe",
|
||||
|
|
@ -31,7 +31,7 @@ const NATIVE_XDP_DRIVERS: &[&str] = &[
|
|||
"macvlan",
|
||||
];
|
||||
|
||||
/// Версия ядра Linux, пригодная для сравнения (`major.minor.patch`).
|
||||
/// Linux kernel version, suitable for comparison (`major.minor.patch`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct KernelVersion {
|
||||
pub major: u16,
|
||||
|
|
@ -45,9 +45,9 @@ impl KernelVersion {
|
|||
Self { major, minor, patch }
|
||||
}
|
||||
|
||||
/// Парсит строку формата `uname -r`. Берёт первые три числовых компонента,
|
||||
/// дистрибутивные суффиксы (`6.8.0-45-generic`, `5.15.0-rc2`) отбрасываются.
|
||||
/// Строка без цифр не парсится.
|
||||
/// Parses a `uname -r` style string. Takes the first three numeric components and
|
||||
/// discards distribution suffixes (`6.8.0-45-generic`, `5.15.0-rc2`). A string without
|
||||
/// digits does not parse.
|
||||
#[must_use]
|
||||
pub fn parse(release: &str) -> Option<Self> {
|
||||
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)]
|
||||
pub enum AttachMode {
|
||||
/// Программа исполняется в контексте драйвера NIC — минимальные накладные расходы.
|
||||
/// The program runs in the NIC driver context: lowest overhead.
|
||||
Native,
|
||||
/// Программа вызывается из сетевого стека после ingress — работает везде, дороже по CPU.
|
||||
/// The program is invoked from the network stack after ingress: works everywhere, but
|
||||
/// costs more CPU.
|
||||
Generic,
|
||||
/// Аппаратная разгрузка в NIC — требует явного включения и поддержки железа,
|
||||
/// автоматически не выбирается.
|
||||
/// Hardware offload into the NIC: requires explicit enablement and hardware support,
|
||||
/// never selected automatically.
|
||||
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 {
|
||||
/// Читает файл целиком.
|
||||
/// Reads a file in full.
|
||||
///
|
||||
/// # Errors
|
||||
/// Проксирует ошибку чтения файла.
|
||||
/// Proxies the file read error.
|
||||
fn read_file(&self, path: &str) -> std::io::Result<String>;
|
||||
|
||||
#[must_use]
|
||||
|
|
@ -107,7 +108,7 @@ pub trait SystemProbe {
|
|||
fn effective_uid(&self) -> u32;
|
||||
}
|
||||
|
||||
/// Реальная реализация [`SystemProbe`] поверх `std::fs`.
|
||||
/// Real [`SystemProbe`] implementation on top of `std::fs`.
|
||||
pub struct 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())
|
||||
}
|
||||
|
||||
/// Эвристика: эффективный uid берётся из `/proc/self/status`.
|
||||
/// root почти всегда имеет CAP_BPF/CAP_NET_ADMIN (если явно не урезаны);
|
||||
/// для не-root подтверждение возможно только попыткой attach.
|
||||
/// Нечитаемый статус трактуем как непривилегированный процесс.
|
||||
/// Heuristic: the effective uid is taken from `/proc/self/status`. root almost always
|
||||
/// holds CAP_BPF/CAP_NET_ADMIN (unless explicitly dropped); for non-root the only
|
||||
/// confirmation is an actual attach attempt. An unreadable status is treated as an
|
||||
/// unprivileged process.
|
||||
fn effective_uid(&self) -> u32 {
|
||||
std::fs::read_to_string(STATUS_PATH)
|
||||
.ok()
|
||||
|
|
@ -147,7 +148,7 @@ pub(super) fn driver_from_link(target: &str) -> Option<String> {
|
|||
(!name.is_empty()).then(|| name.to_owned())
|
||||
}
|
||||
|
||||
/// Поддерживает ли драйвер native XDP (по таблице известных драйверов).
|
||||
/// Whether the driver supports native XDP (per the table of known drivers).
|
||||
#[must_use]
|
||||
pub fn driver_supports_native_xdp(driver: &str) -> bool {
|
||||
NATIVE_XDP_DRIVERS.contains(&driver)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! Зондирование XDP-окружения: диагностика, статистика и метрики.
|
||||
//! XDP environment probing: diagnostics, statistics and metrics.
|
||||
|
||||
mod diagnostics;
|
||||
#[cfg(feature = "xdp")]
|
||||
|
|
|
|||
|
|
@ -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)]
|
||||
pub struct XdpStats {
|
||||
pub total: u64,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
//! Config parsing tests: defaults, section parsing and rejected invariants.
|
||||
|
||||
use rampart::config::Config;
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -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::time::Duration;
|
||||
|
||||
|
|
|
|||
|
|
@ -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")]
|
||||
|
||||
use rampart::config::HttpProtocolConfig;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
//! PoW roundtrip tests: solver output must satisfy the verifier, replays and
|
||||
//! garbage must not.
|
||||
|
||||
use rampart::engine::challenge::{Challenge, solve};
|
||||
|
||||
/// Fixed 32-byte token: sha256(hex(token) || "garbage") starts with "ebc1",
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
//! Protocol registry tests: empty registries fail fast, registered handlers
|
||||
//! resolve by name.
|
||||
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! Интеграционные тесты subnet-level детекции: трекер → детектор → вердикты.
|
||||
//! Integration tests for subnet-level detection: tracker, detector and verdicts.
|
||||
|
||||
use rampart::config::Config;
|
||||
use rampart::engine::subnet_tracker::SubnetTracker;
|
||||
|
|
@ -12,7 +12,7 @@ fn v4(octets: [u8; 4]) -> IpAddr {
|
|||
IpAddr::V4(Ipv4Addr::from(octets))
|
||||
}
|
||||
|
||||
/// Фиксированный источник снапшотов — имитирует XDP-карту без ядра.
|
||||
/// Fixed snapshot source that imitates the XDP map without a kernel.
|
||||
struct FixedSource(Vec<(IpAddr, PrefixSnapshot)>);
|
||||
|
||||
impl PrefixStatsSource for FixedSource {
|
||||
|
|
@ -24,8 +24,8 @@ impl PrefixStatsSource for FixedSource {
|
|||
#[tokio::test]
|
||||
async fn tracker_feeds_detector_and_blocks_distributed_attack() {
|
||||
let tracker = SubnetTracker::new();
|
||||
// 40 уникальных источников из одного /24 — распределённая атака
|
||||
// (6 SYN от каждого: 240 >= 4 × threshold(50)).
|
||||
// 40 unique sources from one /24 is a distributed attack: 6 SYNs each,
|
||||
// i.e. 240 >= 4 x threshold(50).
|
||||
for _ in 0..6 {
|
||||
for last in 1..=40u8 {
|
||||
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.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");
|
||||
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]
|
||||
async fn spoof_gate_many_syn_few_sources_no_block() {
|
||||
let tracker = SubnetTracker::new();
|
||||
// 500 SYN всего из 3 адресов — всплеск, но не распределённый.
|
||||
// 500 SYNs from only 3 addresses: a burst, but not distributed.
|
||||
for _ in 0..167 {
|
||||
for ip in [v4([198, 51, 100, 1]), v4([198, 51, 100, 2]), v4([198, 51, 100, 3])] {
|
||||
tracker.record_connection(ip);
|
||||
|
|
@ -180,7 +180,7 @@ fn escalation_ladder_monitor_to_block() {
|
|||
#[test]
|
||||
fn spoof_gate_downgrades_block_to_challenge() {
|
||||
let detector = SubnetDetector::new(100, 16);
|
||||
// Много SYN из одного источника (или неизвестное разнообразие) → нет Block.
|
||||
// Many SYNs from one source (or unknown diversity) must not yield Block.
|
||||
let few = PrefixSnapshot {
|
||||
syn_count: 1000,
|
||||
unique_sources: 3,
|
||||
|
|
|
|||
|
|
@ -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::filter::blacklist::Blacklist;
|
||||
|
|
@ -30,7 +31,7 @@ fn reputation_fall_after_drops_triggers_autoban() {
|
|||
let attacker = ip([198, 51, 100, 7]);
|
||||
|
||||
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);
|
||||
hook.on_connection_end(attacker);
|
||||
}
|
||||
|
|
@ -53,7 +54,7 @@ fn autoban_ttl_expires_ban() {
|
|||
Arc::clone(&reputation),
|
||||
Arc::clone(&blacklist),
|
||||
autoban_cfg(true),
|
||||
// Короткий TTL из «конфига» как мок времени.
|
||||
// Zero TTL taken from the config as a time mock.
|
||||
0,
|
||||
);
|
||||
let attacker = ip([198, 51, 100, 8]);
|
||||
|
|
@ -72,12 +73,12 @@ fn autoban_ttl_expires_ban() {
|
|||
fn detector_flags_synthetic_traffic_spike() {
|
||||
let mut detector = AttackDetector::new();
|
||||
|
||||
// Базовая линия: тихий профиль.
|
||||
// Baseline: a quiet profile.
|
||||
for _ in 0..12 {
|
||||
detector.analyze(500.0, 50.0);
|
||||
}
|
||||
|
||||
// Синтетический всплеск: x200 pps и cps три окна подряд.
|
||||
// Synthetic spike: 200x pps and cps for three consecutive windows.
|
||||
assert_eq!(
|
||||
detector.analyze(100_000.0, 10_000.0),
|
||||
AttackStatus::Suspicious,
|
||||
|
|
|
|||
|
|
@ -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 rampart::tui::fetch::{FetchError, Fetcher, HttpFetcher};
|
||||
use rampart::tui::prometheus::{MetricSample, parse};
|
||||
use rampart::tui::state::{AppState, counter_rate};
|
||||
|
||||
// ---------- парсер ----------
|
||||
|
||||
#[test]
|
||||
fn parses_metric_with_labels_value_and_timestamp() {
|
||||
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);
|
||||
}
|
||||
|
||||
// ---------- rate ----------
|
||||
|
||||
#[test]
|
||||
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);
|
||||
}
|
||||
|
||||
|
|
@ -79,8 +76,6 @@ fn state_accumulates_history_rates() {
|
|||
assert!(frame.snapshot.error.is_none());
|
||||
}
|
||||
|
||||
// ---------- ошибки fetch (мок Fetcher + локальный HTTP-сервер) ----------
|
||||
|
||||
struct FailingFetcher {
|
||||
error: FetchError,
|
||||
}
|
||||
|
|
@ -99,7 +94,7 @@ fn network_error_sets_error_banner_not_panic() {
|
|||
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));
|
||||
assert!(normalized.is_err());
|
||||
let message = match normalized {
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
//! Часы бана: XDP сравнивает expiry с `bpf_ktime_get_ns()` (монотонные ns
|
||||
//! с загрузки), поэтому userspace обязан писать то же самое. Регрессия:
|
||||
//! раньше писался `SystemTime` (epoch ns ≈ 1.7e18), и бан не истекал никогда.
|
||||
//! Ban clock: XDP compares expiry against `bpf_ktime_get_ns()` (monotonic nanoseconds
|
||||
//! since boot), so userspace must write the same clock. Regression: `SystemTime` (epoch
|
||||
//! nanoseconds, about 1.7e18) used to be written, and bans never expired.
|
||||
#![cfg(feature = "xdp")]
|
||||
|
||||
use rampart::xdp::monotonic_ns;
|
||||
|
||||
fn clock_monotonic_ns() -> u64 {
|
||||
let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
|
||||
// SAFETY: `ts` — валидный writable `timespec`; CLOCK_MONOTONIC на Linux
|
||||
// поддерживается всегда (xdp-фича собирается только под Linux).
|
||||
// SAFETY: `ts` is a valid, writable `timespec`, and CLOCK_MONOTONIC is always
|
||||
// supported on Linux (the xdp feature only builds on Linux).
|
||||
let rc = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
|
||||
assert_eq!(rc, 0, "clock_gettime(CLOCK_MONOTONIC) failed");
|
||||
let secs = u64::try_from(ts.tv_sec).expect("tv_sec fits u64");
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
//! Раскладка ключа `blacklist6_map` (LPM-trie): префикс-длина в байтах 0..4
|
||||
//! little-endian + 16 байт адреса в network order (байты 4..20).
|
||||
//! Ядро не нужно: проверяется чистая функция кодирования ключа.
|
||||
//! Layout of the `blacklist6_map` key (LPM trie): the prefix length as a little-endian
|
||||
//! 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")]
|
||||
|
||||
use rampart::xdp::blacklist6_key;
|
||||
|
|
@ -28,7 +28,7 @@ fn key_layout_for_64_prefix() {
|
|||
|
||||
#[test]
|
||||
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]);
|
||||
|
||||
assert_eq!(key[0], 128, "prefixlen is not overwritten by the address");
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! Интеграционные тесты wire-формата и политики авто-бана XDP-событий.
|
||||
//! Ядро/Redis не нужны: проверяем чистые парсер и решение + дефолты конфига.
|
||||
//! Integration tests for the wire format and the auto-ban policy of XDP events.
|
||||
//! No kernel or Redis needed: the pure parser and decision are covered, plus config defaults.
|
||||
#![cfg(feature = "xdp")]
|
||||
|
||||
use rampart::config::Config;
|
||||
|
|
@ -8,21 +8,21 @@ use std::net::Ipv4Addr;
|
|||
|
||||
const IP: [u8; 4] = [203, 0, 113, 7];
|
||||
|
||||
/// Собирает кадр ровно как ядро (`push_event`, common.h:87-97): скаляры — native
|
||||
/// (host) order, `src_ip` — сетевой порядок октетов (raw из заголовка пакета).
|
||||
/// Builds a frame exactly as the kernel does (`push_event`, common.h:87-97): scalars in
|
||||
/// 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] {
|
||||
let mut b = [0u8; XDP_EVENT_LEN];
|
||||
b[0..4].copy_from_slice(&kind.to_ne_bytes());
|
||||
b[4..8].copy_from_slice(&octets);
|
||||
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
|
||||
}
|
||||
|
||||
#[test]
|
||||
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);
|
||||
}
|
||||
|
||||
|
|
@ -47,12 +47,12 @@ fn dirty_padding_does_not_corrupt_parse() {
|
|||
|
||||
#[test]
|
||||
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 ev = parse_xdp_event(&f).expect("parses");
|
||||
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") {
|
||||
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));
|
||||
|
|
@ -86,14 +86,14 @@ fn decision_matrix_by_type_and_enablement() {
|
|||
enabled: false,
|
||||
..AutoBanConfig::default()
|
||||
};
|
||||
// (kind, metadata=fails/хиты, банить ли при enabled)
|
||||
// (kind, metadata=fails/hits, whether to ban when enabled)
|
||||
let rows = [
|
||||
(0u32, 255u32, false), // EVENT_BAN — ядро уже забанило: никогда
|
||||
(1, 100, true), // EVENT_RATE_LIMIT — всегда баним
|
||||
(2, 0, false), // EVENT_POLICY_DROP — политика по дефолту не банит
|
||||
(3, 10, true), // EVENT_CONN_DROP fails=10 >= 3 — баним
|
||||
(3, 0, false), // EVENT_CONN_DROP fails=0 (hook-drop) — не баним
|
||||
(3, 2, false), // EVENT_CONN_DROP fails=2 < 3 — не баним
|
||||
(0u32, 255u32, false), // EVENT_BAN: already banned by the kernel, never
|
||||
(1, 100, true), // EVENT_RATE_LIMIT: always ban
|
||||
(2, 0, false), // EVENT_POLICY_DROP: the policy does not ban by default
|
||||
(3, 10, true), // EVENT_CONN_DROP fails=10 >= 3: ban
|
||||
(3, 0, false), // EVENT_CONN_DROP fails=0 (hook drop): no ban
|
||||
(3, 2, false), // EVENT_CONN_DROP fails=2 < 3: no ban
|
||||
];
|
||||
for (kind, meta, should_ban_when_on) in rows {
|
||||
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.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");
|
||||
assert!(auto_ban_decision(&below, &policy).is_none());
|
||||
let at = parse_xdp_event(&frame(3, IP, 5, 0)).expect("frame parses");
|
||||
|
|
|
|||
58
tests/xdp_object_maps.rs
Normal file
58
tests/xdp_object_maps.rs
Normal 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)"
|
||||
);
|
||||
}
|
||||
|
|
@ -12,13 +12,24 @@
|
|||
#define IP_OFFSET 0x1FFF
|
||||
#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 {
|
||||
STATE_SYN_RECEIVED = 0, // SYN seen, waiting for ACK (handshake completing)
|
||||
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 {
|
||||
__u32 src_ip;
|
||||
__u32 dst_ip;
|
||||
|
|
@ -26,9 +37,14 @@ struct flow_key {
|
|||
__u16 dst_port;
|
||||
};
|
||||
|
||||
// ── Connection tracking entry ──
|
||||
// LRU maps evict stale entries automatically when full; RST/FIN removes
|
||||
// entries explicitly. last_seen supports future timer-based idle cleanup.
|
||||
/**
|
||||
* Connection tracking entry.
|
||||
*
|
||||
* 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 {
|
||||
__u32 state;
|
||||
__u32 expected_seq;
|
||||
|
|
@ -38,25 +54,42 @@ struct conntrack_entry {
|
|||
__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 {
|
||||
__u64 window_start;
|
||||
__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 {
|
||||
__u32 prefixlen;
|
||||
__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 {
|
||||
__u32 prefixlen;
|
||||
__u8 addr[16];
|
||||
};
|
||||
|
||||
// ── Ringbuf event (userspace receives these) ──
|
||||
/**
|
||||
* Event kinds that userspace can receive and react to.
|
||||
*/
|
||||
enum event_type {
|
||||
EVENT_BAN = 0,
|
||||
EVENT_RATE_LIMIT = 1,
|
||||
|
|
@ -64,6 +97,13 @@ enum event_type {
|
|||
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 {
|
||||
__u32 type;
|
||||
__u32 src_ip;
|
||||
|
|
@ -71,7 +111,14 @@ struct xdp_event {
|
|||
__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) \
|
||||
do { \
|
||||
if ((void *)(ptr) + (sz) > (void *)(dend)) \
|
||||
|
|
@ -81,15 +128,35 @@ struct xdp_event {
|
|||
goto error; \
|
||||
} 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))
|
||||
|
||||
// ── 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 {
|
||||
__uint(type, BPF_MAP_TYPE_RINGBUF);
|
||||
__uint(max_entries, 1 << 24);
|
||||
} 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)
|
||||
{
|
||||
struct xdp_event *e = bpf_ringbuf_reserve(&events_ringbuf, sizeof(struct xdp_event), 0);
|
||||
|
|
|
|||
|
|
@ -1,47 +1,138 @@
|
|||
#ifndef RAMPART_CONFIG_H
|
||||
#define RAMPART_CONFIG_H
|
||||
|
||||
// ⚙️ Runtime configurable globals (patched by Rust loader)
|
||||
// These are volatile const — compiler replaces reads with immediate values
|
||||
// after loader writes to .rodata section
|
||||
/**
|
||||
* Runtime-tunable filter configuration.
|
||||
*
|
||||
* 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 ──
|
||||
// Protected port range: packets to ports OUTSIDE this range bypass the
|
||||
// filter (XDP_PASS before any counting/filtering). Default protects all
|
||||
// TCP/UDP ports; narrow it via loader patching for dedicated-edge setups.
|
||||
static volatile const __u16 G_START_PORT = 1;
|
||||
static volatile const __u16 G_END_PORT = 65535;
|
||||
// SYN throttle window: hit count per source, window length, ban length.
|
||||
__u32 syn_hit_count; // 10 max SYNs / window
|
||||
__u64 syn_window_ns; // 3 sec
|
||||
__u64 syn_ban_duration_ns; // 60 sec
|
||||
|
||||
// ── SYN throttle ──
|
||||
static volatile const __u32 G_SYN_HIT_COUNT = 10; // max SYNs / window
|
||||
static volatile const __u64 G_SYN_WINDOW_NS = 3000000000ULL; // 3 sec
|
||||
static volatile const __u64 G_SYN_BAN_DURATION_NS = 60000000000ULL; // 60 sec
|
||||
// Idle timeouts. The XDP path does not read them yet; they are part of
|
||||
// the loader ABI so userspace can drive timer-based cleanup.
|
||||
__u64 conntrack_idle_ns; // 30 sec
|
||||
__u64 player_idle_ns; // 120 sec
|
||||
|
||||
// ── Idle timeouts ──
|
||||
static volatile const __u64 G_CONNTRACK_IDLE_NS = 30000000000ULL; // 30 sec
|
||||
static volatile const __u64 G_PLAYER_IDLE_NS = 120000000000ULL; // 120 sec
|
||||
// Default ban duration userspace applies to new blacklist entries.
|
||||
__u64 ban_duration_ns; // 5 min
|
||||
|
||||
// ── Blacklist default ban duration ──
|
||||
static volatile const __u64 G_BAN_DURATION_NS = 300000000000ULL; // 5 min
|
||||
// Out-of-order payload packets tolerated before the connection is cut.
|
||||
__u8 max_out_of_order; // 4
|
||||
|
||||
// ── Max out-of-order packets before dropping connection ──
|
||||
static volatile const __u8 G_MAX_OUT_OF_ORDER = 4;
|
||||
// UDP policy and its rate-limit window.
|
||||
__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 ──
|
||||
static volatile const __u8 G_UDP_POLICY = 0; // 0 = pass, 1 = drop, 2 = rate-limit
|
||||
static volatile const __u32 G_UDP_HIT_COUNT = 100; // max packets / window
|
||||
static volatile const __u64 G_UDP_WINDOW_NS = 1000000000ULL; // 1 sec
|
||||
// Feature switches read on the hot path.
|
||||
__u8 feature_syn_throttle; // 1
|
||||
__u8 feature_events; // 1
|
||||
|
||||
// ── Feature flags ──
|
||||
static volatile const __u8 G_FEATURE_SYN_THROTTLE = 1;
|
||||
static volatile const __u8 G_FEATURE_EVENTS = 1;
|
||||
// RST-challenge (Oubliette-style liveness proof). 0 disables it, leaving
|
||||
// a single branch and zero cost for legitimate traffic. The secret is
|
||||
// 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.
|
||||
// Secret is patched by the loader at attach time (default is a placeholder).
|
||||
static volatile const __u8 G_SYN_CHALLENGE_ENABLED = 0;
|
||||
static volatile const __u64 G_CHALLENGE_SECRET = 0xA5A55A5A5A5AA5A5ULL;
|
||||
static volatile const __u32 G_CHALLENGE_TIMEOUT_MS = 3000; // pending TTL
|
||||
static volatile const __u64 G_CHALLENGE_VERIFIED_TTL_NS = 300000000000ULL; // 5 min
|
||||
/**
|
||||
* Default configuration image shipped inside the object file.
|
||||
*
|
||||
* volatile const keeps every read tied to the patched .rodata map instead of
|
||||
* being folded into a constant at compile time.
|
||||
*/
|
||||
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 */
|
||||
|
|
|
|||
|
|
@ -1,8 +1,14 @@
|
|||
#ifndef 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 {
|
||||
__uint(type, BPF_MAP_TYPE_LPM_TRIE);
|
||||
__uint(max_entries, 100000);
|
||||
|
|
@ -11,8 +17,12 @@ struct {
|
|||
__uint(map_flags, BPF_F_NO_PREALLOC);
|
||||
} 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 {
|
||||
__uint(type, BPF_MAP_TYPE_LPM_TRIE);
|
||||
__uint(max_entries, 100000);
|
||||
|
|
@ -21,7 +31,12 @@ struct {
|
|||
__uint(map_flags, BPF_F_NO_PREALLOC);
|
||||
} 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 {
|
||||
__uint(type, BPF_MAP_TYPE_LPM_TRIE);
|
||||
__uint(max_entries, 1000);
|
||||
|
|
@ -30,8 +45,12 @@ struct {
|
|||
__uint(map_flags, BPF_F_NO_PREALLOC);
|
||||
} 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 {
|
||||
__uint(type, BPF_MAP_TYPE_LRU_HASH);
|
||||
__uint(max_entries, 16384);
|
||||
|
|
@ -39,7 +58,12 @@ struct {
|
|||
__type(value, struct conntrack_entry);
|
||||
} 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 {
|
||||
__uint(type, BPF_MAP_TYPE_LRU_HASH);
|
||||
__uint(max_entries, 65535);
|
||||
|
|
@ -47,7 +71,12 @@ struct {
|
|||
__type(value, struct throttle_entry);
|
||||
} 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 {
|
||||
__uint(type, BPF_MAP_TYPE_LRU_HASH);
|
||||
__uint(max_entries, 65535);
|
||||
|
|
@ -55,15 +84,39 @@ struct {
|
|||
__type(value, struct throttle_entry);
|
||||
} 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 {
|
||||
__u64 sent_at; // ktime_ns of the reflected SYN-ACK
|
||||
__u32 marker; // our ISN (client may echo it as ack)
|
||||
__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 {
|
||||
__uint(type, BPF_MAP_TYPE_LRU_HASH);
|
||||
__uint(max_entries, 65536);
|
||||
|
|
@ -71,7 +124,12 @@ struct {
|
|||
__type(value, __u64); // last_seen (ktime_ns)
|
||||
} 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 {
|
||||
__uint(type, BPF_MAP_TYPE_LRU_HASH);
|
||||
__uint(max_entries, 16384);
|
||||
|
|
@ -79,7 +137,12 @@ struct {
|
|||
__type(value, struct challenge_pending);
|
||||
} 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_TCP 1
|
||||
#define STAT_WHITELIST 2
|
||||
|
|
@ -93,6 +156,12 @@ struct {
|
|||
#define STAT_CHALLENGE_VERIFIED 10
|
||||
#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 {
|
||||
__uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
|
||||
__uint(max_entries, 16);
|
||||
|
|
|
|||
|
|
@ -3,23 +3,45 @@
|
|||
|
||||
#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 {
|
||||
__u8 family;
|
||||
__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 {
|
||||
__u64 syn_count;
|
||||
__u64 pkt_count;
|
||||
__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 {
|
||||
__uint(type, BPF_MAP_TYPE_LRU_HASH);
|
||||
__uint(max_entries, 65536);
|
||||
|
|
@ -30,17 +52,33 @@ struct {
|
|||
#define PREFIX_FAMILY_V4 4
|
||||
#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,
|
||||
__u32 src_ip_net_order)
|
||||
{
|
||||
__builtin_memset(key, 0, sizeof(*key));
|
||||
key->family = PREFIX_FAMILY_V4;
|
||||
__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,
|
||||
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);
|
||||
}
|
||||
|
||||
// ── 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,
|
||||
__u8 is_syn, __u64 now)
|
||||
{
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue