Scenario 2: install and update as system services (Alpine, Debian, Ubuntu)

- deploy/native: install.sh, update.sh (backup, new code prepared aside,
  stop services, separate DB migration phase, start, automatic rollback;
  OpenVPN keeps running), backup.sh, restore.sh, build-ui.sh (Node 20
  container), lib.sh OS adapter (OpenRC and systemd).
- Root helper reads /etc/ovpmon/helper.conf (service manager, unit, config
  path), validated strictly; process.py/server.py honour OVPMON_RUNTIME,
  OVPMON_OPENVPN_SERVICE, OVPMON_OPENVPN_CONFIG. Debian/Ubuntu use
  openvpn-server@server and /etc/openvpn/server/server.conf.
- Service definitions rewritten (systemd, OpenRC). Fixes found by real runs:
  no seccomp-based options in the profiler unit (they imply NoNewPrivileges
  and break setuid doas); OpenRC start_pre extends PATH instead of
  replacing it; helper syntax check works on a read-only tree.
- Verified in containers with real init systems (Debian 12, Ubuntu 24.04,
  Alpine 3.23): install, PKI/server config/OpenVPN start, update on
  pre-versioned databases, rollback, backup/restore.
- Test: test_helper_config.py. Docs: Scenario 2 guide, change summary,
  README, Index.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-05 10:45:24 +03:00
1 parent 1c49d0b9c2
commit 4abd2044f0
26 files changed
+3326 -255

No files matched your search

