1use bluetooth_host::crypto::EcdhKey;
8
9use crate::crypto::{self, Key};
10
11pub mod pdu {
13 pub const INVITE: u8 = 0x00;
15 pub const CAPABILITIES: u8 = 0x01;
17 pub const START: u8 = 0x02;
19 pub const PUBLIC_KEY: u8 = 0x03;
21 pub const INPUT_COMPLETE: u8 = 0x04;
23 pub const CONFIRMATION: u8 = 0x05;
25 pub const RANDOM: u8 = 0x06;
27 pub const DATA: u8 = 0x07;
29 pub const COMPLETE: u8 = 0x08;
31 pub const FAILED: u8 = 0x09;
33}
34
35pub mod error {
37 pub const INVALID_PDU: u8 = 0x01;
39 pub const INVALID_FORMAT: u8 = 0x02;
41 pub const UNEXPECTED_PDU: u8 = 0x03;
43 pub const CONFIRMATION_FAILED: u8 = 0x04;
45 pub const OUT_OF_RESOURCES: u8 = 0x05;
47 pub const DECRYPTION_FAILED: u8 = 0x06;
49 pub const UNEXPECTED_ERROR: u8 = 0x07;
51 pub const CANNOT_ASSIGN_ADDRESSES: u8 = 0x08;
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct Capabilities {
58 pub elements: u8,
60 pub algorithms: u16,
62 pub public_key_oob: bool,
64 pub static_oob: bool,
66 pub output_oob: (u8, u16),
68 pub input_oob: (u8, u16),
70}
71
72impl Capabilities {
73 fn params(&self) -> [u8; 11] {
74 let a = self.algorithms.to_be_bytes();
75 let o = self.output_oob.1.to_be_bytes();
76 let i = self.input_oob.1.to_be_bytes();
77 [
78 self.elements,
79 a[0],
80 a[1],
81 u8::from(self.public_key_oob),
82 u8::from(self.static_oob),
83 self.output_oob.0,
84 o[0],
85 o[1],
86 self.input_oob.0,
87 i[0],
88 i[1],
89 ]
90 }
91
92 fn parse(p: &[u8]) -> Option<Self> {
93 let p: &[u8; 11] = p.try_into().ok()?;
94 if p[0] == 0 {
95 return None;
96 }
97 Some(Capabilities {
98 elements: p[0],
99 algorithms: u16::from_be_bytes([p[1], p[2]]),
100 public_key_oob: p[3] & 1 != 0,
101 static_oob: p[4] & 1 != 0,
102 output_oob: (p[5], u16::from_be_bytes([p[6], p[7]])),
103 input_oob: (p[8], u16::from_be_bytes([p[9], p[10]])),
104 })
105 }
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum Auth {
111 None,
113 Static(Key),
115 OutputNumeric(u8),
117 InputNumeric(u8),
119}
120
121impl Auth {
122 fn start(&self) -> [u8; 3] {
123 match self {
125 Auth::None => [0, 0, 0],
126 Auth::Static(_) => [1, 0, 0],
127 Auth::OutputNumeric(n) => [2, 3, *n],
128 Auth::InputNumeric(n) => [3, 2, *n],
129 }
130 }
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub struct ProvisioningData {
136 pub net_key: Key,
138 pub key_index: u16,
140 pub flags: u8,
142 pub iv_index: u32,
144 pub address: u16,
146}
147
148impl ProvisioningData {
149 fn bytes(&self) -> [u8; 25] {
150 let mut b = [0u8; 25];
151 b[..16].copy_from_slice(&self.net_key);
152 b[16..18].copy_from_slice(&self.key_index.to_be_bytes());
153 b[18] = self.flags;
154 b[19..23].copy_from_slice(&self.iv_index.to_be_bytes());
155 b[23..25].copy_from_slice(&self.address.to_be_bytes());
156 b
157 }
158
159 fn parse(b: &[u8]) -> Option<Self> {
160 let b: &[u8; 25] = b.try_into().ok()?;
161 let mut k = [0u8; 16];
162 k.copy_from_slice(&b[..16]);
163 let address = u16::from_be_bytes([b[23], b[24]]);
164 if address == 0 || address & 0x8000 != 0 {
165 return None;
166 }
167 Some(ProvisioningData {
168 net_key: k,
169 key_index: u16::from_be_bytes([b[16], b[17]]),
170 flags: b[18],
171 iv_index: u32::from_be_bytes([b[19], b[20], b[21], b[22]]),
172 address,
173 })
174 }
175}
176
177#[derive(Debug, Clone, PartialEq, Eq)]
179pub enum Step {
180 Send(Vec<Vec<u8>>),
182 Show(u32),
184 Done {
186 device_key: Key,
188 data: Option<ProvisioningData>,
190 },
191 Failed {
193 code: u8,
195 send: Option<Vec<u8>>,
197 },
198}
199
200fn random() -> Key {
201 let mut r = [0u8; 16];
202 bluetooth_host::crypto::random_bytes(&mut r);
203 r
204}
205
206fn auth_value(auth: &Auth, number: u32) -> Key {
207 match auth {
208 Auth::None => [0; 16],
209 Auth::Static(k) => *k,
210 Auth::OutputNumeric(_) | Auth::InputNumeric(_) => {
212 let mut v = [0u8; 16];
213 v[12..].copy_from_slice(&number.to_be_bytes());
214 v
215 }
216 }
217}
218
219fn number(digits: u8) -> u32 {
220 let mut b = [0u8; 4];
221 bluetooth_host::crypto::random_bytes(&mut b);
222 let max = 10u32.saturating_pow(u32::from(digits.clamp(1, 8)));
223 u32::from_be_bytes(b) % max
224}
225
226struct Session {
228 secret: [u8; 32],
229 confirmation_salt: Key,
230 confirmation_key: Key,
231}
232
233impl Session {
234 fn new(secret: [u8; 32], inputs: &[u8]) -> Self {
235 let confirmation_salt = crypto::s1(inputs);
236 let confirmation_key = crypto::k1(&secret, &confirmation_salt, b"prck");
237 Session {
238 secret,
239 confirmation_salt,
240 confirmation_key,
241 }
242 }
243
244 fn confirmation(&self, random: &Key, auth: &Key) -> Key {
245 let mut m = [0u8; 32];
246 m[..16].copy_from_slice(random);
247 m[16..].copy_from_slice(auth);
248 crypto::cmac(&self.confirmation_key, &m)
249 }
250
251 fn keys(&self, random_provisioner: &Key, random_device: &Key) -> (Key, [u8; 13], Key) {
253 let mut m = [0u8; 48];
254 m[..16].copy_from_slice(&self.confirmation_salt);
255 m[16..32].copy_from_slice(random_provisioner);
256 m[32..].copy_from_slice(random_device);
257 let salt = crypto::s1(&m);
258 let session_key = crypto::k1(&self.secret, &salt, b"prsk");
259 let n = crypto::k1(&self.secret, &salt, b"prsn");
260 let mut nonce = [0u8; 13];
261 nonce.copy_from_slice(&n[3..]);
262 (session_key, nonce, crypto::k1(&self.secret, &salt, b"prdk"))
263 }
264}
265
266fn public_key_pdu(k: &EcdhKey) -> Vec<u8> {
267 let mut p = vec![pdu::PUBLIC_KEY];
268 p.extend_from_slice(&k.x);
269 p.extend_from_slice(&k.y);
270 p
271}
272
273fn fail(code: u8) -> Step {
274 Step::Failed {
275 code,
276 send: Some(vec![pdu::FAILED, code]),
277 }
278}
279
280fn peer_failed(p: &[u8]) -> Option<Step> {
281 (p.first() == Some(&pdu::FAILED)).then(|| Step::Failed {
282 code: p.get(1).copied().unwrap_or(error::UNEXPECTED_ERROR),
283 send: None,
284 })
285}
286
287#[derive(PartialEq, Eq)]
288enum PState {
289 Capabilities,
290 PublicKey,
291 InputComplete,
292 Confirmation,
293 Random,
294 Complete,
295 Finished,
296}
297
298pub struct Provisioner {
300 state: PState,
301 auth: Auth,
302 data: ProvisioningData,
303 key: EcdhKey,
304 inputs: Vec<u8>,
305 session: Option<Session>,
306 random: Key,
307 number: u32,
308 device_confirmation: Key,
309 capabilities: Option<Capabilities>,
310 device_key: Option<Key>,
311}
312
313impl Provisioner {
314 pub fn start(attention_secs: u8, auth: Auth, data: ProvisioningData) -> (Self, Vec<u8>) {
316 let invite = vec![pdu::INVITE, attention_secs];
317 let p = Provisioner {
318 state: PState::Capabilities,
319 auth,
320 data,
321 key: EcdhKey::generate(),
322 inputs: invite[1..].to_vec(),
323 session: None,
324 random: random(),
325 number: 0,
326 device_confirmation: [0; 16],
327 capabilities: None,
328 device_key: None,
329 };
330 (p, invite)
331 }
332
333 pub fn capabilities(&self) -> Option<Capabilities> {
335 self.capabilities
336 }
337
338 pub fn enter_number(&mut self, n: u32) -> Option<Vec<u8>> {
340 if self.state != PState::Confirmation || !matches!(self.auth, Auth::OutputNumeric(_)) {
341 return None;
342 }
343 self.number = n;
344 self.send_confirmation()
345 }
346
347 fn send_confirmation(&mut self) -> Option<Vec<u8>> {
348 let s = self.session.as_ref()?;
349 let c = s.confirmation(&self.random, &auth_value(&self.auth, self.number));
350 let mut p = vec![pdu::CONFIRMATION];
351 p.extend_from_slice(&c);
352 self.state = PState::Confirmation;
353 Some(p)
354 }
355
356 pub fn receive(&mut self, p: &[u8]) -> Step {
358 if let Some(f) = peer_failed(p) {
359 return f;
360 }
361 let Some((&ty, body)) = p.split_first() else {
362 return fail(error::INVALID_PDU);
363 };
364 match (&self.state, ty) {
365 (PState::Capabilities, pdu::CAPABILITIES) => {
366 let Some(c) = Capabilities::parse(body) else {
367 return fail(error::INVALID_FORMAT);
368 };
369 if c.algorithms & 1 == 0 {
370 return fail(error::INVALID_FORMAT);
371 }
372 self.capabilities = Some(c);
373 let mut start = vec![pdu::START, 0x00, 0x00];
374 start.extend_from_slice(&self.auth.start());
375 self.inputs.extend_from_slice(body);
376 self.inputs.extend_from_slice(&start[1..]);
377 self.inputs.extend_from_slice(&self.key.x);
378 self.inputs.extend_from_slice(&self.key.y);
379 self.state = PState::PublicKey;
380 Step::Send(vec![start, public_key_pdu(&self.key)])
382 }
383 (PState::PublicKey, pdu::PUBLIC_KEY) => {
384 let (Ok(x), Ok(y)) = (
385 <[u8; 32]>::try_from(&body[..body.len().min(32)]),
386 <[u8; 32]>::try_from(body.get(32..64).unwrap_or(&[])),
387 ) else {
388 return fail(error::INVALID_FORMAT);
389 };
390 if body.len() != 64 {
391 return fail(error::INVALID_FORMAT);
392 }
393 let Some(secret) = self.key.dh_key(&x, &y) else {
394 return fail(error::UNEXPECTED_ERROR);
395 };
396 self.inputs.extend_from_slice(body);
397 self.session = Some(Session::new(secret, &self.inputs));
398 match self.auth {
399 Auth::InputNumeric(d) => {
400 self.number = number(d);
401 self.state = PState::InputComplete;
402 Step::Show(self.number)
403 }
404 Auth::OutputNumeric(_) => {
405 self.state = PState::Confirmation;
407 Step::Show(u32::MAX)
408 }
409 _ => match self.send_confirmation() {
410 Some(c) => Step::Send(vec![c]),
411 None => fail(error::UNEXPECTED_ERROR),
412 },
413 }
414 }
415 (PState::InputComplete, pdu::INPUT_COMPLETE) => match self.send_confirmation() {
416 Some(c) => Step::Send(vec![c]),
417 None => fail(error::UNEXPECTED_ERROR),
418 },
419 (PState::Confirmation, pdu::CONFIRMATION) if body.len() == 16 => {
420 self.device_confirmation.copy_from_slice(body);
421 self.state = PState::Random;
422 let mut r = vec![pdu::RANDOM];
423 r.extend_from_slice(&self.random);
424 Step::Send(vec![r])
425 }
426 (PState::Random, pdu::RANDOM) if body.len() == 16 => {
427 let mut device_random = [0u8; 16];
428 device_random.copy_from_slice(body);
429 let Some(s) = &self.session else {
430 return fail(error::UNEXPECTED_ERROR);
431 };
432 if s.confirmation(&device_random, &auth_value(&self.auth, self.number))
433 != self.device_confirmation
434 {
435 return fail(error::CONFIRMATION_FAILED);
436 }
437 let (session_key, nonce, device_key) = s.keys(&self.random, &device_random);
438 let enc = crypto::ccm_encrypt(&session_key, &nonce, &[], &self.data.bytes(), 8);
439 self.device_key = Some(device_key);
440 self.state = PState::Complete;
441 let mut d = vec![pdu::DATA];
442 d.extend_from_slice(&enc);
443 Step::Send(vec![d])
444 }
445 (PState::Complete, pdu::COMPLETE) => {
446 self.state = PState::Finished;
447 match self.device_key {
448 Some(k) => Step::Done {
449 device_key: k,
450 data: None,
451 },
452 None => fail(error::UNEXPECTED_ERROR),
453 }
454 }
455 _ => fail(error::UNEXPECTED_PDU),
456 }
457 }
458}
459
460#[derive(PartialEq, Eq)]
461enum DState {
462 Invite,
463 Start,
464 PublicKey,
465 Confirmation,
466 Random,
467 Data,
468 Finished,
469}
470
471pub struct Device {
474 state: DState,
475 caps: Capabilities,
476 static_oob: Option<Key>,
477 key: EcdhKey,
478 inputs: Vec<u8>,
479 auth: Auth,
480 number: u32,
481 session: Option<Session>,
482 random: Key,
483 provisioner_confirmation: Key,
484 provisioner_random: Key,
485}
486
487impl Device {
488 pub fn new(caps: Capabilities, static_oob: Option<Key>) -> Self {
490 Device {
491 state: DState::Invite,
492 caps,
493 static_oob,
494 key: EcdhKey::generate(),
495 inputs: Vec::new(),
496 auth: Auth::None,
497 number: 0,
498 session: None,
499 random: random(),
500 provisioner_confirmation: [0; 16],
501 provisioner_random: [0; 16],
502 }
503 }
504
505 pub fn enter_number(&mut self, n: u32) -> Option<Vec<u8>> {
507 if self.state != DState::Confirmation || !matches!(self.auth, Auth::InputNumeric(_)) {
508 return None;
509 }
510 self.number = n;
511 Some(vec![pdu::INPUT_COMPLETE])
512 }
513
514 pub fn receive(&mut self, p: &[u8]) -> Step {
516 if let Some(f) = peer_failed(p) {
517 return f;
518 }
519 let Some((&ty, body)) = p.split_first() else {
520 return fail(error::INVALID_PDU);
521 };
522 match (&self.state, ty) {
523 (DState::Invite, pdu::INVITE) if body.len() == 1 => {
524 self.inputs.extend_from_slice(body);
525 let caps = self.caps.params();
526 self.inputs.extend_from_slice(&caps);
527 self.state = DState::Start;
528 let mut c = vec![pdu::CAPABILITIES];
529 c.extend_from_slice(&caps);
530 Step::Send(vec![c])
531 }
532 (DState::Start, pdu::START) if body.len() == 5 => {
533 if body[0] != 0 || body[1] != 0 {
534 return fail(error::INVALID_FORMAT);
535 }
536 self.auth = match (body[2], body[4]) {
537 (0, _) => Auth::None,
538 (1, _) => match self.static_oob {
539 Some(k) => Auth::Static(k),
540 None => return fail(error::INVALID_FORMAT),
541 },
542 (2, n) => Auth::OutputNumeric(n),
543 (3, n) => Auth::InputNumeric(n),
544 _ => return fail(error::INVALID_FORMAT),
545 };
546 self.inputs.extend_from_slice(body);
547 self.state = DState::PublicKey;
548 Step::Send(Vec::new())
549 }
550 (DState::PublicKey, pdu::PUBLIC_KEY) if body.len() == 64 => {
551 let x: [u8; 32] = body[..32].try_into().unwrap_or([0; 32]);
552 let y: [u8; 32] = body[32..].try_into().unwrap_or([0; 32]);
553 if x == self.key.x {
554 return fail(error::UNEXPECTED_ERROR);
555 }
556 let Some(secret) = self.key.dh_key(&x, &y) else {
557 return fail(error::UNEXPECTED_ERROR);
558 };
559 self.inputs.extend_from_slice(body);
560 self.inputs.extend_from_slice(&self.key.x);
561 self.inputs.extend_from_slice(&self.key.y);
562 self.session = Some(Session::new(secret, &self.inputs));
563 self.state = DState::Confirmation;
564 if let Auth::OutputNumeric(d) = self.auth {
565 self.number = number(d);
566 return Step::Show(self.number);
567 }
568 Step::Send(vec![public_key_pdu(&self.key)])
569 }
570 (DState::Confirmation, pdu::CONFIRMATION) if body.len() == 16 => {
571 self.provisioner_confirmation.copy_from_slice(body);
572 let Some(s) = &self.session else {
573 return fail(error::UNEXPECTED_ERROR);
574 };
575 let c = s.confirmation(&self.random, &auth_value(&self.auth, self.number));
576 self.state = DState::Random;
577 let mut p = vec![pdu::CONFIRMATION];
578 p.extend_from_slice(&c);
579 Step::Send(vec![p])
580 }
581 (DState::Random, pdu::RANDOM) if body.len() == 16 => {
582 self.provisioner_random.copy_from_slice(body);
583 let Some(s) = &self.session else {
584 return fail(error::UNEXPECTED_ERROR);
585 };
586 if s.confirmation(
587 &self.provisioner_random,
588 &auth_value(&self.auth, self.number),
589 ) != self.provisioner_confirmation
590 {
591 return fail(error::CONFIRMATION_FAILED);
592 }
593 self.state = DState::Data;
594 let mut r = vec![pdu::RANDOM];
595 r.extend_from_slice(&self.random);
596 Step::Send(vec![r])
597 }
598 (DState::Data, pdu::DATA) if body.len() == 33 => {
599 let Some(s) = &self.session else {
600 return fail(error::UNEXPECTED_ERROR);
601 };
602 let (session_key, nonce, device_key) =
603 s.keys(&self.provisioner_random, &self.random);
604 let Some(plain) = crypto::ccm_decrypt(&session_key, &nonce, &[], body, 8) else {
605 return fail(error::DECRYPTION_FAILED);
606 };
607 let Some(data) = ProvisioningData::parse(&plain) else {
608 return fail(error::INVALID_FORMAT);
609 };
610 self.state = DState::Finished;
611 Step::Done {
612 device_key,
613 data: Some(data),
614 }
615 }
616 _ => fail(error::UNEXPECTED_PDU),
617 }
618 }
619
620 pub fn public_key(&self) -> Vec<u8> {
623 public_key_pdu(&self.key)
624 }
625}
626
627#[cfg(test)]
628mod tests {
629 use super::*;
630
631 fn caps() -> Capabilities {
632 Capabilities {
633 elements: 2,
634 algorithms: 1,
635 public_key_oob: false,
636 static_oob: true,
637 output_oob: (4, 0x0008),
638 input_oob: (4, 0x0008),
639 }
640 }
641
642 fn data() -> ProvisioningData {
643 ProvisioningData {
644 net_key: [0x7d; 16],
645 key_index: 0,
646 flags: 0,
647 iv_index: 0x1234_5678,
648 address: 0x0b0c,
649 }
650 }
651
652 fn run(
655 auth: Auth,
656 static_oob: Option<Key>,
657 tamper: bool,
658 ) -> Result<(Key, Key, ProvisioningData), u8> {
659 let (mut p, invite) = Provisioner::start(5, auth, data());
660 let mut d = Device::new(caps(), static_oob);
661 let mut to_device = vec![invite];
662 let mut shown_by_device = None;
663 let mut shown_by_provisioner = None;
664 let mut device_done = None;
665 for _ in 0..20 {
666 let Some(pdu) = to_device.pop() else { break };
667 let mut pdu = pdu;
668 if tamper && pdu.first() == Some(&pdu::RANDOM) {
669 pdu[3] ^= 1;
670 }
671 let to_provisioner = match d.receive(&pdu) {
672 Step::Send(v) if v.is_empty() => continue,
673 Step::Send(v) => v,
674 Step::Show(n) => {
675 shown_by_device = Some(n);
676 vec![d.public_key()]
677 }
678 Step::Done { device_key, data } => {
679 device_done = Some((device_key, data.unwrap()));
680 vec![vec![pdu::COMPLETE]]
681 }
682 Step::Failed { code, .. } => return Err(code),
683 };
684 for tp in to_provisioner {
685 match p.receive(&tp) {
686 Step::Send(v) => to_device.extend(v.into_iter().rev()),
687 Step::Show(u32::MAX) => {
688 let c = p.enter_number(shown_by_device.unwrap()).unwrap();
689 to_device.push(c);
690 }
691 Step::Show(n) => {
692 shown_by_provisioner = Some(n);
693 let ic = d.enter_number(n).unwrap();
694 match p.receive(&ic) {
695 Step::Send(c) => to_device.extend(c),
696 other => panic!("{other:?}"),
697 }
698 }
699 Step::Done { device_key, .. } => {
700 let (dk, dd) = device_done.unwrap();
701 let _ = shown_by_provisioner;
702 return Ok((device_key, dk, dd));
703 }
704 Step::Failed { code, .. } => return Err(code),
705 }
706 }
707 }
708 Err(0xff)
709 }
710
711 #[test]
712 fn every_auth_method_ends_with_the_same_device_key() {
713 for (auth, so) in [
714 (Auth::None, None),
715 (Auth::Static([0x5a; 16]), Some([0x5a; 16])),
716 (Auth::OutputNumeric(4), None),
717 (Auth::InputNumeric(4), None),
718 ] {
719 let (pk, dk, d) = run(auth, so, false).unwrap_or_else(|e| panic!("{auth:?}: {e}"));
720 assert_eq!(pk, dk, "{auth:?}");
721 assert_eq!(d, data());
722 }
723 }
724
725 #[test]
726 fn a_wrong_static_value_or_tampered_random_fails_confirmation() {
727 assert_eq!(
728 run(Auth::Static([1; 16]), Some([2; 16]), false),
729 Err(error::CONFIRMATION_FAILED)
730 );
731 assert_eq!(run(Auth::None, None, true), Err(error::CONFIRMATION_FAILED));
732 }
733
734 #[test]
735 fn malformed_pdus_fail_cleanly() {
736 let (mut p, _) = Provisioner::start(0, Auth::None, data());
737 assert!(matches!(
738 p.receive(&[pdu::CAPABILITIES, 1, 2]),
739 Step::Failed {
740 code: error::INVALID_FORMAT,
741 ..
742 }
743 ));
744 assert!(matches!(p.receive(&[]), Step::Failed { .. }));
745 let mut d = Device::new(caps(), None);
746 assert!(matches!(
747 d.receive(&[pdu::DATA; 34]),
748 Step::Failed {
749 code: error::UNEXPECTED_PDU,
750 ..
751 }
752 ));
753 }
754}