Skip to main content

vcon_server/
envelope.rs

1//! Keys and the encryption that protects every stored body.
2
3use std::fmt;
4use std::io::{self, Read};
5use std::path::Path;
6
7use aws_lc_rs::aead::{AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey};
8use aws_lc_rs::digest::{SHA256, digest};
9use aws_lc_rs::hkdf::{HKDF_SHA256, KeyType, Salt};
10use uuid::Uuid;
11use zeroize::Zeroizing;
12
13use crate::ids::{KeyId, TenantId, VersionId};
14
15mod locked;
16
17use locked::LockedPage;
18
19/// The length of every key, in bytes.
20const KEY_LEN: usize = 32;
21
22/// The first byte of every blob, naming its layout and algorithm:
23/// AES-256-GCM with a 96-bit nonce and a 128-bit tag.
24const FORMAT: u8 = 1;
25const NONCE_LEN: usize = 12;
26const TAG_LEN: usize = 16;
27
28/// The start of every associated data.
29const LABEL: &[u8] = b"vcon-server/v1";
30
31/// The HKDF info that makes a catalog key.
32const CATALOG_LABEL: &[u8] = b"vcon-server/v1 catalog";
33
34/// A 256-bit key. Its bytes live only in a page of their own that is locked
35/// in memory, so they never reach swap, and that core dumps leave out; they
36/// are zeroed when the key is dropped. A key cannot be copied, and Debug
37/// shows only its id.
38pub struct Key {
39    page: LockedPage,
40}
41
42impl fmt::Debug for Key {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        f.debug_struct("Key")
45            .field("id", &format_args!("{}", self.id()))
46            .finish_non_exhaustive()
47    }
48}
49
50impl Key {
51    /// Makes a new random key, refusing if its memory cannot be locked.
52    ///
53    /// # Errors
54    ///
55    /// [`KeyError::Memory`] if the key's page cannot be locked or kept out
56    /// of core dumps.
57    ///
58    /// # Panics
59    ///
60    /// Never: AWS-LC aborts the process rather than fail to give random
61    /// bytes.
62    pub fn generate() -> Result<Key, KeyError> {
63        let mut page = LockedPage::new().map_err(KeyError::Memory)?;
64        // AWS-LC's RAND_bytes aborts the process when it cannot get enough
65        // randomness, so `fill` never returns its error.
66        aws_lc_rs::rand::fill(&mut page.bytes_mut()[..KEY_LEN])
67            .expect("AWS-LC aborts instead of failing");
68        Ok(Key { page })
69    }
70
71    /// Loads the master key: the file must hold exactly 32 bytes. They are
72    /// read straight into the key's own locked page.
73    ///
74    /// # Errors
75    ///
76    /// [`KeyError::Read`] if the file cannot be opened or read,
77    /// [`KeyError::Refused`] if it is not a regular file, another user owns
78    /// it, or its mode lets other users read it or its group change it (the
79    /// one secret-file rule, `0600`, `0400` or `0640`),
80    /// [`KeyError::WrongSize`] if it holds other than 32 bytes, and
81    /// [`KeyError::Memory`] if the key's page cannot be locked.
82    pub fn load_master(path: &Path) -> Result<Key, KeyError> {
83        Key::load_master_named(path, "master_key")
84    }
85
86    /// [`Key::load_master`], with the file named `key` in a refusal, such as
87    /// `--new-master` for the key `rekey master` moves to.
88    ///
89    /// # Errors
90    ///
91    /// As [`Key::load_master`].
92    pub fn load_master_named(path: &Path, key: &str) -> Result<Key, KeyError> {
93        let mut page = LockedPage::new().map_err(KeyError::Memory)?;
94        let mut file = crate::secret_file::check_open(path).map_err(|problem| match problem {
95            crate::secret_file::Problem::Io(e) => KeyError::Read(e),
96            crate::secret_file::Problem::Refused(refusal) => {
97                KeyError::Refused(crate::secret_file::describe(key, path, refusal))
98            }
99        })?;
100        let buf = page.bytes_mut();
101        file.read_exact(&mut buf[..KEY_LEN])
102            .map_err(|e| match e.kind() {
103                io::ErrorKind::UnexpectedEof => KeyError::WrongSize,
104                _ => KeyError::Read(e),
105            })?;
106        if file
107            .read(&mut buf[KEY_LEN..=KEY_LEN])
108            .map_err(KeyError::Read)?
109            != 0
110        {
111            return Err(KeyError::WrongSize);
112        }
113        Ok(Key { page })
114    }
115
116    /// The key's id: the first 8 bytes of its SHA-256 hash.
117    ///
118    /// # Panics
119    ///
120    /// Never: a SHA-256 hash is 32 bytes.
121    #[must_use]
122    pub fn id(&self) -> KeyId {
123        let hash = digest(&SHA256, self.bytes());
124        KeyId(hash.as_ref()[..8].try_into().expect("SHA-256 is 32 bytes"))
125    }
126
127    fn bytes(&self) -> &[u8] {
128        &self.page.bytes()[..KEY_LEN]
129    }
130
131    /// The key as SQLCipher's raw key literal, `x'` and 64 hex digits and
132    /// `'`, in a buffer that is zeroed when dropped. It is built at its
133    /// final size, so no shorter copy is left behind by a reallocation.
134    pub(crate) fn sqlcipher_raw(&self) -> Zeroizing<String> {
135        const HEX: &[u8; 16] = b"0123456789abcdef";
136        let mut literal = Zeroizing::new(String::with_capacity(3 + 2 * KEY_LEN));
137        literal.push_str("x'");
138        for byte in self.bytes() {
139            literal.push(char::from(HEX[usize::from(byte >> 4)]));
140            literal.push(char::from(HEX[usize::from(byte & 0x0f)]));
141        }
142        literal.push('\'');
143        literal
144    }
145}
146
147/// Why a key could not be made.
148#[derive(Debug)]
149pub enum KeyError {
150    /// The key's memory could not be locked or kept out of core dumps.
151    Memory(io::Error),
152    /// The master key file could not be opened or read.
153    Read(io::Error),
154    /// The master key file breaks the secret-file rule; the text names
155    /// the key, the file and the command that fixes it.
156    Refused(String),
157    /// The master key file does not hold exactly 32 bytes.
158    WrongSize,
159    /// A wrapped key did not open. Like [`OpenError`], it does not say which
160    /// part was wrong.
161    Damaged,
162}
163
164/// The I/O error itself is given by `source`, not repeated here.
165impl fmt::Display for KeyError {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.write_str(match self {
168            KeyError::Refused(why) => why,
169            KeyError::Memory(_) => "the key's memory could not be locked or kept out of core dumps",
170            KeyError::Read(_) => "the master key file could not be read",
171            KeyError::WrongSize => "the master key file does not hold exactly 32 bytes",
172            KeyError::Damaged => "a wrapped key did not open",
173        })
174    }
175}
176
177impl std::error::Error for KeyError {
178    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
179        match self {
180            KeyError::Memory(e) | KeyError::Read(e) => Some(e),
181            KeyError::Refused(_) | KeyError::WrongSize | KeyError::Damaged => None,
182        }
183    }
184}
185
186/// Locks every page of this process in memory, now and as it grows, so
187/// nothing it holds can reach swap: not AWS-LC's expanded keys, which live
188/// in its own allocations for the length of one call, and not plaintext
189/// bodies. It fails if the lock limit is too low; the operator then raises
190/// it (for example LimitMEMLOCK=infinity under systemd).
191///
192/// # Errors
193///
194/// The error mlockall(2) gives: ENOMEM when the limit is too low, EPERM
195/// when it is zero and the process may not lock memory.
196pub fn lock_all_memory() -> io::Result<()> {
197    // SAFETY: mlockall takes only flags.
198    if unsafe { libc::mlockall(libc::MCL_CURRENT | libc::MCL_FUTURE) } != 0 {
199        return Err(io::Error::last_os_error());
200    }
201    Ok(())
202}
203
204/// Stops this process from writing core dumps: the core size limit is set
205/// to zero and the process is marked not dumpable, which also stops other
206/// processes of the same user from reading its memory. Neither is enough on
207/// its own: the limit is not enforced when core dumps are piped to a
208/// program, and a host with `suid_dumpable` set to 2 still dumps processes
209/// that are not dumpable. Each key's page is left out of core dumps as well.
210///
211/// # Errors
212///
213/// The error setrlimit(2) or prctl(2) gives.
214pub fn disable_core_dumps() -> io::Result<()> {
215    let none = libc::rlimit {
216        rlim_cur: 0,
217        rlim_max: 0,
218    };
219    // SAFETY: `none` is a valid rlimit.
220    if unsafe { libc::setrlimit(libc::RLIMIT_CORE, &none) } != 0 {
221        return Err(io::Error::last_os_error());
222    }
223    // SAFETY: PR_SET_DUMPABLE takes one integer argument.
224    if unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0) } != 0 {
225        return Err(io::Error::last_os_error());
226    }
227    Ok(())
228}
229
230/// What a sealed or wrapped value belongs to. It is bound into the
231/// encryption, so a value moved to another tenant, uuid or version does
232/// not open.
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub enum Context {
235    /// A tenant key, wrapped under the master key.
236    Tenant {
237        /// The tenant the key belongs to.
238        tenant: TenantId,
239    },
240    /// One version's data key, wrapped under its tenant key, and the body
241    /// sealed under that data key.
242    Version {
243        /// The tenant the vCon belongs to.
244        tenant: TenantId,
245        /// The vCon's uuid.
246        uuid: Uuid,
247        /// The version.
248        version: VersionId,
249    },
250}
251
252impl Context {
253    /// The label, the blob's format byte, then the context in fixed-length
254    /// fields after a byte naming its kind, so no two contexts give the
255    /// same bytes.
256    fn associated_data(&self, format: u8) -> Vec<u8> {
257        let mut ad = LABEL.to_vec();
258        ad.push(format);
259        match self {
260            Context::Tenant { tenant } => {
261                ad.push(1);
262                ad.extend(tenant.0);
263            }
264            Context::Version {
265                tenant,
266                uuid,
267                version,
268            } => {
269                ad.push(2);
270                ad.extend(tenant.0);
271                ad.extend(uuid.as_bytes());
272                ad.extend(version.0);
273            }
274        }
275        ad
276    }
277}
278
279/// A sealed body or wrapped key did not open. It carries no detail, so a
280/// caller cannot tell which part was wrong.
281#[derive(Debug, PartialEq, Eq)]
282pub struct OpenError;
283
284impl fmt::Display for OpenError {
285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286        f.write_str("the blob did not open under this key and context")
287    }
288}
289
290impl std::error::Error for OpenError {}
291
292/// How many bytes a sealed blob holds beyond its plaintext: the format
293/// byte, the nonce and the tag.
294pub(crate) const SEALED_OVERHEAD: usize = 1 + NONCE_LEN + TAG_LEN;
295
296/// Encrypts `plaintext` under `data_key`, bound to `ctx`, with a random
297/// nonce. The blob is the format byte, the nonce, the ciphertext and the
298/// tag.
299///
300/// # Panics
301///
302/// Never: AWS-LC aborts the process rather than fail to give random
303/// bytes.
304#[must_use]
305pub fn seal(data_key: &Key, ctx: &Context, plaintext: &[u8]) -> Vec<u8> {
306    // Drawn whole from the system generator, so no fixed value is ever a
307    // nonce, even for a moment.
308    let nonce: [u8; NONCE_LEN] = aws_lc_rs::rand::generate(&aws_lc_rs::rand::SystemRandom::new())
309        .expect("AWS-LC aborts instead of failing")
310        .expose();
311    seal_with_nonce(data_key.bytes(), nonce, ctx, plaintext)
312}
313
314/// Decrypts a blob made by [`seal`] with the same key and context. Any
315/// change to the blob, the context or the key is an error, never partial
316/// plaintext.
317///
318/// # Errors
319///
320/// [`OpenError`] for a blob that does not open under this key and context.
321pub fn open(data_key: &Key, ctx: &Context, blob: &[u8]) -> Result<Vec<u8>, OpenError> {
322    let mut text = vec![0; blob.len().saturating_sub(1 + NONCE_LEN)];
323    let len = open_into(data_key.bytes(), ctx, blob, &mut text)?;
324    text.truncate(len);
325    Ok(text)
326}
327
328/// Wraps `key` under `wrapping`, bound to `ctx`: a blob like [`seal`]'s,
329/// whose plaintext is the key.
330#[must_use]
331pub fn wrap(wrapping: &Key, ctx: &Context, key: &Key) -> Vec<u8> {
332    seal(wrapping, ctx, key.bytes())
333}
334
335/// Unwraps a key made by [`wrap`] with the same wrapping key and context.
336/// It is opened straight into the new key's own locked page, so the plain
337/// key is never anywhere else; on any error that page is dropped, and so
338/// zeroed.
339///
340/// # Errors
341///
342/// [`KeyError::Damaged`] for a blob that does not open under this key and
343/// context to exactly 32 bytes, and [`KeyError::Memory`] if the new key's
344/// page cannot be locked.
345pub fn unwrap(wrapping: &Key, ctx: &Context, wrapped: &[u8]) -> Result<Key, KeyError> {
346    let mut page = LockedPage::new().map_err(KeyError::Memory)?;
347    match open_into(wrapping.bytes(), ctx, wrapped, page.bytes_mut()) {
348        Ok(KEY_LEN) => Ok(Key { page }),
349        _ => Err(KeyError::Damaged),
350    }
351}
352
353/// Moves a wrapped key from `old` to `new`, keeping its context: the
354/// rotation step. The plain key exists only in its own locked page in
355/// between, and what it protects is never re-encrypted.
356///
357/// # Errors
358///
359/// Any error [`unwrap`] gives for `wrapped` under `old`.
360pub fn rewrap(old: &Key, new: &Key, ctx: &Context, wrapped: &[u8]) -> Result<Vec<u8>, KeyError> {
361    let key = unwrap(old, ctx, wrapped)?;
362    Ok(wrap(new, ctx, &key))
363}
364
365/// Whether a key that has already wrapped `wraps` keys may wrap another.
366#[derive(Debug, Clone, Copy, PartialEq, Eq)]
367pub enum WrapLimit {
368    /// Wrap.
369    Allow,
370    /// Wrap, and warn that the key needs rotating.
371    Warn,
372    /// Refuse the write until the key is rotated.
373    Refuse,
374}
375
376/// The wrap-count limit for one wrapping key. Each wrap uses a random
377/// nonce, and NIST SP 800-38D 8.3 allows at most 2^32 such encryptions
378/// under one key, so a key that has made 2^32 wraps makes no more. The
379/// warning starts at half that.
380#[must_use]
381pub fn wrap_limit(wraps: u64) -> WrapLimit {
382    const REFUSE_AT: u64 = 1 << 32;
383    const WARN_AT: u64 = 1 << 31;
384    if wraps >= REFUSE_AT {
385        WrapLimit::Refuse
386    } else if wraps >= WARN_AT {
387        WrapLimit::Warn
388    } else {
389        WrapLimit::Allow
390    }
391}
392
393/// Decrypts `blob` into the start of `out` and returns the plaintext's
394/// length. `out` must hold the blob's ciphertext and tag.
395fn open_into(key: &[u8], ctx: &Context, blob: &[u8], out: &mut [u8]) -> Result<usize, OpenError> {
396    let (&format, rest) = blob.split_first().ok_or(OpenError)?;
397    let (nonce, sealed) = rest.split_first_chunk::<NONCE_LEN>().ok_or(OpenError)?;
398    let text = out.get_mut(..sealed.len()).ok_or(OpenError)?;
399    text.copy_from_slice(sealed);
400    gcm_open(key, *nonce, &ctx.associated_data(format), text)
401}
402
403/// The key of the catalog that `parent` protects: the master key's for
404/// server.sqlite, a tenant key's for that tenant's catalog. It is HKDF-SHA256
405/// of the parent with no salt and the info `vcon-server/v1 catalog`, made in
406/// a locked page of its own and never stored.
407///
408/// # Errors
409///
410/// [`KeyError::Memory`] if the key's page cannot be locked or kept out
411/// of core dumps.
412pub fn catalog_key(parent: &Key) -> Result<Key, KeyError> {
413    let mut page = LockedPage::new().map_err(KeyError::Memory)?;
414    hkdf_sha256(
415        &[],
416        parent.bytes(),
417        CATALOG_LABEL,
418        &mut page.bytes_mut()[..KEY_LEN],
419    );
420    Ok(Key { page })
421}
422
423/// HKDF (RFC 5869) with SHA-256, filling `out`.
424fn hkdf_sha256(salt: &[u8], ikm: &[u8], info: &[u8], out: &mut [u8]) {
425    struct Len(usize);
426    impl KeyType for Len {
427        fn len(&self) -> usize {
428            self.0
429        }
430    }
431    // HKDF refuses only outputs over 255 hashes (8160 bytes); every caller
432    // asks for far less.
433    Salt::new(HKDF_SHA256, salt)
434        .extract(ikm)
435        .expand(&[info], Len(out.len()))
436        .and_then(|okm| okm.fill(out))
437        .expect("within HKDF's output limit");
438}
439
440fn seal_with_nonce(key: &[u8], nonce: [u8; NONCE_LEN], ctx: &Context, plaintext: &[u8]) -> Vec<u8> {
441    let mut blob = Vec::with_capacity(1 + NONCE_LEN + plaintext.len() + TAG_LEN);
442    blob.push(FORMAT);
443    blob.extend(nonce);
444    blob.extend(plaintext);
445    let ad = ctx.associated_data(FORMAT);
446    let tag = gcm_seal(key, nonce, &ad, &mut blob[1 + NONCE_LEN..]);
447    blob.extend(tag);
448    blob
449}
450
451fn aead_key(key: &[u8]) -> LessSafeKey {
452    LessSafeKey::new(UnboundKey::new(&AES_256_GCM, key).expect("every key is 32 bytes"))
453}
454
455/// Encrypts `in_out` in place and returns the tag.
456fn gcm_seal(key: &[u8], nonce: [u8; NONCE_LEN], ad: &[u8], in_out: &mut [u8]) -> [u8; TAG_LEN] {
457    // AWS-LC refuses only inputs over 2^36 - 32 bytes, short output buffers
458    // and nonces of another size. Keys are 32 bytes, and the request size
459    // limit must keep bodies far below 64 GiB.
460    let tag = aead_key(key)
461        .seal_in_place_separate_tag(Nonce::assume_unique_for_key(nonce), Aad::from(ad), in_out)
462        .expect("within GCM's limits");
463    tag.as_ref().try_into().expect("a 16-byte tag")
464}
465
466/// Decrypts ciphertext followed by its tag in place and returns the length
467/// of the plaintext now at the start of `in_out`.
468fn gcm_open(
469    key: &[u8],
470    nonce: [u8; NONCE_LEN],
471    ad: &[u8],
472    in_out: &mut [u8],
473) -> Result<usize, OpenError> {
474    aead_key(key)
475        .open_in_place(Nonce::assume_unique_for_key(nonce), Aad::from(ad), in_out)
476        .map(|plaintext| plaintext.len())
477        .map_err(|_| OpenError)
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483
484    #[test]
485    fn every_byte_of_a_key_is_random() {
486        let keys: Vec<Key> = (0..8).map(|_| Key::generate().expect("key")).collect();
487        for i in 0..KEY_LEN {
488            let first = keys[0].bytes()[i];
489            assert!(
490                keys.iter().any(|k| k.bytes()[i] != first),
491                "byte {i} is {first} in all eight keys"
492            );
493        }
494    }
495
496    fn hex(text: &str) -> Vec<u8> {
497        (0..text.len())
498            .step_by(2)
499            .map(|i| u8::from_str_radix(&text[i..i + 2], 16).expect("hex"))
500            .collect()
501    }
502
503    /// Test Case 16 of McGrew and Viega, "The Galois/Counter Mode of
504    /// Operation (GCM)": AES-256, a 96-bit IV and additional data. The same
505    /// values are in AWS-LC's gcm_tests.txt.
506    #[test]
507    fn aes_256_gcm_matches_the_published_vector() {
508        let key = hex("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308");
509        let nonce: [u8; 12] = hex("cafebabefacedbaddecaf888")
510            .try_into()
511            .expect("12 bytes");
512        let ad = hex("feedfacedeadbeeffeedfacedeadbeefabaddad2");
513        let mut text = hex(concat!(
514            "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72",
515            "1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39"
516        ));
517        let tag = gcm_seal(&key, nonce, &ad, &mut text);
518        assert_eq!(
519            text,
520            hex(concat!(
521                "522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa",
522                "8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662"
523            )),
524            "the ciphertext is Test Case 16's"
525        );
526        assert_eq!(
527            tag.to_vec(),
528            hex("76fc6ece0f4e1768cddf8853bb2d551b"),
529            "the tag is Test Case 16's"
530        );
531    }
532
533    const TENANT: TenantId = TenantId([0x11; 16]);
534    const VERSION: VersionId = VersionId([0x22; 16]);
535    const UUID: Uuid = Uuid::from_bytes([0x33; 16]);
536
537    fn version_ctx() -> Context {
538        Context::Version {
539            tenant: TENANT,
540            uuid: UUID,
541            version: VERSION,
542        }
543    }
544
545    /// The blob layout and the associated data are written out here byte by
546    /// byte, so a change to either, which would make stored bodies
547    /// unreadable, fails this test.
548    #[test]
549    fn a_blob_is_the_format_byte_nonce_ciphertext_and_tag() {
550        let key = [0x44; 32];
551        let nonce = [0x55; 12];
552        let mut ad = b"vcon-server/v1".to_vec();
553        ad.extend([1, 2]);
554        ad.extend([0x11; 16]);
555        ad.extend([0x33; 16]);
556        ad.extend([0x22; 16]);
557        let mut ciphertext = b"body".to_vec();
558        let tag = gcm_seal(&key, nonce, &ad, &mut ciphertext);
559        let mut expected = vec![1];
560        expected.extend(nonce);
561        expected.extend(ciphertext);
562        expected.extend(tag);
563        assert_eq!(
564            seal_with_nonce(&key, nonce, &version_ctx(), b"body"),
565            expected,
566            "format byte, nonce, ciphertext, tag, under a version's associated data"
567        );
568
569        let mut tenant_ad = b"vcon-server/v1".to_vec();
570        tenant_ad.extend([1, 1]);
571        tenant_ad.extend([0x11; 16]);
572        let mut ciphertext = b"key".to_vec();
573        let tag = gcm_seal(&key, nonce, &tenant_ad, &mut ciphertext);
574        let mut expected = vec![1];
575        expected.extend(nonce);
576        expected.extend(ciphertext);
577        expected.extend(tag);
578        let tenant = Context::Tenant { tenant: TENANT };
579        assert_eq!(
580            seal_with_nonce(&key, nonce, &tenant, b"key"),
581            expected,
582            "a tenant blob: the same layout under the tenant's associated data"
583        );
584    }
585
586    #[test]
587    fn a_sealed_blob_is_its_body_and_the_stated_overhead() {
588        let key = Key::generate().expect("key");
589        let ctx = Context::Tenant {
590            tenant: crate::ids::TenantId([7; 16]),
591        };
592        for len in [0, 1, 1000] {
593            assert_eq!(
594                seal(&key, &ctx, &vec![0x5a; len]).len(),
595                len + SEALED_OVERHEAD,
596                "a body of {len} bytes"
597            );
598        }
599    }
600
601    #[test]
602    fn a_sealed_body_opens_with_the_same_key_and_context() {
603        let key = Key::generate().expect("key");
604        for body in [&b""[..], b"x", &[0xa5; 100_000]] {
605            let blob = seal(&key, &version_ctx(), body);
606            assert_eq!(
607                blob.len(),
608                1 + 12 + body.len() + 16,
609                "a format byte, a 12-byte nonce, the ciphertext as long as the body, a 16-byte tag"
610            );
611            assert_eq!(
612                open(&key, &version_ctx(), &blob).as_deref(),
613                Ok(body),
614                "the same key and context open what they sealed"
615            );
616        }
617    }
618
619    /// Every byte of the nonce is random: over 1000 seals no nonce repeats
620    /// and no byte position keeps one value. For 96 random bits either
621    /// event has a probability below 2^-76.
622    #[test]
623    fn every_byte_of_a_nonce_is_random() {
624        let key = Key::generate().expect("key");
625        let nonces: Vec<[u8; 12]> = (0..1000)
626            .map(|_| {
627                let blob = seal(&key, &version_ctx(), b"same");
628                blob[1..13].try_into().expect("12 bytes")
629            })
630            .collect();
631        let distinct: std::collections::HashSet<_> = nonces.iter().collect();
632        assert_eq!(distinct.len(), nonces.len(), "a nonce repeated");
633        for i in 0..12 {
634            assert!(
635                nonces.iter().any(|n| n[i] != nonces[0][i]),
636                "byte {i} of the nonce never changes"
637            );
638        }
639    }
640
641    #[test]
642    fn changing_any_byte_of_a_blob_fails() {
643        let key = Key::generate().expect("key");
644        let blob = seal(&key, &version_ctx(), b"a body");
645        assert_eq!(
646            open(&key, &version_ctx(), &blob).as_deref(),
647            Ok(&b"a body"[..]),
648            "unchanged"
649        );
650        for i in 0..blob.len() {
651            let mut bad = blob.clone();
652            bad[i] ^= 0x01;
653            assert_eq!(open(&key, &version_ctx(), &bad), Err(OpenError), "byte {i}");
654        }
655        for len in 0..blob.len() {
656            assert_eq!(
657                open(&key, &version_ctx(), &blob[..len]),
658                Err(OpenError),
659                "first {len} bytes"
660            );
661        }
662        let mut longer = blob.clone();
663        longer.push(0);
664        assert_eq!(
665            open(&key, &version_ctx(), &longer),
666            Err(OpenError),
667            "one byte more"
668        );
669    }
670
671    #[test]
672    fn another_context_or_key_fails() {
673        let key = Key::generate().expect("key");
674        let blob = seal(&key, &version_ctx(), b"a body");
675        assert_eq!(
676            open(&key, &version_ctx(), &blob).as_deref(),
677            Ok(&b"a body"[..]),
678            "unchanged"
679        );
680        let others = [
681            Context::Version {
682                tenant: TenantId([0x12; 16]),
683                uuid: UUID,
684                version: VERSION,
685            },
686            Context::Version {
687                tenant: TENANT,
688                uuid: Uuid::from_bytes([0x34; 16]),
689                version: VERSION,
690            },
691            Context::Version {
692                tenant: TENANT,
693                uuid: UUID,
694                version: VersionId([0x23; 16]),
695            },
696            Context::Tenant { tenant: TENANT },
697        ];
698        for other in others {
699            assert_eq!(open(&key, &other, &blob), Err(OpenError), "{other:?}");
700        }
701        let other_key = Key::generate().expect("key");
702        assert_eq!(
703            open(&other_key, &version_ctx(), &blob),
704            Err(OpenError),
705            "the tag fails under any other key"
706        );
707    }
708
709    const TENANT_CTX: Context = Context::Tenant { tenant: TENANT };
710
711    #[test]
712    fn a_wrapped_key_unwraps_to_the_same_key() {
713        let wrapping = Key::generate().expect("key");
714        let key = Key::generate().expect("key");
715        for ctx in [TENANT_CTX, version_ctx()] {
716            let wrapped = wrap(&wrapping, &ctx, &key);
717            assert_eq!(
718                wrapped.len(),
719                1 + 12 + KEY_LEN + 16,
720                "a wrapped key is a sealed blob of the key's 32 bytes"
721            );
722            let unwrapped = unwrap(&wrapping, &ctx, &wrapped).expect("unwraps");
723            assert_eq!(
724                unwrapped.bytes(),
725                key.bytes(),
726                "unwrap gives back the key wrapped"
727            );
728        }
729    }
730
731    #[test]
732    fn changing_any_byte_of_a_wrapped_key_fails() {
733        let wrapping = Key::generate().expect("key");
734        let key = Key::generate().expect("key");
735        let wrapped = wrap(&wrapping, &TENANT_CTX, &key);
736        assert!(
737            unwrap(&wrapping, &TENANT_CTX, &wrapped).is_ok(),
738            "unchanged"
739        );
740        for i in 0..wrapped.len() {
741            let mut bad = wrapped.clone();
742            bad[i] ^= 0x01;
743            assert!(unwrap(&wrapping, &TENANT_CTX, &bad).is_err(), "byte {i}");
744        }
745        for len in 0..wrapped.len() {
746            assert!(
747                unwrap(&wrapping, &TENANT_CTX, &wrapped[..len]).is_err(),
748                "first {len} bytes"
749            );
750        }
751    }
752
753    #[test]
754    fn another_context_or_wrapping_key_fails() {
755        let wrapping = Key::generate().expect("key");
756        let key = Key::generate().expect("key");
757        let wrapped = wrap(&wrapping, &TENANT_CTX, &key);
758        assert!(
759            unwrap(&wrapping, &TENANT_CTX, &wrapped).is_ok(),
760            "unchanged"
761        );
762        let other_tenant = Context::Tenant {
763            tenant: TenantId([0x12; 16]),
764        };
765        assert!(
766            unwrap(&wrapping, &other_tenant, &wrapped).is_err(),
767            "other tenant"
768        );
769        assert!(
770            unwrap(&wrapping, &version_ctx(), &wrapped).is_err(),
771            "other kind"
772        );
773        let other = Key::generate().expect("key");
774        assert!(
775            unwrap(&other, &TENANT_CTX, &wrapped).is_err(),
776            "other wrapping key"
777        );
778    }
779
780    #[test]
781    fn only_a_32_byte_key_unwraps() {
782        let wrapping = Key::generate().expect("key");
783        for len in [0, 31, 33, 64] {
784            let sealed = seal(&wrapping, &TENANT_CTX, &vec![7; len]);
785            assert!(
786                unwrap(&wrapping, &TENANT_CTX, &sealed).is_err(),
787                "{len} bytes"
788            );
789        }
790        let sealed = seal(&wrapping, &TENANT_CTX, &[7; KEY_LEN]);
791        let key = unwrap(&wrapping, &TENANT_CTX, &sealed).expect("32 bytes unwrap");
792        assert_eq!(key.bytes(), [7; KEY_LEN], "the key is the 32 bytes sealed");
793    }
794
795    /// A key with the given bytes, for tests that need a known key.
796    fn key_of(bytes: [u8; KEY_LEN]) -> Key {
797        let mut page = LockedPage::new().expect("page");
798        page.bytes_mut()[..KEY_LEN].copy_from_slice(&bytes);
799        Key { page }
800    }
801
802    /// RFC 5869, appendix A, test cases 1 to 3 (SHA-256).
803    #[test]
804    fn hkdf_sha256_matches_rfc_5869() {
805        let cases = [
806            (
807                "000102030405060708090a0b0c",
808                "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
809                "f0f1f2f3f4f5f6f7f8f9",
810                concat!(
811                    "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf",
812                    "34007208d5b887185865"
813                ),
814            ),
815            (
816                concat!(
817                    "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f",
818                    "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",
819                    "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"
820                ),
821                concat!(
822                    "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
823                    "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
824                    "404142434445464748494a4b4c4d4e4f"
825                ),
826                concat!(
827                    "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecf",
828                    "d0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeef",
829                    "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"
830                ),
831                concat!(
832                    "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c",
833                    "59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71",
834                    "cc30c58179ec3e87c14c01d5c1f3434f1d87"
835                ),
836            ),
837            (
838                "",
839                "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
840                "",
841                concat!(
842                    "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d",
843                    "9d201395faa4b61a96c8"
844                ),
845            ),
846        ];
847        for (n, (salt, ikm, info, okm)) in cases.into_iter().enumerate() {
848            let expected = hex(okm);
849            let mut out = vec![0; expected.len()];
850            hkdf_sha256(&hex(salt), &hex(ikm), &hex(info), &mut out);
851            assert_eq!(out, expected, "test case {}", n + 1);
852        }
853    }
854
855    /// The expected key was computed with Python's hmac and hashlib: HKDF
856    /// with no salt and the info "vcon-server/v1 catalog". Changing the
857    /// label or the salt would lock every catalog out, so this pins both.
858    #[test]
859    fn a_catalog_key_is_hkdf_of_its_parent_with_the_catalog_label() {
860        let catalog = catalog_key(&key_of([0x44; KEY_LEN])).expect("derives");
861        assert_eq!(
862            catalog.bytes(),
863            hex("c0df4ea4f63e64687ca93c494fff4ca00b3ae13112766d8ea24cca35c6b1031b"),
864            "the value Python's HKDF gives for this parent and label"
865        );
866    }
867
868    #[test]
869    fn distinct_parents_or_labels_give_distinct_keys() {
870        let parent = Key::generate().expect("key");
871        let again = catalog_key(&parent).expect("derives");
872        assert_eq!(
873            catalog_key(&parent).expect("derives").bytes(),
874            again.bytes(),
875            "derivation is deterministic: the same parent gives the same catalog key"
876        );
877        let other = catalog_key(&Key::generate().expect("key")).expect("derives");
878        assert_ne!(
879            other.bytes(),
880            again.bytes(),
881            "another parent gives another catalog key"
882        );
883        let mut a = [0; KEY_LEN];
884        let mut b = [0; KEY_LEN];
885        hkdf_sha256(&[], parent.bytes(), b"label a", &mut a);
886        hkdf_sha256(&[], parent.bytes(), b"label b", &mut b);
887        assert_ne!(a, b, "another label gives another key from the same parent");
888    }
889
890    #[test]
891    fn a_rewrapped_key_opens_under_the_new_key_only() {
892        let old = Key::generate().expect("key");
893        let new = Key::generate().expect("key");
894        let key = Key::generate().expect("key");
895        let wrapped = wrap(&old, &version_ctx(), &key);
896        let rewrapped = rewrap(&old, &new, &version_ctx(), &wrapped).expect("rewraps");
897        let opened = unwrap(&new, &version_ctx(), &rewrapped).expect("opens under new");
898        assert_eq!(
899            opened.bytes(),
900            key.bytes(),
901            "rewrapping keeps the wrapped key itself"
902        );
903        assert!(unwrap(&old, &version_ctx(), &rewrapped).is_err(), "old key");
904        assert!(
905            unwrap(&new, &TENANT_CTX, &rewrapped).is_err(),
906            "context kept"
907        );
908    }
909
910    #[test]
911    fn rewrapping_needs_the_right_old_key_and_context() {
912        let old = Key::generate().expect("key");
913        let new = Key::generate().expect("key");
914        let wrapped = wrap(&old, &TENANT_CTX, &Key::generate().expect("key"));
915        assert!(
916            matches!(
917                rewrap(&new, &new, &TENANT_CTX, &wrapped),
918                Err(KeyError::Damaged)
919            ),
920            "the key was not wrapped under new, so new cannot unwrap it to rewrap"
921        );
922        assert!(
923            matches!(
924                rewrap(&old, &new, &version_ctx(), &wrapped),
925                Err(KeyError::Damaged)
926            ),
927            "the key was wrapped for the tenant context, not a version's"
928        );
929    }
930
931    #[test]
932    fn wrapping_warns_from_2_to_the_31_and_stops_at_2_to_the_32() {
933        let cases = [
934            (0, WrapLimit::Allow),
935            ((1 << 31) - 1, WrapLimit::Allow),
936            (1 << 31, WrapLimit::Warn),
937            ((1 << 32) - 1, WrapLimit::Warn),
938            (1 << 32, WrapLimit::Refuse),
939            (u64::MAX, WrapLimit::Refuse),
940        ];
941        for (wraps, expected) in cases {
942            assert_eq!(wrap_limit(wraps), expected, "{wraps} wraps");
943        }
944    }
945
946    #[test]
947    fn the_sqlcipher_literal_spells_the_key_in_hex() {
948        let mut bytes = [0; KEY_LEN];
949        bytes[0] = 0x0a;
950        bytes[31] = 0xff;
951        let literal = key_of(bytes).sqlcipher_raw();
952        let expected = format!("x'0a{}ff'", "00".repeat(30));
953        assert_eq!(
954            *literal, expected,
955            "SQLCipher's raw key literal is x'' around two lower-case hex digits per byte"
956        );
957        assert_eq!(literal.capacity(), literal.len(), "built at its final size");
958    }
959
960    /// Debug is how a key reaches a log line or a panic message, so it must
961    /// name the key without any rendering of its bytes.
962    #[test]
963    fn a_keys_debug_shows_its_id_and_none_of_its_bytes() {
964        let bytes: [u8; KEY_LEN] = std::array::from_fn(|i| 0xa0 ^ (5 * i as u8));
965        let key = key_of(bytes);
966        let shown = format!("{key:?}");
967        assert!(
968            shown.contains(&key.id().to_string()),
969            "the id tells keys apart in a log: {shown}"
970        );
971        for run in bytes.windows(4) {
972            let lower: String = run.iter().map(|b| format!("{b:02x}")).collect();
973            let upper = lower.to_uppercase();
974            let decimal = run.iter().map(u8::to_string).collect::<Vec<_>>().join(", ");
975            for rendering in [lower, upper, decimal] {
976                assert!(
977                    !shown.contains(&rendering),
978                    "no run of the key's bytes may be printed, found {rendering:?} in {shown}"
979                );
980            }
981        }
982    }
983
984    #[test]
985    fn keys_can_be_shared_between_threads() {
986        fn shared<T: Send + Sync>() {}
987        shared::<Key>();
988    }
989}