Bluetooth: Create SMP device structure for local crypto context
[firefly-linux-kernel-4.4.55.git] / net / bluetooth / smp.c
1 /*
2    BlueZ - Bluetooth protocol stack for Linux
3    Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License version 2 as
7    published by the Free Software Foundation;
8
9    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
11    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
12    IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
13    CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
14    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
18    ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
19    COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
20    SOFTWARE IS DISCLAIMED.
21 */
22
23 #include <linux/debugfs.h>
24 #include <linux/crypto.h>
25 #include <linux/scatterlist.h>
26 #include <crypto/b128ops.h>
27
28 #include <net/bluetooth/bluetooth.h>
29 #include <net/bluetooth/hci_core.h>
30 #include <net/bluetooth/l2cap.h>
31 #include <net/bluetooth/mgmt.h>
32
33 #include "ecc.h"
34 #include "smp.h"
35
36 /* Low-level debug macros to be used for stuff that we don't want
37  * accidentially in dmesg, i.e. the values of the various crypto keys
38  * and the inputs & outputs of crypto functions.
39  */
40 #ifdef DEBUG
41 #define SMP_DBG(fmt, ...) printk(KERN_DEBUG "%s: " fmt, __func__, \
42                                  ##__VA_ARGS__)
43 #else
44 #define SMP_DBG(fmt, ...) no_printk(KERN_DEBUG "%s: " fmt, __func__, \
45                                     ##__VA_ARGS__)
46 #endif
47
48 #define SMP_ALLOW_CMD(smp, code)        set_bit(code, &smp->allow_cmd)
49
50 /* Keys which are not distributed with Secure Connections */
51 #define SMP_SC_NO_DIST (SMP_DIST_ENC_KEY | SMP_DIST_LINK_KEY);
52
53 #define SMP_TIMEOUT     msecs_to_jiffies(30000)
54
55 #define AUTH_REQ_MASK(dev)      (hci_dev_test_flag(dev, HCI_SC_ENABLED) ? \
56                                  0x1f : 0x07)
57 #define KEY_DIST_MASK           0x07
58
59 /* Maximum message length that can be passed to aes_cmac */
60 #define CMAC_MSG_MAX    80
61
62 enum {
63         SMP_FLAG_TK_VALID,
64         SMP_FLAG_CFM_PENDING,
65         SMP_FLAG_MITM_AUTH,
66         SMP_FLAG_COMPLETE,
67         SMP_FLAG_INITIATOR,
68         SMP_FLAG_SC,
69         SMP_FLAG_REMOTE_PK,
70         SMP_FLAG_DEBUG_KEY,
71         SMP_FLAG_WAIT_USER,
72         SMP_FLAG_DHKEY_PENDING,
73         SMP_FLAG_OOB,
74 };
75
76 struct smp_dev {
77         struct crypto_blkcipher *tfm_aes;
78 };
79
80 struct smp_chan {
81         struct l2cap_conn       *conn;
82         struct delayed_work     security_timer;
83         unsigned long           allow_cmd; /* Bitmask of allowed commands */
84
85         u8              preq[7]; /* SMP Pairing Request */
86         u8              prsp[7]; /* SMP Pairing Response */
87         u8              prnd[16]; /* SMP Pairing Random (local) */
88         u8              rrnd[16]; /* SMP Pairing Random (remote) */
89         u8              pcnf[16]; /* SMP Pairing Confirm */
90         u8              tk[16]; /* SMP Temporary Key */
91         u8              rr[16];
92         u8              enc_key_size;
93         u8              remote_key_dist;
94         bdaddr_t        id_addr;
95         u8              id_addr_type;
96         u8              irk[16];
97         struct smp_csrk *csrk;
98         struct smp_csrk *slave_csrk;
99         struct smp_ltk  *ltk;
100         struct smp_ltk  *slave_ltk;
101         struct smp_irk  *remote_irk;
102         u8              *link_key;
103         unsigned long   flags;
104         u8              method;
105         u8              passkey_round;
106
107         /* Secure Connections variables */
108         u8                      local_pk[64];
109         u8                      local_sk[32];
110         u8                      remote_pk[64];
111         u8                      dhkey[32];
112         u8                      mackey[16];
113
114         struct crypto_blkcipher *tfm_aes;
115         struct crypto_hash      *tfm_cmac;
116 };
117
118 /* These debug key values are defined in the SMP section of the core
119  * specification. debug_pk is the public debug key and debug_sk the
120  * private debug key.
121  */
122 static const u8 debug_pk[64] = {
123                 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
124                 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
125                 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
126                 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20,
127
128                 0x8b, 0xd2, 0x89, 0x15, 0xd0, 0x8e, 0x1c, 0x74,
129                 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76,
130                 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63,
131                 0x6d, 0xeb, 0x2a, 0x65, 0x49, 0x9c, 0x80, 0xdc,
132 };
133
134 static const u8 debug_sk[32] = {
135                 0xbd, 0x1a, 0x3c, 0xcd, 0xa6, 0xb8, 0x99, 0x58,
136                 0x99, 0xb7, 0x40, 0xeb, 0x7b, 0x60, 0xff, 0x4a,
137                 0x50, 0x3f, 0x10, 0xd2, 0xe3, 0xb3, 0xc9, 0x74,
138                 0x38, 0x5f, 0xc5, 0xa3, 0xd4, 0xf6, 0x49, 0x3f,
139 };
140
141 static inline void swap_buf(const u8 *src, u8 *dst, size_t len)
142 {
143         size_t i;
144
145         for (i = 0; i < len; i++)
146                 dst[len - 1 - i] = src[i];
147 }
148
149 /* The following functions map to the LE SC SMP crypto functions
150  * AES-CMAC, f4, f5, f6, g2 and h6.
151  */
152
153 static int aes_cmac(struct crypto_hash *tfm, const u8 k[16], const u8 *m,
154                     size_t len, u8 mac[16])
155 {
156         uint8_t tmp[16], mac_msb[16], msg_msb[CMAC_MSG_MAX];
157         struct hash_desc desc;
158         struct scatterlist sg;
159         int err;
160
161         if (len > CMAC_MSG_MAX)
162                 return -EFBIG;
163
164         if (!tfm) {
165                 BT_ERR("tfm %p", tfm);
166                 return -EINVAL;
167         }
168
169         desc.tfm = tfm;
170         desc.flags = 0;
171
172         crypto_hash_init(&desc);
173
174         /* Swap key and message from LSB to MSB */
175         swap_buf(k, tmp, 16);
176         swap_buf(m, msg_msb, len);
177
178         SMP_DBG("msg (len %zu) %*phN", len, (int) len, m);
179         SMP_DBG("key %16phN", k);
180
181         err = crypto_hash_setkey(tfm, tmp, 16);
182         if (err) {
183                 BT_ERR("cipher setkey failed: %d", err);
184                 return err;
185         }
186
187         sg_init_one(&sg, msg_msb, len);
188
189         err = crypto_hash_update(&desc, &sg, len);
190         if (err) {
191                 BT_ERR("Hash update error %d", err);
192                 return err;
193         }
194
195         err = crypto_hash_final(&desc, mac_msb);
196         if (err) {
197                 BT_ERR("Hash final error %d", err);
198                 return err;
199         }
200
201         swap_buf(mac_msb, mac, 16);
202
203         SMP_DBG("mac %16phN", mac);
204
205         return 0;
206 }
207
208 static int smp_f4(struct crypto_hash *tfm_cmac, const u8 u[32], const u8 v[32],
209                   const u8 x[16], u8 z, u8 res[16])
210 {
211         u8 m[65];
212         int err;
213
214         SMP_DBG("u %32phN", u);
215         SMP_DBG("v %32phN", v);
216         SMP_DBG("x %16phN z %02x", x, z);
217
218         m[0] = z;
219         memcpy(m + 1, v, 32);
220         memcpy(m + 33, u, 32);
221
222         err = aes_cmac(tfm_cmac, x, m, sizeof(m), res);
223         if (err)
224                 return err;
225
226         SMP_DBG("res %16phN", res);
227
228         return err;
229 }
230
231 static int smp_f5(struct crypto_hash *tfm_cmac, const u8 w[32],
232                   const u8 n1[16], const u8 n2[16], const u8 a1[7],
233                   const u8 a2[7], u8 mackey[16], u8 ltk[16])
234 {
235         /* The btle, salt and length "magic" values are as defined in
236          * the SMP section of the Bluetooth core specification. In ASCII
237          * the btle value ends up being 'btle'. The salt is just a
238          * random number whereas length is the value 256 in little
239          * endian format.
240          */
241         const u8 btle[4] = { 0x65, 0x6c, 0x74, 0x62 };
242         const u8 salt[16] = { 0xbe, 0x83, 0x60, 0x5a, 0xdb, 0x0b, 0x37, 0x60,
243                               0x38, 0xa5, 0xf5, 0xaa, 0x91, 0x83, 0x88, 0x6c };
244         const u8 length[2] = { 0x00, 0x01 };
245         u8 m[53], t[16];
246         int err;
247
248         SMP_DBG("w %32phN", w);
249         SMP_DBG("n1 %16phN n2 %16phN", n1, n2);
250         SMP_DBG("a1 %7phN a2 %7phN", a1, a2);
251
252         err = aes_cmac(tfm_cmac, salt, w, 32, t);
253         if (err)
254                 return err;
255
256         SMP_DBG("t %16phN", t);
257
258         memcpy(m, length, 2);
259         memcpy(m + 2, a2, 7);
260         memcpy(m + 9, a1, 7);
261         memcpy(m + 16, n2, 16);
262         memcpy(m + 32, n1, 16);
263         memcpy(m + 48, btle, 4);
264
265         m[52] = 0; /* Counter */
266
267         err = aes_cmac(tfm_cmac, t, m, sizeof(m), mackey);
268         if (err)
269                 return err;
270
271         SMP_DBG("mackey %16phN", mackey);
272
273         m[52] = 1; /* Counter */
274
275         err = aes_cmac(tfm_cmac, t, m, sizeof(m), ltk);
276         if (err)
277                 return err;
278
279         SMP_DBG("ltk %16phN", ltk);
280
281         return 0;
282 }
283
284 static int smp_f6(struct crypto_hash *tfm_cmac, const u8 w[16],
285                   const u8 n1[16], const u8 n2[16], const u8 r[16],
286                   const u8 io_cap[3], const u8 a1[7], const u8 a2[7],
287                   u8 res[16])
288 {
289         u8 m[65];
290         int err;
291
292         SMP_DBG("w %16phN", w);
293         SMP_DBG("n1 %16phN n2 %16phN", n1, n2);
294         SMP_DBG("r %16phN io_cap %3phN a1 %7phN a2 %7phN", r, io_cap, a1, a2);
295
296         memcpy(m, a2, 7);
297         memcpy(m + 7, a1, 7);
298         memcpy(m + 14, io_cap, 3);
299         memcpy(m + 17, r, 16);
300         memcpy(m + 33, n2, 16);
301         memcpy(m + 49, n1, 16);
302
303         err = aes_cmac(tfm_cmac, w, m, sizeof(m), res);
304         if (err)
305                 return err;
306
307         SMP_DBG("res %16phN", res);
308
309         return err;
310 }
311
312 static int smp_g2(struct crypto_hash *tfm_cmac, const u8 u[32], const u8 v[32],
313                   const u8 x[16], const u8 y[16], u32 *val)
314 {
315         u8 m[80], tmp[16];
316         int err;
317
318         SMP_DBG("u %32phN", u);
319         SMP_DBG("v %32phN", v);
320         SMP_DBG("x %16phN y %16phN", x, y);
321
322         memcpy(m, y, 16);
323         memcpy(m + 16, v, 32);
324         memcpy(m + 48, u, 32);
325
326         err = aes_cmac(tfm_cmac, x, m, sizeof(m), tmp);
327         if (err)
328                 return err;
329
330         *val = get_unaligned_le32(tmp);
331         *val %= 1000000;
332
333         SMP_DBG("val %06u", *val);
334
335         return 0;
336 }
337
338 static int smp_h6(struct crypto_hash *tfm_cmac, const u8 w[16],
339                   const u8 key_id[4], u8 res[16])
340 {
341         int err;
342
343         SMP_DBG("w %16phN key_id %4phN", w, key_id);
344
345         err = aes_cmac(tfm_cmac, w, key_id, 4, res);
346         if (err)
347                 return err;
348
349         SMP_DBG("res %16phN", res);
350
351         return err;
352 }
353
354 /* The following functions map to the legacy SMP crypto functions e, c1,
355  * s1 and ah.
356  */
357
358 static int smp_e(struct crypto_blkcipher *tfm, const u8 *k, u8 *r)
359 {
360         struct blkcipher_desc desc;
361         struct scatterlist sg;
362         uint8_t tmp[16], data[16];
363         int err;
364
365         if (!tfm) {
366                 BT_ERR("tfm %p", tfm);
367                 return -EINVAL;
368         }
369
370         desc.tfm = tfm;
371         desc.flags = 0;
372
373         /* The most significant octet of key corresponds to k[0] */
374         swap_buf(k, tmp, 16);
375
376         err = crypto_blkcipher_setkey(tfm, tmp, 16);
377         if (err) {
378                 BT_ERR("cipher setkey failed: %d", err);
379                 return err;
380         }
381
382         /* Most significant octet of plaintextData corresponds to data[0] */
383         swap_buf(r, data, 16);
384
385         sg_init_one(&sg, data, 16);
386
387         err = crypto_blkcipher_encrypt(&desc, &sg, &sg, 16);
388         if (err)
389                 BT_ERR("Encrypt data error %d", err);
390
391         /* Most significant octet of encryptedData corresponds to data[0] */
392         swap_buf(data, r, 16);
393
394         return err;
395 }
396
397 static int smp_c1(struct crypto_blkcipher *tfm_aes, const u8 k[16],
398                   const u8 r[16], const u8 preq[7], const u8 pres[7], u8 _iat,
399                   const bdaddr_t *ia, u8 _rat, const bdaddr_t *ra, u8 res[16])
400 {
401         u8 p1[16], p2[16];
402         int err;
403
404         memset(p1, 0, 16);
405
406         /* p1 = pres || preq || _rat || _iat */
407         p1[0] = _iat;
408         p1[1] = _rat;
409         memcpy(p1 + 2, preq, 7);
410         memcpy(p1 + 9, pres, 7);
411
412         /* p2 = padding || ia || ra */
413         memcpy(p2, ra, 6);
414         memcpy(p2 + 6, ia, 6);
415         memset(p2 + 12, 0, 4);
416
417         /* res = r XOR p1 */
418         u128_xor((u128 *) res, (u128 *) r, (u128 *) p1);
419
420         /* res = e(k, res) */
421         err = smp_e(tfm_aes, k, res);
422         if (err) {
423                 BT_ERR("Encrypt data error");
424                 return err;
425         }
426
427         /* res = res XOR p2 */
428         u128_xor((u128 *) res, (u128 *) res, (u128 *) p2);
429
430         /* res = e(k, res) */
431         err = smp_e(tfm_aes, k, res);
432         if (err)
433                 BT_ERR("Encrypt data error");
434
435         return err;
436 }
437
438 static int smp_s1(struct crypto_blkcipher *tfm_aes, const u8 k[16],
439                   const u8 r1[16], const u8 r2[16], u8 _r[16])
440 {
441         int err;
442
443         /* Just least significant octets from r1 and r2 are considered */
444         memcpy(_r, r2, 8);
445         memcpy(_r + 8, r1, 8);
446
447         err = smp_e(tfm_aes, k, _r);
448         if (err)
449                 BT_ERR("Encrypt data error");
450
451         return err;
452 }
453
454 static int smp_ah(struct crypto_blkcipher *tfm, const u8 irk[16],
455                   const u8 r[3], u8 res[3])
456 {
457         u8 _res[16];
458         int err;
459
460         /* r' = padding || r */
461         memcpy(_res, r, 3);
462         memset(_res + 3, 0, 13);
463
464         err = smp_e(tfm, irk, _res);
465         if (err) {
466                 BT_ERR("Encrypt error");
467                 return err;
468         }
469
470         /* The output of the random address function ah is:
471          *      ah(h, r) = e(k, r') mod 2^24
472          * The output of the security function e is then truncated to 24 bits
473          * by taking the least significant 24 bits of the output of e as the
474          * result of ah.
475          */
476         memcpy(res, _res, 3);
477
478         return 0;
479 }
480
481 bool smp_irk_matches(struct hci_dev *hdev, const u8 irk[16],
482                      const bdaddr_t *bdaddr)
483 {
484         struct l2cap_chan *chan = hdev->smp_data;
485         struct smp_dev *smp;
486         u8 hash[3];
487         int err;
488
489         if (!chan || !chan->data)
490                 return false;
491
492         smp = chan->data;
493
494         BT_DBG("RPA %pMR IRK %*phN", bdaddr, 16, irk);
495
496         err = smp_ah(smp->tfm_aes, irk, &bdaddr->b[3], hash);
497         if (err)
498                 return false;
499
500         return !memcmp(bdaddr->b, hash, 3);
501 }
502
503 int smp_generate_rpa(struct hci_dev *hdev, const u8 irk[16], bdaddr_t *rpa)
504 {
505         struct l2cap_chan *chan = hdev->smp_data;
506         struct smp_dev *smp;
507         int err;
508
509         if (!chan || !chan->data)
510                 return -EOPNOTSUPP;
511
512         smp = chan->data;
513
514         get_random_bytes(&rpa->b[3], 3);
515
516         rpa->b[5] &= 0x3f;      /* Clear two most significant bits */
517         rpa->b[5] |= 0x40;      /* Set second most significant bit */
518
519         err = smp_ah(smp->tfm_aes, irk, &rpa->b[3], rpa->b);
520         if (err < 0)
521                 return err;
522
523         BT_DBG("RPA %pMR", rpa);
524
525         return 0;
526 }
527
528 static void smp_send_cmd(struct l2cap_conn *conn, u8 code, u16 len, void *data)
529 {
530         struct l2cap_chan *chan = conn->smp;
531         struct smp_chan *smp;
532         struct kvec iv[2];
533         struct msghdr msg;
534
535         if (!chan)
536                 return;
537
538         BT_DBG("code 0x%2.2x", code);
539
540         iv[0].iov_base = &code;
541         iv[0].iov_len = 1;
542
543         iv[1].iov_base = data;
544         iv[1].iov_len = len;
545
546         memset(&msg, 0, sizeof(msg));
547
548         iov_iter_kvec(&msg.msg_iter, WRITE | ITER_KVEC, iv, 2, 1 + len);
549
550         l2cap_chan_send(chan, &msg, 1 + len);
551
552         if (!chan->data)
553                 return;
554
555         smp = chan->data;
556
557         cancel_delayed_work_sync(&smp->security_timer);
558         schedule_delayed_work(&smp->security_timer, SMP_TIMEOUT);
559 }
560
561 static u8 authreq_to_seclevel(u8 authreq)
562 {
563         if (authreq & SMP_AUTH_MITM) {
564                 if (authreq & SMP_AUTH_SC)
565                         return BT_SECURITY_FIPS;
566                 else
567                         return BT_SECURITY_HIGH;
568         } else {
569                 return BT_SECURITY_MEDIUM;
570         }
571 }
572
573 static __u8 seclevel_to_authreq(__u8 sec_level)
574 {
575         switch (sec_level) {
576         case BT_SECURITY_FIPS:
577         case BT_SECURITY_HIGH:
578                 return SMP_AUTH_MITM | SMP_AUTH_BONDING;
579         case BT_SECURITY_MEDIUM:
580                 return SMP_AUTH_BONDING;
581         default:
582                 return SMP_AUTH_NONE;
583         }
584 }
585
586 static void build_pairing_cmd(struct l2cap_conn *conn,
587                               struct smp_cmd_pairing *req,
588                               struct smp_cmd_pairing *rsp, __u8 authreq)
589 {
590         struct l2cap_chan *chan = conn->smp;
591         struct smp_chan *smp = chan->data;
592         struct hci_conn *hcon = conn->hcon;
593         struct hci_dev *hdev = hcon->hdev;
594         u8 local_dist = 0, remote_dist = 0, oob_flag = SMP_OOB_NOT_PRESENT;
595
596         if (hci_dev_test_flag(hdev, HCI_BONDABLE)) {
597                 local_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
598                 remote_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
599                 authreq |= SMP_AUTH_BONDING;
600         } else {
601                 authreq &= ~SMP_AUTH_BONDING;
602         }
603
604         if (hci_dev_test_flag(hdev, HCI_RPA_RESOLVING))
605                 remote_dist |= SMP_DIST_ID_KEY;
606
607         if (hci_dev_test_flag(hdev, HCI_PRIVACY))
608                 local_dist |= SMP_DIST_ID_KEY;
609
610         if (hci_dev_test_flag(hdev, HCI_SC_ENABLED) &&
611             (authreq & SMP_AUTH_SC)) {
612                 struct oob_data *oob_data;
613                 u8 bdaddr_type;
614
615                 if (hci_dev_test_flag(hdev, HCI_SSP_ENABLED)) {
616                         local_dist |= SMP_DIST_LINK_KEY;
617                         remote_dist |= SMP_DIST_LINK_KEY;
618                 }
619
620                 if (hcon->dst_type == ADDR_LE_DEV_PUBLIC)
621                         bdaddr_type = BDADDR_LE_PUBLIC;
622                 else
623                         bdaddr_type = BDADDR_LE_RANDOM;
624
625                 oob_data = hci_find_remote_oob_data(hdev, &hcon->dst,
626                                                     bdaddr_type);
627                 if (oob_data && oob_data->present) {
628                         set_bit(SMP_FLAG_OOB, &smp->flags);
629                         oob_flag = SMP_OOB_PRESENT;
630                         memcpy(smp->rr, oob_data->rand256, 16);
631                         memcpy(smp->pcnf, oob_data->hash256, 16);
632                 }
633
634         } else {
635                 authreq &= ~SMP_AUTH_SC;
636         }
637
638         if (rsp == NULL) {
639                 req->io_capability = conn->hcon->io_capability;
640                 req->oob_flag = oob_flag;
641                 req->max_key_size = SMP_MAX_ENC_KEY_SIZE;
642                 req->init_key_dist = local_dist;
643                 req->resp_key_dist = remote_dist;
644                 req->auth_req = (authreq & AUTH_REQ_MASK(hdev));
645
646                 smp->remote_key_dist = remote_dist;
647                 return;
648         }
649
650         rsp->io_capability = conn->hcon->io_capability;
651         rsp->oob_flag = oob_flag;
652         rsp->max_key_size = SMP_MAX_ENC_KEY_SIZE;
653         rsp->init_key_dist = req->init_key_dist & remote_dist;
654         rsp->resp_key_dist = req->resp_key_dist & local_dist;
655         rsp->auth_req = (authreq & AUTH_REQ_MASK(hdev));
656
657         smp->remote_key_dist = rsp->init_key_dist;
658 }
659
660 static u8 check_enc_key_size(struct l2cap_conn *conn, __u8 max_key_size)
661 {
662         struct l2cap_chan *chan = conn->smp;
663         struct smp_chan *smp = chan->data;
664
665         if ((max_key_size > SMP_MAX_ENC_KEY_SIZE) ||
666             (max_key_size < SMP_MIN_ENC_KEY_SIZE))
667                 return SMP_ENC_KEY_SIZE;
668
669         smp->enc_key_size = max_key_size;
670
671         return 0;
672 }
673
674 static void smp_chan_destroy(struct l2cap_conn *conn)
675 {
676         struct l2cap_chan *chan = conn->smp;
677         struct smp_chan *smp = chan->data;
678         struct hci_conn *hcon = conn->hcon;
679         bool complete;
680
681         BUG_ON(!smp);
682
683         cancel_delayed_work_sync(&smp->security_timer);
684
685         complete = test_bit(SMP_FLAG_COMPLETE, &smp->flags);
686         mgmt_smp_complete(hcon, complete);
687
688         kzfree(smp->csrk);
689         kzfree(smp->slave_csrk);
690         kzfree(smp->link_key);
691
692         crypto_free_blkcipher(smp->tfm_aes);
693         crypto_free_hash(smp->tfm_cmac);
694
695         /* Ensure that we don't leave any debug key around if debug key
696          * support hasn't been explicitly enabled.
697          */
698         if (smp->ltk && smp->ltk->type == SMP_LTK_P256_DEBUG &&
699             !hci_dev_test_flag(hcon->hdev, HCI_KEEP_DEBUG_KEYS)) {
700                 list_del_rcu(&smp->ltk->list);
701                 kfree_rcu(smp->ltk, rcu);
702                 smp->ltk = NULL;
703         }
704
705         /* If pairing failed clean up any keys we might have */
706         if (!complete) {
707                 if (smp->ltk) {
708                         list_del_rcu(&smp->ltk->list);
709                         kfree_rcu(smp->ltk, rcu);
710                 }
711
712                 if (smp->slave_ltk) {
713                         list_del_rcu(&smp->slave_ltk->list);
714                         kfree_rcu(smp->slave_ltk, rcu);
715                 }
716
717                 if (smp->remote_irk) {
718                         list_del_rcu(&smp->remote_irk->list);
719                         kfree_rcu(smp->remote_irk, rcu);
720                 }
721         }
722
723         chan->data = NULL;
724         kzfree(smp);
725         hci_conn_drop(hcon);
726 }
727
728 static void smp_failure(struct l2cap_conn *conn, u8 reason)
729 {
730         struct hci_conn *hcon = conn->hcon;
731         struct l2cap_chan *chan = conn->smp;
732
733         if (reason)
734                 smp_send_cmd(conn, SMP_CMD_PAIRING_FAIL, sizeof(reason),
735                              &reason);
736
737         clear_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags);
738         mgmt_auth_failed(hcon, HCI_ERROR_AUTH_FAILURE);
739
740         if (chan->data)
741                 smp_chan_destroy(conn);
742 }
743
744 #define JUST_WORKS      0x00
745 #define JUST_CFM        0x01
746 #define REQ_PASSKEY     0x02
747 #define CFM_PASSKEY     0x03
748 #define REQ_OOB         0x04
749 #define DSP_PASSKEY     0x05
750 #define OVERLAP         0xFF
751
752 static const u8 gen_method[5][5] = {
753         { JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
754         { JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
755         { CFM_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, CFM_PASSKEY },
756         { JUST_WORKS,  JUST_CFM,    JUST_WORKS,  JUST_WORKS, JUST_CFM    },
757         { CFM_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, OVERLAP     },
758 };
759
760 static const u8 sc_method[5][5] = {
761         { JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
762         { JUST_WORKS,  CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, CFM_PASSKEY },
763         { DSP_PASSKEY, DSP_PASSKEY, REQ_PASSKEY, JUST_WORKS, DSP_PASSKEY },
764         { JUST_WORKS,  JUST_CFM,    JUST_WORKS,  JUST_WORKS, JUST_CFM    },
765         { DSP_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, CFM_PASSKEY },
766 };
767
768 static u8 get_auth_method(struct smp_chan *smp, u8 local_io, u8 remote_io)
769 {
770         /* If either side has unknown io_caps, use JUST_CFM (which gets
771          * converted later to JUST_WORKS if we're initiators.
772          */
773         if (local_io > SMP_IO_KEYBOARD_DISPLAY ||
774             remote_io > SMP_IO_KEYBOARD_DISPLAY)
775                 return JUST_CFM;
776
777         if (test_bit(SMP_FLAG_SC, &smp->flags))
778                 return sc_method[remote_io][local_io];
779
780         return gen_method[remote_io][local_io];
781 }
782
783 static int tk_request(struct l2cap_conn *conn, u8 remote_oob, u8 auth,
784                                                 u8 local_io, u8 remote_io)
785 {
786         struct hci_conn *hcon = conn->hcon;
787         struct l2cap_chan *chan = conn->smp;
788         struct smp_chan *smp = chan->data;
789         u32 passkey = 0;
790         int ret = 0;
791
792         /* Initialize key for JUST WORKS */
793         memset(smp->tk, 0, sizeof(smp->tk));
794         clear_bit(SMP_FLAG_TK_VALID, &smp->flags);
795
796         BT_DBG("tk_request: auth:%d lcl:%d rem:%d", auth, local_io, remote_io);
797
798         /* If neither side wants MITM, either "just" confirm an incoming
799          * request or use just-works for outgoing ones. The JUST_CFM
800          * will be converted to JUST_WORKS if necessary later in this
801          * function. If either side has MITM look up the method from the
802          * table.
803          */
804         if (!(auth & SMP_AUTH_MITM))
805                 smp->method = JUST_CFM;
806         else
807                 smp->method = get_auth_method(smp, local_io, remote_io);
808
809         /* Don't confirm locally initiated pairing attempts */
810         if (smp->method == JUST_CFM && test_bit(SMP_FLAG_INITIATOR,
811                                                 &smp->flags))
812                 smp->method = JUST_WORKS;
813
814         /* Don't bother user space with no IO capabilities */
815         if (smp->method == JUST_CFM &&
816             hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
817                 smp->method = JUST_WORKS;
818
819         /* If Just Works, Continue with Zero TK */
820         if (smp->method == JUST_WORKS) {
821                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
822                 return 0;
823         }
824
825         /* Not Just Works/Confirm results in MITM Authentication */
826         if (smp->method != JUST_CFM) {
827                 set_bit(SMP_FLAG_MITM_AUTH, &smp->flags);
828                 if (hcon->pending_sec_level < BT_SECURITY_HIGH)
829                         hcon->pending_sec_level = BT_SECURITY_HIGH;
830         }
831
832         /* If both devices have Keyoard-Display I/O, the master
833          * Confirms and the slave Enters the passkey.
834          */
835         if (smp->method == OVERLAP) {
836                 if (hcon->role == HCI_ROLE_MASTER)
837                         smp->method = CFM_PASSKEY;
838                 else
839                         smp->method = REQ_PASSKEY;
840         }
841
842         /* Generate random passkey. */
843         if (smp->method == CFM_PASSKEY) {
844                 memset(smp->tk, 0, sizeof(smp->tk));
845                 get_random_bytes(&passkey, sizeof(passkey));
846                 passkey %= 1000000;
847                 put_unaligned_le32(passkey, smp->tk);
848                 BT_DBG("PassKey: %d", passkey);
849                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
850         }
851
852         if (smp->method == REQ_PASSKEY)
853                 ret = mgmt_user_passkey_request(hcon->hdev, &hcon->dst,
854                                                 hcon->type, hcon->dst_type);
855         else if (smp->method == JUST_CFM)
856                 ret = mgmt_user_confirm_request(hcon->hdev, &hcon->dst,
857                                                 hcon->type, hcon->dst_type,
858                                                 passkey, 1);
859         else
860                 ret = mgmt_user_passkey_notify(hcon->hdev, &hcon->dst,
861                                                 hcon->type, hcon->dst_type,
862                                                 passkey, 0);
863
864         return ret;
865 }
866
867 static u8 smp_confirm(struct smp_chan *smp)
868 {
869         struct l2cap_conn *conn = smp->conn;
870         struct smp_cmd_pairing_confirm cp;
871         int ret;
872
873         BT_DBG("conn %p", conn);
874
875         ret = smp_c1(smp->tfm_aes, smp->tk, smp->prnd, smp->preq, smp->prsp,
876                      conn->hcon->init_addr_type, &conn->hcon->init_addr,
877                      conn->hcon->resp_addr_type, &conn->hcon->resp_addr,
878                      cp.confirm_val);
879         if (ret)
880                 return SMP_UNSPECIFIED;
881
882         clear_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
883
884         smp_send_cmd(smp->conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cp), &cp);
885
886         if (conn->hcon->out)
887                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
888         else
889                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
890
891         return 0;
892 }
893
894 static u8 smp_random(struct smp_chan *smp)
895 {
896         struct l2cap_conn *conn = smp->conn;
897         struct hci_conn *hcon = conn->hcon;
898         u8 confirm[16];
899         int ret;
900
901         if (IS_ERR_OR_NULL(smp->tfm_aes))
902                 return SMP_UNSPECIFIED;
903
904         BT_DBG("conn %p %s", conn, conn->hcon->out ? "master" : "slave");
905
906         ret = smp_c1(smp->tfm_aes, smp->tk, smp->rrnd, smp->preq, smp->prsp,
907                      hcon->init_addr_type, &hcon->init_addr,
908                      hcon->resp_addr_type, &hcon->resp_addr, confirm);
909         if (ret)
910                 return SMP_UNSPECIFIED;
911
912         if (memcmp(smp->pcnf, confirm, sizeof(smp->pcnf)) != 0) {
913                 BT_ERR("Pairing failed (confirmation values mismatch)");
914                 return SMP_CONFIRM_FAILED;
915         }
916
917         if (hcon->out) {
918                 u8 stk[16];
919                 __le64 rand = 0;
920                 __le16 ediv = 0;
921
922                 smp_s1(smp->tfm_aes, smp->tk, smp->rrnd, smp->prnd, stk);
923
924                 memset(stk + smp->enc_key_size, 0,
925                        SMP_MAX_ENC_KEY_SIZE - smp->enc_key_size);
926
927                 if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags))
928                         return SMP_UNSPECIFIED;
929
930                 hci_le_start_enc(hcon, ediv, rand, stk);
931                 hcon->enc_key_size = smp->enc_key_size;
932                 set_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags);
933         } else {
934                 u8 stk[16], auth;
935                 __le64 rand = 0;
936                 __le16 ediv = 0;
937
938                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
939                              smp->prnd);
940
941                 smp_s1(smp->tfm_aes, smp->tk, smp->prnd, smp->rrnd, stk);
942
943                 memset(stk + smp->enc_key_size, 0,
944                        SMP_MAX_ENC_KEY_SIZE - smp->enc_key_size);
945
946                 if (hcon->pending_sec_level == BT_SECURITY_HIGH)
947                         auth = 1;
948                 else
949                         auth = 0;
950
951                 /* Even though there's no _SLAVE suffix this is the
952                  * slave STK we're adding for later lookup (the master
953                  * STK never needs to be stored).
954                  */
955                 hci_add_ltk(hcon->hdev, &hcon->dst, hcon->dst_type,
956                             SMP_STK, auth, stk, smp->enc_key_size, ediv, rand);
957         }
958
959         return 0;
960 }
961
962 static void smp_notify_keys(struct l2cap_conn *conn)
963 {
964         struct l2cap_chan *chan = conn->smp;
965         struct smp_chan *smp = chan->data;
966         struct hci_conn *hcon = conn->hcon;
967         struct hci_dev *hdev = hcon->hdev;
968         struct smp_cmd_pairing *req = (void *) &smp->preq[1];
969         struct smp_cmd_pairing *rsp = (void *) &smp->prsp[1];
970         bool persistent;
971
972         if (smp->remote_irk) {
973                 mgmt_new_irk(hdev, smp->remote_irk);
974                 /* Now that user space can be considered to know the
975                  * identity address track the connection based on it
976                  * from now on (assuming this is an LE link).
977                  */
978                 if (hcon->type == LE_LINK) {
979                         bacpy(&hcon->dst, &smp->remote_irk->bdaddr);
980                         hcon->dst_type = smp->remote_irk->addr_type;
981                         queue_work(hdev->workqueue, &conn->id_addr_update_work);
982                 }
983
984                 /* When receiving an indentity resolving key for
985                  * a remote device that does not use a resolvable
986                  * private address, just remove the key so that
987                  * it is possible to use the controller white
988                  * list for scanning.
989                  *
990                  * Userspace will have been told to not store
991                  * this key at this point. So it is safe to
992                  * just remove it.
993                  */
994                 if (!bacmp(&smp->remote_irk->rpa, BDADDR_ANY)) {
995                         list_del_rcu(&smp->remote_irk->list);
996                         kfree_rcu(smp->remote_irk, rcu);
997                         smp->remote_irk = NULL;
998                 }
999         }
1000
1001         if (hcon->type == ACL_LINK) {
1002                 if (hcon->key_type == HCI_LK_DEBUG_COMBINATION)
1003                         persistent = false;
1004                 else
1005                         persistent = !test_bit(HCI_CONN_FLUSH_KEY,
1006                                                &hcon->flags);
1007         } else {
1008                 /* The LTKs and CSRKs should be persistent only if both sides
1009                  * had the bonding bit set in their authentication requests.
1010                  */
1011                 persistent = !!((req->auth_req & rsp->auth_req) &
1012                                 SMP_AUTH_BONDING);
1013         }
1014
1015
1016         if (smp->csrk) {
1017                 smp->csrk->bdaddr_type = hcon->dst_type;
1018                 bacpy(&smp->csrk->bdaddr, &hcon->dst);
1019                 mgmt_new_csrk(hdev, smp->csrk, persistent);
1020         }
1021
1022         if (smp->slave_csrk) {
1023                 smp->slave_csrk->bdaddr_type = hcon->dst_type;
1024                 bacpy(&smp->slave_csrk->bdaddr, &hcon->dst);
1025                 mgmt_new_csrk(hdev, smp->slave_csrk, persistent);
1026         }
1027
1028         if (smp->ltk) {
1029                 smp->ltk->bdaddr_type = hcon->dst_type;
1030                 bacpy(&smp->ltk->bdaddr, &hcon->dst);
1031                 mgmt_new_ltk(hdev, smp->ltk, persistent);
1032         }
1033
1034         if (smp->slave_ltk) {
1035                 smp->slave_ltk->bdaddr_type = hcon->dst_type;
1036                 bacpy(&smp->slave_ltk->bdaddr, &hcon->dst);
1037                 mgmt_new_ltk(hdev, smp->slave_ltk, persistent);
1038         }
1039
1040         if (smp->link_key) {
1041                 struct link_key *key;
1042                 u8 type;
1043
1044                 if (test_bit(SMP_FLAG_DEBUG_KEY, &smp->flags))
1045                         type = HCI_LK_DEBUG_COMBINATION;
1046                 else if (hcon->sec_level == BT_SECURITY_FIPS)
1047                         type = HCI_LK_AUTH_COMBINATION_P256;
1048                 else
1049                         type = HCI_LK_UNAUTH_COMBINATION_P256;
1050
1051                 key = hci_add_link_key(hdev, smp->conn->hcon, &hcon->dst,
1052                                        smp->link_key, type, 0, &persistent);
1053                 if (key) {
1054                         mgmt_new_link_key(hdev, key, persistent);
1055
1056                         /* Don't keep debug keys around if the relevant
1057                          * flag is not set.
1058                          */
1059                         if (!hci_dev_test_flag(hdev, HCI_KEEP_DEBUG_KEYS) &&
1060                             key->type == HCI_LK_DEBUG_COMBINATION) {
1061                                 list_del_rcu(&key->list);
1062                                 kfree_rcu(key, rcu);
1063                         }
1064                 }
1065         }
1066 }
1067
1068 static void sc_add_ltk(struct smp_chan *smp)
1069 {
1070         struct hci_conn *hcon = smp->conn->hcon;
1071         u8 key_type, auth;
1072
1073         if (test_bit(SMP_FLAG_DEBUG_KEY, &smp->flags))
1074                 key_type = SMP_LTK_P256_DEBUG;
1075         else
1076                 key_type = SMP_LTK_P256;
1077
1078         if (hcon->pending_sec_level == BT_SECURITY_FIPS)
1079                 auth = 1;
1080         else
1081                 auth = 0;
1082
1083         memset(smp->tk + smp->enc_key_size, 0,
1084                SMP_MAX_ENC_KEY_SIZE - smp->enc_key_size);
1085
1086         smp->ltk = hci_add_ltk(hcon->hdev, &hcon->dst, hcon->dst_type,
1087                                key_type, auth, smp->tk, smp->enc_key_size,
1088                                0, 0);
1089 }
1090
1091 static void sc_generate_link_key(struct smp_chan *smp)
1092 {
1093         /* These constants are as specified in the core specification.
1094          * In ASCII they spell out to 'tmp1' and 'lebr'.
1095          */
1096         const u8 tmp1[4] = { 0x31, 0x70, 0x6d, 0x74 };
1097         const u8 lebr[4] = { 0x72, 0x62, 0x65, 0x6c };
1098
1099         smp->link_key = kzalloc(16, GFP_KERNEL);
1100         if (!smp->link_key)
1101                 return;
1102
1103         if (smp_h6(smp->tfm_cmac, smp->tk, tmp1, smp->link_key)) {
1104                 kzfree(smp->link_key);
1105                 smp->link_key = NULL;
1106                 return;
1107         }
1108
1109         if (smp_h6(smp->tfm_cmac, smp->link_key, lebr, smp->link_key)) {
1110                 kzfree(smp->link_key);
1111                 smp->link_key = NULL;
1112                 return;
1113         }
1114 }
1115
1116 static void smp_allow_key_dist(struct smp_chan *smp)
1117 {
1118         /* Allow the first expected phase 3 PDU. The rest of the PDUs
1119          * will be allowed in each PDU handler to ensure we receive
1120          * them in the correct order.
1121          */
1122         if (smp->remote_key_dist & SMP_DIST_ENC_KEY)
1123                 SMP_ALLOW_CMD(smp, SMP_CMD_ENCRYPT_INFO);
1124         else if (smp->remote_key_dist & SMP_DIST_ID_KEY)
1125                 SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_INFO);
1126         else if (smp->remote_key_dist & SMP_DIST_SIGN)
1127                 SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
1128 }
1129
1130 static void sc_generate_ltk(struct smp_chan *smp)
1131 {
1132         /* These constants are as specified in the core specification.
1133          * In ASCII they spell out to 'tmp2' and 'brle'.
1134          */
1135         const u8 tmp2[4] = { 0x32, 0x70, 0x6d, 0x74 };
1136         const u8 brle[4] = { 0x65, 0x6c, 0x72, 0x62 };
1137         struct hci_conn *hcon = smp->conn->hcon;
1138         struct hci_dev *hdev = hcon->hdev;
1139         struct link_key *key;
1140
1141         key = hci_find_link_key(hdev, &hcon->dst);
1142         if (!key) {
1143                 BT_ERR("%s No Link Key found to generate LTK", hdev->name);
1144                 return;
1145         }
1146
1147         if (key->type == HCI_LK_DEBUG_COMBINATION)
1148                 set_bit(SMP_FLAG_DEBUG_KEY, &smp->flags);
1149
1150         if (smp_h6(smp->tfm_cmac, key->val, tmp2, smp->tk))
1151                 return;
1152
1153         if (smp_h6(smp->tfm_cmac, smp->tk, brle, smp->tk))
1154                 return;
1155
1156         sc_add_ltk(smp);
1157 }
1158
1159 static void smp_distribute_keys(struct smp_chan *smp)
1160 {
1161         struct smp_cmd_pairing *req, *rsp;
1162         struct l2cap_conn *conn = smp->conn;
1163         struct hci_conn *hcon = conn->hcon;
1164         struct hci_dev *hdev = hcon->hdev;
1165         __u8 *keydist;
1166
1167         BT_DBG("conn %p", conn);
1168
1169         rsp = (void *) &smp->prsp[1];
1170
1171         /* The responder sends its keys first */
1172         if (hcon->out && (smp->remote_key_dist & KEY_DIST_MASK)) {
1173                 smp_allow_key_dist(smp);
1174                 return;
1175         }
1176
1177         req = (void *) &smp->preq[1];
1178
1179         if (hcon->out) {
1180                 keydist = &rsp->init_key_dist;
1181                 *keydist &= req->init_key_dist;
1182         } else {
1183                 keydist = &rsp->resp_key_dist;
1184                 *keydist &= req->resp_key_dist;
1185         }
1186
1187         if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1188                 if (hcon->type == LE_LINK && (*keydist & SMP_DIST_LINK_KEY))
1189                         sc_generate_link_key(smp);
1190                 if (hcon->type == ACL_LINK && (*keydist & SMP_DIST_ENC_KEY))
1191                         sc_generate_ltk(smp);
1192
1193                 /* Clear the keys which are generated but not distributed */
1194                 *keydist &= ~SMP_SC_NO_DIST;
1195         }
1196
1197         BT_DBG("keydist 0x%x", *keydist);
1198
1199         if (*keydist & SMP_DIST_ENC_KEY) {
1200                 struct smp_cmd_encrypt_info enc;
1201                 struct smp_cmd_master_ident ident;
1202                 struct smp_ltk *ltk;
1203                 u8 authenticated;
1204                 __le16 ediv;
1205                 __le64 rand;
1206
1207                 get_random_bytes(enc.ltk, sizeof(enc.ltk));
1208                 get_random_bytes(&ediv, sizeof(ediv));
1209                 get_random_bytes(&rand, sizeof(rand));
1210
1211                 smp_send_cmd(conn, SMP_CMD_ENCRYPT_INFO, sizeof(enc), &enc);
1212
1213                 authenticated = hcon->sec_level == BT_SECURITY_HIGH;
1214                 ltk = hci_add_ltk(hdev, &hcon->dst, hcon->dst_type,
1215                                   SMP_LTK_SLAVE, authenticated, enc.ltk,
1216                                   smp->enc_key_size, ediv, rand);
1217                 smp->slave_ltk = ltk;
1218
1219                 ident.ediv = ediv;
1220                 ident.rand = rand;
1221
1222                 smp_send_cmd(conn, SMP_CMD_MASTER_IDENT, sizeof(ident), &ident);
1223
1224                 *keydist &= ~SMP_DIST_ENC_KEY;
1225         }
1226
1227         if (*keydist & SMP_DIST_ID_KEY) {
1228                 struct smp_cmd_ident_addr_info addrinfo;
1229                 struct smp_cmd_ident_info idinfo;
1230
1231                 memcpy(idinfo.irk, hdev->irk, sizeof(idinfo.irk));
1232
1233                 smp_send_cmd(conn, SMP_CMD_IDENT_INFO, sizeof(idinfo), &idinfo);
1234
1235                 /* The hci_conn contains the local identity address
1236                  * after the connection has been established.
1237                  *
1238                  * This is true even when the connection has been
1239                  * established using a resolvable random address.
1240                  */
1241                 bacpy(&addrinfo.bdaddr, &hcon->src);
1242                 addrinfo.addr_type = hcon->src_type;
1243
1244                 smp_send_cmd(conn, SMP_CMD_IDENT_ADDR_INFO, sizeof(addrinfo),
1245                              &addrinfo);
1246
1247                 *keydist &= ~SMP_DIST_ID_KEY;
1248         }
1249
1250         if (*keydist & SMP_DIST_SIGN) {
1251                 struct smp_cmd_sign_info sign;
1252                 struct smp_csrk *csrk;
1253
1254                 /* Generate a new random key */
1255                 get_random_bytes(sign.csrk, sizeof(sign.csrk));
1256
1257                 csrk = kzalloc(sizeof(*csrk), GFP_KERNEL);
1258                 if (csrk) {
1259                         if (hcon->sec_level > BT_SECURITY_MEDIUM)
1260                                 csrk->type = MGMT_CSRK_LOCAL_AUTHENTICATED;
1261                         else
1262                                 csrk->type = MGMT_CSRK_LOCAL_UNAUTHENTICATED;
1263                         memcpy(csrk->val, sign.csrk, sizeof(csrk->val));
1264                 }
1265                 smp->slave_csrk = csrk;
1266
1267                 smp_send_cmd(conn, SMP_CMD_SIGN_INFO, sizeof(sign), &sign);
1268
1269                 *keydist &= ~SMP_DIST_SIGN;
1270         }
1271
1272         /* If there are still keys to be received wait for them */
1273         if (smp->remote_key_dist & KEY_DIST_MASK) {
1274                 smp_allow_key_dist(smp);
1275                 return;
1276         }
1277
1278         set_bit(SMP_FLAG_COMPLETE, &smp->flags);
1279         smp_notify_keys(conn);
1280
1281         smp_chan_destroy(conn);
1282 }
1283
1284 static void smp_timeout(struct work_struct *work)
1285 {
1286         struct smp_chan *smp = container_of(work, struct smp_chan,
1287                                             security_timer.work);
1288         struct l2cap_conn *conn = smp->conn;
1289
1290         BT_DBG("conn %p", conn);
1291
1292         hci_disconnect(conn->hcon, HCI_ERROR_REMOTE_USER_TERM);
1293 }
1294
1295 static struct smp_chan *smp_chan_create(struct l2cap_conn *conn)
1296 {
1297         struct l2cap_chan *chan = conn->smp;
1298         struct smp_chan *smp;
1299
1300         smp = kzalloc(sizeof(*smp), GFP_ATOMIC);
1301         if (!smp)
1302                 return NULL;
1303
1304         smp->tfm_aes = crypto_alloc_blkcipher("ecb(aes)", 0, CRYPTO_ALG_ASYNC);
1305         if (IS_ERR(smp->tfm_aes)) {
1306                 BT_ERR("Unable to create ECB crypto context");
1307                 kzfree(smp);
1308                 return NULL;
1309         }
1310
1311         smp->tfm_cmac = crypto_alloc_hash("cmac(aes)", 0, CRYPTO_ALG_ASYNC);
1312         if (IS_ERR(smp->tfm_cmac)) {
1313                 BT_ERR("Unable to create CMAC crypto context");
1314                 crypto_free_blkcipher(smp->tfm_aes);
1315                 kzfree(smp);
1316                 return NULL;
1317         }
1318
1319         smp->conn = conn;
1320         chan->data = smp;
1321
1322         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_FAIL);
1323
1324         INIT_DELAYED_WORK(&smp->security_timer, smp_timeout);
1325
1326         hci_conn_hold(conn->hcon);
1327
1328         return smp;
1329 }
1330
1331 static int sc_mackey_and_ltk(struct smp_chan *smp, u8 mackey[16], u8 ltk[16])
1332 {
1333         struct hci_conn *hcon = smp->conn->hcon;
1334         u8 *na, *nb, a[7], b[7];
1335
1336         if (hcon->out) {
1337                 na   = smp->prnd;
1338                 nb   = smp->rrnd;
1339         } else {
1340                 na   = smp->rrnd;
1341                 nb   = smp->prnd;
1342         }
1343
1344         memcpy(a, &hcon->init_addr, 6);
1345         memcpy(b, &hcon->resp_addr, 6);
1346         a[6] = hcon->init_addr_type;
1347         b[6] = hcon->resp_addr_type;
1348
1349         return smp_f5(smp->tfm_cmac, smp->dhkey, na, nb, a, b, mackey, ltk);
1350 }
1351
1352 static void sc_dhkey_check(struct smp_chan *smp)
1353 {
1354         struct hci_conn *hcon = smp->conn->hcon;
1355         struct smp_cmd_dhkey_check check;
1356         u8 a[7], b[7], *local_addr, *remote_addr;
1357         u8 io_cap[3], r[16];
1358
1359         memcpy(a, &hcon->init_addr, 6);
1360         memcpy(b, &hcon->resp_addr, 6);
1361         a[6] = hcon->init_addr_type;
1362         b[6] = hcon->resp_addr_type;
1363
1364         if (hcon->out) {
1365                 local_addr = a;
1366                 remote_addr = b;
1367                 memcpy(io_cap, &smp->preq[1], 3);
1368         } else {
1369                 local_addr = b;
1370                 remote_addr = a;
1371                 memcpy(io_cap, &smp->prsp[1], 3);
1372         }
1373
1374         memset(r, 0, sizeof(r));
1375
1376         if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
1377                 put_unaligned_le32(hcon->passkey_notify, r);
1378
1379         if (smp->method == REQ_OOB)
1380                 memcpy(r, smp->rr, 16);
1381
1382         smp_f6(smp->tfm_cmac, smp->mackey, smp->prnd, smp->rrnd, r, io_cap,
1383                local_addr, remote_addr, check.e);
1384
1385         smp_send_cmd(smp->conn, SMP_CMD_DHKEY_CHECK, sizeof(check), &check);
1386 }
1387
1388 static u8 sc_passkey_send_confirm(struct smp_chan *smp)
1389 {
1390         struct l2cap_conn *conn = smp->conn;
1391         struct hci_conn *hcon = conn->hcon;
1392         struct smp_cmd_pairing_confirm cfm;
1393         u8 r;
1394
1395         r = ((hcon->passkey_notify >> smp->passkey_round) & 0x01);
1396         r |= 0x80;
1397
1398         get_random_bytes(smp->prnd, sizeof(smp->prnd));
1399
1400         if (smp_f4(smp->tfm_cmac, smp->local_pk, smp->remote_pk, smp->prnd, r,
1401                    cfm.confirm_val))
1402                 return SMP_UNSPECIFIED;
1403
1404         smp_send_cmd(conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cfm), &cfm);
1405
1406         return 0;
1407 }
1408
1409 static u8 sc_passkey_round(struct smp_chan *smp, u8 smp_op)
1410 {
1411         struct l2cap_conn *conn = smp->conn;
1412         struct hci_conn *hcon = conn->hcon;
1413         struct hci_dev *hdev = hcon->hdev;
1414         u8 cfm[16], r;
1415
1416         /* Ignore the PDU if we've already done 20 rounds (0 - 19) */
1417         if (smp->passkey_round >= 20)
1418                 return 0;
1419
1420         switch (smp_op) {
1421         case SMP_CMD_PAIRING_RANDOM:
1422                 r = ((hcon->passkey_notify >> smp->passkey_round) & 0x01);
1423                 r |= 0x80;
1424
1425                 if (smp_f4(smp->tfm_cmac, smp->remote_pk, smp->local_pk,
1426                            smp->rrnd, r, cfm))
1427                         return SMP_UNSPECIFIED;
1428
1429                 if (memcmp(smp->pcnf, cfm, 16))
1430                         return SMP_CONFIRM_FAILED;
1431
1432                 smp->passkey_round++;
1433
1434                 if (smp->passkey_round == 20) {
1435                         /* Generate MacKey and LTK */
1436                         if (sc_mackey_and_ltk(smp, smp->mackey, smp->tk))
1437                                 return SMP_UNSPECIFIED;
1438                 }
1439
1440                 /* The round is only complete when the initiator
1441                  * receives pairing random.
1442                  */
1443                 if (!hcon->out) {
1444                         smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
1445                                      sizeof(smp->prnd), smp->prnd);
1446                         if (smp->passkey_round == 20)
1447                                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1448                         else
1449                                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
1450                         return 0;
1451                 }
1452
1453                 /* Start the next round */
1454                 if (smp->passkey_round != 20)
1455                         return sc_passkey_round(smp, 0);
1456
1457                 /* Passkey rounds are complete - start DHKey Check */
1458                 sc_dhkey_check(smp);
1459                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1460
1461                 break;
1462
1463         case SMP_CMD_PAIRING_CONFIRM:
1464                 if (test_bit(SMP_FLAG_WAIT_USER, &smp->flags)) {
1465                         set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1466                         return 0;
1467                 }
1468
1469                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
1470
1471                 if (hcon->out) {
1472                         smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
1473                                      sizeof(smp->prnd), smp->prnd);
1474                         return 0;
1475                 }
1476
1477                 return sc_passkey_send_confirm(smp);
1478
1479         case SMP_CMD_PUBLIC_KEY:
1480         default:
1481                 /* Initiating device starts the round */
1482                 if (!hcon->out)
1483                         return 0;
1484
1485                 BT_DBG("%s Starting passkey round %u", hdev->name,
1486                        smp->passkey_round + 1);
1487
1488                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
1489
1490                 return sc_passkey_send_confirm(smp);
1491         }
1492
1493         return 0;
1494 }
1495
1496 static int sc_user_reply(struct smp_chan *smp, u16 mgmt_op, __le32 passkey)
1497 {
1498         struct l2cap_conn *conn = smp->conn;
1499         struct hci_conn *hcon = conn->hcon;
1500         u8 smp_op;
1501
1502         clear_bit(SMP_FLAG_WAIT_USER, &smp->flags);
1503
1504         switch (mgmt_op) {
1505         case MGMT_OP_USER_PASSKEY_NEG_REPLY:
1506                 smp_failure(smp->conn, SMP_PASSKEY_ENTRY_FAILED);
1507                 return 0;
1508         case MGMT_OP_USER_CONFIRM_NEG_REPLY:
1509                 smp_failure(smp->conn, SMP_NUMERIC_COMP_FAILED);
1510                 return 0;
1511         case MGMT_OP_USER_PASSKEY_REPLY:
1512                 hcon->passkey_notify = le32_to_cpu(passkey);
1513                 smp->passkey_round = 0;
1514
1515                 if (test_and_clear_bit(SMP_FLAG_CFM_PENDING, &smp->flags))
1516                         smp_op = SMP_CMD_PAIRING_CONFIRM;
1517                 else
1518                         smp_op = 0;
1519
1520                 if (sc_passkey_round(smp, smp_op))
1521                         return -EIO;
1522
1523                 return 0;
1524         }
1525
1526         /* Initiator sends DHKey check first */
1527         if (hcon->out) {
1528                 sc_dhkey_check(smp);
1529                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1530         } else if (test_and_clear_bit(SMP_FLAG_DHKEY_PENDING, &smp->flags)) {
1531                 sc_dhkey_check(smp);
1532                 sc_add_ltk(smp);
1533         }
1534
1535         return 0;
1536 }
1537
1538 int smp_user_confirm_reply(struct hci_conn *hcon, u16 mgmt_op, __le32 passkey)
1539 {
1540         struct l2cap_conn *conn = hcon->l2cap_data;
1541         struct l2cap_chan *chan;
1542         struct smp_chan *smp;
1543         u32 value;
1544         int err;
1545
1546         BT_DBG("");
1547
1548         if (!conn)
1549                 return -ENOTCONN;
1550
1551         chan = conn->smp;
1552         if (!chan)
1553                 return -ENOTCONN;
1554
1555         l2cap_chan_lock(chan);
1556         if (!chan->data) {
1557                 err = -ENOTCONN;
1558                 goto unlock;
1559         }
1560
1561         smp = chan->data;
1562
1563         if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1564                 err = sc_user_reply(smp, mgmt_op, passkey);
1565                 goto unlock;
1566         }
1567
1568         switch (mgmt_op) {
1569         case MGMT_OP_USER_PASSKEY_REPLY:
1570                 value = le32_to_cpu(passkey);
1571                 memset(smp->tk, 0, sizeof(smp->tk));
1572                 BT_DBG("PassKey: %d", value);
1573                 put_unaligned_le32(value, smp->tk);
1574                 /* Fall Through */
1575         case MGMT_OP_USER_CONFIRM_REPLY:
1576                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
1577                 break;
1578         case MGMT_OP_USER_PASSKEY_NEG_REPLY:
1579         case MGMT_OP_USER_CONFIRM_NEG_REPLY:
1580                 smp_failure(conn, SMP_PASSKEY_ENTRY_FAILED);
1581                 err = 0;
1582                 goto unlock;
1583         default:
1584                 smp_failure(conn, SMP_PASSKEY_ENTRY_FAILED);
1585                 err = -EOPNOTSUPP;
1586                 goto unlock;
1587         }
1588
1589         err = 0;
1590
1591         /* If it is our turn to send Pairing Confirm, do so now */
1592         if (test_bit(SMP_FLAG_CFM_PENDING, &smp->flags)) {
1593                 u8 rsp = smp_confirm(smp);
1594                 if (rsp)
1595                         smp_failure(conn, rsp);
1596         }
1597
1598 unlock:
1599         l2cap_chan_unlock(chan);
1600         return err;
1601 }
1602
1603 static void build_bredr_pairing_cmd(struct smp_chan *smp,
1604                                     struct smp_cmd_pairing *req,
1605                                     struct smp_cmd_pairing *rsp)
1606 {
1607         struct l2cap_conn *conn = smp->conn;
1608         struct hci_dev *hdev = conn->hcon->hdev;
1609         u8 local_dist = 0, remote_dist = 0;
1610
1611         if (hci_dev_test_flag(hdev, HCI_BONDABLE)) {
1612                 local_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
1613                 remote_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
1614         }
1615
1616         if (hci_dev_test_flag(hdev, HCI_RPA_RESOLVING))
1617                 remote_dist |= SMP_DIST_ID_KEY;
1618
1619         if (hci_dev_test_flag(hdev, HCI_PRIVACY))
1620                 local_dist |= SMP_DIST_ID_KEY;
1621
1622         if (!rsp) {
1623                 memset(req, 0, sizeof(*req));
1624
1625                 req->init_key_dist   = local_dist;
1626                 req->resp_key_dist   = remote_dist;
1627                 req->max_key_size    = SMP_MAX_ENC_KEY_SIZE;
1628
1629                 smp->remote_key_dist = remote_dist;
1630
1631                 return;
1632         }
1633
1634         memset(rsp, 0, sizeof(*rsp));
1635
1636         rsp->max_key_size    = SMP_MAX_ENC_KEY_SIZE;
1637         rsp->init_key_dist   = req->init_key_dist & remote_dist;
1638         rsp->resp_key_dist   = req->resp_key_dist & local_dist;
1639
1640         smp->remote_key_dist = rsp->init_key_dist;
1641 }
1642
1643 static u8 smp_cmd_pairing_req(struct l2cap_conn *conn, struct sk_buff *skb)
1644 {
1645         struct smp_cmd_pairing rsp, *req = (void *) skb->data;
1646         struct l2cap_chan *chan = conn->smp;
1647         struct hci_dev *hdev = conn->hcon->hdev;
1648         struct smp_chan *smp;
1649         u8 key_size, auth, sec_level;
1650         int ret;
1651
1652         BT_DBG("conn %p", conn);
1653
1654         if (skb->len < sizeof(*req))
1655                 return SMP_INVALID_PARAMS;
1656
1657         if (conn->hcon->role != HCI_ROLE_SLAVE)
1658                 return SMP_CMD_NOTSUPP;
1659
1660         if (!chan->data)
1661                 smp = smp_chan_create(conn);
1662         else
1663                 smp = chan->data;
1664
1665         if (!smp)
1666                 return SMP_UNSPECIFIED;
1667
1668         /* We didn't start the pairing, so match remote */
1669         auth = req->auth_req & AUTH_REQ_MASK(hdev);
1670
1671         if (!hci_dev_test_flag(hdev, HCI_BONDABLE) &&
1672             (auth & SMP_AUTH_BONDING))
1673                 return SMP_PAIRING_NOTSUPP;
1674
1675         if (hci_dev_test_flag(hdev, HCI_SC_ONLY) && !(auth & SMP_AUTH_SC))
1676                 return SMP_AUTH_REQUIREMENTS;
1677
1678         smp->preq[0] = SMP_CMD_PAIRING_REQ;
1679         memcpy(&smp->preq[1], req, sizeof(*req));
1680         skb_pull(skb, sizeof(*req));
1681
1682         /* SMP over BR/EDR requires special treatment */
1683         if (conn->hcon->type == ACL_LINK) {
1684                 /* We must have a BR/EDR SC link */
1685                 if (!test_bit(HCI_CONN_AES_CCM, &conn->hcon->flags) &&
1686                     !hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP))
1687                         return SMP_CROSS_TRANSP_NOT_ALLOWED;
1688
1689                 set_bit(SMP_FLAG_SC, &smp->flags);
1690
1691                 build_bredr_pairing_cmd(smp, req, &rsp);
1692
1693                 key_size = min(req->max_key_size, rsp.max_key_size);
1694                 if (check_enc_key_size(conn, key_size))
1695                         return SMP_ENC_KEY_SIZE;
1696
1697                 /* Clear bits which are generated but not distributed */
1698                 smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1699
1700                 smp->prsp[0] = SMP_CMD_PAIRING_RSP;
1701                 memcpy(&smp->prsp[1], &rsp, sizeof(rsp));
1702                 smp_send_cmd(conn, SMP_CMD_PAIRING_RSP, sizeof(rsp), &rsp);
1703
1704                 smp_distribute_keys(smp);
1705                 return 0;
1706         }
1707
1708         build_pairing_cmd(conn, req, &rsp, auth);
1709
1710         if (rsp.auth_req & SMP_AUTH_SC)
1711                 set_bit(SMP_FLAG_SC, &smp->flags);
1712
1713         if (conn->hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
1714                 sec_level = BT_SECURITY_MEDIUM;
1715         else
1716                 sec_level = authreq_to_seclevel(auth);
1717
1718         if (sec_level > conn->hcon->pending_sec_level)
1719                 conn->hcon->pending_sec_level = sec_level;
1720
1721         /* If we need MITM check that it can be achieved */
1722         if (conn->hcon->pending_sec_level >= BT_SECURITY_HIGH) {
1723                 u8 method;
1724
1725                 method = get_auth_method(smp, conn->hcon->io_capability,
1726                                          req->io_capability);
1727                 if (method == JUST_WORKS || method == JUST_CFM)
1728                         return SMP_AUTH_REQUIREMENTS;
1729         }
1730
1731         key_size = min(req->max_key_size, rsp.max_key_size);
1732         if (check_enc_key_size(conn, key_size))
1733                 return SMP_ENC_KEY_SIZE;
1734
1735         get_random_bytes(smp->prnd, sizeof(smp->prnd));
1736
1737         smp->prsp[0] = SMP_CMD_PAIRING_RSP;
1738         memcpy(&smp->prsp[1], &rsp, sizeof(rsp));
1739
1740         smp_send_cmd(conn, SMP_CMD_PAIRING_RSP, sizeof(rsp), &rsp);
1741
1742         clear_bit(SMP_FLAG_INITIATOR, &smp->flags);
1743
1744         if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1745                 SMP_ALLOW_CMD(smp, SMP_CMD_PUBLIC_KEY);
1746                 /* Clear bits which are generated but not distributed */
1747                 smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1748                 /* Wait for Public Key from Initiating Device */
1749                 return 0;
1750         }
1751
1752         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
1753
1754         /* Request setup of TK */
1755         ret = tk_request(conn, 0, auth, rsp.io_capability, req->io_capability);
1756         if (ret)
1757                 return SMP_UNSPECIFIED;
1758
1759         return 0;
1760 }
1761
1762 static u8 sc_send_public_key(struct smp_chan *smp)
1763 {
1764         struct hci_dev *hdev = smp->conn->hcon->hdev;
1765
1766         BT_DBG("");
1767
1768         if (hci_dev_test_flag(hdev, HCI_USE_DEBUG_KEYS)) {
1769                 BT_DBG("Using debug keys");
1770                 memcpy(smp->local_pk, debug_pk, 64);
1771                 memcpy(smp->local_sk, debug_sk, 32);
1772                 set_bit(SMP_FLAG_DEBUG_KEY, &smp->flags);
1773         } else {
1774                 while (true) {
1775                         /* Generate local key pair for Secure Connections */
1776                         if (!ecc_make_key(smp->local_pk, smp->local_sk))
1777                                 return SMP_UNSPECIFIED;
1778
1779                         /* This is unlikely, but we need to check that
1780                          * we didn't accidentially generate a debug key.
1781                          */
1782                         if (memcmp(smp->local_sk, debug_sk, 32))
1783                                 break;
1784                 }
1785         }
1786
1787         SMP_DBG("Local Public Key X: %32phN", smp->local_pk);
1788         SMP_DBG("Local Public Key Y: %32phN", &smp->local_pk[32]);
1789         SMP_DBG("Local Private Key:  %32phN", smp->local_sk);
1790
1791         smp_send_cmd(smp->conn, SMP_CMD_PUBLIC_KEY, 64, smp->local_pk);
1792
1793         return 0;
1794 }
1795
1796 static u8 smp_cmd_pairing_rsp(struct l2cap_conn *conn, struct sk_buff *skb)
1797 {
1798         struct smp_cmd_pairing *req, *rsp = (void *) skb->data;
1799         struct l2cap_chan *chan = conn->smp;
1800         struct smp_chan *smp = chan->data;
1801         struct hci_dev *hdev = conn->hcon->hdev;
1802         u8 key_size, auth;
1803         int ret;
1804
1805         BT_DBG("conn %p", conn);
1806
1807         if (skb->len < sizeof(*rsp))
1808                 return SMP_INVALID_PARAMS;
1809
1810         if (conn->hcon->role != HCI_ROLE_MASTER)
1811                 return SMP_CMD_NOTSUPP;
1812
1813         skb_pull(skb, sizeof(*rsp));
1814
1815         req = (void *) &smp->preq[1];
1816
1817         key_size = min(req->max_key_size, rsp->max_key_size);
1818         if (check_enc_key_size(conn, key_size))
1819                 return SMP_ENC_KEY_SIZE;
1820
1821         auth = rsp->auth_req & AUTH_REQ_MASK(hdev);
1822
1823         if (hci_dev_test_flag(hdev, HCI_SC_ONLY) && !(auth & SMP_AUTH_SC))
1824                 return SMP_AUTH_REQUIREMENTS;
1825
1826         smp->prsp[0] = SMP_CMD_PAIRING_RSP;
1827         memcpy(&smp->prsp[1], rsp, sizeof(*rsp));
1828
1829         /* Update remote key distribution in case the remote cleared
1830          * some bits that we had enabled in our request.
1831          */
1832         smp->remote_key_dist &= rsp->resp_key_dist;
1833
1834         /* For BR/EDR this means we're done and can start phase 3 */
1835         if (conn->hcon->type == ACL_LINK) {
1836                 /* Clear bits which are generated but not distributed */
1837                 smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1838                 smp_distribute_keys(smp);
1839                 return 0;
1840         }
1841
1842         if ((req->auth_req & SMP_AUTH_SC) && (auth & SMP_AUTH_SC))
1843                 set_bit(SMP_FLAG_SC, &smp->flags);
1844         else if (conn->hcon->pending_sec_level > BT_SECURITY_HIGH)
1845                 conn->hcon->pending_sec_level = BT_SECURITY_HIGH;
1846
1847         /* If we need MITM check that it can be achieved */
1848         if (conn->hcon->pending_sec_level >= BT_SECURITY_HIGH) {
1849                 u8 method;
1850
1851                 method = get_auth_method(smp, req->io_capability,
1852                                          rsp->io_capability);
1853                 if (method == JUST_WORKS || method == JUST_CFM)
1854                         return SMP_AUTH_REQUIREMENTS;
1855         }
1856
1857         get_random_bytes(smp->prnd, sizeof(smp->prnd));
1858
1859         /* Update remote key distribution in case the remote cleared
1860          * some bits that we had enabled in our request.
1861          */
1862         smp->remote_key_dist &= rsp->resp_key_dist;
1863
1864         if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1865                 /* Clear bits which are generated but not distributed */
1866                 smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1867                 SMP_ALLOW_CMD(smp, SMP_CMD_PUBLIC_KEY);
1868                 return sc_send_public_key(smp);
1869         }
1870
1871         auth |= req->auth_req;
1872
1873         ret = tk_request(conn, 0, auth, req->io_capability, rsp->io_capability);
1874         if (ret)
1875                 return SMP_UNSPECIFIED;
1876
1877         set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1878
1879         /* Can't compose response until we have been confirmed */
1880         if (test_bit(SMP_FLAG_TK_VALID, &smp->flags))
1881                 return smp_confirm(smp);
1882
1883         return 0;
1884 }
1885
1886 static u8 sc_check_confirm(struct smp_chan *smp)
1887 {
1888         struct l2cap_conn *conn = smp->conn;
1889
1890         BT_DBG("");
1891
1892         /* Public Key exchange must happen before any other steps */
1893         if (!test_bit(SMP_FLAG_REMOTE_PK, &smp->flags))
1894                 return SMP_UNSPECIFIED;
1895
1896         if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
1897                 return sc_passkey_round(smp, SMP_CMD_PAIRING_CONFIRM);
1898
1899         if (conn->hcon->out) {
1900                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
1901                              smp->prnd);
1902                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
1903         }
1904
1905         return 0;
1906 }
1907
1908 static u8 smp_cmd_pairing_confirm(struct l2cap_conn *conn, struct sk_buff *skb)
1909 {
1910         struct l2cap_chan *chan = conn->smp;
1911         struct smp_chan *smp = chan->data;
1912
1913         BT_DBG("conn %p %s", conn, conn->hcon->out ? "master" : "slave");
1914
1915         if (skb->len < sizeof(smp->pcnf))
1916                 return SMP_INVALID_PARAMS;
1917
1918         memcpy(smp->pcnf, skb->data, sizeof(smp->pcnf));
1919         skb_pull(skb, sizeof(smp->pcnf));
1920
1921         if (test_bit(SMP_FLAG_SC, &smp->flags))
1922                 return sc_check_confirm(smp);
1923
1924         if (conn->hcon->out) {
1925                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
1926                              smp->prnd);
1927                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
1928                 return 0;
1929         }
1930
1931         if (test_bit(SMP_FLAG_TK_VALID, &smp->flags))
1932                 return smp_confirm(smp);
1933
1934         set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1935
1936         return 0;
1937 }
1938
1939 static u8 smp_cmd_pairing_random(struct l2cap_conn *conn, struct sk_buff *skb)
1940 {
1941         struct l2cap_chan *chan = conn->smp;
1942         struct smp_chan *smp = chan->data;
1943         struct hci_conn *hcon = conn->hcon;
1944         u8 *pkax, *pkbx, *na, *nb;
1945         u32 passkey;
1946         int err;
1947
1948         BT_DBG("conn %p", conn);
1949
1950         if (skb->len < sizeof(smp->rrnd))
1951                 return SMP_INVALID_PARAMS;
1952
1953         memcpy(smp->rrnd, skb->data, sizeof(smp->rrnd));
1954         skb_pull(skb, sizeof(smp->rrnd));
1955
1956         if (!test_bit(SMP_FLAG_SC, &smp->flags))
1957                 return smp_random(smp);
1958
1959         if (hcon->out) {
1960                 pkax = smp->local_pk;
1961                 pkbx = smp->remote_pk;
1962                 na   = smp->prnd;
1963                 nb   = smp->rrnd;
1964         } else {
1965                 pkax = smp->remote_pk;
1966                 pkbx = smp->local_pk;
1967                 na   = smp->rrnd;
1968                 nb   = smp->prnd;
1969         }
1970
1971         if (smp->method == REQ_OOB) {
1972                 if (!hcon->out)
1973                         smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
1974                                      sizeof(smp->prnd), smp->prnd);
1975                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1976                 goto mackey_and_ltk;
1977         }
1978
1979         /* Passkey entry has special treatment */
1980         if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
1981                 return sc_passkey_round(smp, SMP_CMD_PAIRING_RANDOM);
1982
1983         if (hcon->out) {
1984                 u8 cfm[16];
1985
1986                 err = smp_f4(smp->tfm_cmac, smp->remote_pk, smp->local_pk,
1987                              smp->rrnd, 0, cfm);
1988                 if (err)
1989                         return SMP_UNSPECIFIED;
1990
1991                 if (memcmp(smp->pcnf, cfm, 16))
1992                         return SMP_CONFIRM_FAILED;
1993         } else {
1994                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
1995                              smp->prnd);
1996                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1997         }
1998
1999 mackey_and_ltk:
2000         /* Generate MacKey and LTK */
2001         err = sc_mackey_and_ltk(smp, smp->mackey, smp->tk);
2002         if (err)
2003                 return SMP_UNSPECIFIED;
2004
2005         if (smp->method == JUST_WORKS || smp->method == REQ_OOB) {
2006                 if (hcon->out) {
2007                         sc_dhkey_check(smp);
2008                         SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
2009                 }
2010                 return 0;
2011         }
2012
2013         err = smp_g2(smp->tfm_cmac, pkax, pkbx, na, nb, &passkey);
2014         if (err)
2015                 return SMP_UNSPECIFIED;
2016
2017         err = mgmt_user_confirm_request(hcon->hdev, &hcon->dst, hcon->type,
2018                                         hcon->dst_type, passkey, 0);
2019         if (err)
2020                 return SMP_UNSPECIFIED;
2021
2022         set_bit(SMP_FLAG_WAIT_USER, &smp->flags);
2023
2024         return 0;
2025 }
2026
2027 static bool smp_ltk_encrypt(struct l2cap_conn *conn, u8 sec_level)
2028 {
2029         struct smp_ltk *key;
2030         struct hci_conn *hcon = conn->hcon;
2031
2032         key = hci_find_ltk(hcon->hdev, &hcon->dst, hcon->dst_type, hcon->role);
2033         if (!key)
2034                 return false;
2035
2036         if (smp_ltk_sec_level(key) < sec_level)
2037                 return false;
2038
2039         if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags))
2040                 return true;
2041
2042         hci_le_start_enc(hcon, key->ediv, key->rand, key->val);
2043         hcon->enc_key_size = key->enc_size;
2044
2045         /* We never store STKs for master role, so clear this flag */
2046         clear_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags);
2047
2048         return true;
2049 }
2050
2051 bool smp_sufficient_security(struct hci_conn *hcon, u8 sec_level,
2052                              enum smp_key_pref key_pref)
2053 {
2054         if (sec_level == BT_SECURITY_LOW)
2055                 return true;
2056
2057         /* If we're encrypted with an STK but the caller prefers using
2058          * LTK claim insufficient security. This way we allow the
2059          * connection to be re-encrypted with an LTK, even if the LTK
2060          * provides the same level of security. Only exception is if we
2061          * don't have an LTK (e.g. because of key distribution bits).
2062          */
2063         if (key_pref == SMP_USE_LTK &&
2064             test_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags) &&
2065             hci_find_ltk(hcon->hdev, &hcon->dst, hcon->dst_type, hcon->role))
2066                 return false;
2067
2068         if (hcon->sec_level >= sec_level)
2069                 return true;
2070
2071         return false;
2072 }
2073
2074 static u8 smp_cmd_security_req(struct l2cap_conn *conn, struct sk_buff *skb)
2075 {
2076         struct smp_cmd_security_req *rp = (void *) skb->data;
2077         struct smp_cmd_pairing cp;
2078         struct hci_conn *hcon = conn->hcon;
2079         struct hci_dev *hdev = hcon->hdev;
2080         struct smp_chan *smp;
2081         u8 sec_level, auth;
2082
2083         BT_DBG("conn %p", conn);
2084
2085         if (skb->len < sizeof(*rp))
2086                 return SMP_INVALID_PARAMS;
2087
2088         if (hcon->role != HCI_ROLE_MASTER)
2089                 return SMP_CMD_NOTSUPP;
2090
2091         auth = rp->auth_req & AUTH_REQ_MASK(hdev);
2092
2093         if (hci_dev_test_flag(hdev, HCI_SC_ONLY) && !(auth & SMP_AUTH_SC))
2094                 return SMP_AUTH_REQUIREMENTS;
2095
2096         if (hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
2097                 sec_level = BT_SECURITY_MEDIUM;
2098         else
2099                 sec_level = authreq_to_seclevel(auth);
2100
2101         if (smp_sufficient_security(hcon, sec_level, SMP_USE_LTK))
2102                 return 0;
2103
2104         if (sec_level > hcon->pending_sec_level)
2105                 hcon->pending_sec_level = sec_level;
2106
2107         if (smp_ltk_encrypt(conn, hcon->pending_sec_level))
2108                 return 0;
2109
2110         smp = smp_chan_create(conn);
2111         if (!smp)
2112                 return SMP_UNSPECIFIED;
2113
2114         if (!hci_dev_test_flag(hdev, HCI_BONDABLE) &&
2115             (auth & SMP_AUTH_BONDING))
2116                 return SMP_PAIRING_NOTSUPP;
2117
2118         skb_pull(skb, sizeof(*rp));
2119
2120         memset(&cp, 0, sizeof(cp));
2121         build_pairing_cmd(conn, &cp, NULL, auth);
2122
2123         smp->preq[0] = SMP_CMD_PAIRING_REQ;
2124         memcpy(&smp->preq[1], &cp, sizeof(cp));
2125
2126         smp_send_cmd(conn, SMP_CMD_PAIRING_REQ, sizeof(cp), &cp);
2127         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RSP);
2128
2129         return 0;
2130 }
2131
2132 int smp_conn_security(struct hci_conn *hcon, __u8 sec_level)
2133 {
2134         struct l2cap_conn *conn = hcon->l2cap_data;
2135         struct l2cap_chan *chan;
2136         struct smp_chan *smp;
2137         __u8 authreq;
2138         int ret;
2139
2140         BT_DBG("conn %p hcon %p level 0x%2.2x", conn, hcon, sec_level);
2141
2142         /* This may be NULL if there's an unexpected disconnection */
2143         if (!conn)
2144                 return 1;
2145
2146         chan = conn->smp;
2147
2148         if (!hci_dev_test_flag(hcon->hdev, HCI_LE_ENABLED))
2149                 return 1;
2150
2151         if (smp_sufficient_security(hcon, sec_level, SMP_USE_LTK))
2152                 return 1;
2153
2154         if (sec_level > hcon->pending_sec_level)
2155                 hcon->pending_sec_level = sec_level;
2156
2157         if (hcon->role == HCI_ROLE_MASTER)
2158                 if (smp_ltk_encrypt(conn, hcon->pending_sec_level))
2159                         return 0;
2160
2161         l2cap_chan_lock(chan);
2162
2163         /* If SMP is already in progress ignore this request */
2164         if (chan->data) {
2165                 ret = 0;
2166                 goto unlock;
2167         }
2168
2169         smp = smp_chan_create(conn);
2170         if (!smp) {
2171                 ret = 1;
2172                 goto unlock;
2173         }
2174
2175         authreq = seclevel_to_authreq(sec_level);
2176
2177         if (hci_dev_test_flag(hcon->hdev, HCI_SC_ENABLED))
2178                 authreq |= SMP_AUTH_SC;
2179
2180         /* Require MITM if IO Capability allows or the security level
2181          * requires it.
2182          */
2183         if (hcon->io_capability != HCI_IO_NO_INPUT_OUTPUT ||
2184             hcon->pending_sec_level > BT_SECURITY_MEDIUM)
2185                 authreq |= SMP_AUTH_MITM;
2186
2187         if (hcon->role == HCI_ROLE_MASTER) {
2188                 struct smp_cmd_pairing cp;
2189
2190                 build_pairing_cmd(conn, &cp, NULL, authreq);
2191                 smp->preq[0] = SMP_CMD_PAIRING_REQ;
2192                 memcpy(&smp->preq[1], &cp, sizeof(cp));
2193
2194                 smp_send_cmd(conn, SMP_CMD_PAIRING_REQ, sizeof(cp), &cp);
2195                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RSP);
2196         } else {
2197                 struct smp_cmd_security_req cp;
2198                 cp.auth_req = authreq;
2199                 smp_send_cmd(conn, SMP_CMD_SECURITY_REQ, sizeof(cp), &cp);
2200                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_REQ);
2201         }
2202
2203         set_bit(SMP_FLAG_INITIATOR, &smp->flags);
2204         ret = 0;
2205
2206 unlock:
2207         l2cap_chan_unlock(chan);
2208         return ret;
2209 }
2210
2211 static int smp_cmd_encrypt_info(struct l2cap_conn *conn, struct sk_buff *skb)
2212 {
2213         struct smp_cmd_encrypt_info *rp = (void *) skb->data;
2214         struct l2cap_chan *chan = conn->smp;
2215         struct smp_chan *smp = chan->data;
2216
2217         BT_DBG("conn %p", conn);
2218
2219         if (skb->len < sizeof(*rp))
2220                 return SMP_INVALID_PARAMS;
2221
2222         SMP_ALLOW_CMD(smp, SMP_CMD_MASTER_IDENT);
2223
2224         skb_pull(skb, sizeof(*rp));
2225
2226         memcpy(smp->tk, rp->ltk, sizeof(smp->tk));
2227
2228         return 0;
2229 }
2230
2231 static int smp_cmd_master_ident(struct l2cap_conn *conn, struct sk_buff *skb)
2232 {
2233         struct smp_cmd_master_ident *rp = (void *) skb->data;
2234         struct l2cap_chan *chan = conn->smp;
2235         struct smp_chan *smp = chan->data;
2236         struct hci_dev *hdev = conn->hcon->hdev;
2237         struct hci_conn *hcon = conn->hcon;
2238         struct smp_ltk *ltk;
2239         u8 authenticated;
2240
2241         BT_DBG("conn %p", conn);
2242
2243         if (skb->len < sizeof(*rp))
2244                 return SMP_INVALID_PARAMS;
2245
2246         /* Mark the information as received */
2247         smp->remote_key_dist &= ~SMP_DIST_ENC_KEY;
2248
2249         if (smp->remote_key_dist & SMP_DIST_ID_KEY)
2250                 SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_INFO);
2251         else if (smp->remote_key_dist & SMP_DIST_SIGN)
2252                 SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
2253
2254         skb_pull(skb, sizeof(*rp));
2255
2256         authenticated = (hcon->sec_level == BT_SECURITY_HIGH);
2257         ltk = hci_add_ltk(hdev, &hcon->dst, hcon->dst_type, SMP_LTK,
2258                           authenticated, smp->tk, smp->enc_key_size,
2259                           rp->ediv, rp->rand);
2260         smp->ltk = ltk;
2261         if (!(smp->remote_key_dist & KEY_DIST_MASK))
2262                 smp_distribute_keys(smp);
2263
2264         return 0;
2265 }
2266
2267 static int smp_cmd_ident_info(struct l2cap_conn *conn, struct sk_buff *skb)
2268 {
2269         struct smp_cmd_ident_info *info = (void *) skb->data;
2270         struct l2cap_chan *chan = conn->smp;
2271         struct smp_chan *smp = chan->data;
2272
2273         BT_DBG("");
2274
2275         if (skb->len < sizeof(*info))
2276                 return SMP_INVALID_PARAMS;
2277
2278         SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_ADDR_INFO);
2279
2280         skb_pull(skb, sizeof(*info));
2281
2282         memcpy(smp->irk, info->irk, 16);
2283
2284         return 0;
2285 }
2286
2287 static int smp_cmd_ident_addr_info(struct l2cap_conn *conn,
2288                                    struct sk_buff *skb)
2289 {
2290         struct smp_cmd_ident_addr_info *info = (void *) skb->data;
2291         struct l2cap_chan *chan = conn->smp;
2292         struct smp_chan *smp = chan->data;
2293         struct hci_conn *hcon = conn->hcon;
2294         bdaddr_t rpa;
2295
2296         BT_DBG("");
2297
2298         if (skb->len < sizeof(*info))
2299                 return SMP_INVALID_PARAMS;
2300
2301         /* Mark the information as received */
2302         smp->remote_key_dist &= ~SMP_DIST_ID_KEY;
2303
2304         if (smp->remote_key_dist & SMP_DIST_SIGN)
2305                 SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
2306
2307         skb_pull(skb, sizeof(*info));
2308
2309         /* Strictly speaking the Core Specification (4.1) allows sending
2310          * an empty address which would force us to rely on just the IRK
2311          * as "identity information". However, since such
2312          * implementations are not known of and in order to not over
2313          * complicate our implementation, simply pretend that we never
2314          * received an IRK for such a device.
2315          *
2316          * The Identity Address must also be a Static Random or Public
2317          * Address, which hci_is_identity_address() checks for.
2318          */
2319         if (!bacmp(&info->bdaddr, BDADDR_ANY) ||
2320             !hci_is_identity_address(&info->bdaddr, info->addr_type)) {
2321                 BT_ERR("Ignoring IRK with no identity address");
2322                 goto distribute;
2323         }
2324
2325         bacpy(&smp->id_addr, &info->bdaddr);
2326         smp->id_addr_type = info->addr_type;
2327
2328         if (hci_bdaddr_is_rpa(&hcon->dst, hcon->dst_type))
2329                 bacpy(&rpa, &hcon->dst);
2330         else
2331                 bacpy(&rpa, BDADDR_ANY);
2332
2333         smp->remote_irk = hci_add_irk(conn->hcon->hdev, &smp->id_addr,
2334                                       smp->id_addr_type, smp->irk, &rpa);
2335
2336 distribute:
2337         if (!(smp->remote_key_dist & KEY_DIST_MASK))
2338                 smp_distribute_keys(smp);
2339
2340         return 0;
2341 }
2342
2343 static int smp_cmd_sign_info(struct l2cap_conn *conn, struct sk_buff *skb)
2344 {
2345         struct smp_cmd_sign_info *rp = (void *) skb->data;
2346         struct l2cap_chan *chan = conn->smp;
2347         struct smp_chan *smp = chan->data;
2348         struct smp_csrk *csrk;
2349
2350         BT_DBG("conn %p", conn);
2351
2352         if (skb->len < sizeof(*rp))
2353                 return SMP_INVALID_PARAMS;
2354
2355         /* Mark the information as received */
2356         smp->remote_key_dist &= ~SMP_DIST_SIGN;
2357
2358         skb_pull(skb, sizeof(*rp));
2359
2360         csrk = kzalloc(sizeof(*csrk), GFP_KERNEL);
2361         if (csrk) {
2362                 if (conn->hcon->sec_level > BT_SECURITY_MEDIUM)
2363                         csrk->type = MGMT_CSRK_REMOTE_AUTHENTICATED;
2364                 else
2365                         csrk->type = MGMT_CSRK_REMOTE_UNAUTHENTICATED;
2366                 memcpy(csrk->val, rp->csrk, sizeof(csrk->val));
2367         }
2368         smp->csrk = csrk;
2369         smp_distribute_keys(smp);
2370
2371         return 0;
2372 }
2373
2374 static u8 sc_select_method(struct smp_chan *smp)
2375 {
2376         struct l2cap_conn *conn = smp->conn;
2377         struct hci_conn *hcon = conn->hcon;
2378         struct smp_cmd_pairing *local, *remote;
2379         u8 local_mitm, remote_mitm, local_io, remote_io, method;
2380
2381         if (test_bit(SMP_FLAG_OOB, &smp->flags))
2382                 return REQ_OOB;
2383
2384         /* The preq/prsp contain the raw Pairing Request/Response PDUs
2385          * which are needed as inputs to some crypto functions. To get
2386          * the "struct smp_cmd_pairing" from them we need to skip the
2387          * first byte which contains the opcode.
2388          */
2389         if (hcon->out) {
2390                 local = (void *) &smp->preq[1];
2391                 remote = (void *) &smp->prsp[1];
2392         } else {
2393                 local = (void *) &smp->prsp[1];
2394                 remote = (void *) &smp->preq[1];
2395         }
2396
2397         local_io = local->io_capability;
2398         remote_io = remote->io_capability;
2399
2400         local_mitm = (local->auth_req & SMP_AUTH_MITM);
2401         remote_mitm = (remote->auth_req & SMP_AUTH_MITM);
2402
2403         /* If either side wants MITM, look up the method from the table,
2404          * otherwise use JUST WORKS.
2405          */
2406         if (local_mitm || remote_mitm)
2407                 method = get_auth_method(smp, local_io, remote_io);
2408         else
2409                 method = JUST_WORKS;
2410
2411         /* Don't confirm locally initiated pairing attempts */
2412         if (method == JUST_CFM && test_bit(SMP_FLAG_INITIATOR, &smp->flags))
2413                 method = JUST_WORKS;
2414
2415         return method;
2416 }
2417
2418 static int smp_cmd_public_key(struct l2cap_conn *conn, struct sk_buff *skb)
2419 {
2420         struct smp_cmd_public_key *key = (void *) skb->data;
2421         struct hci_conn *hcon = conn->hcon;
2422         struct l2cap_chan *chan = conn->smp;
2423         struct smp_chan *smp = chan->data;
2424         struct hci_dev *hdev = hcon->hdev;
2425         struct smp_cmd_pairing_confirm cfm;
2426         int err;
2427
2428         BT_DBG("conn %p", conn);
2429
2430         if (skb->len < sizeof(*key))
2431                 return SMP_INVALID_PARAMS;
2432
2433         memcpy(smp->remote_pk, key, 64);
2434
2435         /* Non-initiating device sends its public key after receiving
2436          * the key from the initiating device.
2437          */
2438         if (!hcon->out) {
2439                 err = sc_send_public_key(smp);
2440                 if (err)
2441                         return err;
2442         }
2443
2444         SMP_DBG("Remote Public Key X: %32phN", smp->remote_pk);
2445         SMP_DBG("Remote Public Key Y: %32phN", &smp->remote_pk[32]);
2446
2447         if (!ecdh_shared_secret(smp->remote_pk, smp->local_sk, smp->dhkey))
2448                 return SMP_UNSPECIFIED;
2449
2450         SMP_DBG("DHKey %32phN", smp->dhkey);
2451
2452         set_bit(SMP_FLAG_REMOTE_PK, &smp->flags);
2453
2454         smp->method = sc_select_method(smp);
2455
2456         BT_DBG("%s selected method 0x%02x", hdev->name, smp->method);
2457
2458         /* JUST_WORKS and JUST_CFM result in an unauthenticated key */
2459         if (smp->method == JUST_WORKS || smp->method == JUST_CFM)
2460                 hcon->pending_sec_level = BT_SECURITY_MEDIUM;
2461         else
2462                 hcon->pending_sec_level = BT_SECURITY_FIPS;
2463
2464         if (!memcmp(debug_pk, smp->remote_pk, 64))
2465                 set_bit(SMP_FLAG_DEBUG_KEY, &smp->flags);
2466
2467         if (smp->method == DSP_PASSKEY) {
2468                 get_random_bytes(&hcon->passkey_notify,
2469                                  sizeof(hcon->passkey_notify));
2470                 hcon->passkey_notify %= 1000000;
2471                 hcon->passkey_entered = 0;
2472                 smp->passkey_round = 0;
2473                 if (mgmt_user_passkey_notify(hdev, &hcon->dst, hcon->type,
2474                                              hcon->dst_type,
2475                                              hcon->passkey_notify,
2476                                              hcon->passkey_entered))
2477                         return SMP_UNSPECIFIED;
2478                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
2479                 return sc_passkey_round(smp, SMP_CMD_PUBLIC_KEY);
2480         }
2481
2482         if (smp->method == REQ_OOB) {
2483                 err = smp_f4(smp->tfm_cmac, smp->remote_pk, smp->remote_pk,
2484                              smp->rr, 0, cfm.confirm_val);
2485                 if (err)
2486                         return SMP_UNSPECIFIED;
2487
2488                 if (memcmp(cfm.confirm_val, smp->pcnf, 16))
2489                         return SMP_CONFIRM_FAILED;
2490
2491                 if (hcon->out)
2492                         smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
2493                                      sizeof(smp->prnd), smp->prnd);
2494
2495                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
2496
2497                 return 0;
2498         }
2499
2500         if (hcon->out)
2501                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
2502
2503         if (smp->method == REQ_PASSKEY) {
2504                 if (mgmt_user_passkey_request(hdev, &hcon->dst, hcon->type,
2505                                               hcon->dst_type))
2506                         return SMP_UNSPECIFIED;
2507                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
2508                 set_bit(SMP_FLAG_WAIT_USER, &smp->flags);
2509                 return 0;
2510         }
2511
2512         /* The Initiating device waits for the non-initiating device to
2513          * send the confirm value.
2514          */
2515         if (conn->hcon->out)
2516                 return 0;
2517
2518         err = smp_f4(smp->tfm_cmac, smp->local_pk, smp->remote_pk, smp->prnd,
2519                      0, cfm.confirm_val);
2520         if (err)
2521                 return SMP_UNSPECIFIED;
2522
2523         smp_send_cmd(conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cfm), &cfm);
2524         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
2525
2526         return 0;
2527 }
2528
2529 static int smp_cmd_dhkey_check(struct l2cap_conn *conn, struct sk_buff *skb)
2530 {
2531         struct smp_cmd_dhkey_check *check = (void *) skb->data;
2532         struct l2cap_chan *chan = conn->smp;
2533         struct hci_conn *hcon = conn->hcon;
2534         struct smp_chan *smp = chan->data;
2535         u8 a[7], b[7], *local_addr, *remote_addr;
2536         u8 io_cap[3], r[16], e[16];
2537         int err;
2538
2539         BT_DBG("conn %p", conn);
2540
2541         if (skb->len < sizeof(*check))
2542                 return SMP_INVALID_PARAMS;
2543
2544         memcpy(a, &hcon->init_addr, 6);
2545         memcpy(b, &hcon->resp_addr, 6);
2546         a[6] = hcon->init_addr_type;
2547         b[6] = hcon->resp_addr_type;
2548
2549         if (hcon->out) {
2550                 local_addr = a;
2551                 remote_addr = b;
2552                 memcpy(io_cap, &smp->prsp[1], 3);
2553         } else {
2554                 local_addr = b;
2555                 remote_addr = a;
2556                 memcpy(io_cap, &smp->preq[1], 3);
2557         }
2558
2559         memset(r, 0, sizeof(r));
2560
2561         if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
2562                 put_unaligned_le32(hcon->passkey_notify, r);
2563
2564         err = smp_f6(smp->tfm_cmac, smp->mackey, smp->rrnd, smp->prnd, r,
2565                      io_cap, remote_addr, local_addr, e);
2566         if (err)
2567                 return SMP_UNSPECIFIED;
2568
2569         if (memcmp(check->e, e, 16))
2570                 return SMP_DHKEY_CHECK_FAILED;
2571
2572         if (!hcon->out) {
2573                 if (test_bit(SMP_FLAG_WAIT_USER, &smp->flags)) {
2574                         set_bit(SMP_FLAG_DHKEY_PENDING, &smp->flags);
2575                         return 0;
2576                 }
2577
2578                 /* Slave sends DHKey check as response to master */
2579                 sc_dhkey_check(smp);
2580         }
2581
2582         sc_add_ltk(smp);
2583
2584         if (hcon->out) {
2585                 hci_le_start_enc(hcon, 0, 0, smp->tk);
2586                 hcon->enc_key_size = smp->enc_key_size;
2587         }
2588
2589         return 0;
2590 }
2591
2592 static int smp_cmd_keypress_notify(struct l2cap_conn *conn,
2593                                    struct sk_buff *skb)
2594 {
2595         struct smp_cmd_keypress_notify *kp = (void *) skb->data;
2596
2597         BT_DBG("value 0x%02x", kp->value);
2598
2599         return 0;
2600 }
2601
2602 static int smp_sig_channel(struct l2cap_chan *chan, struct sk_buff *skb)
2603 {
2604         struct l2cap_conn *conn = chan->conn;
2605         struct hci_conn *hcon = conn->hcon;
2606         struct smp_chan *smp;
2607         __u8 code, reason;
2608         int err = 0;
2609
2610         if (skb->len < 1)
2611                 return -EILSEQ;
2612
2613         if (!hci_dev_test_flag(hcon->hdev, HCI_LE_ENABLED)) {
2614                 reason = SMP_PAIRING_NOTSUPP;
2615                 goto done;
2616         }
2617
2618         code = skb->data[0];
2619         skb_pull(skb, sizeof(code));
2620
2621         smp = chan->data;
2622
2623         if (code > SMP_CMD_MAX)
2624                 goto drop;
2625
2626         if (smp && !test_and_clear_bit(code, &smp->allow_cmd))
2627                 goto drop;
2628
2629         /* If we don't have a context the only allowed commands are
2630          * pairing request and security request.
2631          */
2632         if (!smp && code != SMP_CMD_PAIRING_REQ && code != SMP_CMD_SECURITY_REQ)
2633                 goto drop;
2634
2635         switch (code) {
2636         case SMP_CMD_PAIRING_REQ:
2637                 reason = smp_cmd_pairing_req(conn, skb);
2638                 break;
2639
2640         case SMP_CMD_PAIRING_FAIL:
2641                 smp_failure(conn, 0);
2642                 err = -EPERM;
2643                 break;
2644
2645         case SMP_CMD_PAIRING_RSP:
2646                 reason = smp_cmd_pairing_rsp(conn, skb);
2647                 break;
2648
2649         case SMP_CMD_SECURITY_REQ:
2650                 reason = smp_cmd_security_req(conn, skb);
2651                 break;
2652
2653         case SMP_CMD_PAIRING_CONFIRM:
2654                 reason = smp_cmd_pairing_confirm(conn, skb);
2655                 break;
2656
2657         case SMP_CMD_PAIRING_RANDOM:
2658                 reason = smp_cmd_pairing_random(conn, skb);
2659                 break;
2660
2661         case SMP_CMD_ENCRYPT_INFO:
2662                 reason = smp_cmd_encrypt_info(conn, skb);
2663                 break;
2664
2665         case SMP_CMD_MASTER_IDENT:
2666                 reason = smp_cmd_master_ident(conn, skb);
2667                 break;
2668
2669         case SMP_CMD_IDENT_INFO:
2670                 reason = smp_cmd_ident_info(conn, skb);
2671                 break;
2672
2673         case SMP_CMD_IDENT_ADDR_INFO:
2674                 reason = smp_cmd_ident_addr_info(conn, skb);
2675                 break;
2676
2677         case SMP_CMD_SIGN_INFO:
2678                 reason = smp_cmd_sign_info(conn, skb);
2679                 break;
2680
2681         case SMP_CMD_PUBLIC_KEY:
2682                 reason = smp_cmd_public_key(conn, skb);
2683                 break;
2684
2685         case SMP_CMD_DHKEY_CHECK:
2686                 reason = smp_cmd_dhkey_check(conn, skb);
2687                 break;
2688
2689         case SMP_CMD_KEYPRESS_NOTIFY:
2690                 reason = smp_cmd_keypress_notify(conn, skb);
2691                 break;
2692
2693         default:
2694                 BT_DBG("Unknown command code 0x%2.2x", code);
2695                 reason = SMP_CMD_NOTSUPP;
2696                 goto done;
2697         }
2698
2699 done:
2700         if (!err) {
2701                 if (reason)
2702                         smp_failure(conn, reason);
2703                 kfree_skb(skb);
2704         }
2705
2706         return err;
2707
2708 drop:
2709         BT_ERR("%s unexpected SMP command 0x%02x from %pMR", hcon->hdev->name,
2710                code, &hcon->dst);
2711         kfree_skb(skb);
2712         return 0;
2713 }
2714
2715 static void smp_teardown_cb(struct l2cap_chan *chan, int err)
2716 {
2717         struct l2cap_conn *conn = chan->conn;
2718
2719         BT_DBG("chan %p", chan);
2720
2721         if (chan->data)
2722                 smp_chan_destroy(conn);
2723
2724         conn->smp = NULL;
2725         l2cap_chan_put(chan);
2726 }
2727
2728 static void bredr_pairing(struct l2cap_chan *chan)
2729 {
2730         struct l2cap_conn *conn = chan->conn;
2731         struct hci_conn *hcon = conn->hcon;
2732         struct hci_dev *hdev = hcon->hdev;
2733         struct smp_cmd_pairing req;
2734         struct smp_chan *smp;
2735
2736         BT_DBG("chan %p", chan);
2737
2738         /* Only new pairings are interesting */
2739         if (!test_bit(HCI_CONN_NEW_LINK_KEY, &hcon->flags))
2740                 return;
2741
2742         /* Don't bother if we're not encrypted */
2743         if (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags))
2744                 return;
2745
2746         /* Only master may initiate SMP over BR/EDR */
2747         if (hcon->role != HCI_ROLE_MASTER)
2748                 return;
2749
2750         /* Secure Connections support must be enabled */
2751         if (!hci_dev_test_flag(hdev, HCI_SC_ENABLED))
2752                 return;
2753
2754         /* BR/EDR must use Secure Connections for SMP */
2755         if (!test_bit(HCI_CONN_AES_CCM, &hcon->flags) &&
2756             !hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP))
2757                 return;
2758
2759         /* If our LE support is not enabled don't do anything */
2760         if (!hci_dev_test_flag(hdev, HCI_LE_ENABLED))
2761                 return;
2762
2763         /* Don't bother if remote LE support is not enabled */
2764         if (!lmp_host_le_capable(hcon))
2765                 return;
2766
2767         /* Remote must support SMP fixed chan for BR/EDR */
2768         if (!(conn->remote_fixed_chan & L2CAP_FC_SMP_BREDR))
2769                 return;
2770
2771         /* Don't bother if SMP is already ongoing */
2772         if (chan->data)
2773                 return;
2774
2775         smp = smp_chan_create(conn);
2776         if (!smp) {
2777                 BT_ERR("%s unable to create SMP context for BR/EDR",
2778                        hdev->name);
2779                 return;
2780         }
2781
2782         set_bit(SMP_FLAG_SC, &smp->flags);
2783
2784         BT_DBG("%s starting SMP over BR/EDR", hdev->name);
2785
2786         /* Prepare and send the BR/EDR SMP Pairing Request */
2787         build_bredr_pairing_cmd(smp, &req, NULL);
2788
2789         smp->preq[0] = SMP_CMD_PAIRING_REQ;
2790         memcpy(&smp->preq[1], &req, sizeof(req));
2791
2792         smp_send_cmd(conn, SMP_CMD_PAIRING_REQ, sizeof(req), &req);
2793         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RSP);
2794 }
2795
2796 static void smp_resume_cb(struct l2cap_chan *chan)
2797 {
2798         struct smp_chan *smp = chan->data;
2799         struct l2cap_conn *conn = chan->conn;
2800         struct hci_conn *hcon = conn->hcon;
2801
2802         BT_DBG("chan %p", chan);
2803
2804         if (hcon->type == ACL_LINK) {
2805                 bredr_pairing(chan);
2806                 return;
2807         }
2808
2809         if (!smp)
2810                 return;
2811
2812         if (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags))
2813                 return;
2814
2815         cancel_delayed_work(&smp->security_timer);
2816
2817         smp_distribute_keys(smp);
2818 }
2819
2820 static void smp_ready_cb(struct l2cap_chan *chan)
2821 {
2822         struct l2cap_conn *conn = chan->conn;
2823         struct hci_conn *hcon = conn->hcon;
2824
2825         BT_DBG("chan %p", chan);
2826
2827         conn->smp = chan;
2828         l2cap_chan_hold(chan);
2829
2830         if (hcon->type == ACL_LINK && test_bit(HCI_CONN_ENCRYPT, &hcon->flags))
2831                 bredr_pairing(chan);
2832 }
2833
2834 static int smp_recv_cb(struct l2cap_chan *chan, struct sk_buff *skb)
2835 {
2836         int err;
2837
2838         BT_DBG("chan %p", chan);
2839
2840         err = smp_sig_channel(chan, skb);
2841         if (err) {
2842                 struct smp_chan *smp = chan->data;
2843
2844                 if (smp)
2845                         cancel_delayed_work_sync(&smp->security_timer);
2846
2847                 hci_disconnect(chan->conn->hcon, HCI_ERROR_AUTH_FAILURE);
2848         }
2849
2850         return err;
2851 }
2852
2853 static struct sk_buff *smp_alloc_skb_cb(struct l2cap_chan *chan,
2854                                         unsigned long hdr_len,
2855                                         unsigned long len, int nb)
2856 {
2857         struct sk_buff *skb;
2858
2859         skb = bt_skb_alloc(hdr_len + len, GFP_KERNEL);
2860         if (!skb)
2861                 return ERR_PTR(-ENOMEM);
2862
2863         skb->priority = HCI_PRIO_MAX;
2864         bt_cb(skb)->chan = chan;
2865
2866         return skb;
2867 }
2868
2869 static const struct l2cap_ops smp_chan_ops = {
2870         .name                   = "Security Manager",
2871         .ready                  = smp_ready_cb,
2872         .recv                   = smp_recv_cb,
2873         .alloc_skb              = smp_alloc_skb_cb,
2874         .teardown               = smp_teardown_cb,
2875         .resume                 = smp_resume_cb,
2876
2877         .new_connection         = l2cap_chan_no_new_connection,
2878         .state_change           = l2cap_chan_no_state_change,
2879         .close                  = l2cap_chan_no_close,
2880         .defer                  = l2cap_chan_no_defer,
2881         .suspend                = l2cap_chan_no_suspend,
2882         .set_shutdown           = l2cap_chan_no_set_shutdown,
2883         .get_sndtimeo           = l2cap_chan_no_get_sndtimeo,
2884 };
2885
2886 static inline struct l2cap_chan *smp_new_conn_cb(struct l2cap_chan *pchan)
2887 {
2888         struct l2cap_chan *chan;
2889
2890         BT_DBG("pchan %p", pchan);
2891
2892         chan = l2cap_chan_create();
2893         if (!chan)
2894                 return NULL;
2895
2896         chan->chan_type = pchan->chan_type;
2897         chan->ops       = &smp_chan_ops;
2898         chan->scid      = pchan->scid;
2899         chan->dcid      = chan->scid;
2900         chan->imtu      = pchan->imtu;
2901         chan->omtu      = pchan->omtu;
2902         chan->mode      = pchan->mode;
2903
2904         /* Other L2CAP channels may request SMP routines in order to
2905          * change the security level. This means that the SMP channel
2906          * lock must be considered in its own category to avoid lockdep
2907          * warnings.
2908          */
2909         atomic_set(&chan->nesting, L2CAP_NESTING_SMP);
2910
2911         BT_DBG("created chan %p", chan);
2912
2913         return chan;
2914 }
2915
2916 static const struct l2cap_ops smp_root_chan_ops = {
2917         .name                   = "Security Manager Root",
2918         .new_connection         = smp_new_conn_cb,
2919
2920         /* None of these are implemented for the root channel */
2921         .close                  = l2cap_chan_no_close,
2922         .alloc_skb              = l2cap_chan_no_alloc_skb,
2923         .recv                   = l2cap_chan_no_recv,
2924         .state_change           = l2cap_chan_no_state_change,
2925         .teardown               = l2cap_chan_no_teardown,
2926         .ready                  = l2cap_chan_no_ready,
2927         .defer                  = l2cap_chan_no_defer,
2928         .suspend                = l2cap_chan_no_suspend,
2929         .resume                 = l2cap_chan_no_resume,
2930         .set_shutdown           = l2cap_chan_no_set_shutdown,
2931         .get_sndtimeo           = l2cap_chan_no_get_sndtimeo,
2932 };
2933
2934 static struct l2cap_chan *smp_add_cid(struct hci_dev *hdev, u16 cid)
2935 {
2936         struct l2cap_chan *chan;
2937         struct smp_dev *smp;
2938         struct crypto_blkcipher *tfm_aes;
2939
2940         if (cid == L2CAP_CID_SMP_BREDR) {
2941                 smp = NULL;
2942                 goto create_chan;
2943         }
2944
2945         smp = kzalloc(sizeof(*smp), GFP_KERNEL);
2946         if (!smp)
2947                 return ERR_PTR(-ENOMEM);
2948
2949         tfm_aes = crypto_alloc_blkcipher("ecb(aes)", 0, CRYPTO_ALG_ASYNC);
2950         if (IS_ERR(tfm_aes)) {
2951                 BT_ERR("Unable to create ECB crypto context");
2952                 kzfree(smp);
2953                 return ERR_CAST(tfm_aes);
2954         }
2955
2956         smp->tfm_aes = tfm_aes;
2957
2958 create_chan:
2959         chan = l2cap_chan_create();
2960         if (!chan) {
2961                 crypto_free_blkcipher(smp->tfm_aes);
2962                 kzfree(smp);
2963                 return ERR_PTR(-ENOMEM);
2964         }
2965
2966         chan->data = smp;
2967
2968         l2cap_add_scid(chan, cid);
2969
2970         l2cap_chan_set_defaults(chan);
2971
2972         if (cid == L2CAP_CID_SMP) {
2973                 u8 bdaddr_type;
2974
2975                 hci_copy_identity_address(hdev, &chan->src, &bdaddr_type);
2976
2977                 if (bdaddr_type == ADDR_LE_DEV_PUBLIC)
2978                         chan->src_type = BDADDR_LE_PUBLIC;
2979                 else
2980                         chan->src_type = BDADDR_LE_RANDOM;
2981         } else {
2982                 bacpy(&chan->src, &hdev->bdaddr);
2983                 chan->src_type = BDADDR_BREDR;
2984         }
2985
2986         chan->state = BT_LISTEN;
2987         chan->mode = L2CAP_MODE_BASIC;
2988         chan->imtu = L2CAP_DEFAULT_MTU;
2989         chan->ops = &smp_root_chan_ops;
2990
2991         /* Set correct nesting level for a parent/listening channel */
2992         atomic_set(&chan->nesting, L2CAP_NESTING_PARENT);
2993
2994         return chan;
2995 }
2996
2997 static void smp_del_chan(struct l2cap_chan *chan)
2998 {
2999         struct smp_dev *smp;
3000
3001         BT_DBG("chan %p", chan);
3002
3003         smp = chan->data;
3004         if (smp) {
3005                 chan->data = NULL;
3006                 if (smp->tfm_aes)
3007                         crypto_free_blkcipher(smp->tfm_aes);
3008                 kzfree(smp);
3009         }
3010
3011         l2cap_chan_put(chan);
3012 }
3013
3014 static ssize_t force_bredr_smp_read(struct file *file,
3015                                     char __user *user_buf,
3016                                     size_t count, loff_t *ppos)
3017 {
3018         struct hci_dev *hdev = file->private_data;
3019         char buf[3];
3020
3021         buf[0] = hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP) ? 'Y': 'N';
3022         buf[1] = '\n';
3023         buf[2] = '\0';
3024         return simple_read_from_buffer(user_buf, count, ppos, buf, 2);
3025 }
3026
3027 static ssize_t force_bredr_smp_write(struct file *file,
3028                                      const char __user *user_buf,
3029                                      size_t count, loff_t *ppos)
3030 {
3031         struct hci_dev *hdev = file->private_data;
3032         char buf[32];
3033         size_t buf_size = min(count, (sizeof(buf)-1));
3034         bool enable;
3035
3036         if (copy_from_user(buf, user_buf, buf_size))
3037                 return -EFAULT;
3038
3039         buf[buf_size] = '\0';
3040         if (strtobool(buf, &enable))
3041                 return -EINVAL;
3042
3043         if (enable == hci_dev_test_flag(hdev, HCI_FORCE_BREDR_SMP))
3044                 return -EALREADY;
3045
3046         if (enable) {
3047                 struct l2cap_chan *chan;
3048
3049                 chan = smp_add_cid(hdev, L2CAP_CID_SMP_BREDR);
3050                 if (IS_ERR(chan))
3051                         return PTR_ERR(chan);
3052
3053                 hdev->smp_bredr_data = chan;
3054         } else {
3055                 struct l2cap_chan *chan;
3056
3057                 chan = hdev->smp_bredr_data;
3058                 hdev->smp_bredr_data = NULL;
3059                 smp_del_chan(chan);
3060         }
3061
3062         hci_dev_change_flag(hdev, HCI_FORCE_BREDR_SMP);
3063
3064         return count;
3065 }
3066
3067 static const struct file_operations force_bredr_smp_fops = {
3068         .open           = simple_open,
3069         .read           = force_bredr_smp_read,
3070         .write          = force_bredr_smp_write,
3071         .llseek         = default_llseek,
3072 };
3073
3074 int smp_register(struct hci_dev *hdev)
3075 {
3076         struct l2cap_chan *chan;
3077
3078         BT_DBG("%s", hdev->name);
3079
3080         /* If the controller does not support Low Energy operation, then
3081          * there is also no need to register any SMP channel.
3082          */
3083         if (!lmp_le_capable(hdev))
3084                 return 0;
3085
3086         if (WARN_ON(hdev->smp_data)) {
3087                 chan = hdev->smp_data;
3088                 hdev->smp_data = NULL;
3089                 smp_del_chan(chan);
3090         }
3091
3092         chan = smp_add_cid(hdev, L2CAP_CID_SMP);
3093         if (IS_ERR(chan))
3094                 return PTR_ERR(chan);
3095
3096         hdev->smp_data = chan;
3097
3098         /* If the controller does not support BR/EDR Secure Connections
3099          * feature, then the BR/EDR SMP channel shall not be present.
3100          *
3101          * To test this with Bluetooth 4.0 controllers, create a debugfs
3102          * switch that allows forcing BR/EDR SMP support and accepting
3103          * cross-transport pairing on non-AES encrypted connections.
3104          */
3105         if (!lmp_sc_capable(hdev)) {
3106                 debugfs_create_file("force_bredr_smp", 0644, hdev->debugfs,
3107                                     hdev, &force_bredr_smp_fops);
3108                 return 0;
3109         }
3110
3111         if (WARN_ON(hdev->smp_bredr_data)) {
3112                 chan = hdev->smp_bredr_data;
3113                 hdev->smp_bredr_data = NULL;
3114                 smp_del_chan(chan);
3115         }
3116
3117         chan = smp_add_cid(hdev, L2CAP_CID_SMP_BREDR);
3118         if (IS_ERR(chan)) {
3119                 int err = PTR_ERR(chan);
3120                 chan = hdev->smp_data;
3121                 hdev->smp_data = NULL;
3122                 smp_del_chan(chan);
3123                 return err;
3124         }
3125
3126         hdev->smp_bredr_data = chan;
3127
3128         return 0;
3129 }
3130
3131 void smp_unregister(struct hci_dev *hdev)
3132 {
3133         struct l2cap_chan *chan;
3134
3135         if (hdev->smp_bredr_data) {
3136                 chan = hdev->smp_bredr_data;
3137                 hdev->smp_bredr_data = NULL;
3138                 smp_del_chan(chan);
3139         }
3140
3141         if (hdev->smp_data) {
3142                 chan = hdev->smp_data;
3143                 hdev->smp_data = NULL;
3144                 smp_del_chan(chan);
3145         }
3146 }
3147
3148 #if IS_ENABLED(CONFIG_BT_SELFTEST_SMP)
3149
3150 static int __init test_ah(struct crypto_blkcipher *tfm_aes)
3151 {
3152         const u8 irk[16] = {
3153                         0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
3154                         0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
3155         const u8 r[3] = { 0x94, 0x81, 0x70 };
3156         const u8 exp[3] = { 0xaa, 0xfb, 0x0d };
3157         u8 res[3];
3158         int err;
3159
3160         err = smp_ah(tfm_aes, irk, r, res);
3161         if (err)
3162                 return err;
3163
3164         if (memcmp(res, exp, 3))
3165                 return -EINVAL;
3166
3167         return 0;
3168 }
3169
3170 static int __init test_c1(struct crypto_blkcipher *tfm_aes)
3171 {
3172         const u8 k[16] = {
3173                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3174                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
3175         const u8 r[16] = {
3176                         0xe0, 0x2e, 0x70, 0xc6, 0x4e, 0x27, 0x88, 0x63,
3177                         0x0e, 0x6f, 0xad, 0x56, 0x21, 0xd5, 0x83, 0x57 };
3178         const u8 preq[7] = { 0x01, 0x01, 0x00, 0x00, 0x10, 0x07, 0x07 };
3179         const u8 pres[7] = { 0x02, 0x03, 0x00, 0x00, 0x08, 0x00, 0x05 };
3180         const u8 _iat = 0x01;
3181         const u8 _rat = 0x00;
3182         const bdaddr_t ra = { { 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1 } };
3183         const bdaddr_t ia = { { 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1 } };
3184         const u8 exp[16] = {
3185                         0x86, 0x3b, 0xf1, 0xbe, 0xc5, 0x4d, 0xa7, 0xd2,
3186                         0xea, 0x88, 0x89, 0x87, 0xef, 0x3f, 0x1e, 0x1e };
3187         u8 res[16];
3188         int err;
3189
3190         err = smp_c1(tfm_aes, k, r, preq, pres, _iat, &ia, _rat, &ra, res);
3191         if (err)
3192                 return err;
3193
3194         if (memcmp(res, exp, 16))
3195                 return -EINVAL;
3196
3197         return 0;
3198 }
3199
3200 static int __init test_s1(struct crypto_blkcipher *tfm_aes)
3201 {
3202         const u8 k[16] = {
3203                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3204                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
3205         const u8 r1[16] = {
3206                         0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 };
3207         const u8 r2[16] = {
3208                         0x00, 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99 };
3209         const u8 exp[16] = {
3210                         0x62, 0xa0, 0x6d, 0x79, 0xae, 0x16, 0x42, 0x5b,
3211                         0x9b, 0xf4, 0xb0, 0xe8, 0xf0, 0xe1, 0x1f, 0x9a };
3212         u8 res[16];
3213         int err;
3214
3215         err = smp_s1(tfm_aes, k, r1, r2, res);
3216         if (err)
3217                 return err;
3218
3219         if (memcmp(res, exp, 16))
3220                 return -EINVAL;
3221
3222         return 0;
3223 }
3224
3225 static int __init test_f4(struct crypto_hash *tfm_cmac)
3226 {
3227         const u8 u[32] = {
3228                         0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
3229                         0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
3230                         0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
3231                         0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 };
3232         const u8 v[32] = {
3233                         0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b,
3234                         0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59,
3235                         0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90,
3236                         0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 };
3237         const u8 x[16] = {
3238                         0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
3239                         0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
3240         const u8 z = 0x00;
3241         const u8 exp[16] = {
3242                         0x2d, 0x87, 0x74, 0xa9, 0xbe, 0xa1, 0xed, 0xf1,
3243                         0x1c, 0xbd, 0xa9, 0x07, 0xf1, 0x16, 0xc9, 0xf2 };
3244         u8 res[16];
3245         int err;
3246
3247         err = smp_f4(tfm_cmac, u, v, x, z, res);
3248         if (err)
3249                 return err;
3250
3251         if (memcmp(res, exp, 16))
3252                 return -EINVAL;
3253
3254         return 0;
3255 }
3256
3257 static int __init test_f5(struct crypto_hash *tfm_cmac)
3258 {
3259         const u8 w[32] = {
3260                         0x98, 0xa6, 0xbf, 0x73, 0xf3, 0x34, 0x8d, 0x86,
3261                         0xf1, 0x66, 0xf8, 0xb4, 0x13, 0x6b, 0x79, 0x99,
3262                         0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
3263                         0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
3264         const u8 n1[16] = {
3265                         0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
3266                         0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
3267         const u8 n2[16] = {
3268                         0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
3269                         0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
3270         const u8 a1[7] = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56, 0x00 };
3271         const u8 a2[7] = { 0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7, 0x00 };
3272         const u8 exp_ltk[16] = {
3273                         0x38, 0x0a, 0x75, 0x94, 0xb5, 0x22, 0x05, 0x98,
3274                         0x23, 0xcd, 0xd7, 0x69, 0x11, 0x79, 0x86, 0x69 };
3275         const u8 exp_mackey[16] = {
3276                         0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, 0xfd,
3277                         0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, 0x65, 0x29 };
3278         u8 mackey[16], ltk[16];
3279         int err;
3280
3281         err = smp_f5(tfm_cmac, w, n1, n2, a1, a2, mackey, ltk);
3282         if (err)
3283                 return err;
3284
3285         if (memcmp(mackey, exp_mackey, 16))
3286                 return -EINVAL;
3287
3288         if (memcmp(ltk, exp_ltk, 16))
3289                 return -EINVAL;
3290
3291         return 0;
3292 }
3293
3294 static int __init test_f6(struct crypto_hash *tfm_cmac)
3295 {
3296         const u8 w[16] = {
3297                         0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, 0xfd,
3298                         0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, 0x65, 0x29 };
3299         const u8 n1[16] = {
3300                         0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
3301                         0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
3302         const u8 n2[16] = {
3303                         0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
3304                         0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
3305         const u8 r[16] = {
3306                         0xc8, 0x0f, 0x2d, 0x0c, 0xd2, 0x42, 0xda, 0x08,
3307                         0x54, 0xbb, 0x53, 0xb4, 0x3b, 0x34, 0xa3, 0x12 };
3308         const u8 io_cap[3] = { 0x02, 0x01, 0x01 };
3309         const u8 a1[7] = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56, 0x00 };
3310         const u8 a2[7] = { 0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7, 0x00 };
3311         const u8 exp[16] = {
3312                         0x61, 0x8f, 0x95, 0xda, 0x09, 0x0b, 0x6c, 0xd2,
3313                         0xc5, 0xe8, 0xd0, 0x9c, 0x98, 0x73, 0xc4, 0xe3 };
3314         u8 res[16];
3315         int err;
3316
3317         err = smp_f6(tfm_cmac, w, n1, n2, r, io_cap, a1, a2, res);
3318         if (err)
3319                 return err;
3320
3321         if (memcmp(res, exp, 16))
3322                 return -EINVAL;
3323
3324         return 0;
3325 }
3326
3327 static int __init test_g2(struct crypto_hash *tfm_cmac)
3328 {
3329         const u8 u[32] = {
3330                         0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
3331                         0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
3332                         0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
3333                         0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 };
3334         const u8 v[32] = {
3335                         0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b,
3336                         0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59,
3337                         0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90,
3338                         0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 };
3339         const u8 x[16] = {
3340                         0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
3341                         0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
3342         const u8 y[16] = {
3343                         0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
3344                         0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
3345         const u32 exp_val = 0x2f9ed5ba % 1000000;
3346         u32 val;
3347         int err;
3348
3349         err = smp_g2(tfm_cmac, u, v, x, y, &val);
3350         if (err)
3351                 return err;
3352
3353         if (val != exp_val)
3354                 return -EINVAL;
3355
3356         return 0;
3357 }
3358
3359 static int __init test_h6(struct crypto_hash *tfm_cmac)
3360 {
3361         const u8 w[16] = {
3362                         0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
3363                         0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
3364         const u8 key_id[4] = { 0x72, 0x62, 0x65, 0x6c };
3365         const u8 exp[16] = {
3366                         0x99, 0x63, 0xb1, 0x80, 0xe2, 0xa9, 0xd3, 0xe8,
3367                         0x1c, 0xc9, 0x6d, 0xe7, 0x02, 0xe1, 0x9a, 0x2d };
3368         u8 res[16];
3369         int err;
3370
3371         err = smp_h6(tfm_cmac, w, key_id, res);
3372         if (err)
3373                 return err;
3374
3375         if (memcmp(res, exp, 16))
3376                 return -EINVAL;
3377
3378         return 0;
3379 }
3380
3381 static int __init run_selftests(struct crypto_blkcipher *tfm_aes,
3382                                 struct crypto_hash *tfm_cmac)
3383 {
3384         ktime_t calltime, delta, rettime;
3385         unsigned long long duration;
3386         int err;
3387
3388         calltime = ktime_get();
3389
3390         err = test_ah(tfm_aes);
3391         if (err) {
3392                 BT_ERR("smp_ah test failed");
3393                 return err;
3394         }
3395
3396         err = test_c1(tfm_aes);
3397         if (err) {
3398                 BT_ERR("smp_c1 test failed");
3399                 return err;
3400         }
3401
3402         err = test_s1(tfm_aes);
3403         if (err) {
3404                 BT_ERR("smp_s1 test failed");
3405                 return err;
3406         }
3407
3408         err = test_f4(tfm_cmac);
3409         if (err) {
3410                 BT_ERR("smp_f4 test failed");
3411                 return err;
3412         }
3413
3414         err = test_f5(tfm_cmac);
3415         if (err) {
3416                 BT_ERR("smp_f5 test failed");
3417                 return err;
3418         }
3419
3420         err = test_f6(tfm_cmac);
3421         if (err) {
3422                 BT_ERR("smp_f6 test failed");
3423                 return err;
3424         }
3425
3426         err = test_g2(tfm_cmac);
3427         if (err) {
3428                 BT_ERR("smp_g2 test failed");
3429                 return err;
3430         }
3431
3432         err = test_h6(tfm_cmac);
3433         if (err) {
3434                 BT_ERR("smp_h6 test failed");
3435                 return err;
3436         }
3437
3438         rettime = ktime_get();
3439         delta = ktime_sub(rettime, calltime);
3440         duration = (unsigned long long) ktime_to_ns(delta) >> 10;
3441
3442         BT_INFO("SMP test passed in %llu usecs", duration);
3443
3444         return 0;
3445 }
3446
3447 int __init bt_selftest_smp(void)
3448 {
3449         struct crypto_blkcipher *tfm_aes;
3450         struct crypto_hash *tfm_cmac;
3451         int err;
3452
3453         tfm_aes = crypto_alloc_blkcipher("ecb(aes)", 0, CRYPTO_ALG_ASYNC);
3454         if (IS_ERR(tfm_aes)) {
3455                 BT_ERR("Unable to create ECB crypto context");
3456                 return PTR_ERR(tfm_aes);
3457         }
3458
3459         tfm_cmac = crypto_alloc_hash("cmac(aes)", 0, CRYPTO_ALG_ASYNC);
3460         if (IS_ERR(tfm_cmac)) {
3461                 BT_ERR("Unable to create CMAC crypto context");
3462                 crypto_free_blkcipher(tfm_aes);
3463                 return PTR_ERR(tfm_cmac);
3464         }
3465
3466         err = run_selftests(tfm_aes, tfm_cmac);
3467
3468         crypto_free_hash(tfm_cmac);
3469         crypto_free_blkcipher(tfm_aes);
3470
3471         return err;
3472 }
3473
3474 #endif