diff --git a/deploy/systemd/coulobre-account-offsite.socket b/deploy/systemd/coulobre-account-offsite.socket new file mode 100644 index 0000000..33f9e47 --- /dev/null +++ b/deploy/systemd/coulobre-account-offsite.socket @@ -0,0 +1,14 @@ +[Unit] +Description=Coulobre off-site backup transfer socket + +[Socket] +ListenStream=/run/coulobre-account-offsite.sock +SocketUser=root +SocketGroup=coulobre-offsite-requests +SocketMode=0660 +Accept=yes +MaxConnections=2 +RemoveOnStop=true + +[Install] +WantedBy=sockets.target diff --git a/deploy/systemd/coulobre-account-offsite@.service b/deploy/systemd/coulobre-account-offsite@.service new file mode 100644 index 0000000..a5dbb8a --- /dev/null +++ b/deploy/systemd/coulobre-account-offsite@.service @@ -0,0 +1,23 @@ +[Unit] +Description=Coulobre off-site backup transfer +CollectMode=inactive-or-failed + +[Service] +Type=exec +User=root +WorkingDirectory=/opt/coulobre +StateDirectory=coulobre/offsite +StateDirectoryMode=0700 +UMask=0077 +ExecStart=/opt/coulobre/bin/coulobre-account-backup offsite-request +StandardInput=socket +StandardOutput=socket +StandardError=journal +RuntimeMaxSec=30min +TimeoutStopSec=10s +NoNewPrivileges=true +PrivateTmp=true +PrivateDevices=true +ProtectHome=true +ProtectSystem=strict +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 diff --git a/src/coulobre/account_backup.py b/src/coulobre/account_backup.py index be1f78f..ed8a907 100644 --- a/src/coulobre/account_backup.py +++ b/src/coulobre/account_backup.py @@ -9,6 +9,7 @@ from dataclasses import dataclass from pathlib import Path from shutil import copyfileobj from tempfile import NamedTemporaryFile, TemporaryDirectory +from uuid import UUID from zipfile import ZIP_STORED, BadZipFile, ZipFile from .database_node import DEFAULT_SOCKET, DatabaseSpec @@ -168,6 +169,20 @@ def main(argv=None): commands.add_parser( "restore-request", help="Restore a component for the panel worker." ) + commands.add_parser( + "offsite-request", help="Transfer a scheduled backup for the worker." + ) + verify = commands.add_parser( + "verify-offsite", help="Check access to an off-site destination." + ) + verify.add_argument("destination") + recover = commands.add_parser( + "recover-offsite", help="Retrieve and verify an off-site archive." + ) + recover.add_argument("destination") + recover.add_argument("account_id", type=int) + recover.add_argument("backup_id", type=UUID) + recover.add_argument("output", type=Path) args = parser.parse_args(argv) if args.command == "restore-request": @@ -185,7 +200,28 @@ def main(argv=None): return serve_backup_request() + if args.command == "offsite-request": + from .offsite_node import serve_offsite_request + + return serve_offsite_request() + try: + if args.command == "verify-offsite": + from .offsite_node import verify_destination + + verify_destination(args.destination) + print("Off-site repository access verified.") + return 0 + if args.command == "recover-offsite": + from .offsite_backup import OffsiteBackupRequest + from .offsite_node import recover_offsite_backup + + request = OffsiteBackupRequest( + args.account_id, args.backup_id, args.destination + ) + snapshot = recover_offsite_backup(request, args.output) + print(f"Verified archive recovered from snapshot {snapshot}.") + return 0 if args.command == "unpack": backup = unpack_backup(args.archive, args.directory) else: diff --git a/src/coulobre/offsite_backup.py b/src/coulobre/offsite_backup.py new file mode 100644 index 0000000..02f8cb7 --- /dev/null +++ b/src/coulobre/offsite_backup.py @@ -0,0 +1,82 @@ +import re +from dataclasses import dataclass +from uuid import UUID + +OFFSITE_SOCKET = "/run/coulobre-account-offsite.sock" +TRANSFER_TIMEOUT_SECONDS = 30 * 60 +MAX_DESTINATION_LENGTH = 48 +DESTINATION_ID = re.compile(r"[a-z][a-z0-9-]{0,47}") +HEX_DIGEST = re.compile(r"[0-9a-f]{64}") + + +def validate_destination(destination): + if not isinstance(destination, str) or not DESTINATION_ID.fullmatch( + destination + ): + raise ValueError("Choose a configured off-site backup destination.") + + +def destination_labels(value): + if not isinstance(value, dict) or len(value) > 20: + raise ValueError("Configure an object with up to 20 destinations.") + for destination, label in value.items(): + validate_destination(destination) + if ( + not isinstance(label, str) + or not label.strip() + or not label.isprintable() + or len(label) > 80 + ): + raise ValueError( + "Each destination needs a label of up to 80 characters." + ) + return value + + +@dataclass(frozen=True) +class OffsiteBackupRequest: + account_id: int + backup_id: UUID + destination: str + + def __post_init__(self): + if ( + type(self.account_id) is not int + or not 1 <= self.account_id < 2**63 + ): + raise ValueError("Expected a valid backup account ID.") + if not isinstance(self.backup_id, UUID): + raise ValueError("Expected a backup UUID.") + validate_destination(self.destination) + + @classmethod + def from_manifest(cls, data): + if ( + not isinstance(data, dict) + or data.keys() + != {"version", "account_id", "backup_id", "destination"} + or type(data["version"]) is not int + or data["version"] != 1 + or not isinstance(data["backup_id"], str) + ): + raise ValueError("Expected a version 1 off-site backup request.") + backup_id = UUID(data["backup_id"]) + if str(backup_id) != data["backup_id"]: + raise ValueError("Expected a canonical backup ID.") + return cls(data["account_id"], backup_id, data["destination"]) + + def manifest(self): + return { + "version": 1, + "account_id": self.account_id, + "backup_id": str(self.backup_id), + "destination": self.destination, + } + + @property + def tag(self): + return f"coulobre-{self.backup_id}" + + @property + def archive_name(self): + return f"account-{self.account_id}-{self.backup_id}.zip" diff --git a/src/coulobre/offsite_node.py b/src/coulobre/offsite_node.py new file mode 100644 index 0000000..1a85f33 --- /dev/null +++ b/src/coulobre/offsite_node.py @@ -0,0 +1,268 @@ +import hashlib +import json +import os +import re +import subprocess +from contextlib import suppress +from dataclasses import dataclass +from pathlib import Path +from tempfile import NamedTemporaryFile +from zipfile import BadZipFile + +from .account_backup import open_account_bundle, private_path +from .account_backup_request import backup_archive, expiration_marker +from .node_files import ( + check_root_file, + locked_root_directory, + require_root_directory, +) +from .node_requests import serve_apply_request +from .node_stream import STREAM_CHUNK_SIZE +from .offsite_backup import ( + HEX_DIGEST, + TRANSFER_TIMEOUT_SECONDS, + OffsiteBackupRequest, + validate_destination, +) + +CONFIG = Path("/etc/coulobre/offsite") +STATE = Path("/var/lib/coulobre/offsite") +REPOSITORY = re.compile(r"sftp:coulobre-offsite:/?[A-Za-z0-9._/-]{1,512}") +SHA_TAG = "coulobre-sha256-" +UNREACHABLE = ( + "Could not access the off-site repository. Check its configuration." +) + + +class OffsiteRepositoryError(ValueError): + pass + + +@dataclass(frozen=True) +class Repository: + directory: Path + + @classmethod + def for_destination(cls, destination): + validate_destination(destination) + if os.geteuid() != 0: + raise ValueError("Run off-site backup commands as root.") + directory = CONFIG / destination + require_root_directory(directory) + for name in ( + "repository", + "password", + "ssh_config", + "identity", + "known_hosts", + ): + check_root_file(directory / name, mode=0o600) + with (directory / "repository").open(encoding="ascii") as stream: + location = stream.read(1024).strip() + if not REPOSITORY.fullmatch(location) or {"..", "."}.intersection( + location.removeprefix("sftp:coulobre-offsite:").split("/") + ): + raise ValueError( + "Use the coulobre-offsite SSH host alias in the repository." + ) + return cls(directory) + + def arguments(self, *args): + directory = self.directory + ssh = ( + f"-F {directory / 'ssh_config'} -i {directory / 'identity'} " + "-o BatchMode=yes -o StrictHostKeyChecking=yes " + "-o IdentitiesOnly=yes " + "-o GlobalKnownHostsFile=/dev/null " + f"-o UserKnownHostsFile={directory / 'known_hosts'}" + ) + return [ + "/usr/bin/restic", + "--no-cache", + "--repository-file", + str(directory / "repository"), + "--password-file", + str(directory / "password"), + "-o", + f"sftp.args={ssh}", + *args, + ] + + def run(self, *args, source=None, capture=False, timeout=30): + try: + result = subprocess.run( + self.arguments(*args), + stdin=subprocess.DEVNULL if source is None else source, + stdout=subprocess.PIPE if capture else subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env={"PATH": "/usr/bin:/bin", "LANG": "C.UTF-8"}, + timeout=timeout, + check=True, + ) + except (OSError, subprocess.SubprocessError): + raise OffsiteRepositoryError(UNREACHABLE) from None + return result.stdout + + def snapshot(self, request): + raw = self.run( + "--json", "snapshots", "--tag", request.tag, capture=True + ) + try: + entries = json.loads(raw) + if not isinstance(entries, list): + raise ValueError + if not entries: + return None + if len(entries) != 1: + raise ValueError + entry = entries[0] + identifier = entry["id"] + tags = entry["tags"] + digests = [ + tag[len(SHA_TAG) :] for tag in tags if tag.startswith(SHA_TAG) + ] + if ( + not HEX_DIGEST.fullmatch(identifier) + or request.tag not in tags + or len(digests) != 1 + or not HEX_DIGEST.fullmatch(digests[0]) + or entry["paths"] != [f"/{request.archive_name}"] + ): + raise ValueError + return identifier, digests[0] + except ( + AttributeError, + KeyError, + RecursionError, + TypeError, + ValueError, + ): + raise OffsiteRepositoryError( + "The off-site repository has conflicting snapshot metadata." + ) from None + + def read_archive( + self, request, snapshot, *, target=None, expected_size=None + ): + digest = hashlib.sha256() + size = 0 + with subprocess.Popen( + self.arguments("dump", snapshot, f"/{request.archive_name}"), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + env={"PATH": "/usr/bin:/bin", "LANG": "C.UTF-8"}, + ) as process: + try: + while chunk := process.stdout.read(STREAM_CHUNK_SIZE): + size += len(chunk) + if expected_size is not None and size > expected_size: + raise OffsiteRepositoryError( + "The off-site copy has a different size." + ) + digest.update(chunk) + if target is not None: + target.write(chunk) + if process.wait() != 0: + raise OffsiteRepositoryError( + "Could not read back the off-site copy." + ) + except BaseException: + with suppress(ProcessLookupError): + process.kill() + raise + if expected_size is not None and size != expected_size: + raise OffsiteRepositoryError( + "The off-site copy has a different size." + ) + return digest.hexdigest() + + +def transfer_offsite_backup(request): + repository = Repository.for_destination(request.destination) + archive = backup_archive(request.account_id, request.backup_id) + with locked_root_directory(STATE): + if os.path.lexists(expiration_marker(archive)): + raise OffsiteRepositoryError("The local archive has expired.") + try: + with open_account_bundle(archive) as (_, backup): + if backup.website.account_id != request.account_id: + raise ValueError + except (OSError, BadZipFile, ValueError): + raise OffsiteRepositoryError( + "The local archive could not be validated." + ) from None + with archive.open("rb") as source: + size = os.fstat(source.fileno()).st_size + digest = hashlib.file_digest(source, "sha256").hexdigest() + snapshot = repository.snapshot(request) + if snapshot is None: + source.seek(0) + repository.run( + "backup", + "--stdin", + "--stdin-filename", + request.archive_name, + "--tag", + request.tag, + "--tag", + SHA_TAG + digest, + source=source, + timeout=TRANSFER_TIMEOUT_SECONDS - 15, + ) + snapshot = repository.snapshot(request) + if snapshot is None or snapshot[1] != digest: + raise OffsiteRepositoryError( + "The off-site snapshot has a different checksum." + ) + snapshot_id, _ = snapshot + if ( + repository.read_archive(request, snapshot_id, expected_size=size) + != digest + ): + raise OffsiteRepositoryError( + "The off-site copy failed read-back verification." + ) + return {"snapshot": snapshot_id, "sha256": digest} + + +def verify_destination(destination): + Repository.for_destination(destination).run("cat", "config") + + +def recover_offsite_backup(request, output): + repository = Repository.for_destination(request.destination) + snapshot = repository.snapshot(request) + if snapshot is None: + raise ValueError("No off-site snapshot matches this backup ID.") + output = private_path(output, new=True) + snapshot_id, digest = snapshot + with NamedTemporaryFile(dir=output.parent) as staged: + recovered = repository.read_archive( + request, snapshot_id, target=staged + ) + if recovered != digest: + raise ValueError( + "The off-site copy failed read-back verification." + ) + staged.flush() + with open_account_bundle(Path(staged.name)) as (_, backup): + if backup.website.account_id != request.account_id: + raise ValueError("The archive belongs to a different account.") + os.fsync(staged.fileno()) + os.link(staged.name, output) + return snapshot_id + + +def serve_offsite_request(): + def apply(request): + try: + return transfer_offsite_backup(request) + except OSError: + raise ValueError( + "The backup node could not access the archive or destination." + ) from None + + return serve_apply_request( + 1, OffsiteBackupRequest.from_manifest, apply, include_result=True + )