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