diff --git a/.gitignore b/.gitignore index 3f3c949..0ca56c4 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ backups/ .ovpmon-deploy .ovpmon-lock/ +deploy/native/ui-dist.tar.gz diff --git a/APP_PROFILER/routers/server.py b/APP_PROFILER/routers/server.py index bef28f7..e7d2fe8 100644 --- a/APP_PROFILER/routers/server.py +++ b/APP_PROFILER/routers/server.py @@ -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: diff --git a/APP_PROFILER/services/process.py b/APP_PROFILER/services/process.py index 61c18cb..169507c 100644 --- a/APP_PROFILER/services/process.py +++ b/APP_PROFILER/services/process.py @@ -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) diff --git a/APP_PROFILER/test_helper_config.py b/APP_PROFILER/test_helper_config.py new file mode 100644 index 0000000..846b706 --- /dev/null +++ b/APP_PROFILER/test_helper_config.py @@ -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 ; openrc -> rc-service + 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 diff --git a/DOCS/Changes/2026-09-30_Privilege_Separation.md b/DOCS/Changes/2026-09-30_Privilege_Separation.md index 6de734a..df50d40 100644 --- a/DOCS/Changes/2026-09-30_Privilege_Separation.md +++ b/DOCS/Changes/2026-09-30_Privilege_Separation.md @@ -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 ` (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`. diff --git a/DOCS/Changes/2026-10-05_Scenario2_System_Services.md b/DOCS/Changes/2026-10-05_Scenario2_System_Services.md new file mode 100644 index 0000000..6c39c3e --- /dev/null +++ b/DOCS/Changes/2026-10-05_Scenario2_System_Services.md @@ -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. diff --git a/DOCS/Deployment/Scenario2_System_Services.md b/DOCS/Deployment/Scenario2_System_Services.md new file mode 100644 index 0000000..ce980b1 --- /dev/null +++ b/DOCS/Deployment/Scenario2_System_Services.md @@ -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 /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 /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 /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-.log` | `journalctl -u ovpmon-` | +| OpenVPN service | `openvpn`; config `/etc/openvpn/server.conf`, plus the link `/etc/openvpn/openvpn.conf -> server.conf` | `openvpn-server@server`; config `/etc/openvpn/server/server.conf` | +| nginx site | `/etc/nginx/http.d/ovpmon.conf` | `/etc/nginx/conf.d/ovpmon.conf` | +| doas | package `doas`; our rules in `/etc/doas.d/ovpmon.conf` (own file, as on the existing hosts) | package `opendoas`; our rules as a marked block inside `/etc/doas.conf` | +| `ovpmon` user | `adduser -S`, shell `/sbin/nologin` | `useradd --system`, shell `/usr/sbin/nologin` | + +The nginx site does not collide with the distribution defaults: the default server of Alpine and Debian listens on port 80, ours on 8088, and both distribution `nginx.conf` files include the directory above (the installer checks the `include` line). + +### What `install.sh` does + +| Phase | Content | +|---|---| +| 0 Preflight | root, OS and version, service manager present, no existing installation (otherwise it points to `update.sh`), source checkout complete, UI 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:/` (with `-k`) returns 200; `/api/v1/user/me` and `/profiles-api/config` through nginx return 401 without a token. + +The final summary shows the URL, the certificate fingerprint, the paths and the **generated administrator password once**. The state is recorded in `/etc/ovpmon/deploy.state` (prefix, HTTPS port, OS, version, dates). If the script fails it is **safe to run again**: it resumes, keeps the existing secret, certificate, easy-rsa workspace and data. + +Then in the UI: sign in, change the password and enable 2FA, **PKI Configuration -> Initialize PKI**, generate the server configuration, start the VPN server. + +### Without the script (outline) + +Create the `ovpmon` user and the directories, copy the code, build both virtualenvs, write `/etc/ovpmon/env`, `helper.conf` and the doas rules from the templates, install the service definitions (`DOCS/General/systemd/*.service` or `DOCS/General/openrc/ovpmon-*`; replace `/opt/OpenVPN-Monitoring-Simple` if you use another prefix), copy the UI, add the nginx site from `deploy/native/nginx/ovpmon.conf.template` (replace `@HTTPS_PORT@`, `@WEB_ROOT@`, `@TLS_CRT@`, `@TLS_KEY@`). The commands are exactly what `install.sh` runs; reading the script is the shortest reference. + +## Layout: what is where, who owns it + +| Item | Path | Owner, mode | +|---|---|---| +| Code | `/APP_CORE`, `/APP_PROFILER` | `root:root`, read-only for others | +| Virtualenvs | `/APP_CORE/venv`, `/APP_PROFILER/venv` | `root:root` | +| **PKI** (CA, keys, certificates, CRL) | `/APP_PROFILER/easy-rsa` (real directory) | `ovpmon:ovpmon` 750 | +| **Client profiles** | `/APP_PROFILER/client-config` (real directory) | `ovpmon:ovpmon` 750 | +| Profiler log | `/APP_PROFILER/profiler.log` | `ovpmon:ovpmon` 640 | +| Shipped settings file | `/APP_CORE/config.ini`, `/APP_PROFILER/config.ini` | `root:root`; the environment file overrides it | +| **Databases** | `/var/lib/ovpmon/openvpn_monitor.db`, `ovpn_profiler.db`, migration copies `*.db.bak-*` | `ovpmon:ovpmon` | +| Staging of `server.conf` | `/var/lib/ovpmon/staging/` | `ovpmon:ovpmon` 750 | +| Service environment | `/etc/ovpmon/env` | `root:root` 600 | +| Helper configuration | `/etc/ovpmon/helper.conf` | `root:root` 644 | +| TLS certificate and key | `/etc/ovpmon/tls/ovpmon.crt`, `ovpmon.key` | `root:root` (key 600) | +| Deployment state | `/etc/ovpmon/deploy.state` | `root:root` 644 | +| Root helper | `/usr/local/sbin/ovpmon-helper` | `root:root` 755 | +| doas rules | Alpine: `/etc/doas.d/ovpmon.conf`; Debian/Ubuntu: block in `/etc/doas.conf` | `root:root` | +| OpenVPN configuration | `/etc/openvpn/server.conf` (Alpine) or `/etc/openvpn/server/server.conf`, `/etc/openvpn/crl.pem`, `/etc/openvpn/scripts/` | `root:root` | +| OpenVPN logs | `/var/log/openvpn/openvpn.log`, `openvpn-status.log` (`root:ovpmon` 640) | `root` | +| Service logs | `/var/log/ovpmon/` (OpenRC) or the journal (systemd) | `ovpmon` / systemd | +| UI files | `/var/www/ovpmon` | `root:root` | +| Backups | `/var/backups/ovpmon//` | `root:root` 700 | +| Deployment log | `/var/log/ovpmon-deploy.log` | `root:root` 600 | + +The profiler resolves `easy-rsa/` and `client-config/` relative to its working directory (`APP_PROFILER`) and keeps `client-config/.ovpn` as a relative path in its database; therefore both are real directories inside `APP_PROFILER` (a symlinked `client-config` breaks the real-path checks and the `clear_pki` cleanup). + +## Environment file and helper configuration + +`/etc/ovpmon/env` (`root:root` 600) is read by the init system as root and handed to the services. Lines are `KEY=VALUE` without quotes or spaces (systemd and OpenRC read the same file). + +| Variable | Default written by `install.sh` | Meaning | +|---|---|---| +| `OVPMON_API_SECRET_KEY` | random, 64 hex characters | signing key of both APIs; changing it logs everybody out; keep it across updates | +| `OVPMON_API_HOST`, `OVPMON_API_PORT` | `127.0.0.1`, `5001` | informational: gunicorn is started with `-b 127.0.0.1:5001` | +| `OVPMON_OPENVPN_MONITOR_DB_PATH` | `/var/lib/ovpmon/openvpn_monitor.db` | monitoring database | +| `OVPMON_PROFILER_DB_PATH` | `/var/lib/ovpmon/ovpn_profiler.db` | profiler database | +| `OVPMON_OPENVPN_MONITOR_LOG_PATH` | `/var/log/openvpn/openvpn-status.log` | status log read by the gatherer | +| `OVPMON_LOGGING_LEVEL` | `INFO` | | +| `OVPMON_CORS_ORIGINS` | `https://:` | extra allowed origin (the UI is same-origin behind nginx) | +| `OVPMON_RUNTIME` | `host` | forces host mode (never "container"), needed when the host itself runs inside a container | +| `OVPMON_OPENVPN_SERVICE` | `openvpn` (Alpine) / `openvpn-server@server` | service name for the root (non-helper) path | +| `OVPMON_OPENVPN_CONFIG` | `/etc/openvpn/server.conf` / `/etc/openvpn/server/server.conf` | server config path for the root (non-helper) path | +| `OVPMON_INITIAL_ADMIN_USER`, `OVPMON_INITIAL_ADMIN_PASSWORD` | generated | seed, only while the users table is empty; removed by `install.sh` after the first start | +| `OVPMON_AUTO_MIGRATE` | unset | `0` makes the services refuse to start while migrations are pending | + +With the unprivileged profiler the API only stages `server.conf`; **the helper configuration decides where it is installed and which service is controlled.** + +`/etc/ovpmon/helper.conf` (INI, section `[helper]`, `root:root`, not group/world writable, otherwise the helper refuses to run). Without the file the helper uses the built-in values of the Alpine layout. + +| Key | Alpine (written) | Debian/Ubuntu (written) | Rule | +|---|---|---|---| +| `install_dir` | `/opt/OpenVPN-Monitoring-Simple` | same | absolute, no `..`; the PKI is `/APP_PROFILER/easy-rsa/pki` | +| `service_manager` | `openrc` | `systemd` | `openrc` or `systemd` | +| `service_unit` | `openvpn` | `openvpn-server@server` | `^[A-Za-z0-9@._-]{1,64}$`, not starting with `-` or `.` | +| `config_path` | `/etc/openvpn/server.conf` | `/etc/openvpn/server/server.conf` | absolute, below `/etc/openvpn/`, ends with `.conf` | +| `staged_path` | `/var/lib/ovpmon/staging/server.conf` | same | absolute, below `/var/lib/ovpmon/` | + +OpenRC runs `/sbin/rc-service `, systemd runs `systemctl ` (fixed argument list, fixed `PATH`). Unknown keys or invalid values make the helper refuse. + +## Firewall, NAT and forwarding (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//` (see below) | the update is **refused**, nothing was changed | +| 2 Sources | `git pull --ff-only` of the source checkout (skipped with `--no-pull` or without git) | nothing was changed | +| 3 Prepare | new code copied to `.new`, fresh virtualenvs with `pip install -r requirements.txt`, import check; 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 `.old-