"""Backup package: naming, building (snapshots), reading and safe extraction. A package is a tar.gz named ovpmon-backup__Z.ovpbak (plus .enc when encrypted; -2, -3 after the Z when several packages are made in the same second) with this content: db/openvpn_monitor.db, db/ovpn_profiler.db consistent online snapshots (sqlite3 backup API) pki/... the easy-rsa PKI directory client-config/*.ovpn issued client profiles manifest.json format version, server name, schema versions, SHA-256 of every file """ import hashlib import json import os import re import shutil import socket import sqlite3 import stat import tarfile from datetime import datetime, timezone from . import BackupError FORMAT_NAME = "ovpmon-backup" FORMAT_VERSION = 1 MANIFEST = "manifest.json" DB_MONITOR = "db/openvpn_monitor.db" DB_PROFILER = "db/ovpn_profiler.db" TOP_LEVEL = {"db", "pki", "client-config", MANIFEST} # allowlist of top-level names SERVER_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9.-]{0,62}$") # Packages of the first pass carry the host name in the same place; they match too PACKAGE_RE = re.compile( r"^ovpmon-backup_(?P[A-Za-z0-9][A-Za-z0-9.-]{0,62})_(?P\d{8}T\d{6}Z)(?:-(?P\d{1,3}))?" r"\.ovpbak(?P\.enc)?$") MAX_FILES = 200000 MAX_UNPACKED = int(os.environ.get("OVPMON_BACKUP_MAX_UNPACKED_BYTES", str(20 * 1024 ** 3))) MAX_MANIFEST = 64 * 1024 * 1024 def sanitize_name(text: str) -> str: """Make a server name of arbitrary text (host name, address); empty when nothing is left.""" name = re.sub(r"[^A-Za-z0-9.-]", "-", text or "")[:63].strip("-.") return name if SERVER_NAME_RE.match(name) else "" def host_name() -> str: return sanitize_name(socket.gethostname()) or "host" def utc_stamp(now=None) -> str: return (now or datetime.now(timezone.utc)).strftime("%Y%m%dT%H%M%SZ") def package_name(server: str, stamp: str, encrypted: bool, seq: int = 1) -> str: return (f"ovpmon-backup_{server}_{stamp}" + (f"-{seq}" if seq > 1 else "") + ".ovpbak" + (".enc" if encrypted else "")) def unique_package_name(server: str, stamp: str, encrypted: bool, existing) -> str: """The name for a new package: the plain one, or with -2, -3 ... when the destination already holds a package of the same second. An existing file is never overwritten.""" taken = set(existing) for seq in range(1, 1000): name = package_name(server, stamp, encrypted, seq) if name not in taken: return name raise BackupError("Too many packages with the same time stamp in the destination") def parse_package_name(name: str): """{'host' (server name),'created_at' (ISO UTC),'encrypted','stamp','seq'} or None when the name is not ours.""" m = PACKAGE_RE.match(name or "") if not m: return None ts = datetime.strptime(m.group("ts"), "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc) return {"host": m.group("host"), "created_at": ts.strftime("%Y-%m-%dT%H:%M:%SZ"), "encrypted": bool(m.group("enc")), "stamp": m.group("ts"), "seq": int(m.group("seq") or 1)} # --- SQLite helpers ------------------------------------------------------------------------ def schema_version(db_path: str): """Highest applied migration of a database (0: no migrations table), None if unreadable.""" try: conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30) try: has = conn.execute( "SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_migrations'").fetchone() if not has: return 0 return conn.execute("SELECT COALESCE(MAX(version), 0) FROM schema_migrations").fetchone()[0] finally: conn.close() except sqlite3.Error: return None def integrity_ok(db_path: str) -> bool: try: conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30) try: return [r[0] for r in conn.execute("PRAGMA integrity_check")] == ["ok"] finally: conn.close() except sqlite3.Error: return False def snapshot_db(src_path: str, dst_path: str) -> None: """Consistent copy of a live database (online backup API); the copy is a single file (journal mode DELETE), so no -wal/-shm files belong to it.""" if not os.path.isfile(src_path): raise BackupError(f"Database not found: {os.path.basename(src_path)}") src = sqlite3.connect(f"file:{src_path}?mode=ro", uri=True, timeout=60) dst = sqlite3.connect(dst_path) try: src.backup(dst) dst.execute("PRAGMA journal_mode=DELETE") dst.commit() except sqlite3.Error as e: raise BackupError(f"Cannot snapshot {os.path.basename(src_path)}: {e}") from e finally: src.close() dst.close() os.chmod(dst_path, 0o600) # --- building ------------------------------------------------------------------------------ def _copy_tree_regular(src: str, dst: str) -> int: """Copy regular files and directories only (links and special files are skipped). Returns file count.""" count = 0 os.makedirs(dst, mode=0o700, exist_ok=True) for root, dirs, files in os.walk(src, followlinks=False): rel = os.path.relpath(root, src) target = dst if rel == "." else os.path.join(dst, rel) os.makedirs(target, mode=0o700, exist_ok=True) dirs[:] = [d for d in dirs if not os.path.islink(os.path.join(root, d))] for name in files: path = os.path.join(root, name) st = os.lstat(path) if not stat.S_ISREG(st.st_mode): continue out = os.path.join(target, name) shutil.copyfile(path, out) os.chmod(out, stat.S_IMODE(st.st_mode) & 0o777) count += 1 return count def _sha256(path: str) -> str: h = hashlib.sha256() with open(path, "rb") as f: for block in iter(lambda: f.read(1024 * 1024), b""): h.update(block) return h.hexdigest() def build_package(out_path: str, work_dir: str, profiler_db: str, monitor_db: str, pki_dir: str, client_dir: str, runtime: str, server_name: str = "") -> dict: """Write the (not encrypted) package tar.gz to out_path. Returns the manifest.""" stage = os.path.join(work_dir, "stage") os.makedirs(os.path.join(stage, "db"), mode=0o700) snapshot_db(profiler_db, os.path.join(stage, DB_PROFILER)) snapshot_db(monitor_db, os.path.join(stage, DB_MONITOR)) if os.path.isdir(pki_dir): _copy_tree_regular(pki_dir, os.path.join(stage, "pki")) else: os.makedirs(os.path.join(stage, "pki"), mode=0o700) if os.path.isdir(client_dir): for name in sorted(os.listdir(client_dir)): path = os.path.join(client_dir, name) if name.endswith(".ovpn") and os.path.isfile(path) and not os.path.islink(path): os.makedirs(os.path.join(stage, "client-config"), mode=0o700, exist_ok=True) shutil.copyfile(path, os.path.join(stage, "client-config", name)) os.makedirs(os.path.join(stage, "client-config"), mode=0o700, exist_ok=True) files = {} for root, _dirs, names in os.walk(stage): for name in names: path = os.path.join(root, name) arc = os.path.relpath(path, stage).replace(os.sep, "/") files[arc] = {"sha256": _sha256(path), "size": os.path.getsize(path), "mode": stat.S_IMODE(os.stat(path).st_mode) & 0o777} profiles = 0 try: conn = sqlite3.connect(os.path.join(stage, DB_PROFILER)) try: profiles = conn.execute("SELECT COUNT(*) FROM user_profiles").fetchone()[0] finally: conn.close() except sqlite3.Error: pass manifest = { "format": FORMAT_NAME, "format_version": FORMAT_VERSION, "created_at": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"), "server_name": server_name or host_name(), "hostname": socket.gethostname(), "runtime": runtime, "schema": {"profiler": schema_version(os.path.join(stage, DB_PROFILER)), "monitor": schema_version(os.path.join(stage, DB_MONITOR))}, "profiles": profiles, "files": files, } manifest_path = os.path.join(stage, MANIFEST) with open(manifest_path, "w") as f: json.dump(manifest, f, indent=1, sort_keys=True) fd = os.open(out_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "wb") as raw, tarfile.open(fileobj=raw, mode="w:gz") as tar: # Directories first (so empty ones survive), then files; fixed owner, no time-dependent names entries = [] for root, dirs, names in os.walk(stage): for name in dirs + names: path = os.path.join(root, name) entries.append((os.path.relpath(path, stage).replace(os.sep, "/"), path)) for arc, path in sorted(entries): info = tar.gettarinfo(path, arcname=arc) info.uid = info.gid = 0 info.uname = info.gname = "" if info.isdir(): tar.addfile(info) else: with open(path, "rb") as f: tar.addfile(info, f) shutil.rmtree(stage, ignore_errors=True) return manifest # --- reading and safe extraction ----------------------------------------------------------- def _check_member_name(name: str): if not name or name.startswith("/") or "\\" in name or "\x00" in name: raise BackupError(f"Unsafe path in package: {name!r}") parts = name.split("/") if any(p in ("", ".", "..") for p in parts): raise BackupError(f"Unsafe path in package: {name!r}") if parts[0] not in TOP_LEVEL: raise BackupError(f"Unexpected entry in package: {name!r}") if parts[0] == MANIFEST and len(parts) != 1: raise BackupError(f"Unexpected entry in package: {name!r}") if parts[0] == "db" and name not in ("db", DB_MONITOR, DB_PROFILER): raise BackupError(f"Unexpected entry in package: {name!r}") if parts[0] == "client-config" and len(parts) > 2: raise BackupError(f"Unexpected entry in package: {name!r}") if parts[0] == "client-config" and len(parts) == 2 and not parts[1].endswith(".ovpn"): raise BackupError(f"Unexpected entry in package: {name!r}") def safe_extract(package_path: str, dest: str) -> dict: """Extract an unencrypted package into the empty directory dest, checking every entry. Only regular files and directories under the allowlisted names are accepted: absolute paths, '..', links, devices and oversized content are rejected. Returns the verified manifest.""" os.makedirs(dest, mode=0o700, exist_ok=True) base = os.path.realpath(dest) total, count = 0, 0 try: tar = tarfile.open(package_path, mode="r:gz") except (tarfile.TarError, OSError, EOFError) as e: raise BackupError(f"Cannot read the package: {e}") from e try: for member in tar: count += 1 if count > MAX_FILES: raise BackupError("Package has too many entries") name = member.name.rstrip("/") if member.isdir() else member.name _check_member_name(name) if not (member.isreg() or member.isdir()): raise BackupError(f"Package contains a link or special file: {name!r}") target = os.path.realpath(os.path.join(base, name)) if target != base and not target.startswith(base + os.sep): raise BackupError(f"Unsafe path in package: {name!r}") if member.isdir(): os.makedirs(target, mode=0o700, exist_ok=True) continue if member.size < 0 or total + member.size > MAX_UNPACKED: raise BackupError("Package is larger than the allowed unpacked size") if name == MANIFEST and member.size > MAX_MANIFEST: raise BackupError("Manifest is too large") total += member.size os.makedirs(os.path.dirname(target), mode=0o700, exist_ok=True) src = tar.extractfile(member) fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "wb") as out: shutil.copyfileobj(src, out) os.chmod(target, member.mode & 0o777 & ~0o7000) except (tarfile.TarError, OSError, EOFError) as e: if isinstance(e, FileExistsError): raise BackupError("Package contains duplicate entries") from e raise BackupError(f"Package is damaged or cannot be unpacked: {e}") from e finally: tar.close() return verify_extracted(dest) def verify_extracted(dest: str) -> dict: """Read manifest.json and check that the extracted files are exactly the listed ones with the listed sizes and SHA-256 sums. Returns the manifest.""" path = os.path.join(dest, MANIFEST) if not os.path.isfile(path): raise BackupError("Package has no manifest.json") try: with open(path) as f: manifest = json.load(f) files = manifest["files"] fmt, version = manifest["format"], manifest["format_version"] manifest["schema"]["profiler"], manifest["schema"]["monitor"] except (ValueError, KeyError, TypeError) as e: raise BackupError("Package manifest is invalid") from e if fmt != FORMAT_NAME or not isinstance(version, int) or version > FORMAT_VERSION or version < 1: raise BackupError(f"Unknown package format (format_version {version!r}); " f"this release reads format {FORMAT_VERSION}") if not isinstance(files, dict): raise BackupError("Package manifest is invalid") present = set() for root, _dirs, names in os.walk(dest): for name in names: rel = os.path.relpath(os.path.join(root, name), dest).replace(os.sep, "/") if rel != MANIFEST: present.add(rel) if present != set(files): extra, missing = sorted(present - set(files)), sorted(set(files) - present) raise BackupError("Package content does not match the manifest" + (f" (not listed: {extra[0]})" if extra else "") + (f" (missing: {missing[0]})" if missing else "")) for rel, meta in files.items(): full = os.path.join(dest, rel) if os.path.getsize(full) != meta.get("size") or _sha256(full) != meta.get("sha256"): raise BackupError(f"Checksum mismatch: {rel}. The package is damaged") for required in (DB_PROFILER, DB_MONITOR): if required not in files: raise BackupError(f"Package has no {required}") return manifest