Upgrade bluez5_37 :Merge the code from private
[platform/upstream/bluez.git] / src / shared / crypto.c
1 /*
2  *
3  *  BlueZ - Bluetooth protocol stack for Linux
4  *
5  *  Copyright (C) 2012-2014  Intel Corporation. All rights reserved.
6  *
7  *
8  *  This library is free software; you can redistribute it and/or
9  *  modify it under the terms of the GNU Lesser General Public
10  *  License as published by the Free Software Foundation; either
11  *  version 2.1 of the License, or (at your option) any later version.
12  *
13  *  This library is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  *  Lesser General Public License for more details.
17  *
18  *  You should have received a copy of the GNU Lesser General Public
19  *  License along with this library; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <string.h>
31 #include <sys/socket.h>
32
33 #include "src/shared/util.h"
34 #include "src/shared/crypto.h"
35
36 #ifndef HAVE_LINUX_IF_ALG_H
37 #ifndef HAVE_LINUX_TYPES_H
38 typedef uint8_t __u8;
39 typedef uint16_t __u16;
40 typedef uint32_t __u32;
41 #else
42 #include <linux/types.h>
43 #endif
44
45 struct sockaddr_alg {
46         __u16   salg_family;
47         __u8    salg_type[14];
48         __u32   salg_feat;
49         __u32   salg_mask;
50         __u8    salg_name[64];
51 };
52
53 struct af_alg_iv {
54         __u32   ivlen;
55         __u8    iv[0];
56 };
57
58 #define ALG_SET_KEY                     1
59 #define ALG_SET_IV                      2
60 #define ALG_SET_OP                      3
61
62 #define ALG_OP_DECRYPT                  0
63 #define ALG_OP_ENCRYPT                  1
64
65 #define PF_ALG          38      /* Algorithm sockets.  */
66 #define AF_ALG          PF_ALG
67 #else
68 #include <linux/if_alg.h>
69 #endif
70
71 #ifndef SOL_ALG
72 #define SOL_ALG         279
73 #endif
74
75 /* Maximum message length that can be passed to aes_cmac */
76 #define CMAC_MSG_MAX    80
77
78 struct bt_crypto {
79         int ref_count;
80         int ecb_aes;
81         int urandom;
82         int cmac_aes;
83 };
84
85 static int urandom_setup(void)
86 {
87         int fd;
88
89         fd = open("/dev/urandom", O_RDONLY);
90         if (fd < 0)
91                 return -1;
92
93         return fd;
94 }
95
96 static int ecb_aes_setup(void)
97 {
98         struct sockaddr_alg salg;
99         int fd;
100
101         fd = socket(PF_ALG, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
102         if (fd < 0)
103                 return -1;
104
105         memset(&salg, 0, sizeof(salg));
106         salg.salg_family = AF_ALG;
107         strcpy((char *) salg.salg_type, "skcipher");
108         strcpy((char *) salg.salg_name, "ecb(aes)");
109
110         if (bind(fd, (struct sockaddr *) &salg, sizeof(salg)) < 0) {
111                 close(fd);
112                 return -1;
113         }
114
115         return fd;
116 }
117
118 static int cmac_aes_setup(void)
119 {
120         struct sockaddr_alg salg;
121         int fd;
122
123         fd = socket(PF_ALG, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
124         if (fd < 0)
125                 return -1;
126
127         memset(&salg, 0, sizeof(salg));
128         salg.salg_family = AF_ALG;
129         strcpy((char *) salg.salg_type, "hash");
130         strcpy((char *) salg.salg_name, "cmac(aes)");
131
132         if (bind(fd, (struct sockaddr *) &salg, sizeof(salg)) < 0) {
133                 close(fd);
134                 return -1;
135         }
136
137         return fd;
138 }
139
140 struct bt_crypto *bt_crypto_new(void)
141 {
142         struct bt_crypto *crypto;
143
144         crypto = new0(struct bt_crypto, 1);
145
146         crypto->ecb_aes = ecb_aes_setup();
147         if (crypto->ecb_aes < 0) {
148                 free(crypto);
149                 return NULL;
150         }
151
152         crypto->urandom = urandom_setup();
153         if (crypto->urandom < 0) {
154                 close(crypto->ecb_aes);
155                 free(crypto);
156                 return NULL;
157         }
158
159         crypto->cmac_aes = cmac_aes_setup();
160         if (crypto->cmac_aes < 0) {
161                 close(crypto->urandom);
162                 close(crypto->ecb_aes);
163                 free(crypto);
164                 return NULL;
165         }
166
167         return bt_crypto_ref(crypto);
168 }
169
170 struct bt_crypto *bt_crypto_ref(struct bt_crypto *crypto)
171 {
172         if (!crypto)
173                 return NULL;
174
175         __sync_fetch_and_add(&crypto->ref_count, 1);
176
177         return crypto;
178 }
179
180 void bt_crypto_unref(struct bt_crypto *crypto)
181 {
182         if (!crypto)
183                 return;
184
185         if (__sync_sub_and_fetch(&crypto->ref_count, 1))
186                 return;
187
188         close(crypto->urandom);
189         close(crypto->ecb_aes);
190         close(crypto->cmac_aes);
191
192         free(crypto);
193 }
194
195 bool bt_crypto_random_bytes(struct bt_crypto *crypto,
196                                         uint8_t *buf, uint8_t num_bytes)
197 {
198         ssize_t len;
199
200         if (!crypto)
201                 return false;
202
203         len = read(crypto->urandom, buf, num_bytes);
204         if (len < num_bytes)
205                 return false;
206
207         return true;
208 }
209
210 static int alg_new(int fd, const void *keyval, socklen_t keylen)
211 {
212         if (setsockopt(fd, SOL_ALG, ALG_SET_KEY, keyval, keylen) < 0)
213                 return -1;
214
215         /* FIXME: This should use accept4() with SOCK_CLOEXEC */
216         return accept(fd, NULL, 0);
217 }
218
219 static bool alg_encrypt(int fd, const void *inbuf, size_t inlen,
220                                                 void *outbuf, size_t outlen)
221 {
222         __u32 alg_op = ALG_OP_ENCRYPT;
223         char cbuf[CMSG_SPACE(sizeof(alg_op))];
224         struct cmsghdr *cmsg;
225         struct msghdr msg;
226         struct iovec iov;
227         ssize_t len;
228
229         memset(cbuf, 0, sizeof(cbuf));
230         memset(&msg, 0, sizeof(msg));
231
232         msg.msg_control = cbuf;
233         msg.msg_controllen = sizeof(cbuf);
234
235         cmsg = CMSG_FIRSTHDR(&msg);
236         cmsg->cmsg_level = SOL_ALG;
237         cmsg->cmsg_type = ALG_SET_OP;
238         cmsg->cmsg_len = CMSG_LEN(sizeof(alg_op));
239         memcpy(CMSG_DATA(cmsg), &alg_op, sizeof(alg_op));
240
241         iov.iov_base = (void *) inbuf;
242         iov.iov_len = inlen;
243
244         msg.msg_iov = &iov;
245         msg.msg_iovlen = 1;
246
247         len = sendmsg(fd, &msg, 0);
248         if (len < 0)
249                 return false;
250
251         len = read(fd, outbuf, outlen);
252         if (len < 0)
253                 return false;
254
255         return true;
256 }
257
258 static inline void swap_buf(const uint8_t *src, uint8_t *dst, uint16_t len)
259 {
260         int i;
261
262         for (i = 0; i < len; i++)
263                 dst[len - 1 - i] = src[i];
264 }
265
266 bool bt_crypto_sign_att(struct bt_crypto *crypto, const uint8_t key[16],
267                                 const uint8_t *m, uint16_t m_len,
268                                 uint32_t sign_cnt, uint8_t signature[12])
269 {
270         int fd;
271         int len;
272         uint8_t tmp[16], out[16];
273         uint16_t msg_len = m_len + sizeof(uint32_t);
274         uint8_t msg[msg_len];
275         uint8_t msg_s[msg_len];
276
277         if (!crypto)
278                 return false;
279
280         memset(msg, 0, msg_len);
281         memcpy(msg, m, m_len);
282
283         /* Add sign_counter to the message */
284         put_le32(sign_cnt, msg + m_len);
285
286         /* The most significant octet of key corresponds to key[0] */
287         swap_buf(key, tmp, 16);
288
289         fd = alg_new(crypto->cmac_aes, tmp, 16);
290         if (fd < 0)
291                 return false;
292
293         /* Swap msg before signing */
294         swap_buf(msg, msg_s, msg_len);
295
296         len = send(fd, msg_s, msg_len, 0);
297         if (len < 0) {
298                 close(fd);
299                 return false;
300         }
301
302         len = read(fd, out, 16);
303         if (len < 0) {
304                 close(fd);
305                 return false;
306         }
307
308         close(fd);
309
310         /*
311          * As to BT spec. 4.1 Vol[3], Part C, chapter 10.4.1 sign counter should
312          * be placed in the signature
313          */
314         put_be32(sign_cnt, out + 8);
315
316         /*
317          * The most significant octet of hash corresponds to out[0]  - swap it.
318          * Then truncate in most significant bit first order to a length of
319          * 12 octets
320          */
321         swap_buf(out, tmp, 16);
322         memcpy(signature, tmp + 4, 12);
323
324         return true;
325 }
326 /*
327  * Security function e
328  *
329  * Security function e generates 128-bit encryptedData from a 128-bit key
330  * and 128-bit plaintextData using the AES-128-bit block cypher:
331  *
332  *   encryptedData = e(key, plaintextData)
333  *
334  * The most significant octet of key corresponds to key[0], the most
335  * significant octet of plaintextData corresponds to in[0] and the
336  * most significant octet of encryptedData corresponds to out[0].
337  *
338  */
339 bool bt_crypto_e(struct bt_crypto *crypto, const uint8_t key[16],
340                         const uint8_t plaintext[16], uint8_t encrypted[16])
341 {
342         uint8_t tmp[16], in[16], out[16];
343         int fd;
344
345         if (!crypto)
346                 return false;
347
348         /* The most significant octet of key corresponds to key[0] */
349         swap_buf(key, tmp, 16);
350
351         fd = alg_new(crypto->ecb_aes, tmp, 16);
352         if (fd < 0)
353                 return false;
354
355
356         /* Most significant octet of plaintextData corresponds to in[0] */
357         swap_buf(plaintext, in, 16);
358
359         if (!alg_encrypt(fd, in, 16, out, 16)) {
360                 close(fd);
361                 return false;
362         }
363
364         /* Most significant octet of encryptedData corresponds to out[0] */
365         swap_buf(out, encrypted, 16);
366
367         close(fd);
368
369         return true;
370 }
371
372 /*
373  * Random Address Hash function ah
374  *
375  * The random address hash function ah is used to generate a hash value
376  * that is used in resolvable private addresses.
377  *
378  * The following are inputs to the random address hash function ah:
379  *
380  *   k is 128 bits
381  *   r is 24 bits
382  *   padding is 104 bits
383  *
384  * r is concatenated with padding to generate r' which is used as the
385  * 128-bit input parameter plaintextData to security function e:
386  *
387  *   r' = padding || r
388  *
389  * The least significant octet of r becomes the least significant octet
390  * of r’ and the most significant octet of padding becomes the most
391  * significant octet of r'.
392  *
393  * For example, if the 24-bit value r is 0x423456 then r' is
394  * 0x00000000000000000000000000423456.
395  *
396  * The output of the random address function ah is:
397  *
398  *   ah(k, r) = e(k, r') mod 2^24
399  *
400  * The output of the security function e is then truncated to 24 bits by
401  * taking the least significant 24 bits of the output of e as the result
402  * of ah.
403  */
404 bool bt_crypto_ah(struct bt_crypto *crypto, const uint8_t k[16],
405                                         const uint8_t r[3], uint8_t hash[3])
406 {
407         uint8_t rp[16];
408         uint8_t encrypted[16];
409
410         if (!crypto)
411                 return false;
412
413         /* r' = padding || r */
414         memcpy(rp, r, 3);
415         memset(rp + 3, 0, 13);
416
417         /* e(k, r') */
418         if (!bt_crypto_e(crypto, k, rp, encrypted))
419                 return false;
420
421         /* ah(k, r) = e(k, r') mod 2^24 */
422         memcpy(hash, encrypted, 3);
423
424         return true;
425 }
426
427 typedef struct {
428         uint64_t a, b;
429 } u128;
430
431 static inline void u128_xor(const uint8_t p[16], const uint8_t q[16],
432                                                                 uint8_t r[16])
433 {
434         u128 pp, qq, rr;
435
436         memcpy(&pp, p, 16);
437         memcpy(&qq, q, 16);
438
439         rr.a = pp.a ^ qq.a;
440         rr.b = pp.b ^ qq.b;
441
442         memcpy(r, &rr, 16);
443 }
444
445 /*
446  * Confirm value generation function c1
447  *
448  * During the pairing process confirm values are exchanged. This confirm
449  * value generation function c1 is used to generate the confirm values.
450  *
451  * The following are inputs to the confirm value generation function c1:
452  *
453  *   k is 128 bits
454  *   r is 128 bits
455  *   pres is 56 bits
456  *   preq is 56 bits
457  *   iat is 1 bit
458  *   ia is 48 bits
459  *   rat is 1 bit
460  *   ra is 48 bits
461  *   padding is 32 bits of 0
462  *
463  * iat is concatenated with 7-bits of 0 to create iat' which is 8 bits
464  * in length. iat is the least significant bit of iat'
465  *
466  * rat is concatenated with 7-bits of 0 to create rat' which is 8 bits
467  * in length. rat is the least significant bit of rat'
468  *
469  * pres, preq, rat' and iat' are concatenated to generate p1 which is
470  * XORed with r and used as 128-bit input parameter plaintextData to
471  * security function e:
472  *
473  *   p1 = pres || preq || rat' || iat'
474  *
475  * The octet of iat' becomes the least significant octet of p1 and the
476  * most significant octet of pres becomes the most significant octet of
477  * p1.
478  *
479  * ra is concatenated with ia and padding to generate p2 which is XORed
480  * with the result of the security function e using p1 as the input
481  * paremter plaintextData and is then used as the 128-bit input
482  * parameter plaintextData to security function e:
483  *
484  *   p2 = padding || ia || ra
485  *
486  * The least significant octet of ra becomes the least significant octet
487  * of p2 and the most significant octet of padding becomes the most
488  * significant octet of p2.
489  *
490  * The output of the confirm value generation function c1 is:
491  *
492  *   c1(k, r, preq, pres, iat, rat, ia, ra) = e(k, e(k, r XOR p1) XOR p2)
493  *
494  * The 128-bit output of the security function e is used as the result
495  * of confirm value generation function c1.
496  */
497 bool bt_crypto_c1(struct bt_crypto *crypto, const uint8_t k[16],
498                         const uint8_t r[16], const uint8_t pres[7],
499                         const uint8_t preq[7], uint8_t iat,
500                         const uint8_t ia[6], uint8_t rat,
501                         const uint8_t ra[6], uint8_t res[16])
502 {
503         uint8_t p1[16], p2[16];
504
505         /* p1 = pres || preq || _rat || _iat */
506         p1[0] = iat;
507         p1[1] = rat;
508         memcpy(p1 + 2, preq, 7);
509         memcpy(p1 + 9, pres, 7);
510
511         /* p2 = padding || ia || ra */
512         memcpy(p2, ra, 6);
513         memcpy(p2 + 6, ia, 6);
514         memset(p2 + 12, 0, 4);
515
516         /* res = r XOR p1 */
517         u128_xor(r, p1, res);
518
519         /* res = e(k, res) */
520         if (!bt_crypto_e(crypto, k, res, res))
521                 return false;
522
523         /* res = res XOR p2 */
524         u128_xor(res, p2, res);
525
526         /* res = e(k, res) */
527         return bt_crypto_e(crypto, k, res, res);
528 }
529
530 /*
531  * Key generation function s1
532  *
533  * The key generation function s1 is used to generate the STK during the
534  * pairing process.
535  *
536  * The following are inputs to the key generation function s1:
537  *
538  *   k is 128 bits
539  *   r1 is 128 bits
540  *   r2 is 128 bits
541  *
542  * The most significant 64-bits of r1 are discarded to generate r1' and
543  * the most significant 64-bits of r2 are discarded to generate r2'.
544  *
545  * r1' is concatenated with r2' to generate r' which is used as the
546  * 128-bit input parameter plaintextData to security function e:
547  *
548  *   r' = r1' || r2'
549  *
550  * The least significant octet of r2' becomes the least significant
551  * octet of r' and the most significant octet of r1' becomes the most
552  * significant octet of r'.
553  *
554  * The output of the key generation function s1 is:
555  *
556  *   s1(k, r1, r2) = e(k, r')
557  *
558  * The 128-bit output of the security function e is used as the result
559  * of key generation function s1.
560  */
561 bool bt_crypto_s1(struct bt_crypto *crypto, const uint8_t k[16],
562                         const uint8_t r1[16], const uint8_t r2[16],
563                         uint8_t res[16])
564 {
565         memcpy(res, r2, 8);
566         memcpy(res + 8, r1, 8);
567
568         return bt_crypto_e(crypto, k, res, res);
569 }
570
571 static bool aes_cmac(struct bt_crypto *crypto, uint8_t key[16], uint8_t *msg,
572                                         size_t msg_len, uint8_t res[16])
573 {
574         uint8_t key_msb[16], out[16], msg_msb[CMAC_MSG_MAX];
575         ssize_t len;
576         int fd;
577
578         if (msg_len > CMAC_MSG_MAX)
579                 return false;
580
581         swap_buf(key, key_msb, 16);
582         fd = alg_new(crypto->cmac_aes, key_msb, 16);
583         if (fd < 0)
584                 return false;
585
586         swap_buf(msg, msg_msb, msg_len);
587         len = send(fd, msg_msb, msg_len, 0);
588         if (len < 0) {
589                 close(fd);
590                 return false;
591         }
592
593         len = read(fd, out, 16);
594         if (len < 0) {
595                 close(fd);
596                 return false;
597         }
598
599         swap_buf(out, res, 16);
600
601         close(fd);
602
603         return true;
604 }
605
606 bool bt_crypto_f4(struct bt_crypto *crypto, uint8_t u[32], uint8_t v[32],
607                                 uint8_t x[16], uint8_t z, uint8_t res[16])
608 {
609         uint8_t m[65];
610
611         if (!crypto)
612                 return false;
613
614         m[0] = z;
615         memcpy(&m[1], v, 32);
616         memcpy(&m[33], u, 32);
617
618         return aes_cmac(crypto, x, m, sizeof(m), res);
619 }
620
621 bool bt_crypto_f5(struct bt_crypto *crypto, uint8_t w[32], uint8_t n1[16],
622                                 uint8_t n2[16], uint8_t a1[7], uint8_t a2[7],
623                                 uint8_t mackey[16], uint8_t ltk[16])
624 {
625         uint8_t btle[4] = { 0x65, 0x6c, 0x74, 0x62 };
626         uint8_t salt[16] = { 0xbe, 0x83, 0x60, 0x5a, 0xdb, 0x0b, 0x37, 0x60,
627                              0x38, 0xa5, 0xf5, 0xaa, 0x91, 0x83, 0x88, 0x6c };
628         uint8_t length[2] = { 0x00, 0x01 };
629         uint8_t m[53], t[16];
630
631         if (!aes_cmac(crypto, salt, w, 32, t))
632                 return false;
633
634         memcpy(&m[0], length, 2);
635         memcpy(&m[2], a2, 7);
636         memcpy(&m[9], a1, 7);
637         memcpy(&m[16], n2, 16);
638         memcpy(&m[32], n1, 16);
639         memcpy(&m[48], btle, 4);
640
641         m[52] = 0; /* Counter */
642         if (!aes_cmac(crypto, t, m, sizeof(m), mackey))
643                 return false;
644
645         m[52] = 1; /* Counter */
646         return aes_cmac(crypto, t, m, sizeof(m), ltk);
647 }
648
649 bool bt_crypto_f6(struct bt_crypto *crypto, uint8_t w[16], uint8_t n1[16],
650                         uint8_t n2[16], uint8_t r[16], uint8_t io_cap[3],
651                         uint8_t a1[7], uint8_t a2[7], uint8_t res[16])
652 {
653         uint8_t m[65];
654
655         memcpy(&m[0], a2, 7);
656         memcpy(&m[7], a1, 7);
657         memcpy(&m[14], io_cap, 3);
658         memcpy(&m[17], r, 16);
659         memcpy(&m[33], n2, 16);
660         memcpy(&m[49], n1, 16);
661
662         return aes_cmac(crypto, w, m, sizeof(m), res);
663 }
664
665 bool bt_crypto_g2(struct bt_crypto *crypto, uint8_t u[32], uint8_t v[32],
666                                 uint8_t x[16], uint8_t y[16], uint32_t *val)
667 {
668         uint8_t m[80], tmp[16];
669
670         memcpy(&m[0], y, 16);
671         memcpy(&m[16], v, 32);
672         memcpy(&m[48], u, 32);
673
674         if (!aes_cmac(crypto, x, m, sizeof(m), tmp))
675                 return false;
676
677         *val = get_le32(tmp);
678         *val %= 1000000;
679
680         return true;
681 }