1use crate::ckdf::{mei, network_keys, nonce_prk, DerivedKeys};
18use crate::crypto::{aes128_ecb, ccm_decrypt, ccm_encrypt, increment, CCM_TAG_LEN};
19use crate::drbg::CtrDrbg;
20use crate::{random_bytes, Error, NetworkKey, SecurityClass};
21use std::collections::{BTreeMap, HashMap};
22
23pub const CC_SECURITY_2: u8 = 0x9f;
25
26pub mod cmd {
28 pub const NONCE_GET: u8 = 0x01;
30 pub const NONCE_REPORT: u8 = 0x02;
32 pub const MESSAGE_ENCAPSULATION: u8 = 0x03;
34 pub const KEX_GET: u8 = 0x04;
36 pub const KEX_REPORT: u8 = 0x05;
38 pub const KEX_SET: u8 = 0x06;
40 pub const KEX_FAIL: u8 = 0x07;
42 pub const PUBLIC_KEY_REPORT: u8 = 0x08;
44 pub const NETWORK_KEY_GET: u8 = 0x09;
46 pub const NETWORK_KEY_REPORT: u8 = 0x0a;
48 pub const NETWORK_KEY_VERIFY: u8 = 0x0b;
50 pub const TRANSFER_END: u8 = 0x0c;
52 pub const COMMANDS_SUPPORTED_GET: u8 = 0x0d;
54 pub const COMMANDS_SUPPORTED_REPORT: u8 = 0x0e;
56}
57
58pub const MAX_DECRYPT_ATTEMPTS: usize = 5;
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub enum KeyId {
64 Temporary,
66 Class(SecurityClass),
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
72pub enum Extension {
73 Span {
75 sender_ei: [u8; 16],
77 },
78 Mpan {
80 group: u8,
82 inner_state: [u8; 16],
84 },
85 Mgrp {
87 group: u8,
89 },
90 Mos,
92 Unknown {
94 kind: u8,
96 data: Vec<u8>,
98 },
99}
100
101impl Extension {
102 fn kind(&self) -> u8 {
103 match self {
104 Extension::Span { .. } => 0x01,
105 Extension::Mpan { .. } => 0x02,
106 Extension::Mgrp { .. } => 0x03,
107 Extension::Mos => 0x04,
108 Extension::Unknown { kind, .. } => *kind,
109 }
110 }
111
112 fn critical(&self) -> bool {
113 matches!(
114 self,
115 Extension::Span { .. } | Extension::Mpan { .. } | Extension::Mgrp { .. }
116 )
117 }
118
119 fn is_encrypted(&self) -> bool {
120 matches!(self, Extension::Mpan { .. })
121 }
122
123 fn encode(&self, more: bool, out: &mut Vec<u8>) {
124 let payload: Vec<u8> = match self {
125 Extension::Span { sender_ei } => sender_ei.to_vec(),
126 Extension::Mpan { group, inner_state } => {
127 let mut v = vec![*group];
128 v.extend_from_slice(inner_state);
129 v
130 }
131 Extension::Mgrp { group } => vec![*group],
132 Extension::Mos => vec![],
133 Extension::Unknown { data, .. } => data.clone(),
134 };
135 out.push((2 + payload.len()) as u8);
136 out.push(
137 if more { 0x80 } else { 0 }
138 | if self.critical() { 0x40 } else { 0 }
139 | (self.kind() & 0x3f),
140 );
141 out.extend_from_slice(&payload);
142 }
143}
144
145fn parse_extensions(data: &[u8]) -> Result<(Vec<Extension>, usize), Error> {
147 let mut exts = Vec::new();
148 let mut at = 0;
149 loop {
150 let len = *data.get(at).ok_or(Error::Malformed("extension length"))? as usize;
151 let head = *data
152 .get(at + 1)
153 .ok_or(Error::Malformed("extension header"))?;
154 if len < 2 || at + len > data.len() {
155 return Err(Error::Malformed("extension length"));
156 }
157 let body = &data[at + 2..at + len];
158 let more = head & 0x80 != 0;
159 let critical = head & 0x40 != 0;
160 let kind = head & 0x3f;
161 let ext = match (kind, body.len()) {
162 (0x01, 16) => Extension::Span {
163 sender_ei: body.try_into().expect("16 bytes"),
164 },
165 (0x02, 17) => Extension::Mpan {
166 group: body[0],
167 inner_state: body[1..].try_into().expect("16 bytes"),
168 },
169 (0x03, 1) => Extension::Mgrp { group: body[0] },
170 (0x04, 0) => Extension::Mos,
171 (0x01..=0x04, _) => return Err(Error::Malformed("extension size")),
172 _ if critical => return Err(Error::UnsupportedExtension(kind)),
173 _ => Extension::Unknown {
174 kind,
175 data: body.to_vec(),
176 },
177 };
178 exts.push(ext);
179 at += len;
180 if !more {
181 return Ok((exts, at));
182 }
183 }
184}
185
186fn encode_extensions(exts: &[&Extension], out: &mut Vec<u8>) {
187 for (i, e) in exts.iter().enumerate() {
188 e.encode(i + 1 < exts.len(), out);
189 }
190}
191
192#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct Encapsulation {
195 pub sequence: u8,
197 pub extensions: Vec<Extension>,
199 pub encrypted_extensions: bool,
201 header_len: usize,
203}
204
205impl Encapsulation {
206 pub fn parse(frame: &[u8]) -> Result<Self, Error> {
208 if frame.len() < 4 + CCM_TAG_LEN
209 || frame[0] != CC_SECURITY_2
210 || frame[1] != cmd::MESSAGE_ENCAPSULATION
211 {
212 return Err(Error::Malformed("not an S2 encapsulation"));
213 }
214 let sequence = frame[2];
215 let flags = frame[3];
216 let (extensions, used) = if flags & 0x01 != 0 {
217 parse_extensions(&frame[4..])?
218 } else {
219 (Vec::new(), 0)
220 };
221 let header_len = 2 + used;
222 if 2 + header_len + CCM_TAG_LEN > frame.len() {
223 return Err(Error::Malformed("S2 encapsulation too short"));
224 }
225 Ok(Encapsulation {
226 sequence,
227 extensions,
228 encrypted_extensions: flags & 0x02 != 0,
229 header_len,
230 })
231 }
232
233 pub fn sender_ei(&self) -> Option<[u8; 16]> {
235 self.extensions.iter().find_map(|e| match e {
236 Extension::Span { sender_ei } => Some(*sender_ei),
237 _ => None,
238 })
239 }
240
241 pub fn multicast_group(&self) -> Option<u8> {
243 self.extensions.iter().find_map(|e| match e {
244 Extension::Mgrp { group } => Some(*group),
245 _ => None,
246 })
247 }
248}
249
250fn node_bytes(id: u16, long: bool, out: &mut Vec<u8>) {
251 if long {
252 out.extend_from_slice(&id.to_be_bytes());
253 } else {
254 out.push(id as u8);
255 }
256}
257
258fn aad(sender: u16, dest: u16, home_id: u32, total_len: usize, header: &[u8]) -> Vec<u8> {
259 let long = sender > 0xff || dest > 0xff;
260 let mut a = Vec::with_capacity(10 + header.len());
261 node_bytes(sender, long, &mut a);
262 node_bytes(dest, long, &mut a);
263 a.extend_from_slice(&home_id.to_be_bytes());
264 a.extend_from_slice(&(total_len as u16).to_be_bytes());
265 a.extend_from_slice(header);
266 a
267}
268
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub struct NonceReport {
272 pub sos: bool,
274 pub mos: bool,
276}
277
278#[derive(Debug, Clone, PartialEq, Eq)]
280pub struct Decrypted {
281 pub command: Vec<u8>,
283 pub key: KeyId,
285 pub sequence: u8,
287 pub extensions: Vec<Extension>,
289}
290
291impl Decrypted {
292 pub fn wants_mpan(&self) -> bool {
294 self.extensions.contains(&Extension::Mos)
295 }
296}
297
298enum Span {
299 LocalEi([u8; 16]),
301 RemoteEi([u8; 16]),
303 Established { key: KeyId, drbg: CtrDrbg },
305}
306
307#[derive(Debug, Clone, Default)]
309pub struct EncryptOptions {
310 pub key: Option<KeyId>,
312 pub follow_up_group: Option<u8>,
314 pub send_mpan: Option<u8>,
316 pub mos: bool,
318}
319
320pub struct S2Manager {
322 own_node: u16,
323 home_id: u32,
324 keys: BTreeMap<SecurityClass, DerivedKeys>,
325 temp: HashMap<u16, DerivedKeys>,
326 spans: HashMap<u16, Span>,
327 peer_classes: HashMap<u16, Vec<SecurityClass>>,
328 tx_seq: HashMap<u16, u8>,
329 rx_seq: HashMap<u16, u8>,
330 groups: HashMap<u8, (SecurityClass, [u8; 16])>,
331 peer_mpans: HashMap<(u16, u8), [u8; 16]>,
332}
333
334impl std::fmt::Debug for S2Manager {
335 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
336 f.debug_struct("S2Manager")
337 .field("own_node", &self.own_node)
338 .field("home_id", &format_args!("{:08x}", self.home_id))
339 .field("classes", &self.keys.keys().collect::<Vec<_>>())
340 .finish()
341 }
342}
343
344impl S2Manager {
345 pub fn new(own_node: u16, home_id: u32) -> Self {
347 S2Manager {
348 own_node,
349 home_id,
350 keys: BTreeMap::new(),
351 temp: HashMap::new(),
352 spans: HashMap::new(),
353 peer_classes: HashMap::new(),
354 tx_seq: HashMap::new(),
355 rx_seq: HashMap::new(),
356 groups: HashMap::new(),
357 peer_mpans: HashMap::new(),
358 }
359 }
360
361 pub fn set_home(&mut self, own_node: u16, home_id: u32) {
364 self.own_node = own_node;
365 self.home_id = home_id;
366 self.spans.clear();
367 self.groups.clear();
368 self.peer_mpans.clear();
369 }
370
371 pub fn own_node(&self) -> u16 {
373 self.own_node
374 }
375
376 pub fn home_id(&self) -> u32 {
378 self.home_id
379 }
380
381 pub fn set_network_key(&mut self, class: SecurityClass, key: &NetworkKey) {
383 self.keys.insert(class, network_keys(key));
384 }
385
386 pub fn has_key(&self, class: SecurityClass) -> bool {
388 self.keys.contains_key(&class)
389 }
390
391 pub fn set_peer_classes(&mut self, peer: u16, classes: &[SecurityClass]) {
393 let mut c: Vec<SecurityClass> = classes
394 .iter()
395 .copied()
396 .filter(|c| c.is_s2() || *c == SecurityClass::S0Legacy)
397 .collect();
398 c.sort_by(|a, b| b.cmp(a));
399 c.dedup();
400 self.peer_classes.insert(peer, c);
401 }
402
403 pub fn highest_class(&self, peer: u16) -> Option<SecurityClass> {
405 self.peer_classes
406 .get(&peer)?
407 .iter()
408 .copied()
409 .find(|c| c.is_s2() && self.keys.contains_key(c))
410 }
411
412 pub fn forget_peer(&mut self, peer: u16) {
414 self.temp.remove(&peer);
415 self.spans.remove(&peer);
416 self.peer_classes.remove(&peer);
417 self.tx_seq.remove(&peer);
418 self.rx_seq.remove(&peer);
419 self.peer_mpans.retain(|(p, _), _| *p != peer);
420 }
421
422 pub fn begin_bootstrap(&mut self, peer: u16, temp: DerivedKeys) {
424 self.temp.insert(peer, temp);
425 self.spans.remove(&peer);
426 }
427
428 pub fn end_bootstrap(&mut self, peer: u16) {
430 self.temp.remove(&peer);
431 self.spans.remove(&peer);
432 }
433
434 pub fn is_bootstrapping(&self, peer: u16) -> bool {
436 self.temp.contains_key(&peer)
437 }
438
439 pub fn reset_span(&mut self, peer: u16) {
441 self.spans.remove(&peer);
442 }
443
444 pub fn can_encrypt(&self, peer: u16) -> bool {
446 match self.spans.get(&peer) {
447 Some(Span::RemoteEi(_)) => true,
448 Some(Span::Established { key, .. }) => self.default_key(peer) == Some(*key),
449 _ => false,
450 }
451 }
452
453 fn default_key(&self, peer: u16) -> Option<KeyId> {
454 if self.temp.contains_key(&peer) {
455 Some(KeyId::Temporary)
456 } else {
457 self.highest_class(peer).map(KeyId::Class)
458 }
459 }
460
461 fn keys_for(&self, peer: u16, key: KeyId) -> Result<&DerivedKeys, Error> {
462 match key {
463 KeyId::Temporary => self
464 .temp
465 .get(&peer)
466 .ok_or(Error::NoKey(SecurityClass::S2Unauthenticated)),
467 KeyId::Class(c) => self.keys.get(&c).ok_or(Error::NoKey(c)),
468 }
469 }
470
471 fn next_sequence(&mut self, peer: u16) -> Result<u8, Error> {
472 let seq = match self.tx_seq.get(&peer) {
473 Some(s) => s.wrapping_add(1),
474 None => random_bytes::<1>()?[0],
475 };
476 self.tx_seq.insert(peer, seq);
477 Ok(seq)
478 }
479
480 pub fn nonce_get(&mut self, peer: u16) -> Result<Vec<u8>, Error> {
482 let seq = self.next_sequence(peer)?;
483 Ok(vec![CC_SECURITY_2, cmd::NONCE_GET, seq])
484 }
485
486 pub fn nonce_report(&mut self, peer: u16, mos: bool) -> Result<Vec<u8>, Error> {
489 let seq = self.next_sequence(peer)?;
490 let rei = random_bytes::<16>()?;
491 self.spans.insert(peer, Span::LocalEi(rei));
492 let mut v = vec![
493 CC_SECURITY_2,
494 cmd::NONCE_REPORT,
495 seq,
496 0x01 | if mos { 0x02 } else { 0 },
497 ];
498 v.extend_from_slice(&rei);
499 Ok(v)
500 }
501
502 pub fn nonce_report_mos(&mut self, peer: u16) -> Result<Vec<u8>, Error> {
504 let seq = self.next_sequence(peer)?;
505 Ok(vec![CC_SECURITY_2, cmd::NONCE_REPORT, seq, 0x02])
506 }
507
508 pub fn handle_nonce_report(&mut self, peer: u16, frame: &[u8]) -> Result<NonceReport, Error> {
510 if frame.len() < 4 || frame[0] != CC_SECURITY_2 || frame[1] != cmd::NONCE_REPORT {
511 return Err(Error::Malformed("not a nonce report"));
512 }
513 let flags = frame[3];
514 let sos = flags & 0x01 != 0;
515 let mos = flags & 0x02 != 0;
516 if sos {
517 let rei: [u8; 16] = frame
518 .get(4..20)
519 .ok_or(Error::Malformed("nonce report without REI"))?
520 .try_into()
521 .expect("16 bytes");
522 self.spans.insert(peer, Span::RemoteEi(rei));
523 }
524 Ok(NonceReport { sos, mos })
525 }
526
527 fn span_drbg(
528 &self,
529 peer: u16,
530 key: KeyId,
531 sei: &[u8; 16],
532 rei: &[u8; 16],
533 ) -> Result<CtrDrbg, Error> {
534 let keys = self.keys_for(peer, key)?;
535 Ok(CtrDrbg::new(
536 &mei(&nonce_prk(sei, rei)),
537 &keys.personalization,
538 ))
539 }
540
541 pub fn encrypt(
547 &mut self,
548 peer: u16,
549 command: &[u8],
550 opts: &EncryptOptions,
551 ) -> Result<Vec<u8>, Error> {
552 let key = match opts.key {
553 Some(k) => k,
554 None => self
555 .default_key(peer)
556 .ok_or(Error::NoKey(SecurityClass::S2Unauthenticated))?,
557 };
558 let keys = self.keys_for(peer, key)?.clone();
559 let mut unencrypted: Vec<Extension> = Vec::new();
560 let nonce = match self.spans.remove(&peer) {
561 Some(Span::Established { key: k, mut drbg }) if k == key => {
562 let n = drbg.next_nonce();
563 self.spans.insert(peer, Span::Established { key, drbg });
564 n
565 }
566 Some(Span::RemoteEi(rei)) => {
567 let sei = random_bytes::<16>()?;
568 let mut drbg = self.span_drbg(peer, key, &sei, &rei)?;
569 let n = drbg.next_nonce();
570 self.spans.insert(peer, Span::Established { key, drbg });
571 unencrypted.push(Extension::Span { sender_ei: sei });
572 n
573 }
574 other => {
575 if let Some(s) = other {
576 self.spans.insert(peer, s);
577 }
578 return Err(Error::NoSpan);
579 }
580 };
581 if let Some(group) = opts.follow_up_group {
582 unencrypted.push(Extension::Mgrp { group });
583 }
584 if opts.mos {
585 unencrypted.push(Extension::Mos);
586 }
587 let mut encrypted: Vec<Extension> = Vec::new();
588 if let Some(group) = opts.send_mpan {
589 let (_, state) = self
590 .groups
591 .get(&group)
592 .ok_or(Error::Malformed("unknown multicast group"))?;
593 encrypted.push(Extension::Mpan {
594 group,
595 inner_state: *state,
596 });
597 }
598 let seq = self.next_sequence(peer)?;
599 self.seal(
600 peer,
601 seq,
602 &unencrypted,
603 &encrypted,
604 command,
605 &keys.key_ccm,
606 &nonce,
607 )
608 }
609
610 #[allow(clippy::too_many_arguments)]
611 fn seal(
612 &self,
613 dest: u16,
614 seq: u8,
615 unencrypted: &[Extension],
616 encrypted: &[Extension],
617 command: &[u8],
618 key: &[u8; 16],
619 nonce: &[u8; 13],
620 ) -> Result<Vec<u8>, Error> {
621 let mut header = vec![seq, 0];
622 if !unencrypted.is_empty() {
623 header[1] |= 0x01;
624 encode_extensions(&unencrypted.iter().collect::<Vec<_>>(), &mut header);
625 }
626 let mut plain = Vec::with_capacity(command.len() + 20);
627 if !encrypted.is_empty() {
628 header[1] |= 0x02;
629 encode_extensions(&encrypted.iter().collect::<Vec<_>>(), &mut plain);
630 }
631 plain.extend_from_slice(command);
632 let total = 2 + header.len() + plain.len() + CCM_TAG_LEN;
633 let a = aad(self.own_node, dest, self.home_id, total, &header);
634 let ct = ccm_encrypt(key, nonce, &a, &plain);
635 let mut out = Vec::with_capacity(total);
636 out.extend_from_slice(&[CC_SECURITY_2, cmd::MESSAGE_ENCAPSULATION]);
637 out.extend_from_slice(&header);
638 out.extend_from_slice(&ct);
639 Ok(out)
640 }
641
642 fn candidates(&self, peer: u16) -> Vec<KeyId> {
643 let mut c = Vec::new();
644 if self.temp.contains_key(&peer) {
645 c.push(KeyId::Temporary);
646 }
647 match self.peer_classes.get(&peer) {
648 Some(classes) if !classes.is_empty() => c.extend(
649 classes
650 .iter()
651 .filter(|k| self.keys.contains_key(k))
652 .map(|k| KeyId::Class(*k)),
653 ),
654 _ => c.extend(self.keys.keys().rev().map(|k| KeyId::Class(*k))),
656 }
657 c
658 }
659
660 fn open(
661 &self,
662 frame: &[u8],
663 enc: &Encapsulation,
664 sender: u16,
665 dest: u16,
666 key: &[u8; 16],
667 nonce: &[u8; 13],
668 ) -> Option<Vec<u8>> {
669 let a = aad(
670 sender,
671 dest,
672 self.home_id,
673 frame.len(),
674 &frame[2..2 + enc.header_len],
675 );
676 ccm_decrypt(key, nonce, &a, &frame[2 + enc.header_len..])
677 }
678
679 pub fn decrypt(&mut self, peer: u16, frame: &[u8]) -> Result<Decrypted, Error> {
684 let enc = Encapsulation::parse(frame)?;
685 if self.rx_seq.get(&peer) == Some(&enc.sequence) {
686 return Err(Error::Duplicate);
687 }
688 let own = self.own_node;
689 let (key, plain) = match (self.spans.remove(&peer), enc.sender_ei()) {
690 (Some(Span::LocalEi(rei)), Some(sei)) => {
691 let mut found = None;
692 for key in self.candidates(peer) {
693 let keys = self.keys_for(peer, key)?;
694 let mut drbg =
695 CtrDrbg::new(&mei(&nonce_prk(&sei, &rei)), &keys.personalization);
696 let nonce = drbg.next_nonce();
697 if let Some(p) = self.open(frame, &enc, peer, own, &keys.key_ccm, &nonce) {
698 found = Some((key, drbg, p));
699 break;
700 }
701 }
702 let (key, drbg, p) = found.ok_or(Error::DecryptFailed)?;
703 self.spans.insert(peer, Span::Established { key, drbg });
704 (key, p)
705 }
706 (Some(Span::Established { key, mut drbg }), None) => {
707 let ccm = self.keys_for(peer, key)?.key_ccm;
708 let mut plain = None;
709 for _ in 0..MAX_DECRYPT_ATTEMPTS {
710 let nonce = drbg.next_nonce();
711 if let Some(p) = self.open(frame, &enc, peer, own, &ccm, &nonce) {
712 plain = Some(p);
713 break;
714 }
715 }
716 let p = plain.ok_or(Error::DecryptFailed)?;
717 self.spans.insert(peer, Span::Established { key, drbg });
718 (key, p)
719 }
720 (Some(s @ Span::LocalEi(_)), None) => {
721 self.spans.insert(peer, s);
723 return Err(Error::NoSpan);
724 }
725 (Some(Span::RemoteEi(rei)), _) => {
726 self.spans.insert(peer, Span::RemoteEi(rei));
728 return Err(Error::NoSpan);
729 }
730 _ => return Err(Error::NoSpan),
731 };
732 self.rx_seq.insert(peer, enc.sequence);
733 let mut extensions = enc.extensions.clone();
734 let command = if enc.encrypted_extensions {
735 let (exts, used) = parse_extensions(&plain)?;
736 for e in &exts {
737 if let (Extension::Mpan { group, inner_state }, true) = (e, e.is_encrypted()) {
738 self.peer_mpans.insert((peer, *group), *inner_state);
739 }
740 }
741 extensions.extend(exts);
742 plain[used..].to_vec()
743 } else {
744 plain
745 };
746 if command.is_empty() {
747 return Err(Error::Malformed("empty encapsulated command"));
748 }
749 Ok(Decrypted {
750 command,
751 key,
752 sequence: enc.sequence,
753 extensions,
754 })
755 }
756
757 pub fn create_group(&mut self, group: u8, class: SecurityClass) -> Result<(), Error> {
759 if !self.keys.contains_key(&class) {
760 return Err(Error::NoKey(class));
761 }
762 self.groups.insert(group, (class, random_bytes::<16>()?));
763 Ok(())
764 }
765
766 pub fn encrypt_multicast(&mut self, group: u8, command: &[u8]) -> Result<Vec<u8>, Error> {
768 let (class, state) = self
769 .groups
770 .get_mut(&group)
771 .ok_or(Error::Malformed("unknown multicast group"))?;
772 let class = *class;
773 let keys = self.keys.get(&class).ok_or(Error::NoKey(class))?;
774 let mut nonce = [0u8; 13];
775 nonce.copy_from_slice(&aes128_ecb(&keys.key_mpan, state)[..13]);
776 increment(state);
777 let key = keys.key_ccm;
778 let seq = self.next_sequence(0xff00 | u16::from(group))?;
780 self.seal(
781 u16::from(group),
782 seq,
783 &[Extension::Mgrp { group }],
784 &[],
785 command,
786 &key,
787 &nonce,
788 )
789 }
790
791 pub fn decrypt_multicast(&mut self, peer: u16, frame: &[u8]) -> Result<Decrypted, Error> {
796 let enc = Encapsulation::parse(frame)?;
797 let group = enc
798 .multicast_group()
799 .ok_or(Error::Malformed("multicast without MGRP"))?;
800 let mut state = *self.peer_mpans.get(&(peer, group)).ok_or(Error::NoSpan)?;
801 let class = self.highest_class(peer).ok_or(Error::NoSpan)?;
802 let keys = self.keys.get(&class).ok_or(Error::NoKey(class))?;
803 let (mpan_key, ccm) = (keys.key_mpan, keys.key_ccm);
804 for _ in 0..MAX_DECRYPT_ATTEMPTS {
805 let mut nonce = [0u8; 13];
806 nonce.copy_from_slice(&aes128_ecb(&mpan_key, &state)[..13]);
807 increment(&mut state);
808 if let Some(p) = self.open(frame, &enc, peer, u16::from(group), &ccm, &nonce) {
809 self.peer_mpans.insert((peer, group), state);
810 return Ok(Decrypted {
811 command: p,
812 key: KeyId::Class(class),
813 sequence: enc.sequence,
814 extensions: enc.extensions,
815 });
816 }
817 }
818 self.peer_mpans.remove(&(peer, group));
819 Err(Error::DecryptFailed)
820 }
821}
822
823#[cfg(test)]
824mod tests {
825 use super::*;
826 use crate::kex::{bootstrap_keys, KeyPair};
827
828 const HOME: u32 = 0xc0ff_ee01;
829
830 fn pair() -> (S2Manager, S2Manager) {
831 let mut ctrl = S2Manager::new(1, HOME);
832 let mut node = S2Manager::new(5, HOME);
833 let key = [0x42u8; 16];
834 ctrl.set_network_key(SecurityClass::S2Authenticated, &key);
835 node.set_network_key(SecurityClass::S2Authenticated, &key);
836 ctrl.set_peer_classes(5, &[SecurityClass::S2Authenticated]);
837 node.set_peer_classes(1, &[SecurityClass::S2Authenticated]);
838 (ctrl, node)
839 }
840
841 fn sync(a: &mut S2Manager, a_id: u16, b: &mut S2Manager, b_id: u16) {
843 let _get = a.nonce_get(b_id).unwrap();
844 let report = b.nonce_report(a_id, false).unwrap();
845 assert!(a.handle_nonce_report(b_id, &report).unwrap().sos);
846 }
847
848 #[test]
849 fn span_roundtrip_both_directions() {
850 let (mut c, mut n) = pair();
851 assert_eq!(
852 c.encrypt(5, &[0x31, 0x04], &EncryptOptions::default()),
853 Err(Error::NoSpan)
854 );
855 sync(&mut c, 1, &mut n, 5);
856 let f1 = c
857 .encrypt(5, &[0x31, 0x04], &EncryptOptions::default())
858 .unwrap();
859 assert!(Encapsulation::parse(&f1).unwrap().sender_ei().is_some());
860 let d = n.decrypt(1, &f1).unwrap();
861 assert_eq!(d.command, vec![0x31, 0x04]);
862 assert_eq!(d.key, KeyId::Class(SecurityClass::S2Authenticated));
863 let f2 = n
865 .encrypt(
866 1,
867 &[0x31, 0x05, 0x01, 0x22, 0x00, 0xd2],
868 &EncryptOptions::default(),
869 )
870 .unwrap();
871 assert!(Encapsulation::parse(&f2).unwrap().extensions.is_empty());
872 assert_eq!(
873 c.decrypt(5, &f2).unwrap().command,
874 vec![0x31, 0x05, 0x01, 0x22, 0x00, 0xd2]
875 );
876 let f3 = c
877 .encrypt(5, &[0x25, 0x01, 0xff], &EncryptOptions::default())
878 .unwrap();
879 assert_eq!(n.decrypt(1, &f3).unwrap().command, vec![0x25, 0x01, 0xff]);
880 assert_eq!(n.decrypt(1, &f3), Err(Error::Duplicate));
882 }
883
884 #[test]
885 fn receiver_skips_lost_frames() {
886 let (mut c, mut n) = pair();
887 sync(&mut c, 1, &mut n, 5);
888 let f1 = c
889 .encrypt(5, &[0x20, 0x02], &EncryptOptions::default())
890 .unwrap();
891 n.decrypt(1, &f1).unwrap();
892 let _lost = c
893 .encrypt(5, &[0x20, 0x02], &EncryptOptions::default())
894 .unwrap();
895 let f3 = c
896 .encrypt(5, &[0x20, 0x01, 0x10], &EncryptOptions::default())
897 .unwrap();
898 assert_eq!(n.decrypt(1, &f3).unwrap().command, vec![0x20, 0x01, 0x10]);
899 }
900
901 #[test]
902 fn tampering_and_wrong_key_fail() {
903 let (mut c, mut n) = pair();
904 sync(&mut c, 1, &mut n, 5);
905 let mut f = c
906 .encrypt(5, &[0x20, 0x02], &EncryptOptions::default())
907 .unwrap();
908 let last = f.len() - 1;
909 f[last] ^= 0x01;
910 assert_eq!(n.decrypt(1, &f), Err(Error::DecryptFailed));
911 let report = n.nonce_report(1, false).unwrap();
913 c.handle_nonce_report(5, &report).unwrap();
914 let f = c
915 .encrypt(5, &[0x20, 0x02], &EncryptOptions::default())
916 .unwrap();
917 assert_eq!(n.decrypt(1, &f).unwrap().command, vec![0x20, 0x02]);
918
919 let mut other = S2Manager::new(5, HOME);
920 other.set_network_key(SecurityClass::S2Authenticated, &[0x43; 16]);
921 other.set_peer_classes(1, &[SecurityClass::S2Authenticated]);
922 sync(&mut c, 1, &mut other, 5);
923 let f = c
924 .encrypt(5, &[0x20, 0x02], &EncryptOptions::default())
925 .unwrap();
926 assert_eq!(other.decrypt(1, &f), Err(Error::DecryptFailed));
927 }
928
929 #[test]
930 fn home_id_and_node_ids_are_authenticated() {
931 let (mut c, _) = pair();
932 let mut n = S2Manager::new(5, HOME ^ 1);
933 n.set_network_key(SecurityClass::S2Authenticated, &[0x42; 16]);
934 n.set_peer_classes(1, &[SecurityClass::S2Authenticated]);
935 sync(&mut c, 1, &mut n, 5);
936 let f = c
937 .encrypt(5, &[0x20, 0x02], &EncryptOptions::default())
938 .unwrap();
939 assert_eq!(n.decrypt(1, &f), Err(Error::DecryptFailed));
940 }
941
942 #[test]
943 fn unknown_peer_class_tries_every_key() {
944 let (mut c, _) = pair();
945 let mut n = S2Manager::new(5, HOME);
946 n.set_network_key(SecurityClass::S2Unauthenticated, &[0x11; 16]);
947 n.set_network_key(SecurityClass::S2Authenticated, &[0x42; 16]);
948 sync(&mut c, 1, &mut n, 5);
949 let f = c
950 .encrypt(5, &[0x20, 0x02], &EncryptOptions::default())
951 .unwrap();
952 assert_eq!(
953 n.decrypt(1, &f).unwrap().key,
954 KeyId::Class(SecurityClass::S2Authenticated)
955 );
956 }
957
958 #[test]
959 fn bootstrap_with_temporary_key() {
960 let ckp = KeyPair::generate().unwrap();
961 let nkp = KeyPair::generate().unwrap();
962 let mut c = S2Manager::new(1, HOME);
963 let mut n = S2Manager::new(5, HOME);
964 c.begin_bootstrap(
965 5,
966 bootstrap_keys(
967 &ckp.shared_secret(nkp.public()).unwrap(),
968 ckp.public(),
969 nkp.public(),
970 ),
971 );
972 n.begin_bootstrap(
973 1,
974 bootstrap_keys(
975 &nkp.shared_secret(ckp.public()).unwrap(),
976 ckp.public(),
977 nkp.public(),
978 ),
979 );
980 sync(&mut n, 5, &mut c, 1);
981 let f = n
982 .encrypt(
983 1,
984 &[0x9f, 0x06, 0x01, 0x02, 0x01, 0x02],
985 &EncryptOptions::default(),
986 )
987 .unwrap();
988 let d = c.decrypt(5, &f).unwrap();
989 assert_eq!(d.key, KeyId::Temporary);
990 assert_eq!(d.command, vec![0x9f, 0x06, 0x01, 0x02, 0x01, 0x02]);
991 }
992
993 #[test]
994 fn mpan_multicast() {
995 let (mut c, mut n) = pair();
996 c.create_group(3, SecurityClass::S2Authenticated).unwrap();
997 let m = c.encrypt_multicast(3, &[0x25, 0x01, 0xff]).unwrap();
999 assert_eq!(n.decrypt_multicast(1, &m), Err(Error::NoSpan));
1000 sync(&mut c, 1, &mut n, 5);
1002 let opts = EncryptOptions {
1003 follow_up_group: Some(3),
1004 send_mpan: Some(3),
1005 ..Default::default()
1006 };
1007 let fu = c.encrypt(5, &[0x25, 0x01, 0xff], &opts).unwrap();
1008 let d = n.decrypt(1, &fu).unwrap();
1009 assert_eq!(d.command, vec![0x25, 0x01, 0xff]);
1010 assert!(d
1011 .extensions
1012 .iter()
1013 .any(|e| matches!(e, Extension::Mpan { group: 3, .. })));
1014 let m2 = c.encrypt_multicast(3, &[0x25, 0x01, 0x00]).unwrap();
1015 assert_eq!(
1016 n.decrypt_multicast(1, &m2).unwrap().command,
1017 vec![0x25, 0x01, 0x00]
1018 );
1019 }
1020
1021 #[test]
1022 fn extension_parsing_is_strict() {
1023 assert!(parse_extensions(&[]).is_err());
1024 assert!(parse_extensions(&[1, 0x41]).is_err());
1025 assert!(parse_extensions(&[18, 0x41, 0]).is_err());
1026 assert_eq!(
1027 parse_extensions(&[2, 0x7f]),
1028 Err(Error::UnsupportedExtension(0x3f))
1029 );
1030 let (e, used) = parse_extensions(&[3, 0x3e, 9, 0xaa]).unwrap();
1031 assert_eq!(used, 3);
1032 assert_eq!(
1033 e,
1034 vec![Extension::Unknown {
1035 kind: 0x3e,
1036 data: vec![9]
1037 }]
1038 );
1039 assert!(Encapsulation::parse(&[0x9f, 0x03, 0, 0x01, 2, 0x84]).is_err());
1040 }
1041}