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

+1
View File
@@ -3,3 +3,4 @@
backups/
.ovpmon-deploy
.ovpmon-lock/
deploy/native/ui-dist.tar.gz
+1 -1
View File
@@ -16,7 +16,7 @@ def configure_server(db: Session = Depends(get_db)):
pki.require_server_ready(db)
# Generate to a temporary location or standard location
# As per plan, we behave like srvconf
output_path = "/etc/openvpn/server.conf"
output_path = process.openvpn_config_path()
# Unprivileged service: render to the staging dir, the root helper validates and installs it
if not process.is_container() and os.geteuid() != 0:
+22 -3
View File
@@ -9,7 +9,14 @@ logger = logging.getLogger(__name__)
def is_container():
"""
Checks if the application is running inside a Docker container.
OVPMON_RUNTIME=host|container overrides the detection (a service that runs on a host inside a
test container with /.dockerenv sets host).
"""
forced = os.environ.get("OVPMON_RUNTIME", "").strip().lower()
if forced == "host":
return False
if forced == "container":
return True
if os.path.exists('/.dockerenv'):
return True
try:
@@ -23,6 +30,18 @@ def is_container():
HELPER_PATH = "/usr/local/sbin/ovpmon-helper"
def openvpn_config_path():
"""OpenVPN config path for root/container mode (OVPMON_OPENVPN_CONFIG, default /etc/openvpn/server.conf).
Unprivileged mode only stages the file; the helper's own configuration decides where it is installed."""
return os.environ.get("OVPMON_OPENVPN_CONFIG", "").strip() or "/etc/openvpn/server.conf"
def openvpn_service_name():
"""Service name for the native root path (OVPMON_OPENVPN_SERVICE, default 'openvpn';
systemd hosts use 'openvpn-server@server')."""
return os.environ.get("OVPMON_OPENVPN_SERVICE", "").strip() or "openvpn"
def _run_helper(args):
"""Call the root-side helper through doas (used when this process is unprivileged).
Returns (returncode, parsed_json_or_None, raw_output)."""
@@ -68,7 +87,7 @@ def control_service(action: str):
if action not in ["start", "stop", "restart"]:
raise ValueError("Invalid action")
CONFIG_PATH = "/etc/openvpn/server.conf"
CONFIG_PATH = openvpn_config_path()
PID_FILE = "/run/openvpn.pid"
# In Container: Use direct execution to avoid OpenRC/cgroups issues
@@ -149,9 +168,9 @@ def control_service(action: str):
cmd = []
if os_type == "alpine":
cmd = ["rc-service", "openvpn", action]
cmd = ["rc-service", openvpn_service_name(), action]
else:
cmd = ["systemctl", action, "openvpn"]
cmd = ["systemctl", action, openvpn_service_name()]
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
+83
View File
@@ -0,0 +1,83 @@
"""One test for the root helper's optional configuration (/etc/ovpmon/helper.conf).
The helper has no .py extension, so it is loaded by path. Nothing here touches a real service:
subprocess.run is replaced, the config files live in a temporary directory.
"""
import importlib.machinery
import importlib.util
import os
import subprocess
import types
import pytest
HELPER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "DOCS", "General",
"privilege-separation", "ovpmon-helper")
def load_helper():
loader = importlib.machinery.SourceFileLoader("ovpmon_helper_under_test", HELPER)
spec = importlib.util.spec_from_loader(loader.name, loader)
mod = importlib.util.module_from_spec(spec)
loader.exec_module(mod)
return mod
def write_conf(tmp_path, text, mode=0o644):
p = tmp_path / "helper.conf"
p.write_text(text)
p.chmod(mode)
return str(p)
def test_helper_config(tmp_path, monkeypatch):
if not os.path.isfile(HELPER):
pytest.skip("the helper source (DOCS/General/privilege-separation/ovpmon-helper) is not part of this tree")
h = load_helper()
# 1. Without helper.conf the old hard-coded values apply
assert h.load_config(str(tmp_path / "missing.conf")) == {}
assert h.STAGED == "/var/lib/ovpmon/staging/server.conf"
assert h.TARGET == "/etc/openvpn/server.conf"
assert h.PKI_DIR == "/opt/OpenVPN-Monitoring-Simple/APP_PROFILER/easy-rsa/pki"
assert h.CRL_SRC == h.PKI_DIR + "/crl.pem"
assert h.service_command("restart") == ["/sbin/rc-service", "openvpn", "restart"]
# 2. A valid file (here owned by the test user instead of root) is applied; PKI follows install_dir
own = os.getuid()
conf = write_conf(tmp_path, "[helper]\ninstall_dir = /srv/ovpmon\nservice_manager = systemd\n"
"config_path = /etc/openvpn/server/server.conf\n")
h.load_config(conf, owner_uid=own)
assert h.TARGET == "/etc/openvpn/server/server.conf"
assert h.PKI_DIR == "/srv/ovpmon/APP_PROFILER/easy-rsa/pki"
assert h.SERVICE_UNIT == "openvpn-server@server" # systemd default unit
# 3. Command lines: systemd -> systemctl <action> <unit>; openrc -> rc-service <unit> <action>
calls = []
def fake_run(cmd, **kwargs):
calls.append(cmd)
return subprocess.CompletedProcess(cmd, 0, stdout="ok", stderr="")
monkeypatch.setattr(h, "subprocess", types.SimpleNamespace(run=fake_run))
assert h.service("stop") == (0, "ok")
assert calls[-1][1:] == ["stop", "openvpn-server@server"] and calls[-1][0].endswith("systemctl")
h.load_config(write_conf(tmp_path, "[helper]\nservice_unit = openvpn\n"), owner_uid=own)
h.service("status")
assert calls[-1] == ["/sbin/rc-service", "openvpn", "status"]
# 4. Unsafe or malformed files are rejected; so is a file that is not owned by root
for bad in ("[helper]\ninstall_dir = /opt/../etc\n",
"[helper]\nservice_unit = x; reboot\n",
"[helper]\nservice_unit = -rf\n",
"[helper]\nservice_manager = runit\n",
"[helper]\nconfig_path = /tmp/server.conf\n",
"[helper]\nstaged_path = /etc/passwd\n",
"[helper]\nunknown = 1\n",
"install_dir = /opt/x\n"):
with pytest.raises(h.Reject):
h.load_config(write_conf(tmp_path, bad), owner_uid=own)
with pytest.raises(h.Reject):
h.load_config(write_conf(tmp_path, "[helper]\n", mode=0o666), owner_uid=own) # group/world writable
with pytest.raises(h.Reject):
h.load_config(write_conf(tmp_path, "[helper]\n"), owner_uid=own + 1) # wrong owner
@@ -51,7 +51,7 @@ Only the directives the template produces, each with checked arguments: `dev tun
- The supervisors stay root by design (they only respawn the service user's process).
- Helper checks resolve PKI paths at install time; a service-user-owned PKI directory could later swap a file for a symlink before OpenVPN (root) starts. Impact is limited to OpenVPN failing to parse or reading a key/cert-shaped file; keep the PKI directory owned by `ovpmon` only.
- CRL checking (`crl_verify`) works with the unprivileged API, see the section below.
- systemd deployments: same idea with `User=ovpmon`, a polkit/sudoers rule for the helper's fixed commands, and the same helper (replace `rc-service` with `systemctl`).
- systemd deployments (Debian, Ubuntu): implemented, see the section *Helper configuration and systemd* at the end.
- Rollback: restore `/etc/init.d/ovpmon-*` from `/root/app-bak/p2/`, `chown -R root:root` the data directories, restart the services (the helper and doas rules can stay).
## CRL publishing (`crl_verify`)
@@ -75,3 +75,9 @@ Results (throw-away second OpenVPN instance on another port/subnet running as `n
| `crl_verify=true` via API + `server/configure` | 200; config contains `crl-verify /etc/openvpn/crl.pem`, accepted by the helper; setting restored afterwards, live `server.conf` byte-identical to the original |
| Valid client with active CRL check | connects (`Initialization Sequence Completed`) |
| Revoke through the API, then reconnect | server sends `certificate revoked`, client is refused; no CRL read errors |
## Helper configuration and systemd (2026-10-05)
The helper reads an optional **`/etc/ovpmon/helper.conf`** (INI, section `[helper]`) with keys `install_dir`, `service_manager` (`openrc` or `systemd`), `service_unit`, `config_path`, `staged_path`. Without the file the built-in values apply, which are exactly the previous hard-coded ones (OpenRC `rc-service openvpn`, `/etc/openvpn/server.conf`, PKI below `/opt/OpenVPN-Monitoring-Simple`): existing hosts behave as before. The helper runs through `doas` with a stripped environment, so it reads its own file: it must be a regular file owned by root and not group/world writable, every value is validated strictly (absolute paths without `..`, `config_path` below `/etc/openvpn/`, `staged_path` below `/var/lib/ovpmon/`, unit name `^[A-Za-z0-9@._-]{1,64}$`, fixed set of managers), unknown keys and invalid values make the helper refuse. With `systemd` it runs `systemctl <action> <unit>` (default unit `openvpn-server@server`, fixed argument list and `PATH`); the `/etc/openvpn/openvpn.conf` link is created only for OpenRC. The `doas` rules file is unchanged (on Debian/Ubuntu the package is `opendoas`, rules in `/etc/doas.conf`).
`APP_PROFILER/services/process.py` honours `OVPMON_RUNTIME=host|container` (explicit override of the container detection) and, for the root (non-helper) path, `OVPMON_OPENVPN_SERVICE` (default `openvpn`) and `OVPMON_OPENVPN_CONFIG` (default `/etc/openvpn/server.conf`). Installation: [Scenario 2](../Deployment/Scenario2_System_Services.md). Test: `APP_PROFILER/test_helper_config.py`.
@@ -0,0 +1,52 @@
# 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).
## What was added
| Area | Content |
|---|---|
| `deploy/native/` | `install.sh`, `update.sh`, `backup.sh`, `restore.sh`, `build-ui.sh`, `lib.sh` (OS adapter for Alpine/OpenRC and Debian/Ubuntu/systemd), nginx template |
| Install | Packages, `ovpmon` user, code, two virtualenvs, easy-rsa workspace, `/etc/ovpmon/env` (random secret, admin password shown once), root helper + `doas`, service definitions, OpenVPN prerequisites, nginx with TLS on 8088, health checks. The firewall is **not** touched (hints are printed) |
| Update (phases) | preflight, **backup** (databases through the SQLite backup API, configuration, PKI, client configs, code with virtualenvs, system files; verified), source update, new code and virtualenvs prepared aside, **stop services (OpenVPN keeps running)** and swap code, **database migration as its own step** with the new code, UI/helper/doas/service files, start and health checks, **automatic rollback** from any failure after the stop |
| UI build | `build-ui.sh` builds the UI in a Node 20 container into a tarball; the host needs no Node |
| Debian/Ubuntu support in code | Root helper reads `/etc/ovpmon/helper.conf` (install dir, service manager `openrc|systemd`, unit, config path), validated strictly, defaults equal the old Alpine behaviour; `process.py` and `routers/server.py` use `OVPMON_RUNTIME`, `OVPMON_OPENVPN_SERVICE`, `OVPMON_OPENVPN_CONFIG`. Debian/Ubuntu: unit `openvpn-server@server`, config `/etc/openvpn/server/server.conf` |
| Service definitions | `DOCS/General/systemd/*.service`, `DOCS/General/openrc/*` rewritten (user `ovpmon`, environment file, real commands, no `--reload`); `Service_Management.md` updated |
| Docs | `DOCS/Deployment/Scenario2_System_Services.md`; `Deployment_Native.md` is a pointer |
| Test | `APP_PROFILER/test_helper_config.py` (helper configuration, defaults, rejected values, command lines) |
## Defects found by the real runs and fixed
| Defect | Fix |
|---|---|
| The profiler unit set `ProtectKernelTunables` and `ProtectKernelModules`: systemd implements them with seccomp and then sets NoNewPrivileges implicitly, so the setuid `doas` failed with "not installed setuid" and the root helper never ran | Both options removed from the profiler unit; the reason and the check are in the unit and in the guide |
| OpenRC scripts replaced `PATH` in `start_pre`, dropping `/lib/rc/bin`: OpenRC itself failed with `ebegin: not found` | `PATH` is extended, not replaced (all three scripts) |
| The helper syntax check used `py_compile`, which fails on a read-only source tree | `compile()` without writing a `.pyc` |
## Verification (containers with a real init: systemd on Debian 12 and Ubuntu 24.04, OpenRC on Alpine 3.23)
| Check | Debian 12 | Ubuntu 24.04 | Alpine 3.23 |
|---|---|---|---|
| `install.sh`, health checks, admin seed removed | ok | ok | ok |
| PKI init, server config through the root helper, client, note | ok | ok | ok |
| OpenVPN started through the helper | `openvpn-server@server` | `openvpn-server@server` | `openvpn` (OpenRC) |
| `update.sh` on databases without a version (real data) | ok, migration phase | ok | ok |
| OpenVPN untouched by the update | same PID | active | active |
| Rollback after an injected failure (broken new Profiler) | ok, data intact | not run | ok, data intact |
| `backup.sh`, change, `restore.sh` | not run | ok | not run |
| pytest: helper config test and the earlier tests | passed (all five test files) |||
Test containers, images and the UI archive were removed afterwards.
## Notes and limits
- A container is not a host: no real firewall, cgroup and init details can differ. Run the procedure once on a VM of the target OS before production. Test containers needed explicit help (an init process for OpenRC, writable cgroup); these are test artefacts, not product defects.
- Ubuntu 22.04 and other Debian or Alpine versions are not tested (the script warns and needs `--force`).
- Not tested: BusyBox `su` paths on hosts other than the test image, an upgrade of an existing real Alpine host through `update.sh` (adoption without a state file is implemented, not exercised), a source tree that is itself the install directory.
- Updates need access to the Python package index (fresh virtualenvs).
- `openvpn-server@server` shows as failed at boot until a `server.conf` exists.
- The version in the logs is `unknown` when `git` is not installed or the source is not a checkout.
## Existing installations
An existing Alpine host installed by hand can be adopted: `update.sh` records the state on the first run. Keep a copy of `/etc/doas.d/*` and the helper before the first update; the update replaces files that carry the deploy marker and reports, but does not overwrite, files that differ and have none.
@@ -0,0 +1,404 @@
# 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, nothing needs Node on the host.
| Script | Purpose |
|---|---|
| `deploy/native/build-ui.sh` | builds the web UI in a Node 20 container into `ui-dist.tar.gz` (on any machine with Docker) |
| `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`).
- The UI archive (see below). **The host needs no Node.js.**
- GNU tar (on Alpine the package `tar`; the installer adds it).
## Building the UI (any machine with Docker)
```bash
deploy/native/build-ui.sh # -> deploy/native/ui-dist.tar.gz
deploy/native/build-ui.sh -o /tmp/ui.tar.gz # another output file
OVPMON_NODE_IMAGE=node:20-alpine deploy/native/build-ui.sh --image node:22-alpine
```
The script runs `npm ci` (or `npm install` without a lock file) and `npm run build` in `node:20-alpine`. `APP_UI` is mounted read-only and copied inside the container, so **nothing is written into the source tree** except the output file. The archive holds the content of `dist/` with `index.html` at its top level. Without Docker the script stops with a clear message; you can then build elsewhere (`npm install && npm run build` in `APP_UI`) and pack `dist/` yourself (`tar -czf ui-dist.tar.gz -C dist .`).
Copy the archive to the target host together with the repository checkout and pass it with `--ui-dist FILE`. `install.sh` also picks up `deploy/native/ui-dist.tar.gz` automatically when it exists; `update.sh` uses a UI archive only when you pass `--ui-dist` explicitly (it never reinstalls a stale one).
## Install
Clone the repository on the target host, put the UI archive next to the scripts and run, as root:
### Alpine (OpenRC)
```sh
apk add git # only to clone; the script installs the rest
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --ui-dist /root/ui-dist.tar.gz
```
### Debian 12
```sh
apt-get update && apt-get install -y git
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --ui-dist /root/ui-dist.tar.gz
```
### Ubuntu 24.04
```sh
sudo -i
apt-get update && apt-get install -y git # make sure the "universe" component is enabled
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --ui-dist /root/ui-dist.tar.gz
```
Options:
| Option | Meaning |
|---|---|
| `--prefix DIR` | install directory (default `/opt/OpenVPN-Monitoring-Simple`); letters, digits, `. _ - /` only |
| `--ui-dist FILE` | UI archive from `build-ui.sh`; without it a placeholder page is installed |
| `--https-port N` | HTTPS port of the web UI (default `8088`) |
| `--host-name NAME` | DNS name or IP for the certificate and the CORS origin (default: the detected address of the default route) |
| `--admin-user NAME` | login of the first administrator (default `admin`) |
| `--force` | continue on an untested OS version |
### Differences between the systems
| | Alpine 3.23 | Debian 12 / Ubuntu 24.04 |
|---|---|---|
| Packages | `python3 py3-pip nginx openvpn easy-rsa iptables bash doas openssl curl tar` | `python3 python3-venv python3-pip nginx openvpn easy-rsa iptables opendoas openssl curl ca-certificates tar iproute2` |
| Service manager | OpenRC: `rc-service NAME start\|stop\|restart\|status`, `rc-update add NAME default` | systemd: `systemctl start\|stop\|restart\|status NAME`, `systemctl enable NAME` |
| Our service files | `/etc/init.d/ovpmon-api`, `-gatherer`, `-profiler` (`supervise-daemon`, `command_user=ovpmon:ovpmon`) | `/etc/systemd/system/ovpmon-*.service` (`User=ovpmon`, `EnvironmentFile=/etc/ovpmon/env`) |
| Service logs | `/var/log/ovpmon/ovpmon-<name>.log` | `journalctl -u ovpmon-<name>` |
| OpenVPN service | `openvpn`; config `/etc/openvpn/server.conf`, plus the link `/etc/openvpn/openvpn.conf -> server.conf` | `openvpn-server@server`; config `/etc/openvpn/server/server.conf` |
| nginx site | `/etc/nginx/http.d/ovpmon.conf` | `/etc/nginx/conf.d/ovpmon.conf` |
| doas | package `doas`; our rules in `/etc/doas.d/ovpmon.conf` (own file, as on the existing hosts) | package `opendoas`; our rules as a marked block inside `/etc/doas.conf` |
| `ovpmon` user | `adduser -S`, shell `/sbin/nologin` | `useradd --system`, shell `/usr/sbin/nologin` |
The nginx site does not collide with the distribution defaults: the default server of Alpine and Debian listens on port 80, ours on 8088, and both distribution `nginx.conf` files include the directory above (the installer checks the `include` line).
### What `install.sh` does
| Phase | Content |
|---|---|
| 0 Preflight | root, OS and version, service manager present, no existing installation (otherwise it points to `update.sh`), source checkout complete, UI archive readable, 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`, a self-signed EC certificate (`/etc/ovpmon/tls/`, SAN: host name, detected IP, `127.0.0.1`, `localhost`), the nginx site, nginx enabled and reloaded |
| 7 Start and checks | services started; health checks (below) |
| 8 Administrator | when a user exists in the monitoring database, the seed is removed from `/etc/ovpmon/env` and `ovpmon-api` is restarted; if the database cannot be read or is empty the seed stays and a warning says so |
Health checks: the three services are running; `http://127.0.0.1:5001/` answers; `http://127.0.0.1:8000/` returns 200; `https://127.0.0.1:<port>/` (with `-k`) returns 200; `/api/v1/user/me` and `/profiles-api/config` through nginx return 401 without a token.
The final summary shows the URL, the certificate fingerprint, the paths and the **generated administrator password once**. The state is recorded in `/etc/ovpmon/deploy.state` (prefix, HTTPS port, OS, version, dates). If the script fails it is **safe to run again**: it resumes, keeps the existing secret, certificate, easy-rsa workspace and data.
Then in the UI: sign in, change the password and enable 2FA, **PKI Configuration -> Initialize PKI**, generate the server configuration, start the VPN server.
### Without the script (outline)
Create the `ovpmon` user and the directories, copy the code, build both virtualenvs, write `/etc/ovpmon/env`, `helper.conf` and the doas rules from the templates, install the service definitions (`DOCS/General/systemd/*.service` or `DOCS/General/openrc/ovpmon-*`; replace `/opt/OpenVPN-Monitoring-Simple` if you use another prefix), copy the UI, add the nginx site from `deploy/native/nginx/ovpmon.conf.template` (replace `@HTTPS_PORT@`, `@WEB_ROOT@`, `@TLS_CRT@`, `@TLS_KEY@`). The commands are exactly what `install.sh` runs; reading the script is the shortest reference.
## Layout: what is where, who owns it
| Item | Path | Owner, mode |
|---|---|---|
| Code | `<prefix>/APP_CORE`, `<prefix>/APP_PROFILER` | `root:root`, read-only for others |
| Virtualenvs | `<prefix>/APP_CORE/venv`, `<prefix>/APP_PROFILER/venv` | `root:root` |
| **PKI** (CA, keys, certificates, CRL) | `<prefix>/APP_PROFILER/easy-rsa` (real directory) | `ovpmon:ovpmon` 750 |
| **Client profiles** | `<prefix>/APP_PROFILER/client-config` (real directory) | `ovpmon:ovpmon` 750 |
| Profiler log | `<prefix>/APP_PROFILER/profiler.log` | `ovpmon:ovpmon` 640 |
| Shipped settings file | `<prefix>/APP_CORE/config.ini`, `<prefix>/APP_PROFILER/config.ini` | `root:root`; the environment file overrides it |
| **Databases** | `/var/lib/ovpmon/openvpn_monitor.db`, `ovpn_profiler.db`, migration copies `*.db.bak-*` | `ovpmon:ovpmon` |
| Staging of `server.conf` | `/var/lib/ovpmon/staging/` | `ovpmon:ovpmon` 750 |
| Service environment | `/etc/ovpmon/env` | `root:root` 600 |
| Helper configuration | `/etc/ovpmon/helper.conf` | `root:root` 644 |
| TLS certificate and key | `/etc/ovpmon/tls/ovpmon.crt`, `ovpmon.key` | `root:root` (key 600) |
| Deployment state | `/etc/ovpmon/deploy.state` | `root:root` 644 |
| Root helper | `/usr/local/sbin/ovpmon-helper` | `root:root` 755 |
| doas rules | Alpine: `/etc/doas.d/ovpmon.conf`; Debian/Ubuntu: block in `/etc/doas.conf` | `root:root` |
| OpenVPN configuration | `/etc/openvpn/server.conf` (Alpine) or `/etc/openvpn/server/server.conf`, `/etc/openvpn/crl.pem`, `/etc/openvpn/scripts/` | `root:root` |
| OpenVPN logs | `/var/log/openvpn/openvpn.log`, `openvpn-status.log` (`root:ovpmon` 640) | `root` |
| Service logs | `/var/log/ovpmon/` (OpenRC) or the journal (systemd) | `ovpmon` / systemd |
| UI files | `/var/www/ovpmon` | `root:root` |
| Backups | `/var/backups/ovpmon/<UTC timestamp>/` | `root:root` 700 |
| Deployment log | `/var/log/ovpmon-deploy.log` | `root:root` 600 |
The profiler resolves `easy-rsa/` and `client-config/` relative to its working directory (`APP_PROFILER`) and keeps `client-config/<name>.ovpn` as a relative path in its database; therefore both are real directories inside `APP_PROFILER` (a symlinked `client-config` breaks the real-path checks and the `clear_pki` cleanup).
## Environment file and helper configuration
`/etc/ovpmon/env` (`root:root` 600) is read by the init system as root and handed to the services. Lines are `KEY=VALUE` without quotes or spaces (systemd and OpenRC read the same file).
| Variable | Default written by `install.sh` | Meaning |
|---|---|---|
| `OVPMON_API_SECRET_KEY` | random, 64 hex characters | signing key of both APIs; changing it logs everybody out; keep it across updates |
| `OVPMON_API_HOST`, `OVPMON_API_PORT` | `127.0.0.1`, `5001` | informational: gunicorn is started with `-b 127.0.0.1:5001` |
| `OVPMON_OPENVPN_MONITOR_DB_PATH` | `/var/lib/ovpmon/openvpn_monitor.db` | monitoring database |
| `OVPMON_PROFILER_DB_PATH` | `/var/lib/ovpmon/ovpn_profiler.db` | profiler database |
| `OVPMON_OPENVPN_MONITOR_LOG_PATH` | `/var/log/openvpn/openvpn-status.log` | status log read by the gatherer |
| `OVPMON_LOGGING_LEVEL` | `INFO` | |
| `OVPMON_CORS_ORIGINS` | `https://<host>:<https-port>` | extra allowed origin (the UI is same-origin behind nginx) |
| `OVPMON_RUNTIME` | `host` | forces host mode (never "container"), needed when the host itself runs inside a container |
| `OVPMON_OPENVPN_SERVICE` | `openvpn` (Alpine) / `openvpn-server@server` | service name for the root (non-helper) path |
| `OVPMON_OPENVPN_CONFIG` | `/etc/openvpn/server.conf` / `/etc/openvpn/server/server.conf` | server config path for the root (non-helper) path |
| `OVPMON_INITIAL_ADMIN_USER`, `OVPMON_INITIAL_ADMIN_PASSWORD` | generated | seed, only while the users table is empty; removed by `install.sh` after the first start |
| `OVPMON_AUTO_MIGRATE` | unset | `0` makes the services refuse to start while migrations are pending |
With the unprivileged profiler the API only stages `server.conf`; **the helper configuration decides where it is installed and which service is controlled.**
`/etc/ovpmon/helper.conf` (INI, section `[helper]`, `root:root`, not group/world writable, otherwise the helper refuses to run). Without the file the helper uses the built-in values of the Alpine layout.
| Key | Alpine (written) | Debian/Ubuntu (written) | Rule |
|---|---|---|---|
| `install_dir` | `/opt/OpenVPN-Monitoring-Simple` | same | absolute, no `..`; the PKI is `<install_dir>/APP_PROFILER/easy-rsa/pki` |
| `service_manager` | `openrc` | `systemd` | `openrc` or `systemd` |
| `service_unit` | `openvpn` | `openvpn-server@server` | `^[A-Za-z0-9@._-]{1,64}$`, not starting with `-` or `.` |
| `config_path` | `/etc/openvpn/server.conf` | `/etc/openvpn/server/server.conf` | absolute, below `/etc/openvpn/`, ends with `.conf` |
| `staged_path` | `/var/lib/ovpmon/staging/server.conf` | same | absolute, below `/var/lib/ovpmon/` |
OpenRC runs `/sbin/rc-service <unit> <action>`, systemd runs `systemctl <action> <unit>` (fixed argument list, fixed `PATH`). Unknown keys or invalid values make the helper refuse.
## Firewall, NAT and forwarding (manual)
The scripts **never touch the firewall**. `net.ipv4.ip_forward=1` is set persistently in `/etc/sysctl.d/98-ovpmon-forward.conf`. You open the ports and give the VPN clients access yourself. 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 # also replace the UI files
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, UI archive readable, services state, databases found, free space (backup and new code) | nothing was changed |
| 1 **Backup** | verified backup in `/var/backups/ovpmon/<UTC timestamp>/` (see below) | the update is **refused**, nothing was changed |
| 2 Sources | `git pull --ff-only` of the source checkout (skipped with `--no-pull` or without git) | nothing was changed |
| 3 Prepare | new code copied to `<prefix>.new`, fresh virtualenvs with `pip install -r requirements.txt`, import check; new UI extracted next to the web root. **The running system is not touched** | nothing was changed |
| 4 Stop and swap | the three application services are stopped (**OpenVPN keeps running**, VPN users stay connected); a final consistent snapshot; each code directory is renamed to `<dir>.old-<time>`, the new one moved in; **PKI, client profiles, `profiler.log`, `config.ini` and any database files below the code directory are moved over, never replaced**; virtualenv paths fixed | automatic rollback |
| 5 **Database migration** | its own step, see below | automatic rollback, **nothing is started** |
| 6 Files | UI swap; helper; `helper.conf` (when missing); doas rules; service definitions; missing environment keys added (existing values never changed); nginx site; each replaced only when it differs and is managed by these scripts; units reloaded | automatic rollback |
| 7 Start | services started, health checks, helper self-test | automatic rollback |
| 8 Finish | the old code directories are removed (never one that still holds PKI data), the newest 5 backups kept, state recorded | |
The new `deploy/native/*.sh` take effect on the next run (the running script is not replaced).
### Database migration as its own step
After the services are stopped and the new code is in place, and **before anything is started**, `update.sh` runs for each database, with the **new** code, as user `ovpmon` and with the variables of `/etc/ovpmon/env` loaded:
| Database | Command (working directory) |
|---|---|
| Profiler | `APP_PROFILER/venv/bin/python migrate.py` in `<prefix>/APP_PROFILER` |
| Monitoring | `APP_CORE/venv/bin/python migrate.py` in `<prefix>/APP_CORE` |
For each one: `migrate.py --check` (exit 0 up to date, 2 pending, 1 error or database newer than the code), the migration when 2, and a second check. The reports are printed. A failure or a "too new" database aborts **before any service starts** and triggers the rollback. Migrations are additive, run after an integrity check and a consistent copy `<db>.bak-<UTC timestamp>` next to the database, and are verified afterwards; details in [Database migrations](../General/Database_Migrations.md). The migration also runs by itself when a service starts, so a manual file replacement is safe too; `update.sh` only makes it a visible, controlled step.
### Backup (phase 1, `backup.sh`)
```sh
deploy/native/backup.sh # backup into /var/backups/ovpmon/<UTC timestamp>/
deploy/native/backup.sh --stop # services stopped during the copy, started afterwards
deploy/native/backup.sh --keep 14 # afterwards keep the newest 14
```
Cron example (nightly, 14 kept): `30 3 * * * /opt/OpenVPN-Monitoring-Simple/deploy/native/backup.sh --keep 14 >> /var/log/ovpmon-backup.log 2>&1`.
| Content | File in the backup |
|---|---|
| both databases, consistent copies from the SQLite backup API (integrity-checked, owner and mode kept) | `db/monitor.db`, `db/profiler.db` |
| `/etc/ovpmon` (environment, helper configuration, certificate, state) | `etc-ovpmon.tar.gz` |
| `/etc/openvpn` (`server.conf`, `crl.pem`, scripts, `ipp.txt`) | `etc-openvpn.tar.gz` |
| PKI `APP_PROFILER/easy-rsa` | `easy-rsa.tar.gz` |
| client profiles `APP_PROFILER/client-config` | `client-config.tar.gz` |
| `APP_CORE` and `APP_PROFILER` including the virtualenvs (needed for rollback) | `code.tar.gz` |
| helper, service definitions, nginx site, sysctl file, doas file (Alpine) | `system.tar.gz` |
| doas block (Debian/Ubuntu) | `doas-block.txt` |
| UI files | `ui.tar.gz` |
| checksums, description, completion marker | `SHA256SUMS`, `MANIFEST`, `COMPLETE` |
Every archive is verified (`tar -tzf`), the checksums are checked and each database copy passes `PRAGMA integrity_check` before `COMPLETE` is written; **only a `COMPLETE` backup is ever used**. `update.sh` backs up twice: in phase 1, and again as a final snapshot once the services are stopped (the code archive is reused). The backup holds private keys, password hashes and the signing secret: the directory is mode 700, the files mode 600. Keep copies off the host.
### Restore
```sh
deploy/native/restore.sh /var/backups/ovpmon/20261005T101500Z # asks, stops, saves the current state, restores
deploy/native/restore.sh /var/backups/ovpmon/20261005T101500Z --yes --start
```
It verifies the backup, stops the three application services, saves the **current state** to `/var/backups/ovpmon/<time>-pre-restore` (`OVPMON_NO_SAFETY_BACKUP=1` skips this), then restores code, databases, `/etc/ovpmon`, `/etc/openvpn`, PKI, client profiles, helper, service definitions, nginx site, UI and doas rules. A replaced database is kept as `<db>.failed-<time>`. OpenVPN is not stopped. On a new host run `install.sh` first, then `restore.sh`.
Manual equivalent (services stopped, paths for the default prefix):
```sh
B=/var/backups/ovpmon/20261005T101500Z
( cd $B && sha256sum -c SHA256SUMS )
tar -xzpf $B/code.tar.gz -C /opt/OpenVPN-Monitoring-Simple # after moving the current APP_CORE and APP_PROFILER aside
tar -xzpf $B/easy-rsa.tar.gz -C /opt/OpenVPN-Monitoring-Simple/APP_PROFILER
tar -xzpf $B/client-config.tar.gz -C /opt/OpenVPN-Monitoring-Simple/APP_PROFILER
cp -p $B/db/profiler.db /var/lib/ovpmon/ovpn_profiler.db # the backup was made with the sqlite backup API
cp -p $B/db/monitor.db /var/lib/ovpmon/openvpn_monitor.db
tar -xzpf $B/etc-ovpmon.tar.gz -C / && tar -xzpf $B/etc-openvpn.tar.gz -C /
tar -xzpf $B/system.tar.gz -C / # helper, service definitions, nginx site
```
A single database can also be put back from its migration copy `<db>.bak-<time>` in `/var/lib/ovpmon`: stop the services, copy it over the database, start the OLD release.
### Automatic rollback and `--rollback`
On any failure from phase 4 on: the services are stopped, **code, databases, `/etc/ovpmon`, `/etc/openvpn`, helper, doas rules, service definitions, nginx site and UI files are restored from the backup of this run**, the services are started and checked, and the result is reported with the backup path.
How the code is restored: the current (new or half-swapped) code directories are renamed to `<dir>.rollback-<time>`, `code.tar.gz` is extracted (old code **and old virtualenvs**, so no Internet is needed), and the PKI and client profiles, which the update never replaced, are moved back from the directory that held them. They are restored from `easy-rsa.tar.gz` / `client-config.tar.gz` only if they are missing. The failed databases are kept as `<db>.failed-<time>`. If the rollback itself fails the message says where the backup is and how to retry (`update.sh --rollback` or `restore.sh`).
`update.sh --rollback` does the same by hand from the newest `COMPLETE` backup after a confirmation, with one difference: PKI and client profiles come from the backup too (one consistent set with the databases), and the current state is saved first to `<time>-pre-restore`. Use it when an update succeeded but the new version misbehaves. Data created after that backup is lost (it is in the `-pre-restore` copy).
## Existing installations (adoption)
A host that was set up by hand (the layout of the old guide: code in `/opt/OpenVPN-Monitoring-Simple`, `/etc/ovpmon/env`, init scripts or units, helper and doas rules) can be updated with `update.sh`: it has no state file, so it is adopted and recorded after the first successful update. Files that these scripts do not manage are **left as they are**: init scripts, units, an nginx site and a doas file that do not carry the marker line `managed by ovpmon deploy/native` and differ from the shipped ones are only reported. The helper is replaced (the new one behaves like the old one without `helper.conf`), `helper.conf` is written when missing, and `OVPMON_RUNTIME`, `OVPMON_OPENVPN_SERVICE` and `OVPMON_OPENVPN_CONFIG` are added to the environment file only when absent. If the install directory is a git checkout (the source is the install directory), `git pull` changes the live files, therefore a rollback is armed from phase 2.
## What is preserved on update
| Item | On update |
|---|---|
| Databases | Kept in place, backed up twice (consistent copies), migrated additively with their own `<db>.bak-*` copy; restored automatically if the update fails after the stop |
| PKI (`APP_PROFILER/easy-rsa`): CA, keys, certificates, CRL | Moved, never replaced or deleted, backed up |
| Client profiles (`APP_PROFILER/client-config`) | Moved, never replaced or deleted, backed up |
| `/etc/ovpmon/env` (secret, DB paths) | Kept; only missing keys are added; copied into every backup |
| `/etc/ovpmon/helper.conf`, TLS certificate and key | Kept (helper.conf is rewritten only while it carries our marker and differs) |
| `/etc/openvpn` (`server.conf`, `crl.pem`, scripts, `ipp.txt`) | Not touched by the update; backed up |
| OpenVPN process and VPN sessions | Not stopped or restarted; connected users stay connected |
| `config.ini` of both components | Kept; the shipped one of the new version is saved as `config.ini.dist` when it differs |
| `profiler.log`, other `*.log` / `*.db` files below the code directories | Kept (moved) |
| Code, virtualenvs | **Replaced** (fresh virtualenvs; the old ones are in the backup) |
| UI files | Replaced only with `--ui-dist`; the previous ones are in the backup |
| Service definitions, nginx site, doas rules, helper | Replaced when they differ and are managed by these scripts; the previous ones are in the backup |
| User sessions | Stay valid while the secret is unchanged |
| Backups in `/var/backups/ovpmon` | The newest 5 kept, older ones pruned after a successful update; `-pre-restore` copies are never pruned automatically |
| Data directories (`/var/lib/ovpmon`, PKI, client profiles) | **Never deleted** by any script |
## Troubleshooting
| Symptom | Cause and action |
|---|---|
| `already installed ... use update.sh` / `an installation already exists` | `install.sh` never installs over an installation. Use `update.sh` (it adopts hand-made installations) |
| `installation stopped in phase ...` | Fix the cause and run `install.sh` again: it resumes and keeps secrets, certificate and data |
| `not a tested version ... needs --force` | Untested OS version: `install.sh --force` at your own risk |
| `ports ... already in use` | Another service uses 5001, 8000 or the HTTPS port: stop it or use `--https-port` |
| `pip install failed` | No access to the Python package index (proxy: `pip` honours `HTTPS_PROXY`); on Alpine check that `py3-pip` is installed |
| Health check fails | Alpine: `tail /var/log/ovpmon/ovpmon-api.log` (or `-gatherer`, `-profiler`); systemd: `journalctl -u ovpmon-api -n 50`. The scripts print the last lines of a failing service |
| `FATAL: ... newer than this version` / migration "too new" | The database was migrated by a newer release. Do not start the old version on it: update to the newer sources or restore a matching backup |
| Migration failed | Nothing was started and the rollback restored the databases; the report names the migration, the `<db>.bak-*` copy is in `/var/lib/ovpmon`. Keep the report |
| Profiler cannot start/stop OpenVPN, "helper failed" | The self-test warning of the scripts points at it: check the doas rules (`doas -C /etc/doas.conf` or `/etc/doas.d/ovpmon.conf`), `/etc/ovpmon/helper.conf` (must be `root:root` and not group/world writable; `su -s /bin/sh ovpmon -c "doas -n /usr/local/sbin/ovpmon-helper service status"` prints the reason) |
| `Configuration rejected` when generating the server config | The helper allowlist refused a directive, see [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md) |
| OpenVPN does not start on Debian/Ubuntu | `systemctl status openvpn-server@server`, `journalctl -u openvpn-server@server`; the config must be `/etc/openvpn/server/server.conf` and `/dev/net/tun` must exist |
| Clients connect but have no internet | Forwarding or NAT is missing: see the firewall section |
| nginx: `conflicting server name` / port in use | Another site uses the same port; change `--https-port` (or the `listen` line of the site and reload) |
| Browser warns about the certificate | It is self-signed; check the fingerprint printed by `install.sh`, or install a real certificate under `/etc/ovpmon/tls/` and reload nginx |
| UI shows the placeholder page | Installed without `--ui-dist`: `deploy/native/update.sh --ui-dist FILE` |
| `su`/`doas` self-test fails on a minimal container | Containers often lack `/etc/pam.d/doas` or a real init system; the services may still work (check health) |
## Host hardening (recommended, not done by the scripts)
- SSH: key-only (`PasswordAuthentication no`, `KbdInteractiveAuthentication no`, `PermitRootLogin prohibit-password`). Cloud-init drop-ins in `/etc/ssh/sshd_config.d/` can override the main file, so put your settings in a file that sorts first, for example `00-hardening.conf`.
- fail2ban: jails `sshd` and one for `POST /api/auth/login` (HTTP 401/429/503) on the nginx access log.
- Backends are bound to `127.0.0.1`; only the HTTPS port and the VPN port should be reachable from outside.
- Keep the system updated (`apk upgrade` / `apt-get upgrade`) and watch the advisories of OpenVPN, nginx and OpenSSH.
## Verify an installation
```sh
rc-status | grep -E "ovpmon|nginx|openvpn" # Alpine; Debian/Ubuntu: systemctl status 'ovpmon-*' nginx
ss -tlnp | grep -E ":(8088|5001|8000) "
curl -sk -o /dev/null -w "%{http_code}\n" https://127.0.0.1:8088/ # 200
curl -sk -o /dev/null -w "%{http_code}\n" https://127.0.0.1:8088/profiles-api/config # 401 without a token
su -s /bin/sh ovpmon -c "doas -n /usr/local/sbin/ovpmon-helper service status" # JSON, not "Operation not permitted"
```
## Security notes
- Services run as `ovpmon` (no login shell); code and virtualenvs are root-owned and read-only for them. systemd units add `PrivateTmp`, `ProtectHome`, `ProtectSystem=full`, kernel and cgroup protection; `ovpmon-api` and `ovpmon-gatherer` also set `NoNewPrivileges`. `ovpmon-profiler` must **not** (it calls the setuid `doas`), must not use seccomp-based options either (`ProtectKernelTunables`, `ProtectKernelModules`, `RestrictRealtime`, `LockPersonality`, `SystemCallFilter`, ...): for an unprivileged unit systemd then sets NoNewPrivileges implicitly and `doas` fails with "not installed setuid" (check: `grep NoNewPrivs /proc/<main pid>/status` must show 0). It keeps `/etc/openvpn` writable, because the helper runs inside the profiler's mount namespace.
- The helper accepts six fixed commands, validates `server.conf` against an allowlist and reads its own root-owned configuration; nothing else runs as root. `ovpmon` owns the PKI including the CA key: a compromised profiler can issue client certificates (VPN access) but cannot become root.
- `/etc/ovpmon/env` is `root:root` 600 and never printed; the generated administrator password is shown once and removed from the file after the first start.
- Backups contain private keys, password hashes and the secret: mode 700/600, keep off-host copies encrypted.
- Both APIs listen on `127.0.0.1`; only nginx (HTTPS) and OpenVPN are reachable. Replace the self-signed certificate when a domain is available; consider restricting the UI by address or reaching it through the VPN.
- The scripts do not harden SSH or install fail2ban: see the next section.
Related: [Database migrations](../General/Database_Migrations.md), [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md), [Scenario 1: containers](Scenario1_Containers.md), [Deployment plan](../Changes/2026-10-05_Deployment_Scenarios_PLAN.md).
+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
+2 -1
View File
@@ -14,7 +14,7 @@ Nginx is the only public entry point: `/` UI, `/api/` Monitoring API, `/profiles
## Quick start
- **Containers:** `deploy/docker/install.sh --variant a|b`, open `http://<host>`. Details: [Scenario 1: containers](DOCS/Deployment/Scenario1_Containers.md) (update, backup, rollback included).
- **System services** (systemd / OpenRC, no containers): [Deployment: native](DOCS/General/Deployment_Native.md).
- **System services** (Alpine/OpenRC, Debian and Ubuntu/systemd, no containers): `deploy/native/install.sh`; details, update and rollback: [Scenario 2: system services](DOCS/Deployment/Scenario2_System_Services.md).
After the first start: sign in, open **PKI Configuration** → **Initialize PKI**, generate the server config, start OpenVPN, create profiles.
@@ -67,6 +67,7 @@ No default user is created. Seed the initial admin with `OVPMON_INITIAL_ADMIN_US
| 2026-10-04 | Server setup is closed until the PKI is initialized (VPN menu lock, 409 for configure/start/create client, Clear PKI blocked while OpenVPN runs) | [PKI dependency guard](DOCS/Changes/2026-10-04_PKI_Dependency_Guard.md) |
| 2026-10-05 | Database migrations with backup, integrity checks and downgrade protection; standalone `migrate.py` (phase 1 of install/update scenarios) | [Database migrations](DOCS/Changes/2026-10-05_DB_Migrations.md) |
| 2026-10-05 | Scenario 1: container install and update, variant A (one container) and B (per component); backup, restore, automatic rollback | [Scenario 1: containers](DOCS/Deployment/Scenario1_Containers.md) · [change](DOCS/Changes/2026-10-05_Scenario1_Containers.md) |
| 2026-10-05 | Scenario 2: install and update as system services on Alpine, Debian, Ubuntu; helper config for systemd; backup, restore, automatic rollback | [Scenario 2: system services](DOCS/Deployment/Scenario2_System_Services.md) · [change](DOCS/Changes/2026-10-05_Scenario2_System_Services.md) |
## Notes
+103
View File
@@ -0,0 +1,103 @@
#!/bin/sh
# Back up everything that matters of a system-services installation (usable from cron).
#
# deploy/native/backup.sh [--prefix DIR] [--stop] [--keep N]
#
# --prefix install directory (default: from /etc/ovpmon/deploy.state, else /opt/OpenVPN-Monitoring-Simple)
# --stop stop the application services during the backup and start them again afterwards
# (OpenVPN keeps running). The databases are copied with the SQLite backup API either way, so
# they are consistent without --stop; --stop only makes the PKI/client files and the databases
# one single moment in time
# --keep N afterwards keep only the newest N backups (default: keep all)
#
# Result: /var/backups/ovpmon/<UTC timestamp>/ (mode 700, files mode 600; OVPMON_BACKUP_DIR changes the root):
# database copies, /etc/ovpmon, /etc/openvpn, PKI (easy-rsa), client profiles, code with virtualenvs, helper,
# service definitions, nginx site, UI files, doas rules, MANIFEST, SHA256SUMS and COMPLETE (written last).
# Exit code 0 only if the backup was written and verified. Restore: deploy/native/restore.sh <directory>
# The backup holds private keys and password hashes: keep it private and store copies off the host.
# See DOCS/Deployment/Scenario2_System_Services.md
set -eu
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
. "$SCRIPT_DIR/lib.sh"
usage() {
sed -n '2,18p' "$0" | sed 's/^# \{0,1\}//'
}
PREFIX=""
STOP=0
KEEP=""
STOPPED=0
FORCE=1
cleanup() {
_rc=$?
set +e
if [ "$STOPPED" = 1 ]; then
log "starting the application services again"
start_app_services >/dev/null 2>&1 || warn "could not start all services again: start them (ovpmon-api, ovpmon-gatherer, ovpmon-profiler)"
STOPPED=0
fi
release_lock
exit "$_rc"
}
while [ $# -gt 0 ]; do
case "$1" in
--prefix) [ $# -ge 2 ] || die "--prefix needs a value"; PREFIX="$2"; shift 2 ;;
--stop) STOP=1; shift ;;
--keep) [ $# -ge 2 ] || die "--keep needs a value"; KEEP="$2"; shift 2 ;;
-h|--help) usage; exit 0 ;;
*) usage >&2; die "unknown option: $1" ;;
esac
done
case "$KEEP" in
""|[1-9]|[1-9][0-9]*) ;;
*) die "--keep must be a positive number" ;;
esac
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
need_root
check_os
require_init
check_gnu_tar
acquire_lock
[ -n "$PREFIX" ] || PREFIX=$(state_get OVPMON_PREFIX)
[ -n "$PREFIX" ] || PREFIX="$DEFAULT_PREFIX"
valid_prefix "$PREFIX" || die "invalid install directory '$PREFIX'"
[ -d "$PREFIX/APP_CORE" ] && [ -d "$PREFIX/APP_PROFILER" ] && [ -f "$ENV_FILE" ] \
|| die "no installation found (need $PREFIX/APP_CORE, $PREFIX/APP_PROFILER and $ENV_FILE): wrong --prefix?"
log "backup of the installation in $PREFIX"
mkdir -p "$BACKUP_ROOT"
chmod 700 "$BACKUP_ROOT"
_kb=$(du -sk "$PREFIX/APP_CORE" "$PREFIX/APP_PROFILER" "$DATA_DIR" "$ETC_DIR" /etc/openvpn "$WEB_ROOT" 2>/dev/null | awk '{ s += $1 } END { print s + 0 }')
_need=$(( _kb / 1024 + 50 ))
[ "$_need" -ge "$MIN_FREE_BACKUP_MB" ] || _need="$MIN_FREE_BACKUP_MB"
check_free "$BACKUP_ROOT" "$_need" "the backup"
BACKUP_DIR="$BACKUP_ROOT/$(stamp)"
[ ! -e "$BACKUP_DIR" ] || die "backup directory already exists: $BACKUP_DIR (retry in a second)"
mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR"
if [ "$STOP" = 1 ]; then
_any=0
for _s in $SERVICES; do svc_active "$_s" && _any=1; done
if [ "$_any" = 1 ]; then
log "stopping the application services for a single-moment copy"
STOPPED=1
stop_app_services || die "could not stop the services"
fi
fi
make_backup "$BACKUP_DIR" backup "$PREFIX" || die "the BACKUP FAILED (incomplete files in $BACKUP_DIR are never used by restore or rollback)"
if [ -n "$KEEP" ]; then
prune_backups "$KEEP"
fi
log "backup complete and verified: $BACKUP_DIR"
+70
View File
@@ -0,0 +1,70 @@
#!/bin/sh
# Build the web UI (APP_UI, Vue/Vite) in a Node 20 container into a tarball for install.sh / update.sh.
#
# deploy/native/build-ui.sh [-o FILE] [--image IMAGE]
#
# -o FILE output tarball (default: deploy/native/ui-dist.tar.gz); its top level is the content of dist/
# --image IMAGE Node image (default node:20-alpine, or OVPMON_NODE_IMAGE)
#
# Needs Docker on the machine that builds (not on the target host, which needs no Node at all).
# Nothing is written into the source tree: APP_UI is mounted read-only and copied inside the
# container; only the output file is created. Then, on the target host:
# deploy/native/install.sh --ui-dist deploy/native/ui-dist.tar.gz
# deploy/native/update.sh --ui-dist deploy/native/ui-dist.tar.gz
# See DOCS/Deployment/Scenario2_System_Services.md
set -eu
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
ROOT_DIR=$(cd "$SCRIPT_DIR/../.." && pwd)
log() { printf '%s %s\n' "$(date -u '+%Y-%m-%d %H:%M:%S')" "$*"; }
die() { log "ERROR: $*" >&2; exit 1; }
usage() { sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//'; }
OUT="$SCRIPT_DIR/ui-dist.tar.gz"
IMAGE="${OVPMON_NODE_IMAGE:-node:20-alpine}"
while [ $# -gt 0 ]; do
case "$1" in
-o) [ $# -ge 2 ] || die "-o needs a value"; OUT="$2"; shift 2 ;;
--image) [ $# -ge 2 ] || die "--image needs a value"; IMAGE="$2"; shift 2 ;;
-h|--help) usage; exit 0 ;;
*) usage >&2; die "unknown option: $1" ;;
esac
done
command -v docker >/dev/null 2>&1 || die "docker not found in PATH. This script builds the UI in a Node 20 container; install Docker on the build machine (the target host does not need it), or build APP_UI yourself (npm install && npm run build) and pack the content of dist/ as a .tar.gz with index.html at its top level"
docker info >/dev/null 2>&1 || die "the Docker daemon is not running or not accessible for this user (start it, use sudo or join the docker group)"
[ -f "$ROOT_DIR/APP_UI/package.json" ] || die "APP_UI/package.json not found in $ROOT_DIR"
case "$OUT" in /*) ;; *) OUT="$PWD/$OUT" ;; esac
OUT_DIR=$(dirname "$OUT")
OUT_NAME=$(basename "$OUT")
mkdir -p "$OUT_DIR"
OUT_DIR=$(cd "$OUT_DIR" && pwd)
TMP_NAME=".$OUT_NAME.tmp.$$"
trap 'rm -f "$OUT_DIR/$TMP_NAME"' EXIT
log "building the UI with $IMAGE (APP_UI is mounted read-only, nothing is written into the source tree)"
# npm ci when a lock file exists (reproducible), npm install otherwise (as the all-in-one Dockerfile)
docker run --rm \
-v "$ROOT_DIR/APP_UI":/src:ro \
-v "$OUT_DIR":/out \
-e TMP_NAME="$TMP_NAME" -e HOST_UID="$(id -u)" -e HOST_GID="$(id -g)" \
"$IMAGE" sh -c '
set -eu
mkdir /build
tar -C /src --exclude=node_modules --exclude=dist -cf - . | tar -C /build -xf -
cd /build
if [ -f package-lock.json ]; then npm ci --no-audit --no-fund; else npm install --no-audit --no-fund; fi
npm run build
[ -f dist/index.html ] || { echo "build produced no dist/index.html" >&2; exit 1; }
tar -czf "/out/$TMP_NAME" -C dist .
chown "$HOST_UID:$HOST_GID" "/out/$TMP_NAME"
' || die "the UI build failed (see the output above)"
tar -tzf "$OUT_DIR/$TMP_NAME" | grep -q -E '^(\./)?index\.html$' || die "the archive has no index.html"
mv "$OUT_DIR/$TMP_NAME" "$OUT"
trap - EXIT
log "UI archive written: $OUT ($(du -h "$OUT" | awk '{print $1}'))"
log "use it with: deploy/native/install.sh --ui-dist $OUT or deploy/native/update.sh --ui-dist $OUT"
+444
View File
@@ -0,0 +1,444 @@
#!/bin/sh
# Install OpenVPN Monitor & Profiler as system services (no containers): Alpine (OpenRC), Debian, Ubuntu (systemd).
#
# deploy/native/install.sh [--prefix DIR] [--ui-dist FILE] [--https-port N] [--host-name NAME]
# [--admin-user NAME] [--force]
#
# --prefix install directory (default /opt/OpenVPN-Monitoring-Simple): APP_CORE, APP_PROFILER, venvs
# --ui-dist UI tarball made by deploy/native/build-ui.sh (the host needs no Node). Without it a
# placeholder page is installed; add the UI later with update.sh --ui-dist
# --https-port HTTPS port of the web UI (default 8088)
# --host-name DNS name or IP of this host: certificate name and CORS origin (default: detected address)
# --admin-user login of the initial administrator (default: admin); the password is generated
# --force continue on an untested OS version / Debian derivative
#
# Run as root from a checkout of the repository. Refuses when an installation exists (use update.sh).
# After a failure it is safe to run again: every step is idempotent and nothing is generated twice.
# It does NOT touch the firewall: NAT/forwarding commands are printed and documented.
# See DOCS/Deployment/Scenario2_System_Services.md
set -eu
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
. "$SCRIPT_DIR/lib.sh"
usage() {
sed -n '2,18p' "$0" | sed 's/^# \{0,1\}//'
}
PREFIX="$DEFAULT_PREFIX"
UI_DIST=""
HTTPS_PORT=8088
HOST_NAME=""
ADMIN_USER="admin"
FORCE=0
CURRENT_PHASE="start"
while [ $# -gt 0 ]; do
case "$1" in
--prefix) [ $# -ge 2 ] || die "--prefix needs a value"; PREFIX="$2"; shift 2 ;;
--ui-dist) [ $# -ge 2 ] || die "--ui-dist needs a value"; UI_DIST="$2"; shift 2 ;;
--https-port) [ $# -ge 2 ] || die "--https-port needs a value"; HTTPS_PORT="$2"; shift 2 ;;
--host-name) [ $# -ge 2 ] || die "--host-name needs a value"; HOST_NAME="$2"; shift 2 ;;
--admin-user) [ $# -ge 2 ] || die "--admin-user needs a value"; ADMIN_USER="$2"; shift 2 ;;
--force) FORCE=1; shift ;;
-h|--help) usage; exit 0 ;;
*) usage >&2; die "unknown option: $1" ;;
esac
done
valid_prefix "$PREFIX" || die "invalid --prefix '$PREFIX' (absolute path of letters, digits, . _ - and /)"
valid_port "$HTTPS_PORT" || die "invalid --https-port '$HTTPS_PORT'"
case "$ADMIN_USER" in
""|*[!A-Za-z0-9._-]*) die "invalid --admin-user (letters, digits, . _ - only)" ;;
esac
case "$HOST_NAME" in
*[!A-Za-z0-9.-]*) die "invalid --host-name (letters, digits, . and - only)" ;;
esac
[ -z "$UI_DIST" ] || case "$UI_DIST" in /*) ;; *) UI_DIST="$PWD/$UI_DIST" ;; esac
SRC="$ROOT_DIR"
on_exit() {
_rc=$?
set +e
trap '' INT TERM
if [ "$_rc" -ne 0 ]; then
log "install stopped in phase '$CURRENT_PHASE'. Nothing is lost: fix the cause and run the script again (it resumes; existing secrets, certificates and data are kept)" >&2
fi
[ -z "${TMPD:-}" ] || rm -rf "$TMPD"
release_lock
exit "$_rc"
}
TMPD=$(mktemp -d /tmp/ovpmon-install.XXXXXX) || die "cannot create a temporary directory"
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="0 preflight"
phase 0 "preflight"
need_root
check_os
require_init
acquire_lock
# An existing installation is updated, not installed over
if [ -f "$STATE_FILE" ]; then
die "already installed (state file $STATE_FILE). To upgrade use: $SCRIPT_DIR/update.sh"
fi
if [ ! -f "$INCOMPLETE_MARK" ]; then
for _p in "$PREFIX/APP_CORE" "$PREFIX/APP_PROFILER" "$ENV_FILE" "$(unit_file ovpmon-api)"; do
if [ -e "$_p" ]; then
die "an installation already exists ($_p). install.sh never installs over one. To upgrade or adopt it use: $SCRIPT_DIR/update.sh"
fi
done
fi
[ -f "$SRC/APP_CORE/openvpn_api_v3.py" ] && [ -f "$SRC/APP_PROFILER/main.py" ] \
|| die "run the script from a complete checkout of the repository (APP_CORE and APP_PROFILER not found in $SRC)"
if [ -z "$UI_DIST" ] && [ -f "$SCRIPT_DIR/ui-dist.tar.gz" ]; then
UI_DIST="$SCRIPT_DIR/ui-dist.tar.gz"
log "using the UI archive $UI_DIST"
fi
if [ -n "$UI_DIST" ]; then
check_ui_archive "$UI_DIST"
else
warn "no --ui-dist: a placeholder page is installed instead of the web UI (build it with deploy/native/build-ui.sh, then update.sh --ui-dist FILE)"
fi
# ports: ours may already be bound when the script is resumed
if svc_active ovpmon-api 2>/dev/null; then
log "ovpmon services are already running (resumed install): application ports not checked"
else
check_port 5001 tcp "monitoring API"
check_port 8000 tcp "profiler API"
fi
if [ ! -f "$NGINX_SITE" ]; then
check_port "$HTTPS_PORT" tcp "HTTPS (UI)"
fi
if port_in_use 1194 udp; then log "note: 1194/udp is in use; OpenVPN uses the port set in the server settings of the UI"; fi
check_free "$PREFIX" "$MIN_FREE_PREFIX_MB" "the installation (code and virtualenvs)"
check_free /var/lib 256 "data"
mkdir -p "$ETC_DIR"
chmod 755 "$ETC_DIR"
: > "$INCOMPLETE_MARK"
chmod 600 "$INCOMPLETE_MARK"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="1 packages"
phase 1 "packages"
log "installing: $PKG_LIST"
# shellcheck disable=SC2086
pkg_install $PKG_LIST
check_gnu_tar
python3 -c 'import sys, sqlite3, venv; sys.exit(0 if sys.version_info >= (3, 9) else 1)' \
|| die "Python 3.9 or newer with the sqlite3 and venv modules is required (found: $(python3 --version 2>&1))"
for _c in curl openssl nginx openvpn; do
command -v "$_c" >/dev/null 2>&1 || die "$_c is not available after the package installation"
done
[ -f "$EASYRSA_SRC/easyrsa" ] || die "$EASYRSA_SRC/easyrsa not found (package easy-rsa)"
check_nginx_include
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="2 user and directories"
phase 2 "service user and directories"
ensure_service_user
ensure_dir "$DATA_DIR" "$SERVICE_USER:$SERVICE_USER" 750
ensure_dir "$DATA_DIR/staging" "$SERVICE_USER:$SERVICE_USER" 750
ensure_dir "$APP_LOG_DIR" "$SERVICE_USER:$SERVICE_USER" 750
ensure_dir "$OVPN_LOG_DIR" root:root 755
# distribution-owned directories are only created when missing, never re-owned
for _d in /etc/openvpn "$(dirname "$OVPN_CONFIG")"; do
if [ ! -d "$_d" ]; then mkdir -p "$_d"; chmod 755 "$_d"; fi
done
ensure_dir /etc/openvpn/scripts root:root 755
# status log: written by OpenVPN (root), read by the gatherer (group ovpmon); the helper keeps these rights
if [ ! -e "$OVPN_LOG_DIR/openvpn-status.log" ]; then : > "$OVPN_LOG_DIR/openvpn-status.log"; fi
chown root:"$SERVICE_USER" "$OVPN_LOG_DIR/openvpn-status.log"
chmod 640 "$OVPN_LOG_DIR/openvpn-status.log"
log "directories ready: $DATA_DIR, $APP_LOG_DIR, $OVPN_LOG_DIR, /etc/openvpn/scripts, $ETC_DIR"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="3 code"
phase 3 "application code to $PREFIX"
mkdir -p "$PREFIX"
chmod 755 "$PREFIX"
copy_component "$SRC/APP_CORE" "$PREFIX/APP_CORE"
copy_component "$SRC/APP_PROFILER" "$PREFIX/APP_PROFILER"
sync_deploy_files "$SRC" "$PREFIX"
echo "$(version_of "$SRC")" > "$PREFIX/VERSION"
log "code installed (version $(cat "$PREFIX/VERSION")); the virtualenvs and data are not part of the copy"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="4 virtualenvs and easy-rsa"
phase 4 "Python virtualenvs and the easy-rsa workspace"
make_venv "$PREFIX/APP_CORE" gunicorn
make_venv "$PREFIX/APP_PROFILER"
smoke_component "$PREFIX/APP_CORE" core || die "the APP_CORE virtualenv cannot import the application's dependencies"
smoke_component "$PREFIX/APP_PROFILER" profiler || die "the APP_PROFILER virtualenv cannot import the application's dependencies"
log "dependencies import correctly"
# easy-rsa workspace: real directory owned by the service user (never a symlink); never overwritten
if [ ! -f "$PREFIX/APP_PROFILER/easy-rsa/easyrsa" ]; then
mkdir -p "$PREFIX/APP_PROFILER/easy-rsa"
cp -R "$EASYRSA_SRC"/. "$PREFIX/APP_PROFILER/easy-rsa/"
chown -R "$SERVICE_USER:$SERVICE_USER" "$PREFIX/APP_PROFILER/easy-rsa"
chmod 750 "$PREFIX/APP_PROFILER/easy-rsa"
log "easy-rsa workspace created from $EASYRSA_SRC"
else
log "easy-rsa workspace exists: kept"
fi
ensure_runtime_files "$PREFIX"
lock_down_code "$PREFIX/APP_CORE" "$PREFIX/APP_PROFILER"
compile_code "$PREFIX/APP_CORE"
compile_code "$PREFIX/APP_PROFILER"
log "code and virtualenvs are root-owned and read-only for the service user; easy-rsa, client-config and profiler.log belong to $SERVICE_USER"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="5 configuration"
phase 5 "configuration: environment file, root helper, doas, forwarding"
detect_ip() {
local ip
ip=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p' | head -n 1 || true)
[ -n "$ip" ] || ip=$(hostname -i 2>/dev/null | awk '{print $1}' || true)
case "$ip" in ""|127.*) ip="" ;; esac
printf '%s' "$ip"
}
HOST_IP=$(detect_ip)
CERT_HOST="${HOST_NAME:-${HOST_IP:-localhost}}"
SHOW_USER=""
SHOW_PASSWORD=""
if [ -f "$ENV_FILE" ]; then
log "$ENV_FILE exists and is kept as it is"
else
SECRET=$(openssl rand -hex 32 2>/dev/null || true)
[ "${#SECRET}" -eq 64 ] || SECRET=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')
[ "${#SECRET}" -eq 64 ] || die "cannot generate a random secret"
ADMIN_PASSWORD=$(LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 24)
[ "${#ADMIN_PASSWORD}" -eq 24 ] || die "cannot generate a random password"
(
umask 077
{
echo "# Created by deploy/native/install.sh on $(date -u '+%Y-%m-%d %H:%M:%S') UTC. root:root 600: keep it private, never commit it."
echo "# Read by the init system (systemd EnvironmentFile / OpenRC start_pre) as root; the services run as $SERVICE_USER."
echo "OVPMON_API_SECRET_KEY=$SECRET"
echo "OVPMON_API_HOST=127.0.0.1"
echo "OVPMON_API_PORT=5001"
echo "OVPMON_OPENVPN_MONITOR_DB_PATH=$DATA_DIR/openvpn_monitor.db"
echo "OVPMON_OPENVPN_MONITOR_LOG_PATH=$OVPN_LOG_DIR/openvpn-status.log"
echo "OVPMON_PROFILER_DB_PATH=$DATA_DIR/ovpn_profiler.db"
echo "OVPMON_LOGGING_LEVEL=INFO"
echo "OVPMON_CORS_ORIGINS=https://$CERT_HOST:$HTTPS_PORT"
echo "# This is a host install, never a container (matters when the host itself runs inside a container)"
echo "OVPMON_RUNTIME=host"
echo "OVPMON_OPENVPN_SERVICE=$OVPN_SERVICE"
echo "OVPMON_OPENVPN_CONFIG=$OVPN_CONFIG"
echo "# Initial administrator: used only while the users table is empty; install.sh removes these two lines after the first start"
echo "OVPMON_INITIAL_ADMIN_USER=$ADMIN_USER"
echo "OVPMON_INITIAL_ADMIN_PASSWORD=$ADMIN_PASSWORD"
} > "$ENV_FILE"
)
chown root:root "$ENV_FILE"
chmod 600 "$ENV_FILE"
unset SECRET ADMIN_PASSWORD
log "$ENV_FILE created (root:root 600, random secret)"
fi
# helper configuration (read by the root helper; strictly validated there)
_tmp="$TMPD/helper.conf"
helper_conf_text "$PREFIX" > "$_tmp"
if install_managed "$_tmp" "$HELPER_CONF" 644 "deploy/native/lib.sh helper_conf_text"; then log "$HELPER_CONF written (root:root 644)"; else log "$HELPER_CONF unchanged"; fi
[ -f "$HELPER_CONF" ] || die "$HELPER_CONF could not be written"
if install_helper "$SRC"; then log "helper installed: $HELPER_DEST (root:root 755)"; else log "helper unchanged: $HELPER_DEST"; fi
rc=0
install_doas "$SRC" || rc=$?
doas_target
case "$rc" in
0) log "doas rules installed ($DOAS_MODE: $DOAS_FILE)" ;;
1) log "doas rules unchanged ($DOAS_FILE)" ;;
2) warn "doas rules NOT installed: add the rules of DOCS/General/privilege-separation/doas-ovpmon.conf to $DOAS_FILE yourself" ;;
esac
if doas_selftest; then log "self-test: $SERVICE_USER can call the helper through doas"; else warn "the helper self-test failed: the profiler will not be able to configure or start OpenVPN until this is fixed"; fi
# IP forwarding (persistent) and the OpenVPN service prerequisites
printf '# %s\nnet.ipv4.ip_forward = 1\n' "$MARKER" > "$SYSCTL_FILE"
chmod 644 "$SYSCTL_FILE"
sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || warn "could not enable net.ipv4.ip_forward now (it is set for the next boot); on a container the host must allow it"
if [ "$INIT" = openrc ]; then
rc-update add sysctl boot >/dev/null 2>&1 || true
fi
if [ "$OS_FAMILY" = alpine ]; then
# the OpenRC service reads /etc/openvpn/openvpn.conf: link it to server.conf (as the helper does)
if [ ! -e /etc/openvpn/openvpn.conf ] && [ ! -L /etc/openvpn/openvpn.conf ]; then
ln -s server.conf /etc/openvpn/openvpn.conf
log "/etc/openvpn/openvpn.conf -> server.conf"
fi
fi
svc_enable "$OVPN_SERVICE" || warn "could not enable the OpenVPN service $OVPN_SERVICE"
log "OpenVPN service $OVPN_SERVICE enabled, NOT started (no server.conf yet: generate it in the UI first)"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="6 services, UI, nginx"
phase 6 "service definitions, web UI, TLS certificate and nginx"
for s in $SERVICES; do
_tmp="$TMPD/$s"
render_unit "$SRC" "$s" "$PREFIX" "$_tmp"
if [ "$INIT" = systemd ]; then _mode=644; else _mode=755; fi
rc=0
install_managed "$_tmp" "$(unit_file "$s")" "$_mode" "$(unit_src "$SRC" "$s")" || rc=$?
case "$rc" in
0) log "installed $(unit_file "$s")" ;;
1) log "unchanged $(unit_file "$s")" ;;
2) warn "$(unit_file "$s") is not ours: left untouched" ;;
esac
done
svc_defs_reload
for s in $SERVICES; do svc_enable "$s" || warn "could not enable $s"; done
log "services enabled at boot: $SERVICES"
# UI files
mkdir -p "$(dirname "$WEB_ROOT")"
if [ -n "$UI_DIST" ]; then
stage_ui "$UI_DIST" "$WEB_ROOT.new"
swap_dir "$WEB_ROOT.new" "$WEB_ROOT" "$WEB_ROOT.old"
rm -rf "$WEB_ROOT.old"
log "UI files installed to $WEB_ROOT from $UI_DIST"
elif [ ! -f "$WEB_ROOT/index.html" ]; then
mkdir -p "$WEB_ROOT"
cat > "$WEB_ROOT/index.html" <<'EOF'
<!doctype html><meta charset="utf-8"><title>OpenVPN Monitor</title>
<h1>OpenVPN Monitor</h1><p>The web UI is not installed yet. Build it with deploy/native/build-ui.sh and run deploy/native/update.sh --ui-dist FILE.</p>
EOF
chmod -R a+rX "$WEB_ROOT"
log "placeholder page written to $WEB_ROOT"
fi
# TLS certificate: self-signed, never regenerated
mkdir -p "$TLS_DIR"
chmod 750 "$TLS_DIR"
if [ -f "$TLS_DIR/ovpmon.crt" ] && [ -f "$TLS_DIR/ovpmon.key" ]; then
log "TLS certificate exists: kept ($TLS_DIR/ovpmon.crt)"
else
SAN="DNS:ovpmon,DNS:localhost,IP:127.0.0.1"
[ -z "$HOST_IP" ] || SAN="$SAN,IP:$HOST_IP"
if [ -n "$HOST_NAME" ] && [ "$HOST_NAME" != "$HOST_IP" ]; then
case "$HOST_NAME" in
*[!0-9.]*) SAN="$SAN,DNS:$HOST_NAME" ;;
*) SAN="$SAN,IP:$HOST_NAME" ;;
esac
fi
( umask 077
openssl req -x509 -nodes -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -days 825 \
-subj "/CN=$CERT_HOST" -addext "subjectAltName=$SAN" \
-keyout "$TLS_DIR/ovpmon.key" -out "$TLS_DIR/ovpmon.crt" >/dev/null 2>&1 ) \
|| die "cannot create the self-signed certificate"
chmod 600 "$TLS_DIR/ovpmon.key"
chmod 644 "$TLS_DIR/ovpmon.crt"
log "self-signed TLS certificate created for $SAN"
fi
# nginx site
_tmp="$TMPD/ovpmon.conf"
mkdir -p "$NGINX_CONF_DIR"
render_nginx "$SRC" "$HTTPS_PORT" "$_tmp"
rc=0
install_managed "$_tmp" "$NGINX_SITE" 644 "deploy/native/nginx/ovpmon.conf.template" || rc=$?
case "$rc" in
0) log "nginx site written: $NGINX_SITE (HTTPS on $HTTPS_PORT)" ;;
1) log "nginx site unchanged: $NGINX_SITE" ;;
2) die "$NGINX_SITE exists and is not ours; remove or rename it, then run the script again" ;;
esac
svc_enable nginx || warn "could not enable nginx at boot"
nginx_apply || die "nginx did not accept the configuration (see above)"
log "nginx running with the new site"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="7 start and health checks"
phase 7 "start the services and check them"
for s in $SERVICES; do
if svc_active "$s"; then
log "restarting $s (resumed install)"
svc_restart "$s" >/dev/null 2>&1 || { show_service_log "$s"; die "$s failed to restart"; }
else
log "starting $s"
svc_start "$s" >/dev/null 2>&1 || { show_service_log "$s"; die "$s failed to start"; }
fi
done
health_check "$HTTPS_PORT" || die "health checks failed (see above). Logs: $APP_LOG_DIR/ (OpenRC) or journalctl -u ovpmon-api -u ovpmon-gatherer -u ovpmon-profiler (systemd)"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="8 initial administrator"
phase 8 "initial administrator"
resolve_db_paths "$PREFIX"
if [ -n "$(env_get OVPMON_INITIAL_ADMIN_USER)$(env_get OVPMON_INITIAL_ADMIN_PASSWORD)" ]; then
COUNT=$(users_count "$DB_MONITOR" || true)
case "$COUNT" in
""|*[!0-9]*)
warn "cannot read the users table (got '$COUNT'): OVPMON_INITIAL_ADMIN_* are LEFT in $ENV_FILE. Remove them by hand after you have logged in, then restart ovpmon-api"
;;
0)
warn "the users table is empty: the administrator was not created. OVPMON_INITIAL_ADMIN_* stay in $ENV_FILE. Check the log of ovpmon-api"
;;
*)
SHOW_USER=$(env_get OVPMON_INITIAL_ADMIN_USER)
SHOW_PASSWORD=$(env_get OVPMON_INITIAL_ADMIN_PASSWORD)
env_remove_admin
log "$COUNT user(s) exist: OVPMON_INITIAL_ADMIN_* removed from $ENV_FILE, restarting ovpmon-api without them"
if ! svc_restart ovpmon-api >/dev/null 2>&1 || ! wait_http "monitoring API" "http://127.0.0.1:5001/" '[1-5][0-9][0-9]'; then
# the seed is gone from the file: the one-time credentials must not be lost
printf '\n Administrator (shown ONCE): login %s, password %s\n' "$SHOW_USER" "$SHOW_PASSWORD"
die "ovpmon-api did not come back after removing the seed (see its log)"
fi
;;
esac
else
COUNT=$(users_count "$DB_MONITOR" || true)
case "$COUNT" in
0) warn "no users exist and $ENV_FILE has no OVPMON_INITIAL_ADMIN_USER / OVPMON_INITIAL_ADMIN_PASSWORD: add them and restart ovpmon-api" ;;
*) log "users already exist: nothing to seed" ;;
esac
fi
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="finish"
state_set OVPMON_PREFIX "$PREFIX"
state_set OVPMON_HTTPS_PORT "$HTTPS_PORT"
state_set OVPMON_OS "$OS_ID $OS_VERSION_ID"
state_set OVPMON_VERSION "$(cat "$PREFIX/VERSION")"
[ -n "$(state_get OVPMON_INSTALLED_AT)" ] || state_set OVPMON_INSTALLED_AT "$(now_iso)"
rm -f "$INCOMPLETE_MARK"
UPLINK=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* dev \([^ ]*\).*/\1/p' | head -n 1 || true)
UPLINK="${UPLINK:-<uplink-interface>}"
FP=$(openssl x509 -noout -fingerprint -sha256 -in "$TLS_DIR/ovpmon.crt" 2>/dev/null | sed 's/^.*=//' || true)
printf '\n'
log "=== INSTALLED: $OS_ID $OS_VERSION_ID, $INIT, prefix $PREFIX ==="
printf ' Web UI: https://%s:%s/ (self-signed certificate; SHA-256 %s)\n' "${HOST_NAME:-${HOST_IP:-<server-address>}}" "$HTTPS_PORT" "${FP:-n/a}"
printf ' Config: %s (root:root 600), helper: %s, %s\n' "$ENV_FILE" "$HELPER_CONF" "$HELPER_DEST"
printf ' Data: %s (databases), %s/APP_PROFILER/easy-rsa (PKI), %s/APP_PROFILER/client-config\n' "$DATA_DIR" "$PREFIX" "$PREFIX"
printf ' Logs: %s, %s\n' "$APP_LOG_DIR" "$OVPN_LOG_DIR"
if [ -n "$SHOW_PASSWORD" ]; then
printf '\n Administrator (shown ONCE, it is not stored anywhere any more):\n'
printf ' login: %s\n' "$SHOW_USER"
printf ' password: %s\n' "$SHOW_PASSWORD"
fi
cat <<EOF
Next steps:
1. Open the Web UI and sign in; change the password and enable 2FA (Account).
2. PKI Configuration -> Initialize PKI (wait until it finishes).
3. Generate the server configuration and start the VPN server in the UI
(the profiler installs $OVPN_CONFIG through the root helper and controls $OVPN_SERVICE).
4. Firewall (NOT configured by this script): open ${HTTPS_PORT}/tcp and the VPN port (1194/udp by default),
and give the VPN clients internet access, for example (replace the subnet with the one of the server settings):
iptables -t nat -A POSTROUTING -s 172.20.1.0/24 -o $UPLINK -j MASQUERADE
iptables -A FORWARD -i tun+ -o $UPLINK -j ACCEPT
iptables -A FORWARD -i $UPLINK -o tun+ -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
net.ipv4.ip_forward is enabled ($SYSCTL_FILE). Persistence and nftables variants: see the guide.
5. Replace the self-signed certificate ($TLS_DIR/ovpmon.crt and .key) with a real one when a domain is available.
Update later with: $SCRIPT_DIR/update.sh Backup: $SCRIPT_DIR/backup.sh
Log of this run: $DEPLOY_LOG
EOF
+1135
View File
File diff suppressed because it is too large. Load diff
+75
View File
@@ -0,0 +1,75 @@
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# HTTPS site of OpenVPN Monitor & Profiler. Rendered by install.sh / update.sh: they fill in the HTTPS port
# (default 8088), the UI directory (/var/www/ovpmon) and the certificate and key paths (/etc/ovpmon/tls/ovpmon.crt
# and .key: self-signed by install.sh; replace them with a real certificate under the same names, or edit this
# file and remove the marker line above so that updates leave it alone).
# Installed to the nginx include directory (Alpine /etc/nginx/http.d, Debian/Ubuntu /etc/nginx/conf.d),
# both are included in the http {} block of the distribution nginx.conf. No ssl_session_cache is declared
# here on purpose: a second "shared:SSL" zone with another size would conflict with nginx.conf.
# Reference: DOCS/General/Nginx_Configuration.md, APP_UI/default.conf.template
# 5 login attempts per minute per client address (the application has its own lockout as well)
limit_req_zone $binary_remote_addr zone=ovpmon_login:1m rate=5r/m;
server {
listen @HTTPS_PORT@ ssl;
server_name _;
ssl_certificate @TLS_CRT@;
ssl_certificate_key @TLS_KEY@;
ssl_protocols TLSv1.2 TLSv1.3;
server_tokens off;
client_max_body_size 2m;
# Plain HTTP on the TLS port: redirect to HTTPS
error_page 497 =301 https://$host:@HTTPS_PORT@$request_uri;
# Security headers (declared only here: add_header in a location would drop these)
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "no-referrer" always;
add_header Cache-Control "no-store" always;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
root @WEB_ROOT@;
index index.html;
# UI (single-page application)
location / {
try_files $uri $uri/ /index.html;
}
# Login: rate limited
location = /api/auth/login {
limit_req zone=ovpmon_login burst=3 nodelay;
limit_req_status 503;
proxy_pass http://127.0.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# Monitoring API (Flask, APP_CORE)
location /api/ {
proxy_pass http://127.0.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass_header Authorization;
}
# Profiler API (FastAPI, APP_PROFILER): /profiles-api/x is /api/x inside the profiler
location /profiles-api/ {
proxy_pass http://127.0.0.1:8000/api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Prefix /profiles-api;
proxy_read_timeout 120s;
}
}
+91
View File
@@ -0,0 +1,91 @@
#!/bin/sh
# Restore an installation from a backup directory (made by backup.sh or update.sh).
#
# deploy/native/restore.sh BACKUP_DIR [--prefix DIR] [--yes] [--start]
#
# BACKUP_DIR e.g. /var/backups/ovpmon/20261005T101500Z
# --prefix install directory (default: from /etc/ovpmon/deploy.state, else /opt/OpenVPN-Monitoring-Simple)
# --start start the services after the restore (default: only print the command)
#
# The application services are stopped (after confirmation). The CURRENT state is first saved to
# <backups>/<timestamp>-pre-restore (OVPMON_NO_SAFETY_BACKUP=1 skips it); then code, databases,
# /etc/ovpmon, /etc/openvpn, PKI, client profiles, helper, service definitions, nginx site, UI and doas
# rules are put back from the backup. OpenVPN is not touched. The packages and the ovpmon user must
# exist (on a new host run install.sh first, then restore).
# See DOCS/Deployment/Scenario2_System_Services.md
set -eu
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
. "$SCRIPT_DIR/lib.sh"
usage() {
sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//'
}
PREFIX=""
ASSUME_YES=0
START=0
SRC=""
FORCE=1
RESTORE_STAMP=$(stamp)
while [ $# -gt 0 ]; do
case "$1" in
--prefix) [ $# -ge 2 ] || die "--prefix needs a value"; PREFIX="$2"; shift 2 ;;
--yes|-y) ASSUME_YES=1; shift ;;
--start) START=1; shift ;;
-h|--help) usage; exit 0 ;;
-*) usage >&2; die "unknown option: $1" ;;
*) [ -z "$SRC" ] || die "only one backup directory can be given"; SRC="$1"; shift ;;
esac
done
[ -n "$SRC" ] || { usage >&2; die "BACKUP_DIR is required"; }
[ -d "$SRC" ] || die "not a directory: $SRC"
SRC=$(abs_dir "$SRC")
trap release_lock EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
need_root
check_os
require_init
check_gnu_tar
acquire_lock
[ -n "$PREFIX" ] || PREFIX=$(state_get OVPMON_PREFIX)
[ -n "$PREFIX" ] || PREFIX=$(manifest_get "$SRC" prefix)
[ -n "$PREFIX" ] || PREFIX="$DEFAULT_PREFIX"
valid_prefix "$PREFIX" || die "invalid install directory '$PREFIX'"
getent passwd "$SERVICE_USER" >/dev/null 2>&1 || die "user $SERVICE_USER does not exist: run install.sh first"
BK_PREFIX=$(manifest_get "$SRC" prefix)
if [ -n "$BK_PREFIX" ] && [ "$BK_PREFIX" != "$PREFIX" ]; then
die "the backup was made for install directory '$BK_PREFIX', this host uses '$PREFIX' (use --prefix $BK_PREFIX)"
fi
log "backup: $SRC"
[ -f "$SRC/MANIFEST" ] && sed 's/^/ /' "$SRC/MANIFEST"
[ -f "$SRC/COMPLETE" ] || warn "the backup is not marked COMPLETE (an interrupted backup?)"
[ "$(manifest_get "$SRC" init)" = "$INIT" ] || warn "the backup comes from a host with service manager '$(manifest_get "$SRC" init)', this one uses '$INIT': service definitions and the helper configuration are restored as saved"
log "verifying the backup"
verify_backup "$SRC" || die "the backup is damaged or incomplete: nothing was changed"
log "code, databases, configuration, PKI and client profiles will be REPLACED by this backup (the current state is saved first)"
confirm "Stop the services and restore?" || die "aborted by the user"
stop_app_services || die "could not stop the application services"
if [ "${OVPMON_NO_SAFETY_BACKUP:-0}" != 1 ]; then
_safe="$BACKUP_ROOT/$(stamp)-pre-restore"
log "saving the current state first: $_safe"
mkdir -p "$BACKUP_ROOT"; chmod 700 "$BACKUP_ROOT"
make_backup "$_safe" pre-restore "$PREFIX" || die "the safety backup failed: nothing was changed"
fi
restore_all "$SRC" "$PREFIX" full || die "the restore failed (see above). The backup is intact: $SRC"
log "restore complete"
if [ "$START" = 1 ]; then
svc_defs_reload || true
start_app_services || die "the services did not start after the restore"
health_check "$(state_get OVPMON_HTTPS_PORT)" || die "the health checks failed after the restore"
else
log "start the services when ready: $(for _s in $SERVICES; do printf '%s ' "$_s"; done)(rc-service <name> start / systemctl start <name>)"
fi
+486
View File
@@ -0,0 +1,486 @@
#!/bin/sh
# Update OpenVPN Monitor & Profiler (system services) without touching the data.
#
# deploy/native/update.sh [--prefix DIR] [--ui-dist FILE] [--source DIR] [--no-pull] [--yes] [--rollback]
#
# --prefix install directory (default: from /etc/ovpmon/deploy.state, else /opt/OpenVPN-Monitoring-Simple)
# --ui-dist UI tarball from build-ui.sh; without it the UI files are left as they are
# --source checkout with the new version (default: the repository this script is in)
# --no-pull no "git pull --ff-only" of the source checkout (offline hosts, sources already in place)
# --yes no confirmation questions
# --rollback restore code, databases, configuration, PKI and client profiles from the newest backup
#
# Phases: 0 preflight, 1 BACKUP (verified, /var/backups/ovpmon/<UTC time>/), 2 git pull, 3 PREPARE the new
# code and virtualenvs next to the install dir (old code untouched), 4 STOP the application services (OpenVPN
# keeps running) and swap the code in, 5 DATABASE MIGRATION as its own step with the new code (nothing is
# started on an unmigrated database), 6 UI, nginx, helper, doas rules, service definitions, 7 START and health
# checks. A failure after the stop triggers an automatic rollback from the backup of this run.
# The PKI (easy-rsa), client profiles and databases are never replaced or deleted by an update.
# See DOCS/Deployment/Scenario2_System_Services.md and DOCS/General/Database_Migrations.md
set -eu
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
. "$SCRIPT_DIR/lib.sh"
usage() {
sed -n '2,19p' "$0" | sed 's/^# \{0,1\}//'
}
PREFIX=""
UI_DIST=""
SOURCE=""
NO_PULL=0
ASSUME_YES=0
DO_ROLLBACK=0
FORCE=1 # an update never refuses on an untested OS version (install.sh decides that)
BACKUP_DIR=""
CURRENT_PHASE="start"
ROLLBACK_ARMED=0
SWAP_BEGAN=0
STAMP=$(stamp)
RESTORE_STAMP="$STAMP"
STAGING=""
HTTPS_PORT=""
OLD_VERSION="unknown"
NEW_VERSION="unknown"
UI_STAGED=0
SERVICES_WERE_RUNNING=0
# ---------------------------------------------------------------------------------------------
# Rollback
# ---------------------------------------------------------------------------------------------
rollback_failed() {
log "!!! ROLLBACK FAILED: $1" >&2
log "!!! Your data is safe in the backup: $BACKUP_DIR" >&2
log "!!! Retry: $SCRIPT_DIR/update.sh --rollback (or restore everything: $SCRIPT_DIR/restore.sh $BACKUP_DIR)" >&2
}
# Automatic rollback after a failure from phase 4 on (called from the EXIT trap)
auto_rollback() {
printf '\n' >&2
log "!!! UPDATE FAILED in phase: $CURRENT_PHASE" >&2
stop_app_services >/dev/null 2>&1 || true
if [ "$SWAP_BEGAN" = 1 ]; then
log "!!! Automatic rollback: code, databases, configuration and system files are restored from $BACKUP_DIR" >&2
RESTORE_STAMP="$STAMP"
if ! restore_all "$BACKUP_DIR" "$PREFIX" auto; then
rollback_failed "the restore from the backup failed (see above)"
return 0
fi
else
log "!!! The code was not replaced yet: the old version is started again" >&2
fi
svc_defs_reload || true
if ! start_app_services; then
rollback_failed "the previous version could not be started"
return 0
fi
if ! health_check "$HTTPS_PORT"; then
rollback_failed "the previous version did not become healthy"
return 0
fi
log "!!! ROLLED BACK: the previous version ($OLD_VERSION) runs again on the data as it was before the update." >&2
log "!!! The update failed in phase '$CURRENT_PHASE'; see the messages above. Backup kept in: $BACKUP_DIR" >&2
}
on_exit() {
_rc=$?
set +e
trap '' INT TERM
if [ "$_rc" -ne 0 ]; then
if [ "$ROLLBACK_ARMED" = 1 ]; then
ROLLBACK_ARMED=0
auto_rollback
elif [ -n "$BACKUP_DIR" ]; then
log "update stopped in phase '$CURRENT_PHASE' before the running system was changed. Backup: $BACKUP_DIR" >&2
fi
fi
if [ -n "$STAGING" ] && [ -f "$STAGING/.ovpmon-staging" ]; then rm -rf "$STAGING"; fi
[ "$UI_STAGED" = 0 ] || rm -rf "$WEB_ROOT.new"
[ -z "${TMPD:-}" ] || rm -rf "$TMPD"
release_lock
exit "$_rc"
}
manual_rollback() {
local safe
BACKUP_DIR=$(latest_backup)
[ -n "$BACKUP_DIR" ] || die "no complete backup found in $BACKUP_ROOT"
log "newest complete backup: $BACKUP_DIR"
sed 's/^/ /' "$BACKUP_DIR/MANIFEST"
[ "$(manifest_get "$BACKUP_DIR" prefix)" = "$PREFIX" ] || die "the backup belongs to install directory '$(manifest_get "$BACKUP_DIR" prefix)', not '$PREFIX' (use --prefix)"
log "code, databases, configuration, PKI and client profiles will be REPLACED by this backup; the current state is saved first to $BACKUP_ROOT/<timestamp>-pre-restore"
confirm "Restore from this backup and start the previous version?" || die "aborted by the user"
phase R1 "stop the application services"
stop_app_services || die "could not stop the services"
if [ "${OVPMON_NO_SAFETY_BACKUP:-0}" != 1 ]; then
phase R2 "safety backup of the current state"
safe="$BACKUP_ROOT/$(stamp)-pre-restore"
make_backup "$safe" pre-restore "$PREFIX" || die "the safety backup failed: nothing was changed"
log "current state saved: $safe"
fi
phase R3 "restore from the backup"
RESTORE_STAMP="$STAMP"
restore_all "$BACKUP_DIR" "$PREFIX" full || die "the restore failed (see above). The backup is intact: $BACKUP_DIR"
phase R4 "start"
svc_defs_reload || true
start_app_services || die "the services did not start after the restore"
health_check "$HTTPS_PORT" || die "the health checks failed after the restore"
printf '\n'
log "=== ROLLBACK DONE: the state of $BACKUP_DIR is in use ==="
}
# ---------------------------------------------------------------------------------------------
# Phase 5 helper: one component's database, with the NEW code, as the service user with its environment
# ---------------------------------------------------------------------------------------------
migrate_component() { # NAME DIR
local name dir rc out
name="$1"; dir="$2"
log "--- $name database: check ---"
rc=0
out=$(run_as_service_user "$dir" "$dir/venv/bin/python" migrate.py --check 2>&1) || rc=$?
indent "$out"
case "$rc" in
0) log "$name: up to date, nothing to migrate"; return 0 ;;
2) log "$name: migrations pending: applying (a consistent backup of the database is made first)" ;;
*) die "$name: the check failed with exit code $rc (database newer than this version, damaged, or the check could not run)" ;;
esac
rc=0
out=$(run_as_service_user "$dir" "$dir/venv/bin/python" migrate.py 2>&1) || rc=$?
indent "$out"
[ "$rc" -eq 0 ] || die "$name: the migration failed with exit code $rc"
rc=0
out=$(run_as_service_user "$dir" "$dir/venv/bin/python" migrate.py --check 2>&1) || rc=$?
[ "$rc" -eq 0 ] || { indent "$out"; die "$name: the database is not up to date after the migration (exit code $rc)"; }
log "$name: migrated, database is up to date"
}
# Phase 4 helper: data that lives below a code directory moves to the new one (same file system, rename)
preserve_data() { # OLD_DIR NEW_DIR NAME
local old new item f
old="$1"; new="$2"
if [ "$3" = APP_PROFILER ]; then
for item in easy-rsa client-config profiler.log; do
if [ -e "$old/$item" ] && [ ! -e "$new/$item" ]; then
mv "$old/$item" "$new/$item" || die "cannot move $item to the new code directory"
log " kept $3/$item"
fi
done
fi
# config.ini is configuration: the current one stays, the shipped one is saved next to it
if [ -f "$old/config.ini" ]; then
if [ -f "$new/config.ini" ] && ! cmp -s "$old/config.ini" "$new/config.ini"; then
mv "$new/config.ini" "$new/config.ini.dist"
log " $3/config.ini kept (the shipped one of the new version is config.ini.dist)"
else
rm -f "$new/config.ini"
fi
mv "$old/config.ini" "$new/config.ini"
fi
# legacy data files that older installations kept next to the code (databases, logs)
for f in "$old"/*.db "$old"/*.db-* "$old"/*.log; do
[ -e "$f" ] || continue
item=$(basename "$f")
if [ ! -e "$new/$item" ]; then mv "$f" "$new/$item"; log " kept $3/$item"; fi
done
}
detect_https_port() {
[ -f "$NGINX_SITE" ] || return 0
sed -n 's/^[[:space:]]*listen[[:space:]][[:space:]]*\([0-9][0-9]*\)[[:space:]][[:space:]]*ssl.*/\1/p' "$NGINX_SITE" | head -n 1
}
# apply_file RESULT_CODE LABEL: log what install_managed / install_doas did
report() {
case "$1" in
0) log " updated: $2"; CHANGES=$((CHANGES + 1)) ;;
1) log " unchanged: $2" ;;
*) log " NOT touched (not managed by these scripts): $2" ;;
esac
}
# ---------------------------------------------------------------------------------------------
main() {
while [ $# -gt 0 ]; do
case "$1" in
--prefix) [ $# -ge 2 ] || die "--prefix needs a value"; PREFIX="$2"; shift 2 ;;
--ui-dist) [ $# -ge 2 ] || die "--ui-dist needs a value"; UI_DIST="$2"; shift 2 ;;
--source) [ $# -ge 2 ] || die "--source needs a value"; SOURCE="$2"; shift 2 ;;
--no-pull) NO_PULL=1; shift ;;
--yes|-y) ASSUME_YES=1; shift ;;
--rollback) DO_ROLLBACK=1; shift ;;
-h|--help) usage; exit 0 ;;
*) usage >&2; die "unknown option: $1" ;;
esac
done
TMPD=$(mktemp -d /tmp/ovpmon-update.XXXXXX) || die "cannot create a temporary directory"
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
need_root
check_os
require_init
acquire_lock
[ -n "$PREFIX" ] || PREFIX=$(state_get OVPMON_PREFIX)
[ -n "$PREFIX" ] || PREFIX="$DEFAULT_PREFIX"
valid_prefix "$PREFIX" || die "invalid install directory '$PREFIX'"
HTTPS_PORT=$(state_get OVPMON_HTTPS_PORT)
[ -n "$HTTPS_PORT" ] || HTTPS_PORT=$(detect_https_port || true)
SOURCE="${SOURCE:-$ROOT_DIR}"
case "$UI_DIST" in ""|/*) ;; *) UI_DIST="$PWD/$UI_DIST" ;; esac
if [ "$DO_ROLLBACK" = 1 ]; then
[ -f "$ENV_FILE" ] || die "$ENV_FILE not found: nothing is installed"
manual_rollback
return 0
fi
# ----- Phase 0 -------------------------------------------------------------------------
CURRENT_PHASE="0 preflight"
phase 0 "preflight"
log "install directory: $PREFIX; source: $SOURCE; backups: $BACKUP_ROOT"
check_gnu_tar
command -v python3 >/dev/null 2>&1 || die "python3 not found"
command -v curl >/dev/null 2>&1 || die "curl not found"
[ ! -f "$INCOMPLETE_MARK" ] || die "an unfinished install.sh run exists ($INCOMPLETE_MARK): run install.sh again to finish it, then update"
[ -d "$PREFIX/APP_CORE" ] && [ -d "$PREFIX/APP_PROFILER" ] && [ -f "$ENV_FILE" ] \
|| die "no installation found (need $PREFIX/APP_CORE, $PREFIX/APP_PROFILER and $ENV_FILE): wrong --prefix? Use install.sh for a new host"
if [ -f "$STATE_FILE" ]; then
log "installed version: $(state_get OVPMON_VERSION), installed $(state_get OVPMON_INSTALLED_AT)"
else
warn "no state file ($STATE_FILE): this installation was not made by install.sh; it is adopted and recorded after a successful update. Files that these scripts do not manage (init scripts, nginx site, doas file) are left as they are"
fi
OLD_VERSION=$(cat "$PREFIX/VERSION" 2>/dev/null || echo "unknown")
for _f in APP_CORE/openvpn_api_v3.py APP_CORE/openvpn_gatherer_v3.py APP_CORE/migrate.py APP_CORE/requirements.txt \
APP_PROFILER/main.py APP_PROFILER/migrate.py APP_PROFILER/requirements.txt \
DOCS/General/privilege-separation/ovpmon-helper DOCS/General/privilege-separation/doas-ovpmon.conf \
deploy/native/nginx/ovpmon.conf.template; do
[ -f "$SOURCE/$_f" ] || die "the source directory is not a complete checkout: $SOURCE/$_f is missing (--source)"
done
for _s in $SERVICES; do
[ -f "$(unit_src "$SOURCE" "$_s")" ] || die "service definition missing in the source: $(unit_src "$SOURCE" "$_s")"
done
if [ "$(abs_dir "$SOURCE")" = "$(abs_dir "$PREFIX")" ]; then
log "the source is the install directory itself (a checkout used as the install directory): git pull changes the live files, so a rollback is armed from phase 2"
PULL_TOUCHES_LIVE=1
else
PULL_TOUCHES_LIVE=0
fi
if [ -n "$UI_DIST" ]; then
check_ui_archive "$UI_DIST"
log "UI archive: $UI_DIST"
else
log "no --ui-dist: the UI files stay as they are (if APP_UI changed, build and pass a new archive)"
fi
SERVICES_WERE_RUNNING=1
for _s in $SERVICES; do
if svc_known "$_s"; then
log " $_s: $(svc_state_word "$_s")"
svc_active "$_s" || SERVICES_WERE_RUNNING=0
else
log " $_s: no service definition yet (it will be installed)"
SERVICES_WERE_RUNNING=0
fi
done
if [ "$SERVICES_WERE_RUNNING" = 0 ]; then
warn "not all application services are running"
confirm "Continue anyway? (the services will be started at the end)" || die "aborted by the user"
fi
log " OpenVPN ($OVPN_SERVICE): $(svc_state_word "$OVPN_SERVICE") (not touched by the update)"
resolve_db_paths "$PREFIX"
for _d in "$DB_MONITOR" "$DB_PROFILER"; do
if [ -f "$_d" ]; then log "database: $_d ($(du -h "$_d" | awk '{print $1}'))"; else warn "database not found yet: $_d"; fi
done
mkdir -p "$BACKUP_ROOT"
chmod 700 "$BACKUP_ROOT"
_kb=$(du -sk "$PREFIX/APP_CORE" "$PREFIX/APP_PROFILER" "$DATA_DIR" "$ETC_DIR" /etc/openvpn "$WEB_ROOT" 2>/dev/null | awk '{ s += $1 } END { print s + 0 }')
_need=$(( _kb / 1024 * 2 + 100 ))
[ "$_need" -ge "$MIN_FREE_BACKUP_MB" ] || _need="$MIN_FREE_BACKUP_MB"
check_free "$BACKUP_ROOT" "$_need" "the backup"
check_free "$(dirname "$PREFIX")" "$MIN_FREE_PREFIX_MB" "the new code and virtualenvs"
log "plan: backup -> git pull -> prepare (staging) -> stop -> swap code -> DATABASE MIGRATION -> files -> start (automatic rollback after the stop)"
confirm "Update now?" || die "aborted by the user"
# ----- Phase 1: backup -----------------------------------------------------------------
CURRENT_PHASE="1 backup"
phase 1 "BACKUP (databases, configuration, PKI, client profiles, code, system files)"
BACKUP_DIR="$BACKUP_ROOT/$STAMP"
[ ! -e "$BACKUP_DIR" ] || die "backup directory already exists: $BACKUP_DIR (retry in a second)"
mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR"
log "backup directory: $BACKUP_DIR"
if ! make_backup "$BACKUP_DIR" update "$PREFIX"; then
die "the BACKUP FAILED. Nothing was changed, the update is refused. (The incomplete backup in $BACKUP_DIR is never used.)"
fi
log "backup complete and verified: $BACKUP_DIR"
# ----- Phase 2: sources ----------------------------------------------------------------
CURRENT_PHASE="2 git pull"
phase 2 "source update"
if [ "$NO_PULL" = 1 ]; then
log "skipped (--no-pull)"
elif ! git -C "$SOURCE" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
log "not a git checkout: skipped (put the new sources in place yourself before running this script)"
else
if [ "$PULL_TOUCHES_LIVE" = 1 ]; then ROLLBACK_ARMED=1; SWAP_BEGAN=1; fi # the live files change: restore them on failure
git -C "$SOURCE" pull --ff-only || die "git pull --ff-only failed (local changes, diverged history, no network, or 'dubious ownership': git config --global --add safe.directory $SOURCE). The running system was not changed. Fix the checkout, or use --no-pull"
fi
NEW_VERSION=$(version_of "$SOURCE")
log "source version: $OLD_VERSION -> $NEW_VERSION"
if [ "$NO_PULL" = 0 ] && [ "$PULL_TOUCHES_LIVE" = 0 ]; then
log "note: if deploy/native/*.sh changed, the new versions are used from the next run"
fi
# ----- Phase 3: prepare ----------------------------------------------------------------
CURRENT_PHASE="3 prepare"
phase 3 "PREPARE the new code and virtualenvs (the running system is not touched)"
STAGING="${PREFIX}.new"
if [ -e "$STAGING" ]; then
[ -f "$STAGING/.ovpmon-staging" ] || die "$STAGING exists and was not created by this script: remove or rename it"
rm -rf "$STAGING"
fi
mkdir -p "$STAGING"
: > "$STAGING/.ovpmon-staging"
copy_component "$SOURCE/APP_CORE" "$STAGING/APP_CORE"
copy_component "$SOURCE/APP_PROFILER" "$STAGING/APP_PROFILER"
make_venv "$STAGING/APP_CORE" gunicorn
make_venv "$STAGING/APP_PROFILER"
smoke_component "$STAGING/APP_CORE" core || die "the new APP_CORE virtualenv cannot import the application's dependencies"
smoke_component "$STAGING/APP_PROFILER" profiler || die "the new APP_PROFILER virtualenv cannot import the application's dependencies"
lock_down_code "$STAGING/APP_CORE" "$STAGING/APP_PROFILER"
log "new code and virtualenvs are ready in $STAGING (dependencies installed and importable)"
if [ -n "$UI_DIST" ]; then
stage_ui "$UI_DIST" "$WEB_ROOT.new"
UI_STAGED=1
log "new UI files are ready in $WEB_ROOT.new"
fi
# ----- Phase 4: stop and swap ----------------------------------------------------------
CURRENT_PHASE="4 stop and swap"
phase 4 "STOP the application services (OpenVPN keeps running) and swap the code in"
ROLLBACK_ARMED=1 # from here on a failure restores the backup
stop_app_services || die "could not stop the application services"
log "final consistent snapshot (nothing writes to the databases now)"
make_backup "$BACKUP_DIR" update "$PREFIX" 1 || die "the final snapshot failed"
SWAP_BEGAN=1
for _c in APP_CORE APP_PROFILER; do
mv "$PREFIX/$_c" "$PREFIX/$_c.old-$STAMP" || die "cannot move the old $_c aside"
mv "$STAGING/$_c" "$PREFIX/$_c" || die "cannot move the new $_c into place"
preserve_data "$PREFIX/$_c.old-$STAMP" "$PREFIX/$_c" "$_c"
fix_venv_paths "$PREFIX/$_c" "$STAGING/$_c" "$PREFIX/$_c"
log " $_c replaced (the old one is kept as $_c.old-$STAMP until the update succeeds)"
done
rm -rf "$STAGING"
ensure_runtime_files "$PREFIX"
lock_down_code "$PREFIX/APP_CORE" "$PREFIX/APP_PROFILER"
compile_code "$PREFIX/APP_CORE"
compile_code "$PREFIX/APP_PROFILER"
smoke_component "$PREFIX/APP_CORE" core || die "the relocated APP_CORE virtualenv does not work"
smoke_component "$PREFIX/APP_PROFILER" profiler || die "the relocated APP_PROFILER virtualenv does not work"
log "PKI, client profiles and databases were not touched"
# ----- Phase 5: database migration -----------------------------------------------------
CURRENT_PHASE="5 database migration"
phase 5 "DATABASE MIGRATION (own step; no service is started on an unmigrated database)"
log "run with the NEW code, as user $SERVICE_USER, with the environment of $ENV_FILE; reports below"
migrate_component "profiler" "$PREFIX/APP_PROFILER"
migrate_component "monitoring" "$PREFIX/APP_CORE"
log "all databases are up to date"
# ----- Phase 6: files ------------------------------------------------------------------
CURRENT_PHASE="6 files"
phase 6 "UI, nginx site, helper, doas rules, service definitions"
CHANGES=0
if [ "$UI_STAGED" = 1 ]; then
swap_dir "$WEB_ROOT.new" "$WEB_ROOT" "$WEB_ROOT.old"
UI_STAGED=0
log " UI files replaced (the previous ones are in the backup)"
CHANGES=$((CHANGES + 1))
fi
rc=0; install_helper "$SOURCE" || rc=$?
report "$rc" "$HELPER_DEST"
# helper.conf: written when missing (adopted hosts), kept when it is not ours
helper_conf_text "$PREFIX" > "$TMPD/helper.conf"
rc=0; install_managed "$TMPD/helper.conf" "$HELPER_CONF" 644 "deploy/native/lib.sh helper_conf_text" || rc=$?
report "$rc" "$HELPER_CONF"
rc=0; install_doas "$SOURCE" || rc=$?
doas_target
report "$rc" "doas rules ($DOAS_FILE)"
if [ ! -f "$SYSCTL_FILE" ]; then
printf '# %s\nnet.ipv4.ip_forward = 1\n' "$MARKER" > "$SYSCTL_FILE"; chmod 644 "$SYSCTL_FILE"
log " added: $SYSCTL_FILE"
fi
# service definitions
for _s in $SERVICES; do
render_unit "$SOURCE" "$_s" "$PREFIX" "$TMPD/$_s"
if [ "$INIT" = systemd ]; then _mode=644; else _mode=755; fi
rc=0; install_managed "$TMPD/$_s" "$(unit_file "$_s")" "$_mode" "$(unit_src "$SOURCE" "$_s")" || rc=$?
report "$rc" "$(unit_file "$_s")"
done
svc_defs_reload
for _s in $SERVICES; do svc_enable "$_s" || warn "could not enable $_s at boot"; done
# environment: add the settings of this version when they are missing (existing values are never changed)
for _kv in "OVPMON_RUNTIME=host" "OVPMON_OPENVPN_SERVICE=$OVPN_SERVICE" "OVPMON_OPENVPN_CONFIG=$OVPN_CONFIG"; do
_k=${_kv%%=*}
if [ -z "$(env_get "$_k")" ]; then
kv_set "$ENV_FILE" "$_k" "${_kv#*=}" 600
log " added $_k to $ENV_FILE"
fi
done
# OpenVPN prerequisites that may be missing on an adopted host
[ -d "$(dirname "$OVPN_CONFIG")" ] || { mkdir -p "$(dirname "$OVPN_CONFIG")"; chmod 755 "$(dirname "$OVPN_CONFIG")"; }
[ -d /etc/openvpn/scripts ] || ensure_dir /etc/openvpn/scripts root:root 755
# nginx site (only when it is ours and the port is known)
if [ -n "$HTTPS_PORT" ]; then
render_nginx "$SOURCE" "$HTTPS_PORT" "$TMPD/ovpmon.conf"
rc=0; install_managed "$TMPD/ovpmon.conf" "$NGINX_SITE" 644 "deploy/native/nginx/ovpmon.conf.template" || rc=$?
report "$rc" "$NGINX_SITE"
if [ "$rc" = 0 ]; then
nginx_apply || die "nginx did not accept the new site (it is restored from the backup)"
log " nginx reloaded"
fi
else
warn "no HTTPS port known (no state file and no nginx site found): the nginx site is not managed"
fi
sync_deploy_files "$SOURCE" "$PREFIX"
echo "$NEW_VERSION" > "$PREFIX/VERSION"
log "$CHANGES file(s) changed in this phase"
# ----- Phase 7: start ------------------------------------------------------------------
CURRENT_PHASE="7 start"
phase 7 "START the services and check them"
start_app_services
if svc_known nginx && ! svc_active nginx; then svc_start nginx >/dev/null 2>&1 || warn "nginx is not running"; fi
health_check "$HTTPS_PORT" || die "the new version did not become healthy"
doas_selftest && log "self-test: $SERVICE_USER can call the helper through doas" || warn "the helper self-test failed: starting OpenVPN from the UI may not work (see $DOAS_FILE and $HELPER_CONF)"
# ----- Done ----------------------------------------------------------------------------
ROLLBACK_ARMED=0
CURRENT_PHASE="finish"
phase 8 "finish"
for _c in APP_CORE APP_PROFILER; do safe_remove_old "$PREFIX/$_c.old-$STAMP"; done
rm -rf "$WEB_ROOT.old"
state_set OVPMON_PREFIX "$PREFIX"
[ -z "$HTTPS_PORT" ] || state_set OVPMON_HTTPS_PORT "$HTTPS_PORT"
state_set OVPMON_OS "$OS_ID $OS_VERSION_ID"
state_set OVPMON_VERSION "$NEW_VERSION"
[ -n "$(state_get OVPMON_INSTALLED_AT)" ] || state_set OVPMON_INSTALLED_AT "adopted $(now_iso)"
state_set OVPMON_LAST_UPDATE "$(now_iso)"
prune_backups
printf '\n'
log "=== UPDATE SUCCESSFUL: $OLD_VERSION -> $NEW_VERSION ==="
printf ' Install dir: %s\n' "$PREFIX"
printf ' Backup: %s (the newest %s backups are kept)\n' "$BACKUP_DIR" "$KEEP_BACKUPS"
printf ' Rollback: %s --rollback\n' "$0"
printf ' OpenVPN was not restarted by the update: connected VPN users stayed connected.\n'
printf ' Log of this run: %s\n' "$DEPLOY_LOG"
}
main "$@"; exit $?