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:
1 parent
f95a0b63e6
commit
ad6995bb63
85 files changed
+2723
-1198
No files matched your search
@@ -0,0 +1,5 @@
|
|||||||
|
# Закоммиченная сборка UI (минифицированный JS) - шум для графа
|
||||||
|
deploy/ui-dist/assets/
|
||||||
|
|
||||||
|
# Site-specific records of one deployment (Timeweb host, Hysteria2 chain): not part of the product documentation
|
||||||
|
DEPLOYMENTS/
|
||||||
@@ -26,6 +26,9 @@ python3 -m venv venv
|
|||||||
source venv/bin/activate
|
source venv/bin/activate
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# JWT key (required, no built-in default; at least 32 characters). Give the same value to APP_PROFILER
|
||||||
|
export OVPMON_API_SECRET_KEY=$(openssl rand -hex 32)
|
||||||
|
|
||||||
# Run API
|
# Run API
|
||||||
python3 openvpn_api_v3.py
|
python3 openvpn_api_v3.py
|
||||||
|
|
||||||
|
|||||||
+9
-1
@@ -2,12 +2,20 @@
|
|||||||
host = 0.0.0.0
|
host = 0.0.0.0
|
||||||
port = 5001
|
port = 5001
|
||||||
debug = false
|
debug = false
|
||||||
secret_key = ovpmon-secret-change-me
|
# Set OVPMON_API_SECRET_KEY or this value; at least 32 characters, random (openssl rand -hex 32). There is no built-in default.
|
||||||
|
secret_key =
|
||||||
|
|
||||||
[openvpn_monitor]
|
[openvpn_monitor]
|
||||||
log_path = /var/log/openvpn/openvpn-status.log
|
log_path = /var/log/openvpn/openvpn-status.log
|
||||||
db_path = openvpn_monitor.db
|
db_path = openvpn_monitor.db
|
||||||
check_interval = 10
|
check_interval = 10
|
||||||
|
# Optional gatherer reliability settings (defaults shown)
|
||||||
|
# ticks before a session missing from the status file is forgotten
|
||||||
|
session_grace_ticks = 3
|
||||||
|
# status file older than this (TIME line) means OpenVPN is stopped, no clients
|
||||||
|
status_stale_seconds = 60
|
||||||
|
# consecutive skipped ticks (bad/missing status file) before logging at ERROR
|
||||||
|
status_invalid_max = 6
|
||||||
|
|
||||||
[logging]
|
[logging]
|
||||||
level = INFO
|
level = INFO
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
# The API refuses to start without a strong JWT key (no built-in default), and tests import the
|
||||||
|
# application: give them a throwaway key before anything is imported. A real key in the
|
||||||
|
# environment is left untouched.
|
||||||
|
os.environ.setdefault("OVPMON_API_SECRET_KEY", "x" * 64)
|
||||||
@@ -10,6 +10,7 @@ import pyotp
|
|||||||
import bcrypt
|
import bcrypt
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from db import DatabaseManager
|
from db import DatabaseManager
|
||||||
|
from secret_key import resolve_secret_key, SecretKeyError
|
||||||
|
|
||||||
|
|
||||||
import io
|
import io
|
||||||
@@ -41,18 +42,27 @@ class OpenVPNAPI:
|
|||||||
return fallback
|
return fallback
|
||||||
|
|
||||||
def __init__(self, config_file='config.ini'):
|
def __init__(self, config_file='config.ini'):
|
||||||
self.db_manager = DatabaseManager(config_file)
|
|
||||||
self.db_manager.init_database()
|
|
||||||
self.config = configparser.ConfigParser()
|
self.config = configparser.ConfigParser()
|
||||||
self.config.read(config_file)
|
self.config.read(config_file)
|
||||||
|
|
||||||
|
# Security: fail closed on a missing/weak signing key, before any DB work or admin creation
|
||||||
|
try:
|
||||||
|
self.secret_key, key_source = resolve_secret_key(
|
||||||
|
os.getenv('OVPMON_API_SECRET_KEY'),
|
||||||
|
self.config.get('api', 'secret_key', fallback=None),
|
||||||
|
os.getenv('OVPMON_SECRET_KEY'))
|
||||||
|
except SecretKeyError as e:
|
||||||
|
logger.critical(f"Refusing to start: {e}")
|
||||||
|
raise SystemExit(1)
|
||||||
|
logger.info(f"JWT secret key loaded from {key_source}")
|
||||||
|
app.config['SECRET_KEY'] = self.secret_key
|
||||||
|
|
||||||
|
self.db_manager = DatabaseManager(config_file)
|
||||||
|
self.db_manager.init_database()
|
||||||
|
|
||||||
# Paths
|
# Paths
|
||||||
self.public_ip = self.get_config_value('openvpn_monitor', 'public_ip', fallback='')
|
self.public_ip = self.get_config_value('openvpn_monitor', 'public_ip', fallback='')
|
||||||
|
|
||||||
# Security
|
|
||||||
self.secret_key = self.get_config_value('api', 'secret_key', fallback='ovpmon-secret-change-me')
|
|
||||||
app.config['SECRET_KEY'] = self.secret_key
|
|
||||||
|
|
||||||
# Ensure at least one user exists
|
# Ensure at least one user exists
|
||||||
self.ensure_default_admin()
|
self.ensure_default_admin()
|
||||||
|
|
||||||
|
|||||||
+335
-134
@@ -1,11 +1,29 @@
|
|||||||
import sqlite3
|
import sqlite3
|
||||||
import time
|
import time
|
||||||
import os
|
import os
|
||||||
|
import calendar
|
||||||
|
import signal
|
||||||
|
import threading
|
||||||
import configparser
|
import configparser
|
||||||
import logging
|
import logging
|
||||||
|
from collections import namedtuple
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from db import DatabaseManager
|
from db import DatabaseManager
|
||||||
|
|
||||||
|
# Результат чтения файла статуса OpenVPN.
|
||||||
|
# valid - файл целостный, тик можно обрабатывать (False = тик пропустить целиком);
|
||||||
|
# clients - список сессий (пустой при stale или при невалидном чтении);
|
||||||
|
# stale - файл целостный, но устарел (OpenVPN остановлен), клиентов нет;
|
||||||
|
# reason - причина невалидности/устаревания (для лога).
|
||||||
|
StatusReading = namedtuple('StatusReading', ['valid', 'clients', 'stale', 'reason'])
|
||||||
|
|
||||||
|
# Время хранения "памяти" о завершённой сессии (ключ + последние счётчики), сек.
|
||||||
|
# Нужна, чтобы сессия с тем же ключом, вернувшаяся после льготного периода, не считалась с нуля.
|
||||||
|
SESSION_MEMORY_SECONDS = 3600
|
||||||
|
|
||||||
|
# Формат времени в таблице active_sessions (UTC для connected_since)
|
||||||
|
TS_FORMAT = '%Y-%m-%d %H:%M:%S'
|
||||||
|
|
||||||
# --- КЛАСС АГРЕГАЦИИ ДАННЫХ (TSDB LOGIC) ---
|
# --- КЛАСС АГРЕГАЦИИ ДАННЫХ (TSDB LOGIC) ---
|
||||||
class TimeSeriesAggregator:
|
class TimeSeriesAggregator:
|
||||||
def __init__(self, db_provider):
|
def __init__(self, db_provider):
|
||||||
@@ -101,7 +119,13 @@ class OpenVPNDataGatherer:
|
|||||||
# Инициализируем дату последней очистки вчерашним днем для корректного старта
|
# Инициализируем дату последней очистки вчерашним днем для корректного старта
|
||||||
self.last_cleanup_date = (datetime.now() - timedelta(days=1)).date()
|
self.last_cleanup_date = (datetime.now() - timedelta(days=1)).date()
|
||||||
|
|
||||||
self.last_cleanup_date = (datetime.now() - timedelta(days=1)).date()
|
# Момент запуска демона (epoch): сессии, начавшиеся раньше, считаются "продолжающимися"
|
||||||
|
self.started_at = self._now()
|
||||||
|
# Флаг остановки (SIGTERM/SIGINT) и счётчик подряд идущих пропущенных тиков
|
||||||
|
self.stop_event = threading.Event()
|
||||||
|
self.invalid_ticks = 0
|
||||||
|
# Проверка настроек цикла: неверное значение = отказ запуска
|
||||||
|
self._load_settings()
|
||||||
|
|
||||||
self.db_manager = DatabaseManager(config_file)
|
self.db_manager = DatabaseManager(config_file)
|
||||||
self.db_manager.init_database()
|
self.db_manager.init_database()
|
||||||
@@ -110,10 +134,74 @@ class OpenVPNDataGatherer:
|
|||||||
# Передаем ссылку на метод подключения к БД
|
# Передаем ссылку на метод подключения к БД
|
||||||
self.ts_aggregator = TimeSeriesAggregator(self.db_manager.get_connection)
|
self.ts_aggregator = TimeSeriesAggregator(self.db_manager.get_connection)
|
||||||
|
|
||||||
# In-Memory Cache для отслеживания сессий (CN, RealAddress) -> {last_bytes...}
|
# In-Memory Cache для отслеживания сессий:
|
||||||
|
# (CN, RealAddress, connected_since_ts) -> {
|
||||||
|
# 'bytes_received', 'bytes_sent': счётчики на прошлом тике,
|
||||||
|
# 'last_seen': строка времени, 'connected_since': строка UTC (начало сессии),
|
||||||
|
# 'missing_ticks': сколько тиков подряд сессии нет в статусе (льготный период)}
|
||||||
# Используется для корректного расчета инкрементов при множественных сессиях одного CN
|
# Используется для корректного расчета инкрементов при множественных сессиях одного CN
|
||||||
self.session_cache = {}
|
self.session_cache = {}
|
||||||
|
|
||||||
|
# Базовая линия: ключ сессии -> (rx, tx, момент записи, epoch).
|
||||||
|
# Сюда попадают сессии из снимка active_sessions (после перезапуска демона)
|
||||||
|
# и сессии, удалённые из кэша после льготного периода.
|
||||||
|
self.baseline = {}
|
||||||
|
self._load_baseline()
|
||||||
|
|
||||||
|
def _now(self):
|
||||||
|
"""Текущее время (epoch). Вынесено в метод, чтобы тесты могли управлять временем."""
|
||||||
|
return time.time()
|
||||||
|
|
||||||
|
def _read_int_setting(self, key, default, minimum):
|
||||||
|
"""Читает целое из [openvpn_monitor] (ENV > config.ini > умолчание) и проверяет минимум."""
|
||||||
|
raw = self.get_config_value('openvpn_monitor', key, default)
|
||||||
|
try:
|
||||||
|
value = int(str(raw).strip())
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError(f"[openvpn_monitor] {key} must be an integer, got {raw!r}")
|
||||||
|
if value < minimum:
|
||||||
|
raise ValueError(f"[openvpn_monitor] {key} must be >= {minimum}, got {value}")
|
||||||
|
return value
|
||||||
|
|
||||||
|
def _load_settings(self):
|
||||||
|
"""Загрузка и проверка параметров цикла. При ошибке - понятное сообщение и выход с кодом 1."""
|
||||||
|
try:
|
||||||
|
self.interval = self._read_int_setting('check_interval', 10, 1)
|
||||||
|
self.grace_ticks = self._read_int_setting('session_grace_ticks', 3, 0)
|
||||||
|
self.stale_seconds = self._read_int_setting('status_stale_seconds', 60, 1)
|
||||||
|
self.invalid_max = self._read_int_setting('status_invalid_max', 6, 1)
|
||||||
|
except ValueError as e:
|
||||||
|
self.logger.error(f"Invalid configuration: {e}")
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
def _load_baseline(self):
|
||||||
|
"""
|
||||||
|
Загрузка снимка active_sessions (последнее состояние до остановки демона) как базовой линии.
|
||||||
|
connected_since в таблице - UTC 'YYYY-MM-DD HH:MM:SS'; переводим в epoch для ключа сессии.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
conn = self.db_manager.get_connection()
|
||||||
|
try:
|
||||||
|
rows = conn.execute(
|
||||||
|
'SELECT common_name, real_address, bytes_received, bytes_sent, connected_since '
|
||||||
|
'FROM active_sessions'
|
||||||
|
).fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.warning(f"Could not load active_sessions snapshot: {e}")
|
||||||
|
return
|
||||||
|
|
||||||
|
for name, real_addr, rx, tx, since in rows:
|
||||||
|
try:
|
||||||
|
since_ts = calendar.timegm(time.strptime(str(since)[:19].replace('T', ' '), TS_FORMAT))
|
||||||
|
self.baseline[(name, real_addr, since_ts)] = (int(rx), int(tx), self.started_at)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
# Старый формат (локальное время первого наблюдения) - совпасть с ключом не может
|
||||||
|
continue
|
||||||
|
if self.baseline:
|
||||||
|
self.logger.info(f"Loaded {len(self.baseline)} sessions from active_sessions snapshot")
|
||||||
|
|
||||||
def load_config(self, config_file):
|
def load_config(self, config_file):
|
||||||
"""Загрузка конфигурации или создание дефолтной со сложной структурой"""
|
"""Загрузка конфигурации или создание дефолтной со сложной структурой"""
|
||||||
config = configparser.ConfigParser()
|
config = configparser.ConfigParser()
|
||||||
@@ -129,6 +217,9 @@ class OpenVPNDataGatherer:
|
|||||||
'log_path': '/var/log/openvpn/openvpn-status.log',
|
'log_path': '/var/log/openvpn/openvpn-status.log',
|
||||||
'db_path': 'openvpn_monitor.db',
|
'db_path': 'openvpn_monitor.db',
|
||||||
'check_interval': '10', # Интервал 10 секунд
|
'check_interval': '10', # Интервал 10 секунд
|
||||||
|
'session_grace_ticks': '3', # Тиков до удаления пропавшей из статуса сессии
|
||||||
|
'status_stale_seconds': '60', # Файл статуса старше этого = OpenVPN остановлен
|
||||||
|
'status_invalid_max': '6', # Подряд пропущенных тиков до уровня ERROR в логе
|
||||||
},
|
},
|
||||||
'logging': {
|
'logging': {
|
||||||
'level': 'INFO',
|
'level': 'INFO',
|
||||||
@@ -260,65 +351,149 @@ class OpenVPNDataGatherer:
|
|||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
def parse_log_file(self):
|
def parse_status(self, path, now=None):
|
||||||
"""
|
"""
|
||||||
Парсинг лога версии 2 (CSV формат).
|
Разбор файла статуса версии 2 (CSV формат) с проверкой целостности и свежести.
|
||||||
Ожидает формат: CLIENT_LIST,Common Name,Real Address,...,Bytes Received,Bytes Sent,...
|
Ожидает: TITLE,... / TIME,<текст>,<epoch> / CLIENT_LIST,Common Name,Real Address,...,
|
||||||
|
Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t),... / END
|
||||||
|
|
||||||
|
Возвращает StatusReading:
|
||||||
|
- нет файла, ошибка чтения, нет TITLE, нет END последней строкой, нет TIME:
|
||||||
|
valid=False (тик нужно пропустить целиком, БД и кэш не трогать);
|
||||||
|
- TIME старше status_stale_seconds: valid=True, stale=True, клиентов нет (OpenVPN остановлен);
|
||||||
|
- иначе valid=True и список клиентов (пустой файл без CLIENT_LIST - штатный случай).
|
||||||
"""
|
"""
|
||||||
log_path = self.get_config_value('openvpn_monitor', 'log_path', '/var/log/openvpn/openvpn-status.log')
|
if now is None:
|
||||||
clients = []
|
now = self._now()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if not os.path.exists(log_path):
|
if not os.path.exists(path):
|
||||||
self.logger.warning(f"Log file not found: {log_path}")
|
return StatusReading(False, [], False, f"status file not found: {path}")
|
||||||
return clients
|
with open(path, 'r') as file:
|
||||||
|
lines = [line.strip() for line in file]
|
||||||
with open(log_path, 'r') as file:
|
|
||||||
for line in file:
|
|
||||||
line = line.strip()
|
|
||||||
# Фильтруем только строки с данными клиентов
|
|
||||||
if not line.startswith('CLIENT_LIST'):
|
|
||||||
continue
|
|
||||||
|
|
||||||
parts = line.split(',')
|
|
||||||
# V2 Index Map:
|
|
||||||
# 1: Common Name
|
|
||||||
# 2: Real Address
|
|
||||||
# 5: Bytes Received
|
|
||||||
# 6: Bytes Sent
|
|
||||||
|
|
||||||
if len(parts) >= 8 and parts[1] != 'Common Name':
|
|
||||||
# SKIPPING 'UNDEF' CLIENTS
|
|
||||||
if parts[1].strip() == 'UNDEF':
|
|
||||||
continue
|
|
||||||
|
|
||||||
try:
|
|
||||||
client = {
|
|
||||||
'common_name': parts[1].strip(),
|
|
||||||
'real_address': parts[2].strip(),
|
|
||||||
'bytes_received': int(parts[5].strip()),
|
|
||||||
'bytes_sent': int(parts[6].strip()),
|
|
||||||
'status': 'Active'
|
|
||||||
}
|
|
||||||
clients.append(client)
|
|
||||||
except (ValueError, IndexError) as e:
|
|
||||||
self.logger.warning(f"Error parsing client line: {e}")
|
|
||||||
|
|
||||||
self.logger.debug(f"Parsed {len(clients)} active clients")
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.error(f"Error parsing log file: {e}")
|
return StatusReading(False, [], False, f"cannot read status file: {e}")
|
||||||
|
|
||||||
return clients
|
lines = [line for line in lines if line]
|
||||||
|
if not any(line.startswith('TITLE') for line in lines):
|
||||||
|
return StatusReading(False, [], False, "no TITLE line (not a status file)")
|
||||||
|
if lines[-1] != 'END':
|
||||||
|
return StatusReading(False, [], False, "no END line (file is incomplete)")
|
||||||
|
|
||||||
|
status_time = None
|
||||||
|
clients = []
|
||||||
|
for line in lines:
|
||||||
|
if line.startswith('TIME,'):
|
||||||
|
try:
|
||||||
|
status_time = int(line.split(',')[2])
|
||||||
|
except (IndexError, ValueError):
|
||||||
|
pass
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Фильтруем только строки с данными клиентов
|
||||||
|
if not line.startswith('CLIENT_LIST'):
|
||||||
|
continue
|
||||||
|
|
||||||
|
parts = line.split(',')
|
||||||
|
# V2 Index Map:
|
||||||
|
# 1: Common Name
|
||||||
|
# 2: Real Address
|
||||||
|
# 5: Bytes Received
|
||||||
|
# 6: Bytes Sent
|
||||||
|
# 8: Connected Since (time_t) - начало сессии, epoch
|
||||||
|
|
||||||
|
if len(parts) >= 8 and parts[1] != 'Common Name':
|
||||||
|
# SKIPPING 'UNDEF' CLIENTS
|
||||||
|
if parts[1].strip() == 'UNDEF':
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
since_ts = None
|
||||||
|
if len(parts) > 8:
|
||||||
|
try:
|
||||||
|
since_ts = int(parts[8].strip())
|
||||||
|
except ValueError:
|
||||||
|
since_ts = None
|
||||||
|
if since_ts is not None and since_ts <= 0:
|
||||||
|
since_ts = None
|
||||||
|
|
||||||
|
client = {
|
||||||
|
'common_name': parts[1].strip(),
|
||||||
|
'real_address': parts[2].strip(),
|
||||||
|
'bytes_received': int(parts[5].strip()),
|
||||||
|
'bytes_sent': int(parts[6].strip()),
|
||||||
|
'connected_since_ts': since_ts,
|
||||||
|
'status': 'Active'
|
||||||
|
}
|
||||||
|
clients.append(client)
|
||||||
|
except (ValueError, IndexError) as e:
|
||||||
|
self.logger.warning(f"Error parsing client line: {e}")
|
||||||
|
|
||||||
|
if status_time is None:
|
||||||
|
return StatusReading(False, [], False, "no valid TIME line (cannot check freshness)")
|
||||||
|
|
||||||
|
age = now - status_time
|
||||||
|
if age > self.stale_seconds:
|
||||||
|
return StatusReading(True, [], True, f"status file is stale ({int(age)}s old): OpenVPN stopped?")
|
||||||
|
|
||||||
|
self.logger.debug(f"Parsed {len(clients)} active clients")
|
||||||
|
return StatusReading(True, clients, False, "")
|
||||||
|
|
||||||
|
def parse_log_file(self):
|
||||||
|
"""Читает файл статуса из [openvpn_monitor] log_path (см. parse_status). Возвращает StatusReading."""
|
||||||
|
log_path = self.get_config_value('openvpn_monitor', 'log_path', '/var/log/openvpn/openvpn-status.log')
|
||||||
|
return self.parse_status(log_path)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _delta(current, previous):
|
||||||
|
"""Прирост счётчика сессии; уменьшение счётчика при том же ключе = сброс (прирост = текущее)."""
|
||||||
|
return current if current < previous else current - previous
|
||||||
|
|
||||||
|
def _first_seen_increment(self, key, curr_recv, curr_sent):
|
||||||
|
"""
|
||||||
|
Прирост для сессии, которой нет в кэше (правила: DOCS/Changes/2026-10-05_Gatherer_Reliability_PLAN.md, 2.2).
|
||||||
|
Возвращает (inc_recv, inc_sent).
|
||||||
|
"""
|
||||||
|
name, real_addr, since_ts = key
|
||||||
|
|
||||||
|
if since_ts is None:
|
||||||
|
# Нестандартный статус: время начала сессии неизвестно, запасная эвристика по размеру счётчиков
|
||||||
|
self.logger.warning(f"No connected_since time_t for {name} ({real_addr}): using 10 MB heuristic")
|
||||||
|
threshold = 10 * 1024 * 1024
|
||||||
|
if curr_recv < threshold and curr_sent < threshold:
|
||||||
|
return curr_recv, curr_sent
|
||||||
|
return 0, 0
|
||||||
|
|
||||||
|
# Сессия известна: снимок active_sessions после перезапуска демона
|
||||||
|
# или сессия, удалённая из кэша после льготного периода (счётчики на последнем тике)
|
||||||
|
base = self.baseline.get(key)
|
||||||
|
if base is not None:
|
||||||
|
return self._delta(curr_recv, base[0]), self._delta(curr_sent, base[1])
|
||||||
|
|
||||||
|
# Сессия началась уже после запуска демона (с запасом 2 интервала): считаем с нуля
|
||||||
|
if since_ts >= self.started_at - 2 * self.interval:
|
||||||
|
return curr_recv, curr_sent
|
||||||
|
|
||||||
|
# Сессия старше демона, снимка нет: базовая линия, трафик до этого момента потерян
|
||||||
|
self.logger.warning(
|
||||||
|
f"Session of {name} ({real_addr}) started before the gatherer and has no snapshot: "
|
||||||
|
f"baseline set, {curr_recv} B received / {curr_sent} B sent before this moment are not counted"
|
||||||
|
)
|
||||||
|
return 0, 0
|
||||||
|
|
||||||
def update_client_status_and_bytes(self, active_clients):
|
def update_client_status_and_bytes(self, active_clients):
|
||||||
"""
|
"""
|
||||||
Обновление статусов и расчет инкрементов трафика.
|
Обновление статусов и расчет инкрементов трафика.
|
||||||
Использует In-Memory Cache (self.session_cache) для корректной обработки
|
Использует In-Memory Cache (self.session_cache) для корректной обработки
|
||||||
множественных сессий одного пользователя (Ping-Pong effect fix).
|
множественных сессий одного пользователя (Ping-Pong effect fix).
|
||||||
|
Изменения кэша накапливаются в new_cache и применяются только после успешного commit:
|
||||||
|
при откате транзакции кэш остаётся прежним, приращения не теряются.
|
||||||
|
При ошибке БД откатывает транзакцию и пробрасывает исключение (его обработает цикл).
|
||||||
"""
|
"""
|
||||||
conn = self.db_manager.get_connection()
|
conn = self.db_manager.get_connection()
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
|
now_ts = self._now()
|
||||||
|
last_seen_str = datetime.fromtimestamp(now_ts).strftime(TS_FORMAT)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 1. Загружаем текущее состояние CNs из БД для обновления статусов
|
# 1. Загружаем текущее состояние CNs из БД для обновления статусов
|
||||||
@@ -329,8 +504,8 @@ class OpenVPNDataGatherer:
|
|||||||
# cn -> { 'inc_rx': 0, 'inc_tx': 0, 'curr_rx': 0, 'curr_tx': 0, 'real_address': '...'}
|
# cn -> { 'inc_rx': 0, 'inc_tx': 0, 'curr_rx': 0, 'curr_tx': 0, 'real_address': '...'}
|
||||||
cn_updates = {}
|
cn_updates = {}
|
||||||
|
|
||||||
# Множество активных ключей сессий (CN, RealAddr) для очистки кэша
|
# Новое состояние кэша сессий (применяется после commit) и активные CN
|
||||||
active_session_keys = set()
|
new_cache = {}
|
||||||
active_cns = set()
|
active_cns = set()
|
||||||
|
|
||||||
# 2. Обрабатываем каждую активную сессию
|
# 2. Обрабатываем каждую активную сессию
|
||||||
@@ -339,66 +514,39 @@ class OpenVPNDataGatherer:
|
|||||||
real_addr = client['real_address']
|
real_addr = client['real_address']
|
||||||
curr_recv = client['bytes_received']
|
curr_recv = client['bytes_received']
|
||||||
curr_sent = client['bytes_sent']
|
curr_sent = client['bytes_sent']
|
||||||
|
since_ts = client.get('connected_since_ts')
|
||||||
|
|
||||||
# Уникальный ключ сессии
|
# Уникальный ключ сессии: один и тот же CN/адрес может переподключиться
|
||||||
session_key = (name, real_addr)
|
# (новый connected_since) - это уже новая сессия
|
||||||
active_session_keys.add(session_key)
|
session_key = (name, real_addr, since_ts)
|
||||||
active_cns.add(name)
|
active_cns.add(name)
|
||||||
|
|
||||||
# --- ЛОГИКА РАСЧЕТА ДЕЛЬТЫ (In-Memory) ---
|
# --- ЛОГИКА РАСЧЕТА ДЕЛЬТЫ (In-Memory) ---
|
||||||
if session_key in self.session_cache:
|
prev_state = self.session_cache.get(session_key)
|
||||||
prev_state = self.session_cache[session_key]
|
if prev_state is not None:
|
||||||
prev_recv = prev_state['bytes_received']
|
prev_recv = prev_state['bytes_received']
|
||||||
prev_sent = prev_state['bytes_sent']
|
prev_sent = prev_state['bytes_sent']
|
||||||
|
|
||||||
# Расчет RX
|
|
||||||
if curr_recv < prev_recv:
|
if curr_recv < prev_recv:
|
||||||
# Рестарт сессии (счетчик сбросился)
|
|
||||||
inc_recv = curr_recv
|
|
||||||
self.logger.info(f"Session reset detected for {session_key} (Recv)")
|
self.logger.info(f"Session reset detected for {session_key} (Recv)")
|
||||||
else:
|
|
||||||
inc_recv = curr_recv - prev_recv
|
|
||||||
|
|
||||||
# Расчет TX
|
|
||||||
if curr_sent < prev_sent:
|
if curr_sent < prev_sent:
|
||||||
inc_sent = curr_sent
|
|
||||||
self.logger.info(f"Session reset detected for {session_key} (Sent)")
|
self.logger.info(f"Session reset detected for {session_key} (Sent)")
|
||||||
else:
|
inc_recv = self._delta(curr_recv, prev_recv)
|
||||||
inc_sent = curr_sent - prev_sent
|
inc_sent = self._delta(curr_sent, prev_sent)
|
||||||
|
connected_since = prev_state['connected_since']
|
||||||
else:
|
else:
|
||||||
# Новая сессия (или после рестарта сервиса)
|
# Сессия не в кэше: новая, продолжающаяся после перезапуска или вернувшаяся
|
||||||
# Если сервиса только запустился, мы не знаем предыдущего состояния.
|
inc_recv, inc_sent = self._first_seen_increment(session_key, curr_recv, curr_sent)
|
||||||
# Чтобы избежать спайков, считаем инкремент = 0 для первого появления,
|
# В active_sessions пишем реальное начало сессии (UTC); без time_t - время первого наблюдения
|
||||||
# если это похоже на продолжающуюся сессию (большие числа).
|
connected_since = time.strftime(TS_FORMAT, time.gmtime(since_ts if since_ts else now_ts))
|
||||||
# Если числа маленькие (<10MB), считаем как новую.
|
|
||||||
|
|
||||||
# 10 MB threshold
|
new_cache[session_key] = {
|
||||||
threshold = 10 * 1024 * 1024
|
'bytes_received': curr_recv,
|
||||||
|
'bytes_sent': curr_sent,
|
||||||
if curr_recv < threshold and curr_sent < threshold:
|
'last_seen': last_seen_str,
|
||||||
inc_recv = curr_recv
|
'connected_since': connected_since,
|
||||||
inc_sent = curr_sent
|
'missing_ticks': 0
|
||||||
else:
|
}
|
||||||
# Скорее всего рестарт сервиса, пропускаем первый тик
|
|
||||||
inc_recv = 0
|
|
||||||
inc_sent = 0
|
|
||||||
self.logger.debug(f"New session tracking started for {session_key}. Initializing baseline.")
|
|
||||||
|
|
||||||
# Обновляем кэш
|
|
||||||
if session_key not in self.session_cache:
|
|
||||||
# New session
|
|
||||||
self.session_cache[session_key] = {
|
|
||||||
'bytes_received': curr_recv,
|
|
||||||
'bytes_sent': curr_sent,
|
|
||||||
'last_seen': datetime.now(),
|
|
||||||
'connected_since': datetime.now() # Track start time
|
|
||||||
}
|
|
||||||
else:
|
|
||||||
# Update existing
|
|
||||||
self.session_cache[session_key]['bytes_received'] = curr_recv
|
|
||||||
self.session_cache[session_key]['bytes_sent'] = curr_sent
|
|
||||||
self.session_cache[session_key]['last_seen'] = datetime.now()
|
|
||||||
|
|
||||||
# Добавляем в клиентский объект (для истории/графиков)
|
# Добавляем в клиентский объект (для истории/графиков)
|
||||||
# Важно: это инкремент конкретной сессии
|
# Важно: это инкремент конкретной сессии
|
||||||
@@ -424,12 +572,16 @@ class OpenVPNDataGatherer:
|
|||||||
cn_updates[name]['max_tx'] = max(cn_updates[name]['max_tx'], curr_sent)
|
cn_updates[name]['max_tx'] = max(cn_updates[name]['max_tx'], curr_sent)
|
||||||
cn_updates[name]['real_address'] = real_addr
|
cn_updates[name]['real_address'] = real_addr
|
||||||
|
|
||||||
# 3. Очистка кэша от мертвых сессий
|
# 3. Льготный период для сессий, которых нет в текущем статусе:
|
||||||
# Создаем список ключей для удаления, чтобы не менять словарь во время итерации
|
# запись остаётся в кэше, пока missing_ticks < session_grace_ticks
|
||||||
dead_sessions = [k for k in self.session_cache if k not in active_session_keys]
|
for key, state in self.session_cache.items():
|
||||||
for k in dead_sessions:
|
if key in new_cache:
|
||||||
del self.session_cache[k]
|
continue
|
||||||
self.logger.debug(f"Removed inactive session from cache: {k}")
|
missing = state['missing_ticks'] + 1
|
||||||
|
if missing < self.grace_ticks:
|
||||||
|
new_cache[key] = dict(state, missing_ticks=missing)
|
||||||
|
else:
|
||||||
|
self.logger.debug(f"Removed inactive session from cache: {key}")
|
||||||
|
|
||||||
# 4. Обновление БД (Upsert Clients)
|
# 4. Обновление БД (Upsert Clients)
|
||||||
for name, data in cn_updates.items():
|
for name, data in cn_updates.items():
|
||||||
@@ -463,14 +615,17 @@ class OpenVPNDataGatherer:
|
|||||||
client['db_id'] = db_id
|
client['db_id'] = db_id
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# INSERT (New Client)
|
# INSERT (New Client): итоги стартуют с прироста первого кадра, а не с нуля
|
||||||
|
# (иначе трафик первого тика нового клиента не попадал в total_bytes_*)
|
||||||
cursor.execute('''
|
cursor.execute('''
|
||||||
INSERT INTO clients
|
INSERT INTO clients
|
||||||
(common_name, real_address, status, total_bytes_received, total_bytes_sent, last_bytes_received, last_bytes_sent)
|
(common_name, real_address, status, total_bytes_received, total_bytes_sent, last_bytes_received, last_bytes_sent)
|
||||||
VALUES (?, ?, 'Active', 0, 0, ?, ?)
|
VALUES (?, ?, 'Active', ?, ?, ?, ?)
|
||||||
''', (
|
''', (
|
||||||
name,
|
name,
|
||||||
data['real_address'],
|
data['real_address'],
|
||||||
|
data['inc_recv'],
|
||||||
|
data['inc_tx'],
|
||||||
data['max_rx'],
|
data['max_rx'],
|
||||||
data['max_tx']
|
data['max_tx']
|
||||||
))
|
))
|
||||||
@@ -494,11 +649,11 @@ class OpenVPNDataGatherer:
|
|||||||
# Clear old state
|
# Clear old state
|
||||||
cursor.execute('DELETE FROM active_sessions')
|
cursor.execute('DELETE FROM active_sessions')
|
||||||
|
|
||||||
# Insert current state
|
# Insert current state (только сессии, присутствующие в статусе)
|
||||||
for client in active_clients:
|
for client in active_clients:
|
||||||
# client['db_id'] should be populated by now (from step 4)
|
# client['db_id'] should be populated by now (from step 4)
|
||||||
if 'db_id' in client and 'session_key' in client:
|
if 'db_id' in client and 'session_key' in client:
|
||||||
sess_data = self.session_cache.get(client['session_key'])
|
sess_data = new_cache.get(client['session_key'])
|
||||||
if sess_data:
|
if sess_data:
|
||||||
cursor.execute('''
|
cursor.execute('''
|
||||||
INSERT INTO active_sessions
|
INSERT INTO active_sessions
|
||||||
@@ -510,18 +665,29 @@ class OpenVPNDataGatherer:
|
|||||||
client['real_address'],
|
client['real_address'],
|
||||||
client['bytes_received'],
|
client['bytes_received'],
|
||||||
client['bytes_sent'],
|
client['bytes_sent'],
|
||||||
sess_data.get('connected_since', datetime.now()),
|
sess_data['connected_since'],
|
||||||
sess_data.get('last_seen', datetime.now())
|
sess_data['last_seen']
|
||||||
))
|
))
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
except Exception as e:
|
except Exception:
|
||||||
self.logger.error(f"Error updating client status: {e}")
|
# Кэш не менялся: приращения не потеряны, следующий тик посчитает разницу за весь интервал
|
||||||
conn.rollback()
|
conn.rollback()
|
||||||
|
raise
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
# 7. Применяем изменения кэша только после успешного commit
|
||||||
|
for key, state in self.session_cache.items():
|
||||||
|
if key not in new_cache and key[2] is not None:
|
||||||
|
# Сессия удалена из кэша: помним последние счётчики на случай возврата с тем же ключом
|
||||||
|
self.baseline[key] = (state['bytes_received'], state['bytes_sent'], now_ts)
|
||||||
|
self.session_cache = new_cache
|
||||||
|
for key in new_cache:
|
||||||
|
self.baseline.pop(key, None)
|
||||||
|
self.baseline = {k: v for k, v in self.baseline.items() if now_ts - v[2] < SESSION_MEMORY_SECONDS}
|
||||||
|
|
||||||
return active_clients
|
return active_clients
|
||||||
|
|
||||||
def calculate_rates(self, clients, time_diff):
|
def calculate_rates(self, clients, time_diff):
|
||||||
@@ -572,28 +738,39 @@ class OpenVPNDataGatherer:
|
|||||||
"""Один цикл мониторинга"""
|
"""Один цикл мониторинга"""
|
||||||
current_time = datetime.now()
|
current_time = datetime.now()
|
||||||
|
|
||||||
# 1. Получаем активных клиентов
|
# 1. Читаем файл статуса (с проверкой целостности и свежести)
|
||||||
active_clients = self.parse_log_file()
|
reading = self.parse_log_file()
|
||||||
|
|
||||||
# 2. Обновляем статусы и считаем дельту трафика
|
if not reading.valid:
|
||||||
clients_with_updates = self.update_client_status_and_bytes(active_clients)
|
# Рваное чтение / нет файла: тик пропускаем целиком, БД и кэш не трогаем.
|
||||||
|
# last_check_time тоже не меняем: скорость следующего тика считается за весь интервал
|
||||||
|
self.invalid_ticks += 1
|
||||||
|
level = logging.ERROR if self.invalid_ticks >= self.invalid_max else logging.WARNING
|
||||||
|
self.logger.log(level, f"Skipping tick ({self.invalid_ticks} in a row): {reading.reason}")
|
||||||
|
else:
|
||||||
|
self.invalid_ticks = 0
|
||||||
|
if reading.stale:
|
||||||
|
self.logger.warning(reading.reason)
|
||||||
|
|
||||||
if clients_with_updates:
|
# 2. Обновляем статусы и считаем дельту трафика
|
||||||
# 3. Считаем интервал времени
|
clients_with_updates = self.update_client_status_and_bytes(reading.clients)
|
||||||
time_diff = 10.0 # Номинал
|
|
||||||
if self.last_check_time:
|
|
||||||
time_diff = (current_time - self.last_check_time).total_seconds()
|
|
||||||
|
|
||||||
# 4. Считаем скорости
|
if clients_with_updates:
|
||||||
clients_rated = self.calculate_rates(clients_with_updates, time_diff)
|
# 3. Считаем интервал времени
|
||||||
|
time_diff = 10.0 # Номинал
|
||||||
|
if self.last_check_time:
|
||||||
|
time_diff = (current_time - self.last_check_time).total_seconds()
|
||||||
|
|
||||||
# 5. Сохраняем RAW историю (для графиков реального времени)
|
# 4. Считаем скорости
|
||||||
self.store_usage_history(clients_rated)
|
clients_rated = self.calculate_rates(clients_with_updates, time_diff)
|
||||||
|
|
||||||
# 6. Агрегируем в TSDB (5m, 15m, 1h, 6h, 1d)
|
# 5. Сохраняем RAW историю (для графиков реального времени)
|
||||||
self.ts_aggregator.aggregate(clients_rated)
|
self.store_usage_history(clients_rated)
|
||||||
|
|
||||||
self.last_check_time = current_time
|
# 6. Агрегируем в TSDB (5m, 15m, 1h, 6h, 1d)
|
||||||
|
self.ts_aggregator.aggregate(clients_rated)
|
||||||
|
|
||||||
|
self.last_check_time = current_time
|
||||||
|
|
||||||
# 7. Проверка необходимости очистки (раз в сутки)
|
# 7. Проверка необходимости очистки (раз в сутки)
|
||||||
if current_time.date() > self.last_cleanup_date:
|
if current_time.date() > self.last_cleanup_date:
|
||||||
@@ -601,21 +778,45 @@ class OpenVPNDataGatherer:
|
|||||||
self.cleanup_old_data()
|
self.cleanup_old_data()
|
||||||
self.last_cleanup_date = current_time.date()
|
self.last_cleanup_date = current_time.date()
|
||||||
|
|
||||||
|
def _handle_signal(self, signum, frame):
|
||||||
|
"""SIGTERM/SIGINT: только выставляем флаг, текущий цикл доделывается до конца."""
|
||||||
|
self.logger.info(f"Signal {signum} received, stopping after the current cycle")
|
||||||
|
self.stop_event.set()
|
||||||
|
|
||||||
def start_monitoring(self):
|
def start_monitoring(self):
|
||||||
"""Запуск цикла"""
|
"""Запуск цикла. Цикл переживает любые исключения; остановка по SIGTERM/SIGINT штатная."""
|
||||||
interval = int(self.get_config_value('openvpn_monitor', 'check_interval', 10))
|
interval = self.interval
|
||||||
self.logger.info(f"Starting OpenVPN Monitoring. Interval: {interval}s")
|
self.logger.info(f"Starting OpenVPN Monitoring. Interval: {interval}s")
|
||||||
self.logger.info("Press Ctrl+C to stop")
|
self.logger.info("Press Ctrl+C to stop")
|
||||||
|
|
||||||
|
# Обработчики сигналов ставятся только в главном потоке; прежние восстанавливаем при выходе
|
||||||
|
previous = {}
|
||||||
try:
|
try:
|
||||||
while True:
|
for sig in (signal.SIGTERM, signal.SIGINT):
|
||||||
self.run_monitoring_cycle()
|
previous[sig] = signal.signal(sig, self._handle_signal)
|
||||||
time.sleep(interval)
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
failures = 0
|
||||||
self.logger.info("Monitoring stopped by user")
|
try:
|
||||||
except Exception as e:
|
while not self.stop_event.is_set():
|
||||||
self.logger.error(f"Critical error in main loop: {e}")
|
try:
|
||||||
|
self.run_monitoring_cycle()
|
||||||
|
failures = 0
|
||||||
|
except Exception:
|
||||||
|
failures += 1
|
||||||
|
self.logger.exception(f"Monitoring cycle failed ({failures} in a row)")
|
||||||
|
|
||||||
|
# Пауза: интервал, а при подряд идущих сбоях - экспоненциально до 60 с
|
||||||
|
delay = interval
|
||||||
|
if failures:
|
||||||
|
delay = max(interval, min(interval * 2 ** min(failures, 10), 60))
|
||||||
|
self.stop_event.wait(delay)
|
||||||
|
finally:
|
||||||
|
for sig, handler in previous.items():
|
||||||
|
signal.signal(sig, handler)
|
||||||
|
|
||||||
|
self.logger.info("Monitoring stopped")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
gatherer = OpenVPNDataGatherer()
|
gatherer = OpenVPNDataGatherer()
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""JWT signing key rule (fail closed). Identical copy lives in APP_PROFILER/utils/secret_key.py."""
|
||||||
|
|
||||||
|
ENV_NAME = "OVPMON_API_SECRET_KEY"
|
||||||
|
LEGACY_ENV_NAME = "OVPMON_SECRET_KEY"
|
||||||
|
DEFAULT_KEY = "ovpmon-secret-change-me"
|
||||||
|
MIN_LENGTH = 32
|
||||||
|
|
||||||
|
HOW_TO_FIX = f"Generate one with: openssl rand -hex 32, and set it in {ENV_NAME} (or [api] secret_key in config.ini)."
|
||||||
|
|
||||||
|
|
||||||
|
class SecretKeyError(Exception):
|
||||||
|
"""The signing key is missing or weak. The message never contains the key value."""
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_secret_key(env, ini_value, legacy_env=None):
|
||||||
|
"""Return (key, source) where source is "environment" or "config.ini".
|
||||||
|
|
||||||
|
env: value of OVPMON_API_SECRET_KEY (or None); ini_value: [api] secret_key (or None);
|
||||||
|
legacy_env: value of OVPMON_SECRET_KEY (not used by the application, only for the hint).
|
||||||
|
Priority: environment > config.ini. Raises SecretKeyError; does not log or exit.
|
||||||
|
"""
|
||||||
|
if env is not None:
|
||||||
|
key, source = env, f"environment variable {ENV_NAME}"
|
||||||
|
result_source = "environment"
|
||||||
|
else:
|
||||||
|
key, source = ini_value, "[api] secret_key in config.ini"
|
||||||
|
result_source = "config.ini"
|
||||||
|
|
||||||
|
if key is None or not key.strip():
|
||||||
|
msg = f"JWT secret key is not set (checked {ENV_NAME} and [api] secret_key in config.ini)."
|
||||||
|
if legacy_env is not None and legacy_env.strip():
|
||||||
|
msg += (f" {LEGACY_ENV_NAME} is set but is not used by the application: "
|
||||||
|
f"rename it to {ENV_NAME}.")
|
||||||
|
raise SecretKeyError(f"{msg} {HOW_TO_FIX}")
|
||||||
|
|
||||||
|
lowered = key.strip().lower()
|
||||||
|
if lowered == DEFAULT_KEY or "change-me" in lowered or "changeme" in lowered:
|
||||||
|
raise SecretKeyError(f"JWT secret key from {source} is a placeholder/default value. {HOW_TO_FIX}")
|
||||||
|
if len(key) < MIN_LENGTH:
|
||||||
|
raise SecretKeyError(f"JWT secret key from {source} is too short "
|
||||||
|
f"({len(key)} characters, at least {MIN_LENGTH} required). {HOW_TO_FIX}")
|
||||||
|
return key, result_source
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
import copy
|
||||||
|
import logging
|
||||||
|
import signal
|
||||||
|
import sqlite3
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from openvpn_gatherer_v3 import OpenVPNDataGatherer
|
||||||
|
|
||||||
|
MB = 1024 * 1024
|
||||||
|
T0 = 1_800_000_000 # fixed "now" of the fake clock (epoch)
|
||||||
|
|
||||||
|
HEADER = ("HEADER,CLIENT_LIST,Common Name,Real Address,Virtual Address,Virtual IPv6 Address,"
|
||||||
|
"Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t),Username,Client ID,"
|
||||||
|
"Peer ID,Data Channel Cipher")
|
||||||
|
|
||||||
|
|
||||||
|
def write_status(path, now, clients, complete=True):
|
||||||
|
"""Synthetic OpenVPN status file v2. clients: (cn, real_address, rx, tx, connected_since_ts)."""
|
||||||
|
lines = ["TITLE,OpenVPN 2.6.8 x86_64-pc-linux-gnu", f"TIME,Mon Jan 1 00:00:00 2027,{int(now)}", HEADER]
|
||||||
|
for cn, real, rx, tx, since in clients:
|
||||||
|
lines.append(f"CLIENT_LIST,{cn},{real},10.8.0.2,,{rx},{tx},Mon Jan 1 00:00:00 2027,{since},"
|
||||||
|
f"UNDEF,1,0,AES-256-GCM")
|
||||||
|
lines += ["HEADER,ROUTING_TABLE,Virtual Address,Common Name,Real Address,Last Ref,Last Ref (time_t)",
|
||||||
|
"GLOBAL_STATS,Max bcast/mcast queue length,0"]
|
||||||
|
if complete:
|
||||||
|
lines.append("END")
|
||||||
|
with open(path, "w") as f:
|
||||||
|
f.write("\n".join(lines) + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
class Clock:
|
||||||
|
def __init__(self):
|
||||||
|
self.t = T0
|
||||||
|
|
||||||
|
def __call__(self):
|
||||||
|
return self.t
|
||||||
|
|
||||||
|
|
||||||
|
class FakeEvent:
|
||||||
|
"""Replaces threading.Event: records the pauses instead of sleeping."""
|
||||||
|
def __init__(self):
|
||||||
|
self.flag = False
|
||||||
|
self.delays = []
|
||||||
|
|
||||||
|
def is_set(self):
|
||||||
|
return self.flag
|
||||||
|
|
||||||
|
def set(self):
|
||||||
|
self.flag = True
|
||||||
|
|
||||||
|
def wait(self, timeout):
|
||||||
|
self.delays.append(timeout)
|
||||||
|
return self.flag
|
||||||
|
|
||||||
|
|
||||||
|
class Env:
|
||||||
|
def __init__(self, tmp_path):
|
||||||
|
self.status = str(tmp_path / "status.log")
|
||||||
|
self.db = str(tmp_path / "gatherer.db")
|
||||||
|
self.clock = Clock()
|
||||||
|
|
||||||
|
def gatherer(self):
|
||||||
|
"""New daemon 'started' at the current fake time (config.ini and log go to the cwd = tmp_path)."""
|
||||||
|
g = OpenVPNDataGatherer()
|
||||||
|
g._now = self.clock
|
||||||
|
g.started_at = self.clock()
|
||||||
|
return g
|
||||||
|
|
||||||
|
def tick(self, g, clients, complete=True, advance=10):
|
||||||
|
self.clock.t += advance
|
||||||
|
write_status(self.status, self.clock.t, clients, complete)
|
||||||
|
g.run_monitoring_cycle()
|
||||||
|
|
||||||
|
def query(self, sql, args=()):
|
||||||
|
conn = sqlite3.connect(self.db)
|
||||||
|
try:
|
||||||
|
return conn.execute(sql, args).fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def totals(self, cn):
|
||||||
|
return self.query("SELECT total_bytes_received, total_bytes_sent FROM clients WHERE common_name=?",
|
||||||
|
(cn,))[0]
|
||||||
|
|
||||||
|
def history_sum(self):
|
||||||
|
return self.query("SELECT COALESCE(SUM(bytes_received),0), COUNT(*) FROM usage_history")[0]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def env(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.chdir(tmp_path) # the gatherer writes config.ini and its log into the cwd
|
||||||
|
e = Env(tmp_path)
|
||||||
|
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", e.db)
|
||||||
|
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_LOG_PATH", e.status)
|
||||||
|
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
|
||||||
|
return e
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_fast_session_is_counted_from_zero(env):
|
||||||
|
g = env.gatherer()
|
||||||
|
since = T0 + 5 # started 5 s before the first frame
|
||||||
|
env.tick(g, [("alice", "1.1.1.1:1000", 50 * MB, MB, since)])
|
||||||
|
|
||||||
|
# BUG-03: 50 MB in the very first frame must not be dropped as "a continuing session"
|
||||||
|
assert env.totals("alice") == (50 * MB, MB)
|
||||||
|
assert env.query("SELECT bytes_received FROM usage_history") == [(50 * MB,)]
|
||||||
|
# active_sessions holds the real session start (UTC), not the first observation time
|
||||||
|
assert env.query("SELECT connected_since FROM active_sessions") == \
|
||||||
|
[(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(since)),)]
|
||||||
|
|
||||||
|
env.tick(g, [("alice", "1.1.1.1:1000", 51 * MB, MB, since)])
|
||||||
|
assert env.totals("alice") == (51 * MB, MB)
|
||||||
|
|
||||||
|
|
||||||
|
def test_daemon_restart_uses_snapshot_or_sets_baseline(env, caplog):
|
||||||
|
since = T0 + 5
|
||||||
|
g1 = env.gatherer()
|
||||||
|
env.tick(g1, [("alice", "1.1.1.1:1000", 1000, 500, since)])
|
||||||
|
env.tick(g1, [("alice", "1.1.1.1:1000", 3000, 700, since)])
|
||||||
|
assert env.totals("alice") == (3000, 700)
|
||||||
|
|
||||||
|
# Daemon restarts; the session is older than the daemon and the snapshot is in active_sessions:
|
||||||
|
# the traffic of the downtime is counted, nothing is counted twice
|
||||||
|
env.clock.t += 100
|
||||||
|
g2 = env.gatherer()
|
||||||
|
env.tick(g2, [("alice", "1.1.1.1:1000", 9000, 1700, since)])
|
||||||
|
assert env.totals("alice") == (9000, 1700)
|
||||||
|
|
||||||
|
# Snapshot lost: baseline, increment 0, one line in the log with the client name
|
||||||
|
conn = sqlite3.connect(env.db)
|
||||||
|
conn.execute("DELETE FROM active_sessions")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
env.clock.t += 100
|
||||||
|
g3 = env.gatherer()
|
||||||
|
with caplog.at_level(logging.WARNING):
|
||||||
|
env.tick(g3, [("alice", "1.1.1.1:1000", 20000, 2000, since)])
|
||||||
|
assert env.totals("alice") == (9000, 1700)
|
||||||
|
assert any(r.levelno == logging.WARNING and "alice" in r.getMessage() for r in caplog.records)
|
||||||
|
# the baseline works from now on
|
||||||
|
env.tick(g3, [("alice", "1.1.1.1:1000", 21000, 2100, since)])
|
||||||
|
assert env.totals("alice") == (10000, 1800)
|
||||||
|
|
||||||
|
|
||||||
|
def test_torn_read_skips_the_tick(env):
|
||||||
|
g = env.gatherer()
|
||||||
|
since = T0 + 5
|
||||||
|
env.tick(g, [("alice", "1.1.1.1:1000", 1000, 100, since)])
|
||||||
|
db_before = (env.totals("alice"), env.history_sum(),
|
||||||
|
env.query("SELECT status FROM clients"), env.query("SELECT * FROM active_sessions"))
|
||||||
|
cache_before = copy.deepcopy(g.session_cache)
|
||||||
|
|
||||||
|
# Frame without END (read while OpenVPN rewrites the file): no clients visible
|
||||||
|
env.tick(g, [], complete=False)
|
||||||
|
|
||||||
|
assert g.invalid_ticks == 1
|
||||||
|
assert (env.totals("alice"), env.history_sum(),
|
||||||
|
env.query("SELECT status FROM clients"), env.query("SELECT * FROM active_sessions")) == db_before
|
||||||
|
assert g.session_cache == cache_before
|
||||||
|
|
||||||
|
# Next intact frame: the difference for both intervals, no duplicates
|
||||||
|
env.tick(g, [("alice", "1.1.1.1:1000", 3000, 300, since)])
|
||||||
|
assert g.invalid_ticks == 0
|
||||||
|
assert env.totals("alice") == (3000, 300)
|
||||||
|
assert env.history_sum() == (3000, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_session_missing_for_a_tick_and_beyond_grace(env):
|
||||||
|
g = env.gatherer()
|
||||||
|
since = T0 + 5
|
||||||
|
|
||||||
|
def alice(rx, s):
|
||||||
|
return [("alice", "1.1.1.1:1000", rx, 0, s)]
|
||||||
|
|
||||||
|
env.tick(g, alice(1000, since))
|
||||||
|
|
||||||
|
# Missing for one tick, returns with the same key: continues, no double counting
|
||||||
|
env.tick(g, [])
|
||||||
|
env.tick(g, alice(1500, since))
|
||||||
|
assert env.totals("alice") == (1500, 0)
|
||||||
|
assert env.history_sum()[0] == 1500
|
||||||
|
assert env.query("SELECT status FROM clients") == [("Active",)]
|
||||||
|
|
||||||
|
# Grace period (3 ticks): kept for two missing ticks, forgotten on the third
|
||||||
|
env.tick(g, [])
|
||||||
|
env.tick(g, [])
|
||||||
|
assert len(g.session_cache) == 1 and list(g.session_cache.values())[0]["missing_ticks"] == 2
|
||||||
|
env.tick(g, [])
|
||||||
|
assert g.session_cache == {}
|
||||||
|
|
||||||
|
# Reconnect with a new connected_since: counted from zero (50 MB in the first frame)
|
||||||
|
env.tick(g, alice(50 * MB, env.clock.t + 10 - 5))
|
||||||
|
assert env.totals("alice") == (1500 + 50 * MB, 0)
|
||||||
|
assert len(g.session_cache) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_loop_survives_exceptions_and_stops_on_signal(env):
|
||||||
|
g = env.gatherer()
|
||||||
|
g.stop_event = FakeEvent()
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def cycle():
|
||||||
|
calls.append(1)
|
||||||
|
if len(calls) <= 2:
|
||||||
|
raise RuntimeError("boom")
|
||||||
|
if len(calls) == 4:
|
||||||
|
g._handle_signal(signal.SIGTERM, None) # what the SIGTERM handler does
|
||||||
|
|
||||||
|
g.run_monitoring_cycle = cycle
|
||||||
|
g.start_monitoring() # returns normally, no exception escapes
|
||||||
|
|
||||||
|
# 2 failures (exponential pause), 1 success (reset), the cycle that got the signal finishes, then exit
|
||||||
|
assert len(calls) == 4
|
||||||
|
assert g.stop_event.delays == [20, 40, 10, 10]
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from secret_key import resolve_secret_key, SecretKeyError
|
||||||
|
|
||||||
|
GOOD = "0123456789abcdef" * 4 # 64 hex characters
|
||||||
|
|
||||||
|
|
||||||
|
def test_weak_or_missing_key_is_refused():
|
||||||
|
for bad in (None, "", " ", "ovpmon-secret-change-me", "Change-Me-Please", "k" * 31):
|
||||||
|
with pytest.raises(SecretKeyError) as exc:
|
||||||
|
resolve_secret_key(bad, None)
|
||||||
|
assert "openssl rand -hex 32" in str(exc.value)
|
||||||
|
if bad and bad.strip():
|
||||||
|
assert bad not in str(exc.value) # the key value is never part of the message
|
||||||
|
# the same checks apply to the config.ini value
|
||||||
|
with pytest.raises(SecretKeyError):
|
||||||
|
resolve_secret_key(None, "ovpmon-secret-change-me")
|
||||||
|
# legacy variable name is called out explicitly
|
||||||
|
with pytest.raises(SecretKeyError) as exc:
|
||||||
|
resolve_secret_key(None, "", legacy_env=GOOD)
|
||||||
|
assert "OVPMON_SECRET_KEY" in str(exc.value) and "OVPMON_API_SECRET_KEY" in str(exc.value)
|
||||||
|
assert GOOD not in str(exc.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_good_key_and_priority():
|
||||||
|
assert resolve_secret_key(GOOD, None) == (GOOD, "environment")
|
||||||
|
assert resolve_secret_key(None, GOOD) == (GOOD, "config.ini")
|
||||||
|
# environment wins over config.ini, even when the config.ini value is the old default
|
||||||
|
assert resolve_secret_key(GOOD, "ovpmon-secret-change-me") == (GOOD, "environment")
|
||||||
@@ -19,6 +19,9 @@ python3 -m venv venv
|
|||||||
source venv/bin/activate
|
source venv/bin/activate
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# JWT key (required, no built-in default; at least 32 characters). Must be the same value as for APP_CORE
|
||||||
|
export OVPMON_API_SECRET_KEY=$(openssl rand -hex 32)
|
||||||
|
|
||||||
# Run
|
# Run
|
||||||
python3 main.py
|
python3 main.py
|
||||||
# Swagger UI available at http://localhost:8000/docs
|
# Swagger UI available at http://localhost:8000/docs
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
[api]
|
[api]
|
||||||
# Secret key for JWT token verification.
|
# Secret key for JWT token verification.
|
||||||
# MUST match the key in APP_CORE/config.ini if not overridden by ENV.
|
# MUST match the key of APP_CORE (same OVPMON_API_SECRET_KEY or the same value in its config.ini).
|
||||||
secret_key = ovpmon-secret-change-me
|
# Set OVPMON_API_SECRET_KEY or this value; at least 32 characters, random (openssl rand -hex 32). There is no built-in default.
|
||||||
|
secret_key =
|
||||||
|
|
||||||
[profiler]
|
[profiler]
|
||||||
# Path to the profiler database relative to component root
|
# Path to the profiler database relative to component root
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
# utils.auth refuses to import without a strong JWT key (no built-in default), and tests import
|
||||||
|
# main: give them a throwaway key before anything is imported. A real key in the environment is
|
||||||
|
# left untouched.
|
||||||
|
os.environ.setdefault("OVPMON_API_SECRET_KEY", "x" * 64)
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import importlib
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from utils.secret_key import resolve_secret_key, SecretKeyError
|
||||||
|
|
||||||
|
GOOD = "0123456789abcdef" * 4 # 64 hex characters
|
||||||
|
|
||||||
|
|
||||||
|
def test_weak_or_missing_key_is_refused():
|
||||||
|
for bad in (None, "", " ", "ovpmon-secret-change-me", "Change-Me-Please", "k" * 31):
|
||||||
|
with pytest.raises(SecretKeyError) as exc:
|
||||||
|
resolve_secret_key(bad, None)
|
||||||
|
assert "openssl rand -hex 32" in str(exc.value)
|
||||||
|
if bad and bad.strip():
|
||||||
|
assert bad not in str(exc.value) # the key value is never part of the message
|
||||||
|
# the same checks apply to the config.ini value
|
||||||
|
with pytest.raises(SecretKeyError):
|
||||||
|
resolve_secret_key(None, "ovpmon-secret-change-me")
|
||||||
|
# legacy variable name is called out explicitly
|
||||||
|
with pytest.raises(SecretKeyError) as exc:
|
||||||
|
resolve_secret_key(None, "", legacy_env=GOOD)
|
||||||
|
assert "OVPMON_SECRET_KEY" in str(exc.value) and "OVPMON_API_SECRET_KEY" in str(exc.value)
|
||||||
|
assert GOOD not in str(exc.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_good_key_and_priority():
|
||||||
|
assert resolve_secret_key(GOOD, None) == (GOOD, "environment")
|
||||||
|
assert resolve_secret_key(None, GOOD) == (GOOD, "config.ini")
|
||||||
|
# environment wins over config.ini, even when the config.ini value is the old default
|
||||||
|
assert resolve_secret_key(GOOD, "ovpmon-secret-change-me") == (GOOD, "environment")
|
||||||
|
|
||||||
|
|
||||||
|
def test_auth_import_fails_closed(monkeypatch):
|
||||||
|
# Fresh import each time; the original module is restored in sys.modules after the test
|
||||||
|
monkeypatch.delitem(sys.modules, "utils.auth", raising=False)
|
||||||
|
monkeypatch.setenv("OVPMON_API_SECRET_KEY", "ovpmon-secret-change-me")
|
||||||
|
with pytest.raises(SystemExit) as exc:
|
||||||
|
importlib.import_module("utils.auth")
|
||||||
|
assert exc.value.code == 1
|
||||||
|
|
||||||
|
monkeypatch.delitem(sys.modules, "utils.auth", raising=False)
|
||||||
|
monkeypatch.setenv("OVPMON_API_SECRET_KEY", GOOD)
|
||||||
|
assert importlib.import_module("utils.auth").SECRET_KEY == GOOD
|
||||||
+18
-16
@@ -1,29 +1,31 @@
|
|||||||
import jwt
|
import jwt
|
||||||
import configparser
|
import logging
|
||||||
import os
|
import os
|
||||||
from fastapi import Header, HTTPException, status
|
from fastapi import Header, HTTPException, status
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from .config import get_config_value
|
from .config import get_config_value
|
||||||
|
from .secret_key import resolve_secret_key, SecretKeyError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def get_secret_key():
|
def get_secret_key():
|
||||||
# Use consistent OVPMON_API_SECRET_KEY as primary source
|
"""JWT signing key: OVPMON_API_SECRET_KEY, else [api] secret_key of config.ini. No built-in default."""
|
||||||
key = get_config_value('api', 'secret_key', fallback='ovpmon-secret-change-me')
|
try:
|
||||||
|
# get_config_value returns the environment value first, then the config.ini value
|
||||||
if key == 'ovpmon-secret-change-me':
|
key, source = resolve_secret_key(
|
||||||
print("[AUTH] WARNING: Using default fallback SECRET_KEY")
|
os.getenv('OVPMON_API_SECRET_KEY'),
|
||||||
else:
|
get_config_value('api', 'secret_key'),
|
||||||
# Check if it was from env (get_config_value prioritizes env)
|
os.getenv('OVPMON_SECRET_KEY'))
|
||||||
import os
|
except SecretKeyError as e:
|
||||||
if os.getenv('OVPMON_API_SECRET_KEY'):
|
logger.critical(f"Refusing to start: {e}")
|
||||||
print("[AUTH] Using SECRET_KEY from OVPMON_API_SECRET_KEY environment variable")
|
raise SystemExit(1)
|
||||||
elif os.getenv('OVPMON_SECRET_KEY'):
|
logger.info(f"JWT secret key loaded from {source}")
|
||||||
print("[AUTH] Using SECRET_KEY from OVPMON_SECRET_KEY environment variable")
|
|
||||||
else:
|
|
||||||
print("[AUTH] SECRET_KEY loaded (config.ini or fallback)")
|
|
||||||
|
|
||||||
return key
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
# Fails the import (and so the uvicorn start, exit code 1) when the key is missing or weak
|
||||||
SECRET_KEY = get_secret_key()
|
SECRET_KEY = get_secret_key()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""JWT signing key rule (fail closed). Identical copy lives in APP_CORE/secret_key.py."""
|
||||||
|
|
||||||
|
ENV_NAME = "OVPMON_API_SECRET_KEY"
|
||||||
|
LEGACY_ENV_NAME = "OVPMON_SECRET_KEY"
|
||||||
|
DEFAULT_KEY = "ovpmon-secret-change-me"
|
||||||
|
MIN_LENGTH = 32
|
||||||
|
|
||||||
|
HOW_TO_FIX = f"Generate one with: openssl rand -hex 32, and set it in {ENV_NAME} (or [api] secret_key in config.ini)."
|
||||||
|
|
||||||
|
|
||||||
|
class SecretKeyError(Exception):
|
||||||
|
"""The signing key is missing or weak. The message never contains the key value."""
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_secret_key(env, ini_value, legacy_env=None):
|
||||||
|
"""Return (key, source) where source is "environment" or "config.ini".
|
||||||
|
|
||||||
|
env: value of OVPMON_API_SECRET_KEY (or None); ini_value: [api] secret_key (or None);
|
||||||
|
legacy_env: value of OVPMON_SECRET_KEY (not used by the application, only for the hint).
|
||||||
|
Priority: environment > config.ini. Raises SecretKeyError; does not log or exit.
|
||||||
|
"""
|
||||||
|
if env is not None:
|
||||||
|
key, source = env, f"environment variable {ENV_NAME}"
|
||||||
|
result_source = "environment"
|
||||||
|
else:
|
||||||
|
key, source = ini_value, "[api] secret_key in config.ini"
|
||||||
|
result_source = "config.ini"
|
||||||
|
|
||||||
|
if key is None or not key.strip():
|
||||||
|
msg = f"JWT secret key is not set (checked {ENV_NAME} and [api] secret_key in config.ini)."
|
||||||
|
if legacy_env is not None and legacy_env.strip():
|
||||||
|
msg += (f" {LEGACY_ENV_NAME} is set but is not used by the application: "
|
||||||
|
f"rename it to {ENV_NAME}.")
|
||||||
|
raise SecretKeyError(f"{msg} {HOW_TO_FIX}")
|
||||||
|
|
||||||
|
lowered = key.strip().lower()
|
||||||
|
if lowered == DEFAULT_KEY or "change-me" in lowered or "changeme" in lowered:
|
||||||
|
raise SecretKeyError(f"JWT secret key from {source} is a placeholder/default value. {HOW_TO_FIX}")
|
||||||
|
if len(key) < MIN_LENGTH:
|
||||||
|
raise SecretKeyError(f"JWT secret key from {source} is too short "
|
||||||
|
f"({len(key)} characters, at least {MIN_LENGTH} required). {HOW_TO_FIX}")
|
||||||
|
return key, result_source
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,17 @@
|
|||||||
|
# Deployment records: ENTRY on Timeweb with a Hysteria2 chain
|
||||||
|
|
||||||
|
Records of **one concrete deployment**: the OpenVPN Monitor on an Alpine host at Timeweb ("ENTRY") whose VPN clients leave the internet through a Hysteria2 tunnel to an exit node ("EXIT", Debian, Gcore). Host addresses, the account name and the certificate fingerprint appear in these files; no passwords or keys are stored.
|
||||||
|
|
||||||
|
**This folder is not part of the product documentation.** To install the application use [DOCS/Deployment](../../DOCS/Deployment/README.md). Nothing in `DOCS/` depends on these files, and you do not need Hysteria2 to run the application.
|
||||||
|
|
||||||
|
| Document | Content |
|
||||||
|
|---|---|
|
||||||
|
| [Hysteria_Chain_Manifest.md](Hysteria_Chain_Manifest.md) | The entry-exit chain: prerequisites, EXIT and ENTRY setup, clients, diagnostics, error table |
|
||||||
|
| [Egress_via_Hysteria2.md](Egress_via_Hysteria2.md) | Routing the OpenVPN client network through the `hytun` tunnel (policy routing, anti-leak) |
|
||||||
|
| [SUMMARY-ovpn-monitor.md](SUMMARY-ovpn-monitor.md) | State of the host, access, install, security findings and fixes, open items (Russian) |
|
||||||
|
| [REBOOT-TEST.md](REBOOT-TEST.md) | Reboot tests of both nodes |
|
||||||
|
| [PLAN-validation-and-privilege-drop.md](PLAN-validation-and-privilege-drop.md) | Plan: settings validation and running the APIs unprivileged (Russian) |
|
||||||
|
| [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 |
|
||||||
|
|
||||||
|
The product-side description of the same changes is in [DOCS/Changes](../../DOCS/Changes/README.md) (settings validation, privilege separation).
|
||||||
File renamed without changes.
File renamed without changes.
@@ -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`).
|
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`.
|
||||||
@@ -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,6 +1,6 @@
|
|||||||
# nftables script for system-service installs: summary (2026-10-05)
|
# 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
|
## Done
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Scenario 1: containers, variants A and B (2026-10-05)
|
# 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
|
## What was added
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Scenario 2: system services, Alpine, Debian, Ubuntu (2026-10-05)
|
# 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
|
## What was added
|
||||||
|
|
||||||
|
|||||||
@@ -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) |
|
||||||
@@ -214,6 +214,10 @@ Real-time list of currently connected clients.
|
|||||||
|
|
||||||
### `GET /sessions`
|
### `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
|
#### Example Response
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,13 +8,29 @@ The gatherer runs a continuous loop (default interval: **10 seconds**).
|
|||||||
|
|
||||||
### A. Log Parsing
|
### A. Log Parsing
|
||||||
- **Source**: `/var/log/openvpn/openvpn-status.log` (Status File v2, CSV format).
|
- **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`.
|
- **Filtering**: Only lines starting with `CLIENT_LIST`.
|
||||||
|
|
||||||
### B. Delta Calculation (`update_client_status_and_bytes`)
|
### 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.
|
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.
|
||||||
- **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.
|
| 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
|
### C. Rate Calculation
|
||||||
- **Speed**: Calculated as `Increment * 8 / (Interval * 1_000_000)` to get **Mbps**.
|
- **Speed**: Calculated as `Increment * 8 / (Interval * 1_000_000)` to get **Mbps**.
|
||||||
|
|||||||
@@ -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).
|
||||||
@@ -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)
|
||||||
@@ -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.
|
||||||
@@ -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).
|
||||||
@@ -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) |
|
||||||
@@ -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` |
|
||||||
File renamed without changes.
@@ -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 |
|
||||||
@@ -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).
|
||||||
+3
-3
@@ -1,6 +1,6 @@
|
|||||||
# Service Setup Guide
|
# 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 |
|
| 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
|
## 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/`).
|
- 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 (systemd): [`systemd/ovpmon-*.service`](systemd) in `/etc/systemd/system/` (`User=ovpmon`, `EnvironmentFile=/etc/ovpmon/env`, moderate hardening, log in the journal).
|
- 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.
|
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.
|
||||||
@@ -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).
|
||||||
@@ -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.
|
||||||
@@ -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.
|
|
||||||
@@ -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
|
|
||||||
```
|
|
||||||
@@ -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).
|
|
||||||
@@ -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.
|
|
||||||
@@ -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)
|
||||||
@@ -18,15 +18,15 @@ This includes:
|
|||||||
## Proposed Changes
|
## Proposed Changes
|
||||||
|
|
||||||
### Backend (Python/Flask)
|
### 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`).
|
- 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:
|
- Update `init_database` to create:
|
||||||
- `users` table: `id`, `username`, `password_hash`, `totp_secret`, `is_2fa_enabled`.
|
- `users` table: `id`, `username`, `password_hash`, `totp_secret`, `is_2fa_enabled`.
|
||||||
- `login_attempts` table (for brute-force protection): `ip_address`, `attempts`, `last_attempt`.
|
- `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`.
|
- **New Imports**: `jwt`, `pyotp`, `functools.wraps`.
|
||||||
- **Helper Functions**:
|
- **Helper Functions**:
|
||||||
- `check_rate_limit(ip)`: Verify login attempts.
|
- `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/setup-2fa`: Generate secret & QR code.
|
||||||
- `POST /api/auth/enable-2fa`: Confirm and save secret.
|
- `POST /api/auth/enable-2fa`: Confirm and save secret.
|
||||||
- **Protect Routes**: Apply `@token_required` to all existing API routes (except auth).
|
- **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)
|
### 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).
|
- Login form (Username/Password).
|
||||||
- 2FA Input (conditional, appears if server responses "2FA required").
|
- 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.
|
- 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 `/login` route.
|
||||||
- Add global `beforeEach` guard:
|
- Add global `beforeEach` guard:
|
||||||
- Check if route `requiresAuth`.
|
- Check if route `requiresAuth`.
|
||||||
- Check if token exists in `localStorage`.
|
- Check if token exists in `localStorage`.
|
||||||
- Redirect to `/login` if unauthorized.
|
- 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.
|
- Add `Logout` button to the sidebar.
|
||||||
- Conditionally render Sidebar only if logged in (optional, or just redirect).
|
- 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:
|
- Setup `axios` interceptors:
|
||||||
- **Request**: Add `Authorization: Bearer <token>`.
|
- **Request**: Add `Authorization: Bearer <token>`.
|
||||||
- **Response**: On `401 Unauthorized`, clear token and redirect to `/login`.
|
- **Response**: On `401 Unauthorized`, clear token and redirect to `/login`.
|
||||||
|
|||||||
@@ -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`.
|
`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).
|
||||||
@@ -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 |
|
|
||||||
@@ -19,7 +19,7 @@ A modern, Python-based REST API for managing OpenVPN servers, Public Key Infrast
|
|||||||
|
|
||||||
### Usage
|
### 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`
|
* **Swagger UI**: `http://<your-server>:8000/docs`
|
||||||
* **ReDoc**: `http://<your-server>:8000/redoc`
|
* **ReDoc**: `http://<your-server>:8000/redoc`
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -32,4 +32,4 @@ The UI is served by Nginx in production and proxies API requests to:
|
|||||||
- `/api/v1/` -> **APP_CORE** (Flask, Port 5000)
|
- `/api/v1/` -> **APP_CORE** (Flask, Port 5000)
|
||||||
- `/profiles-api/` -> **APP_PROFILER** (FastAPI, Port 8000)
|
- `/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`.
|
||||||
@@ -1,77 +1,59 @@
|
|||||||
# OpenVPN Monitor & Profiler
|
# OpenVPN Monitor & Profiler
|
||||||
|
|
||||||
Web suite for OpenVPN servers: real-time traffic monitoring, history/analytics, PKI and client-profile management, one UI.
|
Web suite for OpenVPN servers: real-time traffic monitoring, history and analytics, PKI and client-profile management, one UI.
|
||||||
|
|
||||||
| Component | Dir | Stack | Default port |
|
| Component | Dir | Stack | Port |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| UI | `APP_UI/` | Vue 3 + Vite, served by Nginx | 80 (Docker) / 8088 (native, TLS) |
|
| UI | `APP_UI/` | Vue 3 + Vite, served by Nginx | 80 (containers) / 8088 (system services, HTTPS) |
|
||||||
| Monitoring API | `APP_CORE/` | Flask (gunicorn) | 5001 (internal) |
|
| Monitoring API + data gatherer | `APP_CORE/` | Flask (gunicorn), Python daemon | 5001, internal |
|
||||||
| Data gatherer | `APP_CORE/` | Python daemon | - |
|
| Profiler API | `APP_PROFILER/` | FastAPI (uvicorn) | 8000, internal |
|
||||||
| Profiler API | `APP_PROFILER/` | FastAPI (uvicorn) | 8000 (internal) |
|
|
||||||
|
|
||||||
Nginx is the only public entry point: `/` UI, `/api/` Monitoring API, `/profiles-api/` Profiler API.
|
Nginx is the only public entry point. More: [Overview](DOCS/General/Overview.md).
|
||||||
|
|
||||||
## Quick start
|
## Get it running
|
||||||
|
|
||||||
- **Containers:** `deploy/docker/install.sh --variant a|b`, open `http://<host>`. Details: [Scenario 1: containers](DOCS/Deployment/Scenario1_Containers.md) (update, backup, rollback included).
|
1. **Pick a method** ([comparison](DOCS/Deployment/README.md)), clone the repository on the host and run one command as root:
|
||||||
- **System services** (Alpine/OpenRC, Debian and Ubuntu/systemd, no containers): `deploy/native/install.sh --prefix DIR` (the install directory is always asked for; the checkout is only the source; the web UI is installed from `deploy/ui-dist` of the repository); details, update and rollback: [Scenario 2: system services](DOCS/Deployment/Scenario2_System_Services.md).
|
|
||||||
- **NAT, MSS and TTL for the VPN clients** (nftables, optional): `deploy/native/firewall.sh [--dry-run]` reads the interfaces of the server and sets masquerade, TCP MSS clamping and TTL for traffic from the VPN network to all other networks; see [Firewall, NAT and forwarding](DOCS/Deployment/Scenario2_System_Services.md#firewall-nat-and-forwarding).
|
|
||||||
|
|
||||||
After the first start: sign in, open **PKI Configuration** → **Initialize PKI**, generate the server config, start OpenVPN, create profiles.
|
| Method | Command | Guide |
|
||||||
|
|---|---|---|
|
||||||
|
| Containers (Docker) | `deploy/docker/install.sh --variant a` (`b` = one container per component) | [Containers](DOCS/Deployment/Containers/README.md) |
|
||||||
|
| System services (Alpine, Debian, Ubuntu) | `deploy/native/install.sh --prefix /opt/OpenVPN-Monitoring-Simple` | [System services](DOCS/Deployment/System_Services/README.md) |
|
||||||
|
|
||||||
## First login and credentials
|
Not sure? Docker on the host: containers, variant A. Otherwise: system services.
|
||||||
|
2. The script prints the URL and the **administrator password once** (no default account exists).
|
||||||
|
3. Follow [First steps](DOCS/Deployment/First_Steps.md): secure the account, initialize the PKI, configure and start the VPN server, create the first client.
|
||||||
|
|
||||||
No default user is created. Seed the initial admin with `OVPMON_INITIAL_ADMIN_USER` / `OVPMON_INITIAL_ADMIN_PASSWORD` on first start (empty `users` table only), then remove them. Change the username and password and enable 2FA in **Account**.
|
Optional: NAT, MSS clamping and TTL for the VPN clients on system-service hosts: `deploy/native/firewall.sh --dry-run` ([Firewall](DOCS/Deployment/System_Services/Firewall.md)).
|
||||||
|
|
||||||
## Security defaults
|
|
||||||
|
|
||||||
- No built-in account; the username can be changed in **Account** (API `POST /api/auth/change-username`).
|
|
||||||
- All API routes require a JWT; 2FA-pending tokens are accepted only by `/api/auth/verify-2fa`.
|
|
||||||
- Server/PKI settings are validated before they reach `server.conf` (ports, networks, routes, DNS, host names, script paths, DN fields); scripts run only from `/etc/openvpn/scripts/`.
|
|
||||||
- Native deployments: APIs run as user `ovpmon`; a root helper installs the validated `server.conf`, publishes the CRL (`crl_verify`) and controls `openvpn` through `doas` (fixed commands).
|
|
||||||
- CORS is same-origin only unless `OVPMON_CORS_ORIGINS` is set; TLS on the panel port; brute-force limits on login (Nginx + app, fail2ban jail in the deployment guide).
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
`config.ini` per component; overridden by `OVPMON_{SECTION}_{KEY}` environment variables.
|
|
||||||
|
|
||||||
| Variable | Purpose |
|
|
||||||
|---|---|
|
|
||||||
| `OVPMON_API_SECRET_KEY` | JWT secret shared by both APIs (**must be random**) |
|
|
||||||
| `OVPMON_INITIAL_ADMIN_USER` / `_PASSWORD` | One-time admin seed |
|
|
||||||
| `OVPMON_CORS_ORIGINS` | Extra allowed CORS origins, comma-separated (empty = same-origin only) |
|
|
||||||
| `OVPMON_OPENVPN_MONITOR_DB_PATH` | Monitoring DB |
|
|
||||||
| `OVPMON_PROFILER_DB_PATH` | Profiler DB |
|
|
||||||
| `OVPMON_OPENVPN_MONITOR_LOG_PATH` | `openvpn-status.log` path |
|
|
||||||
| `OVPMON_LOGGING_LEVEL` | `INFO` / `DEBUG` |
|
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
- Index: [DOCS/General/Index.md](DOCS/General/Index.md)
|
| Level | Where |
|
||||||
- Deployment: [Docker](DOCS/General/Deployment_Docker.md) · [System services](DOCS/General/Deployment_Native.md) · [Nginx](DOCS/General/Nginx_Configuration.md) · [Service management](DOCS/General/Service_Management.md)
|
|---|---|
|
||||||
- Deployment records (state, results, reboot test, plans): [DOCS/Operations](DOCS/Operations/README.md)
|
| General information | [Overview](DOCS/General/Overview.md) · [Configuration](DOCS/General/Configuration.md) · [Security architecture](DOCS/General/Security_Architecture.md) · [Database migrations](DOCS/General/Database_Migrations.md) |
|
||||||
- Security model: [Security Architecture](DOCS/General/Security_Architecture.md) · root helper and doas rules: [`DOCS/General/privilege-separation/`](DOCS/General/privilege-separation/)
|
| Installation methods | [Choose a method](DOCS/Deployment/README.md) · [First steps](DOCS/Deployment/First_Steps.md) |
|
||||||
- APIs: [Monitoring](DOCS/Core_Monitoring/API_Reference.md) · [Profiler](DOCS/Profiler_Management/API_Reference.md)
|
| Details per method | [Containers](DOCS/Deployment/Containers/README.md) (operations, reference, troubleshooting) · [System services](DOCS/Deployment/System_Services/README.md) (operations, reference, web UI, firewall, nginx, troubleshooting) |
|
||||||
|
| APIs | [Monitoring](DOCS/Core_Monitoring/API_Reference.md) · [Profiler](DOCS/Profiler_Management/API_Reference.md) · [UI](DOCS/UI/Architecture.md) |
|
||||||
|
| Changes | [Changes and results](DOCS/Changes/README.md) |
|
||||||
|
| Code review | [DOCS/code_review/](DOCS/code_review/2026-10-05_1607Z_Codebase_Analysis.md) (state of the code, risks, recommendations; time-stamped) |
|
||||||
|
|
||||||
## Changes and results
|
The full map: [DOCS/README.md](DOCS/README.md).
|
||||||
|
|
||||||
| Date | Change | Document |
|
## Security defaults
|
||||||
|---|---|---|
|
|
||||||
| 2026-09-30 | Security hardening: path traversal, 2FA token bypass, CORS, log leak, HTTPS, SSH, fail2ban | [Security hardening](DOCS/Changes/2026-09-30_Security_Hardening.md) |
|
|
||||||
| 2026-09-30 | Admin username change (API + UI), no built-in default admin | [Admin username change](DOCS/Changes/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](DOCS/Changes/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](DOCS/Changes/2026-09-30_Privilege_Separation.md) (includes CRL publishing for `crl_verify`) |
|
|
||||||
| 2026-09-30 | Route OpenVPN clients through a Hysteria2 tunnel to an exit node | [Egress via Hysteria2](DOCS/Changes/2026-09-30_Egress_via_Hysteria2.md) |
|
|
||||||
| 2026-10-04 | Certificates page: clickable rows, profile details modal with a saved note (`PUT /profiles/{id}/note`) | [Profile notes](DOCS/Changes/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](DOCS/Changes/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](DOCS/Changes/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](DOCS/Changes/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](DOCS/Changes/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 | [Scenario 1: containers](DOCS/Deployment/Scenario1_Containers.md) · [change](DOCS/Changes/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 | [Scenario 2: system services](DOCS/Deployment/Scenario2_System_Services.md) · [change](DOCS/Changes/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](DOCS/Deployment/Scenario2_System_Services.md#firewall-nat-and-forwarding) · [plan](DOCS/Changes/2026-10-05_NFT_Firewall_PLAN.md) · [change](DOCS/Changes/2026-10-05_NFT_Firewall.md) |
|
|
||||||
|
|
||||||
## Notes
|
- No built-in account; the first administrator is seeded once at install time. Change the username and password and enable 2FA in **Account Settings**.
|
||||||
|
- No default signing key: both APIs refuse to start without a random `OVPMON_API_SECRET_KEY` of at least 32 characters (installers generate one).
|
||||||
|
- All API routes require a JWT; server and PKI settings are validated before they reach `server.conf`.
|
||||||
|
- System-service installs: the APIs run as the unprivileged user `ovpmon`; a root helper (`doas`, fixed commands) installs the validated `server.conf` and controls OpenVPN.
|
||||||
|
- CORS is same-origin only unless `OVPMON_CORS_ORIGINS` is set; brute-force limits on login.
|
||||||
|
|
||||||
- Native deployments run the APIs as user `ovpmon`; OpenVPN config install and service control go through a root helper (`doas`, fixed commands): see [Privilege separation](DOCS/Changes/2026-09-30_Privilege_Separation.md).
|
Keep `easy-rsa/`, `client-config/`, databases and `*.env` out of git: they contain private keys and secrets.
|
||||||
- Keep `easy-rsa/`, `client-config/`, databases and `*.env` out of git: they contain private keys and secrets.
|
|
||||||
|
## Repository layout
|
||||||
|
|
||||||
|
| Path | Content |
|
||||||
|
|---|---|
|
||||||
|
| `APP_UI/`, `APP_CORE/`, `APP_PROFILER/` | the three components (each has its own short README for development) |
|
||||||
|
| `deploy/docker/`, `deploy/allinone/`, `docker-compose*.yml` | container installation |
|
||||||
|
| `deploy/native/`, `deploy/ui-dist/` | system-service installation and the ready web UI build |
|
||||||
|
| `DOCS/` | documentation |
|
||||||
|
| `DEPLOYMENTS/` | records of one concrete site (not product documentation) |
|
||||||
@@ -18,6 +18,17 @@ if [ -z "${OVPMON_API_SECRET_KEY:-}" ] && [ -n "${JWT_SECRET:-}" ]; then
|
|||||||
fi
|
fi
|
||||||
[ -n "${OVPMON_API_SECRET_KEY:-}" ] || die "JWT_SECRET (or OVPMON_API_SECRET_KEY) is not set. Generate one: openssl rand -hex 32"
|
[ -n "${OVPMON_API_SECRET_KEY:-}" ] || die "JWT_SECRET (or OVPMON_API_SECRET_KEY) is not set. Generate one: openssl rand -hex 32"
|
||||||
export OVPMON_API_SECRET_KEY
|
export OVPMON_API_SECRET_KEY
|
||||||
|
# Key rule (same as APP_CORE/secret_key.py; lib.sh cannot be sourced in the image): no placeholder, at least 32 characters
|
||||||
|
_key_lc=$(printf '%s' "$OVPMON_API_SECRET_KEY" | tr '[:upper:]' '[:lower:]')
|
||||||
|
case "$_key_lc" in
|
||||||
|
*[![:space:]]*) ;;
|
||||||
|
*) die "JWT_SECRET is blank. Generate one: openssl rand -hex 32" ;;
|
||||||
|
esac
|
||||||
|
case "$_key_lc" in
|
||||||
|
*change-me*|*changeme*) die "JWT_SECRET is a placeholder/default value: the API refuses to start with a weak signing key. Generate one: openssl rand -hex 32" ;;
|
||||||
|
esac
|
||||||
|
[ "${#OVPMON_API_SECRET_KEY}" -ge 32 ] || die "JWT_SECRET is too short (${#OVPMON_API_SECRET_KEY} characters, at least 32 required). Generate one: openssl rand -hex 32"
|
||||||
|
unset _key_lc
|
||||||
|
|
||||||
# Database locations (same defaults as in the image and in docker-compose.allinone.yml)
|
# Database locations (same defaults as in the image and in docker-compose.allinone.yml)
|
||||||
export OVPMON_PROFILER_DB_PATH="${OVPMON_PROFILER_DB_PATH:-/app/db/ovpn_profiler.db}"
|
export OVPMON_PROFILER_DB_PATH="${OVPMON_PROFILER_DB_PATH:-/app/db/ovpn_profiler.db}"
|
||||||
@@ -77,7 +88,7 @@ run_migration() {
|
|||||||
name="$1"; dir="$2"
|
name="$1"; dir="$2"
|
||||||
log "Database migration: $name"
|
log "Database migration: $name"
|
||||||
if ! ( cd "$dir" && python migrate.py ); then
|
if ! ( cd "$dir" && python migrate.py ); then
|
||||||
die "database migration of $name failed (see the report above). Nothing was started. Restore the volumes from the last backup or use the previous image; see DOCS/Deployment/Scenario1_Containers.md"
|
die "database migration of $name failed (see the report above). Nothing was started. Restore the volumes from the last backup or use the previous image; see DOCS/Deployment/Containers/Operations.md"
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
run_migration "profiler" /app/APP_PROFILER
|
run_migration "profiler" /app/APP_PROFILER
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
# Result: backups/<UTC timestamp>/ with <volume>.tar.gz, SHA256SUMS, .env (mode 600), MANIFEST and the
|
# Result: backups/<UTC timestamp>/ with <volume>.tar.gz, SHA256SUMS, .env (mode 600), MANIFEST and the
|
||||||
# recorded image IDs. The directory can be set with OVPMON_BACKUP_DIR. Exit code 0 only if the
|
# recorded image IDs. The directory can be set with OVPMON_BACKUP_DIR. Exit code 0 only if the
|
||||||
# backup was written and verified. Restore: deploy/docker/restore.sh <directory>
|
# backup was written and verified. Restore: deploy/docker/restore.sh <directory>
|
||||||
# See DOCS/Deployment/Scenario1_Containers.md
|
# See DOCS/Deployment/Containers/README.md
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
#
|
#
|
||||||
# Safe to run again: .env is created only if it does not exist, an existing stack is only rebuilt
|
# Safe to run again: .env is created only if it does not exist, an existing stack is only rebuilt
|
||||||
# and started. Variants A and B cannot run on the same host together (same ports and names).
|
# and started. Variants A and B cannot run on the same host together (same ports and names).
|
||||||
# See DOCS/Deployment/Scenario1_Containers.md
|
# See DOCS/Deployment/Containers/README.md
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
|||||||
+25
-1
@@ -201,7 +201,7 @@ resolve_stack() {
|
|||||||
sv=$(state_get OVPMON_VARIANT)
|
sv=$(state_get OVPMON_VARIANT)
|
||||||
sp=$(state_get OVPMON_PROJECT)
|
sp=$(state_get OVPMON_PROJECT)
|
||||||
if [ -n "$sv" ]; then
|
if [ -n "$sv" ]; then
|
||||||
[ -z "${ARG_VARIANT:-}" ] || [ "$ARG_VARIANT" = "$sv" ] || die "--variant $ARG_VARIANT does not match the installed variant '$sv' (state file $STATE_FILE). Switching variants is described in DOCS/Deployment/Scenario1_Containers.md"
|
[ -z "${ARG_VARIANT:-}" ] || [ "$ARG_VARIANT" = "$sv" ] || die "--variant $ARG_VARIANT does not match the installed variant '$sv' (state file $STATE_FILE). Switching variants is described in DOCS/Deployment/Containers/Operations.md"
|
||||||
[ -z "${ARG_PROJECT:-}" ] || [ "$ARG_PROJECT" = "$sp" ] || die "--project $ARG_PROJECT does not match the installed project '$sp' (state file $STATE_FILE)"
|
[ -z "${ARG_PROJECT:-}" ] || [ "$ARG_PROJECT" = "$sp" ] || die "--project $ARG_PROJECT does not match the installed project '$sp' (state file $STATE_FILE)"
|
||||||
PROJECT="$sp"
|
PROJECT="$sp"
|
||||||
set_variant "$sv"
|
set_variant "$sv"
|
||||||
@@ -251,9 +251,33 @@ env_remove_admin() {
|
|||||||
mv "$tmp" "$ENV_FILE"
|
mv "$tmp" "$ENV_FILE"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# secret_problem KEY: JWT key rule (same as APP_CORE/secret_key.py: not empty, no change-me/changeme,
|
||||||
|
# at least 32 characters). Prints the reason (never the key) and returns 1 when the key is not acceptable.
|
||||||
|
# Use it as: if reason=$(secret_problem "$key"); then ...ok...; else ...$reason...; fi (set -e safe)
|
||||||
|
secret_problem() {
|
||||||
|
local _lc
|
||||||
|
case "$1" in
|
||||||
|
*[![:space:]]*) ;;
|
||||||
|
*) printf 'not set or empty'; return 1 ;;
|
||||||
|
esac
|
||||||
|
_lc=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')
|
||||||
|
case "$_lc" in
|
||||||
|
*change-me*|*changeme*) printf 'a placeholder/default value (contains change-me)'; return 1 ;;
|
||||||
|
esac
|
||||||
|
if [ "${#1}" -lt 32 ]; then
|
||||||
|
printf 'too short (%s characters, at least 32 required)' "${#1}"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
check_env_file() {
|
check_env_file() {
|
||||||
|
local _reason
|
||||||
[ -f "$ENV_FILE" ] || die ".env not found at $ENV_FILE (install.sh creates it)"
|
[ -f "$ENV_FILE" ] || die ".env not found at $ENV_FILE (install.sh creates it)"
|
||||||
[ -n "$(env_get JWT_SECRET)" ] || die "JWT_SECRET is empty in $ENV_FILE"
|
[ -n "$(env_get JWT_SECRET)" ] || die "JWT_SECRET is empty in $ENV_FILE"
|
||||||
|
if ! _reason=$(secret_problem "$(env_get JWT_SECRET)"); then
|
||||||
|
die "JWT_SECRET in $ENV_FILE is $_reason: the API refuses to start with a weak signing key. Set a random value of at least 32 characters (for example: openssl rand -hex 32); note that a changed key signs out all users"
|
||||||
|
fi
|
||||||
if [ -n "$(find "$ENV_FILE" \( -perm -040 -o -perm -004 \) 2>/dev/null)" ]; then
|
if [ -n "$(find "$ENV_FILE" \( -perm -040 -o -perm -004 \) 2>/dev/null)" ]; then
|
||||||
warn ".env is readable by other users; fix with: chmod 600 $ENV_FILE"
|
warn ".env is readable by other users; fix with: chmod 600 $ENV_FILE"
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
# first saved to backups/<timestamp>-pre-restore (OVPMON_NO_SAFETY_BACKUP=1 skips it), then each volume
|
# first saved to backups/<timestamp>-pre-restore (OVPMON_NO_SAFETY_BACKUP=1 skips it), then each volume
|
||||||
# is emptied and refilled from its archive. Volumes are never removed. .env is not touched: the copy
|
# is emptied and refilled from its archive. Volumes are never removed. .env is not touched: the copy
|
||||||
# in the backup is only reported. To also go back to the previous images use: update.sh --rollback
|
# in the backup is only reported. To also go back to the previous images use: update.sh --rollback
|
||||||
# See DOCS/Deployment/Scenario1_Containers.md
|
# See DOCS/Deployment/Containers/README.md
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
# 4 STOP, 5 DATABASE MIGRATION (own step, nothing is started yet), 6 START and health check.
|
# 4 STOP, 5 DATABASE MIGRATION (own step, nothing is started yet), 6 START and health check.
|
||||||
# A failure in phases 4-6 triggers an automatic rollback: the volumes are restored from the backup of
|
# A failure in phases 4-6 triggers an automatic rollback: the volumes are restored from the backup of
|
||||||
# this run and the previous images are started. Volumes are never removed.
|
# this run and the previous images are started. Volumes are never removed.
|
||||||
# See DOCS/Deployment/Scenario1_Containers.md and DOCS/General/Database_Migrations.md
|
# See DOCS/Deployment/Containers/README.md and DOCS/General/Database_Migrations.md
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
|||||||
@@ -15,7 +15,7 @@
|
|||||||
# service definitions, nginx site, UI files, doas rules, MANIFEST, SHA256SUMS and COMPLETE (written last).
|
# service definitions, nginx site, UI files, doas rules, MANIFEST, SHA256SUMS and COMPLETE (written last).
|
||||||
# Exit code 0 only if the backup was written and verified. Restore: deploy/native/restore.sh <directory>
|
# Exit code 0 only if the backup was written and verified. Restore: deploy/native/restore.sh <directory>
|
||||||
# The backup holds private keys and password hashes: keep it private and store copies off the host.
|
# The backup holds private keys and password hashes: keep it private and store copies off the host.
|
||||||
# See DOCS/Deployment/Scenario2_System_Services.md
|
# See DOCS/Deployment/System_Services/README.md
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
# the current sources. On the target host, use the build directly or pass the tarball:
|
# the current sources. On the target host, use the build directly or pass the tarball:
|
||||||
# deploy/native/install.sh --ui-dist deploy/native/ui-dist.tar.gz
|
# deploy/native/install.sh --ui-dist deploy/native/ui-dist.tar.gz
|
||||||
# deploy/native/update.sh --ui-dist deploy/native/ui-dist.tar.gz
|
# deploy/native/update.sh --ui-dist deploy/native/ui-dist.tar.gz
|
||||||
# See DOCS/Deployment/Scenario2_System_Services.md
|
# See DOCS/Deployment/System_Services/README.md
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
# Prints fresh, stale or missing. Exit code: 0 fresh, 1 stale (the build is older than the sources: run
|
# Prints fresh, stale or missing. Exit code: 0 fresh, 1 stale (the build is older than the sources: run
|
||||||
# deploy/native/build-ui.sh --publish and commit deploy/ui-dist), 2 missing or not checkable.
|
# deploy/native/build-ui.sh --publish and commit deploy/ui-dist), 2 missing or not checkable.
|
||||||
# Run it before a commit or a release that touches APP_UI. It changes nothing.
|
# Run it before a commit or a release that touches APP_UI. It changes nothing.
|
||||||
# See DOCS/Deployment/Scenario2_System_Services.md
|
# See DOCS/Deployment/System_Services/README.md
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
|||||||
@@ -25,7 +25,7 @@
|
|||||||
# distribution's nftables service are never touched. IPv4 only. The options are not remembered: give them on
|
# distribution's nftables service are never touched. IPv4 only. The options are not remembered: give them on
|
||||||
# every run (e.g. after the VPN subnet was changed in the UI). Persistence: /etc/ovpmon/nftables.nft loaded at
|
# every run (e.g. after the VPN subnet was changed in the UI). Persistence: /etc/ovpmon/nftables.nft loaded at
|
||||||
# boot by the service ovpmon-nft. install.sh and update.sh do not call this script.
|
# boot by the service ovpmon-nft. install.sh and update.sh do not call this script.
|
||||||
# See DOCS/Deployment/Scenario2_System_Services.md
|
# See DOCS/Deployment/System_Services/README.md
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
|||||||
@@ -25,7 +25,7 @@
|
|||||||
# Run as root from a checkout of the repository. Refuses when an installation exists (use update.sh).
|
# Run as root from a checkout of the repository. Refuses when an installation exists (use update.sh).
|
||||||
# After a failure it is safe to run again: every step is idempotent and nothing is generated twice.
|
# After a failure it is safe to run again: every step is idempotent and nothing is generated twice.
|
||||||
# It does NOT touch the firewall: NAT/forwarding commands are printed and documented.
|
# It does NOT touch the firewall: NAT/forwarding commands are printed and documented.
|
||||||
# See DOCS/Deployment/Scenario2_System_Services.md
|
# See DOCS/Deployment/System_Services/README.md
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
||||||
@@ -174,6 +174,12 @@ if [ ! -f "$INCOMPLETE_MARK" ]; then
|
|||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
fi
|
fi
|
||||||
|
# A kept env file (resumed install) must hold a usable JWT key: the APIs refuse to start with a weak one
|
||||||
|
if [ -f "$ENV_FILE" ]; then
|
||||||
|
if ! _reason=$(secret_problem "$(env_get OVPMON_API_SECRET_KEY)"); then
|
||||||
|
die "OVPMON_API_SECRET_KEY in $ENV_FILE is $_reason: the APIs refuse to start with a weak signing key. Set a random value of at least 32 characters (openssl rand -hex 32) and run install.sh again"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
[ -f "$SRC/APP_CORE/openvpn_api_v3.py" ] && [ -f "$SRC/APP_PROFILER/main.py" ] \
|
[ -f "$SRC/APP_CORE/openvpn_api_v3.py" ] && [ -f "$SRC/APP_PROFILER/main.py" ] \
|
||||||
|| die "run the script from a complete checkout of the repository (APP_CORE and APP_PROFILER not found in $SRC)"
|
|| die "run the script from a complete checkout of the repository (APP_CORE and APP_PROFILER not found in $SRC)"
|
||||||
|
|||||||
+21
-1
@@ -363,6 +363,26 @@ kv_set() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
env_get() { kv_get "$ENV_FILE" "$1"; }
|
env_get() { kv_get "$ENV_FILE" "$1"; }
|
||||||
|
|
||||||
|
# secret_problem KEY: JWT key rule (same as APP_CORE/secret_key.py: not empty, no change-me/changeme,
|
||||||
|
# at least 32 characters). Prints the reason (never the key) and returns 1 when the key is not acceptable.
|
||||||
|
# Use it as: if reason=$(secret_problem "$key"); then ...ok...; else ...$reason...; fi (set -e safe)
|
||||||
|
secret_problem() {
|
||||||
|
local _lc
|
||||||
|
case "$1" in
|
||||||
|
*[![:space:]]*) ;;
|
||||||
|
*) printf 'not set or empty'; return 1 ;;
|
||||||
|
esac
|
||||||
|
_lc=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')
|
||||||
|
case "$_lc" in
|
||||||
|
*change-me*|*changeme*) printf 'a placeholder/default value (contains change-me)'; return 1 ;;
|
||||||
|
esac
|
||||||
|
if [ "${#1}" -lt 32 ]; then
|
||||||
|
printf 'too short (%s characters, at least 32 required)' "${#1}"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
}
|
||||||
state_get() { kv_get "$STATE_FILE" "$1"; }
|
state_get() { kv_get "$STATE_FILE" "$1"; }
|
||||||
state_set() { kv_set "$STATE_FILE" "$1" "$2" 644; }
|
state_set() { kv_set "$STATE_FILE" "$1" "$2" 644; }
|
||||||
|
|
||||||
@@ -718,7 +738,7 @@ ensure_runtime_files() {
|
|||||||
# ---- UI: sources, committed build, staging ----
|
# ---- UI: sources, committed build, staging ----
|
||||||
# The UI is part of the repository: deploy/ui-dist holds a build of APP_UI together with SOURCE_HASH, the hash
|
# The UI is part of the repository: deploy/ui-dist holds a build of APP_UI together with SOURCE_HASH, the hash
|
||||||
# of the sources it was built from (ui_source_hash). The installed web root records the hash it came from in
|
# of the sources it was built from (ui_source_hash). The installed web root records the hash it came from in
|
||||||
# $UI_HASH_FILE, so update.sh can tell when the UI changed. See DOCS/Deployment/Scenario2_System_Services.md
|
# $UI_HASH_FILE, so update.sh can tell when the UI changed. See DOCS/Deployment/System_Services/README.md
|
||||||
UI_HASH_FILE=.ui-source-hash
|
UI_HASH_FILE=.ui-source-hash
|
||||||
|
|
||||||
# sha256_run [FILE...]: sha256sum, or shasum -a 256 (macOS); "hash name" lines, stdin when no file is given
|
# sha256_run [FILE...]: sha256sum, or shasum -a 256 (macOS); "hash name" lines, stdin when no file is given
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
# Installed to the nginx include directory (Alpine /etc/nginx/http.d, Debian/Ubuntu /etc/nginx/conf.d),
|
# Installed to the nginx include directory (Alpine /etc/nginx/http.d, Debian/Ubuntu /etc/nginx/conf.d),
|
||||||
# both are included in the http {} block of the distribution nginx.conf. No ssl_session_cache is declared
|
# both are included in the http {} block of the distribution nginx.conf. No ssl_session_cache is declared
|
||||||
# here on purpose: a second "shared:SSL" zone with another size would conflict with nginx.conf.
|
# here on purpose: a second "shared:SSL" zone with another size would conflict with nginx.conf.
|
||||||
# Reference: DOCS/General/Nginx_Configuration.md, APP_UI/default.conf.template
|
# Reference: DOCS/Deployment/System_Services/Nginx_Configuration.md, APP_UI/default.conf.template
|
||||||
|
|
||||||
# 5 login attempts per minute per client address (the application has its own lockout as well)
|
# 5 login attempts per minute per client address (the application has its own lockout as well)
|
||||||
limit_req_zone $binary_remote_addr zone=ovpmon_login:1m rate=5r/m;
|
limit_req_zone $binary_remote_addr zone=ovpmon_login:1m rate=5r/m;
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
# /etc/ovpmon, /etc/openvpn, PKI, client profiles, helper, service definitions, nginx site, UI and doas
|
# /etc/ovpmon, /etc/openvpn, PKI, client profiles, helper, service definitions, nginx site, UI and doas
|
||||||
# rules are put back from the backup. OpenVPN is not touched. The packages and the ovpmon user must
|
# rules are put back from the backup. OpenVPN is not touched. The packages and the ovpmon user must
|
||||||
# exist (on a new host run install.sh first, then restore).
|
# exist (on a new host run install.sh first, then restore).
|
||||||
# See DOCS/Deployment/Scenario2_System_Services.md
|
# See DOCS/Deployment/System_Services/README.md
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
|||||||
+12
-1
@@ -22,7 +22,7 @@
|
|||||||
# started on an unmigrated database), 6 UI, nginx, helper, doas rules, service definitions, 7 START and health
|
# started on an unmigrated database), 6 UI, nginx, helper, doas rules, service definitions, 7 START and health
|
||||||
# checks. A failure after the stop triggers an automatic rollback from the backup of this run.
|
# checks. A failure after the stop triggers an automatic rollback from the backup of this run.
|
||||||
# The PKI (easy-rsa), client profiles and databases are never replaced or deleted by an update.
|
# The PKI (easy-rsa), client profiles and databases are never replaced or deleted by an update.
|
||||||
# See DOCS/Deployment/Scenario2_System_Services.md and DOCS/General/Database_Migrations.md
|
# See DOCS/Deployment/System_Services/README.md and DOCS/General/Database_Migrations.md
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
||||||
@@ -456,6 +456,17 @@ main() {
|
|||||||
done
|
done
|
||||||
svc_defs_reload
|
svc_defs_reload
|
||||||
for _s in $SERVICES; do svc_enable "$_s" || warn "could not enable $_s at boot"; done
|
for _s in $SERVICES; do svc_enable "$_s" || warn "could not enable $_s at boot"; done
|
||||||
|
# JWT key: the APIs refuse to start with a missing or weak key, so one is issued here, before the start.
|
||||||
|
# The env file is part of the backup, a failed update restores the previous one.
|
||||||
|
if ! _reason=$(secret_problem "$(env_get OVPMON_API_SECRET_KEY)"); then
|
||||||
|
_new_key=$(openssl rand -hex 32 2>/dev/null || true)
|
||||||
|
[ "${#_new_key}" -eq 64 ] || _new_key=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')
|
||||||
|
[ "${#_new_key}" -eq 64 ] || die "cannot generate a random JWT key"
|
||||||
|
kv_set "$ENV_FILE" OVPMON_API_SECRET_KEY "$_new_key" 600
|
||||||
|
unset _new_key
|
||||||
|
warn "OVPMON_API_SECRET_KEY in $ENV_FILE was $_reason: a new random key was issued. ALL USER SESSIONS ARE RESET: everyone has to sign in again"
|
||||||
|
CHANGES=$((CHANGES + 1))
|
||||||
|
fi
|
||||||
# environment: add the settings of this version when they are missing (existing values are never changed)
|
# environment: add the settings of this version when they are missing (existing values are never changed)
|
||||||
for _kv in "OVPMON_RUNTIME=host" "OVPMON_OPENVPN_SERVICE=$OVPN_SERVICE" "OVPMON_OPENVPN_CONFIG=$OVPN_CONFIG"; do
|
for _kv in "OVPMON_RUNTIME=host" "OVPMON_OPENVPN_SERVICE=$OVPN_SERVICE" "OVPMON_OPENVPN_CONFIG=$OVPN_CONFIG"; do
|
||||||
_k=${_kv%%=*}
|
_k=${_kv%%=*}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
# First start only: OVPMON_INITIAL_ADMIN_USER / OVPMON_INITIAL_ADMIN_PASSWORD in .env
|
# First start only: OVPMON_INITIAL_ADMIN_USER / OVPMON_INITIAL_ADMIN_PASSWORD in .env
|
||||||
# Optional: OVPMON_CORS_ORIGINS, OVPMON_HTTP_PORT (host port of the UI, default 80),
|
# Optional: OVPMON_CORS_ORIGINS, OVPMON_HTTP_PORT (host port of the UI, default 80),
|
||||||
# OVPMON_VPN_PORT (host UDP port of OpenVPN, default 1194)
|
# OVPMON_VPN_PORT (host UDP port of OpenVPN, default 1194)
|
||||||
# Install/update with the scripts in deploy/docker (see DOCS/Deployment/Scenario1_Containers.md)
|
# Install/update with the scripts in deploy/docker (see DOCS/Deployment/Containers/README.md)
|
||||||
#
|
#
|
||||||
# Variants A (this file) and B (docker-compose.yml) publish the same host ports and use fixed
|
# Variants A (this file) and B (docker-compose.yml) publish the same host ports and use fixed
|
||||||
# container names (ovp-*): run only ONE variant per host. Both use the same five volumes with the
|
# container names (ovp-*): run only ONE variant per host. Both use the same five volumes with the
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
# First start only: OVPMON_INITIAL_ADMIN_USER / OVPMON_INITIAL_ADMIN_PASSWORD in .env
|
# First start only: OVPMON_INITIAL_ADMIN_USER / OVPMON_INITIAL_ADMIN_PASSWORD in .env
|
||||||
# Optional: OVPMON_CORS_ORIGINS (comma-separated origins; off by default, UI is same-origin via Nginx)
|
# Optional: OVPMON_CORS_ORIGINS (comma-separated origins; off by default, UI is same-origin via Nginx)
|
||||||
# Optional: OVPMON_HTTP_PORT (host port of the UI, default 80), OVPMON_VPN_PORT (host UDP port of OpenVPN, default 1194)
|
# Optional: OVPMON_HTTP_PORT (host port of the UI, default 80), OVPMON_VPN_PORT (host UDP port of OpenVPN, default 1194)
|
||||||
# Install/update with the scripts in deploy/docker (see DOCS/Deployment/Scenario1_Containers.md)
|
# Install/update with the scripts in deploy/docker (see DOCS/Deployment/Containers/README.md)
|
||||||
|
|
||||||
x-secret: &jwt-secret
|
x-secret: &jwt-secret
|
||||||
OVPMON_API_SECRET_KEY: ${JWT_SECRET:?JWT_SECRET must be set in .env (openssl rand -hex 32)}
|
OVPMON_API_SECRET_KEY: ${JWT_SECRET:?JWT_SECRET must be set in .env (openssl rand -hex 32)}
|
||||||
|
|||||||
Reference in new issue
Block a user