Skip to main content

ic_mac/
cmac.rs

1//! SP 800-38B CMAC over AES.
2//!
3//! CMAC is the approved way to authenticate with a block cipher when a hash is
4//! unavailable or undesirable, and it underpins the SP 800-90A CTR_DRBG
5//! derivation function and SP 800-108 KDFs in CMAC mode.
6
7//! Indexed loops over fixed-size limb and word arrays are used throughout; they
8//! mirror the index algebra in the specifications these routines implement, so
9//! `needless_range_loop` is allowed rather than obscuring the correspondence.
10#![allow(clippy::needless_range_loop)]
11
12use ic_cipher::aes::{Aes128, Aes192, Aes256, BLOCK_LEN};
13use ic_core::traits::{Algorithm, BlockCipher, Mac, SelfTest};
14use ic_core::{ensure, Result, Zeroize};
15
16/// The CMAC subkey generation constant for a 128-bit block, `x^128 + x^7 + x^2 + x + 1`.
17const RB: u8 = 0x87;
18
19/// Double a 128-bit value in GF(2^128), constant-time.
20fn dbl(block: &mut [u8; BLOCK_LEN]) {
21    let msb = block[0] >> 7;
22    let mut carry = 0u8;
23    for byte in block.iter_mut().rev() {
24        let next = *byte >> 7;
25        *byte = (*byte << 1) | carry;
26        carry = next;
27    }
28    block[BLOCK_LEN - 1] ^= RB & msb.wrapping_neg();
29}
30
31/// Generic CMAC state over a 128-bit block cipher.
32#[derive(Clone)]
33pub struct Cmac<C: BlockCipher + Clone> {
34    cipher: C,
35    k1: [u8; BLOCK_LEN],
36    k2: [u8; BLOCK_LEN],
37    acc: [u8; BLOCK_LEN],
38    buf: [u8; BLOCK_LEN],
39    buffered: usize,
40}
41
42impl<C: BlockCipher + Clone> Drop for Cmac<C> {
43    fn drop(&mut self) {
44        self.k1.zeroize();
45        self.k2.zeroize();
46        self.acc.zeroize();
47        self.buf.zeroize();
48    }
49}
50
51impl<C: BlockCipher + Clone> Cmac<C> {
52    fn build(cipher: C) -> Result<Self> {
53        // L = E_K(0^128); K1 = dbl(L); K2 = dbl(K1).
54        let mut l = [0u8; BLOCK_LEN];
55        cipher.encrypt_block(&mut l)?;
56        let mut k1 = l;
57        dbl(&mut k1);
58        let mut k2 = k1;
59        dbl(&mut k2);
60        l.zeroize();
61        Ok(Self {
62            cipher,
63            k1,
64            k2,
65            acc: [0u8; BLOCK_LEN],
66            buf: [0u8; BLOCK_LEN],
67            buffered: 0,
68        })
69    }
70
71    fn absorb(&mut self, block: &[u8]) -> Result<()> {
72        for i in 0..BLOCK_LEN {
73            self.acc[i] ^= block[i];
74        }
75        let mut tmp = self.acc;
76        self.cipher.encrypt_block(&mut tmp)?;
77        self.acc = tmp;
78        Ok(())
79    }
80
81    fn absorb_buffered(&mut self) {
82        let block = self.buf;
83        // The cipher cannot fail on a correctly sized block; a failure here
84        // would be an internal invariant break, so the accumulator is poisoned
85        // rather than silently accepting a short MAC.
86        if self.absorb(&block).is_err() {
87            self.acc = [0xFFu8; BLOCK_LEN];
88        }
89        self.buffered = 0;
90    }
91}
92
93/// A CMAC tag: always one block.
94pub type CmacTag = [u8; BLOCK_LEN];
95
96macro_rules! cmac_variant {
97    (
98        $name:ident, $inner:ty, $id:literal, $disp:literal, $keylen:literal,
99        $kat_key:literal, $kat_tag:literal
100    ) => {
101        #[doc = concat!($disp, " (SP 800-38B).")]
102        pub type $name = Cmac<$inner>;
103
104        impl Algorithm for Cmac<$inner> {
105            const ID: &'static str = $id;
106            const NAME: &'static str = $disp;
107        }
108
109        impl SelfTest for Cmac<$inner> {
110            fn self_test() -> Result<()> {
111                // SP 800-38B example 1: the empty message.
112                let mut key = [0u8; $keylen];
113                ic_core::codec::hex_decode($kat_key.as_bytes(), &mut key)?;
114                let tag = <Self as Mac>::mac(&key, b"")?;
115                let mut want = [0u8; BLOCK_LEN];
116                ic_core::codec::hex_decode($kat_tag.as_bytes(), &mut want)?;
117                key.zeroize();
118                ensure!(ic_core::ct::verify(&want, &tag), SelfTestFailed, $id);
119                Ok(())
120            }
121        }
122    };
123}
124
125impl<C: BlockCipher + Clone> Mac for Cmac<C>
126where
127    Cmac<C>: Algorithm,
128{
129    type Tag = CmacTag;
130    const TAG_LEN: usize = BLOCK_LEN;
131
132    fn new(key: &[u8]) -> Result<Self> {
133        ensure!(
134            C::BLOCK_LEN == BLOCK_LEN,
135            InvalidParameter,
136            "cmac needs a 128-bit block"
137        );
138        Self::build(C::new(key)?)
139    }
140
141    fn update(&mut self, mut data: &[u8]) {
142        if self.buffered > 0 {
143            let take = core::cmp::min(BLOCK_LEN - self.buffered, data.len());
144            self.buf[self.buffered..self.buffered + take].copy_from_slice(&data[..take]);
145            self.buffered += take;
146            data = &data[take..];
147            // The final block is handled in `finalize`, so a full buffer is
148            // only flushed once more data is known to follow.
149            if self.buffered < BLOCK_LEN || data.is_empty() {
150                return;
151            }
152            self.absorb_buffered();
153        }
154        while data.len() > BLOCK_LEN {
155            let (block, rest) = data.split_at(BLOCK_LEN);
156            let _ = self.absorb(block);
157            data = rest;
158        }
159        self.buf[..data.len()].copy_from_slice(data);
160        self.buffered = data.len();
161    }
162
163    fn finalize(mut self) -> CmacTag {
164        let mut last = self.buf;
165        if self.buffered == BLOCK_LEN {
166            // Complete final block: XOR with K1.
167            for i in 0..BLOCK_LEN {
168                last[i] ^= self.k1[i];
169            }
170        } else {
171            // Incomplete (or empty) final block: 10* padding, XOR with K2.
172            last[self.buffered] = 0x80;
173            for b in last[self.buffered + 1..].iter_mut() {
174                *b = 0;
175            }
176            for i in 0..BLOCK_LEN {
177                last[i] ^= self.k2[i];
178            }
179        }
180        if self.absorb(&last).is_err() {
181            return [0xFFu8; BLOCK_LEN];
182        }
183        last.zeroize();
184        self.acc
185    }
186}
187
188cmac_variant!(
189    CmacAes128,
190    Aes128,
191    "cmac-aes-128",
192    "CMAC-AES-128",
193    16,
194    "2b7e151628aed2a6abf7158809cf4f3c",
195    "bb1d6929e95937287fa37d129b756746"
196);
197cmac_variant!(
198    CmacAes192,
199    Aes192,
200    "cmac-aes-192",
201    "CMAC-AES-192",
202    24,
203    "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
204    "d17ddf46adaacde531cac483de7a9367"
205);
206cmac_variant!(
207    CmacAes256,
208    Aes256,
209    "cmac-aes-256",
210    "CMAC-AES-256",
211    32,
212    "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
213    "028962f61b7bf89efc6b551f4667d983"
214);
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219    use ic_core::codec::{hex, unhex};
220
221    /// The SP 800-38B example message, from which each case takes a prefix.
222    const MSG: &str = "6bc1bee22e409f96e93d7e117393172a\
223                       ae2d8a571e03ac9c9eb76fac45af8e51\
224                       30c81c46a35ce411e5fbc1191a0a52ef\
225                       f69f2445df4f9b17ad2b417be66c3710";
226
227    fn msg_prefix(len: usize) -> Vec<u8> {
228        unhex(&MSG.replace(char::is_whitespace, "")).unwrap()[..len].to_vec()
229    }
230
231    #[test]
232    fn sp800_38b_aes128_examples() {
233        let key = unhex("2b7e151628aed2a6abf7158809cf4f3c").unwrap();
234        for (len, want) in [
235            (0usize, "bb1d6929e95937287fa37d129b756746"),
236            (16, "070a16b46b4d4144f79bdd9dd04a287c"),
237            (40, "dfa66747de9ae63030ca32611497c827"),
238            (64, "51f0bebf7e3b9d92fc49741779363cfe"),
239        ] {
240            let tag = CmacAes128::mac(&key, &msg_prefix(len)).unwrap();
241            assert_eq!(hex(&tag), want, "AES-128 CMAC over {len} bytes");
242        }
243    }
244
245    #[test]
246    fn sp800_38b_aes192_examples() {
247        let key = unhex("8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b").unwrap();
248        for (len, want) in [
249            (0usize, "d17ddf46adaacde531cac483de7a9367"),
250            (16, "9e99a7bf31e710900662f65e617c5184"),
251            (64, "a1d5df0eed790f794d77589659f39a11"),
252        ] {
253            let tag = CmacAes192::mac(&key, &msg_prefix(len)).unwrap();
254            assert_eq!(hex(&tag), want, "AES-192 CMAC over {len} bytes");
255        }
256    }
257
258    #[test]
259    fn sp800_38b_aes256_examples() {
260        let key =
261            unhex("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4").unwrap();
262        for (len, want) in [
263            (0usize, "028962f61b7bf89efc6b551f4667d983"),
264            (16, "28a7023f452e8f82bd4bf28d8c37c35c"),
265            (64, "e1992190549f6ed5696a2c056c315410"),
266        ] {
267            let tag = CmacAes256::mac(&key, &msg_prefix(len)).unwrap();
268            assert_eq!(hex(&tag), want, "AES-256 CMAC over {len} bytes");
269        }
270    }
271
272    #[test]
273    fn streaming_matches_one_shot() {
274        let key = unhex("2b7e151628aed2a6abf7158809cf4f3c").unwrap();
275        let data = msg_prefix(64);
276        for split in [0usize, 1, 15, 16, 17, 32, 63, 64] {
277            let mut m = CmacAes128::new(&key).unwrap();
278            m.update(&data[..split]);
279            m.update(&data[split..]);
280            assert_eq!(
281                m.finalize(),
282                CmacAes128::mac(&key, &data).unwrap(),
283                "split at {split}"
284            );
285        }
286    }
287
288    #[test]
289    fn subkey_doubling_reduces() {
290        // A value with the high bit set must pick up the Rb constant.
291        let mut b = [0u8; BLOCK_LEN];
292        b[0] = 0x80;
293        dbl(&mut b);
294        assert_eq!(b[BLOCK_LEN - 1], RB);
295        assert_eq!(b[0], 0);
296    }
297
298    #[test]
299    fn verify_detects_tampering() {
300        let key = unhex("2b7e151628aed2a6abf7158809cf4f3c").unwrap();
301        let tag = CmacAes128::mac(&key, b"data").unwrap();
302        CmacAes128::verify(&key, b"data", &tag).unwrap();
303        assert!(CmacAes128::verify(&key, b"datb", &tag).is_err());
304    }
305
306    #[test]
307    fn self_tests_pass() {
308        CmacAes128::self_test().unwrap();
309        CmacAes192::self_test().unwrap();
310        CmacAes256::self_test().unwrap();
311    }
312}