Docs restructure, code review, gatherer reliability, JWT key fail-closed

Documentation
- Three levels: DOCS/General (overview, configuration), DOCS/Deployment
  (choose a method, first steps), details per method in Containers/ and
  System_Services/; new root README and DOCS/README map.
- Remove superseded pages (Deployment.md, Deployment_Docker/Native.md, Index.md);
  split the two scenario guides by section.
- Isolate the Timeweb/Hysteria2 records in DEPLOYMENTS/timeweb-hysteria2/
  (not linked from DOCS, listed in .graphifyignore).
- Add DOCS/code_review/ with a time-stamped analysis of the code base.

Gatherer (BUG-02, BUG-03)
- Session key (CN, address, connected_since_ts), baseline from the
  active_sessions snapshot, grace period for sessions missing from the status.
- Status file integrity (TITLE/TIME/END) and freshness; a torn read skips the tick.
- Cache applied after commit; main loop survives exceptions, backs off, and
  stops cleanly on SIGTERM/SIGINT; new client rows start with the first
  frame's totals; five tests.

JWT signing key (SEC-01)
- No built-in default: Core and Profiler refuse to start with a missing,
  placeholder or short (< 32) key; shipped config.ini has an empty value.
- Same rule in install.sh, update.sh (issues a new key when missing or weak),
  docker lib/entrypoint; five tests, conftest.py for the test key.

Each change has a plan and a summary under DOCS/Changes/.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-05 20:30:45 +03:00
1 parent f95a0b63e6
commit ad6995bb63
85 files changed
+2805 -1280

No files matched your search

