Source code for s365b.storage.crypto

"""Repository cryptography: keys, blob IDs and blob encryption.

Key hierarchy:

* A random 64-byte **repository key** is created when the repository is
  initialised. Its first half encrypts blobs (AES-256-GCM); its second half
  keys the BLAKE3 hash that names blobs.
* The repository key is stored in the repository config, **wrapped**
  (AES-256-GCM) with a key-encryption key derived from the admin's passphrase
  using Argon2id.

Blob IDs are a *keyed* hash of the plaintext, so identical content
deduplicates, but someone holding only the repository files cannot test
whether a known file is present.
"""

from __future__ import annotations

import os
import secrets
from dataclasses import dataclass

import blake3
from argon2.low_level import Type, hash_secret_raw
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

[docs] NONCE_LEN = 12
[docs] TAG_LEN = 16
[docs] BLOB_ID_LEN = 32
[docs] class CryptoError(Exception): """Raised when decryption fails: wrong passphrase, wrong key or tampered data."""
@dataclass(frozen=True, slots=True)
[docs] class KdfParams: """Argon2id parameters used to derive the key-encryption key. Attributes: time_cost: Iterations. memory_kib: Memory in KiB. parallelism: Lanes. salt: Random salt, hex-encoded. """
[docs] time_cost: int
[docs] memory_kib: int
[docs] parallelism: int
[docs] salt: str
@classmethod
[docs] def new( cls, *, time_cost: int = 3, memory_kib: int = 64 * 1024, parallelism: int = 4 ) -> KdfParams: """Create parameters with a fresh random salt. Args: time_cost: Iterations. memory_kib: Memory in KiB (default 64 MiB). parallelism: Lanes. Returns: New parameters. """ return cls(time_cost, memory_kib, parallelism, secrets.token_hex(16))
[docs] def derive(self, passphrase: str) -> bytes: """Derive the 32-byte key-encryption key from a passphrase. Args: passphrase: The repository passphrase. Returns: 32-byte key. """ return hash_secret_raw( passphrase.encode(), bytes.fromhex(self.salt), time_cost=self.time_cost, memory_cost=self.memory_kib, parallelism=self.parallelism, hash_len=32, type=Type.ID, )
@dataclass(frozen=True, slots=True, repr=False)
[docs] class RepoKeys: """The unwrapped repository key, split into its two uses. Attributes: enc_key: AES-256-GCM key for blobs and index files. id_key: BLAKE3 key for blob IDs. """
[docs] enc_key: bytes
[docs] id_key: bytes
@classmethod
[docs] def generate(cls) -> RepoKeys: """Create a new random repository key. Returns: New keys. """ raw = secrets.token_bytes(64) return cls(raw[:32], raw[32:])
[docs] def wrap(self, kek: bytes) -> bytes: """Encrypt this key with a key-encryption key. Args: kek: Key from :meth:`KdfParams.derive`. Returns: ``nonce || ciphertext``. """ nonce = os.urandom(NONCE_LEN) return nonce + AESGCM(kek).encrypt(nonce, self.enc_key + self.id_key, b"s365b-repo-key")
@classmethod
[docs] def unwrap(cls, wrapped: bytes, kek: bytes) -> RepoKeys: """Decrypt a wrapped key. Args: wrapped: Output of :meth:`wrap`. kek: Key-encryption key. Returns: The repository keys. Raises: CryptoError: If the passphrase (and so the KEK) is wrong. """ try: raw = AESGCM(kek).decrypt(wrapped[:NONCE_LEN], wrapped[NONCE_LEN:], b"s365b-repo-key") except InvalidTag as exc: raise CryptoError("wrong repository passphrase") from exc return cls(raw[:32], raw[32:])
[docs] def blob_id(self, plaintext: bytes) -> str: """Compute the content address of a blob. Args: plaintext: Uncompressed, unencrypted blob content. Returns: 64-character hex ID. """ return blake3.blake3(plaintext, key=self.id_key).hexdigest()
[docs] def encrypt(self, data: bytes, aad: bytes) -> bytes: """Encrypt data with the repository key. Args: data: Plaintext. aad: Associated data bound to the ciphertext (e.g. the blob ID). Returns: ``nonce || ciphertext || tag``. """ nonce = os.urandom(NONCE_LEN) return nonce + AESGCM(self.enc_key).encrypt(nonce, data, aad)
[docs] def decrypt(self, data: bytes, aad: bytes) -> bytes: """Decrypt data produced by :meth:`encrypt`. Args: data: ``nonce || ciphertext || tag``. aad: The associated data used when encrypting. Returns: Plaintext. Raises: CryptoError: If the data was modified or belongs elsewhere. """ try: return AESGCM(self.enc_key).decrypt(data[:NONCE_LEN], data[NONCE_LEN:], aad) except InvalidTag as exc: raise CryptoError("blob failed authentication (corrupted or tampered)") from exc