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:
1 parent
1c49d0b9c2
commit
4abd2044f0
26 files changed
+3326
-255
No files matched your search
@@ -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"}))
|
||||
|
||||
Reference in new issue
Block a user