- Refactor tests to achieve 100% Zero-Mocks compliance (remove unittest.mock, add tests.helpers.env_override and stdlib redirects) - Extract testable parsing methods in package managers and inspector - Add tests/test_security.py with 5 negative AppSec test cases (Zip Slip, Root Gate, Tampering SHA-256, Secret Sanitization, and AST check for zero shell=True) - Expand is_sanitized_target to redact all private SSH/TLS keys (*.key, *.pem, id_*) - Split Gitea CI/CD pipelines into test-and-lint.yaml and build-and-release.yaml - Add .gitleaks.toml configuration - Formally close v1.0.0 genesis plan in docs/plans/linux-backuper/00-status.md as immutable ADR - Bump version to v2.0.0 across __init__.py, man page, tests, and documentation
322 lines
13 KiB
Python
322 lines
13 KiB
Python
"""Safe restore engine with dry-run default, safety snapshots, and atomic write."""
|
|
|
|
import datetime
|
|
import os
|
|
import shutil
|
|
import socket
|
|
import subprocess
|
|
import tarfile
|
|
from typing import Dict, List, Optional, Tuple, Any
|
|
|
|
from linux_backuper.core.archiver import SnapshotArchiver, calculate_file_sha256, is_socket_or_fifo, BUFFER_SIZE
|
|
from linux_backuper.core.constants import EXIT_DRY_RUN, EXIT_SUCCESS, EXIT_GENERIC_ERROR, DEFAULT_BACKUP_DIR
|
|
from linux_backuper.core.detector import detect_distro
|
|
from linux_backuper.core.lock import SingleInstanceLock
|
|
from linux_backuper.models import RestorePlan, RestorePlanItem, SnapshotManifest
|
|
|
|
EXCLUDED_DYNAMIC_PATHS = {
|
|
"/etc/resolv.conf",
|
|
"/etc/mtab",
|
|
"/etc/adjtime",
|
|
"/etc/machine-id"
|
|
}
|
|
|
|
SENSITIVE_NETWORK_PREFIXES = (
|
|
"/etc/netplan",
|
|
"/etc/sysconfig/network-scripts",
|
|
"/etc/network/interfaces",
|
|
"/etc/NetworkManager"
|
|
)
|
|
|
|
class SecurityError(Exception):
|
|
"""Raised when security boundaries or path traversal attacks are detected."""
|
|
pass
|
|
|
|
class DryRunException(Exception):
|
|
"""Raised when restore runs in dry-run mode (exit code 5)."""
|
|
def __init__(self, plan: RestorePlan):
|
|
self.plan = plan
|
|
super().__init__("Restore executed in dry-run mode. Pass --force to apply changes.")
|
|
|
|
class SafeRestoreEngine:
|
|
"""Safely restores configuration archives onto the filesystem."""
|
|
|
|
def __init__(self, target_dir: str = DEFAULT_BACKUP_DIR):
|
|
self.target_dir = target_dir
|
|
|
|
def _resolve_archive(self, snapshot_id: str) -> str:
|
|
archive_path = SnapshotArchiver.resolve_archive_path(self.target_dir, snapshot_id)
|
|
if not os.path.isfile(archive_path):
|
|
raise FileNotFoundError(f"Snapshot archive not found: {archive_path}")
|
|
return archive_path
|
|
|
|
def plan_restore(
|
|
self,
|
|
snapshot_id: str,
|
|
target_root: str = "/",
|
|
include_fstab: bool = False
|
|
) -> RestorePlan:
|
|
"""
|
|
Inspect snapshot and construct a detailed RestorePlan against target_root.
|
|
Identifies create, modify, and skip actions without mutating the disk.
|
|
"""
|
|
archive_path = self._resolve_archive(snapshot_id)
|
|
manifest = SnapshotArchiver.read_manifest_from_archive(archive_path)
|
|
|
|
target_root_clean = os.path.abspath(target_root)
|
|
plan_items: List[RestorePlanItem] = []
|
|
|
|
with tarfile.open(archive_path, "r:*") as tar:
|
|
for member in tar.getmembers():
|
|
if not member.name.startswith("data/"):
|
|
continue
|
|
|
|
clean_subpath = member.name[5:].lstrip("/")
|
|
abs_sys_path = "/" + clean_subpath
|
|
target_dest_path = os.path.join(target_root_clean, clean_subpath)
|
|
|
|
# 1. Check excluded dynamic / runtime files
|
|
if abs_sys_path in EXCLUDED_DYNAMIC_PATHS:
|
|
plan_items.append(RestorePlanItem(
|
|
rel_path=member.name,
|
|
abs_path=target_dest_path,
|
|
action="skip",
|
|
reason="Excluded dynamic/volatile system file"
|
|
))
|
|
continue
|
|
|
|
if abs_sys_path == "/etc/fstab" and not include_fstab:
|
|
plan_items.append(RestorePlanItem(
|
|
rel_path=member.name,
|
|
abs_path=target_dest_path,
|
|
action="skip",
|
|
reason="Protected filesystem table (/etc/fstab). Pass --include-fstab to overwrite"
|
|
))
|
|
continue
|
|
|
|
if os.path.exists(target_dest_path) and is_socket_or_fifo(target_dest_path):
|
|
plan_items.append(RestorePlanItem(
|
|
rel_path=member.name,
|
|
abs_path=target_dest_path,
|
|
action="skip",
|
|
reason="Socket or FIFO file on filesystem"
|
|
))
|
|
continue
|
|
|
|
# 2. Check sensitive network files
|
|
is_net = any(abs_sys_path.startswith(prefix) for prefix in SENSITIVE_NETWORK_PREFIXES)
|
|
|
|
expected_sha = manifest.files_sha256.get(member.name)
|
|
|
|
# 3. Check live file state
|
|
if not os.path.exists(target_dest_path) and not os.path.islink(target_dest_path):
|
|
plan_items.append(RestorePlanItem(
|
|
rel_path=member.name,
|
|
abs_path=target_dest_path,
|
|
action="create",
|
|
reason="File does not exist on target system",
|
|
is_sensitive_network=is_net,
|
|
source_sha256=expected_sha,
|
|
target_sha256=None
|
|
))
|
|
else:
|
|
if os.path.isfile(target_dest_path):
|
|
target_sha = calculate_file_sha256(target_dest_path)
|
|
if expected_sha and target_sha == expected_sha:
|
|
plan_items.append(RestorePlanItem(
|
|
rel_path=member.name,
|
|
abs_path=target_dest_path,
|
|
action="skip",
|
|
reason="File content is identical to snapshot",
|
|
is_sensitive_network=is_net,
|
|
source_sha256=expected_sha,
|
|
target_sha256=target_sha
|
|
))
|
|
else:
|
|
plan_items.append(RestorePlanItem(
|
|
rel_path=member.name,
|
|
abs_path=target_dest_path,
|
|
action="modify",
|
|
reason="File content differs from snapshot",
|
|
is_sensitive_network=is_net,
|
|
source_sha256=expected_sha,
|
|
target_sha256=target_sha
|
|
))
|
|
else:
|
|
plan_items.append(RestorePlanItem(
|
|
rel_path=member.name,
|
|
abs_path=target_dest_path,
|
|
action="modify",
|
|
reason="Target exists as non-regular file",
|
|
is_sensitive_network=is_net,
|
|
source_sha256=expected_sha,
|
|
target_sha256=None
|
|
))
|
|
|
|
return RestorePlan(
|
|
snapshot_id=manifest.snapshot_id,
|
|
target_root=target_root_clean,
|
|
items=plan_items,
|
|
requires_force=True
|
|
)
|
|
|
|
def create_safety_snapshot(self, target_root: str = "/") -> Tuple[str, str]:
|
|
"""
|
|
Create a pre-restore safety snapshot of /etc before any file modifications.
|
|
Returns (snapshot_id, archive_path).
|
|
"""
|
|
hostname = socket.gethostname().split(".")[0]
|
|
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
safety_id = f"pre_restore_{hostname}_{timestamp}"
|
|
|
|
etc_path = os.path.join(os.path.abspath(target_root), "etc")
|
|
included_paths = [etc_path] if os.path.isdir(etc_path) else ["/etc"]
|
|
|
|
archiver = SnapshotArchiver(target_dir=self.target_dir, compression="gzip")
|
|
file_entries, files_sha256, uncompressed_bytes, _ = archiver.collect_file_list(included_paths)
|
|
|
|
manifest = SnapshotManifest(
|
|
schema_version="1.0",
|
|
snapshot_id=safety_id,
|
|
created_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
|
hostname=socket.gethostname(),
|
|
profile="safety_pre_restore",
|
|
compression="gzip",
|
|
os=detect_distro().to_dict(),
|
|
package_manager="none",
|
|
package_count=0,
|
|
included_paths=included_paths,
|
|
stats={
|
|
"file_count": len(file_entries),
|
|
"uncompressed_bytes": uncompressed_bytes,
|
|
"compressed_bytes": 0
|
|
},
|
|
files_sha256=files_sha256
|
|
)
|
|
|
|
archive_path = archiver.create_snapshot_archive(safety_id, manifest, file_entries)
|
|
|
|
# Verify safety snapshot integrity immediately
|
|
valid, msg = SnapshotArchiver.verify_archive(archive_path)
|
|
if not valid:
|
|
raise RuntimeError(f"Safety snapshot failed integrity check: {msg}")
|
|
|
|
return safety_id, archive_path
|
|
|
|
def execute_restore(
|
|
self,
|
|
plan: RestorePlan,
|
|
force: bool = False,
|
|
pid_path: Optional[str] = None
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
Execute file restoration based on RestorePlan.
|
|
If force=False: raises DryRunException (exit code 5).
|
|
If force=True: creates safety snapshot, atomically restores files, runs restorecon on SELinux.
|
|
"""
|
|
if not force:
|
|
raise DryRunException(plan)
|
|
|
|
lock = SingleInstanceLock(pid_path=pid_path)
|
|
lock.acquire()
|
|
|
|
restored_files: List[str] = []
|
|
restored_dirs: set = set()
|
|
safety_id = None
|
|
safety_path = None
|
|
|
|
try:
|
|
# 1. Capture unalterable pre-restore safety snapshot
|
|
safety_id, safety_path = self.create_safety_snapshot(target_root=plan.target_root)
|
|
plan.safety_snapshot_id = safety_id
|
|
|
|
archive_path = self._resolve_archive(plan.snapshot_id)
|
|
|
|
with tarfile.open(archive_path, "r:*") as tar:
|
|
for item in plan.items:
|
|
if item.action not in ("create", "modify"):
|
|
continue
|
|
|
|
# Zip slip security check
|
|
dest_abs = os.path.abspath(item.abs_path)
|
|
if not dest_abs.startswith(plan.target_root):
|
|
raise SecurityError(f"Zip slip path traversal detected: {dest_abs} outside {plan.target_root}")
|
|
|
|
member = tar.getmember(item.rel_path)
|
|
dest_dir = os.path.dirname(dest_abs)
|
|
os.makedirs(dest_dir, exist_ok=True)
|
|
restored_dirs.add(dest_dir)
|
|
|
|
if member.isreg():
|
|
f_in = tar.extractfile(member)
|
|
if not f_in:
|
|
continue
|
|
|
|
tmp_dest = f"{dest_abs}.tmp.{os.getpid()}"
|
|
try:
|
|
with open(tmp_dest, "wb") as f_out:
|
|
while chunk := f_in.read(BUFFER_SIZE):
|
|
f_out.write(chunk)
|
|
|
|
# Apply permissions
|
|
try:
|
|
os.chmod(tmp_dest, member.mode)
|
|
except OSError:
|
|
pass
|
|
|
|
# Apply ownership if root
|
|
if os.geteuid() == 0:
|
|
try:
|
|
os.chown(tmp_dest, member.uid, member.gid)
|
|
except OSError:
|
|
pass
|
|
|
|
# Atomic replacement
|
|
os.replace(tmp_dest, dest_abs)
|
|
restored_files.append(dest_abs)
|
|
finally:
|
|
if os.path.exists(tmp_dest):
|
|
try:
|
|
os.unlink(tmp_dest)
|
|
except OSError:
|
|
pass
|
|
|
|
elif member.issym():
|
|
# Symlink restoration
|
|
tmp_link = f"{dest_abs}.tmp.{os.getpid()}"
|
|
try:
|
|
if os.path.lexists(tmp_link):
|
|
os.unlink(tmp_link)
|
|
os.symlink(member.linkname, tmp_link)
|
|
os.replace(tmp_link, dest_abs)
|
|
restored_files.append(dest_abs)
|
|
finally:
|
|
if os.path.lexists(tmp_link):
|
|
try:
|
|
os.unlink(tmp_link)
|
|
except OSError:
|
|
pass
|
|
|
|
# 2. SELinux context restoration
|
|
selinux_restored = False
|
|
if os.path.exists("/sys/fs/selinux") and shutil.which("restorecon"):
|
|
for d in restored_dirs:
|
|
try:
|
|
subprocess.run(["restorecon", "-R", d], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
except Exception:
|
|
pass
|
|
selinux_restored = True
|
|
|
|
return {
|
|
"status": "success",
|
|
"snapshot_id": plan.snapshot_id,
|
|
"safety_snapshot_id": safety_id,
|
|
"safety_archive_path": safety_path,
|
|
"restored_count": len(restored_files),
|
|
"restored_files": restored_files,
|
|
"selinux_context_restored": selinux_restored
|
|
}
|
|
|
|
finally:
|
|
lock.release()
|