Skip to main content

capsule_core/crypto/keys/
safety_code.rs

1//! The cross-device-add **safety code** and the enrollee's **key commitment** (SSoT:
2//! [Device Enrollment § Cross-Device Add], step 4).
3//!
4//! The enrollment relay is a dumb pipe: anyone holding the channel handle may post in either
5//! direction, so a relay (or anyone on it) can substitute the keys each device advertises. The
6//! defence is a short code both devices derive from what they *received* and the user compares
7//! by eye. If nothing was substituted, both sides hash the same two key sets and the codes match;
8//! a man in the middle leaves each side hashing a different pair, and the codes diverge.
9//!
10//! ## Why a commitment rides alongside the code
11//!
12//! A short code alone is grindable. A man in the middle chooses the keys it shows *both* sides,
13//! so it needs only `code(A, M1) == code(M2, B)` — a birthday search over the code space, cheap
14//! for any code short enough for a human to compare. The ceremony therefore orders the reveal:
15//! the enrollee sends [`key_commitment`] of its keys first, the initiator then reveals its own,
16//! and only then does the enrollee reveal the keys it committed to (which the initiator checks
17//! against the commitment with [`commitment_matches`]).
18//!
19//! Ordering alone is not enough, because device keys are **static**: the initiator's are already
20//! published in the directory, and an enrollee's become known the first time it reveals them. A
21//! man in the middle that can predict one side's input finishes the other side first, then
22//! grinds offline for the keys it commits to. So each side's input also carries a **fresh
23//! per-ceremony random nonce** (the `nonce` field of the enrollment payloads), and the code and
24//! the commitment both cover it. The initiator's nonce is unknown until after the man in the
25//! middle has committed toward the initiator; the enrollee's is hidden under its commitment until
26//! after the man in the middle has revealed toward the enrollee. Every input it controls is then
27//! fixed before it learns an input it needs, so it gets exactly one blind guess at the code:
28//! `1 / 10^SAFETY_CODE_DIGITS`.
29//!
30//! ## Inputs are bytes, by design
31//!
32//! Both functions take each side's **canonical advertised-key bytes**, not a typed bundle: the
33//! bundle and its canonical CBOR belong to the enrollment payload encoding
34//! (`lifecycle::enrollment`), and this module must agree with any implementation that produces
35//! the same bytes. Each input is length-prefixed and the two are role-ordered (initiator first),
36//! so no split of one concatenation can be passed off as another and swapping the roles changes
37//! the code.
38//!
39//! [Device Enrollment § Cross-Device Add]: https://docs/design/device-enrollment/#cross-device-add
40
41use sha2::{Digest, Sha256};
42
43/// Domain separator for the safety code — distinct from the commitment's so a commitment can
44/// never be presented as a code or vice versa.
45const SAFETY_CODE_DOMAIN: &[u8] = b"capsule/enrollment/safety-code/v1";
46
47/// Domain separator for the enrollee's key commitment.
48const COMMITMENT_DOMAIN: &[u8] = b"capsule/enrollment/key-commitment/v1";
49
50/// How many decimal digits a safety code carries. Under the commit-then-reveal ordering over
51/// nonce-bearing inputs a man in the middle gets one blind guess, so twelve digits bound it at one
52/// in 10^12.
53pub const SAFETY_CODE_DIGITS: usize = 12;
54
55/// The digits per displayed chunk. Both devices render the code in the same chunked,
56/// fixed-length shape so the human comparison is chunk-by-chunk rather than one long run.
57pub const SAFETY_CODE_CHUNK: usize = 4;
58
59/// The length of a [`key_commitment`].
60pub const KEY_COMMITMENT_LEN: usize = 32;
61
62/// Feed one length-prefixed field into the hash, so field boundaries are unambiguous.
63fn absorb(hasher: &mut Sha256, field: &[u8]) {
64    let len = u64::try_from(field.len()).expect("a slice length fits in u64");
65    hasher.update(len.to_be_bytes());
66    hasher.update(field);
67}
68
69/// The safety code both devices display, over the **initiator's** and the **enrollee's**
70/// canonical advertised-key bytes, in that order.
71///
72/// Each input must include that side's fresh per-ceremony nonce: over static keys alone the code
73/// is grindable whatever the reveal order (see the module docs).
74///
75/// The result is [`SAFETY_CODE_DIGITS`] decimal digits in groups of [`SAFETY_CODE_CHUNK`]
76/// separated by single spaces (e.g. `0412 7730 9958`), zero-padded so it is always the same
77/// length. Deterministic: the same two inputs always give the same code, on every platform.
78pub fn safety_code(a_keys: &[u8], b_keys: &[u8]) -> String {
79    let mut hasher = Sha256::new();
80    absorb(&mut hasher, SAFETY_CODE_DOMAIN);
81    absorb(&mut hasher, a_keys);
82    absorb(&mut hasher, b_keys);
83    let digest = hasher.finalize();
84
85    // The first 8 digest bytes reduced mod 10^12. The modulo bias is below 10^12 / 2^64
86    // (about 5e-8) — far beneath the guessing bound the code exists to provide.
87    let mut head = [0u8; 8];
88    head.copy_from_slice(&digest[..8]);
89    let modulus = 10u64.pow(u32::try_from(SAFETY_CODE_DIGITS).expect("digit count fits in u32"));
90    let value = u64::from_be_bytes(head) % modulus;
91    let digits = format!("{value:0SAFETY_CODE_DIGITS$}");
92
93    let chunks: Vec<&str> = digits
94        .as_bytes()
95        .chunks(SAFETY_CODE_CHUNK)
96        .map(|chunk| std::str::from_utf8(chunk).expect("ASCII digits"))
97        .collect();
98    let code = chunks.join(" ");
99    tracing::debug!(
100        a_len = a_keys.len(),
101        b_len = b_keys.len(),
102        "enrollment: derived a safety code"
103    );
104    code
105}
106
107/// The enrollee's commitment to its canonical advertised-key bytes, sent before the initiator
108/// reveals its own keys (see the module docs for why the order matters).
109pub fn key_commitment(keys: &[u8]) -> [u8; KEY_COMMITMENT_LEN] {
110    let mut hasher = Sha256::new();
111    absorb(&mut hasher, COMMITMENT_DOMAIN);
112    absorb(&mut hasher, keys);
113    hasher.finalize().into()
114}
115
116/// Whether revealed key bytes are the ones a commitment was made to. A mismatch is the abort
117/// path: the enrollee revealed keys it did not commit to, or the commitment was substituted.
118pub fn commitment_matches(commitment: &[u8; KEY_COMMITMENT_LEN], keys: &[u8]) -> bool {
119    let matches = key_commitment(keys) == *commitment;
120    if !matches {
121        tracing::warn!("enrollment: revealed keys do not match the enrollee's commitment");
122    }
123    matches
124}
125
126#[cfg(test)]
127mod tests;