pax_global_header00006660000000000000000000000064147573503360014527gustar00rootroot0000000000000052 comment=1ae56fc99ede42d3c57fb640507d1e784e6954ff pvizeli-securetar-1ae56fc/000077500000000000000000000000001475735033600157005ustar00rootroot00000000000000pvizeli-securetar-1ae56fc/.devcontainer/000077500000000000000000000000001475735033600204375ustar00rootroot00000000000000pvizeli-securetar-1ae56fc/.devcontainer/Dockerfile000066400000000000000000000025331475735033600224340ustar00rootroot00000000000000# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.217.4/containers/python-3/.devcontainer/base.Dockerfile # [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.10, 3.9, 3.8, 3.7, 3.6, 3-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3.7-bullseye, 3.6-bullseye, 3-buster, 3.10-buster, 3.9-buster, 3.8-buster, 3.7-buster, 3.6-buster ARG VARIANT="3.10-bullseye" FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 ARG NODE_VERSION="none" RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi # [Optional] If your pip requirements rarely change, uncomment this section to add them to the image. # COPY requirements.txt /tmp/pip-tmp/ # RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ # && rm -rf /tmp/pip-tmp # [Optional] Uncomment this section to install additional OS packages. # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ # && apt-get -y install --no-install-recommends # [Optional] Uncomment this line to install global node packages. # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1pvizeli-securetar-1ae56fc/.devcontainer/devcontainer.json000066400000000000000000000036161475735033600240210ustar00rootroot00000000000000// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: // https://github.com/microsoft/vscode-dev-containers/tree/v0.217.4/containers/python-3 { "name": "Python 3", "build": { "dockerfile": "Dockerfile", "context": "..", "args": { // Update 'VARIANT' to pick a Python version: 3, 3.10, 3.9, 3.8, 3.7, 3.6 // Append -bullseye or -buster to pin to an OS version. // Use -bullseye variants on local on arm64/Apple Silicon. "VARIANT": "3.9", // Options "NODE_VERSION": "lts/*" } }, // Set *default* container specific settings.json values on container create. "settings": { "python.defaultInterpreterPath": "/usr/local/bin/python", "python.linting.enabled": true, "python.linting.pylintEnabled": true, "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8", "python.formatting.blackPath": "/usr/local/py-utils/bin/black", "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf", "python.linting.banditPath": "/usr/local/py-utils/bin/bandit", "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8", "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy", "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle", "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle", "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint" }, // Add the IDs of extensions you want installed when the container is created. "extensions": [ "ms-python.python", "ms-python.vscode-pylance" ], // Use 'forwardPorts' to make a list of ports inside the container available locally. // "forwardPorts": [], // Use 'postCreateCommand' to run commands after the container is created. // "postCreateCommand": "pip3 install --user -r requirements.txt", // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. "remoteUser": "vscode" } pvizeli-securetar-1ae56fc/.github/000077500000000000000000000000001475735033600172405ustar00rootroot00000000000000pvizeli-securetar-1ae56fc/.github/dependabot.yml000066400000000000000000000001751475735033600220730ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: pip directory: "/" schedule: interval: daily open-pull-requests-limit: 10 pvizeli-securetar-1ae56fc/.github/release-drafter.yml000066400000000000000000000000541475735033600230270ustar00rootroot00000000000000template: | ## What's Changed $CHANGES pvizeli-securetar-1ae56fc/.github/workflows/000077500000000000000000000000001475735033600212755ustar00rootroot00000000000000pvizeli-securetar-1ae56fc/.github/workflows/pythonpublish.yml000066400000000000000000000014601475735033600247310ustar00rootroot00000000000000# This workflows will upload a Python Package using Twine when a release is created # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries name: Upload Python Package on: release: types: [published] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v1 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install build twine - name: Build and publish env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} run: | python -m build twine upload dist/* pvizeli-securetar-1ae56fc/.github/workflows/release-drafter.yml000066400000000000000000000005061475735033600250660ustar00rootroot00000000000000name: Release Drafter on: push: branches: - main jobs: update_release_draft: runs-on: ubuntu-latest steps: # Drafts your next Release notes as Pull Requests are merged into "master" - uses: release-drafter/release-drafter@v5 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} pvizeli-securetar-1ae56fc/.github/workflows/test.yml000066400000000000000000000020361475735033600230000ustar00rootroot00000000000000# This workflow will install Python dependencies, run tests and lint with a single version of Python # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: Run Tests on: push: branches: [main] pull_request: branches: [main] jobs: test: runs-on: ubuntu-latest strategy: matrix: python-version: ["3.10", "3.11", "3.12", "3.13"] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | pip install -r requirements.txt pip install -r requirements-test.txt pip install -e . - name: Lint with flake8 run: | flake8 securetar tests - name: Check formatting with black run: | black securetar tests --check - name: Run tests run: | pytest tests pvizeli-securetar-1ae56fc/.gitignore000066400000000000000000000034071475735033600176740ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ pvizeli-securetar-1ae56fc/LICENSE000066400000000000000000000261351475735033600167140ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. pvizeli-securetar-1ae56fc/MANIFEST.in000066400000000000000000000001501475735033600174320ustar00rootroot00000000000000include README.md include requirements.txt include LICENSE graft securetar recursive-exclude * *.py[co] pvizeli-securetar-1ae56fc/README.md000066400000000000000000000031261475735033600171610ustar00rootroot00000000000000# Secure Tar Secure Tarfile library It's a streaming wrapper around python tarfile and allow secure handling files and support encryption. ```python from securetar import SecureTarFile, atomic_contents_add from pathlib import Path path_to_add = Path(".") with SecureTarFile("test.tar", "w") as tar_file: atomic_contents_add( tar_file, path_to_add, file_filter=lambda _: False, arcname=".", ) with SecureTarFile("test.tar", "w", b"AES128_KEY_SIZE") as tar_file: atomic_contents_add( tar_file, path_to_add, file_filter=lambda _: False, arcname=".", ) ``` A common pattern is to create an outer uncompressed tarfile that contains a variety of inner tar files. This can be accomplished without writing out multiple files with the following pattern. ```python from securetar import SecureTarFile, atomic_contents_add from pathlib import Path path_1 = Path("path1") path_2 = Path("path2") outer_secure_tar_file = SecureTarFile("pkg.tar", "w", gzip=False) with outer_secure_tar_file as outer_tar_file: with outer_secure_tar_file.create_inner_tar( "./backup1.tar.gz", gzip=True ) as inner_tar_file: atomic_contents_add( inner_tar_file, path_1, file_filter=lambda _: False, arcname=".", ) with outer_secure_tar_file.create_inner_tar( "./backup2.tar.gz", gzip=True ) as inner_tar_file: atomic_contents_add( inner_tar_file, path_2, file_filter=lambda _: False, arcname=".", ) ``` pvizeli-securetar-1ae56fc/pyproject.toml000066400000000000000000000014771475735033600206250ustar00rootroot00000000000000[build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [project] name = "securetar" version = "2025.2.1" license = {text = "Apache-2.0"} description = "Python module to handle tarfile backups." readme = "README.md" authors = [{name = "Pascal Vizeli", email = "pvizeli@syshack.ch"}] classifiers = [ "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ] requires-python = ">=3.10.0" dynamic = ["dependencies"] [project.urls] Homepage = "https://github.com/pvizeli/securetar" [tool.setuptools.dynamic] dependencies = {file = "requirements.txt"} [tool.setuptools.packages.find] include = ["securetar*"] pvizeli-securetar-1ae56fc/requirements-test.txt000066400000000000000000000000521475735033600221360ustar00rootroot00000000000000flake8==7.1.2 black==25.1.0 pytest==8.3.4 pvizeli-securetar-1ae56fc/requirements.txt000066400000000000000000000000151475735033600211600ustar00rootroot00000000000000cryptography pvizeli-securetar-1ae56fc/securetar/000077500000000000000000000000001475735033600176755ustar00rootroot00000000000000pvizeli-securetar-1ae56fc/securetar/__init__.py000066400000000000000000000511641475735033600220150ustar00rootroot00000000000000"""Tarfile fileobject handler for encrypted files.""" from __future__ import annotations from collections.abc import Callable, Generator import enum import hashlib import logging import os import tarfile import time from contextlib import contextmanager from pathlib import Path, PurePath from typing import Any, IO, BinaryIO from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import padding from cryptography.hazmat.primitives.ciphers import ( Cipher, CipherContext, algorithms, modes, ) _LOGGER: logging.Logger = logging.getLogger(__name__) BLOCK_SIZE = 16 BLOCK_SIZE_BITS = 128 IV_SIZE = BLOCK_SIZE DEFAULT_BUFSIZE = 10240 SECURETAR_MAGIC = b"SecureTar\x02\x00\x00\x00\x00\x00\x00" SECURETAR_HEADER_SIZE = len(SECURETAR_MAGIC) + 16 GZIP_MAGIC_BYTES = b"\x1f\x8b\x08" TAR_MAGIC_BYTES = b"ustar" TAR_MAGIC_OFFSET = 257 MOD_READ = "r" MOD_WRITE = "w" class CipherMode(enum.Enum): """Cipher mode.""" ENCRYPT = 1 DECRYPT = 2 class SecureTarHeader: """SecureTar header. Reads and produces the SecureTar header. Also accepts the magic-less format used in earlier releases of SecureTar. """ def __init__(self, cbc_rand: bytes, plaintext_size: int | None) -> None: """Initialize SecureTar header.""" self.cbc_rand = cbc_rand self.plaintext_size = plaintext_size @classmethod def from_bytes(cls, f: IO[bytes]) -> SecureTarHeader: """Return header bytes.""" header = f.read(len(SECURETAR_MAGIC)) plaintext_size: int | None = None if header != SECURETAR_MAGIC: cbc_rand = header else: plaintext_size = int.from_bytes(f.read(8), "big") f.read(8) # Skip reserved bytes cbc_rand = f.read(IV_SIZE) return cls(cbc_rand, plaintext_size) def to_bytes(self) -> bytes: """Return header bytes.""" if self.plaintext_size is None: raise ValueError("Plaintext size is required") return ( SECURETAR_MAGIC + self.plaintext_size.to_bytes(8, "big") + bytes(8) + self.cbc_rand ) class SecureTarError(Exception): """SecureTar error.""" class AddFileError(SecureTarError): """Raised when a file could not be added to an archive.""" def __init__(self, path: Path, *args: Any) -> None: """Initialize.""" self.path = path super().__init__(*args) class SecureTarReadError(SecureTarError): """SecureTar read error.""" class SecureTarFile: """Handle encrypted files for tarfile library.""" def __init__( self, name: Path | None = None, mode: str = "r", key: bytes | None = None, gzip: bool = True, bufsize: int = DEFAULT_BUFSIZE, fileobj: IO[bytes] | None = None, nonce: bytes | None = None, ) -> None: """Initialize encryption handler.""" self._file: IO[bytes] | None = None self._mode: str = mode self._name: Path | None = name self._bufsize: int = bufsize self._extra_args = {} self._fileobj = fileobj self._nonce = nonce # Tarfile options self._tar: tarfile.TarFile | None = None if key: self._tar_mode = f"{mode}|" else: self._tar_mode = f"{mode}:" if gzip: self._extra_args["compresslevel"] = 6 if gzip: self._tar_mode = self._tar_mode + "gz" # Encryption/Description self._aes: Cipher | None = None self._key: bytes | None = key # Function helper self._cipher: CipherContext | None = None self._padder: padding.PaddingContext | None = None self.padding_length = 0 self.securetar_header: SecureTarHeader | None = None def create_inner_tar( self, name: str, key: bytes | None = None, gzip: bool = True ) -> "_InnerSecureTarFile": """Create inner tar file.""" if not self._tar: raise SecureTarError("SecureTar not open") return _InnerSecureTarFile( self._tar, name=Path(name), mode="w", key=key, gzip=gzip, bufsize=self._bufsize, ) def __enter__(self) -> tarfile.TarFile: """Start context manager tarfile.""" return self.open() def open(self) -> tarfile.TarFile: """Open SecureTar file. Returns tarfile object, data written to is encrypted if key is provided. """ if not self._key: self._tar = tarfile.open( name=str(self._name), mode=self._tar_mode, dereference=False, bufsize=self._bufsize, **self._extra_args, **({"fileobj": self._fileobj} if self._fileobj else {}), ) return self._tar # Encrypted/Decrypted Tarfile self._open_file() if self._mode == MOD_READ: self.securetar_header = SecureTarHeader.from_bytes(self._file) cipher_mode = CipherMode.DECRYPT else: cbc_rand = self._nonce if self._nonce is not None else os.urandom(IV_SIZE) self.securetar_header = SecureTarHeader(cbc_rand, 0) self._file.write(self.securetar_header.to_bytes()) cipher_mode = CipherMode.ENCRYPT self._setup_cipher(cipher_mode) self._tar = tarfile.open( fileobj=self, mode=self._tar_mode, dereference=False, bufsize=self._bufsize, ) return self._tar def _open_file(self) -> None: if self._fileobj: # If we have a fileobj, we don't need to open a file self._file = self._fileobj else: if not self._name: raise ValueError("No filename or fileobj provided") read_mode = self._mode.startswith("r") if read_mode: file_mode: int = os.O_RDONLY else: file_mode = os.O_WRONLY | os.O_CREAT fd = os.open(self._name, file_mode, 0o666) self._file = os.fdopen(fd, "rb" if read_mode else "wb") def _setup_cipher(self, cipher_mode: CipherMode) -> None: # Extract IV for CBC cbc_rand = self.securetar_header.cbc_rand # Create Cipher self._aes = Cipher( algorithms.AES(self._key), modes.CBC(_generate_iv(self._key, cbc_rand)), backend=default_backend(), ) if cipher_mode == CipherMode.DECRYPT: self._cipher = self._aes.decryptor() else: self._cipher = self._aes.encryptor() self._padder = padding.PKCS7(BLOCK_SIZE_BITS).padder() def __exit__(self, exc_type, exc_value, traceback) -> None: self.close() def close(self) -> None: """Close file.""" if self._tar: self._tar.close() self._tar = None self._close_file() def _close_file(self) -> None: """Close file.""" if self._file: if not self._mode.startswith("r"): padding = self._padder.finalize() self._file.write(self._cipher.update(padding)) self.padding_length = len(padding) if not self._fileobj: self._file.close() self._file = None class DecryptEncryptInnerTar: """Base class to decrypt or encrypt inner tar file.""" def __init__(self, parent: SecureTarFile, size: int) -> None: """Initialize.""" self._head: bytes | None = None self._parent = parent self._pos = 0 self._size = size self._tail: bytes | None = None def read(self, size: int = 0) -> bytes: """Read data.""" if self._tail is not None: # Finish reading tail data = self._tail[:size] self._tail = self._tail[size:] return data if self._head: # Read from head data = self._head[:size] self._head = self._head[size:] remaining = size - len(data) if remaining: data += self._parent.read(remaining) else: data = self._parent.read(size) self._pos += len(data) if not data or self._size - self._pos > BLOCK_SIZE: return data # Last block: Append any remaining head, read tail and handle padding if self._head: data += self._head data += self._parent.read(max(self._size - self._pos, 0)) data = self._process_padding(data) self._tail = data[size:] return data[:size] def _process_padding(self, data: bytes) -> bytes: """Process padding.""" raise NotImplementedError @contextmanager def decrypt(self, tarinfo: tarfile.TarInfo) -> Generator[BinaryIO, None, None]: """Decrypt inner tar. This is a helper to decrypt data and discard the padding. """ class DecryptInnerTar(SecureTarFile.DecryptEncryptInnerTar): """Decrypt inner tar file.""" def __init__(self, parent: SecureTarFile) -> None: """Initialize.""" size = tarinfo.size - IV_SIZE if parent.securetar_header.plaintext_size is not None: size -= SECURETAR_HEADER_SIZE super().__init__(parent, size) @staticmethod def _validate_inner_tar(head: bytes) -> None: """Validate inner tar.""" if ( head[0 : len(GZIP_MAGIC_BYTES)] != GZIP_MAGIC_BYTES and head[TAR_MAGIC_OFFSET : TAR_MAGIC_OFFSET + len(TAR_MAGIC_BYTES)] != TAR_MAGIC_BYTES ): raise SecureTarReadError( "The inner tar is not gzip or tar, wrong key?" ) def read(self, size: int = 0) -> bytes: """Read data.""" if self._head is None: # Read and validate header self._head = self._parent.read(max(size, 512)) self._validate_inner_tar(self._head) return super().read(size) def _process_padding(self, data: bytes) -> bytes: """Process padding.""" padding_len = data[-1] return data[:-padding_len] try: self._open_file() self.securetar_header = SecureTarHeader.from_bytes(self._file) self._setup_cipher(CipherMode.DECRYPT) yield DecryptInnerTar(self) finally: self._close_file() @contextmanager def encrypt(self, tarinfo: tarfile.TarInfo) -> Generator[BinaryIO, None, None]: """Encrypt inner tar. This is a helper to encrypt data and add padding. """ class EncryptInnerTar(SecureTarFile.DecryptEncryptInnerTar): """Encrypt inner tar file.""" def __init__(self, parent: SecureTarFile) -> None: """Initialize.""" size = tarinfo.size + BLOCK_SIZE - tarinfo.size % BLOCK_SIZE size += IV_SIZE + SECURETAR_HEADER_SIZE self.encrypted_size = size super().__init__(parent, size) self._head = parent.securetar_header.to_bytes() def _process_padding(self, data: bytes) -> bytes: """Process padding.""" padding = self._parent._padder.finalize() return data + self._parent._cipher.update(padding) try: self._open_file() cbc_rand = self._nonce if self._nonce is not None else os.urandom(IV_SIZE) self.securetar_header = SecureTarHeader(cbc_rand, tarinfo.size) self._setup_cipher(CipherMode.ENCRYPT) yield EncryptInnerTar(self) finally: self._close_file() def write(self, data: bytes) -> None: """Write data.""" data = self._padder.update(data) self._file.write(self._cipher.update(data)) def read(self, size: int = 0) -> bytes: """Read data.""" data = self._padder.update(self._file.read(size)) return self._cipher.update(data) @property def path(self) -> Path: """Return path object of tarfile.""" return self._name @property def size(self) -> float: """Return backup size.""" if not self._name.is_file(): return 0 return round(self._name.stat().st_size / 1_048_576, 2) # calc mbyte class _InnerSecureTarFile(SecureTarFile): """Handle encrypted files for tarfile library inside another tarfile.""" def __init__( self, outer_tar: tarfile.TarFile, name: Path, mode: str, key: bytes | None = None, gzip: bool = True, bufsize: int = DEFAULT_BUFSIZE, ) -> None: """Initialize inner handler.""" super().__init__( name=name, mode=mode, key=key, gzip=gzip, bufsize=bufsize, fileobj=outer_tar.fileobj, ) self.outer_tar = outer_tar self.stream: Generator[BinaryIO, None, None] | None = None def __enter__(self) -> tarfile.TarFile: """Start context manager tarfile.""" tar_info = tarfile.TarInfo(name=str(self._name)) if self.outer_tar.format == tarfile.PAX_FORMAT: # Ensure we always set mtime as a float to force # a PAX header to be written. # # This is necessary to # handle large files as TarInfo.tobuf will try to # use a shorter ustar header if we do not have at # least one float in the tarinfo. # https://github.com/python/cpython/blob/53b84e772cac6e4a55cebf908d6bb9c48fe254dc/Lib/tarfile.py#L1066 tar_info.mtime = time.time() else: tar_info.mtime = int(time.time()) self.stream = _add_stream(self.outer_tar, tar_info, self) self.stream.__enter__() return super().__enter__() def __exit__(self, exc_type, exc_value, traceback) -> None: """Close file.""" super().__exit__(exc_type, exc_value, traceback) self.stream.__exit__(exc_type, exc_value, traceback) @contextmanager def _add_stream( tar: tarfile.TarFile, tar_info: tarfile.TarInfo, inner_tar: _InnerSecureTarFile ) -> Generator[BinaryIO, None, None]: """Add a stream to the tarfile. This only works with uncompressed, unencrypted tar files. The typical usage is: with _add_stream(tar, tar_info) as fileobj: fileobj.write(data) It is critical that the tar_info is not modified inside the context manager, as the tar file header size may change. :param tar: The outer tar file to add the stream to. :param tar_info: TarInfo for the added stream. :param padding: PKCS7 padding added at the end of the stream. If non-empty, the inner tar is encrypted, and we calculate the plaintext size from the padding and add a pax header with the plaintext size. If empty, the inner tar is not encrypted and we don't add a plaintext size pax header. """ fileobj = tar.fileobj tell_before_adding_inner_file_header = fileobj.tell() # Write an empty header for the inner tar file # We'll seek back to this position later to update the header with the correct size tar_info_header = tar_info.tobuf(tar.format, tar.encoding, tar.errors) tar_info_header_len = len(tar_info_header) fileobj.write(tar_info_header) try: yield fileobj finally: tell_after_writing_inner_tar = fileobj.tell() size_of_inner_tar = ( tell_after_writing_inner_tar - tell_before_adding_inner_file_header - tar_info_header_len ) # Pad the outer tar file to a multiple of BLOCKSIZE # in case the inner tar file is not a multiple of BLOCKSIZE blocks, remainder = divmod(size_of_inner_tar, tarfile.BLOCKSIZE) padding_size = 0 if remainder > 0: padding_size = tarfile.BLOCKSIZE - remainder fileobj.write(tarfile.NUL * padding_size) blocks += 1 tar.offset += size_of_inner_tar + padding_size tar_info.size = size_of_inner_tar if inner_tar.padding_length: # Update the size in the header inner_tar.securetar_header.plaintext_size = ( size_of_inner_tar - inner_tar.padding_length - IV_SIZE - SECURETAR_HEADER_SIZE ) fileobj.seek(tell_before_adding_inner_file_header + tar_info_header_len) tar.fileobj.write(inner_tar.securetar_header.to_bytes()) # Now that we know the size of the inner tar, we seek back # to where we started and re-add the member with the correct size fileobj.seek(tell_before_adding_inner_file_header) # We can't call tar.addfile here because it doesn't allow a non-zero # size to be set without passing a fileobj. Instead we manually write # the header. https://github.com/python/cpython/pull/117988 buf = tar_info.tobuf(tar.format, tar.encoding, tar.errors) tar.fileobj.write(buf) tar.offset += len(buf) tar.members.append(tar_info) # Finally return to the end of the outer tar file fileobj.seek(tell_after_writing_inner_tar + padding_size) def _generate_iv(key: bytes, salt: bytes) -> bytes: """Generate an iv from data.""" temp_iv = key + salt for _ in range(100): temp_iv = hashlib.sha256(temp_iv).digest() return temp_iv[:IV_SIZE] def secure_path(tar: tarfile.TarFile) -> Generator[tarfile.TarInfo, None, None]: """Security safe check of path. Prevent ../ or absolut paths """ for member in tar: file_path = Path(member.name) try: if file_path.is_absolute(): raise ValueError() Path("/fake", file_path).resolve().relative_to("/fake") except (ValueError, RuntimeError): _LOGGER.warning("Found issue with file %s", file_path) continue else: yield member def atomic_contents_add( tar_file: tarfile.TarFile, origin_path: Path, file_filter: Callable[[PurePath], bool], arcname: str = ".", ) -> None: """Append directories and/or files to the TarFile if file_filter returns False. :param file_filter: A filter function, should return True if the item should be excluded from the archive. The function should take a single argument, a pathlib.PurePath object representing the relative path of the item to be archived. """ if file_filter(PurePath(arcname)): return None return _atomic_contents_add(tar_file, origin_path, file_filter, arcname) def _atomic_contents_add( tar_file: tarfile.TarFile, origin_path: Path, file_filter: Callable[[PurePath], bool], arcname: str, ) -> None: """Append directories and/or files to the TarFile if file_filter returns False.""" # Add directory only (recursive=False) to ensure we also archive empty directories try: tar_file.add(origin_path.as_posix(), arcname=arcname, recursive=False) except (OSError, tarfile.TarError) as err: raise AddFileError( origin_path, f"Error adding {origin_path} to tarfile: {err} ({err.__class__.__name__})", ) from err try: dir_iterator = origin_path.iterdir() except OSError as err: raise AddFileError( origin_path, f"Error iterating over {origin_path}: {err} ({err.__class__.__name__})", ) from err for directory_item in dir_iterator: try: item_arcpath = PurePath(arcname, directory_item.name) if file_filter(PurePath(item_arcpath)): continue item_arcname = item_arcpath.as_posix() if directory_item.is_dir() and not directory_item.is_symlink(): _atomic_contents_add( tar_file, directory_item, file_filter, item_arcname ) continue tar_file.add( directory_item.as_posix(), arcname=item_arcname, recursive=False ) except (OSError, tarfile.TarError) as err: raise AddFileError( directory_item, ( f"Error adding {directory_item} to tarfile: " f"{err} ({err.__class__.__name__})" ), ) from err return None pvizeli-securetar-1ae56fc/setup.cfg000066400000000000000000000004031475735033600175160ustar00rootroot00000000000000[flake8] # To work with Black max-line-length = 88 # E501: line too long # W503: Line break occurred before a binary operator # E203: Whitespace before ':' # D202 No blank lines allowed after function docstring ignore = E501, W503, E203, D202 pvizeli-securetar-1ae56fc/tests/000077500000000000000000000000001475735033600170425ustar00rootroot00000000000000pvizeli-securetar-1ae56fc/tests/__init__.py000066400000000000000000000000351475735033600211510ustar00rootroot00000000000000"""Pytests for securetar.""" pvizeli-securetar-1ae56fc/tests/fixtures/000077500000000000000000000000001475735033600207135ustar00rootroot00000000000000pvizeli-securetar-1ae56fc/tests/fixtures/backup_encrypted_gzipped_legacy_format.tar000066400000000000000000000240001475735033600313570ustar00rootroot00000000000000././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1736768114.600526 core.tar.gz0000644000000000000000000000064014741175163010074 0ustar00:Lj]/gzQN 8A6 WI[gnV@~2oإ +H!Ha3G}o Koޖ`Ů#䁙~!8G&<y=a /_ln:ߌ+OiCeeJOI3`ޜ>-]B1^qB\{W]?s˔̍vjk9T A |SġAóBo](%]rd&J }<6x p3l}M`zJ۔CәG(|fit& qZ5e% ԐGd&wJ, !$F ^z$ZY aHW?Riq+M+/85ލ9М4|^././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1736768114.601938 core2.tar.gz0000644000000000000000000000064014741175163010156 0ustar00uzC-HQRu=zH# 7pu104hfhE}O\zHtmhO0Jy}!YY?1)&6y#vg_]|>(xbLEw6G?<Yv-MWcaTfpvizeli-securetar-1ae56fc/tests/fixtures/tar_data/000077500000000000000000000000001475735033600224725ustar00rootroot00000000000000pvizeli-securetar-1ae56fc/tests/fixtures/tar_data/README.md000066400000000000000000000000611475735033600237460ustar00rootroot00000000000000# Tar Data This is just a test for backup files pvizeli-securetar-1ae56fc/tests/fixtures/tar_data/test1/000077500000000000000000000000001475735033600235325ustar00rootroot00000000000000pvizeli-securetar-1ae56fc/tests/fixtures/tar_data/test1/script.sh000077500000000000000000000000351475735033600253730ustar00rootroot00000000000000#!/bin/sh echo "Test Script"pvizeli-securetar-1ae56fc/tests/fixtures/tar_data/test_symlink000077700000000000000000000000001475735033600261202test1ustar00rootroot00000000000000pvizeli-securetar-1ae56fc/tests/test_tar.py000066400000000000000000000766271475735033600212630ustar00rootroot00000000000000"""Test Tarfile functions.""" import gzip import io import os import shutil import tarfile import time from dataclasses import dataclass from pathlib import Path, PurePath from typing import Any from unittest.mock import Mock, patch import pytest from securetar import ( AddFileError, SECURETAR_MAGIC, SecureTarError, SecureTarFile, SecureTarReadError, _add_stream, atomic_contents_add, secure_path, ) @dataclass class TarInfo: """Fake TarInfo.""" name: str def test_secure_path() -> None: """Test Secure Path.""" test_list = [ TarInfo("test.txt"), TarInfo("data/xy.blob"), TarInfo("bla/blu/ble"), TarInfo("data/../xy.blob"), ] assert test_list == list(secure_path(test_list)) def test_not_secure_path() -> None: """Test Not secure path.""" test_list = [ TarInfo("/test.txt"), TarInfo("data/../../xy.blob"), TarInfo("/bla/blu/ble"), ] assert [] == list(secure_path(test_list)) def test_file_filter(tmp_path: Path) -> None: """Test exclude filter.""" file_filter = Mock(return_value=False) # Prepare test folder temp_orig = tmp_path.joinpath("orig") fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data") shutil.copytree(fixture_data, temp_orig, symlinks=True) # Create Tarfile temp_tar = tmp_path.joinpath("backup.tar") with SecureTarFile(temp_tar, "w") as tar_file: atomic_contents_add( tar_file, temp_orig, file_filter=file_filter, arcname=".", ) paths = [call[1][0] for call in file_filter.mock_calls] expected_paths = { PurePath("."), PurePath("README.md"), PurePath("test_symlink"), PurePath("test1"), PurePath("test1/script.sh"), } assert len(paths) == len(expected_paths) assert set(paths) == expected_paths @pytest.mark.parametrize("bufsize", [10240, 4 * 2**20]) def test_create_pure_tar(tmp_path: Path, bufsize: int) -> None: """Test to create a tar file without encryption.""" # Prepare test folder temp_orig = tmp_path.joinpath("orig") fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data") shutil.copytree(fixture_data, temp_orig, symlinks=True) # Create Tarfile temp_tar = tmp_path.joinpath("backup.tar") with SecureTarFile(temp_tar, "w", bufsize=bufsize) as tar_file: atomic_contents_add( tar_file, temp_orig, file_filter=lambda _: False, arcname=".", ) assert temp_tar.exists() # Restore temp_new = tmp_path.joinpath("new") with SecureTarFile(temp_tar, "r", bufsize=bufsize) as tar_file: tar_file.extractall(path=temp_new, members=tar_file) assert temp_new.is_dir() assert temp_new.joinpath("test_symlink").is_symlink() assert temp_new.joinpath("test1").is_dir() assert temp_new.joinpath("test1/script.sh").is_file() # 775 is correct for local, but in GitHub action it's 755, both is fine assert oct(temp_new.joinpath("test1/script.sh").stat().st_mode)[-3:] in [ "755", "775", ] assert temp_new.joinpath("README.md").is_file() @pytest.mark.parametrize( ("target", "attribute", "expected_error"), [ ( tarfile.TarFile, "addfile", r"Error adding {temp_orig} to tarfile: Boom! \(OSError\)", ), ( tarfile, "copyfileobj", r"Error adding {temp_orig}/.+ to tarfile: Boom! \(OSError\)", ), ( Path, "is_dir", r"Error adding {temp_orig}/.+ to tarfile: Boom! \(OSError\)", ), ( Path, "is_symlink", r"Error adding {temp_orig}/.+ to tarfile: Boom! \(OSError\)", ), ( Path, "iterdir", r"Error iterating over {temp_orig}: Boom! \(OSError\)", ), ], ) def test_create_with_error( tmp_path: Path, target: Any, attribute: str, expected_error: str ) -> None: """Test error in atomic_contents_add.""" # Prepare test folder temp_orig = tmp_path.joinpath("orig") fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data") shutil.copytree(fixture_data, temp_orig, symlinks=True) # Create Tarfile temp_tar = tmp_path.joinpath("backup.tar") with ( patch.object(target, attribute, side_effect=OSError("Boom!")), pytest.raises( AddFileError, match=expected_error.format(temp_orig=temp_orig), ), SecureTarFile(temp_tar, "w") as tar_file, ): atomic_contents_add( tar_file, temp_orig, file_filter=lambda _: False, arcname=".", ) @pytest.mark.parametrize("bufsize", [333, 10240, 4 * 2**20]) def test_create_encrypted_tar(tmp_path: Path, bufsize: int) -> None: """Test to create a tar file with encryption.""" key = os.urandom(16) # Prepare test folder temp_orig = tmp_path.joinpath("orig") fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data") shutil.copytree(fixture_data, temp_orig, symlinks=True) with open(temp_orig / "randbytes1", "wb") as file: file.write(os.urandom(12345)) with open(temp_orig / "randbytes2", "wb") as file: file.write(os.urandom(12345)) # Create Tarfile temp_tar = tmp_path.joinpath("backup.tar") with SecureTarFile(temp_tar, "w", key=key, bufsize=bufsize) as tar_file: atomic_contents_add( tar_file, temp_orig, file_filter=lambda _: False, arcname=".", ) assert temp_tar.exists() # Iterate over the tar file files = set() with SecureTarFile(temp_tar, "r", key=key, bufsize=bufsize) as tar_file: for tar_info in tar_file: files.add(tar_info.name) assert files == { ".", "README.md", "randbytes1", "randbytes2", "test_symlink", "test1", "test1/script.sh", } # Restore temp_new = tmp_path.joinpath("new") with SecureTarFile(temp_tar, "r", key=key, bufsize=bufsize) as tar_file: tar_file.extractall(path=temp_new, members=tar_file) assert temp_new.is_dir() assert temp_new.joinpath("test_symlink").is_symlink() assert temp_new.joinpath("test1").is_dir() assert temp_new.joinpath("test1/script.sh").is_file() assert temp_new.joinpath("randbytes1").is_file() assert temp_new.joinpath("randbytes2").is_file() # 775 is correct for local, but in GitHub action it's 755, both is fine assert oct(temp_new.joinpath("test1/script.sh").stat().st_mode)[-3:] in [ "755", "775", ] assert temp_new.joinpath("README.md").is_file() @pytest.mark.parametrize( ("nonce", "expect_same_content"), [(None, False), (os.urandom(16), True)], ) def test_create_encrypted_tar_fixed_nonce( tmp_path: Path, nonce: bytes | None, expect_same_content: bool ) -> None: """Test to create a tar file with pre-defined nonce.""" key = os.urandom(16) # Prepare test folder temp_orig = tmp_path.joinpath("orig") fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data") shutil.copytree(fixture_data, temp_orig, symlinks=True) with open(temp_orig / "randbytes1", "wb") as file: file.write(os.urandom(12345)) with open(temp_orig / "randbytes2", "wb") as file: file.write(os.urandom(12345)) # Create Tarfile1 temp_tar1 = tmp_path.joinpath("backup1.tar") with SecureTarFile(temp_tar1, "w", key=key, nonce=nonce) as tar_file: atomic_contents_add( tar_file, temp_orig, file_filter=lambda _: False, arcname=".", ) # Create Tarfile2 temp_tar2 = tmp_path.joinpath("backup2.tar") with SecureTarFile(temp_tar2, "w", key=key, nonce=nonce) as tar_file: atomic_contents_add( tar_file, temp_orig, file_filter=lambda _: False, arcname=".", ) same_content = temp_tar1.read_bytes() == temp_tar2.read_bytes() assert same_content == expect_same_content @pytest.mark.parametrize( ("enable_gzip", "inner_tar_files"), [ (True, ("core.tar.gz", "core2.tar.gz", "core3.tar.gz")), (False, ("core.tar", "core2.tar", "core3.tar")), ], ) def test_tar_inside_tar( tmp_path: Path, enable_gzip: bool, inner_tar_files: tuple[str, ...] ) -> None: # Prepare test folder temp_orig = tmp_path.joinpath("orig") fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data") shutil.copytree(fixture_data, temp_orig, symlinks=True) # Create Tarfile main_tar = tmp_path.joinpath("backup.tar") outer_secure_tar_file = SecureTarFile(main_tar, "w", gzip=False) with outer_secure_tar_file as outer_tar_file: for inner_tar_file in inner_tar_files: with outer_secure_tar_file.create_inner_tar( inner_tar_file, gzip=enable_gzip ) as inner_tar_file: atomic_contents_add( inner_tar_file, temp_orig, file_filter=lambda _: False, arcname=".", ) assert len(outer_tar_file.getmembers()) == 3 raw_bytes = b'{"test": "test"}' fileobj = io.BytesIO(raw_bytes) tar_info = tarfile.TarInfo(name="backup.json") tar_info.size = len(raw_bytes) tar_info.mtime = time.time() outer_tar_file.addfile(tar_info, fileobj=fileobj) assert len(outer_tar_file.getmembers()) == 4 assert main_tar.exists() # Iterate over the tar file, and check there's no securetar header files = set() with SecureTarFile(main_tar, "r", gzip=False) as tar_file: for tar_info in tar_file: inner_tar = tar_file.extractfile(tar_info) assert inner_tar.read(len(SECURETAR_MAGIC)) != SECURETAR_MAGIC files.add(tar_info.name) assert files == {"backup.json", *inner_tar_files} # Restore temp_new = tmp_path.joinpath("new") with SecureTarFile(main_tar, "r", gzip=False) as tar_file: tar_file.extractall(path=temp_new) assert temp_new.is_dir() core_tar = temp_new.joinpath(inner_tar_files[0]) assert core_tar.is_file() if enable_gzip: compressed = core_tar.read_bytes() uncompressed = gzip.decompress(core_tar.read_bytes()) assert len(uncompressed) > len(compressed) assert temp_new.joinpath(inner_tar_files[1]).is_file() assert temp_new.joinpath(inner_tar_files[2]).is_file() backup_json = temp_new.joinpath("backup.json") assert backup_json.is_file() assert backup_json.read_bytes() == raw_bytes # Extract inner tars for inner_tar_file in inner_tar_files: temp_inner_new = tmp_path.joinpath(f"{inner_tar_file}_inner_new") with SecureTarFile( temp_new.joinpath(inner_tar_file), "r", gzip=enable_gzip ) as tar_file: tar_file.extractall(path=temp_inner_new, members=tar_file) assert temp_inner_new.is_dir() assert temp_inner_new.joinpath("test_symlink").is_symlink() assert temp_inner_new.joinpath("test1").is_dir() assert temp_inner_new.joinpath("test1/script.sh").is_file() # 775 is correct for local, but in GitHub action it's 755, both is fine assert oct(temp_inner_new.joinpath("test1/script.sh").stat().st_mode)[-3:] in [ "755", "775", ] assert temp_inner_new.joinpath("README.md").is_file() @pytest.mark.parametrize("bufsize", [33, 333, 10240, 4 * 2**20]) @pytest.mark.parametrize( ("enable_gzip", "inner_tar_files"), [ (True, ("core.tar.gz", "core2.tar.gz", "core3.tar.gz")), (False, ("core.tar", "core2.tar", "core3.tar")), ], ) def test_tar_inside_tar_encrypt( tmp_path: Path, bufsize: int, enable_gzip: bool, inner_tar_files: tuple[str, ...] ) -> None: """Test we can make encrypted versions of plaintext tars.""" # Prepare test folder temp_orig = tmp_path.joinpath("orig") fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data") shutil.copytree(fixture_data, temp_orig, symlinks=True) # Create Tarfile main_tar = tmp_path.joinpath("backup.tar") outer_secure_tar_file = SecureTarFile(main_tar, "w", gzip=False) with outer_secure_tar_file as outer_tar_file: for inner_tar_file in inner_tar_files: with outer_secure_tar_file.create_inner_tar( inner_tar_file, gzip=enable_gzip ) as inner_tar_file: atomic_contents_add( inner_tar_file, temp_orig, file_filter=lambda _: False, arcname=".", ) assert len(outer_tar_file.getmembers()) == 3 raw_bytes = b'{"test": "test"}' fileobj = io.BytesIO(raw_bytes) tar_info = tarfile.TarInfo(name="backup.json") tar_info.size = len(raw_bytes) tar_info.mtime = time.time() outer_tar_file.addfile(tar_info, fileobj=fileobj) assert len(outer_tar_file.getmembers()) == 4 assert main_tar.exists() # Iterate over the tar file, and check there's no securetar header files = set() with SecureTarFile(main_tar, "r", gzip=False) as tar_file: for tar_info in tar_file: inner_tar = tar_file.extractfile(tar_info) assert inner_tar.read(len(SECURETAR_MAGIC)) != SECURETAR_MAGIC files.add(tar_info.name) assert files == {"backup.json", *inner_tar_files} # Encrypt the inner tar files key = os.urandom(16) temp_encrypted = tmp_path.joinpath("encrypted") os.makedirs(temp_encrypted, exist_ok=True) with SecureTarFile(main_tar, "r", gzip=False, bufsize=bufsize) as tar_file: for inner_tar_file in inner_tar_files: tar_info = tar_file.getmember(inner_tar_file) istf = SecureTarFile( None, gzip=False, # We encrypt the compressed tar key=key, mode="r", fileobj=tar_file.extractfile(tar_info), ) inner_tar_path = temp_encrypted.joinpath(tar_info.name) with open(inner_tar_path, "wb") as file: with istf.encrypt(tar_info) as encrypted: read = 0 while data := encrypted.read(bufsize): read += len(data) file.write(data) assert read == encrypted.encrypted_size # Check the indicated size is correct assert ( inner_tar_path.stat().st_size == tar_info.size + 16 - tar_info.size % 16 + 16 + 32 ) # Check the encrypted files can be opened temp_decrypted = tmp_path.joinpath("decrypted") os.makedirs(temp_decrypted, exist_ok=True) for inner_tar_file in inner_tar_files: encrypted_inner_tar_path = temp_encrypted.joinpath(inner_tar_file) with open(encrypted_inner_tar_path, "rb") as encrypted_inner_tar: tar_info = tarfile.TarInfo(inner_tar_file) tar_info.size = encrypted_inner_tar_path.stat().st_size with open(encrypted_inner_tar_path, "rb") as encrypted_inner_tar: istf = SecureTarFile( None, gzip=False, # We decrypt the compressed tar key=key, mode="r", fileobj=encrypted_inner_tar, ) decrypted_inner_tar_path = temp_decrypted.joinpath(inner_tar_file) with open(decrypted_inner_tar_path, "wb") as file: with istf.decrypt(tar_info) as decrypted: while data := decrypted.read(bufsize): file.write(data) # Check decrypted file is valid gzip, this fails if the padding is not # handled correctly if enable_gzip: assert decrypted_inner_tar_path.stat().st_size > 0 gzip.decompress(decrypted_inner_tar_path.read_bytes()) # Check the tar file can be opened and iterate over it files = set() with tarfile.open(decrypted_inner_tar_path, "r") as itf: for tar_info in itf: files.add(tar_info.name) assert files == { ".", "README.md", "test1", "test1/script.sh", "test_symlink", } def test_gzipped_tar_inside_tar_failure(tmp_path: Path) -> None: # Prepare test folder temp_orig = tmp_path.joinpath("orig") fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data") shutil.copytree(fixture_data, temp_orig, symlinks=True) # Create Tarfile main_tar = tmp_path.joinpath("backup.tar") outer_secure_tar_file = SecureTarFile(main_tar, "w", gzip=False) with outer_secure_tar_file as outer_tar_file: # Make the first tar file to ensure that # the second tar file can still be created with pytest.raises(ValueError, match="Test"): with outer_secure_tar_file.create_inner_tar( "failed.tar.gz", gzip=True ) as inner_tar_file: raise ValueError("Test") with pytest.raises(ValueError, match="Test"): with outer_secure_tar_file.create_inner_tar( "good.tar.gz", gzip=True ) as inner_tar_file: atomic_contents_add( inner_tar_file, temp_orig, file_filter=lambda _: False, arcname=".", ) raise ValueError("Test") assert len(outer_tar_file.getmembers()) == 2 assert main_tar.exists() # Restore temp_new = tmp_path.joinpath("new") with SecureTarFile(main_tar, "r", gzip=False) as tar_file: tar_file.extractall(path=temp_new) assert temp_new.is_dir() assert temp_new.joinpath("good.tar.gz").is_file() failed_path = temp_new.joinpath("failed.tar.gz") assert failed_path.is_file() # Extract inner tar temp_inner_new = tmp_path.joinpath("good.tar.gz_inner_new") with SecureTarFile(temp_new.joinpath("good.tar.gz"), "r", gzip=True) as tar_file: tar_file.extractall(path=temp_inner_new, members=tar_file) assert temp_inner_new.is_dir() assert temp_inner_new.joinpath("test_symlink").is_symlink() assert temp_inner_new.joinpath("test1").is_dir() assert temp_inner_new.joinpath("test1/script.sh").is_file() # 775 is correct for local, but in GitHub action it's 755, both is fine assert oct(temp_inner_new.joinpath("test1/script.sh").stat().st_mode)[-3:] in [ "755", "775", ] assert temp_inner_new.joinpath("README.md").is_file() # Extract failed inner tar (should not raise but will be empty) temp_inner_new = tmp_path.joinpath("failed.tar.gz_inner_new") with SecureTarFile(temp_new.joinpath("failed.tar.gz"), "r", gzip=True) as tar_file: tar_file.extractall(path=temp_inner_new, members=tar_file) @pytest.mark.parametrize("bufsize", [33, 333, 10240, 4 * 2**20]) @pytest.mark.parametrize( ("enable_gzip", "inner_tar_files"), [ (True, ("core.tar.gz", "core2.tar.gz", "core3.tar.gz")), (False, ("core.tar", "core2.tar", "core3.tar")), ], ) def test_encrypted_tar_inside_tar( tmp_path: Path, bufsize: int, enable_gzip: bool, inner_tar_files: tuple[str, ...] ) -> None: key = os.urandom(16) # Prepare test folder temp_orig = tmp_path.joinpath("orig") fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data") shutil.copytree(fixture_data, temp_orig, symlinks=True) # Create Tarfile main_tar = tmp_path.joinpath("backup.tar") outer_secure_tar_file = SecureTarFile(main_tar, "w", gzip=False, bufsize=bufsize) with outer_secure_tar_file as outer_tar_file: for inner_tar_file in inner_tar_files: with outer_secure_tar_file.create_inner_tar( inner_tar_file, key=key, gzip=enable_gzip ) as inner_tar_file: atomic_contents_add( inner_tar_file, temp_orig, file_filter=lambda _: False, arcname=".", ) assert len(outer_tar_file.getmembers()) == 3 assert main_tar.exists() # Iterate over the tar file file_sizes: dict[str, int] = {} with SecureTarFile(main_tar, "r", gzip=False, bufsize=bufsize) as tar_file: for tar_info in tar_file: inner_tar = tar_file.extractfile(tar_info) assert inner_tar.read(len(SECURETAR_MAGIC)) == SECURETAR_MAGIC file_sizes[tar_info.name] = int.from_bytes(inner_tar.read(8), "big") assert set(file_sizes) == {*inner_tar_files} # Decrypt the inner tar with wrong key temp_decrypted = tmp_path.joinpath("decrypted") os.makedirs(temp_decrypted, exist_ok=True) with SecureTarFile(main_tar, "r", gzip=False, bufsize=bufsize) as tar_file: for tar_info in tar_file: istf = SecureTarFile( None, gzip=False, # We decrypt the compressed tar key=b"wrong_key_abcdef", mode="r", fileobj=tar_file.extractfile(tar_info), ) inner_tar_path = temp_decrypted.joinpath(tar_info.name) with open(inner_tar_path, "wb") as file: with istf.decrypt(tar_info) as decrypted: with pytest.raises( SecureTarReadError, match="The inner tar is not gzip or tar" ): while data := decrypted.read(bufsize): file.write(data) # Decrypt the inner tar temp_decrypted = tmp_path.joinpath("decrypted") os.makedirs(temp_decrypted, exist_ok=True) with SecureTarFile(main_tar, "r", gzip=False, bufsize=bufsize) as tar_file: for tar_info in tar_file: istf = SecureTarFile( None, gzip=False, # We decrypt the compressed tar key=key, mode="r", fileobj=tar_file.extractfile(tar_info), ) inner_tar_path = temp_decrypted.joinpath(tar_info.name) with open(inner_tar_path, "wb") as file: with istf.decrypt(tar_info) as decrypted: while data := decrypted.read(bufsize): file.write(data) # Check the indicated size is correct assert inner_tar_path.stat().st_size == file_sizes[tar_info.name] # Check decrypted file is valid gzip, this fails if the padding is not # discarded correctly if enable_gzip: assert inner_tar_path.stat().st_size > 0 gzip.decompress(inner_tar_path.read_bytes()) # Check the tar file can be opened and iterate over it files = set() with tarfile.open(inner_tar_path, "r") as inner_tar_file: for tar_info in inner_tar_file: files.add(tar_info.name) assert files == { ".", "README.md", "test1", "test1/script.sh", "test_symlink", } # Restore temp_new = tmp_path.joinpath("new") with SecureTarFile(main_tar, "r", gzip=False, bufsize=bufsize) as tar_file: tar_file.extractall(path=temp_new) assert temp_new.is_dir() for inner_tar_file in inner_tar_files: assert temp_new.joinpath(inner_tar_file).is_file() # Extract inner encrypted tars for inner_tar_file in inner_tar_files: temp_inner_new = tmp_path.joinpath(f"{inner_tar_file}_inner_new") with SecureTarFile( temp_new.joinpath(inner_tar_file), "r", key=key, gzip=enable_gzip, bufsize=bufsize, ) as tar_file: tar_file.extractall(path=temp_inner_new, members=tar_file) assert temp_inner_new.is_dir() assert temp_inner_new.joinpath("test_symlink").is_symlink() assert temp_inner_new.joinpath("test1").is_dir() assert temp_inner_new.joinpath("test1/script.sh").is_file() # 775 is correct for local, but in GitHub action it's 755, both is fine assert oct(temp_inner_new.joinpath("test1/script.sh").stat().st_mode)[-3:] in [ "755", "775", ] assert temp_inner_new.joinpath("README.md").is_file() @pytest.mark.parametrize("bufsize", [33, 333, 10240, 4 * 2**20]) def test_encrypted_gzipped_tar_inside_tar_legacy_format( tmp_path: Path, bufsize: int ) -> None: key = b"0123456789abcdef" fixture_path = Path(__file__).parent.joinpath("fixtures") main_tar = fixture_path.joinpath("./backup_encrypted_gzipped_legacy_format.tar") # Iterate over the tar file, and check there's no securetar header files: set[str] = set() with SecureTarFile(main_tar, "r", gzip=False, bufsize=bufsize) as tar_file: for tar_info in tar_file: inner_tar = tar_file.extractfile(tar_info) assert inner_tar.read(len(SECURETAR_MAGIC)) != SECURETAR_MAGIC files.add(tar_info.name) assert files == { "core.tar.gz", "core2.tar.gz", "core3.tar.gz", } # Decrypt the inner tar temp_decrypted = tmp_path.joinpath("decrypted") os.makedirs(temp_decrypted, exist_ok=True) with SecureTarFile(main_tar, "r", gzip=False, bufsize=bufsize) as tar_file: for tar_info in tar_file: istf = SecureTarFile( None, gzip=False, # We decrypt the compressed tar key=key, mode="r", fileobj=tar_file.extractfile(tar_info), ) inner_tar_path = temp_decrypted.joinpath(tar_info.name) with open(inner_tar_path, "wb") as file: with istf.decrypt(tar_info) as decrypted: while data := decrypted.read(bufsize): file.write(data) shutil.copy(inner_tar_path, f"./{inner_tar_path.name}.orig") # Rewrite the gzip footer # Version 1 of SecureTarFile split the gzip footer in two 16-byte parts, # combine them back into a single footer. with open(inner_tar_path, "r+b") as file: file.seek(-4, io.SEEK_END) size_bytes = file.read(4) file.seek(-20, io.SEEK_END) crc = file.read(4) file.seek(-36, io.SEEK_END) last_block = file.read(16) padding = last_block[-1] # Note: This is not a full implementation of the padding removal. Version 1 # did not add any padding if the inner tar size was a multiple of 16. This # means a full implementation needs to try to first treat the file as unpadded. # If it fails and the tail is in the range 1..15, it may be padded. Remove # the padding and try again. If this also fails, the file is corrupted. # In this test case, we only handle the case where the padding is 1..15. assert 1 <= padding <= 15 file.seek(-20 - last_block[-1], io.SEEK_END) file.write(crc) file.write(size_bytes) file.truncate() shutil.copy(inner_tar_path, f"./{inner_tar_path.name}.fixed") # Check decrypted file is valid gzip, this fails if the padding is not # discarded correctly assert inner_tar_path.stat().st_size > 0 gzip.decompress(inner_tar_path.read_bytes()) # Check the tar file can be opened and iterate over it files = set() with tarfile.open(inner_tar_path, "r:gz") as inner_tar_file: for tar_info in inner_tar_file: files.add(tar_info.name) assert files == { ".", "README.md", "test1", "test1/script.sh", "test_symlink", } def test_inner_tar_not_allowed_in_encrypted(tmp_path: Path) -> None: # Create Tarfile main_tar = tmp_path.joinpath("backup.tar") key = os.urandom(16) outer_secure_tar_file = SecureTarFile(main_tar, "w", key=key, gzip=False) with pytest.raises(tarfile.StreamError): with outer_secure_tar_file: with outer_secure_tar_file.create_inner_tar("any.tgz", gzip=True): pass def test_outer_tar_must_not_be_compressed(tmp_path: Path) -> None: # Create Tarfile main_tar = tmp_path.joinpath("backup.tar.gz") outer_secure_tar_file = SecureTarFile(main_tar, "w", gzip=True) with pytest.raises(OSError): with outer_secure_tar_file: with outer_secure_tar_file.create_inner_tar("any.tgz", gzip=True): pass @pytest.mark.parametrize( "format", [tarfile.PAX_FORMAT, tarfile.GNU_FORMAT, tarfile.USTAR_FORMAT] ) def test_tar_stream(tmp_path: Path, format: int) -> None: # Create Tarfile main_tar = tmp_path.joinpath("backup.tar") with patch.object(tarfile, "DEFAULT_FORMAT", format): ostf = SecureTarFile(main_tar, "w", gzip=False) with ostf as tar_file: tar_info = tarfile.TarInfo(name="test.txt") with _add_stream(tar_file, tar_info, ostf) as stream: stream.write(b"test") # Restore temp_new = tmp_path.joinpath("new") with SecureTarFile(main_tar, "r", gzip=False) as tar_file: tar_file.extractall(path=temp_new) assert temp_new.is_dir() test_file = temp_new.joinpath("test.txt") assert test_file.is_file() assert test_file.read_bytes() == b"test" def test_outer_tar_must_be_open(tmp_path: Path) -> None: # Create Tarfile main_tar = tmp_path.joinpath("backup.tar") outer_secure_tar_file = SecureTarFile(main_tar, "w", gzip=False) with pytest.raises(SecureTarError): with outer_secure_tar_file.create_inner_tar("any.tgz", gzip=True): pass def test_outer_tar_open_close(tmp_path: Path) -> None: # Prepare test folder temp_orig = tmp_path.joinpath("orig") fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data") shutil.copytree(fixture_data, temp_orig, symlinks=True) # Create Tarfile main_tar = tmp_path.joinpath("backup.tar") outer_secure_tar_file = SecureTarFile(main_tar, "w", gzip=False) outer_secure_tar_file.open() with outer_secure_tar_file.create_inner_tar("any.tgz", gzip=True) as tar_file: atomic_contents_add( tar_file, temp_orig, file_filter=lambda _: False, arcname=".", ) outer_secure_tar_file.close() # Restore temp_new = tmp_path.joinpath("new") with SecureTarFile(main_tar, "r", gzip=False) as tar_file: tar_file.extractall(path=temp_new, members=tar_file) assert temp_new.is_dir() assert temp_new.joinpath("any.tgz").is_file() def test_outer_tar_exclusive_mode(tmp_path: Path) -> None: # Create Tarfile main_tar = tmp_path.joinpath("backup.tar") outer_secure_tar_file = SecureTarFile(main_tar, "x", gzip=False) with outer_secure_tar_file: with outer_secure_tar_file.create_inner_tar( "any.tgz", key=os.urandom(16), gzip=True ): pass assert main_tar.exists() outer_secure_tar_file = SecureTarFile(main_tar, "x", gzip=False) with pytest.raises(FileExistsError): outer_secure_tar_file.open()