1use super::header::{Destination, MessageHeader, SessionType};
35use super::ids::NodeId;
36use crate::crypto::{
37 AEAD_MIC_LENGTH_BYTES, AEAD_NONCE_LENGTH_BYTES, SymmetricKey, aead_decrypt_in_place,
38 aead_encrypt_in_place, privacy_key, privacy_xor,
39};
40use crate::error::{Error, ErrorCode, Result, bail};
41
42#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct SessionKeys {
49 pub encryption: SymmetricKey,
51 pub privacy: SymmetricKey,
53}
54
55impl SessionKeys {
56 pub fn from_encryption_key(encryption: SymmetricKey) -> Result<Self> {
58 let privacy = privacy_key(&encryption)?;
59 Ok(Self {
60 encryption,
61 privacy,
62 })
63 }
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum NonceSource {
69 Pase,
76 Case(NodeId),
79 Group,
84}
85
86impl NonceSource {
87 fn resolve(self, header: &MessageHeader) -> Result<NodeId> {
88 match self {
89 Self::Pase => Ok(NodeId::UNSPECIFIED),
90 Self::Case(id) => Ok(id),
91 Self::Group => header.source.ok_or(Error::new(ErrorCode::MessageReserved)),
92 }
93 }
94}
95
96fn nonce(
102 security_flags: u8,
103 message_counter: u32,
104 source: NodeId,
105) -> [u8; AEAD_NONCE_LENGTH_BYTES] {
106 let mut out = [0u8; AEAD_NONCE_LENGTH_BYTES];
107 out[0] = security_flags;
108 if let Some(slot) = out.get_mut(1..5) {
110 slot.copy_from_slice(&message_counter.to_le_bytes());
111 }
112 if let Some(slot) = out.get_mut(5..13) {
113 slot.copy_from_slice(&source.0.to_le_bytes());
114 }
115 out
116}
117
118fn privacy_nonce(
120 session_id: u16,
121 mic: &[u8; AEAD_MIC_LENGTH_BYTES],
122) -> Result<[u8; AEAD_NONCE_LENGTH_BYTES]> {
123 let mut out = [0u8; AEAD_NONCE_LENGTH_BYTES];
124 let Some(slot) = out.get_mut(..2) else {
127 bail!(BufferTooSmall)
128 };
129 slot.copy_from_slice(&session_id.to_be_bytes());
130 let (Some(dst), Some(src)) = (out.get_mut(2..13), mic.get(5..16)) else {
131 bail!(BufferTooSmall)
132 };
133 dst.copy_from_slice(src);
134 Ok(out)
135}
136
137const PRIVACY_OFFSET: usize = 4;
144
145fn privacy_len(header: &MessageHeader) -> usize {
146 let counter = 4usize;
147 let source = if header.source.is_some() { 8 } else { 0 };
148 let destination = match header.destination {
149 Destination::None => 0,
150 Destination::Node(_) => 8,
151 Destination::Group(_) => 2,
152 };
153 counter.saturating_add(source).saturating_add(destination)
154}
155
156pub fn protect(
163 header: &MessageHeader,
164 nonce_source: NonceSource,
165 payload: &[u8],
166 keys: &SessionKeys,
167 out: &mut [u8],
168) -> Result<usize> {
169 if header.is_unsecured() {
170 bail!(InvalidState)
175 }
176 if matches!(header.session_type, SessionType::Group) && header.source.is_none() {
177 bail!(MessageReserved)
179 }
180
181 let header_len = header.encode(out)?;
182 let source = nonce_source.resolve(header)?;
183 let n = nonce(security_flags_of(header), header.message_counter, source);
184
185 let Some(aad) = out.get(..header_len) else {
188 bail!(BufferTooSmall)
189 };
190 let mut aad_copy = [0u8; MAX_HEADER];
191 let Some(aad_slot) = aad_copy.get_mut(..header_len) else {
192 bail!(BufferTooSmall)
193 };
194 aad_slot.copy_from_slice(aad);
195
196 let cipher_end = header_len
197 .checked_add(payload.len())
198 .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
199 let total = cipher_end
200 .checked_add(AEAD_MIC_LENGTH_BYTES)
201 .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
202 let Some(body) = out.get_mut(header_len..cipher_end) else {
203 bail!(BufferTooSmall)
204 };
205 body.copy_from_slice(payload);
206
207 let mut tag = [0u8; AEAD_MIC_LENGTH_BYTES];
208 aead_encrypt_in_place(&keys.encryption, &n, aad_slot, body, &mut tag)?;
209
210 let Some(mic) = out.get_mut(cipher_end..total) else {
211 bail!(BufferTooSmall)
212 };
213 mic.copy_from_slice(&tag);
214
215 if header.privacy {
216 let nonce = privacy_nonce(header.session_id.0, &tag)?;
219 let end = PRIVACY_OFFSET
220 .checked_add(privacy_len(header))
221 .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
222 let Some(region) = out.get_mut(PRIVACY_OFFSET..end) else {
223 bail!(BufferTooSmall)
224 };
225 privacy_xor(&keys.privacy, &nonce, region)?;
226 }
227
228 Ok(total)
229}
230
231const MAX_HEADER: usize = 1 + 2 + 1 + 4 + 8 + 8;
233
234fn security_flags_of(header: &MessageHeader) -> u8 {
236 let mut bits = match header.session_type {
237 SessionType::Unicast => 0u8,
238 SessionType::Group => 1,
239 };
240 if header.privacy {
241 bits |= 0b1000_0000;
242 }
243 if header.control {
244 bits |= 0b0100_0000;
245 }
246 bits
247}
248
249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254pub struct Preview {
255 pub session_id: super::ids::SessionId,
257 pub session_type: SessionType,
259 pub privacy: bool,
261 pub control: bool,
263}
264
265pub fn preview(buf: &[u8]) -> Result<Preview> {
270 let (Some(&flags), Some(session), Some(&security)) = (buf.first(), buf.get(1..3), buf.get(3))
271 else {
272 bail!(MessageTruncated)
273 };
274 if (flags >> 4) != super::header::MESSAGE_FORMAT_VERSION {
275 bail!(UnsupportedVersion)
276 }
277 let Ok(id) = <[u8; 2]>::try_from(session) else {
278 bail!(MessageTruncated)
279 };
280 let session_type = match security & 0b11 {
281 0 => SessionType::Unicast,
282 1 => SessionType::Group,
283 _ => bail!(MessageReserved),
284 };
285 Ok(Preview {
286 session_id: super::ids::SessionId(u16::from_le_bytes(id)),
287 session_type,
288 privacy: security & 0b1000_0000 != 0,
289 control: security & 0b0100_0000 != 0,
290 })
291}
292
293pub fn unprotect(
300 buf: &mut [u8],
301 keys: &SessionKeys,
302 nonce_source: NonceSource,
303) -> Result<(MessageHeader, core::ops::Range<usize>)> {
304 let head = preview(buf)?;
305
306 if head.privacy {
307 let total = buf.len();
310 let mic_start = total
311 .checked_sub(AEAD_MIC_LENGTH_BYTES)
312 .ok_or(Error::new(ErrorCode::MessageTruncated))?;
313 let Some(mic) = buf.get(mic_start..total) else {
314 bail!(MessageTruncated)
315 };
316 let Ok(mic) = <[u8; AEAD_MIC_LENGTH_BYTES]>::try_from(mic) else {
317 bail!(MessageTruncated)
318 };
319 let nonce = privacy_nonce(head.session_id.0, &mic)?;
320
321 let Some(&flags) = buf.first() else {
324 bail!(MessageTruncated)
325 };
326 let obfuscated = privacy_len_from_flags(flags)?;
327 let end = PRIVACY_OFFSET
328 .checked_add(obfuscated)
329 .ok_or(Error::new(ErrorCode::MessageTruncated))?;
330 let Some(region) = buf.get_mut(PRIVACY_OFFSET..end) else {
331 bail!(MessageTruncated)
332 };
333 privacy_xor(&keys.privacy, &nonce, region)?;
334 }
335
336 let (header, rest) = MessageHeader::decode(buf)?;
337 if header.is_unsecured() {
338 bail!(InvalidState)
341 }
342 match header.session_type {
344 SessionType::Unicast => {
345 if matches!(header.destination, Destination::Group(_)) {
346 bail!(MessageReserved)
349 }
350 }
351 SessionType::Group => {
352 if matches!(header.destination, Destination::None) || header.source.is_none() {
353 bail!(MessageReserved)
355 }
356 }
357 }
358
359 let header_len = buf.len().saturating_sub(rest.len());
360 let mut aad = [0u8; MAX_HEADER];
361 let (Some(aad_slot), Some(header_bytes)) = (aad.get_mut(..header_len), buf.get(..header_len))
362 else {
363 bail!(MessageTruncated)
364 };
365 aad_slot.copy_from_slice(header_bytes);
366
367 let total = buf.len();
368 let mic_start = total
369 .checked_sub(AEAD_MIC_LENGTH_BYTES)
370 .ok_or(Error::new(ErrorCode::MessageTruncated))?;
371 if mic_start < header_len {
372 bail!(MessageTruncated)
373 }
374 let Some(mic) = buf.get(mic_start..total) else {
375 bail!(MessageTruncated)
376 };
377 let Ok(tag) = <[u8; AEAD_MIC_LENGTH_BYTES]>::try_from(mic) else {
378 bail!(MessageTruncated)
379 };
380
381 let source = nonce_source.resolve(&header)?;
382 let n = nonce(security_flags_of(&header), header.message_counter, source);
383
384 let Some(body) = buf.get_mut(header_len..mic_start) else {
385 bail!(MessageTruncated)
386 };
387 aead_decrypt_in_place(&keys.encryption, &n, aad_slot, body, &tag)?;
388
389 Ok((header, header_len..mic_start))
390}
391
392fn privacy_len_from_flags(flags: u8) -> Result<usize> {
394 let source = if flags & 0b0000_0100 != 0 { 8 } else { 0 };
395 let destination = match flags & 0b11 {
396 0 => 0usize,
397 1 => 8,
398 2 => 2,
399 _ => bail!(MessageReserved),
400 };
401 Ok(4usize.saturating_add(source).saturating_add(destination))
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407 use crate::msg::{ExchangeId, GroupId, ProtocolHeader, ProtocolId, SessionId};
408
409 fn keys() -> SessionKeys {
410 SessionKeys::from_encryption_key(SymmetricKey::new([0x5A; 16])).expect("derive")
411 }
412
413 fn case_header() -> MessageHeader {
414 MessageHeader {
415 session_id: SessionId(0x1234),
416 message_counter: 0x0102_0304,
417 ..MessageHeader::default()
418 }
419 }
420
421 #[test]
422 fn the_nonce_is_table_17() {
423 let n = nonce(0x80, 0x0A0B_0C0D, NodeId(0x1122_3344_5566_7788));
425 assert_eq!(
426 n,
427 [
428 0x80, 0x0D, 0x0C, 0x0B, 0x0A, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, ]
432 );
433 }
434
435 #[test]
436 fn the_privacy_nonce_matches_the_specs_worked_example() {
437 let mic = [
439 0xc5, 0xa0, 0x06, 0x3a, 0xd5, 0xd2, 0x51, 0x81, 0x91, 0x40, 0x0d, 0xd6, 0x8c, 0x5c,
440 0x16, 0x3b,
441 ];
442 let n = privacy_nonce(42, &mic).expect("nonce");
443 assert_eq!(
444 n,
445 [
446 0x00, 0x2a, 0xd2, 0x51, 0x81, 0x91, 0x40, 0x0d, 0xd6, 0x8c, 0x5c, 0x16,
448 0x3b, ]
450 );
451 }
452
453 #[test]
454 fn a_case_message_round_trips() {
455 let keys = keys();
456 let header = case_header();
457 let payload = b"protocol header and payload";
458
459 let mut buf = [0u8; 256];
460 let n = protect(
461 &header,
462 NonceSource::Case(NodeId(7)),
463 payload,
464 &keys,
465 &mut buf,
466 )
467 .expect("protect");
468
469 let (decoded, range) =
470 unprotect(&mut buf[..n], &keys, NonceSource::Case(NodeId(7))).expect("unprotect");
471 assert_eq!(decoded, header);
472 assert_eq!(&buf[range], payload);
473 }
474
475 #[test]
476 fn a_pase_message_round_trips() {
477 let keys = keys();
478 let header = case_header();
479 let payload = b"pake1";
480 let mut buf = [0u8; 128];
481 let n = protect(&header, NonceSource::Pase, payload, &keys, &mut buf).expect("protect");
482 let (_, range) = unprotect(&mut buf[..n], &keys, NonceSource::Pase).expect("unprotect");
483 assert_eq!(&buf[range], payload);
484 }
485
486 #[test]
487 fn the_wrong_nonce_source_does_not_decrypt() {
488 let keys = keys();
491 let header = case_header();
492 let mut buf = [0u8; 128];
493 let n =
494 protect(&header, NonceSource::Case(NodeId(7)), b"x", &keys, &mut buf).expect("protect");
495 assert_eq!(
496 unprotect(&mut buf[..n], &keys, NonceSource::Pase)
497 .unwrap_err()
498 .code(),
499 ErrorCode::IntegrityCheckFailed
500 );
501 }
502
503 #[test]
504 fn a_private_message_round_trips_and_hides_the_counter() {
505 let keys = keys();
506 let header = MessageHeader {
507 privacy: true,
508 source: Some(NodeId(0x1122_3344_5566_7788)),
509 destination: Destination::Node(NodeId(9)),
510 ..case_header()
511 };
512 let payload = b"obfuscated header, encrypted body";
513
514 let mut buf = [0u8; 256];
515 let n = protect(
516 &header,
517 NonceSource::Case(NodeId(0x1122_3344_5566_7788)),
518 payload,
519 &keys,
520 &mut buf,
521 )
522 .expect("protect");
523
524 assert_ne!(
526 &buf[4..8],
527 &header.message_counter.to_le_bytes(),
528 "the counter should be obfuscated"
529 );
530 let head = preview(&buf[..n]).expect("preview");
532 assert_eq!(head.session_id, header.session_id);
533 assert!(head.privacy);
534
535 let (decoded, range) = unprotect(
536 &mut buf[..n],
537 &keys,
538 NonceSource::Case(NodeId(0x1122_3344_5566_7788)),
539 )
540 .expect("unprotect");
541 assert_eq!(decoded, header);
542 assert_eq!(&buf[range], payload);
543 }
544
545 #[test]
546 fn a_group_message_round_trips() {
547 let keys = keys();
548 let header = MessageHeader {
549 session_type: SessionType::Group,
550 session_id: SessionId(5),
551 source: Some(NodeId(42)),
552 destination: Destination::Group(GroupId(7)),
553 ..MessageHeader::default()
554 };
555 let mut buf = [0u8; 128];
556 let n = protect(&header, NonceSource::Group, b"grouped", &keys, &mut buf).expect("protect");
557 let (decoded, range) =
558 unprotect(&mut buf[..n], &keys, NonceSource::Group).expect("unprotect");
559 assert_eq!(decoded.source, Some(NodeId(42)));
560 assert_eq!(&buf[range], b"grouped");
561 }
562
563 #[test]
564 fn a_group_message_without_a_source_is_refused() {
565 let keys = keys();
568 let header = MessageHeader {
569 session_type: SessionType::Group,
570 session_id: SessionId(5),
571 destination: Destination::Group(GroupId(7)),
572 ..MessageHeader::default()
573 };
574 let mut buf = [0u8; 128];
575 assert_eq!(
576 protect(&header, NonceSource::Group, b"x", &keys, &mut buf)
577 .unwrap_err()
578 .code(),
579 ErrorCode::MessageReserved
580 );
581 }
582
583 #[test]
584 fn an_unsecured_message_cannot_be_protected() {
585 let keys = keys();
586 let mut buf = [0u8; 64];
587 assert_eq!(
588 protect(
589 &MessageHeader::default(),
590 NonceSource::Pase,
591 b"x",
592 &keys,
593 &mut buf
594 )
595 .unwrap_err()
596 .code(),
597 ErrorCode::InvalidState
598 );
599 }
600
601 #[test]
602 fn every_single_bit_flip_is_caught() {
603 let keys = keys();
606 let header = case_header();
607 let mut buf = [0u8; 128];
608 let n = protect(
609 &header,
610 NonceSource::Case(NodeId(7)),
611 b"payload",
612 &keys,
613 &mut buf,
614 )
615 .expect("protect");
616 let original = buf;
617
618 for byte in 0..n {
619 for bit in 0..8u32 {
620 let mut broken = original;
621 broken[byte] ^= 1u8 << bit;
622 let result = unprotect(&mut broken[..n], &keys, NonceSource::Case(NodeId(7)));
623 assert!(
624 result.is_err(),
625 "flipping bit {bit} of octet {byte} went undetected"
626 );
627 }
628 }
629 }
630
631 #[test]
632 fn the_wrong_key_does_not_decrypt() {
633 let keys = keys();
634 let other = SessionKeys::from_encryption_key(SymmetricKey::new([0xA5; 16])).expect("k");
635 let mut buf = [0u8; 128];
636 let n = protect(&case_header(), NonceSource::Pase, b"x", &keys, &mut buf).expect("protect");
637 assert!(unprotect(&mut buf[..n], &other, NonceSource::Pase).is_err());
638 }
639
640 #[test]
641 fn a_group_id_on_a_unicast_session_is_refused() {
642 let keys = keys();
645 let header = MessageHeader {
646 destination: Destination::Group(GroupId(1)),
647 ..case_header()
648 };
649 let mut buf = [0u8; 128];
650 let n =
651 protect(&header, NonceSource::Case(NodeId(1)), b"x", &keys, &mut buf).expect("protect");
652 assert_eq!(
653 unprotect(&mut buf[..n], &keys, NonceSource::Case(NodeId(1)))
654 .unwrap_err()
655 .code(),
656 ErrorCode::MessageReserved
657 );
658 }
659
660 #[test]
661 fn truncation_at_every_length_is_an_error_not_a_panic() {
662 let keys = keys();
663 let mut buf = [0u8; 128];
664 let n = protect(
665 &case_header(),
666 NonceSource::Pase,
667 b"payload",
668 &keys,
669 &mut buf,
670 )
671 .expect("protect");
672 for cut in 0..n {
673 let mut copy = buf;
674 let _ = unprotect(&mut copy[..cut], &keys, NonceSource::Pase);
675 }
676 }
677
678 #[test]
679 fn a_whole_message_round_trips_with_its_protocol_header() {
680 let keys = keys();
682 let protocol = ProtocolHeader {
683 initiator: true,
684 reliability: true,
685 exchange_id: ExchangeId(3),
686 protocol: ProtocolId::SECURE_CHANNEL,
687 opcode: 0x20,
688 ..ProtocolHeader::default()
689 };
690 let mut inner = [0u8; 64];
691 let inner_len = protocol.encode(&mut inner).expect("encode");
692
693 let mut buf = [0u8; 256];
694 let n = protect(
695 &case_header(),
696 NonceSource::Pase,
697 &inner[..inner_len],
698 &keys,
699 &mut buf,
700 )
701 .expect("protect");
702
703 let (_, range) = unprotect(&mut buf[..n], &keys, NonceSource::Pase).expect("unprotect");
704 let (decoded, app) = ProtocolHeader::decode(&buf[range]).expect("decode");
705 assert_eq!(decoded, protocol);
706 assert!(app.is_empty());
707 }
708
709 #[test]
710 fn the_preview_refuses_what_the_header_would() {
711 assert_eq!(
712 preview(&[]).unwrap_err().code(),
713 ErrorCode::MessageTruncated
714 );
715 assert_eq!(
716 preview(&[0x10, 0, 0, 0]).unwrap_err().code(),
717 ErrorCode::UnsupportedVersion
718 );
719 assert_eq!(
720 preview(&[0x00, 0, 0, 0x02]).unwrap_err().code(),
721 ErrorCode::MessageReserved
722 );
723 }
724}