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 #[cfg(feature = "rustcrypto")]
1211 pub fn accept_sigma3<C: crate::config::Config, const N: usize>(
1212 &mut self,
1213 sigma3: &Sigma3<'_>,
1214 fabrics: &crate::fabric::FabricTable<C, N>,
1215 fabric: crate::msg::FabricIndex,
1216 at: Option<u32>,
1217 out: &mut [u8],
1218 ) -> Result<(CaseOutcome, usize)> {
1219 let rcac = fabrics
1220 .find(fabric)
1221 .map(|f| f.credentials.rcac.clone())
1222 .ok_or(Error::new(ErrorCode::NoSession))?;
1223 let root = MatterCertificate::decode(&rcac)?;
1224 let outcome = self.handle_sigma3(sigma3, &root, at)?;
1225 let n = self.finished(out)?;
1226 Ok((outcome, n))
1227 }
1228
1229 pub fn handle_sigma3(
1236 &mut self,
1237 sigma3: &Sigma3<'_>,
1238 root: &MatterCertificate<'_>,
1239 at: Option<u32>,
1240 ) -> Result<CaseOutcome> {
1241 let ResponderState::AwaitingSigma3(state) = &self.state else {
1242 self.state = ResponderState::Failed;
1243 bail!(InvalidState)
1244 };
1245
1246 let mut plaintext = [0u8; MAX_ENCRYPTED3];
1247 let s3k = sigma3_key(&state.shared_secret, &state.ipk, &state.transcript.hash())?;
1248 let decrypted_len = match open(&s3k, &SIGMA3_NONCE, &mut plaintext, sigma3.encrypted3) {
1249 Ok(len) => len,
1250 Err(e) => {
1251 self.state = ResponderState::Failed;
1252 return Err(e);
1253 }
1254 };
1255
1256 let outcome = (|| {
1257 let tbe = TbeData::decode(plaintext.get(..decrypted_len).ok_or_else(parse_error)?)?;
1258 let peer = verify_peer(
1259 &tbe,
1260 root,
1261 at,
1262 state.fabric_id,
1263 None,
1265 &state.initiator_eph_pub_key,
1266 &state.responder_eph_pub_key,
1267 )?;
1268
1269 let mut transcript = state.transcript.clone();
1270 transcript.update(sigma3.encoded());
1271 let keys = session_keys(&state.shared_secret, &state.ipk, &transcript.hash())?;
1272
1273 Ok(CaseOutcome {
1274 keys,
1275 peer: peer.clone(),
1276 peer_session_id: state.initiator_session_id,
1277 peer_session_params: state.initiator_session_params,
1278 resumption: ResumptionState {
1279 shared_secret: state.shared_secret.clone(),
1280 resumption_id: state.resumption_id,
1281 fabric_index: state.fabric_index,
1282 identity: peer,
1283 },
1284 })
1285 })();
1286
1287 self.state = if outcome.is_ok() {
1288 ResponderState::Done
1289 } else {
1290 ResponderState::Failed
1291 };
1292 outcome
1293 }
1294
1295 pub fn finished(&self, out: &mut [u8]) -> Result<usize> {
1297 if !matches!(self.state, ResponderState::Done) {
1298 bail!(InvalidState)
1299 }
1300 StatusReport::secure_channel(SecureChannelCode::SessionEstablishmentSuccess).encode(out)
1301 }
1302
1303 #[must_use]
1305 pub const fn is_failed(&self) -> bool {
1306 matches!(self.state, ResponderState::Failed)
1307 }
1308}
1309
1310#[derive(Debug, Clone, Copy)]
1318pub struct Sigma2Randomness<'a> {
1319 pub ephemeral: &'a [u8; GROUP_SIZE_BYTES],
1321 pub responder: &'a [u8; RANDOM_LEN],
1323 pub resumption: &'a [u8; RESUMPTION_ID_LEN],
1325}
1326
1327pub fn accept_sigma1<C: crate::config::Config, const N: usize, K: KeyStore>(
1345 sigma1: &Sigma1<'_>,
1346 fabrics: &crate::fabric::FabricTable<C, N>,
1347 keys: &mut K,
1348 local: SessionId,
1349 session_params: Option<SessionParams>,
1350 randomness: &Sigma2Randomness<'_>,
1351 out: &mut [u8],
1352) -> Result<(CaseResponder, crate::msg::FabricIndex, usize)> {
1353 let Sigma2Randomness {
1354 ephemeral: ephemeral_random,
1355 responder: responder_random,
1356 resumption: resumption_random,
1357 } = randomness;
1358 let fabric = fabrics
1359 .find_by_destination_identifier(&sigma1.initiator_random, &sigma1.destination_id)?
1360 .ok_or(Error::new(ErrorCode::NoSession))?;
1361 let index = fabric.index;
1362 let noc = fabric.credentials.noc.clone();
1363 let icac = fabric.credentials.icac.clone();
1364 let fabric = fabric.clone();
1365
1366 let mut responder = CaseResponder::new(local, session_params);
1367 let n = responder.handle_sigma1(
1368 sigma1,
1369 &fabric,
1370 &noc,
1371 icac.as_deref(),
1372 keys,
1373 ephemeral_random,
1374 responder_random,
1375 resumption_random,
1376 out,
1377 )?;
1378 Ok((responder, index, n))
1379}
1380
1381#[derive(Debug)]
1385pub struct CaseInitiator {
1386 session_id: SessionId,
1387 session_params: Option<SessionParams>,
1388 state: InitiatorState,
1389}
1390
1391#[expect(
1393 clippy::large_enum_variant,
1394 reason = "no allocator, and the state is transient"
1395)]
1396#[derive(Debug)]
1397enum InitiatorState {
1398 Start,
1399 AwaitingSigma2(Box1),
1400 Done,
1401 Failed,
1402}
1403
1404#[derive(Debug)]
1406struct Box1 {
1407 initiator_random: [u8; RANDOM_LEN],
1408 eph_handle: KeyHandle,
1409 initiator_eph_pub_key: PublicKey,
1410 ipk: SymmetricKey,
1411 fabric_index: crate::msg::FabricIndex,
1412 fabric_id: crate::msg::FabricId,
1414 peer_node_id: crate::msg::NodeId,
1417 transcript: Transcript,
1418}
1419
1420impl CaseInitiator {
1421 #[must_use]
1423 pub fn new(session_id: SessionId, session_params: Option<SessionParams>) -> Self {
1424 Self {
1425 session_id,
1426 session_params,
1427 state: InitiatorState::Start,
1428 }
1429 }
1430
1431 pub fn start<K: KeyStore>(
1433 &mut self,
1434 fabric: &Fabric,
1435 peer_node_id: crate::msg::NodeId,
1436 keys: &mut K,
1437 initiator_random: &[u8; RANDOM_LEN],
1438 ephemeral_random: &[u8; GROUP_SIZE_BYTES],
1439 out: &mut [u8],
1440 ) -> Result<usize> {
1441 if !matches!(self.state, InitiatorState::Start) {
1442 bail!(InvalidState)
1443 }
1444 let destination_id = crate::fabric::destination_identifier(
1447 &fabric.ipk,
1448 initiator_random,
1449 &fabric.root_public_key,
1450 fabric.fabric_id,
1451 peer_node_id,
1452 )?;
1453 let (eph_handle, initiator_eph_pub_key) =
1454 keys.generate(KeyPurpose::Ephemeral, ephemeral_random)?;
1455
1456 let sigma1 = Sigma1 {
1457 initiator_random: *initiator_random,
1458 initiator_session_id: self.session_id,
1459 destination_id,
1460 initiator_eph_pub_key,
1461 session_params: self.session_params,
1462 resumption_id: None,
1463 initiator_resume_mic: None,
1464 encoded: &[],
1465 };
1466 let len = sigma1.encode(out)?.len();
1467 let mut transcript = Transcript::new();
1468 transcript.update(out.get(..len).ok_or_else(parse_error)?);
1469
1470 self.state = InitiatorState::AwaitingSigma2(Box1 {
1471 initiator_random: *initiator_random,
1472 eph_handle,
1473 initiator_eph_pub_key,
1474 ipk: fabric.ipk.clone(),
1475 fabric_index: fabric.index,
1476 fabric_id: fabric.fabric_id,
1477 peer_node_id,
1478 transcript,
1479 });
1480 Ok(len)
1481 }
1482
1483 #[expect(
1489 clippy::too_many_arguments,
1490 reason = "see CaseResponder::handle_sigma1"
1491 )]
1492 pub fn handle_sigma2<K: KeyStore>(
1493 &mut self,
1494 sigma2: &Sigma2<'_>,
1495 fabric: &Fabric,
1496 root: &MatterCertificate<'_>,
1497 noc: &[u8],
1498 icac: Option<&[u8]>,
1499 keys: &mut K,
1500 at: Option<u32>,
1501 out: &mut [u8],
1502 ) -> Result<(usize, CaseOutcome)> {
1503 let result = self.build_sigma3(sigma2, fabric, root, noc, icac, keys, at, out);
1504 if result.is_err() {
1505 if let InitiatorState::AwaitingSigma2(state) = &self.state {
1509 let _ = keys.remove(state.eph_handle);
1510 }
1511 self.state = InitiatorState::Failed;
1512 }
1513 result
1514 }
1515
1516 #[expect(
1517 clippy::too_many_arguments,
1518 reason = "see CaseResponder::handle_sigma1"
1519 )]
1520 fn build_sigma3<K: KeyStore>(
1521 &mut self,
1522 sigma2: &Sigma2<'_>,
1523 fabric: &Fabric,
1524 root: &MatterCertificate<'_>,
1525 noc: &[u8],
1526 icac: Option<&[u8]>,
1527 keys: &mut K,
1528 at: Option<u32>,
1529 out: &mut [u8],
1530 ) -> Result<(usize, CaseOutcome)> {
1531 let InitiatorState::AwaitingSigma2(state) = &self.state else {
1532 bail!(InvalidState)
1533 };
1534
1535 let shared_secret = keys.ecdh(state.eph_handle, &sigma2.responder_eph_pub_key)?;
1536 let s2k = sigma2_key(
1537 &shared_secret,
1538 &state.ipk,
1539 &sigma2.responder_random,
1540 &sigma2.responder_eph_pub_key,
1541 &state.transcript.hash(),
1542 )?;
1543
1544 let mut plaintext = [0u8; MAX_ENCRYPTED2];
1545 let decrypted_len = open(&s2k, &SIGMA2_NONCE, &mut plaintext, sigma2.encrypted2)?;
1546 let tbe = TbeData::decode(plaintext.get(..decrypted_len).ok_or_else(parse_error)?)?;
1547 let peer = verify_peer(
1548 &tbe,
1549 root,
1550 at,
1551 state.fabric_id,
1552 Some(state.peer_node_id),
1553 &sigma2.responder_eph_pub_key,
1554 &state.initiator_eph_pub_key,
1555 )?;
1556 let resumption_id = tbe.resumption_id.ok_or_else(parse_error)?;
1559
1560 let mut transcript = state.transcript.clone();
1561 transcript.update(sigma2.encoded());
1562
1563 let mut tbs = [0u8; MAX_TBSDATA];
1566 let tbsdata = encode_tbsdata(
1567 noc,
1568 icac,
1569 &state.initiator_eph_pub_key,
1570 &sigma2.responder_eph_pub_key,
1571 &mut tbs,
1572 )?;
1573 let signature = keys.sign(fabric.operational_key, tbsdata)?;
1574
1575 let tbe3 = TbeData {
1576 noc,
1577 icac,
1578 signature,
1579 resumption_id: None,
1580 };
1581 let mut encrypted = [0u8; MAX_ENCRYPTED3];
1582 let plaintext_len = tbe3.encode(&mut encrypted)?.len();
1583 let s3k = sigma3_key(&shared_secret, &state.ipk, &transcript.hash())?;
1584 let encrypted3 = seal(&s3k, &SIGMA3_NONCE, &mut encrypted, plaintext_len)?;
1585
1586 let len = Sigma3::encode(encrypted3, out)?.len();
1587 transcript.update(out.get(..len).ok_or_else(parse_error)?);
1588
1589 let session = session_keys(&shared_secret, &state.ipk, &transcript.hash())?;
1590 let fabric_index = state.fabric_index;
1591
1592 keys.remove(state.eph_handle)?;
1593 self.state = InitiatorState::Done;
1594
1595 Ok((
1596 len,
1597 CaseOutcome {
1598 keys: session,
1599 peer: peer.clone(),
1600 peer_session_id: sigma2.responder_session_id,
1601 peer_session_params: sigma2.session_params,
1602 resumption: ResumptionState {
1603 shared_secret,
1604 resumption_id,
1605 fabric_index,
1606 identity: peer,
1607 },
1608 },
1609 ))
1610 }
1611
1612 pub fn accept_finished(&mut self, report: &[u8]) -> Result<()> {
1618 let report = StatusReport::decode(report)?;
1619 if report.is_success()
1620 && report.secure_channel_code() == Some(SecureChannelCode::SessionEstablishmentSuccess)
1621 {
1622 Ok(())
1623 } else {
1624 self.state = InitiatorState::Failed;
1625 Err(Error::new(ErrorCode::InvalidState))
1626 }
1627 }
1628
1629 #[must_use]
1631 pub const fn is_failed(&self) -> bool {
1632 matches!(self.state, InitiatorState::Failed)
1633 }
1634}
1635
1636fn verify_peer(
1655 tbe: &TbeData<'_>,
1656 root: &MatterCertificate<'_>,
1657 at: Option<u32>,
1658 expected_fabric: crate::msg::FabricId,
1659 expected_node: Option<crate::msg::NodeId>,
1660 signer_eph_pub_key: &PublicKey,
1661 peer_eph_pub_key: &PublicKey,
1662) -> Result<VerifiedIdentity> {
1663 let noc = MatterCertificate::decode(tbe.noc)?;
1664 let icac = match tbe.icac {
1665 Some(bytes) => Some(MatterCertificate::decode(bytes)?),
1666 None => None,
1667 };
1668 let identity = verify_chain(&noc, icac.as_ref(), root, at)?;
1671
1672 if identity.fabric_id != expected_fabric {
1673 bail!(CertPathInvalid)
1674 }
1675 if expected_node.is_some_and(|expected| identity.node_id != expected) {
1676 bail!(CertPathInvalid)
1677 }
1678
1679 let mut tbs = [0u8; MAX_TBSDATA];
1680 let tbsdata = encode_tbsdata(
1681 tbe.noc,
1682 tbe.icac,
1683 signer_eph_pub_key,
1684 peer_eph_pub_key,
1685 &mut tbs,
1686 )?;
1687 if !verify(&noc.public_key, tbsdata, &tbe.signature)? {
1688 bail!(CertPathInvalid)
1689 }
1690 Ok(identity)
1691}
1692
1693impl CaseInitiator {
1696 #[expect(
1704 clippy::too_many_arguments,
1705 reason = "see CaseResponder::handle_sigma1"
1706 )]
1707 pub fn start_resumption<K: KeyStore>(
1708 &mut self,
1709 fabric: &Fabric,
1710 peer_node_id: crate::msg::NodeId,
1711 previous: &ResumptionState,
1712 keys: &mut K,
1713 initiator_random: &[u8; RANDOM_LEN],
1714 ephemeral_random: &[u8; GROUP_SIZE_BYTES],
1715 out: &mut [u8],
1716 ) -> Result<usize> {
1717 let len = self.start(
1718 fabric,
1719 peer_node_id,
1720 keys,
1721 initiator_random,
1722 ephemeral_random,
1723 out,
1724 )?;
1725
1726 let s1rk = sigma1_resume_key(
1730 &previous.shared_secret,
1731 initiator_random,
1732 &previous.resumption_id,
1733 )?;
1734 let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
1735 let mic = fixed::<AEAD_MIC_LENGTH_BYTES>(seal(&s1rk, &RESUME1_NONCE, &mut empty, 0)?)?;
1736
1737 let mut sigma1 = Sigma1::decode(out.get(..len).ok_or_else(parse_error)?)?;
1738 sigma1.resumption_id = Some(previous.resumption_id);
1739 sigma1.initiator_resume_mic = Some(mic);
1740
1741 let mut rebuilt = [0u8; MAX_SIGMA1];
1744 let encoded = sigma1.encode(&mut rebuilt)?;
1745 let new_len = encoded.len();
1746 out.get_mut(..new_len)
1747 .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?
1748 .copy_from_slice(encoded);
1749
1750 if let InitiatorState::AwaitingSigma2(state) = &mut self.state {
1753 state.transcript = Transcript::new();
1754 state
1755 .transcript
1756 .update(out.get(..new_len).ok_or_else(parse_error)?);
1757 }
1758 Ok(new_len)
1759 }
1760
1761 pub fn accept_resume<K: KeyStore>(
1767 &mut self,
1768 message: &Sigma2Resume,
1769 previous: &ResumptionState,
1770 keys: &mut K,
1771 ) -> Result<CaseOutcome> {
1772 let InitiatorState::AwaitingSigma2(state) = &self.state else {
1773 bail!(InvalidState)
1774 };
1775 let initiator_random = state.initiator_random;
1776 let eph_handle = state.eph_handle;
1777 let fabric_index = state.fabric_index;
1778
1779 let s2rk = sigma2_resume_key(
1780 &previous.shared_secret,
1781 &initiator_random,
1782 &message.resumption_id,
1783 )?;
1784 let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
1785 if let Err(e) = open(
1786 &s2rk,
1787 &RESUME2_NONCE,
1788 &mut empty,
1789 &message.sigma2_resume_mic,
1790 ) {
1791 let _ = keys.remove(eph_handle);
1793 self.state = InitiatorState::Failed;
1794 return Err(e);
1795 }
1796
1797 let session = resumption_session_keys(
1798 &previous.shared_secret,
1799 &initiator_random,
1800 &message.resumption_id,
1801 )?;
1802 keys.remove(eph_handle)?;
1804 self.state = InitiatorState::Done;
1805
1806 Ok(CaseOutcome {
1807 keys: session,
1808 peer: previous.identity.clone(),
1809 peer_session_id: message.responder_session_id,
1810 peer_session_params: message.session_params,
1811 resumption: ResumptionState {
1812 shared_secret: previous.shared_secret.clone(),
1814 resumption_id: message.resumption_id,
1815 fabric_index,
1816 identity: previous.identity.clone(),
1817 },
1818 })
1819 }
1820}
1821
1822impl CaseResponder {
1823 pub fn handle_sigma1_resumption(
1834 &mut self,
1835 sigma1: &Sigma1<'_>,
1836 previous: &ResumptionState,
1837 resumption_random: &[u8; RESUMPTION_ID_LEN],
1838 out: &mut [u8],
1839 ) -> Result<(usize, CaseOutcome)> {
1840 if !matches!(self.state, ResponderState::AwaitingSigma1) {
1841 bail!(InvalidState)
1842 }
1843 let (Some(offered), Some(mic)) = (sigma1.resumption_id, sigma1.initiator_resume_mic) else {
1844 bail!(InvalidArgument)
1847 };
1848 if !ct_eq(&offered, &previous.resumption_id) {
1849 bail!(InvalidArgument)
1850 }
1851
1852 let s1rk = sigma1_resume_key(
1853 &previous.shared_secret,
1854 &sigma1.initiator_random,
1855 &previous.resumption_id,
1856 )?;
1857 let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
1858 open(&s1rk, &RESUME1_NONCE, &mut empty, &mic)?;
1861
1862 let s2rk = sigma2_resume_key(
1863 &previous.shared_secret,
1864 &sigma1.initiator_random,
1865 resumption_random,
1866 )?;
1867 let mut mic_buf = [0u8; AEAD_MIC_LENGTH_BYTES];
1868 let sigma2_resume_mic =
1869 fixed::<AEAD_MIC_LENGTH_BYTES>(seal(&s2rk, &RESUME2_NONCE, &mut mic_buf, 0)?)?;
1870
1871 let message = Sigma2Resume {
1872 resumption_id: *resumption_random,
1873 sigma2_resume_mic,
1874 responder_session_id: self.session_id,
1875 session_params: self.session_params,
1876 };
1877 let len = message.encode(out)?.len();
1878
1879 let keys = resumption_session_keys(
1880 &previous.shared_secret,
1881 &sigma1.initiator_random,
1882 resumption_random,
1883 )?;
1884 self.state = ResponderState::Done;
1885
1886 Ok((
1887 len,
1888 CaseOutcome {
1889 keys,
1890 peer: previous.identity.clone(),
1891 peer_session_id: sigma1.initiator_session_id,
1892 peer_session_params: sigma1.session_params,
1893 resumption: ResumptionState {
1894 shared_secret: previous.shared_secret.clone(),
1895 resumption_id: *resumption_random,
1896 fabric_index: previous.fabric_index,
1897 identity: previous.identity.clone(),
1898 },
1899 },
1900 ))
1901 }
1902}
1903
1904#[cfg(test)]
1905mod tests {
1906 use super::*;
1907 use crate::sc::SessionParams;
1908
1909 fn a_public_key() -> PublicKey {
1910 let mut k = [0x11u8; PUBLIC_KEY_SIZE_BYTES];
1911 k[0] = 0x04;
1912 PublicKey::from_bytes(k)
1913 }
1914
1915 fn full_sigma1() -> Sigma1<'static> {
1916 Sigma1 {
1917 initiator_random: [1; RANDOM_LEN],
1918 initiator_session_id: SessionId(0x1234),
1919 destination_id: [2; HASH_LEN_BYTES],
1920 initiator_eph_pub_key: a_public_key(),
1921 session_params: Some(SessionParams::announce(
1922 &crate::exchange::MrpParams::default(),
1923 )),
1924 resumption_id: Some([3; RESUMPTION_ID_LEN]),
1925 initiator_resume_mic: Some([4; AEAD_MIC_LENGTH_BYTES]),
1926 encoded: &[],
1927 }
1928 }
1929
1930 #[test]
1931 fn a_nested_structure_does_not_swallow_the_fields_after_it() {
1932 let sigma1 = full_sigma1();
1938 let mut buf = [0u8; MAX_SIGMA1];
1939 let len = sigma1.encode(&mut buf).expect("encode").len();
1940 let mut round = [0u8; MAX_SIGMA1];
1941 round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1942 let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
1943
1944 assert_eq!(decoded.session_params, sigma1.session_params);
1945 assert_eq!(decoded.resumption_id, sigma1.resumption_id);
1946 assert_eq!(decoded.initiator_resume_mic, sigma1.initiator_resume_mic);
1947 assert!(decoded.is_resumption());
1948 }
1949
1950 #[test]
1951 fn a_sigma1_with_session_params_and_no_resumption_still_reads() {
1952 let mut sigma1 = full_sigma1();
1953 sigma1.resumption_id = None;
1954 sigma1.initiator_resume_mic = None;
1955 let mut buf = [0u8; MAX_SIGMA1];
1956 let len = sigma1.encode(&mut buf).expect("encode").len();
1957 let mut round = [0u8; MAX_SIGMA1];
1958 round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1959 let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
1960 assert_eq!(decoded.session_params, sigma1.session_params);
1961 assert!(!decoded.is_resumption());
1962 }
1963
1964 #[test]
1965 fn a_duplicate_tag_is_refused() {
1966 let mut buf = [0u8; MAX_SIGMA1];
1971 let mut w = TlvWriter::new(&mut buf);
1972 w.start_structure(Tag::Anonymous).expect("start");
1973 w.octets(Tag::Context(1), &[1u8; RANDOM_LEN])
1974 .expect("random");
1975 w.unsigned(Tag::Context(2), 1).expect("session id");
1976 w.octets(Tag::Context(3), &[2u8; HASH_LEN_BYTES])
1977 .expect("destination");
1978 w.octets(Tag::Context(4), a_public_key().as_bytes())
1979 .expect("key");
1980 w.octets(Tag::Context(1), &[9u8; RANDOM_LEN])
1982 .expect("duplicate");
1983 w.end_container().expect("end");
1984 let len = w.finish().expect("finish").len();
1985
1986 let mut round = [0u8; MAX_SIGMA1];
1987 round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1988 assert_eq!(
1989 Sigma1::decode(round.get(..len).expect("in range"))
1990 .map(|_| ())
1991 .unwrap_err()
1992 .code(),
1993 ErrorCode::TlvDuplicateTag
1994 );
1995 }
1996
1997 #[test]
1998 fn an_unknown_tag_is_still_skipped() {
1999 let mut buf = [0u8; MAX_SIGMA1];
2003 let mut w = TlvWriter::new(&mut buf);
2004 w.start_structure(Tag::Anonymous).expect("start");
2005 w.octets(Tag::Context(1), &[1u8; RANDOM_LEN])
2006 .expect("random");
2007 w.unsigned(Tag::Context(2), 1).expect("session id");
2008 w.octets(Tag::Context(3), &[2u8; HASH_LEN_BYTES])
2009 .expect("destination");
2010 w.octets(Tag::Context(4), a_public_key().as_bytes())
2011 .expect("key");
2012 w.unsigned(Tag::Context(200), 42)
2013 .expect("a tag from the future");
2014 w.end_container().expect("end");
2015 let len = w.finish().expect("finish").len();
2016
2017 let mut round = [0u8; MAX_SIGMA1];
2018 round[..len].copy_from_slice(buf.get(..len).expect("in range"));
2019 let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
2020 assert_eq!(decoded.initiator_session_id, SessionId(1));
2021 }
2022}