Skip to main content

bitwarden_crypto/safe/key_hierarchy/
key_encryption_key.rs

1use crate::{CoseKeyView, KeySlotIds, KeyStoreContext, SymmetricCryptoKey, SymmetricKeyAlgorithm};
2
3/// A key-encryption-key (KEK): a key that can be used to encrypt other keys, and shared between
4/// users. It MAY be re-used for multiple encrypt operations.
5///
6/// New KEKs are XAES-256-GCM keys (see [`KeyEncryptionKey::make`]). AES-256-CBC-HMAC keys are also
7/// accepted as KEKs, so that existing (V1) keys that act as KEKs, such as user keys and cipher
8/// keys, can adopt safe objects before they are rotated. AES-256-CBC-HMAC uses a random 128-bit IV,
9/// so it does not have the nonce-reuse problem that rules out plain AES-256-GCM for a reused key.
10///
11/// See the `key_hierarchy` module documentation for its place in the key hierarchy.
12pub struct KeyEncryptionKey;
13
14/// The reasons a key cannot be used as a [`KeyEncryptionKey`].
15#[derive(Debug)]
16pub(crate) enum KeyEncryptionKeyError {
17    /// There is no key in the given key slot.
18    Missing,
19    /// The key uses an algorithm that is not permitted for a key-encryption-key.
20    WrongKeyType,
21}
22
23impl KeyEncryptionKey {
24    /// Generates a fresh key-encryption-key, stores it in the key store context, and returns its
25    /// key id. Key material never leaves the key store.
26    pub fn make<Ids: KeySlotIds>(ctx: &mut KeyStoreContext<Ids>) -> Ids::Symmetric {
27        // XAES-256-GCM is used because a KEK is reused: the same key wraps many other keys over its
28        // lifetime, and each wrap draws a fresh random nonce under that one key. Plain AES-256-GCM
29        // has only a 96-bit nonce, so across the many encryptions a long-lived KEK performs, two
30        // random nonces could eventually collide -- and a nonce reuse in GCM is catastrophic (it
31        // leaks the authentication subkey and the XOR of the affected plaintexts). XAES-256-GCM
32        // extends the nonce to 192 bits, making random-nonce collisions negligible even under heavy
33        // reuse.
34        ctx.make_symmetric_key(SymmetricKeyAlgorithm::XAes256Gcm)
35    }
36
37    /// Looks up the symmetric key `key_id` refers to and returns a [`CoseKeyView`] of it, if it is
38    /// an XAES-256-GCM or AES-256-CBC-HMAC key, the algorithms accepted for a [`KeyEncryptionKey`].
39    pub(crate) fn get_cose_key_view<'k, Ids: KeySlotIds>(
40        ctx: &'k KeyStoreContext<'_, Ids>,
41        key_id: Ids::Symmetric,
42    ) -> Result<CoseKeyView<'k>, KeyEncryptionKeyError> {
43        match ctx
44            .get_symmetric_key(key_id)
45            .map_err(|_| KeyEncryptionKeyError::Missing)?
46        {
47            SymmetricCryptoKey::XAes256GcmKey(key) => Ok(CoseKeyView::XAes256Gcm(key)),
48            SymmetricCryptoKey::Aes256CbcHmacKey(key) => Ok(CoseKeyView::Aes256CbcHmac(key)),
49            _ => Err(KeyEncryptionKeyError::WrongKeyType),
50        }
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57    use crate::{
58        KeyStore,
59        cose::symmetric::CoseContentEncryptionAlgorithm,
60        traits::tests::{TestIds, TestSymmKey},
61    };
62
63    #[test]
64    fn make_generates_xaes256_gcm_key_in_context() {
65        let key_store = KeyStore::<TestIds>::default();
66        let mut ctx = key_store.context_mut();
67
68        let kek_id = KeyEncryptionKey::make(&mut ctx);
69
70        let key = ctx.get_symmetric_key(kek_id).expect("KEK should be stored");
71        assert!(matches!(key, SymmetricCryptoKey::XAes256GcmKey(_)));
72    }
73
74    #[test]
75    fn make_generates_distinct_keys() {
76        let key_store = KeyStore::<TestIds>::default();
77        let mut ctx = key_store.context_mut();
78
79        let first = KeyEncryptionKey::make(&mut ctx);
80        let second = KeyEncryptionKey::make(&mut ctx);
81
82        ctx.assert_symmetric_keys_not_equal(first, second);
83    }
84
85    #[test]
86    fn get_cose_key_view_accepts_kek_algorithms() {
87        let key_store = KeyStore::<TestIds>::default();
88        let mut ctx = key_store.context_mut();
89
90        for (algorithm, expected_cose_algorithm) in [
91            (
92                SymmetricKeyAlgorithm::XAes256Gcm,
93                CoseContentEncryptionAlgorithm::XAes256Gcm,
94            ),
95            (
96                SymmetricKeyAlgorithm::Aes256CbcHmac,
97                CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead,
98            ),
99        ] {
100            let key_id = ctx.make_symmetric_key(algorithm);
101            let view = KeyEncryptionKey::get_cose_key_view(&ctx, key_id)
102                .expect("KEK algorithm should be accepted");
103            assert_eq!(view.algorithm(), expected_cose_algorithm);
104        }
105    }
106
107    #[test]
108    fn get_cose_key_view_rejects_non_kek_algorithms() {
109        let key_store = KeyStore::<TestIds>::default();
110        let mut ctx = key_store.context_mut();
111
112        for algorithm in [
113            SymmetricKeyAlgorithm::Aes256Gcm,
114            SymmetricKeyAlgorithm::XChaCha20Poly1305,
115        ] {
116            let key_id = ctx.make_symmetric_key(algorithm);
117            assert!(matches!(
118                KeyEncryptionKey::get_cose_key_view(&ctx, key_id),
119                Err(KeyEncryptionKeyError::WrongKeyType)
120            ));
121        }
122    }
123
124    #[test]
125    fn get_cose_key_view_rejects_missing_key() {
126        let key_store = KeyStore::<TestIds>::default();
127        let ctx = key_store.context();
128
129        assert!(matches!(
130            KeyEncryptionKey::get_cose_key_view(&ctx, TestSymmKey::A(0)),
131            Err(KeyEncryptionKeyError::Missing)
132        ));
133    }
134}