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:
1 parent
d29c261347
commit
f8cdcd0fc6
55 files changed
+4401
-37
No files matched your search
@@ -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)."""
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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]
|
||||
Reference in new issue
Block a user