use crate::codec::{Decode, Error, ErrorKind, Reader, Result, SliceWriter, Writer};
use crate::xdlms::{ApduTag, CipheredService, GeneralCiphering, GeneralGloCiphering, KeyInfo, Protection};
use super::counter::ReplayWindow;
use super::keys::SystemTitle;
use super::protect::{Protector, SecurityPolicy};
use super::{CryptoProvider, SecuritySuite};
pub(crate) struct Outgoing<'a> {
pub system_title: SystemTitle,
pub invocation_counter: u32,
pub auth_key: Option<&'a [u8]>,
pub policy: SecurityPolicy,
pub general_allowed: bool,
}
const HEADER_MAX: usize = 1 + (1 + 8) + 5 + 1 + 4;
pub(crate) fn protect_apdu<P: CryptoProvider>(
protector: &Protector<P>,
out_ctx: &Outgoing<'_>,
plain: &[u8],
out: &mut [u8],
) -> Result<usize> {
if out_ctx.policy.is_none() {
let mut w = SliceWriter::new(out);
w.write_bytes(plain)?;
return Ok(w.written());
}
let plain_tag = plain
.first()
.copied()
.and_then(ApduTag::from_u8)
.ok_or_else(|| Error::new(ErrorKind::InvalidTag(plain.first().copied().unwrap_or(0)), 0))?;
let protection = if out_ctx.policy.dedicated() { Protection::Dedicated } else { Protection::Global };
let auth_key = out_ctx.auth_key.ok_or_else(|| Error::new(ErrorKind::Unsupported, 0))?;
let payload_len = plain
.len()
.checked_add(if out_ctx.policy.authenticated { SecuritySuite::TAG_LEN } else { 0 })
.ok_or_else(|| Error::new(ErrorKind::InvalidLength, 0))?;
let control = out_ctx.policy.control();
let mut header = [0u8; HEADER_MAX];
let mut hw = SliceWriter::new(&mut header);
if let Some(tag) = plain_tag.protected_as(protection) {
hw.write_u8(tag.as_u8())?;
} else {
if !out_ctx.general_allowed {
return Err(Error::new(ErrorKind::Unsupported, 0));
}
let tag = match protection {
Protection::Dedicated => ApduTag::GeneralDedCiphering,
_ => ApduTag::GeneralGloCiphering,
};
hw.write_u8(tag.as_u8())?;
hw.write_length_prefixed(out_ctx.system_title.as_bytes())?;
}
hw.write_length(5usize.saturating_add(payload_len))?;
hw.write_u8(control.0)?;
hw.write_u32(out_ctx.invocation_counter)?;
let header_len = hw.written();
let head = out
.get_mut(..header_len)
.ok_or_else(|| Error::new(ErrorKind::BufferTooSmall { needed: header_len }, 0))?;
head.copy_from_slice(header.get(..header_len).unwrap_or(&[]));
let body = out
.get_mut(header_len..)
.ok_or_else(|| Error::new(ErrorKind::BufferTooSmall { needed: header_len }, 0))?;
let written = protector
.protect_as(out_ctx.policy, &out_ctx.system_title, out_ctx.invocation_counter, auth_key, plain, body)?
.len();
debug_assert_eq!(written, payload_len);
if written != payload_len {
return Err(Error::new(ErrorKind::InvalidLength, header_len));
}
Ok(header_len.saturating_add(written))
}
pub(crate) struct Incoming<'a> {
pub local: Option<SystemTitle>,
pub peer: Option<SystemTitle>,
pub auth_key: Option<&'a [u8]>,
pub policy: SecurityPolicy,
pub plain_allowed: &'a [ApduTag],
}
enum Parsed<'a> {
Plain,
Ciphered { policy: SecurityPolicy, expect_tag: Option<ApduTag>, ciphered: CipheredService<'a> },
}
pub(crate) fn unprotect_apdu<'b, P: CryptoProvider>(
protector: &Protector<P>,
ctx: &Incoming<'_>,
replay: &mut ReplayWindow,
apdu: &[u8],
buf: &'b mut [u8],
) -> Result<&'b [u8]> {
match parse_header(ctx, apdu)? {
Parsed::Plain => {
let n = apdu.len();
buf.get_mut(..n)
.ok_or_else(|| Error::new(ErrorKind::BufferTooSmall { needed: n }, 0))?
.copy_from_slice(apdu);
buf.get(..n).ok_or_else(|| Error::new(ErrorKind::InvalidLength, 0))
}
Parsed::Ciphered { policy, expect_tag, ciphered } => {
let n = ciphered.payload.len();
buf.get_mut(..n)
.ok_or_else(|| Error::new(ErrorKind::BufferTooSmall { needed: n }, 0))?
.copy_from_slice(ciphered.payload);
let control = ciphered.security_control;
let counter = ciphered.invocation_counter;
let len = decrypt_front(protector, ctx, replay, policy, expect_tag, control, counter, n, buf)?;
buf.get(..len).ok_or_else(|| Error::new(ErrorKind::InvalidLength, 0))
}
}
}
#[cfg(feature = "client")]
pub(crate) fn unprotect_apdu_in_place<P: CryptoProvider>(
protector: &Protector<P>,
ctx: &Incoming<'_>,
replay: &mut ReplayWindow,
buf: &mut [u8],
len: usize,
) -> Result<core::ops::Range<usize>> {
let apdu = buf.get(..len).ok_or_else(|| Error::new(ErrorKind::InvalidLength, 0))?;
let (policy, expect_tag, control, counter, start, n) = match parse_header(ctx, apdu)? {
Parsed::Plain => return Ok(0..len),
Parsed::Ciphered { policy, expect_tag, ciphered } => {
let start = (ciphered.payload.as_ptr() as usize).saturating_sub(apdu.as_ptr() as usize);
(
policy,
expect_tag,
ciphered.security_control,
ciphered.invocation_counter,
start,
ciphered.payload.len(),
)
}
};
let end =
start.checked_add(n).filter(|&e| e <= len).ok_or_else(|| Error::new(ErrorKind::InvalidLength, 0))?;
buf.copy_within(start..end, 0);
let plain = decrypt_front(protector, ctx, replay, policy, expect_tag, control, counter, n, buf)?;
Ok(0..plain)
}
fn parse_header<'a>(ctx: &Incoming<'_>, apdu: &'a [u8]) -> Result<Parsed<'a>> {
let tag_byte = apdu.first().copied().unwrap_or(0);
let tag = ApduTag::from_u8(tag_byte).ok_or_else(|| Error::new(ErrorKind::InvalidTag(tag_byte), 0))?;
let mut r = Reader::new(apdu);
r.skip(1)?;
let (policy, expect_tag, ciphered) = match tag {
ApduTag::GeneralGloCiphering | ApduTag::GeneralDedCiphering => {
let g = GeneralGloCiphering::decode(&mut r)?;
if let Some(peer) = ctx.peer {
if g.system_title != peer.as_bytes() {
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
}
let dedicated = tag == ApduTag::GeneralDedCiphering;
if dedicated != ctx.policy.dedicated() {
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
(ctx.policy, None, g.ciphered)
}
ApduTag::GeneralCiphering => {
let g = GeneralCiphering::decode(&mut r)?;
if let Some(peer) = ctx.peer {
if g.originator_system_title != peer.as_bytes() {
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
}
if let Some(local) = ctx.local {
if !g.recipient_system_title.is_empty() && g.recipient_system_title != local.as_bytes() {
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
}
match g.key_info {
None => {}
Some(KeyInfo::Identified { key_id }) if Some(key_id) == ctx.policy.key_usage().key_id() => {}
Some(KeyInfo::Identified { .. }) => {
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
Some(KeyInfo::Wrapped { .. } | KeyInfo::Agreed { .. }) => {
return Err(Error::new(ErrorKind::Unsupported, 0));
}
}
if ctx.policy.dedicated() {
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
(ctx.policy, None, g.ciphered)
}
ApduTag::GeneralSigning => {
return Err(Error::new(ErrorKind::Unsupported, 0));
}
_ => {
let Some((protection, plain_tag)) = tag.unprotect() else {
if !ctx.policy.is_none() && !ctx.plain_allowed.contains(&tag) {
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
return Ok(Parsed::Plain);
};
let dedicated = protection == Protection::Dedicated;
if dedicated != ctx.policy.dedicated() {
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
(ctx.policy, Some(plain_tag), CipheredService::decode(&mut r)?)
}
};
Ok(Parsed::Ciphered { policy, expect_tag, ciphered })
}
#[allow(clippy::too_many_arguments, reason = "the header fields are passed by value so the payload can move")]
fn decrypt_front<P: CryptoProvider>(
protector: &Protector<P>,
ctx: &Incoming<'_>,
replay: &mut ReplayWindow,
policy: SecurityPolicy,
expect_tag: Option<ApduTag>,
control: crate::xdlms::SecurityControl,
counter: u32,
n: usize,
buf: &mut [u8],
) -> Result<usize> {
let peer = ctx.peer.ok_or_else(|| Error::new(ErrorKind::UnexpectedMessage, 0))?;
replay.check(counter)?;
let body = buf.get_mut(..n).ok_or_else(|| Error::new(ErrorKind::BufferTooSmall { needed: n }, 0))?;
let plain_len = protector
.unprotect_as(
policy,
control,
&peer,
counter,
ctx.auth_key.ok_or_else(|| Error::new(ErrorKind::Unsupported, 0))?,
body,
)?
.len();
replay.accept(counter)?;
if let Some(expected) = expect_tag {
if buf.first() != Some(&expected.as_u8()) {
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
}
Ok(plain_len)
}