Skip to main content

zwave_security/
crypto.rs

1//! Thin wrappers over the RustCrypto primitives in the shapes Z-Wave uses.
2//!
3//! Every function here is a direct call into a maintained crate: AES-128
4//! (`aes`), AES-CMAC (`cmac`), AES-CCM with an 8-byte tag and a 13-byte nonce
5//! (`ccm`), AES-OFB (`ofb`) and AES-CBC-MAC (`cbc-mac`).
6
7use aes::cipher::{BlockCipherEncrypt, KeyInit, KeyIvInit, StreamCipher};
8use aes::Aes128;
9use ccm::aead::{Aead, Payload};
10use ccm::consts::{U13, U8};
11use cmac::Mac;
12
13/// AES-128-CCM as S2 uses it: 8-byte tag, 13-byte nonce.
14type S2Ccm = ccm::Ccm<Aes128, U8, U13>;
15
16/// Length of the CCM authentication tag S2 appends.
17pub const CCM_TAG_LEN: usize = 8;
18/// Length of the S2 CCM nonce.
19pub const CCM_NONCE_LEN: usize = 13;
20
21/// Encrypts one 16-byte block with AES-128 (ECB).
22pub fn aes128_ecb(key: &[u8; 16], block: &[u8; 16]) -> [u8; 16] {
23    let cipher = Aes128::new(key.into());
24    let mut b = aes::Block::from(*block);
25    cipher.encrypt_block(&mut b);
26    b.into()
27}
28
29/// AES-128-CMAC (NIST SP 800-38B) of `msg` under `key`.
30pub fn cmac(key: &[u8; 16], msg: &[u8]) -> [u8; 16] {
31    let mut mac = <cmac::Cmac<Aes128> as KeyInit>::new(key.into());
32    mac.update(msg);
33    mac.finalize().into_bytes().into()
34}
35
36/// AES-128-CCM encryption: returns ciphertext followed by the 8-byte tag.
37pub fn ccm_encrypt(key: &[u8; 16], nonce: &[u8; 13], aad: &[u8], plaintext: &[u8]) -> Vec<u8> {
38    let cipher = S2Ccm::new(key.into());
39    cipher
40        .encrypt(
41            nonce.into(),
42            Payload {
43                msg: plaintext,
44                aad,
45            },
46        )
47        // CCM with L=2 only fails for messages over 64 KiB, which a Z-Wave
48        // frame can never be.
49        .expect("CCM input within limits")
50}
51
52/// AES-128-CCM decryption of ciphertext-with-tag; `None` when authentication fails.
53pub fn ccm_decrypt(
54    key: &[u8; 16],
55    nonce: &[u8; 13],
56    aad: &[u8],
57    ciphertext_and_tag: &[u8],
58) -> Option<Vec<u8>> {
59    if ciphertext_and_tag.len() < CCM_TAG_LEN {
60        return None;
61    }
62    let cipher = S2Ccm::new(key.into());
63    cipher
64        .decrypt(
65            nonce.into(),
66            Payload {
67                msg: ciphertext_and_tag,
68                aad,
69            },
70        )
71        .ok()
72}
73
74/// AES-128-OFB keystream applied to `data` (encrypts and decrypts).
75pub fn aes128_ofb(key: &[u8; 16], iv: &[u8; 16], data: &[u8]) -> Vec<u8> {
76    let mut out = data.to_vec();
77    let mut cipher = ofb::Ofb::<Aes128>::new(key.into(), iv.into());
78    cipher.apply_keystream(&mut out);
79    out
80}
81
82/// AES-128-CBC-MAC with a zero IV and zero padding: the full last block.
83pub fn cbc_mac(key: &[u8; 16], data: &[u8]) -> [u8; 16] {
84    let mut mac = <cbc_mac::CbcMac<Aes128> as KeyInit>::new(key.into());
85    mac.update(data);
86    mac.finalize().into_bytes().into()
87}
88
89/// Increments a big-endian counter in place, wrapping.
90pub(crate) fn increment(block: &mut [u8]) {
91    for b in block.iter_mut().rev() {
92        let (v, carry) = b.overflowing_add(1);
93        *b = v;
94        if !carry {
95            break;
96        }
97    }
98}
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103
104    fn h(s: &str) -> Vec<u8> {
105        hex::decode(s.replace(' ', "")).unwrap()
106    }
107    fn k(s: &str) -> [u8; 16] {
108        h(s).try_into().unwrap()
109    }
110
111    // FIPS-197 appendix C.1.
112    #[test]
113    fn aes128_fips197() {
114        let key = k("000102030405060708090a0b0c0d0e0f");
115        let pt = k("00112233445566778899aabbccddeeff");
116        assert_eq!(
117            aes128_ecb(&key, &pt).to_vec(),
118            h("69c4e0d86a7b0430d8cdb78070b4c55a")
119        );
120    }
121
122    // RFC 4493 section 4, examples 1 to 4.
123    #[test]
124    fn cmac_rfc4493() {
125        let key = k("2b7e151628aed2a6abf7158809cf4f3c");
126        let m = h("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710");
127        assert_eq!(
128            cmac(&key, &[]).to_vec(),
129            h("bb1d6929e95937287fa37d129b756746")
130        );
131        assert_eq!(
132            cmac(&key, &m[..16]).to_vec(),
133            h("070a16b46b4d4144f79bdd9dd04a287c")
134        );
135        assert_eq!(
136            cmac(&key, &m[..40]).to_vec(),
137            h("dfa66747de9ae63030ca32611497c827")
138        );
139        assert_eq!(
140            cmac(&key, &m).to_vec(),
141            h("51f0bebf7e3b9d92fc49741779363cfe")
142        );
143    }
144
145    // RFC 3610 packet vector #1: AES-128, M = 8 (tag), L = 2 (13-byte nonce),
146    // the parameters S2 uses.
147    #[test]
148    fn ccm_rfc3610_vector1() {
149        let key = k("c0c1c2c3c4c5c6c7c8c9cacbcccdcecf");
150        let nonce: [u8; 13] = h("00000003020100a0a1a2a3a4a5").try_into().unwrap();
151        let aad = h("0001020304050607");
152        let pt = h("08090a0b0c0d0e0f101112131415161718191a1b1c1d1e");
153        let ct = ccm_encrypt(&key, &nonce, &aad, &pt);
154        assert_eq!(
155            ct,
156            h("588c979a61c663d2f066d0c2c0f989806d5f6b61dac38417e8d12cfdf926e0")
157        );
158        assert_eq!(ccm_decrypt(&key, &nonce, &aad, &ct).unwrap(), pt);
159        let mut bad = ct.clone();
160        bad[0] ^= 1;
161        assert!(ccm_decrypt(&key, &nonce, &aad, &bad).is_none());
162    }
163
164    // NIST SP 800-38A F.4.1 (OFB-AES128.Encrypt), first two blocks.
165    #[test]
166    fn ofb_sp800_38a() {
167        let key = k("2b7e151628aed2a6abf7158809cf4f3c");
168        let iv = k("000102030405060708090a0b0c0d0e0f");
169        let pt = h("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51");
170        assert_eq!(
171            aes128_ofb(&key, &iv, &pt),
172            h("3b3fd92eb72dad20333449f8e83cfb4a7789508d16918f03f53c52dac54ed825")
173        );
174    }
175
176    // CBC-MAC equals the last block of CBC encryption with a zero IV
177    // (SP 800-38A F.2.1, CBC-AES128.Encrypt, with that IV's effect removed by
178    // XORing it into the first plaintext block).
179    #[test]
180    fn cbc_mac_matches_cbc() {
181        let key = k("2b7e151628aed2a6abf7158809cf4f3c");
182        let iv = h("000102030405060708090a0b0c0d0e0f");
183        let mut pt = h("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51");
184        for (p, i) in pt.iter_mut().zip(iv) {
185            *p ^= i;
186        }
187        assert_eq!(
188            cbc_mac(&key, &pt).to_vec(),
189            h("5086cb9b507219ee95db113a917678b2")
190        );
191    }
192
193    // An S0 MAC from captured Z-Wave traffic (published with Z-Wave JS's tests).
194    #[test]
195    fn s0_mac_real_capture() {
196        let key = k("c5fe1ca17d36c992731a0c0c468c1ef9");
197        let data = h("ddd360c382a437514392826cbba0b3128114010cf3fb762d6e82126681c18597");
198        assert_eq!(cbc_mac(&key, &data)[..8].to_vec(), h("2bc20a8aa9bbb371"));
199    }
200
201    #[test]
202    fn increment_wraps() {
203        let mut b = [0x00, 0xff, 0xff];
204        increment(&mut b);
205        assert_eq!(b, [0x01, 0x00, 0x00]);
206        let mut b = [0xff; 2];
207        increment(&mut b);
208        assert_eq!(b, [0, 0]);
209    }
210}