diff --git a/.graphifyignore b/.graphifyignore new file mode 100644 index 0000000..48cb6df --- /dev/null +++ b/.graphifyignore @@ -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/ diff --git a/APP_CORE/README.md b/APP_CORE/README.md index 47d4d1f..ac4e050 100644 --- a/APP_CORE/README.md +++ b/APP_CORE/README.md @@ -26,6 +26,9 @@ python3 -m venv venv source venv/bin/activate 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 python3 openvpn_api_v3.py diff --git a/APP_CORE/config.ini b/APP_CORE/config.ini index 595e489..733896c 100644 --- a/APP_CORE/config.ini +++ b/APP_CORE/config.ini @@ -2,12 +2,20 @@ host = 0.0.0.0 port = 5001 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] log_path = /var/log/openvpn/openvpn-status.log db_path = openvpn_monitor.db 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] level = INFO diff --git a/APP_CORE/conftest.py b/APP_CORE/conftest.py new file mode 100644 index 0000000..602c725 --- /dev/null +++ b/APP_CORE/conftest.py @@ -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) diff --git a/APP_CORE/openvpn_api_v3.py b/APP_CORE/openvpn_api_v3.py index 01db519..77f7edd 100644 --- a/APP_CORE/openvpn_api_v3.py +++ b/APP_CORE/openvpn_api_v3.py @@ -10,6 +10,7 @@ import pyotp import bcrypt from functools import wraps from db import DatabaseManager +from secret_key import resolve_secret_key, SecretKeyError import io @@ -41,18 +42,27 @@ class OpenVPNAPI: return fallback def __init__(self, config_file='config.ini'): - self.db_manager = DatabaseManager(config_file) - self.db_manager.init_database() self.config = configparser.ConfigParser() 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 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 self.ensure_default_admin() diff --git a/APP_CORE/openvpn_gatherer_v3.py b/APP_CORE/openvpn_gatherer_v3.py index 0e8af92..8f780b4 100644 --- a/APP_CORE/openvpn_gatherer_v3.py +++ b/APP_CORE/openvpn_gatherer_v3.py @@ -1,11 +1,29 @@ import sqlite3 import time import os +import calendar +import signal +import threading import configparser import logging +from collections import namedtuple from datetime import datetime, timedelta 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) --- class TimeSeriesAggregator: def __init__(self, db_provider): @@ -34,24 +52,24 @@ class TimeSeriesAggregator: conn = self.db_provider() cursor = conn.cursor() - + now = datetime.utcnow() - + # --- РАСЧЕТ ВРЕМЕННЫХ КВАНТОВ --- # 1. Сутки (00:00:00) ts_1d = now.replace(hour=0, minute=0, second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:%S') - + # 2. 6 часов (00, 06, 12, 18) hour_6h = now.hour - (now.hour % 6) ts_6h = now.replace(hour=hour_6h, minute=0, second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:%S') - + # 3. 1 час (XX:00:00) ts_1h = now.replace(minute=0, second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:%S') - + # 4. 15 минут (00, 15, 30, 45) min_15m = now.minute - (now.minute % 15) ts_15m = now.replace(minute=min_15m, second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:%S') - + # 5. 5 минут (00, 05, 10...) min_5m = now.minute - (now.minute % 5) ts_5m = now.replace(minute=min_5m, second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:%S') @@ -60,16 +78,16 @@ class TimeSeriesAggregator: updates_count = 0 for client in client_updates: client_id = client.get('db_id') - + # Пропускаем, если ID не определен - if client_id is None: + if client_id is None: continue - + rx = client.get('bytes_received_inc', 0) tx = client.get('bytes_sent_inc', 0) - + # Пропускаем, если нет трафика - if rx == 0 and tx == 0: + if rx == 0 and tx == 0: continue # Запись во все уровни агрегации @@ -78,7 +96,7 @@ class TimeSeriesAggregator: self._upsert_bucket(cursor, 'stats_hourly', ts_1h, client_id, rx, tx) self._upsert_bucket(cursor, 'stats_6h', ts_6h, client_id, rx, tx) self._upsert_bucket(cursor, 'stats_daily', ts_1d, client_id, rx, tx) - + updates_count += 1 conn.commit() @@ -100,24 +118,94 @@ class OpenVPNDataGatherer: self.last_check_time = None # Инициализируем дату последней очистки вчерашним днем для корректного старта 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.init_database() - + # Инициализация модуля агрегации # Передаем ссылку на метод подключения к БД 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 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): """Загрузка конфигурации или создание дефолтной со сложной структурой""" config = configparser.ConfigParser() - + # Полная структура конфига согласно требованиям defaults = { 'api': { @@ -129,6 +217,9 @@ class OpenVPNDataGatherer: 'log_path': '/var/log/openvpn/openvpn-status.log', 'db_path': 'openvpn_monitor.db', 'check_interval': '10', # Интервал 10 секунд + 'session_grace_ticks': '3', # Тиков до удаления пропавшей из статуса сессии + 'status_stale_seconds': '60', # Файл статуса старше этого = OpenVPN остановлен + 'status_invalid_max': '6', # Подряд пропущенных тиков до уровня ERROR в логе }, 'logging': { 'level': 'INFO', @@ -170,7 +261,7 @@ class OpenVPNDataGatherer: with open(config_file, 'w') as f: config.write(f) print(f"Created default configuration file: {config_file}") - + except Exception as e: print(f"Error loading config: {e}") # Fallback в памяти @@ -179,14 +270,14 @@ class OpenVPNDataGatherer: config.add_section(section) for key, val in options.items(): config.set(section, key, val) - + return config - + def setup_logging(self): try: log_level = self.config.get('logging', 'level', fallback='INFO') log_file = self.config.get('logging', 'log_file', fallback='openvpn_gatherer.log') - + # Создаем директорию для логов если нужно log_dir = os.path.dirname(log_file) if log_dir and not os.path.exists(log_dir): @@ -217,17 +308,17 @@ class OpenVPNDataGatherer: return self.config.get(section, key, fallback=default) except: return default - - + + # get_db_connection and init_database removed - - + + def cleanup_old_data(self): """Очистка данных согласно retention policies в config.ini""" self.logger.info("Starting data cleanup procedure...") conn = self.db_manager.get_connection() cursor = conn.cursor() - + # Маппинг: Таблица -> Ключ конфига -> Дефолт (дни) retention_rules = [ ('usage_history', 'raw_retention_days', 7), @@ -249,88 +340,172 @@ class OpenVPNDataGatherer: if deleted > 0: self.logger.info(f"Cleaned {table}: removed {deleted} records older than {days} days") total_deleted += deleted - + conn.commit() if total_deleted == 0: self.logger.info("Cleanup finished: nothing to delete") - + except Exception as e: self.logger.error(f"Cleanup Error: {e}") conn.rollback() finally: conn.close() - - def parse_log_file(self): + + def parse_status(self, path, now=None): """ - Парсинг лога версии 2 (CSV формат). - Ожидает формат: CLIENT_LIST,Common Name,Real Address,...,Bytes Received,Bytes Sent,... + Разбор файла статуса версии 2 (CSV формат) с проверкой целостности и свежести. + Ожидает: TITLE,... / TIME,<текст>, / 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') - clients = [] - + if now is None: + now = self._now() + try: - if not os.path.exists(log_path): - self.logger.warning(f"Log file not found: {log_path}") - return clients - - 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") - + if not os.path.exists(path): + return StatusReading(False, [], False, f"status file not found: {path}") + with open(path, 'r') as file: + lines = [line.strip() for line in file] except Exception as e: - self.logger.error(f"Error parsing log file: {e}") - - return clients - + return StatusReading(False, [], False, f"cannot read status file: {e}") + + 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): """ Обновление статусов и расчет инкрементов трафика. Использует In-Memory Cache (self.session_cache) для корректной обработки множественных сессий одного пользователя (Ping-Pong effect fix). + Изменения кэша накапливаются в new_cache и применяются только после успешного commit: + при откате транзакции кэш остаётся прежним, приращения не теряются. + При ошибке БД откатывает транзакцию и пробрасывает исключение (его обработает цикл). """ conn = self.db_manager.get_connection() cursor = conn.cursor() - + now_ts = self._now() + last_seen_str = datetime.fromtimestamp(now_ts).strftime(TS_FORMAT) + try: # 1. Загружаем текущее состояние CNs из БД для обновления статусов cursor.execute('SELECT id, common_name, status, total_bytes_received, total_bytes_sent FROM clients') db_clients = {row[1]: {'id': row[0], 'status': row[2]} for row in cursor.fetchall()} - + # Структура для агрегации инкрементов по Common Name перед записью в БД # cn -> { 'inc_rx': 0, 'inc_tx': 0, 'curr_rx': 0, 'curr_tx': 0, 'real_address': '...'} cn_updates = {} - - # Множество активных ключей сессий (CN, RealAddr) для очистки кэша - active_session_keys = set() + + # Новое состояние кэша сессий (применяется после commit) и активные CN + new_cache = {} active_cns = set() # 2. Обрабатываем каждую активную сессию @@ -339,67 +514,40 @@ class OpenVPNDataGatherer: real_addr = client['real_address'] curr_recv = client['bytes_received'] curr_sent = client['bytes_sent'] - - # Уникальный ключ сессии - session_key = (name, real_addr) - active_session_keys.add(session_key) + since_ts = client.get('connected_since_ts') + + # Уникальный ключ сессии: один и тот же CN/адрес может переподключиться + # (новый connected_since) - это уже новая сессия + session_key = (name, real_addr, since_ts) active_cns.add(name) - + # --- ЛОГИКА РАСЧЕТА ДЕЛЬТЫ (In-Memory) --- - if session_key in self.session_cache: - prev_state = self.session_cache[session_key] + prev_state = self.session_cache.get(session_key) + if prev_state is not None: prev_recv = prev_state['bytes_received'] prev_sent = prev_state['bytes_sent'] - - # Расчет RX - if curr_recv < prev_recv: - # Рестарт сессии (счетчик сбросился) - inc_recv = curr_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: - inc_sent = curr_sent - self.logger.info(f"Session reset detected for {session_key} (Sent)") - else: - inc_sent = curr_sent - prev_sent - - else: - # Новая сессия (или после рестарта сервиса) - # Если сервиса только запустился, мы не знаем предыдущего состояния. - # Чтобы избежать спайков, считаем инкремент = 0 для первого появления, - # если это похоже на продолжающуюся сессию (большие числа). - # Если числа маленькие (<10MB), считаем как новую. - - # 10 MB threshold - threshold = 10 * 1024 * 1024 - - if curr_recv < threshold and curr_sent < threshold: - inc_recv = curr_recv - inc_sent = curr_sent - 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 - } + if curr_recv < prev_recv: + self.logger.info(f"Session reset detected for {session_key} (Recv)") + if curr_sent < prev_sent: + self.logger.info(f"Session reset detected for {session_key} (Sent)") + inc_recv = self._delta(curr_recv, prev_recv) + inc_sent = self._delta(curr_sent, prev_sent) + connected_since = prev_state['connected_since'] 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() - + # Сессия не в кэше: новая, продолжающаяся после перезапуска или вернувшаяся + inc_recv, inc_sent = self._first_seen_increment(session_key, curr_recv, curr_sent) + # В active_sessions пишем реальное начало сессии (UTC); без time_t - время первого наблюдения + connected_since = time.strftime(TS_FORMAT, time.gmtime(since_ts if since_ts else now_ts)) + + new_cache[session_key] = { + 'bytes_received': curr_recv, + 'bytes_sent': curr_sent, + 'last_seen': last_seen_str, + 'connected_since': connected_since, + 'missing_ticks': 0 + } + # Добавляем в клиентский объект (для истории/графиков) # Важно: это инкремент конкретной сессии client['bytes_received_inc'] = inc_recv @@ -407,15 +555,15 @@ class OpenVPNDataGatherer: # Ensure db_id is available for active_sessions later (populated in step 4 or from cache) # We defer writing to active_sessions until we have DB IDs client['session_key'] = session_key - + # --- АГРЕГАЦИЯ ДЛЯ БД (по Common Name) --- if name not in cn_updates: cn_updates[name] = { - 'inc_recv': 0, 'inc_tx': 0, + 'inc_recv': 0, 'inc_tx': 0, 'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД сохраним текущие счетчики самой большой сессии (примерно) 'real_address': real_addr # Берем последний адрес } - + cn_updates[name]['inc_recv'] += inc_recv cn_updates[name]['inc_tx'] += inc_sent # Сохраняем "текущее" значение как максимальное из сессий, чтобы в БД last_bytes было хоть что-то осмысленное @@ -424,12 +572,16 @@ class OpenVPNDataGatherer: cn_updates[name]['max_tx'] = max(cn_updates[name]['max_tx'], curr_sent) cn_updates[name]['real_address'] = real_addr - # 3. Очистка кэша от мертвых сессий - # Создаем список ключей для удаления, чтобы не менять словарь во время итерации - dead_sessions = [k for k in self.session_cache if k not in active_session_keys] - for k in dead_sessions: - del self.session_cache[k] - self.logger.debug(f"Removed inactive session from cache: {k}") + # 3. Льготный период для сессий, которых нет в текущем статусе: + # запись остаётся в кэше, пока missing_ticks < session_grace_ticks + for key, state in self.session_cache.items(): + if key in new_cache: + continue + 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) for name, data in cn_updates.items(): @@ -437,9 +589,9 @@ class OpenVPNDataGatherer: # UPDATE db_id = db_clients[name]['id'] cursor.execute(''' - UPDATE clients - SET status = 'Active', - real_address = ?, + UPDATE clients + SET status = 'Active', + real_address = ?, total_bytes_received = total_bytes_received + ?, total_bytes_sent = total_bytes_sent + ?, last_bytes_received = ?, @@ -455,22 +607,25 @@ class OpenVPNDataGatherer: data['max_tx'], db_id )) - + # Прокидываем DB ID обратно в объекты клиентов (для TSDB) # Так как active_clients - это список сессий, ищем все сессии этого юзера for client in active_clients: if client['common_name'] == name: client['db_id'] = db_id - + else: - # INSERT (New Client) + # INSERT (New Client): итоги стартуют с прироста первого кадра, а не с нуля + # (иначе трафик первого тика нового клиента не попадал в total_bytes_*) 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) - VALUES (?, ?, 'Active', 0, 0, ?, ?) + VALUES (?, ?, 'Active', ?, ?, ?, ?) ''', ( name, data['real_address'], + data['inc_recv'], + data['inc_tx'], data['max_rx'], data['max_tx'] )) @@ -484,8 +639,8 @@ class OpenVPNDataGatherer: for name, db_info in db_clients.items(): if name not in active_cns and db_info['status'] == 'Active': cursor.execute(''' - UPDATE clients - SET status = 'Disconnected', updated_at = CURRENT_TIMESTAMP + UPDATE clients + SET status = 'Disconnected', updated_at = CURRENT_TIMESTAMP WHERE id = ? ''', (db_info['id'],)) self.logger.info(f"Client disconnected: {name}") @@ -493,15 +648,15 @@ class OpenVPNDataGatherer: # 6. SYNC ACTIVE SESSIONS TO DB (Snapshot) # Clear old state cursor.execute('DELETE FROM active_sessions') - - # Insert current state + + # Insert current state (только сессии, присутствующие в статусе) for client in active_clients: # client['db_id'] should be populated by now (from step 4) 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: cursor.execute(''' - INSERT INTO active_sessions + INSERT INTO active_sessions (client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen) VALUES (?, ?, ?, ?, ?, ?, ?) ''', ( @@ -510,47 +665,58 @@ class OpenVPNDataGatherer: client['real_address'], client['bytes_received'], client['bytes_sent'], - sess_data.get('connected_since', datetime.now()), - sess_data.get('last_seen', datetime.now()) + sess_data['connected_since'], + sess_data['last_seen'] )) conn.commit() - - except Exception as e: - self.logger.error(f"Error updating client status: {e}") + + except Exception: + # Кэш не менялся: приращения не потеряны, следующий тик посчитает разницу за весь интервал conn.rollback() + raise finally: 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 - + def calculate_rates(self, clients, time_diff): """Расчет скорости в Mbps""" if time_diff <= 0: time_diff = 1.0 # Защита от деления на 0 - + # Коэффициент: (байты * 8 бит) / (секунды * 1 млн) factor = 8 / (time_diff * 1_000_000) - + for client in clients: client['bytes_received_rate_mbps'] = client.get('bytes_received_inc', 0) * factor client['bytes_sent_rate_mbps'] = client.get('bytes_sent_inc', 0) * factor - + return clients - + def store_usage_history(self, clients): """Сохранение высокодетализированной (Raw) истории""" if not clients: return - + conn = self.db_manager.get_connection() cursor = conn.cursor() - + try: for client in clients: if client.get('db_id'): cursor.execute(''' - INSERT INTO usage_history + INSERT INTO usage_history (client_id, bytes_received, bytes_sent, bytes_received_rate_mbps, bytes_sent_rate_mbps) VALUES (?, ?, ?, ?, ?) ''', ( @@ -560,62 +726,97 @@ class OpenVPNDataGatherer: client.get('bytes_received_rate_mbps', 0), client.get('bytes_sent_rate_mbps', 0) )) - + conn.commit() except Exception as e: self.logger.error(f"Error storing raw history: {e}") conn.rollback() finally: conn.close() - + def run_monitoring_cycle(self): """Один цикл мониторинга""" current_time = datetime.now() - - # 1. Получаем активных клиентов - active_clients = self.parse_log_file() - - # 2. Обновляем статусы и считаем дельту трафика - clients_with_updates = self.update_client_status_and_bytes(active_clients) - - if clients_with_updates: - # 3. Считаем интервал времени - time_diff = 10.0 # Номинал - if self.last_check_time: - time_diff = (current_time - self.last_check_time).total_seconds() - - # 4. Считаем скорости - clients_rated = self.calculate_rates(clients_with_updates, time_diff) - - # 5. Сохраняем RAW историю (для графиков реального времени) - self.store_usage_history(clients_rated) - - # 6. Агрегируем в TSDB (5m, 15m, 1h, 6h, 1d) - self.ts_aggregator.aggregate(clients_rated) - - self.last_check_time = current_time - + + # 1. Читаем файл статуса (с проверкой целостности и свежести) + reading = self.parse_log_file() + + if not reading.valid: + # Рваное чтение / нет файла: тик пропускаем целиком, БД и кэш не трогаем. + # 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) + + # 2. Обновляем статусы и считаем дельту трафика + clients_with_updates = self.update_client_status_and_bytes(reading.clients) + + if clients_with_updates: + # 3. Считаем интервал времени + time_diff = 10.0 # Номинал + if self.last_check_time: + time_diff = (current_time - self.last_check_time).total_seconds() + + # 4. Считаем скорости + clients_rated = self.calculate_rates(clients_with_updates, time_diff) + + # 5. Сохраняем RAW историю (для графиков реального времени) + self.store_usage_history(clients_rated) + + # 6. Агрегируем в TSDB (5m, 15m, 1h, 6h, 1d) + self.ts_aggregator.aggregate(clients_rated) + + self.last_check_time = current_time + # 7. Проверка необходимости очистки (раз в сутки) if current_time.date() > self.last_cleanup_date: self.logger.info("New day detected. Initiating cleanup.") self.cleanup_old_data() 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): - """Запуск цикла""" - interval = int(self.get_config_value('openvpn_monitor', 'check_interval', 10)) + """Запуск цикла. Цикл переживает любые исключения; остановка по SIGTERM/SIGINT штатная.""" + interval = self.interval self.logger.info(f"Starting OpenVPN Monitoring. Interval: {interval}s") self.logger.info("Press Ctrl+C to stop") - + + # Обработчики сигналов ставятся только в главном потоке; прежние восстанавливаем при выходе + previous = {} try: - while True: - self.run_monitoring_cycle() - time.sleep(interval) - - except KeyboardInterrupt: - self.logger.info("Monitoring stopped by user") - except Exception as e: - self.logger.error(f"Critical error in main loop: {e}") + for sig in (signal.SIGTERM, signal.SIGINT): + previous[sig] = signal.signal(sig, self._handle_signal) + except ValueError: + pass + + failures = 0 + try: + while not self.stop_event.is_set(): + 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__": gatherer = OpenVPNDataGatherer() diff --git a/APP_CORE/secret_key.py b/APP_CORE/secret_key.py new file mode 100644 index 0000000..e01e3d6 --- /dev/null +++ b/APP_CORE/secret_key.py @@ -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 diff --git a/APP_CORE/test_gatherer.py b/APP_CORE/test_gatherer.py new file mode 100644 index 0000000..6d21e88 --- /dev/null +++ b/APP_CORE/test_gatherer.py @@ -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] diff --git a/APP_CORE/test_secret_key.py b/APP_CORE/test_secret_key.py new file mode 100644 index 0000000..49e9849 --- /dev/null +++ b/APP_CORE/test_secret_key.py @@ -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") diff --git a/APP_PROFILER/README.md b/APP_PROFILER/README.md index 6558285..5df897e 100644 --- a/APP_PROFILER/README.md +++ b/APP_PROFILER/README.md @@ -19,6 +19,9 @@ python3 -m venv venv source venv/bin/activate 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 python3 main.py # Swagger UI available at http://localhost:8000/docs diff --git a/APP_PROFILER/config.ini b/APP_PROFILER/config.ini index 1c4206a..4d36bce 100644 --- a/APP_PROFILER/config.ini +++ b/APP_PROFILER/config.ini @@ -1,7 +1,8 @@ [api] -# Secret key for JWT token verification. -# MUST match the key in APP_CORE/config.ini if not overridden by ENV. -secret_key = ovpmon-secret-change-me +# Secret key for JWT token verification. +# MUST match the key of APP_CORE (same OVPMON_API_SECRET_KEY or the same value in its config.ini). +# 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] # Path to the profiler database relative to component root diff --git a/APP_PROFILER/conftest.py b/APP_PROFILER/conftest.py new file mode 100644 index 0000000..d4caa5f --- /dev/null +++ b/APP_PROFILER/conftest.py @@ -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) diff --git a/APP_PROFILER/test_secret_key.py b/APP_PROFILER/test_secret_key.py new file mode 100644 index 0000000..7d9827a --- /dev/null +++ b/APP_PROFILER/test_secret_key.py @@ -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 diff --git a/APP_PROFILER/utils/auth.py b/APP_PROFILER/utils/auth.py index 97806b1..3ee4d66 100644 --- a/APP_PROFILER/utils/auth.py +++ b/APP_PROFILER/utils/auth.py @@ -1,29 +1,31 @@ import jwt -import configparser +import logging import os from fastapi import Header, HTTPException, status from pathlib import Path from .config import get_config_value +from .secret_key import resolve_secret_key, SecretKeyError + +logger = logging.getLogger(__name__) + def get_secret_key(): - # Use consistent OVPMON_API_SECRET_KEY as primary source - key = get_config_value('api', 'secret_key', fallback='ovpmon-secret-change-me') - - if key == 'ovpmon-secret-change-me': - print("[AUTH] WARNING: Using default fallback SECRET_KEY") - else: - # Check if it was from env (get_config_value prioritizes env) - import os - if os.getenv('OVPMON_API_SECRET_KEY'): - print("[AUTH] Using SECRET_KEY from OVPMON_API_SECRET_KEY environment variable") - elif os.getenv('OVPMON_SECRET_KEY'): - print("[AUTH] Using SECRET_KEY from OVPMON_SECRET_KEY environment variable") - else: - print("[AUTH] SECRET_KEY loaded (config.ini or fallback)") - + """JWT signing key: OVPMON_API_SECRET_KEY, else [api] secret_key of config.ini. No built-in default.""" + try: + # get_config_value returns the environment value first, then the config.ini value + key, source = resolve_secret_key( + os.getenv('OVPMON_API_SECRET_KEY'), + get_config_value('api', 'secret_key'), + 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 {source}") 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() diff --git a/APP_PROFILER/utils/secret_key.py b/APP_PROFILER/utils/secret_key.py new file mode 100644 index 0000000..8c2f83b --- /dev/null +++ b/APP_PROFILER/utils/secret_key.py @@ -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 diff --git a/DOCS/Changes/2026-09-30_Egress_via_Hysteria2.md b/DEPLOYMENTS/timeweb-hysteria2/Egress_via_Hysteria2.md similarity index 100% rename from DOCS/Changes/2026-09-30_Egress_via_Hysteria2.md rename to DEPLOYMENTS/timeweb-hysteria2/Egress_via_Hysteria2.md diff --git a/DOCS/Operations/Hysteria_Chain_Manifest.md b/DEPLOYMENTS/timeweb-hysteria2/Hysteria_Chain_Manifest.md similarity index 100% rename from DOCS/Operations/Hysteria_Chain_Manifest.md rename to DEPLOYMENTS/timeweb-hysteria2/Hysteria_Chain_Manifest.md diff --git a/DOCS/Operations/IMPLEMENTATION-01-settings-validation.md b/DEPLOYMENTS/timeweb-hysteria2/IMPLEMENTATION-01-settings-validation.md similarity index 100% rename from DOCS/Operations/IMPLEMENTATION-01-settings-validation.md rename to DEPLOYMENTS/timeweb-hysteria2/IMPLEMENTATION-01-settings-validation.md diff --git a/DOCS/Operations/IMPLEMENTATION-02-privilege-separation.md b/DEPLOYMENTS/timeweb-hysteria2/IMPLEMENTATION-02-privilege-separation.md similarity index 100% rename from DOCS/Operations/IMPLEMENTATION-02-privilege-separation.md rename to DEPLOYMENTS/timeweb-hysteria2/IMPLEMENTATION-02-privilege-separation.md diff --git a/DOCS/Operations/PLAN-validation-and-privilege-drop.md b/DEPLOYMENTS/timeweb-hysteria2/PLAN-validation-and-privilege-drop.md similarity index 100% rename from DOCS/Operations/PLAN-validation-and-privilege-drop.md rename to DEPLOYMENTS/timeweb-hysteria2/PLAN-validation-and-privilege-drop.md diff --git a/DEPLOYMENTS/timeweb-hysteria2/README.md b/DEPLOYMENTS/timeweb-hysteria2/README.md new file mode 100644 index 0000000..3b53f8d --- /dev/null +++ b/DEPLOYMENTS/timeweb-hysteria2/README.md @@ -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). diff --git a/DOCS/Operations/REBOOT-TEST.md b/DEPLOYMENTS/timeweb-hysteria2/REBOOT-TEST.md similarity index 100% rename from DOCS/Operations/REBOOT-TEST.md rename to DEPLOYMENTS/timeweb-hysteria2/REBOOT-TEST.md diff --git a/DOCS/Operations/SUMMARY-ovpn-monitor.md b/DEPLOYMENTS/timeweb-hysteria2/SUMMARY-ovpn-monitor.md similarity index 100% rename from DOCS/Operations/SUMMARY-ovpn-monitor.md rename to DEPLOYMENTS/timeweb-hysteria2/SUMMARY-ovpn-monitor.md diff --git a/DOCS/Changes/2026-09-30_Privilege_Separation.md b/DOCS/Changes/2026-09-30_Privilege_Separation.md index df50d40..38a88b1 100644 --- a/DOCS/Changes/2026-09-30_Privilege_Separation.md +++ b/DOCS/Changes/2026-09-30_Privilege_Separation.md @@ -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 ` (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`. diff --git a/DOCS/Changes/2026-10-05_Code_Review.md b/DOCS/Changes/2026-10-05_Code_Review.md new file mode 100644 index 0000000..76b1293 --- /dev/null +++ b/DOCS/Changes/2026-10-05_Code_Review.md @@ -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`; файл удалён. diff --git a/DOCS/Changes/2026-10-05_Code_Review_PLAN.md b/DOCS/Changes/2026-10-05_Code_Review_PLAN.md new file mode 100644 index 0000000..8aa4610 --- /dev/null +++ b/DOCS/Changes/2026-10-05_Code_Review_PLAN.md @@ -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/_Codebase_Analysis.md` и сводка по выполненному в `2026-10-05_Code_Review.md`. diff --git a/DOCS/Changes/2026-10-05_Docs_Refactoring.md b/DOCS/Changes/2026-10-05_Docs_Refactoring.md new file mode 100644 index 0000000..9d2672b --- /dev/null +++ b/DOCS/Changes/2026-10-05_Docs_Refactoring.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/`). diff --git a/DOCS/Changes/2026-10-05_Docs_Refactoring_PLAN.md b/DOCS/Changes/2026-10-05_Docs_Refactoring_PLAN.md new file mode 100644 index 0000000..bedd353 --- /dev/null +++ b/DOCS/Changes/2026-10-05_Docs_Refactoring_PLAN.md @@ -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`). diff --git a/DOCS/Changes/2026-10-05_Gatherer_Reliability.md b/DOCS/Changes/2026-10-05_Gatherer_Reliability.md new file mode 100644 index 0000000..d604ce3 --- /dev/null +++ b/DOCS/Changes/2026-10-05_Gatherer_Reliability.md @@ -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 контейнера проверяет только наличие процесса. diff --git a/DOCS/Changes/2026-10-05_Gatherer_Reliability_PLAN.md b/DOCS/Changes/2026-10-05_Gatherer_Reliability_PLAN.md new file mode 100644 index 0000000..0a3bac0 --- /dev/null +++ b/DOCS/Changes/2026-10-05_Gatherer_Reliability_PLAN.md @@ -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,<текст>, HEADER,CLIENT_LIST,... +CLIENT_LIST,,,,,,,,,... +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`) | да | diff --git a/DOCS/Changes/2026-10-05_JWT_Secret_Fail_Closed.md b/DOCS/Changes/2026-10-05_JWT_Secret_Fail_Closed.md new file mode 100644 index 0000000..68b449e --- /dev/null +++ b/DOCS/Changes/2026-10-05_JWT_Secret_Fail_Closed.md @@ -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). diff --git a/DOCS/Changes/2026-10-05_JWT_Secret_Fail_Closed_PLAN.md b/DOCS/Changes/2026-10-05_JWT_Secret_Fail_Closed_PLAN.md new file mode 100644 index 0000000..0678ad8 --- /dev/null +++ b/DOCS/Changes/2026-10-05_JWT_Secret_Fail_Closed_PLAN.md @@ -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` | да | diff --git a/DOCS/Changes/2026-10-05_NFT_Firewall.md b/DOCS/Changes/2026-10-05_NFT_Firewall.md index 47b47e1..ade8b12 100644 --- a/DOCS/Changes/2026-10-05_NFT_Firewall.md +++ b/DOCS/Changes/2026-10-05_NFT_Firewall.md @@ -1,6 +1,6 @@ # nftables script for system-service installs: summary (2026-10-05) -Plan: [2026-10-05_NFT_Firewall_PLAN.md](2026-10-05_NFT_Firewall_PLAN.md). Guide: [Firewall, NAT and forwarding](../Deployment/Scenario2_System_Services.md#firewall-nat-and-forwarding). +Plan: [2026-10-05_NFT_Firewall_PLAN.md](2026-10-05_NFT_Firewall_PLAN.md). Guide: [Firewall, NAT and forwarding](../Deployment/System_Services/Firewall.md). ## Done diff --git a/DOCS/Changes/2026-10-05_Scenario1_Containers.md b/DOCS/Changes/2026-10-05_Scenario1_Containers.md index dd161fd..8bfda38 100644 --- a/DOCS/Changes/2026-10-05_Scenario1_Containers.md +++ b/DOCS/Changes/2026-10-05_Scenario1_Containers.md @@ -1,6 +1,6 @@ # Scenario 1: containers, variants A and B (2026-10-05) -Phase 2 of [Deployment_Scenarios_PLAN](2026-10-05_Deployment_Scenarios_PLAN.md). Guide: [Scenario 1: containers](../Deployment/Scenario1_Containers.md). +Phase 2 of [Deployment_Scenarios_PLAN](2026-10-05_Deployment_Scenarios_PLAN.md). Guide: [Scenario 1: containers](../Deployment/Containers/README.md). ## What was added diff --git a/DOCS/Changes/2026-10-05_Scenario2_System_Services.md b/DOCS/Changes/2026-10-05_Scenario2_System_Services.md index 83dc2a2..4ee0ccf 100644 --- a/DOCS/Changes/2026-10-05_Scenario2_System_Services.md +++ b/DOCS/Changes/2026-10-05_Scenario2_System_Services.md @@ -1,6 +1,6 @@ # Scenario 2: system services, Alpine, Debian, Ubuntu (2026-10-05) -Phase 3 of [Deployment_Scenarios_PLAN](2026-10-05_Deployment_Scenarios_PLAN.md). Guide: [Scenario 2: system services](../Deployment/Scenario2_System_Services.md). +Phase 3 of [Deployment_Scenarios_PLAN](2026-10-05_Deployment_Scenarios_PLAN.md). Guide: [Scenario 2: system services](../Deployment/System_Services/README.md). ## What was added diff --git a/DOCS/Changes/README.md b/DOCS/Changes/README.md new file mode 100644 index 0000000..206919d --- /dev/null +++ b/DOCS/Changes/README.md @@ -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) | diff --git a/DOCS/Core_Monitoring/API_Reference.md b/DOCS/Core_Monitoring/API_Reference.md index 7c4f853..e2d527b 100644 --- a/DOCS/Core_Monitoring/API_Reference.md +++ b/DOCS/Core_Monitoring/API_Reference.md @@ -214,6 +214,10 @@ Real-time list of currently connected clients. ### `GET /sessions` +Field notes: +- `connected_since`: the real start of the session as reported by OpenVPN (`Connected Since (time_t)` of the status file), in **UTC**, format `YYYY-MM-DD HH:MM:SS`. It does not depend on when the gatherer first saw the session (older versions returned the local time of the first observation). If OpenVPN does not report the value, the time of the first observation (UTC) is used. +- `last_seen`: time of the last gatherer tick that saw the session (gatherer host local time). + #### Example Response ```json { diff --git a/DOCS/Core_Monitoring/Data_Architecture.md b/DOCS/Core_Monitoring/Data_Architecture.md index ca1b8b5..8d0edf9 100644 --- a/DOCS/Core_Monitoring/Data_Architecture.md +++ b/DOCS/Core_Monitoring/Data_Architecture.md @@ -8,13 +8,29 @@ The gatherer runs a continuous loop (default interval: **10 seconds**). ### A. Log Parsing - **Source**: `/var/log/openvpn/openvpn-status.log` (Status File v2, CSV format). -- **Target Fields**: `Common Name`, `Real Address`, `Bytes Sent`, `Bytes Received`. +- **Target Fields**: `Common Name`, `Real Address`, `Bytes Sent`, `Bytes Received`, `Connected Since (time_t)`. - **Filtering**: Only lines starting with `CLIENT_LIST`. ### B. Delta Calculation (`update_client_status_and_bytes`) -The log provides *lifetime* counters for a session. The gatherer calculates the traffic *delta* (increment) since the last check. -- **Logic**: `Increment = Current Value - Last Saved Value`. -- **Reset Detection**: If `Current Value < Last Saved Value`, it assumes a session/server restart and counts the entire `Current Value` as the increment. +The log provides *lifetime* counters for a session. The gatherer calculates the traffic *delta* (increment) since the last check. A session is identified by the key `(common_name, real_address, connected_since_ts)`, where `connected_since_ts` is the `Connected Since (time_t)` column (index 8) of `CLIENT_LIST`. A reconnect always gets a new `connected_since_ts` and therefore a new session. + +| Situation | Increment | +|-----------|-----------| +| Key is in the in-memory cache | `Current - Previous`. If a counter decreased (same key), it is treated as a reset and the whole `Current` is counted. | +| Not in cache, key is in the baseline (snapshot of `active_sessions` loaded at start, or a session recently dropped from the cache) | `Current - Baseline` (traffic during a daemon downtime is counted, nothing is counted twice). | +| Not in cache, session started after the daemon start (with a margin of `2 x check_interval`) | New session: the whole `Current` value, whatever its size. For a client seen for the first time the `clients` row is created with these totals (the first frame is not lost). | +| Not in cache, session older than the daemon and no snapshot (first start after an update, lost DB) | Baseline: increment `0`, a WARNING with the client name is logged (the only case of lost traffic, once per session). | +| `connected_since_ts` is missing or not a number (non-standard status file) | Fallback heuristic: counters below 10 MB are counted as a new session, otherwise increment `0`; a WARNING is logged. | + +Cache changes are collected in a temporary structure and applied only after the database transaction is committed. If the transaction fails, the cache is unchanged and the next tick counts the difference for the whole interval. + +### B1. Read Validity, Grace Period, Restart and Shutdown +- **Validity** (`parse_status`): the status file must contain a `TITLE` line, a `TIME,,` line and end with `END`. A missing file, a read error or an incomplete file (read while OpenVPN rewrites it) makes the gatherer **skip the tick entirely**: the database and the cache are not touched, and the next valid tick counts the difference for the whole interval. After `status_invalid_max` (default 6) skipped ticks in a row the message is logged at ERROR level. +- **Freshness**: if `TIME` is older than `status_stale_seconds` (default 60 s), OpenVPN is considered stopped: there are no clients, all clients become `Disconnected`, sessions leave the cache via the grace period. A valid, fresh file without `CLIENT_LIST` lines simply means no clients. +- **Grace period**: a session missing from the status is not dropped at once. Its `missing_ticks` counter grows each tick and the session is removed from the cache when it reaches `session_grace_ticks` (default 3, about 30 s). A session that comes back with the same key continues without double counting. A removed session is remembered (last counters, 1 hour) so that a late return with the same key is still counted as a continuation. +- **Restart**: at start the gatherer loads `active_sessions` as the baseline (see the table above). `active_sessions.connected_since` stores the real session start in UTC (`YYYY-MM-DD HH:MM:SS`), which is also what `/sessions` returns. +- **Resilience and shutdown**: every cycle runs in `try/except`; a failure is logged with a traceback and does not stop the daemon. After consecutive failures the pause grows as `min(interval * 2^n, 60)` seconds and resets after a successful cycle. `SIGTERM`/`SIGINT` only set a stop flag: the current cycle is finished, the pause is interrupted and the process exits normally (code 0). +- **Settings** (`[openvpn_monitor]`, can be overridden by `OVPMON_OPENVPN_MONITOR_*`): `check_interval` (>= 1), `session_grace_ticks` (>= 0), `status_stale_seconds` (>= 1), `status_invalid_max` (>= 1). An invalid value stops the start with a clear message and exit code 1. ### C. Rate Calculation - **Speed**: Calculated as `Increment * 8 / (Interval * 1_000_000)` to get **Mbps**. diff --git a/DOCS/Deployment/Containers/Operations.md b/DOCS/Deployment/Containers/Operations.md new file mode 100644 index 0000000..46a8e9a --- /dev/null +++ b/DOCS/Deployment/Containers/Operations.md @@ -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//*.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 `: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 `.bak-` 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// +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/-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 `.bak-` 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 --project `. 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 `.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 `: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). diff --git a/DOCS/Deployment/Containers/README.md b/DOCS/Deployment/Containers/README.md new file mode 100644 index 0000000..3479f38 --- /dev/null +++ b/DOCS/Deployment/Containers/README.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 && 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 +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) diff --git a/DOCS/Deployment/Containers/Reference.md b/DOCS/Deployment/Containers/Reference.md new file mode 100644 index 0000000..67fbd6e --- /dev/null +++ b/DOCS/Deployment/Containers/Reference.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 `_`; 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/.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). diff --git a/DOCS/Deployment/Containers/Troubleshooting.md b/DOCS/Deployment/Containers/Troubleshooting.md new file mode 100644 index 0000000..a89f639 --- /dev/null +++ b/DOCS/Deployment/Containers/Troubleshooting.md @@ -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 ` (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 `.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. diff --git a/DOCS/Deployment/First_Steps.md b/DOCS/Deployment/First_Steps.md new file mode 100644 index 0000000..dbfb34a --- /dev/null +++ b/DOCS/Deployment/First_Steps.md @@ -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://[:port]`, system services `https://: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). diff --git a/DOCS/Deployment/README.md b/DOCS/Deployment/README.md new file mode 100644 index 0000000..003907c --- /dev/null +++ b/DOCS/Deployment/README.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://` (port 80, change with `--http-port`); put TLS in front | `https://: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) | diff --git a/DOCS/Deployment/Scenario1_Containers.md b/DOCS/Deployment/Scenario1_Containers.md deleted file mode 100644 index 4bb892e..0000000 --- a/DOCS/Deployment/Scenario1_Containers.md +++ /dev/null @@ -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 -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 `_`; 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/.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//*.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 `: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 `.bak-` 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// -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/-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 `.bak-` 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 --project `. 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 ` (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 `.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 `.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 `: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). diff --git a/DOCS/Deployment/Scenario2_System_Services.md b/DOCS/Deployment/Scenario2_System_Services.md deleted file mode 100644 index f2ef524..0000000 --- a/DOCS/Deployment/Scenario2_System_Services.md +++ /dev/null @@ -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-.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 /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 /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 /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-.log` | `journalctl -u ovpmon-` | -| 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:/` (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 | `/APP_CORE`, `/APP_PROFILER` | `root:root`, read-only for others | -| Virtualenvs | `/APP_CORE/venv`, `/APP_PROFILER/venv` | `root:root` | -| **PKI** (CA, keys, certificates, CRL) | `/APP_PROFILER/easy-rsa` (real directory) | `ovpmon:ovpmon` 750 | -| **Client profiles** | `/APP_PROFILER/client-config` (real directory) | `ovpmon:ovpmon` 750 | -| Profiler log | `/APP_PROFILER/profiler.log` | `ovpmon:ovpmon` 640 | -| Shipped settings file | `/APP_CORE/config.ini`, `/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//` | `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/.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://:` | 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 `/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 `, systemd runs `systemctl ` (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//` (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 `.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 `.old-