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