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