Backup and Restore: packages, Local/S3/SFTP/FTP destinations, UI and API

Encrypted packages (databases, PKI, client profiles) with safe restore and
a pre-restore safety copy, usable for server-to-server migration across
container and system-service installs. New Management page, ovp_backups
volume, migrations code in the profiler image, server name in package names.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-07 09:38:09 +03:00
1 parent d29c261347
commit f8cdcd0fc6
55 files changed
+4401 -37

No files matched your search

+6 -1
View File
@@ -11,7 +11,12 @@ COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Ensure DB directory exists
RUN mkdir -p /app/db
RUN mkdir -p /app/db /app/backups
# Migrations of the monitoring database (standard library only), from the build context 'core'
# (additional_contexts in docker-compose.yml). A restore migrates the package copy with them.
COPY --from=core migrations.py migrate.py db.py /opt/core/
ENV OVPMON_CORE_DIR=/opt/core
# Copy source code and entrypoint
COPY . .
+11 -1
View File
@@ -1,5 +1,6 @@
import uvicorn
from fastapi import FastAPI
import logging
import sys
import os
@@ -9,7 +10,7 @@ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from database import db_path
import migrations
from routers import system, server, profiles, server_process
from routers import system, server, profiles, server_process, backup
from utils.logging import setup_logging
from fastapi.middleware.cors import CORSMiddleware
@@ -20,6 +21,14 @@ setup_logging()
# pending while OVPMON_AUTO_MIGRATE=0.
migrations.startup_or_exit(db_path)
# Settings, destinations and history of backup and restore (own SQLite file, see services/backup/store.py).
# A failure here must not stop the VPN management: the backup routes then report the error.
try:
from services.backup import store as backup_store
backup_store.init()
except Exception:
logging.getLogger(__name__).exception("Backup store is not available")
app = FastAPI(
title="OpenVPN Profiler API",
description="REST API for managing OpenVPN profiles and configuration",
@@ -39,6 +48,7 @@ app.include_router(system.router, prefix="/api", tags=["System"])
app.include_router(server.router, prefix="/api", tags=["Server"])
app.include_router(profiles.router, prefix="/api", tags=["Profiles"])
app.include_router(server_process.router, prefix="/api", tags=["Process Control"])
app.include_router(backup.router, prefix="/api", tags=["Backup"])
@app.get("/")
def read_root():
+3
View File
@@ -6,3 +6,6 @@ python-multipart
jinja2
pyjwt
requests
cryptography
minio
paramiko
+218
View File
@@ -0,0 +1,218 @@
import re
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from utils.auth import verify_token
from services.backup import BackupError, Busy, Invalid, destinations, engine, package, store
router = APIRouter(dependencies=[Depends(verify_token)])
NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 _.-]{0,63}$")
PASSPHRASE_MIN = 8
class SettingsUpdate(BaseModel):
passphrase: Optional[str] = Field(None, max_length=256) # set or change; never returned
clear_passphrase: bool = False
default_retention: Optional[int] = Field(None, ge=1, le=1000)
server_name: Optional[str] = Field(None, max_length=63) # '' clears it (fallback names are used)
class DestinationIn(BaseModel):
name: str = Field(..., max_length=64)
type: str = Field(..., max_length=20)
enabled: bool = True
retention_count: Optional[int] = Field(None, ge=1, le=1000)
params: dict = {}
secrets: dict = {} # absent, empty or masked values keep the stored secret
class TrustIn(BaseModel):
fingerprint: str = Field(..., max_length=80) # the one shown by Test
class RunIn(BaseModel):
destination_ids: Optional[list[int]] = None
class RestoreIn(BaseModel):
destination_id: int
package: str = Field(..., max_length=200)
passphrase: Optional[str] = Field(None, max_length=256)
def _fail(e: Exception):
"""BackupError family -> HTTP error. Messages never contain secrets."""
if isinstance(e, Busy):
raise HTTPException(status_code=409, detail=str(e))
if isinstance(e, destinations.DestinationError):
raise HTTPException(status_code=502, detail=str(e))
raise HTTPException(status_code=400, detail=str(e))
def _types_info():
return [{"id": t, "label": cls.label, "remote": t in destinations.REMOTE_TYPES, "fields": cls.FIELDS,
"pins_host_key": bool(cls.PIN_PARAMS)}
for t, cls in destinations.DESTINATION_TYPES.items()]
@router.get("/backup/settings")
def get_settings():
effective, source = engine.effective_server_name()
return {
"encryption_enabled": store.has_passphrase(),
"default_retention": store.default_retention(),
"server_name": store.get_server_name(),
"effective_server_name": effective,
"server_name_source": source,
"local_root": destinations.local_root(),
"types": _types_info(),
}
@router.put("/backup/settings")
def update_settings(body: SettingsUpdate):
if engine.is_running():
raise HTTPException(status_code=409, detail="A backup or restore is running")
if body.passphrase is not None and body.clear_passphrase:
raise HTTPException(status_code=400, detail="Give a passphrase or clear it, not both")
server_name = (body.server_name or "").strip()
if server_name and not package.SERVER_NAME_RE.match(server_name):
raise HTTPException(status_code=400, detail="Server name: 1-63 letters, digits, '.' or '-', "
"starting with a letter or digit")
if body.passphrase is not None:
if len(body.passphrase) < PASSPHRASE_MIN:
raise HTTPException(status_code=400, detail=f"Passphrase must have at least {PASSPHRASE_MIN} characters")
store.set_passphrase(body.passphrase)
if body.clear_passphrase:
remote = [d["name"] for d in store.list_destinations()
if d["enabled"] and d["type"] in destinations.REMOTE_TYPES]
if remote:
raise HTTPException(status_code=400, detail="Remote destinations need a passphrase: disable or "
f"delete them first ({', '.join(remote)})")
store.set_passphrase(None)
if body.default_retention is not None:
store.set_default_retention(body.default_retention)
if body.server_name is not None:
store.set_server_name(server_name)
return get_settings()
@router.get("/backup/destinations")
def list_destinations():
return store.list_destinations()
def _prepare(body: DestinationIn, previous: Optional[dict]):
cls = destinations.DESTINATION_TYPES.get(body.type)
if cls is None:
raise HTTPException(status_code=400, detail=f"Unsupported destination type: {body.type}")
name = body.name.strip()
if not NAME_RE.match(name):
raise HTTPException(status_code=400, detail="Name: 1-64 letters, digits, spaces, '.', '_' or '-'")
same_type = bool(previous and previous["type"] == body.type)
# Secrets of another type never carry over
keep = previous["secrets"] if same_type else {}
given = {k: v for k, v in body.secrets.items() if isinstance(v, str) and v and v != store.MASK}
# A pinned host key comes only from the trust call, never from the client
client_params = {k: v for k, v in body.params.items() if k not in cls.PIN_PARAMS}
try:
params, secrets = cls.validate(client_params, given, keep)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
if same_type and cls.PIN_PARAMS:
old = previous["params"]
if all(old.get(k) == params.get(k) for k in cls.PIN_DEPENDS): # same server: the pin stays
params.update({k: old[k] for k in cls.PIN_PARAMS if old.get(k)})
retention = body.retention_count or (previous["retention_count"] if previous else store.default_retention())
return name, params, secrets, retention
@router.post("/backup/destinations", status_code=201)
def create_destination(body: DestinationIn):
name, params, secrets, retention = _prepare(body, None)
try:
dest_id = store.save_destination(None, name, body.type, body.enabled, retention, params, secrets)
except BackupError as e:
raise HTTPException(status_code=409, detail=str(e))
return store.get_destination(dest_id)
@router.put("/backup/destinations/{dest_id}")
def update_destination(dest_id: int, body: DestinationIn):
if engine.is_running():
raise HTTPException(status_code=409, detail="A backup or restore is running")
previous = store.get_destination(dest_id, with_secrets=True)
if not previous:
raise HTTPException(status_code=404, detail="Destination not found")
name, params, secrets, retention = _prepare(body, previous)
try:
store.save_destination(dest_id, name, body.type, body.enabled, retention, params, secrets)
except BackupError as e:
raise HTTPException(status_code=409, detail=str(e))
return store.get_destination(dest_id)
@router.delete("/backup/destinations/{dest_id}")
def delete_destination(dest_id: int):
if engine.is_running():
raise HTTPException(status_code=409, detail="A backup or restore is running")
if not store.delete_destination(dest_id):
raise HTTPException(status_code=404, detail="Destination not found")
return {"message": "Destination deleted"}
@router.post("/backup/destinations/{dest_id}/test")
def test_destination(dest_id: int):
try:
return engine.test_destination(dest_id)
except BackupError as e:
_fail(e)
@router.post("/backup/destinations/{dest_id}/trust-host-key")
def trust_host_key(dest_id: int, body: TrustIn):
if engine.is_running():
raise HTTPException(status_code=409, detail="A backup or restore is running")
try:
return engine.trust_host_key(dest_id, body.fingerprint.strip())
except BackupError as e:
_fail(e)
@router.get("/backup/destinations/{dest_id}/packages")
def list_packages(dest_id: int):
try:
return {"packages": engine.list_packages(dest_id)}
except BackupError as e:
_fail(e)
@router.post("/backup/run", status_code=202)
def run_backup(body: RunIn = RunIn()):
try:
engine.start_backup(body.destination_ids)
except BackupError as e:
_fail(e)
return {"state": "running"}
@router.post("/backup/restore", status_code=202)
def run_restore(body: RestoreIn):
try:
engine.start_restore(body.destination_id, body.package, body.passphrase)
except BackupError as e:
_fail(e)
return {"state": "running"}
@router.get("/backup/status")
def get_status():
return engine.status()
@router.get("/backup/history")
def get_history(limit: int = Query(20, ge=1, le=100)):
return store.history_list(limit)
+4 -3
View File
@@ -4,6 +4,7 @@ from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from database import get_db
from utils.auth import verify_token
from utils.guards import forbid_during_restore
from models import UserProfile
from schemas import UserProfile as UserProfileSchema, UserProfileCreate, UserProfileNoteUpdate
from services import pki, generator
@@ -69,7 +70,7 @@ def list_profiles(db: Session = Depends(get_db)):
return updated_profiles
@router.post("/profiles", response_model=UserProfileSchema)
@router.post("/profiles", response_model=UserProfileSchema, dependencies=[Depends(forbid_during_restore)])
def create_profile(
profile_in: UserProfileCreate,
db: Session = Depends(get_db)
@@ -123,7 +124,7 @@ def create_profile(
db.refresh(new_profile)
return new_profile
@router.put("/profiles/{profile_id}/note", response_model=UserProfileSchema)
@router.put("/profiles/{profile_id}/note", response_model=UserProfileSchema, dependencies=[Depends(forbid_during_restore)])
def update_profile_note(profile_id: int, body: UserProfileNoteUpdate, db: Session = Depends(get_db)):
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
if not profile:
@@ -134,7 +135,7 @@ def update_profile_note(profile_id: int, body: UserProfileNoteUpdate, db: Sessio
db.refresh(profile)
return profile
@router.delete("/profiles/{profile_id}")
@router.delete("/profiles/{profile_id}", dependencies=[Depends(forbid_during_restore)])
def revoke_profile(profile_id: int, db: Session = Depends(get_db)):
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
if not profile:
+2 -1
View File
@@ -4,13 +4,14 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from utils.auth import verify_token
from utils.guards import forbid_during_restore
from services import generator, process, config, pki
logger = logging.getLogger(__name__)
router = APIRouter(dependencies=[Depends(verify_token)])
@router.post("/server/configure")
@router.post("/server/configure", dependencies=[Depends(forbid_during_restore)])
def configure_server(db: Session = Depends(get_db)):
try:
pki.require_server_ready(db)
+2 -1
View File
@@ -4,6 +4,7 @@ from services import process, pki
from database import get_db
from sqlalchemy.orm import Session
from utils.auth import verify_token
from utils.guards import forbid_during_restore
from typing import Optional
from fastapi import Depends
@@ -22,7 +23,7 @@ class ProcessStats(BaseModel):
memory_mb: float
uptime: Optional[str] = None
@router.post("/server/process/{action}", response_model=ProcessActionResponse)
@router.post("/server/process/{action}", response_model=ProcessActionResponse, dependencies=[Depends(forbid_during_restore)])
def manage_process(action: str, db: Session = Depends(get_db)):
"""
Control the OpenVPN server process.
+4 -3
View File
@@ -2,6 +2,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import get_db
from utils.auth import verify_token
from utils.guards import forbid_during_restore
from schemas import (
ConfigResponse, SystemSettings, PKISetting,
SystemSettingsUpdate, PKISettingUpdate
@@ -22,14 +23,14 @@ def get_config(
response.pki = config.get_pki_settings(db)
return response
@router.put("/config/server", response_model=SystemSettings)
@router.put("/config/server", response_model=SystemSettings, dependencies=[Depends(forbid_during_restore)])
def update_server_config(
settings: SystemSettingsUpdate,
db: Session = Depends(get_db)
):
return config.update_system_settings(db, settings)
@router.put("/config/pki", response_model=PKISetting)
@router.put("/config/pki", response_model=PKISetting, dependencies=[Depends(forbid_during_restore)])
def update_pki_config(
settings: PKISettingUpdate,
db: Session = Depends(get_db)
@@ -48,7 +49,7 @@ def init_system_pki(db: Session = Depends(get_db)):
def get_init_status(db: Session = Depends(get_db)):
return pki.init_status(db)
@router.delete("/system/pki")
@router.delete("/system/pki", dependencies=[Depends(forbid_during_restore)])
def clear_system_pki(db: Session = Depends(get_db)):
if pki.is_init_running():
raise HTTPException(status_code=409, detail="PKI initialization is running")
+21
View File
@@ -0,0 +1,21 @@
"""Backup and restore of the application data (databases, PKI, client profiles).
Modules:
package.py package format (tar.gz + manifest), snapshots, safe extraction
crypto.py optional package encryption (AES-256-GCM, scrypt)
destinations.py where packages go: common interface, local folder and S3 (minio)
store.py settings, destinations and history in a separate SQLite file
engine.py backup job and restore engine (one background job at a time)
"""
class BackupError(Exception):
"""A backup or restore step failed. The message is safe to show to the user (no secrets)."""
class Invalid(BackupError):
"""The request cannot be accepted as it is (API: 400)."""
class Busy(BackupError):
"""Another backup or restore job is running (API: 409)."""
+98
View File
@@ -0,0 +1,98 @@
"""Package encryption: AES-256-GCM in chunks, key from the passphrase with scrypt.
File layout:
magic "OVPBAKE1" | log2(N) 1 byte | r 1 byte | p 1 byte | salt 16 | nonce prefix 8 (header, 35 bytes)
then chunks of CHUNK bytes of plaintext, each stored as ciphertext + 16 byte tag.
Chunk i uses the nonce prefix || i (4 bytes, big endian). The header and a "final chunk" flag
are authenticated data of every chunk, so a truncated, reordered or modified file is rejected.
"""
import os
import struct
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from . import BackupError
MAGIC = b"OVPBAKE1"
HEADER_LEN = len(MAGIC) + 3 + 16 + 8
CHUNK = 1024 * 1024
TAG = 16
SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P = 15, 8, 1 # about 32 MiB of memory
# Bounds for the parameters read from a file: a crafted header must not exhaust memory or CPU
MAX_LOG_N, MAX_R, MAX_P = 20, 16, 4
class WrongPassphrase(BackupError):
"""Wrong passphrase, or the file is damaged (AES-GCM cannot tell the two apart)."""
def is_encrypted(path: str) -> bool:
try:
with open(path, "rb") as f:
return f.read(len(MAGIC)) == MAGIC
except OSError:
return False
def _derive(passphrase: str, salt: bytes, log_n: int, r: int, p: int) -> bytes:
return Scrypt(salt=salt, length=32, n=2 ** log_n, r=r, p=p).derive(passphrase.encode("utf-8"))
def _nonce(prefix: bytes, index: int) -> bytes:
return prefix + struct.pack(">I", index)
def _aad(header: bytes, final: bool) -> bytes:
return header + (b"\x01" if final else b"\x00")
def encrypt_file(src: str, dst: str, passphrase: str) -> None:
if not passphrase:
raise BackupError("Passphrase is empty")
salt, prefix = os.urandom(16), os.urandom(8)
header = MAGIC + bytes([SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P]) + salt + prefix
aes = AESGCM(_derive(passphrase, salt, SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P))
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with open(src, "rb") as fin, os.fdopen(fd, "wb") as fout:
fout.write(header)
index = 0
block = fin.read(CHUNK)
while True:
nxt = fin.read(CHUNK)
final = not nxt
fout.write(aes.encrypt(_nonce(prefix, index), block, _aad(header, final)))
if final:
break
block, index = nxt, index + 1
def decrypt_file(src: str, dst: str, passphrase: str) -> None:
if not passphrase:
raise WrongPassphrase("Passphrase is required for an encrypted package")
with open(src, "rb") as fin:
header = fin.read(HEADER_LEN)
if len(header) != HEADER_LEN or not header.startswith(MAGIC):
raise BackupError("Not an encrypted package (bad header)")
log_n, r, p = header[8], header[9], header[10]
if not (1 <= log_n <= MAX_LOG_N and 1 <= r <= MAX_R and 1 <= p <= MAX_P):
raise BackupError("Encrypted package has unsupported key derivation parameters")
salt, prefix = header[11:27], header[27:35]
aes = AESGCM(_derive(passphrase, salt, log_n, r, p))
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "wb") as fout:
index = 0
block = fin.read(CHUNK + TAG)
if not block:
raise BackupError("Encrypted package is truncated")
while True:
nxt = fin.read(CHUNK + TAG)
final = not nxt
try:
fout.write(aes.decrypt(_nonce(prefix, index), block, _aad(header, final)))
except InvalidTag:
raise WrongPassphrase("Wrong passphrase, or the package is damaged") from None
if final:
break
block, index = nxt, index + 1
@@ -0,0 +1,876 @@
"""Backup destinations. Every type implements the same interface:
test() check the connection and the right to write and delete; returns a message
put(local_path, name) store a file under name
list() [{"name", "size", "mtime"}] of the files in the destination folder
get(name, local_path) download to a local file
delete(name) remove a file
Implemented: "local", "s3", "sftp" and "ftp". To add a type (smb): write a Destination subclass
with FIELDS, validate() and the five methods, and add it to DESTINATION_TYPES. The API accepts
exactly the types of that registry.
"""
import hmac
import hashlib
import base64
import io
import os
import re
import shutil
import socket
import ssl
import stat
import uuid
from contextlib import contextmanager
from datetime import datetime, timezone
from typing import Optional
from . import BackupError
from .package import PACKAGE_RE
DEFAULT_LOCAL_ROOT = "/var/lib/ovpmon/backups"
SAFE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
FOLDER_SEGMENT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
HOST_RE = re.compile(r"^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$")
BUCKET_RE = re.compile(r"^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$")
REGION_RE = re.compile(r"^[A-Za-z0-9-]{1,40}$")
class DestinationError(BackupError):
"""The destination refused or could not be reached. The message never contains secrets."""
class NeedsTrust(DestinationError):
"""The SSH host key of the server is not pinned yet (or changed). Carries what the server showed."""
def __init__(self, message: str, fingerprint: str, key_type: str, changed: bool = False):
super().__init__(message)
self.fingerprint, self.key_type, self.changed = fingerprint, key_type, changed
def local_root() -> str:
return os.environ.get("OVPMON_BACKUP_LOCAL_ROOT", "").strip() or DEFAULT_LOCAL_ROOT
def _check_name(name: str) -> str:
if not isinstance(name, str) or not SAFE_NAME_RE.match(name) or ".." in name:
raise DestinationError("Invalid file name")
return name
def _short(e: Exception) -> str:
return f"{type(e).__name__}: {str(e)[:300]}"
class Destination:
type = ""
label = ""
# Field description for the UI: name, label, kind (text|number|bool|secret|secret_multiline),
# required, default, hint; optional warning + warn_if (shown while the value equals warn_if)
FIELDS: list = []
# Parameters set by pinning a host key (never accepted from the client, kept while the parameters
# of PIN_DEPENDS stay the same); empty for types without pinning
PIN_PARAMS: tuple = ()
PIN_DEPENDS: tuple = ()
def __init__(self, params: dict, secrets: dict):
self.params = params
self.secrets = secrets
@classmethod
def validate(cls, params: dict, secrets: dict, previous_secrets: Optional[dict] = None):
"""Return (clean_params, clean_secrets) or raise ValueError with a message for the user."""
raise NotImplementedError
def test(self) -> str:
raise NotImplementedError
def put(self, local_path: str, name: str) -> None:
raise NotImplementedError
def list(self) -> list:
raise NotImplementedError
def get(self, name: str, local_path: str) -> None:
raise NotImplementedError
def delete(self, name: str) -> None:
raise NotImplementedError
def fetch_host_key(self):
"""(fingerprint, key type) the server shows now; no credentials are sent. Pinning types only."""
raise NotImplementedError
def _unknown_keys(given: dict, allowed: set, what: str):
extra = sorted(set(given) - allowed)
if extra:
raise ValueError(f"Unknown {what}: {', '.join(extra)}")
# --- local folder --------------------------------------------------------------------------
class LocalDestination(Destination):
"""A sub folder inside the root OVPMON_BACKUP_LOCAL_ROOT. Paths outside the root and
symbolic links are rejected."""
type = "local"
label = "Local folder"
FIELDS = [
{"name": "folder", "label": "Folder (inside the backup root)", "kind": "text", "required": True,
"default": "default", "hint": "Sub folder of the server's backup root, for example 'daily'"},
]
@classmethod
def validate(cls, params, secrets, previous_secrets=None):
_unknown_keys(params, {"folder"}, "parameters")
if secrets:
raise ValueError("A local destination has no secrets")
folder = str(params.get("folder", "")).strip().strip("/")
if not folder:
raise ValueError("Folder is required")
parts = folder.split("/")
if len(parts) > 4 or not all(FOLDER_SEGMENT_RE.match(p) and ".." not in p for p in parts):
raise ValueError("Folder must be a relative path of letters, digits, '.', '_' and '-' "
"(no '..', no leading dot, at most 4 levels)")
return {"folder": "/".join(parts)}, {}
def _root(self) -> str:
root = local_root()
try:
os.makedirs(root, mode=0o700, exist_ok=True)
except OSError as e:
raise DestinationError(f"Backup root {root} is not usable: {e.strerror or e}") from e
return os.path.realpath(root)
def _dir(self, create: bool) -> str:
root = self._root()
current = root
for part in self.params["folder"].split("/"):
current = os.path.join(current, part)
try:
st = os.lstat(current)
except FileNotFoundError:
if not create:
raise DestinationError("Folder does not exist yet") from None
try:
os.mkdir(current, 0o700)
except OSError as e:
raise DestinationError(f"Cannot create the folder: {e.strerror or e}") from e
continue
if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
raise DestinationError("Folder is a symbolic link or not a directory: refused")
real = os.path.realpath(current)
if real != root and not real.startswith(root + os.sep):
raise DestinationError("Folder is outside the backup root: refused")
return real
def test(self) -> str:
directory = self._dir(create=True)
probe = os.path.join(directory, f".ovpmon-test-{uuid.uuid4().hex[:8]}")
try:
with open(probe, "wb") as f:
f.write(b"ok")
os.remove(probe)
except OSError as e:
raise DestinationError(f"Cannot write to the folder: {e.strerror or e}") from e
free = shutil.disk_usage(directory).free // (1024 * 1024)
return f"Folder is writable ({free} MB free)"
def put(self, local_path, name):
_check_name(name)
directory = self._dir(create=True)
final = os.path.join(directory, name)
tmp = os.path.join(directory, f".{name}.part")
try:
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "wb") as out, open(local_path, "rb") as src:
shutil.copyfileobj(src, out, 1024 * 1024)
os.replace(tmp, final)
except OSError as e:
try:
os.remove(tmp)
except OSError:
pass
raise DestinationError(f"Cannot write the package: {e.strerror or e}") from e
def list(self):
try:
directory = self._dir(create=False)
except DestinationError as e:
if "does not exist" in str(e):
return []
raise
out = []
with os.scandir(directory) as it:
for entry in it:
try:
st = entry.stat(follow_symlinks=False)
except OSError:
continue
if stat.S_ISREG(st.st_mode) and not entry.name.startswith("."):
out.append({"name": entry.name, "size": st.st_size, "mtime": st.st_mtime})
return out
def get(self, name, local_path):
_check_name(name)
path = os.path.join(self._dir(create=False), name)
try:
st = os.lstat(path)
if not stat.S_ISREG(st.st_mode):
raise DestinationError("Not a regular file: refused")
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "wb") as out, open(path, "rb") as src:
shutil.copyfileobj(src, out, 1024 * 1024)
except OSError as e:
raise DestinationError(f"Cannot read the package: {e.strerror or e}") from e
def delete(self, name):
_check_name(name)
path = os.path.join(self._dir(create=False), name)
try:
if stat.S_ISREG(os.lstat(path).st_mode):
os.remove(path)
except FileNotFoundError:
pass
except OSError as e:
raise DestinationError(f"Cannot delete the package: {e.strerror or e}") from e
# --- S3 (minio client) ---------------------------------------------------------------------
class S3Destination(Destination):
"""AWS S3 or a compatible store, through the minio Python SDK."""
type = "s3"
label = "S3 bucket"
FIELDS = [
{"name": "endpoint", "label": "Endpoint (host[:port])", "kind": "text", "required": True,
"default": "s3.amazonaws.com", "hint": "Without http:// or https://"},
{"name": "secure", "label": "Use TLS (https)", "kind": "bool", "required": False, "default": True},
{"name": "region", "label": "Region (optional)", "kind": "text", "required": False, "default": ""},
{"name": "bucket", "label": "Bucket", "kind": "text", "required": True, "default": ""},
{"name": "prefix", "label": "Prefix (optional)", "kind": "text", "required": False, "default": "",
"hint": "Folder inside the bucket, for example 'ovpmon/'"},
{"name": "access_key", "label": "Access key", "kind": "secret", "required": True},
{"name": "secret_key", "label": "Secret key", "kind": "secret", "required": True},
]
@classmethod
def validate(cls, params, secrets, previous_secrets=None):
_unknown_keys(params, {"endpoint", "secure", "region", "bucket", "prefix"}, "parameters")
_unknown_keys(secrets, {"access_key", "secret_key"}, "secrets")
endpoint = str(params.get("endpoint", "")).strip()
host, _, port = endpoint.partition(":")
if not endpoint or "/" in endpoint or not HOST_RE.match(host) or (port and not (port.isdigit() and 0 < int(port) < 65536)):
raise ValueError("Endpoint must be host[:port] without http:// or a path")
bucket = str(params.get("bucket", "")).strip()
if not BUCKET_RE.match(bucket) or ".." in bucket:
raise ValueError("Bucket name is invalid (3-63 lowercase letters, digits, '.' and '-')")
region = str(params.get("region", "") or "").strip()
if region and not REGION_RE.match(region):
raise ValueError("Region is invalid")
prefix = str(params.get("prefix", "") or "").strip().strip("/")
if prefix:
parts = prefix.split("/")
if len(prefix) > 200 or not all(re.match(r"^[A-Za-z0-9][A-Za-z0-9._ -]{0,63}$", p) for p in parts) or ".." in prefix:
raise ValueError("Prefix is invalid: use folders of letters, digits, '.', '_', '-' and spaces")
prefix += "/"
clean_secrets = {}
previous = previous_secrets or {}
for key in ("access_key", "secret_key"):
value = str(secrets.get(key) or "").strip() or previous.get(key, "")
if not value:
raise ValueError(f"{'Access key' if key == 'access_key' else 'Secret key'} is required")
if len(value) > 512:
raise ValueError("Key is too long")
clean_secrets[key] = value
clean = {"endpoint": endpoint, "secure": bool(params.get("secure", True)),
"region": region, "bucket": bucket, "prefix": prefix}
return clean, clean_secrets
def _client(self):
try:
import urllib3
from minio import Minio
except ImportError as e: # the package is in requirements.txt; this is a broken installation
raise DestinationError("The 'minio' library is not installed") from e
http = urllib3.PoolManager(timeout=urllib3.Timeout(connect=10, read=120),
retries=urllib3.Retry(total=2, backoff_factor=0.5))
return Minio(self.params["endpoint"], access_key=self.secrets["access_key"],
secret_key=self.secrets["secret_key"], secure=self.params["secure"],
region=self.params["region"] or None, http_client=http)
def _call(self, fn):
from minio.error import S3Error
try:
return fn()
except DestinationError:
raise
except S3Error as e:
raise DestinationError(f"S3 error {e.code}: {str(e.message)[:200]}") from e
except Exception as e:
raise DestinationError(_short(e)) from e
def _key(self, name: str) -> str:
return self.params["prefix"] + _check_name(name)
def test(self) -> str:
client = self._client()
bucket = self.params["bucket"]
def probe():
if not client.bucket_exists(bucket):
raise DestinationError(f"Bucket '{bucket}' does not exist or is not visible to this key")
key = self.params["prefix"] + f".ovpmon-test-{uuid.uuid4().hex[:8]}"
import io
client.put_object(bucket, key, io.BytesIO(b"ok"), 2)
try:
client.remove_object(bucket, key)
except Exception:
return "Bucket is writable, but deleting objects is not allowed (rotation will not work)"
return "Bucket is reachable, write and delete work"
return self._call(probe)
def put(self, local_path, name):
client = self._client()
self._call(lambda: client.fput_object(self.params["bucket"], self._key(name), local_path,
content_type="application/octet-stream"))
def list(self):
client = self._client()
prefix = self.params["prefix"]
def run():
out = []
for obj in client.list_objects(self.params["bucket"], prefix=prefix or None, recursive=False):
if obj.is_dir or not obj.object_name.startswith(prefix):
continue
name = obj.object_name[len(prefix):]
if "/" in name or not name:
continue
mtime = obj.last_modified.timestamp() if obj.last_modified else None
out.append({"name": name, "size": obj.size or 0, "mtime": mtime})
return out
return self._call(run)
def get(self, name, local_path):
client = self._client()
def run():
resp = client.get_object(self.params["bucket"], self._key(name))
try:
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "wb") as out:
shutil.copyfileobj(resp, out, 1024 * 1024)
finally:
resp.close()
resp.release_conn()
self._call(run)
def delete(self, name):
client = self._client()
self._call(lambda: client.remove_object(self.params["bucket"], self._key(name)))
# --- shared by SFTP and FTP ----------------------------------------------------------------
CONNECT_TIMEOUT = 15 # seconds: connection, banner, login
TRANSFER_TIMEOUT = 120 # seconds without data on an open transfer
USER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._@-]{0,127}$")
FINGERPRINT_RE = re.compile(r"^SHA256:[A-Za-z0-9+/]{43}$")
def _check_host_port(params: dict, default_port: int):
host = str(params.get("host", "")).strip()
if not host or not HOST_RE.match(host):
raise ValueError("Host must be a host name or an IPv4 address")
try:
port = int(params.get("port") or default_port)
except (TypeError, ValueError):
raise ValueError("Port must be a number") from None
if not 0 < port < 65536:
raise ValueError("Port must be between 1 and 65535")
return host, port
def _check_username(params: dict) -> str:
user = str(params.get("username", "")).strip()
if not USER_RE.match(user):
raise ValueError("User name is required (letters, digits, '.', '_', '-', '@')")
return user
def _check_directory(params: dict) -> str:
"""Remote directory: the same rule as the local folder (relative, no '..', at most 4 levels)."""
directory = str(params.get("directory", "")).strip().rstrip("/")
if not directory:
raise ValueError("Directory is required")
if directory.startswith("/"):
raise ValueError("Directory must be relative to the login directory of the user (no leading '/')")
parts = directory.split("/")
if len(parts) > 4 or not all(FOLDER_SEGMENT_RE.match(p) and ".." not in p for p in parts):
raise ValueError("Directory must be a relative path of letters, digits, '.', '_' and '-' "
"(no '..', no leading dot, at most 4 levels)")
return "/".join(parts)
def _secret_value(secrets: dict, key: str, label: str, limit: int = 512) -> str:
value = str(secrets.get(key) or "").strip()
if len(value) > limit:
raise ValueError(f"{label} is too long")
return value
def _ssh_fingerprint(key) -> str:
return "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode("ascii").rstrip("=")
# --- SFTP (paramiko) -----------------------------------------------------------------------
def _paramiko():
try:
import paramiko
except ImportError as e: # the package is in requirements.txt; this is a broken installation
raise DestinationError("The 'paramiko' library is not installed") from e
return paramiko
def _load_private_key(text: str, passphrase: str):
"""paramiko key object of a PEM / OpenSSH private key text. ValueError without any key material."""
paramiko = _paramiko()
for cls in (paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.RSAKey):
try:
return cls.from_private_key(io.StringIO(text), password=passphrase or None)
except Exception:
continue # not this key type, or a wrong passphrase: the message below covers both
raise ValueError("The private key cannot be read: check the key text and its passphrase "
"(supported: RSA, ECDSA, Ed25519; OpenSSH or PEM)")
class SFTPDestination(Destination):
"""SFTP server. The SSH host key is pinned by its SHA-256 fingerprint: the first Test shows it,
the administrator confirms it ('Trust'), after that every connection must present exactly that
key. Nothing is copied, listed, read or deleted while the key is not pinned."""
type = "sftp"
label = "SFTP server"
PIN_PARAMS = ("host_key", "host_key_type")
PIN_DEPENDS = ("host", "port")
FIELDS = [
{"name": "host", "label": "Host", "kind": "text", "required": True, "default": "",
"hint": "Host name or IPv4 address"},
{"name": "port", "label": "Port", "kind": "number", "required": True, "default": 22},
{"name": "username", "label": "User name", "kind": "text", "required": True, "default": ""},
{"name": "directory", "label": "Directory", "kind": "text", "required": True, "default": "ovpmon-backups",
"hint": "Relative to the login directory of the user; created if missing"},
{"name": "password", "label": "Password", "kind": "secret", "required": False,
"hint": "Password or private key: give one of them"},
{"name": "private_key", "label": "Private key (PEM / OpenSSH text)", "kind": "secret_multiline",
"required": False},
{"name": "key_passphrase", "label": "Private key passphrase (if the key is encrypted)", "kind": "secret",
"required": False},
]
@classmethod
def validate(cls, params, secrets, previous_secrets=None):
_unknown_keys(params, {"host", "port", "username", "directory"}, "parameters")
_unknown_keys(secrets, {"password", "private_key", "key_passphrase"}, "secrets")
host, port = _check_host_port(params, 22)
clean = {"host": host, "port": port, "username": _check_username(params),
"directory": _check_directory(params)}
previous = previous_secrets or {}
password = _secret_value(secrets, "password", "Password")
key = _secret_value(secrets, "private_key", "Private key", 16384).replace("\r\n", "\n")
phrase = _secret_value(secrets, "key_passphrase", "Key passphrase")
if password and key:
raise ValueError("Give a password or a private key, not both")
if not password and not key:
# nothing new: keep what is stored (a new passphrase goes with the stored key)
password, key = previous.get("password", ""), previous.get("private_key", "")
phrase = phrase or previous.get("key_passphrase", "")
if not password and not key:
raise ValueError("A password or a private key is required")
if key:
if "PRIVATE KEY" not in key:
raise ValueError("The private key must be the text of the key file (-----BEGIN ... PRIVATE KEY-----)")
_load_private_key(key + "\n", phrase)
clean_secrets = {"private_key": key.strip() + "\n"}
if phrase:
clean_secrets["key_passphrase"] = phrase
else:
clean_secrets = {"password": password}
return clean, clean_secrets
# -- connection --
@staticmethod
def _policy(pinned: Optional[str], seen: dict):
"""Host key policy: records what the server shows and accepts ONLY the pinned fingerprint.
Unknown keys are rejected (never added automatically)."""
paramiko = _paramiko()
class PinnedPolicy(paramiko.MissingHostKeyPolicy):
def missing_host_key(self, client, hostname, key):
seen["fingerprint"], seen["key_type"] = _ssh_fingerprint(key), key.get_name()
if not pinned or not hmac.compare_digest(seen["fingerprint"], pinned):
raise paramiko.SSHException("host key is not trusted")
return PinnedPolicy()
def _connect(self, allow_trust: bool = False):
"""Open the SSH connection and return the client. allow_trust: for Test and the pinning
call; a key that is unknown or changed then raises NeedsTrust with the fingerprint."""
paramiko = _paramiko()
pinned = self.params.get("host_key") or None
if not pinned and not allow_trust:
raise DestinationError("The host key of the server is not trusted yet: run Test and confirm the fingerprint")
pkey = None
if self.secrets.get("private_key"):
try:
pkey = _load_private_key(self.secrets["private_key"], self.secrets.get("key_passphrase", ""))
except ValueError as e:
raise DestinationError(str(e)) from None
seen: dict = {}
client = paramiko.SSHClient() # no known_hosts is loaded: every key goes to the policy
client.set_missing_host_key_policy(self._policy(pinned, seen))
try:
client.connect(self.params["host"], port=self.params["port"], username=self.params["username"],
password=self.secrets.get("password") or None, pkey=pkey,
timeout=CONNECT_TIMEOUT, banner_timeout=CONNECT_TIMEOUT, auth_timeout=CONNECT_TIMEOUT,
allow_agent=False, look_for_keys=False)
except Exception as e:
client.close()
fp = seen.get("fingerprint")
if fp and fp != pinned:
if allow_trust:
raise NeedsTrust(
("The host key changed: it differs from the trusted one" if pinned
else "The host key of the server is not trusted yet"),
fp, seen.get("key_type", ""), changed=bool(pinned)) from None
raise DestinationError("The host key of the server changed: connection refused. "
"Run Test to see the new fingerprint and trust it if the change is expected") from None
raise DestinationError(self._explain(e)) from None
return client
@staticmethod
def _explain(e: Exception) -> str:
paramiko = _paramiko()
if isinstance(e, paramiko.AuthenticationException):
return "Authentication failed: check the user name and the password or key"
if isinstance(e, (socket.timeout, TimeoutError)):
return "Connection timed out"
if isinstance(e, socket.gaierror):
return "Host name cannot be resolved"
if isinstance(e, ConnectionRefusedError):
return "Connection refused"
if isinstance(e, paramiko.SSHException):
return f"SSH error: {str(e)[:200]}"
if isinstance(e, OSError):
return f"Network error: {e.strerror or type(e).__name__}"
return _short(e)
@contextmanager
def _session(self, allow_trust: bool = False):
client = self._connect(allow_trust)
try:
sftp = client.open_sftp()
sftp.get_channel().settimeout(TRANSFER_TIMEOUT)
yield sftp
except DestinationError:
raise
except FileNotFoundError:
raise DestinationError("File or directory not found on the server") from None
except Exception as e:
raise DestinationError(self._explain(e)) from None
finally:
client.close()
def fetch_host_key(self):
try:
self._connect(allow_trust=True).close()
except NeedsTrust as n:
return n.fingerprint, n.key_type
return self.params.get("host_key", ""), self.params.get("host_key_type", "")
# -- operations --
def _dir(self, sftp, create: bool) -> str:
"""Change into the directory (creating the levels when asked). Returns the path."""
path = ""
for part in self.params["directory"].split("/"):
path = f"{path}/{part}" if path else part
try:
if not stat.S_ISDIR(sftp.stat(path).st_mode):
raise DestinationError(f"'{path}' on the server is not a directory")
except FileNotFoundError:
if not create:
raise DestinationError("Directory does not exist yet") from None
sftp.mkdir(path, 0o700)
return path
def test(self) -> str:
with self._session(allow_trust=True) as sftp:
directory = self._dir(sftp, create=True)
probe = f"{directory}/.ovpmon-test-{uuid.uuid4().hex[:8]}"
sftp.putfo(io.BytesIO(b"ok"), probe)
try:
sftp.remove(probe)
except Exception:
return "Server is writable, but deleting files is not allowed (rotation will not work)"
return "SFTP server is reachable, host key matches, write and delete work"
def put(self, local_path, name):
_check_name(name)
with self._session() as sftp:
directory = self._dir(sftp, create=True)
final, tmp = f"{directory}/{name}", f"{directory}/.{name}.part"
try:
sftp.put(local_path, tmp, confirm=True)
try:
sftp.posix_rename(tmp, final)
except OSError: # the server has no posix-rename extension
sftp.rename(tmp, final)
except Exception:
try:
sftp.remove(tmp)
except Exception:
pass
raise
def list(self):
with self._session() as sftp:
try:
directory = self._dir(sftp, create=False)
except DestinationError as e:
if "does not exist" in str(e):
return []
raise
return [{"name": a.filename, "size": a.st_size or 0, "mtime": a.st_mtime}
for a in sftp.listdir_attr(directory)
if stat.S_ISREG(a.st_mode or 0) and PACKAGE_RE.match(a.filename)]
def get(self, name, local_path):
_check_name(name)
with self._session() as sftp:
remote = f"{self._dir(sftp, create=False)}/{name}"
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "wb") as out:
sftp.getfo(remote, out)
def delete(self, name):
_check_name(name)
with self._session() as sftp:
try:
sftp.remove(f"{self._dir(sftp, create=False)}/{name}")
except FileNotFoundError:
pass
# --- FTP / FTPS (ftplib) -------------------------------------------------------------------
class FTPDestination(Destination):
"""FTP server; explicit FTPS (AUTH TLS) with certificate verification by default. Plain FTP and a
disabled certificate check are allowed explicitly (the UI warns)."""
type = "ftp"
label = "FTP / FTPS server"
FIELDS = [
{"name": "host", "label": "Host", "kind": "text", "required": True, "default": "",
"hint": "Host name or IPv4 address"},
{"name": "port", "label": "Port", "kind": "number", "required": True, "default": 21},
{"name": "username", "label": "User name", "kind": "text", "required": True, "default": ""},
{"name": "directory", "label": "Directory", "kind": "text", "required": True, "default": "ovpmon-backups",
"hint": "Relative to the login directory of the user; created if missing"},
{"name": "tls", "label": "Use TLS (explicit FTPS)", "kind": "bool", "required": False, "default": True,
"warning": "Without TLS the password and the packages travel in clear text. Use only inside a trusted network.",
"warn_if": False},
{"name": "verify_cert", "label": "Verify the server certificate", "kind": "bool", "required": False,
"default": True,
"warning": "Certificate verification is off: the server cannot be told from an impostor. Use only for a self-signed certificate in a trusted network.",
"warn_if": False},
{"name": "passive", "label": "Passive mode", "kind": "bool", "required": False, "default": True},
{"name": "password", "label": "Password", "kind": "secret", "required": True},
]
@classmethod
def validate(cls, params, secrets, previous_secrets=None):
_unknown_keys(params, {"host", "port", "username", "directory", "tls", "verify_cert", "passive"}, "parameters")
_unknown_keys(secrets, {"password"}, "secrets")
host, port = _check_host_port(params, 21)
clean = {"host": host, "port": port, "username": _check_username(params),
"directory": _check_directory(params),
"tls": bool(params.get("tls", True)), "verify_cert": bool(params.get("verify_cert", True)),
"passive": bool(params.get("passive", True))}
password = _secret_value(secrets, "password", "Password") or (previous_secrets or {}).get("password", "")
if not password:
raise ValueError("Password is required")
return clean, {"password": password}
@contextmanager
def _session(self, create_dir: bool = False):
import ftplib
p = self.params
try:
if p["tls"]:
ctx = ssl.create_default_context()
if not p["verify_cert"]:
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
ftp = ftplib.FTP_TLS(context=ctx, timeout=TRANSFER_TIMEOUT)
else:
ftp = ftplib.FTP(timeout=TRANSFER_TIMEOUT)
except Exception as e:
raise DestinationError(_short(e)) from None
try:
try:
ftp.connect(p["host"], p["port"], timeout=CONNECT_TIMEOUT)
ftp.login(p["username"], self.secrets["password"])
ftp.timeout = TRANSFER_TIMEOUT # transfers (data connections) wait longer than the login
ftp.sock.settimeout(TRANSFER_TIMEOUT)
if p["tls"]:
ftp.prot_p() # TLS for the data connection too
ftp.set_pasv(p["passive"])
self._cd(ftp, create_dir)
yield ftp
except DestinationError:
raise
except Exception as e:
raise DestinationError(self._explain(e)) from None
finally:
try:
ftp.quit()
except Exception:
ftp.close()
@staticmethod
def _explain(e: Exception) -> str:
import ftplib
if isinstance(e, ssl.SSLCertVerificationError):
return f"TLS certificate check failed: {(e.verify_message or 'invalid certificate')[:150]}. " \
"For a self-signed certificate turn the verification off in the destination"
if isinstance(e, ssl.SSLError):
return f"TLS error: {(e.reason or type(e).__name__)}"
if isinstance(e, ftplib.error_perm):
text = str(e)[:200]
return "Login failed: check the user name and the password" if text.startswith("530") else f"Server refused: {text}"
if isinstance(e, ftplib.Error):
return f"FTP error: {str(e)[:200]}"
if isinstance(e, (socket.timeout, TimeoutError)):
return "Connection timed out"
if isinstance(e, socket.gaierror):
return "Host name cannot be resolved"
if isinstance(e, ConnectionRefusedError):
return "Connection refused"
if isinstance(e, EOFError):
return "The server closed the connection"
if isinstance(e, OSError):
return f"Network error: {e.strerror or type(e).__name__}"
return _short(e)
def _cd(self, ftp, create: bool) -> None:
import ftplib
for part in self.params["directory"].split("/"):
try:
ftp.cwd(part)
except ftplib.error_perm:
if not create:
raise DestinationError("Directory does not exist yet") from None
ftp.mkd(part)
ftp.cwd(part)
def test(self) -> str:
with self._session(create_dir=True) as ftp:
probe = f".ovpmon-test-{uuid.uuid4().hex[:8]}"
ftp.storbinary(f"STOR {probe}", io.BytesIO(b"ok"))
try:
ftp.delete(probe)
except Exception:
return "Server is writable, but deleting files is not allowed (rotation will not work)"
mode = "TLS" if self.params["tls"] else "NO TLS (clear text)"
return f"FTP server is reachable ({mode}), write and delete work"
def put(self, local_path, name):
_check_name(name)
tmp = f".{name}.part"
with self._session(create_dir=True) as ftp:
try:
with open(local_path, "rb") as src:
ftp.storbinary(f"STOR {tmp}", src, blocksize=1024 * 1024)
ftp.rename(tmp, name)
except Exception:
try:
ftp.delete(tmp)
except Exception:
pass
raise
def list(self):
try:
with self._session() as ftp:
return self._packages(ftp)
except DestinationError as e:
if "does not exist" in str(e):
return []
raise
@staticmethod
def _packages(ftp):
import ftplib
out = []
try:
for name, facts in ftp.mlsd(facts=["type", "size", "modify"]):
if facts.get("type") == "file" and PACKAGE_RE.match(name):
out.append({"name": name, "size": int(facts.get("size") or 0),
"mtime": FTPDestination._mtime(facts.get("modify"))})
return out
except ftplib.error_perm:
out = [] # no MLSD on this server: names first, then size and time of our packages
ftp.voidcmd("TYPE I")
for entry in ftp.nlst():
name = entry.rsplit("/", 1)[-1]
if not PACKAGE_RE.match(name):
continue
try:
size = ftp.size(name) or 0
except ftplib.Error:
size = 0
try:
mtime = FTPDestination._mtime(ftp.voidcmd(f"MDTM {name}").split()[-1])
except ftplib.Error:
mtime = None
out.append({"name": name, "size": size, "mtime": mtime})
return out
@staticmethod
def _mtime(modify):
try:
return datetime.strptime(modify[:14], "%Y%m%d%H%M%S").replace(tzinfo=timezone.utc).timestamp()
except (TypeError, ValueError):
return None
def get(self, name, local_path):
_check_name(name)
with self._session() as ftp:
ftp.voidcmd("TYPE I")
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "wb") as out:
ftp.retrbinary(f"RETR {name}", out.write, blocksize=1024 * 1024)
def delete(self, name):
_check_name(name)
with self._session() as ftp:
ftp.delete(name)
# Registry: the API accepts exactly these types. smb comes in a later pass.
DESTINATION_TYPES = {
LocalDestination.type: LocalDestination,
S3Destination.type: S3Destination,
SFTPDestination.type: SFTPDestination,
FTPDestination.type: FTPDestination,
}
REMOTE_TYPES = {t for t in DESTINATION_TYPES if t != "local"} # these need an encryption passphrase
def build_destination(dtype: str, params: dict, secrets: dict) -> Destination:
cls = DESTINATION_TYPES.get(dtype)
if cls is None:
raise BackupError(f"Unsupported destination type: {dtype}")
return cls(params, secrets)
+657
View File
@@ -0,0 +1,657 @@
"""Backup job and restore engine.
One background job at a time for the whole service (a backup or a restore), like the async PKI
initialization: the state lives in memory of the single Profiler process, results go to the history
in ovpmon_backup.db.
"""
import copy
import logging
import os
import shutil
import sqlite3
import subprocess
import sys
import tempfile
import threading
from datetime import datetime, timezone
from typing import Optional
import migrations
from database import SessionLocal, engine as sa_engine
from . import BackupError, Busy, Invalid, crypto, destinations, package, store
from services import pki, process
logger = logging.getLogger(__name__)
PRE_RESTORE_FOLDER = "pre-restore"
PRE_RESTORE_KEEP = 5
_lock = threading.Lock()
_job = {"kind": None, "state": "idle", "stages": [], "results": [], "warnings": [],
"started_at": None, "finished_at": None, "message": None, "relogin": False}
# --- paths ---------------------------------------------------------------------------------
def profiler_db_path() -> str:
from database import db_path
return os.path.abspath(db_path)
def monitor_db_path() -> str:
env = os.environ.get("OVPMON_OPENVPN_MONITOR_DB_PATH", "").strip()
return os.path.abspath(env) if env else os.path.join(os.path.dirname(profiler_db_path()), "openvpn_monitor.db")
def pki_dir() -> str:
return pki.PKI_DIR
def client_dir() -> str:
return os.path.join(os.getcwd(), "client-config")
def runtime() -> str:
return "container" if process.is_container() else "host"
def _work_dir() -> str:
"""Temporary directory for a job: next to the local backups (they have room by definition),
else the system temporary directory."""
base = os.environ.get("OVPMON_BACKUP_WORK_DIR", "").strip() or os.path.join(destinations.local_root(), ".work")
try:
os.makedirs(base, mode=0o700, exist_ok=True)
except OSError:
base = None
return tempfile.mkdtemp(prefix="job-", dir=base)
# --- job state -----------------------------------------------------------------------------
def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def status() -> dict:
with _lock:
return copy.deepcopy(_job)
def is_running() -> bool:
with _lock:
return _job["state"] == "running"
def _claim(kind: str, stages: list, results: list) -> None:
with _lock:
if _job["state"] == "running":
raise Busy(f"A {_job['kind']} is already running")
_job.update(kind=kind, state="running", stages=[{"name": n, "state": "pending"} for n in stages],
results=results, warnings=[], started_at=_now(), finished_at=None, message=None,
relogin=False)
def _stage(name: str, state: str = "running") -> None:
with _lock:
for s in _job["stages"]:
if s["name"] == name:
s["state"] = state
elif s["state"] == "running" and state == "running":
s["state"] = "done"
def _warn(text: str) -> None:
logger.warning(f"[BACKUP] {text}")
with _lock:
_job["warnings"].append(text)
def _finish(state: str, message: str, relogin: bool = False) -> None:
with _lock:
for s in _job["stages"]:
if s["state"] == "running":
s["state"] = "done" if state in ("done", "partial") else "error"
_job.update(state=state, message=message, finished_at=_now(), relogin=relogin)
def _result(index: int, **fields) -> None:
with _lock:
_job["results"][index].update(fields)
# --- destinations --------------------------------------------------------------------------
def build_dest(rec: dict) -> destinations.Destination:
if not rec.get("secrets_ok", True):
raise BackupError("Stored secrets of this destination cannot be decrypted "
"(the JWT secret changed). Edit the destination and enter them again.")
return destinations.build_destination(rec["type"], rec["params"], rec["secrets"])
def test_destination(dest_id: int) -> dict:
rec = store.get_destination(dest_id, with_secrets=True)
if not rec:
raise Invalid("Destination not found")
try:
message = build_dest(rec).test()
except destinations.NeedsTrust as e:
# SFTP: the host key is not pinned (or changed): show it, the administrator decides
store.set_last_result(dest_id, False, str(e))
return {"ok": False, "message": str(e), "needs_trust": True, "fingerprint": e.fingerprint,
"key_type": e.key_type, "key_changed": e.changed}
except BackupError as e:
store.set_last_result(dest_id, False, str(e))
return {"ok": False, "message": str(e)}
except Exception as e: # a driver error that is not mapped: report it, never crash the API
logger.exception("Destination test failed")
message = f"{type(e).__name__}: {str(e)[:200]}"
store.set_last_result(dest_id, False, message)
return {"ok": False, "message": message}
store.set_last_result(dest_id, True, message)
return {"ok": True, "message": message}
def effective_server_name() -> tuple:
"""(name, source): the server name of the settings, else the public address from the VPN
settings, else the host name. The name goes into the package names."""
name = store.get_server_name()
if name and package.SERVER_NAME_RE.match(name):
return name, "setting"
try:
conn = sqlite3.connect(f"file:{profiler_db_path()}?mode=ro", uri=True, timeout=5)
try:
row = conn.execute("SELECT public_ip FROM system_settings LIMIT 1").fetchone()
finally:
conn.close()
name = package.sanitize_name(row[0]) if row and row[0] else ""
if name:
return name, "public_ip"
except sqlite3.Error:
pass # no settings yet (or the column is absent): fall through
return package.host_name(), "hostname"
def trust_host_key(dest_id: int, fingerprint: str) -> dict:
"""Pin the host key the server shows now, if it is the one the administrator saw (`fingerprint`)."""
rec = store.get_destination(dest_id, with_secrets=True)
if not rec:
raise Invalid("Destination not found")
cls = destinations.DESTINATION_TYPES.get(rec["type"])
if not cls or not cls.PIN_PARAMS:
raise Invalid("This destination type has no host key")
if not destinations.FINGERPRINT_RE.match(fingerprint or ""):
raise Invalid("Invalid fingerprint")
shown, key_type = build_dest(rec).fetch_host_key()
if shown != fingerprint:
raise Invalid("The server now shows a different host key than the one you saw: run Test again")
params = dict(rec["params"], host_key=shown, host_key_type=key_type)
store.save_destination(rec["id"], rec["name"], rec["type"], rec["enabled"], rec["retention_count"],
params, rec["secrets"])
store.set_last_result(rec["id"], True, f"Host key {shown} trusted")
return store.get_destination(rec["id"])
def list_packages(dest_id: int) -> list:
"""Packages of our name pattern in the destination, newest first."""
rec = store.get_destination(dest_id, with_secrets=True)
if not rec:
raise Invalid("Destination not found")
items = []
for obj in build_dest(rec).list():
meta = package.parse_package_name(obj["name"])
if meta:
items.append({"name": obj["name"], "server_name": meta["host"], "created_at": meta["created_at"],
"encrypted": meta["encrypted"], "size": obj["size"],
"_key": (meta["stamp"], meta["seq"], obj["name"])})
items.sort(key=lambda i: i["_key"], reverse=True)
for i in items:
del i["_key"]
return items
def put_unique(dest: destinations.Destination, path: str, base_name: str) -> str:
"""Store the package under base_name, or under -2, -3 ... when the destination already has a
package of that second. Returns the name used."""
meta = package.parse_package_name(base_name)
name = package.unique_package_name(meta["host"], meta["stamp"], meta["encrypted"],
(o["name"] for o in dest.list()))
dest.put(path, name)
return name
def rotate(dest: destinations.Destination, keep: int, keep_name: str, server_name: str) -> int:
"""Delete the oldest packages of this server name beyond `keep` (never keep_name). Packages
with another name in the same folder (other servers, or made under an earlier name or by host
name) are not ours to delete. Returns the number removed."""
mine = []
for obj in dest.list():
meta = package.parse_package_name(obj["name"])
if meta and meta["host"] == server_name:
mine.append(((meta["stamp"], meta["seq"]), obj["name"]))
mine.sort(reverse=True)
removed = 0
for _key, name in mine[max(keep, 1):]:
if name != keep_name:
dest.delete(name)
removed += 1
return removed
# --- package creation ----------------------------------------------------------------------
def create_package(work: str, passphrase: Optional[str]):
"""Build (and encrypt, if a passphrase is given) a package in `work`. Returns (path, name, manifest);
name is the plain name, a destination may add -2, -3 when that second is taken (put_unique)."""
stamp = package.utc_stamp()
server_name, _source = effective_server_name()
plain = os.path.join(work, "package.tar.gz")
manifest = package.build_package(plain, work, profiler_db_path(), monitor_db_path(),
pki_dir(), client_dir(), runtime(), server_name)
path = plain
if passphrase:
path = os.path.join(work, "package.enc")
crypto.encrypt_file(plain, path, passphrase)
os.remove(plain)
return path, package.package_name(server_name, stamp, bool(passphrase)), manifest
# --- backup job ----------------------------------------------------------------------------
def start_backup(destination_ids: Optional[list] = None) -> None:
all_dests = store.list_destinations(with_secrets=True)
if destination_ids is None:
selected = [d for d in all_dests if d["enabled"]]
else:
by_id = {d["id"]: d for d in all_dests}
selected = []
for i in dict.fromkeys(destination_ids):
if i not in by_id:
raise Invalid(f"Destination {i} not found")
if not by_id[i]["enabled"]:
raise Invalid(f"Destination '{by_id[i]['name']}' is disabled")
selected.append(by_id[i])
if not selected:
raise Invalid("No destinations selected: add and enable a destination first")
if any(d["type"] in destinations.REMOTE_TYPES for d in selected) and not store.has_passphrase():
raise Invalid("A passphrase is required for remote destinations: set the encryption passphrase first")
passphrase = store.get_passphrase()
stages = ["package"] + (["encrypt"] if passphrase else []) + ["upload"]
results = [{"destination_id": d["id"], "name": d["name"], "type": d["type"], "state": "pending",
"message": None, "package": None} for d in selected]
_claim("backup", stages, results)
hist_id = store.history_start("backup")
threading.Thread(target=_backup_worker, args=(selected, passphrase, hist_id), daemon=True).start()
def _backup_worker(selected: list, passphrase: Optional[str], hist_id: int) -> None:
work = None
try:
work = _work_dir()
_stage("package")
# create_package encrypts too: show the second stage once the tar is written
path, name, manifest = create_package(work, passphrase)
if passphrase:
_stage("encrypt", "done")
_stage("upload")
size = os.path.getsize(path)
server_name = manifest["server_name"]
for i, rec in enumerate(selected):
_result(i, state="running")
try:
dest = build_dest(rec)
stored = put_unique(dest, path, name)
note = f"{stored} ({size // 1024} KB)"
try:
removed = rotate(dest, rec["retention_count"], stored, server_name)
if removed:
note += f", {removed} old removed"
except Exception as e:
logger.warning(f"[BACKUP] rotation failed for '{rec['name']}': {type(e).__name__}")
note += f", rotation failed: {str(e)[:150]}"
_result(i, state="ok", message=note, package=stored)
store.set_last_result(rec["id"], True, note)
except Exception as e:
msg = str(e)[:300] if isinstance(e, BackupError) else f"{type(e).__name__}: {str(e)[:200]}"
logger.error(f"[BACKUP] destination '{rec['name']}' failed: {msg}")
_result(i, state="error", message=msg)
store.set_last_result(rec["id"], False, msg)
with _lock:
results = copy.deepcopy(_job["results"])
ok = sum(1 for r in results if r["state"] == "ok")
if ok == len(results):
state, message = "done", f"Backup stored in {ok} destination(s)"
elif ok:
state, message = "partial", f"Backup stored in {ok} of {len(results)} destinations"
else:
state, message = "error", "Backup failed in every destination"
_finish(state, message)
store.history_finish(hist_id, state, message, results)
except Exception as e:
logger.exception("Backup failed")
message = str(e)[:500] if isinstance(e, BackupError) else f"Backup failed: {type(e).__name__}: {str(e)[:300]}"
for i in range(len(selected)):
_result(i, state="skipped", message="Package was not created")
_finish("error", message)
store.history_finish(hist_id, "error", message, [])
finally:
if work:
shutil.rmtree(work, ignore_errors=True)
# --- restore -------------------------------------------------------------------------------
RESTORE_STAGES = ["download", "decrypt", "verify", "prepare", "safety_backup", "stop_openvpn",
"replace", "finalize"]
def start_restore(destination_id: int, package_name: str, passphrase: Optional[str]) -> None:
rec = store.get_destination(destination_id, with_secrets=True)
if not rec:
raise Invalid("Destination not found")
meta = package.parse_package_name(package_name)
if not meta:
raise Invalid("Invalid package name")
if meta["encrypted"] and not passphrase:
raise Invalid("The package is encrypted: enter its passphrase")
if pki.is_init_running():
raise Busy("PKI initialization is running")
if is_running():
raise Busy(f"A {status()['kind']} is already running")
# Only names from the destination's listing are restored
if package_name not in {o["name"] for o in build_dest(rec).list()}:
raise Invalid("The package is not in the destination")
stages = [s for s in RESTORE_STAGES if s != "decrypt" or meta["encrypted"]]
_claim("restore", stages, [{"destination_id": rec["id"], "name": rec["name"], "type": rec["type"],
"state": "running", "message": None, "package": package_name}])
pki.set_restore_running(True)
hist_id = store.history_start("restore")
threading.Thread(target=_restore_worker, args=(rec, package_name, meta["encrypted"], passphrase, hist_id),
daemon=True).start()
def core_dir() -> Optional[str]:
"""Directory of the monitoring component (it owns the migrations of openvpn_monitor.db):
migrate.py with migrations.py and db.py (standard library only).
OVPMON_CORE_DIR (profiler image: /opt/core), else APP_CORE next to APP_PROFILER (system
services, all-in-one container). None for an old profiler image without that directory."""
env = os.environ.get("OVPMON_CORE_DIR", "").strip()
if not env:
code = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
env = os.path.join(os.path.dirname(code), "APP_CORE")
if all(os.path.isfile(os.path.join(env, f)) for f in ("migrate.py", "migrations.py", "db.py")):
return env
return None
def _migrate_monitor(db_file: str) -> None:
"""Bring the monitoring database of the package up to this release's schema.
The migrations live in the monitoring component, which this process cannot import (separate
virtualenv). Its own migrate.py runs on the staged copy with the interpreter of APP_CORE/venv
(or this one: the code uses the standard library only). Without the code on disk (an old
profiler image) only a package with exactly the schema of the running monitoring database is
accepted: the monitoring services would otherwise read an unmigrated database."""
version = package.schema_version(db_file)
core = core_dir()
if core:
venv_python = os.path.join(core, "venv", "bin", "python")
python = venv_python if os.path.isfile(venv_python) else sys.executable
try:
r = subprocess.run([python, "migrate.py", "--db", db_file], cwd=core, capture_output=True,
text=True, timeout=300)
except (OSError, subprocess.TimeoutExpired) as e:
raise BackupError(f"Cannot run the monitoring database migration: {e}") from e
if r.returncode != 0:
lines = [ln for ln in (r.stderr or r.stdout or "").strip().splitlines() if ln.strip()]
raise BackupError("The monitoring database of the package cannot be migrated: "
+ (lines[-1][:300] if lines else f"exit code {r.returncode}"))
return
live = package.schema_version(monitor_db_path())
if not live:
raise BackupError("The monitoring database schema cannot be checked: the monitoring component "
"is not available to this service and its database is not initialized")
if version != live:
which = "newer" if (version or 0) > live else "older"
raise BackupError(
f"The package has a {which} monitoring database schema ({version}) than this installation "
f"({live}). The migration code of the monitoring component (OVPMON_CORE_DIR) is not "
f"available to this service. Rebuild the profiler image or restore on the same release.")
def _prepare_staged(extracted: str, manifest: dict) -> None:
"""Checks and migrations on the unpacked copies: nothing of the running system is touched yet."""
prof = os.path.join(extracted, package.DB_PROFILER)
mon = os.path.join(extracted, package.DB_MONITOR)
for path in (prof, mon):
if not package.integrity_ok(path):
raise BackupError(f"{os.path.basename(path)} in the package failed the integrity check")
version, latest = package.schema_version(prof), migrations.latest_version()
if version is None or version > latest:
raise BackupError(f"The package was made by a newer release (profiler database schema {version}, "
f"this release knows up to {latest}). Update this installation first.")
try:
migrations.run(prof)
except migrations.MigrationError as e:
raise BackupError(f"The profiler database of the package cannot be migrated: {str(e)[:300]}") from e
_migrate_monitor(mon)
def _safety_backup() -> str:
"""Package of the current state in the local pre-restore folder. Raises when it cannot be made."""
try:
passphrase = store.get_passphrase()
except BackupError:
passphrase = None
_warn("The safety copy is not encrypted: the stored passphrase cannot be decrypted")
work = _work_dir()
try:
path, name, manifest = create_package(work, passphrase)
dest = destinations.LocalDestination({"folder": PRE_RESTORE_FOLDER}, {})
name = put_unique(dest, path, name)
try:
rotate(dest, PRE_RESTORE_KEEP, name, manifest["server_name"])
except Exception as e:
logger.warning(f"[BACKUP] pre-restore rotation failed: {type(e).__name__}")
return name
finally:
shutil.rmtree(work, ignore_errors=True)
def _replace_db(target: str, new_file: str, tag: str, undo: list) -> None:
"""Atomic replacement of a database file. The old file (and its -wal/-shm) is kept under a
.old-<tag> name until the whole restore succeeded."""
tmp = f"{target}.restore-{tag}"
old = f"{target}.old-{tag}"
shutil.copyfile(new_file, tmp)
os.chmod(tmp, (os.stat(target).st_mode & 0o777) if os.path.exists(target) else 0o600)
if os.path.exists(target):
try:
os.link(target, old)
except OSError:
shutil.copy2(target, old)
undo.append(("db", target, old))
# A leftover journal of the old database must never be applied to the new file
for suffix in ("-wal", "-shm"):
if os.path.exists(target + suffix):
os.replace(target + suffix, old + suffix)
else:
undo.append(("db_new", target, old))
os.replace(tmp, target)
def _swap_dir(target: str, extracted: str, tag: str, undo: list) -> None:
"""Replace the CONTENT of a directory (the directory itself may be a volume mount point):
old entries move into .restore-old-<tag>, new ones come from .restore-new-<tag>."""
os.makedirs(target, mode=0o700, exist_ok=True)
staged = os.path.join(target, f".restore-new-{tag}")
old = os.path.join(target, f".restore-old-{tag}")
if os.path.isdir(extracted):
shutil.copytree(extracted, staged)
else:
os.mkdir(staged, 0o700)
os.mkdir(old, 0o700)
undo.append(("dir", target, old, staged))
for name in os.listdir(target):
if not name.startswith(".restore-"):
os.replace(os.path.join(target, name), os.path.join(old, name))
for name in os.listdir(staged):
os.replace(os.path.join(staged, name), os.path.join(target, name))
os.rmdir(staged)
def _remove(path: str) -> None:
if os.path.isdir(path) and not os.path.islink(path):
shutil.rmtree(path, ignore_errors=True)
elif os.path.lexists(path):
os.remove(path)
def _rollback(undo: list) -> None:
for item in reversed(undo):
try:
if item[0] == "db":
_, target, old = item
for suffix in ("", "-wal", "-shm"):
if os.path.exists(old + suffix):
os.replace(old + suffix, target + suffix)
elif item[0] == "db_new":
_remove(item[1])
else:
_, target, old, staged = item
for name in os.listdir(target):
if not name.startswith(".restore-"):
_remove(os.path.join(target, name))
for name in os.listdir(old):
os.replace(os.path.join(old, name), os.path.join(target, name))
shutil.rmtree(old, ignore_errors=True)
shutil.rmtree(staged, ignore_errors=True)
except Exception:
logger.exception("[BACKUP] rollback step failed")
def _commit(undo: list) -> None:
for item in undo:
if item[0] == "db":
for suffix in ("", "-wal", "-shm"):
if os.path.lexists(item[2] + suffix):
_remove(item[2] + suffix)
elif item[0] == "dir":
shutil.rmtree(item[2], ignore_errors=True)
shutil.rmtree(item[3], ignore_errors=True)
def _apply_server_config() -> bool:
"""Regenerate server.conf and publish the CRL through the same code as POST /server/configure."""
from fastapi import HTTPException
from routers import server as server_router
db = SessionLocal()
try:
server_router.configure_server(db)
return True
except HTTPException as e:
_warn(f"server.conf was not regenerated: {e.detail}")
except Exception as e:
_warn(f"server.conf was not regenerated: {type(e).__name__}: {str(e)[:200]}")
finally:
db.close()
return False
def _start_openvpn(was_running: bool) -> None:
if not was_running:
return
res = process.control_service("start")
if res.get("status") == "error":
_warn(f"OpenVPN was running before the restore, but could not be started: {res.get('message')}")
def _restore_worker(rec: dict, name: str, encrypted: bool, passphrase: Optional[str], hist_id: int) -> None:
work = None
undo = []
was_running = False
stopped = False
committed = False
try:
work = _work_dir()
downloaded = os.path.join(work, "downloaded")
_stage("download")
build_dest(rec).get(name, downloaded)
archive = downloaded
if encrypted:
_stage("decrypt")
archive = os.path.join(work, "package.tar.gz")
crypto.decrypt_file(downloaded, archive, passphrase)
os.remove(downloaded)
elif crypto.is_encrypted(downloaded):
raise BackupError("The package is encrypted but its name says it is not")
_stage("verify")
extracted = os.path.join(work, "extracted")
manifest = package.safe_extract(archive, extracted)
os.remove(archive)
_stage("prepare")
_prepare_staged(extracted, manifest)
_stage("safety_backup")
safety = _safety_backup()
_stage("stop_openvpn")
was_running = process.get_process_stats().get("status") == "running"
if was_running:
res = process.control_service("stop")
if res.get("status") == "error":
raise BackupError(f"Cannot stop OpenVPN: {res.get('message')}")
stopped = True
_stage("replace")
tag = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
try:
sa_engine.dispose()
_swap_dir(pki_dir(), os.path.join(extracted, "pki"), tag, undo)
_swap_dir(client_dir(), os.path.join(extracted, "client-config"), tag, undo)
_replace_db(monitor_db_path(), os.path.join(extracted, package.DB_MONITOR), tag, undo)
_replace_db(profiler_db_path(), os.path.join(extracted, package.DB_PROFILER), tag, undo)
marker = pki._marker_path()
if os.path.exists(marker):
os.remove(marker)
except Exception:
logger.exception("[BACKUP] replacement failed, rolling back")
_rollback(undo)
sa_engine.dispose()
raise
_commit(undo)
committed = True
sa_engine.dispose()
_stage("finalize")
configured = _apply_server_config()
if configured:
_start_openvpn(was_running)
elif was_running:
_warn("OpenVPN was running before the restore and was not started")
message = f"Restored from {name}. The previous state is saved as {PRE_RESTORE_FOLDER}/{safety}"
_result(0, state="ok", message=message)
_finish("done", message, relogin=True)
store.history_finish(hist_id, "done", message, status()["results"])
except Exception as e:
logger.exception("Restore failed")
message = str(e)[:500] if isinstance(e, BackupError) else f"Restore failed: {type(e).__name__}: {str(e)[:300]}"
if committed:
message += ". The data was restored, but the final steps failed (see the log)."
else:
message += ". Nothing was changed." if not undo else ". The previous state was put back."
if stopped:
try:
_start_openvpn(True)
except Exception:
logger.exception("[BACKUP] OpenVPN start after a failed restore")
_result(0, state="error", message=message)
_finish("error", message)
store.history_finish(hist_id, "error", message, status()["results"])
finally:
pki.set_restore_running(False)
if work:
shutil.rmtree(work, ignore_errors=True)
+335
View File
@@ -0,0 +1,335 @@
"""Backup package: naming, building (snapshots), reading and safe extraction.
A package is a tar.gz named ovpmon-backup_<server-name>_<YYYYMMDDTHHMMSS>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<host>[A-Za-z0-9][A-Za-z0-9.-]{0,62})_(?P<ts>\d{8}T\d{6}Z)(?:-(?P<seq>\d{1,3}))?"
r"\.ovpbak(?P<enc>\.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
+252
View File
@@ -0,0 +1,252 @@
"""Settings, destinations and history of the backup feature.
A separate SQLite file (ovpmon_backup.db) next to the profiler database. A restore replaces
ovpn_profiler.db and openvpn_monitor.db, but never this file, so the destinations survive it and
never travel inside a package. The schema is created at service start (own version table, the
migrations of the two application databases are not involved).
Secrets (destination keys, the package passphrase) are encrypted at rest with a key derived
(HKDF-SHA256) from the JWT signing key. They are never returned by the API and never logged.
If the JWT key changes they cannot be decrypted any more and have to be entered again.
"""
import base64
import json
import logging
import os
import sqlite3
import threading
from contextlib import contextmanager
from datetime import datetime, timezone
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from . import BackupError
logger = logging.getLogger(__name__)
SCHEMA_VERSION = 1
DEFAULT_RETENTION = 14
HISTORY_KEEP = 100
MASK = "********"
_lock = threading.Lock()
def db_file() -> str:
from database import db_path
return os.path.join(os.path.dirname(os.path.abspath(db_path)), "ovpmon_backup.db")
def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
@contextmanager
def _conn():
conn = sqlite3.connect(db_file(), timeout=30)
conn.row_factory = sqlite3.Row
try:
yield conn
conn.commit()
except BaseException:
conn.rollback()
raise
finally:
conn.close()
def init() -> None:
"""Create the schema (idempotent). Called at service start."""
path = db_file()
new = not os.path.exists(path)
with _lock, _conn() as c:
c.execute("CREATE TABLE IF NOT EXISTS backup_schema (version INTEGER NOT NULL)")
c.execute("CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)")
c.execute("""CREATE TABLE IF NOT EXISTS destinations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
type TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
retention_count INTEGER NOT NULL DEFAULT 14,
params TEXT NOT NULL DEFAULT '{}',
secrets_enc TEXT NOT NULL DEFAULT '',
last_status TEXT,
last_message TEXT,
last_at TEXT,
created_at TEXT NOT NULL)""")
c.execute("""CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL,
state TEXT NOT NULL,
started_at TEXT NOT NULL,
finished_at TEXT,
message TEXT,
results TEXT NOT NULL DEFAULT '[]')""")
if not c.execute("SELECT 1 FROM backup_schema").fetchone():
c.execute("INSERT INTO backup_schema (version) VALUES (?)", (SCHEMA_VERSION,))
# A job that was running when the service stopped did not finish
c.execute("UPDATE history SET state='interrupted', finished_at=? WHERE state='running'", (_now(),))
if new:
os.chmod(path, 0o600)
# --- secrets -------------------------------------------------------------------------------
def _fernet() -> Fernet:
from utils.auth import SECRET_KEY
key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None,
info=b"ovpmon-backup-secrets-v1").derive(SECRET_KEY.encode("utf-8"))
return Fernet(base64.urlsafe_b64encode(key))
def encrypt_text(text: str) -> str:
return _fernet().encrypt(text.encode("utf-8")).decode("ascii")
def decrypt_text(token: str) -> str:
try:
return _fernet().decrypt(token.encode("ascii")).decode("utf-8")
except (InvalidToken, ValueError):
raise BackupError("Stored secrets cannot be decrypted (the JWT secret changed). "
"Enter them again.") from None
# --- settings ------------------------------------------------------------------------------
def _get_setting(key):
with _conn() as c:
row = c.execute("SELECT value FROM settings WHERE key=?", (key,)).fetchone()
return row["value"] if row else None
def _set_setting(key, value):
with _lock, _conn() as c:
if value is None:
c.execute("DELETE FROM settings WHERE key=?", (key,))
else:
c.execute("INSERT INTO settings (key, value) VALUES (?, ?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value", (key, value))
def has_passphrase() -> bool:
return bool(_get_setting("passphrase_enc"))
def get_passphrase():
"""The package passphrase, or None when none is set. Raises BackupError if it cannot be decrypted."""
token = _get_setting("passphrase_enc")
return decrypt_text(token) if token else None
def set_passphrase(value) -> None:
_set_setting("passphrase_enc", encrypt_text(value) if value else None)
def default_retention() -> int:
try:
return int(_get_setting("default_retention") or DEFAULT_RETENTION)
except ValueError:
return DEFAULT_RETENTION
def set_default_retention(n: int) -> None:
_set_setting("default_retention", str(int(n)))
def get_server_name() -> str:
"""The server name set by the administrator ('' when none). Lives here, not in the profiler
database: a restore replaces that one, and the name belongs to this server."""
return _get_setting("server_name") or ""
def set_server_name(value) -> None:
_set_setting("server_name", value or None)
# --- destinations --------------------------------------------------------------------------
def _row_to_dest(row, with_secrets=False):
d = {"id": row["id"], "name": row["name"], "type": row["type"], "enabled": bool(row["enabled"]),
"retention_count": row["retention_count"], "params": json.loads(row["params"]),
"last_status": row["last_status"], "last_message": row["last_message"], "last_at": row["last_at"]}
secrets, secrets_ok = {}, True
if row["secrets_enc"]:
try:
secrets = json.loads(decrypt_text(row["secrets_enc"]))
except BackupError:
secrets_ok = False
d["secrets_ok"] = secrets_ok
if with_secrets:
d["secrets"] = secrets
else:
# Masked: the UI only learns which secrets are set
d["secrets"] = {k: MASK for k, v in secrets.items() if v}
return d
def list_destinations(with_secrets=False):
with _conn() as c:
rows = c.execute("SELECT * FROM destinations ORDER BY id").fetchall()
return [_row_to_dest(r, with_secrets) for r in rows]
def get_destination(dest_id: int, with_secrets=False):
with _conn() as c:
row = c.execute("SELECT * FROM destinations WHERE id=?", (dest_id,)).fetchone()
return _row_to_dest(row, with_secrets) if row else None
def save_destination(dest_id, name, dtype, enabled, retention_count, params, secrets) -> int:
"""Insert (dest_id None) or update. Raises BackupError on a duplicate name."""
enc = encrypt_text(json.dumps(secrets)) if secrets else ""
try:
with _lock, _conn() as c:
if dest_id is None:
cur = c.execute(
"INSERT INTO destinations (name, type, enabled, retention_count, params, secrets_enc, created_at) "
"VALUES (?, ?, ?, ?, ?, ?, ?)",
(name, dtype, int(enabled), retention_count, json.dumps(params), enc, _now()))
return cur.lastrowid
c.execute("UPDATE destinations SET name=?, type=?, enabled=?, retention_count=?, params=?, "
"secrets_enc=? WHERE id=?",
(name, dtype, int(enabled), retention_count, json.dumps(params), enc, dest_id))
return dest_id
except sqlite3.IntegrityError:
raise BackupError(f"A destination named '{name}' already exists") from None
def delete_destination(dest_id: int) -> bool:
with _lock, _conn() as c:
return c.execute("DELETE FROM destinations WHERE id=?", (dest_id,)).rowcount > 0
def set_last_result(dest_id: int, ok: bool, message: str) -> None:
with _lock, _conn() as c:
c.execute("UPDATE destinations SET last_status=?, last_message=?, last_at=? WHERE id=?",
("ok" if ok else "error", (message or "")[:500], _now(), dest_id))
# --- history -------------------------------------------------------------------------------
def history_start(kind: str) -> int:
with _lock, _conn() as c:
return c.execute("INSERT INTO history (kind, state, started_at) VALUES (?, 'running', ?)",
(kind, _now())).lastrowid
def history_finish(hist_id: int, state: str, message: str, results: list) -> None:
with _lock, _conn() as c:
c.execute("UPDATE history SET state=?, finished_at=?, message=?, results=? WHERE id=?",
(state, _now(), (message or "")[:1000], json.dumps(results), hist_id))
c.execute("DELETE FROM history WHERE id NOT IN (SELECT id FROM history ORDER BY id DESC LIMIT ?)",
(HISTORY_KEEP,))
def history_list(limit: int = 20) -> list:
with _conn() as c:
rows = c.execute("SELECT * FROM history ORDER BY id DESC LIMIT ?", (limit,)).fetchall()
return [{"id": r["id"], "kind": r["kind"], "state": r["state"], "started_at": r["started_at"],
"finished_at": r["finished_at"], "message": r["message"], "results": json.loads(r["results"])}
for r in rows]
+15
View File
@@ -144,6 +144,19 @@ def is_init_running() -> bool:
with _init_lock:
return _init_job["state"] == "running"
# A backup restore replaces the PKI, the profile files and the databases: while it runs,
# everything that changes them is refused (set by services/backup/engine.py)
_restore_running = False
def set_restore_running(value: bool):
global _restore_running
_restore_running = bool(value)
def is_restore_running() -> bool:
return _restore_running
RESTORE_RUNNING_MSG = "A backup restore is running"
class PkiNotReady(Exception):
"""An operation needs keys that are not there (PKI absent, init running or server files missing)."""
@@ -243,6 +256,8 @@ def start_init_async(db: Session):
with _init_lock:
if _init_job["state"] == "running":
raise InitConflict("PKI initialization is already running")
if is_restore_running():
raise InitConflict(RESTORE_RUNNING_MSG)
if is_initialized():
raise InitConflict("PKI is already initialized")
# Here the PKI is absent, has no CA, or carries the marker of an interrupted run:
+404
View File
@@ -0,0 +1,404 @@
import io
import os
import sqlite3
import tarfile
import tempfile
import types
import pytest
# The DB path must be set before database.py is imported (via main)
_tmp = tempfile.TemporaryDirectory()
os.environ.setdefault("OVPMON_PROFILER_DB_PATH", os.path.join(_tmp.name, "test.db"))
from fastapi.testclient import TestClient
from main import app
import migrations
from services import pki, process
from services.backup import BackupError, crypto, destinations, engine, package, store
from utils.auth import verify_token
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
client = TestClient(app)
PASS = "correct horse battery"
class InlineThread:
"""Runs the job in the calling thread: the tests need no polling."""
def __init__(self, target, args=(), daemon=None):
self.target, self.args = target, args
def start(self):
self.target(*self.args)
@pytest.fixture
def env(tmp_path, monkeypatch):
"""A complete data layout in a temporary directory, nothing of the real system is touched."""
data = tmp_path / "data"
data.mkdir()
prof, mon = str(data / "ovpn_profiler.db"), str(data / "openvpn_monitor.db")
migrations.run(prof)
conn = sqlite3.connect(mon)
conn.executescript("CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT);"
"INSERT INTO schema_migrations VALUES (2, 'x', 'now');"
"CREATE TABLE users (name TEXT); INSERT INTO users VALUES ('admin');")
conn.commit()
conn.close()
pki_dir, client_dir = tmp_path / "easy-rsa" / "pki", tmp_path / "client-config"
(pki_dir / "private").mkdir(parents=True)
(pki_dir / "ca.crt").write_text("CA")
(pki_dir / "private" / "ca.key").write_text("SECRET")
os.chmod(pki_dir / "private" / "ca.key", 0o600)
client_dir.mkdir()
(client_dir / "alice.ovpn").write_text("client config")
monkeypatch.setenv("OVPMON_BACKUP_LOCAL_ROOT", str(tmp_path / "backups"))
monkeypatch.setattr(engine, "profiler_db_path", lambda: prof)
monkeypatch.setattr(engine, "monitor_db_path", lambda: mon)
monkeypatch.setattr(engine, "client_dir", lambda: str(client_dir))
monkeypatch.setattr(engine, "core_dir", lambda: None) # the schemas are equal: no migration needed
monkeypatch.setattr(pki, "PKI_DIR", str(pki_dir))
monkeypatch.setattr(process, "get_process_stats", lambda: {"status": "stopped"})
monkeypatch.setattr(engine, "threading", types.SimpleNamespace(Thread=InlineThread))
monkeypatch.setattr(store, "db_file", lambda: str(tmp_path / "ovpmon_backup.db"))
store.init()
return types.SimpleNamespace(root=tmp_path, prof=prof, mon=mon, pki=pki_dir, clients=client_dir)
def test_package_round_trip_and_wrong_passphrase(env, tmp_path):
work = tmp_path / "w"
work.mkdir()
path, name, manifest = engine.create_package(str(work), PASS)
assert name.endswith(".ovpbak.enc") and package.parse_package_name(name)["encrypted"]
assert crypto.is_encrypted(path) and b"SECRET" not in open(path, "rb").read()
assert manifest["schema"]["monitor"] == 2 and "pki/private/ca.key" in manifest["files"]
with pytest.raises(crypto.WrongPassphrase):
crypto.decrypt_file(path, str(tmp_path / "bad.tar.gz"), "wrong passphrase")
crypto.decrypt_file(path, str(tmp_path / "ok.tar.gz"), PASS)
out = tmp_path / "out"
package.safe_extract(str(tmp_path / "ok.tar.gz"), str(out))
assert (out / "pki" / "ca.crt").read_text() == "CA"
assert (out / "pki" / "private" / "ca.key").read_text() == "SECRET"
assert oct(os.stat(out / "pki" / "private" / "ca.key").st_mode & 0o777) == "0o600"
assert (out / "client-config" / "alice.ovpn").read_text() == "client config"
assert sqlite3.connect(out / "db" / "openvpn_monitor.db").execute("SELECT name FROM users").fetchone() == ("admin",)
assert package.integrity_ok(str(out / "db" / "ovpn_profiler.db"))
def _tar(path, members):
with tarfile.open(path, "w:gz") as tar:
for info, data in members:
tar.addfile(info, io.BytesIO(data) if data is not None else None)
def test_safe_extraction_and_newer_schema(env, tmp_path):
def reg(name, data=b"x"):
info = tarfile.TarInfo(name)
info.size = len(data)
return info, data
link = tarfile.TarInfo("pki/link")
link.type, link.linkname = tarfile.SYMTYPE, "/etc/passwd"
for i, members in enumerate([[reg("../evil")], [reg("/abs/evil")], [reg("pki/../../evil")],
[(link, None)], [reg("other/file")], [reg("db/extra.db")]]):
bad = str(tmp_path / f"bad{i}.tar.gz")
_tar(bad, members)
with pytest.raises(BackupError):
package.safe_extract(bad, str(tmp_path / f"out{i}"))
assert not (tmp_path / "evil").exists()
# A valid package from a newer release is refused before anything is touched
work = tmp_path / "w"
work.mkdir()
path, _name, _ = engine.create_package(str(work), None)
out = tmp_path / "ok"
manifest = package.safe_extract(path, str(out))
conn = sqlite3.connect(out / "db" / "ovpn_profiler.db")
conn.execute("INSERT INTO schema_migrations VALUES (999, 'future', 'now')")
conn.commit()
conn.close()
with pytest.raises(BackupError, match="newer release"):
engine._prepare_staged(str(out), manifest)
# An unknown format version is refused too
import json
manifest["format_version"] = 99
(out / "manifest.json").write_text(json.dumps(manifest))
with pytest.raises(BackupError, match="Unknown package format"):
package.verify_extracted(str(out))
class FailingDestination(destinations.Destination):
type = "stub"
label = "Stub"
def put(self, local_path, name):
raise destinations.DestinationError("disk on fire")
def list(self):
return []
def test_multi_destination_backup_rotation_and_restore(env, tmp_path, monkeypatch):
monkeypatch.setitem(destinations.DESTINATION_TYPES, "stub", FailingDestination)
good = store.save_destination(None, "local-good", "local", True, 2, {"folder": "daily"}, {})
bad = store.save_destination(None, "broken", "stub", True, 14, {}, {})
stamps = iter(f"20261007T1000{i:02d}Z" for i in range(10))
monkeypatch.setattr(package, "utc_stamp", lambda now=None: next(stamps))
for _ in range(3):
engine.start_backup(None)
job = engine.status()
assert job["state"] == "partial" # one failed, the other still got the package
by_name = {r["name"]: r for r in job["results"]}
assert by_name["local-good"]["state"] == "ok" and by_name["broken"]["state"] == "error"
assert "disk on fire" in by_name["broken"]["message"]
assert store.get_destination(bad)["last_status"] == "error"
names = sorted(p["name"] for p in engine.list_packages(good))
assert len(names) == 2 and names[0].endswith("100001Z.ovpbak") # oldest of 3 rotated away
# Restore the newest package after the live data was damaged
newest = engine.list_packages(good)[0]["name"]
env.pki.joinpath("ca.crt").write_text("DAMAGED")
(env.clients / "alice.ovpn").unlink()
(env.clients / "stray.ovpn").write_text("not in the package")
sqlite3.connect(env.mon).execute("DROP TABLE users").connection.commit()
engine.start_restore(good, newest, None)
job = engine.status()
assert job["state"] == "done", job["message"]
assert job["relogin"] is True
assert env.pki.joinpath("ca.crt").read_text() == "CA"
assert (env.clients / "alice.ovpn").read_text() == "client config" and not (env.clients / "stray.ovpn").exists()
assert sqlite3.connect(env.mon).execute("SELECT name FROM users").fetchone() == ("admin",)
assert not [p for p in os.listdir(env.pki) if p.startswith(".restore-")]
# the previous state was saved first, locally
pre = destinations.LocalDestination({"folder": "pre-restore"}, {}).list()
assert len(pre) == 1 and package.parse_package_name(pre[0]["name"])
# A package that is not in the listing is not accepted
with pytest.raises(BackupError):
engine.start_restore(good, "ovpmon-backup_x_20200101T000000Z.ovpbak", None)
def test_api_requires_jwt_masks_secrets_and_refuses_remote_without_passphrase(env):
saved = app.dependency_overrides.pop(verify_token)
try:
for method, path in [("get", "/api/backup/settings"), ("put", "/api/backup/settings"),
("get", "/api/backup/destinations"), ("post", "/api/backup/destinations"),
("put", "/api/backup/destinations/1"), ("delete", "/api/backup/destinations/1"),
("post", "/api/backup/destinations/1/test"), ("get", "/api/backup/destinations/1/packages"),
("post", "/api/backup/run"), ("post", "/api/backup/restore"),
("get", "/api/backup/status"), ("get", "/api/backup/history")]:
assert getattr(client, method)(path).status_code == 401, (method, path)
finally:
app.dependency_overrides[verify_token] = saved
s3 = {"name": "bucket", "type": "s3", "params": {"endpoint": "s3.example.com", "bucket": "my-backups"},
"secrets": {"access_key": "AKIAEXAMPLE", "secret_key": "TOPSECRETVALUE"}}
r = client.post("/api/backup/destinations", json=s3)
assert r.status_code == 201
dest = r.json()
assert "TOPSECRETVALUE" not in r.text and "AKIAEXAMPLE" not in r.text
assert dest["secrets"] == {"access_key": store.MASK, "secret_key": store.MASK}
assert "TOPSECRETVALUE" not in client.get("/api/backup/destinations").text
assert "TOPSECRETVALUE" not in open(store.db_file(), "rb").read().decode("latin-1") # encrypted at rest
# Only implemented types; updating with the mask keeps the stored secret
assert client.post("/api/backup/destinations", json={**s3, "name": "x", "type": "smb"}).status_code == 400
s3["secrets"] = {"access_key": store.MASK, "secret_key": ""}
assert client.put(f"/api/backup/destinations/{dest['id']}", json=s3).status_code == 200
assert store.get_destination(dest["id"], with_secrets=True)["secrets"]["secret_key"] == "TOPSECRETVALUE"
# Remote destination without a passphrase: no backup
r = client.post("/api/backup/run", json={})
assert r.status_code == 400 and "passphrase" in r.json()["detail"].lower()
assert client.put("/api/backup/settings", json={"passphrase": "short"}).status_code == 400
r = client.put("/api/backup/settings", json={"passphrase": PASS})
assert r.status_code == 200 and r.json()["encryption_enabled"] is True and PASS not in r.text
assert client.put("/api/backup/settings", json={"clear_passphrase": True}).status_code == 400 # remote needs it
def test_package_name_server_name_fallback_and_unique_names(env, tmp_path, monkeypatch):
import re
import socket
monkeypatch.setattr(socket, "gethostname", lambda: "3f9a1c0b2d44")
assert engine.effective_server_name() == ("3f9a1c0b2d44", "hostname")
conn = sqlite3.connect(env.prof)
conn.execute("INSERT INTO system_settings (id, public_ip) VALUES (1, 'vpn.example.com')")
conn.commit()
conn.close()
assert engine.effective_server_name() == ("vpn.example.com", "public_ip")
# The setting wins, is validated, and can be cleared again
assert client.put("/api/backup/settings", json={"server_name": "bad name!"}).status_code == 400
r = client.put("/api/backup/settings", json={"server_name": "vpn-main"}).json()
assert (r["server_name"], r["effective_server_name"], r["server_name_source"]) == ("vpn-main", "vpn-main", "setting")
assert client.put("/api/backup/settings", json={"server_name": ""}).json()["server_name_source"] == "public_ip"
store.set_server_name("vpn-main")
# Name format, manifest, and -2 / -3 when the same second is taken (nothing is overwritten)
monkeypatch.setattr(package, "utc_stamp", lambda now=None: "20261007T101500Z")
dest = store.save_destination(None, "local-daily", "local", True, 2, {"folder": "daily"}, {})
old = "ovpmon-backup_oldhost_20200101T000000Z.ovpbak" # first-pass name: listed, never rotated
destinations.LocalDestination({"folder": "daily"}, {}).put(str(env.prof), old)
for _ in range(3):
engine.start_backup(None)
assert engine.status()["state"] == "done"
packages = engine.list_packages(dest)
assert [p["name"] for p in packages] == [
"ovpmon-backup_vpn-main_20261007T101500Z-3.ovpbak",
"ovpmon-backup_vpn-main_20261007T101500Z-2.ovpbak", old] # newest first; -1 rotated away
assert packages[0]["server_name"] == "vpn-main" and packages[2]["server_name"] == "oldhost"
work = tmp_path / "w"
work.mkdir()
_path, name, manifest = engine.create_package(str(work), None)
assert name == "ovpmon-backup_vpn-main_20261007T101500Z.ovpbak"
assert manifest["server_name"] == "vpn-main" and manifest["hostname"] == "3f9a1c0b2d44"
assert re.match(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$", manifest["created_at"])
class FakeKey:
blob = b"server-host-key-A"
def asbytes(self):
return self.blob
def get_name(self):
return "ssh-ed25519"
class FakeSFTP:
files, dirs = {}, set()
def get_channel(self):
return types.SimpleNamespace(settimeout=lambda t: None)
def stat(self, path):
if path in self.dirs:
return types.SimpleNamespace(st_mode=0o40700)
raise FileNotFoundError(path)
def mkdir(self, path, mode=0o777):
self.dirs.add(path)
def put(self, local, remote, confirm=True):
self.files[remote] = open(local, "rb").read()
def putfo(self, fh, remote):
self.files[remote] = fh.read()
def posix_rename(self, a, b):
self.files[b] = self.files.pop(a)
def remove(self, path):
del self.files[path]
def listdir_attr(self, directory):
return [types.SimpleNamespace(filename=p.rsplit("/", 1)[-1], st_mode=0o100600, st_size=len(v), st_mtime=1.0)
for p, v in self.files.items() if p.rsplit("/", 1)[0] == directory]
def getfo(self, remote, out):
out.write(self.files[remote])
class FakeSSH:
connects = []
def set_missing_host_key_policy(self, policy):
self.policy = policy
def connect(self, host, **kw):
FakeSSH.connects.append((host, kw.get("password"), kw.get("pkey")))
self.policy.missing_host_key(self, host, FakeKey()) # raises unless the key is the pinned one
def open_sftp(self):
return FakeSFTP()
def close(self):
pass
def test_sftp_ftp_validation_and_host_key_pinning(env, monkeypatch):
import paramiko
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
monkeypatch.setattr(paramiko, "SSHClient", FakeSSH)
FakeSFTP.files, FakeSFTP.dirs = {}, set()
FakeSSH.connects.clear()
sftp, ftp = destinations.SFTPDestination, destinations.FTPDestination
base = {"host": "files.example.com", "port": 22, "username": "backup", "directory": "ovpmon/daily"}
# Parameter and secret rules
for bad in ({"host": "bad host!"}, {"port": 70000}, {"username": ""}, {"directory": "../x"}, {"directory": "/etc"}):
with pytest.raises(ValueError):
sftp.validate({**base, **bad}, {"password": "pw"})
with pytest.raises(ValueError):
sftp.validate(base, {}) # neither password nor key
with pytest.raises(ValueError):
sftp.validate(base, {"password": "pw", "private_key": "x"}) # both
with pytest.raises(ValueError):
sftp.validate(base, {"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\nnot a key\n"})
key = ed25519.Ed25519PrivateKey.generate().private_bytes(
serialization.Encoding.PEM, serialization.PrivateFormat.OpenSSH, serialization.NoEncryption()).decode()
assert sftp.validate(base, {"private_key": key})[1] == {"private_key": key.strip() + "\n"}
with pytest.raises(ValueError):
sftp.validate({**base, "host_key": "SHA256:x"}, {"password": "pw"}) # a pin never comes with the form
fclean, _ = ftp.validate({"host": "ftp.example.com", "username": "u", "directory": "bk"}, {"password": "pw"})
assert (fclean["port"], fclean["tls"], fclean["verify_cert"], fclean["passive"]) == (21, True, True, True)
with pytest.raises(ValueError):
ftp.validate({"host": "ftp.example.com", "username": "u", "directory": "bk"}, {}) # no password
# Not pinned: Test shows the fingerprint, nothing else works, no connection is even opened
body = {"name": "offsite", "type": "sftp", "params": base, "secrets": {"password": "pw"}}
dest = client.post("/api/backup/destinations", json=body).json()
assert dest["secrets"] == {"password": store.MASK} and "host_key" not in dest["params"]
shown = engine.test_destination(dest["id"])
assert shown["ok"] is False and shown["needs_trust"] is True and shown["key_changed"] is False
fp = shown["fingerprint"]
assert fp == destinations._ssh_fingerprint(FakeKey())
rec = store.get_destination(dest["id"], with_secrets=True)
unpinned = destinations.build_destination("sftp", rec["params"], rec["secrets"])
n = len(FakeSSH.connects)
for call in (lambda: unpinned.put(__file__, "ovpmon-backup_x_20260101T000000Z.ovpbak"), unpinned.list,
lambda: unpinned.get("ovpmon-backup_x_20260101T000000Z.ovpbak", "/dev/null"),
lambda: unpinned.delete("ovpmon-backup_x_20260101T000000Z.ovpbak")):
with pytest.raises(destinations.DestinationError, match="not trusted"):
call()
assert len(FakeSSH.connects) == n
# Trust: only the fingerprint the administrator saw is accepted
with pytest.raises(BackupError):
engine.trust_host_key(dest["id"], "SHA256:" + "A" * 43)
pinned = engine.trust_host_key(dest["id"], fp)
assert pinned["params"]["host_key"] == fp and pinned["secrets"] == {"password": store.MASK}
assert engine.test_destination(dest["id"])["ok"] is True
rec = store.get_destination(dest["id"], with_secrets=True)
d = destinations.build_destination("sftp", rec["params"], rec["secrets"])
name = "ovpmon-backup_vpn_20261007T101500Z.ovpbak"
d.put(__file__, name)
assert f"ovpmon/daily/{name}" in FakeSFTP.files and not [f for f in FakeSFTP.files if f.endswith(".part")]
FakeSFTP.files["ovpmon/daily/notes.txt"] = b"x"
assert [o["name"] for o in d.list()] == [name] # only our package names
out = os.path.join(os.path.dirname(env.prof), "got")
d.get(name, out)
assert open(out, "rb").read() == open(__file__, "rb").read()
# Pin and the form: an edit of other fields keeps the pin, a client cannot set it, a new host drops it
edit = {**body, "params": {**base, "host_key": "SHA256:" + "B" * 43, "directory": "ovpmon/other"}, "secrets": {}}
r = client.put(f"/api/backup/destinations/{dest['id']}", json=edit).json()
assert r["params"]["host_key"] == fp and r["params"]["directory"] == "ovpmon/other"
r = client.put(f"/api/backup/destinations/{dest['id']}", json={**edit, "params": {**base, "host": "other.example.com"}}).json()
assert "host_key" not in r["params"]
client.put(f"/api/backup/destinations/{dest['id']}", json={**edit, "params": base})
engine.trust_host_key(dest["id"], fp)
# A different key from the server: connection refused, Test offers the new fingerprint (changed)
FakeKey.blob = b"server-host-key-B"
try:
with pytest.raises(destinations.DestinationError, match="host key of the server changed"):
d.list()
changed = engine.test_destination(dest["id"])
assert changed["needs_trust"] is True and changed["key_changed"] is True and changed["fingerprint"] != fp
finally:
FakeKey.blob = b"server-host-key-A"
+10
View File
@@ -0,0 +1,10 @@
from fastapi import HTTPException
from services import pki
def forbid_during_restore():
"""Dependency of the routes that change the PKI, the profiles or the settings: 409 while a
backup restore replaces them."""
if pki.is_restore_running():
raise HTTPException(status_code=409, detail=pki.RESTORE_RUNNING_MSG)