1use std::future::Future;
11use std::pin::Pin;
12use std::sync::{Arc, Mutex};
13use std::time::Duration;
14
15use bt_hci::cmd::le::{
16 LeEnableEncryption, LeLongTermKeyRequestNegativeReply, LeLongTermKeyRequestReply,
17};
18use bt_hci::param::ConnHandle;
19use serde::{Deserialize, Serialize};
20use tokio::sync::{mpsc, oneshot};
21
22use crate::address::{Address, AddressType};
23use crate::connection::{ConnState, Connection, Role, Security};
24use crate::crypto::{self, EcdhKey};
25use crate::error::{Error, Result};
26use crate::host::{Host, HostEvent};
27use crate::keys::{Bond, LongTermKey};
28use crate::l2cap::cid;
29
30mod code {
32 pub const PAIRING_REQUEST: u8 = 0x01;
33 pub const PAIRING_RESPONSE: u8 = 0x02;
34 pub const PAIRING_CONFIRM: u8 = 0x03;
35 pub const PAIRING_RANDOM: u8 = 0x04;
36 pub const PAIRING_FAILED: u8 = 0x05;
37 pub const ENCRYPTION_INFORMATION: u8 = 0x06;
38 pub const CENTRAL_IDENTIFICATION: u8 = 0x07;
39 pub const IDENTITY_INFORMATION: u8 = 0x08;
40 pub const IDENTITY_ADDRESS_INFORMATION: u8 = 0x09;
41 pub const SIGNING_INFORMATION: u8 = 0x0a;
42 pub const SECURITY_REQUEST: u8 = 0x0b;
43 pub const PAIRING_PUBLIC_KEY: u8 = 0x0c;
44 pub const PAIRING_DHKEY_CHECK: u8 = 0x0d;
45 pub const KEYPRESS_NOTIFICATION: u8 = 0x0e;
46}
47
48pub mod reason {
50 pub const PASSKEY_ENTRY_FAILED: u8 = 0x01;
52 pub const OOB_NOT_AVAILABLE: u8 = 0x02;
54 pub const AUTHENTICATION_REQUIREMENTS: u8 = 0x03;
56 pub const CONFIRM_VALUE_FAILED: u8 = 0x04;
58 pub const PAIRING_NOT_SUPPORTED: u8 = 0x05;
60 pub const ENCRYPTION_KEY_SIZE: u8 = 0x06;
62 pub const COMMAND_NOT_SUPPORTED: u8 = 0x07;
64 pub const UNSPECIFIED: u8 = 0x08;
66 pub const INVALID_PARAMETERS: u8 = 0x0a;
68 pub const DHKEY_CHECK_FAILED: u8 = 0x0b;
70 pub const NUMERIC_COMPARISON_FAILED: u8 = 0x0c;
72}
73
74fn reason_name(r: u8) -> &'static str {
75 match r {
76 0x01 => "Passkey Entry Failed",
77 0x02 => "OOB Not Available",
78 0x03 => "Authentication Requirements",
79 0x04 => "Confirm Value Failed",
80 0x05 => "Pairing Not Supported",
81 0x06 => "Encryption Key Size",
82 0x07 => "Command Not Supported",
83 0x08 => "Unspecified Reason",
84 0x09 => "Repeated Attempts",
85 0x0a => "Invalid Parameters",
86 0x0b => "DHKey Check Failed",
87 0x0c => "Numeric Comparison Failed",
88 0x0d => "BR/EDR pairing in progress",
89 0x0e => "Cross-transport Key Derivation/Generation not allowed",
90 0x0f => "Key Rejected",
91 0x10 => "Busy",
92 _ => "Reserved",
93 }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
98#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
99#[serde(rename_all = "snake_case")]
100pub enum IoCapability {
101 DisplayOnly,
103 DisplayYesNo,
105 KeyboardOnly,
107 NoInputNoOutput,
109 KeyboardDisplay,
111}
112
113impl IoCapability {
114 fn wire(self) -> u8 {
115 match self {
116 IoCapability::DisplayOnly => 0,
117 IoCapability::DisplayYesNo => 1,
118 IoCapability::KeyboardOnly => 2,
119 IoCapability::NoInputNoOutput => 3,
120 IoCapability::KeyboardDisplay => 4,
121 }
122 }
123
124 fn from_wire(v: u8) -> Option<Self> {
125 Some(match v {
126 0 => IoCapability::DisplayOnly,
127 1 => IoCapability::DisplayYesNo,
128 2 => IoCapability::KeyboardOnly,
129 3 => IoCapability::NoInputNoOutput,
130 4 => IoCapability::KeyboardDisplay,
131 _ => return None,
132 })
133 }
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
138#[serde(rename_all = "snake_case")]
139pub enum Method {
140 JustWorks,
142 NumericComparison,
144 PasskeyInitiatorInputs,
146 PasskeyResponderInputs,
148 PasskeyBothInput,
150 OutOfBand,
152}
153
154pub fn method(init: IoCapability, resp: IoCapability, sc: bool) -> Method {
157 use IoCapability::*;
158 use Method::*;
159 match (resp, init) {
160 (NoInputNoOutput, _) | (_, NoInputNoOutput) => JustWorks,
161 (DisplayOnly, DisplayOnly | DisplayYesNo) => JustWorks,
162 (DisplayOnly, KeyboardOnly | KeyboardDisplay) => PasskeyInitiatorInputs,
163 (DisplayYesNo, DisplayOnly) => JustWorks,
164 (DisplayYesNo, DisplayYesNo) => {
165 if sc {
166 NumericComparison
167 } else {
168 JustWorks
169 }
170 }
171 (DisplayYesNo, KeyboardOnly) => PasskeyInitiatorInputs,
172 (DisplayYesNo, KeyboardDisplay) => {
173 if sc {
174 NumericComparison
175 } else {
176 PasskeyInitiatorInputs
177 }
178 }
179 (KeyboardOnly, KeyboardOnly) => PasskeyBothInput,
180 (KeyboardOnly, _) => PasskeyResponderInputs,
181 (KeyboardDisplay, DisplayOnly) => PasskeyResponderInputs,
182 (KeyboardDisplay, DisplayYesNo) => {
183 if sc {
184 NumericComparison
185 } else {
186 PasskeyResponderInputs
187 }
188 }
189 (KeyboardDisplay, KeyboardOnly) => PasskeyInitiatorInputs,
190 (KeyboardDisplay, KeyboardDisplay) => {
191 if sc {
192 NumericComparison
193 } else {
194 PasskeyInitiatorInputs
195 }
196 }
197 }
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub enum OobData {
203 Legacy([u8; 16]),
205 SecureConnections {
207 random: u128,
209 confirm: u128,
211 },
212}
213
214pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
216
217pub trait Agent: Send + Sync {
220 fn accept(&self, peer: Address, method: Method) -> BoxFuture<'_, bool>;
222 fn display_passkey(&self, peer: Address, passkey: u32) -> BoxFuture<'_, ()>;
224 fn request_passkey(&self, peer: Address) -> BoxFuture<'_, Option<u32>>;
226 fn confirm_number(&self, peer: Address, number: u32) -> BoxFuture<'_, bool>;
228 fn oob_data(&self, peer: Address) -> BoxFuture<'_, Option<OobData>>;
230}
231
232pub struct AutoAgent;
235
236impl Agent for AutoAgent {
237 fn accept(&self, _peer: Address, m: Method) -> BoxFuture<'_, bool> {
238 Box::pin(async move { matches!(m, Method::JustWorks | Method::NumericComparison) })
239 }
240 fn display_passkey(&self, peer: Address, passkey: u32) -> BoxFuture<'_, ()> {
241 Box::pin(async move { tracing::info!("pairing with {peer}: passkey {passkey:06}") })
242 }
243 fn request_passkey(&self, _peer: Address) -> BoxFuture<'_, Option<u32>> {
244 Box::pin(async { None })
245 }
246 fn confirm_number(&self, _peer: Address, _n: u32) -> BoxFuture<'_, bool> {
247 Box::pin(async { true })
248 }
249 fn oob_data(&self, _peer: Address) -> BoxFuture<'_, Option<OobData>> {
250 Box::pin(async { None })
251 }
252}
253
254#[derive(Debug, Clone, Default)]
257pub struct FixedAgent {
258 pub passkey: Option<u32>,
260 pub confirm: bool,
262 pub oob: Option<OobData>,
264}
265
266impl Agent for FixedAgent {
267 fn accept(&self, _peer: Address, _m: Method) -> BoxFuture<'_, bool> {
268 Box::pin(async { true })
269 }
270 fn display_passkey(&self, peer: Address, passkey: u32) -> BoxFuture<'_, ()> {
271 Box::pin(async move { tracing::info!("pairing with {peer}: passkey {passkey:06}") })
272 }
273 fn request_passkey(&self, _peer: Address) -> BoxFuture<'_, Option<u32>> {
274 Box::pin(async move { self.passkey })
275 }
276 fn confirm_number(&self, _peer: Address, _n: u32) -> BoxFuture<'_, bool> {
277 Box::pin(async move { self.confirm })
278 }
279 fn oob_data(&self, _peer: Address) -> BoxFuture<'_, Option<OobData>> {
280 Box::pin(async move { self.oob })
281 }
282}
283
284pub(crate) enum Command {
286 Pair(oneshot::Sender<Result<Security>>),
287}
288
289const SMP_TIMEOUT: Duration = Duration::from_secs(30);
290const MIN_KEY_SIZE: u8 = 7;
291
292const KEY_ENC: u8 = 0x01;
294const KEY_ID: u8 = 0x02;
295const KEY_SIGN: u8 = 0x04;
296
297const AUTH_BOND: u8 = 0x01;
299const AUTH_MITM: u8 = 0x04;
300const AUTH_SC: u8 = 0x08;
301const AUTH_CT2: u8 = 0x20;
302
303#[derive(Debug, Clone, Copy)]
304struct Features {
305 io: u8,
306 oob: u8,
307 auth: u8,
308 max_key: u8,
309 init_keys: u8,
310 resp_keys: u8,
311}
312
313impl Features {
314 fn pdu(&self, opcode: u8) -> [u8; 7] {
315 [
316 opcode,
317 self.io,
318 self.oob,
319 self.auth,
320 self.max_key,
321 self.init_keys,
322 self.resp_keys,
323 ]
324 }
325
326 fn parse(p: &[u8]) -> Option<Features> {
327 let p: &[u8; 7] = p.try_into().ok()?;
328 IoCapability::from_wire(p[1])?;
329 if !(MIN_KEY_SIZE..=16).contains(&p[4]) {
330 return None;
331 }
332 Some(Features {
333 io: p[1],
334 oob: p[2],
335 auth: p[3],
336 max_key: p[4],
337 init_keys: p[5] & 0x0f,
338 resp_keys: p[6] & 0x0f,
339 })
340 }
341}
342
343#[cfg(feature = "fuzzing")]
345pub(crate) fn parse_features(p: &[u8]) -> bool {
346 Features::parse(p).is_some()
347}
348
349struct Pairing<'a> {
351 host: &'a Host,
352 conn: &'a Arc<ConnState>,
353 rx: &'a mut mpsc::Receiver<Vec<u8>>,
354 initiator: bool,
355 preq: [u8; 7],
356 pres: [u8; 7],
357 ours: Features,
358 theirs: Features,
359}
360
361fn addresses(host: &Host, conn: &ConnState) -> (u8, [u8; 6], u8, [u8; 6]) {
363 let local = host.address();
364 let peer = conn.peer;
365 match conn.role {
366 Role::Central => (local.hci_type(), local.bytes, peer.hci_type(), peer.bytes),
367 Role::Peripheral => (peer.hci_type(), peer.bytes, local.hci_type(), local.bytes),
368 }
369}
370
371impl Pairing<'_> {
372 async fn send(&self, pdu: &[u8]) -> Result<()> {
373 self.conn.send(self.host, cid::SMP, pdu).await
374 }
375
376 async fn expect(&mut self, want: u8) -> Result<Vec<u8>> {
379 loop {
380 let pdu = tokio::select! {
381 p = tokio::time::timeout(SMP_TIMEOUT, self.rx.recv()) => match p {
382 Ok(Some(p)) => p,
383 Ok(None) => return Err(Error::Disconnected),
384 Err(_) => return Err(Error::Pairing("the peer stopped answering (SMP timeout)".into())),
385 },
386 _ = self.conn.wait_closed() => return Err(Error::Disconnected),
387 };
388 match pdu.first().copied() {
389 Some(c) if c == want => return Ok(pdu),
390 Some(code::PAIRING_FAILED) => {
391 let r = pdu.get(1).copied().unwrap_or(0);
392 return Err(Error::Pairing(format!(
393 "the peer failed it: {}",
394 reason_name(r)
395 )));
396 }
397 Some(code::KEYPRESS_NOTIFICATION) => continue,
399 Some(code::SECURITY_REQUEST) => continue,
400 _ => {
401 self.fail(reason::UNSPECIFIED).await;
402 return Err(Error::Pairing(format!(
403 "unexpected SMP PDU {:02x?}",
404 pdu.first()
405 )));
406 }
407 }
408 }
409 }
410
411 async fn fail(&self, r: u8) {
412 let _ = self.send(&[code::PAIRING_FAILED, r]).await;
413 }
414
415 async fn failed<T>(&self, r: u8, msg: &str) -> Result<T> {
416 self.fail(r).await;
417 Err(Error::Pairing(format!("{msg} ({})", reason_name(r))))
418 }
419
420 fn peer(&self) -> Address {
421 self.conn.identity()
422 }
423
424 fn key_size(&self) -> u8 {
425 self.ours.max_key.min(self.theirs.max_key)
426 }
427
428 fn init_io(&self) -> IoCapability {
429 let io = if self.initiator {
430 self.ours.io
431 } else {
432 self.theirs.io
433 };
434 IoCapability::from_wire(io).unwrap_or(IoCapability::NoInputNoOutput)
435 }
436
437 fn resp_io(&self) -> IoCapability {
438 let io = if self.initiator {
439 self.theirs.io
440 } else {
441 self.ours.io
442 };
443 IoCapability::from_wire(io).unwrap_or(IoCapability::NoInputNoOutput)
444 }
445
446 async fn run(mut self) -> Result<Security> {
448 let config = &self.host.inner.config;
449 let sc = self.ours.auth & self.theirs.auth & AUTH_SC != 0;
450 let mitm = (self.ours.auth | self.theirs.auth) & AUTH_MITM != 0;
451 if !sc && config.secure_connections_only {
452 return self
453 .failed(
454 reason::AUTHENTICATION_REQUIREMENTS,
455 "the peer does not do Secure Connections",
456 )
457 .await;
458 }
459 let oob = if sc {
460 self.ours.oob != 0 || self.theirs.oob != 0
461 } else {
462 self.ours.oob != 0 && self.theirs.oob != 0
463 };
464 let m = if oob {
465 Method::OutOfBand
466 } else if !mitm {
467 Method::JustWorks
468 } else {
469 method(self.init_io(), self.resp_io(), sc)
470 };
471 if config.mitm && m == Method::JustWorks {
472 return self
473 .failed(
474 reason::AUTHENTICATION_REQUIREMENTS,
475 "MITM protection is required",
476 )
477 .await;
478 }
479 let key_size = self.key_size();
480 tracing::info!(
481 "pairing with {} ({}, {:?}, {key_size}-octet key)",
482 self.peer(),
483 if sc { "Secure Connections" } else { "legacy" },
484 m
485 );
486 let (key, authenticated) = if sc {
487 (self.secure_connections(m).await?, m != Method::JustWorks)
488 } else {
489 (self.legacy(m).await?, m != Method::JustWorks)
490 };
491 let key = mask(key, key_size);
492 let security = Security {
493 encrypted: true,
494 authenticated,
495 secure_connections: sc,
496 key_size,
497 bonded: false,
498 };
499 self.encrypt_with(key, 0, 0, security).await?;
501 let bonded = self.distribute(sc, key, security).await?;
503 let security = Security { bonded, ..security };
504 self.conn.security.send_replace(Security {
505 encrypted: true,
506 ..security
507 });
508 Ok(security)
509 }
510
511 async fn encrypt_with(
512 &self,
513 key: u128,
514 ediv: u16,
515 rand: u64,
516 security: Security,
517 ) -> Result<()> {
518 *self
519 .conn
520 .pairing_key
521 .lock()
522 .unwrap_or_else(|e| e.into_inner()) = Some((key, security));
523 let (tx, rx) = oneshot::channel();
524 self.conn.waiters().encryption = Some(tx);
525 if self.initiator {
526 self.host
527 .inner
528 .hci
529 .exec_async(&LeEnableEncryption::new(
530 ConnHandle::new(self.conn.handle),
531 rand.to_le_bytes(),
532 ediv,
533 crypto::le(key),
534 ))
535 .await?;
536 }
537 match tokio::time::timeout(SMP_TIMEOUT, rx).await {
540 Ok(Ok(0)) => {
541 self.conn.security.send_replace(security);
542 Ok(())
543 }
544 Ok(Ok(s)) => Err(Error::Pairing(format!(
545 "encryption failed: {}",
546 crate::error::status_name(s)
547 ))),
548 Ok(Err(_)) => Err(Error::Disconnected),
549 Err(_) => Err(Error::Pairing("encryption did not start".into())),
550 }
551 }
552
553 async fn legacy(&mut self, m: Method) -> Result<u128> {
556 let agent = self.host.inner.config.agent.clone();
557 let tk: u128 = match m {
558 Method::JustWorks => 0,
559 Method::OutOfBand => match agent.oob_data(self.peer()).await {
560 Some(OobData::Legacy(tk)) => crypto::from_le(tk),
561 _ => return self.failed(reason::OOB_NOT_AVAILABLE, "no OOB data").await,
562 },
563 _ => u128::from(self.passkey(m).await?),
564 };
565 let (iat, ia, rat, ra) = addresses(self.host, self.conn);
566 let mrand_or_srand = crypto::random_u128();
567 let our_confirm = crypto::c1(
568 tk,
569 mrand_or_srand,
570 &self.preq,
571 &self.pres,
572 iat,
573 rat,
574 &ia,
575 &ra,
576 );
577 let (mrand, srand) = if self.initiator {
578 self.send(&confirm_pdu(code::PAIRING_CONFIRM, our_confirm))
579 .await?;
580 let sconfirm = value(&self.expect(code::PAIRING_CONFIRM).await?);
581 self.send(&confirm_pdu(code::PAIRING_RANDOM, mrand_or_srand))
582 .await?;
583 let srand = value(&self.expect(code::PAIRING_RANDOM).await?);
584 if crypto::c1(tk, srand, &self.preq, &self.pres, iat, rat, &ia, &ra) != sconfirm {
585 return self
586 .failed(
587 reason::CONFIRM_VALUE_FAILED,
588 "the peer's confirm value is wrong",
589 )
590 .await;
591 }
592 (mrand_or_srand, srand)
593 } else {
594 let mconfirm = value(&self.expect(code::PAIRING_CONFIRM).await?);
595 self.send(&confirm_pdu(code::PAIRING_CONFIRM, our_confirm))
596 .await?;
597 let mrand = value(&self.expect(code::PAIRING_RANDOM).await?);
598 if crypto::c1(tk, mrand, &self.preq, &self.pres, iat, rat, &ia, &ra) != mconfirm {
599 return self
600 .failed(
601 reason::CONFIRM_VALUE_FAILED,
602 "the peer's confirm value is wrong",
603 )
604 .await;
605 }
606 self.send(&confirm_pdu(code::PAIRING_RANDOM, mrand_or_srand))
607 .await?;
608 (mrand, mrand_or_srand)
609 };
610 Ok(crypto::s1(tk, srand, mrand))
611 }
612
613 async fn passkey(&self, m: Method) -> Result<u32> {
615 let agent = self.host.inner.config.agent.clone();
616 let we_input = matches!(
617 (m, self.initiator),
618 (Method::PasskeyInitiatorInputs, true)
619 | (Method::PasskeyResponderInputs, false)
620 | (Method::PasskeyBothInput, _)
621 );
622 if we_input {
623 match agent.request_passkey(self.peer()).await {
624 Some(p) if p <= 999_999 => Ok(p),
625 _ => {
626 self.failed(reason::PASSKEY_ENTRY_FAILED, "no passkey entered")
627 .await
628 }
629 }
630 } else {
631 let p = match agent.request_passkey(self.peer()).await {
634 Some(p) if p <= 999_999 => p,
635 _ => {
636 let mut b = [0u8; 4];
637 crypto::random_bytes(&mut b);
638 u32::from_le_bytes(b) % 1_000_000
639 }
640 };
641 agent.display_passkey(self.peer(), p).await;
642 Ok(p)
643 }
644 }
645
646 async fn secure_connections(&mut self, m: Method) -> Result<u128> {
649 let config = &self.host.inner.config;
650 let agent = config.agent.clone();
651 let local = EcdhKey::generate();
652 let pk = |k: &EcdhKey| {
653 let mut v = vec![code::PAIRING_PUBLIC_KEY];
654 v.extend(k.x.iter().rev());
655 v.extend(k.y.iter().rev());
656 v
657 };
658 let theirs = if self.initiator {
660 self.send(&pk(&local)).await?;
661 self.expect(code::PAIRING_PUBLIC_KEY).await?
662 } else {
663 let t = self.expect(code::PAIRING_PUBLIC_KEY).await?;
664 self.send(&pk(&local)).await?;
665 t
666 };
667 if theirs.len() != 65 {
668 return self
669 .failed(reason::INVALID_PARAMETERS, "malformed public key")
670 .await;
671 }
672 let mut px = [0u8; 32];
673 let mut py = [0u8; 32];
674 px.copy_from_slice(&theirs[1..33]);
675 py.copy_from_slice(&theirs[33..65]);
676 px.reverse();
677 py.reverse();
678 if px == crypto::DEBUG_PUBLIC_X && !config.allow_debug_keys {
679 return self
680 .failed(
681 reason::AUTHENTICATION_REQUIREMENTS,
682 "the peer uses the debug key",
683 )
684 .await;
685 }
686 if px == local.x {
687 return self
689 .failed(
690 reason::INVALID_PARAMETERS,
691 "the peer sent our own public key",
692 )
693 .await;
694 }
695 let Some(dh) = local.dh_key(&px, &py) else {
696 return self
697 .failed(
698 reason::DHKEY_CHECK_FAILED,
699 "the peer's public key is not on the curve",
700 )
701 .await;
702 };
703 let (pka, pkb) = if self.initiator {
704 (local.x, px)
705 } else {
706 (px, local.x)
707 };
708
709 let (na, nb, ra, rb) = match m {
711 Method::JustWorks | Method::NumericComparison => {
712 let n = crypto::random_u128();
713 let (na, nb) = if self.initiator {
714 let cb = value(&self.expect(code::PAIRING_CONFIRM).await?);
715 self.send(&confirm_pdu(code::PAIRING_RANDOM, n)).await?;
716 let nb = value(&self.expect(code::PAIRING_RANDOM).await?);
717 if crypto::f4(&pkb, &pka, nb, 0) != cb {
718 return self
719 .failed(
720 reason::CONFIRM_VALUE_FAILED,
721 "the peer's confirm value is wrong",
722 )
723 .await;
724 }
725 (n, nb)
726 } else {
727 self.send(&confirm_pdu(
728 code::PAIRING_CONFIRM,
729 crypto::f4(&pkb, &pka, n, 0),
730 ))
731 .await?;
732 let na = value(&self.expect(code::PAIRING_RANDOM).await?);
733 self.send(&confirm_pdu(code::PAIRING_RANDOM, n)).await?;
734 (na, n)
735 };
736 if m == Method::NumericComparison {
737 let v = crypto::g2(&pka, &pkb, na, nb) % 1_000_000;
738 if !agent.confirm_number(self.peer(), v).await {
739 return self
740 .failed(
741 reason::NUMERIC_COMPARISON_FAILED,
742 "the numbers were not confirmed",
743 )
744 .await;
745 }
746 } else if !self.initiator && !agent.accept(self.peer(), m).await {
747 return self.failed(reason::PAIRING_NOT_SUPPORTED, "refused").await;
748 }
749 (na, nb, 0, 0)
750 }
751 Method::OutOfBand => {
752 let peer_oob = match agent.oob_data(self.peer()).await {
755 Some(OobData::SecureConnections { random, confirm }) => Some((random, confirm)),
756 _ => None,
757 };
758 let we_have_theirs = self.ours.oob != 0;
759 let r_peer = match (we_have_theirs, peer_oob) {
760 (true, Some((r, c))) => {
761 let peer_pk = if self.initiator { &pkb } else { &pka };
762 if crypto::f4(peer_pk, peer_pk, r, 0) != c {
763 return self
764 .failed(
765 reason::CONFIRM_VALUE_FAILED,
766 "the OOB confirm value is wrong",
767 )
768 .await;
769 }
770 r
771 }
772 (true, None) => {
773 return self.failed(reason::OOB_NOT_AVAILABLE, "no OOB data").await
774 }
775 (false, _) => 0,
776 };
777 let n = crypto::random_u128();
778 let (na, nb) = if self.initiator {
779 self.send(&confirm_pdu(code::PAIRING_RANDOM, n)).await?;
780 (n, value(&self.expect(code::PAIRING_RANDOM).await?))
781 } else {
782 let na = value(&self.expect(code::PAIRING_RANDOM).await?);
783 self.send(&confirm_pdu(code::PAIRING_RANDOM, n)).await?;
784 (na, n)
785 };
786 let (ra, rb) = if self.initiator {
788 (0, r_peer)
789 } else {
790 (r_peer, 0)
791 };
792 (na, nb, ra, rb)
793 }
794 _ => {
795 let passkey = self.passkey(m).await?;
796 let mut last = (0, 0);
797 for i in 0..20 {
798 let bit = 0x80 | ((passkey >> i) & 1) as u8;
799 let n = crypto::random_u128();
800 if self.initiator {
801 self.send(&confirm_pdu(
802 code::PAIRING_CONFIRM,
803 crypto::f4(&pka, &pkb, n, bit),
804 ))
805 .await?;
806 let cb = value(&self.expect(code::PAIRING_CONFIRM).await?);
807 self.send(&confirm_pdu(code::PAIRING_RANDOM, n)).await?;
808 let nb = value(&self.expect(code::PAIRING_RANDOM).await?);
809 if crypto::f4(&pkb, &pka, nb, bit) != cb {
810 return self
811 .failed(reason::CONFIRM_VALUE_FAILED, "passkey round failed")
812 .await;
813 }
814 last = (n, nb);
815 } else {
816 let ca = value(&self.expect(code::PAIRING_CONFIRM).await?);
817 self.send(&confirm_pdu(
818 code::PAIRING_CONFIRM,
819 crypto::f4(&pkb, &pka, n, bit),
820 ))
821 .await?;
822 let na = value(&self.expect(code::PAIRING_RANDOM).await?);
823 if crypto::f4(&pka, &pkb, na, bit) != ca {
824 return self
825 .failed(reason::CONFIRM_VALUE_FAILED, "passkey round failed")
826 .await;
827 }
828 self.send(&confirm_pdu(code::PAIRING_RANDOM, n)).await?;
829 last = (na, n);
830 }
831 }
832 let r = u128::from(passkey);
833 (last.0, last.1, r, r)
834 }
835 };
836
837 let (iat, ia, rat, ra_addr) = addresses(self.host, self.conn);
839 let a = crypto::addr56(iat, &ia);
840 let b = crypto::addr56(rat, &ra_addr);
841 let (mac_key, ltk) = crypto::f5(&dh, na, nb, &a, &b);
842 let (init, resp) = if self.initiator {
843 (self.ours, self.theirs)
844 } else {
845 (self.theirs, self.ours)
846 };
847 let io_a = [init.auth, init.oob, init.io];
848 let io_b = [resp.auth, resp.oob, resp.io];
849 let ea = crypto::f6(mac_key, na, nb, rb, &io_a, &a, &b);
850 let eb = crypto::f6(mac_key, nb, na, ra, &io_b, &b, &a);
851 if self.initiator {
852 self.send(&confirm_pdu(code::PAIRING_DHKEY_CHECK, ea))
853 .await?;
854 if value(&self.expect(code::PAIRING_DHKEY_CHECK).await?) != eb {
855 return self
856 .failed(
857 reason::DHKEY_CHECK_FAILED,
858 "the peer's DHKey check is wrong",
859 )
860 .await;
861 }
862 } else {
863 if value(&self.expect(code::PAIRING_DHKEY_CHECK).await?) != ea {
864 return self
865 .failed(
866 reason::DHKEY_CHECK_FAILED,
867 "the peer's DHKey check is wrong",
868 )
869 .await;
870 }
871 self.send(&confirm_pdu(code::PAIRING_DHKEY_CHECK, eb))
872 .await?;
873 }
874 Ok(ltk)
875 }
876
877 async fn distribute(&mut self, sc: bool, ltk: u128, security: Security) -> Result<bool> {
882 let (init, resp) = if self.initiator {
883 (self.ours, self.theirs)
884 } else {
885 (self.theirs, self.ours)
886 };
887 let (resp_keys, init_keys) = (resp.resp_keys, resp.init_keys);
889 let (ours_bits, theirs_bits) = if self.initiator {
890 (init_keys, resp_keys)
891 } else {
892 (resp_keys, init_keys)
893 };
894 let bonding = init.auth & resp.auth & AUTH_BOND != 0 && self.host.inner.config.bonding;
895 let mut bond = Bond::new(self.conn.peer);
896 bond.authenticated = security.authenticated;
897 bond.secure_connections = sc;
898 if sc {
899 bond.ltk = Some(LongTermKey {
900 key: ltk,
901 ediv: 0,
902 rand: 0,
903 key_size: security.key_size,
904 });
905 }
906 if self.initiator {
907 self.receive_keys(theirs_bits, sc, &mut bond, security)
908 .await?;
909 self.send_keys(ours_bits, sc, &mut bond, security).await?;
910 } else {
911 self.send_keys(ours_bits, sc, &mut bond, security).await?;
912 self.receive_keys(theirs_bits, sc, &mut bond, security)
913 .await?;
914 }
915 if bond.identity != self.conn.peer && !self.conn.peer.is_resolvable() {
916 bond.aliases.push(self.conn.peer);
917 }
918 self.conn.set_identity(bond.identity);
919 if bonding {
920 bond.cccd = self.host.inner.gatt.subscriptions_of(self.conn.handle);
921 self.host.inner.keys.store(bond)?;
922 }
923 Ok(bonding)
924 }
925
926 async fn send_keys(
927 &self,
928 bits: u8,
929 sc: bool,
930 bond: &mut Bond,
931 security: Security,
932 ) -> Result<()> {
933 if bits & KEY_ENC != 0 && !sc {
934 let key = mask(crypto::random_u128(), security.key_size);
935 let mut r = [0u8; 10];
936 crypto::random_bytes(&mut r);
937 let ediv = u16::from_le_bytes([r[0], r[1]]);
938 let rand = u64::from_le_bytes([r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9]]);
939 self.send(&confirm_pdu(code::ENCRYPTION_INFORMATION, key))
940 .await?;
941 let mut ci = vec![code::CENTRAL_IDENTIFICATION];
942 ci.extend_from_slice(&ediv.to_le_bytes());
943 ci.extend_from_slice(&rand.to_le_bytes());
944 self.send(&ci).await?;
945 bond.local_ltk = Some(LongTermKey {
946 key,
947 ediv,
948 rand,
949 key_size: security.key_size,
950 });
951 }
952 if bits & KEY_ID != 0 {
953 self.send(&confirm_pdu(
954 code::IDENTITY_INFORMATION,
955 self.host.inner.keys.local_irk(),
956 ))
957 .await?;
958 let me = self.host.address();
959 let mut ia = vec![code::IDENTITY_ADDRESS_INFORMATION, me.hci_type()];
960 ia.extend_from_slice(&me.bytes);
961 self.send(&ia).await?;
962 }
963 if bits & KEY_SIGN != 0 {
964 self.send(&confirm_pdu(
965 code::SIGNING_INFORMATION,
966 crypto::random_u128(),
967 ))
968 .await?;
969 }
970 Ok(())
971 }
972
973 async fn receive_keys(
974 &mut self,
975 bits: u8,
976 sc: bool,
977 bond: &mut Bond,
978 security: Security,
979 ) -> Result<()> {
980 if bits & KEY_ENC != 0 && !sc {
981 let key = value(&self.expect(code::ENCRYPTION_INFORMATION).await?);
982 let ci = self.expect(code::CENTRAL_IDENTIFICATION).await?;
983 if ci.len() != 11 {
984 return self
985 .failed(
986 reason::INVALID_PARAMETERS,
987 "malformed Central Identification",
988 )
989 .await;
990 }
991 bond.ltk = Some(LongTermKey {
992 key,
993 ediv: u16::from_le_bytes([ci[1], ci[2]]),
994 rand: u64::from_le_bytes(ci[3..11].try_into().unwrap_or([0; 8])),
995 key_size: security.key_size,
996 });
997 }
998 if bits & KEY_ID != 0 {
999 let irk = value(&self.expect(code::IDENTITY_INFORMATION).await?);
1000 let ia = self.expect(code::IDENTITY_ADDRESS_INFORMATION).await?;
1001 if ia.len() != 8 {
1002 return self
1003 .failed(
1004 reason::INVALID_PARAMETERS,
1005 "malformed Identity Address Information",
1006 )
1007 .await;
1008 }
1009 let addr = Address::from_hci(ia[1], ia[2..8].try_into().unwrap_or([0; 6]));
1010 if addr.kind == AddressType::Random
1011 && addr.random_kind() != Some(crate::address::RandomKind::Static)
1012 {
1013 return self
1014 .failed(
1015 reason::INVALID_PARAMETERS,
1016 "the identity address is not static",
1017 )
1018 .await;
1019 }
1020 bond.identity = addr;
1021 bond.irk = (irk != 0).then_some(irk);
1023 }
1024 if bits & KEY_SIGN != 0 {
1025 bond.csrk = Some(value(&self.expect(code::SIGNING_INFORMATION).await?));
1026 }
1027 Ok(())
1028 }
1029}
1030
1031fn mask(key: u128, size: u8) -> u128 {
1032 if size >= 16 {
1033 key
1034 } else {
1035 key & ((1u128 << (8 * u32::from(size))) - 1)
1036 }
1037}
1038
1039fn confirm_pdu(opcode: u8, v: u128) -> Vec<u8> {
1040 let mut p = vec![opcode];
1041 p.extend_from_slice(&crypto::le(v));
1042 p
1043}
1044
1045fn value(pdu: &[u8]) -> u128 {
1047 pdu.get(1..17)
1048 .and_then(|s| <[u8; 16]>::try_from(s).ok())
1049 .map(crypto::from_le)
1050 .unwrap_or(0)
1051}
1052
1053async fn local_features(host: &Host, peer: Address) -> Features {
1055 let c = &host.inner.config;
1056 let keys = KEY_ENC | KEY_ID;
1057 let oob = c.agent.oob_data(peer).await.is_some();
1058 Features {
1059 io: c.io_capability.wire(),
1060 oob: u8::from(oob),
1061 auth: (if c.bonding { AUTH_BOND } else { 0 })
1062 | (if c.mitm { AUTH_MITM } else { 0 })
1063 | AUTH_SC
1064 | AUTH_CT2,
1065 max_key: 16,
1066 init_keys: keys,
1067 resp_keys: keys,
1068 }
1069}
1070
1071pub(crate) async fn run(
1073 host: Host,
1074 conn: Arc<ConnState>,
1075 mut rx: mpsc::Receiver<Vec<u8>>,
1076 mut cmds: mpsc::Receiver<Command>,
1077) {
1078 loop {
1079 tokio::select! {
1080 p = rx.recv() => {
1081 let Some(pdu) = p else { return };
1082 on_idle_pdu(&host, &conn, &mut rx, pdu).await;
1083 }
1084 c = cmds.recv() => {
1085 let Some(Command::Pair(reply)) = c else { return };
1086 let r = initiate(&host, &conn, &mut rx).await;
1087 report(&host, &conn, &r);
1088 let _ = reply.send(r);
1089 }
1090 _ = conn.wait_closed() => return,
1091 }
1092 }
1093}
1094
1095fn report(host: &Host, conn: &ConnState, r: &Result<Security>) {
1096 match r {
1097 Ok(s) => host.emit(HostEvent::Paired {
1098 handle: conn.handle,
1099 identity: conn.identity(),
1100 bonded: s.bonded,
1101 security: *s,
1102 }),
1103 Err(e) => {
1104 tracing::info!("pairing on {:#05x} failed: {e}", conn.handle);
1105 host.emit(HostEvent::PairingFailed {
1106 handle: conn.handle,
1107 reason: e.to_string(),
1108 })
1109 }
1110 }
1111}
1112
1113async fn on_idle_pdu(
1116 host: &Host,
1117 conn: &Arc<ConnState>,
1118 rx: &mut mpsc::Receiver<Vec<u8>>,
1119 pdu: Vec<u8>,
1120) {
1121 match pdu.first().copied() {
1122 Some(code::PAIRING_REQUEST) if conn.role == Role::Peripheral => {
1123 let r = respond(host, conn, rx, &pdu).await;
1124 report(host, conn, &r);
1125 }
1126 Some(code::SECURITY_REQUEST) if conn.role == Role::Central => {
1127 let _one = conn.security_op.lock().await;
1128 if conn.security.borrow().encrypted {
1129 return; }
1131 let r = match encrypt_with_bond(host, conn).await {
1133 Ok(Some(s)) => Ok(s),
1134 _ => {
1135 let r = initiate(host, conn, rx).await;
1136 report(host, conn, &r);
1137 r
1138 }
1139 };
1140 if let Err(e) = r {
1141 tracing::info!("security request on {:#05x}: {e}", conn.handle);
1142 }
1143 }
1144 Some(code::PAIRING_FAILED) | Some(code::KEYPRESS_NOTIFICATION) => {}
1145 Some(_) => {
1146 let _ = conn
1147 .send(
1148 host,
1149 cid::SMP,
1150 &[code::PAIRING_FAILED, reason::COMMAND_NOT_SUPPORTED],
1151 )
1152 .await;
1153 }
1154 None => {}
1155 }
1156}
1157
1158async fn initiate(
1160 host: &Host,
1161 conn: &Arc<ConnState>,
1162 rx: &mut mpsc::Receiver<Vec<u8>>,
1163) -> Result<Security> {
1164 let ours = local_features(host, conn.identity()).await;
1165 let preq = ours.pdu(code::PAIRING_REQUEST);
1166 conn.send(host, cid::SMP, &preq).await?;
1167 let mut p = Pairing {
1168 host,
1169 conn,
1170 rx,
1171 initiator: true,
1172 preq,
1173 pres: [0; 7],
1174 ours,
1175 theirs: ours,
1176 };
1177 let rsp = p.expect(code::PAIRING_RESPONSE).await?;
1178 let Some(theirs) = Features::parse(&rsp) else {
1179 return p
1180 .failed(reason::INVALID_PARAMETERS, "malformed Pairing Response")
1181 .await;
1182 };
1183 p.pres = rsp.as_slice().try_into().unwrap_or([0; 7]);
1184 p.theirs = theirs;
1185 p.run().await
1186}
1187
1188async fn respond(
1190 host: &Host,
1191 conn: &Arc<ConnState>,
1192 rx: &mut mpsc::Receiver<Vec<u8>>,
1193 req: &[u8],
1194) -> Result<Security> {
1195 let Some(theirs) = Features::parse(req) else {
1196 let _ = conn
1197 .send(
1198 host,
1199 cid::SMP,
1200 &[code::PAIRING_FAILED, reason::INVALID_PARAMETERS],
1201 )
1202 .await;
1203 return Err(Error::Pairing("malformed Pairing Request".into()));
1204 };
1205 let mut ours = local_features(host, conn.identity()).await;
1206 ours.init_keys &= theirs.init_keys;
1208 ours.resp_keys &= theirs.resp_keys;
1209 let pres = ours.pdu(code::PAIRING_RESPONSE);
1210 let p = Pairing {
1211 host,
1212 conn,
1213 rx,
1214 initiator: false,
1215 preq: req.try_into().unwrap_or([0; 7]),
1216 pres,
1217 ours,
1218 theirs,
1219 };
1220 p.send(&pres).await?;
1221 p.run().await
1222}
1223
1224async fn encrypt_with_bond(host: &Host, conn: &Arc<ConnState>) -> Result<Option<Security>> {
1226 let Some(bond) = host.inner.keys.bond(&conn.identity()) else {
1227 return Ok(None);
1228 };
1229 let Some(ltk) = bond.ltk else { return Ok(None) };
1230 let security = Security {
1231 encrypted: true,
1232 authenticated: bond.authenticated,
1233 secure_connections: bond.secure_connections,
1234 key_size: ltk.key_size,
1235 bonded: true,
1236 };
1237 let (tx, rx) = oneshot::channel();
1238 conn.waiters().encryption = Some(tx);
1239 host.inner
1240 .hci
1241 .exec_async(&LeEnableEncryption::new(
1242 ConnHandle::new(conn.handle),
1243 ltk.rand.to_le_bytes(),
1244 ltk.ediv,
1245 crypto::le(ltk.key),
1246 ))
1247 .await?;
1248 match tokio::time::timeout(SMP_TIMEOUT, rx).await {
1249 Ok(Ok(0)) => {
1250 conn.security.send_replace(security);
1251 Ok(Some(security))
1252 }
1253 Ok(Ok(s)) => Err(Error::Pairing(format!(
1254 "encryption with the stored key failed: {}",
1255 crate::error::status_name(s)
1256 ))),
1257 Ok(Err(_)) => Err(Error::Disconnected),
1258 Err(_) => Err(Error::Timeout("encryption")),
1259 }
1260}
1261
1262pub(crate) async fn pair(c: &Connection) -> Result<Security> {
1264 match c.state.role {
1265 Role::Central => {
1266 let (tx, rx) = oneshot::channel();
1267 let _one = c.state.security_op.lock().await;
1268 c.state
1269 .smp_cmd
1270 .send(Command::Pair(tx))
1271 .await
1272 .map_err(|_| Error::Disconnected)?;
1273 rx.await.map_err(|_| Error::Disconnected)?
1274 }
1275 Role::Peripheral => {
1276 let mut events = c.host.events();
1277 let auth = local_features(&c.host, c.identity()).await.auth;
1278 c.state
1279 .send(&c.host, cid::SMP, &[code::SECURITY_REQUEST, auth])
1280 .await?;
1281 let deadline = tokio::time::Instant::now() + SMP_TIMEOUT * 2;
1282 loop {
1283 match tokio::time::timeout_at(deadline, events.recv()).await {
1284 Ok(Ok(HostEvent::Paired {
1285 handle, security, ..
1286 })) if handle == c.handle() => return Ok(security),
1287 Ok(Ok(HostEvent::PairingFailed { handle, reason })) if handle == c.handle() => {
1288 return Err(Error::Pairing(reason))
1289 }
1290 Ok(Ok(_)) | Ok(Err(tokio::sync::broadcast::error::RecvError::Lagged(_))) => {
1291 let s = c.security();
1293 if s.encrypted && s.bonded {
1294 return Ok(s);
1295 }
1296 }
1297 Ok(Err(_)) => return Err(Error::Stopped),
1298 Err(_) => return Err(Error::Timeout("the central to pair")),
1299 }
1300 }
1301 }
1302 }
1303}
1304
1305pub(crate) async fn secure(c: &Connection) -> Result<Security> {
1307 if c.security().encrypted {
1308 return Ok(c.security());
1309 }
1310 if c.state.role == Role::Central {
1311 let one = c.state.security_op.lock().await;
1312 if c.security().encrypted {
1313 return Ok(c.security());
1314 }
1315 match encrypt_with_bond(&c.host, &c.state).await {
1316 Ok(Some(s)) => return Ok(s),
1317 Ok(None) => {}
1318 Err(e) => tracing::info!("{}: {e}; pairing again", c.identity()),
1319 }
1320 drop(one);
1321 }
1322 pair(c).await
1323}
1324
1325pub(crate) fn on_ltk_request(host: &Host, handle: u16, rand: [u8; 8], ediv: u16) {
1328 let Some(conn) = host.state(handle) else {
1329 return;
1330 };
1331 let rand = u64::from_le_bytes(rand);
1332 let pairing = conn
1333 .pairing_key
1334 .lock()
1335 .unwrap_or_else(|e| e.into_inner())
1336 .take();
1337 let found: Option<(u128, Security)> = match pairing {
1338 Some(k) if ediv == 0 && rand == 0 => Some(k),
1339 _ => {
1340 let bond = if ediv == 0 && rand == 0 {
1341 host.inner
1342 .keys
1343 .bond(&conn.identity())
1344 .filter(|b| b.secure_connections)
1345 } else {
1346 host.inner.keys.by_ediv_rand(ediv, rand)
1347 };
1348 bond.and_then(|b| {
1349 let k = if b.secure_connections {
1350 b.ltk
1351 } else {
1352 b.local_ltk
1353 }?;
1354 Some((
1355 k.key,
1356 Security {
1357 encrypted: true,
1358 authenticated: b.authenticated,
1359 secure_connections: b.secure_connections,
1360 key_size: k.key_size,
1361 bonded: true,
1362 },
1363 ))
1364 })
1365 }
1366 };
1367 let host = host.clone();
1368 tokio::spawn(async move {
1369 let h = ConnHandle::new(handle);
1370 let r = match found {
1371 Some((key, security)) => {
1372 if security.bonded {
1373 let (tx, rx) = oneshot::channel();
1375 let had_waiter = {
1376 let mut w = conn.waiters();
1377 let had = w.encryption.is_some();
1378 if !had {
1379 w.encryption = Some(tx);
1380 }
1381 had
1382 };
1383 if !had_waiter {
1384 let conn = conn.clone();
1385 tokio::spawn(async move {
1386 if let Ok(Ok(0)) = tokio::time::timeout(SMP_TIMEOUT, rx).await {
1387 conn.security.send_replace(security);
1388 }
1389 });
1390 }
1391 }
1392 host.inner
1393 .hci
1394 .exec(&LeLongTermKeyRequestReply::new(h, crypto::le(key)))
1395 .await
1396 .map(|_| ())
1397 }
1398 None => host
1399 .inner
1400 .hci
1401 .exec(&LeLongTermKeyRequestNegativeReply::new(h))
1402 .await
1403 .map(|_| ()),
1404 };
1405 if let Err(e) = r {
1406 tracing::warn!("answering the LTK request on {handle:#05x}: {e}");
1407 }
1408 });
1409}
1410
1411pub(crate) type PairingKey = Mutex<Option<(u128, Security)>>;
1413
1414#[cfg(test)]
1415mod tests {
1416 use super::*;
1417 use IoCapability::*;
1418
1419 #[test]
1420 fn association_models() {
1421 assert_eq!(
1422 method(DisplayYesNo, DisplayYesNo, true),
1423 Method::NumericComparison
1424 );
1425 assert_eq!(method(DisplayYesNo, DisplayYesNo, false), Method::JustWorks);
1426 assert_eq!(
1427 method(KeyboardOnly, DisplayOnly, false),
1428 Method::PasskeyInitiatorInputs
1429 );
1430 assert_eq!(
1431 method(DisplayOnly, KeyboardOnly, true),
1432 Method::PasskeyResponderInputs
1433 );
1434 assert_eq!(
1435 method(KeyboardOnly, KeyboardOnly, true),
1436 Method::PasskeyBothInput
1437 );
1438 assert_eq!(
1439 method(KeyboardDisplay, KeyboardDisplay, false),
1440 Method::PasskeyInitiatorInputs
1441 );
1442 assert_eq!(
1443 method(KeyboardDisplay, KeyboardDisplay, true),
1444 Method::NumericComparison
1445 );
1446 assert_eq!(
1447 method(NoInputNoOutput, KeyboardDisplay, true),
1448 Method::JustWorks
1449 );
1450 }
1451
1452 #[test]
1453 fn features_and_masks() {
1454 assert!(Features::parse(&[1, 3, 0, 0x2d, 16, 3, 3]).is_some());
1455 assert!(Features::parse(&[1, 9, 0, 0x2d, 16, 3, 3]).is_none());
1456 assert!(Features::parse(&[1, 3, 0, 0x2d, 6, 3, 3]).is_none());
1457 assert_eq!(mask(u128::MAX, 7), 0x00ff_ffff_ffff_ffff);
1458 assert_eq!(mask(5, 16), 5);
1459 }
1460}