feat: modernize to Software Factory standards, add AppSec suite, and bump to v2.0.0
- 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
This commit is contained in:
1 parent
3e5f2ab498
commit
4b3346fd74
22 files changed
+577
-203
No files matched your search
@@ -1,4 +1,4 @@
|
||||
"""linux-backuper - Enterprise Linux system snapshot and configuration backup utility."""
|
||||
|
||||
__version__ = "1.0.0"
|
||||
__version__ = "2.0.0"
|
||||
__author__ = "wiredLAB"
|
||||
@@ -34,8 +34,12 @@ def is_sanitized_target(filepath: str) -> bool:
|
||||
name = os.path.basename(filepath)
|
||||
if name in ("shadow", "gshadow", "opasswd", "shadow-", "gshadow-"):
|
||||
return True
|
||||
if name in ("id_rsa", "id_ed25519", "id_ecdsa", "id_dsa"):
|
||||
return True
|
||||
if name.startswith("ssh_host_") and "key" in name and not name.endswith(".pub"):
|
||||
return True
|
||||
if (name.endswith(".key") or name.endswith(".pem")) and not name.endswith(".pub"):
|
||||
return True
|
||||
return False
|
||||
|
||||
class SnapshotArchiver:
|
||||
|
||||
@@ -105,16 +105,61 @@ class SystemInspector:
|
||||
"subgid": subgids
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def parse_lsblk_json(out: str) -> List[Dict[str, Any]]:
|
||||
"""Parse JSON output from lsblk -J."""
|
||||
if not out.strip():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(out)
|
||||
return data.get("blockdevices", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def parse_df_output(out: str) -> List[Dict[str, str]]:
|
||||
"""Parse columnized output from df -hT."""
|
||||
mount_points = []
|
||||
for line in out.splitlines()[1:]:
|
||||
parts = line.split()
|
||||
if len(parts) >= 7:
|
||||
mount_points.append({
|
||||
"device": parts[0],
|
||||
"fstype": parts[1],
|
||||
"size": parts[2],
|
||||
"used": parts[3],
|
||||
"avail": parts[4],
|
||||
"percent": parts[5],
|
||||
"mount": parts[6]
|
||||
})
|
||||
return mount_points
|
||||
|
||||
@staticmethod
|
||||
def parse_ip_a(out: str) -> List[Dict[str, Any]]:
|
||||
"""Parse JSON output from ip -j a."""
|
||||
if not out.strip():
|
||||
return []
|
||||
try:
|
||||
return json.loads(out)
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def parse_ip_r(out: str) -> List[Dict[str, Any]]:
|
||||
"""Parse JSON output from ip -j r."""
|
||||
if not out.strip():
|
||||
return []
|
||||
try:
|
||||
return json.loads(out)
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
def inspect_storage(self, fstab_path: str = "/etc/fstab") -> StorageState:
|
||||
"""Inspect storage topology: lsblk block devices, df mounts, LVM, and fstab."""
|
||||
block_devices = []
|
||||
rc, out = self._run_cmd(["lsblk", "-J", "-o", "NAME,SIZE,TYPE,MOUNTPOINT,FSTYPE,UUID"])
|
||||
if rc == 0 and out.strip():
|
||||
try:
|
||||
data = json.loads(out)
|
||||
block_devices = data.get("blockdevices", [])
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
if rc == 0:
|
||||
block_devices = self.parse_lsblk_json(out)
|
||||
if not block_devices:
|
||||
# Fallback plain lsblk
|
||||
rc, out = self._run_cmd(["lsblk", "-l", "-o", "NAME,SIZE,TYPE,MOUNTPOINT"])
|
||||
@@ -128,19 +173,7 @@ class SystemInspector:
|
||||
mount_points = []
|
||||
rc, out = self._run_cmd(["df", "-hT"])
|
||||
if rc == 0:
|
||||
lines = out.splitlines()
|
||||
for line in lines[1:]:
|
||||
parts = line.split()
|
||||
if len(parts) >= 7:
|
||||
mount_points.append({
|
||||
"device": parts[0],
|
||||
"fstype": parts[1],
|
||||
"size": parts[2],
|
||||
"used": parts[3],
|
||||
"avail": parts[4],
|
||||
"percent": parts[5],
|
||||
"mount": parts[6]
|
||||
})
|
||||
mount_points = self.parse_df_output(out)
|
||||
|
||||
# LVM Inspection if tools exist
|
||||
lvm_pvs, lvm_vgs, lvm_lvs = None, None, None
|
||||
@@ -187,34 +220,26 @@ class SystemInspector:
|
||||
"""Inspect network interfaces, IP routes, and DNS resolvers."""
|
||||
interfaces = []
|
||||
rc, out = self._run_cmd(["ip", "-j", "a"])
|
||||
if rc == 0 and out.strip():
|
||||
try:
|
||||
raw_ifaces = json.loads(out)
|
||||
for item in raw_ifaces:
|
||||
interfaces.append({
|
||||
"name": item.get("ifname", ""),
|
||||
"flags": item.get("flags", []),
|
||||
"addresses": [
|
||||
f"{a.get('local')}/{a.get('prefixlen')}"
|
||||
for a in item.get("addr_info", []) if "local" in a
|
||||
]
|
||||
})
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
if rc == 0:
|
||||
for item in self.parse_ip_a(out):
|
||||
interfaces.append({
|
||||
"name": item.get("ifname", ""),
|
||||
"flags": item.get("flags", []),
|
||||
"addresses": [
|
||||
f"{a.get('local')}/{a.get('prefixlen')}"
|
||||
for a in item.get("addr_info", []) if "local" in a
|
||||
]
|
||||
})
|
||||
|
||||
routes = []
|
||||
rc, out = self._run_cmd(["ip", "-j", "r"])
|
||||
if rc == 0 and out.strip():
|
||||
try:
|
||||
raw_routes = json.loads(out)
|
||||
for r in raw_routes:
|
||||
routes.append({
|
||||
"dst": r.get("dst", ""),
|
||||
"gateway": r.get("gateway", ""),
|
||||
"dev": r.get("dev", "")
|
||||
})
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
if rc == 0:
|
||||
for r in self.parse_ip_r(out):
|
||||
routes.append({
|
||||
"dst": r.get("dst", ""),
|
||||
"gateway": r.get("gateway", ""),
|
||||
"dev": r.get("dev", "")
|
||||
})
|
||||
|
||||
dns_servers = []
|
||||
if os.path.isfile(resolv_path):
|
||||
@@ -291,7 +316,7 @@ class SystemInspector:
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
def dump_meta_files(self, meta_dir: str) -> Dict[str, str]:
|
||||
def dump_meta_files(self, meta_dir: str, packages: Optional[List[PackageItem]] = None) -> Dict[str, str]:
|
||||
"""
|
||||
Dump all telemetry command outputs and structured JSON into meta_dir.
|
||||
Returns a mapping of archive relative path to host absolute path.
|
||||
@@ -300,7 +325,8 @@ class SystemInspector:
|
||||
files_map: Dict[str, str] = {}
|
||||
|
||||
# 1. Packages
|
||||
packages = self.inspect_packages()
|
||||
if packages is None:
|
||||
packages = self.inspect_packages()
|
||||
pkg_path = os.path.join(meta_dir, "packages.txt")
|
||||
with open(pkg_path, "w", encoding="utf-8") as f:
|
||||
for p in packages:
|
||||
|
||||
@@ -28,6 +28,10 @@ SENSITIVE_NETWORK_PREFIXES = (
|
||||
"/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):
|
||||
|
||||
@@ -12,18 +12,10 @@ class DpkgPackageManager(BasePackageManager):
|
||||
def get_manager_name(self) -> str:
|
||||
return "dpkg-query"
|
||||
|
||||
def list_packages(self) -> List[PackageItem]:
|
||||
"""List installed packages via dpkg-query."""
|
||||
cmd = ["dpkg-query", "-W", "-f=${Package}|${Version}|${Architecture}\n"]
|
||||
try:
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
|
||||
if res.returncode != 0:
|
||||
return []
|
||||
except (OSError, FileNotFoundError):
|
||||
return []
|
||||
|
||||
def parse_package_output(self, output: str) -> List[PackageItem]:
|
||||
"""Parse raw dpkg-query stdout into a sorted list of PackageItem instances."""
|
||||
packages: List[PackageItem] = []
|
||||
for line in res.stdout.splitlines():
|
||||
for line in output.splitlines():
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
@@ -36,3 +28,14 @@ class DpkgPackageManager(BasePackageManager):
|
||||
|
||||
packages.sort(key=lambda p: p.name)
|
||||
return packages
|
||||
|
||||
def list_packages(self) -> List[PackageItem]:
|
||||
"""List installed packages via dpkg-query."""
|
||||
cmd = ["dpkg-query", "-W", "-f=${Package}|${Version}|${Architecture}\n"]
|
||||
try:
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
|
||||
if res.returncode != 0:
|
||||
return []
|
||||
return self.parse_package_output(res.stdout)
|
||||
except (OSError, FileNotFoundError):
|
||||
return []
|
||||
@@ -12,18 +12,10 @@ class PacmanPackageManager(BasePackageManager):
|
||||
def get_manager_name(self) -> str:
|
||||
return "pacman"
|
||||
|
||||
def list_packages(self) -> List[PackageItem]:
|
||||
"""List installed packages via pacman -Q."""
|
||||
cmd = ["pacman", "-Q"]
|
||||
try:
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
|
||||
if res.returncode != 0:
|
||||
return []
|
||||
except (OSError, FileNotFoundError):
|
||||
return []
|
||||
|
||||
def parse_package_output(self, output: str) -> List[PackageItem]:
|
||||
"""Parse raw pacman -Q stdout into a sorted list of PackageItem instances."""
|
||||
packages: List[PackageItem] = []
|
||||
for line in res.stdout.splitlines():
|
||||
for line in output.splitlines():
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
@@ -35,3 +27,14 @@ class PacmanPackageManager(BasePackageManager):
|
||||
|
||||
packages.sort(key=lambda p: p.name)
|
||||
return packages
|
||||
|
||||
def list_packages(self) -> List[PackageItem]:
|
||||
"""List installed packages via pacman -Q."""
|
||||
cmd = ["pacman", "-Q"]
|
||||
try:
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
|
||||
if res.returncode != 0:
|
||||
return []
|
||||
return self.parse_package_output(res.stdout)
|
||||
except (OSError, FileNotFoundError):
|
||||
return []
|
||||
@@ -12,18 +12,10 @@ class RpmPackageManager(BasePackageManager):
|
||||
def get_manager_name(self) -> str:
|
||||
return "rpm"
|
||||
|
||||
def list_packages(self) -> List[PackageItem]:
|
||||
"""List installed packages via rpm query."""
|
||||
cmd = ["rpm", "-qa", "--qf", "%{NAME}|%{VERSION}-%{RELEASE}|%{ARCH}\n"]
|
||||
try:
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
|
||||
if res.returncode != 0:
|
||||
return []
|
||||
except (OSError, FileNotFoundError):
|
||||
return []
|
||||
|
||||
def parse_package_output(self, output: str) -> List[PackageItem]:
|
||||
"""Parse raw rpm query stdout into a sorted list of PackageItem instances."""
|
||||
packages: List[PackageItem] = []
|
||||
for line in res.stdout.splitlines():
|
||||
for line in output.splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("("):
|
||||
continue
|
||||
@@ -36,3 +28,14 @@ class RpmPackageManager(BasePackageManager):
|
||||
|
||||
packages.sort(key=lambda p: p.name)
|
||||
return packages
|
||||
|
||||
def list_packages(self) -> List[PackageItem]:
|
||||
"""List installed packages via rpm query."""
|
||||
cmd = ["rpm", "-qa", "--qf", "%{NAME}|%{VERSION}-%{RELEASE}|%{ARCH}\n"]
|
||||
try:
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
|
||||
if res.returncode != 0:
|
||||
return []
|
||||
return self.parse_package_output(res.stdout)
|
||||
except (OSError, FileNotFoundError):
|
||||
return []
|
||||
Reference in new issue
Block a user