1use crate::cert::{CERT_TLV_MAX, MatterCertificate, VerifiedIdentity, verify_chain};
64use crate::crypto::{
65 AEAD_MIC_LENGTH_BYTES, AEAD_NONCE_LENGTH_BYTES, GROUP_SIZE_BYTES, HASH_LEN_BYTES, Hasher,
66 KeyHandle, KeyPurpose, KeyStore, PUBLIC_KEY_SIZE_BYTES, PublicKey, SIGNATURE_LEN_BYTES, Secret,
67 Signature, SymmetricKey, aead_decrypt_in_place, aead_encrypt_in_place, ct_eq, kdf_key, verify,
68};
69use crate::error::{Error, ErrorCode, Result, bail};
70use crate::fabric::{Fabric, INITIATOR_RANDOM_LEN};
71use crate::msg::SessionId;
72use crate::sc::status::{SecureChannelCode, StatusReport};
73use crate::sc::{Fields, SessionParams};
74use crate::tlv::{Tag, TlvWriter, set_once};
75
76pub mod opcode {
78 pub const SIGMA1: u8 = 0x30;
80 pub const SIGMA2: u8 = 0x31;
82 pub const SIGMA3: u8 = 0x32;
84 pub const SIGMA2_RESUME: u8 = 0x33;
86 pub const STATUS_REPORT: u8 = 0x40;
88}
89
90pub const RANDOM_LEN: usize = INITIATOR_RANDOM_LEN;
92
93pub const RESUMPTION_ID_LEN: usize = 16;
95
96pub const S2K_INFO: &[u8] = b"Sigma2";
100pub const S3K_INFO: &[u8] = b"Sigma3";
102pub const S1RK_INFO: &[u8] = b"Sigma1_Resume";
104pub const S2RK_INFO: &[u8] = b"Sigma2_Resume";
106pub const SESSION_KEYS_INFO: &[u8] = crate::session::SESSION_KEYS_INFO;
108pub const RESUMPTION_SESSION_KEYS_INFO: &[u8] = b"SessionResumptionKeys";
110
111pub const SIGMA2_NONCE: [u8; AEAD_NONCE_LENGTH_BYTES] = *b"NCASE_Sigma2N";
115pub const SIGMA3_NONCE: [u8; AEAD_NONCE_LENGTH_BYTES] = *b"NCASE_Sigma3N";
117pub const RESUME1_NONCE: [u8; AEAD_NONCE_LENGTH_BYTES] = *b"NCASE_SigmaS1";
119pub const RESUME2_NONCE: [u8; AEAD_NONCE_LENGTH_BYTES] = *b"NCASE_SigmaS2";
121
122const LONG_STRING_HEADER: usize = 4;
127const SHORT_STRING_HEADER: usize = 3;
130const STRUCTURE_OVERHEAD: usize = 2;
132
133const MAX_TBEDATA2: usize = STRUCTURE_OVERHEAD
141 + (2 * (LONG_STRING_HEADER + CERT_TLV_MAX))
142 + (SHORT_STRING_HEADER + SIGNATURE_LEN_BYTES)
143 + (SHORT_STRING_HEADER + RESUMPTION_ID_LEN);
144
145const MAX_TBEDATA3: usize = STRUCTURE_OVERHEAD
147 + (2 * (LONG_STRING_HEADER + CERT_TLV_MAX))
148 + (SHORT_STRING_HEADER + SIGNATURE_LEN_BYTES);
149
150pub const MAX_ENCRYPTED2: usize = MAX_TBEDATA2 + AEAD_MIC_LENGTH_BYTES;
155
156pub const MAX_ENCRYPTED3: usize = MAX_TBEDATA3 + AEAD_MIC_LENGTH_BYTES;
158
159pub const MAX_TBSDATA: usize = STRUCTURE_OVERHEAD
162 + (2 * (LONG_STRING_HEADER + CERT_TLV_MAX))
163 + (2 * (SHORT_STRING_HEADER + PUBLIC_KEY_SIZE_BYTES));
164
165pub const MAX_SIGMA1: usize = RANDOM_LEN
168 + HASH_LEN_BYTES
169 + PUBLIC_KEY_SIZE_BYTES
170 + RESUMPTION_ID_LEN
171 + AEAD_MIC_LENGTH_BYTES
172 + 64;
173
174pub const MAX_SIGMA2: usize = STRUCTURE_OVERHEAD
181 + (SHORT_STRING_HEADER + RANDOM_LEN)
182 + 4
183 + (SHORT_STRING_HEADER + PUBLIC_KEY_SIZE_BYTES)
184 + (LONG_STRING_HEADER + MAX_ENCRYPTED2)
185 + MAX_SESSION_PARAMS;
186
187pub const MAX_SIGMA3: usize = STRUCTURE_OVERHEAD + LONG_STRING_HEADER + MAX_ENCRYPTED3;
189
190pub const MAX_SESSION_PARAMS: usize = STRUCTURE_OVERHEAD + (9 * 6);
193
194const _: () = {
206 assert!(
208 MAX_ENCRYPTED2
209 >= 2 + 2 * (4 + CERT_TLV_MAX)
210 + (3 + SIGNATURE_LEN_BYTES)
211 + (3 + RESUMPTION_ID_LEN)
212 + AEAD_MIC_LENGTH_BYTES
213 );
214 assert!(
216 MAX_ENCRYPTED3
217 >= 2 + 2 * (4 + CERT_TLV_MAX) + (3 + SIGNATURE_LEN_BYTES) + AEAD_MIC_LENGTH_BYTES
218 );
219 assert!(MAX_TBSDATA >= 2 + 2 * (4 + CERT_TLV_MAX) + 2 * (3 + PUBLIC_KEY_SIZE_BYTES));
221 assert!(MAX_SESSION_PARAMS >= 2 + 9 * (1 + 1 + 4));
223 assert!(
225 MAX_SIGMA2
226 >= 2 + (3 + RANDOM_LEN)
227 + 4
228 + (3 + PUBLIC_KEY_SIZE_BYTES)
229 + (4 + MAX_ENCRYPTED2)
230 + MAX_SESSION_PARAMS
231 );
232 assert!(MAX_SIGMA3 >= 2 + 4 + MAX_ENCRYPTED3);
233 assert!(MAX_SIGMA2 + 64 <= crate::config::MAX_UDP_MESSAGE);
236};
237
238fn parse_error() -> Error {
239 Error::new(ErrorCode::TlvWrongType)
240}
241
242fn seal<'b>(
249 key: &SymmetricKey,
250 nonce: &[u8; AEAD_NONCE_LENGTH_BYTES],
251 buf: &'b mut [u8],
252 len: usize,
253) -> Result<&'b [u8]> {
254 let end = len
255 .checked_add(AEAD_MIC_LENGTH_BYTES)
256 .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
257 if buf.len() < end {
258 bail!(BufferTooSmall)
259 }
260 let (plaintext, rest) = buf.split_at_mut(len);
261 let mut mic = [0u8; AEAD_MIC_LENGTH_BYTES];
262 aead_encrypt_in_place(key, nonce, &[], plaintext, &mut mic)?;
263 rest.get_mut(..AEAD_MIC_LENGTH_BYTES)
264 .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?
265 .copy_from_slice(&mic);
266 buf.get(..end)
267 .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))
268}
269
270fn open(
276 key: &SymmetricKey,
277 nonce: &[u8; AEAD_NONCE_LENGTH_BYTES],
278 buf: &mut [u8],
279 sealed: &[u8],
280) -> Result<usize> {
281 let len = sealed
282 .len()
283 .checked_sub(AEAD_MIC_LENGTH_BYTES)
284 .ok_or_else(|| Error::new(ErrorCode::IntegrityCheckFailed))?;
285 let (body, mic) = sealed.split_at(len);
286 let mic = <[u8; AEAD_MIC_LENGTH_BYTES]>::try_from(mic)
287 .map_err(|_| Error::new(ErrorCode::IntegrityCheckFailed))?;
288 let slot = buf
289 .get_mut(..len)
290 .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
291 slot.copy_from_slice(body);
292 aead_decrypt_in_place(key, nonce, &[], slot, &mic)?;
293 Ok(len)
294}
295
296#[derive(Debug, Clone, PartialEq, Eq)]
300pub struct Sigma1<'a> {
301 pub initiator_random: [u8; RANDOM_LEN],
303 pub initiator_session_id: SessionId,
305 pub destination_id: [u8; HASH_LEN_BYTES],
307 pub initiator_eph_pub_key: PublicKey,
309 pub session_params: Option<SessionParams>,
311 pub resumption_id: Option<[u8; RESUMPTION_ID_LEN]>,
313 pub initiator_resume_mic: Option<[u8; AEAD_MIC_LENGTH_BYTES]>,
315 encoded: &'a [u8],
318}
319
320impl<'a> Sigma1<'a> {
321 #[must_use]
323 pub const fn encoded(&self) -> &'a [u8] {
324 self.encoded
325 }
326
327 #[must_use]
331 pub const fn is_resumption(&self) -> bool {
332 self.resumption_id.is_some() && self.initiator_resume_mic.is_some()
333 }
334
335 pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
337 let mut w = TlvWriter::new(buf);
338 w.start_structure(Tag::Anonymous)?;
339 w.octets(Tag::Context(1), &self.initiator_random)?;
340 w.unsigned(Tag::Context(2), u64::from(self.initiator_session_id.0))?;
341 w.octets(Tag::Context(3), &self.destination_id)?;
342 w.octets(Tag::Context(4), self.initiator_eph_pub_key.as_bytes())?;
343 if let Some(params) = self.session_params {
344 params.encode(&mut w, Tag::Context(5))?;
345 }
346 if let Some(id) = self.resumption_id.as_ref() {
347 w.octets(Tag::Context(6), id)?;
348 }
349 if let Some(mic) = self.initiator_resume_mic.as_ref() {
350 w.octets(Tag::Context(7), mic)?;
351 }
352 w.end_container()?;
353 w.finish()
354 }
355
356 pub fn decode(buf: &'a [u8]) -> Result<Self> {
358 let mut fields = Fields::new(buf)?;
359 let mut initiator_random = None;
360 let mut initiator_session_id = None;
361 let mut destination_id = None;
362 let mut initiator_eph_pub_key = None;
363 let mut session_params = None;
364 let mut resumption_id = None;
365 let mut initiator_resume_mic = None;
366
367 while let Some((tag, element)) = fields.next()? {
368 match tag {
369 1 => set_once(
370 &mut initiator_random,
371 fixed::<RANDOM_LEN>(element.octets()?)?,
372 )?,
373 2 => {
374 let id =
375 SessionId(u16::try_from(element.unsigned()?).map_err(|_| parse_error())?);
376 set_once(&mut initiator_session_id, id)?;
377 }
378 3 => set_once(
379 &mut destination_id,
380 fixed::<HASH_LEN_BYTES>(element.octets()?)?,
381 )?,
382 4 => set_once(
383 &mut initiator_eph_pub_key,
384 PublicKey::from_slice(element.octets()?)?,
385 )?,
386 5 => set_once(&mut session_params, SessionParams::decode(&mut fields)?)?,
387 6 => set_once(
388 &mut resumption_id,
389 fixed::<RESUMPTION_ID_LEN>(element.octets()?)?,
390 )?,
391 7 => {
392 let mic = fixed::<AEAD_MIC_LENGTH_BYTES>(element.octets()?)?;
393 set_once(&mut initiator_resume_mic, mic)?;
394 }
395 _ => fields.skip(&element)?,
399 }
400 }
401
402 Ok(Self {
403 initiator_random: initiator_random.ok_or_else(parse_error)?,
404 initiator_session_id: initiator_session_id.ok_or_else(parse_error)?,
405 destination_id: destination_id.ok_or_else(parse_error)?,
406 initiator_eph_pub_key: initiator_eph_pub_key.ok_or_else(parse_error)?,
407 session_params,
408 resumption_id,
409 initiator_resume_mic,
410 encoded: buf,
411 })
412 }
413}
414
415#[derive(Debug, Clone, PartialEq, Eq)]
419pub struct Sigma2<'a> {
420 pub responder_random: [u8; RANDOM_LEN],
422 pub responder_session_id: SessionId,
424 pub responder_eph_pub_key: PublicKey,
426 pub encrypted2: &'a [u8],
428 pub session_params: Option<SessionParams>,
430 encoded: &'a [u8],
431}
432
433impl<'a> Sigma2<'a> {
434 #[must_use]
436 pub const fn encoded(&self) -> &'a [u8] {
437 self.encoded
438 }
439
440 pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
442 let mut w = TlvWriter::new(buf);
443 w.start_structure(Tag::Anonymous)?;
444 w.octets(Tag::Context(1), &self.responder_random)?;
445 w.unsigned(Tag::Context(2), u64::from(self.responder_session_id.0))?;
446 w.octets(Tag::Context(3), self.responder_eph_pub_key.as_bytes())?;
447 w.octets(Tag::Context(4), self.encrypted2)?;
448 if let Some(params) = self.session_params {
449 params.encode(&mut w, Tag::Context(5))?;
450 }
451 w.end_container()?;
452 w.finish()
453 }
454
455 pub fn decode(buf: &'a [u8]) -> Result<Self> {
457 let mut fields = Fields::new(buf)?;
458 let mut responder_random = None;
459 let mut responder_session_id = None;
460 let mut responder_eph_pub_key = None;
461 let mut encrypted2 = None;
462 let mut session_params = None;
463
464 while let Some((tag, element)) = fields.next()? {
465 match tag {
466 1 => set_once(
467 &mut responder_random,
468 fixed::<RANDOM_LEN>(element.octets()?)?,
469 )?,
470 2 => {
471 let id =
472 SessionId(u16::try_from(element.unsigned()?).map_err(|_| parse_error())?);
473 set_once(&mut responder_session_id, id)?;
474 }
475 3 => set_once(
476 &mut responder_eph_pub_key,
477 PublicKey::from_slice(element.octets()?)?,
478 )?,
479 4 => set_once(&mut encrypted2, element.octets()?)?,
480 5 => set_once(&mut session_params, SessionParams::decode(&mut fields)?)?,
481 _ => fields.skip(&element)?,
482 }
483 }
484
485 Ok(Self {
486 responder_random: responder_random.ok_or_else(parse_error)?,
487 responder_session_id: responder_session_id.ok_or_else(parse_error)?,
488 responder_eph_pub_key: responder_eph_pub_key.ok_or_else(parse_error)?,
489 encrypted2: encrypted2.ok_or_else(parse_error)?,
490 session_params,
491 encoded: buf,
492 })
493 }
494}
495
496#[derive(Debug, Clone, PartialEq, Eq)]
500pub struct Sigma3<'a> {
501 pub encrypted3: &'a [u8],
503 encoded: &'a [u8],
504}
505
506impl<'a> Sigma3<'a> {
507 #[must_use]
509 pub const fn encoded(&self) -> &'a [u8] {
510 self.encoded
511 }
512
513 pub fn encode<'b>(encrypted3: &[u8], buf: &'b mut [u8]) -> Result<&'b [u8]> {
515 let mut w = TlvWriter::new(buf);
516 w.start_structure(Tag::Anonymous)?;
517 w.octets(Tag::Context(1), encrypted3)?;
518 w.end_container()?;
519 w.finish()
520 }
521
522 pub fn decode(buf: &'a [u8]) -> Result<Self> {
524 let mut fields = Fields::new(buf)?;
525 let mut encrypted3 = None;
526 while let Some((tag, element)) = fields.next()? {
527 match tag {
528 1 => set_once(&mut encrypted3, element.octets()?)?,
529 _ => fields.skip(&element)?,
530 }
531 }
532 Ok(Self {
533 encrypted3: encrypted3.ok_or_else(parse_error)?,
534 encoded: buf,
535 })
536 }
537}
538
539#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub struct Sigma2Resume {
542 pub resumption_id: [u8; RESUMPTION_ID_LEN],
544 pub sigma2_resume_mic: [u8; AEAD_MIC_LENGTH_BYTES],
546 pub responder_session_id: SessionId,
548 pub session_params: Option<SessionParams>,
550}
551
552impl Sigma2Resume {
553 pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
555 let mut w = TlvWriter::new(buf);
556 w.start_structure(Tag::Anonymous)?;
557 w.octets(Tag::Context(1), &self.resumption_id)?;
558 w.octets(Tag::Context(2), &self.sigma2_resume_mic)?;
559 w.unsigned(Tag::Context(3), u64::from(self.responder_session_id.0))?;
560 if let Some(params) = self.session_params {
561 params.encode(&mut w, Tag::Context(4))?;
562 }
563 w.end_container()?;
564 w.finish()
565 }
566
567 pub fn decode(buf: &[u8]) -> Result<Self> {
569 let mut fields = Fields::new(buf)?;
570 let mut resumption_id = None;
571 let mut sigma2_resume_mic = None;
572 let mut responder_session_id = None;
573 let mut session_params = None;
574 while let Some((tag, element)) = fields.next()? {
575 match tag {
576 1 => set_once(
577 &mut resumption_id,
578 fixed::<RESUMPTION_ID_LEN>(element.octets()?)?,
579 )?,
580 2 => {
581 let mic = fixed::<AEAD_MIC_LENGTH_BYTES>(element.octets()?)?;
582 set_once(&mut sigma2_resume_mic, mic)?;
583 }
584 3 => {
585 let id =
586 SessionId(u16::try_from(element.unsigned()?).map_err(|_| parse_error())?);
587 set_once(&mut responder_session_id, id)?;
588 }
589 4 => set_once(&mut session_params, SessionParams::decode(&mut fields)?)?,
590 _ => fields.skip(&element)?,
591 }
592 }
593 Ok(Self {
594 resumption_id: resumption_id.ok_or_else(parse_error)?,
595 sigma2_resume_mic: sigma2_resume_mic.ok_or_else(parse_error)?,
596 responder_session_id: responder_session_id.ok_or_else(parse_error)?,
597 session_params,
598 })
599 }
600}
601
602pub fn failure_report(code: SecureChannelCode, out: &mut [u8]) -> Result<usize> {
629 StatusReport::secure_channel(code).encode(out)
630}
631
632fn fixed<const N: usize>(bytes: &[u8]) -> Result<[u8; N]> {
633 <[u8; N]>::try_from(bytes).map_err(|_| parse_error())
634}
635
636#[derive(Debug, Clone)]
645pub struct Transcript(Hasher);
646
647impl Default for Transcript {
648 fn default() -> Self {
649 Self::new()
650 }
651}
652
653impl Transcript {
654 #[must_use]
656 pub fn new() -> Self {
657 Self(Hasher::new())
658 }
659
660 pub fn update(&mut self, message: &[u8]) {
662 self.0.update(message);
663 }
664
665 #[must_use]
667 pub fn hash(&self) -> [u8; HASH_LEN_BYTES] {
668 self.0.clone().finish()
669 }
670}
671
672const S2K_SALT_LEN: usize =
674 crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES + RANDOM_LEN + PUBLIC_KEY_SIZE_BYTES + HASH_LEN_BYTES;
675
676pub fn sigma2_key(
678 shared_secret: &Secret<GROUP_SIZE_BYTES>,
679 ipk: &SymmetricKey,
680 responder_random: &[u8; RANDOM_LEN],
681 responder_eph_pub_key: &PublicKey,
682 transcript_hash: &[u8; HASH_LEN_BYTES],
683) -> Result<SymmetricKey> {
684 let mut salt = [0u8; S2K_SALT_LEN];
685 let mut at = 0usize;
686 at = put(&mut salt, at, ipk.as_bytes())?;
687 at = put(&mut salt, at, responder_random)?;
688 at = put(&mut salt, at, responder_eph_pub_key.as_bytes())?;
689 at = put(&mut salt, at, transcript_hash)?;
690 let salt = salt.get(..at).ok_or_else(parse_error)?;
691 kdf_key(shared_secret.as_bytes(), salt, S2K_INFO)
692}
693
694const IPK_TRANSCRIPT_SALT_LEN: usize = crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES + HASH_LEN_BYTES;
696
697fn ipk_transcript_salt(
698 ipk: &SymmetricKey,
699 transcript_hash: &[u8; HASH_LEN_BYTES],
700) -> [u8; IPK_TRANSCRIPT_SALT_LEN] {
701 let mut salt = [0u8; IPK_TRANSCRIPT_SALT_LEN];
702 let (head, tail) = salt.split_at_mut(crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES);
703 head.copy_from_slice(ipk.as_bytes());
704 tail.copy_from_slice(transcript_hash);
705 salt
706}
707
708pub fn sigma3_key(
710 shared_secret: &Secret<GROUP_SIZE_BYTES>,
711 ipk: &SymmetricKey,
712 transcript_hash: &[u8; HASH_LEN_BYTES],
713) -> Result<SymmetricKey> {
714 kdf_key(
715 shared_secret.as_bytes(),
716 &ipk_transcript_salt(ipk, transcript_hash),
717 S3K_INFO,
718 )
719}
720
721const RESUME_SALT_LEN: usize = RANDOM_LEN + RESUMPTION_ID_LEN;
723
724fn resume_salt(
725 initiator_random: &[u8; RANDOM_LEN],
726 resumption_id: &[u8; RESUMPTION_ID_LEN],
727) -> [u8; RESUME_SALT_LEN] {
728 let mut salt = [0u8; RESUME_SALT_LEN];
729 let (head, tail) = salt.split_at_mut(RANDOM_LEN);
730 head.copy_from_slice(initiator_random);
731 tail.copy_from_slice(resumption_id);
732 salt
733}
734
735pub fn sigma1_resume_key(
737 shared_secret: &Secret<GROUP_SIZE_BYTES>,
738 initiator_random: &[u8; RANDOM_LEN],
739 resumption_id: &[u8; RESUMPTION_ID_LEN],
740) -> Result<SymmetricKey> {
741 kdf_key(
742 shared_secret.as_bytes(),
743 &resume_salt(initiator_random, resumption_id),
744 S1RK_INFO,
745 )
746}
747
748pub fn sigma2_resume_key(
754 shared_secret: &Secret<GROUP_SIZE_BYTES>,
755 initiator_random: &[u8; RANDOM_LEN],
756 resumption_id: &[u8; RESUMPTION_ID_LEN],
757) -> Result<SymmetricKey> {
758 kdf_key(
759 shared_secret.as_bytes(),
760 &resume_salt(initiator_random, resumption_id),
761 S2RK_INFO,
762 )
763}
764
765pub fn session_keys(
767 shared_secret: &Secret<GROUP_SIZE_BYTES>,
768 ipk: &SymmetricKey,
769 transcript_hash: &[u8; HASH_LEN_BYTES],
770) -> Result<crate::session::EstablishedKeys> {
771 crate::session::EstablishedKeys::derive(
772 shared_secret.as_bytes(),
773 &ipk_transcript_salt(ipk, transcript_hash),
774 )
775}
776
777pub fn resumption_session_keys(
783 shared_secret: &Secret<GROUP_SIZE_BYTES>,
784 initiator_random: &[u8; RANDOM_LEN],
785 resumption_id: &[u8; RESUMPTION_ID_LEN],
786) -> Result<crate::session::EstablishedKeys> {
787 crate::session::EstablishedKeys::derive_with_info(
788 shared_secret.as_bytes(),
789 &resume_salt(initiator_random, resumption_id),
790 RESUMPTION_SESSION_KEYS_INFO,
791 )
792}
793
794fn put(buf: &mut [u8], at: usize, src: &[u8]) -> Result<usize> {
795 let end = at
796 .checked_add(src.len())
797 .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
798 let Some(slot) = buf.get_mut(at..end) else {
799 bail!(BufferTooSmall)
800 };
801 slot.copy_from_slice(src);
802 Ok(end)
803}
804
805pub fn encode_tbsdata<'b>(
815 noc: &[u8],
816 icac: Option<&[u8]>,
817 own_eph_pub_key: &PublicKey,
818 peer_eph_pub_key: &PublicKey,
819 buf: &'b mut [u8],
820) -> Result<&'b [u8]> {
821 let mut w = TlvWriter::new(buf);
822 w.start_structure(Tag::Anonymous)?;
823 w.octets(Tag::Context(1), noc)?;
824 if let Some(icac) = icac {
825 w.octets(Tag::Context(2), icac)?;
826 }
827 w.octets(Tag::Context(3), own_eph_pub_key.as_bytes())?;
828 w.octets(Tag::Context(4), peer_eph_pub_key.as_bytes())?;
829 w.end_container()?;
830 w.finish()
831}
832
833#[derive(Debug, Clone, PartialEq, Eq)]
835pub struct TbeData<'a> {
836 pub noc: &'a [u8],
838 pub icac: Option<&'a [u8]>,
840 pub signature: Signature,
842 pub resumption_id: Option<[u8; RESUMPTION_ID_LEN]>,
845}
846
847impl<'a> TbeData<'a> {
848 pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
854 let mut w = TlvWriter::new(buf);
855 w.start_structure(Tag::Anonymous)?;
856 w.octets(Tag::Context(1), self.noc)?;
857 if let Some(icac) = self.icac {
858 w.octets(Tag::Context(2), icac)?;
859 }
860 w.octets(Tag::Context(3), self.signature.as_bytes())?;
861 if let Some(id) = self.resumption_id.as_ref() {
862 w.octets(Tag::Context(4), id)?;
863 }
864 w.end_container()?;
865 w.finish()
866 }
867
868 pub fn decode(buf: &'a [u8]) -> Result<Self> {
870 let mut fields = Fields::new(buf)?;
871 let mut noc = None;
872 let mut icac = None;
873 let mut signature = None;
874 let mut resumption_id = None;
875 while let Some((tag, element)) = fields.next()? {
876 match tag {
877 1 => set_once(&mut noc, element.octets()?)?,
878 2 => set_once(&mut icac, element.octets()?)?,
879 3 => set_once(&mut signature, Signature::from_slice(element.octets()?)?)?,
880 4 => set_once(
881 &mut resumption_id,
882 fixed::<RESUMPTION_ID_LEN>(element.octets()?)?,
883 )?,
884 _ => fields.skip(&element)?,
885 }
886 }
887 Ok(Self {
888 noc: noc.ok_or_else(parse_error)?,
889 icac,
890 signature: signature.ok_or_else(parse_error)?,
891 resumption_id,
892 })
893 }
894}
895
896#[derive(Debug, Clone)]
905pub struct ResumptionState {
906 pub shared_secret: Secret<GROUP_SIZE_BYTES>,
909 pub resumption_id: [u8; RESUMPTION_ID_LEN],
911 pub fabric_index: crate::msg::FabricIndex,
913 pub identity: VerifiedIdentity,
915}
916
917#[derive(Debug)]
919pub struct CaseOutcome {
920 pub keys: crate::session::EstablishedKeys,
922 pub peer: VerifiedIdentity,
924 pub peer_session_id: SessionId,
926 pub peer_session_params: Option<SessionParams>,
928 pub resumption: ResumptionState,
930}
931
932impl CaseOutcome {
933 pub fn into_session(
955 &self,
956 local_session_id: SessionId,
957 fabric: &Fabric,
958 randomness: u32,
959 now: crate::platform::Instant,
960 ) -> crate::session::SecureSession {
961 let mut session = crate::session::SecureSession::new(
962 local_session_id,
963 self.peer_session_id,
964 crate::session::SessionKind::Case,
965 crate::session::Role::Responder,
966 self.keys.clone(),
967 randomness,
968 now,
969 );
970 session.role = crate::session::Role::Responder;
971 session.local_node_id = fabric.node_id;
972 session.peer_node_id = self.peer.node_id;
973 session.fabric_index = fabric.index;
974 for cat in &self.peer.cats {
977 let _ = session.peer_cats.push(*cat);
978 }
979 if let Some(params) = self.peer_session_params {
983 session.mrp = params.to_mrp();
984 }
985 session
986 }
987
988 pub fn into_initiator_session(
994 &self,
995 local_session_id: SessionId,
996 fabric: &Fabric,
997 randomness: u32,
998 now: crate::platform::Instant,
999 ) -> crate::session::SecureSession {
1000 let mut session = self.into_session(local_session_id, fabric, randomness, now);
1001 session.role = crate::session::Role::Initiator;
1002 session
1003 }
1004}
1005
1006#[derive(Debug)]
1010pub struct CaseResponder {
1011 session_id: SessionId,
1012 session_params: Option<SessionParams>,
1013 state: ResponderState,
1014}
1015
1016#[expect(
1021 clippy::large_enum_variant,
1022 reason = "no allocator, and the state is transient"
1023)]
1024#[derive(Debug)]
1025enum ResponderState {
1026 AwaitingSigma1,
1027 AwaitingSigma3(Box2),
1028 Done,
1029 Failed,
1030}
1031
1032#[derive(Debug)]
1034struct Box2 {
1035 shared_secret: Secret<GROUP_SIZE_BYTES>,
1036 ipk: SymmetricKey,
1037 transcript: Transcript,
1038 fabric_index: crate::msg::FabricIndex,
1039 fabric_id: crate::msg::FabricId,
1042 initiator_session_id: SessionId,
1043 initiator_session_params: Option<SessionParams>,
1044 initiator_eph_pub_key: PublicKey,
1045 responder_eph_pub_key: PublicKey,
1046 resumption_id: [u8; RESUMPTION_ID_LEN],
1047}
1048
1049impl CaseResponder {
1050 #[must_use]
1052 pub fn new(session_id: SessionId, session_params: Option<SessionParams>) -> Self {
1053 Self {
1054 session_id,
1055 session_params,
1056 state: ResponderState::AwaitingSigma1,
1057 }
1058 }
1059
1060 #[expect(
1071 clippy::too_many_arguments,
1072 reason = "Sigma2 genuinely needs all of this, and bundling it into a struct would \
1073 only move the list somewhere the reader has to go and look for it."
1074 )]
1075 pub fn handle_sigma1<K: KeyStore>(
1076 &mut self,
1077 sigma1: &Sigma1<'_>,
1078 fabric: &Fabric,
1079 noc: &[u8],
1080 icac: Option<&[u8]>,
1081 keys: &mut K,
1082 ephemeral_random: &[u8; GROUP_SIZE_BYTES],
1083 responder_random: &[u8; RANDOM_LEN],
1084 resumption_random: &[u8; RESUMPTION_ID_LEN],
1085 out: &mut [u8],
1086 ) -> Result<usize> {
1087 if !matches!(self.state, ResponderState::AwaitingSigma1) {
1088 self.state = ResponderState::Failed;
1089 bail!(InvalidState)
1090 }
1091 let result = self.build_sigma2(
1092 sigma1,
1093 fabric,
1094 noc,
1095 icac,
1096 keys,
1097 ephemeral_random,
1098 responder_random,
1099 resumption_random,
1100 out,
1101 );
1102 if result.is_err() {
1103 self.state = ResponderState::Failed;
1104 }
1105 result
1106 }
1107
1108 #[expect(clippy::too_many_arguments, reason = "see handle_sigma1")]
1109 fn build_sigma2<K: KeyStore>(
1110 &mut self,
1111 sigma1: &Sigma1<'_>,
1112 fabric: &Fabric,
1113 noc: &[u8],
1114 icac: Option<&[u8]>,
1115 keys: &mut K,
1116 ephemeral_random: &[u8; GROUP_SIZE_BYTES],
1117 responder_random: &[u8; RANDOM_LEN],
1118 resumption_random: &[u8; RESUMPTION_ID_LEN],
1119 out: &mut [u8],
1120 ) -> Result<usize> {
1121 let expected = fabric.destination_identifier(&sigma1.initiator_random)?;
1125 if !ct_eq(&expected, &sigma1.destination_id) {
1126 bail!(CertPathInvalid)
1127 }
1128
1129 let (eph_handle, responder_eph_pub_key) =
1131 keys.generate(KeyPurpose::Ephemeral, ephemeral_random)?;
1132 let shared_secret = keys.ecdh(eph_handle, &sigma1.initiator_eph_pub_key);
1136 keys.remove(eph_handle)?;
1137 let shared_secret = shared_secret?;
1138
1139 let mut transcript = Transcript::new();
1140 transcript.update(sigma1.encoded());
1141 let s2k = sigma2_key(
1142 &shared_secret,
1143 &fabric.ipk,
1144 responder_random,
1145 &responder_eph_pub_key,
1146 &transcript.hash(),
1147 )?;
1148
1149 let mut tbs = [0u8; MAX_TBSDATA];
1151 let tbsdata = encode_tbsdata(
1152 noc,
1153 icac,
1154 &responder_eph_pub_key,
1155 &sigma1.initiator_eph_pub_key,
1156 &mut tbs,
1157 )?;
1158 let signature = keys.sign(fabric.operational_key, tbsdata)?;
1159
1160 let tbe = TbeData {
1161 noc,
1162 icac,
1163 signature,
1164 resumption_id: Some(*resumption_random),
1165 };
1166 let mut encrypted = [0u8; MAX_ENCRYPTED2];
1167 let plaintext_len = tbe.encode(&mut encrypted)?.len();
1168 let encrypted2 = seal(&s2k, &SIGMA2_NONCE, &mut encrypted, plaintext_len)?;
1171
1172 let sigma2 = Sigma2 {
1173 responder_random: *responder_random,
1174 responder_session_id: self.session_id,
1175 responder_eph_pub_key,
1176 encrypted2,
1177 session_params: self.session_params,
1178 encoded: &[],
1179 };
1180 let len = sigma2.encode(out)?.len();
1181 let encoded = out.get(..len).ok_or_else(parse_error)?;
1182 transcript.update(encoded);
1183
1184 self.state = ResponderState::AwaitingSigma3(Box2 {
1185 shared_secret,
1186 ipk: fabric.ipk.clone(),
1187 transcript,
1188 fabric_index: fabric.index,
1189 fabric_id: fabric.fabric_id,
1190 initiator_session_id: sigma1.initiator_session_id,
1191 initiator_session_params: sigma1.session_params,
1192 initiator_eph_pub_key: sigma1.initiator_eph_pub_key,
1193 responder_eph_pub_key,
1194 resumption_id: *resumption_random,
1195 });
1196 Ok(len)
1197 }
1198
1199 pub fn handle_sigma3(
1204 &mut self,
1205 sigma3: &Sigma3<'_>,
1206 root: &MatterCertificate<'_>,
1207 at: Option<u32>,
1208 ) -> Result<CaseOutcome> {
1209 let ResponderState::AwaitingSigma3(state) = &self.state else {
1210 self.state = ResponderState::Failed;
1211 bail!(InvalidState)
1212 };
1213
1214 let mut plaintext = [0u8; MAX_ENCRYPTED3];
1215 let s3k = sigma3_key(&state.shared_secret, &state.ipk, &state.transcript.hash())?;
1216 let decrypted_len = match open(&s3k, &SIGMA3_NONCE, &mut plaintext, sigma3.encrypted3) {
1217 Ok(len) => len,
1218 Err(e) => {
1219 self.state = ResponderState::Failed;
1220 return Err(e);
1221 }
1222 };
1223
1224 let outcome = (|| {
1225 let tbe = TbeData::decode(plaintext.get(..decrypted_len).ok_or_else(parse_error)?)?;
1226 let peer = verify_peer(
1227 &tbe,
1228 root,
1229 at,
1230 state.fabric_id,
1231 None,
1233 &state.initiator_eph_pub_key,
1234 &state.responder_eph_pub_key,
1235 )?;
1236
1237 let mut transcript = state.transcript.clone();
1238 transcript.update(sigma3.encoded());
1239 let keys = session_keys(&state.shared_secret, &state.ipk, &transcript.hash())?;
1240
1241 Ok(CaseOutcome {
1242 keys,
1243 peer: peer.clone(),
1244 peer_session_id: state.initiator_session_id,
1245 peer_session_params: state.initiator_session_params,
1246 resumption: ResumptionState {
1247 shared_secret: state.shared_secret.clone(),
1248 resumption_id: state.resumption_id,
1249 fabric_index: state.fabric_index,
1250 identity: peer,
1251 },
1252 })
1253 })();
1254
1255 self.state = if outcome.is_ok() {
1256 ResponderState::Done
1257 } else {
1258 ResponderState::Failed
1259 };
1260 outcome
1261 }
1262
1263 pub fn finished(&self, out: &mut [u8]) -> Result<usize> {
1265 if !matches!(self.state, ResponderState::Done) {
1266 bail!(InvalidState)
1267 }
1268 StatusReport::secure_channel(SecureChannelCode::SessionEstablishmentSuccess).encode(out)
1269 }
1270
1271 #[must_use]
1273 pub const fn is_failed(&self) -> bool {
1274 matches!(self.state, ResponderState::Failed)
1275 }
1276}
1277
1278#[derive(Debug)]
1282pub struct CaseInitiator {
1283 session_id: SessionId,
1284 session_params: Option<SessionParams>,
1285 state: InitiatorState,
1286}
1287
1288#[expect(
1290 clippy::large_enum_variant,
1291 reason = "no allocator, and the state is transient"
1292)]
1293#[derive(Debug)]
1294enum InitiatorState {
1295 Start,
1296 AwaitingSigma2(Box1),
1297 Done,
1298 Failed,
1299}
1300
1301#[derive(Debug)]
1303struct Box1 {
1304 initiator_random: [u8; RANDOM_LEN],
1305 eph_handle: KeyHandle,
1306 initiator_eph_pub_key: PublicKey,
1307 ipk: SymmetricKey,
1308 fabric_index: crate::msg::FabricIndex,
1309 fabric_id: crate::msg::FabricId,
1311 peer_node_id: crate::msg::NodeId,
1314 transcript: Transcript,
1315}
1316
1317impl CaseInitiator {
1318 #[must_use]
1320 pub fn new(session_id: SessionId, session_params: Option<SessionParams>) -> Self {
1321 Self {
1322 session_id,
1323 session_params,
1324 state: InitiatorState::Start,
1325 }
1326 }
1327
1328 pub fn start<K: KeyStore>(
1330 &mut self,
1331 fabric: &Fabric,
1332 peer_node_id: crate::msg::NodeId,
1333 keys: &mut K,
1334 initiator_random: &[u8; RANDOM_LEN],
1335 ephemeral_random: &[u8; GROUP_SIZE_BYTES],
1336 out: &mut [u8],
1337 ) -> Result<usize> {
1338 if !matches!(self.state, InitiatorState::Start) {
1339 bail!(InvalidState)
1340 }
1341 let destination_id = crate::fabric::destination_identifier(
1344 &fabric.ipk,
1345 initiator_random,
1346 &fabric.root_public_key,
1347 fabric.fabric_id,
1348 peer_node_id,
1349 )?;
1350 let (eph_handle, initiator_eph_pub_key) =
1351 keys.generate(KeyPurpose::Ephemeral, ephemeral_random)?;
1352
1353 let sigma1 = Sigma1 {
1354 initiator_random: *initiator_random,
1355 initiator_session_id: self.session_id,
1356 destination_id,
1357 initiator_eph_pub_key,
1358 session_params: self.session_params,
1359 resumption_id: None,
1360 initiator_resume_mic: None,
1361 encoded: &[],
1362 };
1363 let len = sigma1.encode(out)?.len();
1364 let mut transcript = Transcript::new();
1365 transcript.update(out.get(..len).ok_or_else(parse_error)?);
1366
1367 self.state = InitiatorState::AwaitingSigma2(Box1 {
1368 initiator_random: *initiator_random,
1369 eph_handle,
1370 initiator_eph_pub_key,
1371 ipk: fabric.ipk.clone(),
1372 fabric_index: fabric.index,
1373 fabric_id: fabric.fabric_id,
1374 peer_node_id,
1375 transcript,
1376 });
1377 Ok(len)
1378 }
1379
1380 #[expect(
1386 clippy::too_many_arguments,
1387 reason = "see CaseResponder::handle_sigma1"
1388 )]
1389 pub fn handle_sigma2<K: KeyStore>(
1390 &mut self,
1391 sigma2: &Sigma2<'_>,
1392 fabric: &Fabric,
1393 root: &MatterCertificate<'_>,
1394 noc: &[u8],
1395 icac: Option<&[u8]>,
1396 keys: &mut K,
1397 at: Option<u32>,
1398 out: &mut [u8],
1399 ) -> Result<(usize, CaseOutcome)> {
1400 let result = self.build_sigma3(sigma2, fabric, root, noc, icac, keys, at, out);
1401 if result.is_err() {
1402 if let InitiatorState::AwaitingSigma2(state) = &self.state {
1406 let _ = keys.remove(state.eph_handle);
1407 }
1408 self.state = InitiatorState::Failed;
1409 }
1410 result
1411 }
1412
1413 #[expect(
1414 clippy::too_many_arguments,
1415 reason = "see CaseResponder::handle_sigma1"
1416 )]
1417 fn build_sigma3<K: KeyStore>(
1418 &mut self,
1419 sigma2: &Sigma2<'_>,
1420 fabric: &Fabric,
1421 root: &MatterCertificate<'_>,
1422 noc: &[u8],
1423 icac: Option<&[u8]>,
1424 keys: &mut K,
1425 at: Option<u32>,
1426 out: &mut [u8],
1427 ) -> Result<(usize, CaseOutcome)> {
1428 let InitiatorState::AwaitingSigma2(state) = &self.state else {
1429 bail!(InvalidState)
1430 };
1431
1432 let shared_secret = keys.ecdh(state.eph_handle, &sigma2.responder_eph_pub_key)?;
1433 let s2k = sigma2_key(
1434 &shared_secret,
1435 &state.ipk,
1436 &sigma2.responder_random,
1437 &sigma2.responder_eph_pub_key,
1438 &state.transcript.hash(),
1439 )?;
1440
1441 let mut plaintext = [0u8; MAX_ENCRYPTED2];
1442 let decrypted_len = open(&s2k, &SIGMA2_NONCE, &mut plaintext, sigma2.encrypted2)?;
1443 let tbe = TbeData::decode(plaintext.get(..decrypted_len).ok_or_else(parse_error)?)?;
1444 let peer = verify_peer(
1445 &tbe,
1446 root,
1447 at,
1448 state.fabric_id,
1449 Some(state.peer_node_id),
1450 &sigma2.responder_eph_pub_key,
1451 &state.initiator_eph_pub_key,
1452 )?;
1453 let resumption_id = tbe.resumption_id.ok_or_else(parse_error)?;
1456
1457 let mut transcript = state.transcript.clone();
1458 transcript.update(sigma2.encoded());
1459
1460 let mut tbs = [0u8; MAX_TBSDATA];
1463 let tbsdata = encode_tbsdata(
1464 noc,
1465 icac,
1466 &state.initiator_eph_pub_key,
1467 &sigma2.responder_eph_pub_key,
1468 &mut tbs,
1469 )?;
1470 let signature = keys.sign(fabric.operational_key, tbsdata)?;
1471
1472 let tbe3 = TbeData {
1473 noc,
1474 icac,
1475 signature,
1476 resumption_id: None,
1477 };
1478 let mut encrypted = [0u8; MAX_ENCRYPTED3];
1479 let plaintext_len = tbe3.encode(&mut encrypted)?.len();
1480 let s3k = sigma3_key(&shared_secret, &state.ipk, &transcript.hash())?;
1481 let encrypted3 = seal(&s3k, &SIGMA3_NONCE, &mut encrypted, plaintext_len)?;
1482
1483 let len = Sigma3::encode(encrypted3, out)?.len();
1484 transcript.update(out.get(..len).ok_or_else(parse_error)?);
1485
1486 let session = session_keys(&shared_secret, &state.ipk, &transcript.hash())?;
1487 let fabric_index = state.fabric_index;
1488
1489 keys.remove(state.eph_handle)?;
1490 self.state = InitiatorState::Done;
1491
1492 Ok((
1493 len,
1494 CaseOutcome {
1495 keys: session,
1496 peer: peer.clone(),
1497 peer_session_id: sigma2.responder_session_id,
1498 peer_session_params: sigma2.session_params,
1499 resumption: ResumptionState {
1500 shared_secret,
1501 resumption_id,
1502 fabric_index,
1503 identity: peer,
1504 },
1505 },
1506 ))
1507 }
1508
1509 pub fn accept_finished(&mut self, report: &[u8]) -> Result<()> {
1515 let report = StatusReport::decode(report)?;
1516 if report.is_success()
1517 && report.secure_channel_code() == Some(SecureChannelCode::SessionEstablishmentSuccess)
1518 {
1519 Ok(())
1520 } else {
1521 self.state = InitiatorState::Failed;
1522 Err(Error::new(ErrorCode::InvalidState))
1523 }
1524 }
1525
1526 #[must_use]
1528 pub const fn is_failed(&self) -> bool {
1529 matches!(self.state, InitiatorState::Failed)
1530 }
1531}
1532
1533fn verify_peer(
1552 tbe: &TbeData<'_>,
1553 root: &MatterCertificate<'_>,
1554 at: Option<u32>,
1555 expected_fabric: crate::msg::FabricId,
1556 expected_node: Option<crate::msg::NodeId>,
1557 signer_eph_pub_key: &PublicKey,
1558 peer_eph_pub_key: &PublicKey,
1559) -> Result<VerifiedIdentity> {
1560 let noc = MatterCertificate::decode(tbe.noc)?;
1561 let icac = match tbe.icac {
1562 Some(bytes) => Some(MatterCertificate::decode(bytes)?),
1563 None => None,
1564 };
1565 let identity = verify_chain(&noc, icac.as_ref(), root, at)?;
1568
1569 if identity.fabric_id != expected_fabric {
1570 bail!(CertPathInvalid)
1571 }
1572 if expected_node.is_some_and(|expected| identity.node_id != expected) {
1573 bail!(CertPathInvalid)
1574 }
1575
1576 let mut tbs = [0u8; MAX_TBSDATA];
1577 let tbsdata = encode_tbsdata(
1578 tbe.noc,
1579 tbe.icac,
1580 signer_eph_pub_key,
1581 peer_eph_pub_key,
1582 &mut tbs,
1583 )?;
1584 if !verify(&noc.public_key, tbsdata, &tbe.signature)? {
1585 bail!(CertPathInvalid)
1586 }
1587 Ok(identity)
1588}
1589
1590impl CaseInitiator {
1593 #[expect(
1601 clippy::too_many_arguments,
1602 reason = "see CaseResponder::handle_sigma1"
1603 )]
1604 pub fn start_resumption<K: KeyStore>(
1605 &mut self,
1606 fabric: &Fabric,
1607 peer_node_id: crate::msg::NodeId,
1608 previous: &ResumptionState,
1609 keys: &mut K,
1610 initiator_random: &[u8; RANDOM_LEN],
1611 ephemeral_random: &[u8; GROUP_SIZE_BYTES],
1612 out: &mut [u8],
1613 ) -> Result<usize> {
1614 let len = self.start(
1615 fabric,
1616 peer_node_id,
1617 keys,
1618 initiator_random,
1619 ephemeral_random,
1620 out,
1621 )?;
1622
1623 let s1rk = sigma1_resume_key(
1627 &previous.shared_secret,
1628 initiator_random,
1629 &previous.resumption_id,
1630 )?;
1631 let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
1632 let mic = fixed::<AEAD_MIC_LENGTH_BYTES>(seal(&s1rk, &RESUME1_NONCE, &mut empty, 0)?)?;
1633
1634 let mut sigma1 = Sigma1::decode(out.get(..len).ok_or_else(parse_error)?)?;
1635 sigma1.resumption_id = Some(previous.resumption_id);
1636 sigma1.initiator_resume_mic = Some(mic);
1637
1638 let mut rebuilt = [0u8; MAX_SIGMA1];
1641 let encoded = sigma1.encode(&mut rebuilt)?;
1642 let new_len = encoded.len();
1643 out.get_mut(..new_len)
1644 .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?
1645 .copy_from_slice(encoded);
1646
1647 if let InitiatorState::AwaitingSigma2(state) = &mut self.state {
1650 state.transcript = Transcript::new();
1651 state
1652 .transcript
1653 .update(out.get(..new_len).ok_or_else(parse_error)?);
1654 }
1655 Ok(new_len)
1656 }
1657
1658 pub fn accept_resume<K: KeyStore>(
1664 &mut self,
1665 message: &Sigma2Resume,
1666 previous: &ResumptionState,
1667 keys: &mut K,
1668 ) -> Result<CaseOutcome> {
1669 let InitiatorState::AwaitingSigma2(state) = &self.state else {
1670 bail!(InvalidState)
1671 };
1672 let initiator_random = state.initiator_random;
1673 let eph_handle = state.eph_handle;
1674 let fabric_index = state.fabric_index;
1675
1676 let s2rk = sigma2_resume_key(
1677 &previous.shared_secret,
1678 &initiator_random,
1679 &message.resumption_id,
1680 )?;
1681 let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
1682 if let Err(e) = open(
1683 &s2rk,
1684 &RESUME2_NONCE,
1685 &mut empty,
1686 &message.sigma2_resume_mic,
1687 ) {
1688 let _ = keys.remove(eph_handle);
1690 self.state = InitiatorState::Failed;
1691 return Err(e);
1692 }
1693
1694 let session = resumption_session_keys(
1695 &previous.shared_secret,
1696 &initiator_random,
1697 &message.resumption_id,
1698 )?;
1699 keys.remove(eph_handle)?;
1701 self.state = InitiatorState::Done;
1702
1703 Ok(CaseOutcome {
1704 keys: session,
1705 peer: previous.identity.clone(),
1706 peer_session_id: message.responder_session_id,
1707 peer_session_params: message.session_params,
1708 resumption: ResumptionState {
1709 shared_secret: previous.shared_secret.clone(),
1711 resumption_id: message.resumption_id,
1712 fabric_index,
1713 identity: previous.identity.clone(),
1714 },
1715 })
1716 }
1717}
1718
1719impl CaseResponder {
1720 pub fn handle_sigma1_resumption(
1731 &mut self,
1732 sigma1: &Sigma1<'_>,
1733 previous: &ResumptionState,
1734 resumption_random: &[u8; RESUMPTION_ID_LEN],
1735 out: &mut [u8],
1736 ) -> Result<(usize, CaseOutcome)> {
1737 if !matches!(self.state, ResponderState::AwaitingSigma1) {
1738 bail!(InvalidState)
1739 }
1740 let (Some(offered), Some(mic)) = (sigma1.resumption_id, sigma1.initiator_resume_mic) else {
1741 bail!(InvalidArgument)
1744 };
1745 if !ct_eq(&offered, &previous.resumption_id) {
1746 bail!(InvalidArgument)
1747 }
1748
1749 let s1rk = sigma1_resume_key(
1750 &previous.shared_secret,
1751 &sigma1.initiator_random,
1752 &previous.resumption_id,
1753 )?;
1754 let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
1755 open(&s1rk, &RESUME1_NONCE, &mut empty, &mic)?;
1758
1759 let s2rk = sigma2_resume_key(
1760 &previous.shared_secret,
1761 &sigma1.initiator_random,
1762 resumption_random,
1763 )?;
1764 let mut mic_buf = [0u8; AEAD_MIC_LENGTH_BYTES];
1765 let sigma2_resume_mic =
1766 fixed::<AEAD_MIC_LENGTH_BYTES>(seal(&s2rk, &RESUME2_NONCE, &mut mic_buf, 0)?)?;
1767
1768 let message = Sigma2Resume {
1769 resumption_id: *resumption_random,
1770 sigma2_resume_mic,
1771 responder_session_id: self.session_id,
1772 session_params: self.session_params,
1773 };
1774 let len = message.encode(out)?.len();
1775
1776 let keys = resumption_session_keys(
1777 &previous.shared_secret,
1778 &sigma1.initiator_random,
1779 resumption_random,
1780 )?;
1781 self.state = ResponderState::Done;
1782
1783 Ok((
1784 len,
1785 CaseOutcome {
1786 keys,
1787 peer: previous.identity.clone(),
1788 peer_session_id: sigma1.initiator_session_id,
1789 peer_session_params: sigma1.session_params,
1790 resumption: ResumptionState {
1791 shared_secret: previous.shared_secret.clone(),
1792 resumption_id: *resumption_random,
1793 fabric_index: previous.fabric_index,
1794 identity: previous.identity.clone(),
1795 },
1796 },
1797 ))
1798 }
1799}
1800
1801#[cfg(test)]
1802mod tests {
1803 use super::*;
1804 use crate::sc::SessionParams;
1805
1806 fn a_public_key() -> PublicKey {
1807 let mut k = [0x11u8; PUBLIC_KEY_SIZE_BYTES];
1808 k[0] = 0x04;
1809 PublicKey::from_bytes(k)
1810 }
1811
1812 fn full_sigma1() -> Sigma1<'static> {
1813 Sigma1 {
1814 initiator_random: [1; RANDOM_LEN],
1815 initiator_session_id: SessionId(0x1234),
1816 destination_id: [2; HASH_LEN_BYTES],
1817 initiator_eph_pub_key: a_public_key(),
1818 session_params: Some(SessionParams::announce(
1819 &crate::exchange::MrpParams::default(),
1820 )),
1821 resumption_id: Some([3; RESUMPTION_ID_LEN]),
1822 initiator_resume_mic: Some([4; AEAD_MIC_LENGTH_BYTES]),
1823 encoded: &[],
1824 }
1825 }
1826
1827 #[test]
1828 fn a_nested_structure_does_not_swallow_the_fields_after_it() {
1829 let sigma1 = full_sigma1();
1835 let mut buf = [0u8; MAX_SIGMA1];
1836 let len = sigma1.encode(&mut buf).expect("encode").len();
1837 let mut round = [0u8; MAX_SIGMA1];
1838 round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1839 let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
1840
1841 assert_eq!(decoded.session_params, sigma1.session_params);
1842 assert_eq!(decoded.resumption_id, sigma1.resumption_id);
1843 assert_eq!(decoded.initiator_resume_mic, sigma1.initiator_resume_mic);
1844 assert!(decoded.is_resumption());
1845 }
1846
1847 #[test]
1848 fn a_sigma1_with_session_params_and_no_resumption_still_reads() {
1849 let mut sigma1 = full_sigma1();
1850 sigma1.resumption_id = None;
1851 sigma1.initiator_resume_mic = None;
1852 let mut buf = [0u8; MAX_SIGMA1];
1853 let len = sigma1.encode(&mut buf).expect("encode").len();
1854 let mut round = [0u8; MAX_SIGMA1];
1855 round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1856 let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
1857 assert_eq!(decoded.session_params, sigma1.session_params);
1858 assert!(!decoded.is_resumption());
1859 }
1860
1861 #[test]
1862 fn a_duplicate_tag_is_refused() {
1863 let mut buf = [0u8; MAX_SIGMA1];
1868 let mut w = TlvWriter::new(&mut buf);
1869 w.start_structure(Tag::Anonymous).expect("start");
1870 w.octets(Tag::Context(1), &[1u8; RANDOM_LEN])
1871 .expect("random");
1872 w.unsigned(Tag::Context(2), 1).expect("session id");
1873 w.octets(Tag::Context(3), &[2u8; HASH_LEN_BYTES])
1874 .expect("destination");
1875 w.octets(Tag::Context(4), a_public_key().as_bytes())
1876 .expect("key");
1877 w.octets(Tag::Context(1), &[9u8; RANDOM_LEN])
1879 .expect("duplicate");
1880 w.end_container().expect("end");
1881 let len = w.finish().expect("finish").len();
1882
1883 let mut round = [0u8; MAX_SIGMA1];
1884 round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1885 assert_eq!(
1886 Sigma1::decode(round.get(..len).expect("in range"))
1887 .map(|_| ())
1888 .unwrap_err()
1889 .code(),
1890 ErrorCode::TlvDuplicateTag
1891 );
1892 }
1893
1894 #[test]
1895 fn an_unknown_tag_is_still_skipped() {
1896 let mut buf = [0u8; MAX_SIGMA1];
1900 let mut w = TlvWriter::new(&mut buf);
1901 w.start_structure(Tag::Anonymous).expect("start");
1902 w.octets(Tag::Context(1), &[1u8; RANDOM_LEN])
1903 .expect("random");
1904 w.unsigned(Tag::Context(2), 1).expect("session id");
1905 w.octets(Tag::Context(3), &[2u8; HASH_LEN_BYTES])
1906 .expect("destination");
1907 w.octets(Tag::Context(4), a_public_key().as_bytes())
1908 .expect("key");
1909 w.unsigned(Tag::Context(200), 42)
1910 .expect("a tag from the future");
1911 w.end_container().expect("end");
1912 let len = w.finish().expect("finish").len();
1913
1914 let mut round = [0u8; MAX_SIGMA1];
1915 round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1916 let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
1917 assert_eq!(decoded.initiator_session_id, SessionId(1));
1918 }
1919}