use super::header::{Destination, MessageHeader, SessionType};
use super::ids::NodeId;
use crate::crypto::{
AEAD_MIC_LENGTH_BYTES, AEAD_NONCE_LENGTH_BYTES, SymmetricKey, aead_decrypt_in_place,
aead_encrypt_in_place, privacy_key, privacy_xor,
};
use crate::error::{Error, ErrorCode, Result, bail};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionKeys {
pub encryption: SymmetricKey,
pub privacy: SymmetricKey,
}
impl SessionKeys {
pub fn from_encryption_key(encryption: SymmetricKey) -> Result<Self> {
let privacy = privacy_key(&encryption)?;
Ok(Self {
encryption,
privacy,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NonceSource {
Pase,
Case(NodeId),
Group,
}
impl NonceSource {
fn resolve(self, header: &MessageHeader) -> Result<NodeId> {
match self {
Self::Pase => Ok(NodeId::UNSPECIFIED),
Self::Case(id) => Ok(id),
Self::Group => header.source.ok_or(Error::new(ErrorCode::MessageReserved)),
}
}
}
fn nonce(
security_flags: u8,
message_counter: u32,
source: NodeId,
) -> [u8; AEAD_NONCE_LENGTH_BYTES] {
let mut out = [0u8; AEAD_NONCE_LENGTH_BYTES];
out[0] = security_flags;
if let Some(slot) = out.get_mut(1..5) {
slot.copy_from_slice(&message_counter.to_le_bytes());
}
if let Some(slot) = out.get_mut(5..13) {
slot.copy_from_slice(&source.0.to_le_bytes());
}
out
}
fn privacy_nonce(
session_id: u16,
mic: &[u8; AEAD_MIC_LENGTH_BYTES],
) -> Result<[u8; AEAD_NONCE_LENGTH_BYTES]> {
let mut out = [0u8; AEAD_NONCE_LENGTH_BYTES];
let Some(slot) = out.get_mut(..2) else {
bail!(BufferTooSmall)
};
slot.copy_from_slice(&session_id.to_be_bytes());
let (Some(dst), Some(src)) = (out.get_mut(2..13), mic.get(5..16)) else {
bail!(BufferTooSmall)
};
dst.copy_from_slice(src);
Ok(out)
}
const PRIVACY_OFFSET: usize = 4;
fn privacy_len(header: &MessageHeader) -> usize {
let counter = 4usize;
let source = if header.source.is_some() { 8 } else { 0 };
let destination = match header.destination {
Destination::None => 0,
Destination::Node(_) => 8,
Destination::Group(_) => 2,
};
counter.saturating_add(source).saturating_add(destination)
}
pub fn protect(
header: &MessageHeader,
nonce_source: NonceSource,
payload: &[u8],
keys: &SessionKeys,
out: &mut [u8],
) -> Result<usize> {
if header.is_unsecured() {
bail!(InvalidState)
}
if matches!(header.session_type, SessionType::Group) && header.source.is_none() {
bail!(MessageReserved)
}
let header_len = header.encode(out)?;
let source = nonce_source.resolve(header)?;
let n = nonce(security_flags_of(header), header.message_counter, source);
let Some(aad) = out.get(..header_len) else {
bail!(BufferTooSmall)
};
let mut aad_copy = [0u8; MAX_HEADER];
let Some(aad_slot) = aad_copy.get_mut(..header_len) else {
bail!(BufferTooSmall)
};
aad_slot.copy_from_slice(aad);
let cipher_end = header_len
.checked_add(payload.len())
.ok_or(Error::new(ErrorCode::BufferTooSmall))?;
let total = cipher_end
.checked_add(AEAD_MIC_LENGTH_BYTES)
.ok_or(Error::new(ErrorCode::BufferTooSmall))?;
let Some(body) = out.get_mut(header_len..cipher_end) else {
bail!(BufferTooSmall)
};
body.copy_from_slice(payload);
let mut tag = [0u8; AEAD_MIC_LENGTH_BYTES];
aead_encrypt_in_place(&keys.encryption, &n, aad_slot, body, &mut tag)?;
let Some(mic) = out.get_mut(cipher_end..total) else {
bail!(BufferTooSmall)
};
mic.copy_from_slice(&tag);
if header.privacy {
let nonce = privacy_nonce(header.session_id.0, &tag)?;
let end = PRIVACY_OFFSET
.checked_add(privacy_len(header))
.ok_or(Error::new(ErrorCode::BufferTooSmall))?;
let Some(region) = out.get_mut(PRIVACY_OFFSET..end) else {
bail!(BufferTooSmall)
};
privacy_xor(&keys.privacy, &nonce, region)?;
}
Ok(total)
}
const MAX_HEADER: usize = 1 + 2 + 1 + 4 + 8 + 8;
fn security_flags_of(header: &MessageHeader) -> u8 {
let mut bits = match header.session_type {
SessionType::Unicast => 0u8,
SessionType::Group => 1,
};
if header.privacy {
bits |= 0b1000_0000;
}
if header.control {
bits |= 0b0100_0000;
}
bits
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Preview {
pub session_id: super::ids::SessionId,
pub session_type: SessionType,
pub privacy: bool,
pub control: bool,
}
pub fn preview(buf: &[u8]) -> Result<Preview> {
let (Some(&flags), Some(session), Some(&security)) = (buf.first(), buf.get(1..3), buf.get(3))
else {
bail!(MessageTruncated)
};
if (flags >> 4) != super::header::MESSAGE_FORMAT_VERSION {
bail!(UnsupportedVersion)
}
let Ok(id) = <[u8; 2]>::try_from(session) else {
bail!(MessageTruncated)
};
let session_type = match security & 0b11 {
0 => SessionType::Unicast,
1 => SessionType::Group,
_ => bail!(MessageReserved),
};
Ok(Preview {
session_id: super::ids::SessionId(u16::from_le_bytes(id)),
session_type,
privacy: security & 0b1000_0000 != 0,
control: security & 0b0100_0000 != 0,
})
}
pub fn unprotect(
buf: &mut [u8],
keys: &SessionKeys,
nonce_source: NonceSource,
) -> Result<(MessageHeader, core::ops::Range<usize>)> {
let head = preview(buf)?;
if head.privacy {
let total = buf.len();
let mic_start = total
.checked_sub(AEAD_MIC_LENGTH_BYTES)
.ok_or(Error::new(ErrorCode::MessageTruncated))?;
let Some(mic) = buf.get(mic_start..total) else {
bail!(MessageTruncated)
};
let Ok(mic) = <[u8; AEAD_MIC_LENGTH_BYTES]>::try_from(mic) else {
bail!(MessageTruncated)
};
let nonce = privacy_nonce(head.session_id.0, &mic)?;
let Some(&flags) = buf.first() else {
bail!(MessageTruncated)
};
let obfuscated = privacy_len_from_flags(flags)?;
let end = PRIVACY_OFFSET
.checked_add(obfuscated)
.ok_or(Error::new(ErrorCode::MessageTruncated))?;
let Some(region) = buf.get_mut(PRIVACY_OFFSET..end) else {
bail!(MessageTruncated)
};
privacy_xor(&keys.privacy, &nonce, region)?;
}
let (header, rest) = MessageHeader::decode(buf)?;
if header.is_unsecured() {
bail!(InvalidState)
}
match header.session_type {
SessionType::Unicast => {
if matches!(header.destination, Destination::Group(_)) {
bail!(MessageReserved)
}
}
SessionType::Group => {
if matches!(header.destination, Destination::None) || header.source.is_none() {
bail!(MessageReserved)
}
}
}
let header_len = buf.len().saturating_sub(rest.len());
let mut aad = [0u8; MAX_HEADER];
let (Some(aad_slot), Some(header_bytes)) = (aad.get_mut(..header_len), buf.get(..header_len))
else {
bail!(MessageTruncated)
};
aad_slot.copy_from_slice(header_bytes);
let total = buf.len();
let mic_start = total
.checked_sub(AEAD_MIC_LENGTH_BYTES)
.ok_or(Error::new(ErrorCode::MessageTruncated))?;
if mic_start < header_len {
bail!(MessageTruncated)
}
let Some(mic) = buf.get(mic_start..total) else {
bail!(MessageTruncated)
};
let Ok(tag) = <[u8; AEAD_MIC_LENGTH_BYTES]>::try_from(mic) else {
bail!(MessageTruncated)
};
let source = nonce_source.resolve(&header)?;
let n = nonce(security_flags_of(&header), header.message_counter, source);
let Some(body) = buf.get_mut(header_len..mic_start) else {
bail!(MessageTruncated)
};
aead_decrypt_in_place(&keys.encryption, &n, aad_slot, body, &tag)?;
Ok((header, header_len..mic_start))
}
fn privacy_len_from_flags(flags: u8) -> Result<usize> {
let source = if flags & 0b0000_0100 != 0 { 8 } else { 0 };
let destination = match flags & 0b11 {
0 => 0usize,
1 => 8,
2 => 2,
_ => bail!(MessageReserved),
};
Ok(4usize.saturating_add(source).saturating_add(destination))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::msg::{ExchangeId, GroupId, ProtocolHeader, ProtocolId, SessionId};
fn keys() -> SessionKeys {
SessionKeys::from_encryption_key(SymmetricKey::new([0x5A; 16])).expect("derive")
}
fn case_header() -> MessageHeader {
MessageHeader {
session_id: SessionId(0x1234),
message_counter: 0x0102_0304,
..MessageHeader::default()
}
}
#[test]
fn the_nonce_is_table_17() {
let n = nonce(0x80, 0x0A0B_0C0D, NodeId(0x1122_3344_5566_7788));
assert_eq!(
n,
[
0x80, 0x0D, 0x0C, 0x0B, 0x0A, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, ]
);
}
#[test]
fn the_privacy_nonce_matches_the_specs_worked_example() {
let mic = [
0xc5, 0xa0, 0x06, 0x3a, 0xd5, 0xd2, 0x51, 0x81, 0x91, 0x40, 0x0d, 0xd6, 0x8c, 0x5c,
0x16, 0x3b,
];
let n = privacy_nonce(42, &mic).expect("nonce");
assert_eq!(
n,
[
0x00, 0x2a, 0xd2, 0x51, 0x81, 0x91, 0x40, 0x0d, 0xd6, 0x8c, 0x5c, 0x16,
0x3b, ]
);
}
#[test]
fn a_case_message_round_trips() {
let keys = keys();
let header = case_header();
let payload = b"protocol header and payload";
let mut buf = [0u8; 256];
let n = protect(
&header,
NonceSource::Case(NodeId(7)),
payload,
&keys,
&mut buf,
)
.expect("protect");
let (decoded, range) =
unprotect(&mut buf[..n], &keys, NonceSource::Case(NodeId(7))).expect("unprotect");
assert_eq!(decoded, header);
assert_eq!(&buf[range], payload);
}
#[test]
fn a_pase_message_round_trips() {
let keys = keys();
let header = case_header();
let payload = b"pake1";
let mut buf = [0u8; 128];
let n = protect(&header, NonceSource::Pase, payload, &keys, &mut buf).expect("protect");
let (_, range) = unprotect(&mut buf[..n], &keys, NonceSource::Pase).expect("unprotect");
assert_eq!(&buf[range], payload);
}
#[test]
fn the_wrong_nonce_source_does_not_decrypt() {
let keys = keys();
let header = case_header();
let mut buf = [0u8; 128];
let n =
protect(&header, NonceSource::Case(NodeId(7)), b"x", &keys, &mut buf).expect("protect");
assert_eq!(
unprotect(&mut buf[..n], &keys, NonceSource::Pase)
.unwrap_err()
.code(),
ErrorCode::IntegrityCheckFailed
);
}
#[test]
fn a_private_message_round_trips_and_hides_the_counter() {
let keys = keys();
let header = MessageHeader {
privacy: true,
source: Some(NodeId(0x1122_3344_5566_7788)),
destination: Destination::Node(NodeId(9)),
..case_header()
};
let payload = b"obfuscated header, encrypted body";
let mut buf = [0u8; 256];
let n = protect(
&header,
NonceSource::Case(NodeId(0x1122_3344_5566_7788)),
payload,
&keys,
&mut buf,
)
.expect("protect");
assert_ne!(
&buf[4..8],
&header.message_counter.to_le_bytes(),
"the counter should be obfuscated"
);
let head = preview(&buf[..n]).expect("preview");
assert_eq!(head.session_id, header.session_id);
assert!(head.privacy);
let (decoded, range) = unprotect(
&mut buf[..n],
&keys,
NonceSource::Case(NodeId(0x1122_3344_5566_7788)),
)
.expect("unprotect");
assert_eq!(decoded, header);
assert_eq!(&buf[range], payload);
}
#[test]
fn a_group_message_round_trips() {
let keys = keys();
let header = MessageHeader {
session_type: SessionType::Group,
session_id: SessionId(5),
source: Some(NodeId(42)),
destination: Destination::Group(GroupId(7)),
..MessageHeader::default()
};
let mut buf = [0u8; 128];
let n = protect(&header, NonceSource::Group, b"grouped", &keys, &mut buf).expect("protect");
let (decoded, range) =
unprotect(&mut buf[..n], &keys, NonceSource::Group).expect("unprotect");
assert_eq!(decoded.source, Some(NodeId(42)));
assert_eq!(&buf[range], b"grouped");
}
#[test]
fn a_group_message_without_a_source_is_refused() {
let keys = keys();
let header = MessageHeader {
session_type: SessionType::Group,
session_id: SessionId(5),
destination: Destination::Group(GroupId(7)),
..MessageHeader::default()
};
let mut buf = [0u8; 128];
assert_eq!(
protect(&header, NonceSource::Group, b"x", &keys, &mut buf)
.unwrap_err()
.code(),
ErrorCode::MessageReserved
);
}
#[test]
fn an_unsecured_message_cannot_be_protected() {
let keys = keys();
let mut buf = [0u8; 64];
assert_eq!(
protect(
&MessageHeader::default(),
NonceSource::Pase,
b"x",
&keys,
&mut buf
)
.unwrap_err()
.code(),
ErrorCode::InvalidState
);
}
#[test]
fn every_single_bit_flip_is_caught() {
let keys = keys();
let header = case_header();
let mut buf = [0u8; 128];
let n = protect(
&header,
NonceSource::Case(NodeId(7)),
b"payload",
&keys,
&mut buf,
)
.expect("protect");
let original = buf;
for byte in 0..n {
for bit in 0..8u32 {
let mut broken = original;
broken[byte] ^= 1u8 << bit;
let result = unprotect(&mut broken[..n], &keys, NonceSource::Case(NodeId(7)));
assert!(
result.is_err(),
"flipping bit {bit} of octet {byte} went undetected"
);
}
}
}
#[test]
fn the_wrong_key_does_not_decrypt() {
let keys = keys();
let other = SessionKeys::from_encryption_key(SymmetricKey::new([0xA5; 16])).expect("k");
let mut buf = [0u8; 128];
let n = protect(&case_header(), NonceSource::Pase, b"x", &keys, &mut buf).expect("protect");
assert!(unprotect(&mut buf[..n], &other, NonceSource::Pase).is_err());
}
#[test]
fn a_group_id_on_a_unicast_session_is_refused() {
let keys = keys();
let header = MessageHeader {
destination: Destination::Group(GroupId(1)),
..case_header()
};
let mut buf = [0u8; 128];
let n =
protect(&header, NonceSource::Case(NodeId(1)), b"x", &keys, &mut buf).expect("protect");
assert_eq!(
unprotect(&mut buf[..n], &keys, NonceSource::Case(NodeId(1)))
.unwrap_err()
.code(),
ErrorCode::MessageReserved
);
}
#[test]
fn truncation_at_every_length_is_an_error_not_a_panic() {
let keys = keys();
let mut buf = [0u8; 128];
let n = protect(
&case_header(),
NonceSource::Pase,
b"payload",
&keys,
&mut buf,
)
.expect("protect");
for cut in 0..n {
let mut copy = buf;
let _ = unprotect(&mut copy[..cut], &keys, NonceSource::Pase);
}
}
#[test]
fn a_whole_message_round_trips_with_its_protocol_header() {
let keys = keys();
let protocol = ProtocolHeader {
initiator: true,
reliability: true,
exchange_id: ExchangeId(3),
protocol: ProtocolId::SECURE_CHANNEL,
opcode: 0x20,
..ProtocolHeader::default()
};
let mut inner = [0u8; 64];
let inner_len = protocol.encode(&mut inner).expect("encode");
let mut buf = [0u8; 256];
let n = protect(
&case_header(),
NonceSource::Pase,
&inner[..inner_len],
&keys,
&mut buf,
)
.expect("protect");
let (_, range) = unprotect(&mut buf[..n], &keys, NonceSource::Pase).expect("unprotect");
let (decoded, app) = ProtocolHeader::decode(&buf[range]).expect("decode");
assert_eq!(decoded, protocol);
assert!(app.is_empty());
}
#[test]
fn the_preview_refuses_what_the_header_would() {
assert_eq!(
preview(&[]).unwrap_err().code(),
ErrorCode::MessageTruncated
);
assert_eq!(
preview(&[0x10, 0, 0, 0]).unwrap_err().code(),
ErrorCode::UnsupportedVersion
);
assert_eq!(
preview(&[0x00, 0, 0, 0x02]).unwrap_err().code(),
ErrorCode::MessageReserved
);
}
}