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