Bluetooth: Add MGMT interface for setting IRK
[profile/mobile/platform/kernel/linux-3.10-sc7730.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)      (test_bit(HCI_SC_ENABLED, &(dev)->dev_flags) ? \
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_chan {
77         struct l2cap_conn       *conn;
78         struct delayed_work     security_timer;
79         unsigned long           allow_cmd; /* Bitmask of allowed commands */
80
81         u8              preq[7]; /* SMP Pairing Request */
82         u8              prsp[7]; /* SMP Pairing Response */
83         u8              prnd[16]; /* SMP Pairing Random (local) */
84         u8              rrnd[16]; /* SMP Pairing Random (remote) */
85         u8              pcnf[16]; /* SMP Pairing Confirm */
86         u8              tk[16]; /* SMP Temporary Key */
87         u8              rr[16];
88         u8              enc_key_size;
89         u8              remote_key_dist;
90         bdaddr_t        id_addr;
91         u8              id_addr_type;
92         u8              irk[16];
93         struct smp_csrk *csrk;
94         struct smp_csrk *slave_csrk;
95         struct smp_ltk  *ltk;
96         struct smp_ltk  *slave_ltk;
97         struct smp_irk  *remote_irk;
98         u8              *link_key;
99         unsigned long   flags;
100         u8              method;
101         u8              passkey_round;
102
103         /* Secure Connections variables */
104         u8                      local_pk[64];
105         u8                      local_sk[32];
106         u8                      remote_pk[64];
107         u8                      dhkey[32];
108         u8                      mackey[16];
109
110         struct crypto_blkcipher *tfm_aes;
111         struct crypto_hash      *tfm_cmac;
112 };
113
114 /* These debug key values are defined in the SMP section of the core
115  * specification. debug_pk is the public debug key and debug_sk the
116  * private debug key.
117  */
118 static const u8 debug_pk[64] = {
119                 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
120                 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
121                 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
122                 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20,
123
124                 0x8b, 0xd2, 0x89, 0x15, 0xd0, 0x8e, 0x1c, 0x74,
125                 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76,
126                 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63,
127                 0x6d, 0xeb, 0x2a, 0x65, 0x49, 0x9c, 0x80, 0xdc,
128 };
129
130 static const u8 debug_sk[32] = {
131                 0xbd, 0x1a, 0x3c, 0xcd, 0xa6, 0xb8, 0x99, 0x58,
132                 0x99, 0xb7, 0x40, 0xeb, 0x7b, 0x60, 0xff, 0x4a,
133                 0x50, 0x3f, 0x10, 0xd2, 0xe3, 0xb3, 0xc9, 0x74,
134                 0x38, 0x5f, 0xc5, 0xa3, 0xd4, 0xf6, 0x49, 0x3f,
135 };
136
137 static inline void swap_buf(const u8 *src, u8 *dst, size_t len)
138 {
139         size_t i;
140
141         for (i = 0; i < len; i++)
142                 dst[len - 1 - i] = src[i];
143 }
144
145 /* The following functions map to the LE SC SMP crypto functions
146  * AES-CMAC, f4, f5, f6, g2 and h6.
147  */
148
149 static int aes_cmac(struct crypto_hash *tfm, const u8 k[16], const u8 *m,
150                     size_t len, u8 mac[16])
151 {
152         uint8_t tmp[16], mac_msb[16], msg_msb[CMAC_MSG_MAX];
153         struct hash_desc desc;
154         struct scatterlist sg;
155         int err;
156
157         if (len > CMAC_MSG_MAX)
158                 return -EFBIG;
159
160         if (!tfm) {
161                 BT_ERR("tfm %p", tfm);
162                 return -EINVAL;
163         }
164
165         desc.tfm = tfm;
166         desc.flags = 0;
167
168         crypto_hash_init(&desc);
169
170         /* Swap key and message from LSB to MSB */
171         swap_buf(k, tmp, 16);
172         swap_buf(m, msg_msb, len);
173
174         SMP_DBG("msg (len %zu) %*phN", len, (int) len, m);
175         SMP_DBG("key %16phN", k);
176
177         err = crypto_hash_setkey(tfm, tmp, 16);
178         if (err) {
179                 BT_ERR("cipher setkey failed: %d", err);
180                 return err;
181         }
182
183         sg_init_one(&sg, msg_msb, len);
184
185         err = crypto_hash_update(&desc, &sg, len);
186         if (err) {
187                 BT_ERR("Hash update error %d", err);
188                 return err;
189         }
190
191         err = crypto_hash_final(&desc, mac_msb);
192         if (err) {
193                 BT_ERR("Hash final error %d", err);
194                 return err;
195         }
196
197         swap_buf(mac_msb, mac, 16);
198
199         SMP_DBG("mac %16phN", mac);
200
201         return 0;
202 }
203
204 static int smp_f4(struct crypto_hash *tfm_cmac, const u8 u[32], const u8 v[32],
205                   const u8 x[16], u8 z, u8 res[16])
206 {
207         u8 m[65];
208         int err;
209
210         SMP_DBG("u %32phN", u);
211         SMP_DBG("v %32phN", v);
212         SMP_DBG("x %16phN z %02x", x, z);
213
214         m[0] = z;
215         memcpy(m + 1, v, 32);
216         memcpy(m + 33, u, 32);
217
218         err = aes_cmac(tfm_cmac, x, m, sizeof(m), res);
219         if (err)
220                 return err;
221
222         SMP_DBG("res %16phN", res);
223
224         return err;
225 }
226
227 static int smp_f5(struct crypto_hash *tfm_cmac, const u8 w[32],
228                   const u8 n1[16], const u8 n2[16], const u8 a1[7],
229                   const u8 a2[7], u8 mackey[16], u8 ltk[16])
230 {
231         /* The btle, salt and length "magic" values are as defined in
232          * the SMP section of the Bluetooth core specification. In ASCII
233          * the btle value ends up being 'btle'. The salt is just a
234          * random number whereas length is the value 256 in little
235          * endian format.
236          */
237         const u8 btle[4] = { 0x65, 0x6c, 0x74, 0x62 };
238         const u8 salt[16] = { 0xbe, 0x83, 0x60, 0x5a, 0xdb, 0x0b, 0x37, 0x60,
239                               0x38, 0xa5, 0xf5, 0xaa, 0x91, 0x83, 0x88, 0x6c };
240         const u8 length[2] = { 0x00, 0x01 };
241         u8 m[53], t[16];
242         int err;
243
244         SMP_DBG("w %32phN", w);
245         SMP_DBG("n1 %16phN n2 %16phN", n1, n2);
246         SMP_DBG("a1 %7phN a2 %7phN", a1, a2);
247
248         err = aes_cmac(tfm_cmac, salt, w, 32, t);
249         if (err)
250                 return err;
251
252         SMP_DBG("t %16phN", t);
253
254         memcpy(m, length, 2);
255         memcpy(m + 2, a2, 7);
256         memcpy(m + 9, a1, 7);
257         memcpy(m + 16, n2, 16);
258         memcpy(m + 32, n1, 16);
259         memcpy(m + 48, btle, 4);
260
261         m[52] = 0; /* Counter */
262
263         err = aes_cmac(tfm_cmac, t, m, sizeof(m), mackey);
264         if (err)
265                 return err;
266
267         SMP_DBG("mackey %16phN", mackey);
268
269         m[52] = 1; /* Counter */
270
271         err = aes_cmac(tfm_cmac, t, m, sizeof(m), ltk);
272         if (err)
273                 return err;
274
275         SMP_DBG("ltk %16phN", ltk);
276
277         return 0;
278 }
279
280 static int smp_f6(struct crypto_hash *tfm_cmac, const u8 w[16],
281                   const u8 n1[16], const u8 n2[16], const u8 r[16],
282                   const u8 io_cap[3], const u8 a1[7], const u8 a2[7],
283                   u8 res[16])
284 {
285         u8 m[65];
286         int err;
287
288         SMP_DBG("w %16phN", w);
289         SMP_DBG("n1 %16phN n2 %16phN", n1, n2);
290         SMP_DBG("r %16phN io_cap %3phN a1 %7phN a2 %7phN", r, io_cap, a1, a2);
291
292         memcpy(m, a2, 7);
293         memcpy(m + 7, a1, 7);
294         memcpy(m + 14, io_cap, 3);
295         memcpy(m + 17, r, 16);
296         memcpy(m + 33, n2, 16);
297         memcpy(m + 49, n1, 16);
298
299         err = aes_cmac(tfm_cmac, w, m, sizeof(m), res);
300         if (err)
301                 return err;
302
303         SMP_DBG("res %16phN", res);
304
305         return err;
306 }
307
308 static int smp_g2(struct crypto_hash *tfm_cmac, const u8 u[32], const u8 v[32],
309                   const u8 x[16], const u8 y[16], u32 *val)
310 {
311         u8 m[80], tmp[16];
312         int err;
313
314         SMP_DBG("u %32phN", u);
315         SMP_DBG("v %32phN", v);
316         SMP_DBG("x %16phN y %16phN", x, y);
317
318         memcpy(m, y, 16);
319         memcpy(m + 16, v, 32);
320         memcpy(m + 48, u, 32);
321
322         err = aes_cmac(tfm_cmac, x, m, sizeof(m), tmp);
323         if (err)
324                 return err;
325
326         *val = get_unaligned_le32(tmp);
327         *val %= 1000000;
328
329         SMP_DBG("val %06u", *val);
330
331         return 0;
332 }
333
334 static int smp_h6(struct crypto_hash *tfm_cmac, const u8 w[16],
335                   const u8 key_id[4], u8 res[16])
336 {
337         int err;
338
339         SMP_DBG("w %16phN key_id %4phN", w, key_id);
340
341         err = aes_cmac(tfm_cmac, w, key_id, 4, res);
342         if (err)
343                 return err;
344
345         SMP_DBG("res %16phN", res);
346
347         return err;
348 }
349
350 /* The following functions map to the legacy SMP crypto functions e, c1,
351  * s1 and ah.
352  */
353
354 static int smp_e(struct crypto_blkcipher *tfm, const u8 *k, u8 *r)
355 {
356         struct blkcipher_desc desc;
357         struct scatterlist sg;
358         uint8_t tmp[16], data[16];
359         int err;
360
361         if (!tfm) {
362                 BT_ERR("tfm %p", tfm);
363                 return -EINVAL;
364         }
365
366         desc.tfm = tfm;
367         desc.flags = 0;
368
369         /* The most significant octet of key corresponds to k[0] */
370         swap_buf(k, tmp, 16);
371
372         err = crypto_blkcipher_setkey(tfm, tmp, 16);
373         if (err) {
374                 BT_ERR("cipher setkey failed: %d", err);
375                 return err;
376         }
377
378         /* Most significant octet of plaintextData corresponds to data[0] */
379         swap_buf(r, data, 16);
380
381         sg_init_one(&sg, data, 16);
382
383         err = crypto_blkcipher_encrypt(&desc, &sg, &sg, 16);
384         if (err)
385                 BT_ERR("Encrypt data error %d", err);
386
387         /* Most significant octet of encryptedData corresponds to data[0] */
388         swap_buf(data, r, 16);
389
390         return err;
391 }
392
393 static int smp_c1(struct crypto_blkcipher *tfm_aes, const u8 k[16],
394                   const u8 r[16], const u8 preq[7], const u8 pres[7], u8 _iat,
395                   const bdaddr_t *ia, u8 _rat, const bdaddr_t *ra, u8 res[16])
396 {
397         u8 p1[16], p2[16];
398         int err;
399
400         memset(p1, 0, 16);
401
402         /* p1 = pres || preq || _rat || _iat */
403         p1[0] = _iat;
404         p1[1] = _rat;
405         memcpy(p1 + 2, preq, 7);
406         memcpy(p1 + 9, pres, 7);
407
408         /* p2 = padding || ia || ra */
409         memcpy(p2, ra, 6);
410         memcpy(p2 + 6, ia, 6);
411         memset(p2 + 12, 0, 4);
412
413         /* res = r XOR p1 */
414         u128_xor((u128 *) res, (u128 *) r, (u128 *) p1);
415
416         /* res = e(k, res) */
417         err = smp_e(tfm_aes, k, res);
418         if (err) {
419                 BT_ERR("Encrypt data error");
420                 return err;
421         }
422
423         /* res = res XOR p2 */
424         u128_xor((u128 *) res, (u128 *) res, (u128 *) p2);
425
426         /* res = e(k, res) */
427         err = smp_e(tfm_aes, k, res);
428         if (err)
429                 BT_ERR("Encrypt data error");
430
431         return err;
432 }
433
434 static int smp_s1(struct crypto_blkcipher *tfm_aes, const u8 k[16],
435                   const u8 r1[16], const u8 r2[16], u8 _r[16])
436 {
437         int err;
438
439         /* Just least significant octets from r1 and r2 are considered */
440         memcpy(_r, r2, 8);
441         memcpy(_r + 8, r1, 8);
442
443         err = smp_e(tfm_aes, k, _r);
444         if (err)
445                 BT_ERR("Encrypt data error");
446
447         return err;
448 }
449
450 static int smp_ah(struct crypto_blkcipher *tfm, const u8 irk[16],
451                   const u8 r[3], u8 res[3])
452 {
453         u8 _res[16];
454         int err;
455
456         /* r' = padding || r */
457         memcpy(_res, r, 3);
458         memset(_res + 3, 0, 13);
459
460         err = smp_e(tfm, irk, _res);
461         if (err) {
462                 BT_ERR("Encrypt error");
463                 return err;
464         }
465
466         /* The output of the random address function ah is:
467          *      ah(h, r) = e(k, r') mod 2^24
468          * The output of the security function e is then truncated to 24 bits
469          * by taking the least significant 24 bits of the output of e as the
470          * result of ah.
471          */
472         memcpy(res, _res, 3);
473
474         return 0;
475 }
476
477 bool smp_irk_matches(struct hci_dev *hdev, const u8 irk[16],
478                      const bdaddr_t *bdaddr)
479 {
480         struct l2cap_chan *chan = hdev->smp_data;
481         struct crypto_blkcipher *tfm;
482         u8 hash[3];
483         int err;
484
485         if (!chan || !chan->data)
486                 return false;
487
488         tfm = chan->data;
489
490         BT_DBG("RPA %pMR IRK %*phN", bdaddr, 16, irk);
491
492         err = smp_ah(tfm, irk, &bdaddr->b[3], hash);
493         if (err)
494                 return false;
495
496         return !memcmp(bdaddr->b, hash, 3);
497 }
498
499 int smp_generate_rpa(struct hci_dev *hdev, const u8 irk[16], bdaddr_t *rpa)
500 {
501         struct l2cap_chan *chan = hdev->smp_data;
502         struct crypto_blkcipher *tfm;
503         int err;
504
505         if (!chan || !chan->data)
506                 return -EOPNOTSUPP;
507
508         tfm = chan->data;
509
510         get_random_bytes(&rpa->b[3], 3);
511
512         rpa->b[5] &= 0x3f;      /* Clear two most significant bits */
513         rpa->b[5] |= 0x40;      /* Set second most significant bit */
514
515         err = smp_ah(tfm, irk, &rpa->b[3], rpa->b);
516         if (err < 0)
517                 return err;
518
519         BT_DBG("RPA %pMR", rpa);
520
521         return 0;
522 }
523
524 static void smp_send_cmd(struct l2cap_conn *conn, u8 code, u16 len, void *data)
525 {
526         struct l2cap_chan *chan = conn->smp;
527         struct smp_chan *smp;
528         struct kvec iv[2];
529         struct msghdr msg;
530
531         if (!chan)
532                 return;
533
534         BT_DBG("code 0x%2.2x", code);
535
536         iv[0].iov_base = &code;
537         iv[0].iov_len = 1;
538
539         iv[1].iov_base = data;
540         iv[1].iov_len = len;
541
542         memset(&msg, 0, sizeof(msg));
543 #ifdef CONFIG_TIZEN_WIP
544         msg.msg_iov = (struct iovec *) &iv;
545         msg.msg_iovlen = 2;
546 #else
547         iov_iter_kvec(&msg.msg_iter, WRITE | ITER_KVEC, iv, 2, 1 + len);
548 #endif
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 (test_bit(HCI_BONDABLE, &conn->hcon->hdev->dev_flags)) {
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 (test_bit(HCI_RPA_RESOLVING, &hdev->dev_flags))
605                 remote_dist |= SMP_DIST_ID_KEY;
606
607         if (test_bit(HCI_PRIVACY, &hdev->dev_flags))
608                 local_dist |= SMP_DIST_ID_KEY;
609
610         if (test_bit(HCI_SC_ENABLED, &hdev->dev_flags) &&
611             (authreq & SMP_AUTH_SC)) {
612                 struct oob_data *oob_data;
613                 u8 bdaddr_type;
614
615                 if (test_bit(HCI_SSP_ENABLED, &hdev->dev_flags)) {
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) {
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         kfree(smp->csrk);
689         kfree(smp->slave_csrk);
690         kfree(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             !test_bit(HCI_KEEP_DEBUG_KEYS, &hcon->hdev->dev_flags)) {
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         kfree(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 (!test_bit(HCI_KEEP_DEBUG_KEYS, &hdev->dev_flags) &&
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                 kfree(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                 kfree(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                         csrk->master = 0x00;
1260                         memcpy(csrk->val, sign.csrk, sizeof(csrk->val));
1261                 }
1262                 smp->slave_csrk = csrk;
1263
1264                 smp_send_cmd(conn, SMP_CMD_SIGN_INFO, sizeof(sign), &sign);
1265
1266                 *keydist &= ~SMP_DIST_SIGN;
1267         }
1268
1269         /* If there are still keys to be received wait for them */
1270         if (smp->remote_key_dist & KEY_DIST_MASK) {
1271                 smp_allow_key_dist(smp);
1272                 return;
1273         }
1274
1275         set_bit(SMP_FLAG_COMPLETE, &smp->flags);
1276         smp_notify_keys(conn);
1277
1278         smp_chan_destroy(conn);
1279 }
1280
1281 static void smp_timeout(struct work_struct *work)
1282 {
1283         struct smp_chan *smp = container_of(work, struct smp_chan,
1284                                             security_timer.work);
1285         struct l2cap_conn *conn = smp->conn;
1286
1287         BT_DBG("conn %p", conn);
1288
1289         hci_disconnect(conn->hcon, HCI_ERROR_REMOTE_USER_TERM);
1290 }
1291
1292 static struct smp_chan *smp_chan_create(struct l2cap_conn *conn)
1293 {
1294         struct l2cap_chan *chan = conn->smp;
1295         struct smp_chan *smp;
1296
1297         smp = kzalloc(sizeof(*smp), GFP_ATOMIC);
1298         if (!smp)
1299                 return NULL;
1300
1301         smp->tfm_aes = crypto_alloc_blkcipher("ecb(aes)", 0, CRYPTO_ALG_ASYNC);
1302         if (IS_ERR(smp->tfm_aes)) {
1303                 BT_ERR("Unable to create ECB crypto context");
1304                 kfree(smp);
1305                 return NULL;
1306         }
1307
1308         smp->tfm_cmac = crypto_alloc_hash("cmac(aes)", 0, CRYPTO_ALG_ASYNC);
1309         if (IS_ERR(smp->tfm_cmac)) {
1310                 BT_ERR("Unable to create CMAC crypto context");
1311                 crypto_free_blkcipher(smp->tfm_aes);
1312                 kfree(smp);
1313                 return NULL;
1314         }
1315
1316         smp->conn = conn;
1317         chan->data = smp;
1318
1319         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_FAIL);
1320
1321         INIT_DELAYED_WORK(&smp->security_timer, smp_timeout);
1322
1323         hci_conn_hold(conn->hcon);
1324
1325         return smp;
1326 }
1327
1328 static int sc_mackey_and_ltk(struct smp_chan *smp, u8 mackey[16], u8 ltk[16])
1329 {
1330         struct hci_conn *hcon = smp->conn->hcon;
1331         u8 *na, *nb, a[7], b[7];
1332
1333         if (hcon->out) {
1334                 na   = smp->prnd;
1335                 nb   = smp->rrnd;
1336         } else {
1337                 na   = smp->rrnd;
1338                 nb   = smp->prnd;
1339         }
1340
1341         memcpy(a, &hcon->init_addr, 6);
1342         memcpy(b, &hcon->resp_addr, 6);
1343         a[6] = hcon->init_addr_type;
1344         b[6] = hcon->resp_addr_type;
1345
1346         return smp_f5(smp->tfm_cmac, smp->dhkey, na, nb, a, b, mackey, ltk);
1347 }
1348
1349 static void sc_dhkey_check(struct smp_chan *smp)
1350 {
1351         struct hci_conn *hcon = smp->conn->hcon;
1352         struct smp_cmd_dhkey_check check;
1353         u8 a[7], b[7], *local_addr, *remote_addr;
1354         u8 io_cap[3], r[16];
1355
1356         memcpy(a, &hcon->init_addr, 6);
1357         memcpy(b, &hcon->resp_addr, 6);
1358         a[6] = hcon->init_addr_type;
1359         b[6] = hcon->resp_addr_type;
1360
1361         if (hcon->out) {
1362                 local_addr = a;
1363                 remote_addr = b;
1364                 memcpy(io_cap, &smp->preq[1], 3);
1365         } else {
1366                 local_addr = b;
1367                 remote_addr = a;
1368                 memcpy(io_cap, &smp->prsp[1], 3);
1369         }
1370
1371         memset(r, 0, sizeof(r));
1372
1373         if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
1374                 put_unaligned_le32(hcon->passkey_notify, r);
1375
1376         if (smp->method == REQ_OOB)
1377                 memcpy(r, smp->rr, 16);
1378
1379         smp_f6(smp->tfm_cmac, smp->mackey, smp->prnd, smp->rrnd, r, io_cap,
1380                local_addr, remote_addr, check.e);
1381
1382         smp_send_cmd(smp->conn, SMP_CMD_DHKEY_CHECK, sizeof(check), &check);
1383 }
1384
1385 static u8 sc_passkey_send_confirm(struct smp_chan *smp)
1386 {
1387         struct l2cap_conn *conn = smp->conn;
1388         struct hci_conn *hcon = conn->hcon;
1389         struct smp_cmd_pairing_confirm cfm;
1390         u8 r;
1391
1392         r = ((hcon->passkey_notify >> smp->passkey_round) & 0x01);
1393         r |= 0x80;
1394
1395         get_random_bytes(smp->prnd, sizeof(smp->prnd));
1396
1397         if (smp_f4(smp->tfm_cmac, smp->local_pk, smp->remote_pk, smp->prnd, r,
1398                    cfm.confirm_val))
1399                 return SMP_UNSPECIFIED;
1400
1401         smp_send_cmd(conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cfm), &cfm);
1402
1403         return 0;
1404 }
1405
1406 static u8 sc_passkey_round(struct smp_chan *smp, u8 smp_op)
1407 {
1408         struct l2cap_conn *conn = smp->conn;
1409         struct hci_conn *hcon = conn->hcon;
1410         struct hci_dev *hdev = hcon->hdev;
1411         u8 cfm[16], r;
1412
1413         /* Ignore the PDU if we've already done 20 rounds (0 - 19) */
1414         if (smp->passkey_round >= 20)
1415                 return 0;
1416
1417         switch (smp_op) {
1418         case SMP_CMD_PAIRING_RANDOM:
1419                 r = ((hcon->passkey_notify >> smp->passkey_round) & 0x01);
1420                 r |= 0x80;
1421
1422                 if (smp_f4(smp->tfm_cmac, smp->remote_pk, smp->local_pk,
1423                            smp->rrnd, r, cfm))
1424                         return SMP_UNSPECIFIED;
1425
1426                 if (memcmp(smp->pcnf, cfm, 16))
1427                         return SMP_CONFIRM_FAILED;
1428
1429                 smp->passkey_round++;
1430
1431                 if (smp->passkey_round == 20) {
1432                         /* Generate MacKey and LTK */
1433                         if (sc_mackey_and_ltk(smp, smp->mackey, smp->tk))
1434                                 return SMP_UNSPECIFIED;
1435                 }
1436
1437                 /* The round is only complete when the initiator
1438                  * receives pairing random.
1439                  */
1440                 if (!hcon->out) {
1441                         smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
1442                                      sizeof(smp->prnd), smp->prnd);
1443                         if (smp->passkey_round == 20)
1444                                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1445                         else
1446                                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
1447                         return 0;
1448                 }
1449
1450                 /* Start the next round */
1451                 if (smp->passkey_round != 20)
1452                         return sc_passkey_round(smp, 0);
1453
1454                 /* Passkey rounds are complete - start DHKey Check */
1455                 sc_dhkey_check(smp);
1456                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1457
1458                 break;
1459
1460         case SMP_CMD_PAIRING_CONFIRM:
1461                 if (test_bit(SMP_FLAG_WAIT_USER, &smp->flags)) {
1462                         set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1463                         return 0;
1464                 }
1465
1466                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
1467
1468                 if (hcon->out) {
1469                         smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
1470                                      sizeof(smp->prnd), smp->prnd);
1471                         return 0;
1472                 }
1473
1474                 return sc_passkey_send_confirm(smp);
1475
1476         case SMP_CMD_PUBLIC_KEY:
1477         default:
1478                 /* Initiating device starts the round */
1479                 if (!hcon->out)
1480                         return 0;
1481
1482                 BT_DBG("%s Starting passkey round %u", hdev->name,
1483                        smp->passkey_round + 1);
1484
1485                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
1486
1487                 return sc_passkey_send_confirm(smp);
1488         }
1489
1490         return 0;
1491 }
1492
1493 static int sc_user_reply(struct smp_chan *smp, u16 mgmt_op, __le32 passkey)
1494 {
1495         struct l2cap_conn *conn = smp->conn;
1496         struct hci_conn *hcon = conn->hcon;
1497         u8 smp_op;
1498
1499         clear_bit(SMP_FLAG_WAIT_USER, &smp->flags);
1500
1501         switch (mgmt_op) {
1502         case MGMT_OP_USER_PASSKEY_NEG_REPLY:
1503                 smp_failure(smp->conn, SMP_PASSKEY_ENTRY_FAILED);
1504                 return 0;
1505         case MGMT_OP_USER_CONFIRM_NEG_REPLY:
1506                 smp_failure(smp->conn, SMP_NUMERIC_COMP_FAILED);
1507                 return 0;
1508         case MGMT_OP_USER_PASSKEY_REPLY:
1509                 hcon->passkey_notify = le32_to_cpu(passkey);
1510                 smp->passkey_round = 0;
1511
1512                 if (test_and_clear_bit(SMP_FLAG_CFM_PENDING, &smp->flags))
1513                         smp_op = SMP_CMD_PAIRING_CONFIRM;
1514                 else
1515                         smp_op = 0;
1516
1517                 if (sc_passkey_round(smp, smp_op))
1518                         return -EIO;
1519
1520                 return 0;
1521         }
1522
1523         /* Initiator sends DHKey check first */
1524         if (hcon->out) {
1525                 sc_dhkey_check(smp);
1526                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1527         } else if (test_and_clear_bit(SMP_FLAG_DHKEY_PENDING, &smp->flags)) {
1528                 sc_dhkey_check(smp);
1529                 sc_add_ltk(smp);
1530         }
1531
1532         return 0;
1533 }
1534
1535 int smp_user_confirm_reply(struct hci_conn *hcon, u16 mgmt_op, __le32 passkey)
1536 {
1537         struct l2cap_conn *conn = hcon->l2cap_data;
1538         struct l2cap_chan *chan;
1539         struct smp_chan *smp;
1540         u32 value;
1541         int err;
1542
1543         BT_DBG("");
1544
1545         if (!conn)
1546                 return -ENOTCONN;
1547
1548         chan = conn->smp;
1549         if (!chan)
1550                 return -ENOTCONN;
1551
1552         l2cap_chan_lock(chan);
1553         if (!chan->data) {
1554                 err = -ENOTCONN;
1555                 goto unlock;
1556         }
1557
1558         smp = chan->data;
1559
1560         if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1561                 err = sc_user_reply(smp, mgmt_op, passkey);
1562                 goto unlock;
1563         }
1564
1565         switch (mgmt_op) {
1566         case MGMT_OP_USER_PASSKEY_REPLY:
1567                 value = le32_to_cpu(passkey);
1568                 memset(smp->tk, 0, sizeof(smp->tk));
1569                 BT_DBG("PassKey: %d", value);
1570                 put_unaligned_le32(value, smp->tk);
1571                 /* Fall Through */
1572         case MGMT_OP_USER_CONFIRM_REPLY:
1573                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
1574                 break;
1575         case MGMT_OP_USER_PASSKEY_NEG_REPLY:
1576         case MGMT_OP_USER_CONFIRM_NEG_REPLY:
1577                 smp_failure(conn, SMP_PASSKEY_ENTRY_FAILED);
1578                 err = 0;
1579                 goto unlock;
1580         default:
1581                 smp_failure(conn, SMP_PASSKEY_ENTRY_FAILED);
1582                 err = -EOPNOTSUPP;
1583                 goto unlock;
1584         }
1585
1586         err = 0;
1587
1588         /* If it is our turn to send Pairing Confirm, do so now */
1589         if (test_bit(SMP_FLAG_CFM_PENDING, &smp->flags)) {
1590                 u8 rsp = smp_confirm(smp);
1591                 if (rsp)
1592                         smp_failure(conn, rsp);
1593         }
1594
1595 unlock:
1596         l2cap_chan_unlock(chan);
1597         return err;
1598 }
1599
1600 static void build_bredr_pairing_cmd(struct smp_chan *smp,
1601                                     struct smp_cmd_pairing *req,
1602                                     struct smp_cmd_pairing *rsp)
1603 {
1604         struct l2cap_conn *conn = smp->conn;
1605         struct hci_dev *hdev = conn->hcon->hdev;
1606         u8 local_dist = 0, remote_dist = 0;
1607
1608         if (test_bit(HCI_BONDABLE, &hdev->dev_flags)) {
1609                 local_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
1610                 remote_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
1611         }
1612
1613         if (test_bit(HCI_RPA_RESOLVING, &hdev->dev_flags))
1614                 remote_dist |= SMP_DIST_ID_KEY;
1615
1616         if (test_bit(HCI_PRIVACY, &hdev->dev_flags))
1617                 local_dist |= SMP_DIST_ID_KEY;
1618
1619         if (!rsp) {
1620                 memset(req, 0, sizeof(*req));
1621
1622                 req->init_key_dist   = local_dist;
1623                 req->resp_key_dist   = remote_dist;
1624                 req->max_key_size    = SMP_MAX_ENC_KEY_SIZE;
1625
1626                 smp->remote_key_dist = remote_dist;
1627
1628                 return;
1629         }
1630
1631         memset(rsp, 0, sizeof(*rsp));
1632
1633         rsp->max_key_size    = SMP_MAX_ENC_KEY_SIZE;
1634         rsp->init_key_dist   = req->init_key_dist & remote_dist;
1635         rsp->resp_key_dist   = req->resp_key_dist & local_dist;
1636
1637         smp->remote_key_dist = rsp->init_key_dist;
1638 }
1639
1640 static u8 smp_cmd_pairing_req(struct l2cap_conn *conn, struct sk_buff *skb)
1641 {
1642         struct smp_cmd_pairing rsp, *req = (void *) skb->data;
1643         struct l2cap_chan *chan = conn->smp;
1644         struct hci_dev *hdev = conn->hcon->hdev;
1645         struct smp_chan *smp;
1646         u8 key_size, auth, sec_level;
1647         int ret;
1648
1649         BT_DBG("conn %p", conn);
1650
1651         if (skb->len < sizeof(*req))
1652                 return SMP_INVALID_PARAMS;
1653
1654         if (conn->hcon->role != HCI_ROLE_SLAVE)
1655                 return SMP_CMD_NOTSUPP;
1656
1657         if (!chan->data)
1658                 smp = smp_chan_create(conn);
1659         else
1660                 smp = chan->data;
1661
1662         if (!smp)
1663                 return SMP_UNSPECIFIED;
1664
1665         /* We didn't start the pairing, so match remote */
1666         auth = req->auth_req & AUTH_REQ_MASK(hdev);
1667
1668         if (!test_bit(HCI_BONDABLE, &hdev->dev_flags) &&
1669             (auth & SMP_AUTH_BONDING))
1670                 return SMP_PAIRING_NOTSUPP;
1671
1672         if (test_bit(HCI_SC_ONLY, &hdev->dev_flags) && !(auth & SMP_AUTH_SC))
1673                 return SMP_AUTH_REQUIREMENTS;
1674
1675         smp->preq[0] = SMP_CMD_PAIRING_REQ;
1676         memcpy(&smp->preq[1], req, sizeof(*req));
1677         skb_pull(skb, sizeof(*req));
1678
1679         /* SMP over BR/EDR requires special treatment */
1680         if (conn->hcon->type == ACL_LINK) {
1681                 /* We must have a BR/EDR SC link */
1682                 if (!test_bit(HCI_CONN_AES_CCM, &conn->hcon->flags) &&
1683                     !test_bit(HCI_FORCE_BREDR_SMP, &hdev->dbg_flags))
1684                         return SMP_CROSS_TRANSP_NOT_ALLOWED;
1685
1686                 set_bit(SMP_FLAG_SC, &smp->flags);
1687
1688                 build_bredr_pairing_cmd(smp, req, &rsp);
1689
1690                 key_size = min(req->max_key_size, rsp.max_key_size);
1691                 if (check_enc_key_size(conn, key_size))
1692                         return SMP_ENC_KEY_SIZE;
1693
1694                 /* Clear bits which are generated but not distributed */
1695                 smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1696
1697                 smp->prsp[0] = SMP_CMD_PAIRING_RSP;
1698                 memcpy(&smp->prsp[1], &rsp, sizeof(rsp));
1699                 smp_send_cmd(conn, SMP_CMD_PAIRING_RSP, sizeof(rsp), &rsp);
1700
1701                 smp_distribute_keys(smp);
1702                 return 0;
1703         }
1704
1705         build_pairing_cmd(conn, req, &rsp, auth);
1706
1707         if (rsp.auth_req & SMP_AUTH_SC)
1708                 set_bit(SMP_FLAG_SC, &smp->flags);
1709
1710         if (conn->hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
1711                 sec_level = BT_SECURITY_MEDIUM;
1712         else
1713                 sec_level = authreq_to_seclevel(auth);
1714
1715         if (sec_level > conn->hcon->pending_sec_level)
1716                 conn->hcon->pending_sec_level = sec_level;
1717
1718         /* If we need MITM check that it can be achieved */
1719         if (conn->hcon->pending_sec_level >= BT_SECURITY_HIGH) {
1720                 u8 method;
1721
1722                 method = get_auth_method(smp, conn->hcon->io_capability,
1723                                          req->io_capability);
1724                 if (method == JUST_WORKS || method == JUST_CFM)
1725                         return SMP_AUTH_REQUIREMENTS;
1726         }
1727
1728         key_size = min(req->max_key_size, rsp.max_key_size);
1729         if (check_enc_key_size(conn, key_size))
1730                 return SMP_ENC_KEY_SIZE;
1731
1732         get_random_bytes(smp->prnd, sizeof(smp->prnd));
1733
1734         smp->prsp[0] = SMP_CMD_PAIRING_RSP;
1735         memcpy(&smp->prsp[1], &rsp, sizeof(rsp));
1736
1737         smp_send_cmd(conn, SMP_CMD_PAIRING_RSP, sizeof(rsp), &rsp);
1738
1739         clear_bit(SMP_FLAG_INITIATOR, &smp->flags);
1740
1741         if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1742                 SMP_ALLOW_CMD(smp, SMP_CMD_PUBLIC_KEY);
1743                 /* Clear bits which are generated but not distributed */
1744                 smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1745                 /* Wait for Public Key from Initiating Device */
1746                 return 0;
1747         } else {
1748                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
1749         }
1750
1751         /* Request setup of TK */
1752         ret = tk_request(conn, 0, auth, rsp.io_capability, req->io_capability);
1753         if (ret)
1754                 return SMP_UNSPECIFIED;
1755
1756         return 0;
1757 }
1758
1759 static u8 sc_send_public_key(struct smp_chan *smp)
1760 {
1761         struct hci_dev *hdev = smp->conn->hcon->hdev;
1762
1763         BT_DBG("");
1764
1765         if (test_bit(HCI_USE_DEBUG_KEYS, &hdev->dev_flags)) {
1766                 BT_DBG("Using debug keys");
1767                 memcpy(smp->local_pk, debug_pk, 64);
1768                 memcpy(smp->local_sk, debug_sk, 32);
1769                 set_bit(SMP_FLAG_DEBUG_KEY, &smp->flags);
1770         } else {
1771                 while (true) {
1772                         /* Generate local key pair for Secure Connections */
1773                         if (!ecc_make_key(smp->local_pk, smp->local_sk))
1774                                 return SMP_UNSPECIFIED;
1775
1776                         /* This is unlikely, but we need to check that
1777                          * we didn't accidentially generate a debug key.
1778                          */
1779                         if (memcmp(smp->local_sk, debug_sk, 32))
1780                                 break;
1781                 }
1782         }
1783
1784         SMP_DBG("Local Public Key X: %32phN", smp->local_pk);
1785         SMP_DBG("Local Public Key Y: %32phN", &smp->local_pk[32]);
1786         SMP_DBG("Local Private Key:  %32phN", smp->local_sk);
1787
1788         smp_send_cmd(smp->conn, SMP_CMD_PUBLIC_KEY, 64, smp->local_pk);
1789
1790         return 0;
1791 }
1792
1793 static u8 smp_cmd_pairing_rsp(struct l2cap_conn *conn, struct sk_buff *skb)
1794 {
1795         struct smp_cmd_pairing *req, *rsp = (void *) skb->data;
1796         struct l2cap_chan *chan = conn->smp;
1797         struct smp_chan *smp = chan->data;
1798         struct hci_dev *hdev = conn->hcon->hdev;
1799         u8 key_size, auth;
1800         int ret;
1801
1802         BT_DBG("conn %p", conn);
1803
1804         if (skb->len < sizeof(*rsp))
1805                 return SMP_INVALID_PARAMS;
1806
1807         if (conn->hcon->role != HCI_ROLE_MASTER)
1808                 return SMP_CMD_NOTSUPP;
1809
1810         skb_pull(skb, sizeof(*rsp));
1811
1812         req = (void *) &smp->preq[1];
1813
1814         key_size = min(req->max_key_size, rsp->max_key_size);
1815         if (check_enc_key_size(conn, key_size))
1816                 return SMP_ENC_KEY_SIZE;
1817
1818         auth = rsp->auth_req & AUTH_REQ_MASK(hdev);
1819
1820         if (test_bit(HCI_SC_ONLY, &hdev->dev_flags) && !(auth & SMP_AUTH_SC))
1821                 return SMP_AUTH_REQUIREMENTS;
1822
1823         smp->prsp[0] = SMP_CMD_PAIRING_RSP;
1824         memcpy(&smp->prsp[1], rsp, sizeof(*rsp));
1825
1826         /* Update remote key distribution in case the remote cleared
1827          * some bits that we had enabled in our request.
1828          */
1829         smp->remote_key_dist &= rsp->resp_key_dist;
1830
1831         /* For BR/EDR this means we're done and can start phase 3 */
1832         if (conn->hcon->type == ACL_LINK) {
1833                 /* Clear bits which are generated but not distributed */
1834                 smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1835                 smp_distribute_keys(smp);
1836                 return 0;
1837         }
1838
1839         if ((req->auth_req & SMP_AUTH_SC) && (auth & SMP_AUTH_SC))
1840                 set_bit(SMP_FLAG_SC, &smp->flags);
1841         else if (conn->hcon->pending_sec_level > BT_SECURITY_HIGH)
1842                 conn->hcon->pending_sec_level = BT_SECURITY_HIGH;
1843
1844         /* If we need MITM check that it can be achieved */
1845         if (conn->hcon->pending_sec_level >= BT_SECURITY_HIGH) {
1846                 u8 method;
1847
1848                 method = get_auth_method(smp, req->io_capability,
1849                                          rsp->io_capability);
1850                 if (method == JUST_WORKS || method == JUST_CFM)
1851                         return SMP_AUTH_REQUIREMENTS;
1852         }
1853
1854         get_random_bytes(smp->prnd, sizeof(smp->prnd));
1855
1856         /* Update remote key distribution in case the remote cleared
1857          * some bits that we had enabled in our request.
1858          */
1859         smp->remote_key_dist &= rsp->resp_key_dist;
1860
1861         if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1862                 /* Clear bits which are generated but not distributed */
1863                 smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1864                 SMP_ALLOW_CMD(smp, SMP_CMD_PUBLIC_KEY);
1865                 return sc_send_public_key(smp);
1866         }
1867
1868         auth |= req->auth_req;
1869
1870         ret = tk_request(conn, 0, auth, req->io_capability, rsp->io_capability);
1871         if (ret)
1872                 return SMP_UNSPECIFIED;
1873
1874         set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1875
1876         /* Can't compose response until we have been confirmed */
1877         if (test_bit(SMP_FLAG_TK_VALID, &smp->flags))
1878                 return smp_confirm(smp);
1879
1880         return 0;
1881 }
1882
1883 static u8 sc_check_confirm(struct smp_chan *smp)
1884 {
1885         struct l2cap_conn *conn = smp->conn;
1886
1887         BT_DBG("");
1888
1889         /* Public Key exchange must happen before any other steps */
1890         if (!test_bit(SMP_FLAG_REMOTE_PK, &smp->flags))
1891                 return SMP_UNSPECIFIED;
1892
1893         if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
1894                 return sc_passkey_round(smp, SMP_CMD_PAIRING_CONFIRM);
1895
1896         if (conn->hcon->out) {
1897                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
1898                              smp->prnd);
1899                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
1900         }
1901
1902         return 0;
1903 }
1904
1905 static u8 smp_cmd_pairing_confirm(struct l2cap_conn *conn, struct sk_buff *skb)
1906 {
1907         struct l2cap_chan *chan = conn->smp;
1908         struct smp_chan *smp = chan->data;
1909
1910         BT_DBG("conn %p %s", conn, conn->hcon->out ? "master" : "slave");
1911
1912         if (skb->len < sizeof(smp->pcnf))
1913                 return SMP_INVALID_PARAMS;
1914
1915         memcpy(smp->pcnf, skb->data, sizeof(smp->pcnf));
1916         skb_pull(skb, sizeof(smp->pcnf));
1917
1918         if (test_bit(SMP_FLAG_SC, &smp->flags))
1919                 return sc_check_confirm(smp);
1920
1921         if (conn->hcon->out) {
1922                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
1923                              smp->prnd);
1924                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
1925                 return 0;
1926         }
1927
1928         if (test_bit(SMP_FLAG_TK_VALID, &smp->flags))
1929                 return smp_confirm(smp);
1930         else
1931                 set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1932
1933         return 0;
1934 }
1935
1936 static u8 smp_cmd_pairing_random(struct l2cap_conn *conn, struct sk_buff *skb)
1937 {
1938         struct l2cap_chan *chan = conn->smp;
1939         struct smp_chan *smp = chan->data;
1940         struct hci_conn *hcon = conn->hcon;
1941         u8 *pkax, *pkbx, *na, *nb;
1942         u32 passkey;
1943         int err;
1944
1945         BT_DBG("conn %p", conn);
1946
1947         if (skb->len < sizeof(smp->rrnd))
1948                 return SMP_INVALID_PARAMS;
1949
1950         memcpy(smp->rrnd, skb->data, sizeof(smp->rrnd));
1951         skb_pull(skb, sizeof(smp->rrnd));
1952
1953         if (!test_bit(SMP_FLAG_SC, &smp->flags))
1954                 return smp_random(smp);
1955
1956         if (hcon->out) {
1957                 pkax = smp->local_pk;
1958                 pkbx = smp->remote_pk;
1959                 na   = smp->prnd;
1960                 nb   = smp->rrnd;
1961         } else {
1962                 pkax = smp->remote_pk;
1963                 pkbx = smp->local_pk;
1964                 na   = smp->rrnd;
1965                 nb   = smp->prnd;
1966         }
1967
1968         if (smp->method == REQ_OOB) {
1969                 if (!hcon->out)
1970                         smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
1971                                      sizeof(smp->prnd), smp->prnd);
1972                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1973                 goto mackey_and_ltk;
1974         }
1975
1976         /* Passkey entry has special treatment */
1977         if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
1978                 return sc_passkey_round(smp, SMP_CMD_PAIRING_RANDOM);
1979
1980         if (hcon->out) {
1981                 u8 cfm[16];
1982
1983                 err = smp_f4(smp->tfm_cmac, smp->remote_pk, smp->local_pk,
1984                              smp->rrnd, 0, cfm);
1985                 if (err)
1986                         return SMP_UNSPECIFIED;
1987
1988                 if (memcmp(smp->pcnf, cfm, 16))
1989                         return SMP_CONFIRM_FAILED;
1990         } else {
1991                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
1992                              smp->prnd);
1993                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1994         }
1995
1996 mackey_and_ltk:
1997         /* Generate MacKey and LTK */
1998         err = sc_mackey_and_ltk(smp, smp->mackey, smp->tk);
1999         if (err)
2000                 return SMP_UNSPECIFIED;
2001
2002         if (smp->method == JUST_WORKS || smp->method == REQ_OOB) {
2003                 if (hcon->out) {
2004                         sc_dhkey_check(smp);
2005                         SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
2006                 }
2007                 return 0;
2008         }
2009
2010         err = smp_g2(smp->tfm_cmac, pkax, pkbx, na, nb, &passkey);
2011         if (err)
2012                 return SMP_UNSPECIFIED;
2013
2014         err = mgmt_user_confirm_request(hcon->hdev, &hcon->dst, hcon->type,
2015                                         hcon->dst_type, passkey, 0);
2016         if (err)
2017                 return SMP_UNSPECIFIED;
2018
2019         set_bit(SMP_FLAG_WAIT_USER, &smp->flags);
2020
2021         return 0;
2022 }
2023
2024 static bool smp_ltk_encrypt(struct l2cap_conn *conn, u8 sec_level)
2025 {
2026         struct smp_ltk *key;
2027         struct hci_conn *hcon = conn->hcon;
2028
2029         key = hci_find_ltk(hcon->hdev, &hcon->dst, hcon->dst_type, hcon->role);
2030         if (!key)
2031                 return false;
2032
2033         if (smp_ltk_sec_level(key) < sec_level)
2034                 return false;
2035
2036         if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags))
2037                 return true;
2038
2039         hci_le_start_enc(hcon, key->ediv, key->rand, key->val);
2040         hcon->enc_key_size = key->enc_size;
2041
2042         /* We never store STKs for master role, so clear this flag */
2043         clear_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags);
2044
2045         return true;
2046 }
2047
2048 bool smp_sufficient_security(struct hci_conn *hcon, u8 sec_level,
2049                              enum smp_key_pref key_pref)
2050 {
2051         if (sec_level == BT_SECURITY_LOW)
2052                 return true;
2053
2054         /* If we're encrypted with an STK but the caller prefers using
2055          * LTK claim insufficient security. This way we allow the
2056          * connection to be re-encrypted with an LTK, even if the LTK
2057          * provides the same level of security. Only exception is if we
2058          * don't have an LTK (e.g. because of key distribution bits).
2059          */
2060         if (key_pref == SMP_USE_LTK &&
2061             test_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags) &&
2062             hci_find_ltk(hcon->hdev, &hcon->dst, hcon->dst_type, hcon->role))
2063                 return false;
2064
2065         if (hcon->sec_level >= sec_level)
2066                 return true;
2067
2068         return false;
2069 }
2070
2071 static u8 smp_cmd_security_req(struct l2cap_conn *conn, struct sk_buff *skb)
2072 {
2073         struct smp_cmd_security_req *rp = (void *) skb->data;
2074         struct smp_cmd_pairing cp;
2075         struct hci_conn *hcon = conn->hcon;
2076         struct hci_dev *hdev = hcon->hdev;
2077         struct smp_chan *smp;
2078         u8 sec_level, auth;
2079
2080         BT_DBG("conn %p", conn);
2081
2082         if (skb->len < sizeof(*rp))
2083                 return SMP_INVALID_PARAMS;
2084
2085         if (hcon->role != HCI_ROLE_MASTER)
2086                 return SMP_CMD_NOTSUPP;
2087
2088         auth = rp->auth_req & AUTH_REQ_MASK(hdev);
2089
2090         if (test_bit(HCI_SC_ONLY, &hdev->dev_flags) && !(auth & SMP_AUTH_SC))
2091                 return SMP_AUTH_REQUIREMENTS;
2092
2093         if (hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
2094                 sec_level = BT_SECURITY_MEDIUM;
2095         else
2096                 sec_level = authreq_to_seclevel(auth);
2097
2098         if (smp_sufficient_security(hcon, sec_level, SMP_USE_LTK))
2099                 return 0;
2100
2101         if (sec_level > hcon->pending_sec_level)
2102                 hcon->pending_sec_level = sec_level;
2103
2104         if (smp_ltk_encrypt(conn, hcon->pending_sec_level))
2105                 return 0;
2106
2107         smp = smp_chan_create(conn);
2108         if (!smp)
2109                 return SMP_UNSPECIFIED;
2110
2111         if (!test_bit(HCI_BONDABLE, &hcon->hdev->dev_flags) &&
2112             (auth & SMP_AUTH_BONDING))
2113                 return SMP_PAIRING_NOTSUPP;
2114
2115         skb_pull(skb, sizeof(*rp));
2116
2117         memset(&cp, 0, sizeof(cp));
2118         build_pairing_cmd(conn, &cp, NULL, auth);
2119
2120         smp->preq[0] = SMP_CMD_PAIRING_REQ;
2121         memcpy(&smp->preq[1], &cp, sizeof(cp));
2122
2123         smp_send_cmd(conn, SMP_CMD_PAIRING_REQ, sizeof(cp), &cp);
2124         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RSP);
2125
2126         return 0;
2127 }
2128
2129 int smp_conn_security(struct hci_conn *hcon, __u8 sec_level)
2130 {
2131         struct l2cap_conn *conn = hcon->l2cap_data;
2132         struct l2cap_chan *chan;
2133         struct smp_chan *smp;
2134         __u8 authreq;
2135         int ret;
2136
2137         BT_DBG("conn %p hcon %p level 0x%2.2x", conn, hcon, sec_level);
2138
2139         /* This may be NULL if there's an unexpected disconnection */
2140         if (!conn)
2141                 return 1;
2142
2143         chan = conn->smp;
2144
2145         if (!test_bit(HCI_LE_ENABLED, &hcon->hdev->dev_flags))
2146                 return 1;
2147
2148         if (smp_sufficient_security(hcon, sec_level, SMP_USE_LTK))
2149                 return 1;
2150
2151         if (sec_level > hcon->pending_sec_level)
2152                 hcon->pending_sec_level = sec_level;
2153
2154         if (hcon->role == HCI_ROLE_MASTER)
2155                 if (smp_ltk_encrypt(conn, hcon->pending_sec_level))
2156                         return 0;
2157
2158         l2cap_chan_lock(chan);
2159
2160         /* If SMP is already in progress ignore this request */
2161         if (chan->data) {
2162                 ret = 0;
2163                 goto unlock;
2164         }
2165
2166         smp = smp_chan_create(conn);
2167         if (!smp) {
2168                 ret = 1;
2169                 goto unlock;
2170         }
2171
2172         authreq = seclevel_to_authreq(sec_level);
2173
2174         if (test_bit(HCI_SC_ENABLED, &hcon->hdev->dev_flags))
2175                 authreq |= SMP_AUTH_SC;
2176
2177         /* Require MITM if IO Capability allows or the security level
2178          * requires it.
2179          */
2180         if (hcon->io_capability != HCI_IO_NO_INPUT_OUTPUT ||
2181             hcon->pending_sec_level > BT_SECURITY_MEDIUM)
2182                 authreq |= SMP_AUTH_MITM;
2183
2184         if (hcon->role == HCI_ROLE_MASTER) {
2185                 struct smp_cmd_pairing cp;
2186
2187                 build_pairing_cmd(conn, &cp, NULL, authreq);
2188                 smp->preq[0] = SMP_CMD_PAIRING_REQ;
2189                 memcpy(&smp->preq[1], &cp, sizeof(cp));
2190
2191                 smp_send_cmd(conn, SMP_CMD_PAIRING_REQ, sizeof(cp), &cp);
2192                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RSP);
2193         } else {
2194                 struct smp_cmd_security_req cp;
2195                 cp.auth_req = authreq;
2196                 smp_send_cmd(conn, SMP_CMD_SECURITY_REQ, sizeof(cp), &cp);
2197                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_REQ);
2198         }
2199
2200         set_bit(SMP_FLAG_INITIATOR, &smp->flags);
2201         ret = 0;
2202
2203 unlock:
2204         l2cap_chan_unlock(chan);
2205         return ret;
2206 }
2207
2208 static int smp_cmd_encrypt_info(struct l2cap_conn *conn, struct sk_buff *skb)
2209 {
2210         struct smp_cmd_encrypt_info *rp = (void *) skb->data;
2211         struct l2cap_chan *chan = conn->smp;
2212         struct smp_chan *smp = chan->data;
2213
2214         BT_DBG("conn %p", conn);
2215
2216         if (skb->len < sizeof(*rp))
2217                 return SMP_INVALID_PARAMS;
2218
2219         SMP_ALLOW_CMD(smp, SMP_CMD_MASTER_IDENT);
2220
2221         skb_pull(skb, sizeof(*rp));
2222
2223         memcpy(smp->tk, rp->ltk, sizeof(smp->tk));
2224
2225         return 0;
2226 }
2227
2228 static int smp_cmd_master_ident(struct l2cap_conn *conn, struct sk_buff *skb)
2229 {
2230         struct smp_cmd_master_ident *rp = (void *) skb->data;
2231         struct l2cap_chan *chan = conn->smp;
2232         struct smp_chan *smp = chan->data;
2233         struct hci_dev *hdev = conn->hcon->hdev;
2234         struct hci_conn *hcon = conn->hcon;
2235         struct smp_ltk *ltk;
2236         u8 authenticated;
2237
2238         BT_DBG("conn %p", conn);
2239
2240         if (skb->len < sizeof(*rp))
2241                 return SMP_INVALID_PARAMS;
2242
2243         /* Mark the information as received */
2244         smp->remote_key_dist &= ~SMP_DIST_ENC_KEY;
2245
2246         if (smp->remote_key_dist & SMP_DIST_ID_KEY)
2247                 SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_INFO);
2248         else if (smp->remote_key_dist & SMP_DIST_SIGN)
2249                 SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
2250
2251         skb_pull(skb, sizeof(*rp));
2252
2253         authenticated = (hcon->sec_level == BT_SECURITY_HIGH);
2254         ltk = hci_add_ltk(hdev, &hcon->dst, hcon->dst_type, SMP_LTK,
2255                           authenticated, smp->tk, smp->enc_key_size,
2256                           rp->ediv, rp->rand);
2257         smp->ltk = ltk;
2258         if (!(smp->remote_key_dist & KEY_DIST_MASK))
2259                 smp_distribute_keys(smp);
2260
2261         return 0;
2262 }
2263
2264 static int smp_cmd_ident_info(struct l2cap_conn *conn, struct sk_buff *skb)
2265 {
2266         struct smp_cmd_ident_info *info = (void *) skb->data;
2267         struct l2cap_chan *chan = conn->smp;
2268         struct smp_chan *smp = chan->data;
2269
2270         BT_DBG("");
2271
2272         if (skb->len < sizeof(*info))
2273                 return SMP_INVALID_PARAMS;
2274
2275         SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_ADDR_INFO);
2276
2277         skb_pull(skb, sizeof(*info));
2278
2279         memcpy(smp->irk, info->irk, 16);
2280
2281         return 0;
2282 }
2283
2284 static int smp_cmd_ident_addr_info(struct l2cap_conn *conn,
2285                                    struct sk_buff *skb)
2286 {
2287         struct smp_cmd_ident_addr_info *info = (void *) skb->data;
2288         struct l2cap_chan *chan = conn->smp;
2289         struct smp_chan *smp = chan->data;
2290         struct hci_conn *hcon = conn->hcon;
2291         bdaddr_t rpa;
2292
2293         BT_DBG("");
2294
2295         if (skb->len < sizeof(*info))
2296                 return SMP_INVALID_PARAMS;
2297
2298         /* Mark the information as received */
2299         smp->remote_key_dist &= ~SMP_DIST_ID_KEY;
2300
2301         if (smp->remote_key_dist & SMP_DIST_SIGN)
2302                 SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
2303
2304         skb_pull(skb, sizeof(*info));
2305
2306         /* Strictly speaking the Core Specification (4.1) allows sending
2307          * an empty address which would force us to rely on just the IRK
2308          * as "identity information". However, since such
2309          * implementations are not known of and in order to not over
2310          * complicate our implementation, simply pretend that we never
2311          * received an IRK for such a device.
2312          *
2313          * The Identity Address must also be a Static Random or Public
2314          * Address, which hci_is_identity_address() checks for.
2315          */
2316         if (!bacmp(&info->bdaddr, BDADDR_ANY) ||
2317             !hci_is_identity_address(&info->bdaddr, info->addr_type)) {
2318                 BT_ERR("Ignoring IRK with no identity address");
2319                 goto distribute;
2320         }
2321
2322         bacpy(&smp->id_addr, &info->bdaddr);
2323         smp->id_addr_type = info->addr_type;
2324
2325         if (hci_bdaddr_is_rpa(&hcon->dst, hcon->dst_type))
2326                 bacpy(&rpa, &hcon->dst);
2327         else
2328                 bacpy(&rpa, BDADDR_ANY);
2329
2330         smp->remote_irk = hci_add_irk(conn->hcon->hdev, &smp->id_addr,
2331                                       smp->id_addr_type, smp->irk, &rpa);
2332
2333 distribute:
2334         if (!(smp->remote_key_dist & KEY_DIST_MASK))
2335                 smp_distribute_keys(smp);
2336
2337         return 0;
2338 }
2339
2340 static int smp_cmd_sign_info(struct l2cap_conn *conn, struct sk_buff *skb)
2341 {
2342         struct smp_cmd_sign_info *rp = (void *) skb->data;
2343         struct l2cap_chan *chan = conn->smp;
2344         struct smp_chan *smp = chan->data;
2345         struct smp_csrk *csrk;
2346
2347         BT_DBG("conn %p", conn);
2348
2349         if (skb->len < sizeof(*rp))
2350                 return SMP_INVALID_PARAMS;
2351
2352         /* Mark the information as received */
2353         smp->remote_key_dist &= ~SMP_DIST_SIGN;
2354
2355         skb_pull(skb, sizeof(*rp));
2356
2357         csrk = kzalloc(sizeof(*csrk), GFP_KERNEL);
2358         if (csrk) {
2359                 csrk->master = 0x01;
2360                 memcpy(csrk->val, rp->csrk, sizeof(csrk->val));
2361         }
2362         smp->csrk = csrk;
2363         smp_distribute_keys(smp);
2364
2365         return 0;
2366 }
2367
2368 static u8 sc_select_method(struct smp_chan *smp)
2369 {
2370         struct l2cap_conn *conn = smp->conn;
2371         struct hci_conn *hcon = conn->hcon;
2372         struct smp_cmd_pairing *local, *remote;
2373         u8 local_mitm, remote_mitm, local_io, remote_io, method;
2374
2375         if (test_bit(SMP_FLAG_OOB, &smp->flags))
2376                 return REQ_OOB;
2377
2378         /* The preq/prsp contain the raw Pairing Request/Response PDUs
2379          * which are needed as inputs to some crypto functions. To get
2380          * the "struct smp_cmd_pairing" from them we need to skip the
2381          * first byte which contains the opcode.
2382          */
2383         if (hcon->out) {
2384                 local = (void *) &smp->preq[1];
2385                 remote = (void *) &smp->prsp[1];
2386         } else {
2387                 local = (void *) &smp->prsp[1];
2388                 remote = (void *) &smp->preq[1];
2389         }
2390
2391         local_io = local->io_capability;
2392         remote_io = remote->io_capability;
2393
2394         local_mitm = (local->auth_req & SMP_AUTH_MITM);
2395         remote_mitm = (remote->auth_req & SMP_AUTH_MITM);
2396
2397         /* If either side wants MITM, look up the method from the table,
2398          * otherwise use JUST WORKS.
2399          */
2400         if (local_mitm || remote_mitm)
2401                 method = get_auth_method(smp, local_io, remote_io);
2402         else
2403                 method = JUST_WORKS;
2404
2405         /* Don't confirm locally initiated pairing attempts */
2406         if (method == JUST_CFM && test_bit(SMP_FLAG_INITIATOR, &smp->flags))
2407                 method = JUST_WORKS;
2408
2409         return method;
2410 }
2411
2412 static int smp_cmd_public_key(struct l2cap_conn *conn, struct sk_buff *skb)
2413 {
2414         struct smp_cmd_public_key *key = (void *) skb->data;
2415         struct hci_conn *hcon = conn->hcon;
2416         struct l2cap_chan *chan = conn->smp;
2417         struct smp_chan *smp = chan->data;
2418         struct hci_dev *hdev = hcon->hdev;
2419         struct smp_cmd_pairing_confirm cfm;
2420         int err;
2421
2422         BT_DBG("conn %p", conn);
2423
2424         if (skb->len < sizeof(*key))
2425                 return SMP_INVALID_PARAMS;
2426
2427         memcpy(smp->remote_pk, key, 64);
2428
2429         /* Non-initiating device sends its public key after receiving
2430          * the key from the initiating device.
2431          */
2432         if (!hcon->out) {
2433                 err = sc_send_public_key(smp);
2434                 if (err)
2435                         return err;
2436         }
2437
2438         SMP_DBG("Remote Public Key X: %32phN", smp->remote_pk);
2439         SMP_DBG("Remote Public Key Y: %32phN", &smp->remote_pk[32]);
2440
2441         if (!ecdh_shared_secret(smp->remote_pk, smp->local_sk, smp->dhkey))
2442                 return SMP_UNSPECIFIED;
2443
2444         SMP_DBG("DHKey %32phN", smp->dhkey);
2445
2446         set_bit(SMP_FLAG_REMOTE_PK, &smp->flags);
2447
2448         smp->method = sc_select_method(smp);
2449
2450         BT_DBG("%s selected method 0x%02x", hdev->name, smp->method);
2451
2452         /* JUST_WORKS and JUST_CFM result in an unauthenticated key */
2453         if (smp->method == JUST_WORKS || smp->method == JUST_CFM)
2454                 hcon->pending_sec_level = BT_SECURITY_MEDIUM;
2455         else
2456                 hcon->pending_sec_level = BT_SECURITY_FIPS;
2457
2458         if (!memcmp(debug_pk, smp->remote_pk, 64))
2459                 set_bit(SMP_FLAG_DEBUG_KEY, &smp->flags);
2460
2461         if (smp->method == DSP_PASSKEY) {
2462                 get_random_bytes(&hcon->passkey_notify,
2463                                  sizeof(hcon->passkey_notify));
2464                 hcon->passkey_notify %= 1000000;
2465                 hcon->passkey_entered = 0;
2466                 smp->passkey_round = 0;
2467                 if (mgmt_user_passkey_notify(hdev, &hcon->dst, hcon->type,
2468                                              hcon->dst_type,
2469                                              hcon->passkey_notify,
2470                                              hcon->passkey_entered))
2471                         return SMP_UNSPECIFIED;
2472                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
2473                 return sc_passkey_round(smp, SMP_CMD_PUBLIC_KEY);
2474         }
2475
2476         if (smp->method == REQ_OOB) {
2477                 err = smp_f4(smp->tfm_cmac, smp->remote_pk, smp->remote_pk,
2478                              smp->rr, 0, cfm.confirm_val);
2479                 if (err)
2480                         return SMP_UNSPECIFIED;
2481
2482                 if (memcmp(cfm.confirm_val, smp->pcnf, 16))
2483                         return SMP_CONFIRM_FAILED;
2484
2485                 if (hcon->out)
2486                         smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
2487                                      sizeof(smp->prnd), smp->prnd);
2488
2489                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
2490
2491                 return 0;
2492         }
2493
2494         if (hcon->out)
2495                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
2496
2497         if (smp->method == REQ_PASSKEY) {
2498                 if (mgmt_user_passkey_request(hdev, &hcon->dst, hcon->type,
2499                                               hcon->dst_type))
2500                         return SMP_UNSPECIFIED;
2501                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
2502                 set_bit(SMP_FLAG_WAIT_USER, &smp->flags);
2503                 return 0;
2504         }
2505
2506         /* The Initiating device waits for the non-initiating device to
2507          * send the confirm value.
2508          */
2509         if (conn->hcon->out)
2510                 return 0;
2511
2512         err = smp_f4(smp->tfm_cmac, smp->local_pk, smp->remote_pk, smp->prnd,
2513                      0, cfm.confirm_val);
2514         if (err)
2515                 return SMP_UNSPECIFIED;
2516
2517         smp_send_cmd(conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cfm), &cfm);
2518         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
2519
2520         return 0;
2521 }
2522
2523 static int smp_cmd_dhkey_check(struct l2cap_conn *conn, struct sk_buff *skb)
2524 {
2525         struct smp_cmd_dhkey_check *check = (void *) skb->data;
2526         struct l2cap_chan *chan = conn->smp;
2527         struct hci_conn *hcon = conn->hcon;
2528         struct smp_chan *smp = chan->data;
2529         u8 a[7], b[7], *local_addr, *remote_addr;
2530         u8 io_cap[3], r[16], e[16];
2531         int err;
2532
2533         BT_DBG("conn %p", conn);
2534
2535         if (skb->len < sizeof(*check))
2536                 return SMP_INVALID_PARAMS;
2537
2538         memcpy(a, &hcon->init_addr, 6);
2539         memcpy(b, &hcon->resp_addr, 6);
2540         a[6] = hcon->init_addr_type;
2541         b[6] = hcon->resp_addr_type;
2542
2543         if (hcon->out) {
2544                 local_addr = a;
2545                 remote_addr = b;
2546                 memcpy(io_cap, &smp->prsp[1], 3);
2547         } else {
2548                 local_addr = b;
2549                 remote_addr = a;
2550                 memcpy(io_cap, &smp->preq[1], 3);
2551         }
2552
2553         memset(r, 0, sizeof(r));
2554
2555         if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
2556                 put_unaligned_le32(hcon->passkey_notify, r);
2557
2558         err = smp_f6(smp->tfm_cmac, smp->mackey, smp->rrnd, smp->prnd, r,
2559                      io_cap, remote_addr, local_addr, e);
2560         if (err)
2561                 return SMP_UNSPECIFIED;
2562
2563         if (memcmp(check->e, e, 16))
2564                 return SMP_DHKEY_CHECK_FAILED;
2565
2566         if (!hcon->out) {
2567                 if (test_bit(SMP_FLAG_WAIT_USER, &smp->flags)) {
2568                         set_bit(SMP_FLAG_DHKEY_PENDING, &smp->flags);
2569                         return 0;
2570                 }
2571
2572                 /* Slave sends DHKey check as response to master */
2573                 sc_dhkey_check(smp);
2574         }
2575
2576         sc_add_ltk(smp);
2577
2578         if (hcon->out) {
2579                 hci_le_start_enc(hcon, 0, 0, smp->tk);
2580                 hcon->enc_key_size = smp->enc_key_size;
2581         }
2582
2583         return 0;
2584 }
2585
2586 static int smp_cmd_keypress_notify(struct l2cap_conn *conn,
2587                                    struct sk_buff *skb)
2588 {
2589         struct smp_cmd_keypress_notify *kp = (void *) skb->data;
2590
2591         BT_DBG("value 0x%02x", kp->value);
2592
2593         return 0;
2594 }
2595
2596 static int smp_sig_channel(struct l2cap_chan *chan, struct sk_buff *skb)
2597 {
2598         struct l2cap_conn *conn = chan->conn;
2599         struct hci_conn *hcon = conn->hcon;
2600         struct smp_chan *smp;
2601         __u8 code, reason;
2602         int err = 0;
2603
2604         if (skb->len < 1)
2605                 return -EILSEQ;
2606
2607         if (!test_bit(HCI_LE_ENABLED, &hcon->hdev->dev_flags)) {
2608                 reason = SMP_PAIRING_NOTSUPP;
2609                 goto done;
2610         }
2611
2612         code = skb->data[0];
2613         skb_pull(skb, sizeof(code));
2614
2615         smp = chan->data;
2616
2617         if (code > SMP_CMD_MAX)
2618                 goto drop;
2619
2620         if (smp && !test_and_clear_bit(code, &smp->allow_cmd))
2621                 goto drop;
2622
2623         /* If we don't have a context the only allowed commands are
2624          * pairing request and security request.
2625          */
2626         if (!smp && code != SMP_CMD_PAIRING_REQ && code != SMP_CMD_SECURITY_REQ)
2627                 goto drop;
2628
2629         switch (code) {
2630         case SMP_CMD_PAIRING_REQ:
2631                 reason = smp_cmd_pairing_req(conn, skb);
2632                 break;
2633
2634         case SMP_CMD_PAIRING_FAIL:
2635                 smp_failure(conn, 0);
2636                 err = -EPERM;
2637                 break;
2638
2639         case SMP_CMD_PAIRING_RSP:
2640                 reason = smp_cmd_pairing_rsp(conn, skb);
2641                 break;
2642
2643         case SMP_CMD_SECURITY_REQ:
2644                 reason = smp_cmd_security_req(conn, skb);
2645                 break;
2646
2647         case SMP_CMD_PAIRING_CONFIRM:
2648                 reason = smp_cmd_pairing_confirm(conn, skb);
2649                 break;
2650
2651         case SMP_CMD_PAIRING_RANDOM:
2652                 reason = smp_cmd_pairing_random(conn, skb);
2653                 break;
2654
2655         case SMP_CMD_ENCRYPT_INFO:
2656                 reason = smp_cmd_encrypt_info(conn, skb);
2657                 break;
2658
2659         case SMP_CMD_MASTER_IDENT:
2660                 reason = smp_cmd_master_ident(conn, skb);
2661                 break;
2662
2663         case SMP_CMD_IDENT_INFO:
2664                 reason = smp_cmd_ident_info(conn, skb);
2665                 break;
2666
2667         case SMP_CMD_IDENT_ADDR_INFO:
2668                 reason = smp_cmd_ident_addr_info(conn, skb);
2669                 break;
2670
2671         case SMP_CMD_SIGN_INFO:
2672                 reason = smp_cmd_sign_info(conn, skb);
2673                 break;
2674
2675         case SMP_CMD_PUBLIC_KEY:
2676                 reason = smp_cmd_public_key(conn, skb);
2677                 break;
2678
2679         case SMP_CMD_DHKEY_CHECK:
2680                 reason = smp_cmd_dhkey_check(conn, skb);
2681                 break;
2682
2683         case SMP_CMD_KEYPRESS_NOTIFY:
2684                 reason = smp_cmd_keypress_notify(conn, skb);
2685                 break;
2686
2687         default:
2688                 BT_DBG("Unknown command code 0x%2.2x", code);
2689                 reason = SMP_CMD_NOTSUPP;
2690                 goto done;
2691         }
2692
2693 done:
2694         if (!err) {
2695                 if (reason)
2696                         smp_failure(conn, reason);
2697                 kfree_skb(skb);
2698         }
2699
2700         return err;
2701
2702 drop:
2703         BT_ERR("%s unexpected SMP command 0x%02x from %pMR", hcon->hdev->name,
2704                code, &hcon->dst);
2705         kfree_skb(skb);
2706         return 0;
2707 }
2708
2709 static void smp_teardown_cb(struct l2cap_chan *chan, int err)
2710 {
2711         struct l2cap_conn *conn = chan->conn;
2712
2713         BT_DBG("chan %p", chan);
2714
2715         if (chan->data)
2716                 smp_chan_destroy(conn);
2717
2718         conn->smp = NULL;
2719         l2cap_chan_put(chan);
2720 }
2721
2722 static void bredr_pairing(struct l2cap_chan *chan)
2723 {
2724         struct l2cap_conn *conn = chan->conn;
2725         struct hci_conn *hcon = conn->hcon;
2726         struct hci_dev *hdev = hcon->hdev;
2727         struct smp_cmd_pairing req;
2728         struct smp_chan *smp;
2729
2730         BT_DBG("chan %p", chan);
2731
2732         /* Only new pairings are interesting */
2733         if (!test_bit(HCI_CONN_NEW_LINK_KEY, &hcon->flags))
2734                 return;
2735
2736         /* Don't bother if we're not encrypted */
2737         if (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags))
2738                 return;
2739
2740         /* Only master may initiate SMP over BR/EDR */
2741         if (hcon->role != HCI_ROLE_MASTER)
2742                 return;
2743
2744         /* Secure Connections support must be enabled */
2745         if (!test_bit(HCI_SC_ENABLED, &hdev->dev_flags))
2746                 return;
2747
2748         /* BR/EDR must use Secure Connections for SMP */
2749         if (!test_bit(HCI_CONN_AES_CCM, &hcon->flags) &&
2750             !test_bit(HCI_FORCE_BREDR_SMP, &hdev->dbg_flags))
2751                 return;
2752
2753         /* If our LE support is not enabled don't do anything */
2754         if (!test_bit(HCI_LE_ENABLED, &hdev->dev_flags))
2755                 return;
2756
2757         /* Don't bother if remote LE support is not enabled */
2758         if (!lmp_host_le_capable(hcon))
2759                 return;
2760
2761         /* Remote must support SMP fixed chan for BR/EDR */
2762         if (!(conn->remote_fixed_chan & L2CAP_FC_SMP_BREDR))
2763                 return;
2764
2765         /* Don't bother if SMP is already ongoing */
2766         if (chan->data)
2767                 return;
2768
2769         smp = smp_chan_create(conn);
2770         if (!smp) {
2771                 BT_ERR("%s unable to create SMP context for BR/EDR",
2772                        hdev->name);
2773                 return;
2774         }
2775
2776         set_bit(SMP_FLAG_SC, &smp->flags);
2777
2778         BT_DBG("%s starting SMP over BR/EDR", hdev->name);
2779
2780         /* Prepare and send the BR/EDR SMP Pairing Request */
2781         build_bredr_pairing_cmd(smp, &req, NULL);
2782
2783         smp->preq[0] = SMP_CMD_PAIRING_REQ;
2784         memcpy(&smp->preq[1], &req, sizeof(req));
2785
2786         smp_send_cmd(conn, SMP_CMD_PAIRING_REQ, sizeof(req), &req);
2787         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RSP);
2788 }
2789
2790 static void smp_resume_cb(struct l2cap_chan *chan)
2791 {
2792         struct smp_chan *smp = chan->data;
2793         struct l2cap_conn *conn = chan->conn;
2794         struct hci_conn *hcon = conn->hcon;
2795
2796         BT_DBG("chan %p", chan);
2797
2798         if (hcon->type == ACL_LINK) {
2799                 bredr_pairing(chan);
2800                 return;
2801         }
2802
2803         if (!smp)
2804                 return;
2805
2806         if (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags))
2807                 return;
2808
2809         cancel_delayed_work(&smp->security_timer);
2810
2811         smp_distribute_keys(smp);
2812 }
2813
2814 static void smp_ready_cb(struct l2cap_chan *chan)
2815 {
2816         struct l2cap_conn *conn = chan->conn;
2817         struct hci_conn *hcon = conn->hcon;
2818
2819         BT_DBG("chan %p", chan);
2820
2821         conn->smp = chan;
2822         l2cap_chan_hold(chan);
2823
2824         if (hcon->type == ACL_LINK && test_bit(HCI_CONN_ENCRYPT, &hcon->flags))
2825                 bredr_pairing(chan);
2826 }
2827
2828 static int smp_recv_cb(struct l2cap_chan *chan, struct sk_buff *skb)
2829 {
2830         int err;
2831
2832         BT_DBG("chan %p", chan);
2833
2834         err = smp_sig_channel(chan, skb);
2835         if (err) {
2836                 struct smp_chan *smp = chan->data;
2837
2838                 if (smp)
2839                         cancel_delayed_work_sync(&smp->security_timer);
2840
2841                 hci_disconnect(chan->conn->hcon, HCI_ERROR_AUTH_FAILURE);
2842         }
2843
2844         return err;
2845 }
2846
2847 static struct sk_buff *smp_alloc_skb_cb(struct l2cap_chan *chan,
2848                                         unsigned long hdr_len,
2849                                         unsigned long len, int nb)
2850 {
2851         struct sk_buff *skb;
2852
2853         skb = bt_skb_alloc(hdr_len + len, GFP_KERNEL);
2854         if (!skb)
2855                 return ERR_PTR(-ENOMEM);
2856
2857         skb->priority = HCI_PRIO_MAX;
2858         bt_cb(skb)->chan = chan;
2859
2860         return skb;
2861 }
2862
2863 static const struct l2cap_ops smp_chan_ops = {
2864         .name                   = "Security Manager",
2865         .ready                  = smp_ready_cb,
2866         .recv                   = smp_recv_cb,
2867         .alloc_skb              = smp_alloc_skb_cb,
2868         .teardown               = smp_teardown_cb,
2869         .resume                 = smp_resume_cb,
2870
2871         .new_connection         = l2cap_chan_no_new_connection,
2872         .state_change           = l2cap_chan_no_state_change,
2873         .close                  = l2cap_chan_no_close,
2874         .defer                  = l2cap_chan_no_defer,
2875         .suspend                = l2cap_chan_no_suspend,
2876         .set_shutdown           = l2cap_chan_no_set_shutdown,
2877         .get_sndtimeo           = l2cap_chan_no_get_sndtimeo,
2878 #ifdef CONFIG_TIZEN_WIP
2879         .memcpy_fromiovec       = l2cap_chan_no_memcpy_fromiovec,
2880 #endif
2881 };
2882
2883 static inline struct l2cap_chan *smp_new_conn_cb(struct l2cap_chan *pchan)
2884 {
2885         struct l2cap_chan *chan;
2886
2887         BT_DBG("pchan %p", pchan);
2888
2889         chan = l2cap_chan_create();
2890         if (!chan)
2891                 return NULL;
2892
2893         chan->chan_type = pchan->chan_type;
2894         chan->ops       = &smp_chan_ops;
2895         chan->scid      = pchan->scid;
2896         chan->dcid      = chan->scid;
2897         chan->imtu      = pchan->imtu;
2898         chan->omtu      = pchan->omtu;
2899         chan->mode      = pchan->mode;
2900
2901         /* Other L2CAP channels may request SMP routines in order to
2902          * change the security level. This means that the SMP channel
2903          * lock must be considered in its own category to avoid lockdep
2904          * warnings.
2905          */
2906         atomic_set(&chan->nesting, L2CAP_NESTING_SMP);
2907
2908         BT_DBG("created chan %p", chan);
2909
2910         return chan;
2911 }
2912
2913 static const struct l2cap_ops smp_root_chan_ops = {
2914         .name                   = "Security Manager Root",
2915         .new_connection         = smp_new_conn_cb,
2916
2917         /* None of these are implemented for the root channel */
2918         .close                  = l2cap_chan_no_close,
2919         .alloc_skb              = l2cap_chan_no_alloc_skb,
2920         .recv                   = l2cap_chan_no_recv,
2921         .state_change           = l2cap_chan_no_state_change,
2922         .teardown               = l2cap_chan_no_teardown,
2923         .ready                  = l2cap_chan_no_ready,
2924         .defer                  = l2cap_chan_no_defer,
2925         .suspend                = l2cap_chan_no_suspend,
2926         .resume                 = l2cap_chan_no_resume,
2927         .set_shutdown           = l2cap_chan_no_set_shutdown,
2928         .get_sndtimeo           = l2cap_chan_no_get_sndtimeo,
2929 #ifdef CONFIG_TIZEN_WIP
2930         .memcpy_fromiovec       = l2cap_chan_no_memcpy_fromiovec,
2931 #endif
2932 };
2933
2934 static struct l2cap_chan *smp_add_cid(struct hci_dev *hdev, u16 cid)
2935 {
2936         struct l2cap_chan *chan;
2937         struct crypto_blkcipher *tfm_aes;
2938
2939         if (cid == L2CAP_CID_SMP_BREDR) {
2940                 tfm_aes = NULL;
2941                 goto create_chan;
2942         }
2943
2944         tfm_aes = crypto_alloc_blkcipher("ecb(aes)", 0, 0);
2945         if (IS_ERR(tfm_aes)) {
2946                 BT_ERR("Unable to create crypto context");
2947                 return ERR_CAST(tfm_aes);
2948         }
2949
2950 create_chan:
2951         chan = l2cap_chan_create();
2952         if (!chan) {
2953                 crypto_free_blkcipher(tfm_aes);
2954                 return ERR_PTR(-ENOMEM);
2955         }
2956
2957         chan->data = tfm_aes;
2958
2959         l2cap_add_scid(chan, cid);
2960
2961         l2cap_chan_set_defaults(chan);
2962
2963         if (cid == L2CAP_CID_SMP) {
2964                 /* If usage of static address is forced or if the devices
2965                  * does not have a public address, then listen on the static
2966                  * address.
2967                  *
2968                  * In case BR/EDR has been disabled on a dual-mode controller
2969                  * and a static address has been configued, then listen on
2970                  * the static address instead.
2971                  */
2972                 if (test_bit(HCI_FORCE_STATIC_ADDR, &hdev->dbg_flags) ||
2973                     !bacmp(&hdev->bdaddr, BDADDR_ANY) ||
2974                     (!test_bit(HCI_BREDR_ENABLED, &hdev->dev_flags) &&
2975                      bacmp(&hdev->static_addr, BDADDR_ANY))) {
2976                         bacpy(&chan->src, &hdev->static_addr);
2977                         chan->src_type = BDADDR_LE_RANDOM;
2978                 } else {
2979                         bacpy(&chan->src, &hdev->bdaddr);
2980                         chan->src_type = BDADDR_LE_PUBLIC;
2981                 }
2982         } else {
2983                 bacpy(&chan->src, &hdev->bdaddr);
2984                 chan->src_type = BDADDR_BREDR;
2985         }
2986
2987         chan->state = BT_LISTEN;
2988         chan->mode = L2CAP_MODE_BASIC;
2989         chan->imtu = L2CAP_DEFAULT_MTU;
2990         chan->ops = &smp_root_chan_ops;
2991
2992         /* Set correct nesting level for a parent/listening channel */
2993         atomic_set(&chan->nesting, L2CAP_NESTING_PARENT);
2994
2995         return chan;
2996 }
2997
2998 static void smp_del_chan(struct l2cap_chan *chan)
2999 {
3000         struct crypto_blkcipher *tfm_aes;
3001
3002         BT_DBG("chan %p", chan);
3003
3004         tfm_aes = chan->data;
3005         if (tfm_aes) {
3006                 chan->data = NULL;
3007                 crypto_free_blkcipher(tfm_aes);
3008         }
3009
3010         l2cap_chan_put(chan);
3011 }
3012
3013 static ssize_t force_bredr_smp_read(struct file *file,
3014                                     char __user *user_buf,
3015                                     size_t count, loff_t *ppos)
3016 {
3017         struct hci_dev *hdev = file->private_data;
3018         char buf[3];
3019
3020         buf[0] = test_bit(HCI_FORCE_BREDR_SMP, &hdev->dbg_flags) ? 'Y': 'N';
3021         buf[1] = '\n';
3022         buf[2] = '\0';
3023         return simple_read_from_buffer(user_buf, count, ppos, buf, 2);
3024 }
3025
3026 static ssize_t force_bredr_smp_write(struct file *file,
3027                                      const char __user *user_buf,
3028                                      size_t count, loff_t *ppos)
3029 {
3030         struct hci_dev *hdev = file->private_data;
3031         char buf[32];
3032         size_t buf_size = min(count, (sizeof(buf)-1));
3033         bool enable;
3034
3035         if (copy_from_user(buf, user_buf, buf_size))
3036                 return -EFAULT;
3037
3038         buf[buf_size] = '\0';
3039         if (strtobool(buf, &enable))
3040                 return -EINVAL;
3041
3042         if (enable == test_bit(HCI_FORCE_BREDR_SMP, &hdev->dbg_flags))
3043                 return -EALREADY;
3044
3045         if (enable) {
3046                 struct l2cap_chan *chan;
3047
3048                 chan = smp_add_cid(hdev, L2CAP_CID_SMP_BREDR);
3049                 if (IS_ERR(chan))
3050                         return PTR_ERR(chan);
3051
3052                 hdev->smp_bredr_data = chan;
3053         } else {
3054                 struct l2cap_chan *chan;
3055
3056                 chan = hdev->smp_bredr_data;
3057                 hdev->smp_bredr_data = NULL;
3058                 smp_del_chan(chan);
3059         }
3060
3061         change_bit(HCI_FORCE_BREDR_SMP, &hdev->dbg_flags);
3062
3063         return count;
3064 }
3065
3066 static const struct file_operations force_bredr_smp_fops = {
3067         .open           = simple_open,
3068         .read           = force_bredr_smp_read,
3069         .write          = force_bredr_smp_write,
3070         .llseek         = default_llseek,
3071 };
3072
3073 int smp_register(struct hci_dev *hdev)
3074 {
3075         struct l2cap_chan *chan;
3076
3077         BT_DBG("%s", hdev->name);
3078
3079         /* If the controller does not support Low Energy operation, then
3080          * there is also no need to register any SMP channel.
3081          */
3082         if (!lmp_le_capable(hdev))
3083                 return 0;
3084
3085         if (WARN_ON(hdev->smp_data)) {
3086                 chan = hdev->smp_data;
3087                 hdev->smp_data = NULL;
3088                 smp_del_chan(chan);
3089         }
3090
3091         chan = smp_add_cid(hdev, L2CAP_CID_SMP);
3092         if (IS_ERR(chan))
3093                 return PTR_ERR(chan);
3094
3095         hdev->smp_data = chan;
3096
3097         /* If the controller does not support BR/EDR Secure Connections
3098          * feature, then the BR/EDR SMP channel shall not be present.
3099          *
3100          * To test this with Bluetooth 4.0 controllers, create a debugfs
3101          * switch that allows forcing BR/EDR SMP support and accepting
3102          * cross-transport pairing on non-AES encrypted connections.
3103          */
3104         if (!lmp_sc_capable(hdev)) {
3105                 debugfs_create_file("force_bredr_smp", 0644, hdev->debugfs,
3106                                     hdev, &force_bredr_smp_fops);
3107                 return 0;
3108         }
3109
3110         if (WARN_ON(hdev->smp_bredr_data)) {
3111                 chan = hdev->smp_bredr_data;
3112                 hdev->smp_bredr_data = NULL;
3113                 smp_del_chan(chan);
3114         }
3115
3116         chan = smp_add_cid(hdev, L2CAP_CID_SMP_BREDR);
3117         if (IS_ERR(chan)) {
3118                 int err = PTR_ERR(chan);
3119                 chan = hdev->smp_data;
3120                 hdev->smp_data = NULL;
3121                 smp_del_chan(chan);
3122                 return err;
3123         }
3124
3125         hdev->smp_bredr_data = chan;
3126
3127         return 0;
3128 }
3129
3130 void smp_unregister(struct hci_dev *hdev)
3131 {
3132         struct l2cap_chan *chan;
3133
3134         if (hdev->smp_bredr_data) {
3135                 chan = hdev->smp_bredr_data;
3136                 hdev->smp_bredr_data = NULL;
3137                 smp_del_chan(chan);
3138         }
3139
3140         if (hdev->smp_data) {
3141                 chan = hdev->smp_data;
3142                 hdev->smp_data = NULL;
3143                 smp_del_chan(chan);
3144         }
3145 }
3146
3147 #if IS_ENABLED(CONFIG_BT_SELFTEST_SMP)
3148
3149 static int __init test_ah(struct crypto_blkcipher *tfm_aes)
3150 {
3151         const u8 irk[16] = {
3152                         0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
3153                         0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
3154         const u8 r[3] = { 0x94, 0x81, 0x70 };
3155         const u8 exp[3] = { 0xaa, 0xfb, 0x0d };
3156         u8 res[3];
3157         int err;
3158
3159         err = smp_ah(tfm_aes, irk, r, res);
3160         if (err)
3161                 return err;
3162
3163         if (memcmp(res, exp, 3))
3164                 return -EINVAL;
3165
3166         return 0;
3167 }
3168
3169 static int __init test_c1(struct crypto_blkcipher *tfm_aes)
3170 {
3171         const u8 k[16] = {
3172                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3173                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
3174         const u8 r[16] = {
3175                         0xe0, 0x2e, 0x70, 0xc6, 0x4e, 0x27, 0x88, 0x63,
3176                         0x0e, 0x6f, 0xad, 0x56, 0x21, 0xd5, 0x83, 0x57 };
3177         const u8 preq[7] = { 0x01, 0x01, 0x00, 0x00, 0x10, 0x07, 0x07 };
3178         const u8 pres[7] = { 0x02, 0x03, 0x00, 0x00, 0x08, 0x00, 0x05 };
3179         const u8 _iat = 0x01;
3180         const u8 _rat = 0x00;
3181         const bdaddr_t ra = { { 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1 } };
3182         const bdaddr_t ia = { { 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1 } };
3183         const u8 exp[16] = {
3184                         0x86, 0x3b, 0xf1, 0xbe, 0xc5, 0x4d, 0xa7, 0xd2,
3185                         0xea, 0x88, 0x89, 0x87, 0xef, 0x3f, 0x1e, 0x1e };
3186         u8 res[16];
3187         int err;
3188
3189         err = smp_c1(tfm_aes, k, r, preq, pres, _iat, &ia, _rat, &ra, res);
3190         if (err)
3191                 return err;
3192
3193         if (memcmp(res, exp, 16))
3194                 return -EINVAL;
3195
3196         return 0;
3197 }
3198
3199 static int __init test_s1(struct crypto_blkcipher *tfm_aes)
3200 {
3201         const u8 k[16] = {
3202                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3203                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
3204         const u8 r1[16] = {
3205                         0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 };
3206         const u8 r2[16] = {
3207                         0x00, 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99 };
3208         const u8 exp[16] = {
3209                         0x62, 0xa0, 0x6d, 0x79, 0xae, 0x16, 0x42, 0x5b,
3210                         0x9b, 0xf4, 0xb0, 0xe8, 0xf0, 0xe1, 0x1f, 0x9a };
3211         u8 res[16];
3212         int err;
3213
3214         err = smp_s1(tfm_aes, k, r1, r2, res);
3215         if (err)
3216                 return err;
3217
3218         if (memcmp(res, exp, 16))
3219                 return -EINVAL;
3220
3221         return 0;
3222 }
3223
3224 static int __init test_f4(struct crypto_hash *tfm_cmac)
3225 {
3226         const u8 u[32] = {
3227                         0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
3228                         0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
3229                         0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
3230                         0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 };
3231         const u8 v[32] = {
3232                         0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b,
3233                         0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59,
3234                         0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90,
3235                         0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 };
3236         const u8 x[16] = {
3237                         0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
3238                         0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
3239         const u8 z = 0x00;
3240         const u8 exp[16] = {
3241                         0x2d, 0x87, 0x74, 0xa9, 0xbe, 0xa1, 0xed, 0xf1,
3242                         0x1c, 0xbd, 0xa9, 0x07, 0xf1, 0x16, 0xc9, 0xf2 };
3243         u8 res[16];
3244         int err;
3245
3246         err = smp_f4(tfm_cmac, u, v, x, z, res);
3247         if (err)
3248                 return err;
3249
3250         if (memcmp(res, exp, 16))
3251                 return -EINVAL;
3252
3253         return 0;
3254 }
3255
3256 static int __init test_f5(struct crypto_hash *tfm_cmac)
3257 {
3258         const u8 w[32] = {
3259                         0x98, 0xa6, 0xbf, 0x73, 0xf3, 0x34, 0x8d, 0x86,
3260                         0xf1, 0x66, 0xf8, 0xb4, 0x13, 0x6b, 0x79, 0x99,
3261                         0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
3262                         0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
3263         const u8 n1[16] = {
3264                         0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
3265                         0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
3266         const u8 n2[16] = {
3267                         0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
3268                         0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
3269         const u8 a1[7] = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56, 0x00 };
3270         const u8 a2[7] = { 0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7, 0x00 };
3271         const u8 exp_ltk[16] = {
3272                         0x38, 0x0a, 0x75, 0x94, 0xb5, 0x22, 0x05, 0x98,
3273                         0x23, 0xcd, 0xd7, 0x69, 0x11, 0x79, 0x86, 0x69 };
3274         const u8 exp_mackey[16] = {
3275                         0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, 0xfd,
3276                         0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, 0x65, 0x29 };
3277         u8 mackey[16], ltk[16];
3278         int err;
3279
3280         err = smp_f5(tfm_cmac, w, n1, n2, a1, a2, mackey, ltk);
3281         if (err)
3282                 return err;
3283
3284         if (memcmp(mackey, exp_mackey, 16))
3285                 return -EINVAL;
3286
3287         if (memcmp(ltk, exp_ltk, 16))
3288                 return -EINVAL;
3289
3290         return 0;
3291 }
3292
3293 static int __init test_f6(struct crypto_hash *tfm_cmac)
3294 {
3295         const u8 w[16] = {
3296                         0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, 0xfd,
3297                         0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, 0x65, 0x29 };
3298         const u8 n1[16] = {
3299                         0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
3300                         0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
3301         const u8 n2[16] = {
3302                         0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
3303                         0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
3304         const u8 r[16] = {
3305                         0xc8, 0x0f, 0x2d, 0x0c, 0xd2, 0x42, 0xda, 0x08,
3306                         0x54, 0xbb, 0x53, 0xb4, 0x3b, 0x34, 0xa3, 0x12 };
3307         const u8 io_cap[3] = { 0x02, 0x01, 0x01 };
3308         const u8 a1[7] = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56, 0x00 };
3309         const u8 a2[7] = { 0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7, 0x00 };
3310         const u8 exp[16] = {
3311                         0x61, 0x8f, 0x95, 0xda, 0x09, 0x0b, 0x6c, 0xd2,
3312                         0xc5, 0xe8, 0xd0, 0x9c, 0x98, 0x73, 0xc4, 0xe3 };
3313         u8 res[16];
3314         int err;
3315
3316         err = smp_f6(tfm_cmac, w, n1, n2, r, io_cap, a1, a2, res);
3317         if (err)
3318                 return err;
3319
3320         if (memcmp(res, exp, 16))
3321                 return -EINVAL;
3322
3323         return 0;
3324 }
3325
3326 static int __init test_g2(struct crypto_hash *tfm_cmac)
3327 {
3328         const u8 u[32] = {
3329                         0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
3330                         0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
3331                         0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
3332                         0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 };
3333         const u8 v[32] = {
3334                         0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b,
3335                         0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59,
3336                         0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90,
3337                         0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 };
3338         const u8 x[16] = {
3339                         0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff,
3340                         0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 };
3341         const u8 y[16] = {
3342                         0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21,
3343                         0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 };
3344         const u32 exp_val = 0x2f9ed5ba % 1000000;
3345         u32 val;
3346         int err;
3347
3348         err = smp_g2(tfm_cmac, u, v, x, y, &val);
3349         if (err)
3350                 return err;
3351
3352         if (val != exp_val)
3353                 return -EINVAL;
3354
3355         return 0;
3356 }
3357
3358 static int __init test_h6(struct crypto_hash *tfm_cmac)
3359 {
3360         const u8 w[16] = {
3361                         0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34,
3362                         0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec };
3363         const u8 key_id[4] = { 0x72, 0x62, 0x65, 0x6c };
3364         const u8 exp[16] = {
3365                         0x99, 0x63, 0xb1, 0x80, 0xe2, 0xa9, 0xd3, 0xe8,
3366                         0x1c, 0xc9, 0x6d, 0xe7, 0x02, 0xe1, 0x9a, 0x2d };
3367         u8 res[16];
3368         int err;
3369
3370         err = smp_h6(tfm_cmac, w, key_id, res);
3371         if (err)
3372                 return err;
3373
3374         if (memcmp(res, exp, 16))
3375                 return -EINVAL;
3376
3377         return 0;
3378 }
3379
3380 static int __init run_selftests(struct crypto_blkcipher *tfm_aes,
3381                                 struct crypto_hash *tfm_cmac)
3382 {
3383         ktime_t calltime, delta, rettime;
3384         unsigned long long duration;
3385         int err;
3386
3387         calltime = ktime_get();
3388
3389         err = test_ah(tfm_aes);
3390         if (err) {
3391                 BT_ERR("smp_ah test failed");
3392                 return err;
3393         }
3394
3395         err = test_c1(tfm_aes);
3396         if (err) {
3397                 BT_ERR("smp_c1 test failed");
3398                 return err;
3399         }
3400
3401         err = test_s1(tfm_aes);
3402         if (err) {
3403                 BT_ERR("smp_s1 test failed");
3404                 return err;
3405         }
3406
3407         err = test_f4(tfm_cmac);
3408         if (err) {
3409                 BT_ERR("smp_f4 test failed");
3410                 return err;
3411         }
3412
3413         err = test_f5(tfm_cmac);
3414         if (err) {
3415                 BT_ERR("smp_f5 test failed");
3416                 return err;
3417         }
3418
3419         err = test_f6(tfm_cmac);
3420         if (err) {
3421                 BT_ERR("smp_f6 test failed");
3422                 return err;
3423         }
3424
3425         err = test_g2(tfm_cmac);
3426         if (err) {
3427                 BT_ERR("smp_g2 test failed");
3428                 return err;
3429         }
3430
3431         err = test_h6(tfm_cmac);
3432         if (err) {
3433                 BT_ERR("smp_h6 test failed");
3434                 return err;
3435         }
3436
3437         rettime = ktime_get();
3438         delta = ktime_sub(rettime, calltime);
3439         duration = (unsigned long long) ktime_to_ns(delta) >> 10;
3440
3441         BT_INFO("SMP test passed in %llu usecs", duration);
3442
3443         return 0;
3444 }
3445
3446 int __init bt_selftest_smp(void)
3447 {
3448         struct crypto_blkcipher *tfm_aes;
3449         struct crypto_hash *tfm_cmac;
3450         int err;
3451
3452         tfm_aes = crypto_alloc_blkcipher("ecb(aes)", 0, CRYPTO_ALG_ASYNC);
3453         if (IS_ERR(tfm_aes)) {
3454                 BT_ERR("Unable to create ECB crypto context");
3455                 return PTR_ERR(tfm_aes);
3456         }
3457
3458         tfm_cmac = crypto_alloc_hash("cmac(aes)", 0, CRYPTO_ALG_ASYNC);
3459         if (IS_ERR(tfm_cmac)) {
3460                 BT_ERR("Unable to create CMAC crypto context");
3461                 crypto_free_blkcipher(tfm_aes);
3462                 return PTR_ERR(tfm_cmac);
3463         }
3464
3465         err = run_selftests(tfm_aes, tfm_cmac);
3466
3467         crypto_free_hash(tfm_cmac);
3468         crypto_free_blkcipher(tfm_aes);
3469
3470         return err;
3471 }
3472
3473 #endif