Skip to main content

huddle_core/crypto/
sas.rs

1//! Short-Authentication-String (SAS) verification — Phase G.
2//!
3//! Two peers OOB-compare a short derived code to confirm they each
4//! hold the matching Ed25519 keys (defense against MITM during initial
5//! contact, before fingerprint trust is established).
6//!
7//! Protocol shape (each step is a signed `RoomMessage` on the room's
8//! gossipsub topic):
9//!
10//! 1. Initiator picks a random 16-byte `tx_id` + an ephemeral X25519
11//!    keypair. Sends `SasInit { tx_id, ephemeral_x25519_pubkey, target_fp }`.
12//! 2. Responder generates their own ephemeral X25519 keypair, computes
13//!    ECDH with the initiator's pubkey, derives the SAS code via
14//!    `derive_sas_code(shared, tx_id)`, and replies with
15//!    `SasResponse { tx_id, ephemeral_x25519_pubkey }`. The responder
16//!    sees the code locally and shows it.
17//! 3. The initiator computes ECDH the other direction, derives the
18//!    same code, shows it.
19//! 4. Both users compare codes OOB. Each side presses Match → broadcasts
20//!    `SasConfirm { tx_id, matched: true }`.
21//! 5. On receiving the other side's `matched=true`, set the partner's
22//!    fingerprint as `verified=true` (per-room + global `verified_peers`).
23//!
24//! The signatures on each envelope bind the ephemeral X25519 pubkeys to
25//! the sender's Ed25519 identity. A MITM who substitutes their own
26//! ephemeral key into the exchange ends up with a *different* SAS code
27//! than the legitimate peer would compute, so the OOB comparison fails.
28//!
29//! ## SAS table — Matrix MSC 2241 alignment (huddle 0.3.x follow-up)
30//!
31//! Previously the emoji table was a 64-entry "in spirit" derivative;
32//! it has been realigned to the canonical 49-entry Matrix MSC 2241
33//! table so any future cross-client SAS interop just works. The
34//! derivation now uses 7 emoji (42 bits / 6 = 7 chunks, each mod 49)
35//! and 3 four-digit decimal groups (39 bits / 13 = 3 chunks, each
36//! offset +1000 so values land in 1000..9192), exactly as MSC 2241
37//! specifies.
38
39use hkdf::Hkdf;
40use rand::RngCore;
41use sha2::Sha256;
42use x25519_dalek::{PublicKey, StaticSecret};
43
44use crate::error::{HuddleError, Result};
45
46/// Length of the transaction id used as HKDF salt. 16 bytes (128 bits)
47/// is plenty of unforgeability; sized to be base64-friendly.
48pub const TX_ID_LEN: usize = 16;
49
50/// SAS code information given to both sides for OOB comparison.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct SasCode {
53    /// 7 emoji indices into [`SAS_EMOJI`] (each 0..49). Human-friendly
54    /// for visual comparison; works in any modern terminal with emoji
55    /// support. Matches Matrix MSC 2241 shape.
56    pub emoji_indices: [u8; 7],
57    /// Three 4-digit groups separated by `-`, each in `1000..=9191`,
58    /// per MSC 2241. Easier to read aloud than a flat 7-digit number.
59    pub decimal: String,
60}
61
62impl SasCode {
63    pub fn emoji_string(&self) -> String {
64        self.emoji_indices
65            .iter()
66            .map(|i| SAS_EMOJI[*i as usize].0)
67            .collect::<Vec<_>>()
68            .join(" ")
69    }
70
71    pub fn emoji_labels(&self) -> String {
72        self.emoji_indices
73            .iter()
74            .map(|i| SAS_EMOJI[*i as usize].1)
75            .collect::<Vec<_>>()
76            .join(" / ")
77    }
78}
79
80/// Fresh X25519 ephemeral keypair + random tx_id. The secret stays on
81/// the initiator's machine until the SAS finishes; the pubkey is
82/// transmitted in the signed envelope.
83pub fn new_session() -> ([u8; TX_ID_LEN], StaticSecret, PublicKey) {
84    let mut tx_id = [0u8; TX_ID_LEN];
85    rand::thread_rng().fill_bytes(&mut tx_id);
86    // StaticSecret here is the X25519 "long-term" type from x25519-dalek;
87    // we use it as ephemeral (drop after the SAS). Need the
88    // `static_secrets` feature flag because the `EphemeralSecret` type
89    // is more restrictive in v2 — `StaticSecret` lets us hold onto it
90    // across a few async hops.
91    let secret = StaticSecret::random_from_rng(rand::thread_rng());
92    let public = PublicKey::from(&secret);
93    (tx_id, secret, public)
94}
95
96/// Derive the 7-emoji + 3-group-decimal SAS code from the X25519
97/// shared secret and the agreed-upon `tx_id`. Both peers compute this
98/// independently and must end up with the same answer for OOB
99/// comparison to succeed.
100///
101/// Matches the MSC 2241 derivation: HKDF-SHA256 with `tx_id` as salt
102/// and `b"huddle-sas-v1"` as info, expanded to 11 bytes. First 6 bytes
103/// → 7 6-bit chunks (mod 49) → emoji indices. Next 5 bytes → 3 13-bit
104/// chunks (+ 1000) → 3 four-digit decimal groups.
105pub fn derive_sas_code(
106    our_secret: &StaticSecret,
107    their_public: &PublicKey,
108    tx_id: &[u8; TX_ID_LEN],
109) -> SasCode {
110    let shared = our_secret.diffie_hellman(their_public);
111    // HKDF over the shared secret. tx_id as salt prevents replay
112    // (two SAS flows between the same pair must produce different
113    // codes); info domain-separates from any other HKDF use.
114    let hk = Hkdf::<Sha256>::new(Some(tx_id), shared.as_bytes());
115    let mut okm = [0u8; 11];
116    hk.expand(b"huddle-sas-v1", &mut okm)
117        .expect("11 bytes is well within HKDF output limit");
118
119    // First 6 bytes = 48 bits. Use the high 42 bits (7 × 6) for emoji.
120    // Bit extraction (big-endian, MSB-first):
121    let b = &okm[..6];
122    let mut raw_emoji = [0u8; 7];
123    raw_emoji[0] = b[0] >> 2;
124    raw_emoji[1] = ((b[0] & 0x03) << 4) | (b[1] >> 4);
125    raw_emoji[2] = ((b[1] & 0x0f) << 2) | (b[2] >> 6);
126    raw_emoji[3] = b[2] & 0x3f;
127    raw_emoji[4] = b[3] >> 2;
128    raw_emoji[5] = ((b[3] & 0x03) << 4) | (b[4] >> 4);
129    raw_emoji[6] = ((b[4] & 0x0f) << 2) | (b[5] >> 6);
130    // huddle 0.7.11: rejection sampling instead of `raw % 49`.
131    // 6-bit values in 0..64 mod 49 makes indices 0..14 twice as likely
132    // (hit by raw 0..14 AND raw 49..63), measurably under-sampling the
133    // 49^7 SAS space and reducing effective entropy. Now we expand
134    // additional HKDF output to refill any byte that falls in 49..63
135    // — the canonical MSC 2241 approach. The expansion is cheap and
136    // deterministic, so both sides still derive the same code.
137    let emoji_indices = derive_emoji_indices_rejection(&hk, raw_emoji);
138
139    // Bytes 6..11 = 40 bits. Use the high 39 bits for the decimal
140    // (3 × 13-bit chunks, each offset by 1000).
141    let d = &okm[6..11];
142    let chunk0 = ((u32::from(d[0]) << 5) | (u32::from(d[1]) >> 3)) & 0x1fff;
143    let chunk1 = ((u32::from(d[1] & 0x07) << 10)
144        | (u32::from(d[2]) << 2)
145        | (u32::from(d[3]) >> 6))
146        & 0x1fff;
147    let chunk2 = ((u32::from(d[3] & 0x3f) << 7) | (u32::from(d[4]) >> 1)) & 0x1fff;
148    let decimal = format!("{}-{}-{}", chunk0 + 1000, chunk1 + 1000, chunk2 + 1000);
149
150    SasCode {
151        emoji_indices,
152        decimal,
153    }
154}
155
156/// The canonical 49-emoji table from Matrix MSC 2241, English labels.
157/// Indices 0-48; the derivation above maps 6-bit HKDF chunks mod 49.
158pub const SAS_EMOJI: [(&str, &str); 49] = [
159    ("🐶", "dog"),
160    ("🐱", "cat"),
161    ("🦁", "lion"),
162    ("🐎", "horse"),
163    ("🦄", "unicorn"),
164    ("🐷", "pig"),
165    ("🐘", "elephant"),
166    ("🐰", "rabbit"),
167    ("🐼", "panda"),
168    ("🐓", "rooster"),
169    ("🐧", "penguin"),
170    ("🐢", "turtle"),
171    ("🐟", "fish"),
172    ("🐙", "octopus"),
173    ("🦋", "butterfly"),
174    ("🌷", "flower"),
175    ("🌳", "tree"),
176    ("🌵", "cactus"),
177    ("🍄", "mushroom"),
178    ("🌏", "globe"),
179    ("🌙", "moon"),
180    ("☁️", "cloud"),
181    ("🔥", "fire"),
182    ("🍌", "banana"),
183    ("🍎", "apple"),
184    ("🍓", "strawberry"),
185    ("🌽", "corn"),
186    ("🍕", "pizza"),
187    ("🎂", "cake"),
188    ("❤️", "heart"),
189    ("🙂", "smiley"),
190    ("🤖", "robot"),
191    ("🎩", "hat"),
192    ("👓", "glasses"),
193    ("🔧", "spanner"),
194    ("🎅", "santa"),
195    ("👍", "thumbs up"),
196    ("☂️", "umbrella"),
197    ("⌛", "hourglass"),
198    ("⏰", "clock"),
199    ("🎁", "gift"),
200    ("💡", "light bulb"),
201    ("📕", "book"),
202    ("✏️", "pencil"),
203    ("📎", "paperclip"),
204    ("✂️", "scissors"),
205    ("🔒", "lock"),
206    ("🔑", "key"),
207    ("🔨", "hammer"),
208];
209
210/// huddle 0.7.11: rejection-sampling emoji-index derivation. Refills any
211/// index ≥ 49 with deterministic additional HKDF expansion so the
212/// distribution over the 49-element table is uniform.
213fn derive_emoji_indices_rejection(
214    hk: &Hkdf<Sha256>,
215    initial: [u8; 7],
216) -> [u8; 7] {
217    let mut out = [0u8; 7];
218    let mut accepted = 0usize;
219    // Use the initial bytes first.
220    for &v in &initial {
221        if v < 49 {
222            out[accepted] = v;
223            accepted += 1;
224            if accepted == 7 {
225                return out;
226            }
227        }
228    }
229    // Refill by expanding additional 6-bit chunks. We pull in 6-byte
230    // blocks of HKDF output, each yielding 8 candidate 6-bit values
231    // (high-bit pair discarded — each byte gives one 6-bit candidate
232    // via `v & 0x3f`). The info string includes a salt counter so
233    // multiple refills don't repeat the same bytes.
234    let mut counter: u32 = 0;
235    while accepted < 7 {
236        let info = {
237            let mut buf = [0u8; 24];
238            buf[..16].copy_from_slice(b"huddle-sas-v1-rs");
239            buf[16..20].copy_from_slice(&counter.to_be_bytes());
240            buf
241        };
242        let mut block = [0u8; 32];
243        if hk.expand(&info, &mut block).is_err() {
244            // The expander only fails when len > 255 * HashLen (8160
245            // bytes for SHA-256); 32 is far under, so this branch is
246            // unreachable in practice. Fall back to modulo if it
247            // somehow happens — degrades to pre-0.7.11 behavior but
248            // never panics or hangs.
249            for v in &mut initial.iter().copied() {
250                if accepted < 7 {
251                    out[accepted] = v % 49;
252                    accepted += 1;
253                }
254            }
255            break;
256        }
257        for &byte in block.iter() {
258            let candidate = byte & 0x3f;
259            if candidate < 49 {
260                out[accepted] = candidate;
261                accepted += 1;
262                if accepted == 7 {
263                    return out;
264                }
265            }
266        }
267        counter += 1;
268    }
269    out
270}
271
272/// Decode a base64-encoded 32-byte X25519 pubkey received over the wire.
273pub fn parse_pubkey(b64: &str) -> Result<PublicKey> {
274    use base64::engine::general_purpose::STANDARD as B64;
275    use base64::Engine;
276    let bytes = B64
277        .decode(b64)
278        .map_err(|e| HuddleError::Session(format!("bad x25519 pubkey b64: {e}")))?;
279    if bytes.len() != 32 {
280        return Err(HuddleError::Session(format!(
281            "x25519 pubkey is {} bytes, expected 32",
282            bytes.len()
283        )));
284    }
285    let mut arr = [0u8; 32];
286    arr.copy_from_slice(&bytes);
287    Ok(PublicKey::from(arr))
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    #[test]
295    fn both_sides_derive_same_code() {
296        let (tx_id, alice_secret, alice_pub) = new_session();
297        let (_, bob_secret, bob_pub) = new_session();
298
299        let alice_code = derive_sas_code(&alice_secret, &bob_pub, &tx_id);
300        let bob_code = derive_sas_code(&bob_secret, &alice_pub, &tx_id);
301        assert_eq!(alice_code, bob_code);
302        // Decimal shape: three 4-digit groups joined by '-', each in
303        // [1000, 9191].
304        let parts: Vec<&str> = alice_code.decimal.split('-').collect();
305        assert_eq!(parts.len(), 3);
306        for p in parts {
307            assert_eq!(p.len(), 4);
308            let n: u32 = p.parse().unwrap();
309            assert!((1000..=9191).contains(&n));
310        }
311        // Indices must all be in 0..49 (MSC 2241 table size).
312        for i in alice_code.emoji_indices {
313            assert!((i as usize) < SAS_EMOJI.len());
314        }
315    }
316
317    #[test]
318    fn different_tx_id_yields_different_code() {
319        let (tx_id_a, alice_secret, _) = new_session();
320        let (_, bob_secret, bob_pub) = new_session();
321        let alice_code = derive_sas_code(&alice_secret, &bob_pub, &tx_id_a);
322
323        let mut tx_id_b = tx_id_a;
324        tx_id_b[0] ^= 0xff;
325        let alice_code_b = derive_sas_code(&alice_secret, &bob_pub, &tx_id_b);
326        let _ = bob_secret;
327        assert_ne!(alice_code, alice_code_b);
328    }
329
330    #[test]
331    fn mitm_substitute_yields_different_code() {
332        // Mallory MITMs: Alice's traffic to Bob is replaced with
333        // Mallory's pubkey, and vice versa. Alice computes ECDH with
334        // Mallory's pub; Bob computes ECDH with Mallory's pub. Their
335        // SAS codes will both differ from each other and from a
336        // legitimate same-pubkey-pair derivation — so OOB comparison
337        // catches the attack.
338        let (tx_id, alice_secret, alice_pub) = new_session();
339        let (_, bob_secret, bob_pub) = new_session();
340        let (_, _mallory_secret, mallory_pub) = new_session();
341
342        let alice_thinks_bob = derive_sas_code(&alice_secret, &mallory_pub, &tx_id);
343        let bob_thinks_alice = derive_sas_code(&bob_secret, &mallory_pub, &tx_id);
344        assert_ne!(alice_thinks_bob, bob_thinks_alice);
345
346        // Sanity: without MITM, both sides agree.
347        let alice_real = derive_sas_code(&alice_secret, &bob_pub, &tx_id);
348        let bob_real = derive_sas_code(&bob_secret, &alice_pub, &tx_id);
349        assert_eq!(alice_real, bob_real);
350    }
351
352    #[test]
353    fn pubkey_round_trip() {
354        let (_, _, pub_) = new_session();
355        use base64::engine::general_purpose::STANDARD as B64;
356        use base64::Engine;
357        let encoded = B64.encode(pub_.as_bytes());
358        let decoded = parse_pubkey(&encoded).unwrap();
359        assert_eq!(decoded.as_bytes(), pub_.as_bytes());
360    }
361}