Skip to main content

coven_crypto/
derivation.rs

1//! HKDF labels are the durable separation between cryptographic purposes (Appendix D).
2
3use hkdf::Hkdf;
4use hmac::{Hmac, KeyInit, Mac};
5use sha2::{Digest, Sha256};
6use zeroize::{Zeroize, Zeroizing};
7
8use crate::{cipher, AuthorshipHasher, CryptoError};
9
10pub(crate) const ENCRYPTION: &[u8] = b"coven/encryption/v1";
11pub(crate) const JOIN_REQUEST: &[u8] = b"coven/join-request/v1";
12pub(crate) const CONFIRMATION_NUMBER: &[u8] = b"coven/confirmation-number/v1";
13pub(crate) const SEALED_BOX: &[u8] = b"coven/sealed-box/v1";
14pub(crate) const HANDOVER: &[u8] = b"coven/handover/v1";
15pub(crate) const OWN_COPY: &[u8] = b"coven/own-copy/v1";
16pub(crate) const AUTHORSHIP: &[u8] = b"coven/row-authorship/v1";
17pub(crate) const KEPT_VALUE: &[u8] = b"coven/kept-value/v1";
18
19pub(crate) fn derive(key: &[u8; 32], context: &[u8]) -> Zeroizing<[u8; 32]> {
20    let mut output = Zeroizing::new([0; 32]);
21    let (mut extracted, hkdf) = Hkdf::<Sha256>::extract(None, key);
22    extracted.as_mut_slice().zeroize();
23    hkdf.expand(context, output.as_mut())
24        .expect("32-byte derived keys fit HKDF-SHA256's output limit");
25    output
26}
27
28pub(crate) fn derive_label(key: &[u8; 32], label: &[u8]) -> Zeroizing<[u8; 32]> {
29    derive(key, &cipher::context(&[label]))
30}
31
32pub(crate) fn mac(key: &[u8; 32]) -> Hmac<Sha256> {
33    Hmac::<Sha256>::new_from_slice(key).expect("HMAC-SHA256 accepts a 32-byte key")
34}
35
36/// A purpose-derived key for objects, including an invite's join request (Appendix D).
37pub struct EncryptionKey(pub(crate) Zeroizing<[u8; 32]>);
38
39impl EncryptionKey {
40    /// Seal an object chunk with a random nonce, binding its whole cleartext prefix.
41    /// Section 0 holds a write's header; part i uses section i + 1. A snapshot
42    /// uses section 0. Indices start at zero within each section.
43    /// Panics if the storage path is empty.
44    pub fn seal_object_chunk(
45        &self,
46        path: &str,
47        prefix: &[u8],
48        section: u64,
49        index: u64,
50        plaintext: &[u8],
51    ) -> Result<Vec<u8>, CryptoError> {
52        cipher::seal_random(&self.0, &object_chunk_aad(path, prefix, section, index), plaintext)
53    }
54
55    /// Open a chunk only at its authenticated path, prefix, section and index.
56    /// Panics if the storage path is empty.
57    pub fn open_object_chunk(
58        &self,
59        path: &str,
60        prefix: &[u8],
61        section: u64,
62        index: u64,
63        sealed: &[u8],
64    ) -> Result<Vec<u8>, CryptoError> {
65        cipher::open_random(&self.0, &object_chunk_aad(path, prefix, section, index), sealed)
66    }
67}
68
69impl std::fmt::Debug for EncryptionKey {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        f.write_str("EncryptionKey([REDACTED])")
72    }
73}
74
75/// Separate encryption and authorship keys for one audience.
76pub struct DerivedKeys {
77    encryption: EncryptionKey,
78    authorship: Zeroizing<[u8; 32]>,
79}
80
81impl DerivedKeys {
82    pub(crate) fn new(key: &[u8; 32]) -> Self {
83        Self {
84            encryption: EncryptionKey(derive_label(key, ENCRYPTION)),
85            authorship: derive_label(key, AUTHORSHIP),
86        }
87    }
88
89    /// Hash a write part's authorship leaves and branches under this
90    /// audience's key, so only its readers can test a row guess (D9, D11).
91    pub fn authorship_hasher(&self) -> AuthorshipHasher {
92        AuthorshipHasher::new(&self.authorship)
93    }
94
95    /// Seal one chunk with this audience's derived encryption key (Appendix D).
96    /// See [`EncryptionKey::seal_object_chunk`] for section and index numbering.
97    pub fn seal_object_chunk(
98        &self,
99        path: &str,
100        prefix: &[u8],
101        section: u64,
102        index: u64,
103        plaintext: &[u8],
104    ) -> Result<Vec<u8>, CryptoError> {
105        self.encryption.seal_object_chunk(path, prefix, section, index, plaintext)
106    }
107
108    /// Re-seal an inner-write or sequence-slot chunk identically on every
109    /// attempt (D9/D11).
110    /// The nonce binds the path, complete cleartext prefix, section, index and
111    /// SHA-256 of the complete chunk plaintext, including any frame bytes.
112    /// Different content at a reused path has different nonce inputs. Retries
113    /// fix plaintext, prefix and key choices to reproduce the same bytes.
114    /// Snapshots, floors and join requests use `seal_object_chunk` instead.
115    pub fn reseal_object_chunk(
116        &self,
117        path: &str,
118        prefix: &[u8],
119        section: u64,
120        index: u64,
121        plaintext: &[u8],
122    ) -> Vec<u8> {
123        let key = &self.encryption.0;
124        let mut nonce = mac(key);
125        nonce.update(&cipher::context(&[
126            b"coven/object-nonce/v2",
127            cipher::storage_path(path),
128            prefix,
129            &section.to_be_bytes(),
130            &index.to_be_bytes(),
131            &Sha256::digest(plaintext),
132        ]));
133        let nonce = nonce.finalize().into_bytes();
134        let nonce: &[u8; 24] = nonce[..24].try_into().expect("24-byte nonce");
135        let mut sealed = nonce.to_vec();
136        sealed.extend(cipher::seal(
137            key,
138            nonce,
139            &object_chunk_aad(path, prefix, section, index),
140            plaintext,
141        ));
142        sealed
143    }
144
145    /// Open a chunk only at its authenticated path, prefix, section and index.
146    /// Panics if the storage path is empty.
147    pub fn open_object_chunk(
148        &self,
149        path: &str,
150        prefix: &[u8],
151        section: u64,
152        index: u64,
153        sealed: &[u8],
154    ) -> Result<Vec<u8>, CryptoError> {
155        self.encryption.open_object_chunk(path, prefix, section, index, sealed)
156    }
157
158    /// Open a header whose authentication identity is inside its plaintext.
159    /// `identity` receives only the fixed routing prefix as an untrusted hint;
160    /// it must only construct the identity, never install or report that hint.
161    /// No plaintext is returned until the ordinary AEAD check succeeds with
162    /// the selected identity, exact prefix, and header coordinates (0, 0).
163    ///
164    /// D9 inner writes use this because their stable write number is sealed.
165    /// ChaCha's keystream does not depend on associated data (RFC 8439 ยง2.8).
166    /// The tentative bytes and cipher state are erased after routing.
167    pub fn open_identified_header<const N: usize>(
168        &self,
169        prefix: &[u8],
170        sealed: &[u8],
171        identity: impl FnOnce(&[u8; N]) -> Result<String, CryptoError>,
172    ) -> Result<Vec<u8>, CryptoError> {
173        use chacha20::{
174            cipher::{StreamCipher, StreamCipherSeek},
175            KeyIvInit, XChaCha20,
176        };
177        let (nonce, ciphertext) = sealed.split_at_checked(24).ok_or(CryptoError::Malformed)?;
178        if ciphertext.len().checked_sub(cipher::FILE_CHUNK_TAG_LEN).is_none_or(|length| length < N)
179        {
180            return Err(CryptoError::Malformed);
181        }
182        let mut tentative = Zeroizing::new([0; N]);
183        tentative.copy_from_slice(&ciphertext[..N]);
184        let key: &[u8; 32] = &self.encryption.0;
185        let nonce: &[u8; 24] = nonce.try_into().expect("24-byte split");
186        let mut stream = XChaCha20::new(key.into(), nonce.into());
187        // Block zero supplies Poly1305's key; payload encryption starts at one.
188        stream.seek(64u64);
189        stream.apply_keystream(tentative.as_mut());
190        let path = identity(&tentative)?;
191        self.open_object_chunk(&path, prefix, 0, 0, sealed)
192    }
193}
194
195impl std::fmt::Debug for DerivedKeys {
196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197        f.write_str("DerivedKeys([REDACTED])")
198    }
199}
200
201fn object_chunk_aad(path: &str, prefix: &[u8], section: u64, index: u64) -> Vec<u8> {
202    cipher::context(&[
203        b"coven/object-chunk/v1",
204        cipher::storage_path(path),
205        prefix,
206        &section.to_be_bytes(),
207        &index.to_be_bytes(),
208    ])
209}
210
211#[cfg(test)]
212#[path = "derivation_tests.rs"]
213mod tests;