1#![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
53const 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
71const NO_SLOT: u8 = 0xff;
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76#[non_exhaustive]
77pub enum PairRefusal {
78 WrongCode,
81 Expired,
83 Exhausted,
85 Throttled,
87 Denied,
89 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#[derive(Debug)]
133#[non_exhaustive]
134pub enum PairingError {
135 Refused(PairRefusal),
137 Protocol,
139 Unverified,
142 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#[derive(Clone, PartialEq, Eq)]
174pub struct Channel {
175 pub local: KeyMaterial,
177 pub remote: Option<KeyMaterial>,
180 pub verified: bool,
184 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
203#[non_exhaustive]
204pub enum Mode {
205 Invitation,
207 Pin,
209 Device,
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
215pub enum PinRole {
216 Typed,
218 Shown,
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
225#[non_exhaustive]
226pub enum Shown {
227 Pin(PairingCode),
229 UserCode {
231 code: UserCode,
233 expires: SystemTime,
235 },
236}
237
238#[derive(Debug, Clone, PartialEq, Eq)]
240#[non_exhaustive]
241pub struct Paired {
242 pub peer: KeyMaterial,
245 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#[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 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 #[cfg(feature = "pin")]
300 pub fn pin(pin: Pin, role: PinRole) -> Self {
301 Self::of(Kind::Pin { pin, role })
302 }
303
304 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 #[must_use]
330 pub fn allow_unverified(mut self, allow: bool) -> Self {
331 self.allow_unverified = allow;
332 self
333 }
334
335 pub fn allows_unverified(&self) -> bool {
337 self.allow_unverified
338 }
339
340 #[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 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 pub fn inviter(&self) -> Option<PeerId> {
360 match self.kind {
361 Kind::Invitation { inviter, .. } => Some(inviter),
362 _ => None,
363 }
364 }
365
366 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
436pub 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 pub fn transmit(&mut self) -> Option<Vec<u8>> {
460 self.out.pop_front()
461 }
462
463 pub fn shown(&self) -> Option<&Shown> {
465 self.shown.as_ref()
466 }
467
468 pub fn is_complete(&self) -> bool {
470 matches!(self.state, Joining::Complete)
471 }
472
473 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 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 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
643pub trait PairingStore: Send + Sync {
648 fn accept_key(&self, key: &KeyMaterial) -> Result<PeerId, Error>;
655
656 fn redeem(&self, secret: &[u8; 32]) -> Result<crate::Invitation, Error>;
663
664 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
697pub 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 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 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 pub fn transmit(&mut self) -> Option<Vec<u8>> {
759 self.out.pop_front()
760 }
761
762 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 pub fn joiner(&self) -> Option<&KeyMaterial> {
779 self.joiner.as_ref()
780 }
781
782 pub fn is_complete(&self) -> bool {
784 matches!(self.state, Responding::Complete)
785 }
786
787 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 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 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 pub fn deadline(&self) -> Option<SystemTime> {
837 self.deadline
838 }
839
840 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 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 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 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#[derive(Debug, Clone, Copy)]
1076pub struct Rotation;
1077
1078impl Rotation {
1079 pub fn announce(successor: &KeyMaterial) -> Vec<u8> {
1081 let mut out = Writer::new(ANNOUNCE);
1082 out.key(successor);
1083 out.finish()
1084 }
1085
1086 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
1102fn 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#[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
1147struct 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 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 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 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
1193struct Reader<'a>(&'a [u8]);
1195
1196impl<'a> Reader<'a> {
1197 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}