Skip to content

Commit

Permalink
ConnId: Grow to store more legal values (and process them)
Browse files Browse the repository at this point in the history
  • Loading branch information
chrysn committed Nov 4, 2024
1 parent 13886f0 commit 78c4004
Showing 1 changed file with 72 additions and 21 deletions.
93 changes: 72 additions & 21 deletions shared/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ pub const ENC_STRUCTURE_LEN: usize = 8 + 5 + SHA256_DIGEST_LEN; // 8 for ENCRYPT

pub const MAX_EAD_SIZE_LEN: usize = SCALE_FACTOR * 64;

/// Maximum length of a [`ConnId`] (`C_x`).
///
/// This length includes the leading CBOR encoding byte.
///
/// This needs to be <= 24; allowing longer connection identifiers requires extending [`ConnId`]'s
/// invariants to also allow more than one leading byte, and [`ConnIdType`] to extend its
/// processing.
const MAX_CONNID_ENCODED_LEN: usize = 8;

pub type BytesSuites = [u8; SUITES_LEN];
pub type BytesSupportedSuites = [u8; SUPPORTED_SUITES_LEN];
pub const EDHOC_SUITES: BytesSuites = [0, 1, 2, 3, 4, 5, 6, 24, 25]; // all but private cipher suites
Expand Down Expand Up @@ -124,13 +133,35 @@ pub type EADMessageBuffer = EdhocMessageBuffer; // TODO: make it of size MAX_EAD
///
/// Semantically, this is a byte string of some length.
///
/// This currently only supports numeric values (see
/// https://github.com/openwsn-berkeley/lakers/issues/258), but may support larger values in the
/// future.
/// Its legal values are constrained to only contain a single CBOR item that is either a byte
/// string or a number in -24..=23, all in preferred encoding.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
// TODO: This should not be needed, there is nothing special about the value 0.
#[derive(Default)]
pub struct ConnId(u8);
pub struct ConnId([u8; MAX_CONNID_ENCODED_LEN]);

enum ConnIdType {
SingleByte,
ByteString(usize),
}

impl ConnIdType {
fn classify(byte: u8) -> Option<Self> {
if byte >> 5 <= 1 && byte & 0x1f < 24 {
return Some(ConnIdType::SingleByte);
} else if byte >> 5 == 2 && byte & 0x1f < 24 {
return Some(ConnIdType::ByteString((byte & 0x1f).into()));
}
None
}

fn length(&self) -> usize {
match self {
ConnIdType::SingleByte => 1,
ConnIdType::ByteString(n) => 1 + n,
}
}
}

impl ConnId {
/// Construct a ConnId from the result of [`cbor_decoder::int_raw`], which is a
Expand All @@ -141,7 +172,16 @@ impl ConnId {
pub const fn from_int_raw(raw: u8) -> Self {
debug_assert!(raw >> 5 <= 1, "Major type is not an integer");
debug_assert!(raw & 0x1f < 24, "Value is not immediate");
Self(raw)
let mut s = [0; MAX_CONNID_ENCODED_LEN];
s[0] = raw;
Self(s)
}

fn classify(&self) -> ConnIdType {
let Some(t) = ConnIdType::classify(self.0[0]) else {
unreachable!("Type invariant requires valid classification")
};
t
}

/// Read a connection identifier from a given decoder.
Expand All @@ -150,12 +190,20 @@ impl ConnId {
/// exceed the maximum allowed ConnId length, or to contain a byte string that should have been
/// encoded as a small integer.
pub fn from_decoder(decoder: &mut CBORDecoder<'_>) -> Result<Self, CBORError> {
Ok(Self(decoder.int_raw()?))
let mut s = [0; MAX_CONNID_ENCODED_LEN];
let len = ConnIdType::classify(decoder.current()?)
.ok_or(CBORError::DecodingError)?
.length();
s[..len].copy_from_slice(decoder.read_slice(len)?);
Ok(Self(s))
}

/// The bytes that form the identifier (an arbitrary byte string)
pub fn as_slice(&self) -> &[u8] {
core::slice::from_ref(&self.0)
match self.classify() {
ConnIdType::SingleByte => &self.0[..1],
ConnIdType::ByteString(n) => &self.0[1..1 + n],
}
}

/// The CBOR encoding of the identifier.
Expand All @@ -171,13 +219,13 @@ impl ConnId {
///
/// For other IDs, this contains an extra byte header (but those are currently unsupported):
///
/// ```should_panic
/// ```
/// # use lakers_shared::ConnId;
/// let c_i = ConnId::from_slice(&[0xff]).unwrap();
/// assert_eq!(c_i.as_cbor(), &[0x41, 0xff]);
/// ```
pub fn as_cbor(&self) -> &[u8] {
core::slice::from_ref(&self.0)
&self.0[..self.classify().length()]
}

/// Try to construct a ConnId from a slice.
Expand All @@ -191,20 +239,23 @@ impl ConnId {
/// let c_i = ConnId::from_slice(c_i).unwrap();
/// assert!(c_i.as_slice() == &[0x04]);
///
/// // So far, longer slices are unsupported
/// assert!(ConnId::from_slice(&[0x12, 0x34]).is_none());
/// let long = ConnId::from_slice(&[0x12, 0x34]).unwrap();
/// assert!(long.as_slice() == &[0x12, 0x34]);
/// ```
pub fn from_slice(input: &[u8]) -> Option<Self> {
if input.len() != 1 {
return None;
}
if input[0] >> 5 > 1 {
return None;
}
if input[0] & 0x1f >= 24 {
return None;
let mut s = [0; MAX_CONNID_ENCODED_LEN];
if let &[single_byte] = input {
if matches!(
ConnIdType::classify(single_byte),
Some(ConnIdType::SingleByte)
) {
s[0] = single_byte;
return Some(Self(s));
}
}
Some(Self(input[0]))
s[0] = input.len() as u8 | 0x40;
s.get_mut(1..1 + input.len())?.copy_from_slice(input);
Some(Self(s))
}
}

Expand Down Expand Up @@ -840,7 +891,7 @@ mod cbor_decoder {
}

/// Consume and return *n* bytes starting at the current position.
fn read_slice(&mut self, n: usize) -> Result<&'a [u8], CBORError> {
pub fn read_slice(&mut self, n: usize) -> Result<&'a [u8], CBORError> {
if let Some(b) = self
.pos
.checked_add(n)
Expand Down

0 comments on commit 78c4004

Please sign in to comment.