rustls-ccm 0.2.0

CCM and CCM-8 cipher suites for rustls (TLS 1.2 and TLS 1.3)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#![warn(missing_docs)]
//! AES-CCM cipher suites for [rustls](https://github.com/rustls/rustls).
//!
//! Neither [aws-lc-rs](https://github.com/aws/aws-lc-rs) nor
//! [ring](https://github.com/briansmith/ring) expose AES-CCM, so rustls's
//! built-in providers cannot offer these suites. This crate fills the gap
//! using the [RustCrypto](https://github.com/RustCrypto) `aes` + `ccm` crates,
//! plugged in via rustls's [`CryptoProvider`]
//! extension point.
//!
//! CCM cipher suites are required or recommended by several IoT and energy
//! protocols, including IEEE 2030.5 (Smart Energy), Matter, Thread, and
//! constrained-device TLS profiles (RFC 7925).
//!
//! # Cipher suites
//!
//! ## TLS 1.2 ([RFC 7251](https://www.rfc-editor.org/rfc/rfc7251))
//!
//! | Suite | Tag | Key |
//! |---|---|---|
//! | [`TLS_ECDHE_ECDSA_WITH_AES_128_CCM`] | 16 B | 128-bit |
//! | [`TLS_ECDHE_ECDSA_WITH_AES_256_CCM`] | 16 B | 256-bit |
//! | [`TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8`] | 8 B | 128-bit |
//! | [`TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8`] | 8 B | 256-bit |
//!
//! ## TLS 1.3 ([RFC 8446](https://www.rfc-editor.org/rfc/rfc8446))
//!
//! | Suite | Tag | Key |
//! |---|---|---|
//! | [`TLS13_AES_128_CCM_SHA256`] | 16 B | 128-bit |
//! | [`TLS13_AES_128_CCM_8_SHA256`] | 8 B | 128-bit |
//!
//! # Limitations
//!
//! Raw traffic-secret extraction for kTLS/hardware offload
//! (`dangerous_extract_secrets()`) is not supported:
//! [`ConnectionTrafficSecrets`](rustls::ConnectionTrafficSecrets) has no CCM
//! variant, so `extract_keys` returns `UnsupportedOperationError` for all CCM
//! suites. `SSLKEYLOGFILE`-style key logging ([`rustls::KeyLog`]) works
//! normally — it is fed from the key schedule and does not involve
//! `extract_keys`.
//!
//! # Usage
//!
//! Use [`crypto_provider()`] for an aws-lc-rs provider with all CCM suites
//! appended after the defaults (CCM is negotiated only when the peer offers
//! nothing stronger), or pick individual suites and build your own provider.
//!
//! ```
//! let provider = rustls_ccm::crypto_provider();
//! let config = rustls::ClientConfig::builder_with_provider(provider.into())
//!     .with_safe_default_protocol_versions()
//!     .unwrap();
//! ```

use std::sync::LazyLock;

use aes::{Aes128, Aes256};
use ccm::Ccm;
use ccm::aead::{AeadCore, AeadInOut, KeyInit};
use ccm::consts::{U8, U12, U16};
use rustls::crypto::CryptoProvider;
use rustls::{
    CipherSuite, CipherSuiteCommon, SupportedCipherSuite, Tls12CipherSuite, Tls13CipherSuite,
};

mod tls12;
mod tls13;

// ---------------------------------------------------------------------------
// Cipher variant abstraction
// ---------------------------------------------------------------------------

/// Trait abstracting over the four AES-CCM cipher configurations.
pub(crate) trait CcmVariant: Send + Sync + 'static {
    type Cipher: AeadInOut + AeadCore<NonceSize = U12> + KeyInit + Send + Sync;
    const KEY_LEN: usize;
    const TAG_LEN: usize;
}

pub(crate) enum Aes128Ccm8V {}
impl CcmVariant for Aes128Ccm8V {
    type Cipher = Ccm<Aes128, U8, U12>;
    const KEY_LEN: usize = 16;
    const TAG_LEN: usize = 8;
}

pub(crate) enum Aes128Ccm16V {}
impl CcmVariant for Aes128Ccm16V {
    type Cipher = Ccm<Aes128, U16, U12>;
    const KEY_LEN: usize = 16;
    const TAG_LEN: usize = 16;
}

