Inspect DirectAdmin account backups
This commit is contained in:
1 parent
053fd9907c
commit
6ff77f3aed
4 files changed
+449
No files matched your search
@@ -0,0 +1,248 @@
|
||||
import argparse
|
||||
import gzip
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import tarfile
|
||||
import zlib
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
from .domain_names import canonical_domain
|
||||
from .mail_node import MailboxSpec
|
||||
|
||||
MAX_METADATA_SIZE = 8 * 1024 * 1024
|
||||
ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
|
||||
HOME_ARCHIVES = {"home.tar", "home.tar.gz", "home.tar.zst"}
|
||||
|
||||
|
||||
class BackupTarInfo(tarfile.TarInfo):
|
||||
@classmethod
|
||||
def fromtarfile(cls, archive):
|
||||
try:
|
||||
return super().fromtarfile(archive)
|
||||
except (tarfile.InvalidHeaderError, tarfile.SubsequentHeaderError):
|
||||
raise tarfile.ReadError("Invalid backup tar header.") from None
|
||||
|
||||
|
||||
@dataclass
|
||||
class DomainInventory:
|
||||
website_files: int = 0
|
||||
dns_zone: bool = False
|
||||
mailboxes: set[str] = field(default_factory=set)
|
||||
mail_files: int = 0
|
||||
unrecognized_mailbox_entries: int = 0
|
||||
|
||||
def report(self, name):
|
||||
return {
|
||||
"name": name,
|
||||
"website_files": self.website_files,
|
||||
"dns_zone": self.dns_zone,
|
||||
"mailboxes": sorted(self.mailboxes),
|
||||
"mail_files": self.mail_files,
|
||||
"unrecognized_mailbox_entries": self.unrecognized_mailbox_entries,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class BackupInventory:
|
||||
username: str | None = None
|
||||
primary_domain: str | None = None
|
||||
domains: dict[str, DomainInventory] = field(default_factory=dict)
|
||||
databases: set[str] = field(default_factory=set)
|
||||
home_archive: bool = False
|
||||
skipped_non_regular_entries: int = 0
|
||||
metadata_paths: set[tuple[str, ...]] = field(default_factory=set)
|
||||
|
||||
def domain(self, value):
|
||||
inventory = self.domains.get(value)
|
||||
if inventory is None:
|
||||
inventory = self.domains.setdefault(
|
||||
canonical_domain(value), DomainInventory()
|
||||
)
|
||||
return inventory
|
||||
|
||||
def visit(self, archive, member):
|
||||
path = PurePosixPath(member.name)
|
||||
parts = path.parts
|
||||
if path.is_absolute() or ".." in parts:
|
||||
raise ValueError("The archive contains an unsafe member path.")
|
||||
if not member.isreg():
|
||||
if not member.isdir():
|
||||
self.skipped_non_regular_entries += 1
|
||||
return
|
||||
|
||||
match parts:
|
||||
case ("backup", "user.conf"):
|
||||
settings = read_account_settings(
|
||||
self.read_metadata(archive, member, parts)
|
||||
)
|
||||
self.username = settings["username"]
|
||||
if settings["domain"]:
|
||||
self.primary_domain = canonical_domain(settings["domain"])
|
||||
self.domain(self.primary_domain)
|
||||
case ("backup", "domains.list"):
|
||||
for line in self.read_metadata(archive, member, parts).splitlines():
|
||||
if line.strip():
|
||||
self.domain(line.strip())
|
||||
case ("backup", filename):
|
||||
if match := re.fullmatch(r"([a-zA-Z0-9_]{1,64})\.sql", filename):
|
||||
self.databases.add(match[1])
|
||||
if filename in HOME_ARCHIVES:
|
||||
self.home_archive = True
|
||||
case ("backup", domain, filename) if filename == f"{domain}.db":
|
||||
self.domain(domain).dns_zone = True
|
||||
case ("backup", domain, filename) if filename == f"{domain}.conf":
|
||||
self.domain(domain)
|
||||
case ("backup", domain, "email", "passwd"):
|
||||
lines = self.read_metadata(archive, member, parts)
|
||||
self.visit_mailboxes(domain, lines)
|
||||
case ("backup", domain, "email", "data", "imap", *tail) if (
|
||||
tail and tail != [".direct_imap_backup"]
|
||||
):
|
||||
self.domain(domain).mail_files += 1
|
||||
case ("domains", domain, "public_html" | "private_html", *tail) if tail:
|
||||
self.domain(domain).website_files += 1
|
||||
case ("domains", domain, "domain.conf"):
|
||||
self.domain(domain)
|
||||
case ("imap", domain, *tail) if tail:
|
||||
self.domain(domain).mail_files += 1
|
||||
|
||||
def read_metadata(self, archive, member, parts):
|
||||
if parts in self.metadata_paths:
|
||||
raise ValueError(
|
||||
"The archive contains duplicate account or mailbox metadata."
|
||||
)
|
||||
self.metadata_paths.add(parts)
|
||||
if not 0 <= member.size <= MAX_METADATA_SIZE:
|
||||
raise ValueError(
|
||||
"An account or mailbox metadata file exceeds the size limit."
|
||||
)
|
||||
with archive.extractfile(member) as stream:
|
||||
return stream.read().decode("utf-8", errors="replace")
|
||||
|
||||
def visit_mailboxes(self, domain, text):
|
||||
inventory = self.domain(domain)
|
||||
for line in text.splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
local_part, separator, _ = line.partition(":")
|
||||
try:
|
||||
if not separator:
|
||||
raise ValueError
|
||||
mailbox = MailboxSpec(domain, local_part)
|
||||
except ValueError:
|
||||
inventory.unrecognized_mailbox_entries += 1
|
||||
else:
|
||||
inventory.mailboxes.add(mailbox.address)
|
||||
|
||||
def report(self):
|
||||
if self.username is None:
|
||||
raise ValueError(
|
||||
"Expected a DirectAdmin account backup with backup/user.conf."
|
||||
)
|
||||
return {
|
||||
"version": 1,
|
||||
"kind": "directadmin_backup_inventory",
|
||||
"username": self.username,
|
||||
"primary_domain": self.primary_domain,
|
||||
"domains": [
|
||||
inventory.report(name)
|
||||
for name, inventory in sorted(self.domains.items())
|
||||
],
|
||||
"databases": sorted(self.databases),
|
||||
"home_archive": self.home_archive,
|
||||
"skipped_non_regular_entries": self.skipped_non_regular_entries,
|
||||
}
|
||||
|
||||
|
||||
def read_account_settings(text):
|
||||
settings = {}
|
||||
for line in text.splitlines():
|
||||
key, separator, value = line.partition("=")
|
||||
if separator and key in {"username", "domain"}:
|
||||
if key in settings:
|
||||
raise ValueError("The account metadata repeats an identity field.")
|
||||
settings[key] = value.strip()
|
||||
username = settings.get("username", "")
|
||||
if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}", username):
|
||||
raise ValueError(
|
||||
"The account metadata is missing a valid DirectAdmin username."
|
||||
)
|
||||
return {"username": username, "domain": settings.get("domain")}
|
||||
|
||||
|
||||
@contextmanager
|
||||
def archive_stream(path):
|
||||
with path.open("rb", buffering=0) as source:
|
||||
magic = source.read(4)
|
||||
source.seek(0)
|
||||
if magic.startswith(b"\x1f\x8b"):
|
||||
with gzip.GzipFile(fileobj=source) as stream:
|
||||
yield stream
|
||||
elif magic == ZSTD_MAGIC:
|
||||
try:
|
||||
decoder = subprocess.Popen(
|
||||
["zstd", "--decompress", "--stdout", "--quiet"],
|
||||
stdin=source,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
raise ValueError("Install zstd to inspect Zstandard backups.") from None
|
||||
with decoder:
|
||||
try:
|
||||
yield decoder.stdout
|
||||
except BaseException:
|
||||
decoder.kill()
|
||||
raise
|
||||
if decoder.wait():
|
||||
raise ValueError("The Zstandard backup is damaged or incomplete.")
|
||||
else:
|
||||
yield source
|
||||
|
||||
|
||||
def check_tar_padding(archive):
|
||||
size = 0
|
||||
while chunk := archive.fileobj.read(64 * 1024):
|
||||
if chunk.strip(b"\0"):
|
||||
raise ValueError("Unexpected data after the end of the tar archive.")
|
||||
size += len(chunk)
|
||||
if size < tarfile.BLOCKSIZE:
|
||||
raise ValueError("The tar archive is missing its end marker.")
|
||||
|
||||
|
||||
def inspect_backup(path):
|
||||
inventory = BackupInventory()
|
||||
try:
|
||||
with (
|
||||
archive_stream(path) as stream,
|
||||
tarfile.open(fileobj=stream, mode="r|", tarinfo=BackupTarInfo) as archive,
|
||||
):
|
||||
while (member := archive.next()) is not None:
|
||||
inventory.visit(archive, member)
|
||||
# The reader only walks forward and does not need tarfile's member cache.
|
||||
archive.members.clear()
|
||||
check_tar_padding(archive)
|
||||
except (EOFError, tarfile.TarError, zlib.error, gzip.BadGzipFile):
|
||||
raise ValueError(
|
||||
"The backup is not a readable or complete tar archive."
|
||||
) from None
|
||||
return inventory.report()
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(prog="coulobre-directadmin")
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
inspect = commands.add_parser(
|
||||
"inspect", help="Inventory a DirectAdmin account backup."
|
||||
)
|
||||
inspect.add_argument("backup", type=Path)
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
report = inspect_backup(args.backup)
|
||||
except (OSError, ValueError) as error:
|
||||
parser.exit(1, f"coulobre-directadmin: {error}\n")
|
||||
print(json.dumps(report, indent=2))
|
||||
return 0
|
||||
@@ -0,0 +1,175 @@
|
||||
import gzip
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from io import BytesIO, StringIO
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from unittest import skipUnless
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.test import SimpleTestCase
|
||||
|
||||
from coulobre.directadmin import inspect_backup, main
|
||||
|
||||
|
||||
def make_tar(entries):
|
||||
output = BytesIO()
|
||||
with tarfile.open(fileobj=output, mode="w") as archive:
|
||||
for name, payload in entries:
|
||||
member = tarfile.TarInfo(name)
|
||||
if payload is None:
|
||||
member.type = tarfile.SYMTYPE
|
||||
member.linkname = "public_html"
|
||||
archive.addfile(member)
|
||||
else:
|
||||
data = payload.encode("utf-8")
|
||||
member.size = len(data)
|
||||
archive.addfile(member, BytesIO(data))
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
class DirectAdminInventoryTests(SimpleTestCase):
|
||||
def setUp(self):
|
||||
self.directory = Path(self.enterContext(TemporaryDirectory()))
|
||||
self.entries = [
|
||||
(
|
||||
"./backup/user.conf",
|
||||
"username=customer\npassword=private-account-hash\ndomain=Bücher.Example\n",
|
||||
),
|
||||
("backup/domains.list", "bücher.example\n"),
|
||||
("backup/other.example/other.example.conf", "domain=other.example\n"),
|
||||
(
|
||||
"backup/xn--bcher-kva.example/email/passwd",
|
||||
"Support:private-mail-hash:10\nold.value+tag:other-private-hash:10\n",
|
||||
),
|
||||
("backup/xn--bcher-kva.example/xn--bcher-kva.example.db", "; DNS zone"),
|
||||
("backup/customer_wp.sql", "private database content"),
|
||||
("backup/home.tar.gz", "nested home archive content"),
|
||||
(
|
||||
"domains/xn--bcher-kva.example/public_html/index.php",
|
||||
"private website content",
|
||||
),
|
||||
("domains/xn--bcher-kva.example/private_html", None),
|
||||
("imap/xn--bcher-kva.example/support/Maildir/cur/message", "private email"),
|
||||
("backup/other.example/email/data/imap/Maildir/cur/message", "old Maildir"),
|
||||
("backup/other.example/email/data/imap/.direct_imap_backup", ""),
|
||||
]
|
||||
|
||||
def save(self, content, name="user.admin.customer.tar"):
|
||||
path = self.directory / name
|
||||
path.write_bytes(content)
|
||||
return path
|
||||
|
||||
def test_inventory_describes_contents_without_emitting_private_payloads(self):
|
||||
path = self.save(
|
||||
gzip.compress(make_tar(self.entries)), "user.admin.customer.tar.gz"
|
||||
)
|
||||
output = self.enterContext(redirect_stdout(StringIO()))
|
||||
|
||||
self.assertEqual(main(["inspect", str(path)]), 0)
|
||||
|
||||
report = json.loads(output.getvalue())
|
||||
self.assertEqual(report["username"], "customer")
|
||||
self.assertEqual(report["primary_domain"], "xn--bcher-kva.example")
|
||||
self.assertEqual(report["databases"], ["customer_wp"])
|
||||
self.assertTrue(report["home_archive"])
|
||||
self.assertEqual(report["skipped_non_regular_entries"], 1)
|
||||
self.assertEqual(
|
||||
report["domains"],
|
||||
[
|
||||
{
|
||||
"name": "other.example",
|
||||
"website_files": 0,
|
||||
"dns_zone": False,
|
||||
"mailboxes": [],
|
||||
"mail_files": 1,
|
||||
"unrecognized_mailbox_entries": 0,
|
||||
},
|
||||
{
|
||||
"name": "xn--bcher-kva.example",
|
||||
"website_files": 1,
|
||||
"dns_zone": True,
|
||||
"mailboxes": ["support@xn--bcher-kva.example"],
|
||||
"mail_files": 1,
|
||||
"unrecognized_mailbox_entries": 1,
|
||||
},
|
||||
],
|
||||
)
|
||||
self.assertNotIn("private", output.getvalue())
|
||||
self.assertEqual(list(self.directory.iterdir()), [path])
|
||||
|
||||
def test_plain_tar_allows_a_backup_with_only_account_metadata(self):
|
||||
path = self.save(make_tar([("backup/user.conf", "username=mailadmin\n")]))
|
||||
|
||||
report = inspect_backup(path)
|
||||
|
||||
self.assertEqual(report["username"], "mailadmin")
|
||||
self.assertIsNone(report["primary_domain"])
|
||||
self.assertEqual(report["domains"], [])
|
||||
|
||||
@skipUnless(shutil.which("zstd"), "zstd is required for Zstandard fixtures")
|
||||
def test_zstandard_stream_uses_the_same_inventory_and_rejects_truncation(self):
|
||||
tar = make_tar(self.entries)
|
||||
compressed = subprocess.run(
|
||||
["zstd", "--stdout", "--quiet"], input=tar, capture_output=True, check=True
|
||||
).stdout
|
||||
path = self.save(compressed, "user.admin.customer.tar.zst")
|
||||
self.assertEqual(inspect_backup(path), inspect_backup(self.save(tar)))
|
||||
path.write_bytes(compressed[:-1])
|
||||
with self.assertRaisesRegex(ValueError, "backup|archive"):
|
||||
inspect_backup(path)
|
||||
|
||||
def test_archive_requires_regular_and_unambiguous_account_metadata(self):
|
||||
for entries, problem in (
|
||||
([("backup/user.conf", None)], "Expected a DirectAdmin account backup"),
|
||||
(
|
||||
[*self.entries, ("backup/user.conf", "username=other\n")],
|
||||
"duplicate account or mailbox metadata",
|
||||
),
|
||||
):
|
||||
with (
|
||||
self.subTest(problem=problem),
|
||||
self.assertRaisesRegex(ValueError, problem),
|
||||
):
|
||||
inspect_backup(self.save(make_tar(entries)))
|
||||
|
||||
def test_rejects_oversized_metadata_without_printing_it(self):
|
||||
path = self.save(make_tar(self.entries))
|
||||
with (
|
||||
patch("coulobre.directadmin.MAX_METADATA_SIZE", 4),
|
||||
self.assertRaisesRegex(ValueError, "metadata file exceeds the size limit"),
|
||||
):
|
||||
inspect_backup(path)
|
||||
|
||||
def test_truncated_gzip_fails_before_emitting_an_inventory(self):
|
||||
path = self.save(gzip.compress(make_tar(self.entries))[:-4])
|
||||
output = self.enterContext(redirect_stdout(StringIO()))
|
||||
errors = self.enterContext(redirect_stderr(StringIO()))
|
||||
|
||||
with self.assertRaises(SystemExit) as exit:
|
||||
main(["inspect", str(path)])
|
||||
|
||||
self.assertEqual(exit.exception.code, 1)
|
||||
self.assertEqual(output.getvalue(), "")
|
||||
self.assertIn("not a readable or complete tar archive", errors.getvalue())
|
||||
self.assertNotIn("private", errors.getvalue())
|
||||
|
||||
def test_plain_tar_requires_its_end_marker(self):
|
||||
archive = make_tar([("backup/user.conf", "username=customer\n")])
|
||||
self.assertGreater(len(archive), 3 * tarfile.BLOCKSIZE)
|
||||
path = self.save(archive[: 3 * tarfile.BLOCKSIZE])
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "missing its end marker"):
|
||||
inspect_backup(path)
|
||||
|
||||
def test_invalid_header_does_not_end_an_otherwise_readable_tar(self):
|
||||
archive = bytearray(make_tar([("backup/user.conf", "username=customer\n")]))
|
||||
archive[2 * tarfile.BLOCKSIZE] = ord("x")
|
||||
|
||||
with self.assertRaisesRegex(
|
||||
ValueError, "not a readable or complete tar archive"
|
||||
):
|
||||
inspect_backup(self.save(archive))
|
||||
Reference in new issue
Block a user