Skip to main content

iwlink/
pairing.rs

1//! The pairing QR code, and the confirmation code both screens show.
2//!
3//! # QR payload
4//!
5//! `iwlink:` followed by unpadded base64url of:
6//!
7//! ```text
8//! u8   format (1)
9//! u16  highest protocol version the helper speaks, big endian
10//! 16   helper install id
11//! 32   helper static public key
12//! 32   one-time pre-shared key
13//! i64  expiry, unix seconds, big endian
14//! u8   name length in bytes (at most 64)
15//! ..   computer name, UTF-8
16//! ```
17//!
18//! Binary rather than JSON because a QR code grows with every byte, and a
19//! smaller code scans faster from a laptop screen.
20//!
21//! The pre-shared key is what stops a helper that did not show this QR code
22//! from completing the pairing handshake, and it is valid for
23//! [`OFFER_TTL_SECS`] only. The confirmation code covers the remaining case: a
24//! photographed QR code used by someone else within those two minutes.
25
26use base64::Engine;
27use base64::engine::general_purpose::URL_SAFE_NO_PAD;
28use zeroize::Zeroizing;
29
30use crate::error::{LinkError, Result};
31use crate::keys::{KEY_LEN, PublicKey};
32use crate::random;
33
34/// URI scheme prefix of the QR payload.
35pub const OFFER_PREFIX: &str = "iwlink:";
36
37/// How long a pairing offer stays valid.
38pub const OFFER_TTL_SECS: i64 = 120;
39
40/// Longest computer name carried in an offer, in bytes.
41pub const MAX_NAME_BYTES: usize = 64;
42
43/// Length of the pre-shared key.
44pub const PSK_LEN: usize = 32;
45
46const FORMAT: u8 = 1;
47const FIXED_LEN: usize = 1 + 2 + HelperId::LEN + KEY_LEN + PSK_LEN + 8 + 1;
48
49/// Random identifier of one helper install. Stable across reboots, replaced
50/// only if the helper's keys are reset.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52pub struct HelperId(pub [u8; HelperId::LEN]);
53
54impl HelperId {
55    pub const LEN: usize = 16;
56
57    pub fn generate() -> Result<HelperId> {
58        Ok(HelperId(random::bytes()?))
59    }
60
61    /// Lowercase hex, for storage keys and logs.
62    pub fn to_hex(&self) -> String {
63        self.0.iter().map(|b| format!("{b:02x}")).collect()
64    }
65
66    /// Parse the output of [`HelperId::to_hex`].
67    pub fn from_hex(text: &str) -> Result<HelperId> {
68        if text.len() != Self::LEN * 2 || !text.is_ascii() {
69            return Err(LinkError::InvalidKey("helper id"));
70        }
71        let mut out = [0u8; Self::LEN];
72        for (i, byte) in out.iter_mut().enumerate() {
73            *byte = u8::from_str_radix(&text[i * 2..i * 2 + 2], 16)
74                .map_err(|_| LinkError::InvalidKey("helper id"))?;
75        }
76        Ok(HelperId(out))
77    }
78}
79
80/// Everything the phone needs to start pairing with a helper.
81#[derive(Clone, PartialEq, Eq)]
82pub struct PairingOffer {
83    /// Highest protocol version the helper speaks.
84    pub version: u16,
85    pub helper_id: HelperId,
86    pub helper_public: PublicKey,
87    pub psk: Zeroizing<[u8; PSK_LEN]>,
88    /// Unix seconds after which the helper refuses this offer.
89    pub expires_at: i64,
90    /// Display name of the computer, shown on the phone.
91    pub name: String,
92}
93
94impl PairingOffer {
95    /// A new offer with a fresh pre-shared key, valid for [`OFFER_TTL_SECS`].
96    pub fn create(
97        helper_id: HelperId,
98        helper_public: PublicKey,
99        name: &str,
100        now: i64,
101    ) -> Result<PairingOffer> {
102        Ok(PairingOffer {
103            version: crate::version::PROTOCOL_VERSION,
104            helper_id,
105            helper_public,
106            psk: Zeroizing::new(random::bytes()?),
107            expires_at: now.saturating_add(OFFER_TTL_SECS),
108            name: truncate_name(name),
109        })
110    }
111
112    pub fn is_expired(&self, now: i64) -> bool {
113        now >= self.expires_at
114    }
115
116    /// The text to put in the QR code.
117    pub fn to_uri(&self) -> String {
118        let name = self.name.as_bytes();
119        let mut raw = Zeroizing::new(Vec::with_capacity(FIXED_LEN + name.len()));
120        raw.push(FORMAT);
121        raw.extend_from_slice(&self.version.to_be_bytes());
122        raw.extend_from_slice(&self.helper_id.0);
123        raw.extend_from_slice(self.helper_public.as_bytes());
124        raw.extend_from_slice(self.psk.as_ref());
125        raw.extend_from_slice(&self.expires_at.to_be_bytes());
126        // `name` was truncated to MAX_NAME_BYTES on the way in, so it fits a u8.
127        raw.push(name.len() as u8);
128        raw.extend_from_slice(name);
129        format!("{OFFER_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw.as_slice()))
130    }
131
132    /// Parse a scanned QR code. Does not check expiry; see
133    /// [`PairingOffer::is_expired`].
134    pub fn parse(uri: &str) -> Result<PairingOffer> {
135        let encoded = uri
136            .strip_prefix(OFFER_PREFIX)
137            .ok_or(LinkError::InvalidOffer("not an IntelliWallet pairing code"))?;
138        let raw = Zeroizing::new(
139            URL_SAFE_NO_PAD
140                .decode(encoded.trim())
141                .map_err(|_| LinkError::InvalidOffer("encoding"))?,
142        );
143        if raw.len() < FIXED_LEN {
144            return Err(LinkError::InvalidOffer("too short"));
145        }
146        if raw[0] != FORMAT {
147            return Err(LinkError::InvalidOffer("unknown format"));
148        }
149
150        let mut at = 1;
151        let mut take = |n: usize| {
152            let slice = &raw[at..at + n];
153            at += n;
154            slice
155        };
156        let version = u16::from_be_bytes(take(2).try_into().expect("2 bytes"));
157        let helper_id = HelperId(take(HelperId::LEN).try_into().expect("16 bytes"));
158        let helper_public = PublicKey::from_slice(take(KEY_LEN))?;
159        let psk = Zeroizing::new(<[u8; PSK_LEN]>::try_from(take(PSK_LEN)).expect("32 bytes"));
160        let expires_at = i64::from_be_bytes(take(8).try_into().expect("8 bytes"));
161        let name_len = take(1)[0] as usize;
162
163        if name_len > MAX_NAME_BYTES || raw.len() != FIXED_LEN + name_len {
164            return Err(LinkError::InvalidOffer("name length"));
165        }
166        let name = std::str::from_utf8(&raw[FIXED_LEN..])
167            .map_err(|_| LinkError::InvalidOffer("name encoding"))?
168            .to_owned();
169        if version == 0 {
170            return Err(LinkError::InvalidOffer("version"));
171        }
172
173        Ok(PairingOffer {
174            version,
175            helper_id,
176            helper_public,
177            psk,
178            expires_at,
179            name,
180        })
181    }
182}
183
184impl std::fmt::Debug for PairingOffer {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        f.debug_struct("PairingOffer")
187            .field("version", &self.version)
188            .field("helper_id", &self.helper_id.to_hex())
189            .field("expires_at", &self.expires_at)
190            .field("name", &self.name)
191            .finish_non_exhaustive()
192    }
193}
194
195/// The 6 digit code both screens show after the pairing handshake.
196///
197/// Derived from the Noise handshake hash, which is identical on both sides
198/// only if both saw exactly the same handshake: same keys, same pre-shared
199/// key, no one in the middle. The hash is a BLAKE2s output, so its first four
200/// bytes are uniformly distributed, and reducing them modulo one million has a
201/// bias below one part in four thousand, which is irrelevant for a code a
202/// human compares once.
203pub fn confirmation_code(handshake_hash: &[u8]) -> String {
204    let mut word = [0u8; 4];
205    let n = handshake_hash.len().min(4);
206    word[..n].copy_from_slice(&handshake_hash[..n]);
207    format!("{:06}", u32::from_be_bytes(word) % 1_000_000)
208}
209
210/// Cut a name to at most [`MAX_NAME_BYTES`] bytes on a character boundary.
211fn truncate_name(name: &str) -> String {
212    let name = name.trim();
213    if name.len() <= MAX_NAME_BYTES {
214        return name.to_owned();
215    }
216    let mut end = MAX_NAME_BYTES;
217    while !name.is_char_boundary(end) {
218        end -= 1;
219    }
220    name[..end].to_owned()
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    fn offer(name: &str) -> PairingOffer {
228        PairingOffer::create(
229            HelperId([7; HelperId::LEN]),
230            PublicKey([9; KEY_LEN]),
231            name,
232            1_000,
233        )
234        .unwrap()
235    }
236
237    #[test]
238    fn round_trips() {
239        let original = offer("Studio MacBook");
240        let parsed = PairingOffer::parse(&original.to_uri()).unwrap();
241        assert_eq!(parsed, original);
242        assert_eq!(parsed.expires_at, 1_000 + OFFER_TTL_SECS);
243    }
244
245    #[test]
246    fn each_offer_has_a_fresh_psk() {
247        assert_ne!(offer("a").psk, offer("a").psk);
248    }
249
250    #[test]
251    fn expiry() {
252        let o = offer("a");
253        assert!(!o.is_expired(1_000 + OFFER_TTL_SECS - 1));
254        assert!(o.is_expired(1_000 + OFFER_TTL_SECS));
255    }
256
257    #[test]
258    fn long_names_are_cut_on_a_character_boundary() {
259        let long = "ü".repeat(40); // 80 bytes
260        let o = offer(&long);
261        assert!(o.name.len() <= MAX_NAME_BYTES);
262        assert!(o.name.chars().all(|c| c == 'ü'));
263        assert_eq!(PairingOffer::parse(&o.to_uri()).unwrap().name, o.name);
264    }
265
266    #[test]
267    fn rejects_malformed_input() {
268        let good = offer("a").to_uri();
269        let body = good.strip_prefix(OFFER_PREFIX).unwrap();
270
271        assert!(PairingOffer::parse(body).is_err(), "missing prefix");
272        assert!(PairingOffer::parse("iwlink:!!!").is_err(), "bad base64");
273        assert!(PairingOffer::parse("iwlink:AAAA").is_err(), "too short");
274
275        let mut raw = URL_SAFE_NO_PAD.decode(body).unwrap();
276        raw[0] = 2;
277        let bad_format = format!("{OFFER_PREFIX}{}", URL_SAFE_NO_PAD.encode(&raw));
278        assert!(PairingOffer::parse(&bad_format).is_err(), "unknown format");
279
280        let mut raw = URL_SAFE_NO_PAD.decode(body).unwrap();
281        raw.push(b'x');
282        let trailing = format!("{OFFER_PREFIX}{}", URL_SAFE_NO_PAD.encode(&raw));
283        assert!(PairingOffer::parse(&trailing).is_err(), "trailing byte");
284    }
285
286    #[test]
287    fn debug_does_not_print_the_psk() {
288        let text = format!("{:?}", offer("a"));
289        assert!(!text.contains("psk"), "{text}");
290    }
291
292    #[test]
293    fn helper_id_hex_round_trips() {
294        let id = HelperId::generate().unwrap();
295        assert_eq!(HelperId::from_hex(&id.to_hex()).unwrap(), id);
296        assert!(HelperId::from_hex("zz").is_err());
297    }
298
299    #[test]
300    fn confirmation_code_is_six_digits_and_input_sensitive() {
301        let a = confirmation_code(&[0xFF; 32]);
302        assert_eq!(a.len(), 6);
303        assert!(a.chars().all(|c| c.is_ascii_digit()));
304        assert_eq!(confirmation_code(&[0; 32]), "000000");
305        assert_ne!(
306            confirmation_code(&[1, 2, 3, 4]),
307            confirmation_code(&[1, 2, 3, 5])
308        );
309    }
310}