Files
EvoFirewall/docs/agents.md
T
Denozordec 3815575799
Build and Push EvoFirewall Docker Image / build-and-push (push) Successful in 2m11s
Build and Push EvoFirewall Docker Image / create-release (push) Skipped
feat(api): update mikrotik-install script for improved filter rule management and versioning
- Updated the `client_version` in the `mikrotik-install.rsc` script from `rsc/5` to `rsc/6` to reflect the latest changes.
- Enhanced the firewall filter rule management by ensuring that new rules are added at the top of the `input` and `forward` chains using `place-before`, improving the order of execution and efficiency.
- Updated documentation in `agents.md` to clarify the new behavior of filter rules being placed at the beginning of the chains.

These changes enhance the functionality and clarity of the MikroTik installation process, improving overall firewall management.
2026-08-07 15:22:43 +07:00

112 lines
5.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Agents
## Short install (рекомендуется)
В UI `/agents`**Добавить агента**:
1. Создаётся агент со статусом **Invited** (сразу виден в таблице) + install-ссылка.
2. Скопируйте one-liner (колонка Install или Sheet):
**Linux:**
```bash
curl -fsSL https://<cp>/agent-install/<id> | bash
```
**MikroTik:**
```
/tool fetch url="https://<cp>/agent-install/<id>" dst-path=evofw-install.rsc; /import file-name=evofw-install.rsc
```
3. После enroll статус станет **Pending** — одобрите агента (Approve).
4. **Approved** — агент синхронизирует политику.
**Повторный запуск той же install-ссылки** на хосте, где агент уже стоит: обновляет sync-скрипт / timer (или MikroTik scheduler), **без** повторного enroll — `CLIENT_ID`/`token` сохраняются. Полный переустановки с новым токеном: `EVOFW_INSTALL_FORCE=1` (Linux).
API (auth): `POST /api/v1/install-links` `{ "name": "web-01", "platform": "linux" | "mikrotik" }`.
## Linux (legacy one-liner)
```bash
curl -fsSL https://<cp>/v1/agent/install.sh | \
EVOFW_CP_URL=https://<cp> \
EVOFW_SEED=<seed> \
EVOFW_CLIENT_NAME="web-01" \
bash
```
Создаёт нового агента со статусом Pending (без Invited).
Файлы: `/etc/evofw/agent.conf`, `/usr/local/sbin/evofw-firewall.sh`, timer `evofw-firewall.timer` (default 1min).
Install сам ставит зависимости через apt/dnf/yum/apk: `curl`, `jq` (или `python3`), `nftables`/`iptables`(+`ipset`). Планировщик: **systemd timer** если есть `/run/systemd/system`, иначе ставит `cron`/`cronie` и пишет crontab. Значения в `agent.conf` всегда в single quotes (имена с пробелами безопасны). Sync при статусе pending завершается с exit 0 (`pending approval`), чтобы systemd timer не был failed.
Если `/etc/evofw/agent.conf` уже есть — install переходит в **update**: скачивает свежий `sync-script` + `uninstall.sh`, перезаписывает unit/timer, оставляет токен. `EVOFW_INSTALL_FORCE=1` — полный re-enroll (новый токен; для уже Approved install-link обычно не сработает).
**Uninstall (Linux):**
```bash
curl -fsSL https://<cp>/v1/agent/uninstall.sh | bash
# или локально после install:
sudo /usr/local/sbin/evofw-uninstall.sh
```
Backend auto-detect: nft → ipset → iptables.
Whitelist: nft chain policy drop + allow set. Blacklist: policy accept + deny set.
## Per-IP blocked stats (Linux)
Linux agent reports optional `ip_hits` in `POST /v1/agent/apply-report`:
- **nft:** tries set `deny_v4` with `flags interval; counter;`. If the kernel rejects counters on interval sets, falls back to plain interval (aggregate Traffic ↓ still works; per-IP empty).
- Upgrade path: on install-link re-run, `last_hash` is cleared once so sets can be recreated (chain deleted before set replace).
- **ipset:** prefers `hash:net … counters` on create; existing sets without counters are left as-is.
- Payload: only entries with `packets > 0`, **top 200** by packets.
- Control plane: `agent_ip_block_stats`, `GET /api/v1/agents/:id/blocked-ips`, reset via `POST …/stats/reset`.
- UI: agent detail → **Blocked IPs**.
IPv6 skipped.
## MikroTik (RouterOS 7.21+)
В UI `/agents`**Добавить агента** → platform **MikroTik**. Скопируйте one-liner:
```
/tool fetch url="https://<cp>/agent-install/<id>" dst-path=evofw-install.rsc; /import file-name=evofw-install.rsc
```
Или короткий slug: `https://<cp>/<slug>`.
Install RSC:
1. Enroll (с `install_link_id` → агент Invited → Pending).
2. Создаёт filter-правила `evofw-*` **в начале** цепочек `input`/`forward` (`place-before`) и address-list `EVOFW_DENY` / `EVOFW_ALLOW` / dynamic **`EVOFW_HITS`**.
3. Scheduler `evofw-sync` каждую минуту: `GET /v1/agent/policy` (JSON) → rebuild deny/allow + report (+ `ip_hits` из HITS). Не использует `/import` огромного `.rsc`.
Лог: `/log print where message~"evofw"`. Ручной sync: `/system script run evofw-sync`.
Traffic ↓/↑ в UI — сумма `packets` с `evofw-deny-drop-*` / `evofw-allow-*` / `evofw-default-drop-*` (накопительно, пока правила не пересозданы re-install).
### Per-IP / Blocked IPs (MikroTik)
Цепочка deny: **hit → drop** (семантика drop/allow/default как раньше):
1. `evofw-deny-hit-input/forward``add-src-to-address-list``EVOFW_HITS`, `address-list-timeout=1h` (passthrough).
2. `evofw-deny-drop-input/forward``drop` по `EVOFW_DENY`.
В `EVOFW_HITS` попадают реальные src **/32**. Policy rebuild **не** чистит HITS (только DENY/ALLOW). Sync шлёт top-200 в `ip_hits`; CP mode **presence**: `last_seen` каждый report, `packets` = число sync-окон (~минут), пока IP в HITS.
UI: agent detail → **Blocked IPs** (колонка Sync windows).
**Default action** задаётся на **агенте** (`default_action: accept | drop`):
- **accept** — пакет вне deny/allow пропускается
- **drop** — пакет вне deny/allow отбрасывается (forward)
Цепочка: deny-hit → deny-drop → allow-accept → default. Наборы несут только правила deny/allow, без exclusive mode.
## Force sync
```bash
sudo rm -f /var/lib/evofw/last_hash
sudo /usr/local/sbin/evofw-firewall.sh
```