876 lines
38 KiB
Python
876 lines
38 KiB
Python
"""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)
|