Files
soda64 4b3346fd74
Test, Lint and Security Gate / Security Scan and Quality Audits (push) Failing after 8s
Test, Lint and Security Gate / Unit & Security Tests (Coverage >= 80%) (push) Has been skipped
Build and Publish Release / Build Packages and Publish (push) Successful in 1m31s
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
2026-10-23 22:08:15 +02:00

206 lines
8.8 KiB
Python

"""Security tests (AppSec verification):
- Zip Slip / Path Traversal prevention
- Root privilege boundary enforcement (EXIT_PERMISSION_DENIED)
- Cryptographic SHA-256 integrity & anti-tampering
- Sensitive secret sanitization (--sanitize)
- Zero command injection: static AST verification of zero shell=True in subprocess calls
"""
import ast
from contextlib import redirect_stdout, redirect_stderr
import io
import json
import os
import shutil
import tarfile
import tempfile
import unittest
from linux_backuper.cli import main
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.constants import (
EXIT_SUCCESS,
EXIT_PERM_DENIED,
EXIT_CORRUPTED,
EXIT_DRY_RUN
)
from linux_backuper.core.restore import SafeRestoreEngine, RestorePlan, RestorePlanItem, SecurityError
from linux_backuper.models import SnapshotManifest
from tests.helpers import env_override
class TestSecurityAudit(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp(prefix="test_security_")
self.backup_dir = os.path.join(self.test_dir, "backups")
os.makedirs(self.backup_dir, exist_ok=True)
self.mock_root = os.path.join(self.test_dir, "sandbox_root")
self.mock_etc = os.path.join(self.mock_root, "etc")
os.makedirs(self.mock_etc, exist_ok=True)
with open(os.path.join(self.mock_etc, "hosts"), "w") as f:
f.write("127.0.0.1 localhost\n")
def tearDown(self):
shutil.rmtree(self.test_dir, ignore_errors=True)
def test_path_traversal_zip_slip_blocked(self):
"""Verify that attempting to restore files outside target_root triggers SecurityError."""
archiver = SnapshotArchiver(target_dir=self.backup_dir)
dummy_f = os.path.join(self.mock_etc, "hosts")
entries, sha, uncomp, _ = archiver.collect_file_list([dummy_f])
manifest = SnapshotManifest(
schema_version="1.0",
snapshot_id="snap_malicious",
created_at="2026-10-23T12:00:00Z",
hostname="host",
profile="quick",
compression="gzip",
os={},
package_manager="none",
package_count=0,
included_paths=[dummy_f],
stats={"file_count": 1, "uncompressed_bytes": uncomp, "compressed_bytes": 0},
files_sha256=sha
)
archive_path = archiver.create_snapshot_archive("snap_malicious", manifest, entries)
engine = SafeRestoreEngine(target_dir=self.backup_dir)
# Construct a malicious plan that attempts to write outside mock_root to /tmp
malicious_item = RestorePlanItem(
rel_path="data" + dummy_f,
abs_path="/tmp/evil_pwned_file.txt",
action="modify",
reason="malicious overwrite attempt"
)
malicious_plan = RestorePlan(
snapshot_id="snap_malicious",
target_root=self.mock_root,
items=[malicious_item]
)
pid_file = os.path.join(self.test_dir, "test.pid")
with env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
with self.assertRaises(SecurityError):
engine.execute_restore(malicious_plan, force=True, pid_path=pid_file)
# Verify that malicious file was never created
self.assertFalse(os.path.exists("/tmp/evil_pwned_file.txt"))
def test_root_boundary_enforcement(self):
"""Verify that non-root execution without override is strictly denied."""
# Ensure LINUX_BACKUPER_ALLOW_NON_ROOT is completely unset
with env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": ""}):
# Temporarily clear it from environ
if "LINUX_BACKUPER_ALLOW_NON_ROOT" in os.environ:
del os.environ["LINUX_BACKUPER_ALLOW_NON_ROOT"]
# When euid != 0, snapshot must exit with EXIT_PERM_DENIED (4)
if os.geteuid() != 0:
stderr_buf = io.StringIO()
with redirect_stderr(stderr_buf):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
"--paths", self.mock_etc
])
self.assertEqual(exit_code, EXIT_PERM_DENIED)
self.assertIn("requires root privileges", stderr_buf.getvalue())
def test_tampering_sha256_detection(self):
"""Verify that any modification to archive contents fails SHA-256 integrity check."""
stdout = io.StringIO()
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_data = json.loads(stdout.getvalue().strip())
snap_id = snap_data["snapshot_id"]
archive_path = snap_data["archive_path"]
# Valid before tampering
is_valid, _ = SnapshotArchiver.verify_archive(archive_path)
self.assertTrue(is_valid)
# Corrupt bytes in the middle of archive
with open(archive_path, "r+b") as f:
f.seek(50)
f.write(b"CORRUPTED_BYTES_INJECTION")
is_valid, err_msg = SnapshotArchiver.verify_archive(archive_path)
self.assertFalse(is_valid)
self.assertTrue("corrupted" in err_msg.lower() or "failed" in err_msg.lower())
# Verify CLI returns EXIT_CORRUPTED (3)
with redirect_stdout(io.StringIO()):
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
self.assertEqual(exit_code, EXIT_CORRUPTED)
def test_sanitize_redacts_sensitive_keys_and_shadow(self):
"""Verify that --sanitize mode purges shadow hashes and private keys from the snapshot."""
shadow_f = os.path.join(self.mock_etc, "shadow")
with open(shadow_f, "w") as f:
f.write("root:$6$supersecretsalt$hashedpassword:19000:0:99999:7:::\n")
ssh_key_f = os.path.join(self.mock_etc, "id_rsa")
with open(ssh_key_f, "w") as f:
f.write("-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA...\n-----END RSA PRIVATE KEY-----\n")
stdout = io.StringIO()
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
"--paths", self.mock_etc,
"--sanitize",
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
snap_data = json.loads(stdout.getvalue().strip())
archive_path = snap_data["archive_path"]
with tarfile.open(archive_path, "r:gz") as tar:
names = tar.getnames()
# 1. Neither shadow nor id_rsa should exist in data/
self.assertFalse(any("data" in n and "shadow" in n for n in names))
self.assertFalse(any("data" in n and "id_rsa" in n for n in names))
# 2. meta/sanitized.txt must document redacted files
self.assertIn("meta/sanitized.txt", names)
sanitized_txt = tar.extractfile("meta/sanitized.txt").read().decode("utf-8")
self.assertIn("shadow", sanitized_txt)
self.assertIn("id_rsa", sanitized_txt)
def test_zero_command_injection_no_shell_true_in_source(self):
"""Static AST audit verifying that no subprocess invocation in linux_backuper uses shell=True."""
src_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "linux_backuper"))
violations = []
subprocess_funcs = {"run", "Popen", "call", "check_call", "check_output"}
for root, _, files in os.walk(src_root):
for file in files:
if not file.endswith(".py"):
continue
file_path = os.path.join(root, file)
with open(file_path, "r", encoding="utf-8") as f:
tree = ast.parse(f.read(), filename=file_path)
for node in ast.walk(tree):
if isinstance(node, ast.Call):
# Detect subprocess.<func>(..., shell=True)
is_subp = False
if isinstance(node.func, ast.Attribute) and node.func.attr in subprocess_funcs:
if isinstance(node.func.value, ast.Name) and node.func.value.id == "subprocess":
is_subp = True
if is_subp:
for kw in node.keywords:
if kw.arg == "shell":
if isinstance(kw.value, ast.Constant) and kw.value.value is True:
violations.append(f"{file_path}:{node.lineno} shell=True detected!")
self.assertEqual(len(violations), 0, f"Found unsafe shell=True subprocess calls: {violations}")
if __name__ == "__main__":
unittest.main()