• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  NIST SP800-38C compliant CCM implementation
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 /*
9  * Definition of CCM:
10  * http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf
11  * RFC 3610 "Counter with CBC-MAC (CCM)"
12  *
13  * Related:
14  * RFC 5116 "An Interface and Algorithms for Authenticated Encryption"
15  */
16 
17 #include "common.h"
18 
19 #if defined(MBEDTLS_CCM_C)
20 
21 #include "mbedtls/ccm.h"
22 #include "mbedtls/platform_util.h"
23 #include "mbedtls/error.h"
24 #include "mbedtls/constant_time.h"
25 
26 #include <string.h>
27 
28 #include "mbedtls/platform.h"
29 
30 #if !defined(MBEDTLS_CCM_ALT)
31 
32 #define CCM_VALIDATE_RET(cond) \
33     MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_CCM_BAD_INPUT)
34 #define CCM_VALIDATE(cond) \
35     MBEDTLS_INTERNAL_VALIDATE(cond)
36 
37 #define CCM_ENCRYPT 0
38 #define CCM_DECRYPT 1
39 
40 /*
41  * Initialize context
42  */
mbedtls_ccm_init(mbedtls_ccm_context * ctx)43 void mbedtls_ccm_init(mbedtls_ccm_context *ctx)
44 {
45     CCM_VALIDATE(ctx != NULL);
46     memset(ctx, 0, sizeof(mbedtls_ccm_context));
47 }
48 
mbedtls_ccm_setkey(mbedtls_ccm_context * ctx,mbedtls_cipher_id_t cipher,const unsigned char * key,unsigned int keybits)49 int mbedtls_ccm_setkey(mbedtls_ccm_context *ctx,
50                        mbedtls_cipher_id_t cipher,
51                        const unsigned char *key,
52                        unsigned int keybits)
53 {
54     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
55     const mbedtls_cipher_info_t *cipher_info;
56 
57     CCM_VALIDATE_RET(ctx != NULL);
58     CCM_VALIDATE_RET(key != NULL);
59 
60     cipher_info = mbedtls_cipher_info_from_values(cipher, keybits,
61                                                   MBEDTLS_MODE_ECB);
62     if (cipher_info == NULL) {
63         return MBEDTLS_ERR_CCM_BAD_INPUT;
64     }
65 
66     if (cipher_info->block_size != 16) {
67         return MBEDTLS_ERR_CCM_BAD_INPUT;
68     }
69 
70     mbedtls_cipher_free(&ctx->cipher_ctx);
71 
72     if ((ret = mbedtls_cipher_setup(&ctx->cipher_ctx, cipher_info)) != 0) {
73         return ret;
74     }
75 
76     if ((ret = mbedtls_cipher_setkey(&ctx->cipher_ctx, key, keybits,
77                                      MBEDTLS_ENCRYPT)) != 0) {
78         return ret;
79     }
80 
81     return 0;
82 }
83 
84 /*
85  * Free context
86  */
mbedtls_ccm_free(mbedtls_ccm_context * ctx)87 void mbedtls_ccm_free(mbedtls_ccm_context *ctx)
88 {
89     if (ctx == NULL) {
90         return;
91     }
92     mbedtls_cipher_free(&ctx->cipher_ctx);
93     mbedtls_platform_zeroize(ctx, sizeof(mbedtls_ccm_context));
94 }
95 
96 /*
97  * Macros for common operations.
98  * Results in smaller compiled code than static inline functions.
99  */
100 
101 /*
102  * Update the CBC-MAC state in y using a block in b
103  * (Always using b as the source helps the compiler optimise a bit better.)
104  */
105 #define UPDATE_CBC_MAC                                                      \
106     for (i = 0; i < 16; i++)                                               \
107     y[i] ^= b[i];                                                       \
108                                                                             \
109     if ((ret = mbedtls_cipher_update(&ctx->cipher_ctx, y, 16, y, &olen)) != 0) \
110     return ret;
111 
112 /*
113  * Encrypt or decrypt a partial block with CTR
114  * Warning: using b for temporary storage! src and dst must not be b!
115  * This avoids allocating one more 16 bytes buffer while allowing src == dst.
116  */
117 #define CTR_CRYPT(dst, src, len)                                            \
118     do                                                                  \
119     {                                                                   \
120         if ((ret = mbedtls_cipher_update(&ctx->cipher_ctx, ctr,       \
121                                          16, b, &olen)) != 0)      \
122         {                                                               \
123             return ret;                                              \
124         }                                                               \
125                                                                       \
126         for (i = 0; i < (len); i++)                                    \
127         (dst)[i] = (src)[i] ^ b[i];                                 \
128     } while (0)
129 
130 /*
131  * Authenticated encryption or decryption
132  */
ccm_auth_crypt(mbedtls_ccm_context * ctx,int mode,size_t length,const unsigned char * iv,size_t iv_len,const unsigned char * add,size_t add_len,const unsigned char * input,unsigned char * output,unsigned char * tag,size_t tag_len)133 static int ccm_auth_crypt(mbedtls_ccm_context *ctx, int mode, size_t length,
134                           const unsigned char *iv, size_t iv_len,
135                           const unsigned char *add, size_t add_len,
136                           const unsigned char *input, unsigned char *output,
137                           unsigned char *tag, size_t tag_len)
138 {
139     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
140     unsigned char i;
141     unsigned char q;
142     size_t len_left, olen;
143     unsigned char b[16];
144     unsigned char y[16];
145     unsigned char ctr[16];
146     const unsigned char *src;
147     unsigned char *dst;
148 
149     /*
150      * Check length requirements: SP800-38C A.1
151      * Additional requirement: a < 2^16 - 2^8 to simplify the code.
152      * 'length' checked later (when writing it to the first block)
153      *
154      * Also, loosen the requirements to enable support for CCM* (IEEE 802.15.4).
155      */
156     if (tag_len == 2 || tag_len > 16 || tag_len % 2 != 0) {
157         return MBEDTLS_ERR_CCM_BAD_INPUT;
158     }
159 
160     /* Also implies q is within bounds */
161     if (iv_len < 7 || iv_len > 13) {
162         return MBEDTLS_ERR_CCM_BAD_INPUT;
163     }
164 
165     if (add_len >= 0xFF00) {
166         return MBEDTLS_ERR_CCM_BAD_INPUT;
167     }
168 
169     q = 16 - 1 - (unsigned char) iv_len;
170 
171     /*
172      * First block B_0:
173      * 0        .. 0        flags
174      * 1        .. iv_len   nonce (aka iv)
175      * iv_len+1 .. 15       length
176      *
177      * With flags as (bits):
178      * 7        0
179      * 6        add present?
180      * 5 .. 3   (t - 2) / 2
181      * 2 .. 0   q - 1
182      */
183     b[0] = 0;
184     b[0] |= (add_len > 0) << 6;
185     b[0] |= ((tag_len - 2) / 2) << 3;
186     b[0] |= q - 1;
187 
188     memcpy(b + 1, iv, iv_len);
189 
190     for (i = 0, len_left = length; i < q; i++, len_left >>= 8) {
191         b[15-i] = MBEDTLS_BYTE_0(len_left);
192     }
193 
194     if (len_left > 0) {
195         return MBEDTLS_ERR_CCM_BAD_INPUT;
196     }
197 
198 
199     /* Start CBC-MAC with first block */
200     memset(y, 0, 16);
201     UPDATE_CBC_MAC;
202 
203     /*
204      * If there is additional data, update CBC-MAC with
205      * add_len, add, 0 (padding to a block boundary)
206      */
207     if (add_len > 0) {
208         size_t use_len;
209         len_left = add_len;
210         src = add;
211 
212         memset(b, 0, 16);
213         MBEDTLS_PUT_UINT16_BE(add_len, b, 0);
214 
215         use_len = len_left < 16 - 2 ? len_left : 16 - 2;
216         memcpy(b + 2, src, use_len);
217         len_left -= use_len;
218         src += use_len;
219 
220         UPDATE_CBC_MAC;
221 
222         while (len_left > 0) {
223             use_len = len_left > 16 ? 16 : len_left;
224 
225             memset(b, 0, 16);
226             memcpy(b, src, use_len);
227             UPDATE_CBC_MAC;
228 
229             len_left -= use_len;
230             src += use_len;
231         }
232     }
233 
234     /*
235      * Prepare counter block for encryption:
236      * 0        .. 0        flags
237      * 1        .. iv_len   nonce (aka iv)
238      * iv_len+1 .. 15       counter (initially 1)
239      *
240      * With flags as (bits):
241      * 7 .. 3   0
242      * 2 .. 0   q - 1
243      */
244     ctr[0] = q - 1;
245     memcpy(ctr + 1, iv, iv_len);
246     memset(ctr + 1 + iv_len, 0, q);
247     ctr[15] = 1;
248 
249     /*
250      * Authenticate and {en,de}crypt the message.
251      *
252      * The only difference between encryption and decryption is
253      * the respective order of authentication and {en,de}cryption.
254      */
255     len_left = length;
256     src = input;
257     dst = output;
258 
259     while (len_left > 0) {
260         size_t use_len = len_left > 16 ? 16 : len_left;
261 
262         if (mode == CCM_ENCRYPT) {
263             memset(b, 0, 16);
264             memcpy(b, src, use_len);
265             UPDATE_CBC_MAC;
266         }
267 
268         CTR_CRYPT(dst, src, use_len);
269 
270         if (mode == CCM_DECRYPT) {
271             memset(b, 0, 16);
272             memcpy(b, dst, use_len);
273             UPDATE_CBC_MAC;
274         }
275 
276         dst += use_len;
277         src += use_len;
278         len_left -= use_len;
279 
280         /*
281          * Increment counter.
282          * No need to check for overflow thanks to the length check above.
283          */
284         for (i = 0; i < q; i++) {
285             if (++ctr[15-i] != 0) {
286                 break;
287             }
288         }
289     }
290 
291     /*
292      * Authentication: reset counter and crypt/mask internal tag
293      */
294     for (i = 0; i < q; i++) {
295         ctr[15-i] = 0;
296     }
297 
298     CTR_CRYPT(y, y, 16);
299     memcpy(tag, y, tag_len);
300 
301     return 0;
302 }
303 
304 /*
305  * Authenticated encryption
306  */
mbedtls_ccm_star_encrypt_and_tag(mbedtls_ccm_context * ctx,size_t length,const unsigned char * iv,size_t iv_len,const unsigned char * add,size_t add_len,const unsigned char * input,unsigned char * output,unsigned char * tag,size_t tag_len)307 int mbedtls_ccm_star_encrypt_and_tag(mbedtls_ccm_context *ctx, size_t length,
308                                      const unsigned char *iv, size_t iv_len,
309                                      const unsigned char *add, size_t add_len,
310                                      const unsigned char *input, unsigned char *output,
311                                      unsigned char *tag, size_t tag_len)
312 {
313     CCM_VALIDATE_RET(ctx != NULL);
314     CCM_VALIDATE_RET(iv != NULL);
315     CCM_VALIDATE_RET(add_len == 0 || add != NULL);
316     CCM_VALIDATE_RET(length == 0 || input != NULL);
317     CCM_VALIDATE_RET(length == 0 || output != NULL);
318     CCM_VALIDATE_RET(tag_len == 0 || tag != NULL);
319     return ccm_auth_crypt(ctx, CCM_ENCRYPT, length, iv, iv_len,
320                           add, add_len, input, output, tag, tag_len);
321 }
322 
mbedtls_ccm_encrypt_and_tag(mbedtls_ccm_context * ctx,size_t length,const unsigned char * iv,size_t iv_len,const unsigned char * add,size_t add_len,const unsigned char * input,unsigned char * output,unsigned char * tag,size_t tag_len)323 int mbedtls_ccm_encrypt_and_tag(mbedtls_ccm_context *ctx, size_t length,
324                                 const unsigned char *iv, size_t iv_len,
325                                 const unsigned char *add, size_t add_len,
326                                 const unsigned char *input, unsigned char *output,
327                                 unsigned char *tag, size_t tag_len)
328 {
329     CCM_VALIDATE_RET(ctx != NULL);
330     CCM_VALIDATE_RET(iv != NULL);
331     CCM_VALIDATE_RET(add_len == 0 || add != NULL);
332     CCM_VALIDATE_RET(length == 0 || input != NULL);
333     CCM_VALIDATE_RET(length == 0 || output != NULL);
334     CCM_VALIDATE_RET(tag_len == 0 || tag != NULL);
335     if (tag_len == 0) {
336         return MBEDTLS_ERR_CCM_BAD_INPUT;
337     }
338 
339     return mbedtls_ccm_star_encrypt_and_tag(ctx, length, iv, iv_len, add,
340                                             add_len, input, output, tag, tag_len);
341 }
342 
343 /*
344  * Authenticated decryption
345  */
mbedtls_ccm_star_auth_decrypt(mbedtls_ccm_context * ctx,size_t length,const unsigned char * iv,size_t iv_len,const unsigned char * add,size_t add_len,const unsigned char * input,unsigned char * output,const unsigned char * tag,size_t tag_len)346 int mbedtls_ccm_star_auth_decrypt(mbedtls_ccm_context *ctx, size_t length,
347                                   const unsigned char *iv, size_t iv_len,
348                                   const unsigned char *add, size_t add_len,
349                                   const unsigned char *input, unsigned char *output,
350                                   const unsigned char *tag, size_t tag_len)
351 {
352     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
353     unsigned char check_tag[16];
354     int diff;
355 
356     CCM_VALIDATE_RET(ctx != NULL);
357     CCM_VALIDATE_RET(iv != NULL);
358     CCM_VALIDATE_RET(add_len == 0 || add != NULL);
359     CCM_VALIDATE_RET(length == 0 || input != NULL);
360     CCM_VALIDATE_RET(length == 0 || output != NULL);
361     CCM_VALIDATE_RET(tag_len == 0 || tag != NULL);
362 
363     if ((ret = ccm_auth_crypt(ctx, CCM_DECRYPT, length,
364                               iv, iv_len, add, add_len,
365                               input, output, check_tag, tag_len)) != 0) {
366         return ret;
367     }
368 
369     /* Check tag in "constant-time" */
370     diff = mbedtls_ct_memcmp(tag, check_tag, tag_len);
371 
372     if (diff != 0) {
373         mbedtls_platform_zeroize(output, length);
374         return MBEDTLS_ERR_CCM_AUTH_FAILED;
375     }
376 
377     return 0;
378 }
379 
mbedtls_ccm_auth_decrypt(mbedtls_ccm_context * ctx,size_t length,const unsigned char * iv,size_t iv_len,const unsigned char * add,size_t add_len,const unsigned char * input,unsigned char * output,const unsigned char * tag,size_t tag_len)380 int mbedtls_ccm_auth_decrypt(mbedtls_ccm_context *ctx, size_t length,
381                              const unsigned char *iv, size_t iv_len,
382                              const unsigned char *add, size_t add_len,
383                              const unsigned char *input, unsigned char *output,
384                              const unsigned char *tag, size_t tag_len)
385 {
386     CCM_VALIDATE_RET(ctx != NULL);
387     CCM_VALIDATE_RET(iv != NULL);
388     CCM_VALIDATE_RET(add_len == 0 || add != NULL);
389     CCM_VALIDATE_RET(length == 0 || input != NULL);
390     CCM_VALIDATE_RET(length == 0 || output != NULL);
391     CCM_VALIDATE_RET(tag_len == 0 || tag != NULL);
392 
393     if (tag_len == 0) {
394         return MBEDTLS_ERR_CCM_BAD_INPUT;
395     }
396 
397     return mbedtls_ccm_star_auth_decrypt(ctx, length, iv, iv_len, add,
398                                          add_len, input, output, tag, tag_len);
399 }
400 #endif /* !MBEDTLS_CCM_ALT */
401 
402 #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
403 /*
404  * Examples 1 to 3 from SP800-38C Appendix C
405  */
406 
407 #define NB_TESTS 3
408 #define CCM_SELFTEST_PT_MAX_LEN 24
409 #define CCM_SELFTEST_CT_MAX_LEN 32
410 /*
411  * The data is the same for all tests, only the used length changes
412  */
413 static const unsigned char key_test_data[] = {
414     0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
415     0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f
416 };
417 
418 static const unsigned char iv_test_data[] = {
419     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
420     0x18, 0x19, 0x1a, 0x1b
421 };
422 
423 static const unsigned char ad_test_data[] = {
424     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
425     0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
426     0x10, 0x11, 0x12, 0x13
427 };
428 
429 static const unsigned char msg_test_data[CCM_SELFTEST_PT_MAX_LEN] = {
430     0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
431     0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
432     0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
433 };
434 
435 static const size_t iv_len_test_data[NB_TESTS] = { 7, 8,  12 };
436 static const size_t add_len_test_data[NB_TESTS] = { 8, 16, 20 };
437 static const size_t msg_len_test_data[NB_TESTS] = { 4, 16, 24 };
438 static const size_t tag_len_test_data[NB_TESTS] = { 4, 6,  8  };
439 
440 static const unsigned char res_test_data[NB_TESTS][CCM_SELFTEST_CT_MAX_LEN] = {
441     {   0x71, 0x62, 0x01, 0x5b, 0x4d, 0xac, 0x25, 0x5d },
442     {   0xd2, 0xa1, 0xf0, 0xe0, 0x51, 0xea, 0x5f, 0x62,
443         0x08, 0x1a, 0x77, 0x92, 0x07, 0x3d, 0x59, 0x3d,
444         0x1f, 0xc6, 0x4f, 0xbf, 0xac, 0xcd },
445     {   0xe3, 0xb2, 0x01, 0xa9, 0xf5, 0xb7, 0x1a, 0x7a,
446         0x9b, 0x1c, 0xea, 0xec, 0xcd, 0x97, 0xe7, 0x0b,
447         0x61, 0x76, 0xaa, 0xd9, 0xa4, 0x42, 0x8a, 0xa5,
448         0x48, 0x43, 0x92, 0xfb, 0xc1, 0xb0, 0x99, 0x51 }
449 };
450 
mbedtls_ccm_self_test(int verbose)451 int mbedtls_ccm_self_test(int verbose)
452 {
453     mbedtls_ccm_context ctx;
454     /*
455      * Some hardware accelerators require the input and output buffers
456      * would be in RAM, because the flash is not accessible.
457      * Use buffers on the stack to hold the test vectors data.
458      */
459     unsigned char plaintext[CCM_SELFTEST_PT_MAX_LEN];
460     unsigned char ciphertext[CCM_SELFTEST_CT_MAX_LEN];
461     size_t i;
462     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
463 
464     mbedtls_ccm_init(&ctx);
465 
466     if (mbedtls_ccm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, key_test_data,
467                            8 * sizeof(key_test_data)) != 0) {
468         if (verbose != 0) {
469             mbedtls_printf("  CCM: setup failed");
470         }
471 
472         return 1;
473     }
474 
475     for (i = 0; i < NB_TESTS; i++) {
476         if (verbose != 0) {
477             mbedtls_printf("  CCM-AES #%u: ", (unsigned int) i + 1);
478         }
479 
480         memset(plaintext, 0, CCM_SELFTEST_PT_MAX_LEN);
481         memset(ciphertext, 0, CCM_SELFTEST_CT_MAX_LEN);
482         memcpy(plaintext, msg_test_data, msg_len_test_data[i]);
483 
484         ret = mbedtls_ccm_encrypt_and_tag(&ctx, msg_len_test_data[i],
485                                           iv_test_data, iv_len_test_data[i],
486                                           ad_test_data, add_len_test_data[i],
487                                           plaintext, ciphertext,
488                                           ciphertext + msg_len_test_data[i],
489                                           tag_len_test_data[i]);
490 
491         if (ret != 0 ||
492             memcmp(ciphertext, res_test_data[i],
493                    msg_len_test_data[i] + tag_len_test_data[i]) != 0) {
494             if (verbose != 0) {
495                 mbedtls_printf("failed\n");
496             }
497 
498             return 1;
499         }
500         memset(plaintext, 0, CCM_SELFTEST_PT_MAX_LEN);
501 
502         ret = mbedtls_ccm_auth_decrypt(&ctx, msg_len_test_data[i],
503                                        iv_test_data, iv_len_test_data[i],
504                                        ad_test_data, add_len_test_data[i],
505                                        ciphertext, plaintext,
506                                        ciphertext + msg_len_test_data[i],
507                                        tag_len_test_data[i]);
508 
509         if (ret != 0 ||
510             memcmp(plaintext, msg_test_data, msg_len_test_data[i]) != 0) {
511             if (verbose != 0) {
512                 mbedtls_printf("failed\n");
513             }
514 
515             return 1;
516         }
517 
518         if (verbose != 0) {
519             mbedtls_printf("passed\n");
520         }
521     }
522 
523     mbedtls_ccm_free(&ctx);
524 
525     if (verbose != 0) {
526         mbedtls_printf("\n");
527     }
528 
529     return 0;
530 }
531 
532 #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
533 
534 #endif /* MBEDTLS_CCM_C */
535