1 /*
2  * aes_icm_mbedtls.c
3  *
4  * AES Integer Counter Mode
5  *
6  * YongCheng Yang
7  */
8 
9 /*
10  *
11  * Copyright (c) 2013-2017, Cisco Systems, Inc.
12  * All rights reserved.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  *
18  *   Redistributions of source code must retain the above copyright
19  *   notice, this list of conditions and the following disclaimer.
20  *
21  *   Redistributions in binary form must reproduce the above
22  *   copyright notice, this list of conditions and the following
23  *   disclaimer in the documentation and/or other materials provided
24  *   with the distribution.
25  *
26  *   Neither the name of the Cisco Systems, Inc. nor the names of its
27  *   contributors may be used to endorse or promote products derived
28  *   from this software without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
31  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
32  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
33  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
34  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
35  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
36  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
37  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
41  * OF THE POSSIBILITY OF SUCH DAMAGE.
42  *
43  */
44 
45 #ifdef HAVE_CONFIG_H
46 #include <config.h>
47 #endif
48 #include <mbedtls/aes.h>
49 #include "aes_icm_ext.h"
50 #include "crypto_types.h"
51 #include "err.h" /* for srtp_debug */
52 #include "alloc.h"
53 #include "cipher_types.h"
54 #include "cipher_test_cases.h"
55 
56 srtp_debug_module_t srtp_mod_aes_icm = {
57     0,                /* debugging is off by default */
58     "aes icm mbedtls" /* printable module name       */
59 };
60 
61 /*
62  * integer counter mode works as follows:
63  *
64  * https://tools.ietf.org/html/rfc3711#section-4.1.1
65  *
66  * E(k, IV) || E(k, IV + 1 mod 2^128) || E(k, IV + 2 mod 2^128) ...
67  * IV = (k_s * 2^16) XOR (SSRC * 2^64) XOR (i * 2^16)
68  *
69  * IV SHALL be defined by the SSRC, the SRTP packet index i,
70  * and the SRTP session salting key k_s.
71  *
72  * SSRC: 32bits.
73  * Sequence number: 16bits.
74  * nonce is 64bits. .
75  * packet index = ROC || SEQ. (ROC: Rollover counter)
76  *
77  * 16 bits
78  * <----->
79  * +------+------+------+------+------+------+------+------+
80  * |           nonce           |    packet index    |  ctr |---+
81  * +------+------+------+------+------+------+------+------+   |
82  *                                                             |
83  * +------+------+------+------+------+------+------+------+   v
84  * |                      salt                      |000000|->(+)
85  * +------+------+------+------+------+------+------+------+   |
86  *                                                             |
87  *                                                        +---------+
88  *                                                        | encrypt |
89  *                                                        +---------+
90  *                                                             |
91  * +------+------+------+------+------+------+------+------+   |
92  * |                    keystream block                    |<--+
93  * +------+------+------+------+------+------+------+------+
94  *
95  * All fields are big-endian
96  *
97  * ctr is the block counter, which increments from zero for
98  * each packet (16 bits wide)
99  *
100  * packet index is distinct for each packet (48 bits wide)
101  *
102  * nonce can be distinct across many uses of the same key, or
103  * can be a fixed value per key, or can be per-packet randomness
104  * (64 bits)
105  *
106  */
107 
108 /*
109  * This function allocates a new instance of this crypto engine.
110  * The key_len parameter should be one of 30, 38, or 46 for
111  * AES-128, AES-192, and AES-256 respectively.  Note, this key_len
112  * value is inflated, as it also accounts for the 112 bit salt
113  * value.  The tlen argument is for the AEAD tag length, which
114  * isn't used in counter mode.
115  */
srtp_aes_icm_mbedtls_alloc(srtp_cipher_t ** c,int key_len,int tlen)116 static srtp_err_status_t srtp_aes_icm_mbedtls_alloc(srtp_cipher_t **c,
117                                                     int key_len,
118                                                     int tlen)
119 {
120     srtp_aes_icm_ctx_t *icm;
121 
122     debug_print(srtp_mod_aes_icm, "allocating cipher with key length %d",
123                 key_len);
124 
125     /*
126      * Verify the key_len is valid for one of: AES-128/192/256
127      */
128     if (key_len != SRTP_AES_ICM_128_KEY_LEN_WSALT &&
129         key_len != SRTP_AES_ICM_192_KEY_LEN_WSALT &&
130         key_len != SRTP_AES_ICM_256_KEY_LEN_WSALT) {
131         return srtp_err_status_bad_param;
132     }
133 
134     /* allocate memory a cipher of type aes_icm */
135     *c = (srtp_cipher_t *)srtp_crypto_alloc(sizeof(srtp_cipher_t));
136     if (*c == NULL) {
137         return srtp_err_status_alloc_fail;
138     }
139 
140     icm = (srtp_aes_icm_ctx_t *)srtp_crypto_alloc(sizeof(srtp_aes_icm_ctx_t));
141     if (icm == NULL) {
142         srtp_crypto_free(*c);
143         *c = NULL;
144         return srtp_err_status_alloc_fail;
145     }
146 
147     icm->ctx =
148         (mbedtls_aes_context *)srtp_crypto_alloc(sizeof(mbedtls_aes_context));
149     if (icm->ctx == NULL) {
150         srtp_crypto_free(icm);
151         srtp_crypto_free(*c);
152         *c = NULL;
153         return srtp_err_status_alloc_fail;
154     }
155 
156     mbedtls_aes_init(icm->ctx);
157 
158     /* set pointers */
159     (*c)->state = icm;
160 
161     /* setup cipher parameters */
162     switch (key_len) {
163     case SRTP_AES_ICM_128_KEY_LEN_WSALT:
164         (*c)->algorithm = SRTP_AES_ICM_128;
165         (*c)->type = &srtp_aes_icm_128;
166         icm->key_size = SRTP_AES_128_KEY_LEN;
167         break;
168     case SRTP_AES_ICM_192_KEY_LEN_WSALT:
169         (*c)->algorithm = SRTP_AES_ICM_192;
170         (*c)->type = &srtp_aes_icm_192;
171         icm->key_size = SRTP_AES_192_KEY_LEN;
172         break;
173     case SRTP_AES_ICM_256_KEY_LEN_WSALT:
174         (*c)->algorithm = SRTP_AES_ICM_256;
175         (*c)->type = &srtp_aes_icm_256;
176         icm->key_size = SRTP_AES_256_KEY_LEN;
177         break;
178     }
179 
180     /* set key size        */
181     (*c)->key_len = key_len;
182 
183     return srtp_err_status_ok;
184 }
185 
186 /*
187  * This function deallocates an instance of this engine
188  */
srtp_aes_icm_mbedtls_dealloc(srtp_cipher_t * c)189 static srtp_err_status_t srtp_aes_icm_mbedtls_dealloc(srtp_cipher_t *c)
190 {
191     srtp_aes_icm_ctx_t *ctx;
192 
193     if (c == NULL) {
194         return srtp_err_status_bad_param;
195     }
196 
197     /*
198      * Free the aes context
199      */
200     ctx = (srtp_aes_icm_ctx_t *)c->state;
201     if (ctx != NULL) {
202         mbedtls_aes_free(ctx->ctx);
203         srtp_crypto_free(ctx->ctx);
204         /* zeroize the key material */
205         octet_string_set_to_zero(ctx, sizeof(srtp_aes_icm_ctx_t));
206         srtp_crypto_free(ctx);
207     }
208 
209     /* free memory */
210     srtp_crypto_free(c);
211 
212     return srtp_err_status_ok;
213 }
214 
srtp_aes_icm_mbedtls_context_init(void * cv,const uint8_t * key)215 static srtp_err_status_t srtp_aes_icm_mbedtls_context_init(void *cv,
216                                                            const uint8_t *key)
217 {
218     srtp_aes_icm_ctx_t *c = (srtp_aes_icm_ctx_t *)cv;
219     uint32_t key_size_in_bits = (c->key_size << 3);
220     int errcode = 0;
221 
222     /*
223      * set counter and initial values to 'offset' value, being careful not to
224      * go past the end of the key buffer
225      */
226     v128_set_to_zero(&c->counter);
227     v128_set_to_zero(&c->offset);
228     memcpy(&c->counter, key + c->key_size, SRTP_SALT_LEN);
229     memcpy(&c->offset, key + c->key_size, SRTP_SALT_LEN);
230 
231     /* force last two octets of the offset to zero (for srtp compatibility) */
232     c->offset.v8[SRTP_SALT_LEN] = c->offset.v8[SRTP_SALT_LEN + 1] = 0;
233     c->counter.v8[SRTP_SALT_LEN] = c->counter.v8[SRTP_SALT_LEN + 1] = 0;
234     debug_print(srtp_mod_aes_icm, "key:  %s",
235                 srtp_octet_string_hex_string(key, c->key_size));
236     debug_print(srtp_mod_aes_icm, "offset: %s", v128_hex_string(&c->offset));
237 
238     switch (c->key_size) {
239     case SRTP_AES_256_KEY_LEN:
240     case SRTP_AES_192_KEY_LEN:
241     case SRTP_AES_128_KEY_LEN:
242         break;
243     default:
244         return srtp_err_status_bad_param;
245         break;
246     }
247 
248     errcode = mbedtls_aes_setkey_enc(c->ctx, key, key_size_in_bits);
249     if (errcode != 0) {
250         debug_print(srtp_mod_aes_icm, "errCode: %d", errcode);
251     }
252 
253     return srtp_err_status_ok;
254 }
255 
256 /*
257  * aes_icm_set_iv(c, iv) sets the counter value to the exor of iv with
258  * the offset
259  */
srtp_aes_icm_mbedtls_set_iv(void * cv,uint8_t * iv,srtp_cipher_direction_t dir)260 static srtp_err_status_t srtp_aes_icm_mbedtls_set_iv(
261     void *cv,
262     uint8_t *iv,
263     srtp_cipher_direction_t dir)
264 {
265     srtp_aes_icm_ctx_t *c = (srtp_aes_icm_ctx_t *)cv;
266     v128_t nonce;
267     c->nc_off = 0;
268     /* set nonce (for alignment) */
269     v128_copy_octet_string(&nonce, iv);
270 
271     debug_print(srtp_mod_aes_icm, "setting iv: %s", v128_hex_string(&nonce));
272 
273     v128_xor(&c->counter, &c->offset, &nonce);
274 
275     debug_print(srtp_mod_aes_icm, "set_counter: %s",
276                 v128_hex_string(&c->counter));
277 
278     return srtp_err_status_ok;
279 }
280 
281 /*
282  * This function encrypts a buffer using AES CTR mode
283  *
284  * Parameters:
285  *	c	Crypto context
286  *	buf	data to encrypt
287  *	enc_len	length of encrypt buffer
288  */
srtp_aes_icm_mbedtls_encrypt(void * cv,unsigned char * buf,unsigned int * enc_len)289 static srtp_err_status_t srtp_aes_icm_mbedtls_encrypt(void *cv,
290                                                       unsigned char *buf,
291                                                       unsigned int *enc_len)
292 {
293     srtp_aes_icm_ctx_t *c = (srtp_aes_icm_ctx_t *)cv;
294 
295     int errCode = 0;
296     debug_print(srtp_mod_aes_icm, "rs0: %s", v128_hex_string(&c->counter));
297 
298     errCode =
299         mbedtls_aes_crypt_ctr(c->ctx, *enc_len, &(c->nc_off), c->counter.v8,
300                               c->stream_block.v8, buf, buf);
301     if (errCode != 0) {
302         debug_print(srtp_mod_aes_icm, "encrypt error: %d", errCode);
303         return srtp_err_status_cipher_fail;
304     }
305 
306     return srtp_err_status_ok;
307 }
308 
309 /*
310  * Name of this crypto engine
311  */
312 static const char srtp_aes_icm_128_mbedtls_description[] =
313     "AES-128 counter mode using mbedtls";
314 static const char srtp_aes_icm_192_mbedtls_description[] =
315     "AES-192 counter mode using mbedtls";
316 static const char srtp_aes_icm_256_mbedtls_description[] =
317     "AES-256 counter mode using mbedtls";
318 
319 /*
320  * This is the function table for this crypto engine.
321  * note: the encrypt function is identical to the decrypt function
322  */
323 const srtp_cipher_type_t srtp_aes_icm_128 = {
324     srtp_aes_icm_mbedtls_alloc,           /* */
325     srtp_aes_icm_mbedtls_dealloc,         /* */
326     srtp_aes_icm_mbedtls_context_init,    /* */
327     0,                                    /* set_aad */
328     srtp_aes_icm_mbedtls_encrypt,         /* */
329     srtp_aes_icm_mbedtls_encrypt,         /* */
330     srtp_aes_icm_mbedtls_set_iv,          /* */
331     0,                                    /* get_tag */
332     srtp_aes_icm_128_mbedtls_description, /* */
333     &srtp_aes_icm_128_test_case_0,        /* */
334     SRTP_AES_ICM_128                      /* */
335 };
336 
337 /*
338  * This is the function table for this crypto engine.
339  * note: the encrypt function is identical to the decrypt function
340  */
341 const srtp_cipher_type_t srtp_aes_icm_192 = {
342     srtp_aes_icm_mbedtls_alloc,           /* */
343     srtp_aes_icm_mbedtls_dealloc,         /* */
344     srtp_aes_icm_mbedtls_context_init,    /* */
345     0,                                    /* set_aad */
346     srtp_aes_icm_mbedtls_encrypt,         /* */
347     srtp_aes_icm_mbedtls_encrypt,         /* */
348     srtp_aes_icm_mbedtls_set_iv,          /* */
349     0,                                    /* get_tag */
350     srtp_aes_icm_192_mbedtls_description, /* */
351     &srtp_aes_icm_192_test_case_0,        /* */
352     SRTP_AES_ICM_192                      /* */
353 };
354 
355 /*
356  * This is the function table for this crypto engine.
357  * note: the encrypt function is identical to the decrypt function
358  */
359 const srtp_cipher_type_t srtp_aes_icm_256 = {
360     srtp_aes_icm_mbedtls_alloc,           /* */
361     srtp_aes_icm_mbedtls_dealloc,         /* */
362     srtp_aes_icm_mbedtls_context_init,    /* */
363     0,                                    /* set_aad */
364     srtp_aes_icm_mbedtls_encrypt,         /* */
365     srtp_aes_icm_mbedtls_encrypt,         /* */
366     srtp_aes_icm_mbedtls_set_iv,          /* */
367     0,                                    /* get_tag */
368     srtp_aes_icm_256_mbedtls_description, /* */
369     &srtp_aes_icm_256_test_case_0,        /* */
370     SRTP_AES_ICM_256                      /* */
371 };
372