Skip to main content

dlms_cosem_kit/security/
protect.rs

1//! Applying and removing protection.
2//!
3//! The composition rules are the part worth stating plainly, because the three modes
4//! authenticate different things:
5//!
6//! | Security control | Additional authenticated data | Payload |
7//! |---|---|---|
8//! | authenticated **and** encrypted | `SC ‖ AK` | ciphertext ‖ tag |
9//! | authenticated only | `SC ‖ AK ‖ plaintext` | plaintext ‖ tag |
10//! | encrypted only | *(none)* | ciphertext |
11//!
12//! An implementation that authenticates the ciphertext in the second row, or omits the
13//! authentication key from the first, produces frames that decode locally and are
14//! rejected by every other stack.
15
16use crate::codec::{Error, ErrorKind, Result};
17use crate::xdlms::SecurityControl;
18
19use super::keys::{Key, KeyRef, KeyUsage, SystemTitle, nonce};
20use super::{CryptoProvider, SecuritySuite};
21
22/// Which symmetric key set an association protects with.
23///
24/// One field rather than two flags: the three are alternatives, and "dedicated and
25/// broadcast at once" would name a key nothing holds.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub enum KeySet {
28    /// The global unicast encryption key — ordinary traffic, and everything that runs
29    /// before an association has a key of its own.
30    #[default]
31    GlobalUnicast,
32    /// The global broadcast encryption key, shared across a fleet.
33    GlobalBroadcast,
34    /// The key this association negotiated, delivered in the `InitiateRequest`.
35    Dedicated,
36}
37
38impl KeySet {
39    /// The key this set resolves to.
40    #[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    /// Whether the security control byte's broadcast bit is set for this key set.
50    #[must_use]
51    pub const fn is_broadcast(self) -> bool {
52        matches!(self, Self::GlobalBroadcast)
53    }
54
55    /// Whether this is the association's own negotiated key.
56    #[must_use]
57    pub const fn is_dedicated(self) -> bool {
58        matches!(self, Self::Dedicated)
59    }
60}
61
62/// What protection an association applies and demands.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub struct SecurityPolicy {
65    /// The suite in use.
66    pub suite: SecuritySuite,
67    /// Whether outgoing APDUs are authenticated.
68    pub authenticated: bool,
69    /// Whether outgoing APDUs are encrypted.
70    pub encrypted: bool,
71    /// Which key set protects an APDU — and, on the receiving side, which one this end
72    /// will *accept*.
73    ///
74    /// The security control byte's broadcast bit is the sender's claim. Letting it choose
75    /// the key would hand an attacker that choice, and a broadcast key is shared with a
76    /// whole fleet: a unicast exchange accepted under one lets any fleet member speak as
77    /// the head-end, with a tag that verifies. So this states what is demanded, and a
78    /// frame whose bit disagrees is refused before a key is touched.
79    pub key_set: KeySet,
80}
81
82impl SecurityPolicy {
83    /// No protection at all.
84    pub const NONE: Self = Self {
85        suite: SecuritySuite::Suite0,
86        authenticated: false,
87        encrypted: false,
88        key_set: KeySet::GlobalUnicast,
89    };
90
91    /// Authenticated and encrypted with the given suite — what a ciphered association
92    /// normally uses.
93    #[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    /// The same protection on the **global unicast** key set.
99    ///
100    /// The `InitiateRequest` and `InitiateResponse` are always protected this way, even
101    /// in an association that will use a dedicated key for everything afterwards: the
102    /// dedicated key is *delivered* inside the ciphered `InitiateRequest`, so nothing
103    /// can be protected with it before that message has been opened. The same holds for
104    /// HLS, which runs before the association is open.
105    #[must_use]
106    pub const fn global(self) -> Self {
107        Self { key_set: KeySet::GlobalUnicast, ..self }
108    }
109
110    /// The same protection with the dedicated key set, or back on the unicast one.
111    #[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    /// The same protection on the broadcast key set, or back on the unicast one.
117    ///
118    /// For a receiver this says which key set it will *accept*; see
119    /// [`SecurityPolicy::key_set`].
120    #[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    /// True when this association uses the key it negotiated for itself.
126    #[must_use]
127    pub const fn dedicated(self) -> bool {
128        self.key_set.is_dedicated()
129    }
130
131    /// True when this association uses the broadcast key set.
132    #[must_use]
133    pub const fn broadcast(self) -> bool {
134        self.key_set.is_broadcast()
135    }
136
137    /// Which key this policy's key set resolves to.
138    #[must_use]
139    pub const fn key_usage(self) -> KeyUsage {
140        self.key_set.usage()
141    }
142
143    /// The security control byte this policy produces.
144    #[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    /// True when nothing is applied.
151    #[must_use]
152    pub const fn is_none(self) -> bool {
153        !self.authenticated && !self.encrypted
154    }
155
156    /// Check that a received security control byte is at least as strong as this
157    /// policy demands.
158    ///
159    /// This is the downgrade check. A peer that stops encrypting, or drops to a weaker
160    /// suite, is refused here rather than quietly accepted — which is the whole point
161    /// of negotiating a policy in the first place.
162    ///
163    /// # Errors
164    /// [`ErrorKind::UnexpectedMessage`] when the received protection is weaker, the
165    /// suite differs, or the frame names a key set this policy did not ask for;
166    /// [`ErrorKind::Unsupported`] when compression is claimed.
167    pub fn check_received(self, control: SecurityControl) -> Result<()> {
168        if control.compressed() {
169            return Err(Error::new(ErrorKind::Unsupported, 0));
170        }
171        // Checked ahead of the `is_none` shortcut, because this bit does not describe
172        // how *strongly* a frame is protected — it decides which key opens it, and a
173        // receiver must never take that from the sender.
174        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/// Applies and removes protection for one association.
191#[derive(Debug)]
192pub struct Protector<P> {
193    provider: P,
194    policy: SecurityPolicy,
195}
196
197impl<P: CryptoProvider> Protector<P> {
198    /// A protector over `provider` applying `policy`.
199    pub const fn new(provider: P, policy: SecurityPolicy) -> Self {
200        Self { provider, policy }
201    }
202
203    /// The policy in force for service APDUs.
204    pub const fn policy(&self) -> SecurityPolicy {
205        self.policy
206    }
207
208    /// Switch service APDUs between the global and the dedicated key set.
209    ///
210    /// A server learns which to use from the `InitiateRequest` — a client that delivers
211    /// a dedicated key expects `ded-` tagged APDUs back — so this cannot be settled at
212    /// construction. Both ends must agree, or every APDU decrypts to noise and fails its
213    /// tag.
214    pub const fn set_dedicated(&mut self, dedicated: bool) {
215        self.policy = self.policy.with_dedicated(dedicated);
216    }
217
218    /// The provider, for operations that are not protection — challenges, key wrap.
219    pub const fn provider(&self) -> &P {
220        &self.provider
221    }
222
223    /// The provider, mutably — for installing the dedicated key of an association.
224    pub const fn provider_mut(&mut self) -> &mut P {
225        &mut self.provider
226    }
227
228    /// The authentication key's bytes, which every protected APDU authenticates.
229    pub fn auth_key(&self) -> Option<&[u8]> {
230        self.provider.authentication_key()
231    }
232
233    /// Protect `plaintext` into `out`, returning the protected payload.
234    ///
235    /// The payload is what goes after the security control byte and invocation counter
236    /// in a `glo-`/`ded-` APDU. `auth_key` is the authentication key's bytes, which are
237    /// authenticated data rather than a cipher key.
238    ///
239    /// # Errors
240    /// When the buffer is too small, or the provider cannot find the key.
241    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    /// Protect under a policy other than this protector's — the Initiate exchange, which
253    /// is global even in a dedicated association.
254    ///
255    /// # Errors
256    /// As [`Protector::protect`].
257    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            // Authentication only: the plaintext travels in the clear and is
291            // authenticated as additional data.
292            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    /// Remove protection from `payload` in place, returning the plaintext.
301    ///
302    /// The tag is verified before any plaintext is returned.
303    ///
304    /// # Errors
305    /// [`ErrorKind::BadTag`] when authentication fails;
306    /// [`ErrorKind::UnexpectedMessage`] when the protection is weaker than the policy
307    /// demands.
308    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    /// Remove protection under a policy other than this protector's.
320    ///
321    /// # Errors
322    /// As [`Protector::unprotect`].
323    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    /// A GMAC over the security control byte, the authentication key and `data`.
366    ///
367    /// This is both the authentication-only protection tag and the HLS mechanism 5
368    /// response, which is why it is one function.
369    ///
370    /// The three parts are handed to the provider as segments rather than joined, so
371    /// `data` may be a whole APDU of any size. Joining them into a fixed buffer here is
372    /// how authentication-only protection quietly acquires a maximum PDU size that
373    /// nothing in the standard has.
374    ///
375    /// # Errors
376    /// When the provider fails or the suite is not one it implements.
377    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    /// The HLS mechanism 5 response to a challenge.
404    ///
405    /// Returns `SC ‖ IC ‖ tag`, which is what goes into
406    /// `reply_to_HLS_authentication`. The nonce uses the *responder's* own system title
407    /// and counter, so each side's answer is bound to its own identity.
408    ///
409    /// # Errors
410    /// When the provider fails or the challenge is longer than the buffer allows.
411    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        // HLS runs before the association is open, so it is always the global key set:
422        // a dedicated key delivered in the InitiateRequest is not yet in force.
423        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    /// Check the peer's HLS mechanism 5 response to a challenge we sent.
431    ///
432    /// # Errors
433    /// [`ErrorKind::BadTag`] when the response does not match;
434    /// [`ErrorKind::InvalidLength`] when it is not 17 bytes.
435    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        // The reply's own security control byte is the peer's claim about how it
447        // computed the tag, and every field of it feeds the tag we are about to
448        // recompute. A peer that names a different suite, or sets the encryption,
449        // broadcast or compression bits, is not answering the challenge that was sent —
450        // and verifying under whatever it claimed would let it choose the construction.
451        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/// Compare two byte strings without leaking where they differ.
485#[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
505/// Decryption without authentication, which GCM makes possible and DLMS permits.
506///
507/// Split out because it is the one operation a caller should have to reach for by name:
508/// there is no integrity guarantee, and a policy that demands authentication never
509/// reaches it.
510trait 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        // GCM is counter mode: encrypting the ciphertext with the same nonce recovers
529        // the plaintext. The tag the seal returns is discarded, which is exactly the
530        // guarantee this mode does not offer.
531        let _ = self.aead_seal(key, suite, nonce, &[], buf)?;
532        Ok(())
533    }
534}
535
536#[cfg(test)]
537mod tests {
538    use super::*;
539
540    /// The broadcast bit chooses *which key* opens a frame, so a receiver must take it
541    /// from its own configuration and never from the sender. A broadcast key is shared
542    /// with a whole fleet by definition: a unicast exchange accepted under one lets any
543    /// meter in that fleet answer as the head-end, with a tag that verifies.
544    #[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        // Each accepts its own bit and refuses the other's.
555        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    /// The bit is checked ahead of the "no protection demanded" shortcut, because it is
569    /// not a statement about *how strongly* a frame is protected.
570    #[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    /// HLS and the Initiate exchange both run before an association has a key set of its
580    /// own, so `global()` has to mean the global *unicast* set and clear both switches.
581    #[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}