use core::cell::RefCell;
use crate::commissioning::admission::{Admit, PaseAdmission};
use crate::commissioning::window::CommissioningWindow;
use crate::config::Config;
use crate::crypto::{KeyStore, Spake2pVerifierData, SymmetricKey};
use crate::error::Result;
use crate::fabric::FabricTable;
use crate::messaging::{Evicted, Messaging};
use crate::msg::{FabricIndex, SessionId};
use crate::platform::{Instant, Rng};
use crate::sc::status::{SecureChannelCode, StatusReport};
use crate::sc::{
CaseResponder, PaseResponder, PbkdfParameters, ResponderConfig, SessionParams, Sigma1, Sigma3,
opcode,
};
use crate::session::{Role, SecureSession, SessionKind};
pub struct ChannelContext<'a, C: Config, const N: usize, K: KeyStore, R: Rng> {
pub fabrics: &'a RefCell<FabricTable<C, N>>,
pub keys: &'a RefCell<K>,
pub rng: &'a R,
pub window: &'a RefCell<CommissioningWindow>,
pub verifier: &'a Spake2pVerifierData,
pub parameters: &'a PbkdfParameters,
pub now: Instant,
}
pub struct ChannelBuffers<'a> {
pub reply: &'a mut [u8],
pub frame: &'a mut [u8],
pub evict: &'a mut [u8],
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Established {
pub session: SessionId,
pub kind: SessionKind,
pub fabric: FabricIndex,
pub challenge: Option<SymmetricKey>,
}
#[derive(Debug)]
#[non_exhaustive]
pub struct ChannelReply {
pub reply: Option<(u8, usize)>,
pub established: Option<Established>,
pub evicted: Option<Evicted>,
}
impl ChannelReply {
const SILENT: Self = Self {
reply: None,
established: None,
evicted: None,
};
const fn answer(opcode: u8, len: usize) -> Self {
Self {
reply: Some((opcode, len)),
established: None,
evicted: None,
}
}
}
#[derive(Debug)]
pub struct Channel {
admission: PaseAdmission,
pase: Option<PaseResponder>,
pase_local: SessionId,
case: Option<CaseResponder>,
case_local: SessionId,
case_fabric: FabricIndex,
challenge: Option<SymmetricKey>,
}
impl Default for Channel {
fn default() -> Self {
Self::new()
}
}
impl Channel {
#[must_use]
pub const fn new() -> Self {
Self {
admission: PaseAdmission::new(),
pase: None,
pase_local: SessionId(0),
case: None,
case_local: SessionId(0),
case_fabric: FabricIndex::NONE,
challenge: None,
}
}
#[must_use]
pub fn attestation_challenge(&self) -> Option<&SymmetricKey> {
self.challenge.as_ref()
}
#[must_use]
pub const fn is_established(&self) -> bool {
self.admission.is_established()
}
pub const fn reopen(&mut self) {
self.admission.reset();
}
pub fn closed(&mut self, session: SessionId) {
if session == self.pase_local {
self.admission.closed();
self.pase = None;
self.challenge = None;
}
}
pub fn release(&mut self) {
self.admission.closed();
self.pase = None;
}
#[must_use]
pub const fn deadline(&self) -> Option<Instant> {
self.admission.deadline()
}
pub fn poll(&mut self, now: Instant, window: &RefCell<CommissioningWindow>) {
if let Some(failure) = self.admission.poll(now) {
self.pase = None;
if failure.exit_commissioning_mode {
window.borrow_mut().close();
}
}
}
pub fn on_message<C, const S: usize, const X: usize, const N: usize, K, R>(
&mut self,
stack: &mut Messaging<C, S, X>,
opcode: u8,
body: &[u8],
ctx: &ChannelContext<'_, C, N, K, R>,
buffers: &mut ChannelBuffers<'_>,
) -> Result<ChannelReply>
where
C: Config,
K: KeyStore,
R: Rng,
{
match opcode {
opcode::PBKDF_PARAM_REQUEST => self.pbkdf_param_request(body, ctx, buffers.reply),
opcode::PAKE1 => self.pake1(body, ctx, buffers.reply),
opcode::PAKE3 => self.pake3(stack, body, ctx, buffers),
opcode::SIGMA1 => self.sigma1(body, ctx, buffers.reply),
opcode::SIGMA3 => self.sigma3(stack, body, ctx, buffers),
_ => Ok(ChannelReply::SILENT),
}
}
#[expect(
clippy::cast_possible_truncation,
reason = "§4.13.2.4 wants an unpredictable 16-bit local session id; any 16 bits of the draw serve"
)]
fn pbkdf_param_request<C, const N: usize, K, R>(
&mut self,
body: &[u8],
ctx: &ChannelContext<'_, C, N, K, R>,
reply: &mut [u8],
) -> Result<ChannelReply>
where
C: Config,
K: KeyStore,
R: Rng,
{
match self.admission.admit(true, ctx.now) {
Admit::Admitted => {}
refusal => {
let code = if matches!(refusal, Admit::Busy) {
SecureChannelCode::Busy
} else {
SecureChannelCode::InvalidParameter
};
let len = StatusReport::secure_channel(code).encode(reply)?;
return Ok(ChannelReply::answer(opcode::STATUS_REPORT, len));
}
}
let ephemeral = ctx.window.borrow().ephemeral(ctx.now).and_then(|e| {
let verifier = Spake2pVerifierData::from_bytes(&e.verifier).ok()?;
let parameters = PbkdfParameters::new(e.iterations, &e.salt).ok()?;
Some((verifier, parameters))
});
let (verifier, parameters) = match ephemeral {
Some(pair) => pair,
None => (*ctx.verifier, ctx.parameters.clone()),
};
let mut responder = PaseResponder::new(
ResponderConfig {
verifier,
parameters,
session_params: Some(SessionParams::default()),
},
SessionId(ctx.rng.next_u32()? as u16 | 1),
);
let mut random = [0u8; 32];
ctx.rng.fill(&mut random)?;
match responder.on_pbkdf_param_request(body, &random, reply) {
Ok(len) => {
self.pase_local = responder.local_session_id();
self.pase = Some(responder);
Ok(ChannelReply::answer(opcode::PBKDF_PARAM_RESPONSE, len))
}
Err(e) => {
self.fail(ctx.window);
Err(e)
}
}
}
fn pake1<C, const N: usize, K, R>(
&mut self,
body: &[u8],
ctx: &ChannelContext<'_, C, N, K, R>,
reply: &mut [u8],
) -> Result<ChannelReply>
where
C: Config,
K: KeyStore,
R: Rng,
{
let Some(pase) = self.pase.as_mut() else {
return Ok(ChannelReply::SILENT);
};
let mut random = [0u8; 32];
ctx.rng.fill(&mut random)?;
match pase.on_pake1(body, &random, reply) {
Ok(len) => Ok(ChannelReply::answer(opcode::PAKE2, len)),
Err(e) => {
self.fail(ctx.window);
Err(e)
}
}
}
fn pake3<C, const S: usize, const X: usize, const N: usize, K, R>(
&mut self,
stack: &mut Messaging<C, S, X>,
body: &[u8],
ctx: &ChannelContext<'_, C, N, K, R>,
buffers: &mut ChannelBuffers<'_>,
) -> Result<ChannelReply>
where
C: Config,
K: KeyStore,
R: Rng,
{
let Some(pase) = self.pase.as_mut() else {
return Ok(ChannelReply::SILENT);
};
let (len, keys) = match pase.on_pake3(body, buffers.reply) {
Ok(pair) => pair,
Err(e) => {
self.fail(ctx.window);
return Err(e);
}
};
let challenge = keys.attestation_challenge.clone();
let session = SecureSession::new(
self.pase_local,
pase.peer_session_id(),
SessionKind::Pase,
Role::Responder,
keys,
ctx.rng.next_u32()?,
ctx.now,
);
let evicted = match stack.install_session(
session,
ctx.now,
ctx.rng.next_u32()?,
buffers.frame,
buffers.evict,
) {
Ok(evicted) => evicted,
Err(e) => {
self.fail(ctx.window);
return Err(e);
}
};
self.challenge = Some(challenge.clone());
self.admission.established();
Ok(ChannelReply {
reply: Some((opcode::STATUS_REPORT, len)),
established: Some(Established {
session: self.pase_local,
kind: SessionKind::Pase,
fabric: FabricIndex::NONE,
challenge: Some(challenge),
}),
evicted,
})
}
#[expect(
clippy::cast_possible_truncation,
reason = "§4.13.2.4 wants an unpredictable 16-bit local session id; any 16 bits of the draw serve"
)]
fn sigma1<C, const N: usize, K, R>(
&mut self,
body: &[u8],
ctx: &ChannelContext<'_, C, N, K, R>,
reply: &mut [u8],
) -> Result<ChannelReply>
where
C: Config,
K: KeyStore,
R: Rng,
{
let local = SessionId(ctx.rng.next_u32()? as u16 | 1);
let mut responder_random = [0u8; 32];
let mut ephemeral = [0u8; 32];
let mut resumption = [0u8; 16];
ctx.rng.fill(&mut responder_random)?;
ctx.rng.fill(&mut ephemeral)?;
ctx.rng.fill(&mut resumption)?;
let accepted = Sigma1::decode(body).and_then(|sigma1| {
super::case::accept_sigma1(
&sigma1,
&ctx.fabrics.borrow(),
&mut *ctx.keys.borrow_mut(),
local,
Some(SessionParams::default()),
&super::case::Sigma2Randomness {
ephemeral: &ephemeral,
responder: &responder_random,
resumption: &resumption,
},
reply,
)
});
match accepted {
Ok((responder, fabric, len)) => {
self.case_local = local;
self.case_fabric = fabric;
self.case = Some(responder);
Ok(ChannelReply::answer(opcode::SIGMA2, len))
}
Err(_) => {
self.case = None;
let len = StatusReport::secure_channel(SecureChannelCode::NoSharedTrustRoots)
.encode(reply)?;
Ok(ChannelReply::answer(opcode::STATUS_REPORT, len))
}
}
}
fn sigma3<C, const S: usize, const X: usize, const N: usize, K, R>(
&mut self,
stack: &mut Messaging<C, S, X>,
body: &[u8],
ctx: &ChannelContext<'_, C, N, K, R>,
buffers: &mut ChannelBuffers<'_>,
) -> Result<ChannelReply>
where
C: Config,
K: KeyStore,
R: Rng,
{
let Some(responder) = self.case.as_mut() else {
return Ok(ChannelReply::SILENT);
};
let accepted = Sigma3::decode(body).and_then(|sigma3| {
responder.accept_sigma3(
&sigma3,
&ctx.fabrics.borrow(),
self.case_fabric,
None,
buffers.reply,
)
});
let (outcome, len) = match accepted {
Ok(pair) => pair,
Err(e) => {
self.case = None;
return Err(e);
}
};
let fabric = ctx
.fabrics
.borrow()
.iter()
.find(|f| f.fabric_id == outcome.peer.fabric_id)
.cloned();
let Some(fabric) = fabric else {
self.case = None;
return Ok(ChannelReply::answer(opcode::STATUS_REPORT, len));
};
let index = fabric.index;
let session = outcome.into_session(self.case_local, &fabric, ctx.rng.next_u32()?, ctx.now);
let evicted = stack.install_session(
session,
ctx.now,
ctx.rng.next_u32()?,
buffers.frame,
buffers.evict,
)?;
self.case = None;
Ok(ChannelReply {
reply: Some((opcode::STATUS_REPORT, len)),
established: Some(Established {
session: self.case_local,
kind: SessionKind::Case,
fabric: index,
challenge: None,
}),
evicted,
})
}
fn fail(&mut self, window: &RefCell<CommissioningWindow>) {
self.pase = None;
if self.admission.failed().exit_commissioning_mode {
window.borrow_mut().close();
}
}
}