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    /// The blob layout and the associated data are written out here byte by
551    /// byte, so a change to either, which would make stored bodies
552    /// unreadable, fails this test.
553    #[test]
554    fn a_blob_is_the_format_byte_nonce_ciphertext_and_tag() {
555        let key = [0x44; 32];
556        let nonce = [0x55; 12];
557        let mut ad = b"vcon-server/v1".to_vec();
558        ad.extend([1, 2]);
559        ad.extend([0x11; 16]);
560        ad.extend([0x33; 16]);
561        ad.extend([0x22; 16]);
562        let mut ciphertext = b"body".to_vec();
563        let tag = gcm_seal(&key, nonce, &ad, &mut ciphertext);
564        let mut expected = vec![1];
565        expected.extend(nonce);
566        expected.extend(ciphertext);
567        expected.extend(tag);
568        assert_eq!(
569            seal_with_nonce(&key, nonce, &version_ctx(), b"body"),
570            expected,
571            "format byte, nonce, ciphertext, tag, under a version's associated data"
572        );
573
574        let mut tenant_ad = b"vcon-server/v1".to_vec();
575        tenant_ad.extend([1, 1]);
576        tenant_ad.extend([0x11; 16]);
577        let mut ciphertext = b"key".to_vec();
578        let tag = gcm_seal(&key, nonce, &tenant_ad, &mut ciphertext);
579        let mut expected = vec![1];
580        expected.extend(nonce);
581        expected.extend(ciphertext);
582        expected.extend(tag);
583        let tenant = Context::Tenant { tenant: TENANT };
584        assert_eq!(
585            seal_with_nonce(&key, nonce, &tenant, b"key"),
586            expected,
587            "a tenant blob: the same layout under the tenant's associated data"
588        );
589    }
590
591    #[test]
592    fn a_sealed_blob_is_its_body_and_the_stated_overhead() {
593        let key = Key::generate().expect("key");
594        let ctx = Context::Tenant {
595            tenant: crate::ids::TenantId([7; 16]),
596        };
597        for len in [0, 1, 1000] {
598            assert_eq!(
599                seal(&key, &ctx, &vec![0x5a; len]).len(),
600                len + SEALED_OVERHEAD,
601                "a body of {len} bytes"
602            );
603        }
604    }
605
606    #[test]
607    fn a_sealed_body_opens_with_the_same_key_and_context() {
608        let key = Key::generate().expect("key");
609        for body in [&b""[..], b"x", &[0xa5; 100_000]] {
610            let blob = seal(&key, &version_ctx(), body);
611            assert_eq!(
612                blob.len(),
613                1 + 12 + body.len() + 16,
614                "a format byte, a 12-byte nonce, the ciphertext as long as the body, a 16-byte tag"
615            );
616            assert_eq!(
617                open(&key, &version_ctx(), &blob).as_deref(),
618                Ok(body),
619                "the same key and context open what they sealed"
620            );
621        }
622    }
623
624    /// Every byte of the nonce is random: over 1000 seals no nonce repeats
625    /// and no byte position keeps one value. For 96 random bits either
626    /// event has a probability below 2^-76.
627    #[test]
628    fn every_byte_of_a_nonce_is_random() {
629        let key = Key::generate().expect("key");
630        let nonces: Vec<[u8; 12]> = (0..1000)
631            .map(|_| {
632                let blob = seal(&key, &version_ctx(), b"same");
633                blob[1..13].try_into().expect("12 bytes")
634            })
635            .collect();
636        let distinct: std::collections::HashSet<_> = nonces.iter().collect();
637        assert_eq!(distinct.len(), nonces.len(), "a nonce repeated");
638        for i in 0..12 {
639            assert!(
640                nonces.iter().any(|n| n[i] != nonces[0][i]),
641                "byte {i} of the nonce never changes"
642            );
643        }
644    }
645
646    #[test]
647    fn changing_any_byte_of_a_blob_fails() {
648        let key = Key::generate().expect("key");
649        let blob = seal(&key, &version_ctx(), b"a body");
650        assert_eq!(
651            open(&key, &version_ctx(), &blob).as_deref(),
652            Ok(&b"a body"[..]),
653            "unchanged"
654        );
655        for i in 0..blob.len() {
656            let mut bad = blob.clone();
657            bad[i] ^= 0x01;
658            assert_eq!(open(&key, &version_ctx(), &bad), Err(OpenError), "byte {i}");
659        }
660        for len in 0..blob.len() {
661            assert_eq!(
662                open(&key, &version_ctx(), &blob[..len]),
663                Err(OpenError),
664                "first {len} bytes"
665            );
666        }
667        let mut longer = blob.clone();
668        longer.push(0);
669        assert_eq!(
670            open(&key, &version_ctx(), &longer),
671            Err(OpenError),
672            "one byte more"
673        );
674    }
675
676    #[test]
677    fn another_context_or_key_fails() {
678        let key = Key::generate().expect("key");
679        let blob = seal(&key, &version_ctx(), b"a body");
680        assert_eq!(
681            open(&key, &version_ctx(), &blob).as_deref(),
682            Ok(&b"a body"[..]),
683            "unchanged"
684        );
685        let others = [
686            Context::Version {
687                tenant: TenantId([0x12; 16]),
688                uuid: UUID,
689                version: VERSION,
690            },
691            Context::Version {
692                tenant: TENANT,
693                uuid: Uuid::from_bytes([0x34; 16]),
694                version: VERSION,
695            },
696            Context::Version {
697                tenant: TENANT,
698                uuid: UUID,
699                version: VersionId([0x23; 16]),
700            },
701            Context::Tenant { tenant: TENANT },
702        ];
703        for other in others {
704            assert_eq!(open(&key, &other, &blob), Err(OpenError), "{other:?}");
705        }
706        let other_key = Key::generate().expect("key");
707        assert_eq!(
708            open(&other_key, &version_ctx(), &blob),
709            Err(OpenError),
710            "the tag fails under any other key"
711        );
712    }
713
714    const TENANT_CTX: Context = Context::Tenant { tenant: TENANT };
715
716    #[test]
717    fn a_wrapped_key_unwraps_to_the_same_key() {
718        let wrapping = Key::generate().expect("key");
719        let key = Key::generate().expect("key");
720        for ctx in [TENANT_CTX, version_ctx()] {
721            let wrapped = wrap(&wrapping, &ctx, &key);
722            assert_eq!(
723                wrapped.len(),
724                1 + 12 + KEY_LEN + 16,
725                "a wrapped key is a sealed blob of the key's 32 bytes"
726            );
727            let unwrapped = unwrap(&wrapping, &ctx, &wrapped).expect("unwraps");
728            assert_eq!(
729                unwrapped.bytes(),
730                key.bytes(),
731                "unwrap gives back the key wrapped"
732            );
733        }
734    }
735
736    #[test]
737    fn changing_any_byte_of_a_wrapped_key_fails() {
738        let wrapping = Key::generate().expect("key");
739        let key = Key::generate().expect("key");
740        let wrapped = wrap(&wrapping, &TENANT_CTX, &key);
741        assert!(
742            unwrap(&wrapping, &TENANT_CTX, &wrapped).is_ok(),
743            "unchanged"
744        );
745        for i in 0..wrapped.len() {
746            let mut bad = wrapped.clone();
747            bad[i] ^= 0x01;
748            assert!(unwrap(&wrapping, &TENANT_CTX, &bad).is_err(), "byte {i}");
749        }
750        for len in 0..wrapped.len() {
751            assert!(
752                unwrap(&wrapping, &TENANT_CTX, &wrapped[..len]).is_err(),
753                "first {len} bytes"
754            );
755        }
756    }
757
758    #[test]
759    fn another_context_or_wrapping_key_fails() {
760        let wrapping = Key::generate().expect("key");
761        let key = Key::generate().expect("key");
762        let wrapped = wrap(&wrapping, &TENANT_CTX, &key);
763        assert!(
764            unwrap(&wrapping, &TENANT_CTX, &wrapped).is_ok(),
765            "unchanged"
766        );
767        let other_tenant = Context::Tenant {
768            tenant: TenantId([0x12; 16]),
769        };
770        assert!(
771            unwrap(&wrapping, &other_tenant, &wrapped).is_err(),
772            "other tenant"
773        );
774        assert!(
775            unwrap(&wrapping, &version_ctx(), &wrapped).is_err(),
776            "other kind"
777        );
778        let other = Key::generate().expect("key");
779        assert!(
780            unwrap(&other, &TENANT_CTX, &wrapped).is_err(),
781            "other wrapping key"
782        );
783    }
784
785    #[test]
786    fn only_a_32_byte_key_unwraps() {
787        let wrapping = Key::generate().expect("key");
788        for len in [0, 31, 33, 64] {
789            let sealed = seal(&wrapping, &TENANT_CTX, &vec![7; len]);
790            assert!(
791                unwrap(&wrapping, &TENANT_CTX, &sealed).is_err(),
792                "{len} bytes"
793            );
794        }
795        let sealed = seal(&wrapping, &TENANT_CTX, &[7; KEY_LEN]);
796        let key = unwrap(&wrapping, &TENANT_CTX, &sealed).expect("32 bytes unwrap");
797        assert_eq!(key.bytes(), [7; KEY_LEN], "the key is the 32 bytes sealed");
798    }
799
800    /// A key with the given bytes, for tests that need a known key.
801    fn key_of(bytes: [u8; KEY_LEN]) -> Key {
802        let mut page = LockedPage::new().expect("page");
803        page.bytes_mut()[..KEY_LEN].copy_from_slice(&bytes);
804        Key { page }
805    }
806
807    /// RFC 5869, appendix A, test cases 1 to 3 (SHA-256).
808    #[test]
809    fn hkdf_sha256_matches_rfc_5869() {
810        let cases = [
811            (
812                "000102030405060708090a0b0c",
813                "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
814                "f0f1f2f3f4f5f6f7f8f9",
815                concat!(
816                    "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf",
817                    "34007208d5b887185865"
818                ),
819            ),
820            (
821                concat!(
822                    "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f",
823                    "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",
824                    "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"
825                ),
826                concat!(
827                    "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
828                    "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
829                    "404142434445464748494a4b4c4d4e4f"
830                ),
831                concat!(
832                    "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecf",
833                    "d0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeef",
834                    "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"
835                ),
836                concat!(
837                    "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c",
838                    "59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71",
839                    "cc30c58179ec3e87c14c01d5c1f3434f1d87"
840                ),
841            ),
842            (
843                "",
844                "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
845                "",
846                concat!(
847                    "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d",
848                    "9d201395faa4b61a96c8"
849                ),
850            ),
851        ];
852        for (n, (salt, ikm, info, okm)) in cases.into_iter().enumerate() {
853            let expected = hex(okm);
854            let mut out = vec![0; expected.len()];
855            hkdf_sha256(&hex(salt), &hex(ikm), &hex(info), &mut out);
856            assert_eq!(out, expected, "test case {}", n + 1);
857        }
858    }
859
860    /// The expected key was computed with Python's hmac and hashlib: HKDF
861    /// with no salt and the info "vcon-server/v1 catalog". Changing the
862    /// label or the salt would lock every catalog out, so this pins both.
863    #[test]
864    fn a_catalog_key_is_hkdf_of_its_parent_with_the_catalog_label() {
865        let catalog = catalog_key(&key_of([0x44; KEY_LEN])).expect("derives");
866        assert_eq!(
867            catalog.bytes(),
868            hex("c0df4ea4f63e64687ca93c494fff4ca00b3ae13112766d8ea24cca35c6b1031b"),
869            "the value Python's HKDF gives for this parent and label"
870        );
871    }
872
873    #[test]
874    fn distinct_parents_or_labels_give_distinct_keys() {
875        let parent = Key::generate().expect("key");
876        let again = catalog_key(&parent).expect("derives");
877        assert_eq!(
878            catalog_key(&parent).expect("derives").bytes(),
879            again.bytes(),
880            "derivation is deterministic: the same parent gives the same catalog key"
881        );
882        let other = catalog_key(&Key::generate().expect("key")).expect("derives");
883        assert_ne!(
884            other.bytes(),
885            again.bytes(),
886            "another parent gives another catalog key"
887        );
888        let mut a = [0; KEY_LEN];
889        let mut b = [0; KEY_LEN];
890        hkdf_sha256(&[], parent.bytes(), b"label a", &mut a);
891        hkdf_sha256(&[], parent.bytes(), b"label b", &mut b);
892        assert_ne!(a, b, "another label gives another key from the same parent");
893    }
894
895    #[test]
896    fn a_rewrapped_key_opens_under_the_new_key_only() {
897        let old = Key::generate().expect("key");
898        let new = Key::generate().expect("key");
899        let key = Key::generate().expect("key");
900        let wrapped = wrap(&old, &version_ctx(), &key);
901        let rewrapped = rewrap(&old, &new, &version_ctx(), &wrapped).expect("rewraps");
902        let opened = unwrap(&new, &version_ctx(), &rewrapped).expect("opens under new");
903        assert_eq!(
904            opened.bytes(),
905            key.bytes(),
906            "rewrapping keeps the wrapped key itself"
907        );
908        assert!(unwrap(&old, &version_ctx(), &rewrapped).is_err(), "old key");
909        assert!(
910            unwrap(&new, &TENANT_CTX, &rewrapped).is_err(),
911            "context kept"
912        );
913    }
914
915    #[test]
916    fn rewrapping_needs_the_right_old_key_and_context() {
917        let old = Key::generate().expect("key");
918        let new = Key::generate().expect("key");
919        let wrapped = wrap(&old, &TENANT_CTX, &Key::generate().expect("key"));
920        assert!(
921            matches!(
922                rewrap(&new, &new, &TENANT_CTX, &wrapped),
923                Err(KeyError::Damaged)
924            ),
925            "the key was not wrapped under new, so new cannot unwrap it to rewrap"
926        );
927        assert!(
928            matches!(
929                rewrap(&old, &new, &version_ctx(), &wrapped),
930                Err(KeyError::Damaged)
931            ),
932            "the key was wrapped for the tenant context, not a version's"
933        );
934    }
935
936    #[test]
937    fn wrapping_warns_from_2_to_the_31_and_stops_at_2_to_the_32() {
938        let cases = [
939            (0, WrapLimit::Allow),
940            ((1 << 31) - 1, WrapLimit::Allow),
941            (1 << 31, WrapLimit::Warn),
942            ((1 << 32) - 1, WrapLimit::Warn),
943            (1 << 32, WrapLimit::Refuse),
944            (u64::MAX, WrapLimit::Refuse),
945        ];
946        for (wraps, expected) in cases {
947            assert_eq!(wrap_limit(wraps), expected, "{wraps} wraps");
948        }
949    }
950
951    #[test]
952    fn the_sqlcipher_literal_spells_the_key_in_hex() {
953        let mut bytes = [0; KEY_LEN];
954        bytes[0] = 0x0a;
955        bytes[31] = 0xff;
956        let literal = key_of(bytes).sqlcipher_raw();
957        let expected = format!("x'0a{}ff'", "00".repeat(30));
958        assert_eq!(
959            *literal, expected,
960            "SQLCipher's raw key literal is x'' around two lower-case hex digits per byte"
961        );
962        assert_eq!(literal.capacity(), literal.len(), "built at its final size");
963    }
964
965    #[test]
966    fn debug_of_the_sqlcipher_literal_is_the_redaction_text() {
967        let mut bytes = [0u8; KEY_LEN];
968        bytes[0] = 0x0a;
969        let literal = key_of(bytes).sqlcipher_raw();
970        // No assertion prints what it formatted (secret_file.rs's tests).
971        assert!(
972            format!("{literal:?}") == crate::secret_file::REDACTED,
973            "Debug never shows the key"
974        );
975    }
976
977    /// Debug is how a key reaches a log line or a panic message, so it must
978    /// name the key without any rendering of its bytes.
979    #[test]
980    fn a_keys_debug_shows_its_id_and_none_of_its_bytes() {
981        let bytes: [u8; KEY_LEN] = std::array::from_fn(|i| 0xa0 ^ (5 * i as u8));
982        let key = key_of(bytes);
983        let shown = format!("{key:?}");
984        assert!(
985            shown.contains(&key.id().to_string()),
986            "the id tells keys apart in a log: {shown}"
987        );
988        for run in bytes.windows(4) {
989            let lower: String = run.iter().map(|b| format!("{b:02x}")).collect();
990            let upper = lower.to_uppercase();
991            let decimal = run.iter().map(u8::to_string).collect::<Vec<_>>().join(", ");
992            for rendering in [lower, upper, decimal] {
993                assert!(
994                    !shown.contains(&rendering),
995                    "no run of the key's bytes may be printed, found {rendering:?} in {shown}"
996                );
997            }
998        }
999    }
1000
1001    #[test]
1002    fn keys_can_be_shared_between_threads() {
1003        fn shared<T: Send + Sync>() {}
1004        shared::<Key>();
1005    }
1006}