Python module to handle tarfile backups.
Actively maintained. Last release 7 weeks ago, commits in 15 of the last 26 weeks. A safe choice.
pip install securetarSecure Tar
Secure Tarfile library
SecureTar is a streaming wrapper around Python's tarfile module. It
creates and reads tar archives that contain inner tar files, which can be
encrypted. It is the archive format used for Home Assistant backups.
Archive layout
A SecureTar archive is a plain, uncompressed outer tar in PAX format. Its
members are either inner tar files, optionally gzip compressed and optionally
encrypted, or plain metadata files such as backup.json that are added to
the outer tar directly.
Encrypted inner tar files start with a SecureTar header followed by the ciphertext. Two header versions can be written:
| Version | Cipher | Key derivation |
|---|---|---|
| 2 | AES-128-CBC | 100 rounds of SHA-256 (legacy) |
| 3 | XChaCha20-Poly1305 secretstream | Argon2id, per-file BLAKE2b subkeys |
Version 3 is the default. It authenticates the data, detects truncation, and allows the password to be checked without decrypting the whole file. Version 1 (AES-128-CBC without a header) can still be read.
Creating an archive
from pathlib import Path
from securetar import SecureTarArchive, atomic_contents_add
with SecureTarArchive(Path("backup.tar"), "w", password="hunter2") as archive:
with archive.create_tar("./homeassistant.tar.gz", gzip=True) as inner_tar:
atomic_contents_add(
inner_tar,
Path("/config"),
file_filter=lambda path: path.name == "home-assistant.log",
arcname=".",
)
with archive.create_tar("./share.tar.gz", gzip=True) as inner_tar:
atomic_contents_add(
inner_tar,
Path("/share"),
file_filter=lambda _: False,
arcname=".",
)
create_tar returns a context manager that yields a regular
tarfile.TarFile. Everything written to it is streamed into the outer tar;
no temporary files are needed. The inner tar is encrypted when the archive was
opened with a password or a root_key_context. Leave both out to create a
plain archive.
atomic_contents_add recursively adds a directory. The file_filter
callback receives the archive-relative PurePath of each item and returns
True to exclude it. Errors while adding a file raise AddFileError, which
carries the offending path.
Pass create_version=2 to to write the legacy AES format.