pub(crate) enum Aes256Ccm8V {}
impl CcmVariant for Aes256Ccm8V {
    type Cipher = Ccm<Aes256, U8, U12>;
    const KEY_LEN: usize = 32;
    const TAG_LEN: usize = 8;
}

pub(crate) enum Aes256Ccm16V {}
impl CcmVariant for Aes256Ccm16V {
    type Cipher = Ccm<Aes256, U16, U12>;
    const KEY_LEN: usize = 32;
    const TAG_LEN: usize = 16;
}

// CCM makes two block-cipher calls per 16-byte block (CBC-MAC + CTR), so per
// the CFRG AEAD limits analysis its confidentiality margin at a given data
// volume is roughly half of GCM's. rustls uses 1 << 24 records for AES-GCM;
// halve it for CCM.
const CONFIDENTIALITY_LIMIT: u64 = 1 << 23;

// ---------------------------------------------------------------------------
// TLS 1.2 suite definitions (RFC 7251) — all use SHA-256
// ---------------------------------------------------------------------------

fn tls12_base() -> &'static Tls12CipherSuite {
    let base = rustls::crypto::aws_lc_rs::cipher_suite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256;
    let SupportedCipherSuite::Tls12(s) = base else {
        unreachable!()
    };
    s
}

static SUITE_TLS12_128_CCM: LazyLock<Tls12CipherSuite> = LazyLock::new(|| {
    let base = tls12_base();
    Tls12CipherSuite {
        common: CipherSuiteCommon {
            suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
            hash_provider: base.common.hash_provider,
            confidentiality_limit: CONFIDENTIALITY_LIMIT,
        },
        prf_provider: base.prf_provider,
        kx: base.kx,
        sign: base.sign,
        aead_alg: &tls12::Tls12CcmAead::<Aes128Ccm16V>::NEW,
    }
});

static SUITE_TLS12_256_CCM: LazyLock<Tls12CipherSuite> = LazyLock::new(|| {
    let base = tls12_base();
    Tls12CipherSuite {
        common: CipherSuiteCommon {
            suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CCM,
            hash_provider: base.common.hash_provider,
            confidentiality_limit: CONFIDENTIALITY_LIMIT,
        },
        prf_provider: base.prf_provider,
        kx: base.kx,
        sign: base.sign,
        aead_alg: &tls12::Tls12CcmAead::<Aes256Ccm16V>::NEW,
    }
});

static SUITE_TLS12_128_CCM8: LazyLock<Tls12CipherSuite> = LazyLock::new(|| {
    let base = tls12_base();
    Tls12CipherSuite {
        common: CipherSuiteCommon {
            suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
            hash_provider: base.common.hash_provider,
            confidentiality_limit: CONFIDENTIALITY_LIMIT,
        },
        prf_provider: base.prf_provider,
        kx: base.kx,
        sign: base.sign,
        aead_alg: &tls12::Tls12CcmAead::<Aes128Ccm8V>::NEW,
    }
});

static SUITE_TLS12_256_CCM8: LazyLock<Tls12CipherSuite> = LazyLock::new(|| {
    let base = tls12_base();
    Tls12CipherSuite {
        common: CipherSuiteCommon {
            suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
            hash_provider: base.common.hash_provider,
            confidentiality_limit: CONFIDENTIALITY_LIMIT,
        },
        prf_provider: base.prf_provider,
        kx: base.kx,
        sign: base.sign,
        aead_alg: &tls12::Tls12CcmAead::<Aes256Ccm8V>::NEW,
    }
});

// ---------------------------------------------------------------------------
// TLS 1.3 suite definitions (RFC 8446) — both use SHA-256
// ---------------------------------------------------------------------------

fn tls13_base() -> &'static Tls13CipherSuite {
    let base = rustls::crypto::aws_lc_rs::cipher_suite::TLS13_AES_128_GCM_SHA256;
    let SupportedCipherSuite::Tls13(s) = base else {
        unreachable!()
    };
    s
}

static SUITE_TLS13_128_CCM: LazyLock<Tls13CipherSuite> = LazyLock::new(|| {
    let base = tls13_base();
    Tls13CipherSuite {
        common: CipherSuiteCommon {
            suite: CipherSuite::TLS13_AES_128_CCM_SHA256,
            hash_provider: base.common.hash_provider,
            confidentiality_limit: CONFIDENTIALITY_LIMIT,
        },
        hkdf_provider: base.hkdf_provider,
        aead_alg: &tls13::Tls13CcmAead::<Aes128Ccm16V>::NEW,
        quic: None,
    }
});

