use crate::axdr::{Data, DateTime};
use crate::codec::{Decode, Error, ErrorKind, Reader, Result};
use crate::security::{CryptoProvider, KeyRing, Protector, ReplayWindow, SecurityPolicy, SystemTitle};
use crate::xdlms::{Apdu, ApduTag, CipheredService, DataNotification, SecurityControl};
pub trait PushKeyLookup {
fn keys_for(&self, system_title: &SystemTitle) -> Option<&KeyRing>;
fn replay_window(&mut self, system_title: &SystemTitle) -> Option<&mut ReplayWindow>;
}
#[derive(Debug, Clone)]
pub struct SingleMeterKeys {
pub system_title: SystemTitle,
pub keys: KeyRing,
pub replay: ReplayWindow,
}
impl SingleMeterKeys {
#[must_use]
pub const fn new(system_title: SystemTitle, keys: KeyRing) -> Self {
Self { system_title, keys, replay: ReplayWindow::strict() }
}
}
impl PushKeyLookup for SingleMeterKeys {
fn keys_for(&self, system_title: &SystemTitle) -> Option<&KeyRing> {
(*system_title == self.system_title).then_some(&self.keys)
}
fn replay_window(&mut self, system_title: &SystemTitle) -> Option<&mut ReplayWindow> {
(*system_title == self.system_title).then_some(&mut self.replay)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ReceivedNotification<'a> {
pub system_title: Option<SystemTitle>,
pub invocation_counter: Option<u32>,
pub captured_at: Option<DateTime>,
pub body: Data<'a>,
}
#[derive(Debug)]
pub struct NotificationListener<P, L> {
provider: P,
lookup: L,
required: SecurityPolicy,
}
impl<P: CryptoProvider, L: PushKeyLookup> NotificationListener<P, L> {
pub const fn new(provider: P, lookup: L, required: SecurityPolicy) -> Self {
Self { provider, lookup, required }
}
#[must_use]
pub const fn required(&self) -> SecurityPolicy {
self.required
}
pub const fn lookup_mut(&mut self) -> &mut L {
&mut self.lookup
}
pub fn handle<'b>(&mut self, apdu: &[u8], buf: &'b mut [u8]) -> Result<ReceivedNotification<'b>> {
self.handle_inner(apdu, None, buf)
}
pub fn handle_from<'b>(
&mut self,
sender: SystemTitle,
apdu: &[u8],
buf: &'b mut [u8],
) -> Result<ReceivedNotification<'b>> {
self.handle_inner(apdu, Some(sender), buf)
}
fn handle_inner<'b>(
&mut self,
apdu: &[u8],
sender: Option<SystemTitle>,
buf: &'b mut [u8],
) -> Result<ReceivedNotification<'b>> {
let tag_byte = apdu.first().copied().unwrap_or(0);
let tag = ApduTag::from_u8(tag_byte).ok_or(Error::new(ErrorKind::InvalidTag(tag_byte), 0))?;
let mut r = Reader::new(apdu);
r.skip(1)?;
let (system_title, ciphered): (Option<SystemTitle>, Option<CipheredService<'_>>) = match tag {
ApduTag::DataNotification => (None, None),
ApduTag::GeneralGloCiphering | ApduTag::GeneralDedCiphering => {
let g = crate::xdlms::GeneralGloCiphering::decode(&mut r)?;
(Some(SystemTitle::from_slice(g.system_title)?), Some(g.ciphered))
}
ApduTag::GloEventNotification | ApduTag::DedEventNotification => {
(sender, Some(CipheredService::decode(&mut r)?))
}
_ => return Err(Error::new(ErrorKind::UnexpectedMessage, 0)),
};
let plain: &[u8] = match ciphered {
None => {
if !self.required.is_none() {
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
let rest = r.take_rest();
let n = rest.len();
buf.get_mut(..n)
.ok_or(Error::new(ErrorKind::BufferTooSmall { needed: n }, 0))?
.copy_from_slice(rest);
&buf[..n]
}
Some(c) => {
self.required.check_received(c.security_control)?;
let title = system_title.ok_or(Error::new(ErrorKind::Unsupported, 0))?;
let keys = self.lookup.keys_for(&title).ok_or(Error::new(ErrorKind::Unsupported, 0))?.clone();
let auth_key = keys
.get(crate::security::KeyUsage::Authentication)
.map(crate::security::Key::from_slice)
.transpose()?
.ok_or(Error::new(ErrorKind::Unsupported, 0))?;
self.lookup
.replay_window(&title)
.ok_or(Error::new(ErrorKind::Unsupported, 0))?
.check(c.invocation_counter)?;
let n = c.payload.len();
let body = buf.get_mut(..n).ok_or(Error::new(ErrorKind::BufferTooSmall { needed: n }, 0))?;
body.copy_from_slice(c.payload);
let mut policy = self.required;
policy.suite = crate::security::SecuritySuite::from_id(c.security_control.suite())?;
policy = policy.with_dedicated(
tag == ApduTag::GeneralDedCiphering || tag == ApduTag::DedEventNotification,
);
let protector = Protector::new(ProviderWithKeys { inner: &self.provider, keys }, policy);
let len = protector
.unprotect(c.security_control, &title, c.invocation_counter, auth_key.expose(), body)?
.len();
self.lookup
.replay_window(&title)
.ok_or(Error::new(ErrorKind::Unsupported, 0))?
.accept(c.invocation_counter)?;
&buf[..len]
}
};
let mut pr = Reader::new(plain);
let inner_tag = pr.peek_u8()?;
let notification = if ApduTag::from_u8(inner_tag) == Some(ApduTag::DataNotification) {
let apdu = Apdu::from_bytes(plain)?;
match apdu {
Apdu::DataNotification(n) => n,
_ => return Err(Error::new(ErrorKind::UnexpectedMessage, 0)),
}
} else {
DataNotification::decode(&mut pr)?
};
Ok(ReceivedNotification {
system_title,
invocation_counter: ciphered.map(|c| c.invocation_counter),
captured_at: notification.date_time.0,
body: notification.body,
})
}
}
#[derive(Debug)]
struct ProviderWithKeys<'p, P> {
inner: &'p P,
keys: KeyRing,
}
impl<P: CryptoProvider> CryptoProvider for ProviderWithKeys<'_, P> {
fn aead_seal(
&self,
key: crate::security::keys::KeyRef<'_>,
suite: crate::security::SecuritySuite,
nonce: &[u8; 12],
aad: &[u8],
buf: &mut [u8],
) -> Result<[u8; 12]> {
self.inner.aead_seal(self.resolve(key)?, suite, nonce, aad, buf)
}
fn aead_open(
&self,
key: crate::security::keys::KeyRef<'_>,
suite: crate::security::SecuritySuite,
nonce: &[u8; 12],
aad: &[u8],
buf: &mut [u8],
tag: &[u8; 12],
) -> Result<()> {
self.inner.aead_open(self.resolve(key)?, suite, nonce, aad, buf, tag)
}
fn gmac(
&self,
key: crate::security::keys::KeyRef<'_>,
suite: crate::security::SecuritySuite,
nonce: &[u8; 12],
aad: &[&[u8]],
) -> Result<[u8; 12]> {
self.inner.gmac(self.resolve(key)?, suite, nonce, aad)
}
fn random(&self, out: &mut [u8]) -> Result<()> {
self.inner.random(out)
}
fn authentication_key(&self) -> Option<&[u8]> {
self.keys.get(crate::security::KeyUsage::Authentication)
}
fn dedicated_key(&self) -> Option<&[u8]> {
self.keys.get(crate::security::KeyUsage::Dedicated)
}
}
impl<P> ProviderWithKeys<'_, P> {
fn resolve<'k>(
&'k self,
key: crate::security::keys::KeyRef<'k>,
) -> Result<crate::security::keys::KeyRef<'k>> {
match key {
crate::security::keys::KeyRef::Raw(_) => Ok(key),
crate::security::keys::KeyRef::Usage(u) => self
.keys
.get(u)
.map(crate::security::keys::KeyRef::Raw)
.ok_or(Error::new(ErrorKind::Unsupported, 0)),
}
}
}
impl SecurityControl {
#[must_use]
pub const fn is_protected(self) -> bool {
!self.is_plain()
}
}