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