use crate::codec::{Error, ErrorKind, Result};
use crate::xdlms::SecurityControl;
use super::keys::{Key, KeyRef, KeyUsage, SystemTitle, nonce};
use super::{CryptoProvider, SecuritySuite};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum KeySet {
#[default]
GlobalUnicast,
GlobalBroadcast,
Dedicated,
}
impl KeySet {
#[must_use]
pub const fn usage(self) -> KeyUsage {
match self {
Self::GlobalUnicast => KeyUsage::GlobalUnicastEncryption,
Self::GlobalBroadcast => KeyUsage::GlobalBroadcastEncryption,
Self::Dedicated => KeyUsage::Dedicated,
}
}
#[must_use]
pub const fn is_broadcast(self) -> bool {
matches!(self, Self::GlobalBroadcast)
}
#[must_use]
pub const fn is_dedicated(self) -> bool {
matches!(self, Self::Dedicated)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SecurityPolicy {
pub suite: SecuritySuite,
pub authenticated: bool,
pub encrypted: bool,
pub key_set: KeySet,
}
impl SecurityPolicy {
pub const NONE: Self = Self {
suite: SecuritySuite::Suite0,
authenticated: false,
encrypted: false,
key_set: KeySet::GlobalUnicast,
};
#[must_use]
pub const fn authenticated_encrypted(suite: SecuritySuite) -> Self {
Self { suite, authenticated: true, encrypted: true, key_set: KeySet::GlobalUnicast }
}
#[must_use]
pub const fn global(self) -> Self {
Self { key_set: KeySet::GlobalUnicast, ..self }
}
#[must_use]
pub const fn with_dedicated(self, dedicated: bool) -> Self {
Self { key_set: if dedicated { KeySet::Dedicated } else { KeySet::GlobalUnicast }, ..self }
}
#[must_use]
pub const fn with_broadcast(self, broadcast: bool) -> Self {
Self { key_set: if broadcast { KeySet::GlobalBroadcast } else { KeySet::GlobalUnicast }, ..self }
}
#[must_use]
pub const fn dedicated(self) -> bool {
self.key_set.is_dedicated()
}
#[must_use]
pub const fn broadcast(self) -> bool {
self.key_set.is_broadcast()
}
#[must_use]
pub const fn key_usage(self) -> KeyUsage {
self.key_set.usage()
}
#[must_use]
pub const fn control(self) -> SecurityControl {
SecurityControl::new(self.suite.id(), self.authenticated, self.encrypted)
.with_broadcast(self.key_set.is_broadcast())
}
#[must_use]
pub const fn is_none(self) -> bool {
!self.authenticated && !self.encrypted
}
pub fn check_received(self, control: SecurityControl) -> Result<()> {
if control.compressed() {
return Err(Error::new(ErrorKind::Unsupported, 0));
}
if control.broadcast_key() != self.key_set.is_broadcast() {
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
if self.is_none() {
return Ok(());
}
if control.suite() != self.suite.id()
|| (self.authenticated && !control.authenticated())
|| (self.encrypted && !control.encrypted())
{
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
Ok(())
}
}
#[derive(Debug)]
pub struct Protector<P> {
provider: P,
policy: SecurityPolicy,
}
impl<P: CryptoProvider> Protector<P> {
pub const fn new(provider: P, policy: SecurityPolicy) -> Self {
Self { provider, policy }
}
pub const fn policy(&self) -> SecurityPolicy {
self.policy
}
pub const fn set_dedicated(&mut self, dedicated: bool) {
self.policy = self.policy.with_dedicated(dedicated);
}
pub const fn provider(&self) -> &P {
&self.provider
}
pub const fn provider_mut(&mut self) -> &mut P {
&mut self.provider
}
pub fn auth_key(&self) -> Option<&[u8]> {
self.provider.authentication_key()
}
pub fn protect<'o>(
&self,
system_title: &SystemTitle,
invocation_counter: u32,
auth_key: &[u8],
plaintext: &[u8],
out: &'o mut [u8],
) -> Result<&'o [u8]> {
self.protect_as(self.policy, system_title, invocation_counter, auth_key, plaintext, out)
}
pub fn protect_as<'o>(
&self,
policy: SecurityPolicy,
system_title: &SystemTitle,
invocation_counter: u32,
auth_key: &[u8],
plaintext: &[u8],
out: &'o mut [u8],
) -> Result<&'o [u8]> {
let control = policy.control();
let iv = nonce(system_title, invocation_counter);
let key = KeyRef::Usage(policy.key_usage());
if policy.is_none() {
let n = plaintext.len();
out.get_mut(..n)
.ok_or_else(|| Error::new(ErrorKind::BufferTooSmall { needed: n }, 0))?
.copy_from_slice(plaintext);
return Ok(&out[..n]);
}
let needed = plaintext.len() + if policy.authenticated { SecuritySuite::TAG_LEN } else { 0 };
if out.len() < needed {
return Err(Error::new(ErrorKind::BufferTooSmall { needed: needed - out.len() }, 0));
}
out[..plaintext.len()].copy_from_slice(plaintext);
if policy.authenticated && policy.encrypted {
let mut aad = [0u8; 1 + Key::MAX_LEN];
let aad = build_aad(&mut aad, control, auth_key)?;
let tag = self.provider.aead_seal(key, policy.suite, &iv, aad, &mut out[..plaintext.len()])?;
out[plaintext.len()..needed].copy_from_slice(&tag);
} else if policy.authenticated {
let tag = self.gmac_with(policy, control, auth_key, &iv, plaintext)?;
out[plaintext.len()..needed].copy_from_slice(&tag);
} else {
let _ = self.provider.aead_seal(key, policy.suite, &iv, &[], &mut out[..plaintext.len()])?;
}
Ok(&out[..needed])
}
pub fn unprotect<'o>(
&self,
control: SecurityControl,
system_title: &SystemTitle,
invocation_counter: u32,
auth_key: &[u8],
payload: &'o mut [u8],
) -> Result<&'o [u8]> {
self.unprotect_as(self.policy, control, system_title, invocation_counter, auth_key, payload)
}
pub fn unprotect_as<'o>(
&self,
policy: SecurityPolicy,
control: SecurityControl,
system_title: &SystemTitle,
invocation_counter: u32,
auth_key: &[u8],
payload: &'o mut [u8],
) -> Result<&'o [u8]> {
policy.check_received(control)?;
let iv = nonce(system_title, invocation_counter);
let key = KeyRef::Usage(policy.key_usage());
let suite = SecuritySuite::from_id(control.suite())?;
if control.is_plain() {
return Ok(payload);
}
if !control.authenticated() {
self.provider.aead_open_unauthenticated(key, suite, &iv, payload)?;
return Ok(payload);
}
let len = payload
.len()
.checked_sub(SecuritySuite::TAG_LEN)
.ok_or_else(|| Error::new(ErrorKind::InvalidLength, 0))?;
let mut tag = [0u8; SecuritySuite::TAG_LEN];
tag.copy_from_slice(&payload[len..]);
if control.encrypted() {
let mut aad = [0u8; 1 + Key::MAX_LEN];
let aad = build_aad(&mut aad, control, auth_key)?;
self.provider.aead_open(key, suite, &iv, aad, &mut payload[..len], &tag)?;
} else {
let expected = self.gmac_with(policy, control, auth_key, &iv, &payload[..len])?;
if !constant_time_eq(&expected, &tag) {
return Err(Error::new(ErrorKind::BadTag, 0));
}
}
Ok(&payload[..len])
}
pub fn gmac_over(
&self,
control: SecurityControl,
auth_key: &[u8],
iv: &[u8; 12],
data: &[u8],
) -> Result<[u8; 12]> {
self.gmac_with(self.policy, control, auth_key, iv, data)
}
fn gmac_with(
&self,
policy: SecurityPolicy,
control: SecurityControl,
auth_key: &[u8],
iv: &[u8; 12],
data: &[u8],
) -> Result<[u8; 12]> {
self.provider.gmac(
KeyRef::Usage(policy.key_usage()),
SecuritySuite::from_id(control.suite())?,
iv,
&[&[control.0][..], auth_key, data],
)
}
pub fn hls_gmac_response(
&self,
system_title: &SystemTitle,
invocation_counter: u32,
auth_key: &[u8],
challenge: &[u8],
out: &mut [u8; 17],
) -> Result<()> {
let control = SecurityControl::new(self.policy.suite.id(), true, false);
let iv = nonce(system_title, invocation_counter);
let tag = self.gmac_with(self.policy.global(), control, auth_key, &iv, challenge)?;
out[0] = control.0;
out[1..5].copy_from_slice(&invocation_counter.to_be_bytes());
out[5..].copy_from_slice(&tag);
Ok(())
}
pub fn verify_hls_gmac(
&self,
peer_title: &SystemTitle,
auth_key: &[u8],
challenge: &[u8],
response: &[u8],
) -> Result<()> {
if response.len() != 17 {
return Err(Error::new(ErrorKind::InvalidLength, 0));
}
let control = SecurityControl(response[0]);
if !control.authenticated()
|| control.encrypted()
|| control.broadcast_key()
|| control.compressed()
|| control.suite() != self.policy.suite.id()
{
return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
}
let ic = u32::from_be_bytes([response[1], response[2], response[3], response[4]]);
let iv = nonce(peer_title, ic);
let expected = self.gmac_with(self.policy.global(), control, auth_key, &iv, challenge)?;
if constant_time_eq(&expected, &response[5..]) {
Ok(())
} else {
Err(Error::new(ErrorKind::BadTag, 0))
}
}
}
fn build_aad<'a>(
buf: &'a mut [u8; 1 + Key::MAX_LEN],
control: SecurityControl,
auth_key: &[u8],
) -> Result<&'a [u8]> {
let n = 1 + auth_key.len();
if n > buf.len() {
return Err(Error::new(ErrorKind::Unsupported, 0));
}
buf[0] = control.0;
buf.get_mut(1..n).ok_or_else(|| Error::new(ErrorKind::Unsupported, 0))?.copy_from_slice(auth_key);
Ok(buf.get(..n).unwrap_or(&[]))
}
#[must_use]
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
#[cfg(feature = "crypto")]
{
use subtle::ConstantTimeEq;
a.ct_eq(b).into()
}
#[cfg(not(feature = "crypto"))]
{
let mut diff = 0u8;
for (x, y) in a.iter().zip(b) {
diff |= x ^ y;
}
diff == 0
}
}
trait AeadOpenUnauthenticated {
fn aead_open_unauthenticated(
&self,
key: KeyRef<'_>,
suite: SecuritySuite,
nonce: &[u8; 12],
buf: &mut [u8],
) -> Result<()>;
}
impl<T: CryptoProvider> AeadOpenUnauthenticated for T {
fn aead_open_unauthenticated(
&self,
key: KeyRef<'_>,
suite: SecuritySuite,
nonce: &[u8; 12],
buf: &mut [u8],
) -> Result<()> {
let _ = self.aead_seal(key, suite, nonce, &[], buf)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_key_set_is_what_this_end_demands_not_what_the_frame_claims() {
let unicast = SecurityPolicy::authenticated_encrypted(SecuritySuite::Suite0);
let broadcast = unicast.with_broadcast(true);
assert_eq!(unicast.key_usage(), KeyUsage::GlobalUnicastEncryption);
assert_eq!(broadcast.key_usage(), KeyUsage::GlobalBroadcastEncryption);
assert!(broadcast.control().broadcast_key());
assert!(!unicast.control().broadcast_key());
assert!(unicast.check_received(unicast.control()).is_ok());
assert!(broadcast.check_received(broadcast.control()).is_ok());
assert_eq!(
unicast.check_received(broadcast.control()).unwrap_err().kind,
ErrorKind::UnexpectedMessage,
"a frame naming the broadcast key set on a unicast association is a key downgrade"
);
assert_eq!(
broadcast.check_received(unicast.control()).unwrap_err().kind,
ErrorKind::UnexpectedMessage
);
}
#[test]
fn an_unprotected_policy_still_refuses_a_key_set_it_did_not_ask_for() {
assert!(SecurityPolicy::NONE.check_received(SecurityControl(0x00)).is_ok());
assert_eq!(
SecurityPolicy::NONE.check_received(SecurityControl(0x40)).unwrap_err().kind,
ErrorKind::UnexpectedMessage
);
}
#[test]
fn global_means_the_unicast_key_set() {
let p = SecurityPolicy::authenticated_encrypted(SecuritySuite::Suite2)
.with_dedicated(true)
.with_broadcast(true);
assert_eq!(p.global().key_usage(), KeyUsage::GlobalUnicastEncryption);
assert_eq!(p.global().suite, SecuritySuite::Suite2, "and changes nothing else");
}
}