static SUITE_TLS13_128_CCM8: LazyLock<Tls13CipherSuite> = LazyLock::new(|| {
    let base = tls13_base();
    Tls13CipherSuite {
        common: CipherSuiteCommon {
            suite: CipherSuite::TLS13_AES_128_CCM_8_SHA256,
            hash_provider: base.common.hash_provider,
            confidentiality_limit: CONFIDENTIALITY_LIMIT,
        },
        hkdf_provider: base.hkdf_provider,
        aead_alg: &tls13::Tls13CcmAead::<Aes128Ccm8V>::NEW,
        quic: None,
    }
});

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// `TLS_ECDHE_ECDSA_WITH_AES_128_CCM` (0xC0AC, RFC 7251).
pub static TLS_ECDHE_ECDSA_WITH_AES_128_CCM: LazyLock<SupportedCipherSuite> =
    LazyLock::new(|| SupportedCipherSuite::Tls12(&SUITE_TLS12_128_CCM));

/// `TLS_ECDHE_ECDSA_WITH_AES_256_CCM` (0xC0AD, RFC 7251).
pub static TLS_ECDHE_ECDSA_WITH_AES_256_CCM: LazyLock<SupportedCipherSuite> =
    LazyLock::new(|| SupportedCipherSuite::Tls12(&SUITE_TLS12_256_CCM));

/// `TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8` (0xC0AE, RFC 7251).
pub static TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: LazyLock<SupportedCipherSuite> =
    LazyLock::new(|| SupportedCipherSuite::Tls12(&SUITE_TLS12_128_CCM8));

/// `TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8` (0xC0AF, RFC 7251).
pub static TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8: LazyLock<SupportedCipherSuite> =
    LazyLock::new(|| SupportedCipherSuite::Tls12(&SUITE_TLS12_256_CCM8));

/// `TLS_AES_128_CCM_SHA256` (0x1304, RFC 8446). Recommended=Y.
///
/// Standard TLS 1.3 cipher suite for constrained environments (Matter, Thread, CoAP).
pub static TLS13_AES_128_CCM_SHA256: LazyLock<SupportedCipherSuite> =
    LazyLock::new(|| SupportedCipherSuite::Tls13(&SUITE_TLS13_128_CCM));

/// `TLS_AES_128_CCM_8_SHA256` (0x1305, RFC 8446).
///
/// TLS 1.3 cipher suite with truncated 8-byte tag for bandwidth-constrained devices.
pub static TLS13_AES_128_CCM_8_SHA256: LazyLock<SupportedCipherSuite> =
    LazyLock::new(|| SupportedCipherSuite::Tls13(&SUITE_TLS13_128_CCM8));

/// All CCM cipher suites provided by this crate (TLS 1.2 + TLS 1.3).
pub fn all_suites() -> [SupportedCipherSuite; 6] {
    [
        *TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
        *TLS_ECDHE_ECDSA_WITH_AES_256_CCM,
        *TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
        *TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
        *TLS13_AES_128_CCM_SHA256,
        *TLS13_AES_128_CCM_8_SHA256,
    ]
}

