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