Skip to main content

capsule_core/crypto/encryption/
keywrap.rs

1//! `asset-keywrap/v1` — sealing an externally-chosen file key `K` under the album's AMK.
2//!
3//! An asset a member did *not* author — an [adopted web-upload drop] — arrives already
4//! STREAM-encrypted under a random key `K` the guest chose, which no member can re-derive
5//! from the AMK. The adopting client therefore **carries** `K` wrapped under the AMK
6//! instead of deriving it. The wrapped bytes travel in the signed
7//! [manifest](crate::crypto::provenance)'s `wrapped_file_key` field under `key_mode =
8//! wrapped`; a reader holding the AMK unwraps `K` and runs the unchanged
9//! [STREAM construction](super::stream) to decrypt.
10//!
11//! Wire format (fixed length, opaque to the server):
12//!
13//! ```text
14//! +--------------------+----------------------------+----------------+
15//! | wrap_nonce (12)    | AES-256-GCM(K) (32)        | tag (16)       |
16//! +--------------------+----------------------------+----------------+
17//! ```
18//!
19//! The wrap key is `HKDF(ikm=AMK, salt=file_id || wrap_nonce, info="asset-keywrap/v1")`
20//! ([`Amk::derive_wrap_key`]). The fresh `wrap_nonce` is folded into the salt exactly as a
21//! derived key's `nonce_prefix` is, so no `(wrap_key, wrap_nonce)` pair repeats and AES-GCM
22//! nonce reuse is structurally impossible. This is the sole case where a per-file key is
23//! stored rather than recomputed. SSoT: [Encryption § Asset Key Derivation].
24//!
25//! [adopted web-upload drop]: https://docs/design/web-upload/#why-adopt-in-place
26//! [Encryption § Asset Key Derivation]: https://docs/design/cryptography/encryption/#asset-key-derivation
27
28use aes_gcm::aead::{Aead, KeyInit};
29use aes_gcm::{Aes256Gcm, Key, Nonce};
30use uuid::Uuid;
31
32use crate::crypto::CryptoError;
33use crate::crypto::keys::Amk;
34
35/// Length of the fresh per-wrap nonce (the AES-256-GCM nonce for the wrap).
36pub const WRAP_NONCE_LEN: usize = 12;
37/// Length of the wrapped file key: `wrap_nonce(12) ‖ ciphertext(32) ‖ tag(16)`.
38pub const WRAPPED_FILE_KEY_LEN: usize = WRAP_NONCE_LEN + 32 + 16;
39
40/// Seal an externally-chosen 32-byte file key `K` under `amk`, scoped to `file_id`.
41///
42/// Draws a fresh `wrap_nonce`, derives the wrap key with the nonce folded into the salt,
43/// and returns `wrap_nonce ‖ AES-256-GCM(K) ‖ tag` — the bytes stored verbatim in the
44/// manifest's `wrapped_file_key`. Wrap key derivation is deferred to the AMK so nonce
45/// generation and derivation stay coupled (the salt depends on the nonce).
46pub fn seal_file_key(amk: &Amk, file_id: &Uuid, file_key: &[u8; 32]) -> Vec<u8> {
47    let wrap_nonce = crate::crypto::rng::random_array::<WRAP_NONCE_LEN>();
48    let wrap_key = amk.derive_wrap_key(file_id, &wrap_nonce);
49    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&wrap_key));
50    let ct_and_tag = cipher
51        .encrypt(Nonce::from_slice(&wrap_nonce), file_key.as_slice())
52        .expect("AES-256-GCM seal is infallible for a valid key/nonce");
53
54    let mut out = Vec::with_capacity(WRAPPED_FILE_KEY_LEN);
55    out.extend_from_slice(&wrap_nonce);
56    out.extend_from_slice(&ct_and_tag);
57    debug_assert_eq!(out.len(), WRAPPED_FILE_KEY_LEN);
58    out
59}
60
61/// Recover the file key `K` from a `wrapped_file_key` under `amk`, scoped to `file_id`.
62///
63/// Fail-closed: a wrong length is [`CryptoError::Malformed`]; a wrong AMK / `file_id`, a
64/// tampered nonce, or a tampered ciphertext all fail AEAD authentication
65/// ([`CryptoError::Auth`]) — the same terminal rejection any tampered signed field earns.
66pub fn unseal_file_key(amk: &Amk, file_id: &Uuid, wrapped: &[u8]) -> Result<[u8; 32], CryptoError> {
67    if wrapped.len() != WRAPPED_FILE_KEY_LEN {
68        return Err(CryptoError::Malformed("wrapped file key wrong length"));
69    }
70    let (wrap_nonce, ct_and_tag) = wrapped.split_at(WRAP_NONCE_LEN);
71    let wrap_key = amk.derive_wrap_key(file_id, wrap_nonce);
72    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&wrap_key));
73    let plaintext = cipher
74        .decrypt(Nonce::from_slice(wrap_nonce), ct_and_tag)
75        .map_err(|_| CryptoError::Auth("wrapped file key authentication failed"))?;
76    // A valid GCM open of a 32-byte plaintext is exactly 32 bytes; guard defensively.
77    let key: [u8; 32] = plaintext
78        .as_slice()
79        .try_into()
80        .map_err(|_| CryptoError::Malformed("unwrapped file key wrong length"))?;
81    Ok(key)
82}
83
84/// Recover the file key of the **original** a manifest describes, honouring its `key_mode`.
85///
86/// `amk` is the AMK of the epoch the manifest was written under (`core.amk_version`); the
87/// caller resolves it, because where the epoch keys live differs per reader (a workspace's
88/// album, a backup artifact's ledger, a share link's album grant). A `derived` original
89/// re-derives `HKDF(AMK, file_id ‖ nonce_prefix)`; a `wrapped` one — an adopted web-upload
90/// drop, whose key a guest chose and nobody can derive — unwraps `wrapped_file_key` under the
91/// AMK. Every reader that recovers an original's key goes through here, so no reader can
92/// silently assume `derived`.
93///
94/// Fail-closed: a `wrapped` manifest without a `wrapped_file_key` is
95/// [`CryptoError::Malformed`]; a key that does not open is [`CryptoError::Auth`].
96pub fn recover_file_key(
97    amk: &Amk,
98    core: &crate::crypto::provenance::ManifestCore,
99) -> Result<[u8; 32], CryptoError> {
100    recover_file_key_parts(
101        amk,
102        &core.file_id,
103        &core.nonce_prefix,
104        core.key_mode,
105        core.wrapped_file_key.as_ref(),
106    )
107}
108
109/// [`recover_file_key`] over the manifest fields it reads, for a reader that holds those
110/// fields but not the manifest: the share viewer, which is served an asset's key-free crypto
111/// parameters and never its signed manifest (that would carry the device and account ids the
112/// export strip removes). Same dispatch and the same fail-closed errors.
113pub fn recover_file_key_parts(
114    amk: &Amk,
115    file_id: &Uuid,
116    nonce_prefix: &[u8],
117    key_mode: crate::crypto::provenance::KeyMode,
118    wrapped_file_key: Option<&crate::crypto::provenance::WrappedFileKey>,
119) -> Result<[u8; 32], CryptoError> {
120    use crate::crypto::provenance::KeyMode;
121    match key_mode {
122        KeyMode::Derived => Ok(amk.derive_file_key(file_id, nonce_prefix)),
123        KeyMode::Wrapped => {
124            let wrapped = wrapped_file_key.ok_or(CryptoError::Malformed(
125                "wrapped key mode without a wrapped_file_key",
126            ))?;
127            unseal_file_key(amk, file_id, &wrapped.0)
128        }
129    }
130}
131
132#[cfg(test)]
133mod tests;