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