1 /*
2  * Copyright (c) 2017 Nordic Semiconductor ASA
3  * Copyright (c) 2015-2016 Intel Corporation
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <string.h>
9 #include <bt_errno.h>
10 
11 #include <ble_os.h>
12 #include <misc/byteorder.h>
13 
14 #include <bluetooth/bluetooth.h>
15 #include <bluetooth/hci.h>
16 #include <bluetooth/conn.h>
17 
18 #include <tinycrypt/constants.h>
19 #include <tinycrypt/hmac_prng.h>
20 #include <tinycrypt/aes.h>
21 #include <tinycrypt/utils.h>
22 #include <tinycrypt/cmac_mode.h>
23 #include <tinycrypt/ccm_mode.h>
24 
25 #define BT_DBG_ENABLED 0
26 #include "common/log.h"
27 
28 #include "host/hci_core.h"
29 #include "hci_api.h"
30 
31 #include "bt_crypto.h"
32 
33 #define __BT_CRYPTO_WEAK__ __attribute__((weak))
34 
35 static struct tc_hmac_prng_struct prng;
36 
prng_reseed(struct tc_hmac_prng_struct * h)37 static int prng_reseed(struct tc_hmac_prng_struct *h)
38 {
39     u8_t seed[32];
40     s64_t extra;
41     int ret, i;
42 
43 	for (i = 0; i < (sizeof(seed) / 8); i++) {
44 #if !defined(CONFIG_BT_USE_HCI_API)
45 		struct bt_hci_rp_le_rand *rp;
46 		struct net_buf *rsp;
47 
48 		ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp);
49 		if (ret) {
50 			return ret;
51 		}
52 
53 		rp = (void *)rsp->data;
54 		memcpy(&seed[i * 8], rp->rand, 8);
55 
56 		net_buf_unref(rsp);
57 #else
58         hci_api_le_rand(&seed[i * 8]);
59 #endif
60 	}
61 
62     extra = k_uptime_get();
63 
64     ret = tc_hmac_prng_reseed(h, seed, sizeof(seed), (u8_t *)&extra,
65                               sizeof(extra));
66 
67     if (ret == TC_CRYPTO_FAIL) {
68         BT_ERR("Failed to re-seed PRNG");
69         return -EIO;
70     }
71 
72     return 0;
73 }
74 
prng_init(void)75 __BT_CRYPTO_WEAK__ int prng_init(void)
76 {
77     u8_t rand[8];
78     int ret;
79 
80 #if !defined(CONFIG_BT_USE_HCI_API)
81 	struct bt_hci_rp_le_rand *rp;
82 	struct net_buf *rsp;
83 
84 	ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp);
85 	if (ret) {
86 		return ret;
87 	}
88 
89 	rp = (void *)rsp->data;
90     memcpy(rand, rp, 8);
91 #else
92     hci_api_le_rand(rand);
93 #endif
94     ret = tc_hmac_prng_init(&prng, rand, sizeof(rand));
95 
96     if (ret == TC_CRYPTO_FAIL) {
97         BT_ERR("Failed to initialize PRNG");
98         return -EIO;
99     }
100 
101     /* re-seed is needed after init */
102     return prng_reseed(&prng);
103 }
104 
bt_crypto_rand(void * buf,size_t len)105 __BT_CRYPTO_WEAK__ int bt_crypto_rand(void *buf, size_t len)
106 {
107     int ret;
108 
109     ret = tc_hmac_prng_generate(buf, len, &prng);
110 
111     if (ret == TC_HMAC_PRNG_RESEED_REQ) {
112         ret = prng_reseed(&prng);
113 
114         if (ret) {
115             return ret;
116         }
117 
118         ret = tc_hmac_prng_generate(buf, len, &prng);
119     }
120 
121     if (ret == TC_CRYPTO_SUCCESS) {
122         return 0;
123     }
124 
125     return -EIO;
126 }
127 
bt_crypto_encrypt_le(const u8_t key[16],const u8_t plaintext[16],u8_t enc_data[16])128 __BT_CRYPTO_WEAK__ int bt_crypto_encrypt_le(const u8_t key[16], const u8_t plaintext[16],
129         u8_t enc_data[16])
130 {
131     struct tc_aes_key_sched_struct s;
132     u8_t tmp[16];
133 
134     BT_DBG("key %s plaintext %s", bt_hex(key, 16), bt_hex(plaintext, 16));
135 
136     sys_memcpy_swap(tmp, key, 16);
137 
138     if (tc_aes128_set_encrypt_key(&s, tmp) == TC_CRYPTO_FAIL) {
139         return -EINVAL;
140     }
141 
142     sys_memcpy_swap(tmp, plaintext, 16);
143 
144     if (tc_aes_encrypt(enc_data, tmp, &s) == TC_CRYPTO_FAIL) {
145         return -EINVAL;
146     }
147 
148     sys_mem_swap(enc_data, 16);
149 
150     BT_DBG("enc_data %s", bt_hex(enc_data, 16));
151 
152     return 0;
153 }
154 
bt_crypto_encrypt_be(const u8_t key[16],const u8_t plaintext[16],u8_t enc_data[16])155 __BT_CRYPTO_WEAK__ int bt_crypto_encrypt_be(const u8_t key[16], const u8_t plaintext[16],
156         u8_t enc_data[16])
157 {
158     struct tc_aes_key_sched_struct s;
159 
160     BT_DBG("key %s plaintext %s", bt_hex(key, 16), bt_hex(plaintext, 16));
161 
162     if (tc_aes128_set_encrypt_key(&s, key) == TC_CRYPTO_FAIL) {
163         return -EINVAL;
164     }
165 
166     if (tc_aes_encrypt(enc_data, plaintext, &s) == TC_CRYPTO_FAIL) {
167         return -EINVAL;
168     }
169 
170     BT_DBG("enc_data %s", bt_hex(enc_data, 16));
171 
172     return 0;
173 }
174 
bt_crypto_decrypt_be(const u8_t key[16],const u8_t enc_data[16],u8_t dec_data[16])175 __BT_CRYPTO_WEAK__ int bt_crypto_decrypt_be(const u8_t key[16], const u8_t enc_data[16],
176 		  u8_t dec_data[16])
177 {
178     struct tc_aes_key_sched_struct s;
179 
180     if (tc_aes128_set_decrypt_key(&s, key) == TC_CRYPTO_FAIL) {
181         return -EINVAL;
182     }
183 
184     if (tc_aes_decrypt(dec_data, enc_data, &s) == TC_CRYPTO_FAIL) {
185         return -EINVAL;
186     }
187 
188     BT_DBG("dec_data %s", bt_hex(dec_data, 16));
189 
190     return 0;
191 }
192 
193 
194 /* bt_crypto_cmac_* functions is modified from tinycrypt cmac_mode.c. the aes function is replaced
195    by bt_encrypt_be which call aes ctypto from controller.
196 */
197 
198 /*
199  *  Copyright (C) 2017 by Intel Corporation, All Rights Reserved.
200  *
201  *  Redistribution and use in source and binary forms, with or without
202  *  modification, are permitted provided that the following conditions are met:
203  *
204  *    - Redistributions of source code must retain the above copyright notice,
205  *     this list of conditions and the following disclaimer.
206  *
207  *    - Redistributions in binary form must reproduce the above copyright
208  *    notice, this list of conditions and the following disclaimer in the
209  *    documentation and/or other materials provided with the distribution.
210  *
211  *    - Neither the name of Intel Corporation nor the names of its contributors
212  *    may be used to endorse or promote products derived from this software
213  *    without specific prior written permission.
214  *
215  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
216  *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
217  *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
218  *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
219  *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
220  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
221  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
222  *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
223  *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
224  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
225  *  POSSIBILITY OF SUCH DAMAGE.
226  */
227 
228 /*
229  *  gf_wrap -- In our implementation, GF(2^128) is represented as a 16 byte
230  *  array with byte 0 the most significant and byte 15 the least significant.
231  *  High bit carry reduction is based on the primitive polynomial
232  *
233  *                     X^128 + X^7 + X^2 + X + 1,
234  *
235  *  which leads to the reduction formula X^128 = X^7 + X^2 + X + 1. Indeed,
236  *  since 0 = (X^128 + X^7 + X^2 + 1) mod (X^128 + X^7 + X^2 + X + 1) and since
237  *  addition of polynomials with coefficients in Z/Z(2) is just XOR, we can
238  *  add X^128 to both sides to get
239  *
240  *       X^128 = (X^7 + X^2 + X + 1) mod (X^128 + X^7 + X^2 + X + 1)
241  *
242  *  and the coefficients of the polynomial on the right hand side form the
243  *  string 1000 0111 = 0x87, which is the value of gf_wrap.
244  *
245  *  This gets used in the following way. Doubling in GF(2^128) is just a left
246  *  shift by 1 bit, except when the most significant bit is 1. In the latter
247  *  case, the relation X^128 = X^7 + X^2 + X + 1 says that the high order bit
248  *  that overflows beyond 128 bits can be replaced by addition of
249  *  X^7 + X^2 + X + 1 <--> 0x87 to the low order 128 bits. Since addition
250  *  in GF(2^128) is represented by XOR, we therefore only have to XOR 0x87
251  *  into the low order byte after a left shift when the starting high order
252  *  bit is 1.
253  */
254 static const unsigned char gf_wrap = 0x87;
255 
256 /*
257  *  assumes: out != NULL and points to a GF(2^n) value to receive the
258  *            doubled value;
259  *           in != NULL and points to a 16 byte GF(2^n) value
260  *            to double;
261  *           the in and out buffers do not overlap.
262  *  effects: doubles the GF(2^n) value pointed to by "in" and places
263  *           the result in the GF(2^n) value pointed to by "out."
264  */
gf_double(uint8_t * out,uint8_t * in)265 static void gf_double(uint8_t *out, uint8_t *in)
266 {
267 
268     /* start with low order byte */
269     uint8_t *x = in + (16 - 1);
270 
271     /* if msb == 1, we need to add the gf_wrap value, otherwise add 0 */
272     uint8_t carry = (in[0] >> 7) ? gf_wrap : 0;
273 
274     out += (16 - 1);
275 
276     for (;;) {
277         *out-- = (*x << 1) ^ carry;
278 
279         if (x == in) {
280             break;
281         }
282 
283         carry = *x-- >> 7;
284     }
285 }
286 
bt_crypto_cmac_setup(struct bt_crypto_cmac_t * ctx,const uint8_t key[16])287 __BT_CRYPTO_WEAK__ int bt_crypto_cmac_setup(struct bt_crypto_cmac_t *ctx, const uint8_t key[16])
288 {
289     if (NULL == ctx || NULL == key) {
290         return -1;
291     }
292 
293     memset(ctx, 0, sizeof(*ctx));
294     memcpy(ctx->aes_key, key, 16);
295 
296     memset(ctx->iv, 0, 16);
297     bt_crypto_encrypt_be(ctx->aes_key, ctx->iv, ctx->iv);
298 
299     gf_double(ctx->K1, ctx->iv);
300     gf_double(ctx->K2, ctx->K1);
301 
302     memset(ctx->iv, 0, 16);
303     memset(ctx->leftover, 0, 16);
304     ctx->leftover_offset = 0;
305 
306     ctx->countdown = ((uint64_t)1 << 48);
307 
308     return 0;
309 }
310 
bt_crypto_cmac_update(struct bt_crypto_cmac_t * ctx,const uint8_t * data,uint16_t data_length)311 __BT_CRYPTO_WEAK__ int bt_crypto_cmac_update(struct bt_crypto_cmac_t *ctx, const uint8_t *data, uint16_t data_length)
312 {
313     unsigned int i;
314 
315     /* input sanity check: */
316     if (ctx == NULL) {
317         return -1;
318     }
319 
320     if (data_length == 0) {
321         return 0;
322     }
323 
324     if (data == NULL) {
325         return -1;
326     }
327 
328     if (ctx->countdown == 0) {
329         return -1;
330     }
331 
332     ctx->countdown--;
333 
334     if (ctx->leftover_offset > 0) {
335         /* last data added to s didn't end on a 16 byte boundary */
336         size_t remaining_space = 16 - ctx->leftover_offset;
337 
338         if (data_length < remaining_space) {
339             /* still not enough data to encrypt this time either */
340             memcpy(&ctx->leftover[ctx->leftover_offset], data, data_length);
341             ctx->leftover_offset += data_length;
342             return 0;
343         }
344 
345         /* leftover block is now full; encrypt it first */
346         memcpy(&ctx->leftover[ctx->leftover_offset],
347                data,
348                remaining_space);
349         data_length -= remaining_space;
350         data += remaining_space;
351         ctx->leftover_offset = 0;
352 
353         for (i = 0; i < 16; ++i) {
354             ctx->iv[i] ^= ctx->leftover[i];
355         }
356 
357         bt_crypto_encrypt_be(ctx->aes_key, ctx->iv, ctx->iv);
358     }
359 
360     /* CBC encrypt each (except the last) of the data blocks */
361     while (data_length > 16) {
362         for (i = 0; i < 16; ++i) {
363             ctx->iv[i] ^= data[i];
364         }
365 
366         bt_crypto_encrypt_be(ctx->aes_key, ctx->iv, ctx->iv);
367         data += 16;
368         data_length  -= 16;
369     }
370 
371     if (data_length > 0) {
372         /* save leftover data for next time */
373         memcpy(ctx->leftover, data, data_length);
374         ctx->leftover_offset = data_length;
375     }
376 
377     return 0;
378 }
379 
bt_crypto_cmac_finish(struct bt_crypto_cmac_t * ctx,uint8_t out[16])380 __BT_CRYPTO_WEAK__ int bt_crypto_cmac_finish(struct bt_crypto_cmac_t *ctx, uint8_t out[16])
381 {
382     uint8_t *k;
383     unsigned int i;
384 
385     if (ctx == NULL || out == NULL) {
386         return -1;
387     }
388 
389     if (ctx->leftover_offset == 16) {
390         /* the last message block is a full-sized block */
391         k = (uint8_t *) ctx->K1;
392     } else {
393         /* the final message block is not a full-sized  block */
394         size_t remaining = 16 - ctx->leftover_offset;
395 
396         memset(&ctx->leftover[ctx->leftover_offset], 0, remaining);
397         ctx->leftover[ctx->leftover_offset] = 0x80;
398         k = (uint8_t *) ctx->K2;
399     }
400 
401     for (i = 0; i < 16; ++i) {
402         ctx->iv[i] ^= ctx->leftover[i] ^ k[i];
403     }
404 
405     bt_crypto_encrypt_be(ctx->aes_key, ctx->iv, out);
406 
407     memset(ctx, 0, sizeof(*ctx));
408 
409     return 0;
410 }
411 
412 
bt_crypto_aes_cmac(const u8_t key[16],struct bt_crypto_sg * sg,size_t sg_len,u8_t mac[16])413 __BT_CRYPTO_WEAK__ int bt_crypto_aes_cmac(const u8_t key[16], struct bt_crypto_sg *sg,
414         size_t sg_len, u8_t mac[16])
415 {
416     struct tc_aes_key_sched_struct sched;
417     struct tc_cmac_struct state;
418 
419     if (tc_cmac_setup(&state, key, &sched) == TC_CRYPTO_FAIL) {
420         return -EIO;
421     }
422 
423     for (; sg_len; sg_len--, sg++) {
424         if (tc_cmac_update(&state, sg->data,
425                            sg->len) == TC_CRYPTO_FAIL) {
426             return -EIO;
427         }
428     }
429 
430     if (tc_cmac_final(mac, &state) == TC_CRYPTO_FAIL) {
431         return -EIO;
432     }
433 
434     return 0;
435 }
436