+6 -81
View File
@@ -1,87 +1,12 @@
# Deployment: system services (no containers)
Tested on **Alpine 3.23 (OpenRC)**; Debian/Ubuntu (systemd) differs only in service manager. Unit/init templates: [`systemd/`](systemd), [`openrc/`](openrc/INSTALL.md). Generic notes: [Deployment](Deployment.md), [Service management](Service_Management.md), [Nginx](Nginx_Configuration.md).
This page is now a pointer. Installation and update on **Alpine (OpenRC), Debian and Ubuntu (systemd)** are done with the scripts in `deploy/native/` and described in **[Scenario 2: system services](../Deployment/Scenario2_System_Services.md)**: install, update with a separate database migration step, backup, restore, rollback, firewall and NAT commands, layout, environment file, troubleshooting and the "what is preserved" table.
## 1. Packages
Quick start (as root, from a checkout of the repository; build the UI with `deploy/native/build-ui.sh` on a machine with Docker first):
- Alpine: `apk add python3 py3-pip nginx nodejs npm openvpn easy-rsa iptables bash`
- Debian/Ubuntu: `apt install python3-venv nginx nodejs npm openvpn easy-rsa iptables`
## 2. Backend
```bash
cd APP_CORE && python3 -m venv venv && venv/bin/pip install -r requirements.txt gunicorn
cd APP_PROFILER && python3 -m venv venv && venv/bin/pip install -r requirements.txt
mkdir -p APP_PROFILER/easy-rsa && cp -r /usr/share/easy-rsa/* APP_PROFILER/easy-rsa/ # Docker entrypoint does this automatically
```sh
deploy/native/install.sh --ui-dist ui-dist.tar.gz # first installation
deploy/native/update.sh --ui-dist ui-dist.tar.gz # later: update with backup and rollback
```
## 3. Environment file
`/etc/ovpmon/env` (chmod 600), loaded by the services:
```
OVPMON_API_SECRET_KEY=<openssl rand -hex 32>
OVPMON_API_HOST=127.0.0.1
OVPMON_API_PORT=5001
OVPMON_OPENVPN_MONITOR_DB_PATH=/var/lib/ovpmon/openvpn_monitor.db
OVPMON_OPENVPN_MONITOR_LOG_PATH=/var/log/openvpn/openvpn-status.log
OVPMON_PROFILER_DB_PATH=/var/lib/ovpmon/ovpn_profiler.db
OVPMON_LOGGING_LEVEL=INFO
OVPMON_CORS_ORIGINS=https://<HOST>:8088
```
Create `/var/lib/ovpmon`, `/var/log/ovpmon`, `/var/log/openvpn`. For the first start also set `OVPMON_INITIAL_ADMIN_USER` / `OVPMON_INITIAL_ADMIN_PASSWORD`, then remove them.
## 4. Services
| Service | Command | Listens |
|---|---|---|
| `ovpmon-api` | `APP_CORE/venv/bin/gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app` (cwd `APP_CORE`) | 127.0.0.1:5001 |
| `ovpmon-gatherer` | `APP_CORE/venv/bin/python openvpn_gatherer_v3.py` (cwd `APP_CORE`) | - |
| `ovpmon-profiler` | `APP_PROFILER/venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000` (cwd `APP_PROFILER`) | 127.0.0.1:8000 |
OpenRC (Alpine): `supervisor=supervise-daemon`, `respawn_delay=3`, source `/etc/ovpmon/env` in `start_pre`, then `rc-update add <svc> default && rc-service <svc> start`. systemd: use the units from `systemd/` with `EnvironmentFile=/etc/ovpmon/env`.
The Profiler restarts OpenVPN through `rc-service openvpn` (Alpine) or `systemctl openvpn`; on Alpine link the config: `ln -s server.conf /etc/openvpn/openvpn.conf` and enable the `openvpn` service.
## 4a. Run as an unprivileged user (recommended)
Create the `ovpmon` user, give it the data directories, add `command_user="ovpmon:ovpmon"` to the init scripts (or `User=ovpmon` in systemd units), install the root helper and the doas rules. The API then renders `server.conf` to `/var/lib/ovpmon/staging/`; the helper validates and installs it, publishes the CRL for OpenVPN and controls the `openvpn` service. Full procedure, helper source and results: [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md); files in [`privilege-separation/`](privilege-separation/).
## 5. UI and Nginx (HTTPS on 8088)
```bash
cd APP_UI && npm install && npm run build
mkdir -p /var/www/ovpmon && cp -r dist/. /var/www/ovpmon/
```
Certificate (self-signed, replace with a real one when a domain is available):
```bash
mkdir -p /etc/ovpmon/tls && cd /etc/ovpmon/tls
openssl req -x509 -nodes -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -days 825 \
-subj "/CN=ovpmon" -addext "subjectAltName=IP:<HOST-IP>,DNS:ovpmon" -keyout ovpmon.key -out ovpmon.crt
chmod 600 ovpmon.key
```
Nginx server (`/etc/nginx/http.d/ovpmon.conf` on Alpine): `listen 8088 ssl`, TLS 1.2/1.3, `error_page 497 =301 https://$host:8088$request_uri`, security headers, `limit_req` (5 r/min) on `/api/auth/login`, `/` → static UI, `/api/` → `127.0.0.1:5001`, `/profiles-api/` → `127.0.0.1:8000/api/`. Full listing: [Nginx configuration](Nginx_Configuration.md). Do not declare a second `ssl_session_cache shared:SSL` zone with a different size than the main `nginx.conf`.
## 6. First run
1. `https://<host>:8088/` → sign in with the seeded admin → **Account**: change username/password, enable 2FA.
2. **PKI Configuration → Initialize PKI** → generate server config → start OpenVPN → create profiles.
## 7. Host hardening (recommended)
- SSH: key-only (`PasswordAuthentication no`, `KbdInteractiveAuthentication no`, `PermitRootLogin prohibit-password`); note that cloud-init drop-ins in `/etc/ssh/sshd_config.d/` can override the main file, so put settings in `00-*.conf`.
- fail2ban: jails `sshd` and one for `POST /api/auth/login` (401/429/503) on the Nginx access log.
- Backends bound to `127.0.0.1`; only 8088 (UI/API) and the VPN port are public.
## 8. Verify
```bash
rc-status | grep -E "ovpmon|nginx|openvpn" # or: systemctl status ovpmon-*
ss -tlnp | grep -E ":(8088|5001|8000) "
curl -sk -o /dev/null -w "%{http_code}\n" https://127.0.0.1:8088/ # 200
curl -sk -o /dev/null -w "%{http_code}\n" https://127.0.0.1:8088/profiles-api/config # 401 without token
```
Related: [Nginx configuration](Nginx_Configuration.md), [Service management](Service_Management.md), [Database migrations](Database_Migrations.md), [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md), [Scenario 1: containers](../Deployment/Scenario1_Containers.md). The service definitions are in [`systemd/`](systemd) and [`openrc/`](openrc/INSTALL.md).
+1
View File
@@ -25,6 +25,7 @@ Welcome to the documentation for the OpenVPN Monitor suite.
- [PKI dependency guard (2026-10-04)](../Changes/2026-10-04_PKI_Dependency_Guard.md)
- [Database migrations (2026-10-05)](../Changes/2026-10-05_DB_Migrations.md) · [reference](Database_Migrations.md)
- [Scenario 1: containers (2026-10-05)](../Changes/2026-10-05_Scenario1_Containers.md) · [guide](../Deployment/Scenario1_Containers.md)
- [Scenario 2: system services (2026-10-05)](../Changes/2026-10-05_Scenario2_System_Services.md) · [guide](../Deployment/Scenario2_System_Services.md)
## 🔍 Core Monitoring (`APP_CORE`)
The core module responsible for log parsing, real-time statistics, and the primary API.
+21 -83
View File
@@ -1,93 +1,31 @@
# Service Setup Guide
This guide describes how to set up the OpenVPN Monitor components as system services.
The OpenVPN Monitor components run as three system services under the unprivileged user `ovpmon`. `deploy/native/install.sh` installs and enables them (see [Scenario 2: system services](../Deployment/Scenario2_System_Services.md)); this page is the day-to-day reference.
## Components
| Service | Command (working directory under the install dir, default `/opt/OpenVPN-Monitoring-Simple`) | Listens |
|---|---|---|
| `ovpmon-api` | `APP_CORE/venv/bin/python -m gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app` | 127.0.0.1:5001 |
| `ovpmon-gatherer` | `APP_CORE/venv/bin/python openvpn_gatherer_v3.py` | - |
| `ovpmon-profiler` | `APP_PROFILER/venv/bin/python -m uvicorn main:app --host 127.0.0.1 --port 8000` | 127.0.0.1:8000 |
1. **ovpmon-api**: The main Flask API (`APP/openvpn_api_v3.py`).
2. **ovpmon-gatherer**: The background data gatherer (`APP/openvpn_gatherer_v3.py`).
3. **ovpmon-profiler**: The new FastAPI profiler module (`NEW_MODULES/main.py`).
Settings: `/etc/ovpmon/env` (`root:root` 600). The services start after the network and do not depend on OpenVPN.
## Common Prerequisites
## Definitions
- **Install Directory**: `/opt/ovpmon` (Recommended)
- **Virtual Environment**: `/opt/ovpmon/venv`
- Alpine (OpenRC): [`openrc/ovpmon-*`](openrc/INSTALL.md) in `/etc/init.d/` (`supervise-daemon`, `command_user=ovpmon:ovpmon`, environment sourced in `start_pre`, log in `/var/log/ovpmon/`).
- Debian / Ubuntu (systemd): [`systemd/ovpmon-*.service`](systemd) in `/etc/systemd/system/` (`User=ovpmon`, `EnvironmentFile=/etc/ovpmon/env`, moderate hardening, log in the journal).
---
Install them with the scripts (they adjust the install directory); by hand, copy a file, replace `/opt/OpenVPN-Monitoring-Simple` if needed and enable it as below.
## 1. Alpine Linux (OpenRC)
## Commands
### Installation
| | OpenRC (Alpine) | systemd (Debian, Ubuntu) |
|---|---|---|
| Enable at boot | `rc-update add ovpmon-api default` | `systemctl enable ovpmon-api` |
| Start / stop / restart | `rc-service ovpmon-api start\|stop\|restart` | `systemctl start\|stop\|restart ovpmon-api` |
| Status | `rc-service ovpmon-api status` | `systemctl status ovpmon-api` |
| Log | `tail -f /var/log/ovpmon/ovpmon-api.log` | `journalctl -u ovpmon-api -f` |
| After editing `/etc/ovpmon/env` | restart the services | restart the services |
| After editing a unit file | - | `systemctl daemon-reload` |
1. **Copy Service Scripts**:
Copy the scripts from `Deployment/APP/openrc/` to `/etc/init.d/`.
```sh
cp DOCS/General/openrc/ovpmon-api /etc/init.d/
cp DOCS/General/openrc/ovpmon-gatherer /etc/init.d/
cp DOCS/General/openrc/ovpmon-profiler /etc/init.d/
```
2. **Set Permissions**:
```sh
chmod +x /etc/init.d/ovpmon-*
```
3. **Enable Services**:
```sh
rc-update add ovpmon-api default
rc-update add ovpmon-gatherer default
rc-update add ovpmon-profiler default
```
4. **Start Services**:
```sh
rc-service ovpmon-api start
rc-service ovpmon-gatherer start
rc-service ovpmon-profiler start
```
### Configuration
To override defaults (e.g., if you installed to a different directory), create files in `/etc/conf.d/`:
**File:** `/etc/conf.d/ovpmon-api` (example)
```sh
directory="/var/www/my-monitoring"
command_args="/var/www/my-monitoring/APP_CORE/openvpn_api_v3.py"
```
---
## 2. Debian / Ubuntu (Systemd)
### Installation Steps
1. **Copy Service Files**:
Copy the provided service files from `DOCS/General/systemd/` to `/etc/systemd/system/`.
```bash
cp DOCS/General/systemd/ovpmon-api.service /etc/systemd/system/
cp DOCS/General/systemd/ovpmon-gatherer.service /etc/systemd/system/
cp DOCS/General/systemd/ovpmon-profiler.service /etc/systemd/system/
```
2. **Reload Daemon**:
```bash
systemctl daemon-reload
```
3. **Enable Services** (Start on boot):
```bash
systemctl enable ovpmon-api ovpmon-gatherer ovpmon-profiler
```
4. **Start Services**:
```bash
systemctl start ovpmon-api ovpmon-gatherer ovpmon-profiler
```
5. **Check Status**:
```bash
systemctl status ovpmon-api
```
The OpenVPN server itself (`openvpn` on Alpine, `openvpn-server@server` on Debian/Ubuntu) is started and stopped from the UI through the root helper (`doas`); it is not an `ovpmon-*` service.
+3 -47
View File
@@ -1,49 +1,5 @@
# OpenRC Service Installation Guide
# OpenRC service scripts
This guide explains how to install and enable the `ovpmon-api` and `ovpmon-gatherer` services on an Alpine Linux (or other OpenRC-based) system.
`ovpmon-api`, `ovpmon-gatherer` and `ovpmon-profiler` are the OpenRC scripts (Alpine) of the system-services deployment. They run the services as the user `ovpmon`, source `/etc/ovpmon/env` in `start_pre` and are supervised by `supervise-daemon`.
## Prerequisites
- **Paths**: The scripts assume the application is installed at `/opt/ovpmon`.
- **Virtualenv**: A python virtual environment should exist at `/opt/ovpmon/venv`.
If your paths differ, you can edit the scripts directly or create configuration files in `/etc/conf.d/`.
## Installation Steps
1. **Copy the scripts to `/etc/init.d/`**:
```sh
cp ovpmon-api /etc/init.d/
cp ovpmon-gatherer /etc/init.d/
```
2. **Make them executable**:
```sh
chmod 755 /etc/init.d/ovpmon-api
chmod 755 /etc/init.d/ovpmon-gatherer
```
3. **Add to default runlevel** (to start on boot):
```sh
rc-update add ovpmon-api default
rc-update add ovpmon-gatherer default
```
4. **Start the services**:
```sh
rc-service ovpmon-api start
rc-service ovpmon-gatherer start
```
## Configuration (Optional)
You can override default variables without editing the script by creating files in `/etc/conf.d/`.
**Example `/etc/conf.d/ovpmon-api`**:
```sh
# Override installation directory
directory="/var/www/ovpmon/APP"
# Override command arguments
command_args="/var/www/ovpmon/APP/openvpn_api_v3.py --debug"
```
Do not copy them by hand: `deploy/native/install.sh` installs them (adjusting the install directory when it is not `/opt/OpenVPN-Monitoring-Simple`) and `deploy/native/update.sh` keeps them current. The full procedure, the layout and the systemd counterparts are in [Scenario 2: system services](../../Deployment/Scenario2_System_Services.md).
Regular → Executable
+32 -5
View File
@@ -1,16 +1,43 @@
#!/sbin/openrc-run
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# OpenVPN Monitor API (Flask under gunicorn, APP_CORE), OpenRC (Alpine).
# Install: deploy/native/install.sh renders this template (install dir, if not the default) into
# /etc/init.d/ovpmon-api. Manual use: copy it there (chmod 755), `rc-update add ovpmon-api default`,
# `rc-service ovpmon-api start`. Guide: DOCS/Deployment/Scenario2_System_Services.md
#
# Settings come from /etc/ovpmon/env (root:root 600), sourced in start_pre while still root; the
# daemon then runs as ovpmon. supervise-daemon restarts it after a crash.
# The service does not depend on openvpn: the VPN server is started from the UI through the root helper.
name="ovpmon-api"
description="OpenVPN Monitor API Service"
description="OpenVPN Monitor API (gunicorn)"
supervisor="supervise-daemon"
respawn_delay=3
respawn_max=0
: ${directory:="/opt/ovpmon/APP"}
: ${command_user:="root"}
command_user="ovpmon:ovpmon"
directory="/opt/OpenVPN-Monitoring-Simple/APP_CORE"
command="/opt/OpenVPN-Monitoring-Simple/APP_CORE/venv/bin/python"
command_args="-m gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app"
command="/opt/ovpmon/venv/bin/python"
command_args="/opt/ovpmon/APP/openvpn_api_v3.py"
output_log="/var/log/ovpmon/ovpmon-api.log"
error_log="/var/log/ovpmon/ovpmon-api.log"
depend() {
need net
after firewall
}
start_pre() {
# log file writable for the service user (the log directory is owned by ovpmon)
checkpath -f -m 0640 -o ovpmon:ovpmon "$output_log" || return 1
# export the service environment; the file is data written by install.sh (KEY=VALUE lines)
[ -r /etc/ovpmon/env ] || { eerror "/etc/ovpmon/env is missing"; return 1; }
set -a
. /etc/ovpmon/env
set +a
# extend, never replace: OpenRC itself needs /lib/rc/bin (ebegin, eend) on the PATH
export PATH="/usr/local/sbin:/usr/local/bin:$PATH"
}
+25 -5
View File
@@ -1,16 +1,36 @@
#!/sbin/openrc-run
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# OpenVPN Monitor gatherer (reads the OpenVPN status log into the monitoring database, APP_CORE),
# OpenRC (Alpine). Install: see ovpmon-api. Settings come from /etc/ovpmon/env.
# The gatherer keeps running while OpenVPN is down (it waits for the status log).
name="ovpmon-gatherer"
description="OpenVPN Monitor Gatherer Service"
description="OpenVPN Monitor Gatherer"
supervisor="supervise-daemon"
respawn_delay=3
respawn_max=0
: ${directory:="/opt/ovpmon/APP"}
: ${command_user:="root"}
command_user="ovpmon:ovpmon"
directory="/opt/OpenVPN-Monitoring-Simple/APP_CORE"
command="/opt/OpenVPN-Monitoring-Simple/APP_CORE/venv/bin/python"
command_args="openvpn_gatherer_v3.py"
command="/opt/ovpmon/venv/bin/python"
command_args="/opt/ovpmon/APP/openvpn_gatherer_v3.py"
output_log="/var/log/ovpmon/ovpmon-gatherer.log"
error_log="/var/log/ovpmon/ovpmon-gatherer.log"
depend() {
need net
after firewall
}
start_pre() {
checkpath -f -m 0640 -o ovpmon:ovpmon "$output_log" || return 1
[ -r /etc/ovpmon/env ] || { eerror "/etc/ovpmon/env is missing"; return 1; }
set -a
. /etc/ovpmon/env
set +a
# extend, never replace: OpenRC itself needs /lib/rc/bin (ebegin, eend) on the PATH
export PATH="/usr/local/sbin:/usr/local/bin:$PATH"
}
+29 -5
View File
@@ -1,16 +1,40 @@
#!/sbin/openrc-run
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# OpenVPN Profiler API (FastAPI under uvicorn, APP_PROFILER), OpenRC (Alpine): PKI (easy-rsa),
# profiles, server settings. Install: see ovpmon-api. Settings come from /etc/ovpmon/env.
#
# Runs as ovpmon. Anything that needs root (install server.conf, publish the CRL, start/stop OpenVPN)
# goes through `doas /usr/local/sbin/ovpmon-helper <fixed args>` (rules: /etc/doas.conf or
# /etc/doas.d/ovpmon.conf, configuration: /etc/ovpmon/helper.conf).
# Started without --reload and without depending on openvpn.
name="ovpmon-profiler"
description="OpenVPN Monitor Profiler Service (FastAPI)"
description="OpenVPN Profiler API (uvicorn)"
supervisor="supervise-daemon"
respawn_delay=3
respawn_max=0
: ${directory:="/opt/ovpmon/NEW_MODULES"}
: ${command_user:="root"}
command_user="ovpmon:ovpmon"
directory="/opt/OpenVPN-Monitoring-Simple/APP_PROFILER"
command="/opt/OpenVPN-Monitoring-Simple/APP_PROFILER/venv/bin/python"
command_args="-m uvicorn main:app --host 127.0.0.1 --port 8000"
command="/opt/ovpmon/venv/bin/python"
command_args="/opt/ovpmon/NEW_MODULES/main.py"
output_log="/var/log/ovpmon/ovpmon-profiler.log"
error_log="/var/log/ovpmon/ovpmon-profiler.log"
depend() {
need net
after firewall
}
start_pre() {
checkpath -f -m 0640 -o ovpmon:ovpmon "$output_log" || return 1
[ -r /etc/ovpmon/env ] || { eerror "/etc/ovpmon/env is missing"; return 1; }
set -a
. /etc/ovpmon/env
set +a
# extend, never replace: OpenRC itself needs /lib/rc/bin (ebegin, eend) on the PATH
export PATH="/usr/local/sbin:/usr/local/bin:$PATH"
}
+143 -8
View File
@@ -2,10 +2,30 @@
"""ovpmon-helper: the only root-side entry point for the unprivileged ovpmon services.
Usage (via doas): ovpmon-helper install-config
ovpmon-helper publish-crl
ovpmon-helper service start|stop|restart|status
install-config reads the staged OpenVPN server config, validates it against a strict
allowlist of directives and installs it atomically to /etc/openvpn/server.conf.
allowlist of directives and installs it atomically to the OpenVPN config path
(default /etc/openvpn/server.conf).
Optional configuration: /etc/ovpmon/helper.conf (INI, section [helper]). The helper runs through
doas with a stripped environment, so it reads its own root-owned file; the file must be owned by
root and not writable by group/other, otherwise the helper refuses to run. Without the file the
built-in defaults below apply (Alpine/OpenRC layout, unchanged behaviour). Keys:
[helper]
install_dir = /opt/OpenVPN-Monitoring-Simple # PKI = <install_dir>/APP_PROFILER/easy-rsa/pki
service_manager = openrc # openrc | systemd
service_unit = openvpn # systemd default: openvpn-server@server
config_path = /etc/openvpn/server.conf # Debian/Ubuntu: /etc/openvpn/server/server.conf
staged_path = /var/lib/ovpmon/staging/server.conf
Every value is validated strictly (absolute paths without "..", fixed prefixes, unit-name
pattern, fixed set of managers); unknown keys and invalid values make the helper refuse.
OpenRC runs `/sbin/rc-service <unit> <action>`; systemd runs `systemctl <action> <unit>`
(fixed argv, fixed PATH).
"""
import configparser
import ipaddress
import json
import os
@@ -16,17 +36,38 @@ import stat
import subprocess
import sys
STAGED = "/var/lib/ovpmon/staging/server.conf"
TARGET = "/etc/openvpn/server.conf"
PKI_DIR = "/opt/OpenVPN-Monitoring-Simple/APP_PROFILER/easy-rsa/pki"
CONF_PATH = "/etc/ovpmon/helper.conf"
# Built-in defaults = the values that were hard-coded before helper.conf existed
DEFAULT_INSTALL_DIR = "/opt/OpenVPN-Monitoring-Simple"
DEFAULT_SERVICE_MANAGER = "openrc"
DEFAULT_SERVICE_UNIT = "openvpn"
DEFAULT_SYSTEMD_UNIT = "openvpn-server@server"
DEFAULT_CONFIG_PATH = "/etc/openvpn/server.conf"
DEFAULT_STAGED_PATH = "/var/lib/ovpmon/staging/server.conf"
# Active settings (defaults until apply_settings() is called by load_config())
INSTALL_DIR = DEFAULT_INSTALL_DIR
SERVICE_MANAGER = DEFAULT_SERVICE_MANAGER
SERVICE_UNIT = DEFAULT_SERVICE_UNIT
STAGED = DEFAULT_STAGED_PATH
TARGET = DEFAULT_CONFIG_PATH
PKI_DIR = INSTALL_DIR + "/APP_PROFILER/easy-rsa/pki"
CRL_SRC = PKI_DIR + "/crl.pem"
SCRIPTS_DIR = "/etc/openvpn/scripts"
STATUS_LOG = "/var/log/openvpn/openvpn-status.log"
CRL_SRC = PKI_DIR + "/crl.pem"
CRL_PUBLISHED = "/etc/openvpn/crl.pem"
CRL_MAX = 1024 * 1024
SERVICE_USER = "ovpmon"
MAX_SIZE = 64 * 1024
CIPHERS_RE = re.compile(r"^[A-Za-z0-9:_-]{1,200}$")
UNIT_RE = re.compile(r"^[A-Za-z0-9@._-]{1,64}$")
PATH_RE = re.compile(r"^/[A-Za-z0-9._/+@-]{1,200}$")
MANAGERS = ("openrc", "systemd")
CONF_KEYS = ("install_dir", "service_manager", "service_unit", "config_path", "staged_path")
RC_SERVICE = "/sbin/rc-service"
SYSTEMCTL_CANDIDATES = ("/usr/bin/systemctl", "/bin/systemctl")
os.environ["PATH"] = "/usr/sbin:/usr/bin:/sbin:/bin"
@@ -36,6 +77,7 @@ class Reject(Exception):
def under(path, base):
real = os.path.realpath(path)
base = os.path.realpath(base)
return real == base or real.startswith(base.rstrip("/") + "/")
@@ -44,6 +86,89 @@ def need(cond, msg):
raise Reject(msg)
# ---------------------------------------------------------------------------
# Optional configuration /etc/ovpmon/helper.conf
# ---------------------------------------------------------------------------
def clean_path(key, value, prefix=None, min_parts=1, suffix=None):
"""Strict check of an absolute path from helper.conf; returns it without a trailing slash."""
need(PATH_RE.fullmatch(value) is not None, key + ": must be an absolute path of letters, digits and . _ / + @ -")
path = value.rstrip("/") or "/"
parts = path.split("/")[1:]
need("" not in parts and "." not in parts and ".." not in parts, key + ": no empty, '.' or '..' components")
if prefix is not None:
need(path.startswith(prefix), key + ": must be below " + prefix)
need(len(parts) >= min_parts, key + ": path too short")
if suffix is not None:
need(path.endswith(suffix), key + ": must end with " + suffix)
return path
def parse_config(text):
"""Parse and validate the text of helper.conf. Returns a dict with the keys that are set."""
cp = configparser.ConfigParser(interpolation=None, strict=True)
try:
need(all(ord(c) < 128 for c in text), "helper.conf: ASCII only")
cp.read_string(text)
except configparser.Error as e:
raise Reject("helper.conf: " + str(e).splitlines()[0][:150])
need(cp.sections() == ["helper"], "helper.conf: exactly one section [helper] is required")
raw = dict(cp["helper"])
unknown = sorted(set(raw) - set(CONF_KEYS))
need(not unknown, "helper.conf: unknown key(s): " + ", ".join(unknown)[:100])
out = {}
if "install_dir" in raw:
out["install_dir"] = clean_path("install_dir", raw["install_dir"], min_parts=2)
if "service_manager" in raw:
need(raw["service_manager"] in MANAGERS, "service_manager: must be one of " + ", ".join(MANAGERS))
out["service_manager"] = raw["service_manager"]
if "service_unit" in raw:
need(UNIT_RE.fullmatch(raw["service_unit"]) is not None and raw["service_unit"][0] not in "-.",
"service_unit: must match " + UNIT_RE.pattern + " and not start with - or .")
out["service_unit"] = raw["service_unit"]
if "config_path" in raw:
out["config_path"] = clean_path("config_path", raw["config_path"], prefix="/etc/openvpn/", min_parts=3, suffix=".conf")
if "staged_path" in raw:
out["staged_path"] = clean_path("staged_path", raw["staged_path"], prefix="/var/lib/ovpmon/", min_parts=4)
return out
def apply_settings(settings):
"""Set the module-level settings from a validated dict (missing keys: built-in defaults)."""
global INSTALL_DIR, SERVICE_MANAGER, SERVICE_UNIT, STAGED, TARGET, PKI_DIR, CRL_SRC
INSTALL_DIR = settings.get("install_dir", DEFAULT_INSTALL_DIR)
SERVICE_MANAGER = settings.get("service_manager", DEFAULT_SERVICE_MANAGER)
default_unit = DEFAULT_SYSTEMD_UNIT if SERVICE_MANAGER == "systemd" else DEFAULT_SERVICE_UNIT
SERVICE_UNIT = settings.get("service_unit", default_unit)
TARGET = settings.get("config_path", DEFAULT_CONFIG_PATH)
STAGED = settings.get("staged_path", DEFAULT_STAGED_PATH)
PKI_DIR = INSTALL_DIR + "/APP_PROFILER/easy-rsa/pki"
CRL_SRC = PKI_DIR + "/crl.pem"
def load_config(path=None, owner_uid=0):
"""Read helper.conf (if it exists) and apply it. The file must be a regular file (no symlink)
owned by owner_uid (root) and not writable by group/other, otherwise Reject."""
path = path or CONF_PATH
try:
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
except FileNotFoundError:
apply_settings({})
return {}
except OSError as e:
raise Reject("helper.conf cannot be opened: " + e.strerror)
try:
st = os.fstat(fd)
need(stat.S_ISREG(st.st_mode), "helper.conf must be a regular file")
need(st.st_uid == owner_uid and not st.st_mode & 0o022, "helper.conf must be owned by root and not group/other-writable")
need(st.st_size <= 4096, "helper.conf too large")
data = os.read(fd, 4097)
finally:
os.close(fd)
settings = parse_config(data.decode("ascii", "replace"))
apply_settings(settings)
return settings
def is_int(x, lo, hi):
return re.fullmatch(r"\d{1,6}", x) is not None and lo <= int(x) <= hi
@@ -183,8 +308,9 @@ def install_config():
f.write(text)
os.chmod(tmp, 0o644)
os.replace(tmp, TARGET)
if not os.path.lexists("/etc/openvpn/openvpn.conf"):
os.symlink("server.conf", "/etc/openvpn/openvpn.conf")
# OpenRC's openvpn service reads /etc/openvpn/openvpn.conf; systemd units use their own config path
if SERVICE_MANAGER == "openrc" and os.path.dirname(TARGET) == "/etc/openvpn" and not os.path.lexists("/etc/openvpn/openvpn.conf"):
os.symlink(os.path.basename(TARGET), "/etc/openvpn/openvpn.conf")
def prepare_status_log():
@@ -221,6 +347,14 @@ def publish_crl():
os.replace(tmp, CRL_PUBLISHED)
def service_command(action):
"""Fixed argv of the service manager (no shell, values come from the validated helper.conf)."""
if SERVICE_MANAGER == "systemd":
systemctl = next((p for p in SYSTEMCTL_CANDIDATES if os.path.exists(p)), SYSTEMCTL_CANDIDATES[0])
return [systemctl, action, SERVICE_UNIT]
return [RC_SERVICE, SERVICE_UNIT, action]
def service(action):
need(action in ("start", "stop", "restart", "status"), "invalid action")
if action in ("start", "restart"):
@@ -231,12 +365,13 @@ def service(action):
publish_crl()
except Exception:
pass # a broken CRL must not stop the VPN; crl-verify will then keep the previously published file
r = subprocess.run(["/sbin/rc-service", "openvpn", action], capture_output=True, text=True, timeout=60)
r = subprocess.run(service_command(action), capture_output=True, text=True, timeout=60)
return r.returncode, (r.stdout + r.stderr).strip()[-500:]
def main(argv):
try:
load_config()
if argv == ["install-config"]:
install_config()
print(json.dumps({"status": "ok"}))
+30 -5
View File
@@ -1,14 +1,39 @@
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# OpenVPN Monitor API (Flask under gunicorn, APP_CORE).
# Install: deploy/native/install.sh renders this template (install dir, if not the default) into
# /etc/systemd/system/ovpmon-api.service. Manual use: copy it there, `systemctl daemon-reload`,
# `systemctl enable --now ovpmon-api`. Guide: DOCS/Deployment/Scenario2_System_Services.md
#
# Settings come from /etc/ovpmon/env (root:root 600; systemd reads it as root before the user switch).
# The service does not depend on openvpn: the VPN server is started from the UI through the root helper.
[Unit]
Description=OpenVPN Monitor API
Description=OpenVPN Monitor API (gunicorn)
After=network.target
Wants=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/ovpmon/APP_CORE
ExecStart=/opt/ovpmon/venv/bin/python /opt/ovpmon/APP_CORE/openvpn_api_v3.py
User=ovpmon
Group=ovpmon
EnvironmentFile=/etc/ovpmon/env
WorkingDirectory=/opt/OpenVPN-Monitoring-Simple/APP_CORE
ExecStart=/opt/OpenVPN-Monitoring-Simple/APP_CORE/venv/bin/python -m gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app
Restart=always
RestartSec=5
RestartSec=3
# Hardening: code and virtualenv are root-owned and read-only for the service
NoNewPrivileges=yes
PrivateTmp=yes
ProtectHome=yes
ProtectSystem=full
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictRealtime=yes
LockPersonality=yes
# Write access: databases (and their migration backups) and logs
ReadWritePaths=/var/lib/ovpmon /var/log/ovpmon
[Install]
WantedBy=multi-user.target
+25 -4
View File
@@ -1,14 +1,35 @@
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# OpenVPN Monitor gatherer (reads the OpenVPN status log into the monitoring database, APP_CORE).
# Install: see ovpmon-api.service. Settings come from /etc/ovpmon/env.
# The gatherer starts and keeps running while OpenVPN is down (it waits for the status log).
[Unit]
Description=OpenVPN Monitor Gatherer
After=network.target
Wants=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/ovpmon/APP_CORE
ExecStart=/opt/ovpmon/venv/bin/python /opt/ovpmon/APP_CORE/openvpn_gatherer_v3.py
User=ovpmon
Group=ovpmon
EnvironmentFile=/etc/ovpmon/env
WorkingDirectory=/opt/OpenVPN-Monitoring-Simple/APP_CORE
ExecStart=/opt/OpenVPN-Monitoring-Simple/APP_CORE/venv/bin/python openvpn_gatherer_v3.py
Restart=always
RestartSec=10
RestartSec=3
# Hardening: code and virtualenv are root-owned and read-only for the service
NoNewPrivileges=yes
PrivateTmp=yes
ProtectHome=yes
ProtectSystem=full
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictRealtime=yes
LockPersonality=yes
# Write access: monitoring database (and its migration backups) and logs
ReadWritePaths=/var/lib/ovpmon /var/log/ovpmon
[Install]
WantedBy=multi-user.target
+35 -6
View File
@@ -1,15 +1,44 @@
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# OpenVPN Profiler API (FastAPI under uvicorn, APP_PROFILER): PKI (easy-rsa), profiles, server settings.
# Install: see ovpmon-api.service. Settings come from /etc/ovpmon/env.
#
# The profiler runs as the unprivileged user ovpmon. Anything that needs root (install server.conf,
# publish the CRL, start/stop OpenVPN) goes through `doas /usr/local/sbin/ovpmon-helper <fixed args>`
# (rules: /etc/doas.conf, configuration: /etc/ovpmon/helper.conf). Therefore, unlike the other two
# services, this unit must NOT set NoNewPrivileges (doas is setuid) nor any seccomp-based option (see below), must not restrict capabilities,
# and must leave /etc/openvpn writable: the helper is a child of this process and inherits its
# mount namespace.
# Started without --reload and without depending on openvpn.
[Unit]
Description=OpenVPN Profiler API
Description=OpenVPN Profiler API (uvicorn)
After=network.target
Wants=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/ovpmon/APP_PROFILER
# Running directly via python as main.py has uvicorn.run
ExecStart=/opt/ovpmon/venv/bin/python /opt/ovpmon/APP_PROFILER/main.py
User=ovpmon
Group=ovpmon
EnvironmentFile=/etc/ovpmon/env
WorkingDirectory=/opt/OpenVPN-Monitoring-Simple/APP_PROFILER
ExecStart=/opt/OpenVPN-Monitoring-Simple/APP_PROFILER/venv/bin/python -m uvicorn main:app --host 127.0.0.1 --port 8000
Restart=always
RestartSec=5
RestartSec=3
# Hardening (moderate, see the note above)
PrivateTmp=yes
ProtectHome=yes
ProtectSystem=full
ProtectControlGroups=yes
# Deliberately absent: ProtectKernelTunables, ProtectKernelModules, RestrictRealtime, LockPersonality,
# SystemCallFilter, RestrictAddressFamilies, MemoryDenyWriteExecute, RestrictNamespaces. They are enforced with a seccomp filter, and for an
# unprivileged unit systemd then sets NoNewPrivileges implicitly, which breaks the setuid doas
# ("doas: not installed setuid"). Verify with: grep NoNewPrivs /proc/<main pid>/status (must be 0)
# Write access: databases and logs; PKI, client profiles and the profiler log inside the install dir;
# /etc/openvpn and /var/log/openvpn for the root helper (a leading "-" ignores a missing path)
ReadWritePaths=/var/lib/ovpmon /var/log/ovpmon /opt/OpenVPN-Monitoring-Simple/APP_PROFILER/easy-rsa /opt/OpenVPN-Monitoring-Simple/APP_PROFILER/client-config
ReadWritePaths=-/opt/OpenVPN-Monitoring-Simple/APP_PROFILER/profiler.log
ReadWritePaths=-/etc/openvpn -/var/log/openvpn
[Install]
WantedBy=multi-user.target