1use crate::codec::{Error, ErrorKind, Result};
17use crate::xdlms::SecurityControl;
18
19use super::keys::{Key, KeyRef, KeyUsage, SystemTitle, nonce};
20use super::{CryptoProvider, SecuritySuite};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub enum KeySet {
28 #[default]
31 GlobalUnicast,
32 GlobalBroadcast,
34 Dedicated,
36}
37
38impl KeySet {
39 #[must_use]
41 pub const fn usage(self) -> KeyUsage {
42 match self {
43 Self::GlobalUnicast => KeyUsage::GlobalUnicastEncryption,
44 Self::GlobalBroadcast => KeyUsage::GlobalBroadcastEncryption,
45 Self::Dedicated => KeyUsage::Dedicated,
46 }
47 }
48
49 #[must_use]
51 pub const fn is_broadcast(self) -> bool {
52 matches!(self, Self::GlobalBroadcast)
53 }
54
55 #[must_use]
57 pub const fn is_dedicated(self) -> bool {
58 matches!(self, Self::Dedicated)
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub struct SecurityPolicy {
65 pub suite: SecuritySuite,
67 pub authenticated: bool,
69 pub encrypted: bool,
71 pub key_set: KeySet,
80}
81
82impl SecurityPolicy {
83 pub const NONE: Self = Self {
85 suite: SecuritySuite::Suite0,
86 authenticated: false,
87 encrypted: false,
88 key_set: KeySet::GlobalUnicast,
89 };
90
91 #[must_use]
94 pub const fn authenticated_encrypted(suite: SecuritySuite) -> Self {
95 Self { suite, authenticated: true, encrypted: true, key_set: KeySet::GlobalUnicast }
96 }
97
98 #[must_use]
106 pub const fn global(self) -> Self {
107 Self { key_set: KeySet::GlobalUnicast, ..self }
108 }
109
110 #[must_use]
112 pub const fn with_dedicated(self, dedicated: bool) -> Self {
113 Self { key_set: if dedicated { KeySet::Dedicated } else { KeySet::GlobalUnicast }, ..self }
114 }
115
116 #[must_use]
121 pub const fn with_broadcast(self, broadcast: bool) -> Self {
122 Self { key_set: if broadcast { KeySet::GlobalBroadcast } else { KeySet::GlobalUnicast }, ..self }
123 }
124
125 #[must_use]
127 pub const fn dedicated(self) -> bool {
128 self.key_set.is_dedicated()
129 }
130
131 #[must_use]
133 pub const fn broadcast(self) -> bool {
134 self.key_set.is_broadcast()
135 }
136
137 #[must_use]
139 pub const fn key_usage(self) -> KeyUsage {
140 self.key_set.usage()
141 }
142
143 #[must_use]
145 pub const fn control(self) -> SecurityControl {
146 SecurityControl::new(self.suite.id(), self.authenticated, self.encrypted)
147 .with_broadcast(self.key_set.is_broadcast())
148 }
149
150 #[must_use]
152 pub const fn is_none(self) -> bool {
153 !self.authenticated && !self.encrypted
154 }
155
156 pub fn check_received(self, control: SecurityControl) -> Result<()> {
168 if control.compressed() {
169 return Err(Error::new(ErrorKind::Unsupported, 0));
170 }
171 if control.broadcast_key() != self.key_set.is_broadcast() {
175 return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
176 }
177 if self.is_none() {
178 return Ok(());
179 }
180 if control.suite() != self.suite.id()
181 || (self.authenticated && !control.authenticated())
182 || (self.encrypted && !control.encrypted())
183 {
184 return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
185 }
186 Ok(())
187 }
188}
189
190#[derive(Debug)]
192pub struct Protector<P> {
193 provider: P,
194 policy: SecurityPolicy,
195}
196
197impl<P: CryptoProvider> Protector<P> {
198 pub const fn new(provider: P, policy: SecurityPolicy) -> Self {
200 Self { provider, policy }
201 }
202
203 pub const fn policy(&self) -> SecurityPolicy {
205 self.policy
206 }
207
208 pub const fn set_dedicated(&mut self, dedicated: bool) {
215 self.policy = self.policy.with_dedicated(dedicated);
216 }
217
218 pub const fn provider(&self) -> &P {
220 &self.provider
221 }
222
223 pub const fn provider_mut(&mut self) -> &mut P {
225 &mut self.provider
226 }
227
228 pub fn auth_key(&self) -> Option<&[u8]> {
230 self.provider.authentication_key()
231 }
232
233 pub fn protect<'o>(
242 &self,
243 system_title: &SystemTitle,
244 invocation_counter: u32,
245 auth_key: &[u8],
246 plaintext: &[u8],
247 out: &'o mut [u8],
248 ) -> Result<&'o [u8]> {
249 self.protect_as(self.policy, system_title, invocation_counter, auth_key, plaintext, out)
250 }
251
252 pub fn protect_as<'o>(
258 &self,
259 policy: SecurityPolicy,
260 system_title: &SystemTitle,
261 invocation_counter: u32,
262 auth_key: &[u8],
263 plaintext: &[u8],
264 out: &'o mut [u8],
265 ) -> Result<&'o [u8]> {
266 let control = policy.control();
267 let iv = nonce(system_title, invocation_counter);
268 let key = KeyRef::Usage(policy.key_usage());
269
270 if policy.is_none() {
271 let n = plaintext.len();
272 out.get_mut(..n)
273 .ok_or_else(|| Error::new(ErrorKind::BufferTooSmall { needed: n }, 0))?
274 .copy_from_slice(plaintext);
275 return Ok(&out[..n]);
276 }
277
278 let needed = plaintext.len() + if policy.authenticated { SecuritySuite::TAG_LEN } else { 0 };
279 if out.len() < needed {
280 return Err(Error::new(ErrorKind::BufferTooSmall { needed: needed - out.len() }, 0));
281 }
282 out[..plaintext.len()].copy_from_slice(plaintext);
283
284 if policy.authenticated && policy.encrypted {
285 let mut aad = [0u8; 1 + Key::MAX_LEN];
286 let aad = build_aad(&mut aad, control, auth_key)?;
287 let tag = self.provider.aead_seal(key, policy.suite, &iv, aad, &mut out[..plaintext.len()])?;
288 out[plaintext.len()..needed].copy_from_slice(&tag);
289 } else if policy.authenticated {
290 let tag = self.gmac_with(policy, control, auth_key, &iv, plaintext)?;
293 out[plaintext.len()..needed].copy_from_slice(&tag);
294 } else {
295 let _ = self.provider.aead_seal(key, policy.suite, &iv, &[], &mut out[..plaintext.len()])?;
296 }
297 Ok(&out[..needed])
298 }
299
300 pub fn unprotect<'o>(
309 &self,
310 control: SecurityControl,
311 system_title: &SystemTitle,
312 invocation_counter: u32,
313 auth_key: &[u8],
314 payload: &'o mut [u8],
315 ) -> Result<&'o [u8]> {
316 self.unprotect_as(self.policy, control, system_title, invocation_counter, auth_key, payload)
317 }
318
319 pub fn unprotect_as<'o>(
324 &self,
325 policy: SecurityPolicy,
326 control: SecurityControl,
327 system_title: &SystemTitle,
328 invocation_counter: u32,
329 auth_key: &[u8],
330 payload: &'o mut [u8],
331 ) -> Result<&'o [u8]> {
332 policy.check_received(control)?;
333 let iv = nonce(system_title, invocation_counter);
334 let key = KeyRef::Usage(policy.key_usage());
335 let suite = SecuritySuite::from_id(control.suite())?;
336
337 if control.is_plain() {
338 return Ok(payload);
339 }
340 if !control.authenticated() {
341 self.provider.aead_open_unauthenticated(key, suite, &iv, payload)?;
342 return Ok(payload);
343 }
344
345 let len = payload
346 .len()
347 .checked_sub(SecuritySuite::TAG_LEN)
348 .ok_or_else(|| Error::new(ErrorKind::InvalidLength, 0))?;
349 let mut tag = [0u8; SecuritySuite::TAG_LEN];
350 tag.copy_from_slice(&payload[len..]);
351
352 if control.encrypted() {
353 let mut aad = [0u8; 1 + Key::MAX_LEN];
354 let aad = build_aad(&mut aad, control, auth_key)?;
355 self.provider.aead_open(key, suite, &iv, aad, &mut payload[..len], &tag)?;
356 } else {
357 let expected = self.gmac_with(policy, control, auth_key, &iv, &payload[..len])?;
358 if !constant_time_eq(&expected, &tag) {
359 return Err(Error::new(ErrorKind::BadTag, 0));
360 }
361 }
362 Ok(&payload[..len])
363 }
364
365 pub fn gmac_over(
378 &self,
379 control: SecurityControl,
380 auth_key: &[u8],
381 iv: &[u8; 12],
382 data: &[u8],
383 ) -> Result<[u8; 12]> {
384 self.gmac_with(self.policy, control, auth_key, iv, data)
385 }
386
387 fn gmac_with(
388 &self,
389 policy: SecurityPolicy,
390 control: SecurityControl,
391 auth_key: &[u8],
392 iv: &[u8; 12],
393 data: &[u8],
394 ) -> Result<[u8; 12]> {
395 self.provider.gmac(
396 KeyRef::Usage(policy.key_usage()),
397 SecuritySuite::from_id(control.suite())?,
398 iv,
399 &[&[control.0][..], auth_key, data],
400 )
401 }
402
403 pub fn hls_gmac_response(
412 &self,
413 system_title: &SystemTitle,
414 invocation_counter: u32,
415 auth_key: &[u8],
416 challenge: &[u8],
417 out: &mut [u8; 17],
418 ) -> Result<()> {
419 let control = SecurityControl::new(self.policy.suite.id(), true, false);
420 let iv = nonce(system_title, invocation_counter);
421 let tag = self.gmac_with(self.policy.global(), control, auth_key, &iv, challenge)?;
424 out[0] = control.0;
425 out[1..5].copy_from_slice(&invocation_counter.to_be_bytes());
426 out[5..].copy_from_slice(&tag);
427 Ok(())
428 }
429
430 pub fn verify_hls_gmac(
436 &self,
437 peer_title: &SystemTitle,
438 auth_key: &[u8],
439 challenge: &[u8],
440 response: &[u8],
441 ) -> Result<()> {
442 if response.len() != 17 {
443 return Err(Error::new(ErrorKind::InvalidLength, 0));
444 }
445 let control = SecurityControl(response[0]);
446 if !control.authenticated()
452 || control.encrypted()
453 || control.broadcast_key()
454 || control.compressed()
455 || control.suite() != self.policy.suite.id()
456 {
457 return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
458 }
459 let ic = u32::from_be_bytes([response[1], response[2], response[3], response[4]]);
460 let iv = nonce(peer_title, ic);
461 let expected = self.gmac_with(self.policy.global(), control, auth_key, &iv, challenge)?;
462 if constant_time_eq(&expected, &response[5..]) {
463 Ok(())
464 } else {
465 Err(Error::new(ErrorKind::BadTag, 0))
466 }
467 }
468}
469
470fn build_aad<'a>(
471 buf: &'a mut [u8; 1 + Key::MAX_LEN],
472 control: SecurityControl,
473 auth_key: &[u8],
474) -> Result<&'a [u8]> {
475 let n = 1 + auth_key.len();
476 if n > buf.len() {
477 return Err(Error::new(ErrorKind::Unsupported, 0));
478 }
479 buf[0] = control.0;
480 buf.get_mut(1..n).ok_or_else(|| Error::new(ErrorKind::Unsupported, 0))?.copy_from_slice(auth_key);
481 Ok(buf.get(..n).unwrap_or(&[]))
482}
483
484#[must_use]
486pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
487 if a.len() != b.len() {
488 return false;
489 }
490 #[cfg(feature = "crypto")]
491 {
492 use subtle::ConstantTimeEq;
493 a.ct_eq(b).into()
494 }
495 #[cfg(not(feature = "crypto"))]
496 {
497 let mut diff = 0u8;
498 for (x, y) in a.iter().zip(b) {
499 diff |= x ^ y;
500 }
501 diff == 0
502 }
503}
504
505trait AeadOpenUnauthenticated {
511 fn aead_open_unauthenticated(
512 &self,
513 key: KeyRef<'_>,
514 suite: SecuritySuite,
515 nonce: &[u8; 12],
516 buf: &mut [u8],
517 ) -> Result<()>;
518}
519
520impl<T: CryptoProvider> AeadOpenUnauthenticated for T {
521 fn aead_open_unauthenticated(
522 &self,
523 key: KeyRef<'_>,
524 suite: SecuritySuite,
525 nonce: &[u8; 12],
526 buf: &mut [u8],
527 ) -> Result<()> {
528 let _ = self.aead_seal(key, suite, nonce, &[], buf)?;
532 Ok(())
533 }
534}
535
536#[cfg(test)]
537mod tests {
538 use super::*;
539
540 #[test]
545 fn the_key_set_is_what_this_end_demands_not_what_the_frame_claims() {
546 let unicast = SecurityPolicy::authenticated_encrypted(SecuritySuite::Suite0);
547 let broadcast = unicast.with_broadcast(true);
548
549 assert_eq!(unicast.key_usage(), KeyUsage::GlobalUnicastEncryption);
550 assert_eq!(broadcast.key_usage(), KeyUsage::GlobalBroadcastEncryption);
551 assert!(broadcast.control().broadcast_key());
552 assert!(!unicast.control().broadcast_key());
553
554 assert!(unicast.check_received(unicast.control()).is_ok());
556 assert!(broadcast.check_received(broadcast.control()).is_ok());
557 assert_eq!(
558 unicast.check_received(broadcast.control()).unwrap_err().kind,
559 ErrorKind::UnexpectedMessage,
560 "a frame naming the broadcast key set on a unicast association is a key downgrade"
561 );
562 assert_eq!(
563 broadcast.check_received(unicast.control()).unwrap_err().kind,
564 ErrorKind::UnexpectedMessage
565 );
566 }
567
568 #[test]
571 fn an_unprotected_policy_still_refuses_a_key_set_it_did_not_ask_for() {
572 assert!(SecurityPolicy::NONE.check_received(SecurityControl(0x00)).is_ok());
573 assert_eq!(
574 SecurityPolicy::NONE.check_received(SecurityControl(0x40)).unwrap_err().kind,
575 ErrorKind::UnexpectedMessage
576 );
577 }
578
579 #[test]
582 fn global_means_the_unicast_key_set() {
583 let p = SecurityPolicy::authenticated_encrypted(SecuritySuite::Suite2)
584 .with_dedicated(true)
585 .with_broadcast(true);
586 assert_eq!(p.global().key_usage(), KeyUsage::GlobalUnicastEncryption);
587 assert_eq!(p.global().suite, SecuritySuite::Suite2, "and changes nothing else");
588 }
589}