Skip to main content

coqui_peer/pair/
mod.rs

1//! Pairing: how a joiner and a responder come to accept each other's keys, over any channel.
2//!
3//! Three modes, each of which a responder may turn off ([`PairingOptions`]):
4//!
5//! - **Invitation**: the responder made an [`Invitation`](crate::Invitation) and the joiner
6//!   holds its secret and the inviter's id. The joiner sends the secret only over a channel
7//!   that proved the inviter's key; the responder redeems it.
8//! - **PIN** (feature `pin`): one side shows a short [`Pin`], a person types it on the other,
9//!   and both run SPAKE2 with key confirmation over both sides' keys and the channel binding.
10//!   An attacker gets one guess per run.
11//! - **Device flow**: the responder issues a [`UserCode`] the joiner shows; an operator enters
12//!   it at the responder and approves. Meant for a joiner that verified the responder.
13//!
14//! The exchange is sans-IO: [`PairingJoiner`] and [`PairingResponder`] take whole messages
15//! with `receive` and give them with `transmit`; the caller moves them over a reliable,
16//! ordered channel. What a person must see or decide is returned as data
17//! ([`PairingJoiner::shown`], the [`PairingDesk`]); the crate shows nothing.
18
19// The PIN mode's slots, throttles and messages are compiled without the `pin` feature too, so
20// the wire format and the desk are the same in every build.
21#![cfg_attr(not(feature = "pin"), allow(dead_code))]
22
23mod code;
24mod desk;
25#[cfg(feature = "pin")]
26mod pin;
27
28use alloc::collections::VecDeque;
29use core::fmt;
30use core::net::SocketAddr;
31use core::time::Duration;
32use std::time::SystemTime;
33
34use zeroize::Zeroizing;
35
36pub use code::{CodeAlphabet, PairingCode, Pin, UserCode};
37pub use desk::{
38    Decided, Decision, DeskLimits, PairingDesk, PairingOptions, PendingDevice, PendingSlot,
39    ShownPin, Ticket,
40};
41
42use crate::clock::{from_unix_seconds, later, unix_seconds};
43use crate::error::Error;
44use crate::id::PeerId;
45use crate::key::KeyMaterial;
46#[cfg(feature = "pin")]
47use crate::random::Random;
48use crate::store::TrustStore;
49use desk::Admission;
50
51/// The first byte of every message.
52const VERSION: u8 = 1;
53
54const HELLO: u8 = 1;
55const READY: u8 = 2;
56const PAKE: u8 = 3;
57const REPLY: u8 = 4;
58const CONFIRM: u8 = 5;
59const ISSUED: u8 = 6;
60const DONE: u8 = 7;
61const REFUSED: u8 = 8;
62const ANNOUNCE: u8 = 9;
63
64const MODE_INVITATION: u8 = 0;
65const MODE_PIN_TYPED: u8 = 1;
66const MODE_PIN_SHOWN: u8 = 2;
67const MODE_DEVICE: u8 = 3;
68
69/// No slot, on the wire.
70const NO_SLOT: u8 = 0xff;
71
72/// Why a pairing was refused, by this side or the other.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74#[non_exhaustive]
75pub enum PairRefusal {
76    /// The code or secret is wrong, or the key confirmation failed (which is also what a
77    /// relaying attacker or a different channel binding looks like).
78    WrongCode,
79    /// The invitation or code expired.
80    Expired,
81    /// The PIN was used up, or none is shown.
82    Exhausted,
83    /// Too many runs, pending exchanges or wrong entries.
84    Throttled,
85    /// The operator denied the device-flow joiner.
86    Denied,
87    /// The responder does not offer this mode.
88    Disabled,
89}
90
91impl PairRefusal {
92    const fn wire(self) -> u8 {
93        match self {
94            Self::WrongCode => 1,
95            Self::Expired => 2,
96            Self::Exhausted => 3,
97            Self::Throttled => 4,
98            Self::Denied => 5,
99            Self::Disabled => 6,
100        }
101    }
102
103    const fn from_wire(byte: u8) -> Option<Self> {
104        Some(match byte {
105            1 => Self::WrongCode,
106            2 => Self::Expired,
107            3 => Self::Exhausted,
108            4 => Self::Throttled,
109            5 => Self::Denied,
110            6 => Self::Disabled,
111            _ => return None,
112        })
113    }
114}
115
116impl fmt::Display for PairRefusal {
117    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
118        formatter.write_str(match self {
119            Self::WrongCode => "the code is wrong or the key confirmation failed",
120            Self::Expired => "the invitation or code expired",
121            Self::Exhausted => "the PIN is used up or none is shown",
122            Self::Throttled => "too many pairing attempts",
123            Self::Denied => "the pairing was denied",
124            Self::Disabled => "this pairing mode is not offered",
125        })
126    }
127}
128
129/// Why a pairing exchange failed. No message holds a secret, a code or key material.
130#[derive(Debug)]
131#[non_exhaustive]
132pub enum PairingError {
133    /// This side or the other refused.
134    Refused(PairRefusal),
135    /// A message was malformed or unexpected, or a key in it is not the one the channel proved.
136    Protocol,
137    /// The mode needs the channel to have proven (and, for an invitation, matched) the other
138    /// side's key, and it did not.
139    Unverified,
140    /// A local failure: the store, the random source, or a code or option the caller passed.
141    Local(Error),
142}
143
144impl fmt::Display for PairingError {
145    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
146        match self {
147            Self::Refused(refusal) => write!(formatter, "pairing refused: {refusal}"),
148            Self::Protocol => formatter.write_str("pairing message is malformed or unexpected"),
149            Self::Unverified => formatter.write_str("the channel did not verify the other side"),
150            Self::Local(error) => write!(formatter, "pairing failed locally: {error}"),
151        }
152    }
153}
154
155impl core::error::Error for PairingError {
156    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
157        match self {
158            Self::Local(error) => Some(error),
159            _ => None,
160        }
161    }
162}
163
164impl From<Error> for PairingError {
165    fn from(error: Error) -> Self {
166        Self::Local(error)
167    }
168}
169
170/// What the channel the exchange runs over gives it. `Debug` does not show the binding.
171#[derive(Clone, PartialEq, Eq)]
172pub struct Channel {
173    /// This side's key, which the other side will accept.
174    pub local: KeyMaterial,
175    /// The other side's key when the channel proved the other side holds it (a TLS handshake
176    /// does); `None` over a channel that proves nothing, where the key comes from the exchange.
177    pub remote: Option<KeyMaterial>,
178    /// Whether the channel also verified that `remote` is the peer this side meant to reach: a
179    /// pin of it, or roots for the name dialled. Proving a key is not that: any certificate
180    /// whose key is proven passes `Trust::AnyWithKeyProof`. The device flow's joiner needs it.
181    pub verified: bool,
182    /// Bytes both ends of this channel and nobody else share (a TLS exporter), bound into the
183    /// PIN confirmation so a relay between two channels fails it; `None` without one.
184    pub binding: Option<Vec<u8>>,
185}
186
187impl fmt::Debug for Channel {
188    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
189        formatter
190            .debug_struct("Channel")
191            .field("local", &self.local.id())
192            .field("remote", &self.remote.as_ref().map(KeyMaterial::id))
193            .field("verified", &self.verified)
194            .field("binding", &self.binding.as_ref().map(|_| ".."))
195            .finish()
196    }
197}
198
199/// The pairing mode.
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
201#[non_exhaustive]
202pub enum Mode {
203    /// An invitation secret.
204    Invitation,
205    /// A PIN and a PAKE.
206    Pin,
207    /// The device flow.
208    Device,
209}
210
211/// Which side of a PIN pairing shows the PIN.
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
213pub enum PinRole {
214    /// The responder shows it ([`PairingDesk::show_pin`]); a person typed it at the joiner.
215    Typed,
216    /// The joiner shows it, with the slot the responder assigns; a person types both at the
217    /// responder ([`PairingDesk::submit_code`]).
218    Shown,
219}
220
221/// What the joiner must show a person, as data.
222#[derive(Debug, Clone, PartialEq, Eq)]
223#[non_exhaustive]
224pub enum Shown {
225    /// This joiner's PIN and its slot, to be typed at the responder.
226    Pin(PairingCode),
227    /// The device-flow user code, to be entered at the responder before `expires`.
228    UserCode {
229        /// The code.
230        code: UserCode,
231        /// When it expires.
232        expires: SystemTime,
233    },
234}
235
236/// A successful pairing: the other side's key, now to be trusted.
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub struct Paired {
239    /// The other side's key. A responder has accepted it in its store; a joiner's caller
240    /// stores it.
241    pub peer: KeyMaterial,
242    /// How it was paired.
243    pub mode: Mode,
244}
245
246#[derive(Clone)]
247enum Kind {
248    Invitation {
249        inviter: PeerId,
250        secret: Zeroizing<[u8; 32]>,
251    },
252    #[cfg(feature = "pin")]
253    Pin {
254        pin: Pin,
255        role: PinRole,
256    },
257    Device {
258        label: String,
259    },
260}
261
262/// How a joiner pairs: build one, then [`join`](Pairing::join) a channel.
263#[derive(Clone)]
264pub struct Pairing {
265    kind: Kind,
266    allow_unverified: bool,
267    #[cfg(feature = "pin")]
268    random: Option<Random>,
269}
270
271impl fmt::Debug for Pairing {
272    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
273        formatter
274            .debug_struct("Pairing")
275            .field("mode", &self.mode())
276            .field("allow_unverified", &self.allow_unverified)
277            .finish_non_exhaustive()
278    }
279}
280
281impl Pairing {
282    /// Pairs with an invitation: `secret` from the inviter, who is `inviter`. The joiner sends
283    /// the secret only when the channel proved `inviter`'s key, so it must be confidential and
284    /// authenticate the inviter (a TLS connection that pins it).
285    pub fn invitation(inviter: PeerId, secret: [u8; 32]) -> Self {
286        Self::of(Kind::Invitation {
287            inviter,
288            secret: Zeroizing::new(secret),
289        })
290    }
291
292    /// Pairs with a PIN: the one the responder shows and a person typed here
293    /// ([`PinRole::Typed`]), or this joiner's own, which it shows with the slot the responder
294    /// assigns ([`PinRole::Shown`]). The PAKE draws from the operating system's generator
295    /// unless [`with_random`](Pairing::with_random) gives another.
296    #[cfg(feature = "pin")]
297    pub fn pin(pin: Pin, role: PinRole) -> Self {
298        Self::of(Kind::Pin { pin, role })
299    }
300
301    /// Pairs by the device flow: the responder issues a user code that this joiner shows, and
302    /// pairs when its operator approves. `label` (at most 255 bytes, one line) is shown to the
303    /// operator if the responder's app chooses; it proves nothing.
304    ///
305    /// The joiner must have verified the responder (a pin, or roots for the name dialled):
306    /// [`join`](Pairing::join) refuses a channel that is not [`Channel::verified`] unless
307    /// [`allow_unverified`](Pairing::allow_unverified) is set.
308    pub fn device(label: &str) -> Self {
309        Self::of(Kind::Device {
310            label: label.to_owned(),
311        })
312    }
313
314    fn of(kind: Kind) -> Self {
315        Self {
316            kind,
317            allow_unverified: false,
318            #[cfg(feature = "pin")]
319            random: None,
320        }
321    }
322
323    /// Lets the device flow run with a responder this joiner did not verify. A relaying
324    /// attacker can then pair in place of both sides: the operator approves the attacker's
325    /// code, and this joiner trusts the attacker. Off by default.
326    #[must_use]
327    pub fn allow_unverified(mut self, allow: bool) -> Self {
328        self.allow_unverified = allow;
329        self
330    }
331
332    /// Whether [`allow_unverified`](Pairing::allow_unverified) is set.
333    pub fn allows_unverified(&self) -> bool {
334        self.allow_unverified
335    }
336
337    /// The PAKE's random source, instead of the operating system's.
338    #[cfg(feature = "pin")]
339    #[must_use]
340    pub fn with_random(mut self, random: Random) -> Self {
341        self.random = Some(random);
342        self
343    }
344
345    /// The mode.
346    pub fn mode(&self) -> Mode {
347        match self.kind {
348            Kind::Invitation { .. } => Mode::Invitation,
349            #[cfg(feature = "pin")]
350            Kind::Pin { .. } => Mode::Pin,
351            Kind::Device { .. } => Mode::Device,
352        }
353    }
354
355    /// The inviter's id, for an invitation.
356    pub fn inviter(&self) -> Option<PeerId> {
357        match self.kind {
358            Kind::Invitation { inviter, .. } => Some(inviter),
359            _ => None,
360        }
361    }
362
363    /// Starts the exchange over `channel`; the first message is ready to
364    /// [`transmit`](PairingJoiner::transmit).
365    ///
366    /// # Errors
367    ///
368    /// [`PairingError::Unverified`] for an invitation whose channel did not prove the
369    /// inviter's key, and for the device flow over a channel that did not verify the responder
370    /// unless allowed;
371    /// [`PairingError::Local`] with [`Error::InvalidOptions`] for a device label longer than
372    /// 255 bytes or with a control or bidirectional formatting character.
373    pub fn join(self, channel: Channel) -> Result<PairingJoiner, PairingError> {
374        let mode_byte = match &self.kind {
375            Kind::Invitation { inviter, .. } => {
376                if channel.remote.as_ref().map(KeyMaterial::id) != Some(*inviter) {
377                    return Err(PairingError::Unverified);
378                }
379                MODE_INVITATION
380            }
381            #[cfg(feature = "pin")]
382            Kind::Pin { role, .. } => match role {
383                PinRole::Typed => MODE_PIN_TYPED,
384                PinRole::Shown => MODE_PIN_SHOWN,
385            },
386            Kind::Device { label } => {
387                let verified = channel.verified && channel.remote.is_some();
388                if !verified && !self.allow_unverified {
389                    return Err(PairingError::Unverified);
390                }
391                if label.len() > 255 || !plain(label) {
392                    return Err(PairingError::Local(Error::InvalidOptions));
393                }
394                MODE_DEVICE
395            }
396        };
397        let mut hello = Writer::new(HELLO);
398        hello.byte(mode_byte);
399        hello.key(&channel.local);
400        match &self.kind {
401            Kind::Invitation { secret, .. } => hello.raw(&secret[..]),
402            #[cfg(feature = "pin")]
403            Kind::Pin { .. } => {}
404            Kind::Device { label } => hello.short(label.as_bytes()),
405        }
406        let mut joiner = PairingJoiner {
407            mode: self.mode(),
408            remote: channel.remote.clone(),
409            channel,
410            pairing: self,
411            out: VecDeque::new(),
412            state: Joining::AwaitReply,
413            shown: None,
414        };
415        joiner.out.push_back(hello.finish());
416        Ok(joiner)
417    }
418}
419
420enum Joining {
421    AwaitReply,
422    #[cfg(feature = "pin")]
423    AwaitPake {
424        pake: pin::Pake,
425        slot: Option<u8>,
426        sent: Vec<u8>,
427    },
428    AwaitDone,
429    Complete,
430    Failed,
431}
432
433/// The joiner's side of a pairing exchange.
434pub struct PairingJoiner {
435    pairing: Pairing,
436    mode: Mode,
437    channel: Channel,
438    remote: Option<KeyMaterial>,
439    out: VecDeque<Vec<u8>>,
440    state: Joining,
441    shown: Option<Shown>,
442}
443
444impl fmt::Debug for PairingJoiner {
445    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
446        formatter
447            .debug_struct("PairingJoiner")
448            .field("mode", &self.mode)
449            .field("complete", &self.is_complete())
450            .finish_non_exhaustive()
451    }
452}
453
454impl PairingJoiner {
455    /// The next message to send, or `None` until more arrives. Call until `None`.
456    pub fn transmit(&mut self) -> Option<Vec<u8>> {
457        self.out.pop_front()
458    }
459
460    /// What this joiner must show a person now, once the responder sent it.
461    pub fn shown(&self) -> Option<&Shown> {
462        self.shown.as_ref()
463    }
464
465    /// Whether the exchange succeeded and [`finish`](PairingJoiner::finish) returns the peer.
466    pub fn is_complete(&self) -> bool {
467        matches!(self.state, Joining::Complete)
468    }
469
470    /// The paired responder.
471    ///
472    /// # Errors
473    ///
474    /// [`PairingError::Protocol`] before completion.
475    pub fn finish(self) -> Result<Paired, PairingError> {
476        match (self.state, self.remote) {
477            (Joining::Complete, Some(peer)) => Ok(Paired {
478                peer,
479                mode: self.mode,
480            }),
481            _ => Err(PairingError::Protocol),
482        }
483    }
484
485    /// Takes one message from the responder.
486    ///
487    /// # Errors
488    ///
489    /// [`PairingError::Refused`] when the responder refused or the key confirmation failed
490    /// (a refusal is then queued for the responder); [`PairingError::Protocol`] for a
491    /// malformed or unexpected message. The exchange is over after an error.
492    pub fn receive(&mut self, message: &[u8]) -> Result<(), PairingError> {
493        let result = self.step(message);
494        if result.is_err() {
495            self.state = Joining::Failed;
496        }
497        result
498    }
499
500    /// Records the responder's key, which must be the one the channel proved, or the one an
501    /// earlier message carried.
502    fn responder_key(&mut self, key: KeyMaterial) -> Result<(), PairingError> {
503        match &self.remote {
504            Some(known) if *known != key => Err(PairingError::Protocol),
505            Some(_) => Ok(()),
506            None => {
507                self.remote = Some(key);
508                Ok(())
509            }
510        }
511    }
512
513    fn refuse(&mut self, refusal: PairRefusal) -> PairingError {
514        self.out.push_back(refused(refusal));
515        PairingError::Refused(refusal)
516    }
517
518    fn step(&mut self, message: &[u8]) -> Result<(), PairingError> {
519        let (tag, mut reader) = Reader::open(message)?;
520        if tag == REFUSED {
521            let refusal = PairRefusal::from_wire(reader.byte()?).ok_or(PairingError::Protocol)?;
522            reader.end()?;
523            return Err(PairingError::Refused(refusal));
524        }
525        match (core::mem::replace(&mut self.state, Joining::Failed), tag) {
526            (Joining::AwaitReply, DONE) if self.mode == Mode::Invitation => {
527                let key = reader.key()?;
528                reader.end()?;
529                self.responder_key(key)?;
530                self.state = Joining::Complete;
531                Ok(())
532            }
533            (Joining::AwaitReply, ISSUED) if self.mode == Mode::Device => {
534                let key = reader.key()?;
535                let code = String::from_utf8(reader.short()?.to_vec())
536                    .map_err(|_| PairingError::Protocol)?;
537                if code.is_empty() || !plain(&code) {
538                    return Err(PairingError::Protocol);
539                }
540                let expires = from_unix_seconds(reader.long()?);
541                reader.end()?;
542                self.responder_key(key)?;
543                self.shown = Some(Shown::UserCode {
544                    code: UserCode::issued(code),
545                    expires,
546                });
547                self.state = Joining::AwaitDone;
548                Ok(())
549            }
550            #[cfg(feature = "pin")]
551            (Joining::AwaitReply, READY) if self.mode == Mode::Pin => {
552                let key = reader.key()?;
553                let slot = reader.byte()?;
554                reader.end()?;
555                self.responder_key(key)?;
556                let Kind::Pin { pin, role } = self.pairing.kind.clone() else {
557                    return Err(PairingError::Protocol);
558                };
559                let slot = (slot != NO_SLOT).then_some(slot);
560                if (role == PinRole::Shown) != slot.is_some() {
561                    return Err(PairingError::Protocol);
562                }
563                if role == PinRole::Shown {
564                    self.shown = Some(Shown::Pin(PairingCode {
565                        slot,
566                        pin: pin.clone(),
567                    }));
568                }
569                let remote = self.remote.as_ref().ok_or(PairingError::Protocol)?;
570                let random = self.pairing.random.clone().unwrap_or_else(Random::os);
571                let (pake, sent) =
572                    pin::start(true, &pin, &self.channel.local.id(), &remote.id(), &random)?;
573                let mut out = Writer::new(PAKE);
574                out.short(&sent);
575                self.out.push_back(out.finish());
576                self.state = Joining::AwaitPake { pake, slot, sent };
577                Ok(())
578            }
579            #[cfg(feature = "pin")]
580            (Joining::AwaitPake { pake, slot, sent }, REPLY) => {
581                let received = reader.short()?.to_vec();
582                let tag = reader.tag()?;
583                reader.end()?;
584                let Some(keys) = pin::finish(pake, &received) else {
585                    return Err(self.refuse(PairRefusal::WrongCode));
586                };
587                let remote = self.remote.as_ref().ok_or(PairingError::Protocol)?;
588                let record = transcript(
589                    &self.channel.local,
590                    remote,
591                    slot,
592                    &sent,
593                    &received,
594                    &self.channel.binding,
595                );
596                if !pin::verify(&keys.responder, &record, &tag) {
597                    return Err(self.refuse(PairRefusal::WrongCode));
598                }
599                let mac = pin::mac(&keys.joiner, &record).ok_or(PairingError::Protocol)?;
600                let mut out = Writer::new(CONFIRM);
601                out.raw(&mac);
602                self.out.push_back(out.finish());
603                self.state = Joining::AwaitDone;
604                Ok(())
605            }
606            (Joining::AwaitDone, DONE) => {
607                let key = reader.key()?;
608                reader.end()?;
609                self.responder_key(key)?;
610                self.state = Joining::Complete;
611                Ok(())
612            }
613            _ => Err(PairingError::Protocol),
614        }
615    }
616}
617
618enum Responding {
619    AwaitHello,
620    #[cfg(feature = "pin")]
621    AwaitPake {
622        typed: bool,
623        slot: Option<u8>,
624    },
625    #[cfg(feature = "pin")]
626    AwaitCode {
627        received: Vec<u8>,
628        slot: Option<u8>,
629    },
630    #[cfg(feature = "pin")]
631    AwaitConfirm {
632        key: Zeroizing<[u8; 32]>,
633        record: Vec<u8>,
634    },
635    AwaitDecision,
636    Complete,
637    Failed,
638}
639
640/// The responder's side of a pairing exchange: it redeems invitations from its
641/// [`TrustStore`], takes PINs and decisions from its [`PairingDesk`], and accepts the joiner's
642/// key in the store when the pairing succeeds.
643pub struct PairingResponder {
644    channel: Channel,
645    store: TrustStore,
646    desk: PairingDesk,
647    source: Option<SocketAddr>,
648    joiner: Option<KeyMaterial>,
649    mode: Option<Mode>,
650    admission: Option<Admission>,
651    deadline: Option<SystemTime>,
652    out: VecDeque<Vec<u8>>,
653    state: Responding,
654}
655
656impl fmt::Debug for PairingResponder {
657    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
658        formatter
659            .debug_struct("PairingResponder")
660            .field("mode", &self.mode)
661            .field("complete", &self.is_complete())
662            .finish_non_exhaustive()
663    }
664}
665
666impl PairingResponder {
667    /// A responder over `channel`, for a joiner that connected from `source` (used by the
668    /// desk's per-source throttle).
669    pub fn new(
670        channel: Channel,
671        store: &TrustStore,
672        desk: &PairingDesk,
673        source: Option<SocketAddr>,
674    ) -> Self {
675        Self {
676            channel,
677            store: store.clone(),
678            desk: desk.clone(),
679            source,
680            joiner: None,
681            mode: None,
682            admission: None,
683            deadline: None,
684            out: VecDeque::new(),
685            state: Responding::AwaitHello,
686        }
687    }
688
689    /// The next message to send, or `None`. Call until `None`.
690    pub fn transmit(&mut self) -> Option<Vec<u8>> {
691        self.out.pop_front()
692    }
693
694    /// The decision this responder waits for, when it waits: hand it to
695    /// [`PairingDesk::wait`] or [`PairingDesk::decided`], then to
696    /// [`resume`](PairingResponder::resume).
697    pub fn awaiting(&self) -> Option<Ticket> {
698        let waits = match self.state {
699            #[cfg(feature = "pin")]
700            Responding::AwaitCode { .. } => true,
701            Responding::AwaitDecision => true,
702            _ => false,
703        };
704        waits
705            .then(|| self.admission.as_ref().map(Admission::ticket))
706            .flatten()
707    }
708
709    /// The joiner's key, once its first message arrived.
710    pub fn joiner(&self) -> Option<&KeyMaterial> {
711        self.joiner.as_ref()
712    }
713
714    /// Whether the exchange succeeded.
715    pub fn is_complete(&self) -> bool {
716        matches!(self.state, Responding::Complete)
717    }
718
719    /// The paired joiner, already accepted in the store.
720    ///
721    /// # Errors
722    ///
723    /// [`PairingError::Protocol`] before completion.
724    pub fn finish(self) -> Result<Paired, PairingError> {
725        match (self.state, self.joiner, self.mode) {
726            (Responding::Complete, Some(peer), Some(mode)) => Ok(Paired { peer, mode }),
727            _ => Err(PairingError::Protocol),
728        }
729    }
730
731    /// Takes one message from the joiner.
732    ///
733    /// # Errors
734    ///
735    /// [`PairingError::Refused`] when this side refuses (a refusal is then queued for the
736    /// joiner) or the joiner did; [`PairingError::Protocol`]; [`PairingError::Local`] when the
737    /// store or the random source fails. The exchange is over after an error.
738    pub fn receive(&mut self, message: &[u8]) -> Result<(), PairingError> {
739        self.check_deadline()?;
740        let result = self.step(message);
741        if result.is_err() {
742            self.state = Responding::Failed;
743            self.admission = None;
744        }
745        result
746    }
747
748    /// Settles the decision [`awaiting`](PairingResponder::awaiting) named.
749    ///
750    /// # Errors
751    ///
752    /// As [`receive`](PairingResponder::receive); [`PairRefusal::Denied`] or
753    /// [`PairRefusal::Expired`] when that is the decision.
754    pub fn resume(&mut self, decision: Decision) -> Result<(), PairingError> {
755        self.check_deadline()?;
756        let result = self.decide(decision);
757        if result.is_err() {
758            self.state = Responding::Failed;
759            self.admission = None;
760        }
761        result
762    }
763
764    /// When this exchange must be over, on the desk's clock: from the joiner's first message,
765    /// [`PairingOptions::pin_ttl`] for a PIN and [`PairingOptions::device_ttl`] for the device
766    /// flow. `None` before that message, and for an invitation, which ends with it. A transport
767    /// reads with a timeout up to it, then calls [`check_deadline`](PairingResponder::check_deadline).
768    pub fn deadline(&self) -> Option<SystemTime> {
769        self.deadline
770    }
771
772    /// How long until the [`deadline`](PairingResponder::deadline), on the desk's clock: zero
773    /// once it passed, `None` while there is none. A transport's read timeout.
774    pub fn time_left(&self) -> Option<Duration> {
775        self.deadline
776            .map(|deadline| deadline.duration_since(self.desk.now()).unwrap_or_default())
777    }
778
779    /// Ends the exchange once its [`deadline`](PairingResponder::deadline) passed: the joiner is
780    /// told `Expired`, and the slot or user code is released. [`receive`](PairingResponder::receive)
781    /// and [`resume`](PairingResponder::resume) check it first.
782    ///
783    /// # Errors
784    ///
785    /// [`PairRefusal::Expired`] when the deadline passed.
786    pub fn check_deadline(&mut self) -> Result<(), PairingError> {
787        if matches!(self.state, Responding::Complete | Responding::Failed) {
788            return Ok(());
789        }
790        if self
791            .deadline
792            .is_some_and(|deadline| self.desk.now() >= deadline)
793        {
794            self.state = Responding::Failed;
795            self.admission = None;
796            return Err(self.refuse(PairRefusal::Expired));
797        }
798        Ok(())
799    }
800
801    fn refuse(&mut self, refusal: PairRefusal) -> PairingError {
802        self.out.push_back(refused(refusal));
803        PairingError::Refused(refusal)
804    }
805
806    /// Accepts the joiner and tells it so.
807    fn accept(&mut self) -> Result<(), PairingError> {
808        let joiner = self.joiner.as_ref().ok_or(PairingError::Protocol)?;
809        match self.store.accept_key(joiner) {
810            Ok(_) | Err(Error::AlreadyAccepted) => {}
811            Err(error) => return Err(PairingError::Local(error)),
812        }
813        let mut done = Writer::new(DONE);
814        done.key(&self.channel.local);
815        self.out.push_back(done.finish());
816        self.state = Responding::Complete;
817        self.admission = None;
818        Ok(())
819    }
820
821    fn decide(&mut self, decision: Decision) -> Result<(), PairingError> {
822        match (
823            core::mem::replace(&mut self.state, Responding::Failed),
824            decision,
825        ) {
826            (Responding::AwaitDecision, Decision::Approved) => self.accept(),
827            (Responding::AwaitDecision, Decision::Denied) => Err(self.refuse(PairRefusal::Denied)),
828            #[cfg(feature = "pin")]
829            (Responding::AwaitCode { received, slot }, Decision::Code(pin)) => {
830                self.reply(&pin, &received, slot)
831            }
832            (_, Decision::Expired) => Err(self.refuse(PairRefusal::Expired)),
833            _ => Err(PairingError::Protocol),
834        }
835    }
836
837    #[cfg(feature = "pin")]
838    fn reply(&mut self, pin: &Pin, received: &[u8], slot: Option<u8>) -> Result<(), PairingError> {
839        let joiner = self.joiner.clone().ok_or(PairingError::Protocol)?;
840        let random = self.desk.random();
841        let (pake, sent) = pin::start(false, pin, &joiner.id(), &self.channel.local.id(), &random)?;
842        let Some(keys) = pin::finish(pake, received) else {
843            return Err(self.refuse(PairRefusal::WrongCode));
844        };
845        let record = transcript(
846            &joiner,
847            &self.channel.local,
848            slot,
849            received,
850            &sent,
851            &self.channel.binding,
852        );
853        let mac = pin::mac(&keys.responder, &record).ok_or(PairingError::Protocol)?;
854        let mut out = Writer::new(REPLY);
855        out.short(&sent);
856        out.raw(&mac);
857        self.out.push_back(out.finish());
858        self.state = Responding::AwaitConfirm {
859            key: Zeroizing::new(keys.joiner),
860            record,
861        };
862        Ok(())
863    }
864
865    fn step(&mut self, message: &[u8]) -> Result<(), PairingError> {
866        let (tag, mut reader) = Reader::open(message)?;
867        if tag == REFUSED {
868            let refusal = PairRefusal::from_wire(reader.byte()?).ok_or(PairingError::Protocol)?;
869            reader.end()?;
870            return Err(PairingError::Refused(refusal));
871        }
872        match (core::mem::replace(&mut self.state, Responding::Failed), tag) {
873            (Responding::AwaitHello, HELLO) => self.hello(&mut reader),
874            #[cfg(feature = "pin")]
875            (Responding::AwaitPake { typed, slot }, PAKE) => {
876                let received = reader.short()?.to_vec();
877                reader.end()?;
878                if typed {
879                    match self.desk.take_pin() {
880                        Ok(pin) => self.reply(&pin, &received, slot),
881                        Err(refusal) => Err(self.refuse(refusal)),
882                    }
883                } else {
884                    self.state = Responding::AwaitCode { received, slot };
885                    Ok(())
886                }
887            }
888            #[cfg(feature = "pin")]
889            (Responding::AwaitConfirm { key, record }, CONFIRM) => {
890                let tag = reader.tag()?;
891                reader.end()?;
892                if pin::verify(&key, &record, &tag) {
893                    self.accept()
894                } else {
895                    Err(self.refuse(PairRefusal::WrongCode))
896                }
897            }
898            _ => Err(PairingError::Protocol),
899        }
900    }
901
902    fn hello(&mut self, reader: &mut Reader<'_>) -> Result<(), PairingError> {
903        let mode = reader.byte()?;
904        let joiner = reader.key()?;
905        if self
906            .channel
907            .remote
908            .as_ref()
909            .is_some_and(|remote| *remote != joiner)
910        {
911            return Err(PairingError::Protocol);
912        }
913        let options = self.desk.options();
914        let (kind, enabled) = match mode {
915            MODE_INVITATION => (Mode::Invitation, options.invitation),
916            MODE_PIN_TYPED | MODE_PIN_SHOWN => (Mode::Pin, options.pin && cfg!(feature = "pin")),
917            MODE_DEVICE => (Mode::Device, options.device),
918            _ => return Err(PairingError::Protocol),
919        };
920        self.joiner = Some(joiner.clone());
921        self.mode = Some(kind);
922        if !enabled {
923            return Err(self.refuse(PairRefusal::Disabled));
924        }
925        let admission = match self.desk.admit(self.source) {
926            Ok(admission) => admission,
927            Err(refusal) => return Err(self.refuse(refusal)),
928        };
929        let ttl = match mode {
930            MODE_DEVICE => Some(options.device_ttl),
931            MODE_PIN_TYPED | MODE_PIN_SHOWN => Some(options.pin_ttl),
932            _ => None,
933        };
934        self.deadline = ttl.map(|ttl| later(self.desk.now(), ttl));
935        match mode {
936            MODE_INVITATION => {
937                let secret: Zeroizing<[u8; 32]> = Zeroizing::new(
938                    reader
939                        .take(32)?
940                        .try_into()
941                        .map_err(|_| PairingError::Protocol)?,
942                );
943                reader.end()?;
944                self.admission = Some(admission);
945                match self.store.redeem(&secret) {
946                    Ok(_) => self.accept(),
947                    Err(Error::NotInvited) => Err(self.refuse(PairRefusal::WrongCode)),
948                    Err(Error::Expired) => Err(self.refuse(PairRefusal::Expired)),
949                    Err(error) => Err(PairingError::Local(error)),
950                }
951            }
952            MODE_DEVICE => {
953                let label = String::from_utf8(reader.short()?.to_vec())
954                    .map_err(|_| PairingError::Protocol)?;
955                if !plain(&label) {
956                    return Err(PairingError::Protocol);
957                }
958                reader.end()?;
959                let (code, expires) =
960                    self.desk
961                        .issue(&admission, joiner.id(), self.source, &label)?;
962                let mut issued = Writer::new(ISSUED);
963                issued.key(&self.channel.local);
964                issued.short(code.as_str().as_bytes());
965                issued.long(unix_seconds(expires));
966                self.out.push_back(issued.finish());
967                self.admission = Some(admission);
968                self.state = Responding::AwaitDecision;
969                Ok(())
970            }
971            #[cfg(feature = "pin")]
972            _ => {
973                reader.end()?;
974                if let Err(refusal) = self.desk.pin_run(self.source) {
975                    return Err(self.refuse(refusal));
976                }
977                let typed = mode == MODE_PIN_TYPED;
978                let slot = if typed {
979                    if let Err(refusal) = self.desk.pin_ready() {
980                        return Err(self.refuse(refusal));
981                    }
982                    None
983                } else {
984                    Some(self.desk.open_slot(&admission, joiner.id(), self.source)?)
985                };
986                let mut ready = Writer::new(READY);
987                ready.key(&self.channel.local);
988                ready.byte(slot.unwrap_or(NO_SLOT));
989                self.out.push_back(ready.finish());
990                self.admission = Some(admission);
991                self.state = Responding::AwaitPake { typed, slot };
992                Ok(())
993            }
994            #[cfg(not(feature = "pin"))]
995            _ => Err(self.refuse(PairRefusal::Disabled)),
996        }
997    }
998}
999
1000/// The key-rotation announcement: the message a peer sends, over a session its current key
1001/// authenticated, to name its successor key.
1002#[derive(Debug, Clone, Copy)]
1003pub struct Rotation;
1004
1005impl Rotation {
1006    /// The announcement of `successor`.
1007    pub fn announce(successor: &KeyMaterial) -> Vec<u8> {
1008        let mut out = Writer::new(ANNOUNCE);
1009        out.key(successor);
1010        out.finish()
1011    }
1012
1013    /// The successor key an announcement names.
1014    ///
1015    /// # Errors
1016    ///
1017    /// [`PairingError::Protocol`] when `message` is not an announcement.
1018    pub fn parse(message: &[u8]) -> Result<KeyMaterial, PairingError> {
1019        let (tag, mut reader) = Reader::open(message)?;
1020        if tag != ANNOUNCE {
1021            return Err(PairingError::Protocol);
1022        }
1023        let key = reader.key()?;
1024        reader.end()?;
1025        Ok(key)
1026    }
1027}
1028
1029/// Whether `text` is safe to show as it is: no control characters (line breaks included) and
1030/// no bidirectional formatting characters, which can make a label or code read as another.
1031fn plain(text: &str) -> bool {
1032    !text.chars().any(|c| {
1033        c.is_control()
1034            || matches!(c, '\u{200E}' | '\u{200F}' | '\u{061C}')
1035            || ('\u{202A}'..='\u{202E}').contains(&c)
1036            || ('\u{2066}'..='\u{2069}').contains(&c)
1037    })
1038}
1039
1040fn refused(refusal: PairRefusal) -> Vec<u8> {
1041    let mut out = Writer::new(REFUSED);
1042    out.byte(refusal.wire());
1043    out.finish()
1044}
1045
1046/// What both PIN confirmations cover: both keys, the slot, both PAKE messages and the channel
1047/// binding, each length-prefixed.
1048#[cfg(feature = "pin")]
1049fn transcript(
1050    joiner: &KeyMaterial,
1051    responder: &KeyMaterial,
1052    slot: Option<u8>,
1053    joiner_message: &[u8],
1054    responder_message: &[u8],
1055    binding: &Option<Vec<u8>>,
1056) -> Vec<u8> {
1057    let mut out = Writer(Vec::new());
1058    out.raw(b"coqui-pair pin");
1059    out.key(joiner);
1060    out.key(responder);
1061    out.byte(slot.unwrap_or(NO_SLOT));
1062    out.short(joiner_message);
1063    out.short(responder_message);
1064    match binding {
1065        Some(binding) => {
1066            out.byte(1);
1067            out.wide(binding);
1068        }
1069        None => out.byte(0),
1070    }
1071    out.finish()
1072}
1073
1074/// Builds a message: the version, a tag, then fields.
1075struct Writer(Vec<u8>);
1076
1077impl Writer {
1078    fn new(tag: u8) -> Self {
1079        Self(vec![VERSION, tag])
1080    }
1081
1082    fn byte(&mut self, value: u8) {
1083        self.0.push(value);
1084    }
1085
1086    fn raw(&mut self, bytes: &[u8]) {
1087        self.0.extend_from_slice(bytes);
1088    }
1089
1090    /// At most 255 bytes, after a one-byte length.
1091    fn short(&mut self, bytes: &[u8]) {
1092        let bytes = &bytes[..bytes.len().min(255)];
1093        self.0.push(bytes.len() as u8);
1094        self.0.extend_from_slice(bytes);
1095    }
1096
1097    /// After a four-byte big-endian length.
1098    fn wide(&mut self, bytes: &[u8]) {
1099        let length = u32::try_from(bytes.len()).unwrap_or(u32::MAX);
1100        self.0.extend_from_slice(&length.to_be_bytes());
1101        self.0.extend_from_slice(&bytes[..length as usize]);
1102    }
1103
1104    fn long(&mut self, value: u64) {
1105        self.0.extend_from_slice(&value.to_be_bytes());
1106    }
1107
1108    /// The method, the label, then the bytes.
1109    fn key(&mut self, key: &KeyMaterial) {
1110        self.short(key.method.as_bytes());
1111        self.short(key.label.as_bytes());
1112        self.wide(&key.bytes);
1113    }
1114
1115    fn finish(self) -> Vec<u8> {
1116        self.0
1117    }
1118}
1119
1120/// Reads a message's fields; every shortfall is [`PairingError::Protocol`].
1121struct Reader<'a>(&'a [u8]);
1122
1123impl<'a> Reader<'a> {
1124    /// A reader of `bytes` past the version, and the message tag.
1125    fn open(bytes: &'a [u8]) -> Result<(u8, Self), PairingError> {
1126        let mut reader = Self(bytes);
1127        if reader.byte()? != VERSION {
1128            return Err(PairingError::Protocol);
1129        }
1130        let tag = reader.byte()?;
1131        Ok((tag, reader))
1132    }
1133
1134    fn take(&mut self, count: usize) -> Result<&'a [u8], PairingError> {
1135        if self.0.len() < count {
1136            return Err(PairingError::Protocol);
1137        }
1138        let (taken, rest) = self.0.split_at(count);
1139        self.0 = rest;
1140        Ok(taken)
1141    }
1142
1143    fn byte(&mut self) -> Result<u8, PairingError> {
1144        Ok(self.take(1)?[0])
1145    }
1146
1147    fn short(&mut self) -> Result<&'a [u8], PairingError> {
1148        let length = usize::from(self.byte()?);
1149        self.take(length)
1150    }
1151
1152    fn wide(&mut self) -> Result<&'a [u8], PairingError> {
1153        let length: [u8; 4] = self
1154            .take(4)?
1155            .try_into()
1156            .map_err(|_| PairingError::Protocol)?;
1157        self.take(usize::try_from(u32::from_be_bytes(length)).map_err(|_| PairingError::Protocol)?)
1158    }
1159
1160    fn long(&mut self) -> Result<u64, PairingError> {
1161        let bytes: [u8; 8] = self
1162            .take(8)?
1163            .try_into()
1164            .map_err(|_| PairingError::Protocol)?;
1165        Ok(u64::from_be_bytes(bytes))
1166    }
1167
1168    #[cfg(feature = "pin")]
1169    fn tag(&mut self) -> Result<[u8; 32], PairingError> {
1170        self.take(32)?
1171            .try_into()
1172            .map_err(|_| PairingError::Protocol)
1173    }
1174
1175    fn key(&mut self) -> Result<KeyMaterial, PairingError> {
1176        let method = core::str::from_utf8(self.short()?).map_err(|_| PairingError::Protocol)?;
1177        let label = core::str::from_utf8(self.short()?).map_err(|_| PairingError::Protocol)?;
1178        let bytes = self.wide()?;
1179        KeyMaterial::new(method, label, bytes).map_err(|_| PairingError::Protocol)
1180    }
1181
1182    fn end(&self) -> Result<(), PairingError> {
1183        if self.0.is_empty() {
1184            Ok(())
1185        } else {
1186            Err(PairingError::Protocol)
1187        }
1188    }
1189}