@@ -1,48 +0,0 @@
# Egress of OpenVPN clients via a Hysteria2 tunnel (2026-09-30)
Goal: all traffic of VPN clients leaves the internet through an exit node reached over an existing Hysteria2 client tunnel (`hytun`) on the VPN host.
```
OpenVPN client --udp/1194--> tun0 (172.20.1.1/24)
-> ip rule 102: from 172.20.1.0/24 -> table 100
-> table 100: default dev hytun (metric 10), blackhole default (metric 1000)
-> iptables nat POSTROUTING -s 172.20.1.0/24 -o hytun -j MASQUERADE
-> hytun (TUN of the Hysteria2 client) --QUIC/UDP 443--> exit node --> Internet
```
## Prerequisites
- A running Hysteria2 client with a TUN device (`hytun`), a routing table (100) with `default dev hytun` and a `blackhole` fallback, and `rp_filter=2` (loose) on all/default/hytun (strict mode drops TUN replies).
- Hysteria server-side `socks5`/`http` outbounds are TCP-only, so UDP needs TUN + policy routing, not a SOCKS chain.
- The exit node needs no changes.
## Implementation (OpenRC service `ovpn-hytun`)
`depend: need hysteria-route; before openvpn`. On start:
```sh
sysctl -qw net.ipv4.ip_forward=1
ip rule add priority 102 from 172.20.1.0/24 lookup 100
iptables -t nat -A POSTROUTING -s 172.20.1.0/24 -o hytun -j MASQUERADE
iptables -t mangle -A FORWARD -o hytun -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu # and -i hytun
iptables -A FORWARD -s 172.20.1.0/24 ! -o hytun -j DROP # anti-leak
```
Rules are idempotent (`-C` before `-A`); `stop` removes them. Adjust `172.20.1.0/24` to the `server` network in `server.conf`. Persist `ip_forward` in `/etc/sysctl.d/`. Use POSIX `sh` in OpenRC scripts (no bash arrays).
## Properties
- Only the VPN subnet enters the tunnel; SSH, OpenVPN's own port (1194) and management traffic use the main table.
- If the Hysteria client dies, table 100 falls to `blackhole`: clients lose internet, they do not leak through `eth0`.
- Clients get public DNS (e.g. 1.1.1.1) that is resolved through the same tunnel.
## Verification
| Check | Result |
|---|---|
| Node: TCP and UDP (DNS) through `hytun` | works |
| Reference (uid routed to `hytun`): external IP | exit node address |
| Real VPN client: `https://ifconfig.me` | exit node address (end-to-end test passed) |
| `ip rule`, `iptables -t nat -S POSTROUTING`, `rc-status` | rules present, services started |
Testing tip: a network namespace test that reuses the VPN subnet conflicts with a live `tun0`; test with a real client or a different, temporary subnet added to the rules.
@@ -80,4 +80,4 @@ Results (throw-away second OpenVPN instance on another port/subnet running as `n
The helper reads an optional **`/etc/ovpmon/helper.conf`** (INI, section `[helper]`) with keys `install_dir`, `service_manager` (`openrc` or `systemd`), `service_unit`, `config_path`, `staged_path`. Without the file the built-in values apply, which are exactly the previous hard-coded ones (OpenRC `rc-service openvpn`, `/etc/openvpn/server.conf`, PKI below `/opt/OpenVPN-Monitoring-Simple`): existing hosts behave as before. The helper runs through `doas` with a stripped environment, so it reads its own file: it must be a regular file owned by root and not group/world writable, every value is validated strictly (absolute paths without `..`, `config_path` below `/etc/openvpn/`, `staged_path` below `/var/lib/ovpmon/`, unit name `^[A-Za-z0-9@._-]{1,64}$`, fixed set of managers), unknown keys and invalid values make the helper refuse. With `systemd` it runs `systemctl <action> <unit>` (default unit `openvpn-server@server`, fixed argument list and `PATH`); the `/etc/openvpn/openvpn.conf` link is created only for OpenRC. The `doas` rules file is unchanged (on Debian/Ubuntu the package is `opendoas`, rules in `/etc/doas.conf`).
`APP_PROFILER/services/process.py` honours `OVPMON_RUNTIME=host|container` (explicit override of the container detection) and, for the root (non-helper) path, `OVPMON_OPENVPN_SERVICE` (default `openvpn`) and `OVPMON_OPENVPN_CONFIG` (default `/etc/openvpn/server.conf`). Installation: [Scenario 2](../Deployment/Scenario2_System_Services.md). Test: `APP_PROFILER/test_helper_config.py`.
`APP_PROFILER/services/process.py` honours `OVPMON_RUNTIME=host|container` (explicit override of the container detection) and, for the root (non-helper) path, `OVPMON_OPENVPN_SERVICE` (default `openvpn`) and `OVPMON_OPENVPN_CONFIG` (default `/etc/openvpn/server.conf`). Installation: [Scenario 2](../Deployment/System_Services/README.md). Test: `APP_PROFILER/test_helper_config.py`.
+21
View File
@@ -0,0 +1,21 @@
# Анализ кодовой базы: итог (2026-10-05)
План: [2026-10-05_Code_Review_PLAN.md](2026-10-05_Code_Review_PLAN.md). Отчёт: [DOCS/code_review/2026-10-05_1607Z_Codebase_Analysis.md](../code_review/2026-10-05_1607Z_Codebase_Analysis.md).
## Что сделано
- Прочитан код `APP_CORE`, `APP_PROFILER`, root-помощника, контейнеров и ключевых скриптов `deploy/`; UI проверен на места риска.
- Граф знаний использован для метрик по областям, самых связных узлов, мостов, когезии сообществ и связей между компонентами. Найден артефакт графа: стандартный `logging` разрешается в `APP_PROFILER/utils/logging.py` (пять ложных рёбер).
- Запущены `pyflakes`, `bandit`, `shellcheck`, `bash -n` и оба набора тестов (в изолированном venv вне репозитория).
## Результат
28 находок с серьёзностью и статусом проверки (12 по безопасности, 9 по корректности, 7 по архитектуре) и отдельный раздел по тестам и качеству; 21 рекомендация в порядке P0, P1, P2. Три главных: ключ JWT по умолчанию, перебор 2FA без ограничения, застревание отзыва сертификата. Измерено: тесты Core 7 из 7, профайлер 11 из 13 (два устаревших теста), 0 ошибок `shellcheck`, 30 замечаний `bandit` (все B608 проверены вручную).
## Не выполнено
Динамическая проверка на живом хосте, сканирование зависимостей, нагрузка. Список в разделе 5 отчёта.
## Побочные эффекты
Код не менялся. Тесты создали `APP_PROFILER/profiler.log`; файл удалён.
@@ -0,0 +1,20 @@
# Анализ кодовой базы: план (2026-10-05)
## Цель
Комплексная оценка кодовой базы с опорой на граф знаний (`graphify-out/`): архитектура, безопасность, корректность, сопровождаемость, тесты, эксплуатация. Результат фиксируется в `DOCS/code_review/` с отметкой времени в имени файла.
## Метод
1. Граф: метрики по областям, связи между компонентами, узлы-мосты, когезия сообществ, самые связные узлы.
2. Чтение кода: `APP_CORE` (API, сборщик, БД), `APP_PROFILER` (роутеры, PKI, процесс, генератор), root-помощник `ovpmon-helper`, UI (маршруты, API-клиент, места риска XSS), контейнеры и compose, скрипты `deploy/`.
3. Инструменты в изолированном venv вне репозитория: `pyflakes`, `bandit`, `shellcheck`, `bash -n`, оба набора тестов.
4. Каждая находка помечается статусом проверки: подтверждено кодом, воспроизведено инструментом, не воспроизведено.
## Границы
Код и конфигурации не меняются. Динамическое тестирование на живом хосте, сканирование уязвимостей зависимостей (`pip-audit`, `npm audit`) и нагрузочные испытания не выполняются.
## Результат
`DOCS/code_review/<UTC-время>_Codebase_Analysis.md` и сводка по выполненному в `2026-10-05_Code_Review.md`.
@@ -0,0 +1,49 @@
# Documentation refactoring: summary (2026-10-05)
Plan: [2026-10-05_Docs_Refactoring_PLAN.md](2026-10-05_Docs_Refactoring_PLAN.md).
## Result
| Category | Where | Content |
|---|---|---|
| General information | `DOCS/General/` | new `Overview.md` (components, ports, data, glossary), new `Configuration.md`, `Security_Architecture.md`, `Database_Migrations.md` |
| Installation methods | `DOCS/Deployment/README.md`, `First_Steps.md` | side-by-side comparison, a recommendation, rules common to both methods; the post-install path (sign in, account, PKI, VPN, start, first client, network) written once for both |
| Details: containers | `DOCS/Deployment/Containers/` | `README` (quick start, variants, requirements, install), `Operations`, `Reference`, `Troubleshooting` |
| Details: system services | `DOCS/Deployment/System_Services/` | `README` (quick start, supported systems, install per OS, verification), `Operations`, `Reference`, `Web_UI`, `Firewall`, `Nginx_Configuration`, `Service_Management`, `Troubleshooting` |
| Entry points | `README.md`, `DOCS/README.md` | the root README is short: what it is, install in three steps, a map; `DOCS/README.md` maps goals to pages |
| Changes | `DOCS/Changes/README.md` | the change log moved out of the root README |
The two long scenario files (261 and 493 lines) were split by sections; the text was moved as it is, only cross-references were updated.
## Isolated: Hysteria2 on Timeweb
`DEPLOYMENTS/timeweb-hysteria2/` (outside `DOCS/`): the chain manifest, the egress change, the host summary, the reboot test, the plan and both rollout records of the settings validation and privilege separation (they describe the rollout on that host). It has its own README; the general documentation does not link to it; the folder is listed in `.graphifyignore`. The host addresses, the account name and the certificate fingerprint now live only there.
Left in the general documentation on purpose: neutral technical mentions of the Hysteria2 tunnel as an example of an uplink (the firewall script and its change records) and two verification rows of the privilege-separation record. They contain no host data.
## Removed or replaced
| Removed | Why |
|---|---|
| `General/Deployment.md` | outdated (port 5000, `UI/client`, other variable name), contradicted the current guides; superseded by `Deployment/` |
| `General/Deployment_Docker.md`, `Deployment_Native.md` | pointers only (the native one carried an outdated quick start) |
| `General/Index.md` | replaced by `DOCS/README.md` |
| `Deployment/Scenario1_Containers.md`, `Scenario2_System_Services.md` | split into the two folders |
## Other fixes
- `Security_Architecture.md`: links to files on the author's Mac (`file:///Users/...`) replaced by repository-relative links; a link to a file that does not exist (`Setup2FA.vue`) turned into text.
- Comments in `deploy/*` scripts, `docker-compose*.yml` and the nginx template, and two runtime error messages (`deploy/allinone/entrypoint.sh`, `deploy/docker/lib.sh`), now point to the new pages. No logic changed (`bash -n` passes on all changed scripts); the all-in-one image picks up the new message at the next rebuild.
- The change records of 2026-09/10 keep their original wording; only their links were updated.
## Verification
- Every relative Markdown link and anchor in `README.md`, `DOCS/`, `DEPLOYMENTS/` and the component READMEs: 60 files, 0 problems.
- No document under `DOCS/` links to `DEPLOYMENTS/`.
- Facts of the new pages were taken from the previous guides and checked against the sources: UI menu and button names (`App.vue`, `PKIConfig.vue`, `ServerManagement.vue`, `Certificates.vue`), container NAT and forwarding (`entrypoint.sh`, compose files).
## Not done
- The newcomer path was **not** walked through on a clean host: the commands are those of the existing, previously tested guides.
- The knowledge graph is stale for the moved files: run `/graphify --update .`.
- Translation: all documents stay in English (the two Russian records live in `DEPLOYMENTS/`).
@@ -0,0 +1,59 @@
# Documentation refactoring: plan (2026-10-05)
## Goal
A newcomer who has never seen the project can bring up a working environment by **any** supported method, using the documentation alone. The documentation is split into three categories; everything specific to one concrete host (Hysteria2 chain on Timeweb) is taken out of the general documentation.
## Problems found (from the knowledge graph and a read of all documents)
| Problem | Evidence |
|---|---|
| No single place says which installation method to pick | the README has three one-line quick starts, `DOCS/General/Index.md` lists four deployment pages |
| Outdated guide competes with the current ones | `General/Deployment.md` (port 5000, `UI/client`, `OVPMON_SECRET_KEY`) contradicts Scenario 1 and 2; `Deployment_Docker.md` and `Deployment_Native.md` are pointers only (the native pointer still says "build the UI with Docker first") |
| Two 260-500 line files mix quick start, reference, operations and troubleshooting | `Scenario1_Containers.md` (261 lines), `Scenario2_System_Services.md` (493 lines) |
| No common "after the install" path | the same three sentences are repeated in each scenario and in the README |
| The README carries a 14-row change log and security notes before the newcomer reaches the install | README sections order |
| Host-specific records sit in the general tree | `DOCS/Operations/` (IPs, login, certificate fingerprint of the Timeweb host) and `Changes/2026-09-30_Egress_via_Hysteria2.md` |
## Target structure
```
README.md what it is, architecture, install in 3 steps, map of the docs
DOCS/README.md documentation map by goal ("I want to ...")
DOCS/General/ 1. general information
Overview.md components, ports, data, glossary
Configuration.md config.ini and environment variables
Security_Architecture.md (kept)
Database_Migrations.md (kept)
systemd/ openrc/ privilege-separation/ service files and the helper: used by the install scripts, not moved
DOCS/Deployment/ 2. installation methods
README.md choose a method, requirements side by side
First_Steps.md the same for every method: sign in, PKI, server, first profile
Containers/ 3a. details: containers (variants A and B)
README.md Operations.md Reference.md Troubleshooting.md
System_Services/ 3b. details: Alpine, Debian, Ubuntu without containers
README.md Operations.md Reference.md Web_UI.md Firewall.md Nginx.md Troubleshooting.md
DOCS/Core_Monitoring, Profiler_Management, UI API and component reference (kept)
DOCS/Changes/ records of changes, with an index (README.md)
DEPLOYMENTS/timeweb-hysteria2/ isolated: records of the Hysteria2 chain and the host on Timeweb
```
## Steps
1. Isolate the host-specific records: `git mv DOCS/Operations` and the Hysteria2 change to `DEPLOYMENTS/timeweb-hysteria2/`; nothing in the general documentation links there; the folder is added to `.graphifyignore`.
2. Split Scenario 1 and Scenario 2 by their sections into the folders above (content is moved, not rewritten); add a short quick start on top of each folder `README.md`.
3. Write the new documents: `Overview`, `Configuration`, `Deployment/README`, `First_Steps`, `DOCS/README`, `Changes/README`.
4. Remove the superseded pages (`General/Deployment.md`, `Deployment_Docker.md`, `Deployment_Native.md`, `Index.md`); move `Service_Management.md` and `Nginx_Configuration.md` under `System_Services/`.
5. Rewrite the root `README.md` and fix the references: comments in `deploy/*` scripts and compose files (comments only), component READMEs, other documents.
6. Check every relative Markdown link and every script reference; `bash -n` on the changed scripts.
## Rules
- Content is not lost: sections are moved as they are; only duplicated text is replaced by a link.
- Install scripts keep working: the paths they read (`DOCS/General/systemd`, `openrc`, `privilege-separation`) do not change.
- Documents stay in English like the rest of the repository.
- No code or behaviour changes; script edits are comments only.
## Out of scope
Translating the documents, rewriting the API references, rebuilding the knowledge graph (the moved files need a `/graphify --update`).
@@ -0,0 +1,46 @@
# Сборщик трафика: устойчивость и точность учёта (итог, 2026-10-05)
План: [2026-10-05_Gatherer_Reliability_PLAN.md](2026-10-05_Gatherer_Reliability_PLAN.md). Закрыты находки BUG-02 и BUG-03 [отчёта анализа кода](../code_review/2026-10-05_1607Z_Codebase_Analysis.md).
## Что сделано
| Область | Изменение |
|---|---|
| Идентичность сессии | ключ `(CN, адрес, connected_since_ts)` из `Connected Since (time_t)` статуса v2; порог 10 МБ остался только как запасной путь без `time_t` |
| Новая сессия | считается с нуля при любом первом объёме (BUG-03); строка нового клиента создаётся с итогами первого кадра (BUG-03b, найдено при ревью) |
| Перезапуск демона | базовая линия из снимка `active_sessions`; трафик простоя учитывается; без снимка прирост 0 и запись в лог |
| Исчезновение из статуса | льготный период `session_grace_ticks`; плюс «память» о удалённых сессиях на 1 час против двойного учёта |
| Чтение статуса | `parse_status`: нужны `TITLE`, `TIME`, последняя строка `END`; рваный кадр пропускает тик целиком; устаревший `TIME` означает остановленный OpenVPN |
| Кэш и БД | изменения кэша применяются после `commit`; при ошибке БД откат и исключение (цикл повторит, прирост не теряется) |
| Цикл | исключение не завершает демон; пауза `max(interval, min(interval*2^n, 60))`; `SIGTERM`/`SIGINT` останавливают после текущего цикла; настройки проверяются при старте |
| `active_sessions.connected_since` | реальное начало сессии в UTC (раньше локальное время первого наблюдения) |
| Конфигурация | `session_grace_ticks=3`, `status_stale_seconds=60`, `status_invalid_max=6` в `[openvpn_monitor]` |
| Документация | `Data_Architecture.md` (разделы B и B1), `API_Reference.md` (`connected_since`, `last_seen`), `config.ini` |
Схема БД и формат API не менялись. Файлы: `APP_CORE/openvpn_gatherer_v3.py`, `APP_CORE/test_gatherer.py` (5 тестов), `APP_CORE/config.ini`.
## Разработка и ревью
Код и тесты написал субагент без запуска тестов. Ревью выполнено отдельно: чтение кода и запуск проверок. Результат ревью: код соответствует плану, отклонения субагента обоснованы (ошибка БД пробрасывается циклу, «память» удалённых сессий, невалидный файл без `TIME`, пауза не меньше интервала). Найден и исправлен один дефект: `INSERT` нового клиента с нулевыми итогами (4 теста из 5 были красными до правки).
## Проверка
| Проверка | Результат |
|---|---|
| `pytest` Core: `test_gatherer.py` + `test_migrations.py` | 12 из 12 (5 новых + 7 прежних) |
| Новые тесты на старой логике (`HEAD`) | 5 из 5 красные |
| `pyflakes` | новых замечаний нет (`sqlite3` не используется: было и раньше) |
| Реальный процесс: рост счётчика 1 МБ/с, `SIGTERM` посреди передачи, перезапуск | итоги `clients` и `usage_history` равны последним счётчикам (12 000 000 / 1 200 000), трафик простоя учтён, оба выхода с кодом 0, предупреждений нет |
| Неверный `check_interval=abc` | сообщение `Invalid configuration` и отказ запуска |
## Не проверялось
- Гонка чтения реального файла OpenVPN (рваный кадр проверен синтетически); `kill -TERM` на живом OpenVPN-хосте и остановка OpenVPN для проверки `Disconnected` по устаревшему `TIME`.
- Обновление через `update.sh` на тестовом хосте (бэкап, перезапуск, откат).
- Сигналы под supervisord, systemd и OpenRC: все три отправляют `SIGTERM`, но на живых службах не запускались.
## Остаточные риски
- Однократно после обновления: сессии, подключённые в момент обновления, получают базовую линию (строки старого снимка не совпадают с новыми ключами).
- Мигание статуса клиента при кадре, прошедшем проверку `END`, но смешанном из старого и нового содержимого: учёт защищён льготным периодом, статус нет.
- Три записи цикла (учёт, история, агрегация) по-прежнему в отдельных транзакциях; healthcheck контейнера проверяет только наличие процесса.
@@ -0,0 +1,145 @@
# Сборщик трафика: устойчивость и точность учёта (план, 2026-10-05)
Источник: [отчёт анализа кода](../code_review/2026-10-05_1607Z_Codebase_Analysis.md), находки **BUG-02** и **BUG-03**. Затронутый код: `APP_CORE/openvpn_gatherer_v3.py`. Схема БД не меняется, API не меняется (кроме смысла поля `connected_since`, см. шаг 4).
## 1. Проблема
| ID | Что происходит сейчас | Последствие |
|---|---|---|
| BUG-02a | Любое исключение вне внутренних `try` выходит из `while True` и завершает процесс (`:604-618`); обработчика `SIGTERM` нет, ловится только `KeyboardInterrupt` | демон падает от разового сбоя; остановка службы может оборвать цикл между тремя записями в БД |
| BUG-02b | Файл статуса читается без проверки целостности (`:263-312`); при чтении в момент перезаписи клиенты «исчезают», кэш сессий очищается (`:429-432`), следующий тик считает их новыми | двойной учёт (малые счётчики считаются заново) или потеря байт (большие пропускаются) |
| BUG-02c (найдено при разборе) | Кэш сессий обновляется до записи в БД (`:388-401`), при откате транзакции (`:521`) приращения теряются | станет заметнее, когда цикл перестанет умирать от исключений |
| BUG-02d (найдено при разборе) | Файл статуса не проверяется на свежесть: после остановки OpenVPN остаётся старое содержимое | клиенты навсегда «Active» с нулевым приростом |
| BUG-03 | Сессия, впервые замеченная с объёмом ≥ 10 МБ, получает нулевой прирост (`:377-386`) | недоучёт нового быстрого клиента: 10 МБ за 10 с это около 8 Мбит/с; то же после каждого перезапуска демона |
Причина общая: сборщик **не знает, когда началась сессия**, и угадывает по размеру счётчика. OpenVPN сообщает это сам.
> **Дополнение по итогам реализации (BUG-03b).** При ревью тесты выявили ещё одну причину недоучёта: строка нового клиента в `clients` создавалась с `total_bytes_* = 0`, поэтому прирост первого кадра не попадал в итоги (попадал только в `usage_history`). Исправлено в той же доработке: строка создаётся с итогами, равными приросту первого кадра.
## 2. Решение
### 2.1 Формат статуса v2 (`status-version 2`, задан в `server.conf.j2`)
```
TITLE,... TIME,<текст>,<epoch> HEADER,CLIENT_LIST,...
CLIENT_LIST,<CN>,<real>,<virt>,<virt6>,<rx>,<tx>,<Connected Since>,<Connected Since (time_t)>,...
HEADER,ROUTING_TABLE,... ROUTING_TABLE,... GLOBAL_STATS,...
END
```
Парсер уже использует индексы 1, 2, 5, 6 и требует не менее 8 полей; индекс 8 (`time_t` начала сессии) у каждой строки есть. Завершающая строка `END` и строка `TIME` (время записи) дают проверку целостности и свежести.
### 2.2 Идентичность сессии и решение «новая или продолжающаяся»
Ключ сессии: `(common_name, real_address, connected_since_ts)`.
| Ситуация | Решение |
|---|---|
| Ключ есть в кэше | прирост `текущее - прежнее`; уменьшение счётчика при том же ключе считается сбросом (`прирост = текущее`), как сейчас |
| Ключа нет, сессия началась позже запуска демона (с запасом `2 × интервал`) | **новая**: прирост = текущие счётчики целиком. Порог 10 МБ не нужен |
| Ключа нет, сессия началась до запуска демона, есть строка в снимке `active_sessions` с тем же ключом | **продолжающаяся после перезапуска**: прирост = `текущее - снимок`, трафик за время простоя учитывается |
| Ключа нет, сессия началась до запуска, снимка нет (первый запуск после обновления, потеря БД) | базовая линия: прирост 0, запись в лог с именем клиента (единственный случай потери, один раз на сессию) |
| `connected_since_ts` не разобрался (нестандартный статус) | прежняя эвристика с порогом 10 МБ как запасной путь, предупреждение в логе |
### 2.3 Исчезновение сессии из статуса
Записи кэша, которых нет в текущем статусе, **не удаляются сразу**: счётчик пропусков `missing_ticks`, удаление после `session_grace_ticks` (по умолчанию 3 тика, около 30 с). Вернувшаяся сессия продолжает прежний ключ: двойного учёта нет. Реально завершённая сессия при повторном подключении получает новый `connected_since_ts` и считается с нуля.
### 2.4 Валидность чтения
`parse_log_file` возвращает результат с признаком валидности:
- нет файла, ошибка чтения, нет строки `END` или `TITLE`: **тик пропускается целиком** (БД и кэш не трогаются, статусы не меняются); после `status_invalid_max` (6) подряд пропусков уровень лога поднимается до ERROR;
- строка `TIME` старше `status_stale_seconds` (60 с): файл устарел (OpenVPN остановлен), клиенты считаются отсутствующими (все завершают сессию через льготный период);
- пустой, но целостный и свежий файл (нет `CLIENT_LIST`): клиентов нет, это штатный случай.
Прирост за пропущенные тики не теряется: кэш не менялся, следующий валидный тик посчитает разницу за весь интервал.
### 2.5 Целостность кэша и БД
Изменения кэша накапливаются во временной структуре и применяются **после** успешного `commit` (шаг 3 ниже). При откате транзакции кэш остаётся прежним, приращения не теряются.
### 2.6 Основной цикл
- Каждый цикл в `try/except Exception` с `logger.exception`; демон не завершается.
- Подряд идущие сбои: ожидание `min(interval × 2^n, 60 с)`; счётчик сбрасывается после успешного цикла.
- Сигналы `SIGTERM` и `SIGINT` выставляют флаг остановки; цикл ждёт `Event.wait(interval)`, текущий цикл доделывается до конца (транзакции короткие), выход с кодом 0. `stop_grace_period` в compose (20 с) и таймауты systemd и OpenRC достаточны.
- Значения `check_interval` и новых ключей проверяются при старте: неверное значение это отказ запуска с понятным сообщением (ошибка конфигурации не должна крутиться в цикле).
## 3. Шаги
| # | Шаг | Результат |
|---|---|---|
| 0 | Тестовый каркас: временная БД (как в `test_migrations.py`), `monkeypatch.chdir(tmp_path)` (сборщик пишет лог в текущий каталог), синтетические файлы статуса v2, управляемое «время» | тесты воспроизводят оба дефекта на текущем коде (красные) |
| 1 | `parse_status(path)`: разбор целостности, `TIME`, `connected_since_ts`; `parse_log_file` остаётся тонкой обёрткой | чтение с признаком валидности |
| 2 | Ключ сессии, правила 2.2, льготный период 2.3, загрузка базовой линии из `active_sessions` при старте | BUG-03 и часть BUG-02b закрыты |
| 3 | Применение изменений кэша после `commit` (2.5) | BUG-02c закрыт |
| 4 | В `active_sessions.connected_since` писать **реальное** начало сессии (UTC, формат `YYYY-MM-DD HH:MM:SS`) вместо локального времени первого наблюдения; снимок служит базовой линией шага 2 | схема без изменений, поле API становится точным |
| 5 | Цикл: устойчивость, откат на экспоненту, сигналы, проверка конфигурации (2.6) | BUG-02a закрыт |
| 6 | Свежесть файла и пропуск невалидного тика (2.4) | BUG-02b и BUG-02d закрыты |
| 7 | Документация: `DOCS/Core_Monitoring/Data_Architecture.md` (раздел «Delta Calculation» описывает прежнюю логику), `API_Reference.md` (смысл `connected_since`), `APP_CORE/config.ini` (новые необязательные ключи), строка в README, сводка `2026-10-05_Gatherer_Reliability.md` | документация актуальна |
Новые ключи (необязательные, переопределяются `OVPMON_OPENVPN_MONITOR_*`): `session_grace_ticks=3`, `status_stale_seconds=60`, `status_invalid_max=6`.
## 4. Тесты (минимум, в духе правил проекта)
Один файл `APP_CORE/test_gatherer.py`, пять тестов на синтетических статусах:
1. **Новая быстрая сессия:** первый кадр с 50 МБ и `connected_since` 5 секунд назад, прирост равен 50 МБ (регрессия BUG-03).
2. **Перезапуск демона:** сессия старше запуска, снимок в `active_sessions` есть, прирост равен разнице со снимком; снимка нет, прирост 0 и запись в логе.
3. **Рваное чтение:** кадр без `END`, тик пропущен, БД и кэш не изменились; следующий целостный кадр даёт разницу за оба интервала без дублей.
4. **Исчезновение на один тик:** сессия вернулась с тем же ключом, двойного учёта нет; пропала дольше льготного периода и вернулась с новым `connected_since`, учёт с нуля.
5. **Цикл:** исключение в `run_monitoring_cycle` не останавливает цикл; установка флага остановки завершает его после текущего цикла.
Существующие тесты не меняются. Дополнительно: `pyflakes` и `bash -n` без новых замечаний.
## 5. Проверка вне модульных тестов
1. Прогон на синтетическом ряде статусов (скрипт в `scratchpad`, не в репозитории): сумма приростов равна разности конечных и начальных счётчиков для сценариев: перезапуск, пропуск тика, быстрая новая сессия, реконнект.
2. Живая проверка на хосте с OpenVPN: `kill -TERM` сборщика посреди передачи и повторный запуск, сравнение `clients.total_bytes_*` с последними значениями в статусе; остановка OpenVPN, статус клиентов становится `Disconnected` не позже `status_stale_seconds`.
3. Нативный запуск через `update.sh` на тестовом хосте (бэкап, перезапуск службы, откат).
## 6. Совместимость, выкат, откат
- Схема БД и формат API не меняются, миграций нет.
- Единственное видимое изменение: `connected_since` в `/api/v1/sessions` становится реальным временем начала сессии в UTC (раньше: локальное время первого наблюдения демоном). UI это поле не использует (проверено поиском по `APP_UI/src`).
- Однократный эффект обновления: строки старого снимка `active_sessions` не совпадают с новыми ключами, подключённые в момент обновления сессии получают базовую линию (прирост 0 за первый тик). Это то же, что происходит сейчас при каждом перезапуске.
- Выкат: обычное обновление (`deploy/native/update.sh`, `deploy/docker/update.sh`): код заменяется, сборщик перезапускается. Откат: автоматический откат обновления или возврат прежнего файла; данные в БД остаются совместимыми в обе стороны.
## 7. Риски
| Риск | Мера |
|---|---|
| OpenVPN пишет файл статуса не тем форматом (v1 или v3) | формат v2 задаёт шаблон `server.conf.j2`; при недоступном `time_t` работает запасная эвристика с предупреждением |
| Рассинхрон часов хоста и `connected_since` | запас `2 × интервал` при сравнении с запуском демона; часы одного хоста |
| Смешанное чтение (начало нового кадра + хвост старого, в конце старый `END`) не отличить по `END` | льготный период кэша гасит двойной учёт; смешанный кадр не может одновременно изменить ключи сессий |
| Зависший цикл с ошибками выглядит «здоровым» (healthcheck проверяет только наличие процесса) | в плане: ERROR в логе с числом подряд сбоев; heartbeat для healthcheck вынесен в «вне объёма» |
| Больше состояния в памяти | кэш по ключу сессии, размер порядка числа клиентов, удаление после льготного периода |
## 8. Критерии приёмки
- Пять тестов зелёные; на старом коде тесты 1-4 красные.
- Демон переживает исключение в цикле и корректно завершается по `SIGTERM` (проверено тестом и вручную).
- Новая сессия с первым кадром ≥ 10 МБ учтена полностью.
- Перезапуск демона не теряет и не дублирует трафик у подключённых клиентов при наличии снимка.
- Рваный кадр не меняет ни БД, ни кэш.
- Документация и `config.ini` обновлены, `DOCS/Changes/2026-10-05_Gatherer_Reliability.md` содержит факт выполнения и результаты проверки.
## 9. Оценка
**M**: 1,5-2 дня (каркас тестов и шаги 1-6 около 1,5 дня, документация и живая проверка около полудня).
## 10. Вне объёма
Атомарность трёх записей цикла (учёт, история, агрегация) в одной транзакции (ARCH-06); heartbeat для healthcheck; сглаживание мигания статуса клиента при рваном чтении; WAL и `busy_timeout`; вынос чтения конфигурации в общий модуль (ARCH-01).
## 11. Решения, которые нужны от вас
Если возражений нет, берутся значения по умолчанию.
| Вопрос | По умолчанию |
|---|---|
| Принять однократную базовую линию для сессий, подключённых в момент обновления | да |
| Менять смысл `connected_since` (реальное начало сессии, UTC) | да |
| Включить шаг 6 (свежесть файла, BUG-02d), он шире исходной находки | да |
| Новые ключи конфигурации и их значения (`3`, `60`, `6`) | да |
@@ -0,0 +1,51 @@
# Ключ подписи JWT: отказ запуска при слабом ключе (итог, 2026-10-05)
План: [2026-10-05_JWT_Secret_Fail_Closed_PLAN.md](2026-10-05_JWT_Secret_Fail_Closed_PLAN.md). Закрыта находка SEC-01 [отчёта анализа кода](../code_review/2026-10-05_1607Z_Codebase_Analysis.md).
## Что сделано
| Область | Изменение |
|---|---|
| Правило ключа | `APP_CORE/secret_key.py` и `APP_PROFILER/utils/secret_key.py` (идентичные копии): `resolve_secret_key(env, ini_value, legacy_env)` возвращает `(ключ, источник)` или бросает `SecretKeyError`. Ключ не пустой, не содержит `change-me` и `changeme`, длина не меньше 32. Встроенного значения по умолчанию нет |
| Core | проверка в начале `OpenVPNAPI.__init__`, до БД и создания администратора; при ошибке `CRITICAL` и выход с кодом 1 |
| Profiler | `utils/auth.py`: `logging` вместо `print`, при плохом ключе `CRITICAL` и `SystemExit(1)` при импорте; ветки про `OVPMON_SECRET_KEY` убраны |
| Старая переменная | если задана `OVPMON_SECRET_KEY` (её приложение никогда не читало), сообщение говорит, что её нужно переименовать в `OVPMON_API_SECRET_KEY` |
| `config.ini` | `secret_key =` пустой в обоих компонентах, с комментарием |
| Скрипты | `secret_problem` в `native/lib.sh` и `docker/lib.sh`; `native/install.sh` проверяет существующий env до установки пакетов; `native/update.sh` выпускает новый случайный ключ, если он отсутствует или слабый (сеансы сбрасываются один раз, значение ключа не печатается), до старта служб и внутри бэкапа; `docker/lib.sh: check_env_file` (вызывается в фазе 0 `install.sh` и `update.sh`); `allinone/entrypoint.sh` со встроенной проверкой |
| Тесты | `conftest.py` в обоих компонентах (ключ для тестов); 5 новых тестов: 2 в Core, 3 в Profiler |
| Документация | `Configuration.md`, `Containers/Reference.md` и `Troubleshooting.md`, `System_Services/Reference.md` и `Troubleshooting.md`, `Security_Architecture.md`, README компонентов и корневой |
Схема БД не менялась. Режим «ephemeral dev key» не добавлялся (решение плана).
## Разработка и ревью
Код, скрипты, тесты и документацию написал субагент без запуска чего-либо. Ревью и проверки выполнены отдельно. Замечание ревью: субагент случайно убрал пробел в `native/install.sh` (`&&[`), исправлено. Остальные отклонения субагента (проверка пробельного ключа в entrypoint, уточнение комментария в `config.ini`) приняты.
## Проверка
| Проверка | Результат |
|---|---|
| `pytest` Core | 14 из 14 (7 миграций, 5 сборщик, 2 ключ) |
| `pytest` Profiler | 14 из 16; 2 падения прежние: устаревшие `test_server_process.py` (404, находка отчёта о коде, этой доработкой не затронуты) |
| Живой запуск Core: нет ключа, значение по умолчанию, короткий, только `OVPMON_SECRET_KEY` | во всех четырёх отказ с кодом 1, БД не создана; хороший ключ: запуск на порту |
| Живой запуск Profiler (`uvicorn`): нет ключа, значение по умолчанию | отказ с кодом 1 и сообщением; хороший ключ: запуск |
| `secret_problem` на матрице значений (хороший, ровно 32, пустой, пробелы, значение по умолчанию, `ChangeMe`, 31) под dash, bash, busybox ash | все совпадения; значение ключа в сообщения не попадает; обе копии идентичны |
| Встроенная проверка `entrypoint.sh` под dash и busybox ash | хороший принят, три плохих отказ с понятным текстом |
| Фрагмент `update.sh` на копиях env (по умолчанию, короткий, нет строки, хороший) | новый ключ 64 символа, режим 600, остальные ключи сохранены, повторный запуск ничего не меняет, хороший ключ не тронут, значение в вывод не попадает |
| `bash -n`, `dash -n`, `shellcheck` | синтаксис чистый, новых замечаний нет (число совпадает с `HEAD`) |
| `pyflakes` | новых замечаний нет |
| `grep` строки `ovpmon-secret-change-me` | только в `secret_key.py` и тестах (по плану) |
| Ссылки документации | 67 файлов, 0 проблем |
## Не проверялось
- `install.sh` и `update.sh` целиком на живых Alpine, Debian и Ubuntu (проверены логика и фрагмент на копиях).
- Контейнеры: `install.sh` и `update.sh` с `JWT_SECRET=changeme`, сборка образа и вариант B (приложение отказывает на уровне процесса).
- Gunicorn: «Worker failed to boot» при `SystemExit` в `OpenVPNAPI()` на уровне модуля проверен только по коду, не запуском.
## Остаточные риски и замечания
- Профайлер на успешном старте не пишет строку об источнике ключа: `setup_logging()` вызывается после импорта `utils.auth`. Отказ виден (через `lastResort` в stderr), успех нет.
- Хосты, у которых ключ был только в `config.ini`, после `update.sh` получат ключ в env (приоритет у env), сеансы сбросятся один раз.
- Откат на старый код снова допускает ключ по умолчанию: после отката проверьте ключ вручную.
- Остаются две копии правила на Python и три на shell (ARCH-01, ARCH-03).
@@ -0,0 +1,140 @@
# Ключ подписи JWT: отказ запуска при слабом ключе (план, 2026-10-05)
Источник: [отчёт анализа кода](../code_review/2026-10-05_1607Z_Codebase_Analysis.md), находка **SEC-01** (высокая). Код меняется в `APP_CORE`, `APP_PROFILER`, скриптах `deploy/`, документации. Схема БД не меняется.
## 1. Проблема
Оба API подписывают и проверяют токены общим ключом HS256. Если ключ не задан, они работают с публично известной строкой `ovpmon-secret-change-me`: Core молча (`APP_CORE/openvpn_api_v3.py:53`), Profiler с предупреждением в `print` (`APP_PROFILER/utils/auth.py:11-14`). Та же строка лежит в поставляемых `config.ini` (`APP_CORE/config.ini:5`, `APP_PROFILER/config.ini:4`). Знание этой строки позволяет подделать токен администратора без пароля и 2FA.
Штатные установки ключ задают (установщики и compose дают случайный), поэтому риск остаётся при: ручном и dev-запуске, ошибке конфигурации (пустая переменная, потерянный `.env`), хостах, настроенных по прежнему руководству.
Найдено при разборе:
| Находка | Где |
|---|---|
| Переменная `OVPMON_SECRET_KEY` (из удалённого ныне руководства `General/Deployment.md`) приложением **не читается**: ключ берётся только из `OVPMON_API_SECRET_KEY`. Профайлер при этом печатает «Using SECRET_KEY from OVPMON_SECRET_KEY» и всё равно использует значение по умолчанию. Хост, настроенный по тому руководству, мог работать на известном ключе | `utils/auth.py:20-21` |
| Compose проверяет только «не пусто» (`${JWT_SECRET:?...}`): `JWT_SECRET=changeme` проходит | `docker-compose*.yml` |
| Установщик и обновление не проверяют качество уже существующего ключа в `/etc/ovpmon/env` | `deploy/native/install.sh:299`, `update.sh` |
## 2. Решение
### 2.1 Правило проверки ключа
Ключ принимается, если выполнены **все** условия:
1. не пустой и не состоит из пробелов;
2. не равен `ovpmon-secret-change-me` и не содержит `change-me` или `changeme` (без учёта регистра);
3. длина не меньше 32 символов (установщики выдают 64 hex-символа; 32 байта это ориентир для HS256).
Источник ключа: **только** переменная окружения `OVPMON_API_SECRET_KEY` либо значение `[api] secret_key` в `config.ini`; **встроенного значения по умолчанию нет**. Порядок прежний: переменная окружения важнее файла.
### 2.2 Поведение при плохом ключе
- Core и Profiler **не запускаются**: понятное сообщение в лог (без значения ключа), код выхода 1, порт не открывается.
- Сообщение называет причину (не задан, значение по умолчанию, слишком короткий), источник и способ исправления (`openssl rand -hex 32`, имя переменной, где её задать для данной установки).
- Если задана `OVPMON_SECRET_KEY`, а `OVPMON_API_SECRET_KEY` нет, сообщение прямо говорит, что эта переменная не используется и как переименовать.
- При хорошем ключе в лог пишется только источник («environment» или «config.ini»), как сейчас у профайлера, но через `logging`, не `print`.
### 2.3 Реализация в коде
| Файл | Изменение |
|---|---|
| `APP_CORE/secret_key.py` (новый, около 30 строк) | чистая функция `resolve_secret_key(env, ini_value)`: возвращает ключ или бросает `SecretKeyError` с сообщением; сама ничего не логирует и не завершает процесс |
| `APP_PROFILER/utils/secret_key.py` (новый) | та же функция (две копии, как и остальной общий код компонентов: общий модуль между образами пока невозможен, см. ARCH-01) |
| `APP_CORE/openvpn_api_v3.py:53` | вместо `get_config_value(..., fallback=...)` вызвать `resolve_secret_key`; при `SecretKeyError` лог `CRITICAL` и `SystemExit(1)` до инициализации БД и создания администратора |
| `APP_PROFILER/utils/auth.py` | `get_secret_key()` через ту же функцию, `print` заменить `logging`, убрать ветки с `OVPMON_SECRET_KEY`; модуль при импорте бросает ошибку, `uvicorn` завершается |
| `APP_CORE/config.ini`, `APP_PROFILER/config.ini` | `secret_key =` пустым, с комментарием «задайте OVPMON_API_SECRET_KEY или здесь; минимум 32 символа» |
| `main.py` профайлера | без изменений (ошибка возникает при импорте `utils.auth`) |
### 2.4 Скрипты развёртывания
| Где | Изменение |
|---|---|
| `deploy/native/lib.sh` | функция `secret_problem KEY` (те же правила 2.1, печатает причину и возвращает 1) |
| `deploy/native/install.sh` | в предполётной проверке: если `/etc/ovpmon/env` уже существует, проверить его ключ и остановиться с понятным сообщением до установки пакетов; новый env по-прежнему получает случайный ключ |
| `deploy/native/update.sh` | в фазе 6 (файлы) рядом с добавлением отсутствующих ключей: если `OVPMON_API_SECRET_KEY` в env отсутствует или не проходит проверку, выпустить новый случайный (`openssl rand -hex 32`, запасной путь `/dev/urandom` как в установщике), записать `kv_set`, режим 600, и записать в лог и итоговую сводку: **все сеансы будут сброшены**. Файл env входит в бэкап и откат фазы 6, сервисы стартуют уже с рабочим ключом |
| `deploy/docker/lib.sh:256` | к проверке «`JWT_SECRET` не пуст» добавить `secret_problem`; `install.sh` и `update.sh` останавливаются до сборки |
| `deploy/allinone/entrypoint.sh:19` | та же проверка после сопоставления `JWT_SECRET` и `OVPMON_API_SECRET_KEY` (отдельная копия в 6 строк: образу нельзя source-ить `lib.sh`) |
| `docker-compose*.yml` | без изменений (`:?` остаётся первой линией защиты); вариант B ловит слабый ключ на уровне приложения (контейнер падает с сообщением) |
Установщики уже генерируют 64 hex-символа, поэтому штатный путь не меняется.
### 2.5 Решение, которое осознанно **не** принимается
Режим «ephemeral dev key» (случайный ключ на процесс при флаге разработчика) отклонён: ещё одна ветка кода ради удобства dev, а два API всё равно должны делить ключ. Разработчик задаёт переменную явно; команда добавляется в README компонентов.
## 3. Шаги
| # | Шаг | Результат |
|---|---|---|
| 1 | `resolve_secret_key` в обоих компонентах + тесты (раздел 4), красные на старом коде | правило проверено |
| 2 | Подключить в Core и Profiler, убрать значение по умолчанию и `print`, обнулить `secret_key` в обоих `config.ini` | отказ запуска |
| 3 | `conftest.py` в `APP_PROFILER` и `APP_CORE`: `os.environ.setdefault("OVPMON_API_SECRET_KEY", <64 символа>)` до импорта приложения (иначе существующие тесты импортируют `main` и падают) | прежние тесты зелёные |
| 4 | `secret_problem` в `native/lib.sh` и `docker/lib.sh`; проверки в `install.sh`, `update.sh`, `docker/install.sh`, `docker/update.sh`, `allinone/entrypoint.sh` | проверка во всех путях развёртывания |
| 5 | Документация: `General/Configuration.md` (правило ключа), `Deployment/Containers/Reference.md` и `Troubleshooting.md`, `Deployment/System_Services/Reference.md` и `Troubleshooting.md` (сообщения и действия), `APP_CORE/README.md`, `APP_PROFILER/README.md` (команда для dev), `General/Security_Architecture.md` (абзац), корневой README (строка в «Security defaults») | документация актуальна |
| 6 | Сводка `2026-10-05_JWT_Secret_Fail_Closed.md`, строка в `DOCS/Changes/README.md` | отчёт |
## 4. Тесты (минимум)
По два теста на компонент (`APP_CORE/test_secret_key.py`, `APP_PROFILER/test_secret_key.py`), на самой функции без запуска серверов:
1. **Отказ:** `None`, пустая и пробельная строка, `ovpmon-secret-change-me`, `Change-Me-Please`, 31 символ, при заданной `OVPMON_SECRET_KEY` без `OVPMON_API_SECRET_KEY` (подсказка в сообщении) дают `SecretKeyError`; в тексте ошибки нет значения ключа.
2. **Приём и приоритет:** 64 hex принимается; значение из окружения важнее `config.ini`; значение по умолчанию в `config.ini` при хорошем ключе в окружении не мешает.
Для профайлера один дополнительный тест: импорт `utils.auth` при плохом ключе завершается ошибкой, при хорошем успешен (через `importlib.reload` и `monkeypatch`). Итого пять тестов.
## 5. Проверка вне модульных тестов
1. Запуск `python openvpn_api_v3.py` и `uvicorn main:app` в изолированном каталоге: без ключа, с ключом по умолчанию, с коротким, с хорошим. Ожидание: три отказа с кодом 1 и сообщением, один нормальный старт.
2. Стенд на шелл-функциях: `secret_problem` на матрице значений; фрагменты `update.sh` (генерация и запись в env с режимом 600) на копии env-файла в `scratchpad`.
3. Прогон `bash -n` и `shellcheck` на изменённых скриптах; тесты обоих компонентов целиком.
4. На живом хосте (вне этой сессии): `update.sh` на хосте с ключом по умолчанию в env, на хосте с короткой, на хосте с хорошей; контейнеры: `JWT_SECRET=changeme` отказывает на установке.
## 6. Совместимость, выкат, откат
| Ситуация после обновления | Результат |
|---|---|
| Хост с хорошим ключом (нормальный случай) | без изменений, сеансы остаются |
| Нативный хост: ключа в env нет или он слабый | `update.sh` выпускает новый, **один раз сбрасывает все сеансы**, об этом сказано в выводе |
| Нативный хост, ключ только в `config.ini` (ручная установка) | считается «ключа в env нет»: `update.sh` выпустит ключ в env (он важнее файла), сеансы сбросятся один раз |
| Контейнеры со слабым `JWT_SECRET` | `install.sh` и `update.sh` останавливаются до сборки; вручную: контейнер падает с сообщением |
| Разработчик | задаёт `OVPMON_API_SECRET_KEY`; тесты получают ключ из `conftest.py` |
Откат: автоматический откат обновления (env входит в бэкап); возврат старого кода снова разрешает ключ по умолчанию, поэтому после отката проверьте ключ вручную.
## 7. Риски
| Риск | Мера |
|---|---|
| Служба не стартует после обновления из-за слабого ключа | `update.sh` исправляет до старта (фаза 6); при ручном обновлении кода сообщение содержит команду |
| Два API получили разные ключи (один из env, другой из `config.ini`) | порядок источников у обоих одинаков; при отличии токены не проходят, как и раньше; отдельная проверка вне объёма |
| Ложные срабатывания проверки `change-me`/`changeme` на настоящем ключе | вероятность пренебрежимо мала для случайного ключа; сообщение объясняет причину |
| Дублирование проверки в трёх shell-местах и двух Python-копиях | функции короткие (5-30 строк), покрыты тестами и стендом; общий модуль вне объёма (ARCH-01, ARCH-03) |
| Ключ в `config.ini` внутри образа контейнера | поставляемый файл теперь без значения |
## 8. Критерии приёмки
- Без ключа, со значением по умолчанию, с коротким и с `changeme` оба API завершаются с кодом 1 и понятным сообщением; порт не открывается; значение ключа не попадает в лог.
- С хорошим ключом поведение прежнее, прежние тесты зелёные, новые пять тестов красные на старом коде и зелёные на новом.
- В поставляемых `config.ini` нет строки `ovpmon-secret-change-me`; `grep` по репозиторию (без записей об изменениях и отчёта) находит её только в сообщениях и тестах.
- Установщики и обновления обоих способов не пропускают слабый ключ; `update.sh` исправляет нативный хост и честно говорит о сбросе сеансов.
- Документация и сводка обновлены.
## 9. Оценка
**S-M**: около 1 дня (код и тесты полдня, скрипты и стенд полдня, документация и сводка пара часов).
## 10. Вне объёма
Раздельные ключи или асимметричная подпись для двух API (SEC-05); автоматическая проверка совпадения ключей двух API; отзыв токенов и срок жизни (SEC-04); ограничение попыток 2FA (SEC-02).
## 11. Решения, которые нужны от вас
Если возражений нет, берутся значения по умолчанию.
| Вопрос | По умолчанию |
|---|---|
| Минимальная длина ключа 32 символа | да |
| `update.sh` сам выпускает новый ключ вместо отказа (с однократным сбросом сеансов) | да |
| Без режима «ephemeral dev key» (разработчик задаёт переменную явно) | да |
| Сообщение с подсказкой при заданной `OVPMON_SECRET_KEY` | да |
+1 -1
View File
@@ -1,6 +1,6 @@
# nftables script for system-service installs: summary (2026-10-05)
Plan: [2026-10-05_NFT_Firewall_PLAN.md](2026-10-05_NFT_Firewall_PLAN.md). Guide: [Firewall, NAT and forwarding](../Deployment/Scenario2_System_Services.md#firewall-nat-and-forwarding).
Plan: [2026-10-05_NFT_Firewall_PLAN.md](2026-10-05_NFT_Firewall_PLAN.md). Guide: [Firewall, NAT and forwarding](../Deployment/System_Services/Firewall.md).
## Done
@@ -1,6 +1,6 @@
# Scenario 1: containers, variants A and B (2026-10-05)
Phase 2 of [Deployment_Scenarios_PLAN](2026-10-05_Deployment_Scenarios_PLAN.md). Guide: [Scenario 1: containers](../Deployment/Scenario1_Containers.md).
Phase 2 of [Deployment_Scenarios_PLAN](2026-10-05_Deployment_Scenarios_PLAN.md). Guide: [Scenario 1: containers](../Deployment/Containers/README.md).
## What was added
@@ -1,6 +1,6 @@
# Scenario 2: system services, Alpine, Debian, Ubuntu (2026-10-05)
Phase 3 of [Deployment_Scenarios_PLAN](2026-10-05_Deployment_Scenarios_PLAN.md). Guide: [Scenario 2: system services](../Deployment/Scenario2_System_Services.md).
Phase 3 of [Deployment_Scenarios_PLAN](2026-10-05_Deployment_Scenarios_PLAN.md). Guide: [Scenario 2: system services](../Deployment/System_Services/README.md).
## What was added
+22
View File
@@ -0,0 +1,22 @@
# Changes and results
Every change has a plan (`*_PLAN.md`) before it and a summary of what was done after it. Newest last. The guides that came out of the changes are linked in the last column.
| Date | Change | Document |
|---|---|---|
| 2026-09-30 | Security hardening: path traversal, 2FA token bypass, CORS, log leak, HTTPS, SSH, fail2ban | [Security hardening](2026-09-30_Security_Hardening.md) |
| 2026-09-30 | Admin username change (API + UI), no built-in default admin | [Admin username change](2026-09-30_Admin_Username_Change.md) |
| 2026-09-30 | Validation of server/PKI settings (config injection into the root-written OpenVPN config) | [Settings validation](2026-09-30_Settings_Validation.md) |
| 2026-09-30 | API services run as an unprivileged user; root helper validates and installs the OpenVPN config, publishes the CRL | [Privilege separation](2026-09-30_Privilege_Separation.md) (includes CRL publishing for `crl_verify`) |
| 2026-10-04 | Certificates page: clickable rows, profile details modal with a saved note (`PUT /profiles/{id}/note`) | [Profile notes](2026-10-04_Profile_Notes.md) (includes the compact modal and the note tooltip on the client name) |
| 2026-10-04 | PKI initialization runs in the background: status endpoint, progress on the PKI page, protection against a second start | [Async PKI init](2026-10-04_Async_PKI_Init.md) |
| 2026-10-04 | Toast notifications moved to the bottom-right corner, shared component, light/dark themes | [Toast notifications](2026-10-04_Toast_Notifications.md) |
| 2026-10-04 | Server setup is closed until the PKI is initialized (VPN menu lock, 409 for configure/start/create client, Clear PKI blocked while OpenVPN runs) | [PKI dependency guard](2026-10-04_PKI_Dependency_Guard.md) |
| 2026-10-05 | Database migrations with backup, integrity checks and downgrade protection; standalone `migrate.py` (phase 1 of install/update scenarios) | [Database migrations](2026-10-05_DB_Migrations.md) |
| 2026-10-05 | Scenario 1: container install and update, variant A (one container) and B (per component); backup, restore, automatic rollback | [Containers guide](../Deployment/Containers/README.md) · [change](2026-10-05_Scenario1_Containers.md) |
| 2026-10-05 | Scenario 2: install and update as system services on Alpine, Debian, Ubuntu; helper config for systemd; backup, restore, automatic rollback | [System services guide](../Deployment/System_Services/README.md) · [change](2026-10-05_Scenario2_System_Services.md) |
| 2026-10-05 | nftables script for system-service installs: masquerade, TCP MSS clamping (path MTU) and TTL for traffic from the VPN network to all other networks; boot service | [Firewall, NAT and forwarding](../Deployment/System_Services/Firewall.md) · [plan](2026-10-05_NFT_Firewall_PLAN.md) · [change](2026-10-05_NFT_Firewall.md) |
| 2026-10-05 | Documentation refactoring: general information, installation methods, details per method; a newcomer path (choose, install, first steps); host-specific Hysteria2/Timeweb records moved out of the general documentation | [plan](2026-10-05_Docs_Refactoring_PLAN.md) · [change](2026-10-05_Docs_Refactoring.md) |
| 2026-10-05 | Комплексный анализ кодовой базы на основе графа знаний: безопасность, корректность, архитектура, тесты, рекомендации P0-P2 | [plan](2026-10-05_Code_Review_PLAN.md) · [change](2026-10-05_Code_Review.md) · [отчёт](../code_review/2026-10-05_1607Z_Codebase_Analysis.md) |
| 2026-10-05 | Сборщик трафика: устойчивый цикл, остановка по сигналу, проверка целостности и свежести файла статуса, учёт сессий по времени их начала (BUG-02, BUG-03) | [plan](2026-10-05_Gatherer_Reliability_PLAN.md) · [change](2026-10-05_Gatherer_Reliability.md) |
| 2026-10-05 | Ключ подписи JWT без значения по умолчанию: Core и Profiler не запускаются при пустом, слабом или заимствованном из примера ключе; проверка в установщиках, `update.sh` выпускает ключ при необходимости (SEC-01) | [plan](2026-10-05_JWT_Secret_Fail_Closed_PLAN.md) · [change](2026-10-05_JWT_Secret_Fail_Closed.md) |
+4
View File
@@ -214,6 +214,10 @@ Real-time list of currently connected clients.
### `GET /sessions`
Field notes:
- `connected_since`: the real start of the session as reported by OpenVPN (`Connected Since (time_t)` of the status file), in **UTC**, format `YYYY-MM-DD HH:MM:SS`. It does not depend on when the gatherer first saw the session (older versions returned the local time of the first observation). If OpenVPN does not report the value, the time of the first observation (UTC) is used.
- `last_seen`: time of the last gatherer tick that saw the session (gatherer host local time).
#### Example Response
```json
{
+20 -4
View File
@@ -8,13 +8,29 @@ The gatherer runs a continuous loop (default interval: **10 seconds**).
### A. Log Parsing
- **Source**: `/var/log/openvpn/openvpn-status.log` (Status File v2, CSV format).
- **Target Fields**: `Common Name`, `Real Address`, `Bytes Sent`, `Bytes Received`.
- **Target Fields**: `Common Name`, `Real Address`, `Bytes Sent`, `Bytes Received`, `Connected Since (time_t)`.
- **Filtering**: Only lines starting with `CLIENT_LIST`.
### B. Delta Calculation (`update_client_status_and_bytes`)
The log provides *lifetime* counters for a session. The gatherer calculates the traffic *delta* (increment) since the last check.
- **Logic**: `Increment = Current Value - Last Saved Value`.
- **Reset Detection**: If `Current Value < Last Saved Value`, it assumes a session/server restart and counts the entire `Current Value` as the increment.
The log provides *lifetime* counters for a session. The gatherer calculates the traffic *delta* (increment) since the last check. A session is identified by the key `(common_name, real_address, connected_since_ts)`, where `connected_since_ts` is the `Connected Since (time_t)` column (index 8) of `CLIENT_LIST`. A reconnect always gets a new `connected_since_ts` and therefore a new session.
| Situation | Increment |
|-----------|-----------|
| Key is in the in-memory cache | `Current - Previous`. If a counter decreased (same key), it is treated as a reset and the whole `Current` is counted. |
| Not in cache, key is in the baseline (snapshot of `active_sessions` loaded at start, or a session recently dropped from the cache) | `Current - Baseline` (traffic during a daemon downtime is counted, nothing is counted twice). |
| Not in cache, session started after the daemon start (with a margin of `2 x check_interval`) | New session: the whole `Current` value, whatever its size. For a client seen for the first time the `clients` row is created with these totals (the first frame is not lost). |
| Not in cache, session older than the daemon and no snapshot (first start after an update, lost DB) | Baseline: increment `0`, a WARNING with the client name is logged (the only case of lost traffic, once per session). |
| `connected_since_ts` is missing or not a number (non-standard status file) | Fallback heuristic: counters below 10 MB are counted as a new session, otherwise increment `0`; a WARNING is logged. |
Cache changes are collected in a temporary structure and applied only after the database transaction is committed. If the transaction fails, the cache is unchanged and the next tick counts the difference for the whole interval.
### B1. Read Validity, Grace Period, Restart and Shutdown
- **Validity** (`parse_status`): the status file must contain a `TITLE` line, a `TIME,<text>,<epoch>` line and end with `END`. A missing file, a read error or an incomplete file (read while OpenVPN rewrites it) makes the gatherer **skip the tick entirely**: the database and the cache are not touched, and the next valid tick counts the difference for the whole interval. After `status_invalid_max` (default 6) skipped ticks in a row the message is logged at ERROR level.
- **Freshness**: if `TIME` is older than `status_stale_seconds` (default 60 s), OpenVPN is considered stopped: there are no clients, all clients become `Disconnected`, sessions leave the cache via the grace period. A valid, fresh file without `CLIENT_LIST` lines simply means no clients.
- **Grace period**: a session missing from the status is not dropped at once. Its `missing_ticks` counter grows each tick and the session is removed from the cache when it reaches `session_grace_ticks` (default 3, about 30 s). A session that comes back with the same key continues without double counting. A removed session is remembered (last counters, 1 hour) so that a late return with the same key is still counted as a continuation.
- **Restart**: at start the gatherer loads `active_sessions` as the baseline (see the table above). `active_sessions.connected_since` stores the real session start in UTC (`YYYY-MM-DD HH:MM:SS`), which is also what `/sessions` returns.
- **Resilience and shutdown**: every cycle runs in `try/except`; a failure is logged with a traceback and does not stop the daemon. After consecutive failures the pause grows as `min(interval * 2^n, 60)` seconds and resets after a successful cycle. `SIGTERM`/`SIGINT` only set a stop flag: the current cycle is finished, the pause is interrupted and the process exits normally (code 0).
- **Settings** (`[openvpn_monitor]`, can be overridden by `OVPMON_OPENVPN_MONITOR_*`): `check_interval` (>= 1), `session_grace_ticks` (>= 0), `status_stale_seconds` (>= 1), `status_invalid_max` (>= 1). An invalid value stops the start with a clear message and exit code 1.
### C. Rate Calculation
- **Speed**: Calculated as `Increment * 8 / (Interval * 1_000_000)` to get **Mbps**.
+118
View File
@@ -0,0 +1,118 @@
# Containers: update, backup, restore, rollback
Day-2 operations of the container installation. Every update takes a verified backup first and rolls back automatically on failure. Install: [Containers](README.md).
## Update
```bash
deploy/docker/update.sh # variant and project from .ovpmon-deploy
deploy/docker/update.sh --yes # no questions
deploy/docker/update.sh --no-pull # sources already in place / offline (no git pull, no base image refresh)
deploy/docker/update.sh --rollback # manual rollback to the newest backup
```
Each phase is logged separately:
| Phase | What happens | If it fails |
|---|---|---|
| 0 Preflight | state file, `.env`, compose configuration, running stack, the other variant not running, `db_data` volume exists, free space | nothing was changed |
| 1 **Backup** | all five volumes → `backups/<UTC timestamp>/*.tar.gz` through a throwaway `alpine` container (volumes mounted read-only), copy of `.env` (mode 600), record of the current image IDs, `SHA256SUMS`; every archive is verified (`tar -tzf`) | the update is **refused**, nothing was changed |
| 2 Sources | `git pull --ff-only` when the directory is a git checkout and `--no-pull` was not given | nothing was changed |
| 3 Build | current images are tagged `<name>:previous`, then the new images are built while the old stack keeps running | nothing was changed, the old version still runs |
| 4 Stop | the application containers are stopped (volumes are kept); a second, final backup of the volumes is taken now that nothing writes to the databases | automatic rollback |
| 5 **Database migration** | a separate step, see below | automatic rollback, nothing is started |
| 6 Start | `up -d` with the new images, wait for the health checks | automatic rollback |
Old backups: the newest 5 are kept; older ones are pruned only after a successful update. Volumes are never deleted and `down -v` is never used. The new `deploy/docker/*.sh` take effect on the next run (the running script is not replaced).
### Database migration as its own step
After the containers are stopped and before any new component starts, `update.sh` runs, for each database, a one-off container **from the new image with the same volumes**:
| Variant | Profiler database | Monitoring database |
|---|---|---|
| B | `app-profiler` image: `cd /app && python migrate.py` | `app-api` image: `cd /app && python migrate.py` |
| A | `ovpmon` image: `cd /app/APP_PROFILER && python migrate.py` | `ovpmon` image: `cd /app/APP_CORE && python migrate.py` |
For each database it runs `python migrate.py --check` (exit 0 up to date, 2 pending, 1 error or database newer than the code), applies the pending migrations with `python migrate.py` and checks again. The reports are printed. A failure or a "too new" database aborts **before anything is started** and triggers the rollback.
What the migration does (details: [Database migrations](../../General/Database_Migrations.md)): versioned, additive-only changes (`CREATE ... IF NOT EXISTS`, `ADD COLUMN` with defaults), never a drop or rewrite; before any change an integrity check and a consistent copy `<db>.bak-<UTC timestamp>` next to the database (newest 5 kept); after the change an integrity check and a comparison of row counts; on a mismatch everything is rolled back; a database newer than the application is not touched.
The migration also runs by itself when a service starts (variant B: profiler and API; variant A: the entrypoint, before `supervisord`), so a plain `docker compose up -d --build` is safe too. `update.sh` only makes it a visible, separate, controlled step.
### Automatic rollback
On any failure in phases 4 to 6: the stack is stopped, all five volumes are restored from the backup of this run, the `:previous` images are started (through a generated `compose.previous.yml` in the backup directory) and the result is reported with the backup path. If the rollback itself fails, the message says where the backup is and how to retry (`update.sh --rollback`, or `restore.sh`).
After a rollback the stack runs on the `:previous` images; the next `update.sh` run builds again and recreates the containers on the new images.
## Backup, restore, rollback
### Backup
```bash
deploy/docker/backup.sh # live backup of the five volumes -> backups/<UTC timestamp>/
deploy/docker/backup.sh --stop # stops the containers during the copy (consistent SQLite files), starts them again
deploy/docker/backup.sh --keep 14 # afterwards keep the newest 14
```
Cron example (nightly, consistent, 14 kept): `30 3 * * * /opt/ovpmon/deploy/docker/backup.sh --stop --keep 14 >> /var/log/ovpmon-backup.log 2>&1`.
A live backup copies the PKI and configuration reliably; a database file that is written at that very moment may be caught half-way, which `--stop` avoids (and `update.sh` always backs up a stopped stack for its final snapshot). The backup holds private keys, password hashes and the secret: the directory is mode 700, the files mode 600. Store copies off the host and protect them.
Manual equivalent for one volume (project `ovpmon`):
```bash
mkdir -p backups/manual
docker run --rm -v ovpmon_db_data:/data:ro -v "$PWD/backups/manual":/backup alpine \
tar -czf /backup/db_data.tar.gz -C /data .
```
### Restore
```bash
deploy/docker/restore.sh backups/20261005T101500Z # asks, stops the stack, restores, prints the start command
deploy/docker/restore.sh backups/20261005T101500Z --yes --start
```
It verifies the archives first, saves the current content to `backups/<timestamp>-pre-restore`, empties each volume and fills it from the archive. Volumes are not removed. `.env` is not touched (a difference to the copy in the backup is reported). Manual equivalent:
```bash
docker compose stop # or: -f docker-compose.allinone.yml
docker run --rm -v ovpmon_db_data:/data -v "$PWD/backups/20261005T101500Z":/backup:ro alpine \
sh -c 'rm -rf /data/* /data/.[!.]* /data/..?* && tar -xzf /backup/db_data.tar.gz -C /data'
docker compose up -d
```
A single database can also be put back from its migration backup in `db_data`: stop the stack, copy `<db>.bak-<timestamp>` over the database file, start the OLD release (see [Database migrations](../../General/Database_Migrations.md)).
### Rollback to the previous version
```bash
deploy/docker/update.sh --rollback
```
After confirmation: stop, restore all volumes from the newest complete backup (current content saved first), start the images recorded in that backup. Use it when an update completed but the new version misbehaves. Data created after that backup is lost (it is in the `-pre-restore` copy).
## Switching between variants
Both variants use the same volumes, so with the same project name the data can be used by the other variant: stop the running one (`docker compose [-f docker-compose.allinone.yml] stop`), take a backup, run `install.sh --variant <other> --project <same name>`. This path has not been tested in a real run; keep the backup. Starting both at once is refused.
## What is preserved on update
| Item | On update |
|---|---|
| Databases (`db_data`) | Kept. Backed up twice (before and after the stop), migrated additively with their own `<db>.bak-*` copy; restored automatically if the update fails after the stop |
| PKI (`ovp_pki`): CA, keys, certificates, CRL | Kept, backed up. The easy-rsa scripts are copied only when the volume does not have them yet |
| Client profiles (`ovp_client_config`) | Kept, backed up |
| Server configuration (`ovp_config`) | Kept, backed up (the new image does not overwrite it) |
| OpenVPN logs and status file (`ovp_logs`) | Kept |
| `.env` (secret, ports) | Kept, copied into every backup |
| User sessions | Stay valid while `JWT_SECRET` is unchanged |
| Images | Replaced; the previous ones stay tagged `<name>:previous` |
| Containers | Recreated; running VPN sessions are interrupted and clients reconnect; the OpenVPN process has to be started again (see troubleshooting) |
| Container file system, `profiler.log`, `openvpn_gatherer.log` | Not kept (use `docker logs`) |
| Backups in `backups/` | The newest 5 kept, older ones pruned after a successful update; `-pre-restore` copies are never pruned automatically |
| Volumes | Never deleted by any script; `down -v` is never used |
Related: [Database migrations](../../General/Database_Migrations.md), [Deployment plan](../../Changes/2026-10-05_Deployment_Scenarios_PLAN.md).
+93
View File
@@ -0,0 +1,93 @@
# Containers (variants A and B)
Install the whole suite with Docker: nothing but Docker is needed on the host. This page: choose a variant, check the requirements, install. Next pages: [Operations](Operations.md) (update, backup, rollback), [Reference](Reference.md) (`.env`, ports, volumes), [Troubleshooting](Troubleshooting.md).
## Quick start
On a host with Docker (root or a member of the `docker` group):
```bash
git clone <repository> && cd OpenVPN-Monitoring-Simple
deploy/docker/install.sh --variant b # or --variant a, see the table below
```
The script prints the URL and the **administrator login and password (shown once)**. Open the URL, then follow [First steps](../First_Steps.md).
## Variants
Two variants, both installed and updated by the scripts in `deploy/docker/`:
| | Variant A: one container | Variant B: one container per component |
|---|---|---|
| Compose file | `docker-compose.allinone.yml` | `docker-compose.yml` |
| Containers | `ovp-allinone` (nginx, gunicorn, gatherer, uvicorn, OpenVPN under `supervisord`) | `ovp-ui`, `ovp-api`, `ovp-gatherer`, `ovp-profiler` |
| Image build | `deploy/allinone/Dockerfile` (build context: repository root) | one Dockerfile per component (`APP_UI`, `APP_CORE`, `APP_PROFILER`) |
| Choose it when | one host, simplest operation, one thing to start/stop/back up | you want to restart, scale or inspect components separately, or follow the usual one-process-per-container practice |
| Trade-off | a failing process is restarted by `supervisord`, the container stays up; one image to rebuild for any change | more moving parts, internal network `ovp-net` |
Both variants use the **same five named volumes with the same in-container paths**, the same environment variables and the same published ports. Backups look identical.
> **Only one variant can run per host.** Both publish the same host ports (`80/tcp`, `1194/udp` by default) and use fixed container names (`ovp-*`). The scripts refuse to start a variant while a container of the other one is running.
## Requirements
- Docker Engine with the compose plugin (`docker compose`, v2, preferred) or `docker-compose`.
- The Docker daemon running and usable by the user that runs the scripts (root, or a member of the `docker` group).
- Access to `/dev/net/tun` on the host and the `NET_ADMIN` capability (already set in the compose files).
- Free disk space: about 2 GB for images and builds, plus room for backups (the scripts check both).
- Internet access for the first build (base images, npm, pip) and for the backup helper image (`alpine:3`). For offline hosts see [Troubleshooting](Troubleshooting.md).
- `openssl` is optional (random secret otherwise comes from `/dev/urandom`).
## Install
Clone the repository, change into it and run the script (as root or a docker user):
```bash
# Variant B: one container per component
deploy/docker/install.sh --variant b
# Variant A: everything in one container
deploy/docker/install.sh --variant a
# Options
deploy/docker/install.sh --variant b --project ovpmon --http-port 8080 --vpn-port 1194 --admin-user admin
```
| Option | Meaning |
|---|---|
| `--variant a\|b` | required |
| `--project NAME` | compose project name = prefix of the volume names (default `ovpmon`: volumes `ovpmon_db_data`, ...) |
| `--http-port N` | host port of the UI (written to `.env` as `OVPMON_HTTP_PORT`, default 80) |
| `--vpn-port N` | host UDP port of OpenVPN (`OVPMON_VPN_PORT`, default 1194) |
| `--admin-user NAME` | login of the first administrator (default `admin`) |
What `install.sh` does:
1. **Preflight:** docker and compose, running daemon, the other variant is not running, no foreign container with the same names, ports free, free disk space.
2. **`.env`** next to the compose files, only if it does not exist: mode 600, random `JWT_SECRET`, initial administrator with a generated 24-character password. An existing `.env` is never overwritten (`--http-port` / `--vpn-port` only set their own keys in it).
3. **Build, start** (`docker compose up -d`), write the state file `.ovpmon-deploy` (variant and project; used by `update.sh`, `backup.sh`, `restore.sh`), wait up to 3 minutes for the health checks.
4. **Initial administrator:** when the users table is not empty, `OVPMON_INITIAL_ADMIN_*` are removed from `.env` and the container that reads them is recreated (variant B: `app-api`, variant A: `ovpmon`). If the table cannot be read or is empty, the lines stay in `.env` and a warning says so.
5. **Result:** URL, ports, and the administrator login and password. **The password is shown once** and stored nowhere else. `JWT_SECRET` is never printed.
Running it again is safe: it rebuilds and starts, keeps `.env`, and makes no new administrator.
Then follow [First steps](../First_Steps.md) (sign in, initialize the PKI, start the VPN server). Put TLS in front of the UI (see [Security](Troubleshooting.md#security)).
### Without the script
```bash
cat > .env <<EOT
JWT_SECRET=$(openssl rand -hex 32)
OVPMON_INITIAL_ADMIN_USER=admin
OVPMON_INITIAL_ADMIN_PASSWORD=<strong password>
EOT
chmod 600 .env
docker compose up -d --build # variant B
docker compose -f docker-compose.allinone.yml up -d --build # variant A
```
After the first start remove the two `OVPMON_INITIAL_ADMIN_*` lines from `.env` and recreate `app-api` (B) or `ovpmon` (A).
## Next
[First steps](../First_Steps.md) · [Operations](Operations.md) · [Reference](Reference.md) · [Troubleshooting](Troubleshooting.md) · [Choose another method](../README.md)
+49
View File
@@ -0,0 +1,49 @@
# Containers: reference
Configuration (`.env`), ports and volumes of the container installation. Install: [Containers](README.md).
## `.env` reference
| Variable | Required | Default | Meaning |
|---|---|---|---|
| `JWT_SECRET` | yes | none (compose refuses to start) | Signing key of both APIs (`OVPMON_API_SECRET_KEY`). At least 32 characters, no `change-me`/`changeme`: `install.sh`, `update.sh` and the all-in-one container refuse a weak value. Changing it logs every user out. Keep the same value across updates |
| `OVPMON_INITIAL_ADMIN_USER`, `OVPMON_INITIAL_ADMIN_PASSWORD` | first start only | empty | Seed for the first user, used only while the users table is empty. Removed by `install.sh` afterwards |
| `OVPMON_CORS_ORIGINS` | no | empty (off) | Comma-separated extra origins; the UI is same-origin behind nginx |
| `OVPMON_HTTP_PORT` | no | `80` | Host port of the UI |
| `OVPMON_VPN_PORT` | no | `1194` | Host UDP port of OpenVPN (the container side is always 1194) |
Variables of the scripts (environment of the shell, not `.env`): `OVPMON_BACKUP_DIR` (backup root, default `./backups`), `OVPMON_BACKUP_IMAGE` (helper image, default `alpine:3`), `OVPMON_HEALTH_TIMEOUT` (seconds, default 180), `OVPMON_MIN_FREE_MB` (docker data, default 2048), `OVPMON_MIN_FREE_BACKUP_MB` (backups, default 1024).
`OVPMON_VPN_PORT` changes only the host side of the mapping. If you change the OpenVPN port in the server settings of the UI, the client profiles carry that port; keep the two consistent.
## Ports
| Port | Published | Purpose |
|---|---|---|
| `${OVPMON_HTTP_PORT:-80}/tcp` | yes | UI and reverse proxy to both APIs (plain HTTP) |
| `${OVPMON_VPN_PORT:-1194}/udp` | yes | OpenVPN |
| `5001` (monitoring API), `8000` (profiler API) | no | variant B: `expose`d on `ovp-net` only; variant A: listen on `127.0.0.1` inside the container |
## Volumes: what is stored where
| Volume | Path in the container | Content | Mounted by (B) |
|---|---|---|---|
| `ovp_logs` | `/var/log/openvpn` | `openvpn-status.log` and OpenVPN logs | gatherer, profiler |
| `ovp_config` | `/etc/openvpn` | `server.conf` generated by the profiler | profiler |
| `ovp_pki` | `/app/easy-rsa` | easy-rsa scripts and `pki/` (CA, server and client keys and certificates, CRL, `ta.key`, `dh.pem`) | profiler |
| `ovp_client_config` | `/app/client-config` | generated client `.ovpn` files | profiler |
| `db_data` | `/app/db` | `ovpn_profiler.db`, `openvpn_monitor.db`, migration backups `*.db.bak-*` | gatherer, api, profiler |
Not stored in volumes (lost when the container is recreated): the container file system, `profiler.log` and `openvpn_gatherer.log` (written into the working directory), supervisor state. Application logs go to `docker logs`.
Volume names are `<project>_<volume>`; the scripts find them by the compose labels, so any project name works.
### Layout of variant A
The code is in `/app/APP_CORE` and `/app/APP_PROFILER`; the volumes are mounted at the same paths as in variant B (`/app/db`, `/app/easy-rsa`, `/app/client-config`, `/etc/openvpn`, `/var/log/openvpn`).
The profiler resolves `easy-rsa/` and `client-config/` relative to its working directory (`services/pki.py`, `routers/profiles.py`), and stores `client-config/<name>.ovpn` as a relative path in its database. In variant B that directory is `/app`. Variant A keeps it that way: **`supervisord` starts the profiler with working directory `/app`** (`uvicorn --app-dir /app/APP_PROFILER main:app`), so `/app/easy-rsa` and `/app/client-config` are the volumes. No symlinks are used, and the database paths are identical in both variants (so a volume set can be used by either variant). The monitoring API and the gatherer run with working directory `/app/APP_CORE`, where `config.ini` lives; their database path comes from `OVPMON_OPENVPN_MONITOR_DB_PATH=/app/db/openvpn_monitor.db`.
Processes in `ovp-allinone` (`deploy/allinone/supervisord.conf`, started in this order, all with `autorestart`, logs to stdout/stderr): `gatherer`, `api` (`gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app`), `profiler` (`uvicorn` on `127.0.0.1:8000`, no reload), `nginx`. OpenVPN is started by the profiler API on request (direct start inside containers), as in variant B.
`deploy/allinone/entrypoint.sh` runs before `supervisord`: secret mapping (`JWT_SECRET` → `OVPMON_API_SECRET_KEY` when only the first is set), `/dev/net/tun`, easy-rsa workspace (copied only when the volume does not have it yet), NAT and MSS rules without duplicates, the nginx configuration rendered from `APP_UI/default.conf.template` for `127.0.0.1`, then the **database migration as an explicit step**: the container does not start if it fails. The services then run with `OVPMON_AUTO_MIGRATE=0` (they only verify the schema).
@@ -0,0 +1,30 @@
# Containers: troubleshooting and security
Install: [Containers](README.md). Update and backup: [Operations](Operations.md).
## Troubleshooting
| Symptom | Cause and action |
|---|---|
| `port 80/tcp is already in use` | Another service uses the port. Install with `--http-port 8080` or set `OVPMON_HTTP_PORT` in `.env` (same for `OVPMON_VPN_PORT`) |
| `container 'ovp-...' of the OTHER variant is running` | Variants A and B cannot run together. Stop the other stack first |
| `container 'ovp-ui' ... belongs to compose project 'x'` | A stack of another project uses the fixed names. Use `--project x` or remove that stack |
| Health check does not turn healthy | `docker compose ps`, then `docker compose logs --tail 100 <service>` (A: `docker logs ovp-allinone`). The scripts print the last log lines of failing services. The profiler allows 40 s and the all-in-one container 60 s before failures count |
| `FATAL: ... newer than this version` / migration "too new" | The database was migrated by a newer release. Do not start the old version on it: update to the newer sources, or restore a matching backup (`update.sh --rollback` or `restore.sh`) |
| Migration failed | Nothing was started and the volumes are restored by the automatic rollback. The report names the migration; the database copy `<db>.bak-*` is in `db_data`. Send the report with the problem |
| `JWT_SECRET must be set in .env` | `.env` missing or empty value; run `install.sh` or add `JWT_SECRET=$(openssl rand -hex 32)` |
| `JWT_SECRET in .env is too short` / `a placeholder/default value` (the all-in-one container: `FATAL: JWT_SECRET is ...`; a service exits with `Refusing to start`) | The signing key is weak (under 32 characters or contains `change-me`/`changeme`). Set `JWT_SECRET=$(openssl rand -hex 32)` in `.env` and run the script again; all users must then sign in again |
| `permission denied` on docker | Run as root or add the user to the `docker` group. Backups belong to the user that runs the scripts |
| Permission errors on bind mounts on SELinux hosts | Backup and restore bind-mount `backups/` into a container; label the directory for containers (`chcon -Rt container_file_t backups`) |
| Cannot pull `alpine:3` (offline) | Make an image with `sh`, `tar` and `sha256sum` available locally and set `OVPMON_BACKUP_IMAGE`; use `--no-pull` with `update.sh` |
| `/dev/net/tun` missing | Load the module on the host (`modprobe tun`); the compose files map the device |
| VPN does not start after an update | The containers were recreated and the profiler starts OpenVPN only on request: start the server in the UI. Check that the server configuration exists (`ovp_config` volume) |
| The UI answers 502 right after start | The APIs are still starting; wait for the health checks |
## Security
- Put **TLS in front** of the UI (reverse proxy or a certificate in nginx): the container serves plain HTTP. See [Nginx configuration](../System_Services/Nginx_Configuration.md).
- `.env` holds the signing secret: mode 600, owned by the operator, never committed (`.gitignore` lists it). The scripts never print `JWT_SECRET`; the generated administrator password is shown once and removed from `.env` after the first start.
- Backups contain the PKI (CA and server private keys), the databases (password hashes, 2FA secrets) and a copy of `.env`: keep them mode 700/600 and store off-host copies encrypted.
- The profiler container is privileged for networking (`NET_ADMIN`, TUN). Variant A runs everything in that one container; its APIs listen on `127.0.0.1` only, so only nginx (80) and OpenVPN (1194/udp) are reachable.
- No secrets in logs: the scripts only log names and paths; the services log the source of the secret, not its value.
+36
View File
@@ -0,0 +1,36 @@
# First steps after the install
The same for every installation method. About ten minutes. You need the URL and the administrator login and password printed by the install script.
| # | Where in the UI | What to do |
|---|---|---|
| 1 | Login page | Open the URL: containers `http://<host>[:port]`, system services `https://<host>:8088` (the certificate is self-signed: check the fingerprint printed by the installer, then accept). Sign in with the printed login and password |
| 2 | **Account Settings** | Change the username and the password; enable two-factor authentication |
| 3 | **PKI** | Check the parameters, press **Initialize PKI**. It runs in the background with progress on the page (key generation takes a while). The **VPN** menu stays locked until it is done |
| 4 | **VPN** | Set the server parameters (port, VPN network, routes, DNS) and press **Apply Configuration**: this writes the OpenVPN `server.conf` |
| 5 | **Server Process** | Press **Start Service**. The page shows the state of OpenVPN |
| 6 | **Certificates** | **Create New Client**, then download its `.ovpn` file (the download icon in the row). Give the file to the user |
| 7 | the host | Open the ports and set up NAT (below) |
| 8 | a client | Import the `.ovpn` file into an OpenVPN client and connect. The client appears on **Clients** and **Analytics** |
## The network side (step 7)
| Method | What is done for you | What you do |
|---|---|---|
| Containers | forwarding, NAT and MSS rules are set inside the container | publish `80/tcp` (or your `--http-port`) and the VPN `udp` port; put TLS in front of the UI |
| System services | `net.ipv4.ip_forward=1` is set; the firewall is **not** touched | open the HTTPS port (`8088`) and the VPN port; NAT for the clients: [Firewall](System_Services/Firewall.md) (`deploy/native/firewall.sh`) |
If you change the OpenVPN port in the **VPN** page, the client profiles carry the new port; with containers keep it consistent with `OVPMON_VPN_PORT`.
## If something does not work
| Symptom | Look at |
|---|---|
| The page does not open | the install script's final summary and health checks; [Containers](Containers/Troubleshooting.md) or [System services](System_Services/Troubleshooting.md) |
| **VPN** menu is locked | the PKI is not initialized yet (step 3) |
| Server does not start | the VPN page was not applied (step 4); then the log: `docker logs` or `/var/log/openvpn/` / `journalctl -u openvpn-server@server` |
| The client connects but has no Internet | forwarding or NAT is missing (step 7) |
## What next
Regular backups ([containers](Containers/Operations.md), [system services](System_Services/Operations.md)), updates (same pages), TLS and host hardening ([Nginx](System_Services/Nginx_Configuration.md), [hardening](System_Services/Troubleshooting.md#host-hardening-recommended-not-done-by-the-scripts)), [security model](../General/Security_Architecture.md).
+42
View File
@@ -0,0 +1,42 @@
# Installation
Two ways to install, both with scripts that check the host, generate the secrets, start everything and print the first administrator login. Pick one; the steps **after** the install are the same: [First steps](First_Steps.md).
## Choose a method
| | [Containers](Containers/README.md) | [System services](System_Services/README.md) |
|---|---|---|
| Choose it when | the host has Docker, or you want the simplest operation | no containers wanted; Alpine, Debian or Ubuntu host |
| Needs on the host | Docker Engine with the compose plugin, `/dev/net/tun` | root, Internet access, Alpine 3.23 / Debian 12 / Ubuntu 24.04 |
| Install command | `deploy/docker/install.sh --variant a\|b` | `deploy/native/install.sh --prefix DIR` |
| Variants | **A**: everything in one container; **B**: one container per component | one per OS (the script detects it) |
| Web UI address | `http://<host>` (port 80, change with `--http-port`); put TLS in front | `https://<host>:8088` (self-signed certificate, change with `--https-port`) |
| VPN port | `1194/udp` (`--vpn-port`) | `1194/udp` by default, set in the UI |
| Free space | about 2 GB | about 1 GB |
| Update, backup, rollback | `update.sh`, `backup.sh`, `restore.sh` in `deploy/docker/` | `update.sh`, `backup.sh`, `restore.sh` in `deploy/native/` |
| Details | [Containers](Containers/README.md) | [System services](System_Services/README.md) |
Not sure? If Docker is already on the host, use **Containers, variant A**; otherwise **System services**.
Use **one method per host**: both use the VPN port `1194/udp` by default. For containers, only one variant can run at a time.
## The same in both methods
- Run the script as root (or, for containers, as a member of the `docker` group) from a clone of this repository.
- The script prints the URL and the **administrator password once**; it is stored nowhere else. No default account exists.
- Containers: running `install.sh` again is safe, it keeps `.env` and the data. System services: after a **failed** install, run it again to resume; a finished installation is changed only with `update.sh`.
- Updates always take a verified backup first and roll back automatically if something fails.
- The scripts do **not** open firewall ports and do not harden SSH. Open the UI port and the VPN port yourself; NAT for the VPN clients: [Firewall](System_Services/Firewall.md) (containers set their own NAT rules).
## After the install
[First steps](First_Steps.md): sign in, secure the account, initialize the PKI, configure and start the VPN server, create the first client profile.
## Other pages
| Topic | Page |
|---|---|
| Configuration variables | [General: Configuration](../General/Configuration.md) |
| Nginx and TLS for the UI | [Nginx configuration](System_Services/Nginx_Configuration.md) |
| Database schema changes on update | [Database migrations](../General/Database_Migrations.md) |
| Security model | [Security architecture](../General/Security_Architecture.md) |
-261
View File
@@ -1,261 +0,0 @@
# Scenario 1: installation in containers
Two variants, both installed and updated by the scripts in `deploy/docker/`:
| | Variant A: one container | Variant B: one container per component |
|---|---|---|
| Compose file | `docker-compose.allinone.yml` | `docker-compose.yml` |
| Containers | `ovp-allinone` (nginx, gunicorn, gatherer, uvicorn, OpenVPN under `supervisord`) | `ovp-ui`, `ovp-api`, `ovp-gatherer`, `ovp-profiler` |
| Image build | `deploy/allinone/Dockerfile` (build context: repository root) | one Dockerfile per component (`APP_UI`, `APP_CORE`, `APP_PROFILER`) |
| Choose it when | one host, simplest operation, one thing to start/stop/back up | you want to restart, scale or inspect components separately, or follow the usual one-process-per-container practice |
| Trade-off | a failing process is restarted by `supervisord`, the container stays up; one image to rebuild for any change | more moving parts, internal network `ovp-net` |
Both variants use the **same five named volumes with the same in-container paths**, the same environment variables and the same published ports. Backups look identical.
> **Only one variant can run per host.** Both publish the same host ports (`80/tcp`, `1194/udp` by default) and use fixed container names (`ovp-*`). The scripts refuse to start a variant while a container of the other one is running.
## Requirements
- Docker Engine with the compose plugin (`docker compose`, v2, preferred) or `docker-compose`.
- The Docker daemon running and usable by the user that runs the scripts (root, or a member of the `docker` group).
- Access to `/dev/net/tun` on the host and the `NET_ADMIN` capability (already set in the compose files).
- Free disk space: about 2 GB for images and builds, plus room for backups (the scripts check both).
- Internet access for the first build (base images, npm, pip) and for the backup helper image (`alpine:3`). For offline hosts see *Troubleshooting*.
- `openssl` is optional (random secret otherwise comes from `/dev/urandom`).
## Install
Clone the repository, change into it and run the script (as root or a docker user):
```bash
# Variant B: one container per component
deploy/docker/install.sh --variant b
# Variant A: everything in one container
deploy/docker/install.sh --variant a
# Options
deploy/docker/install.sh --variant b --project ovpmon --http-port 8080 --vpn-port 1194 --admin-user admin
```
| Option | Meaning |
|---|---|
| `--variant a\|b` | required |
| `--project NAME` | compose project name = prefix of the volume names (default `ovpmon`: volumes `ovpmon_db_data`, ...) |
| `--http-port N` | host port of the UI (written to `.env` as `OVPMON_HTTP_PORT`, default 80) |
| `--vpn-port N` | host UDP port of OpenVPN (`OVPMON_VPN_PORT`, default 1194) |
| `--admin-user NAME` | login of the first administrator (default `admin`) |
What `install.sh` does:
1. **Preflight:** docker and compose, running daemon, the other variant is not running, no foreign container with the same names, ports free, free disk space.
2. **`.env`** next to the compose files, only if it does not exist: mode 600, random `JWT_SECRET`, initial administrator with a generated 24-character password. An existing `.env` is never overwritten (`--http-port` / `--vpn-port` only set their own keys in it).
3. **Build, start** (`docker compose up -d`), write the state file `.ovpmon-deploy` (variant and project; used by `update.sh`, `backup.sh`, `restore.sh`), wait up to 3 minutes for the health checks.
4. **Initial administrator:** when the users table is not empty, `OVPMON_INITIAL_ADMIN_*` are removed from `.env` and the container that reads them is recreated (variant B: `app-api`, variant A: `ovpmon`). If the table cannot be read or is empty, the lines stay in `.env` and a warning says so.
5. **Result:** URL, ports, and the administrator login and password. **The password is shown once** and stored nowhere else. `JWT_SECRET` is never printed.
Running it again is safe: it rebuilds and starts, keeps `.env`, and makes no new administrator.
Then in the UI: sign in, **PKI Configuration → Initialize PKI**, generate the server configuration and start the VPN server. Put TLS in front of the UI (see *Security*).
### Without the script
```bash
cat > .env <<EOT
JWT_SECRET=$(openssl rand -hex 32)
OVPMON_INITIAL_ADMIN_USER=admin
OVPMON_INITIAL_ADMIN_PASSWORD=<strong password>
EOT
chmod 600 .env
docker compose up -d --build # variant B
docker compose -f docker-compose.allinone.yml up -d --build # variant A
```
After the first start remove the two `OVPMON_INITIAL_ADMIN_*` lines from `.env` and recreate `app-api` (B) or `ovpmon` (A).
## `.env` reference
| Variable | Required | Default | Meaning |
|---|---|---|---|
| `JWT_SECRET` | yes | none (compose refuses to start) | Signing key of both APIs (`OVPMON_API_SECRET_KEY`). Changing it logs every user out. Keep the same value across updates |
| `OVPMON_INITIAL_ADMIN_USER`, `OVPMON_INITIAL_ADMIN_PASSWORD` | first start only | empty | Seed for the first user, used only while the users table is empty. Removed by `install.sh` afterwards |
| `OVPMON_CORS_ORIGINS` | no | empty (off) | Comma-separated extra origins; the UI is same-origin behind nginx |
| `OVPMON_HTTP_PORT` | no | `80` | Host port of the UI |
| `OVPMON_VPN_PORT` | no | `1194` | Host UDP port of OpenVPN (the container side is always 1194) |
Variables of the scripts (environment of the shell, not `.env`): `OVPMON_BACKUP_DIR` (backup root, default `./backups`), `OVPMON_BACKUP_IMAGE` (helper image, default `alpine:3`), `OVPMON_HEALTH_TIMEOUT` (seconds, default 180), `OVPMON_MIN_FREE_MB` (docker data, default 2048), `OVPMON_MIN_FREE_BACKUP_MB` (backups, default 1024).
`OVPMON_VPN_PORT` changes only the host side of the mapping. If you change the OpenVPN port in the server settings of the UI, the client profiles carry that port; keep the two consistent.
## Ports
| Port | Published | Purpose |
|---|---|---|
| `${OVPMON_HTTP_PORT:-80}/tcp` | yes | UI and reverse proxy to both APIs (plain HTTP) |
| `${OVPMON_VPN_PORT:-1194}/udp` | yes | OpenVPN |
| `5001` (monitoring API), `8000` (profiler API) | no | variant B: `expose`d on `ovp-net` only; variant A: listen on `127.0.0.1` inside the container |
## Volumes: what is stored where
| Volume | Path in the container | Content | Mounted by (B) |
|---|---|---|---|
| `ovp_logs` | `/var/log/openvpn` | `openvpn-status.log` and OpenVPN logs | gatherer, profiler |
| `ovp_config` | `/etc/openvpn` | `server.conf` generated by the profiler | profiler |
| `ovp_pki` | `/app/easy-rsa` | easy-rsa scripts and `pki/` (CA, server and client keys and certificates, CRL, `ta.key`, `dh.pem`) | profiler |
| `ovp_client_config` | `/app/client-config` | generated client `.ovpn` files | profiler |
| `db_data` | `/app/db` | `ovpn_profiler.db`, `openvpn_monitor.db`, migration backups `*.db.bak-*` | gatherer, api, profiler |
Not stored in volumes (lost when the container is recreated): the container file system, `profiler.log` and `openvpn_gatherer.log` (written into the working directory), supervisor state. Application logs go to `docker logs`.
Volume names are `<project>_<volume>`; the scripts find them by the compose labels, so any project name works.
### Layout of variant A
The code is in `/app/APP_CORE` and `/app/APP_PROFILER`; the volumes are mounted at the same paths as in variant B (`/app/db`, `/app/easy-rsa`, `/app/client-config`, `/etc/openvpn`, `/var/log/openvpn`).
The profiler resolves `easy-rsa/` and `client-config/` relative to its working directory (`services/pki.py`, `routers/profiles.py`), and stores `client-config/<name>.ovpn` as a relative path in its database. In variant B that directory is `/app`. Variant A keeps it that way: **`supervisord` starts the profiler with working directory `/app`** (`uvicorn --app-dir /app/APP_PROFILER main:app`), so `/app/easy-rsa` and `/app/client-config` are the volumes. No symlinks are used, and the database paths are identical in both variants (so a volume set can be used by either variant). The monitoring API and the gatherer run with working directory `/app/APP_CORE`, where `config.ini` lives; their database path comes from `OVPMON_OPENVPN_MONITOR_DB_PATH=/app/db/openvpn_monitor.db`.
Processes in `ovp-allinone` (`deploy/allinone/supervisord.conf`, started in this order, all with `autorestart`, logs to stdout/stderr): `gatherer`, `api` (`gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app`), `profiler` (`uvicorn` on `127.0.0.1:8000`, no reload), `nginx`. OpenVPN is started by the profiler API on request (direct start inside containers), as in variant B.
`deploy/allinone/entrypoint.sh` runs before `supervisord`: secret mapping (`JWT_SECRET` → `OVPMON_API_SECRET_KEY` when only the first is set), `/dev/net/tun`, easy-rsa workspace (copied only when the volume does not have it yet), NAT and MSS rules without duplicates, the nginx configuration rendered from `APP_UI/default.conf.template` for `127.0.0.1`, then the **database migration as an explicit step**: the container does not start if it fails. The services then run with `OVPMON_AUTO_MIGRATE=0` (they only verify the schema).
## Update
```bash
deploy/docker/update.sh # variant and project from .ovpmon-deploy
deploy/docker/update.sh --yes # no questions
deploy/docker/update.sh --no-pull # sources already in place / offline (no git pull, no base image refresh)
deploy/docker/update.sh --rollback # manual rollback to the newest backup
```
Each phase is logged separately:
| Phase | What happens | If it fails |
|---|---|---|
| 0 Preflight | state file, `.env`, compose configuration, running stack, the other variant not running, `db_data` volume exists, free space | nothing was changed |
| 1 **Backup** | all five volumes → `backups/<UTC timestamp>/*.tar.gz` through a throwaway `alpine` container (volumes mounted read-only), copy of `.env` (mode 600), record of the current image IDs, `SHA256SUMS`; every archive is verified (`tar -tzf`) | the update is **refused**, nothing was changed |
| 2 Sources | `git pull --ff-only` when the directory is a git checkout and `--no-pull` was not given | nothing was changed |
| 3 Build | current images are tagged `<name>:previous`, then the new images are built while the old stack keeps running | nothing was changed, the old version still runs |
| 4 Stop | the application containers are stopped (volumes are kept); a second, final backup of the volumes is taken now that nothing writes to the databases | automatic rollback |
| 5 **Database migration** | a separate step, see below | automatic rollback, nothing is started |
| 6 Start | `up -d` with the new images, wait for the health checks | automatic rollback |
Old backups: the newest 5 are kept; older ones are pruned only after a successful update. Volumes are never deleted and `down -v` is never used. The new `deploy/docker/*.sh` take effect on the next run (the running script is not replaced).
### Database migration as its own step
After the containers are stopped and before any new component starts, `update.sh` runs, for each database, a one-off container **from the new image with the same volumes**:
| Variant | Profiler database | Monitoring database |
|---|---|---|
| B | `app-profiler` image: `cd /app && python migrate.py` | `app-api` image: `cd /app && python migrate.py` |
| A | `ovpmon` image: `cd /app/APP_PROFILER && python migrate.py` | `ovpmon` image: `cd /app/APP_CORE && python migrate.py` |
For each database it runs `python migrate.py --check` (exit 0 up to date, 2 pending, 1 error or database newer than the code), applies the pending migrations with `python migrate.py` and checks again. The reports are printed. A failure or a "too new" database aborts **before anything is started** and triggers the rollback.
What the migration does (details: [Database migrations](../General/Database_Migrations.md)): versioned, additive-only changes (`CREATE ... IF NOT EXISTS`, `ADD COLUMN` with defaults), never a drop or rewrite; before any change an integrity check and a consistent copy `<db>.bak-<UTC timestamp>` next to the database (newest 5 kept); after the change an integrity check and a comparison of row counts; on a mismatch everything is rolled back; a database newer than the application is not touched.
The migration also runs by itself when a service starts (variant B: profiler and API; variant A: the entrypoint, before `supervisord`), so a plain `docker compose up -d --build` is safe too. `update.sh` only makes it a visible, separate, controlled step.
### Automatic rollback
On any failure in phases 4 to 6: the stack is stopped, all five volumes are restored from the backup of this run, the `:previous` images are started (through a generated `compose.previous.yml` in the backup directory) and the result is reported with the backup path. If the rollback itself fails, the message says where the backup is and how to retry (`update.sh --rollback`, or `restore.sh`).
After a rollback the stack runs on the `:previous` images; the next `update.sh` run builds again and recreates the containers on the new images.
## Backup, restore, rollback
### Backup
```bash
deploy/docker/backup.sh # live backup of the five volumes -> backups/<UTC timestamp>/
deploy/docker/backup.sh --stop # stops the containers during the copy (consistent SQLite files), starts them again
deploy/docker/backup.sh --keep 14 # afterwards keep the newest 14
```
Cron example (nightly, consistent, 14 kept): `30 3 * * * /opt/ovpmon/deploy/docker/backup.sh --stop --keep 14 >> /var/log/ovpmon-backup.log 2>&1`.
A live backup copies the PKI and configuration reliably; a database file that is written at that very moment may be caught half-way, which `--stop` avoids (and `update.sh` always backs up a stopped stack for its final snapshot). The backup holds private keys, password hashes and the secret: the directory is mode 700, the files mode 600. Store copies off the host and protect them.
Manual equivalent for one volume (project `ovpmon`):
```bash
mkdir -p backups/manual
docker run --rm -v ovpmon_db_data:/data:ro -v "$PWD/backups/manual":/backup alpine \
tar -czf /backup/db_data.tar.gz -C /data .
```
### Restore
```bash
deploy/docker/restore.sh backups/20261005T101500Z # asks, stops the stack, restores, prints the start command
deploy/docker/restore.sh backups/20261005T101500Z --yes --start
```
It verifies the archives first, saves the current content to `backups/<timestamp>-pre-restore`, empties each volume and fills it from the archive. Volumes are not removed. `.env` is not touched (a difference to the copy in the backup is reported). Manual equivalent:
```bash
docker compose stop # or: -f docker-compose.allinone.yml
docker run --rm -v ovpmon_db_data:/data -v "$PWD/backups/20261005T101500Z":/backup:ro alpine \
sh -c 'rm -rf /data/* /data/.[!.]* /data/..?* && tar -xzf /backup/db_data.tar.gz -C /data'
docker compose up -d
```
A single database can also be put back from its migration backup in `db_data`: stop the stack, copy `<db>.bak-<timestamp>` over the database file, start the OLD release (see [Database migrations](../General/Database_Migrations.md)).
### Rollback to the previous version
```bash
deploy/docker/update.sh --rollback
```
After confirmation: stop, restore all volumes from the newest complete backup (current content saved first), start the images recorded in that backup. Use it when an update completed but the new version misbehaves. Data created after that backup is lost (it is in the `-pre-restore` copy).
## Switching between variants
Both variants use the same volumes, so with the same project name the data can be used by the other variant: stop the running one (`docker compose [-f docker-compose.allinone.yml] stop`), take a backup, run `install.sh --variant <other> --project <same name>`. This path has not been tested in a real run; keep the backup. Starting both at once is refused.
## Troubleshooting
| Symptom | Cause and action |
|---|---|
| `port 80/tcp is already in use` | Another service uses the port. Install with `--http-port 8080` or set `OVPMON_HTTP_PORT` in `.env` (same for `OVPMON_VPN_PORT`) |
| `container 'ovp-...' of the OTHER variant is running` | Variants A and B cannot run together. Stop the other stack first |
| `container 'ovp-ui' ... belongs to compose project 'x'` | A stack of another project uses the fixed names. Use `--project x` or remove that stack |
| Health check does not turn healthy | `docker compose ps`, then `docker compose logs --tail 100 <service>` (A: `docker logs ovp-allinone`). The scripts print the last log lines of failing services. The profiler allows 40 s and the all-in-one container 60 s before failures count |
| `FATAL: ... newer than this version` / migration "too new" | The database was migrated by a newer release. Do not start the old version on it: update to the newer sources, or restore a matching backup (`update.sh --rollback` or `restore.sh`) |
| Migration failed | Nothing was started and the volumes are restored by the automatic rollback. The report names the migration; the database copy `<db>.bak-*` is in `db_data`. Send the report with the problem |
| `JWT_SECRET must be set in .env` | `.env` missing or empty value; run `install.sh` or add `JWT_SECRET=$(openssl rand -hex 32)` |
| `permission denied` on docker | Run as root or add the user to the `docker` group. Backups belong to the user that runs the scripts |
| Permission errors on bind mounts on SELinux hosts | Backup and restore bind-mount `backups/` into a container; label the directory for containers (`chcon -Rt container_file_t backups`) |
| Cannot pull `alpine:3` (offline) | Make an image with `sh`, `tar` and `sha256sum` available locally and set `OVPMON_BACKUP_IMAGE`; use `--no-pull` with `update.sh` |
| `/dev/net/tun` missing | Load the module on the host (`modprobe tun`); the compose files map the device |
| VPN does not start after an update | The containers were recreated and the profiler starts OpenVPN only on request: start the server in the UI. Check that the server configuration exists (`ovp_config` volume) |
| The UI answers 502 right after start | The APIs are still starting; wait for the health checks |
## Security
- Put **TLS in front** of the UI (reverse proxy or a certificate in nginx): the container serves plain HTTP. See [Nginx configuration](../General/Nginx_Configuration.md).
- `.env` holds the signing secret: mode 600, owned by the operator, never committed (`.gitignore` lists it). The scripts never print `JWT_SECRET`; the generated administrator password is shown once and removed from `.env` after the first start.
- Backups contain the PKI (CA and server private keys), the databases (password hashes, 2FA secrets) and a copy of `.env`: keep them mode 700/600 and store off-host copies encrypted.
- The profiler container is privileged for networking (`NET_ADMIN`, TUN). Variant A runs everything in that one container; its APIs listen on `127.0.0.1` only, so only nginx (80) and OpenVPN (1194/udp) are reachable.
- No secrets in logs: the scripts only log names and paths; the services log the source of the secret, not its value.
## What is preserved on update
| Item | On update |
|---|---|
| Databases (`db_data`) | Kept. Backed up twice (before and after the stop), migrated additively with their own `<db>.bak-*` copy; restored automatically if the update fails after the stop |
| PKI (`ovp_pki`): CA, keys, certificates, CRL | Kept, backed up. The easy-rsa scripts are copied only when the volume does not have them yet |
| Client profiles (`ovp_client_config`) | Kept, backed up |
| Server configuration (`ovp_config`) | Kept, backed up (the new image does not overwrite it) |
| OpenVPN logs and status file (`ovp_logs`) | Kept |
| `.env` (secret, ports) | Kept, copied into every backup |
| User sessions | Stay valid while `JWT_SECRET` is unchanged |
| Images | Replaced; the previous ones stay tagged `<name>:previous` |
| Containers | Recreated; running VPN sessions are interrupted and clients reconnect; the OpenVPN process has to be started again (see troubleshooting) |
| Container file system, `profiler.log`, `openvpn_gatherer.log` | Not kept (use `docker logs`) |
| Backups in `backups/` | The newest 5 kept, older ones pruned after a successful update; `-pre-restore` copies are never pruned automatically |
| Volumes | Never deleted by any script; `down -v` is never used |
Related: [Database migrations](../General/Database_Migrations.md), [Deployment plan](../Changes/2026-10-05_Deployment_Scenarios_PLAN.md).
@@ -1,493 +0,0 @@
# Scenario 2: installation as system services (no containers)
Install and update on **Alpine (OpenRC)**, **Debian** and **Ubuntu** (systemd) with the scripts in `deploy/native/`. Nothing runs in a container. The web UI is part of the repository (`deploy/ui-dist`) and is installed automatically, so the host needs no Node.
| Script | Purpose |
|---|---|
| `deploy/native/build-ui.sh` | builds the web UI (Docker, or the local Node without a container) into a tarball and/or into the repository (`--publish`) |
| `deploy/native/check-ui.sh` | checks that the committed UI build `deploy/ui-dist` matches the `APP_UI` sources (exit 1 when stale) |
| `deploy/native/install.sh` | first installation: packages, user, code, virtualenvs, configuration, services, nginx with TLS, health checks |
| `deploy/native/update.sh` | update with a verified backup, a separate database migration step and automatic rollback; `--rollback` for a manual one |
| `deploy/native/backup.sh` / `restore.sh` | stand-alone backup (cron friendly) and restore |
| `deploy/native/lib.sh` | shared functions and the OS adapter (sourced, not executed) |
All scripts run as root, support `-h`, log in one style (UTC time stamp, `=== PHASE n ===`) and append every log line to `/var/log/ovpmon-deploy.log`.
## What is installed
```
Browser --https:8088--> nginx --/--------------> /var/www/ovpmon (UI files)
--/api/----------> 127.0.0.1:5001 ovpmon-api (gunicorn, APP_CORE)
--/profiles-api/-> 127.0.0.1:8000 ovpmon-profiler (uvicorn, APP_PROFILER)
ovpmon-gatherer (APP_CORE): OpenVPN status log -> monitoring database
ovpmon-profiler (user ovpmon) --doas--> /usr/local/sbin/ovpmon-helper (root) --> server.conf, CRL, OpenVPN service
```
The three `ovpmon-*` services run as the unprivileged user `ovpmon`. Only the helper acts as root, through six fixed `doas` rules, and it validates everything it installs (see [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md)). The services do not require OpenVPN to be running: the VPN server is created and started from the UI.
## Supported systems
| System | Tested version | Service manager | Notes |
|---|---|---|---|
| Alpine | 3.23 | OpenRC | the original reference platform |
| Debian | 12 | systemd | |
| Ubuntu | 24.04 LTS | systemd | needs the `universe` repository (`easy-rsa`, `opendoas`) |
Another version of these systems is refused with a warning unless you pass `--force` to `install.sh` (the update only warns). Other distributions are not supported (a Debian derivative works with `--force` at your own risk).
## Requirements
- A host with root access, a working package manager and Internet access (packages, Python packages from PyPI).
- `/dev/net/tun` for OpenVPN (a normal VM has it; in containers it must be passed in).
- Free space: about 1 GB for the code and virtualenvs (the script checks it), plus room for the backups.
- Python 3.9 or newer (Alpine 3.23: 3.12, Debian 12: 3.11, Ubuntu 24.04: 3.12).
- Free TCP ports `5001`, `8000` (on `127.0.0.1`) and the HTTPS port (default `8088`).
- A UI build: the clone contains one (`deploy/ui-dist`, see below). **The host needs no Node.js** unless you choose `--build-ui`.
- GNU tar (on Alpine the package `tar`; the installer adds it).
## The web UI
The UI is built from `APP_UI` (Vue/Vite). The repository carries a ready build in `deploy/ui-dist/` together with `SOURCE_HASH`, a SHA-256 over the UI sources it was built from (`APP_UI/src`, `public`, `index.html`, `package.json`, `package-lock.json`, `vite.config.js`, `jsconfig.json`). `install.sh` and `update.sh` find the UI themselves. The directory is outside `APP_UI`, so the container builds are not affected.
### Three ways to get the UI onto a host
| Way | Option | When |
|---|---|---|
| Committed build | none (automatic) | the normal case: `git clone`, `install.sh`, done; no Node, no Docker |
| Build on the host | `--build-ui` | the committed build is stale or missing; builds from `APP_UI` now with Docker (when its daemon works) or the host's Node 20.19+ |
| Build elsewhere | `--ui-dist FILE\|DIR` | a tarball from `build-ui.sh` or a directory with `index.html`, for example from a CI job or another machine |
Order used by `install.sh` and `update.sh`: **1.** `--ui-dist` (explicit, always installed), **2.** `--build-ui` (always builds fresh from the sources), **3.** the committed `deploy/ui-dist` of the checkout (automatic), **4.** nothing found: `install.sh` **stops** (it lists the ways out) unless `--no-ui` is given (a placeholder page on purpose); `update.sh` keeps the installed UI. `install.sh` also still accepts `deploy/native/ui-dist.tar.gz` as a last resort below the committed directory. `--ui-dist` and `--build-ui` exclude each other.
The installed web root records the hash it came from in `/var/www/ovpmon/.ui-source-hash` (`unknown` for archives that were not made by `build-ui.sh`). `update.sh` compares it with the `SOURCE_HASH` of the repository build: equal, the UI is not replaced (and it says so); different or missing (for example a host installed with `--no-ui`), the new UI is staged in phase 3 and swapped in phase 6, with the rest of the update, so it is part of the backup and the automatic rollback. The UI source is decided after `git pull`, so a pulled new build is used in the same run. The old UI is in the backup.
### Staleness guard
When the hash of the current `APP_UI` sources differs from `SOURCE_HASH`, the committed build is **older than the sources** (someone changed the UI and did not refresh the build). `install.sh` and `update.sh` then print a loud warning with the two hashes and the remedy, and still use the committed build (it works, it only lacks the latest UI changes). A host that needs the current UI adds `--build-ui`. A build without a valid `SOURCE_HASH` counts as stale.
### Maintainer routine
After every change in `APP_UI` (or its `package*.json`, `vite.config.js`), **before committing**:
```sh
deploy/native/build-ui.sh --publish # rebuilds deploy/ui-dist/ and SOURCE_HASH from the current sources
deploy/native/check-ui.sh # prints fresh | stale | missing; exit 0 | 1 | 2
git add APP_UI deploy/ui-dist
```
`check-ui.sh` also fits a release checklist or a CI step (it changes nothing). `--publish` replaces the content of `deploy/ui-dist/` by a move (the old directory is only deleted after the new one is in place).
### build-ui.sh
```sh
deploy/native/build-ui.sh # Docker if it works, otherwise local Node -> deploy/native/ui-dist.tar.gz
deploy/native/build-ui.sh --docker # node:20-alpine container (OVPMON_NODE_IMAGE or --image to change)
deploy/native/build-ui.sh --local # Node >= 20.19 and npm of this machine, no container
deploy/native/build-ui.sh --local --node-download # temporary official Node 20, deleted after the build
deploy/native/build-ui.sh --publish # refresh deploy/ui-dist/ in the repository
deploy/native/build-ui.sh -o /tmp/ui.tar.gz # tarball for another host (also with --publish)
deploy/native/build-ui.sh --check # only check that the builder is usable
```
Without `--docker`/`--local` the script uses Docker when its daemon answers, otherwise the local Node. The tarball holds the content of `dist/` and `SOURCE_HASH`. **Nothing is written into the source tree**: a container sees `APP_UI` read-only; `--local` copies it (without `node_modules` and `dist`) into a temporary directory and runs `npm ci` there (`npm install` without a lock file), so the repository gets no `node_modules` and no `dist`.
`--local` needs Node 20.19 or newer with npm. When it is missing or too old the script prints what to do and stops:
| System | What to do |
|---|---|
| Alpine | `apk add nodejs npm` (check `node --version` afterwards) |
| Debian / Ubuntu | the distribution's Node is usually too old (Debian 12 and Ubuntu 24.04 ship Node 18): add `--node-download` (needs `apt-get install -y curl xz-utils`), or install Node 20+ with npm from nodejs.org / NodeSource |
| anything else | Node 20.19+ from nodejs.org, or build with `--docker` on a machine with Docker |
`--node-download` fetches `SHASUMS256.txt` from `https://nodejs.org/dist/latest-v20.x/`, picks `node-v20.*-linux-<x64|arm64>.tar.xz`, verifies its SHA-256, unpacks it into a temporary directory (npm cache included), builds with it and deletes everything; nothing is installed on the host. glibc systems only: on Alpine (musl) it refuses and points to `apk add nodejs npm`. It needs `curl`, `tar`, `xz` and access to nodejs.org (`OVPMON_NODE_MAJOR` selects another major version).
## Install
Clone the repository on the target host (anywhere **outside** the install directory: the checkout is only the source, e.g. `/root/ovpmon-src`) and run, as root. The UI comes with the clone (`deploy/ui-dist`, see above). The install directory is always asked for: pass `--prefix DIR`, or the script prompts for it (and for a confirmation); there is no default. Recommended: `/opt/OpenVPN-Monitoring-Simple`.
### Alpine (OpenRC)
```sh
apk add git # only to clone; the script installs the rest
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --prefix /opt/OpenVPN-Monitoring-Simple
```
### Debian 12
```sh
apt-get update && apt-get install -y git
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --prefix /opt/OpenVPN-Monitoring-Simple
```
### Ubuntu 24.04
```sh
sudo -i
apt-get update && apt-get install -y git # make sure the "universe" component is enabled
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --prefix /opt/OpenVPN-Monitoring-Simple
```
Options:
| Option | Meaning |
|---|---|
| `--prefix DIR` | install directory, **required**: asked interactively when the option is missing (without a terminal the script stops). Absolute path of letters, digits, `. _ - /`, no trailing `/`; must be new or empty, must not be the repository checkout (or contain it, or lie inside it) and must not be a system directory (`/`, `/opt`, `/root`, `/usr`, `/var`, ...) |
| `--ui-dist FILE\|DIR` | UI tarball from `build-ui.sh` or a directory with `index.html`; highest priority |
| `--build-ui` | build the UI now from `APP_UI` (Docker, otherwise the host's Node 20.19+) instead of using `deploy/ui-dist` |
| `--node-download` | with `--build-ui`: use a temporary official Node 20 (checksum verified, glibc only) |
| `--no-ui` | install a placeholder page on purpose; without any UI source and without this option the install stops |
| `--https-port N` | HTTPS port of the web UI (default `8088`) |
| `--host-name NAME` | DNS name or IP for the certificate and the CORS origin (default: the detected address of the default route) |
| `--admin-user NAME` | login of the first administrator (default `admin`) |
| `--force` | continue on an untested OS version |
### Differences between the systems
| | Alpine 3.23 | Debian 12 / Ubuntu 24.04 |
|---|---|---|
| Packages | `python3 py3-pip nginx openvpn easy-rsa iptables bash doas openssl curl tar` | `python3 python3-venv python3-pip nginx openvpn easy-rsa iptables opendoas openssl curl ca-certificates tar iproute2` |
| Service manager | OpenRC: `rc-service NAME start\|stop\|restart\|status`, `rc-update add NAME default` | systemd: `systemctl start\|stop\|restart\|status NAME`, `systemctl enable NAME` |
| Our service files | `/etc/init.d/ovpmon-api`, `-gatherer`, `-profiler` (`supervise-daemon`, `command_user=ovpmon:ovpmon`) | `/etc/systemd/system/ovpmon-*.service` (`User=ovpmon`, `EnvironmentFile=/etc/ovpmon/env`) |
| Service logs | `/var/log/ovpmon/ovpmon-<name>.log` | `journalctl -u ovpmon-<name>` |
| OpenVPN service | `openvpn`; config `/etc/openvpn/server.conf`, plus the link `/etc/openvpn/openvpn.conf -> server.conf` | `openvpn-server@server`; config `/etc/openvpn/server/server.conf` |
| nginx site | `/etc/nginx/http.d/ovpmon.conf` | `/etc/nginx/conf.d/ovpmon.conf` |
| doas | package `doas`; our rules in `/etc/doas.d/ovpmon.conf` (own file, as on the existing hosts) | package `opendoas`; our rules as a marked block inside `/etc/doas.conf` |
| `ovpmon` user | `adduser -S`, shell `/sbin/nologin` | `useradd --system`, shell `/usr/sbin/nologin` |
The nginx site does not collide with the distribution defaults: the default server of Alpine and Debian listens on port 80, ours on 8088, and both distribution `nginx.conf` files include the directory above (the installer checks the `include` line).
### What `install.sh` does
| Phase | Content |
|---|---|
| 0 Preflight | root, OS and version, service manager present, no existing installation (otherwise it points to `update.sh`), source checkout complete, UI source found (and built for `--build-ui`; a stale committed build only warns), ports free, free space |
| 1 Packages | the table above; GNU tar, Python 3.9+ with `venv` and `sqlite3`, `easy-rsa` checked |
| 2 User and directories | user `ovpmon`; `/var/lib/ovpmon` (+ `staging/`), `/var/log/ovpmon`, `/var/log/openvpn` (with `openvpn-status.log` as `root:ovpmon 640`), `/etc/openvpn/scripts`, `/etc/ovpmon` |
| 3 Code | `APP_CORE` and `APP_PROFILER` copied to the prefix (without venvs, databases, logs, Dockerfiles), plus the scripts and templates under `deploy/` and `DOCS/General/` (so the install directory can run `update.sh --source ...`); `VERSION` |
| 4 Virtualenvs and easy-rsa | two virtualenvs (`pip install -r requirements.txt`, plus `gunicorn` for `APP_CORE`), an import check, the easy-rsa workspace copied from `/usr/share/easy-rsa` into `APP_PROFILER/easy-rsa` (a real directory, never a symlink), code made root-owned and read-only |
| 5 Configuration | `/etc/ovpmon/env` (random secret, generated administrator), `/etc/ovpmon/helper.conf`, `/usr/local/sbin/ovpmon-helper`, doas rules and a **self-test** (`ovpmon` runs the helper through doas), forwarding via `/etc/sysctl.d`, OpenVPN prerequisites (Alpine: the `openvpn.conf` link; Debian/Ubuntu: `/etc/openvpn/server/`; the OpenVPN service is **enabled, not started**: there is no `server.conf` yet) |
| 6 Services, UI, nginx | the three service definitions installed and enabled, UI files to `/var/www/ovpmon` (validated, swapped in atomically, with `.ui-source-hash`), a self-signed EC certificate (`/etc/ovpmon/tls/`, SAN: host name, detected IP, `127.0.0.1`, `localhost`), the nginx site, nginx enabled and reloaded |
| 7 Start and checks | services started; health checks (below) |
| 8 Administrator | when a user exists in the monitoring database, the seed is removed from `/etc/ovpmon/env` and `ovpmon-api` is restarted; if the database cannot be read or is empty the seed stays and a warning says so |
Health checks: the three services are running; `http://127.0.0.1:5001/` answers; `http://127.0.0.1:8000/` returns 200; `https://127.0.0.1:<port>/` (with `-k`) returns 200; `/api/v1/user/me` and `/profiles-api/config` through nginx return 401 without a token.
The final summary shows the URL, the certificate fingerprint, the paths and the **generated administrator password once**. The state is recorded in `/etc/ovpmon/deploy.state` (prefix, HTTPS port, OS, version, dates). If the script fails it is **safe to run again**: it resumes, keeps the existing secret, certificate, easy-rsa workspace and data.
Then in the UI: sign in, change the password and enable 2FA, **PKI Configuration -> Initialize PKI**, generate the server configuration, start the VPN server.
### Without the script (outline)
Create the `ovpmon` user and the directories, copy the code, build both virtualenvs, write `/etc/ovpmon/env`, `helper.conf` and the doas rules from the templates, install the service definitions (`DOCS/General/systemd/*.service` or `DOCS/General/openrc/ovpmon-*`; replace `/opt/OpenVPN-Monitoring-Simple` if you use another prefix), copy the UI, add the nginx site from `deploy/native/nginx/ovpmon.conf.template` (replace `@HTTPS_PORT@`, `@WEB_ROOT@`, `@TLS_CRT@`, `@TLS_KEY@`). The commands are exactly what `install.sh` runs; reading the script is the shortest reference.
## Layout: what is where, who owns it
| Item | Path | Owner, mode |
|---|---|---|
| Code | `<prefix>/APP_CORE`, `<prefix>/APP_PROFILER` | `root:root`, read-only for others |
| Virtualenvs | `<prefix>/APP_CORE/venv`, `<prefix>/APP_PROFILER/venv` | `root:root` |
| **PKI** (CA, keys, certificates, CRL) | `<prefix>/APP_PROFILER/easy-rsa` (real directory) | `ovpmon:ovpmon` 750 |
| **Client profiles** | `<prefix>/APP_PROFILER/client-config` (real directory) | `ovpmon:ovpmon` 750 |
| Profiler log | `<prefix>/APP_PROFILER/profiler.log` | `ovpmon:ovpmon` 640 |
| Shipped settings file | `<prefix>/APP_CORE/config.ini`, `<prefix>/APP_PROFILER/config.ini` | `root:root`; the environment file overrides it |
| **Databases** | `/var/lib/ovpmon/openvpn_monitor.db`, `ovpn_profiler.db`, migration copies `*.db.bak-*` | `ovpmon:ovpmon` |
| Staging of `server.conf` | `/var/lib/ovpmon/staging/` | `ovpmon:ovpmon` 750 |
| Service environment | `/etc/ovpmon/env` | `root:root` 600 |
| Helper configuration | `/etc/ovpmon/helper.conf` | `root:root` 644 |
| TLS certificate and key | `/etc/ovpmon/tls/ovpmon.crt`, `ovpmon.key` | `root:root` (key 600) |
| Deployment state | `/etc/ovpmon/deploy.state` | `root:root` 644 |
| nftables ruleset of the VPN clients (only after `firewall.sh`) | `/etc/ovpmon/nftables.nft`, service `ovpmon-nft` | `root:root` 644 |
| Root helper | `/usr/local/sbin/ovpmon-helper` | `root:root` 755 |
| doas rules | Alpine: `/etc/doas.d/ovpmon.conf`; Debian/Ubuntu: block in `/etc/doas.conf` | `root:root` |
| OpenVPN configuration | `/etc/openvpn/server.conf` (Alpine) or `/etc/openvpn/server/server.conf`, `/etc/openvpn/crl.pem`, `/etc/openvpn/scripts/` | `root:root` |
| OpenVPN logs | `/var/log/openvpn/openvpn.log`, `openvpn-status.log` (`root:ovpmon` 640) | `root` |
| Service logs | `/var/log/ovpmon/` (OpenRC) or the journal (systemd) | `ovpmon` / systemd |
| UI files | `/var/www/ovpmon` | `root:root` |
| Backups | `/var/backups/ovpmon/<UTC timestamp>/` | `root:root` 700 |
| Deployment log | `/var/log/ovpmon-deploy.log` | `root:root` 600 |
The profiler resolves `easy-rsa/` and `client-config/` relative to its working directory (`APP_PROFILER`) and keeps `client-config/<name>.ovpn` as a relative path in its database; therefore both are real directories inside `APP_PROFILER` (a symlinked `client-config` breaks the real-path checks and the `clear_pki` cleanup).
## Environment file and helper configuration
`/etc/ovpmon/env` (`root:root` 600) is read by the init system as root and handed to the services. Lines are `KEY=VALUE` without quotes or spaces (systemd and OpenRC read the same file).
| Variable | Default written by `install.sh` | Meaning |
|---|---|---|
| `OVPMON_API_SECRET_KEY` | random, 64 hex characters | signing key of both APIs; changing it logs everybody out; keep it across updates |
| `OVPMON_API_HOST`, `OVPMON_API_PORT` | `127.0.0.1`, `5001` | informational: gunicorn is started with `-b 127.0.0.1:5001` |
| `OVPMON_OPENVPN_MONITOR_DB_PATH` | `/var/lib/ovpmon/openvpn_monitor.db` | monitoring database |
| `OVPMON_PROFILER_DB_PATH` | `/var/lib/ovpmon/ovpn_profiler.db` | profiler database |
| `OVPMON_OPENVPN_MONITOR_LOG_PATH` | `/var/log/openvpn/openvpn-status.log` | status log read by the gatherer |
| `OVPMON_LOGGING_LEVEL` | `INFO` | |
| `OVPMON_CORS_ORIGINS` | `https://<host>:<https-port>` | extra allowed origin (the UI is same-origin behind nginx) |
| `OVPMON_RUNTIME` | `host` | forces host mode (never "container"), needed when the host itself runs inside a container |
| `OVPMON_OPENVPN_SERVICE` | `openvpn` (Alpine) / `openvpn-server@server` | service name for the root (non-helper) path |
| `OVPMON_OPENVPN_CONFIG` | `/etc/openvpn/server.conf` / `/etc/openvpn/server/server.conf` | server config path for the root (non-helper) path |
| `OVPMON_INITIAL_ADMIN_USER`, `OVPMON_INITIAL_ADMIN_PASSWORD` | generated | seed, only while the users table is empty; removed by `install.sh` after the first start |
| `OVPMON_AUTO_MIGRATE` | unset | `0` makes the services refuse to start while migrations are pending |
With the unprivileged profiler the API only stages `server.conf`; **the helper configuration decides where it is installed and which service is controlled.**
`/etc/ovpmon/helper.conf` (INI, section `[helper]`, `root:root`, not group/world writable, otherwise the helper refuses to run). Without the file the helper uses the built-in values of the Alpine layout.
| Key | Alpine (written) | Debian/Ubuntu (written) | Rule |
|---|---|---|---|
| `install_dir` | `/opt/OpenVPN-Monitoring-Simple` | same | absolute, no `..`; the PKI is `<install_dir>/APP_PROFILER/easy-rsa/pki` |
| `service_manager` | `openrc` | `systemd` | `openrc` or `systemd` |
| `service_unit` | `openvpn` | `openvpn-server@server` | `^[A-Za-z0-9@._-]{1,64}$`, not starting with `-` or `.` |
| `config_path` | `/etc/openvpn/server.conf` | `/etc/openvpn/server/server.conf` | absolute, below `/etc/openvpn/`, ends with `.conf` |
| `staged_path` | `/var/lib/ovpmon/staging/server.conf` | same | absolute, below `/var/lib/ovpmon/` |
OpenRC runs `/sbin/rc-service <unit> <action>`, systemd runs `systemctl <action> <unit>` (fixed argument list, fixed `PATH`). Unknown keys or invalid values make the helper refuse.
## Firewall, NAT and forwarding
`install.sh` and `update.sh` **never touch the firewall**. `net.ipv4.ip_forward=1` is set persistently in `/etc/sysctl.d/98-ovpmon-forward.conf`. Opening the ports (UI, VPN) is yours. NAT and packet tuning for the VPN clients are done by a separate opt-in script.
### `deploy/native/firewall.sh` (nftables)
Reads the interfaces of this server and applies, for traffic **from the VPN network to every other network**: masquerade, TCP MSS clamping (path MTU tuning) and TTL tuning. Run it as root after the VPN server configuration exists (the VPN network is read from the `server` line of `server.conf`).
```sh
deploy/native/firewall.sh --dry-run # show what was detected and the ruleset; change nothing
deploy/native/firewall.sh # apply, ask for confirmation, load at boot
deploy/native/firewall.sh status # loaded rules with counters, boot service, detected parameters
deploy/native/firewall.sh remove # delete the rules, the ruleset file and the boot service
```
| Option | Meaning |
|---|---|
| `--vpn-net CIDR` | VPN network. Default: `server` line of the OpenVPN config, else the address of the VPN interface |
| `--vpn-if NAME` | VPN interface. Default: the interface with an address in the VPN network, else the `dev` line, else `tun*` |
| `--out-if A,B` | Only these interfaces (exact names) are "other networks". Default: every interface except `lo` and the VPN interface, so new uplinks (VLAN, `hytun`, a second ISP) need no rerun |
| `--ttl N` / `--no-ttl` | TTL of packets leaving towards the other networks (default 64, set after the forwarding decrement) |
| `--mss pmtu\|N` / `--no-mss` | TCP MSS of SYN and SYN-ACK in both directions: `pmtu` = MTU of the route of each connection (default), or a fixed value |
| `--no-persist` | Running kernel only: no ruleset file, no boot service |
| `--yes`, `--force` | No questions; continue on an untested OS version |
What it creates: only the table `ip ovpmon` (replaced atomically with `nft -f`; other tables and the distribution's `nftables.service` are not touched), the ruleset file `/etc/ovpmon/nftables.nft` and the boot service `ovpmon-nft` (systemd oneshot / OpenRC). The `nftables` package is installed on request only (it is not part of the install packages). IPv4 only.
Notes:
- "Every other network" includes container bridges and tunnels on the host; use `--out-if` to limit it.
- The VPN network must not overlap with the network of another interface (the script stops).
- The options are not remembered: after a change of the VPN subnet in the UI run the script again with the same options.
- The MSS clamp complements `tun-mtu` / `mssfix` of the server settings, it does not replace them. If another nftables table has a `policy drop`, allow the VPN traffic and ICMP "fragmentation needed" (type 3, code 4) there, otherwise path MTU discovery fails.
- Old manual rules (`iptables -t nat ... MASQUERADE` for the same network) are reported: remove them when this script is the one to keep.
- The filtering policy (INPUT/FORWARD allow/drop, ports, anti-leak) is not part of the script.
### Manual rules (iptables / nftables)
Replace `eth0` with the uplink interface and `172.20.1.0/24` with the VPN subnet of the server settings.
```sh
# iptables: services
iptables -A INPUT -p tcp --dport 8088 -j ACCEPT # UI (your HTTPS port)
iptables -A INPUT -p udp --dport 1194 -j ACCEPT # OpenVPN (your VPN port)
# iptables: NAT and forwarding for the VPN clients
iptables -t nat -A POSTROUTING -s 172.20.1.0/24 -o eth0 -j MASQUERADE
iptables -A FORWARD -i tun+ -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o tun+ -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
```
nftables equivalent:
```sh
nft add table inet ovpmon
nft 'add chain inet ovpmon input { type filter hook input priority 0 ; }'
nft add rule inet ovpmon input tcp dport 8088 accept
nft add rule inet ovpmon input udp dport 1194 accept
nft 'add chain inet ovpmon forward { type filter hook forward priority 0 ; }'
nft add rule inet ovpmon forward iifname "tun*" oifname "eth0" accept
nft add rule inet ovpmon forward iifname "eth0" oifname "tun*" ct state established,related accept
nft 'add table ip ovpmon_nat'
nft 'add chain ip ovpmon_nat postrouting { type nat hook postrouting priority 100 ; }'
nft add rule ip ovpmon_nat postrouting ip saddr 172.20.1.0/24 oifname "eth0" masquerade
```
(Add the `input`/`forward` rules only when your firewall policy is `drop`; a chain with priority 0 and policy accept does not block anything on its own.)
Persistence:
| System | Make the rules survive a reboot |
|---|---|
| Alpine | `rc-service iptables save && rc-update add iptables` (rules in `/etc/iptables/rules-save`); nftables: `rc-update add nftables`, rules in `/etc/nftables.nft` |
| Debian / Ubuntu | `apt-get install iptables-persistent`, then `netfilter-persistent save`; nftables: put the rules in `/etc/nftables.conf` and `systemctl enable nftables` |
## Update
```sh
deploy/native/update.sh # run from the checkout with the new version
deploy/native/update.sh --ui-dist /root/ui-dist.tar.gz # install this UI (tarball or directory), always
deploy/native/update.sh --build-ui # build the UI from APP_UI on this host and install it
deploy/native/update.sh --source /root/ovpmon-src --yes # another checkout, no questions
deploy/native/update.sh --no-pull # sources already in place / offline
deploy/native/update.sh --rollback # manual rollback to the newest backup
```
Run it from the checkout that holds the new version (the script uses the templates of that checkout). `--prefix` and the HTTPS port come from `/etc/ovpmon/deploy.state`. The update needs access to PyPI for the new virtualenvs.
Each phase is logged separately:
| Phase | What happens | If it fails |
|---|---|---|
| 0 Preflight | installation present, no unfinished install, source checkout complete, an explicit UI source readable (`--build-ui`: builder usable), services state, databases found, free space (backup and new code) | nothing was changed |
| 1 **Backup** | verified backup in `/var/backups/ovpmon/<UTC timestamp>/` (see below) | the update is **refused**, nothing was changed |
| 2 Sources | `git pull --ff-only` of the source checkout (skipped with `--no-pull` or without git) | nothing was changed |
| 3 Prepare | new code copied to `<prefix>.new`, fresh virtualenvs with `pip install -r requirements.txt`, import check; the UI source is decided (after `git pull`: `--ui-dist`, `--build-ui`, the committed build; unchanged hash means no swap) and the new UI is staged next to the web root. **The running system is not touched** | nothing was changed |
| 4 Stop and swap | the three application services are stopped (**OpenVPN keeps running**, VPN users stay connected); a final consistent snapshot; each code directory is renamed to `<dir>.old-<time>`, the new one moved in; **PKI, client profiles, `profiler.log`, `config.ini` and any database files below the code directory are moved over, never replaced**; virtualenv paths fixed | automatic rollback |
| 5 **Database migration** | its own step, see below | automatic rollback, **nothing is started** |
| 6 Files | UI swap (when a new UI was staged); helper; `helper.conf` (when missing); doas rules; service definitions; missing environment keys added (existing values never changed); nginx site; each replaced only when it differs and is managed by these scripts; units reloaded | automatic rollback |
| 7 Start | services started, health checks, helper self-test | automatic rollback |
| 8 Finish | the old code directories are removed (never one that still holds PKI data), the newest 5 backups kept, state recorded | |
The new `deploy/native/*.sh` take effect on the next run (the running script is not replaced).
### Database migration as its own step
After the services are stopped and the new code is in place, and **before anything is started**, `update.sh` runs for each database, with the **new** code, as user `ovpmon` and with the variables of `/etc/ovpmon/env` loaded:
| Database | Command (working directory) |
|---|---|
| Profiler | `APP_PROFILER/venv/bin/python migrate.py` in `<prefix>/APP_PROFILER` |
| Monitoring | `APP_CORE/venv/bin/python migrate.py` in `<prefix>/APP_CORE` |
For each one: `migrate.py --check` (exit 0 up to date, 2 pending, 1 error or database newer than the code), the migration when 2, and a second check. The reports are printed. A failure or a "too new" database aborts **before any service starts** and triggers the rollback. Migrations are additive, run after an integrity check and a consistent copy `<db>.bak-<UTC timestamp>` next to the database, and are verified afterwards; details in [Database migrations](../General/Database_Migrations.md). The migration also runs by itself when a service starts, so a manual file replacement is safe too; `update.sh` only makes it a visible, controlled step.
### Backup (phase 1, `backup.sh`)
```sh
deploy/native/backup.sh # backup into /var/backups/ovpmon/<UTC timestamp>/
deploy/native/backup.sh --stop # services stopped during the copy, started afterwards
deploy/native/backup.sh --keep 14 # afterwards keep the newest 14
```
Cron example (nightly, 14 kept): `30 3 * * * /opt/OpenVPN-Monitoring-Simple/deploy/native/backup.sh --keep 14 >> /var/log/ovpmon-backup.log 2>&1`.
| Content | File in the backup |
|---|---|
| both databases, consistent copies from the SQLite backup API (integrity-checked, owner and mode kept) | `db/monitor.db`, `db/profiler.db` |
| `/etc/ovpmon` (environment, helper configuration, certificate, state) | `etc-ovpmon.tar.gz` |
| `/etc/openvpn` (`server.conf`, `crl.pem`, scripts, `ipp.txt`) | `etc-openvpn.tar.gz` |
| PKI `APP_PROFILER/easy-rsa` | `easy-rsa.tar.gz` |
| client profiles `APP_PROFILER/client-config` | `client-config.tar.gz` |
| `APP_CORE` and `APP_PROFILER` including the virtualenvs (needed for rollback) | `code.tar.gz` |
| helper, service definitions, nginx site, sysctl file, doas file (Alpine) | `system.tar.gz` |
| doas block (Debian/Ubuntu) | `doas-block.txt` |
| UI files | `ui.tar.gz` |
| checksums, description, completion marker | `SHA256SUMS`, `MANIFEST`, `COMPLETE` |
Every archive is verified (`tar -tzf`), the checksums are checked and each database copy passes `PRAGMA integrity_check` before `COMPLETE` is written; **only a `COMPLETE` backup is ever used**. `update.sh` backs up twice: in phase 1, and again as a final snapshot once the services are stopped (the code archive is reused). The backup holds private keys, password hashes and the signing secret: the directory is mode 700, the files mode 600. Keep copies off the host.
### Restore
```sh
deploy/native/restore.sh /var/backups/ovpmon/20261005T101500Z # asks, stops, saves the current state, restores
deploy/native/restore.sh /var/backups/ovpmon/20261005T101500Z --yes --start
```
It verifies the backup, stops the three application services, saves the **current state** to `/var/backups/ovpmon/<time>-pre-restore` (`OVPMON_NO_SAFETY_BACKUP=1` skips this), then restores code, databases, `/etc/ovpmon`, `/etc/openvpn`, PKI, client profiles, helper, service definitions, nginx site, UI and doas rules. A replaced database is kept as `<db>.failed-<time>`. OpenVPN is not stopped. On a new host run `install.sh` first, then `restore.sh`.
Manual equivalent (services stopped, paths for the default prefix):
```sh
B=/var/backups/ovpmon/20261005T101500Z
( cd $B && sha256sum -c SHA256SUMS )
tar -xzpf $B/code.tar.gz -C /opt/OpenVPN-Monitoring-Simple # after moving the current APP_CORE and APP_PROFILER aside
tar -xzpf $B/easy-rsa.tar.gz -C /opt/OpenVPN-Monitoring-Simple/APP_PROFILER
tar -xzpf $B/client-config.tar.gz -C /opt/OpenVPN-Monitoring-Simple/APP_PROFILER
cp -p $B/db/profiler.db /var/lib/ovpmon/ovpn_profiler.db # the backup was made with the sqlite backup API
cp -p $B/db/monitor.db /var/lib/ovpmon/openvpn_monitor.db
tar -xzpf $B/etc-ovpmon.tar.gz -C / && tar -xzpf $B/etc-openvpn.tar.gz -C /
tar -xzpf $B/system.tar.gz -C / # helper, service definitions, nginx site
```
A single database can also be put back from its migration copy `<db>.bak-<time>` in `/var/lib/ovpmon`: stop the services, copy it over the database, start the OLD release.
### Automatic rollback and `--rollback`
On any failure from phase 4 on: the services are stopped, **code, databases, `/etc/ovpmon`, `/etc/openvpn`, helper, doas rules, service definitions, nginx site and UI files are restored from the backup of this run**, the services are started and checked, and the result is reported with the backup path.
How the code is restored: the current (new or half-swapped) code directories are renamed to `<dir>.rollback-<time>`, `code.tar.gz` is extracted (old code **and old virtualenvs**, so no Internet is needed), and the PKI and client profiles, which the update never replaced, are moved back from the directory that held them. They are restored from `easy-rsa.tar.gz` / `client-config.tar.gz` only if they are missing. The failed databases are kept as `<db>.failed-<time>`. If the rollback itself fails the message says where the backup is and how to retry (`update.sh --rollback` or `restore.sh`).
`update.sh --rollback` does the same by hand from the newest `COMPLETE` backup after a confirmation, with one difference: PKI and client profiles come from the backup too (one consistent set with the databases), and the current state is saved first to `<time>-pre-restore`. Use it when an update succeeded but the new version misbehaves. Data created after that backup is lost (it is in the `-pre-restore` copy).
## Existing installations (adoption)
A host that was set up by hand (the layout of the old guide: code in `/opt/OpenVPN-Monitoring-Simple`, `/etc/ovpmon/env`, init scripts or units, helper and doas rules) can be updated with `update.sh`: it has no state file, so it is adopted and recorded after the first successful update. Files that these scripts do not manage are **left as they are**: init scripts, units, an nginx site and a doas file that do not carry the marker line `managed by ovpmon deploy/native` and differ from the shipped ones are only reported. The helper is replaced (the new one behaves like the old one without `helper.conf`), `helper.conf` is written when missing, and `OVPMON_RUNTIME`, `OVPMON_OPENVPN_SERVICE` and `OVPMON_OPENVPN_CONFIG` are added to the environment file only when absent. If the install directory is a git checkout (the source is the install directory), `git pull` changes the live files, therefore a rollback is armed from phase 2.
## What is preserved on update
| Item | On update |
|---|---|
| Databases | Kept in place, backed up twice (consistent copies), migrated additively with their own `<db>.bak-*` copy; restored automatically if the update fails after the stop |
| PKI (`APP_PROFILER/easy-rsa`): CA, keys, certificates, CRL | Moved, never replaced or deleted, backed up |
| Client profiles (`APP_PROFILER/client-config`) | Moved, never replaced or deleted, backed up |
| `/etc/ovpmon/env` (secret, DB paths) | Kept; only missing keys are added; copied into every backup |
| `/etc/ovpmon/helper.conf`, TLS certificate and key | Kept (helper.conf is rewritten only while it carries our marker and differs) |
| `/etc/openvpn` (`server.conf`, `crl.pem`, scripts, `ipp.txt`) | Not touched by the update; backed up |
| OpenVPN process and VPN sessions | Not stopped or restarted; connected users stay connected |
| `config.ini` of both components | Kept; the shipped one of the new version is saved as `config.ini.dist` when it differs |
| `profiler.log`, other `*.log` / `*.db` files below the code directories | Kept (moved) |
| Code, virtualenvs | **Replaced** (fresh virtualenvs; the old ones are in the backup) |
| UI files | Replaced with `--ui-dist` / `--build-ui`, or automatically when the committed build of the source differs from the installed one (`.ui-source-hash`); kept when there is no UI source; the previous ones are in the backup |
| Service definitions, nginx site, doas rules, helper | Replaced when they differ and are managed by these scripts; the previous ones are in the backup |
| User sessions | Stay valid while the secret is unchanged |
| Backups in `/var/backups/ovpmon` | The newest 5 kept, older ones pruned after a successful update; `-pre-restore` copies are never pruned automatically |
| Data directories (`/var/lib/ovpmon`, PKI, client profiles) | **Never deleted** by any script |
## Troubleshooting
| Symptom | Cause and action |
|---|---|
| `invalid --prefix ...` / `no valid install directory given` | The install directory must be a new or empty dedicated directory, not the repository checkout and not a system directory. Move or clone the repository elsewhere (for example `/root/ovpmon-src`) or choose another directory |
| `already installed ... use update.sh` / `an installation already exists` | `install.sh` never installs over an installation. Use `update.sh` (it adopts hand-made installations) |
| `installation stopped in phase ...` | Fix the cause and run `install.sh` again: it resumes and keeps secrets, certificate and data |
| `not a tested version ... needs --force` | Untested OS version: `install.sh --force` at your own risk |
| `ports ... already in use` | Another service uses 5001, 8000 or the HTTPS port: stop it or use `--https-port` |
| `pip install failed` | No access to the Python package index (proxy: `pip` honours `HTTPS_PROXY`); on Alpine check that `py3-pip` is installed |
| Health check fails | Alpine: `tail /var/log/ovpmon/ovpmon-api.log` (or `-gatherer`, `-profiler`); systemd: `journalctl -u ovpmon-api -n 50`. The scripts print the last lines of a failing service |
| `FATAL: ... newer than this version` / migration "too new" | The database was migrated by a newer release. Do not start the old version on it: update to the newer sources or restore a matching backup |
| Migration failed | Nothing was started and the rollback restored the databases; the report names the migration, the `<db>.bak-*` copy is in `/var/lib/ovpmon`. Keep the report |
| Profiler cannot start/stop OpenVPN, "helper failed" | The self-test warning of the scripts points at it: check the doas rules (`doas -C /etc/doas.conf` or `/etc/doas.d/ovpmon.conf`), `/etc/ovpmon/helper.conf` (must be `root:root` and not group/world writable; `su -s /bin/sh ovpmon -c "doas -n /usr/local/sbin/ovpmon-helper service status"` prints the reason) |
| `Configuration rejected` when generating the server config | The helper allowlist refused a directive, see [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md) |
| OpenVPN does not start on Debian/Ubuntu | `systemctl status openvpn-server@server`, `journalctl -u openvpn-server@server`; the config must be `/etc/openvpn/server/server.conf` and `/dev/net/tun` must exist |
| Clients connect but have no internet | Forwarding or NAT is missing: see the firewall section |
| nginx: `conflicting server name` / port in use | Another site uses the same port; change `--https-port` (or the `listen` line of the site and reload) |
| Browser warns about the certificate | It is self-signed; check the fingerprint printed by `install.sh`, or install a real certificate under `/etc/ovpmon/tls/` and reload nginx |
| `no UI source found` (install stops) | The checkout has no `deploy/ui-dist` (incomplete clone, or the maintainer did not publish it) and no `--ui-dist`. Use `--build-ui` (Docker or Node 20.19+; `--node-download` on Debian/Ubuntu), `--ui-dist FILE\|DIR` from another machine, or `--no-ui` for a placeholder page |
| Warning "committed UI build ... is OLDER than the APP_UI sources" | Someone changed `APP_UI` without refreshing the build. Maintainers: `deploy/native/build-ui.sh --publish` and commit `deploy/ui-dist`. On the host: `--build-ui` |
| `the installed Node is too old` / `node and npm are not installed` (`--build-ui`, `build-ui.sh --local`) | The message lists the commands for the OS: Alpine `apk add nodejs npm`; Debian/Ubuntu `--node-download` or Node 20+ from nodejs.org |
| UI shows the placeholder page | Installed with `--no-ui`: run `deploy/native/update.sh` (installs the UI of the repository), or add `--ui-dist` / `--build-ui` |
| `su`/`doas` self-test fails on a minimal container | Containers often lack `/etc/pam.d/doas` or a real init system; the services may still work (check health) |
## Host hardening (recommended, not done by the scripts)
- SSH: key-only (`PasswordAuthentication no`, `KbdInteractiveAuthentication no`, `PermitRootLogin prohibit-password`). Cloud-init drop-ins in `/etc/ssh/sshd_config.d/` can override the main file, so put your settings in a file that sorts first, for example `00-hardening.conf`.
- fail2ban: jails `sshd` and one for `POST /api/auth/login` (HTTP 401/429/503) on the nginx access log.
- Backends are bound to `127.0.0.1`; only the HTTPS port and the VPN port should be reachable from outside.
- Keep the system updated (`apk upgrade` / `apt-get upgrade`) and watch the advisories of OpenVPN, nginx and OpenSSH.
## Verify an installation
```sh
rc-status | grep -E "ovpmon|nginx|openvpn" # Alpine; Debian/Ubuntu: systemctl status 'ovpmon-*' nginx
ss -tlnp | grep -E ":(8088|5001|8000) "
curl -sk -o /dev/null -w "%{http_code}\n" https://127.0.0.1:8088/ # 200
curl -sk -o /dev/null -w "%{http_code}\n" https://127.0.0.1:8088/profiles-api/config # 401 without a token
su -s /bin/sh ovpmon -c "doas -n /usr/local/sbin/ovpmon-helper service status" # JSON, not "Operation not permitted"
```
## Security notes
- Services run as `ovpmon` (no login shell); code and virtualenvs are root-owned and read-only for them. systemd units add `PrivateTmp`, `ProtectHome`, `ProtectSystem=full`, kernel and cgroup protection; `ovpmon-api` and `ovpmon-gatherer` also set `NoNewPrivileges`. `ovpmon-profiler` must **not** (it calls the setuid `doas`), must not use seccomp-based options either (`ProtectKernelTunables`, `ProtectKernelModules`, `RestrictRealtime`, `LockPersonality`, `SystemCallFilter`, ...): for an unprivileged unit systemd then sets NoNewPrivileges implicitly and `doas` fails with "not installed setuid" (check: `grep NoNewPrivs /proc/<main pid>/status` must show 0). It keeps `/etc/openvpn` writable, because the helper runs inside the profiler's mount namespace.
- The helper accepts six fixed commands, validates `server.conf` against an allowlist and reads its own root-owned configuration; nothing else runs as root. `ovpmon` owns the PKI including the CA key: a compromised profiler can issue client certificates (VPN access) but cannot become root.
- `/etc/ovpmon/env` is `root:root` 600 and never printed; the generated administrator password is shown once and removed from the file after the first start.
- Backups contain private keys, password hashes and the secret: mode 700/600, keep off-host copies encrypted.
- Both APIs listen on `127.0.0.1`; only nginx (HTTPS) and OpenVPN are reachable. Replace the self-signed certificate when a domain is available; consider restricting the UI by address or reaching it through the VPN.
- The scripts do not harden SSH or install fail2ban: see the next section.
Related: [Database migrations](../General/Database_Migrations.md), [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md), [Scenario 1: containers](Scenario1_Containers.md), [Deployment plan](../Changes/2026-10-05_Deployment_Scenarios_PLAN.md).
@@ -0,0 +1,74 @@
# System services: firewall, NAT and forwarding
Install: [System services](README.md).
`install.sh` and `update.sh` **never touch the firewall**. `net.ipv4.ip_forward=1` is set persistently in `/etc/sysctl.d/98-ovpmon-forward.conf`. Opening the ports (UI, VPN) is yours. NAT and packet tuning for the VPN clients are done by a separate opt-in script.
## `deploy/native/firewall.sh` (nftables)
Reads the interfaces of this server and applies, for traffic **from the VPN network to every other network**: masquerade, TCP MSS clamping (path MTU tuning) and TTL tuning. Run it as root after the VPN server configuration exists (the VPN network is read from the `server` line of `server.conf`).
```sh
deploy/native/firewall.sh --dry-run # show what was detected and the ruleset; change nothing
deploy/native/firewall.sh # apply, ask for confirmation, load at boot
deploy/native/firewall.sh status # loaded rules with counters, boot service, detected parameters
deploy/native/firewall.sh remove # delete the rules, the ruleset file and the boot service
```
| Option | Meaning |
|---|---|
| `--vpn-net CIDR` | VPN network. Default: `server` line of the OpenVPN config, else the address of the VPN interface |
| `--vpn-if NAME` | VPN interface. Default: the interface with an address in the VPN network, else the `dev` line, else `tun*` |
| `--out-if A,B` | Only these interfaces (exact names) are "other networks". Default: every interface except `lo` and the VPN interface, so new uplinks (VLAN, `hytun`, a second ISP) need no rerun |
| `--ttl N` / `--no-ttl` | TTL of packets leaving towards the other networks (default 64, set after the forwarding decrement) |
| `--mss pmtu\|N` / `--no-mss` | TCP MSS of SYN and SYN-ACK in both directions: `pmtu` = MTU of the route of each connection (default), or a fixed value |
| `--no-persist` | Running kernel only: no ruleset file, no boot service |
| `--yes`, `--force` | No questions; continue on an untested OS version |
What it creates: only the table `ip ovpmon` (replaced atomically with `nft -f`; other tables and the distribution's `nftables.service` are not touched), the ruleset file `/etc/ovpmon/nftables.nft` and the boot service `ovpmon-nft` (systemd oneshot / OpenRC). The `nftables` package is installed on request only (it is not part of the install packages). IPv4 only.
Notes:
- "Every other network" includes container bridges and tunnels on the host; use `--out-if` to limit it.
- The VPN network must not overlap with the network of another interface (the script stops).
- The options are not remembered: after a change of the VPN subnet in the UI run the script again with the same options.
- The MSS clamp complements `tun-mtu` / `mssfix` of the server settings, it does not replace them. If another nftables table has a `policy drop`, allow the VPN traffic and ICMP "fragmentation needed" (type 3, code 4) there, otherwise path MTU discovery fails.
- Old manual rules (`iptables -t nat ... MASQUERADE` for the same network) are reported: remove them when this script is the one to keep.
- The filtering policy (INPUT/FORWARD allow/drop, ports, anti-leak) is not part of the script.
## Manual rules (iptables / nftables)
Replace `eth0` with the uplink interface and `172.20.1.0/24` with the VPN subnet of the server settings.
```sh
# iptables: services
iptables -A INPUT -p tcp --dport 8088 -j ACCEPT # UI (your HTTPS port)
iptables -A INPUT -p udp --dport 1194 -j ACCEPT # OpenVPN (your VPN port)
# iptables: NAT and forwarding for the VPN clients
iptables -t nat -A POSTROUTING -s 172.20.1.0/24 -o eth0 -j MASQUERADE
iptables -A FORWARD -i tun+ -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o tun+ -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
```
nftables equivalent:
```sh
nft add table inet ovpmon
nft 'add chain inet ovpmon input { type filter hook input priority 0 ; }'
nft add rule inet ovpmon input tcp dport 8088 accept
nft add rule inet ovpmon input udp dport 1194 accept
nft 'add chain inet ovpmon forward { type filter hook forward priority 0 ; }'
nft add rule inet ovpmon forward iifname "tun*" oifname "eth0" accept
nft add rule inet ovpmon forward iifname "eth0" oifname "tun*" ct state established,related accept
nft 'add table ip ovpmon_nat'
nft 'add chain ip ovpmon_nat postrouting { type nat hook postrouting priority 100 ; }'
nft add rule ip ovpmon_nat postrouting ip saddr 172.20.1.0/24 oifname "eth0" masquerade
```
(Add the `input`/`forward` rules only when your firewall policy is `drop`; a chain with priority 0 and policy accept does not block anything on its own.)
Persistence:
| System | Make the rules survive a reboot |
|---|---|
| Alpine | `rc-service iptables save && rc-update add iptables` (rules in `/etc/iptables/rules-save`); nftables: `rc-update add nftables`, rules in `/etc/nftables.nft` |
| Debian / Ubuntu | `apt-get install iptables-persistent`, then `netfilter-persistent save`; nftables: put the rules in `/etc/nftables.conf` and `systemctl enable nftables` |
@@ -0,0 +1,125 @@
# System services: update, backup, restore, rollback
Day-2 operations. Every update takes a verified backup first and rolls back automatically on failure. Install: [System services](README.md).
## Update
```sh
deploy/native/update.sh # run from the checkout with the new version
deploy/native/update.sh --ui-dist /root/ui-dist.tar.gz # install this UI (tarball or directory), always
deploy/native/update.sh --build-ui # build the UI from APP_UI on this host and install it
deploy/native/update.sh --source /root/ovpmon-src --yes # another checkout, no questions
deploy/native/update.sh --no-pull # sources already in place / offline
deploy/native/update.sh --rollback # manual rollback to the newest backup
```
Run it from the checkout that holds the new version (the script uses the templates of that checkout). `--prefix` and the HTTPS port come from `/etc/ovpmon/deploy.state`. The update needs access to PyPI for the new virtualenvs.
Each phase is logged separately:
| Phase | What happens | If it fails |
|---|---|---|
| 0 Preflight | installation present, no unfinished install, source checkout complete, an explicit UI source readable (`--build-ui`: builder usable), services state, databases found, free space (backup and new code) | nothing was changed |
| 1 **Backup** | verified backup in `/var/backups/ovpmon/<UTC timestamp>/` (see below) | the update is **refused**, nothing was changed |
| 2 Sources | `git pull --ff-only` of the source checkout (skipped with `--no-pull` or without git) | nothing was changed |
| 3 Prepare | new code copied to `<prefix>.new`, fresh virtualenvs with `pip install -r requirements.txt`, import check; the UI source is decided (after `git pull`: `--ui-dist`, `--build-ui`, the committed build; unchanged hash means no swap) and the new UI is staged next to the web root. **The running system is not touched** | nothing was changed |
| 4 Stop and swap | the three application services are stopped (**OpenVPN keeps running**, VPN users stay connected); a final consistent snapshot; each code directory is renamed to `<dir>.old-<time>`, the new one moved in; **PKI, client profiles, `profiler.log`, `config.ini` and any database files below the code directory are moved over, never replaced**; virtualenv paths fixed | automatic rollback |
| 5 **Database migration** | its own step, see below | automatic rollback, **nothing is started** |
| 6 Files | UI swap (when a new UI was staged); helper; `helper.conf` (when missing); doas rules; service definitions; missing environment keys added (existing values never changed); nginx site; each replaced only when it differs and is managed by these scripts; units reloaded | automatic rollback |
| 7 Start | services started, health checks, helper self-test | automatic rollback |
| 8 Finish | the old code directories are removed (never one that still holds PKI data), the newest 5 backups kept, state recorded | |
The new `deploy/native/*.sh` take effect on the next run (the running script is not replaced).
### Database migration as its own step
After the services are stopped and the new code is in place, and **before anything is started**, `update.sh` runs for each database, with the **new** code, as user `ovpmon` and with the variables of `/etc/ovpmon/env` loaded:
| Database | Command (working directory) |
|---|---|
| Profiler | `APP_PROFILER/venv/bin/python migrate.py` in `<prefix>/APP_PROFILER` |
| Monitoring | `APP_CORE/venv/bin/python migrate.py` in `<prefix>/APP_CORE` |
For each one: `migrate.py --check` (exit 0 up to date, 2 pending, 1 error or database newer than the code), the migration when 2, and a second check. The reports are printed. A failure or a "too new" database aborts **before any service starts** and triggers the rollback. Migrations are additive, run after an integrity check and a consistent copy `<db>.bak-<UTC timestamp>` next to the database, and are verified afterwards; details in [Database migrations](../../General/Database_Migrations.md). The migration also runs by itself when a service starts, so a manual file replacement is safe too; `update.sh` only makes it a visible, controlled step.
### Backup (phase 1, `backup.sh`)
```sh
deploy/native/backup.sh # backup into /var/backups/ovpmon/<UTC timestamp>/
deploy/native/backup.sh --stop # services stopped during the copy, started afterwards
deploy/native/backup.sh --keep 14 # afterwards keep the newest 14
```
Cron example (nightly, 14 kept): `30 3 * * * /opt/OpenVPN-Monitoring-Simple/deploy/native/backup.sh --keep 14 >> /var/log/ovpmon-backup.log 2>&1`.
| Content | File in the backup |
|---|---|
| both databases, consistent copies from the SQLite backup API (integrity-checked, owner and mode kept) | `db/monitor.db`, `db/profiler.db` |
| `/etc/ovpmon` (environment, helper configuration, certificate, state) | `etc-ovpmon.tar.gz` |
| `/etc/openvpn` (`server.conf`, `crl.pem`, scripts, `ipp.txt`) | `etc-openvpn.tar.gz` |
| PKI `APP_PROFILER/easy-rsa` | `easy-rsa.tar.gz` |
| client profiles `APP_PROFILER/client-config` | `client-config.tar.gz` |
| `APP_CORE` and `APP_PROFILER` including the virtualenvs (needed for rollback) | `code.tar.gz` |
| helper, service definitions, nginx site, sysctl file, doas file (Alpine) | `system.tar.gz` |
| doas block (Debian/Ubuntu) | `doas-block.txt` |
| UI files | `ui.tar.gz` |
| checksums, description, completion marker | `SHA256SUMS`, `MANIFEST`, `COMPLETE` |
Every archive is verified (`tar -tzf`), the checksums are checked and each database copy passes `PRAGMA integrity_check` before `COMPLETE` is written; **only a `COMPLETE` backup is ever used**. `update.sh` backs up twice: in phase 1, and again as a final snapshot once the services are stopped (the code archive is reused). The backup holds private keys, password hashes and the signing secret: the directory is mode 700, the files mode 600. Keep copies off the host.
### Restore
```sh
deploy/native/restore.sh /var/backups/ovpmon/20261005T101500Z # asks, stops, saves the current state, restores
deploy/native/restore.sh /var/backups/ovpmon/20261005T101500Z --yes --start
```
It verifies the backup, stops the three application services, saves the **current state** to `/var/backups/ovpmon/<time>-pre-restore` (`OVPMON_NO_SAFETY_BACKUP=1` skips this), then restores code, databases, `/etc/ovpmon`, `/etc/openvpn`, PKI, client profiles, helper, service definitions, nginx site, UI and doas rules. A replaced database is kept as `<db>.failed-<time>`. OpenVPN is not stopped. On a new host run `install.sh` first, then `restore.sh`.
Manual equivalent (services stopped, paths for the default prefix):
```sh
B=/var/backups/ovpmon/20261005T101500Z
( cd $B && sha256sum -c SHA256SUMS )
tar -xzpf $B/code.tar.gz -C /opt/OpenVPN-Monitoring-Simple # after moving the current APP_CORE and APP_PROFILER aside
tar -xzpf $B/easy-rsa.tar.gz -C /opt/OpenVPN-Monitoring-Simple/APP_PROFILER
tar -xzpf $B/client-config.tar.gz -C /opt/OpenVPN-Monitoring-Simple/APP_PROFILER
cp -p $B/db/profiler.db /var/lib/ovpmon/ovpn_profiler.db # the backup was made with the sqlite backup API
cp -p $B/db/monitor.db /var/lib/ovpmon/openvpn_monitor.db
tar -xzpf $B/etc-ovpmon.tar.gz -C / && tar -xzpf $B/etc-openvpn.tar.gz -C /
tar -xzpf $B/system.tar.gz -C / # helper, service definitions, nginx site
```
A single database can also be put back from its migration copy `<db>.bak-<time>` in `/var/lib/ovpmon`: stop the services, copy it over the database, start the OLD release.
### Automatic rollback and `--rollback`
On any failure from phase 4 on: the services are stopped, **code, databases, `/etc/ovpmon`, `/etc/openvpn`, helper, doas rules, service definitions, nginx site and UI files are restored from the backup of this run**, the services are started and checked, and the result is reported with the backup path.
How the code is restored: the current (new or half-swapped) code directories are renamed to `<dir>.rollback-<time>`, `code.tar.gz` is extracted (old code **and old virtualenvs**, so no Internet is needed), and the PKI and client profiles, which the update never replaced, are moved back from the directory that held them. They are restored from `easy-rsa.tar.gz` / `client-config.tar.gz` only if they are missing. The failed databases are kept as `<db>.failed-<time>`. If the rollback itself fails the message says where the backup is and how to retry (`update.sh --rollback` or `restore.sh`).
`update.sh --rollback` does the same by hand from the newest `COMPLETE` backup after a confirmation, with one difference: PKI and client profiles come from the backup too (one consistent set with the databases), and the current state is saved first to `<time>-pre-restore`. Use it when an update succeeded but the new version misbehaves. Data created after that backup is lost (it is in the `-pre-restore` copy).
## Existing installations (adoption)
A host that was set up by hand (the layout of the old guide: code in `/opt/OpenVPN-Monitoring-Simple`, `/etc/ovpmon/env`, init scripts or units, helper and doas rules) can be updated with `update.sh`: it has no state file, so it is adopted and recorded after the first successful update. Files that these scripts do not manage are **left as they are**: init scripts, units, an nginx site and a doas file that do not carry the marker line `managed by ovpmon deploy/native` and differ from the shipped ones are only reported. The helper is replaced (the new one behaves like the old one without `helper.conf`), `helper.conf` is written when missing, and `OVPMON_RUNTIME`, `OVPMON_OPENVPN_SERVICE` and `OVPMON_OPENVPN_CONFIG` are added to the environment file only when absent. If the install directory is a git checkout (the source is the install directory), `git pull` changes the live files, therefore a rollback is armed from phase 2.
## What is preserved on update
| Item | On update |
|---|---|
| Databases | Kept in place, backed up twice (consistent copies), migrated additively with their own `<db>.bak-*` copy; restored automatically if the update fails after the stop |
| PKI (`APP_PROFILER/easy-rsa`): CA, keys, certificates, CRL | Moved, never replaced or deleted, backed up |
| Client profiles (`APP_PROFILER/client-config`) | Moved, never replaced or deleted, backed up |
| `/etc/ovpmon/env` (secret, DB paths) | Kept; only missing keys are added; copied into every backup |
| `/etc/ovpmon/helper.conf`, TLS certificate and key | Kept (helper.conf is rewritten only while it carries our marker and differs) |
| `/etc/openvpn` (`server.conf`, `crl.pem`, scripts, `ipp.txt`) | Not touched by the update; backed up |
| OpenVPN process and VPN sessions | Not stopped or restarted; connected users stay connected |
| `config.ini` of both components | Kept; the shipped one of the new version is saved as `config.ini.dist` when it differs |
| `profiler.log`, other `*.log` / `*.db` files below the code directories | Kept (moved) |
| Code, virtualenvs | **Replaced** (fresh virtualenvs; the old ones are in the backup) |
| UI files | Replaced with `--ui-dist` / `--build-ui`, or automatically when the committed build of the source differs from the installed one (`.ui-source-hash`); kept when there is no UI source; the previous ones are in the backup |
| Service definitions, nginx site, doas rules, helper | Replaced when they differ and are managed by these scripts; the previous ones are in the backup |
| User sessions | Stay valid while the secret is unchanged |
| Backups in `/var/backups/ovpmon` | The newest 5 kept, older ones pruned after a successful update; `-pre-restore` copies are never pruned automatically |
| Data directories (`/var/lib/ovpmon`, PKI, client profiles) | **Never deleted** by any script |
+158
View File
@@ -0,0 +1,158 @@
# System services (Alpine, Debian, Ubuntu)
Install the suite as system services without containers. This page: what gets installed, supported systems, requirements, install per OS, verification. Next pages: [Operations](Operations.md) (update, backup, rollback), [Reference](Reference.md) (paths, environment, helper), [Web UI](Web_UI.md), [Firewall](Firewall.md), [Nginx](Nginx_Configuration.md), [Services](Service_Management.md), [Troubleshooting](Troubleshooting.md).
## Quick start
As root on Alpine 3.23, Debian 12 or Ubuntu 24.04 (the script installs all other packages and asks for the install directory):
```sh
# Debian/Ubuntu: apt-get update && apt-get install -y git Alpine: apk add git
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --prefix /opt/OpenVPN-Monitoring-Simple
```
The script prints the URL (`https://<host>:8088/`), the certificate fingerprint and the **administrator login and password (shown once)**. Open the URL, then follow [First steps](../First_Steps.md). Details per system are below.
## Scripts
Install and update on **Alpine (OpenRC)**, **Debian** and **Ubuntu** (systemd) with the scripts in `deploy/native/`. Nothing runs in a container. The web UI is part of the repository (`deploy/ui-dist`) and is installed automatically, so the host needs no Node.
| Script | Purpose |
|---|---|
| `deploy/native/build-ui.sh` | builds the web UI (Docker, or the local Node without a container) into a tarball and/or into the repository (`--publish`) |
| `deploy/native/check-ui.sh` | checks that the committed UI build `deploy/ui-dist` matches the `APP_UI` sources (exit 1 when stale) |
| `deploy/native/install.sh` | first installation: packages, user, code, virtualenvs, configuration, services, nginx with TLS, health checks |
| `deploy/native/update.sh` | update with a verified backup, a separate database migration step and automatic rollback; `--rollback` for a manual one |
| `deploy/native/backup.sh` / `restore.sh` | stand-alone backup (cron friendly) and restore |
| `deploy/native/lib.sh` | shared functions and the OS adapter (sourced, not executed) |
All scripts run as root, support `-h`, log in one style (UTC time stamp, `=== PHASE n ===`) and append every log line to `/var/log/ovpmon-deploy.log`.
## What is installed
```
Browser --https:8088--> nginx --/--------------> /var/www/ovpmon (UI files)
--/api/----------> 127.0.0.1:5001 ovpmon-api (gunicorn, APP_CORE)
--/profiles-api/-> 127.0.0.1:8000 ovpmon-profiler (uvicorn, APP_PROFILER)
ovpmon-gatherer (APP_CORE): OpenVPN status log -> monitoring database
ovpmon-profiler (user ovpmon) --doas--> /usr/local/sbin/ovpmon-helper (root) --> server.conf, CRL, OpenVPN service
```
The three `ovpmon-*` services run as the unprivileged user `ovpmon`. Only the helper acts as root, through six fixed `doas` rules, and it validates everything it installs (see [Privilege separation](../../Changes/2026-09-30_Privilege_Separation.md)). The services do not require OpenVPN to be running: the VPN server is created and started from the UI.
## Supported systems
| System | Tested version | Service manager | Notes |
|---|---|---|---|
| Alpine | 3.23 | OpenRC | the original reference platform |
| Debian | 12 | systemd | |
| Ubuntu | 24.04 LTS | systemd | needs the `universe` repository (`easy-rsa`, `opendoas`) |
Another version of these systems is refused with a warning unless you pass `--force` to `install.sh` (the update only warns). Other distributions are not supported (a Debian derivative works with `--force` at your own risk).
## Requirements
- A host with root access, a working package manager and Internet access (packages, Python packages from PyPI).
- `/dev/net/tun` for OpenVPN (a normal VM has it; in containers it must be passed in).
- Free space: about 1 GB for the code and virtualenvs (the script checks it), plus room for the backups.
- Python 3.9 or newer (Alpine 3.23: 3.12, Debian 12: 3.11, Ubuntu 24.04: 3.12).
- Free TCP ports `5001`, `8000` (on `127.0.0.1`) and the HTTPS port (default `8088`).
- A UI build: the clone contains one (`deploy/ui-dist`, see [Web UI](Web_UI.md)). **The host needs no Node.js** unless you choose `--build-ui`.
- GNU tar (on Alpine the package `tar`; the installer adds it).
## Install
Clone the repository on the target host (anywhere **outside** the install directory: the checkout is only the source, e.g. `/root/ovpmon-src`) and run, as root. The UI comes with the clone (`deploy/ui-dist`, see [Web UI](Web_UI.md)). The install directory is always asked for: pass `--prefix DIR`, or the script prompts for it (and for a confirmation); there is no default. Recommended: `/opt/OpenVPN-Monitoring-Simple`.
### Alpine (OpenRC)
```sh
apk add git # only to clone; the script installs the rest
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --prefix /opt/OpenVPN-Monitoring-Simple
```
### Debian 12
```sh
apt-get update && apt-get install -y git
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --prefix /opt/OpenVPN-Monitoring-Simple
```
### Ubuntu 24.04
```sh
sudo -i
apt-get update && apt-get install -y git # make sure the "universe" component is enabled
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --prefix /opt/OpenVPN-Monitoring-Simple
```
Options:
| Option | Meaning |
|---|---|
| `--prefix DIR` | install directory, **required**: asked interactively when the option is missing (without a terminal the script stops). Absolute path of letters, digits, `. _ - /`, no trailing `/`; must be new or empty, must not be the repository checkout (or contain it, or lie inside it) and must not be a system directory (`/`, `/opt`, `/root`, `/usr`, `/var`, ...) |
| `--ui-dist FILE\|DIR` | UI tarball from `build-ui.sh` or a directory with `index.html`; highest priority |
| `--build-ui` | build the UI now from `APP_UI` (Docker, otherwise the host's Node 20.19+) instead of using `deploy/ui-dist` |
| `--node-download` | with `--build-ui`: use a temporary official Node 20 (checksum verified, glibc only) |
| `--no-ui` | install a placeholder page on purpose; without any UI source and without this option the install stops |
| `--https-port N` | HTTPS port of the web UI (default `8088`) |
| `--host-name NAME` | DNS name or IP for the certificate and the CORS origin (default: the detected address of the default route) |
| `--admin-user NAME` | login of the first administrator (default `admin`) |
| `--force` | continue on an untested OS version |
### Differences between the systems
| | Alpine 3.23 | Debian 12 / Ubuntu 24.04 |
|---|---|---|
| Packages | `python3 py3-pip nginx openvpn easy-rsa iptables bash doas openssl curl tar` | `python3 python3-venv python3-pip nginx openvpn easy-rsa iptables opendoas openssl curl ca-certificates tar iproute2` |
| Service manager | OpenRC: `rc-service NAME start\|stop\|restart\|status`, `rc-update add NAME default` | systemd: `systemctl start\|stop\|restart\|status NAME`, `systemctl enable NAME` |
| Our service files | `/etc/init.d/ovpmon-api`, `-gatherer`, `-profiler` (`supervise-daemon`, `command_user=ovpmon:ovpmon`) | `/etc/systemd/system/ovpmon-*.service` (`User=ovpmon`, `EnvironmentFile=/etc/ovpmon/env`) |
| Service logs | `/var/log/ovpmon/ovpmon-<name>.log` | `journalctl -u ovpmon-<name>` |
| OpenVPN service | `openvpn`; config `/etc/openvpn/server.conf`, plus the link `/etc/openvpn/openvpn.conf -> server.conf` | `openvpn-server@server`; config `/etc/openvpn/server/server.conf` |
| nginx site | `/etc/nginx/http.d/ovpmon.conf` | `/etc/nginx/conf.d/ovpmon.conf` |
| doas | package `doas`; our rules in `/etc/doas.d/ovpmon.conf` (own file, as on the existing hosts) | package `opendoas`; our rules as a marked block inside `/etc/doas.conf` |
| `ovpmon` user | `adduser -S`, shell `/sbin/nologin` | `useradd --system`, shell `/usr/sbin/nologin` |
The nginx site does not collide with the distribution defaults: the default server of Alpine and Debian listens on port 80, ours on 8088, and both distribution `nginx.conf` files include the directory above (the installer checks the `include` line).
### What `install.sh` does
| Phase | Content |
|---|---|
| 0 Preflight | root, OS and version, service manager present, no existing installation (otherwise it points to `update.sh`), source checkout complete, UI source found (and built for `--build-ui`; a stale committed build only warns), ports free, free space |
| 1 Packages | the table above; GNU tar, Python 3.9+ with `venv` and `sqlite3`, `easy-rsa` checked |
| 2 User and directories | user `ovpmon`; `/var/lib/ovpmon` (+ `staging/`), `/var/log/ovpmon`, `/var/log/openvpn` (with `openvpn-status.log` as `root:ovpmon 640`), `/etc/openvpn/scripts`, `/etc/ovpmon` |
| 3 Code | `APP_CORE` and `APP_PROFILER` copied to the prefix (without venvs, databases, logs, Dockerfiles), plus the scripts and templates under `deploy/` and `DOCS/General/` (so the install directory can run `update.sh --source ...`); `VERSION` |
| 4 Virtualenvs and easy-rsa | two virtualenvs (`pip install -r requirements.txt`, plus `gunicorn` for `APP_CORE`), an import check, the easy-rsa workspace copied from `/usr/share/easy-rsa` into `APP_PROFILER/easy-rsa` (a real directory, never a symlink), code made root-owned and read-only |
| 5 Configuration | `/etc/ovpmon/env` (random secret, generated administrator), `/etc/ovpmon/helper.conf`, `/usr/local/sbin/ovpmon-helper`, doas rules and a **self-test** (`ovpmon` runs the helper through doas), forwarding via `/etc/sysctl.d`, OpenVPN prerequisites (Alpine: the `openvpn.conf` link; Debian/Ubuntu: `/etc/openvpn/server/`; the OpenVPN service is **enabled, not started**: there is no `server.conf` yet) |
| 6 Services, UI, nginx | the three service definitions installed and enabled, UI files to `/var/www/ovpmon` (validated, swapped in atomically, with `.ui-source-hash`), a self-signed EC certificate (`/etc/ovpmon/tls/`, SAN: host name, detected IP, `127.0.0.1`, `localhost`), the nginx site, nginx enabled and reloaded |
| 7 Start and checks | services started; health checks (below) |
| 8 Administrator | when a user exists in the monitoring database, the seed is removed from `/etc/ovpmon/env` and `ovpmon-api` is restarted; if the database cannot be read or is empty the seed stays and a warning says so |
Health checks: the three services are running; `http://127.0.0.1:5001/` answers; `http://127.0.0.1:8000/` returns 200; `https://127.0.0.1:<port>/` (with `-k`) returns 200; `/api/v1/user/me` and `/profiles-api/config` through nginx return 401 without a token.
The final summary shows the URL, the certificate fingerprint, the paths and the **generated administrator password once**. The state is recorded in `/etc/ovpmon/deploy.state` (prefix, HTTPS port, OS, version, dates). If the script fails it is **safe to run again**: it resumes, keeps the existing secret, certificate, easy-rsa workspace and data.
Then in the UI: sign in, change the password and enable 2FA, **PKI Configuration -> Initialize PKI**, generate the server configuration, start the VPN server.
### Without the script (outline)
Create the `ovpmon` user and the directories, copy the code, build both virtualenvs, write `/etc/ovpmon/env`, `helper.conf` and the doas rules from the templates, install the service definitions (`DOCS/General/systemd/*.service` or `DOCS/General/openrc/ovpmon-*`; replace `/opt/OpenVPN-Monitoring-Simple` if you use another prefix), copy the UI, add the nginx site from `deploy/native/nginx/ovpmon.conf.template` (replace `@HTTPS_PORT@`, `@WEB_ROOT@`, `@TLS_CRT@`, `@TLS_KEY@`). The commands are exactly what `install.sh` runs; reading the script is the shortest reference.
## Verify an installation
```sh
rc-status | grep -E "ovpmon|nginx|openvpn" # Alpine; Debian/Ubuntu: systemctl status 'ovpmon-*' nginx
ss -tlnp | grep -E ":(8088|5001|8000) "
curl -sk -o /dev/null -w "%{http_code}\n" https://127.0.0.1:8088/ # 200
curl -sk -o /dev/null -w "%{http_code}\n" https://127.0.0.1:8088/profiles-api/config # 401 without a token
su -s /bin/sh ovpmon -c "doas -n /usr/local/sbin/ovpmon-helper service status" # JSON, not "Operation not permitted"
```
## Next
[First steps](../First_Steps.md) · [Web UI](Web_UI.md) · [Operations](Operations.md) · [Reference](Reference.md) · [Firewall](Firewall.md) · [Troubleshooting](Troubleshooting.md) · [Choose another method](../README.md)
@@ -0,0 +1,75 @@
# System services: reference
Paths and owners, the environment file, the root helper configuration and security notes. Install: [System services](README.md).
## Layout: what is where, who owns it
| Item | Path | Owner, mode |
|---|---|---|
| Code | `<prefix>/APP_CORE`, `<prefix>/APP_PROFILER` | `root:root`, read-only for others |
| Virtualenvs | `<prefix>/APP_CORE/venv`, `<prefix>/APP_PROFILER/venv` | `root:root` |
| **PKI** (CA, keys, certificates, CRL) | `<prefix>/APP_PROFILER/easy-rsa` (real directory) | `ovpmon:ovpmon` 750 |
| **Client profiles** | `<prefix>/APP_PROFILER/client-config` (real directory) | `ovpmon:ovpmon` 750 |
| Profiler log | `<prefix>/APP_PROFILER/profiler.log` | `ovpmon:ovpmon` 640 |
| Shipped settings file | `<prefix>/APP_CORE/config.ini`, `<prefix>/APP_PROFILER/config.ini` | `root:root`; the environment file overrides it |
| **Databases** | `/var/lib/ovpmon/openvpn_monitor.db`, `ovpn_profiler.db`, migration copies `*.db.bak-*` | `ovpmon:ovpmon` |
| Staging of `server.conf` | `/var/lib/ovpmon/staging/` | `ovpmon:ovpmon` 750 |
| Service environment | `/etc/ovpmon/env` | `root:root` 600 |
| Helper configuration | `/etc/ovpmon/helper.conf` | `root:root` 644 |
| TLS certificate and key | `/etc/ovpmon/tls/ovpmon.crt`, `ovpmon.key` | `root:root` (key 600) |
| Deployment state | `/etc/ovpmon/deploy.state` | `root:root` 644 |
| nftables ruleset of the VPN clients (only after `firewall.sh`) | `/etc/ovpmon/nftables.nft`, service `ovpmon-nft` | `root:root` 644 |
| Root helper | `/usr/local/sbin/ovpmon-helper` | `root:root` 755 |
| doas rules | Alpine: `/etc/doas.d/ovpmon.conf`; Debian/Ubuntu: block in `/etc/doas.conf` | `root:root` |
| OpenVPN configuration | `/etc/openvpn/server.conf` (Alpine) or `/etc/openvpn/server/server.conf`, `/etc/openvpn/crl.pem`, `/etc/openvpn/scripts/` | `root:root` |
| OpenVPN logs | `/var/log/openvpn/openvpn.log`, `openvpn-status.log` (`root:ovpmon` 640) | `root` |
| Service logs | `/var/log/ovpmon/` (OpenRC) or the journal (systemd) | `ovpmon` / systemd |
| UI files | `/var/www/ovpmon` | `root:root` |
| Backups | `/var/backups/ovpmon/<UTC timestamp>/` | `root:root` 700 |
| Deployment log | `/var/log/ovpmon-deploy.log` | `root:root` 600 |
The profiler resolves `easy-rsa/` and `client-config/` relative to its working directory (`APP_PROFILER`) and keeps `client-config/<name>.ovpn` as a relative path in its database; therefore both are real directories inside `APP_PROFILER` (a symlinked `client-config` breaks the real-path checks and the `clear_pki` cleanup).
## Environment file and helper configuration
`/etc/ovpmon/env` (`root:root` 600) is read by the init system as root and handed to the services. Lines are `KEY=VALUE` without quotes or spaces (systemd and OpenRC read the same file).
| Variable | Default written by `install.sh` | Meaning |
|---|---|---|
| `OVPMON_API_SECRET_KEY` | random, 64 hex characters | signing key of both APIs; at least 32 characters, no `change-me`/`changeme` (the APIs refuse to start otherwise); changing it logs everybody out; keep it across updates. `update.sh` issues a new random key when it is missing or weak and resets all sessions |
| `OVPMON_API_HOST`, `OVPMON_API_PORT` | `127.0.0.1`, `5001` | informational: gunicorn is started with `-b 127.0.0.1:5001` |
| `OVPMON_OPENVPN_MONITOR_DB_PATH` | `/var/lib/ovpmon/openvpn_monitor.db` | monitoring database |
| `OVPMON_PROFILER_DB_PATH` | `/var/lib/ovpmon/ovpn_profiler.db` | profiler database |
| `OVPMON_OPENVPN_MONITOR_LOG_PATH` | `/var/log/openvpn/openvpn-status.log` | status log read by the gatherer |
| `OVPMON_LOGGING_LEVEL` | `INFO` | |
| `OVPMON_CORS_ORIGINS` | `https://<host>:<https-port>` | extra allowed origin (the UI is same-origin behind nginx) |
| `OVPMON_RUNTIME` | `host` | forces host mode (never "container"), needed when the host itself runs inside a container |
| `OVPMON_OPENVPN_SERVICE` | `openvpn` (Alpine) / `openvpn-server@server` | service name for the root (non-helper) path |
| `OVPMON_OPENVPN_CONFIG` | `/etc/openvpn/server.conf` / `/etc/openvpn/server/server.conf` | server config path for the root (non-helper) path |
| `OVPMON_INITIAL_ADMIN_USER`, `OVPMON_INITIAL_ADMIN_PASSWORD` | generated | seed, only while the users table is empty; removed by `install.sh` after the first start |
| `OVPMON_AUTO_MIGRATE` | unset | `0` makes the services refuse to start while migrations are pending |
With the unprivileged profiler the API only stages `server.conf`; **the helper configuration decides where it is installed and which service is controlled.**
`/etc/ovpmon/helper.conf` (INI, section `[helper]`, `root:root`, not group/world writable, otherwise the helper refuses to run). Without the file the helper uses the built-in values of the Alpine layout.
| Key | Alpine (written) | Debian/Ubuntu (written) | Rule |
|---|---|---|---|
| `install_dir` | `/opt/OpenVPN-Monitoring-Simple` | same | absolute, no `..`; the PKI is `<install_dir>/APP_PROFILER/easy-rsa/pki` |
| `service_manager` | `openrc` | `systemd` | `openrc` or `systemd` |
| `service_unit` | `openvpn` | `openvpn-server@server` | `^[A-Za-z0-9@._-]{1,64}$`, not starting with `-` or `.` |
| `config_path` | `/etc/openvpn/server.conf` | `/etc/openvpn/server/server.conf` | absolute, below `/etc/openvpn/`, ends with `.conf` |
| `staged_path` | `/var/lib/ovpmon/staging/server.conf` | same | absolute, below `/var/lib/ovpmon/` |
OpenRC runs `/sbin/rc-service <unit> <action>`, systemd runs `systemctl <action> <unit>` (fixed argument list, fixed `PATH`). Unknown keys or invalid values make the helper refuse.
## Security notes
- Services run as `ovpmon` (no login shell); code and virtualenvs are root-owned and read-only for them. systemd units add `PrivateTmp`, `ProtectHome`, `ProtectSystem=full`, kernel and cgroup protection; `ovpmon-api` and `ovpmon-gatherer` also set `NoNewPrivileges`. `ovpmon-profiler` must **not** (it calls the setuid `doas`), must not use seccomp-based options either (`ProtectKernelTunables`, `ProtectKernelModules`, `RestrictRealtime`, `LockPersonality`, `SystemCallFilter`, ...): for an unprivileged unit systemd then sets NoNewPrivileges implicitly and `doas` fails with "not installed setuid" (check: `grep NoNewPrivs /proc/<main pid>/status` must show 0). It keeps `/etc/openvpn` writable, because the helper runs inside the profiler's mount namespace.
- The helper accepts six fixed commands, validates `server.conf` against an allowlist and reads its own root-owned configuration; nothing else runs as root. `ovpmon` owns the PKI including the CA key: a compromised profiler can issue client certificates (VPN access) but cannot become root.
- `/etc/ovpmon/env` is `root:root` 600 and never printed; the generated administrator password is shown once and removed from the file after the first start.
- Backups contain private keys, password hashes and the secret: mode 700/600, keep off-host copies encrypted.
- Both APIs listen on `127.0.0.1`; only nginx (HTTPS) and OpenVPN are reachable. Replace the self-signed certificate when a domain is available; consider restricting the UI by address or reaching it through the VPN.
- The scripts do not harden SSH or install fail2ban: see [Host hardening](Troubleshooting.md#host-hardening-recommended-not-done-by-the-scripts).
Related: [Database migrations](../../General/Database_Migrations.md), [Privilege separation](../../Changes/2026-09-30_Privilege_Separation.md), [Containers](../Containers/README.md), [Deployment plan](../../Changes/2026-10-05_Deployment_Scenarios_PLAN.md).
@@ -1,6 +1,6 @@
# Service Setup Guide
The OpenVPN Monitor components run as three system services under the unprivileged user `ovpmon`. `deploy/native/install.sh` installs and enables them (see [Scenario 2: system services](../Deployment/Scenario2_System_Services.md)); this page is the day-to-day reference.
The OpenVPN Monitor components run as three system services under the unprivileged user `ovpmon`. `deploy/native/install.sh` installs and enables them (see [System services](README.md)); this page is the day-to-day reference.
| Service | Command (working directory under the install dir, default `/opt/OpenVPN-Monitoring-Simple`) | Listens |
|---|---|---|
@@ -12,8 +12,8 @@ Settings: `/etc/ovpmon/env` (`root:root` 600). The services start after the netw
## Definitions
- Alpine (OpenRC): [`openrc/ovpmon-*`](openrc/INSTALL.md) in `/etc/init.d/` (`supervise-daemon`, `command_user=ovpmon:ovpmon`, environment sourced in `start_pre`, log in `/var/log/ovpmon/`).
- Debian / Ubuntu (systemd): [`systemd/ovpmon-*.service`](systemd) in `/etc/systemd/system/` (`User=ovpmon`, `EnvironmentFile=/etc/ovpmon/env`, moderate hardening, log in the journal).
- Alpine (OpenRC): [`openrc/ovpmon-*`](../../General/openrc/INSTALL.md) in `/etc/init.d/` (`supervise-daemon`, `command_user=ovpmon:ovpmon`, environment sourced in `start_pre`, log in `/var/log/ovpmon/`).
- Debian / Ubuntu (../../General/systemd): [`systemd/ovpmon-*.service`](../../General/systemd) in `/etc/systemd/system/` (`User=ovpmon`, `EnvironmentFile=/etc/ovpmon/env`, moderate hardening, log in the journal).
Install them with the scripts (they adjust the install directory); by hand, copy a file, replace `/opt/OpenVPN-Monitoring-Simple` if needed and enable it as below.
@@ -0,0 +1,36 @@
# System services: troubleshooting and host hardening
Install: [System services](README.md). Update and backup: [Operations](Operations.md).
## Troubleshooting
| Symptom | Cause and action |
|---|---|
| `invalid --prefix ...` / `no valid install directory given` | The install directory must be a new or empty dedicated directory, not the repository checkout and not a system directory. Move or clone the repository elsewhere (for example `/root/ovpmon-src`) or choose another directory |
| `already installed ... use update.sh` / `an installation already exists` | `install.sh` never installs over an installation. Use `update.sh` (it adopts hand-made installations) |
| `installation stopped in phase ...` | Fix the cause and run `install.sh` again: it resumes and keeps secrets, certificate and data |
| `OVPMON_API_SECRET_KEY in /etc/ovpmon/env is too short` / `not set` / `a placeholder/default value`; a service exits with `Refusing to start` | The signing key is missing or weak. `install.sh` (resume) stops: set `OVPMON_API_SECRET_KEY=$(openssl rand -hex 32)` in `/etc/ovpmon/env` and run it again. `update.sh` fixes it itself: it issues a new random key before the start and **resets all sessions** (everyone signs in again) |
| `not a tested version ... needs --force` | Untested OS version: `install.sh --force` at your own risk |
| `ports ... already in use` | Another service uses 5001, 8000 or the HTTPS port: stop it or use `--https-port` |
| `pip install failed` | No access to the Python package index (proxy: `pip` honours `HTTPS_PROXY`); on Alpine check that `py3-pip` is installed |
| Health check fails | Alpine: `tail /var/log/ovpmon/ovpmon-api.log` (or `-gatherer`, `-profiler`); systemd: `journalctl -u ovpmon-api -n 50`. The scripts print the last lines of a failing service |
| `FATAL: ... newer than this version` / migration "too new" | The database was migrated by a newer release. Do not start the old version on it: update to the newer sources or restore a matching backup |
| Migration failed | Nothing was started and the rollback restored the databases; the report names the migration, the `<db>.bak-*` copy is in `/var/lib/ovpmon`. Keep the report |
| Profiler cannot start/stop OpenVPN, "helper failed" | The self-test warning of the scripts points at it: check the doas rules (`doas -C /etc/doas.conf` or `/etc/doas.d/ovpmon.conf`), `/etc/ovpmon/helper.conf` (must be `root:root` and not group/world writable; `su -s /bin/sh ovpmon -c "doas -n /usr/local/sbin/ovpmon-helper service status"` prints the reason) |
| `Configuration rejected` when generating the server config | The helper allowlist refused a directive, see [Privilege separation](../../Changes/2026-09-30_Privilege_Separation.md) |
| OpenVPN does not start on Debian/Ubuntu | `systemctl status openvpn-server@server`, `journalctl -u openvpn-server@server`; the config must be `/etc/openvpn/server/server.conf` and `/dev/net/tun` must exist |
| Clients connect but have no internet | Forwarding or NAT is missing: see [Firewall](Firewall.md) |
| nginx: `conflicting server name` / port in use | Another site uses the same port; change `--https-port` (or the `listen` line of the site and reload) |
| Browser warns about the certificate | It is self-signed; check the fingerprint printed by `install.sh`, or install a real certificate under `/etc/ovpmon/tls/` and reload nginx |
| `no UI source found` (install stops) | The checkout has no `deploy/ui-dist` (incomplete clone, or the maintainer did not publish it) and no `--ui-dist`. Use `--build-ui` (Docker or Node 20.19+; `--node-download` on Debian/Ubuntu), `--ui-dist FILE\|DIR` from another machine, or `--no-ui` for a placeholder page |
| Warning "committed UI build ... is OLDER than the APP_UI sources" | Someone changed `APP_UI` without refreshing the build. Maintainers: `deploy/native/build-ui.sh --publish` and commit `deploy/ui-dist`. On the host: `--build-ui` |
| `the installed Node is too old` / `node and npm are not installed` (`--build-ui`, `build-ui.sh --local`) | The message lists the commands for the OS: Alpine `apk add nodejs npm`; Debian/Ubuntu `--node-download` or Node 20+ from nodejs.org |
| UI shows the placeholder page | Installed with `--no-ui`: run `deploy/native/update.sh` (installs the UI of the repository), or add `--ui-dist` / `--build-ui` |
| `su`/`doas` self-test fails on a minimal container | Containers often lack `/etc/pam.d/doas` or a real init system; the services may still work (check health) |
## Host hardening (recommended, not done by the scripts)
- SSH: key-only (`PasswordAuthentication no`, `KbdInteractiveAuthentication no`, `PermitRootLogin prohibit-password`). Cloud-init drop-ins in `/etc/ssh/sshd_config.d/` can override the main file, so put your settings in a file that sorts first, for example `00-hardening.conf`.
- fail2ban: jails `sshd` and one for `POST /api/auth/login` (HTTP 401/429/503) on the nginx access log.
- Backends are bound to `127.0.0.1`; only the HTTPS port and the VPN port should be reachable from outside.
- Keep the system updated (`apk upgrade` / `apt-get upgrade`) and watch the advisories of OpenVPN, nginx and OpenSSH.
+59
View File
@@ -0,0 +1,59 @@
# System services: the web UI
How the UI reaches the host (no Node needed by default), the build script and the maintainer routine. Install: [System services](README.md).
## Overview
The UI is built from `APP_UI` (Vue/Vite). The repository carries a ready build in `deploy/ui-dist/` together with `SOURCE_HASH`, a SHA-256 over the UI sources it was built from (`APP_UI/src`, `public`, `index.html`, `package.json`, `package-lock.json`, `vite.config.js`, `jsconfig.json`). `install.sh` and `update.sh` find the UI themselves. The directory is outside `APP_UI`, so the container builds are not affected.
### Three ways to get the UI onto a host
| Way | Option | When |
|---|---|---|
| Committed build | none (automatic) | the normal case: `git clone`, `install.sh`, done; no Node, no Docker |
| Build on the host | `--build-ui` | the committed build is stale or missing; builds from `APP_UI` now with Docker (when its daemon works) or the host's Node 20.19+ |
| Build elsewhere | `--ui-dist FILE\|DIR` | a tarball from `build-ui.sh` or a directory with `index.html`, for example from a CI job or another machine |
Order used by `install.sh` and `update.sh`: **1.** `--ui-dist` (explicit, always installed), **2.** `--build-ui` (always builds fresh from the sources), **3.** the committed `deploy/ui-dist` of the checkout (automatic), **4.** nothing found: `install.sh` **stops** (it lists the ways out) unless `--no-ui` is given (a placeholder page on purpose); `update.sh` keeps the installed UI. `install.sh` also still accepts `deploy/native/ui-dist.tar.gz` as a last resort below the committed directory. `--ui-dist` and `--build-ui` exclude each other.
The installed web root records the hash it came from in `/var/www/ovpmon/.ui-source-hash` (`unknown` for archives that were not made by `build-ui.sh`). `update.sh` compares it with the `SOURCE_HASH` of the repository build: equal, the UI is not replaced (and it says so); different or missing (for example a host installed with `--no-ui`), the new UI is staged in phase 3 and swapped in phase 6, with the rest of the update, so it is part of the backup and the automatic rollback. The UI source is decided after `git pull`, so a pulled new build is used in the same run. The old UI is in the backup.
### Staleness guard
When the hash of the current `APP_UI` sources differs from `SOURCE_HASH`, the committed build is **older than the sources** (someone changed the UI and did not refresh the build). `install.sh` and `update.sh` then print a loud warning with the two hashes and the remedy, and still use the committed build (it works, it only lacks the latest UI changes). A host that needs the current UI adds `--build-ui`. A build without a valid `SOURCE_HASH` counts as stale.
### Maintainer routine
After every change in `APP_UI` (or its `package*.json`, `vite.config.js`), **before committing**:
```sh
deploy/native/build-ui.sh --publish # rebuilds deploy/ui-dist/ and SOURCE_HASH from the current sources
deploy/native/check-ui.sh # prints fresh | stale | missing; exit 0 | 1 | 2
git add APP_UI deploy/ui-dist
```
`check-ui.sh` also fits a release checklist or a CI step (it changes nothing). `--publish` replaces the content of `deploy/ui-dist/` by a move (the old directory is only deleted after the new one is in place).
### build-ui.sh
```sh
deploy/native/build-ui.sh # Docker if it works, otherwise local Node -> deploy/native/ui-dist.tar.gz
deploy/native/build-ui.sh --docker # node:20-alpine container (OVPMON_NODE_IMAGE or --image to change)
deploy/native/build-ui.sh --local # Node >= 20.19 and npm of this machine, no container
deploy/native/build-ui.sh --local --node-download # temporary official Node 20, deleted after the build
deploy/native/build-ui.sh --publish # refresh deploy/ui-dist/ in the repository
deploy/native/build-ui.sh -o /tmp/ui.tar.gz # tarball for another host (also with --publish)
deploy/native/build-ui.sh --check # only check that the builder is usable
```
Without `--docker`/`--local` the script uses Docker when its daemon answers, otherwise the local Node. The tarball holds the content of `dist/` and `SOURCE_HASH`. **Nothing is written into the source tree**: a container sees `APP_UI` read-only; `--local` copies it (without `node_modules` and `dist`) into a temporary directory and runs `npm ci` there (`npm install` without a lock file), so the repository gets no `node_modules` and no `dist`.
`--local` needs Node 20.19 or newer with npm. When it is missing or too old the script prints what to do and stops:
| System | What to do |
|---|---|
| Alpine | `apk add nodejs npm` (check `node --version` afterwards) |
| Debian / Ubuntu | the distribution's Node is usually too old (Debian 12 and Ubuntu 24.04 ship Node 18): add `--node-download` (needs `apt-get install -y curl xz-utils`), or install Node 20+ with npm from nodejs.org / NodeSource |
| anything else | Node 20.19+ from nodejs.org, or build with `--docker` on a machine with Docker |
`--node-download` fetches `SHASUMS256.txt` from `https://nodejs.org/dist/latest-v20.x/`, picks `node-v20.*-linux-<x64|arm64>.tar.xz`, verifies its SHA-256, unpacks it into a temporary directory (npm cache included), builds with it and deletes everything; nothing is installed on the host. glibc systems only: on Alpine (musl) it refuses and points to `apk add nodejs npm`. It needs `curl`, `tar`, `xz` and access to nodejs.org (`OVPMON_NODE_MAJOR` selects another major version).
+28
View File
@@ -0,0 +1,28 @@
# Configuration
Each component reads `config.ini` (shipped in `APP_CORE/` and `APP_PROFILER/`); any value can be overridden by an environment variable `OVPMON_{SECTION}_{KEY}`. The installation scripts write the environment for you, so a newcomer normally changes nothing here.
## Variables
| Variable | Purpose |
|---|---|
| `OVPMON_API_SECRET_KEY` | JWT signing key shared by both APIs (**must be random**; changing it logs everybody out; keep it across updates) |
| `OVPMON_INITIAL_ADMIN_USER` / `_PASSWORD` | one-time seed of the first administrator (only while the users table is empty); the scripts remove it after the first start |
| `OVPMON_CORS_ORIGINS` | extra allowed CORS origins, comma-separated (empty = same-origin only) |
| `OVPMON_OPENVPN_MONITOR_DB_PATH` | monitoring database |
| `OVPMON_PROFILER_DB_PATH` | profiler database |
| `OVPMON_OPENVPN_MONITOR_LOG_PATH` | path of `openvpn-status.log` |
| `OVPMON_LOGGING_LEVEL` | `INFO` / `DEBUG` |
## JWT signing key rule
The key comes from `OVPMON_API_SECRET_KEY` or, when the variable is not set, from `[api] secret_key` in `config.ini` (the variable wins). There is **no built-in default**: the shipped `config.ini` files have an empty value. A key is accepted when it is not blank, does not contain `change-me` or `changeme` (any case) and has at least 32 characters (`openssl rand -hex 32` gives 64). With a missing or weak key both APIs refuse to start: they log a critical message (never the key itself) naming the reason and the source, and exit with code 1. Both APIs must get the same key. `OVPMON_SECRET_KEY` (a name used by older guides) is **not read**; if it is set instead of `OVPMON_API_SECRET_KEY`, the message says to rename it.
## Where the values are set
| Installation method | File | Reference |
|---|---|---|
| Containers | `.env` next to the compose files (`JWT_SECRET` is mapped to `OVPMON_API_SECRET_KEY`) | [Containers: reference](../Deployment/Containers/Reference.md) |
| System services | `/etc/ovpmon/env` (`root:root`, mode 600) plus `/etc/ovpmon/helper.conf` for the root helper | [System services: reference](../Deployment/System_Services/Reference.md) |
The OpenVPN server settings (port, network, routes, DNS, PKI parameters) are not set here: they are edited in the UI (**VPN** and **PKI** pages) and validated before use.
-110
View File
@@ -1,110 +0,0 @@
# Deployment Guide: OpenVPN Monitor & Profiler
This guide describes how to deploy the full suite on a fresh Linux server (Ubuntu/Debian).
## Architecture Overview
- **Frontend**: Vue.js (Built and served by Nginx) - `APP_UI`
- **Monitoring API (APP_CORE)**: Flask (Port 5000) - Real-time statistics.
- **Profiler API (APP_PROFILER)**: FastAPI (Port 8000) - Profile & Server management.
---
## 1. Prerequisites
- Python 3.10+
- Nginx
- OpenVPN & Easy-RSA (for the Profiler)
- Node.js & NPM (only for building the UI)
---
## 2. Shared Security Setup (Critical)
Both API services must share the same `SECRET_KEY` to recognize the same JWT tokens.
### A. Environment Variable (Recommended)
Add this to your shell profile (`~/.bashrc`) or your Systemd service files:
```bash
export OVPMON_SECRET_KEY='your-very-long-random-secret-key'
```
### B. Configuration File
Alternatively, set it in `APP_CORE/config.ini`:
```ini
[api]
secret_key = your-very-long-random-secret-key
```
---
## 3. Backend Deployment
### Monitoring API (Flask)
1. Navigate to `APP_CORE/`.
2. Create virtual environment: `python3 -m venv venv`.
3. Install dependencies: `venv/bin/pip install -r requirements.txt`.
4. Run with Gunicorn (production):
```bash
venv/bin/gunicorn -w 4 -b 127.0.0.1:5000 openvpn_api_v3:app
```
### Profiler API (FastAPI)
1. Navigate to `APP_PROFILER/`.
2. Create virtual environment: `python3 -m venv venv`.
3. **Important**: Uninstall potential conflicts and install PyJWT:
```bash
venv/bin/pip uninstall jwt PyJWT
venv/bin/pip install -r requirements.txt PyJWT
```
4. Run with Uvicorn:
```bash
venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000
```
---
## 4. Frontend Deployment (Nginx)
### Build the UI
1. Navigate to `UI/client`.
2. Install: `npm install`.
3. Build: `npm run build`.
4. Copy `dist/` contents to `/var/www/ovpmon/`.
### Nginx Configuration
Create `/etc/nginx/sites-available/ovpmon`:
```nginx
server {
listen 80;
server_name your_domain_or_ip;
root /var/www/ovpmon;
index index.html;
# Frontend Routing
location / {
try_files $uri $uri/ /index.html;
}
# Monitoring API (Flask)
location /api/v1/ {
proxy_pass http://127.0.0.1:5000/api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Profiler API (FastAPI)
location /profiles-api/ {
proxy_pass http://127.0.0.1:8000/api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
```
---
## 5. First Run & Initialization
1. Access the UI via browser.
2. Sign in with the admin seeded via OVPMON_INITIAL_ADMIN_USER / OVPMON_INITIAL_ADMIN_PASSWORD (no built-in default user exists).
3. **Immediately** change the password and set up 2FA in the Settings/Profile section.
4. If using the Profiler, ensure the `easy-rsa` directory is present and initialized via the UI.
-10
View File
@@ -1,10 +0,0 @@
# Deployment: Docker
The container deployment (all components in one container, or one container per component), its install and update scripts, backup and rollback are described in **[Scenario 1: installation in containers](../Deployment/Scenario1_Containers.md)**.
Quick start (variant B, one container per component, `docker-compose.yml`):
```bash
deploy/docker/install.sh --variant b # variant A (one container): --variant a
deploy/docker/update.sh # later updates: backup, build, separate database migration, start
```
-12
View File
@@ -1,12 +0,0 @@
# Deployment: system services (no containers)
This page is now a pointer. Installation and update on **Alpine (OpenRC), Debian and Ubuntu (systemd)** are done with the scripts in `deploy/native/` and described in **[Scenario 2: system services](../Deployment/Scenario2_System_Services.md)**: install, update with a separate database migration step, backup, restore, rollback, firewall and NAT commands, layout, environment file, troubleshooting and the "what is preserved" table.
Quick start (as root, from a checkout of the repository; build the UI with `deploy/native/build-ui.sh` on a machine with Docker first):
```sh
deploy/native/install.sh --ui-dist ui-dist.tar.gz # first installation
deploy/native/update.sh --ui-dist ui-dist.tar.gz # later: update with backup and rollback
```
Related: [Nginx configuration](Nginx_Configuration.md), [Service management](Service_Management.md), [Database migrations](Database_Migrations.md), [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md), [Scenario 1: containers](../Deployment/Scenario1_Containers.md). The service definitions are in [`systemd/`](systemd) and [`openrc/`](openrc/INSTALL.md).
-42
View File
@@ -1,42 +0,0 @@
# OpenVPN Monitor & Profiler Documentation
Welcome to the documentation for the OpenVPN Monitor suite.
## 📚 General
- [Deployment: Docker](Deployment_Docker.md): containers with docker-compose.
- [Deployment: system services](Deployment_Native.md): systemd/OpenRC, HTTPS, host hardening.
- [Deployment Guide](Deployment.md): generic native install notes.
- [Service Management](Service_Management.md): Setting up systemd/OpenRC services.
- [Nginx Configuration](Nginx_Configuration.md)
- [Security Architecture](Security_Architecture.md): Details on Authentication, 2FA, and Security features.
## 🗂 Operations
- [Deployment records](../Operations/README.md): state summary, reboot test, plans and rollout records.
## 🛠 Changes and results
- [Security hardening (2026-09-30)](../Changes/2026-09-30_Security_Hardening.md)
- [Admin username change (2026-09-30)](../Changes/2026-09-30_Admin_Username_Change.md)
- [Settings validation (2026-09-30)](../Changes/2026-09-30_Settings_Validation.md)
- [Privilege separation (2026-09-30)](../Changes/2026-09-30_Privilege_Separation.md)
- [Egress via Hysteria2 (2026-09-30)](../Changes/2026-09-30_Egress_via_Hysteria2.md)
- [Profile notes (2026-10-04)](../Changes/2026-10-04_Profile_Notes.md)
- [Async PKI init (2026-10-04)](../Changes/2026-10-04_Async_PKI_Init.md)
- [Toast notifications (2026-10-04)](../Changes/2026-10-04_Toast_Notifications.md)
- [PKI dependency guard (2026-10-04)](../Changes/2026-10-04_PKI_Dependency_Guard.md)
- [Database migrations (2026-10-05)](../Changes/2026-10-05_DB_Migrations.md) · [reference](Database_Migrations.md)
- [Scenario 1: containers (2026-10-05)](../Changes/2026-10-05_Scenario1_Containers.md) · [guide](../Deployment/Scenario1_Containers.md)
- [Scenario 2: system services (2026-10-05)](../Changes/2026-10-05_Scenario2_System_Services.md) · [guide](../Deployment/Scenario2_System_Services.md)
## 🔍 Core Monitoring (`APP_CORE`)
The core module responsible for log parsing, real-time statistics, and the primary API.
- [API Reference](../Core_Monitoring/API_Reference.md): Endpoints for monitoring data.
- [Authentication](../Core_Monitoring/Authentication.md): How the Login and 2FA flows work.
- [Data Architecture](../Core_Monitoring/Data_Architecture.md): Internals of the Data Gatherer and TSDB.
## ⚙️ Profiler Management (`APP_PROFILER`)
The management module for PKI, Certificates, and User Profiles.
- [Overview](../Profiler_Management/Overview.md): Features and usage of the Profiler API.
## 💻 User Interface (`APP_UI`)
The Vue.js frontend application.
- [Architecture](../UI/Architecture.md): UI Tech stack and project structure.
+53
View File
@@ -0,0 +1,53 @@
# Overview
OpenVPN Monitor & Profiler is a web suite for an OpenVPN server: live traffic statistics and history, PKI and client-profile management, and the server process control, all in one UI.
## Components
| Component | Dir | Stack | What it does | Port |
|---|---|---|---|---|
| UI | `APP_UI/` | Vue 3 + Vite, served by Nginx | the web interface | 80 (containers, plain HTTP) / 8088 (system services, HTTPS) |
| Monitoring API | `APP_CORE/` | Flask (gunicorn) | statistics, authentication, accounts | 5001, internal |
| Data gatherer | `APP_CORE/` | Python daemon | reads the OpenVPN status log into the monitoring database | none |
| Profiler API | `APP_PROFILER/` | FastAPI (uvicorn) | PKI (easy-rsa), client profiles, server configuration, OpenVPN process control | 8000, internal |
| OpenVPN | system package or container | | the VPN server itself, started from the UI | 1194/udp (default) |
Nginx is the only public entry point: `/` is the UI, `/api/` the Monitoring API, `/profiles-api/` the Profiler API. Both APIs listen on `127.0.0.1` (or the internal container network) only.
```
Browser --> Nginx --/-----------> UI files
--/api/-------> Monitoring API --> monitoring DB <-- Data gatherer <-- openvpn-status.log
--/profiles-api/> Profiler API --> profiler DB, PKI (easy-rsa), client .ovpn files
|--> server.conf --> OpenVPN (root helper in system-service installs)
VPN clients --udp/1194--> OpenVPN
```
## Where the data lives
| Data | Content |
|---|---|
| Monitoring DB (SQLite) | traffic history and statistics, user accounts, 2FA |
| Profiler DB (SQLite) | client profiles, notes, PKI and server settings |
| PKI | CA, server and client keys and certificates, CRL, `ta.key`, `dh.pem` (**secret, back it up**) |
| Client profiles | generated `.ovpn` files |
| `server.conf` | generated by the profiler from the settings in the UI |
Exact locations per installation method: [Containers: volumes](../Deployment/Containers/Reference.md), [System services: layout](../Deployment/System_Services/Reference.md). Schema changes on update are handled by [database migrations](Database_Migrations.md).
## Glossary
| Term | Meaning |
|---|---|
| PKI | the certificate authority and the certificates issued by it; must be initialized once before the VPN server can be configured |
| Profile / client | one VPN user: a certificate plus the `.ovpn` file given to the user |
| Gatherer | the daemon that turns the OpenVPN status log into statistics |
| Root helper | (system services only) a small root script through which the unprivileged API installs `server.conf` and controls OpenVPN; see [Security architecture](Security_Architecture.md) |
| Variant A / B | the two container layouts: everything in one container / one container per component |
## Security in short
No built-in account (the first administrator is seeded once at install time); every API route needs a JWT; 2FA is available per user; server settings are validated before they reach the OpenVPN configuration; in system-service installs the APIs run as an unprivileged user. Details: [Security architecture](Security_Architecture.md).
## Where to go next
[Install it](../Deployment/README.md) · [Configuration](Configuration.md) · [Monitoring API](../Core_Monitoring/API_Reference.md) · [Profiler API](../Profiler_Management/API_Reference.md) · [UI architecture](../UI/Architecture.md)
+9 -8
View File
@@ -18,15 +18,15 @@ This includes:
## Proposed Changes
### Backend (Python/Flask)
#### [MODIFY] [requirements.txt](file:///Users/tstark/Documents/ovpmon_simple_gitea/APP_CORE/requirements.txt)
#### [MODIFY] [requirements.txt](../../APP_CORE/requirements.txt)
- Add `pyjwt`, `pyotp`, `qrcode`, `bcrypt`, `flask-bcrypt` (or `werkzeug.security`).
#### [MODIFY] [db.py](file:///Users/tstark/Documents/ovpmon_simple_gitea/APP_CORE/db.py)
#### [MODIFY] [db.py](../../APP_CORE/db.py)
- Update `init_database` to create:
- `users` table: `id`, `username`, `password_hash`, `totp_secret`, `is_2fa_enabled`.
- `login_attempts` table (for brute-force protection): `ip_address`, `attempts`, `last_attempt`.
#### [MODIFY] [openvpn_api_v3.py](file:///Users/tstark/Documents/ovpmon_simple_gitea/APP_CORE/openvpn_api_v3.py)
#### [MODIFY] [openvpn_api_v3.py](../../APP_CORE/openvpn_api_v3.py)
- **New Imports**: `jwt`, `pyotp`, `functools.wraps`.
- **Helper Functions**:
- `check_rate_limit(ip)`: Verify login attempts.
@@ -37,27 +37,28 @@ This includes:
- `POST /api/auth/setup-2fa`: Generate secret & QR code.
- `POST /api/auth/enable-2fa`: Confirm and save secret.
- **Protect Routes**: Apply `@token_required` to all existing API routes (except auth).
- **Signing key (fail closed)**: tokens are signed with `OVPMON_API_SECRET_KEY` (or `[api] secret_key`); there is no built-in default. A missing, blank, placeholder (`change-me`/`changeme`) or shorter than 32 characters key stops the API at start (critical log without the key, exit code 1, before the database is opened). The same rule is checked by the install and update scripts. See [Configuration](Configuration.md).
### Frontend (Vue.js)
#### [NEW] [Login.vue](file:///Users/tstark/Documents/ovpmon_simple_gitea/APP_UI/src/views/Login.vue)
#### [NEW] [Login.vue](../../APP_UI/src/views/Login.vue)
- Login form (Username/Password).
- 2FA Input (conditional, appears if server responses "2FA required").
#### [NEW] [Setup2FA.vue](file:///Users/tstark/Documents/ovpmon_simple_gitea/APP_UI/src/views/Setup2FA.vue)
#### [NEW] Setup2FA.vue (planned; the 2FA setup lives in `Account.vue`)
- Screen to show QR code and verify OTP to enable 2FA for the first time.
#### [MODIFY] [router/index.js](file:///Users/tstark/Documents/ovpmon_simple_gitea/APP_UI/src/router/index.js)
#### [MODIFY] [router/index.js](../../APP_UI/src/router/index.js)
- Add `/login` route.
- Add global `beforeEach` guard:
- Check if route `requiresAuth`.
- Check if token exists in `localStorage`.
- Redirect to `/login` if unauthorized.
#### [MODIFY] [App.vue](file:///Users/tstark/Documents/ovpmon_simple_gitea/APP_UI/src/App.vue)
#### [MODIFY] [App.vue](../../APP_UI/src/App.vue)
- Add `Logout` button to the sidebar.
- Conditionally render Sidebar only if logged in (optional, or just redirect).
#### [MODIFY] [main.js](file:///Users/tstark/Documents/ovpmon_simple_gitea/APP_UI/src/main.js)
#### [MODIFY] [main.js](../../APP_UI/src/main.js)
- Setup `axios` interceptors:
- **Request**: Add `Authorization: Bearer <token>`.
- **Response**: On `401 Unauthorized`, clear token and redirect to `/login`.
+1 -1
View File
@@ -2,4 +2,4 @@
`ovpmon-api`, `ovpmon-gatherer` and `ovpmon-profiler` are the OpenRC scripts (Alpine) of the system-services deployment. They run the services as the user `ovpmon`, source `/etc/ovpmon/env` in `start_pre` and are supervised by `supervise-daemon`.
Do not copy them by hand: `deploy/native/install.sh` installs them (adjusting the install directory when it is not `/opt/OpenVPN-Monitoring-Simple`) and `deploy/native/update.sh` keeps them current. The full procedure, the layout and the systemd counterparts are in [Scenario 2: system services](../../Deployment/Scenario2_System_Services.md).
Do not copy them by hand: `deploy/native/install.sh` installs them (adjusting the install directory when it is not `/opt/OpenVPN-Monitoring-Simple`) and `deploy/native/update.sh` keeps them current. The full procedure, the layout and the systemd counterparts are in [Scenario 2: system services](../../Deployment/System_Services/README.md).
-168
View File
@@ -1,168 +0,0 @@
# Hysteria 2 entry→exit chain (manifest)
Client ─hy2/UDP443→ **ENTRY** (Alpine, OpenRC) ─hy2/UDP443→ **EXIT** (Debian, systemd) → Internet (IPv4)
Secrets live only in: `client-uris.txt`, `singbox-*.json`, `/etc/hysteria/*` on hosts (chmod 600). Never commit/print them.
## Inventory (this deployment)
| Role | Host | OS | Access |
|---|---|---|---|
| ENTRY (Timeweb) | 213.226.125.13 | Alpine 3.23 | `ssh -i private.key root@` (key must be chmod 600) |
| EXIT (Gcore Hel) | 85.234.86.140 | Debian 13 | `ssh -i hpriv.key debian@` (sudo NOPASSWD) |
## Prerequisites (verify first, they were the real blockers)
1. **UDP 443 open both ways** (Security Group on EXIT; ENTRY provider). Test: `tcpdump -ni <if> udp port 443` on the receiver while `echo x | nc -u -w1 <ip> 443` from the sender. ICMP/TCP passing proves nothing about UDP.
2. Use **official** binary `apernet/hysteria` (HyNetworks/hysteria is a fork). Verify `sha256sum` against `hashes.txt` of the release:
`https://github.com/apernet/hysteria/releases/latest/download/{hysteria-linux-amd64,hashes.txt}`
3. Hysteria server `socks5`/`http` outbounds are **TCP-only** → for UDP use TUN + policy routing (below), not a SOCKS5 chain.
## EXIT (Debian) — server
- `/usr/local/bin/hysteria`, `/etc/hysteria/{server.crt,server.key(600),config.yaml}`
- Self-signed cert: `openssl req -x509 -nodes -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -days 3650 -subj /CN=<name> -keyout server.key -out server.crt`
- `config.yaml`: `listen: :443`, `tls{cert,key}`, `auth{type: password, password: <rand>}`, `masquerade{type: proxy, proxy{url: https://news.ycombinator.com/, rewriteHost: true}}`
- systemd unit `hysteria-server` (`ExecStart=hysteria server -c ...`, `Restart=always`, `AmbientCapabilities=CAP_NET_BIND_SERVICE`)
- `/etc/sysctl.d/99-quic.conf`: `net.core.rmem_max=7500000`, `net.core.wmem_max=7500000`
- No IPv6 uplink here → IPv4 only.
## ENTRY (Alpine) — tunnel client + client-facing server
Packages: `iproute2 libcap-utils openssl`; user `hyedge` (`adduser -S -D -H -s /sbin/nologin`); `/dev/net/tun` must exist and module `tun` must be in `/etc/modules` (loaded module, not builtin; without it the tunnel does not come up after reboot).
1. **`/etc/hysteria/client.yaml`** (600): `server: <EXIT>:443`, `auth: <pw>`, `tls{sni, insecure: true, pinSHA256: <EXIT cert fp>}`, `lazy: true`, `bandwidth{up: 180 mbps, down: 180 mbps}` (Brutal CC; measured path ≈191-195 Mbps via `hysteria speedtest`, single-flow without it was ~44 Mbps), `socks5{127.0.0.1:1080}`, `http{127.0.0.1:8080}`, `tun{name: hytun, mtu: 1400, timeout: 5m, address{ipv4: 100.100.100.101/30}}` (no `route:` → no auto-routes).
2. **`/etc/hysteria/edge.yaml`** (600, owner hyedge): `listen: :443`, own self-signed `edge.crt/edge.key`, `auth{type: userpass, userpass{<dev>: <pw>}}`, `resolver{type: udp, udp{addr: 1.1.1.1:53}}`, `outbounds[direct{mode: "4"}]`, `trafficStats{listen: 127.0.0.1:9999, secret}`, `acl.inline`: `reject` 10/8,172.16/12,192.168/16,127/8,169.254/16,100.64/10 then `direct(all)`.
- Do **not** add `reject(::/0)` — it matches any domain having AAAA and rejects dual-stack sites.
- DoH resolver timed out via tun; UDP resolver works.
3. Binary copy for low port: `cp hysteria hysteria-edge; setcap cap_net_bind_service=+ep /usr/local/bin/hysteria-edge`.
4. **OpenRC** (`supervisor=supervise-daemon`, `respawn_delay=3`, `respawn_max=0`):
- `hysteria` (client, root) ← `need net`
- `hysteria-route` ← `need hysteria`; waits for `hytun`, then:
```
ip route replace blackhole default metric 1000 table 100 # anti-leak fallback
ip route replace default dev hytun metric 10 table 100
ip rule add priority 100 ipproto udp sport 443 lookup main # edge replies bypass tun
ip rule add priority 101 uidrange <uid hyedge> lookup 100
```
- `hysteria-edge` (`command_user=hyedge`) ← `need net hysteria-route`
- `rc-update add hysteria/hysteria-route/hysteria-edge default`
5. **sysctl (critical):** `net.ipv4.conf.all.rp_filter=2` and `default=2` (`/etc/sysctl.d/99-hytun.conf`). With strict `1` the TUN SYN-ACKs are dropped → TCP via tun silently hangs.
6. Only uid `hyedge` traffic and, since 2026-09-30, the OpenVPN client subnet (`172.20.1.0/24`, rule 102, see below) enter the tunnel; SSH/root traffic untouched.
## OpenVPN Monitor & Profiler on ENTRY (added 2026-09-30)
ENTRY also runs the web suite for OpenVPN (native OpenRC services, no containers). OpenVPN clients exit through the same `hytun` tunnel to EXIT.
| Item | Value |
|---|---|
| Panel | `https://213.226.125.13:8088/` (self-signed TLS, login `tstark`, 2FA; password is set by the owner, not stored here) |
| OpenVPN | `udp/1194`, clients `172.20.1.0/24`, full tunnel |
| Services | `ovpmon-api`, `ovpmon-gatherer`, `ovpmon-profiler` (user `ovpmon`), `nginx`, `openvpn`, `ovpn-hytun`, `fail2ban` |
| Egress | `ip rule 102 from 172.20.1.0/24 → table 100` (hytun, blackhole fallback) + MASQUERADE on `hytun` + FORWARD DROP to any other interface (no leak) |
| Privileges | APIs run unprivileged; a root helper (`ovpmon-helper` via `doas`, 6 fixed commands) validates/installs `server.conf`, publishes the CRL and controls `openvpn` |
| Hardening | SSH key-only (`00-hardening.conf`), fail2ban (`sshd`, `sshd-ddos`, `ovpmon-login`), input validation, CORS restricted |
| Docs | [`SUMMARY-ovpn-monitor.md`](SUMMARY-ovpn-monitor.md) (state, results, security assessment, rollback), `IMPLEMENTATION-01/02-*.md`, `PLAN-validation-and-privilege-drop.md`; application repo `DOCS/` |
Check: `rc-status | grep -E "ovpmon|openvpn|ovpn-hytun|nginx|fail2ban"`, `ip rule | grep 102`, a VPN client on `https://ifconfig.me` shows the EXIT IP (85.234.86.140).
## Clients
- URI: `hy2://<user>:<pw>@<ENTRY>:443/?sni=<edge sni>&insecure=1&pinSHA256=<hex, no colons>#name` (strip `#name` when scripting pin extraction).
- Hiddify/NekoBox/Streisand/Shadowrocket: paste URI. sing-box (SFA/SFI, ≥1.12): JSON profile with `hysteria2` outbound, `password: "<user>:<pw>"`, embedded `tls.certificate` PEM (edge.crt), TUN inbound, DoH via outbound, `hijack-dns`, private + ENTRY IP → direct.
### Recommended client apps
Protocol: Hysteria 2 (QUIC/UDP 443). Server cert is self-signed, so the app must support `pinSHA256`/custom certificate — all apps below do via the URI/QR or sing-box JSON.
| Platform | App | Import | Notes |
|---|---|---|---|
| Android | **Hiddify** (primary) | hy2:// URI or QR | sing-box core, pin support, simplest |
| Android | NekoBox for Android | hy2:// URI or QR | alternative, more knobs |
| Android | SFA (sing-box) | JSON profile only | official sing-box client; use `profiles/singbox/*.json` |
| iOS | **Streisand** (primary) | hy2:// URI or QR | free |
| iOS | Shadowrocket | hy2:// URI or QR | paid, stable |
| iOS | SFI (sing-box) / Hiddify | JSON profile / URI | sing-box >= 1.12 required for the JSON |
| Desktop | Hiddify, sing-box CLI, `hysteria client` | URI / JSON / YAML | sing-box needs root/admin for TUN |
Required client settings (otherwise many sites fail or hang):
- **IPv6 off** (Hiddify: IPv6 mode = Disable / IPv4 only). EXIT has no IPv6; apps sending IPv6 literals get `no IPv4 address available`.
- Remote DNS via the tunnel (DoH `https://1.1.1.1/dns-query`); do not leak DNS outside.
- QUIC blocking is **not** needed (UDP is carried end to end).
- Verify: `ifconfig.me` shows the EXIT IP (85.234.86.140); `test-ipv6.com` shows no IPv6.
App availability/names vary by store and region and change over time; this list comes from the project's client testing (Hiddify confirmed working on a phone) and general knowledge, not a current store check. One profile per person.
## Profiles (20 client users)
`profiles/` (dir 700, files 600; contains secrets): `hy2/clientNN.txt` (hy2:// URI), `singbox/clientNN.json` (sing-box >=1.12), `qr/<user>.png` (QR of the hy2:// URI, 22 files incl. laptop/mobile; made with `qrencode -t PNG -s 8 -m 2 -l M`; decoding verified), `ALL-hy2.txt`, `INDEX.md` (no passwords). Mobile apps: scan QR -> imports hy2:// profile. Users `client01..client20` live in `edge.yaml` `auth.userpass` (backup `edge.yaml.bak4`; `laptop`, `mobile` kept). Wrong password -> client error `authentication error, HTTP status code: 404`.
Add/revoke a user: edit `auth.userpass` on ENTRY, `rc-service hysteria-edge restart` (all sessions reconnect within seconds), then regenerate/delete the profile files. Verified login for client01/10/20 via temp client (egress = EXIT IP).
## Verification checklist
```
su -s /bin/sh hyedge -c 'curl -4 -s https://ifconfig.me' # = EXIT ip (TCP via tun)
su -s /bin/sh hyedge -c 'nslookup example.com 1.1.1.1' # UDP via tun
ip route del default dev hytun table 100; <same curl must FAIL>; ip route replace default dev hytun metric 10 table 100
hysteria client (temp, socks 127.0.0.1:1081) -> curl -x socks5h://... https://ifconfig.me # = EXIT ip; http://10.0.0.1 rejected
```
Logs: ENTRY `/var/log/hysteria.log`, `/var/log/hysteria-edge.log`; EXIT `journalctl -u hysteria-server`.
## Tuning / diagnostics learned
- Path MTU ENTRY↔EXIT = 1500 (DF ping + tracepath); hytun mtu 1400 is safe; MTU is **not** the cause of site failures here.
- Capacity test: on EXIT temporarily add `speedTest: true` to config.yaml, restart, run `hysteria speedtest -c /etc/hysteria/client.yaml` on ENTRY, then remove it.
- `su hyedge -c curl <domain>` is ~4s slower (system resolver = provider DNS, unreachable via EXIT). Not a client issue: hysteria-edge uses its own `resolver` (1.1.1.1). Use `--resolve` or `-x socks5h` when benchmarking.
- Clients that connect to **IPv6 literals** get `no IPv4 address available` (EXIT has no IPv6). Fix on the client: IPv6 off / IPv4-only DNS strategy (Hiddify: IPv6 mode = disable). Server cannot fix it without EXIT IPv6.
- `UdpRcvbufErrors` rises at ~190 Mbps (quic-go requests 7 MB socket buffers; rmem_max already 7.5 MB) — cosmetic.
## Hysteria diagnostics (manual)
Version: v2.12.3. Replace IPs/paths if the layout differs. On ENTRY run as root.
### Service state
```
# ENTRY (OpenRC)
for s in hysteria hysteria-route hysteria-edge; do rc-service $s status; done
ss -lunp | grep -E ':443\b' # edge listener (hysteria-edge)
ss -unp | grep hysteria # client UDP socket to EXIT
tail -f /var/log/hysteria.log /var/log/hysteria-edge.log
# EXIT (systemd)
systemctl status hysteria-server --no-pager; ss -lunp | grep :443
journalctl -u hysteria-server -f # "client connected" / "TCP error"
```
### Tunnel (ENTRY -> EXIT)
```
hysteria ping -c /etc/hysteria/client.yaml 1.1.1.1:443 # RTT of a connect via the tunnel
hysteria speedtest -c /etc/hysteria/client.yaml # needs `speedTest: true` on EXIT (remove afterwards)
ip -br a show hytun; ip rule | grep -E '^10[01]'; ip route show table 100
su -s /bin/sh hyedge -c 'curl -4 -s https://ifconfig.me' # must print the EXIT IP
tcpdump -ni hytun -c 20 # traffic entering the tun
tcpdump -ni eth0 'udp port 443 and host 85.234.86.140' # QUIC to EXIT (on EXIT: enp3s0, host 213.226.125.13)
```
- Client log `connected to server ... count: N` – N grows on each reconnect. `TUN UDP error ... EOF` right after an EXIT restart is normal.
- `rc-service hysteria status` = `crashed` and `connect error: timeout` -> UDP 443 path/Security Group problem (see prerequisites).
### Clients (Traffic Stats API on edge, enabled, 127.0.0.1 only)
Config block in `edge.yaml`: `trafficStats: {listen: 127.0.0.1:9999, secret: <in /etc/hysteria/.stats-secret, 600>}`.
```
S=$(cat /etc/hysteria/.stats-secret); A="Authorization: $S"; U=http://127.0.0.1:9999
curl -s -H "$A" $U/online # {"mobile":1} devices per user
curl -s -H "$A" $U/traffic # {"mobile":{"tx":..,"rx":..}} add ?clear=1 to reset counters
curl -s -H "$A" -H 'Accept: text/plain' $U/dump/streams # live streams: user, bytes, lifetime, req-addr
curl -s -H "$A" -X POST -d '["mobile"]' $U/kick # drop a user's sessions (they reconnect if creds still valid)
```
Without the header the API returns 401. To block a user permanently remove it from `auth.userpass` and restart `hysteria-edge`.
### Useful subcommands
```
hysteria share -c /etc/hysteria/client.yaml # hy2:// URI for a client config (prints the password!)
hysteria check-update # compare with the latest release
hysteria version
```
### Error -> meaning
| Log text | Meaning |
|---|---|
| `no IPv4 address available` (edge) | client asked for an IPv6 literal; EXIT has no IPv6 -> disable IPv6 on the client |
| `rejected` (edge) | ACL hit (private ranges) |
| `resolve error ... deadline exceeded` (edge) | edge `resolver` unreachable through the tunnel |
| `no certificate matches the pinned hash` | wrong `pinSHA256` (strip `#name` from the URI fragment) |
| `authentication failed` / 404 on auth | wrong `user:password` |
| curl via tun hangs, `tcpdump -i hytun` shows SYN-ACK from dst on hytun | strict `rp_filter` -> set `=2` |
## Known issues / notes
- Backups on ENTRY: `/etc/hysteria/*.bak*`. Remote shell: zsh does not word-split variables → use functions for ssh wrappers.
- ENTRY reboot tested (2026-09-30): all three services, hytun, rules, sysctl and tunnel came up by themselves; mobile client reconnected. EXIT reboot tested too: hysteria-server and sysctl came up, ENTRY client reconnected automatically (count 2).
- strongSwan/IKE to Gcore (62.112.222.168) is a separate, unresolved task (needs UDP 500/4500 reachability); `charon` started manually, not enabled at boot.
- SSH on ENTRY is key-only since 2026-09-30 (a cloud-init drop-in used to re-enable passwords; hardening lives in `/etc/ssh/sshd_config.d/00-hardening.conf`). A full ENTRY reboot test after the OpenVPN Monitor changes passed (2026-09-30, see `REBOOT-TEST.md`).
@@ -1,50 +0,0 @@
# Артефакт внедрения: п.1 — валидация настроек Profiler
Дата: 2026-09-30. Узел: 213.226.125.13 (Alpine, OpenRC). Приложение: `/opt/OpenVPN-Monitoring-Simple`. План: `PLAN-validation-and-privilege-drop.md`.
Коммит в репозитории приложения на узле: `05f44b9` («Profiler: validate server/PKI settings before they reach OpenVPN config»), пуш не выполнялся.
## 1. Что внедрено
| Слой | Файл | Суть |
|---|---|---|
| A | `APP_PROFILER/schemas.py` | валидаторы `SystemSettingsUpdate`, `PKISettingUpdate` (422) |
| B | `APP_PROFILER/services/validation.py` (новый), `services/generator.py` | `check_script`: скрипт только из `/etc/openvpn/scripts/`, root-owned, без записи group/other |
| C | `APP_PROFILER/services/generator.py`, `routers/server.py` | отказ при `\n`, `\r`, NUL, управляющих символах, `"`, `\`; `ValueError` → HTTP 400 |
## 2. Порядок внедрения
1. Бэкап изменяемых файлов: `/root/app-bak/p1/` (`schemas.py`, `generator.py`, `server.py`).
2. Добавлен `services/validation.py`; правки `schemas.py`, `generator.py`, `routers/server.py` (Python-патч с проверкой якорей `assert`).
3. Проверка импорта: `venv/bin/python -c "import schemas"`.
4. `rc-service ovpmon-profiler restart`.
5. Тесты (скрипт запускался на узле с локально выпущенным токеном, т.к. на учётке включена 2FA).
6. Документация: `DOCS/Changes/2026-09-30_Settings_Validation.md`, ссылки в `README.md`, `DOCS/General/Index.md`; коммит.
## 3. Доказательства (результаты тестов)
| Проверка | Результат |
|---|---|
| Круговой `PUT` текущих настроек server / pki | 200 / 200 |
| 17 вредоносных или невалидных значений | все 422 |
| 4 валидных изменения | все 200 |
| Скрипты: root 755 / group-writable / симлинк / нет файла / вне каталога / traversal / пусто | принят / отклонён / отклонён / отклонён / отклонён / отклонён / принят |
| Слой C при обходе схемы (5 инъекций) | все заблокированы, ничего не записано |
| Рендер текущих настроек против рабочего `server.conf` | идентичен |
| После тестов | настройки восстановлены и совпадают с исходными; `rc-status`: все сервисы `started` |
## 4. Откат
```sh
cd /opt/OpenVPN-Monitoring-Simple/APP_PROFILER
cp /root/app-bak/p1/schemas.py schemas.py
cp /root/app-bak/p1/generator.py services/generator.py
cp /root/app-bak/p1/server.py routers/server.py
rm services/validation.py
rc-service ovpmon-profiler restart
```
Либо `git revert 05f44b9` в репозитории.
## 5. Оговорки
- Каталога `/etc/openvpn/scripts/` по умолчанию нет (для теста создавался временно и удалён): перед включением скриптов создать `root:root 755`, файлы `755` от root.
- Валидаторы действуют на обновления; ранее сохранённые значения проверяются при рендере (слой C).
- Слой B/C защищает конфиг, но сервис по-прежнему работает от root — это закрывает пункт 2 (см. `IMPLEMENTATION-02-…` после выполнения).
@@ -1,68 +0,0 @@
# Артефакт внедрения: п.2 — API без root + root-помощник
Дата: 2026-09-30. Узел: 213.226.125.13 (Alpine, OpenRC). Приложение: `/opt/OpenVPN-Monitoring-Simple`. План: `PLAN-validation-and-privilege-drop.md`.
Коммит в репозитории приложения на узле: `6f9e800` («Run API services unprivileged; add root helper…»; после `--amend`, ранее упоминался как `10020ca`), дополнение по CRL — `9ffdbfa`, пуш не выполнялся. Полное описание: `DOCS/Changes/2026-09-30_Privilege_Separation.md`.
## 1. Что внедрено
| Компонент | Расположение | Суть |
|---|---|---|
| Пользователь | `ovpmon` (uid 109, nologin) | владелец данных: `/var/lib/ovpmon`, `/var/log/ovpmon`, `easy-rsa`, `client-config`, логи, `__pycache__` |
| OpenRC | `/etc/init.d/ovpmon-{api,gatherer,profiler}` | `command_user="ovpmon:ovpmon"`; `/etc/ovpmon/env` остаётся root 600 |
| Помощник | `/usr/local/sbin/ovpmon-helper` (root, 755) | `install-config` (allowlist директив, атомарная установка) и `service start\|stop\|restart\|status` |
| doas | `/etc/doas.d/ovpmon.conf` | ровно 5 команд помощника, без других аргументов |
| Код Profiler | `services/process.py`, `routers/server.py` | без root: staging → помощник; ветки root/контейнера не менялись |
## 2. Порядок внедрения
1. Бэкап: `/root/backup-p2-2026-09-30-1229.tar`, `/root/app-bak/p2/` (init-скрипты, `process.py`, `server.py`).
2. Создание `ovpmon`, установка помощника и doas-правил; проверка помощника от имени `ovpmon` (сервисы ещё root).
3. Патч `process.py` / `server.py` (+ `except HTTPException: raise`, чтобы отказ 400 не превращался в 500).
4. `chown` данных, `command_user` в init-скриптах; перезапуск gatherer → api → profiler с проверкой каждого.
5. Функциональные и негативные тесты; рестарт OpenVPN через API.
6. Документация и коммит (исправлен эпизод с порчей `Deployment_Native.md`: восстановлен из предыдущего коммита и переделан, коммит переписан `--amend`, пуша не было).
## 3. Доказательства
| Проверка | Результат |
|---|---|
| Процессы | gunicorn, uvicorn, gatherer — `ovpmon`; root остались только supervise-daemon |
| Помощник принимает рабочий `server.conf` | да, файл в `/etc/openvpn` не изменился (sha256 совпал) |
| 17 инъекций директив, отсутствие `user nobody`, cert вне PKI, CR, симлинк staged-файла | все отклонены, боевой конфиг не тронут |
| doas: произвольная команда, другие аргументы помощника | `Operation not permitted` |
| `ovpmon` не может: читать `/etc/shadow`, `/root`, `/etc/hysteria/*.yaml`, `/etc/ovpmon/env`; писать в `/etc/openvpn`, `/etc/init.d`, `authorized_keys`, код приложения; запускать `iptables` | все отказы |
| API: мониторинг, config, process stats, `server/configure` (конфиг идентичен), создание/скачивание/отзыв профиля | всё 200 |
| Рестарт OpenVPN через API (helper) | 200; OpenVPN и `tun0` подняты, статус-лог читается gatherer, `ip rule 102` и MASQUERADE на месте, ошибок в логе gatherer нет |
Побочный эффект тестов: один рестарт OpenVPN (~секунды разрыва VPN-сессий; клиент переподключается сам).
## 4. Откат
```sh
cp /root/app-bak/p2/ovpmon-{api,gatherer,profiler} /etc/init.d/
chown -R root:root /var/lib/ovpmon /var/log/ovpmon /opt/OpenVPN-Monitoring-Simple/APP_PROFILER/{easy-rsa,client-config}
for s in ovpmon-gatherer ovpmon-api ovpmon-profiler; do rc-service $s restart; done
```
(помощник и doas-правила можно оставить; код Profiler при root работает по прежней ветке).
## 5. Оговорки
- `crl_verify`: ограничение снято (2026-09-30, коммит `9ffdbfa`) — см. раздел 6 ниже.
- Проверка путей PKI в помощнике выполняется на момент установки; каталог PKI принадлежит `ovpmon` — держать его только за этим пользователем.
- Скрипты подключения по-прежнему требуют `/etc/openvpn/scripts/` (root, 755) — каталога нет по умолчанию.
## 6. Дополнение: публикация CRL для `crl_verify` (2026-09-30)
Проблема: OpenVPN после старта работает от `nobody`, а `pki/` создаётся с правами 700 (владелец `ovpmon`), поэтому при включённом `crl_verify` все клиенты получили бы отказ.
Решение: новая команда помощника `publish-crl` (6-е правило doas) копирует `pki/crl.pem` в `/etc/openvpn/crl.pem` (`root:root 644`) с проверками (файл внутри PKI, не симлинк, владелец `ovpmon`, ≤ 1 МиБ, PEM-маркеры и разбор `openssl crl`). Вызывается после `gen-crl` (init/revoke), при `server/configure` и при каждом `service start|restart`; ошибка публикации при отзыве возвращается как ошибка API. Генератор без root пишет `crl-verify /etc/openvpn/crl.pem`, помощник разрешает для `crl-verify` только этот путь.
Проверка (отдельный временный экземпляр OpenVPN на другом порту и подсети, от `nobody`, тот же PKI и CRL; боевой OpenVPN не перезапускался):
| Проверка | Результат |
|---|---|
| `publish-crl` от `ovpmon`; права копии; чтение `nobody` | ok; `root:root 644`; читается; исходный `pki/crl.pem` для `nobody` по-прежнему недоступен |
| мусорный файл / поддельные PEM-маркеры / симлинк вместо CRL | отклонены |
| `crl_verify=true` через API + `server/configure` | 200, в конфиге `crl-verify /etc/openvpn/crl.pem`, помощник принял; настройка возвращена, боевой `server.conf` идентичен исходному |
| валидный клиент при активной проверке CRL | подключается |
| отзыв через API и повторное подключение | `certificate revoked`, клиент отклонён, ошибок чтения CRL нет |
Побочное: в списке профилей остались записи со статусом revoked от тестов (`ok-user1`, `p2test-*`, `crl-e2e-*`). Тестовый экземпляр и файлы удалены, боевой OpenVPN (pid 8884) и правила выхода через hel не затронуты. Значение `crl_verify` в настройках оставлено выключенным, как было.
@@ -1,82 +0,0 @@
# План: валидация настроек (п.1) и запуск API не от root (п.2)
Дата: 2026-09-30. Узел: 213.226.125.13 (Alpine, OpenRC). Приложение: `/opt/OpenVPN-Monitoring-Simple`.
Основание: SUMMARY-ovpn-monitor.md, раздел 6.5 — администратор панели фактически равен root, т.к. Profiler работает от root, а настройки без проверки попадают в `server.conf`.
## Исходные факты
- `APP_CORE` (API, gatherer) root не нужен: читает `openvpn-status.log`, пишет свою SQLite-БД и лог.
- Profiler требует root только для: записи `/etc/openvpn/server.conf`, `rc-service openvpn`, чтения PKI-файлов самим OpenVPN.
- В коде уже есть fallback `staging/server.conf`.
- В шаблоне `script-security 2` стоит внутри `{% if user_defined_cdscripts %}`.
- `doas` установлен; конфигурация только `permit nopass :wheel`.
## Пункт 1. Валидация настроек (3 слоя)
**Слой A. Схемы (`APP_PROFILER/schemas.py`)** — валидаторы только на `*Update`-схемах (старые значения из БД не ломают `GET`).
| Поле | Правило |
|---|---|
| `port`, `management_port` | 1–65535 |
| `vpn_network`, `vpn_netmask` | `ipaddress`: сеть и корректная маска |
| `split_routes[]` | CIDR или «сеть маска», нормализация через `ipaddress` |
| `dns_servers[]` | IPv4/IPv6 через `ipaddress` |
| `public_ip` | IP или hostname по маске, без пробелов и кавычек |
| `management_interface_address` | только loopback |
| `tun_mtu` / `mssfix` | 576–9000 / 536–1500 |
| `connect_script`, `disconnect_script` | пусто или `^/etc/openvpn/scripts/[A-Za-z0-9_.-]{1,64}$` |
| PKI `fqdn_ca`, `fqdn_server` | маска как у `username` |
| PKI `easyrsa_dn` | `cn_only` или `org` |
| PKI `req_country` | `^[A-Z]{2}$` |
| PKI `req_province/city/org/ou` | `^[A-Za-z0-9 .,_-]{0,64}$` |
| PKI `req_email` | простая маска email |
| PKI `key_size` | 2048 / 3072 / 4096 |
| PKI сроки | целые в разумных пределах |
**Слой B. Скрипты (`routers/server.py`, до генерации):** `realpath` внутри `/etc/openvpn/scripts/`, файл существует, владелец root, нет прав записи для group/other.
**Слой C. Генератор (`services/generator.py`):** перед записью проверить, что ни одно значение не содержит `\n`, `\r`, `"`, `\`; иначе ошибка и файл не пишется.
Тесты: невалидные значения (перевод строки в DNS, `../` в скрипте, `/` в организации, порт 0) → 422; валидный набор → 200 и корректный `server.conf`.
## Пункт 2. Profiler и API не от root
Схема: пользователь `ovpmon` + маленький root-помощник, сам валидирующий конфиг (защита в глубину: инъекция в конфиг не даёт root даже при обходе слоёв A–C).
1. **Пользователь и права.** Системный `ovpmon`. Владелец: `/var/lib/ovpmon`, `/var/log/ovpmon`, `APP_PROFILER/{easy-rsa,client-config,staging,*.db,profiler.log}`, `APP_CORE/{*.db,*.log}`. `pki/`: каталоги 755, `crl.pem` 644, приватные ключи 600. Код и `venv` остаются root-owned. `/etc/ovpmon/env` остаётся root 600.
2. **OpenRC:** `command_user="ovpmon:ovpmon"` в `ovpmon-*`.
3. **Помощник `/usr/local/sbin/ovpmon-helper`** (root, 755, Python). Подкоманды без пользовательских аргументов:
- `install-config`: читает только `/var/lib/ovpmon/staging/server.conf` (один раз в память, защита от TOCTOU), проверяет allowlist директив (запрещены `up`, `down`, `plugin`, `route-up`, `tls-verify`, `auth-user-pass-verify`, `learn-address`, неизвестные; `client-connect/disconnect` и `script-security` — только со скриптом из `/etc/openvpn/scripts/` с проверкой владельца и прав), пишет `/etc/openvpn/server.conf` атомарно (root:root 644).
- `service start|stop|restart|status` только для `openvpn`.
4. **`doas`:** `/etc/doas.d/ovpmon.conf`, точные `args` для каждой подкоманды.
5. **Код Profiler:** на хосте `services/process.py` и `routers/server.py` вызывают `doas ovpmon-helper …`; ветка контейнера и `staging` не меняются.
6. **`APP_CORE`:** только смена владельца и `command_user`.
7. **Каталог скриптов:** `/etc/openvpn/scripts/` root:root 755, по умолчанию пустой.
### Порядок
1. Бэкап `/etc/openvpn`, БД, `/etc/init.d/ovpmon-*`, код, `easy-rsa/`.
2. Слои A–C + тесты, перезапуск Profiler.
3. Пользователь, `chown`, помощник, `doas`; ручная проверка помощника.
4. Переключить `process.py` и `server.py` на помощник.
5. Переключить init-скрипты на `command_user`, перезапускать по одному.
6. Обновить документацию и SUMMARY, отдельные коммиты.
### Проверка (п.2)
- `ps`: Profiler и API под `ovpmon`.
- От `ovpmon`: нет доступа к `/etc/shadow`, `/root`, `/etc/hysteria/*.yaml`, запись в `/etc/openvpn` запрещена.
- UI: Initialize PKI, генерация и запись конфига, Start/Stop/Restart OpenVPN, создание/скачивание/отзыв профиля, мониторинг.
- Инъекция директивы в `staging/server.conf` отвергается помощником, `/etc/openvpn/server.conf` не меняется.
- Прямые вызовы `doas` с другими аргументами отклоняются.
- OpenVPN-клиент подключается и выходит через hel.
- Не сломаны fail2ban, HTTPS 8088, `ip rule 102`.
## Риски
| Риск | Смягчение |
|---|---|
| Сервис не стартует из-за прав | бэкап, `chown` до переключения, откат правкой init-скриптов |
| Allowlist блокирует легальный конфиг | первый прогон в режиме проверки без записи; список директив из `server.conf.j2` |
| Ошибка в `doas` `args` | негативные тесты от `ovpmon`, запасная root-SSH-сессия |
| Потеря ключей PKI | копия `easy-rsa/` перед `chown` |
## Статус
- Пункт 1 — реализован (2026-09-30), см. SUMMARY раздел 6.6 и DOCS/Changes/2026-09-30_Settings_Validation.md.
- Пункт 2 — реализован (2026-09-30), см. IMPLEMENTATION-02-privilege-separation.md и DOCS/Changes/2026-09-30_Privilege_Separation.md.
-12
View File
@@ -1,12 +0,0 @@
# Operations records (deployment on ENTRY, Timeweb)
Records of one concrete deployment (host addresses, results, rollback). No passwords or keys are stored here.
| Document | Content |
|---|---|
| [SUMMARY-ovpn-monitor.md](SUMMARY-ovpn-monitor.md) | Current state, access, install, egress via Hysteria2, security findings/fixes, risk assessment, commits, backups, open items |
| [Hysteria_Chain_Manifest.md](Hysteria_Chain_Manifest.md) | Hysteria 2 entry-exit chain manifest, diagnostics, plus the OpenVPN Monitor section |
| [REBOOT-TEST.md](REBOOT-TEST.md) | Reboot tests (Hysteria chain; ENTRY after the OpenVPN Monitor deployment) |
| [PLAN-validation-and-privilege-drop.md](PLAN-validation-and-privilege-drop.md) | Plan: settings validation and running the API unprivileged |
| [IMPLEMENTATION-01-settings-validation.md](IMPLEMENTATION-01-settings-validation.md) | Rollout record: settings validation |
| [IMPLEMENTATION-02-privilege-separation.md](IMPLEMENTATION-02-privilege-separation.md) | Rollout record: privilege separation and CRL publishing |
-106
View File
@@ -1,106 +0,0 @@
# Reboot test: ENTRY (Timeweb) and EXIT (Hel)
Date: 2026-09-30. Goal: confirm the Hysteria 2 chain recovers by itself after a reboot of each node, with no manual steps.
Nodes: ENTRY 213.226.125.13 (Alpine, OpenRC), EXIT 85.234.86.140 (Debian 13, systemd).
## Methodology
Order: ENTRY first, then EXIT. Each node is rebooted separately, so the other side is always up and its reconnect behavior is observable.
### 1. Pre-flight (before each reboot)
| Check | ENTRY | EXIT |
|---|---|---|
| Services enabled | `rc-update show default` (hysteria, hysteria-route, hysteria-edge) | `systemctl is-enabled hysteria-server` |
| Kernel module for TUN persists | `lsmod \| grep tun`, `grep -x tun /etc/modules` | not needed |
| sysctl persisted | `ls /etc/sysctl.d/` (99-hytun.conf, 99-quic.conf) | `ls /etc/sysctl.d/99-quic.conf` |
| Temporary test settings removed | n/a | `grep -c speedTest /etc/hysteria/config.yaml` = 0 |
Any gap found is fixed before rebooting.
### 2. Reboot
`sync`, then a delayed `reboot` / `systemctl reboot` (detached, so the SSH command returns). Wait 45 s, then poll SSH every 6 s (up to 20 tries) until `uptime` answers.
### 3. Post-boot verification
ENTRY:
1. `rc-service hysteria|hysteria-route|hysteria-edge status` → `started`.
2. `ls -l /dev/net/tun`, `ip -br a show hytun`.
3. `ip rule | grep -E '^10[01]'` and `ip route show table 100` → both rules, default via hytun, blackhole fallback.
4. `sysctl net.ipv4.conf.all.rp_filter net.core.rmem_max` → 2 and 7500000.
5. `ss -lunp | grep :443` → `hysteria-edge` listening.
6. Tunnel TCP: `su -s /bin/sh hyedge -c 'curl -4 -s https://ifconfig.me'` → must equal the EXIT IP.
7. Tunnel UDP: `su -s /bin/sh hyedge -c 'nslookup example.com 1.1.1.1'` → address returned.
8. Logs: `/var/log/hysteria.log`, `/var/log/hysteria-edge.log`; a real client (mobile) reconnecting is a bonus signal.
EXIT:
1. `systemctl is-active hysteria-server`, `ss -lunp | grep :443`.
2. `sudo /usr/sbin/sysctl net.core.rmem_max net.core.wmem_max` (`sysctl` is not in a non-root user's PATH).
3. `journalctl -u hysteria-server -b` → "server up and running" and "client connected" from ENTRY.
4. From ENTRY: client log shows a new `connected to server` (count incremented) and the `hyedge` curl test (step 6 above) returns the EXIT IP.
## Results
### ENTRY reboot (Timeweb)
| Check | Result |
|---|---|
| Pre-flight | **Gap found:** module `tun` loaded by hand but absent from `/etc/modules` → after reboot `/dev/net/tun` could be missing and the tunnel would not start. Fixed (`echo tun >> /etc/modules`) before rebooting. |
| SSH back | Yes, about 45-60 s after the reboot command |
| Services | hysteria, hysteria-route, hysteria-edge all `started` |
| TUN / routing | `/dev/net/tun` present, `hytun` up (100.100.100.101/30), rules 100 and 101 present, table 100: default dev hytun + blackhole |
| sysctl | `rp_filter=2`, `rmem_max=7500000` applied |
| Listener | `hysteria-edge` on UDP 443 |
| Tunnel TCP | `85.234.86.140` (EXIT IP) |
| Tunnel UDP | DNS answer received |
| Client | Hiddify (`mobile`) reconnected on its own right after boot |
| Noise in logs | A few dial timeouts to individual remote hosts (unreachable destinations, not a tunnel fault) |
Verdict: **PASS** (after the `/etc/modules` fix).
### EXIT reboot (Hel)
| Check | Result |
|---|---|
| Pre-flight | `hysteria-server` enabled, `99-quic.conf` present, `speedTest` absent from config (0) |
| SSH back | Yes, about 45-50 s after the reboot command |
| Service | `hysteria-server` `active`, listening on UDP 443 |
| sysctl | `rmem_max` and `wmem_max` = 7500000 |
| Journal | "server up and running" at boot, then "client connected" from 213.226.125.13 about 30 s later |
| ENTRY side | Client reconnected automatically (`connected to server`, `count: 2`); brief `TUN UDP error ... EOF` while EXIT was down; `hyedge` curl returned `85.234.86.140` |
Verdict: **PASS**.
## Conclusions
- Both nodes recover unattended; the ENTRY hysteria client (supervise-daemon, `lazy: true`) reconnects without restart when EXIT comes back.
- During an EXIT outage the anti-leak blackhole route in table 100 keeps `hyedge` traffic from leaving via ENTRY's own uplink (leak test done separately: removing the tun default route makes the test curl fail instead of exposing the ENTRY IP).
- Not covered: simultaneous reboot of both nodes, power-loss/unclean shutdown, and IKE/strongSwan (separate task, `charon` is not enabled at boot).
## ENTRY reboot after the OpenVPN Monitor deployment (2026-09-30)
Goal: confirm the whole ENTRY stack (Hysteria chain + OpenVPN Monitor, OpenVPN, egress rules, hardening) recovers by itself. Only ENTRY was rebooted; EXIT stayed up.
### Pre-flight
- `rc-update show default`: `hysteria`, `hysteria-route`, `hysteria-edge`, `ovpn-hytun`, `openvpn`, `ovpmon-api`, `ovpmon-gatherer`, `ovpmon-profiler`, `nginx`, `fail2ban`, `sshd`, `chronyd` enabled.
- `tun` in `/etc/modules`; sysctl files present (`ip_forward=1`, `rp_filter=2`); `sshd -t` and `doas -C /etc/doas.d/ovpmon.conf` valid.
- Baseline snapshot `/root/pre-reboot-snapshot.txt`: service states, `ip rule 100-102`, table 100, nat/FORWARD rules, listeners, process owners.
### Reboot and result
`sync`, detached `reboot`; SSH answered again after ~45 s. Post-boot snapshot `/root/post-reboot-snapshot.txt` is **identical** to the baseline.
| Check | Result |
|---|---|
| All services in `default` | started by themselves |
| API processes | gunicorn/uvicorn/gatherer run as `ovpmon` |
| `hytun`, `tun0`, `rp_filter=2`, `ip_forward=1` | present |
| `ip rule` 100/101/102, table 100 (hytun + blackhole), MASQUERADE to `hytun`, FORWARD DROP guard | restored by `hysteria-route` / `ovpn-hytun` |
| Tunnel TCP as `hyedge` | `85.234.86.140` (EXIT) |
| Hysteria client | reconnected to EXIT |
| Panel | `https://…:8088/` 200, profiler without token 401, HTTP→HTTPS 301, login `tstark` works |
| Helper/doas | `service status` and `process stats` OK; gatherer reads `openvpn-status.log` (`root:ovpmon 640` persisted) |
| `/etc/openvpn/crl.pem`, `/var/lib/ovpmon` ownership | intact |
| fail2ban | 3 jails active |
| SSH | `passwordauthentication no`, `permitrootlogin prohibit-password` |
| Errors in `ovpmon-*` logs since boot | none (older entries predate the boot) |
| Real VPN client | reconnected by itself ~3.5 min after boot (UDP client waits for its `keepalive 10 120` timeout); ~5 MB downloaded through the tunnel, MASQUERADE counters rose, leak guard `FORWARD DROP` counter stayed 0 |
### Notes
- Expected client gap after a server reboot is up to ~2-4 minutes for UDP OpenVPN clients (ping-restart), not a fault of the server.
- `openvpn-status.log` keeps `root:ovpmon 640` because the file persists on disk; if it is ever deleted, OpenVPN recreates it as `600` and the gatherer cannot read it until the next `ovpmon-helper service start|restart` (which fixes the mode). Not triggered by a reboot.
-169
View File
@@ -1,169 +0,0 @@
# Summary: OpenVPN Monitor & Profiler на ENTRY (Timeweb) + выход через hysteria2 → hel
Актуализировано: 2026-09-30 (по всем доработкам). Узел: 213.226.125.13 (Alpine 3.23.6, OpenRC), доступ `ssh -i private.key root@213.226.125.13` (только по ключу).
Пароль администратора панели в документе **не хранится** (после развёртывания заменён владельцем; сгенерированный начальный пароль больше не действует). Документ не содержит секретов, но остаётся внутренним (`chmod 600`).
Связанные документы:
- Рядом в `DOCS/Operations/`: `Hysteria_Chain_Manifest.md` (манифест цепочки Hysteria + раздел про OpenVPN Monitor), `PLAN-validation-and-privilege-drop.md`, `IMPLEMENTATION-01-settings-validation.md`, `IMPLEMENTATION-02-privilege-separation.md`.
- В репозитории приложения на узле (`/opt/OpenVPN-Monitoring-Simple/DOCS/`): `General/Deployment_Docker.md`, `General/Deployment_Native.md`, `Changes/2026-09-30_*.md` (Security_Hardening, Admin_Username_Change, Settings_Validation, Privilege_Separation, Egress_via_Hysteria2), `General/privilege-separation/` (помощник и правила doas).
## 1. Текущее состояние
| Компонент | Состояние |
|---|---|
| Панель | `https://213.226.125.13:8088/` — nginx, TLS 1.2/1.3, самоподписанный сертификат |
| Учётная запись | логин `tstark` (не `admin`), 2FA включена владельцем, встроенной `admin/password` нет |
| Сервисы OpenRC (автозагрузка) | `ovpmon-api` (gunicorn, 127.0.0.1:5001), `ovpmon-gatherer`, `ovpmon-profiler` (uvicorn, 127.0.0.1:8000) — **от пользователя `ovpmon`**; `nginx`; `openvpn`; `ovpn-hytun`; `fail2ban` |
| OpenVPN | udp/1194, сеть клиентов 172.20.1.0/24, полный туннель, клиентский трафик уходит через hysteria2 на hel; сквозной тест реальным клиентом пройден |
| Root-помощник | `/usr/local/sbin/ovpmon-helper` + 6 правил `doas` (`/etc/doas.d/ovpmon.conf`) |
| SSH | только ключи (`PasswordAuthentication no`, `PermitRootLogin prohibit-password`, `MaxAuthTries 3`) |
| `crl_verify` | поддерживается (CRL публикуется помощником), в настройках сейчас **выключен** |
| Hysteria (entry/client, UDP 443, 1080, 8080, 9999) | не затрагивалась доработками |
## 2. Доступ к админке
| Параметр | Значение |
|---|---|
| URL | `https://213.226.125.13:8088/` (HTTP на этом порту → 301 на HTTPS) |
| Логин | `tstark` |
| Пароль / 2FA | задаются и меняются владельцем в UI: **Account** (Change Password, Change Username, Two-Factor Authentication) |
| Сертификат | самоподписанный EC P-256, SAN `IP:213.226.125.13, DNS:ovpmon`, до 2029-01-02, файлы `/etc/ovpmon/tls/ovpmon.{crt,key}` |
| SHA-256 отпечаток | `E1:7F:A1:C1:F9:E8:22:C0:32:59:82:EF:D2:D7:FC:75:F6:3D:7E:8E:48:FA:55:88:9F:69:4D:15:3E:2B:7B:58` |
- Проверка клиентом: `curl --cacert ovpmon.crt https://213.226.125.13:8088/` (скопировать `ovpmon.crt` с узла).
- Первая фаза уже выполнена (PKI инициализирован); далее в UI: генерация server.conf, запуск OpenVPN, профили клиентов.
- JWT-секрет: `/etc/ovpmon/env` (`root:root 600`).
- Аварийное восстановление (если таблица `users` пуста): временно задать `OVPMON_INITIAL_ADMIN_USER` / `OVPMON_INITIAL_ADMIN_PASSWORD` в `/etc/ovpmon/env`, `rc-service ovpmon-api restart`, затем удалить переменные и перезапустить сервис. Без переменных пользователь не создаётся (в логе ERROR).
## 3. Установка окружения (без контейнеров)
Приложение: `/opt/OpenVPN-Monitoring-Simple` (не `/opt/ovpn-bash-profiler` — там только bash-профайлер без веб-части). Docker-compose репозитория не используется; сервисы вынесены в OpenRC.
1. Пакеты: `apk add python3 py3-pip nginx nodejs npm openvpn easy-rsa iptables bash` (+ `fail2ban`, `doas` уже был).
2. Backend: venv в `APP_CORE` (+ `gunicorn`) и `APP_PROFILER`, зависимости из `requirements.txt`.
3. UI: `npm install && npm run build` в `APP_UI`, `dist/` → `/var/www/ovpmon` (предыдущая сборка: `/var/www/ovpmon.bak`).
4. Конфиг: `/etc/ovpmon/env` (600): общий JWT-секрет, пути БД `/var/lib/ovpmon/*.db`, путь `openvpn-status.log`, `OVPMON_CORS_ORIGINS=https://213.226.125.13:8088`. Каталоги: `/var/lib/ovpmon` (+ `staging/`), `/var/log/ovpmon`, `/var/log/openvpn`.
5. Сервисы (`supervisor=supervise-daemon`, `respawn_delay=3`, `command_user="ovpmon:ovpmon"`, окружение подгружается в `start_pre` из `/etc/ovpmon/env`).
6. nginx: `/etc/nginx/http.d/ovpmon.conf` — 8088 TLS; `/` статика UI, `/api/` → :5001, `/profiles-api/` → :8000/api/.
7. Для Alpine: каталог `APP_PROFILER/easy-rsa` копируется из `/usr/share/easy-rsa` вручную (в Docker это делает entrypoint); симлинк `/etc/openvpn/openvpn.conf → server.conf`, чтобы кнопка Start в UI (`rc-service openvpn`) работала.
8. Параметры OpenVPN (`/etc/openvpn/server.conf`, генерируется приложением): udp/1194, `server 172.20.1.0/24`, `tun-mtu 1400`, `mssfix 1360`, `redirect-gateway def1`, DNS 1.1.1.1 и 8.8.8.8, `user nobody`, `group nogroup`.
## 4. Трафик клиентов OpenVPN → hysteria2 → hel
```
OpenVPN client ─udp/1194→ tun0 (172.20.1.1/24)
→ ip rule 102: from 172.20.1.0/24 → table 100
→ table 100: default dev hytun (metric 10); blackhole default (metric 1000)
→ iptables nat POSTROUTING -s 172.20.1.0/24 -o hytun -j MASQUERADE
→ hytun (TUN клиента hysteria, 100.100.100.101/30, mtu 1400)
→ hysteria client ─hy2/QUIC UDP 443→ EXIT 85.234.86.140 → Интернет (IPv4)
```
OpenRC-сервис `ovpn-hytun` (`need hysteria-route`, `before openvpn`) ставит `ip rule 102`, MASQUERADE на `hytun`, TCP MSS clamp и анти-утечку `FORWARD -s 172.20.1.0/24 ! -o hytun -j DROP`, а также `net.ipv4.ip_forward=1` (`/etc/sysctl.d/98-forward.conf`). Правила идемпотентны, `stop` их снимает.
- Приоритеты: 100 — ответы `sport 443` в main, 101 — `uid hyedge`, 102 — подсеть OpenVPN; нужен `rp_filter=2`.
- Служебный трафик (SSH, порт 1194 OpenVPN) идёт мимо туннеля. При падении hysteria таблица 100 уходит в blackhole: клиенты теряют интернет, утечки нет. На EXIT изменений не потребовалось.
- Проверка: `ip rule | grep 102`, `iptables -t nat -S POSTROUTING`; клиент на `https://ifconfig.me` видит `85.234.86.140`; эталон на узле — `su -s /bin/sh hyedge -c "curl -4 https://ifconfig.me"`.
- Статус: TCP/UDP через `hytun` подтверждены на узле, сквозной тест с реальным VPN-клиентом пройден (1194/udp достижим снаружи).
## 5. HTTPS
nginx на 8088: TLS 1.2/1.3 (TLS 1.1 отклоняется), HSTS, `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy`, `Cache-Control: no-store`, `server_tokens off`, редирект HTTP→HTTPS (`error_page 497`), `limit_req` 5/мин на `POST /api/auth/login`. Бэкенды слушают только 127.0.0.1. Прежний HTTP-конфиг: `/root/ovpmon.conf.bak`. Не объявлять второй `ssl_session_cache shared:SSL` другого размера — конфликт с `nginx.conf`. Порт управления OpenVPN (management) не включён; при включении — только loopback.
## 6. Безопасность: находки и их устранение
| # | Критичность | Находка | Исправление | Проверка |
|---|---|---|---|---|
| 1 | Критично | SSH: пароль root по сети (drop-in `50-cloud-init.conf` возвращал `PasswordAuthentication yes`; уже шёл перебор — 113 неудачных попыток) | `/etc/ssh/sshd_config.d/00-hardening.conf`: пароли и kbd-interactive выключены, `PermitRootLogin prohibit-password`, `MaxAuthTries 3`, `LoginGraceTime 30`; бэкап `/root/sshd_config.bak` | вход по ключу ок, по паролю `Permission denied (publickey)` |
| 2 | Высоко | Path traversal в Profiler (`username` без валидации, сервис от root) | маска `^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$` в схеме, `validate_username()` в `pki.py`, проверки `realpath` в роутере и генераторе | `../../tmp/pwn`, `a/b`, `..`, `-x` → 422, файл не создан |
| 3 | Высоко | Обход 2FA: временный токен принимался всеми ручками | `token_required` (Flask) и `verify_token` (Profiler) отклоняют `is_2fa_pending`; принимает его только `verify-2fa` | temp-токен → 401 везде, полный токен → 200 |
| 4 | Средне | `enable_2fa` писал OTP и TOTP-секрет в лог | убрано из сообщения | в логе секретов нет |
| 5 | Средне | CORS `*` + credentials | origin из `OVPMON_CORS_ORIGINS` (по умолчанию только same-origin), для Profiler сужены методы/заголовки | чужой `Origin` не получает `Access-Control-Allow-Origin` |
| 6 | Средне | Нет защиты от перебора | fail2ban: jails `sshd`, `sshd-ddos`, `ovpmon-login` (401/429/503 на логине), IP администратора в `ignoreip` | jails активны, баны SSH-сканеров зафиксированы |
| 7 | Средне | Панель по HTTP | TLS в nginx (раздел 5) | HTTPS 200, TLS 1.1 отклонён, rate-limit 503 |
| 8 | Высоко | Инъекция в `server.conf` через настройки (админ-токен → root) | валидация настроек в 3 слоя (раздел 7) | 17 вредных значений → 422, обход схемы блокируется рендером |
| 9 | Высоко | Сервисы API работали от root | пользователь `ovpmon` + root-помощник (раздел 8) | процессы под `ovpmon`, инъекции директив отклоняются |
| 10 | Низко | Стандартное имя `admin`, встроенный `admin/password` | смена имени в приложении, дефолтная учётка удалена (раздел 9) | логин `tstark` 200, `admin` 401 |
| 11 | Функц. | `crl_verify` не работал бы без root (`nobody` не читает `pki/`) | публикация CRL в `/etc/openvpn/crl.pem` (раздел 8) | клиент проходит, отозванный отклоняется |
Проверено без замечаний: алгоритм JWT зафиксирован HS256, секрет — 32 случайных байта; SQL f-строки используют только внутренние имена таблиц/колонок; nginx работает под непривилегированным пользователем; порты 1194/udp и 443/udp открыты по назначению со своей аутентификацией.
## 7. Валидация настроек Profiler (п.1 плана)
Слои: **A** — схемы `SystemSettingsUpdate` / `PKISettingUpdate` (порты, подсеть+маска, маршруты, DNS, `public_ip`, management только loopback, MTU/MSS, пути скриптов, поля DN и FQDN для PKI, размер ключа, сроки); **B** — скрипты подключения только из `/etc/openvpn/scripts/` (root-владелец, без записи group/other, без симлинков наружу); **C** — генератор отказывается писать `server.conf`/`.ovpn`, если значение содержит `\n`, `\r`, NUL, управляющие символы, `"` или `\`.
Результат: 17 вредоносных значений → 422; 4 валидных изменения → 200; инъекции мимо схемы блокируются; рендер текущих настроек идентичен рабочему конфигу. Каталога `/etc/openvpn/scripts/` по умолчанию нет — создать `root:root 755`, файлы `755`, перед включением скриптов. Артефакт: `IMPLEMENTATION-01-settings-validation.md`.
## 8. API не от root: пользователь `ovpmon`, root-помощник, CRL (п.2 плана)
```
ovpmon-api / gatherer / profiler (user ovpmon)
└─ doas -n /usr/local/sbin/ovpmon-helper <фиксированные аргументы> (6 точных правил)
├─ install-config — проверка staged server.conf по allowlist директив, атомарная установка в /etc/openvpn
├─ publish-crl — копия pki/crl.pem → /etc/openvpn/crl.pem (root:root 644)
└─ service start|stop|restart|status — rc-service openvpn
```
- `ovpmon` владеет `/var/lib/ovpmon`, `/var/log/ovpmon`, `APP_PROFILER/{easy-rsa,client-config,profiler.log}`, логами и `__pycache__`; код и venv — root, только чтение. От root остались лишь supervise-daemon.
- Allowlist `install-config`: только директивы шаблона с проверенными аргументами (`dev tun`, `proto`, `port`, пути PKI, `server`, `log`, `status`, `push` трёх видов, `user nobody`, `group nogroup`, шифры, `client-connect/disconnect` только из `/etc/openvpn/scripts/` и т.д.); `up`, `down`, `plugin`, `route-up`, `tls-verify`, `setenv`, `config` и всё неизвестное отклоняются; файл читается один раз, только обычный файл `ovpmon`, ASCII, ≤ 64 КиБ.
- CRL: помощник копирует CRL после `gen-crl` (init/revoke), при `server/configure` и при каждом `start|restart`; для `crl-verify` разрешён только путь `/etc/openvpn/crl.pem`; ошибка публикации при отзыве возвращается ошибкой API.
- Проверено: 17 инъекций директив, отсутствие `user nobody`, cert вне PKI, CR, симлинк — всё отклонено, боевой конфиг не менялся; `doas` отказывает на любую иную команду; `ovpmon` не читает `/etc/shadow`, `/root`, `/etc/hysteria/*.yaml`, `/etc/ovpmon/env`, не пишет в `/etc/openvpn`, `/etc/init.d`, `authorized_keys`, код, не запускает `iptables`; API (мониторинг, конфиг, `server/configure`, создание/скачивание/отзыв профиля, рестарт OpenVPN) работает; CRL проверен на отдельном экземпляре OpenVPN от `nobody` (валидный клиент подключается, отозванный получает `certificate revoked`).
- Артефакт и откат: `IMPLEMENTATION-02-privilege-separation.md`.
## 9. Смена имени администратора
`POST /api/auth/change-username` (JWT + текущий пароль + OTP при 2FA; маска `^[A-Za-z][A-Za-z0-9_.-]{2,31}$`, запрещены `admin, administrator, root, user, test, guest`, уникальность без учёта регистра → 409, неверный пароль/OTP учитываются rate-limit); кнопка «Change Username» в Account; в 2FA-URI подставляется реальное имя; `ensure_default_admin` больше не создаёт `admin/password` (только из `OVPMON_INITIAL_ADMIN_*`); баг UI «в шапке всегда Admin» исправлен (синхронизация с `/user/me`, событие `ovpmon-user-changed`). JWT хранит `user_id`, поэтому смена имени сессии не рвёт. Бэкап БД: `/root/openvpn_monitor.db.bak-2026-09-30`.
Ручной тест владельца в UI (смена пароля, включение 2FA) пройден.
## 10. Оценка вероятности получения root (актуальная)
**Без учётных данных, извне — низкая.** SSH только по ключам + fail2ban; панель за TLS, rate-limit и fail2ban; все API за JWT; OpenVPN — mTLS + `tls-auth`; Hysteria — пароль на пользователя; служебные порты на loopback. Остаточный риск: неизвестные уязвимости OpenVPN/nginx/sshd/hysteria/ядра и отставание пакетов (актуальность индекса `apk` и ядра не проверялась).
**С учётными данными панели (пароль + 2FA / токен).** Раньше это давало root (через инъекцию в `server.conf` от root-процесса). Теперь: валидация настроек (слои A–C), API работает от `ovpmon`, а помощник не пропустит опасные директивы. Остаточные пути:
1. уязвимость в `ovpmon-helper`, `doas` или ядре;
2. включение скриптов подключения (исполняются от `nobody`, берутся только из root-каталога `/etc/openvpn/scripts/`);
3. `ovpmon` владеет PKI, включая ключ CA: компрометация API позволяет выпускать клиентские сертификаты (доступ к VPN), но не даёт root. Проверки путей PKI в помощнике выполняются на момент установки (теоретическое окно TOCTOU с подменой файла на симлинк до старта OpenVPN — влияет на работоспособность, не на выполнение кода).
Итог: цепочка «интернет → root» сводится к неизвестной уязвимости (0-day) в привилегированных компонентах; компрометация админа панели больше не эквивалентна root.
## 11. Репозиторий, резервные копии, откат
Репозиторий приложения на узле (`/opt/OpenVPN-Monitoring-Simple`, ветка `main`), коммиты **не запушены** (автор `iclaoudezin`, пуш за пользователем):
| Коммит | Содержание |
|---|---|
| `11c1b63` | смена имени, 2FA-исправления, валидация `username`, CORS, UI |
| `9b2882d` | README и документация (Docker/native, Changes) |
| `5de0501` | docker-compose: обязательный `JWT_SECRET`, seed админа, порты |
| `05f44b9` | валидация настроек Profiler |
| `6f9e800` | API не от root + root-помощник |
| `9ffdbfa` | публикация CRL для `crl_verify` |
| `e1146ed` | README приложения: раздел Security defaults, ссылки на `privilege-separation/` |
Не вошли в коммиты: `APP_CORE/config.ini` и `APP_UI/package-lock.json` (побочные правки приложения/npm), `venv/`, `easy-rsa/` и `client-config/` (приватные ключи — в `.gitignore` не добавлены, добавить отдельным коммитом).
Бэкапы на узле: `/root/backup-p2-2026-09-30-1229.tar` (`/etc/openvpn`, `/var/lib/ovpmon`, easy-rsa, init-скрипты, doas, код), `/root/openvpn_monitor.db.bak-2026-09-30`, `/root/ovpmon.conf.bak`, `/root/sshd_config.bak`, `/root/app-bak/` (файлы приложения по этапам, `README.md.orig`, `p1/ p2/ p3/`), `/var/www/ovpmon.bak`. Откат — в `IMPLEMENTATION-02-privilege-separation.md` и `DOCS/Changes/*`.
## 12. Открытые вопросы и рекомендации
- Пуш коммитов (учётные данные внешнего репозитория у пользователя).
- Тест перезагрузки ENTRY после доработок **пройден** (2026-09-30): снимок состояния до/после идентичен, все сервисы, правила выхода, hardening и панель поднялись сами; VPN-клиент переподключился сам через ~3,5 мин (ping-restart UDP-клиента), трафик идёт через `hytun`, утечек нет. Подробности — `REBOOT-TEST.md`, раздел «ENTRY reboot after the OpenVPN Monitor deployment». Нюанс: права `root:ovpmon 640` на `openvpn-status.log` сохраняются, пока файл на диске; при его удалении OpenVPN создаст файл с 600 до ближайшего `start|restart` через помощник.
- Самоподписанный сертификат: сверять отпечаток; при появлении домена — Let's Encrypt.
- Ограничить панель по IP или пускать через VPN; сократить срок жизни JWT (сейчас 8 ч) и отзывать токены при смене пароля/имени.
- Включить `crl_verify` в настройках, если нужна проверка отзыва (публикация CRL уже работает).
- Создать `/etc/openvpn/scripts/` (`root:root 755`) перед использованием скриптов подключения.
- В шаблоне клиентского `.ovpn` есть Windows-опция `windows-driver` — не подходит Linux-клиентам; при необходимости вынести в условие (шаблон не менялся).
- Регулярно `apk upgrade`, следить за advisory OpenVPN/nginx/OpenSSH/hysteria.
- В списке профилей остались записи `revoked` от тестов (`ok-user1`, `p2test-*`, `crl-e2e-*`).
## Журнал изменений (2026-09-30)
1. Развёртывание приложения без контейнеров (OpenRC, nginx :8088), инициализация PKI (фикс каталога `easy-rsa`).
2. Выход клиентов OpenVPN через `hytun` → hel (`ovpn-hytun`), сквозной тест пройден.
3. HTTPS на 8088, rate-limit, заголовки.
4. Аудит безопасности; SSH key-only, fail2ban, валидация `username`, CORS.
5. Смена имени администратора (данные + API + UI + без дефолтной учётки); исправление обхода 2FA и лога секретов; баг имени в шапке.
6. Документация и коммиты (README, Docker/native, Changes), актуализация `docker-compose.yml`.
7. Валидация настроек Profiler (п.1).
8. API не от root, root-помощник (п.2), публикация CRL.
9. Актуализация SUMMARY и README.
10. Тест перезагрузки ENTRY: пройден (`REBOOT-TEST.md`).
+1 -1
View File
@@ -19,7 +19,7 @@ A modern, Python-based REST API for managing OpenVPN servers, Public Key Infrast
### Usage
Once the server is running (see [Deployment Guide](../General/Deployment.md)), the full interactive API documentation is available at:
Once the server is running (see [Deployment Guide](../Deployment/README.md)), the full interactive API documentation is available at:
* **Swagger UI**: `http://<your-server>:8000/docs`
* **ReDoc**: `http://<your-server>:8000/redoc`
+37
View File
@@ -0,0 +1,37 @@
# Documentation
Three levels: **general information** about the project, **installation methods**, and **details of each method**. Start with the first row that matches your goal.
## I want to ...
| Goal | Read |
|---|---|
| understand what this is | [General: Overview](General/Overview.md) |
| get a working environment fast | [Installation](Deployment/README.md) (choose a method), then [First steps](Deployment/First_Steps.md) |
| install with Docker | [Containers](Deployment/Containers/README.md) |
| install on Alpine, Debian or Ubuntu without containers | [System services](Deployment/System_Services/README.md) |
| update, back up, restore or roll back | containers: [Operations](Deployment/Containers/Operations.md) · system services: [Operations](Deployment/System_Services/Operations.md) |
| change settings (environment, secrets, ports) | [General: Configuration](General/Configuration.md) |
| fix a problem | containers: [Troubleshooting](Deployment/Containers/Troubleshooting.md) · system services: [Troubleshooting](Deployment/System_Services/Troubleshooting.md) |
| set up NAT, TLS, the web UI build | [Firewall](Deployment/System_Services/Firewall.md) · [Nginx](Deployment/System_Services/Nginx_Configuration.md) · [Web UI](Deployment/System_Services/Web_UI.md) |
| understand the security model | [Security architecture](General/Security_Architecture.md) · [Authentication](Core_Monitoring/Authentication.md) |
| call the APIs | [Monitoring API](Core_Monitoring/API_Reference.md) · [Profiler API](Profiler_Management/API_Reference.md) |
| see what changed and why | [Changes](Changes/README.md) |
| see the code review (state of the code, risks, recommendations) | [code_review/](code_review/2026-10-05_1607Z_Codebase_Analysis.md) (Russian, time-stamped) |
## Map
```
DOCS/
General/ 1. general information: overview, configuration, security, database migrations
Deployment/ 2. installation methods: choice, first steps
Containers/ 3a. details: Docker, variants A and B
System_Services/ 3b. details: Alpine (OpenRC), Debian and Ubuntu (systemd)
Core_Monitoring/ Monitoring API (APP_CORE): API, authentication, data architecture
Profiler_Management/ Profiler API (APP_PROFILER)
UI/ Web UI (APP_UI)
Changes/ records of changes: plans and results
code_review/ time-stamped analyses of the code base
```
`General/systemd/`, `General/openrc/` and `General/privilege-separation/` hold the service definitions and the root helper that the install scripts copy; they are files, not documentation, and stay where the scripts expect them.
+1 -1
View File
@@ -32,4 +32,4 @@ The UI is served by Nginx in production and proxies API requests to:
- `/api/v1/` -> **APP_CORE** (Flask, Port 5000)
- `/profiles-api/` -> **APP_PROFILER** (FastAPI, Port 8000)
See [Deployment Guide](../General/Deployment.md) for Nginx configuration details.
See [Deployment Guide](../Deployment/README.md) for Nginx configuration details.
@@ -0,0 +1,188 @@
# Комплексный анализ кодовой базы
| | |
|---|---|
| Отметка времени | 2026-10-05 16:07 (UTC) |
| Состояние кода | ветка `main`, коммит `f95a0b6` (+ незакоммиченная реорганизация документации) |
| Граф знаний | `graphify-out/graph.json`: 1453 узла, 3060 рёбер, 75 сообществ (95 % рёбер EXTRACTED, 5 % INFERRED); сборка от 2026-10-05 |
| Метод | граф + чтение кода + `pyflakes`, `bandit`, `shellcheck`, `bash -n`, запуск тестов (план: [2026-10-05_Code_Review_PLAN.md](../Changes/2026-10-05_Code_Review_PLAN.md)) |
Статусы находок: **[код]** подтверждено чтением кода, **[инструмент]** воспроизведено инструментом, **[не воспроизведено]** вывод из кода, на живой системе не проверялся.
## 1. Вывод
Кодовая база небольшая (около 5,5 тыс. строк Python, 3,7 тыс. строк Vue/JS, 4,7 тыс. строк shell) и в целом дисциплинированная: защита в глубину вокруг генерации конфигурации OpenVPN, версионные миграции БД, установщики с проверенным бэкапом и откатом. Слабые места лежат в трёх зонах: **аутентификация и сессии** (защита от перебора, срок жизни токенов), **консистентность отзыва сертификатов и учёта трафика**, **эксплуатационные расхождения между способами установки** (в контейнерах варианта B API работает на dev-серверах). Автоматической проверки качества нет: нет CI, два теста из двадцати падают, самый критичный по безопасности код (allowlist помощника) не покрыт тестами.
### Главные риски (по приоритету)
| # | Находка | Серьёзность |
|---|---|---|
| 1 | SEC-01 Подпись JWT по умолчанию `ovpmon-secret-change-me`: при незаданном ключе токены можно подделать | Высокая |
| 2 | SEC-02 Нет ограничения перебора кода 2FA, счётчик попыток сбрасывается после верного пароля | Высокая |
| 3 | BUG-01 Отзыв сертификата может застрять в полуготовом состоянии, активная сессия отозванного клиента не разрывается | Высокая |
| 4 | SEC-03 Защита от перебора считает все запросы одним адресом: любой может заблокировать вход всем | Средняя |
| 5 | SEC-06 Контейнеры варианта B: Flask dev-сервер и `uvicorn reload=True` на `0.0.0.0` | Средняя |
### Сильные стороны
- Три слоя проверки настроек (схемы Pydantic, `check_script`, рендер) и root-помощник со строгим allowlist директив, `O_NOFOLLOW`, фиксированным argv и шестью правилами `doas`.
- Миграции БД: бэкап и проверка целостности до и после, защита от понижения версии. Тесты миграций есть у обоих компонентов.
- Установщики: блокировки, проверенные бэкапы, автоматический откат, отдельный шаг миграции. `shellcheck`: ни одной ошибки, `bash -n` проходит на всех скриптах.
- SQL: все 12 срабатываний `bandit` B608 проверены вручную, в строки подставляются только константы и значения из белого списка, пользовательские значения идут параметрами.
- UI: `v-html` используется только со строковыми константами (`Certificates.vue:193-207`), таймеры очищаются в `onUnmounted`, CORS по умолчанию закрыт.
## 2. Архитектура по графу
### 2.1 Размеры и состав
| Область | Файлов кода | Строк | Узлов графа |
|---|---|---|---|
| `APP_CORE` (API, сборщик, миграции, БД) | 6 | 2 557 | 151 |
| `APP_PROFILER` (FastAPI, PKI, процесс, генератор) | 32 | 2 968 | 259 |
| `APP_UI/src` (Vue 3) | 23 | 3 665 | 327 |
| `deploy/` (shell, nginx, supervisord; без сборки UI) | 17 | 4 713 | 277 |
| `DOCS/` (документы Markdown) | 50 | 3 031 | 330 |
| Root-помощник `ovpmon-helper` | 1 | 397 | (в `DOCS/General/privilege-separation/`) |
Связи графа: 963 `calls`, 643 `references`, 495 `contains`, 245 `defines`, 421 импорта. Компонент образует связный граф из 1369 узлов, ещё 10 малых компонент.
### 2.2 Что показывает граф
- **Центр тяжести проекта: скрипты развёртывания.** Самые связные узлы: `main()` (61 ребро), `install.sh` (54), `die()` (44), `log()` (41). Приложение (Python и Vue) менее связно, чем его собственная установка. Это главный центр сопровождения: 4,7 тыс. строк sh против 5,5 тыс. строк Python.
- **Сообщества-хабы:** «Docker Install & Backup» (85 узлов, когезия 0,07), «Native Lib & Doas» (35), «Core DatabaseManager» (68), «Migrate CLI & Migrations» (68). Низкая когезия «Docker Install & Backup» означает набор слабо связанных утилит одного файла `deploy/docker/lib.sh`, а не единый модуль.
- **Мосты между областями:** `ProfileDetailsModal.vue` (посредничество 0,53, связывает UI, API профилей и документы), «Versioned additive migration engine» (0,42, документация миграций и обоих компонентов), `native/lib.sh` и `native/install.sh` (0,25-0,26).
- **Границы компонентов (UI ↔ API):** 15 рёбер между `APP_CORE` и `APP_UI`: контракт на пути `/api/v1/*`; импортов между `APP_CORE` и `APP_PROFILER` нет (общие только секрет JWT и формат токена; пять рёбер между ними в графе ложные: стандартный `logging` разрешился в `APP_PROFILER/utils/logging.py` из-за совпадения имени). Это хорошая развязка, но контракты нигде не зафиксированы схемой (OpenAPI у Flask-части отсутствует).
- **Слабосвязанные узлы:** 268, в основном документы и конфигурация. Изолирован один узел из 1453.
- **Дубли, видимые в графе:** одноимённые узлы `main()`, `install.sh`, `log()`, `die()` в `deploy/docker` и `deploy/native` (см. ARCH-01, ARCH-03).
### 2.3 Потоки и границы доверия
```
Браузер --> nginx --> Monitoring API (Flask, :5001) --> monitoring DB <-- Gatherer <-- openvpn-status.log
\-> Profiler API (FastAPI, :8000) --> profiler DB, PKI (easy-rsa), .ovpn
|-- doas --> ovpmon-helper (root): server.conf, CRL, сервис OpenVPN
Общий секрет JWT (HS256) у обоих API.
```
Границы доверия: браузер ↔ nginx (TLS только в нативной установке), nginx ↔ API (loopback или сеть контейнеров), профайлер ↔ root-помощник (`doas`, шесть фиксированных команд). PKI вместе с закрытым ключом CA принадлежит пользователю `ovpmon`: компрометация профайлера позволяет выпускать сертификаты клиентов, но не получить root (принятый и задокументированный риск).
## 3. Находки
Шкала: **Высокая** (эксплуатируема или ломает данные при штатной работе), **Средняя** (проявляется при определённых условиях), **Низкая** (гигиена, мелкие дефекты), **Инфо** (наблюдение).
### 3.1 Безопасность
| ID | Сер. | Находка | Где | Статус |
|---|---|---|---|---|
| SEC-01 | Высокая | Ключ JWT по умолчанию. Core берёт `ovpmon-secret-change-me` без предупреждения, Profiler только печатает предупреждение и продолжает. Тот же текст лежит в поставляемых `config.ini`. Установщики и compose задают случайный ключ, поэтому риск остаётся для ручного и dev-запуска, но при ошибке конфигурации система молча работает с публично известным ключом (подделка токена администратора) | `APP_CORE/openvpn_api_v3.py:53`, `APP_PROFILER/utils/auth.py:12-14`, оба `config.ini` | [код] |
| SEC-02 | Высокая | Нет ограничения перебора 2FA. `/api/auth/verify-2fa` не считает неудачные попытки; временный токен живёт 5 минут, его можно получать снова, потому что после верного пароля счётчик попыток удаляется. Нужен верный пароль, но 2FA как второй фактор перестаёт защищать. В нативной установке частично сдерживает nginx (`limit_req` на входе), в контейнерах нет | `openvpn_api_v3.py:656`, `:684-718` | [код] |
| SEC-03 | Средняя | Защита от перебора привязана к `request.remote_addr`. За nginx это всегда адрес прокси (127.0.0.1 или контейнер), `ProxyFix` не настроен: 5 неверных входов от любого человека блокируют вход всем на 15 минут (отказ в доступе), а персональной защиты нет | `openvpn_api_v3.py:645`, `:91-112` | [код], [не воспроизведено] |
| SEC-04 | Средняя | Токены без отзыва: срок 8 часов, в полезной нагрузке только `user_id`. Смена пароля и имени, отключение 2FA их не аннулируют, удалённый пользователь проходит `token_required`. `disable-2fa` не требует пароля и кода (в отличие от `change-username`) | `openvpn_api_v3.py:611-634`, `:792-810` | [код] |
| SEC-05 | Средняя | Общий симметричный секрет у двух API: компрометация профайлера (у него ключ CA и вызовы процессов) даёт и токены администратора для Core API | оба `utils/auth.py` и `token_required` | [код], архитектурное |
| SEC-06 | Средняя | Вариант B контейнеров запускает dev-серверы: API `CMD python openvpn_api_v3.py` (`app.run`), профайлер `python main.py` с `uvicorn.run(host="0.0.0.0", reload=True)`. Вариант A и нативная установка используют gunicorn и uvicorn без reload | `APP_CORE/Dockerfile.api:23`, `APP_PROFILER/main.py:48`, `APP_PROFILER/entrypoint.sh` | [код] |
| SEC-07 | Низкая | Внутренние сообщения уходят клиенту: `str(e)` в ответах 500 Core API (8 мест), stderr easy-rsa и сырой вывод помощника в ответах профайлера | `openvpn_api_v3.py:379,958,972,1043,1055,1064,1086,1101`, `routers/profiles.py:98,111,147` | [код] |
| SEC-08 | Низкая | Нет политики паролей: любой непустой пароль принимается (при смене и при первичном администраторе). Имя пользователя проверяется, пароль нет | `openvpn_api_v3.py:812-845` | [код] |
| SEC-09 | Низкая | Контейнерный nginx без TLS, без заголовков безопасности и без `limit_req` (в нативном шаблоне они есть). CSP нет нигде. Токен хранится в `localStorage` (виден любому XSS; текущих векторов XSS не найдено) | `APP_UI/default.conf.template`, `deploy/native/nginx/ovpmon.conf.template:29-34` | [код] |
| SEC-10 | Низкая | Контейнеры API и профайлера работают от root (нет `USER`); профайлеру нужны `NET_ADMIN` и TUN | `APP_CORE/Dockerfile.api`, `APP_PROFILER/Dockerfile`, `docker-compose.yml:96-120` | [код] |
| SEC-11 | Низкая | easy-rsa получает полное окружение процесса, включая `OVPMON_API_SECRET_KEY`. Публичный IP определяется запросами к трём сторонним сервисам, ответ не проверяется как IP | `services/pki.py:83`, `services/utils.py` | [код] |
| SEC-12 | Инфо | Помощник: allowlist и проверки путей выполнены грамотно. Остаточные замечания: интерфейс `management` без пароля (только loopback), ошибка публикации CRL при старте глушится (`except Exception: pass`), файлы PKI принадлежат `ovpmon` и проверяются на момент установки (окно подмены между проверкой и запуском OpenVPN ограничено расположением в root-владении `/etc/openvpn`) | `DOCS/General/privilege-separation/ovpmon-helper:366`, `templates/server.conf.j2:108` | [код] |
Результаты `bandit` по `APP_CORE` и `APP_PROFILER` (30 срабатываний): 1 высокое (B701, `autoescape=False` в Jinja2: шаблоны конфигураций OpenVPN, не HTML, ложное срабатывание при нынешней проверке значений), 15 средних (12 × B608 проверены вручную, 3 × B104 привязка к `0.0.0.0` в dev-блоках запуска), 14 низких (в основном `try/except/pass` и вызовы `subprocess` с фиксированным argv).
### 3.2 Корректность и надёжность
| ID | Сер. | Находка | Где | Статус |
|---|---|---|---|---|
| BUG-01 | Высокая | Отзыв сертификата. `revoke_client` отзывает сертификат и генерирует CRL, затем при сбое публикации CRL бросает исключение; роутер отвечает 500 и **не** выставляет `status = "revoked"`. Повторная попытка падает на «уже отозван», довести операцию невозможно без ручной правки. Кроме того, активная сессия отозванного клиента не разрывается: отзыв действует с переподключения | `routers/profiles.py:138-152`, `services/pki.py:307-314` | [код] |
| BUG-02 | Средняя | Сборщик: основной цикл завершает демон при любом исключении вне внутренних `try` (`except Exception` вокруг `while True`), обработчика `SIGTERM` нет. Файл статуса читается без проверки завершающей строки `END`: при чтении в момент перезаписи клиенты «исчезают», кэш сессий очищается, следующий тик считает их новыми (возможен двойной учёт или потеря байт) | `openvpn_gatherer_v3.py:604-618`, `:263-312` | [код], гонка [не воспроизведено] |
| BUG-03 | Средняя | Эвристика недоучёта: сессия, впервые замеченная с объёмом ≥ 10 МБ, считается продолжающейся и даёт нулевой прирост. 10 МБ за 10-секундный интервал это около 8 Мбит/с, что легко достижимо для новой сессии | `openvpn_gatherer_v3.py:377-386` | [код] |
| BUG-04 | Средняя | Невалидный профиль «успешно» создаётся: `read_file` подставляет текст `Error: <путь> not found` в `.ovpn`, а `get_public_ip` при недоступности сервисов молча возвращает `127.0.0.1`. Профиль сохраняется как `active` | `services/generator.py:90-96,108`, `services/utils.py:28-29` | [код] |
| BUG-05 | Средняя | Контейнеры: OpenVPN запускается только по запросу из UI, не наблюдается супервизором и не стартует после перезапуска контейнера или обновления (задокументировано). Нативная установка включает службу, но тоже стартует её только при наличии `server.conf` | `services/process.py:97-143`, [Containers: Troubleshooting](../Deployment/Containers/Troubleshooting.md) | [код] |
| BUG-06 | Низкая | Время: смесь наивных `datetime.utcnow()` (устарело в Python 3.12) и локального `datetime.now()`; отсечка хранения считается в локальном времени, данные пишутся в UTC, на хосте не в UTC хранение смещено на часовой пояс. `range=999999999d` даёт `OverflowError` и 500. Устаревшие комментарии (в коде 30 секунд, в комментарии «2 минуты»), в `config` сборщика порт API по умолчанию 5000 вместо 5001 | `openvpn_gatherer_v3.py:246`, `openvpn_api_v3.py:144-170,994-999` | [код] |
| BUG-07 | Низкая | GET с записью в БД: `GET /profiles` синхронизирует срок действия и флаги и делает `commit`, `GET /config` создаёт строки настроек; при параллельных запросах возможна гонка | `routers/profiles.py:17-67`, `services/config.py:5-13` | [код] |
| BUG-08 | Низкая | `get_process_stats` блокирует поток на 1 с (`cpu_percent(interval=1.0)`) на каждый опрос UI (раз в 5 с) и находит **любой** процесс с именем `openvpn` (в том числе клиентский) | `services/process.py:233`, `ServerManagement.vue:159` | [код] |
| BUG-09 | Низкая | `OpenVPNAPI()` создаётся при импорте модуля (`:607`): инициализация БД и создание первого администратора выполняются на каждый воркер gunicorn (`-w 2`), гонка сглажена только уникальностью имени | `openvpn_api_v3.py:607`, `:70-89` | [код] |
### 3.3 Сопровождаемость и архитектура
| ID | Сер. | Находка | Где |
|---|---|---|---|
| ARCH-01 | Средняя | Дубль движка миграций: около 350 строк (`_run_locked`, `_backup`, `_integrity_problems`, статусы, блокировки) совпадают в двух модулях, различаются только шаги конкретной БД (180 из 450 строк diff). Так же дублируются `migrate.py`, тесты, чтение конфигурации (3 реализации `get_config_value`) и проверка JWT. Каждое исправление применяется дважды | `APP_CORE/migrations.py`, `APP_PROFILER/migrations.py`, `*/migrate.py`, `*/test_migrations.py` |
| ARCH-02 | Средняя | `openvpn_api_v3.py` (1113 строк) смешивает маршруты, аутентификацию, SQL и бизнес-логику. Самые тяжёлые функции: `update_client_status_and_bytes` (212 строк, 24 ветвления), `get_client_history` (192 строки, 33 ветвления), `get_analytics_data` (153), `control_service` (111 строк, три режима выполнения). Шесть функций длиннее 80 строк из 187 | `APP_CORE/openvpn_api_v3.py`, `openvpn_gatherer_v3.py`, `APP_PROFILER/services/process.py` |
| ARCH-03 | Средняя | Скрипты развёртывания: 21 одноимённая функция в `docker/lib.sh` и `native/lib.sh` (`die`, `log`, `warn`, `confirm`, `acquire_lock`, `make_backup`, `verify_backup`, `prune_backups`, `latest_backup`...); `native/update.sh: main()` 302 строки. Это крупнейший центр сопровождения (см. 2.2). Замечания `shellcheck` (139 на уровне warning): 99 × SC3043 (`local` в `sh`, работает в ash и dash), 34 × SC2034 (переменные, используемые вызывающим скриптом), 3 × SC2254 в `firewall.sh:209,225,234` (раскрытие в `case`), 2 × SC2010 (`ls \| grep`), 1 × SC2209 | `deploy/docker/lib.sh`, `deploy/native/lib.sh`, `deploy/native/update.sh` |
| ARCH-04 | Низкая | Гигиена репозитория: в git лежит `APP_UI/src/views/Login.vue.bak` (251 строка), закоммичена сборка `deploy/ui-dist/` (минифицированный JS занимал 60 из 143 сообществ графа до исключения; защита от устаревания есть: хеш источника), остались предмиграционные скрипты `add_columns.py`, `scripts/add_*.py`. `pyflakes`: 18 замечаний (неиспользуемые импорты, `os` определён дважды, неиспользуемые переменные). Комментарии смешаны русским и английским, остались пустые блоки-заглушки («Оставлен без изменений») | см. столбец |
| ARCH-05 | Средняя | Зависимости: у профайлера версии не зафиксированы (`fastapi`, `uvicorn`, `sqlalchemy`, `psutil`, `jinja2`, `requests` без ограничений), у Core `>=`; lock-файла для Python нет (для Node есть `package-lock.json`); базовые образы по плавающему тегу `python:3.12-alpine`; проверки зависимостей на уязвимости нет | `APP_PROFILER/requirements.txt`, `APP_CORE/requirements.txt`, `Dockerfile*` |
| ARCH-06 | Средняя | Производительность БД: нет составного индекса `usage_history(client_id, timestamp)` (есть только по `timestamp`), история клиента сканирует диапазон времени всех клиентов; `get_client_stats` загружает статистику всех клиентов ради одного; соединения SQLite без WAL и `busy_timeout`, при этом три писателя и читатели; на каждый цикл сборщика открывается 3 и более соединений в отдельных транзакциях (учёт и история не атомарны) | `APP_CORE/db.py:26-28`, `openvpn_api_v3.py:1002`, `migrations.py:402` |
| ARCH-07 | Низкая | Наблюдаемость: профайлер пишет через `print` (`utils/auth.py`, печатает и первые 20 символов заголовка `Authorization` при ошибке), тесты создают `profiler.log` в каталоге исходников; метрик нет; `/` профайлера отдаёт приветствие вместо состояния | `APP_PROFILER/utils/auth.py:14-23,35`, `utils/logging.py` |
### 3.4 Тесты и контроль качества
| Область | Состояние |
|---|---|
| Набор тестов | 20 тестов: 7 (Core, миграции) и 13 (профайлер). Запуск: Core 7 из 7 успешно, профайлер 11 из 13 |
| Падающие тесты | `test_server_process.py::test_get_stats` и `::test_control_invalid` получают 404: они обращаются к `/server/process/...` без префикса `/api` и без токена (устарели после появления префикса и обязательной аутентификации). В `__main__`-блоке сбои глушатся `except` |
| Не покрыто | маршруты Core API (вход, 2FA, ограничение попыток, история и аналитика), разбор статуса и расчёт приращений в сборщике, **allowlist `ovpmon-helper` (`validate`, `check_line`)**: `test_helper_config.py` проверяет только чтение `helper.conf`, генератор конфигурации, shell-скрипты (проверялись ручными прогонами по записям об изменениях) |
| UI | тестов, линтера и проверки типов нет |
| CI | конфигурации CI, `Makefile`, `pyproject.toml`, `pytest.ini` нет; проверки выполняются вручную |
| Правило проекта | «минимальное количество тестов»: оправданно, но для кода безопасности (allowlist помощника, аутентификация) нужен минимум точечных тестов (см. рекомендации) |
## 4. Рекомендации и порядок работ
Оценка трудоёмкости: **S** до полудня, **M** до двух дней, **L** больше.
### P0: сделать сразу
| # | Действие | Закрывает | Трудоёмкость |
|---|---|---|---|
| 1 | Отказ запуска при ключе JWT по умолчанию, пустом или короче 32 символов (Core и профайлер); убрать значение из `config.ini` | SEC-01 | S |
| 2 | Ограничение попыток 2FA (счётчик на пользователя или токен, блокировка), не сбрасывать счётчик на этапе «пароль верен, ждём 2FA» | SEC-02 | S |
| 3 | Корректный адрес клиента: `ProxyFix` (доверять одному прокси) или ключ «пользователь + адрес» | SEC-03 | S |
| 4 | Отзыв: помечать профиль отозванным сразу после `revoke`, публикацию CRL повторять отдельно и идемпотентно; обработать «уже отозван»; опционально разрыв сессии через management-интерфейс | BUG-01 | M |
| 5 | Контейнеры варианта B: gunicorn для Core, uvicorn без `reload` и на `127.0.0.1`/сети контейнеров для профайлера | SEC-06 | S |
| 6 | Починить два устаревших теста (префикс `/api`, токен); не писать лог в каталог исходников | раздел 3.4 | S |
### P1: ближайший цикл
| # | Действие | Закрывает | Трудоёмкость |
|---|---|---|---|
| 7 | Токены: версия сессии (`token_version` или время смены пароля) в JWT, повторное подтверждение паролем для отключения 2FA, минимальная политика паролей | SEC-04, SEC-08 | M |
| 8 | Сборщик: цикл не умирает от исключения, обработчик `SIGTERM`, пропуск тика при файле статуса без `END`, пересмотр порога 10 МБ (хранить базовую линию в БД) | BUG-02, BUG-03 | M |
| 9 | Генератор: падать, если файл или публичный IP не получены; проверять IP как адрес | BUG-04, SEC-11 | S |
| 10 | Тесты для `ovpmon-helper.validate` (допустимые, запрещённые и граничные директивы), для входа и 2FA, для разбора статуса | раздел 3.4 | M |
| 11 | Не возвращать `str(e)` клиенту; единый обработчик ошибок и идентификатор корреляции в логе | SEC-07 | S |
| 12 | Зафиксировать версии Python-зависимостей (lock-файл), проверку зависимостей (`pip-audit`, `npm audit`) и базовые образы по digest | ARCH-05 | M |
| 13 | CI: `pytest` обоих компонентов, `bash -n` и `shellcheck`, `check-ui.sh`, сборка образов | раздел 3.4 | M |
| 14 | Контейнерный nginx: заголовки безопасности, `limit_req` на вход, `client_max_body_size` (как в нативном шаблоне) | SEC-09 | S |
| 15 | Индекс `usage_history(client_id, timestamp)`, WAL и `busy_timeout`, один клиент вместо выборки всех | ARCH-06 | S |
### P2: плановый рефакторинг
| # | Действие | Закрывает | Трудоёмкость |
|---|---|---|---|
| 16 | Вынести движок миграций в общий модуль (учесть, что образы собираются из разных контекстов; вариант A собирает из корня репозитория) | ARCH-01 | L |
| 17 | Разбить `openvpn_api_v3.py` на blueprint-ы и слой доступа к данным; `flask.g` для пользователя вместо повторного разбора заголовка; убрать побочные эффекты при импорте | ARCH-02, BUG-09 | L |
| 18 | Общая библиотека shell-функций для `docker/` и `native/` либо чёткая граница между ними; разбить `update.sh: main()` | ARCH-03 | L |
| 19 | Удалить `Login.vue.bak`, предмиграционные скрипты, неиспользуемые импорты, унифицировать язык комментариев; добавить `ruff` и `eslint` | ARCH-04, ARCH-07 | S-M |
| 20 | Время только в UTC с часовым поясом (`datetime.now(timezone.utc)`), ограничение `range`, переход с `print` на `logging` | BUG-06, ARCH-07 | M |
| 21 | Рассмотреть раздельные секреты или асимметричную подпись для двух API, пользователя без root в контейнерах | SEC-05, SEC-10 | M-L |
## 5. Что не проверялось
- Живое поведение: гонка чтения файла статуса (BUG-02), блокировка входа за прокси (SEC-03) выведены из кода, не воспроизведены.
- Уязвимости зависимостей (`pip-audit`, `npm audit`) не запускались; версии Python-зависимостей не зафиксированы, поэтому оценка зависела бы от момента сборки.
- Нативные установщики и обновление на Debian и Ubuntu, а также `firewall.sh` на systemd-хостах не выполнялись в этой сессии (в записях об изменениях они отмечены как непроверенные на живых системах).
- Сторонний код `node_modules`, сборка `deploy/ui-dist/assets` и содержимое образов Docker не анализировались.
- Нагрузочное тестирование и профилирование не проводились: выводы о производительности (ARCH-06) основаны на структуре запросов и индексов.
## 6. Воспроизведение
```sh
python3 -m venv /tmp/av && /tmp/av/bin/pip install pyflakes bandit shellcheck-py pytest flask flask-cors pyjwt pyotp bcrypt qrcode fastapi uvicorn sqlalchemy psutil jinja2 requests httpx python-multipart
/tmp/av/bin/pyflakes APP_CORE APP_PROFILER
/tmp/av/bin/bandit -r APP_CORE APP_PROFILER -x '*/test_*,*/venv/*'
/tmp/av/bin/shellcheck -S warning deploy/native/*.sh deploy/docker/*.sh deploy/allinone/entrypoint.sh
(cd APP_CORE && /tmp/av/bin/python -m pytest -q test_migrations.py)
(cd APP_PROFILER && /tmp/av/bin/python -m pytest -q)
```
Граф: `graphify query "<вопрос>"` по `graphify-out/graph.json`, отчёт `graphify-out/GRAPH_REPORT.md`.