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 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
51const 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
69const NO_SLOT: u8 = 0xff;
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74#[non_exhaustive]
75pub enum PairRefusal {
76 WrongCode,
79 Expired,
81 Exhausted,
83 Throttled,
85 Denied,
87 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#[derive(Debug)]
131#[non_exhaustive]
132pub enum PairingError {
133 Refused(PairRefusal),
135 Protocol,
137 Unverified,
140 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#[derive(Clone, PartialEq, Eq)]
172pub struct Channel {
173 pub local: KeyMaterial,
175 pub remote: Option<KeyMaterial>,
178 pub verified: bool,
182 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
201#[non_exhaustive]
202pub enum Mode {
203 Invitation,
205 Pin,
207 Device,
209}
210
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
213pub enum PinRole {
214 Typed,
216 Shown,
219}
220
221#[derive(Debug, Clone, PartialEq, Eq)]
223#[non_exhaustive]
224pub enum Shown {
225 Pin(PairingCode),
227 UserCode {
229 code: UserCode,
231 expires: SystemTime,
233 },
234}
235
236#[derive(Debug, Clone, PartialEq, Eq)]
238pub struct Paired {
239 pub peer: KeyMaterial,
242 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#[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 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 #[cfg(feature = "pin")]
297 pub fn pin(pin: Pin, role: PinRole) -> Self {
298 Self::of(Kind::Pin { pin, role })
299 }
300
301 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 #[must_use]
327 pub fn allow_unverified(mut self, allow: bool) -> Self {
328 self.allow_unverified = allow;
329 self
330 }
331
332 pub fn allows_unverified(&self) -> bool {
334 self.allow_unverified
335 }
336
337 #[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 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 pub fn inviter(&self) -> Option<PeerId> {
357 match self.kind {
358 Kind::Invitation { inviter, .. } => Some(inviter),
359 _ => None,
360 }
361 }
362
363 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
433pub 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 pub fn transmit(&mut self) -> Option<Vec<u8>> {
457 self.out.pop_front()
458 }
459
460 pub fn shown(&self) -> Option<&Shown> {
462 self.shown.as_ref()
463 }
464
465 pub fn is_complete(&self) -> bool {
467 matches!(self.state, Joining::Complete)
468 }
469
470 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 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 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
640pub 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 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 pub fn transmit(&mut self) -> Option<Vec<u8>> {
691 self.out.pop_front()
692 }
693
694 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 pub fn joiner(&self) -> Option<&KeyMaterial> {
711 self.joiner.as_ref()
712 }
713
714 pub fn is_complete(&self) -> bool {
716 matches!(self.state, Responding::Complete)
717 }
718
719 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 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 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 pub fn deadline(&self) -> Option<SystemTime> {
769 self.deadline
770 }
771
772 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 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 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#[derive(Debug, Clone, Copy)]
1003pub struct Rotation;
1004
1005impl Rotation {
1006 pub fn announce(successor: &KeyMaterial) -> Vec<u8> {
1008 let mut out = Writer::new(ANNOUNCE);
1009 out.key(successor);
1010 out.finish()
1011 }
1012
1013 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
1029fn 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#[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
1074struct 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 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 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 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
1120struct Reader<'a>(&'a [u8]);
1122
1123impl<'a> Reader<'a> {
1124 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}