430 lines
16 KiB
Python
430 lines
16 KiB
Python
"""Archive creation, extraction, and verification using Python standard library."""
|
|
|
|
import gzip
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import stat
|
|
import tarfile
|
|
import time
|
|
from typing import Dict, List, Optional, Tuple, Any
|
|
|
|
from linux_backuper.models import SnapshotManifest
|
|
|
|
BUFFER_SIZE = 64 * 1024 # 64 KB chunks for hashing and streaming
|
|
|
|
def calculate_file_sha256(filepath: str) -> str:
|
|
"""Calculate SHA-256 checksum of a file."""
|
|
hasher = hashlib.sha256()
|
|
with open(filepath, "rb") as f:
|
|
while chunk := f.read(BUFFER_SIZE):
|
|
hasher.update(chunk)
|
|
return hasher.hexdigest()
|
|
|
|
def is_socket_or_fifo(filepath: str) -> bool:
|
|
"""Check if path is a UNIX socket, named pipe (FIFO) or character device."""
|
|
try:
|
|
st = os.lstat(filepath)
|
|
return stat.S_ISSOCK(st.st_mode) or stat.S_ISFIFO(st.st_mode)
|
|
except OSError:
|
|
return False
|
|
|
|
def is_sanitized_target(filepath: str) -> bool:
|
|
"""Check if file contains secrets and must be omitted during sanitized export."""
|
|
name = os.path.basename(filepath)
|
|
if name in ("shadow", "gshadow", "opasswd", "shadow-", "gshadow-"):
|
|
return True
|
|
if name.startswith("ssh_host_") and "key" in name and not name.endswith(".pub"):
|
|
return True
|
|
return False
|
|
|
|
class SnapshotArchiver:
|
|
"""Manages creation, listing, and verification of snapshot archives."""
|
|
|
|
def __init__(self, target_dir: str, compression: str = "gzip"):
|
|
self.target_dir = target_dir
|
|
self.compression = "gzip" if compression in ("gz", "gzip") else "none"
|
|
|
|
def _ensure_target_dir() -> None:
|
|
pass
|
|
|
|
def _ensure_target_dir_inst(self) -> None:
|
|
"""Ensure target directory exists with 0700 permissions."""
|
|
os.makedirs(self.target_dir, exist_ok=True)
|
|
try:
|
|
os.chmod(self.target_dir, 0o700)
|
|
except OSError:
|
|
pass
|
|
|
|
def collect_file_list(
|
|
self,
|
|
paths: List[str],
|
|
exclude_patterns: Optional[List[str]] = None,
|
|
sanitize: bool = False,
|
|
one_file_system: bool = True,
|
|
max_file_size_mb: int = 50
|
|
) -> Tuple[List[Tuple[str, str]], Dict[str, str], int, List[str]]:
|
|
"""
|
|
Scan paths and compute pre-archive hashes and metadata.
|
|
Returns:
|
|
- list of (filesystem_abs_path, tar_rel_path)
|
|
- dict of {tar_rel_path: sha256_hash}
|
|
- total uncompressed bytes
|
|
- list of sanitized/redacted relative paths
|
|
"""
|
|
file_entries: List[Tuple[str, str]] = []
|
|
files_sha256: Dict[str, str] = {}
|
|
sanitized_files: List[str] = []
|
|
total_bytes = 0
|
|
exclude_patterns = exclude_patterns or []
|
|
|
|
for base_path in paths:
|
|
abs_base = os.path.abspath(base_path)
|
|
if not os.path.exists(abs_base):
|
|
continue
|
|
|
|
try:
|
|
base_st = os.lstat(abs_base)
|
|
base_dev = base_st.st_dev
|
|
except OSError:
|
|
continue
|
|
|
|
if os.path.isfile(abs_base) or os.path.islink(abs_base):
|
|
rel_name = os.path.join("data", os.path.basename(abs_base))
|
|
if sanitize and is_sanitized_target(abs_base):
|
|
sanitized_files.append(rel_name)
|
|
continue
|
|
|
|
if not is_socket_or_fifo(abs_base):
|
|
file_entries.append((abs_base, rel_name))
|
|
if not os.path.islink(abs_base):
|
|
sha = calculate_file_sha256(abs_base)
|
|
files_sha256[rel_name] = sha
|
|
total_bytes += os.path.getsize(abs_base)
|
|
continue
|
|
|
|
# Directory tree traversal
|
|
for root, dirs, files in os.walk(abs_base, followlinks=False):
|
|
# Filter subdirectories in place
|
|
dirs[:] = [d for d in dirs if not any(p in d for p in exclude_patterns)]
|
|
|
|
# Check one-file-system boundary for subdirectories
|
|
if one_file_system:
|
|
allowed_dirs = []
|
|
for d in dirs:
|
|
dir_path = os.path.join(root, d)
|
|
try:
|
|
if os.lstat(dir_path).st_dev == base_dev:
|
|
allowed_dirs.append(d)
|
|
except OSError:
|
|
pass
|
|
dirs[:] = allowed_dirs
|
|
|
|
for filename in files:
|
|
abs_filepath = os.path.join(root, filename)
|
|
if any(p in filename for p in exclude_patterns):
|
|
continue
|
|
|
|
# One file system boundary check
|
|
try:
|
|
st = os.lstat(abs_filepath)
|
|
if one_file_system and st.st_dev != base_dev:
|
|
continue
|
|
except OSError:
|
|
continue
|
|
|
|
# Large file check (> 50 MB)
|
|
if max_file_size_mb > 0 and st.st_size > (max_file_size_mb * 1024 * 1024):
|
|
continue
|
|
|
|
rel_to_base = os.path.relpath(abs_filepath, os.path.dirname(abs_base))
|
|
arc_path = os.path.join("data", rel_to_base)
|
|
|
|
# Diagnostic sanitization check
|
|
if sanitize and is_sanitized_target(abs_filepath):
|
|
sanitized_files.append(arc_path)
|
|
continue
|
|
|
|
if is_socket_or_fifo(abs_filepath):
|
|
continue
|
|
|
|
file_entries.append((abs_filepath, arc_path))
|
|
|
|
if not os.path.islink(abs_filepath):
|
|
try:
|
|
sha = calculate_file_sha256(abs_filepath)
|
|
files_sha256[arc_path] = sha
|
|
total_bytes += st.st_size
|
|
except (OSError, IOError):
|
|
pass
|
|
|
|
return file_entries, files_sha256, total_bytes, sanitized_files
|
|
|
|
def create_snapshot_archive(
|
|
self,
|
|
snapshot_id: str,
|
|
manifest: SnapshotManifest,
|
|
file_entries: List[Tuple[str, str]]
|
|
) -> str:
|
|
"""
|
|
Create atomic .tar.gz archive with manifest.json as the very first member.
|
|
Enforces 0600 file permissions.
|
|
"""
|
|
self._ensure_target_dir_inst()
|
|
ext = ".tar.gz" if self.compression == "gzip" else ".tar"
|
|
final_archive_path = os.path.join(self.target_dir, f"{snapshot_id}{ext}")
|
|
temp_archive_path = os.path.join(self.target_dir, f".{snapshot_id}.tmp{ext}")
|
|
|
|
# Encode manifest JSON bytes
|
|
manifest_dict = manifest.to_dict()
|
|
manifest_bytes = json.dumps(manifest_dict, indent=2, sort_keys=True).encode("utf-8")
|
|
|
|
# Open temp archive for writing with gzip or plain tar
|
|
tar_mode = "w:gz" if self.compression == "gzip" else "w:"
|
|
with tarfile.open(temp_archive_path, tar_mode) as tar:
|
|
# 1. ADD MANIFEST.JSON AS THE VERY FIRST MEMBER
|
|
manifest_info = tarfile.TarInfo(name="manifest.json")
|
|
manifest_info.size = len(manifest_bytes)
|
|
manifest_info.mtime = int(time.time())
|
|
manifest_info.mode = 0o600
|
|
manifest_info.type = tarfile.REGTYPE
|
|
|
|
import io
|
|
tar.addfile(tarinfo=manifest_info, fileobj=io.BytesIO(manifest_bytes))
|
|
|
|
# 2. ADD ALL COLLECTED DATA FILES
|
|
for abs_path, arc_path in file_entries:
|
|
try:
|
|
tar.add(abs_path, arcname=arc_path, recursive=False)
|
|
except (OSError, IOError):
|
|
pass
|
|
|
|
# Set strict 0600 permissions
|
|
try:
|
|
os.chmod(temp_archive_path, 0o600)
|
|
except OSError:
|
|
pass
|
|
|
|
# Atomic rename to final path
|
|
os.replace(temp_archive_path, final_archive_path)
|
|
|
|
# Update manifest compressed size stat
|
|
compressed_size = os.path.getsize(final_archive_path)
|
|
manifest.stats["compressed_bytes"] = compressed_size
|
|
|
|
return final_archive_path
|
|
|
|
@staticmethod
|
|
def read_manifest_from_archive(archive_path: str) -> SnapshotManifest:
|
|
"""
|
|
Read manifest.json from the first member of the archive stream.
|
|
Ultra-fast: avoids decompressing the rest of the archive.
|
|
"""
|
|
with tarfile.open(archive_path, "r:*") as tar:
|
|
first_member = tar.next()
|
|
if not first_member or first_member.name != "manifest.json":
|
|
# Fallback: scan for manifest.json if not first
|
|
member = tar.getmember("manifest.json")
|
|
else:
|
|
member = first_member
|
|
|
|
manifest_file = tar.extractfile(member)
|
|
if not manifest_file:
|
|
raise ValueError(f"Could not read manifest from {archive_path}")
|
|
|
|
data = json.loads(manifest_file.read().decode("utf-8"))
|
|
manifest = SnapshotManifest.from_dict(data)
|
|
if manifest.stats.get("compressed_bytes", 0) == 0 and os.path.isfile(archive_path):
|
|
manifest.stats["compressed_bytes"] = os.path.getsize(archive_path)
|
|
return manifest
|
|
|
|
@staticmethod
|
|
def verify_archive(archive_path: str) -> Tuple[bool, str]:
|
|
"""
|
|
Verify gzip stream integrity and all file SHA-256 checksums against manifest.json.
|
|
Returns (is_valid, error_message).
|
|
"""
|
|
if not os.path.isfile(archive_path):
|
|
return False, f"Archive not found: {archive_path}"
|
|
|
|
# 1. Check if file is gzip by inspecting header
|
|
is_gz = False
|
|
try:
|
|
with open(archive_path, "rb") as f:
|
|
header = f.read(2)
|
|
is_gz = (header == b"\x1f\x8b")
|
|
except OSError as e:
|
|
return False, f"Cannot open archive: {e}"
|
|
|
|
# If gzipped, verify complete stream integrity
|
|
if is_gz:
|
|
try:
|
|
with gzip.open(archive_path, "rb") as gz:
|
|
while gz.read(BUFFER_SIZE):
|
|
pass
|
|
except Exception as e:
|
|
return False, f"Gzip stream corrupted: {e}"
|
|
|
|
# 2. Manifest and member checksum verification
|
|
try:
|
|
with tarfile.open(archive_path, "r:*") as tar:
|
|
# Read manifest
|
|
try:
|
|
manifest_member = tar.getmember("manifest.json")
|
|
manifest_data = json.loads(tar.extractfile(manifest_member).read().decode("utf-8"))
|
|
except Exception as e:
|
|
return False, f"Invalid or missing manifest.json: {e}"
|
|
|
|
expected_hashes: Dict[str, str] = manifest_data.get("files_sha256", {})
|
|
|
|
for arc_name, expected_sha in expected_hashes.items():
|
|
try:
|
|
member = tar.getmember(arc_name)
|
|
except KeyError:
|
|
return False, f"Missing file in archive: {arc_name}"
|
|
|
|
if member.isreg():
|
|
f = tar.extractfile(member)
|
|
if not f:
|
|
return False, f"Unable to read file: {arc_name}"
|
|
|
|
hasher = hashlib.sha256()
|
|
while chunk := f.read(BUFFER_SIZE):
|
|
hasher.update(chunk)
|
|
actual_sha = hasher.hexdigest()
|
|
|
|
if actual_sha != expected_sha:
|
|
return False, f"Checksum mismatch for {arc_name}: expected {expected_sha}, got {actual_sha}"
|
|
|
|
except Exception as e:
|
|
return False, f"Tar archive corrupted: {e}"
|
|
|
|
return True, "Integrity verified successfully"
|
|
|
|
@staticmethod
|
|
def resolve_archive_path(target_dir: str, snapshot_id: str) -> str:
|
|
"""Resolve a snapshot ID or filename to full archive path."""
|
|
if os.path.isabs(snapshot_id) and os.path.exists(snapshot_id):
|
|
return snapshot_id
|
|
direct = os.path.join(target_dir, snapshot_id)
|
|
if os.path.exists(direct):
|
|
return direct
|
|
tar_gz = os.path.join(target_dir, f"{snapshot_id}.tar.gz")
|
|
if os.path.exists(tar_gz):
|
|
return tar_gz
|
|
tar_plain = os.path.join(target_dir, f"{snapshot_id}.tar")
|
|
if os.path.exists(tar_plain):
|
|
return tar_plain
|
|
if snapshot_id.endswith(".tar.gz") or snapshot_id.endswith(".tar"):
|
|
return direct
|
|
return tar_gz
|
|
|
|
@staticmethod
|
|
def read_meta_file(archive_path: str, meta_relative_path: str) -> Optional[str]:
|
|
"""Read a metadata text file from the archive (e.g. meta/packages.txt)."""
|
|
with tarfile.open(archive_path, "r:*") as tar:
|
|
try:
|
|
member = tar.getmember(meta_relative_path)
|
|
f = tar.extractfile(member)
|
|
if f:
|
|
return f.read().decode("utf-8", errors="replace")
|
|
except KeyError:
|
|
return None
|
|
return None
|
|
|
|
@staticmethod
|
|
def extract_file(archive_path: str, member_path: str, destination_path: str) -> str:
|
|
"""
|
|
Extract a single member from the archive to destination_path.
|
|
Guards strictly against Zip Slip / path traversal.
|
|
Returns final destination path.
|
|
"""
|
|
dest_abs = os.path.abspath(destination_path)
|
|
|
|
# If destination is an existing directory, append member filename
|
|
if os.path.isdir(dest_abs):
|
|
dest_abs = os.path.join(dest_abs, os.path.basename(member_path))
|
|
|
|
dest_dir = os.path.dirname(dest_abs)
|
|
if dest_dir:
|
|
os.makedirs(dest_dir, exist_ok=True)
|
|
|
|
with tarfile.open(archive_path, "r:*") as tar:
|
|
# Candidate names inside archive
|
|
candidates = [
|
|
member_path,
|
|
f"data/{member_path.lstrip('/')}",
|
|
member_path.lstrip("/"),
|
|
f"data{member_path}" if member_path.startswith("/") else f"data/{member_path}"
|
|
]
|
|
target_member = None
|
|
for c in candidates:
|
|
try:
|
|
target_member = tar.getmember(c)
|
|
break
|
|
except KeyError:
|
|
continue
|
|
|
|
if not target_member:
|
|
clean_target = member_path.strip("/")
|
|
for m in tar.getmembers():
|
|
if m.name == clean_target or m.name == f"data/{clean_target}":
|
|
target_member = m
|
|
break
|
|
if m.name.endswith(f"/{clean_target}") or m.name.endswith(clean_target):
|
|
target_member = m
|
|
break
|
|
|
|
if not target_member:
|
|
raise FileNotFoundError(f"File '{member_path}' not found in archive")
|
|
|
|
if not target_member.isreg():
|
|
raise ValueError(f"Member '{target_member.name}' is not a regular file")
|
|
|
|
f_in = tar.extractfile(target_member)
|
|
if not f_in:
|
|
raise IOError(f"Could not read member '{target_member.name}'")
|
|
|
|
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)
|
|
try:
|
|
os.chmod(tmp_dest, target_member.mode)
|
|
except OSError:
|
|
pass
|
|
os.replace(tmp_dest, dest_abs)
|
|
finally:
|
|
if os.path.exists(tmp_dest):
|
|
try:
|
|
os.unlink(tmp_dest)
|
|
except OSError:
|
|
pass
|
|
|
|
return dest_abs
|
|
|
|
def list_snapshots(self) -> List[SnapshotManifest]:
|
|
"""List all valid snapshots in the target directory."""
|
|
if not os.path.isdir(self.target_dir):
|
|
return []
|
|
|
|
snapshots: List[SnapshotManifest] = []
|
|
try:
|
|
entries = sorted(os.listdir(self.target_dir), reverse=True)
|
|
except PermissionError:
|
|
raise PermissionError(f"Permission denied accessing backup directory: {self.target_dir}")
|
|
except OSError:
|
|
return []
|
|
|
|
for filename in entries:
|
|
if (filename.endswith(".tar.gz") or filename.endswith(".tar")) and not filename.startswith("."):
|
|
filepath = os.path.join(self.target_dir, filename)
|
|
try:
|
|
manifest = self.read_manifest_from_archive(filepath)
|
|
snapshots.append(manifest)
|
|
except Exception:
|
|
pass
|
|
return snapshots
|
|
|