/// Returns an aws-lc-rs [`CryptoProvider`] with all CCM suites appended.
///
/// The default suites keep priority: a rustls server built from this provider
/// still prefers AES-GCM / ChaCha20-Poly1305 and falls back to CCM only for
/// peers that offer nothing stronger. To *prefer* CCM (e.g. a profile that
/// mandates it, like IEEE 2030.5), insert the suites you want at the front
/// instead:
///
/// ```
/// let mut provider = rustls::crypto::aws_lc_rs::default_provider();
/// provider
///     .cipher_suites
///     .insert(0, *rustls_ccm::TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
/// ```
pub fn crypto_provider() -> CryptoProvider {
    let mut provider = rustls::crypto::aws_lc_rs::default_provider();
    provider.cipher_suites.extend(all_suites());
    provider
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn all_suites_accessible() {
        let suites = all_suites();
        assert_eq!(
            suites[0].suite(),
            CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CCM
        );
        assert_eq!(
            suites[1].suite(),
            CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CCM
        );
        assert_eq!(
            suites[2].suite(),
            CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
        );
        assert_eq!(
            suites[3].suite(),
            CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8
        );
        assert_eq!(suites[4].suite(), CipherSuite::TLS13_AES_128_CCM_SHA256);
        assert_eq!(suites[5].suite(), CipherSuite::TLS13_AES_128_CCM_8_SHA256);
    }

    #[test]
    fn crypto_provider_includes_all_ccm() {
        let provider = crypto_provider();
        for suite in all_suites() {
            assert!(
                provider
                    .cipher_suites
                    .iter()
                    .any(|s| s.suite() == suite.suite()),
                "missing {:?}",
                suite.suite()
            );
        }
    }

    #[test]
    fn ccm_round_trip() {
        let key = [0x42u8; 16];
        let nonce = ccm::aead::array::Array::from([1u8; 12]);
        let aad = b"additional data";
        let plaintext = b"hello CCM";

        // Full tag (16-byte)
        let cipher = <Ccm<Aes128, U16, U12> as KeyInit>::new_from_slice(&key).unwrap();
        let mut buf = plaintext.to_vec();
        let tag = cipher
            .encrypt_inout_detached(&nonce, aad.as_slice(), buf.as_mut_slice().into())
            .unwrap();
        assert_eq!(tag.len(), 16);
        cipher
            .decrypt_inout_detached(&nonce, aad.as_slice(), buf.as_mut_slice().into(), &tag)
            .unwrap();
        assert_eq!(&buf, plaintext);

        // 8-byte tag
        let cipher8 = <Ccm<Aes128, U8, U12> as KeyInit>::new_from_slice(&key).unwrap();
        let mut buf = plaintext.to_vec();
        let tag = cipher8
            .encrypt_inout_detached(&nonce, aad.as_slice(), buf.as_mut_slice().into())
            .unwrap();
        assert_eq!(tag.len(), 8);
        cipher8
            .decrypt_inout_detached(&nonce, aad.as_slice(), buf.as_mut_slice().into(), &tag)
            .unwrap();
        assert_eq!(&buf, plaintext);
    }

    #[test]
    fn ccm_tampered_fails() {
        let key = [0x42u8; 16];
        let nonce = ccm::aead::array::Array::from([2u8; 12]);
        let cipher = <Ccm<Aes128, U16, U12> as KeyInit>::new_from_slice(&key).unwrap();
        let mut buf = b"secret".to_vec();
        let tag = cipher
            .encrypt_inout_detached(&nonce, b"", buf.as_mut_slice().into())
            .unwrap();
        buf[0] ^= 0xff;
        assert!(
            cipher
                .decrypt_inout_detached(&nonce, b"", buf.as_mut_slice().into(), &tag)
                .is_err()
        );
    }

    #[test]
    fn ccm256_round_trip() {
        let key = [0x42u8; 32];
        let nonce = ccm::aead::array::Array::from([3u8; 12]);
        let cipher = <Ccm<Aes256, U16, U12> as KeyInit>::new_from_slice(&key).unwrap();
        let mut buf = b"aes-256-ccm".to_vec();
        let tag = cipher
            .encrypt_inout_detached(&nonce, b"", buf.as_mut_slice().into())
            .unwrap();
        cipher
            .decrypt_inout_detached(&nonce, b"", buf.as_mut_slice().into(), &tag)
            .unwrap();
        assert_eq!(&buf, b"aes-256-ccm");
    }

    #[test]
    fn tls12_key_block_shapes() {
        use rustls::crypto::cipher::Tls12AeadAlgorithm;

        let aead128 = tls12::Tls12CcmAead::<Aes128Ccm16V>::NEW;
        assert_eq!(aead128.key_block_shape().enc_key_len, 16);

        let aead256 = tls12::Tls12CcmAead::<Aes256Ccm16V>::NEW;
        assert_eq!(aead256.key_block_shape().enc_key_len, 32);

        let aead128_8 = tls12::Tls12CcmAead::<Aes128Ccm8V>::NEW;
        assert_eq!(aead128_8.key_block_shape().enc_key_len, 16);
        assert_eq!(aead128_8.key_block_shape().fixed_iv_len, 4);
        assert_eq!(aead128_8.key_block_shape().explicit_nonce_len, 8);
    }

    #[test]
    fn tls13_key_lens() {
        use rustls::crypto::cipher::Tls13AeadAlgorithm;

        assert_eq!(tls13::Tls13CcmAead::<Aes128Ccm16V>::NEW.key_len(), 16);
        assert_eq!(tls13::Tls13CcmAead::<Aes128Ccm8V>::NEW.key_len(), 16);
    }
}