Skip to main content

second_brain_sync/pairing/
channel.rs

1use std::fmt;
2use std::io::{ErrorKind, Read, Write};
3use std::net::TcpStream;
4use std::time::{Duration, Instant};
5
6use anyhow::{Context, Result, anyhow, bail};
7use chacha20poly1305::aead::Aead;
8use chacha20poly1305::{ChaCha20Poly1305, KeyInit, Nonce};
9use hkdf::Hkdf;
10use serde::Serialize;
11use serde::de::DeserializeOwned;
12use sha2::Sha256;
13use spake2::{Ed25519Group, Identity, Password, Spake2};
14use zeroize::Zeroizing;
15
16use super::code::{CodeKind, HostSecrets, JoinCode};
17
18const MAGIC: &[u8] = b"second-brain-pair/1";
19const JOINER_ID: &[u8] = b"second-brain pairing joiner";
20const HOST_ID: &[u8] = b"second-brain pairing host";
21const JOINER_TO_HOST: &[u8] = b"second-brain pairing joiner to host";
22const HOST_TO_JOINER: &[u8] = b"second-brain pairing host to joiner";
23/// Frames before the code is proven are small, so an unauthenticated peer
24/// cannot make the listener buffer much.
25const OPENING_FRAME_MAX: usize = 256;
26/// The host's reply carries every device row and every epoch wrapped for the
27/// joiner.
28const SEALED_FRAME_MAX: usize = 8 << 20;
29/// The joiner's request, the only sealed frame read before the code is
30/// proven.
31const FIRST_SEALED_MAX: usize = 64 << 10;
32pub const IO_TIMEOUT: Duration = Duration::from_secs(30);
33
34/// The other side closed the channel before replying; for a joiner this is
35/// how a wrong, retired or expired code shows.
36#[derive(Debug)]
37pub struct ChannelClosed;
38
39impl fmt::Display for ChannelClosed {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        f.write_str(
42            "the pairing device closed the connection: the code was wrong, was retired after \
43             failed tries, or its `sb pair` has stopped",
44        )
45    }
46}
47
48impl std::error::Error for ChannelClosed {}
49
50/// A connection both sides keyed from the same code through SPAKE2; every
51/// frame after the opening is sealed with ChaCha20-Poly1305.
52pub struct Channel {
53    stream: TcpStream,
54    seal: ChaCha20Poly1305,
55    open: ChaCha20Poly1305,
56    sent: u64,
57    received: u64,
58}
59
60impl fmt::Debug for Channel {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.debug_struct("Channel")
63            .field("peer", &self.stream.peer_addr().ok())
64            .finish_non_exhaustive()
65    }
66}
67
68pub enum Accepted {
69    /// The joiner proved the code; `first` is its first sealed frame.
70    Opened {
71        channel: Channel,
72        first: Zeroizing<Vec<u8>>,
73    },
74    /// The joiner's first sealed frame did not open, so it ran SPAKE2 over
75    /// another code. This counts as a failed try.
76    WrongCode,
77    /// The connection broke or did not speak the protocol before proving
78    /// anything; this is not a try at the code.
79    Broken(anyhow::Error),
80}
81
82impl Channel {
83    /// The listener's side: the joiner speaks first, naming which secret it
84    /// runs SPAKE2 over.
85    /// Everything before the code is proven must arrive by `deadline`.
86    pub fn accept(mut stream: TcpStream, secrets: &HostSecrets, deadline: Instant) -> Accepted {
87        let opened = (|| -> Result<(Spake2<Ed25519Group>, Vec<u8>)> {
88            set_timeouts(&stream)?;
89            let opening = read_frame_by(&mut stream, OPENING_FRAME_MAX, Some(deadline))?;
90            let rest = opening
91                .strip_prefix(MAGIC)
92                .context("the peer does not speak second-brain pairing")?;
93            let (&kind, joiner_msg) = rest.split_first().context("the opening frame is empty")?;
94            let kind = CodeKind::from_byte(kind).context("the opening frame names no code kind")?;
95            let password = secrets.password(kind);
96            let (state, host_msg) = Spake2::<Ed25519Group>::start_b(
97                &Password::new(password.as_slice()),
98                &Identity::new(JOINER_ID),
99                &Identity::new(HOST_ID),
100            );
101            write_frame(&mut stream, &host_msg)?;
102            Ok((state, joiner_msg.to_vec()))
103        })();
104        let (state, joiner_msg) = match opened {
105            Ok(opened) => opened,
106            Err(e) => return Accepted::Broken(e),
107        };
108        let key = match state.finish(&joiner_msg) {
109            Ok(key) => Zeroizing::new(key),
110            Err(e) => {
111                return Accepted::Broken(anyhow!("the joiner's SPAKE2 message is bad: {e:?}"));
112            }
113        };
114        let mut channel = match Self::keyed(stream, &key, HOST_TO_JOINER, JOINER_TO_HOST) {
115            Ok(channel) => channel,
116            Err(e) => return Accepted::Broken(e),
117        };
118        let sealed = match read_frame_by(&mut channel.stream, FIRST_SEALED_MAX, Some(deadline)) {
119            Ok(sealed) => sealed,
120            Err(e) => return Accepted::Broken(e),
121        };
122        if let Err(e) = set_timeouts(&channel.stream) {
123            return Accepted::Broken(e);
124        }
125        match channel.open_frame(&sealed) {
126            Ok(first) => Accepted::Opened { channel, first },
127            Err(_) => Accepted::WrongCode,
128        }
129    }
130
131    /// The joiner's side. The code is proven only when the host answers the
132    /// first sealed frame.
133    pub fn connect(mut stream: TcpStream, code: &JoinCode) -> Result<Self> {
134        set_timeouts(&stream)?;
135        let (state, joiner_msg) = Spake2::<Ed25519Group>::start_a(
136            &Password::new(code.password()),
137            &Identity::new(JOINER_ID),
138            &Identity::new(HOST_ID),
139        );
140        let mut opening = MAGIC.to_vec();
141        opening.push(code.kind().byte());
142        opening.extend_from_slice(&joiner_msg);
143        write_frame(&mut stream, &opening)?;
144        let host_msg = read_frame(&mut stream, OPENING_FRAME_MAX)?;
145        let key = Zeroizing::new(
146            state
147                .finish(&host_msg)
148                .map_err(|e| anyhow!("the pairing device's SPAKE2 message is bad: {e:?}"))?,
149        );
150        Self::keyed(stream, &key, JOINER_TO_HOST, HOST_TO_JOINER)
151    }
152
153    fn keyed(stream: TcpStream, key: &[u8], seal_info: &[u8], open_info: &[u8]) -> Result<Self> {
154        let hkdf = Hkdf::<Sha256>::new(None, key);
155        let mut seal = Zeroizing::new([0u8; 32]);
156        let mut open = Zeroizing::new([0u8; 32]);
157        hkdf.expand(seal_info, seal.as_mut())
158            .map_err(|e| anyhow!("deriving the pairing keys: {e}"))?;
159        hkdf.expand(open_info, open.as_mut())
160            .map_err(|e| anyhow!("deriving the pairing keys: {e}"))?;
161        Ok(Self {
162            stream,
163            seal: ChaCha20Poly1305::new((&*seal).into()),
164            open: ChaCha20Poly1305::new((&*open).into()),
165            sent: 0,
166            received: 0,
167        })
168    }
169
170    pub fn set_read_timeout(&self, timeout: Duration) -> Result<()> {
171        self.stream.set_read_timeout(Some(timeout))?;
172        Ok(())
173    }
174
175    pub fn send(&mut self, plaintext: &[u8]) -> Result<()> {
176        let nonce = nonce(self.sent);
177        let sealed = self
178            .seal
179            .encrypt(&nonce, plaintext)
180            .map_err(|_| anyhow!("sealing a pairing frame failed"))?;
181        self.sent += 1;
182        write_frame(&mut self.stream, &sealed)
183    }
184
185    pub fn recv(&mut self) -> Result<Zeroizing<Vec<u8>>> {
186        let sealed = read_frame(&mut self.stream, SEALED_FRAME_MAX)?;
187        self.open_frame(&sealed)
188    }
189
190    fn open_frame(&mut self, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
191        let nonce = nonce(self.received);
192        let plaintext = self
193            .open
194            .decrypt(&nonce, sealed)
195            .map_err(|_| anyhow!("a pairing frame did not open"))?;
196        self.received += 1;
197        Ok(Zeroizing::new(plaintext))
198    }
199
200    pub fn send_json<T: Serialize>(&mut self, value: &T) -> Result<()> {
201        let body = Zeroizing::new(serde_json::to_vec(value).context("encoding a pairing frame")?);
202        self.send(&body)
203    }
204
205    pub fn recv_json<T: DeserializeOwned>(&mut self) -> Result<T> {
206        let body = self.recv()?;
207        serde_json::from_slice(&body).context("decoding a pairing frame")
208    }
209}
210
211fn nonce(counter: u64) -> Nonce {
212    let mut bytes = [0u8; 12];
213    bytes[4..].copy_from_slice(&counter.to_be_bytes());
214    bytes.into()
215}
216
217fn set_timeouts(stream: &TcpStream) -> Result<()> {
218    stream.set_read_timeout(Some(IO_TIMEOUT))?;
219    stream.set_write_timeout(Some(IO_TIMEOUT))?;
220    Ok(())
221}
222
223fn write_frame(stream: &mut TcpStream, body: &[u8]) -> Result<()> {
224    let len = u32::try_from(body.len()).context("a pairing frame is too large")?;
225    stream.write_all(&len.to_be_bytes())?;
226    stream.write_all(body)?;
227    stream.flush()?;
228    Ok(())
229}
230
231fn read_frame(stream: &mut TcpStream, max: usize) -> Result<Vec<u8>> {
232    read_frame_by(stream, max, None)
233}
234
235/// With a deadline, every read waits only for the time left, so a peer
236/// trickling bytes cannot hold the connection past it.
237fn read_frame_by(stream: &mut TcpStream, max: usize, deadline: Option<Instant>) -> Result<Vec<u8>> {
238    let mut len = [0u8; 4];
239    read_full(stream, &mut len, deadline)?;
240    let len = usize::try_from(u32::from_be_bytes(len)).unwrap_or(usize::MAX);
241    if len > max {
242        bail!("a pairing frame of {len} bytes is over the {max} byte limit");
243    }
244    let mut body = vec![0u8; len];
245    read_full(stream, &mut body, deadline)?;
246    Ok(body)
247}
248
249fn read_full(stream: &mut TcpStream, buf: &mut [u8], deadline: Option<Instant>) -> Result<()> {
250    let mut filled = 0;
251    while filled < buf.len() {
252        if let Some(deadline) = deadline {
253            let left = deadline.saturating_duration_since(Instant::now());
254            if left.is_zero() {
255                bail!("the peer did not finish the pairing opening in time");
256            }
257            stream.set_read_timeout(Some(left))?;
258        }
259        match stream.read(&mut buf[filled..]) {
260            Ok(0) => return Err(ChannelClosed.into()),
261            Ok(n) => filled += n,
262            Err(e) if e.kind() == ErrorKind::Interrupted => {}
263            Err(e) => return Err(e).context("reading a pairing frame"),
264        }
265    }
266    Ok(())
267}
268
269#[cfg(test)]
270mod tests {
271    use std::net::TcpListener;
272    use std::sync::mpsc;
273    use std::thread;
274
275    use super::*;
276
277    const WAIT: Duration = Duration::from_secs(20);
278
279    fn pair_of(secrets: HostSecrets, code: JoinCode) -> (Result<Channel>, Accepted) {
280        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
281        let addr = listener.local_addr().unwrap();
282        let (tx, rx) = mpsc::channel();
283        let host = thread::spawn(move || {
284            let (stream, _) = listener.accept().unwrap();
285            let accepted = Channel::accept(stream, &secrets, Instant::now() + WAIT);
286            tx.send(()).unwrap();
287            accepted
288        });
289        let joined =
290            Channel::connect(TcpStream::connect(addr).unwrap(), &code).and_then(|mut channel| {
291                channel.send(b"hello")?;
292                Ok(channel)
293            });
294        rx.recv_timeout(WAIT).expect("the host side must finish");
295        (joined, host.join().unwrap())
296    }
297
298    #[test]
299    fn the_same_code_opens_a_channel_both_ways() {
300        let secrets = HostSecrets::generate();
301        let code = JoinCode::parse(&secrets.code()).unwrap();
302        let (joined, accepted) = pair_of(secrets, code);
303        let mut joiner = joined.unwrap();
304        let Accepted::Opened { mut channel, first } = accepted else {
305            panic!("the right code must open the channel");
306        };
307        assert_eq!(&first[..], b"hello");
308        channel.send_json(&vec!["reply".to_string()]).unwrap();
309        let reply: Vec<String> = joiner.recv_json().unwrap();
310        assert_eq!(reply, vec!["reply".to_string()]);
311        joiner.send(b"second").unwrap();
312        assert_eq!(&channel.recv().unwrap()[..], b"second");
313    }
314
315    #[test]
316    fn the_invite_secret_opens_a_channel_too() {
317        let secrets = HostSecrets::generate();
318        let code = JoinCode::parse(&secrets.invite(&["127.0.0.1".into()], 1)).unwrap();
319        let (joined, accepted) = pair_of(secrets, code);
320        joined.unwrap();
321        assert!(matches!(accepted, Accepted::Opened { .. }));
322    }
323
324    #[test]
325    fn a_wrong_code_is_a_failed_try_and_the_joiner_sees_the_channel_close() {
326        let secrets = HostSecrets::generate();
327        let other = HostSecrets::generate();
328        let code = JoinCode::parse(&other.code()).unwrap();
329        let (joined, accepted) = pair_of(secrets, code);
330        assert!(matches!(accepted, Accepted::WrongCode));
331        let mut joiner = joined.unwrap();
332        let err = joiner.recv().unwrap_err();
333        assert!(err.downcast_ref::<ChannelClosed>().is_some(), "{err:#}");
334    }
335
336    #[test]
337    fn a_peer_that_does_not_speak_the_protocol_is_not_a_try() {
338        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
339        let addr = listener.local_addr().unwrap();
340        let host = thread::spawn(move || {
341            let (stream, _) = listener.accept().unwrap();
342            Channel::accept(stream, &HostSecrets::generate(), Instant::now() + WAIT)
343        });
344        let mut stream = TcpStream::connect(addr).unwrap();
345        write_frame(&mut stream, b"GET / HTTP/1.1").unwrap();
346        assert!(matches!(host.join().unwrap(), Accepted::Broken(_)));
347
348        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
349        let addr = listener.local_addr().unwrap();
350        let host = thread::spawn(move || {
351            let (stream, _) = listener.accept().unwrap();
352            Channel::accept(stream, &HostSecrets::generate(), Instant::now() + WAIT)
353        });
354        let mut stream = TcpStream::connect(addr).unwrap();
355        stream.write_all(&u32::MAX.to_be_bytes()).unwrap();
356        assert!(matches!(host.join().unwrap(), Accepted::Broken(_)));
357    }
358
359    #[test]
360    fn a_replayed_or_reordered_frame_does_not_open() {
361        let secrets = HostSecrets::generate();
362        let code = JoinCode::parse(&secrets.code()).unwrap();
363        let (joined, accepted) = pair_of(secrets, code);
364        let mut joiner = joined.unwrap();
365        let Accepted::Opened { mut channel, .. } = accepted else {
366            panic!("the right code must open the channel");
367        };
368        let nonce0 = nonce(0);
369        let replay = joiner.seal.encrypt(&nonce0, &b"again"[..]).unwrap();
370        write_frame(&mut joiner.stream, &replay).unwrap();
371        assert!(channel.recv().is_err());
372    }
373
374    #[test]
375    fn a_peer_trickling_its_opening_is_dropped_at_the_deadline() {
376        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
377        let addr = listener.local_addr().unwrap();
378        let host = thread::spawn(move || {
379            let (stream, _) = listener.accept().unwrap();
380            let started = Instant::now();
381            let accepted = Channel::accept(
382                stream,
383                &HostSecrets::generate(),
384                Instant::now() + Duration::from_millis(500),
385            );
386            (accepted, started.elapsed())
387        });
388        let mut stream = TcpStream::connect(addr).unwrap();
389        stream.write_all(&64u32.to_be_bytes()).unwrap();
390        let trickle = thread::spawn(move || {
391            for _ in 0..40 {
392                if stream.write_all(b"s").is_err() {
393                    return;
394                }
395                thread::sleep(Duration::from_millis(100));
396            }
397        });
398        let (accepted, took) = host.join().unwrap();
399        assert!(matches!(accepted, Accepted::Broken(_)));
400        assert!(took < Duration::from_secs(3), "held for {took:?}");
401        trickle.join().unwrap();
402    }
403}