use zeroize::Zeroize;
use crate::app::{Address, Ell, ci};
use crate::crc::crc16;
use crate::oms::{self, Key};
use crate::wireless::{self, Format, control};
use crate::{Error, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Security {
Plain,
Mode5,
Mode7 {
counter: u32,
mac: bool,
},
Mode10 {
counter: u32,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Telegram<'a> {
pub c: u8,
pub address: Address,
pub ell: Option<Ell>,
pub access_number: u8,
pub status: u8,
pub synchronous: bool,
pub security: Security,
pub records: &'a [u8],
pub tail: &'a [u8],
}
impl<'a> Telegram<'a> {
pub const fn new(address: Address, security: Security, records: &'a [u8]) -> Self {
Self {
c: control::SND_NR,
address,
ell: None,
access_number: 0,
status: 0,
synchronous: false,
security,
records,
tail: &[],
}
}
pub fn write(&self, key: &Key, format: Format, out: &mut [u8]) -> Result<usize> {
let mut buf = [0u8; 256];
let result = self.application(key, &mut buf).and_then(|n| {
let (&first_ci, payload) =
buf.get(..n).and_then(<[u8]>::split_first).ok_or(Error::InvalidLength)?;
wireless::encode(format, self.c, &self.address, first_ci, payload, out)
});
buf.zeroize();
result
}
fn application(&self, key: &Key, buf: &mut [u8]) -> Result<usize> {
let mut w = Writer { buf, n: 0 };
let ell_crc = match self.ell {
Some(ell) => ell_header(&ell, &mut w)?,
None => None,
};
let (counter, mac) = match self.security {
Security::Mode7 { counter, mac } => (counter, mac),
Security::Mode10 { counter } => (counter, false),
_ => (0, false),
};
let counter_le = counter.to_le_bytes();
let mut mac_at = None;
if let Security::Mode7 { .. } = self.security {
let (fcl, mcl, len): (u16, u8, u8) = if mac { (0x2C00, 0x25, 15) } else { (0x2800, 0x20, 7) };
w.put(&[ci::AFL, len])?;
w.put(&fcl.to_le_bytes())?;
w.put(&[mcl])?;
w.put(&counter_le)?;
if mac {
mac_at = Some(w.n);
w.put(&[0; 8])?;
}
}
let s = if self.synchronous { 0x20 } else { 0 };
let tpl = w.n;
w.put(&[ci::RSP_SHORT, self.access_number, self.status])?;
match self.security {
Security::Plain => w.put(&[0x00, s])?,
Security::Mode5 | Security::Mode7 { .. } => {
let blocks = (self.records.len() + 2).div_ceil(16);
if blocks > 15 || (blocks == 15 && !self.tail.is_empty()) {
return Err(Error::InvalidLength);
}
let mode = if self.security == Security::Mode5 { 5 } else { 7 };
w.put(&[u8::try_from(blocks << 4).map_err(|_| Error::InvalidLength)?, mode | s])?;
if mode == 7 {
w.put(&[0x10])?;
}
}
Security::Mode10 { .. } => {
let n = u8::try_from(self.records.len())
.ok()
.filter(|&n| n != 0xFF)
.ok_or(Error::InvalidLength)?;
w.put(&[n, 0x0A | s, 0x10, 0x01])?;
w.put(&counter_le)?;
}
}
let data = w.n;
match self.security {
Security::Plain | Security::Mode10 { .. } => w.put(self.records)?,
Security::Mode5 | Security::Mode7 { .. } => {
w.put(&[0x2F, 0x2F])?;
w.put(self.records)?;
while (w.n - data) % 16 != 0 {
w.put(&[0x2F])?;
}
let plain = w.buf.get_mut(data..w.n).ok_or(Error::InvalidLength)?;
if self.security == Security::Mode5 {
let [a, b, c, d, e, f, g, h] = self.address.to_bytes();
let x = self.access_number;
oms::cbc_encrypt(key, &[a, b, c, d, e, f, g, h, x, x, x, x, x, x, x, x], plain)?;
} else {
let kenc = oms::derive(key, 0x00, counter_le, self.address.id);
oms::cbc_encrypt(&kenc, &[0; 16], plain)?;
}
}
}
let encrypted_end = w.n;
w.put(self.tail)?;
if let Security::Mode10 { .. } = self.security {
let mut aad = [0u8; 256];
let header = w.buf.get(tpl..tpl + 7).ok_or(Error::InvalidLength)?;
let tail_len = self.tail.len();
aad.get_mut(..7).ok_or(Error::InvalidLength)?.copy_from_slice(header);
aad.get_mut(7..7 + tail_len).ok_or(Error::InvalidLength)?.copy_from_slice(self.tail);
let kenc = oms::derive(key, 0x00, counter_le, self.address.id);
let [m0, m1, i0, i1, i2, i3, v, t] = self.address.to_bytes();
let [c0, c1, c2, c3] = counter.to_be_bytes();
let nonce = [m0, m1, i0, i1, i2, i3, v, t, 0, c0, c1, c2, c3];
let plain = w.buf.get_mut(data..encrypted_end).ok_or(Error::InvalidLength)?;
let tag = oms::ccm_encrypt(&kenc, &nonce, aad.get(..7 + tail_len).unwrap_or(&[]), plain)?;
w.put(&tag)?;
}
if let Some(at) = mac_at {
let kmac = oms::derive(key, 0x01, counter_le, self.address.id);
let tpl_bytes = w.buf.get(tpl..w.n).ok_or(Error::InvalidLength)?;
let tag = oms::cmac(&kmac, &[&[0x25], &counter_le, tpl_bytes]);
w.buf
.get_mut(at..at + 8)
.ok_or(Error::InvalidLength)?
.copy_from_slice(tag.get(..8).unwrap_or(&[]));
}
if let (Some(at), Some(ell)) = (ell_crc, self.ell) {
self.ell_seal(&ell, key, at, &mut w)?;
}
Ok(w.n)
}
fn ell_seal(&self, ell: &Ell, key: &Key, at: usize, w: &mut Writer<'_>) -> Result<()> {
let crc = crc16(w.buf.get(at + 2..w.n).ok_or(Error::InvalidLength)?).to_le_bytes();
w.buf.get_mut(at..at + 2).ok_or(Error::InvalidLength)?.copy_from_slice(&crc);
if ell.encrypted() {
let [a, b, c, d, e, f, g, h] = self.address.to_bytes();
let [s0, s1, s2, s3] = ell.session.unwrap_or(0).to_le_bytes();
let iv = [a, b, c, d, e, f, g, h, ell.cc & !0x12, s0, s1, s2, s3, 0, 0, 0];
oms::ctr_apply(key, &iv, w.buf.get_mut(at..w.n).ok_or(Error::InvalidLength)?);
}
Ok(())
}
}
fn ell_header(ell: &Ell, w: &mut Writer<'_>) -> Result<Option<usize>> {
let first = match (ell.receiver, ell.session) {
(None, None) => ci::ELL_SHORT,
(Some(_), None) => ci::ELL_LONG,
(None, Some(_)) => ci::ELL_SHORT_SN,
(Some(_), Some(_)) => ci::ELL_LONG_SN,
};
w.put(&[first, ell.cc, ell.access_number])?;
if let Some(r) = ell.receiver {
w.put(&r.to_bytes())?;
}
let Some(sn) = ell.session else { return Ok(None) };
w.put(&sn.to_le_bytes())?;
let at = w.n;
w.put(&[0, 0])?;
Ok(Some(at))
}
struct Writer<'b> {
buf: &'b mut [u8],
n: usize,
}
impl Writer<'_> {
fn put(&mut self, bytes: &[u8]) -> Result<()> {
let end = self.n.checked_add(bytes.len()).ok_or(Error::InvalidLength)?;
self.buf.get_mut(self.n..end).ok_or(Error::InvalidLength)?.copy_from_slice(bytes);
self.n = end;
Ok(())
}
}