use crate::cert::{CERT_TLV_MAX, MatterCertificate, VerifiedIdentity, verify_chain};
use crate::crypto::{
AEAD_MIC_LENGTH_BYTES, AEAD_NONCE_LENGTH_BYTES, GROUP_SIZE_BYTES, HASH_LEN_BYTES, Hasher,
KeyHandle, KeyPurpose, KeyStore, PUBLIC_KEY_SIZE_BYTES, PublicKey, SIGNATURE_LEN_BYTES, Secret,
Signature, SymmetricKey, aead_decrypt_in_place, aead_encrypt_in_place, ct_eq, kdf_key, verify,
};
use crate::error::{Error, ErrorCode, Result, bail};
use crate::fabric::{Fabric, INITIATOR_RANDOM_LEN};
use crate::msg::SessionId;
use crate::sc::status::{SecureChannelCode, StatusReport};
use crate::sc::{Fields, SessionParams};
use crate::tlv::{Tag, TlvWriter, set_once};
pub mod opcode {
pub const SIGMA1: u8 = 0x30;
pub const SIGMA2: u8 = 0x31;
pub const SIGMA3: u8 = 0x32;
pub const SIGMA2_RESUME: u8 = 0x33;
pub const STATUS_REPORT: u8 = 0x40;
}
pub const RANDOM_LEN: usize = INITIATOR_RANDOM_LEN;
pub const RESUMPTION_ID_LEN: usize = 16;
pub const S2K_INFO: &[u8] = b"Sigma2";
pub const S3K_INFO: &[u8] = b"Sigma3";
pub const S1RK_INFO: &[u8] = b"Sigma1_Resume";
pub const S2RK_INFO: &[u8] = b"Sigma2_Resume";
pub const SESSION_KEYS_INFO: &[u8] = crate::session::SESSION_KEYS_INFO;
pub const RESUMPTION_SESSION_KEYS_INFO: &[u8] = b"SessionResumptionKeys";
pub const SIGMA2_NONCE: [u8; AEAD_NONCE_LENGTH_BYTES] = *b"NCASE_Sigma2N";
pub const SIGMA3_NONCE: [u8; AEAD_NONCE_LENGTH_BYTES] = *b"NCASE_Sigma3N";
pub const RESUME1_NONCE: [u8; AEAD_NONCE_LENGTH_BYTES] = *b"NCASE_SigmaS1";
pub const RESUME2_NONCE: [u8; AEAD_NONCE_LENGTH_BYTES] = *b"NCASE_SigmaS2";
const LONG_STRING_HEADER: usize = 4;
const SHORT_STRING_HEADER: usize = 3;
const STRUCTURE_OVERHEAD: usize = 2;
const MAX_TBEDATA2: usize = STRUCTURE_OVERHEAD
+ (2 * (LONG_STRING_HEADER + CERT_TLV_MAX))
+ (SHORT_STRING_HEADER + SIGNATURE_LEN_BYTES)
+ (SHORT_STRING_HEADER + RESUMPTION_ID_LEN);
const MAX_TBEDATA3: usize = STRUCTURE_OVERHEAD
+ (2 * (LONG_STRING_HEADER + CERT_TLV_MAX))
+ (SHORT_STRING_HEADER + SIGNATURE_LEN_BYTES);
pub const MAX_ENCRYPTED2: usize = MAX_TBEDATA2 + AEAD_MIC_LENGTH_BYTES;
pub const MAX_ENCRYPTED3: usize = MAX_TBEDATA3 + AEAD_MIC_LENGTH_BYTES;
pub const MAX_TBSDATA: usize = STRUCTURE_OVERHEAD
+ (2 * (LONG_STRING_HEADER + CERT_TLV_MAX))
+ (2 * (SHORT_STRING_HEADER + PUBLIC_KEY_SIZE_BYTES));
pub const MAX_SIGMA1: usize = RANDOM_LEN
+ HASH_LEN_BYTES
+ PUBLIC_KEY_SIZE_BYTES
+ RESUMPTION_ID_LEN
+ AEAD_MIC_LENGTH_BYTES
+ 64;
pub const MAX_SIGMA2: usize = STRUCTURE_OVERHEAD
+ (SHORT_STRING_HEADER + RANDOM_LEN)
+ 4
+ (SHORT_STRING_HEADER + PUBLIC_KEY_SIZE_BYTES)
+ (LONG_STRING_HEADER + MAX_ENCRYPTED2)
+ MAX_SESSION_PARAMS;
pub const MAX_SIGMA3: usize = STRUCTURE_OVERHEAD + LONG_STRING_HEADER + MAX_ENCRYPTED3;
pub const MAX_SESSION_PARAMS: usize = STRUCTURE_OVERHEAD + (9 * 6);
const _: () = {
assert!(
MAX_ENCRYPTED2
>= 2 + 2 * (4 + CERT_TLV_MAX)
+ (3 + SIGNATURE_LEN_BYTES)
+ (3 + RESUMPTION_ID_LEN)
+ AEAD_MIC_LENGTH_BYTES
);
assert!(
MAX_ENCRYPTED3
>= 2 + 2 * (4 + CERT_TLV_MAX) + (3 + SIGNATURE_LEN_BYTES) + AEAD_MIC_LENGTH_BYTES
);
assert!(MAX_TBSDATA >= 2 + 2 * (4 + CERT_TLV_MAX) + 2 * (3 + PUBLIC_KEY_SIZE_BYTES));
assert!(MAX_SESSION_PARAMS >= 2 + 9 * (1 + 1 + 4));
assert!(
MAX_SIGMA2
>= 2 + (3 + RANDOM_LEN)
+ 4
+ (3 + PUBLIC_KEY_SIZE_BYTES)
+ (4 + MAX_ENCRYPTED2)
+ MAX_SESSION_PARAMS
);
assert!(MAX_SIGMA3 >= 2 + 4 + MAX_ENCRYPTED3);
assert!(MAX_SIGMA2 + 64 <= crate::config::MAX_UDP_MESSAGE);
};
fn parse_error() -> Error {
Error::new(ErrorCode::TlvWrongType)
}
fn seal<'b>(
key: &SymmetricKey,
nonce: &[u8; AEAD_NONCE_LENGTH_BYTES],
buf: &'b mut [u8],
len: usize,
) -> Result<&'b [u8]> {
let end = len
.checked_add(AEAD_MIC_LENGTH_BYTES)
.ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
if buf.len() < end {
bail!(BufferTooSmall)
}
let (plaintext, rest) = buf.split_at_mut(len);
let mut mic = [0u8; AEAD_MIC_LENGTH_BYTES];
aead_encrypt_in_place(key, nonce, &[], plaintext, &mut mic)?;
rest.get_mut(..AEAD_MIC_LENGTH_BYTES)
.ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?
.copy_from_slice(&mic);
buf.get(..end)
.ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))
}
fn open(
key: &SymmetricKey,
nonce: &[u8; AEAD_NONCE_LENGTH_BYTES],
buf: &mut [u8],
sealed: &[u8],
) -> Result<usize> {
let len = sealed
.len()
.checked_sub(AEAD_MIC_LENGTH_BYTES)
.ok_or_else(|| Error::new(ErrorCode::IntegrityCheckFailed))?;
let (body, mic) = sealed.split_at(len);
let mic = <[u8; AEAD_MIC_LENGTH_BYTES]>::try_from(mic)
.map_err(|_| Error::new(ErrorCode::IntegrityCheckFailed))?;
let slot = buf
.get_mut(..len)
.ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
slot.copy_from_slice(body);
aead_decrypt_in_place(key, nonce, &[], slot, &mic)?;
Ok(len)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sigma1<'a> {
pub initiator_random: [u8; RANDOM_LEN],
pub initiator_session_id: SessionId,
pub destination_id: [u8; HASH_LEN_BYTES],
pub initiator_eph_pub_key: PublicKey,
pub session_params: Option<SessionParams>,
pub resumption_id: Option<[u8; RESUMPTION_ID_LEN]>,
pub initiator_resume_mic: Option<[u8; AEAD_MIC_LENGTH_BYTES]>,
encoded: &'a [u8],
}
impl<'a> Sigma1<'a> {
#[must_use]
pub const fn encoded(&self) -> &'a [u8] {
self.encoded
}
#[must_use]
pub const fn is_resumption(&self) -> bool {
self.resumption_id.is_some() && self.initiator_resume_mic.is_some()
}
pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
let mut w = TlvWriter::new(buf);
w.start_structure(Tag::Anonymous)?;
w.octets(Tag::Context(1), &self.initiator_random)?;
w.unsigned(Tag::Context(2), u64::from(self.initiator_session_id.0))?;
w.octets(Tag::Context(3), &self.destination_id)?;
w.octets(Tag::Context(4), self.initiator_eph_pub_key.as_bytes())?;
if let Some(params) = self.session_params {
params.encode(&mut w, Tag::Context(5))?;
}
if let Some(id) = self.resumption_id.as_ref() {
w.octets(Tag::Context(6), id)?;
}
if let Some(mic) = self.initiator_resume_mic.as_ref() {
w.octets(Tag::Context(7), mic)?;
}
w.end_container()?;
w.finish()
}
pub fn decode(buf: &'a [u8]) -> Result<Self> {
let mut fields = Fields::new(buf)?;
let mut initiator_random = None;
let mut initiator_session_id = None;
let mut destination_id = None;
let mut initiator_eph_pub_key = None;
let mut session_params = None;
let mut resumption_id = None;
let mut initiator_resume_mic = None;
while let Some((tag, element)) = fields.next()? {
match tag {
1 => set_once(
&mut initiator_random,
fixed::<RANDOM_LEN>(element.octets()?)?,
)?,
2 => {
let id =
SessionId(u16::try_from(element.unsigned()?).map_err(|_| parse_error())?);
set_once(&mut initiator_session_id, id)?;
}
3 => set_once(
&mut destination_id,
fixed::<HASH_LEN_BYTES>(element.octets()?)?,
)?,
4 => set_once(
&mut initiator_eph_pub_key,
PublicKey::from_slice(element.octets()?)?,
)?,
5 => set_once(&mut session_params, SessionParams::decode(&mut fields)?)?,
6 => set_once(
&mut resumption_id,
fixed::<RESUMPTION_ID_LEN>(element.octets()?)?,
)?,
7 => {
let mic = fixed::<AEAD_MIC_LENGTH_BYTES>(element.octets()?)?;
set_once(&mut initiator_resume_mic, mic)?;
}
_ => fields.skip(&element)?,
}
}
Ok(Self {
initiator_random: initiator_random.ok_or_else(parse_error)?,
initiator_session_id: initiator_session_id.ok_or_else(parse_error)?,
destination_id: destination_id.ok_or_else(parse_error)?,
initiator_eph_pub_key: initiator_eph_pub_key.ok_or_else(parse_error)?,
session_params,
resumption_id,
initiator_resume_mic,
encoded: buf,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sigma2<'a> {
pub responder_random: [u8; RANDOM_LEN],
pub responder_session_id: SessionId,
pub responder_eph_pub_key: PublicKey,
pub encrypted2: &'a [u8],
pub session_params: Option<SessionParams>,
encoded: &'a [u8],
}
impl<'a> Sigma2<'a> {
#[must_use]
pub const fn encoded(&self) -> &'a [u8] {
self.encoded
}
pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
let mut w = TlvWriter::new(buf);
w.start_structure(Tag::Anonymous)?;
w.octets(Tag::Context(1), &self.responder_random)?;
w.unsigned(Tag::Context(2), u64::from(self.responder_session_id.0))?;
w.octets(Tag::Context(3), self.responder_eph_pub_key.as_bytes())?;
w.octets(Tag::Context(4), self.encrypted2)?;
if let Some(params) = self.session_params {
params.encode(&mut w, Tag::Context(5))?;
}
w.end_container()?;
w.finish()
}
pub fn decode(buf: &'a [u8]) -> Result<Self> {
let mut fields = Fields::new(buf)?;
let mut responder_random = None;
let mut responder_session_id = None;
let mut responder_eph_pub_key = None;
let mut encrypted2 = None;
let mut session_params = None;
while let Some((tag, element)) = fields.next()? {
match tag {
1 => set_once(
&mut responder_random,
fixed::<RANDOM_LEN>(element.octets()?)?,
)?,
2 => {
let id =
SessionId(u16::try_from(element.unsigned()?).map_err(|_| parse_error())?);
set_once(&mut responder_session_id, id)?;
}
3 => set_once(
&mut responder_eph_pub_key,
PublicKey::from_slice(element.octets()?)?,
)?,
4 => set_once(&mut encrypted2, element.octets()?)?,
5 => set_once(&mut session_params, SessionParams::decode(&mut fields)?)?,
_ => fields.skip(&element)?,
}
}
Ok(Self {
responder_random: responder_random.ok_or_else(parse_error)?,
responder_session_id: responder_session_id.ok_or_else(parse_error)?,
responder_eph_pub_key: responder_eph_pub_key.ok_or_else(parse_error)?,
encrypted2: encrypted2.ok_or_else(parse_error)?,
session_params,
encoded: buf,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sigma3<'a> {
pub encrypted3: &'a [u8],
encoded: &'a [u8],
}
impl<'a> Sigma3<'a> {
#[must_use]
pub const fn encoded(&self) -> &'a [u8] {
self.encoded
}
pub fn encode<'b>(encrypted3: &[u8], buf: &'b mut [u8]) -> Result<&'b [u8]> {
let mut w = TlvWriter::new(buf);
w.start_structure(Tag::Anonymous)?;
w.octets(Tag::Context(1), encrypted3)?;
w.end_container()?;
w.finish()
}
pub fn decode(buf: &'a [u8]) -> Result<Self> {
let mut fields = Fields::new(buf)?;
let mut encrypted3 = None;
while let Some((tag, element)) = fields.next()? {
match tag {
1 => set_once(&mut encrypted3, element.octets()?)?,
_ => fields.skip(&element)?,
}
}
Ok(Self {
encrypted3: encrypted3.ok_or_else(parse_error)?,
encoded: buf,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sigma2Resume {
pub resumption_id: [u8; RESUMPTION_ID_LEN],
pub sigma2_resume_mic: [u8; AEAD_MIC_LENGTH_BYTES],
pub responder_session_id: SessionId,
pub session_params: Option<SessionParams>,
}
impl Sigma2Resume {
pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
let mut w = TlvWriter::new(buf);
w.start_structure(Tag::Anonymous)?;
w.octets(Tag::Context(1), &self.resumption_id)?;
w.octets(Tag::Context(2), &self.sigma2_resume_mic)?;
w.unsigned(Tag::Context(3), u64::from(self.responder_session_id.0))?;
if let Some(params) = self.session_params {
params.encode(&mut w, Tag::Context(4))?;
}
w.end_container()?;
w.finish()
}
pub fn decode(buf: &[u8]) -> Result<Self> {
let mut fields = Fields::new(buf)?;
let mut resumption_id = None;
let mut sigma2_resume_mic = None;
let mut responder_session_id = None;
let mut session_params = None;
while let Some((tag, element)) = fields.next()? {
match tag {
1 => set_once(
&mut resumption_id,
fixed::<RESUMPTION_ID_LEN>(element.octets()?)?,
)?,
2 => {
let mic = fixed::<AEAD_MIC_LENGTH_BYTES>(element.octets()?)?;
set_once(&mut sigma2_resume_mic, mic)?;
}
3 => {
let id =
SessionId(u16::try_from(element.unsigned()?).map_err(|_| parse_error())?);
set_once(&mut responder_session_id, id)?;
}
4 => set_once(&mut session_params, SessionParams::decode(&mut fields)?)?,
_ => fields.skip(&element)?,
}
}
Ok(Self {
resumption_id: resumption_id.ok_or_else(parse_error)?,
sigma2_resume_mic: sigma2_resume_mic.ok_or_else(parse_error)?,
responder_session_id: responder_session_id.ok_or_else(parse_error)?,
session_params,
})
}
}
pub fn failure_report(code: SecureChannelCode, out: &mut [u8]) -> Result<usize> {
StatusReport::secure_channel(code).encode(out)
}
fn fixed<const N: usize>(bytes: &[u8]) -> Result<[u8; N]> {
<[u8; N]>::try_from(bytes).map_err(|_| parse_error())
}
#[derive(Debug, Clone)]
pub struct Transcript(Hasher);
impl Default for Transcript {
fn default() -> Self {
Self::new()
}
}
impl Transcript {
#[must_use]
pub fn new() -> Self {
Self(Hasher::new())
}
pub fn update(&mut self, message: &[u8]) {
self.0.update(message);
}
#[must_use]
pub fn hash(&self) -> [u8; HASH_LEN_BYTES] {
self.0.clone().finish()
}
}
const S2K_SALT_LEN: usize =
crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES + RANDOM_LEN + PUBLIC_KEY_SIZE_BYTES + HASH_LEN_BYTES;
pub fn sigma2_key(
shared_secret: &Secret<GROUP_SIZE_BYTES>,
ipk: &SymmetricKey,
responder_random: &[u8; RANDOM_LEN],
responder_eph_pub_key: &PublicKey,
transcript_hash: &[u8; HASH_LEN_BYTES],
) -> Result<SymmetricKey> {
let mut salt = [0u8; S2K_SALT_LEN];
let mut at = 0usize;
at = put(&mut salt, at, ipk.as_bytes())?;
at = put(&mut salt, at, responder_random)?;
at = put(&mut salt, at, responder_eph_pub_key.as_bytes())?;
at = put(&mut salt, at, transcript_hash)?;
let salt = salt.get(..at).ok_or_else(parse_error)?;
kdf_key(shared_secret.as_bytes(), salt, S2K_INFO)
}
const IPK_TRANSCRIPT_SALT_LEN: usize = crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES + HASH_LEN_BYTES;
fn ipk_transcript_salt(
ipk: &SymmetricKey,
transcript_hash: &[u8; HASH_LEN_BYTES],
) -> [u8; IPK_TRANSCRIPT_SALT_LEN] {
let mut salt = [0u8; IPK_TRANSCRIPT_SALT_LEN];
let (head, tail) = salt.split_at_mut(crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES);
head.copy_from_slice(ipk.as_bytes());
tail.copy_from_slice(transcript_hash);
salt
}
pub fn sigma3_key(
shared_secret: &Secret<GROUP_SIZE_BYTES>,
ipk: &SymmetricKey,
transcript_hash: &[u8; HASH_LEN_BYTES],
) -> Result<SymmetricKey> {
kdf_key(
shared_secret.as_bytes(),
&ipk_transcript_salt(ipk, transcript_hash),
S3K_INFO,
)
}
const RESUME_SALT_LEN: usize = RANDOM_LEN + RESUMPTION_ID_LEN;
fn resume_salt(
initiator_random: &[u8; RANDOM_LEN],
resumption_id: &[u8; RESUMPTION_ID_LEN],
) -> [u8; RESUME_SALT_LEN] {
let mut salt = [0u8; RESUME_SALT_LEN];
let (head, tail) = salt.split_at_mut(RANDOM_LEN);
head.copy_from_slice(initiator_random);
tail.copy_from_slice(resumption_id);
salt
}
pub fn sigma1_resume_key(
shared_secret: &Secret<GROUP_SIZE_BYTES>,
initiator_random: &[u8; RANDOM_LEN],
resumption_id: &[u8; RESUMPTION_ID_LEN],
) -> Result<SymmetricKey> {
kdf_key(
shared_secret.as_bytes(),
&resume_salt(initiator_random, resumption_id),
S1RK_INFO,
)
}
pub fn sigma2_resume_key(
shared_secret: &Secret<GROUP_SIZE_BYTES>,
initiator_random: &[u8; RANDOM_LEN],
resumption_id: &[u8; RESUMPTION_ID_LEN],
) -> Result<SymmetricKey> {
kdf_key(
shared_secret.as_bytes(),
&resume_salt(initiator_random, resumption_id),
S2RK_INFO,
)
}
pub fn session_keys(
shared_secret: &Secret<GROUP_SIZE_BYTES>,
ipk: &SymmetricKey,
transcript_hash: &[u8; HASH_LEN_BYTES],
) -> Result<crate::session::EstablishedKeys> {
crate::session::EstablishedKeys::derive(
shared_secret.as_bytes(),
&ipk_transcript_salt(ipk, transcript_hash),
)
}
pub fn resumption_session_keys(
shared_secret: &Secret<GROUP_SIZE_BYTES>,
initiator_random: &[u8; RANDOM_LEN],
resumption_id: &[u8; RESUMPTION_ID_LEN],
) -> Result<crate::session::EstablishedKeys> {
crate::session::EstablishedKeys::derive_with_info(
shared_secret.as_bytes(),
&resume_salt(initiator_random, resumption_id),
RESUMPTION_SESSION_KEYS_INFO,
)
}
fn put(buf: &mut [u8], at: usize, src: &[u8]) -> Result<usize> {
let end = at
.checked_add(src.len())
.ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
let Some(slot) = buf.get_mut(at..end) else {
bail!(BufferTooSmall)
};
slot.copy_from_slice(src);
Ok(end)
}
pub fn encode_tbsdata<'b>(
noc: &[u8],
icac: Option<&[u8]>,
own_eph_pub_key: &PublicKey,
peer_eph_pub_key: &PublicKey,
buf: &'b mut [u8],
) -> Result<&'b [u8]> {
let mut w = TlvWriter::new(buf);
w.start_structure(Tag::Anonymous)?;
w.octets(Tag::Context(1), noc)?;
if let Some(icac) = icac {
w.octets(Tag::Context(2), icac)?;
}
w.octets(Tag::Context(3), own_eph_pub_key.as_bytes())?;
w.octets(Tag::Context(4), peer_eph_pub_key.as_bytes())?;
w.end_container()?;
w.finish()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TbeData<'a> {
pub noc: &'a [u8],
pub icac: Option<&'a [u8]>,
pub signature: Signature,
pub resumption_id: Option<[u8; RESUMPTION_ID_LEN]>,
}
impl<'a> TbeData<'a> {
pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
let mut w = TlvWriter::new(buf);
w.start_structure(Tag::Anonymous)?;
w.octets(Tag::Context(1), self.noc)?;
if let Some(icac) = self.icac {
w.octets(Tag::Context(2), icac)?;
}
w.octets(Tag::Context(3), self.signature.as_bytes())?;
if let Some(id) = self.resumption_id.as_ref() {
w.octets(Tag::Context(4), id)?;
}
w.end_container()?;
w.finish()
}
pub fn decode(buf: &'a [u8]) -> Result<Self> {
let mut fields = Fields::new(buf)?;
let mut noc = None;
let mut icac = None;
let mut signature = None;
let mut resumption_id = None;
while let Some((tag, element)) = fields.next()? {
match tag {
1 => set_once(&mut noc, element.octets()?)?,
2 => set_once(&mut icac, element.octets()?)?,
3 => set_once(&mut signature, Signature::from_slice(element.octets()?)?)?,
4 => set_once(
&mut resumption_id,
fixed::<RESUMPTION_ID_LEN>(element.octets()?)?,
)?,
_ => fields.skip(&element)?,
}
}
Ok(Self {
noc: noc.ok_or_else(parse_error)?,
icac,
signature: signature.ok_or_else(parse_error)?,
resumption_id,
})
}
}
#[derive(Debug, Clone)]
pub struct ResumptionState {
pub shared_secret: Secret<GROUP_SIZE_BYTES>,
pub resumption_id: [u8; RESUMPTION_ID_LEN],
pub fabric_index: crate::msg::FabricIndex,
pub identity: VerifiedIdentity,
}
#[derive(Debug)]
pub struct CaseOutcome {
pub keys: crate::session::EstablishedKeys,
pub peer: VerifiedIdentity,
pub peer_session_id: SessionId,
pub peer_session_params: Option<SessionParams>,
pub resumption: ResumptionState,
}
impl CaseOutcome {
pub fn into_session(
&self,
local_session_id: SessionId,
fabric: &Fabric,
randomness: u32,
now: crate::platform::Instant,
) -> crate::session::SecureSession {
let mut session = crate::session::SecureSession::new(
local_session_id,
self.peer_session_id,
crate::session::SessionKind::Case,
crate::session::Role::Responder,
self.keys.clone(),
randomness,
now,
);
session.role = crate::session::Role::Responder;
session.local_node_id = fabric.node_id;
session.peer_node_id = self.peer.node_id;
session.fabric_index = fabric.index;
for cat in &self.peer.cats {
let _ = session.peer_cats.push(*cat);
}
if let Some(params) = self.peer_session_params {
session.mrp = params.to_mrp();
}
session
}
pub fn into_initiator_session(
&self,
local_session_id: SessionId,
fabric: &Fabric,
randomness: u32,
now: crate::platform::Instant,
) -> crate::session::SecureSession {
let mut session = self.into_session(local_session_id, fabric, randomness, now);
session.role = crate::session::Role::Initiator;
session
}
}
#[derive(Debug)]
pub struct CaseResponder {
session_id: SessionId,
session_params: Option<SessionParams>,
state: ResponderState,
}
#[expect(
clippy::large_enum_variant,
reason = "no allocator, and the state is transient"
)]
#[derive(Debug)]
enum ResponderState {
AwaitingSigma1,
AwaitingSigma3(Box2),
Done,
Failed,
}
#[derive(Debug)]
struct Box2 {
shared_secret: Secret<GROUP_SIZE_BYTES>,
ipk: SymmetricKey,
transcript: Transcript,
fabric_index: crate::msg::FabricIndex,
fabric_id: crate::msg::FabricId,
initiator_session_id: SessionId,
initiator_session_params: Option<SessionParams>,
initiator_eph_pub_key: PublicKey,
responder_eph_pub_key: PublicKey,
resumption_id: [u8; RESUMPTION_ID_LEN],
}
impl CaseResponder {
#[must_use]
pub fn new(session_id: SessionId, session_params: Option<SessionParams>) -> Self {
Self {
session_id,
session_params,
state: ResponderState::AwaitingSigma1,
}
}
#[expect(
clippy::too_many_arguments,
reason = "Sigma2 genuinely needs all of this, and bundling it into a struct would \
only move the list somewhere the reader has to go and look for it."
)]
pub fn handle_sigma1<K: KeyStore>(
&mut self,
sigma1: &Sigma1<'_>,
fabric: &Fabric,
noc: &[u8],
icac: Option<&[u8]>,
keys: &mut K,
ephemeral_random: &[u8; GROUP_SIZE_BYTES],
responder_random: &[u8; RANDOM_LEN],
resumption_random: &[u8; RESUMPTION_ID_LEN],
out: &mut [u8],
) -> Result<usize> {
if !matches!(self.state, ResponderState::AwaitingSigma1) {
self.state = ResponderState::Failed;
bail!(InvalidState)
}
let result = self.build_sigma2(
sigma1,
fabric,
noc,
icac,
keys,
ephemeral_random,
responder_random,
resumption_random,
out,
);
if result.is_err() {
self.state = ResponderState::Failed;
}
result
}
#[expect(clippy::too_many_arguments, reason = "see handle_sigma1")]
fn build_sigma2<K: KeyStore>(
&mut self,
sigma1: &Sigma1<'_>,
fabric: &Fabric,
noc: &[u8],
icac: Option<&[u8]>,
keys: &mut K,
ephemeral_random: &[u8; GROUP_SIZE_BYTES],
responder_random: &[u8; RANDOM_LEN],
resumption_random: &[u8; RESUMPTION_ID_LEN],
out: &mut [u8],
) -> Result<usize> {
let expected = fabric.destination_identifier(&sigma1.initiator_random)?;
if !ct_eq(&expected, &sigma1.destination_id) {
bail!(CertPathInvalid)
}
let (eph_handle, responder_eph_pub_key) =
keys.generate(KeyPurpose::Ephemeral, ephemeral_random)?;
let shared_secret = keys.ecdh(eph_handle, &sigma1.initiator_eph_pub_key);
keys.remove(eph_handle)?;
let shared_secret = shared_secret?;
let mut transcript = Transcript::new();
transcript.update(sigma1.encoded());
let s2k = sigma2_key(
&shared_secret,
&fabric.ipk,
responder_random,
&responder_eph_pub_key,
&transcript.hash(),
)?;
let mut tbs = [0u8; MAX_TBSDATA];
let tbsdata = encode_tbsdata(
noc,
icac,
&responder_eph_pub_key,
&sigma1.initiator_eph_pub_key,
&mut tbs,
)?;
let signature = keys.sign(fabric.operational_key, tbsdata)?;
let tbe = TbeData {
noc,
icac,
signature,
resumption_id: Some(*resumption_random),
};
let mut encrypted = [0u8; MAX_ENCRYPTED2];
let plaintext_len = tbe.encode(&mut encrypted)?.len();
let encrypted2 = seal(&s2k, &SIGMA2_NONCE, &mut encrypted, plaintext_len)?;
let sigma2 = Sigma2 {
responder_random: *responder_random,
responder_session_id: self.session_id,
responder_eph_pub_key,
encrypted2,
session_params: self.session_params,
encoded: &[],
};
let len = sigma2.encode(out)?.len();
let encoded = out.get(..len).ok_or_else(parse_error)?;
transcript.update(encoded);
self.state = ResponderState::AwaitingSigma3(Box2 {
shared_secret,
ipk: fabric.ipk.clone(),
transcript,
fabric_index: fabric.index,
fabric_id: fabric.fabric_id,
initiator_session_id: sigma1.initiator_session_id,
initiator_session_params: sigma1.session_params,
initiator_eph_pub_key: sigma1.initiator_eph_pub_key,
responder_eph_pub_key,
resumption_id: *resumption_random,
});
Ok(len)
}
#[cfg(feature = "rustcrypto")]
pub fn accept_sigma3<C: crate::config::Config, const N: usize>(
&mut self,
sigma3: &Sigma3<'_>,
fabrics: &crate::fabric::FabricTable<C, N>,
fabric: crate::msg::FabricIndex,
at: Option<u32>,
out: &mut [u8],
) -> Result<(CaseOutcome, usize)> {
let rcac = fabrics
.find(fabric)
.map(|f| f.credentials.rcac.clone())
.ok_or(Error::new(ErrorCode::NoSession))?;
let root = MatterCertificate::decode(&rcac)?;
let outcome = self.handle_sigma3(sigma3, &root, at)?;
let n = self.finished(out)?;
Ok((outcome, n))
}
pub fn handle_sigma3(
&mut self,
sigma3: &Sigma3<'_>,
root: &MatterCertificate<'_>,
at: Option<u32>,
) -> Result<CaseOutcome> {
let ResponderState::AwaitingSigma3(state) = &self.state else {
self.state = ResponderState::Failed;
bail!(InvalidState)
};
let mut plaintext = [0u8; MAX_ENCRYPTED3];
let s3k = sigma3_key(&state.shared_secret, &state.ipk, &state.transcript.hash())?;
let decrypted_len = match open(&s3k, &SIGMA3_NONCE, &mut plaintext, sigma3.encrypted3) {
Ok(len) => len,
Err(e) => {
self.state = ResponderState::Failed;
return Err(e);
}
};
let outcome = (|| {
let tbe = TbeData::decode(plaintext.get(..decrypted_len).ok_or_else(parse_error)?)?;
let peer = verify_peer(
&tbe,
root,
at,
state.fabric_id,
None,
&state.initiator_eph_pub_key,
&state.responder_eph_pub_key,
)?;
let mut transcript = state.transcript.clone();
transcript.update(sigma3.encoded());
let keys = session_keys(&state.shared_secret, &state.ipk, &transcript.hash())?;
Ok(CaseOutcome {
keys,
peer: peer.clone(),
peer_session_id: state.initiator_session_id,
peer_session_params: state.initiator_session_params,
resumption: ResumptionState {
shared_secret: state.shared_secret.clone(),
resumption_id: state.resumption_id,
fabric_index: state.fabric_index,
identity: peer,
},
})
})();
self.state = if outcome.is_ok() {
ResponderState::Done
} else {
ResponderState::Failed
};
outcome
}
pub fn finished(&self, out: &mut [u8]) -> Result<usize> {
if !matches!(self.state, ResponderState::Done) {
bail!(InvalidState)
}
StatusReport::secure_channel(SecureChannelCode::SessionEstablishmentSuccess).encode(out)
}
#[must_use]
pub const fn is_failed(&self) -> bool {
matches!(self.state, ResponderState::Failed)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Sigma2Randomness<'a> {
pub ephemeral: &'a [u8; GROUP_SIZE_BYTES],
pub responder: &'a [u8; RANDOM_LEN],
pub resumption: &'a [u8; RESUMPTION_ID_LEN],
}
pub fn accept_sigma1<C: crate::config::Config, const N: usize, K: KeyStore>(
sigma1: &Sigma1<'_>,
fabrics: &crate::fabric::FabricTable<C, N>,
keys: &mut K,
local: SessionId,
session_params: Option<SessionParams>,
randomness: &Sigma2Randomness<'_>,
out: &mut [u8],
) -> Result<(CaseResponder, crate::msg::FabricIndex, usize)> {
let Sigma2Randomness {
ephemeral: ephemeral_random,
responder: responder_random,
resumption: resumption_random,
} = randomness;
let fabric = fabrics
.find_by_destination_identifier(&sigma1.initiator_random, &sigma1.destination_id)?
.ok_or(Error::new(ErrorCode::NoSession))?;
let index = fabric.index;
let noc = fabric.credentials.noc.clone();
let icac = fabric.credentials.icac.clone();
let fabric = fabric.clone();
let mut responder = CaseResponder::new(local, session_params);
let n = responder.handle_sigma1(
sigma1,
&fabric,
&noc,
icac.as_deref(),
keys,
ephemeral_random,
responder_random,
resumption_random,
out,
)?;
Ok((responder, index, n))
}
#[derive(Debug)]
pub struct CaseInitiator {
session_id: SessionId,
session_params: Option<SessionParams>,
state: InitiatorState,
}
#[expect(
clippy::large_enum_variant,
reason = "no allocator, and the state is transient"
)]
#[derive(Debug)]
enum InitiatorState {
Start,
AwaitingSigma2(Box1),
Done,
Failed,
}
#[derive(Debug)]
struct Box1 {
initiator_random: [u8; RANDOM_LEN],
eph_handle: KeyHandle,
initiator_eph_pub_key: PublicKey,
ipk: SymmetricKey,
fabric_index: crate::msg::FabricIndex,
fabric_id: crate::msg::FabricId,
peer_node_id: crate::msg::NodeId,
transcript: Transcript,
}
impl CaseInitiator {
#[must_use]
pub fn new(session_id: SessionId, session_params: Option<SessionParams>) -> Self {
Self {
session_id,
session_params,
state: InitiatorState::Start,
}
}
pub fn start<K: KeyStore>(
&mut self,
fabric: &Fabric,
peer_node_id: crate::msg::NodeId,
keys: &mut K,
initiator_random: &[u8; RANDOM_LEN],
ephemeral_random: &[u8; GROUP_SIZE_BYTES],
out: &mut [u8],
) -> Result<usize> {
if !matches!(self.state, InitiatorState::Start) {
bail!(InvalidState)
}
let destination_id = crate::fabric::destination_identifier(
&fabric.ipk,
initiator_random,
&fabric.root_public_key,
fabric.fabric_id,
peer_node_id,
)?;
let (eph_handle, initiator_eph_pub_key) =
keys.generate(KeyPurpose::Ephemeral, ephemeral_random)?;
let sigma1 = Sigma1 {
initiator_random: *initiator_random,
initiator_session_id: self.session_id,
destination_id,
initiator_eph_pub_key,
session_params: self.session_params,
resumption_id: None,
initiator_resume_mic: None,
encoded: &[],
};
let len = sigma1.encode(out)?.len();
let mut transcript = Transcript::new();
transcript.update(out.get(..len).ok_or_else(parse_error)?);
self.state = InitiatorState::AwaitingSigma2(Box1 {
initiator_random: *initiator_random,
eph_handle,
initiator_eph_pub_key,
ipk: fabric.ipk.clone(),
fabric_index: fabric.index,
fabric_id: fabric.fabric_id,
peer_node_id,
transcript,
});
Ok(len)
}
#[expect(
clippy::too_many_arguments,
reason = "see CaseResponder::handle_sigma1"
)]
pub fn handle_sigma2<K: KeyStore>(
&mut self,
sigma2: &Sigma2<'_>,
fabric: &Fabric,
root: &MatterCertificate<'_>,
noc: &[u8],
icac: Option<&[u8]>,
keys: &mut K,
at: Option<u32>,
out: &mut [u8],
) -> Result<(usize, CaseOutcome)> {
let result = self.build_sigma3(sigma2, fabric, root, noc, icac, keys, at, out);
if result.is_err() {
if let InitiatorState::AwaitingSigma2(state) = &self.state {
let _ = keys.remove(state.eph_handle);
}
self.state = InitiatorState::Failed;
}
result
}
#[expect(
clippy::too_many_arguments,
reason = "see CaseResponder::handle_sigma1"
)]
fn build_sigma3<K: KeyStore>(
&mut self,
sigma2: &Sigma2<'_>,
fabric: &Fabric,
root: &MatterCertificate<'_>,
noc: &[u8],
icac: Option<&[u8]>,
keys: &mut K,
at: Option<u32>,
out: &mut [u8],
) -> Result<(usize, CaseOutcome)> {
let InitiatorState::AwaitingSigma2(state) = &self.state else {
bail!(InvalidState)
};
let shared_secret = keys.ecdh(state.eph_handle, &sigma2.responder_eph_pub_key)?;
let s2k = sigma2_key(
&shared_secret,
&state.ipk,
&sigma2.responder_random,
&sigma2.responder_eph_pub_key,
&state.transcript.hash(),
)?;
let mut plaintext = [0u8; MAX_ENCRYPTED2];
let decrypted_len = open(&s2k, &SIGMA2_NONCE, &mut plaintext, sigma2.encrypted2)?;
let tbe = TbeData::decode(plaintext.get(..decrypted_len).ok_or_else(parse_error)?)?;
let peer = verify_peer(
&tbe,
root,
at,
state.fabric_id,
Some(state.peer_node_id),
&sigma2.responder_eph_pub_key,
&state.initiator_eph_pub_key,
)?;
let resumption_id = tbe.resumption_id.ok_or_else(parse_error)?;
let mut transcript = state.transcript.clone();
transcript.update(sigma2.encoded());
let mut tbs = [0u8; MAX_TBSDATA];
let tbsdata = encode_tbsdata(
noc,
icac,
&state.initiator_eph_pub_key,
&sigma2.responder_eph_pub_key,
&mut tbs,
)?;
let signature = keys.sign(fabric.operational_key, tbsdata)?;
let tbe3 = TbeData {
noc,
icac,
signature,
resumption_id: None,
};
let mut encrypted = [0u8; MAX_ENCRYPTED3];
let plaintext_len = tbe3.encode(&mut encrypted)?.len();
let s3k = sigma3_key(&shared_secret, &state.ipk, &transcript.hash())?;
let encrypted3 = seal(&s3k, &SIGMA3_NONCE, &mut encrypted, plaintext_len)?;
let len = Sigma3::encode(encrypted3, out)?.len();
transcript.update(out.get(..len).ok_or_else(parse_error)?);
let session = session_keys(&shared_secret, &state.ipk, &transcript.hash())?;
let fabric_index = state.fabric_index;
keys.remove(state.eph_handle)?;
self.state = InitiatorState::Done;
Ok((
len,
CaseOutcome {
keys: session,
peer: peer.clone(),
peer_session_id: sigma2.responder_session_id,
peer_session_params: sigma2.session_params,
resumption: ResumptionState {
shared_secret,
resumption_id,
fabric_index,
identity: peer,
},
},
))
}
pub fn accept_finished(&mut self, report: &[u8]) -> Result<()> {
let report = StatusReport::decode(report)?;
if report.is_success()
&& report.secure_channel_code() == Some(SecureChannelCode::SessionEstablishmentSuccess)
{
Ok(())
} else {
self.state = InitiatorState::Failed;
Err(Error::new(ErrorCode::InvalidState))
}
}
#[must_use]
pub const fn is_failed(&self) -> bool {
matches!(self.state, InitiatorState::Failed)
}
}
fn verify_peer(
tbe: &TbeData<'_>,
root: &MatterCertificate<'_>,
at: Option<u32>,
expected_fabric: crate::msg::FabricId,
expected_node: Option<crate::msg::NodeId>,
signer_eph_pub_key: &PublicKey,
peer_eph_pub_key: &PublicKey,
) -> Result<VerifiedIdentity> {
let noc = MatterCertificate::decode(tbe.noc)?;
let icac = match tbe.icac {
Some(bytes) => Some(MatterCertificate::decode(bytes)?),
None => None,
};
let identity = verify_chain(&noc, icac.as_ref(), root, at)?;
if identity.fabric_id != expected_fabric {
bail!(CertPathInvalid)
}
if expected_node.is_some_and(|expected| identity.node_id != expected) {
bail!(CertPathInvalid)
}
let mut tbs = [0u8; MAX_TBSDATA];
let tbsdata = encode_tbsdata(
tbe.noc,
tbe.icac,
signer_eph_pub_key,
peer_eph_pub_key,
&mut tbs,
)?;
if !verify(&noc.public_key, tbsdata, &tbe.signature)? {
bail!(CertPathInvalid)
}
Ok(identity)
}
impl CaseInitiator {
#[expect(
clippy::too_many_arguments,
reason = "see CaseResponder::handle_sigma1"
)]
pub fn start_resumption<K: KeyStore>(
&mut self,
fabric: &Fabric,
peer_node_id: crate::msg::NodeId,
previous: &ResumptionState,
keys: &mut K,
initiator_random: &[u8; RANDOM_LEN],
ephemeral_random: &[u8; GROUP_SIZE_BYTES],
out: &mut [u8],
) -> Result<usize> {
let len = self.start(
fabric,
peer_node_id,
keys,
initiator_random,
ephemeral_random,
out,
)?;
let s1rk = sigma1_resume_key(
&previous.shared_secret,
initiator_random,
&previous.resumption_id,
)?;
let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
let mic = fixed::<AEAD_MIC_LENGTH_BYTES>(seal(&s1rk, &RESUME1_NONCE, &mut empty, 0)?)?;
let mut sigma1 = Sigma1::decode(out.get(..len).ok_or_else(parse_error)?)?;
sigma1.resumption_id = Some(previous.resumption_id);
sigma1.initiator_resume_mic = Some(mic);
let mut rebuilt = [0u8; MAX_SIGMA1];
let encoded = sigma1.encode(&mut rebuilt)?;
let new_len = encoded.len();
out.get_mut(..new_len)
.ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?
.copy_from_slice(encoded);
if let InitiatorState::AwaitingSigma2(state) = &mut self.state {
state.transcript = Transcript::new();
state
.transcript
.update(out.get(..new_len).ok_or_else(parse_error)?);
}
Ok(new_len)
}
pub fn accept_resume<K: KeyStore>(
&mut self,
message: &Sigma2Resume,
previous: &ResumptionState,
keys: &mut K,
) -> Result<CaseOutcome> {
let InitiatorState::AwaitingSigma2(state) = &self.state else {
bail!(InvalidState)
};
let initiator_random = state.initiator_random;
let eph_handle = state.eph_handle;
let fabric_index = state.fabric_index;
let s2rk = sigma2_resume_key(
&previous.shared_secret,
&initiator_random,
&message.resumption_id,
)?;
let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
if let Err(e) = open(
&s2rk,
&RESUME2_NONCE,
&mut empty,
&message.sigma2_resume_mic,
) {
let _ = keys.remove(eph_handle);
self.state = InitiatorState::Failed;
return Err(e);
}
let session = resumption_session_keys(
&previous.shared_secret,
&initiator_random,
&message.resumption_id,
)?;
keys.remove(eph_handle)?;
self.state = InitiatorState::Done;
Ok(CaseOutcome {
keys: session,
peer: previous.identity.clone(),
peer_session_id: message.responder_session_id,
peer_session_params: message.session_params,
resumption: ResumptionState {
shared_secret: previous.shared_secret.clone(),
resumption_id: message.resumption_id,
fabric_index,
identity: previous.identity.clone(),
},
})
}
}
impl CaseResponder {
pub fn handle_sigma1_resumption(
&mut self,
sigma1: &Sigma1<'_>,
previous: &ResumptionState,
resumption_random: &[u8; RESUMPTION_ID_LEN],
out: &mut [u8],
) -> Result<(usize, CaseOutcome)> {
if !matches!(self.state, ResponderState::AwaitingSigma1) {
bail!(InvalidState)
}
let (Some(offered), Some(mic)) = (sigma1.resumption_id, sigma1.initiator_resume_mic) else {
bail!(InvalidArgument)
};
if !ct_eq(&offered, &previous.resumption_id) {
bail!(InvalidArgument)
}
let s1rk = sigma1_resume_key(
&previous.shared_secret,
&sigma1.initiator_random,
&previous.resumption_id,
)?;
let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
open(&s1rk, &RESUME1_NONCE, &mut empty, &mic)?;
let s2rk = sigma2_resume_key(
&previous.shared_secret,
&sigma1.initiator_random,
resumption_random,
)?;
let mut mic_buf = [0u8; AEAD_MIC_LENGTH_BYTES];
let sigma2_resume_mic =
fixed::<AEAD_MIC_LENGTH_BYTES>(seal(&s2rk, &RESUME2_NONCE, &mut mic_buf, 0)?)?;
let message = Sigma2Resume {
resumption_id: *resumption_random,
sigma2_resume_mic,
responder_session_id: self.session_id,
session_params: self.session_params,
};
let len = message.encode(out)?.len();
let keys = resumption_session_keys(
&previous.shared_secret,
&sigma1.initiator_random,
resumption_random,
)?;
self.state = ResponderState::Done;
Ok((
len,
CaseOutcome {
keys,
peer: previous.identity.clone(),
peer_session_id: sigma1.initiator_session_id,
peer_session_params: sigma1.session_params,
resumption: ResumptionState {
shared_secret: previous.shared_secret.clone(),
resumption_id: *resumption_random,
fabric_index: previous.fabric_index,
identity: previous.identity.clone(),
},
},
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sc::SessionParams;
fn a_public_key() -> PublicKey {
let mut k = [0x11u8; PUBLIC_KEY_SIZE_BYTES];
k[0] = 0x04;
PublicKey::from_bytes(k)
}
fn full_sigma1() -> Sigma1<'static> {
Sigma1 {
initiator_random: [1; RANDOM_LEN],
initiator_session_id: SessionId(0x1234),
destination_id: [2; HASH_LEN_BYTES],
initiator_eph_pub_key: a_public_key(),
session_params: Some(SessionParams::announce(
&crate::exchange::MrpParams::default(),
)),
resumption_id: Some([3; RESUMPTION_ID_LEN]),
initiator_resume_mic: Some([4; AEAD_MIC_LENGTH_BYTES]),
encoded: &[],
}
}
#[test]
fn a_nested_structure_does_not_swallow_the_fields_after_it() {
let sigma1 = full_sigma1();
let mut buf = [0u8; MAX_SIGMA1];
let len = sigma1.encode(&mut buf).expect("encode").len();
let mut round = [0u8; MAX_SIGMA1];
round[..len].copy_from_slice(buf.get(..len).expect("in range"));
let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
assert_eq!(decoded.session_params, sigma1.session_params);
assert_eq!(decoded.resumption_id, sigma1.resumption_id);
assert_eq!(decoded.initiator_resume_mic, sigma1.initiator_resume_mic);
assert!(decoded.is_resumption());
}
#[test]
fn a_sigma1_with_session_params_and_no_resumption_still_reads() {
let mut sigma1 = full_sigma1();
sigma1.resumption_id = None;
sigma1.initiator_resume_mic = None;
let mut buf = [0u8; MAX_SIGMA1];
let len = sigma1.encode(&mut buf).expect("encode").len();
let mut round = [0u8; MAX_SIGMA1];
round[..len].copy_from_slice(buf.get(..len).expect("in range"));
let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
assert_eq!(decoded.session_params, sigma1.session_params);
assert!(!decoded.is_resumption());
}
#[test]
fn a_duplicate_tag_is_refused() {
let mut buf = [0u8; MAX_SIGMA1];
let mut w = TlvWriter::new(&mut buf);
w.start_structure(Tag::Anonymous).expect("start");
w.octets(Tag::Context(1), &[1u8; RANDOM_LEN])
.expect("random");
w.unsigned(Tag::Context(2), 1).expect("session id");
w.octets(Tag::Context(3), &[2u8; HASH_LEN_BYTES])
.expect("destination");
w.octets(Tag::Context(4), a_public_key().as_bytes())
.expect("key");
w.octets(Tag::Context(1), &[9u8; RANDOM_LEN])
.expect("duplicate");
w.end_container().expect("end");
let len = w.finish().expect("finish").len();
let mut round = [0u8; MAX_SIGMA1];
round[..len].copy_from_slice(buf.get(..len).expect("in range"));
assert_eq!(
Sigma1::decode(round.get(..len).expect("in range"))
.map(|_| ())
.unwrap_err()
.code(),
ErrorCode::TlvDuplicateTag
);
}
#[test]
fn an_unknown_tag_is_still_skipped() {
let mut buf = [0u8; MAX_SIGMA1];
let mut w = TlvWriter::new(&mut buf);
w.start_structure(Tag::Anonymous).expect("start");
w.octets(Tag::Context(1), &[1u8; RANDOM_LEN])
.expect("random");
w.unsigned(Tag::Context(2), 1).expect("session id");
w.octets(Tag::Context(3), &[2u8; HASH_LEN_BYTES])
.expect("destination");
w.octets(Tag::Context(4), a_public_key().as_bytes())
.expect("key");
w.unsigned(Tag::Context(200), 42)
.expect("a tag from the future");
w.end_container().expect("end");
let len = w.finish().expect("finish").len();
let mut round = [0u8; MAX_SIGMA1];
round[..len].copy_from_slice(buf.get(..len).expect("in range"));
let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
assert_eq!(decoded.initiator_session_id, SessionId(1));
}
}