Bluetooth: Add passkey entry support for LE SC
[cascardo/linux.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/crypto.h>
24 #include <linux/scatterlist.h>
25 #include <crypto/b128ops.h>
26
27 #include <net/bluetooth/bluetooth.h>
28 #include <net/bluetooth/hci_core.h>
29 #include <net/bluetooth/l2cap.h>
30 #include <net/bluetooth/mgmt.h>
31
32 #include "ecc.h"
33 #include "smp.h"
34
35 #define SMP_ALLOW_CMD(smp, code)        set_bit(code, &smp->allow_cmd)
36
37 /* Keys which are not distributed with Secure Connections */
38 #define SMP_SC_NO_DIST (SMP_DIST_ENC_KEY | SMP_DIST_LINK_KEY);
39
40 #define SMP_TIMEOUT     msecs_to_jiffies(30000)
41
42 #define AUTH_REQ_MASK(dev)      (test_bit(HCI_SC_ENABLED, &(dev)->dev_flags) ? \
43                                  0x1f : 0x07)
44 #define KEY_DIST_MASK           0x07
45
46 /* Maximum message length that can be passed to aes_cmac */
47 #define CMAC_MSG_MAX    80
48
49 enum {
50         SMP_FLAG_TK_VALID,
51         SMP_FLAG_CFM_PENDING,
52         SMP_FLAG_MITM_AUTH,
53         SMP_FLAG_COMPLETE,
54         SMP_FLAG_INITIATOR,
55         SMP_FLAG_SC,
56         SMP_FLAG_REMOTE_PK,
57         SMP_FLAG_DEBUG_KEY,
58         SMP_FLAG_WAIT_USER,
59 };
60
61 struct smp_chan {
62         struct l2cap_conn       *conn;
63         struct delayed_work     security_timer;
64         unsigned long           allow_cmd; /* Bitmask of allowed commands */
65
66         u8              preq[7]; /* SMP Pairing Request */
67         u8              prsp[7]; /* SMP Pairing Response */
68         u8              prnd[16]; /* SMP Pairing Random (local) */
69         u8              rrnd[16]; /* SMP Pairing Random (remote) */
70         u8              pcnf[16]; /* SMP Pairing Confirm */
71         u8              tk[16]; /* SMP Temporary Key */
72         u8              enc_key_size;
73         u8              remote_key_dist;
74         bdaddr_t        id_addr;
75         u8              id_addr_type;
76         u8              irk[16];
77         struct smp_csrk *csrk;
78         struct smp_csrk *slave_csrk;
79         struct smp_ltk  *ltk;
80         struct smp_ltk  *slave_ltk;
81         struct smp_irk  *remote_irk;
82         u8              *link_key;
83         unsigned long   flags;
84         u8              method;
85         u8              passkey_round;
86
87         /* Secure Connections variables */
88         u8                      local_pk[64];
89         u8                      local_sk[32];
90         u8                      remote_pk[64];
91         u8                      dhkey[32];
92         u8                      mackey[16];
93
94         struct crypto_blkcipher *tfm_aes;
95         struct crypto_hash      *tfm_cmac;
96 };
97
98 /* These debug key values are defined in the SMP section of the core
99  * specification. debug_pk is the public debug key and debug_sk the
100  * private debug key.
101  */
102 static const u8 debug_pk[64] = {
103                 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc,
104                 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef,
105                 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
106                 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20,
107
108                 0x8b, 0xd2, 0x89, 0x15, 0xd0, 0x8e, 0x1c, 0x74,
109                 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76,
110                 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63,
111                 0x6d, 0xeb, 0x2a, 0x65, 0x49, 0x9c, 0x80, 0xdc,
112 };
113
114 static const u8 debug_sk[32] = {
115                 0xbd, 0x1a, 0x3c, 0xcd, 0xa6, 0xb8, 0x99, 0x58,
116                 0x99, 0xb7, 0x40, 0xeb, 0x7b, 0x60, 0xff, 0x4a,
117                 0x50, 0x3f, 0x10, 0xd2, 0xe3, 0xb3, 0xc9, 0x74,
118                 0x38, 0x5f, 0xc5, 0xa3, 0xd4, 0xf6, 0x49, 0x3f,
119 };
120
121 static inline void swap_buf(const u8 *src, u8 *dst, size_t len)
122 {
123         size_t i;
124
125         for (i = 0; i < len; i++)
126                 dst[len - 1 - i] = src[i];
127 }
128
129 static int aes_cmac(struct crypto_hash *tfm, const u8 k[16], const u8 *m,
130                     size_t len, u8 mac[16])
131 {
132         uint8_t tmp[16], mac_msb[16], msg_msb[CMAC_MSG_MAX];
133         struct hash_desc desc;
134         struct scatterlist sg;
135         int err;
136
137         if (len > CMAC_MSG_MAX)
138                 return -EFBIG;
139
140         if (!tfm) {
141                 BT_ERR("tfm %p", tfm);
142                 return -EINVAL;
143         }
144
145         desc.tfm = tfm;
146         desc.flags = 0;
147
148         crypto_hash_init(&desc);
149
150         /* Swap key and message from LSB to MSB */
151         swap_buf(k, tmp, 16);
152         swap_buf(m, msg_msb, len);
153
154         BT_DBG("msg (len %zu) %*phN", len, (int) len, m);
155         BT_DBG("key %16phN", k);
156
157         err = crypto_hash_setkey(tfm, tmp, 16);
158         if (err) {
159                 BT_ERR("cipher setkey failed: %d", err);
160                 return err;
161         }
162
163         sg_init_one(&sg, msg_msb, len);
164
165         err = crypto_hash_update(&desc, &sg, len);
166         if (err) {
167                 BT_ERR("Hash update error %d", err);
168                 return err;
169         }
170
171         err = crypto_hash_final(&desc, mac_msb);
172         if (err) {
173                 BT_ERR("Hash final error %d", err);
174                 return err;
175         }
176
177         swap_buf(mac_msb, mac, 16);
178
179         BT_DBG("mac %16phN", mac);
180
181         return 0;
182 }
183
184 static int smp_f4(struct crypto_hash *tfm_cmac, const u8 u[32], const u8 v[32],
185                   const u8 x[16], u8 z, u8 res[16])
186 {
187         u8 m[65];
188         int err;
189
190         BT_DBG("u %32phN", u);
191         BT_DBG("v %32phN", v);
192         BT_DBG("x %16phN z %02x", x, z);
193
194         m[0] = z;
195         memcpy(m + 1, v, 32);
196         memcpy(m + 33, u, 32);
197
198         err = aes_cmac(tfm_cmac, x, m, sizeof(m), res);
199         if (err)
200                 return err;
201
202         BT_DBG("res %16phN", res);
203
204         return err;
205 }
206
207 static int smp_f5(struct crypto_hash *tfm_cmac, u8 w[32], u8 n1[16], u8 n2[16],
208                   u8 a1[7], u8 a2[7], u8 mackey[16], u8 ltk[16])
209 {
210         /* The btle, salt and length "magic" values are as defined in
211          * the SMP section of the Bluetooth core specification. In ASCII
212          * the btle value ends up being 'btle'. The salt is just a
213          * random number whereas length is the value 256 in little
214          * endian format.
215          */
216         const u8 btle[4] = { 0x65, 0x6c, 0x74, 0x62 };
217         const u8 salt[16] = { 0xbe, 0x83, 0x60, 0x5a, 0xdb, 0x0b, 0x37, 0x60,
218                               0x38, 0xa5, 0xf5, 0xaa, 0x91, 0x83, 0x88, 0x6c };
219         const u8 length[2] = { 0x00, 0x01 };
220         u8 m[53], t[16];
221         int err;
222
223         BT_DBG("w %32phN", w);
224         BT_DBG("n1 %16phN n2 %16phN", n1, n2);
225         BT_DBG("a1 %7phN a2 %7phN", a1, a2);
226
227         err = aes_cmac(tfm_cmac, salt, w, 32, t);
228         if (err)
229                 return err;
230
231         BT_DBG("t %16phN", t);
232
233         memcpy(m, length, 2);
234         memcpy(m + 2, a2, 7);
235         memcpy(m + 9, a1, 7);
236         memcpy(m + 16, n2, 16);
237         memcpy(m + 32, n1, 16);
238         memcpy(m + 48, btle, 4);
239
240         m[52] = 0; /* Counter */
241
242         err = aes_cmac(tfm_cmac, t, m, sizeof(m), mackey);
243         if (err)
244                 return err;
245
246         BT_DBG("mackey %16phN", mackey);
247
248         m[52] = 1; /* Counter */
249
250         err = aes_cmac(tfm_cmac, t, m, sizeof(m), ltk);
251         if (err)
252                 return err;
253
254         BT_DBG("ltk %16phN", ltk);
255
256         return 0;
257 }
258
259 static int smp_f6(struct crypto_hash *tfm_cmac, const u8 w[16],
260                   const u8 n1[16], u8 n2[16], const u8 r[16],
261                   const u8 io_cap[3], const u8 a1[7], const u8 a2[7],
262                   u8 res[16])
263 {
264         u8 m[65];
265         int err;
266
267         BT_DBG("w %16phN", w);
268         BT_DBG("n1 %16phN n2 %16phN", n1, n2);
269         BT_DBG("r %16phN io_cap %3phN a1 %7phN a2 %7phN", r, io_cap, a1, a2);
270
271         memcpy(m, a2, 7);
272         memcpy(m + 7, a1, 7);
273         memcpy(m + 14, io_cap, 3);
274         memcpy(m + 17, r, 16);
275         memcpy(m + 33, n2, 16);
276         memcpy(m + 49, n1, 16);
277
278         err = aes_cmac(tfm_cmac, w, m, sizeof(m), res);
279         if (err)
280                 return err;
281
282         BT_DBG("res %16phN", res);
283
284         return err;
285 }
286
287 static int smp_g2(struct crypto_hash *tfm_cmac, const u8 u[32], const u8 v[32],
288                   const u8 x[16], const u8 y[16], u32 *val)
289 {
290         u8 m[80], tmp[16];
291         int err;
292
293         BT_DBG("u %32phN", u);
294         BT_DBG("v %32phN", v);
295         BT_DBG("x %16phN y %16phN", x, y);
296
297         memcpy(m, y, 16);
298         memcpy(m + 16, v, 32);
299         memcpy(m + 48, u, 32);
300
301         err = aes_cmac(tfm_cmac, x, m, sizeof(m), tmp);
302         if (err)
303                 return err;
304
305         *val = get_unaligned_le32(tmp);
306         *val %= 1000000;
307
308         BT_DBG("val %06u", *val);
309
310         return 0;
311 }
312
313 static int smp_e(struct crypto_blkcipher *tfm, const u8 *k, u8 *r)
314 {
315         struct blkcipher_desc desc;
316         struct scatterlist sg;
317         uint8_t tmp[16], data[16];
318         int err;
319
320         if (tfm == NULL) {
321                 BT_ERR("tfm %p", tfm);
322                 return -EINVAL;
323         }
324
325         desc.tfm = tfm;
326         desc.flags = 0;
327
328         /* The most significant octet of key corresponds to k[0] */
329         swap_buf(k, tmp, 16);
330
331         err = crypto_blkcipher_setkey(tfm, tmp, 16);
332         if (err) {
333                 BT_ERR("cipher setkey failed: %d", err);
334                 return err;
335         }
336
337         /* Most significant octet of plaintextData corresponds to data[0] */
338         swap_buf(r, data, 16);
339
340         sg_init_one(&sg, data, 16);
341
342         err = crypto_blkcipher_encrypt(&desc, &sg, &sg, 16);
343         if (err)
344                 BT_ERR("Encrypt data error %d", err);
345
346         /* Most significant octet of encryptedData corresponds to data[0] */
347         swap_buf(data, r, 16);
348
349         return err;
350 }
351
352 static int smp_h6(struct crypto_hash *tfm_cmac, const u8 w[16],
353                   const u8 key_id[4], u8 res[16])
354 {
355         int err;
356
357         BT_DBG("w %16phN key_id %4phN", w, key_id);
358
359         err = aes_cmac(tfm_cmac, w, key_id, 4, res);
360         if (err)
361                 return err;
362
363         BT_DBG("res %16phN", res);
364
365         return err;
366 }
367
368 static int smp_ah(struct crypto_blkcipher *tfm, u8 irk[16], u8 r[3], u8 res[3])
369 {
370         u8 _res[16];
371         int err;
372
373         /* r' = padding || r */
374         memcpy(_res, r, 3);
375         memset(_res + 3, 0, 13);
376
377         err = smp_e(tfm, irk, _res);
378         if (err) {
379                 BT_ERR("Encrypt error");
380                 return err;
381         }
382
383         /* The output of the random address function ah is:
384          *      ah(h, r) = e(k, r') mod 2^24
385          * The output of the security function e is then truncated to 24 bits
386          * by taking the least significant 24 bits of the output of e as the
387          * result of ah.
388          */
389         memcpy(res, _res, 3);
390
391         return 0;
392 }
393
394 bool smp_irk_matches(struct hci_dev *hdev, u8 irk[16], bdaddr_t *bdaddr)
395 {
396         struct l2cap_chan *chan = hdev->smp_data;
397         struct crypto_blkcipher *tfm;
398         u8 hash[3];
399         int err;
400
401         if (!chan || !chan->data)
402                 return false;
403
404         tfm = chan->data;
405
406         BT_DBG("RPA %pMR IRK %*phN", bdaddr, 16, irk);
407
408         err = smp_ah(tfm, irk, &bdaddr->b[3], hash);
409         if (err)
410                 return false;
411
412         return !memcmp(bdaddr->b, hash, 3);
413 }
414
415 int smp_generate_rpa(struct hci_dev *hdev, u8 irk[16], bdaddr_t *rpa)
416 {
417         struct l2cap_chan *chan = hdev->smp_data;
418         struct crypto_blkcipher *tfm;
419         int err;
420
421         if (!chan || !chan->data)
422                 return -EOPNOTSUPP;
423
424         tfm = chan->data;
425
426         get_random_bytes(&rpa->b[3], 3);
427
428         rpa->b[5] &= 0x3f;      /* Clear two most significant bits */
429         rpa->b[5] |= 0x40;      /* Set second most significant bit */
430
431         err = smp_ah(tfm, irk, &rpa->b[3], rpa->b);
432         if (err < 0)
433                 return err;
434
435         BT_DBG("RPA %pMR", rpa);
436
437         return 0;
438 }
439
440 static int smp_c1(struct crypto_blkcipher *tfm_aes, u8 k[16], u8 r[16],
441                   u8 preq[7], u8 pres[7], u8 _iat, bdaddr_t *ia, u8 _rat,
442                   bdaddr_t *ra, u8 res[16])
443 {
444         u8 p1[16], p2[16];
445         int err;
446
447         memset(p1, 0, 16);
448
449         /* p1 = pres || preq || _rat || _iat */
450         p1[0] = _iat;
451         p1[1] = _rat;
452         memcpy(p1 + 2, preq, 7);
453         memcpy(p1 + 9, pres, 7);
454
455         /* p2 = padding || ia || ra */
456         memcpy(p2, ra, 6);
457         memcpy(p2 + 6, ia, 6);
458         memset(p2 + 12, 0, 4);
459
460         /* res = r XOR p1 */
461         u128_xor((u128 *) res, (u128 *) r, (u128 *) p1);
462
463         /* res = e(k, res) */
464         err = smp_e(tfm_aes, k, res);
465         if (err) {
466                 BT_ERR("Encrypt data error");
467                 return err;
468         }
469
470         /* res = res XOR p2 */
471         u128_xor((u128 *) res, (u128 *) res, (u128 *) p2);
472
473         /* res = e(k, res) */
474         err = smp_e(tfm_aes, k, res);
475         if (err)
476                 BT_ERR("Encrypt data error");
477
478         return err;
479 }
480
481 static int smp_s1(struct crypto_blkcipher *tfm_aes, u8 k[16], u8 r1[16],
482                   u8 r2[16], u8 _r[16])
483 {
484         int err;
485
486         /* Just least significant octets from r1 and r2 are considered */
487         memcpy(_r, r2, 8);
488         memcpy(_r + 8, r1, 8);
489
490         err = smp_e(tfm_aes, k, _r);
491         if (err)
492                 BT_ERR("Encrypt data error");
493
494         return err;
495 }
496
497 static void smp_send_cmd(struct l2cap_conn *conn, u8 code, u16 len, void *data)
498 {
499         struct l2cap_chan *chan = conn->smp;
500         struct smp_chan *smp;
501         struct kvec iv[2];
502         struct msghdr msg;
503
504         if (!chan)
505                 return;
506
507         BT_DBG("code 0x%2.2x", code);
508
509         iv[0].iov_base = &code;
510         iv[0].iov_len = 1;
511
512         iv[1].iov_base = data;
513         iv[1].iov_len = len;
514
515         memset(&msg, 0, sizeof(msg));
516
517         msg.msg_iov = (struct iovec *) &iv;
518         msg.msg_iovlen = 2;
519
520         l2cap_chan_send(chan, &msg, 1 + len);
521
522         if (!chan->data)
523                 return;
524
525         smp = chan->data;
526
527         cancel_delayed_work_sync(&smp->security_timer);
528         schedule_delayed_work(&smp->security_timer, SMP_TIMEOUT);
529 }
530
531 static u8 authreq_to_seclevel(u8 authreq)
532 {
533         if (authreq & SMP_AUTH_MITM) {
534                 if (authreq & SMP_AUTH_SC)
535                         return BT_SECURITY_FIPS;
536                 else
537                         return BT_SECURITY_HIGH;
538         } else {
539                 return BT_SECURITY_MEDIUM;
540         }
541 }
542
543 static __u8 seclevel_to_authreq(__u8 sec_level)
544 {
545         switch (sec_level) {
546         case BT_SECURITY_FIPS:
547         case BT_SECURITY_HIGH:
548                 return SMP_AUTH_MITM | SMP_AUTH_BONDING;
549         case BT_SECURITY_MEDIUM:
550                 return SMP_AUTH_BONDING;
551         default:
552                 return SMP_AUTH_NONE;
553         }
554 }
555
556 static void build_pairing_cmd(struct l2cap_conn *conn,
557                               struct smp_cmd_pairing *req,
558                               struct smp_cmd_pairing *rsp, __u8 authreq)
559 {
560         struct l2cap_chan *chan = conn->smp;
561         struct smp_chan *smp = chan->data;
562         struct hci_conn *hcon = conn->hcon;
563         struct hci_dev *hdev = hcon->hdev;
564         u8 local_dist = 0, remote_dist = 0;
565
566         if (test_bit(HCI_BONDABLE, &conn->hcon->hdev->dev_flags)) {
567                 local_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
568                 remote_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
569                 authreq |= SMP_AUTH_BONDING;
570         } else {
571                 authreq &= ~SMP_AUTH_BONDING;
572         }
573
574         if (test_bit(HCI_RPA_RESOLVING, &hdev->dev_flags))
575                 remote_dist |= SMP_DIST_ID_KEY;
576
577         if (test_bit(HCI_PRIVACY, &hdev->dev_flags))
578                 local_dist |= SMP_DIST_ID_KEY;
579
580         if (test_bit(HCI_SC_ENABLED, &hdev->dev_flags)) {
581                 if ((authreq & SMP_AUTH_SC) &&
582                     test_bit(HCI_SSP_ENABLED, &hdev->dev_flags)) {
583                         local_dist |= SMP_DIST_LINK_KEY;
584                         remote_dist |= SMP_DIST_LINK_KEY;
585                 }
586         } else {
587                 authreq &= ~SMP_AUTH_SC;
588         }
589
590         if (rsp == NULL) {
591                 req->io_capability = conn->hcon->io_capability;
592                 req->oob_flag = SMP_OOB_NOT_PRESENT;
593                 req->max_key_size = SMP_MAX_ENC_KEY_SIZE;
594                 req->init_key_dist = local_dist;
595                 req->resp_key_dist = remote_dist;
596                 req->auth_req = (authreq & AUTH_REQ_MASK(hdev));
597
598                 smp->remote_key_dist = remote_dist;
599                 return;
600         }
601
602         rsp->io_capability = conn->hcon->io_capability;
603         rsp->oob_flag = SMP_OOB_NOT_PRESENT;
604         rsp->max_key_size = SMP_MAX_ENC_KEY_SIZE;
605         rsp->init_key_dist = req->init_key_dist & remote_dist;
606         rsp->resp_key_dist = req->resp_key_dist & local_dist;
607         rsp->auth_req = (authreq & AUTH_REQ_MASK(hdev));
608
609         smp->remote_key_dist = rsp->init_key_dist;
610 }
611
612 static u8 check_enc_key_size(struct l2cap_conn *conn, __u8 max_key_size)
613 {
614         struct l2cap_chan *chan = conn->smp;
615         struct smp_chan *smp = chan->data;
616
617         if ((max_key_size > SMP_MAX_ENC_KEY_SIZE) ||
618             (max_key_size < SMP_MIN_ENC_KEY_SIZE))
619                 return SMP_ENC_KEY_SIZE;
620
621         smp->enc_key_size = max_key_size;
622
623         return 0;
624 }
625
626 static void smp_chan_destroy(struct l2cap_conn *conn)
627 {
628         struct l2cap_chan *chan = conn->smp;
629         struct smp_chan *smp = chan->data;
630         bool complete;
631
632         BUG_ON(!smp);
633
634         cancel_delayed_work_sync(&smp->security_timer);
635
636         complete = test_bit(SMP_FLAG_COMPLETE, &smp->flags);
637         mgmt_smp_complete(conn->hcon, complete);
638
639         kfree(smp->csrk);
640         kfree(smp->slave_csrk);
641         kfree(smp->link_key);
642
643         crypto_free_blkcipher(smp->tfm_aes);
644         crypto_free_hash(smp->tfm_cmac);
645
646         /* If pairing failed clean up any keys we might have */
647         if (!complete) {
648                 if (smp->ltk) {
649                         list_del_rcu(&smp->ltk->list);
650                         kfree_rcu(smp->ltk, rcu);
651                 }
652
653                 if (smp->slave_ltk) {
654                         list_del_rcu(&smp->slave_ltk->list);
655                         kfree_rcu(smp->slave_ltk, rcu);
656                 }
657
658                 if (smp->remote_irk) {
659                         list_del_rcu(&smp->remote_irk->list);
660                         kfree_rcu(smp->remote_irk, rcu);
661                 }
662         }
663
664         chan->data = NULL;
665         kfree(smp);
666         hci_conn_drop(conn->hcon);
667 }
668
669 static void smp_failure(struct l2cap_conn *conn, u8 reason)
670 {
671         struct hci_conn *hcon = conn->hcon;
672         struct l2cap_chan *chan = conn->smp;
673
674         if (reason)
675                 smp_send_cmd(conn, SMP_CMD_PAIRING_FAIL, sizeof(reason),
676                              &reason);
677
678         clear_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags);
679         mgmt_auth_failed(hcon, HCI_ERROR_AUTH_FAILURE);
680
681         if (chan->data)
682                 smp_chan_destroy(conn);
683 }
684
685 #define JUST_WORKS      0x00
686 #define JUST_CFM        0x01
687 #define REQ_PASSKEY     0x02
688 #define CFM_PASSKEY     0x03
689 #define REQ_OOB         0x04
690 #define DSP_PASSKEY     0x05
691 #define OVERLAP         0xFF
692
693 static const u8 gen_method[5][5] = {
694         { JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
695         { JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
696         { CFM_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, CFM_PASSKEY },
697         { JUST_WORKS,  JUST_CFM,    JUST_WORKS,  JUST_WORKS, JUST_CFM    },
698         { CFM_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, OVERLAP     },
699 };
700
701 static const u8 sc_method[5][5] = {
702         { JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
703         { JUST_WORKS,  CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, CFM_PASSKEY },
704         { DSP_PASSKEY, DSP_PASSKEY, REQ_PASSKEY, JUST_WORKS, DSP_PASSKEY },
705         { JUST_WORKS,  JUST_CFM,    JUST_WORKS,  JUST_WORKS, JUST_CFM    },
706         { DSP_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, CFM_PASSKEY },
707 };
708
709 static u8 get_auth_method(struct smp_chan *smp, u8 local_io, u8 remote_io)
710 {
711         /* If either side has unknown io_caps, use JUST_CFM (which gets
712          * converted later to JUST_WORKS if we're initiators.
713          */
714         if (local_io > SMP_IO_KEYBOARD_DISPLAY ||
715             remote_io > SMP_IO_KEYBOARD_DISPLAY)
716                 return JUST_CFM;
717
718         if (test_bit(SMP_FLAG_SC, &smp->flags))
719                 return sc_method[remote_io][local_io];
720
721         return gen_method[remote_io][local_io];
722 }
723
724 static int tk_request(struct l2cap_conn *conn, u8 remote_oob, u8 auth,
725                                                 u8 local_io, u8 remote_io)
726 {
727         struct hci_conn *hcon = conn->hcon;
728         struct l2cap_chan *chan = conn->smp;
729         struct smp_chan *smp = chan->data;
730         u32 passkey = 0;
731         int ret = 0;
732
733         /* Initialize key for JUST WORKS */
734         memset(smp->tk, 0, sizeof(smp->tk));
735         clear_bit(SMP_FLAG_TK_VALID, &smp->flags);
736
737         BT_DBG("tk_request: auth:%d lcl:%d rem:%d", auth, local_io, remote_io);
738
739         /* If neither side wants MITM, either "just" confirm an incoming
740          * request or use just-works for outgoing ones. The JUST_CFM
741          * will be converted to JUST_WORKS if necessary later in this
742          * function. If either side has MITM look up the method from the
743          * table.
744          */
745         if (!(auth & SMP_AUTH_MITM))
746                 smp->method = JUST_CFM;
747         else
748                 smp->method = get_auth_method(smp, local_io, remote_io);
749
750         /* Don't confirm locally initiated pairing attempts */
751         if (smp->method == JUST_CFM && test_bit(SMP_FLAG_INITIATOR,
752                                                 &smp->flags))
753                 smp->method = JUST_WORKS;
754
755         /* Don't bother user space with no IO capabilities */
756         if (smp->method == JUST_CFM &&
757             hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
758                 smp->method = JUST_WORKS;
759
760         /* If Just Works, Continue with Zero TK */
761         if (smp->method == JUST_WORKS) {
762                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
763                 return 0;
764         }
765
766         /* Not Just Works/Confirm results in MITM Authentication */
767         if (smp->method != JUST_CFM) {
768                 set_bit(SMP_FLAG_MITM_AUTH, &smp->flags);
769                 if (hcon->pending_sec_level < BT_SECURITY_HIGH)
770                         hcon->pending_sec_level = BT_SECURITY_HIGH;
771         }
772
773         /* If both devices have Keyoard-Display I/O, the master
774          * Confirms and the slave Enters the passkey.
775          */
776         if (smp->method == OVERLAP) {
777                 if (hcon->role == HCI_ROLE_MASTER)
778                         smp->method = CFM_PASSKEY;
779                 else
780                         smp->method = REQ_PASSKEY;
781         }
782
783         /* Generate random passkey. */
784         if (smp->method == CFM_PASSKEY) {
785                 memset(smp->tk, 0, sizeof(smp->tk));
786                 get_random_bytes(&passkey, sizeof(passkey));
787                 passkey %= 1000000;
788                 put_unaligned_le32(passkey, smp->tk);
789                 BT_DBG("PassKey: %d", passkey);
790                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
791         }
792
793         if (smp->method == REQ_PASSKEY)
794                 ret = mgmt_user_passkey_request(hcon->hdev, &hcon->dst,
795                                                 hcon->type, hcon->dst_type);
796         else if (smp->method == JUST_CFM)
797                 ret = mgmt_user_confirm_request(hcon->hdev, &hcon->dst,
798                                                 hcon->type, hcon->dst_type,
799                                                 passkey, 1);
800         else
801                 ret = mgmt_user_passkey_notify(hcon->hdev, &hcon->dst,
802                                                 hcon->type, hcon->dst_type,
803                                                 passkey, 0);
804
805         return ret;
806 }
807
808 static u8 smp_confirm(struct smp_chan *smp)
809 {
810         struct l2cap_conn *conn = smp->conn;
811         struct smp_cmd_pairing_confirm cp;
812         int ret;
813
814         BT_DBG("conn %p", conn);
815
816         ret = smp_c1(smp->tfm_aes, smp->tk, smp->prnd, smp->preq, smp->prsp,
817                      conn->hcon->init_addr_type, &conn->hcon->init_addr,
818                      conn->hcon->resp_addr_type, &conn->hcon->resp_addr,
819                      cp.confirm_val);
820         if (ret)
821                 return SMP_UNSPECIFIED;
822
823         clear_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
824
825         smp_send_cmd(smp->conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cp), &cp);
826
827         if (conn->hcon->out)
828                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
829         else
830                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
831
832         return 0;
833 }
834
835 static u8 smp_random(struct smp_chan *smp)
836 {
837         struct l2cap_conn *conn = smp->conn;
838         struct hci_conn *hcon = conn->hcon;
839         u8 confirm[16];
840         int ret;
841
842         if (IS_ERR_OR_NULL(smp->tfm_aes))
843                 return SMP_UNSPECIFIED;
844
845         BT_DBG("conn %p %s", conn, conn->hcon->out ? "master" : "slave");
846
847         ret = smp_c1(smp->tfm_aes, smp->tk, smp->rrnd, smp->preq, smp->prsp,
848                      hcon->init_addr_type, &hcon->init_addr,
849                      hcon->resp_addr_type, &hcon->resp_addr, confirm);
850         if (ret)
851                 return SMP_UNSPECIFIED;
852
853         if (memcmp(smp->pcnf, confirm, sizeof(smp->pcnf)) != 0) {
854                 BT_ERR("Pairing failed (confirmation values mismatch)");
855                 return SMP_CONFIRM_FAILED;
856         }
857
858         if (hcon->out) {
859                 u8 stk[16];
860                 __le64 rand = 0;
861                 __le16 ediv = 0;
862
863                 smp_s1(smp->tfm_aes, smp->tk, smp->rrnd, smp->prnd, stk);
864
865                 memset(stk + smp->enc_key_size, 0,
866                        SMP_MAX_ENC_KEY_SIZE - smp->enc_key_size);
867
868                 if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags))
869                         return SMP_UNSPECIFIED;
870
871                 hci_le_start_enc(hcon, ediv, rand, stk);
872                 hcon->enc_key_size = smp->enc_key_size;
873                 set_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags);
874         } else {
875                 u8 stk[16], auth;
876                 __le64 rand = 0;
877                 __le16 ediv = 0;
878
879                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
880                              smp->prnd);
881
882                 smp_s1(smp->tfm_aes, smp->tk, smp->prnd, smp->rrnd, stk);
883
884                 memset(stk + smp->enc_key_size, 0,
885                        SMP_MAX_ENC_KEY_SIZE - smp->enc_key_size);
886
887                 if (hcon->pending_sec_level == BT_SECURITY_HIGH)
888                         auth = 1;
889                 else
890                         auth = 0;
891
892                 /* Even though there's no _SLAVE suffix this is the
893                  * slave STK we're adding for later lookup (the master
894                  * STK never needs to be stored).
895                  */
896                 hci_add_ltk(hcon->hdev, &hcon->dst, hcon->dst_type,
897                             SMP_STK, auth, stk, smp->enc_key_size, ediv, rand);
898         }
899
900         return 0;
901 }
902
903 static void smp_notify_keys(struct l2cap_conn *conn)
904 {
905         struct l2cap_chan *chan = conn->smp;
906         struct smp_chan *smp = chan->data;
907         struct hci_conn *hcon = conn->hcon;
908         struct hci_dev *hdev = hcon->hdev;
909         struct smp_cmd_pairing *req = (void *) &smp->preq[1];
910         struct smp_cmd_pairing *rsp = (void *) &smp->prsp[1];
911         bool persistent;
912
913         if (smp->remote_irk) {
914                 mgmt_new_irk(hdev, smp->remote_irk);
915                 /* Now that user space can be considered to know the
916                  * identity address track the connection based on it
917                  * from now on.
918                  */
919                 bacpy(&hcon->dst, &smp->remote_irk->bdaddr);
920                 hcon->dst_type = smp->remote_irk->addr_type;
921                 queue_work(hdev->workqueue, &conn->id_addr_update_work);
922
923                 /* When receiving an indentity resolving key for
924                  * a remote device that does not use a resolvable
925                  * private address, just remove the key so that
926                  * it is possible to use the controller white
927                  * list for scanning.
928                  *
929                  * Userspace will have been told to not store
930                  * this key at this point. So it is safe to
931                  * just remove it.
932                  */
933                 if (!bacmp(&smp->remote_irk->rpa, BDADDR_ANY)) {
934                         list_del_rcu(&smp->remote_irk->list);
935                         kfree_rcu(smp->remote_irk, rcu);
936                         smp->remote_irk = NULL;
937                 }
938         }
939
940         /* The LTKs and CSRKs should be persistent only if both sides
941          * had the bonding bit set in their authentication requests.
942          */
943         persistent = !!((req->auth_req & rsp->auth_req) & SMP_AUTH_BONDING);
944
945         if (smp->csrk) {
946                 smp->csrk->bdaddr_type = hcon->dst_type;
947                 bacpy(&smp->csrk->bdaddr, &hcon->dst);
948                 mgmt_new_csrk(hdev, smp->csrk, persistent);
949         }
950
951         if (smp->slave_csrk) {
952                 smp->slave_csrk->bdaddr_type = hcon->dst_type;
953                 bacpy(&smp->slave_csrk->bdaddr, &hcon->dst);
954                 mgmt_new_csrk(hdev, smp->slave_csrk, persistent);
955         }
956
957         if (smp->ltk) {
958                 smp->ltk->bdaddr_type = hcon->dst_type;
959                 bacpy(&smp->ltk->bdaddr, &hcon->dst);
960                 mgmt_new_ltk(hdev, smp->ltk, persistent);
961         }
962
963         if (smp->slave_ltk) {
964                 smp->slave_ltk->bdaddr_type = hcon->dst_type;
965                 bacpy(&smp->slave_ltk->bdaddr, &hcon->dst);
966                 mgmt_new_ltk(hdev, smp->slave_ltk, persistent);
967         }
968
969         if (smp->link_key) {
970                 struct link_key *key;
971                 u8 type;
972
973                 if (test_bit(SMP_FLAG_DEBUG_KEY, &smp->flags))
974                         type = HCI_LK_DEBUG_COMBINATION;
975                 else if (hcon->sec_level == BT_SECURITY_FIPS)
976                         type = HCI_LK_AUTH_COMBINATION_P256;
977                 else
978                         type = HCI_LK_UNAUTH_COMBINATION_P256;
979
980                 key = hci_add_link_key(hdev, smp->conn->hcon, &hcon->dst,
981                                        smp->link_key, type, 0, &persistent);
982                 if (key) {
983                         mgmt_new_link_key(hdev, key, persistent);
984
985                         /* Don't keep debug keys around if the relevant
986                          * flag is not set.
987                          */
988                         if (!test_bit(HCI_KEEP_DEBUG_KEYS, &hdev->dev_flags) &&
989                             key->type == HCI_LK_DEBUG_COMBINATION) {
990                                 list_del_rcu(&key->list);
991                                 kfree_rcu(key, rcu);
992                         }
993                 }
994         }
995 }
996
997 static void sc_generate_link_key(struct smp_chan *smp)
998 {
999         /* These constants are as specified in the core specification.
1000          * In ASCII they spell out to 'tmp1' and 'lebr'.
1001          */
1002         const u8 tmp1[4] = { 0x31, 0x70, 0x6d, 0x74 };
1003         const u8 lebr[4] = { 0x72, 0x62, 0x65, 0x6c };
1004
1005         smp->link_key = kzalloc(16, GFP_KERNEL);
1006         if (!smp->link_key)
1007                 return;
1008
1009         if (smp_h6(smp->tfm_cmac, smp->tk, tmp1, smp->link_key)) {
1010                 kfree(smp->link_key);
1011                 smp->link_key = NULL;
1012                 return;
1013         }
1014
1015         if (smp_h6(smp->tfm_cmac, smp->link_key, lebr, smp->link_key)) {
1016                 kfree(smp->link_key);
1017                 smp->link_key = NULL;
1018                 return;
1019         }
1020 }
1021
1022 static void smp_allow_key_dist(struct smp_chan *smp)
1023 {
1024         /* Allow the first expected phase 3 PDU. The rest of the PDUs
1025          * will be allowed in each PDU handler to ensure we receive
1026          * them in the correct order.
1027          */
1028         if (smp->remote_key_dist & SMP_DIST_ENC_KEY)
1029                 SMP_ALLOW_CMD(smp, SMP_CMD_ENCRYPT_INFO);
1030         else if (smp->remote_key_dist & SMP_DIST_ID_KEY)
1031                 SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_INFO);
1032         else if (smp->remote_key_dist & SMP_DIST_SIGN)
1033                 SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
1034 }
1035
1036 static void smp_distribute_keys(struct smp_chan *smp)
1037 {
1038         struct smp_cmd_pairing *req, *rsp;
1039         struct l2cap_conn *conn = smp->conn;
1040         struct hci_conn *hcon = conn->hcon;
1041         struct hci_dev *hdev = hcon->hdev;
1042         __u8 *keydist;
1043
1044         BT_DBG("conn %p", conn);
1045
1046         rsp = (void *) &smp->prsp[1];
1047
1048         /* The responder sends its keys first */
1049         if (hcon->out && (smp->remote_key_dist & KEY_DIST_MASK)) {
1050                 smp_allow_key_dist(smp);
1051                 return;
1052         }
1053
1054         req = (void *) &smp->preq[1];
1055
1056         if (hcon->out) {
1057                 keydist = &rsp->init_key_dist;
1058                 *keydist &= req->init_key_dist;
1059         } else {
1060                 keydist = &rsp->resp_key_dist;
1061                 *keydist &= req->resp_key_dist;
1062         }
1063
1064         if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1065                 if (*keydist & SMP_DIST_LINK_KEY)
1066                         sc_generate_link_key(smp);
1067
1068                 /* Clear the keys which are generated but not distributed */
1069                 *keydist &= ~SMP_SC_NO_DIST;
1070         }
1071
1072         BT_DBG("keydist 0x%x", *keydist);
1073
1074         if (*keydist & SMP_DIST_ENC_KEY) {
1075                 struct smp_cmd_encrypt_info enc;
1076                 struct smp_cmd_master_ident ident;
1077                 struct smp_ltk *ltk;
1078                 u8 authenticated;
1079                 __le16 ediv;
1080                 __le64 rand;
1081
1082                 get_random_bytes(enc.ltk, sizeof(enc.ltk));
1083                 get_random_bytes(&ediv, sizeof(ediv));
1084                 get_random_bytes(&rand, sizeof(rand));
1085
1086                 smp_send_cmd(conn, SMP_CMD_ENCRYPT_INFO, sizeof(enc), &enc);
1087
1088                 authenticated = hcon->sec_level == BT_SECURITY_HIGH;
1089                 ltk = hci_add_ltk(hdev, &hcon->dst, hcon->dst_type,
1090                                   SMP_LTK_SLAVE, authenticated, enc.ltk,
1091                                   smp->enc_key_size, ediv, rand);
1092                 smp->slave_ltk = ltk;
1093
1094                 ident.ediv = ediv;
1095                 ident.rand = rand;
1096
1097                 smp_send_cmd(conn, SMP_CMD_MASTER_IDENT, sizeof(ident), &ident);
1098
1099                 *keydist &= ~SMP_DIST_ENC_KEY;
1100         }
1101
1102         if (*keydist & SMP_DIST_ID_KEY) {
1103                 struct smp_cmd_ident_addr_info addrinfo;
1104                 struct smp_cmd_ident_info idinfo;
1105
1106                 memcpy(idinfo.irk, hdev->irk, sizeof(idinfo.irk));
1107
1108                 smp_send_cmd(conn, SMP_CMD_IDENT_INFO, sizeof(idinfo), &idinfo);
1109
1110                 /* The hci_conn contains the local identity address
1111                  * after the connection has been established.
1112                  *
1113                  * This is true even when the connection has been
1114                  * established using a resolvable random address.
1115                  */
1116                 bacpy(&addrinfo.bdaddr, &hcon->src);
1117                 addrinfo.addr_type = hcon->src_type;
1118
1119                 smp_send_cmd(conn, SMP_CMD_IDENT_ADDR_INFO, sizeof(addrinfo),
1120                              &addrinfo);
1121
1122                 *keydist &= ~SMP_DIST_ID_KEY;
1123         }
1124
1125         if (*keydist & SMP_DIST_SIGN) {
1126                 struct smp_cmd_sign_info sign;
1127                 struct smp_csrk *csrk;
1128
1129                 /* Generate a new random key */
1130                 get_random_bytes(sign.csrk, sizeof(sign.csrk));
1131
1132                 csrk = kzalloc(sizeof(*csrk), GFP_KERNEL);
1133                 if (csrk) {
1134                         csrk->master = 0x00;
1135                         memcpy(csrk->val, sign.csrk, sizeof(csrk->val));
1136                 }
1137                 smp->slave_csrk = csrk;
1138
1139                 smp_send_cmd(conn, SMP_CMD_SIGN_INFO, sizeof(sign), &sign);
1140
1141                 *keydist &= ~SMP_DIST_SIGN;
1142         }
1143
1144         /* If there are still keys to be received wait for them */
1145         if (smp->remote_key_dist & KEY_DIST_MASK) {
1146                 smp_allow_key_dist(smp);
1147                 return;
1148         }
1149
1150         set_bit(SMP_FLAG_COMPLETE, &smp->flags);
1151         smp_notify_keys(conn);
1152
1153         smp_chan_destroy(conn);
1154 }
1155
1156 static void smp_timeout(struct work_struct *work)
1157 {
1158         struct smp_chan *smp = container_of(work, struct smp_chan,
1159                                             security_timer.work);
1160         struct l2cap_conn *conn = smp->conn;
1161
1162         BT_DBG("conn %p", conn);
1163
1164         hci_disconnect(conn->hcon, HCI_ERROR_REMOTE_USER_TERM);
1165 }
1166
1167 static struct smp_chan *smp_chan_create(struct l2cap_conn *conn)
1168 {
1169         struct l2cap_chan *chan = conn->smp;
1170         struct smp_chan *smp;
1171
1172         smp = kzalloc(sizeof(*smp), GFP_ATOMIC);
1173         if (!smp)
1174                 return NULL;
1175
1176         smp->tfm_aes = crypto_alloc_blkcipher("ecb(aes)", 0, CRYPTO_ALG_ASYNC);
1177         if (IS_ERR(smp->tfm_aes)) {
1178                 BT_ERR("Unable to create ECB crypto context");
1179                 kfree(smp);
1180                 return NULL;
1181         }
1182
1183         smp->tfm_cmac = crypto_alloc_hash("cmac(aes)", 0, CRYPTO_ALG_ASYNC);
1184         if (IS_ERR(smp->tfm_cmac)) {
1185                 BT_ERR("Unable to create CMAC crypto context");
1186                 crypto_free_blkcipher(smp->tfm_aes);
1187                 kfree(smp);
1188                 return NULL;
1189         }
1190
1191         smp->conn = conn;
1192         chan->data = smp;
1193
1194         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_FAIL);
1195
1196         INIT_DELAYED_WORK(&smp->security_timer, smp_timeout);
1197
1198         hci_conn_hold(conn->hcon);
1199
1200         return smp;
1201 }
1202
1203 static int sc_mackey_and_ltk(struct smp_chan *smp, u8 mackey[16], u8 ltk[16])
1204 {
1205         struct hci_conn *hcon = smp->conn->hcon;
1206         u8 *na, *nb, a[7], b[7];
1207
1208         if (hcon->out) {
1209                 na   = smp->prnd;
1210                 nb   = smp->rrnd;
1211         } else {
1212                 na   = smp->rrnd;
1213                 nb   = smp->prnd;
1214         }
1215
1216         memcpy(a, &hcon->init_addr, 6);
1217         memcpy(b, &hcon->resp_addr, 6);
1218         a[6] = hcon->init_addr_type;
1219         b[6] = hcon->resp_addr_type;
1220
1221         return smp_f5(smp->tfm_cmac, smp->dhkey, na, nb, a, b, mackey, ltk);
1222 }
1223
1224 static void sc_dhkey_check(struct smp_chan *smp)
1225 {
1226         struct hci_conn *hcon = smp->conn->hcon;
1227         struct smp_cmd_dhkey_check check;
1228         u8 a[7], b[7], *local_addr, *remote_addr;
1229         u8 io_cap[3], r[16];
1230
1231         memcpy(a, &hcon->init_addr, 6);
1232         memcpy(b, &hcon->resp_addr, 6);
1233         a[6] = hcon->init_addr_type;
1234         b[6] = hcon->resp_addr_type;
1235
1236         if (hcon->out) {
1237                 local_addr = a;
1238                 remote_addr = b;
1239                 memcpy(io_cap, &smp->preq[1], 3);
1240         } else {
1241                 local_addr = b;
1242                 remote_addr = a;
1243                 memcpy(io_cap, &smp->prsp[1], 3);
1244         }
1245
1246         memset(r, 0, sizeof(r));
1247
1248         if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
1249                 put_unaligned_le32(hcon->passkey_notify, r);
1250
1251         smp_f6(smp->tfm_cmac, smp->mackey, smp->prnd, smp->rrnd, r, io_cap,
1252                local_addr, remote_addr, check.e);
1253
1254         smp_send_cmd(smp->conn, SMP_CMD_DHKEY_CHECK, sizeof(check), &check);
1255 }
1256
1257 static u8 sc_passkey_send_confirm(struct smp_chan *smp)
1258 {
1259         struct l2cap_conn *conn = smp->conn;
1260         struct hci_conn *hcon = conn->hcon;
1261         struct smp_cmd_pairing_confirm cfm;
1262         u8 r;
1263
1264         r = ((hcon->passkey_notify >> smp->passkey_round) & 0x01);
1265         r |= 0x80;
1266
1267         get_random_bytes(smp->prnd, sizeof(smp->prnd));
1268
1269         if (smp_f4(smp->tfm_cmac, smp->local_pk, smp->remote_pk, smp->prnd, r,
1270                    cfm.confirm_val))
1271                 return SMP_UNSPECIFIED;
1272
1273         smp_send_cmd(conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cfm), &cfm);
1274
1275         return 0;
1276 }
1277
1278 static u8 sc_passkey_round(struct smp_chan *smp, u8 smp_op)
1279 {
1280         struct l2cap_conn *conn = smp->conn;
1281         struct hci_conn *hcon = conn->hcon;
1282         struct hci_dev *hdev = hcon->hdev;
1283         u8 cfm[16], r;
1284
1285         /* Ignore the PDU if we've already done 20 rounds (0 - 19) */
1286         if (smp->passkey_round >= 20)
1287                 return 0;
1288
1289         switch (smp_op) {
1290         case SMP_CMD_PAIRING_RANDOM:
1291                 r = ((hcon->passkey_notify >> smp->passkey_round) & 0x01);
1292                 r |= 0x80;
1293
1294                 if (smp_f4(smp->tfm_cmac, smp->remote_pk, smp->local_pk,
1295                            smp->rrnd, r, cfm))
1296                         return SMP_UNSPECIFIED;
1297
1298                 if (memcmp(smp->pcnf, cfm, 16))
1299                         return SMP_CONFIRM_FAILED;
1300
1301                 smp->passkey_round++;
1302
1303                 if (smp->passkey_round == 20) {
1304                         /* Generate MacKey and LTK */
1305                         if (sc_mackey_and_ltk(smp, smp->mackey, smp->tk))
1306                                 return SMP_UNSPECIFIED;
1307                 }
1308
1309                 /* The round is only complete when the initiator
1310                  * receives pairing random.
1311                  */
1312                 if (!hcon->out) {
1313                         smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
1314                                      sizeof(smp->prnd), smp->prnd);
1315                         if (smp->passkey_round == 20) {
1316                                 sc_dhkey_check(smp);
1317                                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1318                         } else {
1319                                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
1320                         }
1321                         return 0;
1322                 }
1323
1324                 /* Start the next round */
1325                 if (smp->passkey_round != 20)
1326                         return sc_passkey_round(smp, 0);
1327
1328                 /* Passkey rounds are complete - start DHKey Check */
1329                 sc_dhkey_check(smp);
1330                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1331
1332                 break;
1333
1334         case SMP_CMD_PAIRING_CONFIRM:
1335                 if (test_bit(SMP_FLAG_WAIT_USER, &smp->flags)) {
1336                         set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1337                         return 0;
1338                 }
1339
1340                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
1341
1342                 if (hcon->out) {
1343                         smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM,
1344                                      sizeof(smp->prnd), smp->prnd);
1345                         return 0;
1346                 }
1347
1348                 return sc_passkey_send_confirm(smp);
1349
1350         case SMP_CMD_PUBLIC_KEY:
1351         default:
1352                 /* Initiating device starts the round */
1353                 if (!hcon->out)
1354                         return 0;
1355
1356                 BT_DBG("%s Starting passkey round %u", hdev->name,
1357                        smp->passkey_round + 1);
1358
1359                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
1360
1361                 return sc_passkey_send_confirm(smp);
1362         }
1363
1364         return 0;
1365 }
1366
1367 static int sc_user_reply(struct smp_chan *smp, u16 mgmt_op, __le32 passkey)
1368 {
1369         struct l2cap_conn *conn = smp->conn;
1370         struct hci_conn *hcon = conn->hcon;
1371         u8 smp_op;
1372
1373         clear_bit(SMP_FLAG_WAIT_USER, &smp->flags);
1374
1375         switch (mgmt_op) {
1376         case MGMT_OP_USER_PASSKEY_NEG_REPLY:
1377                 smp_failure(smp->conn, SMP_PASSKEY_ENTRY_FAILED);
1378                 return 0;
1379         case MGMT_OP_USER_CONFIRM_NEG_REPLY:
1380                 smp_failure(smp->conn, SMP_NUMERIC_COMP_FAILED);
1381                 return 0;
1382         case MGMT_OP_USER_PASSKEY_REPLY:
1383                 hcon->passkey_notify = le32_to_cpu(passkey);
1384                 smp->passkey_round = 0;
1385
1386                 if (test_and_clear_bit(SMP_FLAG_CFM_PENDING, &smp->flags))
1387                         smp_op = SMP_CMD_PAIRING_CONFIRM;
1388                 else
1389                         smp_op = 0;
1390
1391                 if (sc_passkey_round(smp, smp_op))
1392                         return -EIO;
1393
1394                 return 0;
1395         }
1396
1397         sc_dhkey_check(smp);
1398
1399         return 0;
1400 }
1401
1402 int smp_user_confirm_reply(struct hci_conn *hcon, u16 mgmt_op, __le32 passkey)
1403 {
1404         struct l2cap_conn *conn = hcon->l2cap_data;
1405         struct l2cap_chan *chan;
1406         struct smp_chan *smp;
1407         u32 value;
1408         int err;
1409
1410         BT_DBG("");
1411
1412         if (!conn)
1413                 return -ENOTCONN;
1414
1415         chan = conn->smp;
1416         if (!chan)
1417                 return -ENOTCONN;
1418
1419         l2cap_chan_lock(chan);
1420         if (!chan->data) {
1421                 err = -ENOTCONN;
1422                 goto unlock;
1423         }
1424
1425         smp = chan->data;
1426
1427         if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1428                 err = sc_user_reply(smp, mgmt_op, passkey);
1429                 goto unlock;
1430         }
1431
1432         switch (mgmt_op) {
1433         case MGMT_OP_USER_PASSKEY_REPLY:
1434                 value = le32_to_cpu(passkey);
1435                 memset(smp->tk, 0, sizeof(smp->tk));
1436                 BT_DBG("PassKey: %d", value);
1437                 put_unaligned_le32(value, smp->tk);
1438                 /* Fall Through */
1439         case MGMT_OP_USER_CONFIRM_REPLY:
1440                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
1441                 break;
1442         case MGMT_OP_USER_PASSKEY_NEG_REPLY:
1443         case MGMT_OP_USER_CONFIRM_NEG_REPLY:
1444                 smp_failure(conn, SMP_PASSKEY_ENTRY_FAILED);
1445                 err = 0;
1446                 goto unlock;
1447         default:
1448                 smp_failure(conn, SMP_PASSKEY_ENTRY_FAILED);
1449                 err = -EOPNOTSUPP;
1450                 goto unlock;
1451         }
1452
1453         err = 0;
1454
1455         /* If it is our turn to send Pairing Confirm, do so now */
1456         if (test_bit(SMP_FLAG_CFM_PENDING, &smp->flags)) {
1457                 u8 rsp = smp_confirm(smp);
1458                 if (rsp)
1459                         smp_failure(conn, rsp);
1460         }
1461
1462 unlock:
1463         l2cap_chan_unlock(chan);
1464         return err;
1465 }
1466
1467 static u8 smp_cmd_pairing_req(struct l2cap_conn *conn, struct sk_buff *skb)
1468 {
1469         struct smp_cmd_pairing rsp, *req = (void *) skb->data;
1470         struct l2cap_chan *chan = conn->smp;
1471         struct hci_dev *hdev = conn->hcon->hdev;
1472         struct smp_chan *smp;
1473         u8 key_size, auth, sec_level;
1474         int ret;
1475
1476         BT_DBG("conn %p", conn);
1477
1478         if (skb->len < sizeof(*req))
1479                 return SMP_INVALID_PARAMS;
1480
1481         if (conn->hcon->role != HCI_ROLE_SLAVE)
1482                 return SMP_CMD_NOTSUPP;
1483
1484         if (!chan->data)
1485                 smp = smp_chan_create(conn);
1486         else
1487                 smp = chan->data;
1488
1489         if (!smp)
1490                 return SMP_UNSPECIFIED;
1491
1492         /* We didn't start the pairing, so match remote */
1493         auth = req->auth_req & AUTH_REQ_MASK(hdev);
1494
1495         if (!test_bit(HCI_BONDABLE, &hdev->dev_flags) &&
1496             (auth & SMP_AUTH_BONDING))
1497                 return SMP_PAIRING_NOTSUPP;
1498
1499         smp->preq[0] = SMP_CMD_PAIRING_REQ;
1500         memcpy(&smp->preq[1], req, sizeof(*req));
1501         skb_pull(skb, sizeof(*req));
1502
1503         build_pairing_cmd(conn, req, &rsp, auth);
1504
1505         if (rsp.auth_req & SMP_AUTH_SC)
1506                 set_bit(SMP_FLAG_SC, &smp->flags);
1507
1508         if (conn->hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
1509                 sec_level = BT_SECURITY_MEDIUM;
1510         else
1511                 sec_level = authreq_to_seclevel(auth);
1512
1513         if (sec_level > conn->hcon->pending_sec_level)
1514                 conn->hcon->pending_sec_level = sec_level;
1515
1516         /* If we need MITM check that it can be achieved */
1517         if (conn->hcon->pending_sec_level >= BT_SECURITY_HIGH) {
1518                 u8 method;
1519
1520                 method = get_auth_method(smp, conn->hcon->io_capability,
1521                                          req->io_capability);
1522                 if (method == JUST_WORKS || method == JUST_CFM)
1523                         return SMP_AUTH_REQUIREMENTS;
1524         }
1525
1526         key_size = min(req->max_key_size, rsp.max_key_size);
1527         if (check_enc_key_size(conn, key_size))
1528                 return SMP_ENC_KEY_SIZE;
1529
1530         get_random_bytes(smp->prnd, sizeof(smp->prnd));
1531
1532         smp->prsp[0] = SMP_CMD_PAIRING_RSP;
1533         memcpy(&smp->prsp[1], &rsp, sizeof(rsp));
1534
1535         smp_send_cmd(conn, SMP_CMD_PAIRING_RSP, sizeof(rsp), &rsp);
1536
1537         clear_bit(SMP_FLAG_INITIATOR, &smp->flags);
1538
1539         if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1540                 SMP_ALLOW_CMD(smp, SMP_CMD_PUBLIC_KEY);
1541                 /* Clear bits which are generated but not distributed */
1542                 smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1543                 /* Wait for Public Key from Initiating Device */
1544                 return 0;
1545         } else {
1546                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
1547         }
1548
1549         /* Request setup of TK */
1550         ret = tk_request(conn, 0, auth, rsp.io_capability, req->io_capability);
1551         if (ret)
1552                 return SMP_UNSPECIFIED;
1553
1554         return 0;
1555 }
1556
1557 static u8 sc_send_public_key(struct smp_chan *smp)
1558 {
1559         BT_DBG("");
1560
1561         while (true) {
1562                 /* Generate local key pair for Secure Connections */
1563                 if (!ecc_make_key(smp->local_pk, smp->local_sk))
1564                         return SMP_UNSPECIFIED;
1565
1566                 /* This is unlikely, but we need to check that we didn't
1567                  * accidentially generate a debug key.
1568                  */
1569                 if (memcmp(smp->local_sk, debug_sk, 32))
1570                         break;
1571         }
1572
1573         BT_DBG("Local Public Key X: %32phN", smp->local_pk);
1574         BT_DBG("Local Public Key Y: %32phN", &smp->local_pk[32]);
1575         BT_DBG("Local Private Key:  %32phN", smp->local_sk);
1576
1577         smp_send_cmd(smp->conn, SMP_CMD_PUBLIC_KEY, 64, smp->local_pk);
1578
1579         return 0;
1580 }
1581
1582 static u8 smp_cmd_pairing_rsp(struct l2cap_conn *conn, struct sk_buff *skb)
1583 {
1584         struct smp_cmd_pairing *req, *rsp = (void *) skb->data;
1585         struct l2cap_chan *chan = conn->smp;
1586         struct smp_chan *smp = chan->data;
1587         struct hci_dev *hdev = conn->hcon->hdev;
1588         u8 key_size, auth;
1589         int ret;
1590
1591         BT_DBG("conn %p", conn);
1592
1593         if (skb->len < sizeof(*rsp))
1594                 return SMP_INVALID_PARAMS;
1595
1596         if (conn->hcon->role != HCI_ROLE_MASTER)
1597                 return SMP_CMD_NOTSUPP;
1598
1599         skb_pull(skb, sizeof(*rsp));
1600
1601         req = (void *) &smp->preq[1];
1602
1603         key_size = min(req->max_key_size, rsp->max_key_size);
1604         if (check_enc_key_size(conn, key_size))
1605                 return SMP_ENC_KEY_SIZE;
1606
1607         auth = rsp->auth_req & AUTH_REQ_MASK(hdev);
1608
1609         if ((req->auth_req & SMP_AUTH_SC) && (auth & SMP_AUTH_SC))
1610                 set_bit(SMP_FLAG_SC, &smp->flags);
1611         else if (conn->hcon->pending_sec_level > BT_SECURITY_HIGH)
1612                 conn->hcon->pending_sec_level = BT_SECURITY_HIGH;
1613
1614         /* If we need MITM check that it can be achieved */
1615         if (conn->hcon->pending_sec_level >= BT_SECURITY_HIGH) {
1616                 u8 method;
1617
1618                 method = get_auth_method(smp, req->io_capability,
1619                                          rsp->io_capability);
1620                 if (method == JUST_WORKS || method == JUST_CFM)
1621                         return SMP_AUTH_REQUIREMENTS;
1622         }
1623
1624         get_random_bytes(smp->prnd, sizeof(smp->prnd));
1625
1626         smp->prsp[0] = SMP_CMD_PAIRING_RSP;
1627         memcpy(&smp->prsp[1], rsp, sizeof(*rsp));
1628
1629         /* Update remote key distribution in case the remote cleared
1630          * some bits that we had enabled in our request.
1631          */
1632         smp->remote_key_dist &= rsp->resp_key_dist;
1633
1634         if (test_bit(SMP_FLAG_SC, &smp->flags)) {
1635                 /* Clear bits which are generated but not distributed */
1636                 smp->remote_key_dist &= ~SMP_SC_NO_DIST;
1637                 SMP_ALLOW_CMD(smp, SMP_CMD_PUBLIC_KEY);
1638                 return sc_send_public_key(smp);
1639         }
1640
1641         auth |= req->auth_req;
1642
1643         ret = tk_request(conn, 0, auth, req->io_capability, rsp->io_capability);
1644         if (ret)
1645                 return SMP_UNSPECIFIED;
1646
1647         set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1648
1649         /* Can't compose response until we have been confirmed */
1650         if (test_bit(SMP_FLAG_TK_VALID, &smp->flags))
1651                 return smp_confirm(smp);
1652
1653         return 0;
1654 }
1655
1656 static u8 sc_check_confirm(struct smp_chan *smp)
1657 {
1658         struct l2cap_conn *conn = smp->conn;
1659
1660         BT_DBG("");
1661
1662         /* Public Key exchange must happen before any other steps */
1663         if (!test_bit(SMP_FLAG_REMOTE_PK, &smp->flags))
1664                 return SMP_UNSPECIFIED;
1665
1666         if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
1667                 return sc_passkey_round(smp, SMP_CMD_PAIRING_CONFIRM);
1668
1669         if (conn->hcon->out) {
1670                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
1671                              smp->prnd);
1672                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
1673         }
1674
1675         return 0;
1676 }
1677
1678 static u8 smp_cmd_pairing_confirm(struct l2cap_conn *conn, struct sk_buff *skb)
1679 {
1680         struct l2cap_chan *chan = conn->smp;
1681         struct smp_chan *smp = chan->data;
1682
1683         BT_DBG("conn %p %s", conn, conn->hcon->out ? "master" : "slave");
1684
1685         if (skb->len < sizeof(smp->pcnf))
1686                 return SMP_INVALID_PARAMS;
1687
1688         memcpy(smp->pcnf, skb->data, sizeof(smp->pcnf));
1689         skb_pull(skb, sizeof(smp->pcnf));
1690
1691         if (test_bit(SMP_FLAG_SC, &smp->flags))
1692                 return sc_check_confirm(smp);
1693
1694         if (conn->hcon->out) {
1695                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
1696                              smp->prnd);
1697                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
1698                 return 0;
1699         }
1700
1701         if (test_bit(SMP_FLAG_TK_VALID, &smp->flags))
1702                 return smp_confirm(smp);
1703         else
1704                 set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
1705
1706         return 0;
1707 }
1708
1709 static u8 smp_cmd_pairing_random(struct l2cap_conn *conn, struct sk_buff *skb)
1710 {
1711         struct l2cap_chan *chan = conn->smp;
1712         struct smp_chan *smp = chan->data;
1713         struct hci_conn *hcon = conn->hcon;
1714         u8 *pkax, *pkbx, *na, *nb;
1715         u32 passkey;
1716         int err;
1717
1718         BT_DBG("conn %p", conn);
1719
1720         if (skb->len < sizeof(smp->rrnd))
1721                 return SMP_INVALID_PARAMS;
1722
1723         memcpy(smp->rrnd, skb->data, sizeof(smp->rrnd));
1724         skb_pull(skb, sizeof(smp->rrnd));
1725
1726         if (!test_bit(SMP_FLAG_SC, &smp->flags))
1727                 return smp_random(smp);
1728
1729         /* Passkey entry has special treatment */
1730         if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
1731                 return sc_passkey_round(smp, SMP_CMD_PAIRING_RANDOM);
1732
1733         if (hcon->out) {
1734                 u8 cfm[16];
1735
1736                 err = smp_f4(smp->tfm_cmac, smp->remote_pk, smp->local_pk,
1737                              smp->rrnd, 0, cfm);
1738                 if (err)
1739                         return SMP_UNSPECIFIED;
1740
1741                 if (memcmp(smp->pcnf, cfm, 16))
1742                         return SMP_CONFIRM_FAILED;
1743
1744                 pkax = smp->local_pk;
1745                 pkbx = smp->remote_pk;
1746                 na   = smp->prnd;
1747                 nb   = smp->rrnd;
1748         } else {
1749                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
1750                              smp->prnd);
1751                 SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1752
1753                 pkax = smp->remote_pk;
1754                 pkbx = smp->local_pk;
1755                 na   = smp->rrnd;
1756                 nb   = smp->prnd;
1757         }
1758
1759         /* Generate MacKey and LTK */
1760         err = sc_mackey_and_ltk(smp, smp->mackey, smp->tk);
1761         if (err)
1762                 return SMP_UNSPECIFIED;
1763
1764         if (smp->method == JUST_WORKS) {
1765                 if (hcon->out) {
1766                         sc_dhkey_check(smp);
1767                         SMP_ALLOW_CMD(smp, SMP_CMD_DHKEY_CHECK);
1768                 }
1769                 return 0;
1770         }
1771
1772         err = smp_g2(smp->tfm_cmac, pkax, pkbx, na, nb, &passkey);
1773         if (err)
1774                 return SMP_UNSPECIFIED;
1775
1776         err = mgmt_user_confirm_request(hcon->hdev, &hcon->dst, hcon->type,
1777                                         hcon->dst_type, passkey, 0);
1778         if (err)
1779                 return SMP_UNSPECIFIED;
1780
1781         set_bit(SMP_FLAG_WAIT_USER, &smp->flags);
1782
1783         return 0;
1784 }
1785
1786 static bool smp_ltk_encrypt(struct l2cap_conn *conn, u8 sec_level)
1787 {
1788         struct smp_ltk *key;
1789         struct hci_conn *hcon = conn->hcon;
1790
1791         key = hci_find_ltk(hcon->hdev, &hcon->dst, hcon->dst_type, hcon->role);
1792         if (!key)
1793                 return false;
1794
1795         if (smp_ltk_sec_level(key) < sec_level)
1796                 return false;
1797
1798         if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags))
1799                 return true;
1800
1801         hci_le_start_enc(hcon, key->ediv, key->rand, key->val);
1802         hcon->enc_key_size = key->enc_size;
1803
1804         /* We never store STKs for master role, so clear this flag */
1805         clear_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags);
1806
1807         return true;
1808 }
1809
1810 bool smp_sufficient_security(struct hci_conn *hcon, u8 sec_level,
1811                              enum smp_key_pref key_pref)
1812 {
1813         if (sec_level == BT_SECURITY_LOW)
1814                 return true;
1815
1816         /* If we're encrypted with an STK but the caller prefers using
1817          * LTK claim insufficient security. This way we allow the
1818          * connection to be re-encrypted with an LTK, even if the LTK
1819          * provides the same level of security. Only exception is if we
1820          * don't have an LTK (e.g. because of key distribution bits).
1821          */
1822         if (key_pref == SMP_USE_LTK &&
1823             test_bit(HCI_CONN_STK_ENCRYPT, &hcon->flags) &&
1824             hci_find_ltk(hcon->hdev, &hcon->dst, hcon->dst_type, hcon->role))
1825                 return false;
1826
1827         if (hcon->sec_level >= sec_level)
1828                 return true;
1829
1830         return false;
1831 }
1832
1833 static u8 smp_cmd_security_req(struct l2cap_conn *conn, struct sk_buff *skb)
1834 {
1835         struct smp_cmd_security_req *rp = (void *) skb->data;
1836         struct smp_cmd_pairing cp;
1837         struct hci_conn *hcon = conn->hcon;
1838         struct hci_dev *hdev = hcon->hdev;
1839         struct smp_chan *smp;
1840         u8 sec_level, auth;
1841
1842         BT_DBG("conn %p", conn);
1843
1844         if (skb->len < sizeof(*rp))
1845                 return SMP_INVALID_PARAMS;
1846
1847         if (hcon->role != HCI_ROLE_MASTER)
1848                 return SMP_CMD_NOTSUPP;
1849
1850         auth = rp->auth_req & AUTH_REQ_MASK(hdev);
1851
1852         if (hcon->io_capability == HCI_IO_NO_INPUT_OUTPUT)
1853                 sec_level = BT_SECURITY_MEDIUM;
1854         else
1855                 sec_level = authreq_to_seclevel(auth);
1856
1857         if (smp_sufficient_security(hcon, sec_level, SMP_USE_LTK))
1858                 return 0;
1859
1860         if (sec_level > hcon->pending_sec_level)
1861                 hcon->pending_sec_level = sec_level;
1862
1863         if (smp_ltk_encrypt(conn, hcon->pending_sec_level))
1864                 return 0;
1865
1866         smp = smp_chan_create(conn);
1867         if (!smp)
1868                 return SMP_UNSPECIFIED;
1869
1870         if (!test_bit(HCI_BONDABLE, &hcon->hdev->dev_flags) &&
1871             (auth & SMP_AUTH_BONDING))
1872                 return SMP_PAIRING_NOTSUPP;
1873
1874         skb_pull(skb, sizeof(*rp));
1875
1876         memset(&cp, 0, sizeof(cp));
1877         build_pairing_cmd(conn, &cp, NULL, auth);
1878
1879         smp->preq[0] = SMP_CMD_PAIRING_REQ;
1880         memcpy(&smp->preq[1], &cp, sizeof(cp));
1881
1882         smp_send_cmd(conn, SMP_CMD_PAIRING_REQ, sizeof(cp), &cp);
1883         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RSP);
1884
1885         return 0;
1886 }
1887
1888 int smp_conn_security(struct hci_conn *hcon, __u8 sec_level)
1889 {
1890         struct l2cap_conn *conn = hcon->l2cap_data;
1891         struct l2cap_chan *chan;
1892         struct smp_chan *smp;
1893         __u8 authreq;
1894         int ret;
1895
1896         BT_DBG("conn %p hcon %p level 0x%2.2x", conn, hcon, sec_level);
1897
1898         /* This may be NULL if there's an unexpected disconnection */
1899         if (!conn)
1900                 return 1;
1901
1902         chan = conn->smp;
1903
1904         if (!test_bit(HCI_LE_ENABLED, &hcon->hdev->dev_flags))
1905                 return 1;
1906
1907         if (smp_sufficient_security(hcon, sec_level, SMP_USE_LTK))
1908                 return 1;
1909
1910         if (sec_level > hcon->pending_sec_level)
1911                 hcon->pending_sec_level = sec_level;
1912
1913         if (hcon->role == HCI_ROLE_MASTER)
1914                 if (smp_ltk_encrypt(conn, hcon->pending_sec_level))
1915                         return 0;
1916
1917         l2cap_chan_lock(chan);
1918
1919         /* If SMP is already in progress ignore this request */
1920         if (chan->data) {
1921                 ret = 0;
1922                 goto unlock;
1923         }
1924
1925         smp = smp_chan_create(conn);
1926         if (!smp) {
1927                 ret = 1;
1928                 goto unlock;
1929         }
1930
1931         authreq = seclevel_to_authreq(sec_level);
1932
1933         if (test_bit(HCI_SC_ENABLED, &hcon->hdev->dev_flags))
1934                 authreq |= SMP_AUTH_SC;
1935
1936         /* Require MITM if IO Capability allows or the security level
1937          * requires it.
1938          */
1939         if (hcon->io_capability != HCI_IO_NO_INPUT_OUTPUT ||
1940             hcon->pending_sec_level > BT_SECURITY_MEDIUM)
1941                 authreq |= SMP_AUTH_MITM;
1942
1943         if (hcon->role == HCI_ROLE_MASTER) {
1944                 struct smp_cmd_pairing cp;
1945
1946                 build_pairing_cmd(conn, &cp, NULL, authreq);
1947                 smp->preq[0] = SMP_CMD_PAIRING_REQ;
1948                 memcpy(&smp->preq[1], &cp, sizeof(cp));
1949
1950                 smp_send_cmd(conn, SMP_CMD_PAIRING_REQ, sizeof(cp), &cp);
1951                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RSP);
1952         } else {
1953                 struct smp_cmd_security_req cp;
1954                 cp.auth_req = authreq;
1955                 smp_send_cmd(conn, SMP_CMD_SECURITY_REQ, sizeof(cp), &cp);
1956                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_REQ);
1957         }
1958
1959         set_bit(SMP_FLAG_INITIATOR, &smp->flags);
1960         ret = 0;
1961
1962 unlock:
1963         l2cap_chan_unlock(chan);
1964         return ret;
1965 }
1966
1967 static int smp_cmd_encrypt_info(struct l2cap_conn *conn, struct sk_buff *skb)
1968 {
1969         struct smp_cmd_encrypt_info *rp = (void *) skb->data;
1970         struct l2cap_chan *chan = conn->smp;
1971         struct smp_chan *smp = chan->data;
1972
1973         BT_DBG("conn %p", conn);
1974
1975         if (skb->len < sizeof(*rp))
1976                 return SMP_INVALID_PARAMS;
1977
1978         SMP_ALLOW_CMD(smp, SMP_CMD_MASTER_IDENT);
1979
1980         skb_pull(skb, sizeof(*rp));
1981
1982         memcpy(smp->tk, rp->ltk, sizeof(smp->tk));
1983
1984         return 0;
1985 }
1986
1987 static int smp_cmd_master_ident(struct l2cap_conn *conn, struct sk_buff *skb)
1988 {
1989         struct smp_cmd_master_ident *rp = (void *) skb->data;
1990         struct l2cap_chan *chan = conn->smp;
1991         struct smp_chan *smp = chan->data;
1992         struct hci_dev *hdev = conn->hcon->hdev;
1993         struct hci_conn *hcon = conn->hcon;
1994         struct smp_ltk *ltk;
1995         u8 authenticated;
1996
1997         BT_DBG("conn %p", conn);
1998
1999         if (skb->len < sizeof(*rp))
2000                 return SMP_INVALID_PARAMS;
2001
2002         /* Mark the information as received */
2003         smp->remote_key_dist &= ~SMP_DIST_ENC_KEY;
2004
2005         if (smp->remote_key_dist & SMP_DIST_ID_KEY)
2006                 SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_INFO);
2007         else if (smp->remote_key_dist & SMP_DIST_SIGN)
2008                 SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
2009
2010         skb_pull(skb, sizeof(*rp));
2011
2012         authenticated = (hcon->sec_level == BT_SECURITY_HIGH);
2013         ltk = hci_add_ltk(hdev, &hcon->dst, hcon->dst_type, SMP_LTK,
2014                           authenticated, smp->tk, smp->enc_key_size,
2015                           rp->ediv, rp->rand);
2016         smp->ltk = ltk;
2017         if (!(smp->remote_key_dist & KEY_DIST_MASK))
2018                 smp_distribute_keys(smp);
2019
2020         return 0;
2021 }
2022
2023 static int smp_cmd_ident_info(struct l2cap_conn *conn, struct sk_buff *skb)
2024 {
2025         struct smp_cmd_ident_info *info = (void *) skb->data;
2026         struct l2cap_chan *chan = conn->smp;
2027         struct smp_chan *smp = chan->data;
2028
2029         BT_DBG("");
2030
2031         if (skb->len < sizeof(*info))
2032                 return SMP_INVALID_PARAMS;
2033
2034         SMP_ALLOW_CMD(smp, SMP_CMD_IDENT_ADDR_INFO);
2035
2036         skb_pull(skb, sizeof(*info));
2037
2038         memcpy(smp->irk, info->irk, 16);
2039
2040         return 0;
2041 }
2042
2043 static int smp_cmd_ident_addr_info(struct l2cap_conn *conn,
2044                                    struct sk_buff *skb)
2045 {
2046         struct smp_cmd_ident_addr_info *info = (void *) skb->data;
2047         struct l2cap_chan *chan = conn->smp;
2048         struct smp_chan *smp = chan->data;
2049         struct hci_conn *hcon = conn->hcon;
2050         bdaddr_t rpa;
2051
2052         BT_DBG("");
2053
2054         if (skb->len < sizeof(*info))
2055                 return SMP_INVALID_PARAMS;
2056
2057         /* Mark the information as received */
2058         smp->remote_key_dist &= ~SMP_DIST_ID_KEY;
2059
2060         if (smp->remote_key_dist & SMP_DIST_SIGN)
2061                 SMP_ALLOW_CMD(smp, SMP_CMD_SIGN_INFO);
2062
2063         skb_pull(skb, sizeof(*info));
2064
2065         /* Strictly speaking the Core Specification (4.1) allows sending
2066          * an empty address which would force us to rely on just the IRK
2067          * as "identity information". However, since such
2068          * implementations are not known of and in order to not over
2069          * complicate our implementation, simply pretend that we never
2070          * received an IRK for such a device.
2071          */
2072         if (!bacmp(&info->bdaddr, BDADDR_ANY)) {
2073                 BT_ERR("Ignoring IRK with no identity address");
2074                 goto distribute;
2075         }
2076
2077         bacpy(&smp->id_addr, &info->bdaddr);
2078         smp->id_addr_type = info->addr_type;
2079
2080         if (hci_bdaddr_is_rpa(&hcon->dst, hcon->dst_type))
2081                 bacpy(&rpa, &hcon->dst);
2082         else
2083                 bacpy(&rpa, BDADDR_ANY);
2084
2085         smp->remote_irk = hci_add_irk(conn->hcon->hdev, &smp->id_addr,
2086                                       smp->id_addr_type, smp->irk, &rpa);
2087
2088 distribute:
2089         if (!(smp->remote_key_dist & KEY_DIST_MASK))
2090                 smp_distribute_keys(smp);
2091
2092         return 0;
2093 }
2094
2095 static int smp_cmd_sign_info(struct l2cap_conn *conn, struct sk_buff *skb)
2096 {
2097         struct smp_cmd_sign_info *rp = (void *) skb->data;
2098         struct l2cap_chan *chan = conn->smp;
2099         struct smp_chan *smp = chan->data;
2100         struct smp_csrk *csrk;
2101
2102         BT_DBG("conn %p", conn);
2103
2104         if (skb->len < sizeof(*rp))
2105                 return SMP_INVALID_PARAMS;
2106
2107         /* Mark the information as received */
2108         smp->remote_key_dist &= ~SMP_DIST_SIGN;
2109
2110         skb_pull(skb, sizeof(*rp));
2111
2112         csrk = kzalloc(sizeof(*csrk), GFP_KERNEL);
2113         if (csrk) {
2114                 csrk->master = 0x01;
2115                 memcpy(csrk->val, rp->csrk, sizeof(csrk->val));
2116         }
2117         smp->csrk = csrk;
2118         smp_distribute_keys(smp);
2119
2120         return 0;
2121 }
2122
2123 static u8 sc_select_method(struct smp_chan *smp)
2124 {
2125         struct l2cap_conn *conn = smp->conn;
2126         struct hci_conn *hcon = conn->hcon;
2127         struct smp_cmd_pairing *local, *remote;
2128         u8 local_mitm, remote_mitm, local_io, remote_io, method;
2129
2130         /* The preq/prsp contain the raw Pairing Request/Response PDUs
2131          * which are needed as inputs to some crypto functions. To get
2132          * the "struct smp_cmd_pairing" from them we need to skip the
2133          * first byte which contains the opcode.
2134          */
2135         if (hcon->out) {
2136                 local = (void *) &smp->preq[1];
2137                 remote = (void *) &smp->prsp[1];
2138         } else {
2139                 local = (void *) &smp->prsp[1];
2140                 remote = (void *) &smp->preq[1];
2141         }
2142
2143         local_io = local->io_capability;
2144         remote_io = remote->io_capability;
2145
2146         local_mitm = (local->auth_req & SMP_AUTH_MITM);
2147         remote_mitm = (remote->auth_req & SMP_AUTH_MITM);
2148
2149         /* If either side wants MITM, look up the method from the table,
2150          * otherwise use JUST WORKS.
2151          */
2152         if (local_mitm || remote_mitm)
2153                 method = get_auth_method(smp, local_io, remote_io);
2154         else
2155                 method = JUST_WORKS;
2156
2157         /* Don't confirm locally initiated pairing attempts */
2158         if (method == JUST_CFM && test_bit(SMP_FLAG_INITIATOR, &smp->flags))
2159                 method = JUST_WORKS;
2160
2161         return method;
2162 }
2163
2164 static int smp_cmd_public_key(struct l2cap_conn *conn, struct sk_buff *skb)
2165 {
2166         struct smp_cmd_public_key *key = (void *) skb->data;
2167         struct hci_conn *hcon = conn->hcon;
2168         struct l2cap_chan *chan = conn->smp;
2169         struct smp_chan *smp = chan->data;
2170         struct hci_dev *hdev = hcon->hdev;
2171         struct smp_cmd_pairing_confirm cfm;
2172         int err;
2173
2174         BT_DBG("conn %p", conn);
2175
2176         if (skb->len < sizeof(*key))
2177                 return SMP_INVALID_PARAMS;
2178
2179         memcpy(smp->remote_pk, key, 64);
2180
2181         /* Non-initiating device sends its public key after receiving
2182          * the key from the initiating device.
2183          */
2184         if (!hcon->out) {
2185                 err = sc_send_public_key(smp);
2186                 if (err)
2187                         return err;
2188         }
2189
2190         BT_DBG("Remote Public Key X: %32phN", smp->remote_pk);
2191         BT_DBG("Remote Public Key Y: %32phN", &smp->remote_pk[32]);
2192
2193         if (!ecdh_shared_secret(smp->remote_pk, smp->local_sk, smp->dhkey))
2194                 return SMP_UNSPECIFIED;
2195
2196         BT_DBG("DHKey %32phN", smp->dhkey);
2197
2198         set_bit(SMP_FLAG_REMOTE_PK, &smp->flags);
2199
2200         smp->method = sc_select_method(smp);
2201
2202         BT_DBG("%s selected method 0x%02x", hdev->name, smp->method);
2203
2204         /* JUST_WORKS and JUST_CFM result in an unauthenticated key */
2205         if (smp->method == JUST_WORKS || smp->method == JUST_CFM)
2206                 hcon->pending_sec_level = BT_SECURITY_MEDIUM;
2207         else
2208                 hcon->pending_sec_level = BT_SECURITY_FIPS;
2209
2210         if (!memcmp(debug_pk, smp->remote_pk, 64))
2211                 set_bit(SMP_FLAG_DEBUG_KEY, &smp->flags);
2212
2213         if (smp->method == DSP_PASSKEY) {
2214                 get_random_bytes(&hcon->passkey_notify,
2215                                  sizeof(hcon->passkey_notify));
2216                 hcon->passkey_notify %= 1000000;
2217                 hcon->passkey_entered = 0;
2218                 smp->passkey_round = 0;
2219                 if (mgmt_user_passkey_notify(hdev, &hcon->dst, hcon->type,
2220                                              hcon->dst_type,
2221                                              hcon->passkey_notify,
2222                                              hcon->passkey_entered))
2223                         return SMP_UNSPECIFIED;
2224                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
2225                 return sc_passkey_round(smp, SMP_CMD_PUBLIC_KEY);
2226         }
2227
2228         if (hcon->out)
2229                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
2230
2231         if (smp->method == REQ_PASSKEY) {
2232                 if (mgmt_user_passkey_request(hdev, &hcon->dst, hcon->type,
2233                                               hcon->dst_type))
2234                         return SMP_UNSPECIFIED;
2235                 SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_CONFIRM);
2236                 set_bit(SMP_FLAG_WAIT_USER, &smp->flags);
2237                 return 0;
2238         }
2239
2240         /* The Initiating device waits for the non-initiating device to
2241          * send the confirm value.
2242          */
2243         if (conn->hcon->out)
2244                 return 0;
2245
2246         err = smp_f4(smp->tfm_cmac, smp->local_pk, smp->remote_pk, smp->prnd,
2247                      0, cfm.confirm_val);
2248         if (err)
2249                 return SMP_UNSPECIFIED;
2250
2251         smp_send_cmd(conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cfm), &cfm);
2252         SMP_ALLOW_CMD(smp, SMP_CMD_PAIRING_RANDOM);
2253
2254         return 0;
2255 }
2256
2257 static int smp_cmd_dhkey_check(struct l2cap_conn *conn, struct sk_buff *skb)
2258 {
2259         struct smp_cmd_dhkey_check *check = (void *) skb->data;
2260         struct l2cap_chan *chan = conn->smp;
2261         struct hci_conn *hcon = conn->hcon;
2262         struct smp_chan *smp = chan->data;
2263         u8 a[7], b[7], *local_addr, *remote_addr;
2264         u8 io_cap[3], r[16], e[16];
2265         u8 key_type, auth;
2266         int err;
2267
2268         BT_DBG("conn %p", conn);
2269
2270         if (skb->len < sizeof(*check))
2271                 return SMP_INVALID_PARAMS;
2272
2273         memcpy(a, &hcon->init_addr, 6);
2274         memcpy(b, &hcon->resp_addr, 6);
2275         a[6] = hcon->init_addr_type;
2276         b[6] = hcon->resp_addr_type;
2277
2278         if (hcon->out) {
2279                 local_addr = a;
2280                 remote_addr = b;
2281                 memcpy(io_cap, &smp->prsp[1], 3);
2282         } else {
2283                 local_addr = b;
2284                 remote_addr = a;
2285                 memcpy(io_cap, &smp->preq[1], 3);
2286         }
2287
2288         memset(r, 0, sizeof(r));
2289
2290         if (smp->method == REQ_PASSKEY || smp->method == DSP_PASSKEY)
2291                 put_unaligned_le32(hcon->passkey_notify, r);
2292
2293         err = smp_f6(smp->tfm_cmac, smp->mackey, smp->rrnd, smp->prnd, r,
2294                      io_cap, remote_addr, local_addr, e);
2295         if (err)
2296                 return SMP_UNSPECIFIED;
2297
2298         if (memcmp(check->e, e, 16))
2299                 return SMP_DHKEY_CHECK_FAILED;
2300
2301         if (test_bit(SMP_FLAG_DEBUG_KEY, &smp->flags))
2302                 key_type = SMP_LTK_P256_DEBUG;
2303         else
2304                 key_type = SMP_LTK_P256;
2305
2306         if (hcon->pending_sec_level == BT_SECURITY_FIPS)
2307                 auth = 1;
2308         else
2309                 auth = 0;
2310
2311         smp->ltk = hci_add_ltk(hcon->hdev, &hcon->dst, hcon->dst_type,
2312                                key_type, auth, smp->tk, smp->enc_key_size,
2313                                0, 0);
2314
2315         if (hcon->out) {
2316                 hci_le_start_enc(hcon, 0, 0, smp->tk);
2317                 hcon->enc_key_size = smp->enc_key_size;
2318         }
2319
2320         return 0;
2321 }
2322
2323 static int smp_sig_channel(struct l2cap_chan *chan, struct sk_buff *skb)
2324 {
2325         struct l2cap_conn *conn = chan->conn;
2326         struct hci_conn *hcon = conn->hcon;
2327         struct smp_chan *smp;
2328         __u8 code, reason;
2329         int err = 0;
2330
2331         if (hcon->type != LE_LINK) {
2332                 kfree_skb(skb);
2333                 return 0;
2334         }
2335
2336         if (skb->len < 1)
2337                 return -EILSEQ;
2338
2339         if (!test_bit(HCI_LE_ENABLED, &hcon->hdev->dev_flags)) {
2340                 reason = SMP_PAIRING_NOTSUPP;
2341                 goto done;
2342         }
2343
2344         code = skb->data[0];
2345         skb_pull(skb, sizeof(code));
2346
2347         smp = chan->data;
2348
2349         if (code > SMP_CMD_MAX)
2350                 goto drop;
2351
2352         if (smp && !test_and_clear_bit(code, &smp->allow_cmd))
2353                 goto drop;
2354
2355         /* If we don't have a context the only allowed commands are
2356          * pairing request and security request.
2357          */
2358         if (!smp && code != SMP_CMD_PAIRING_REQ && code != SMP_CMD_SECURITY_REQ)
2359                 goto drop;
2360
2361         switch (code) {
2362         case SMP_CMD_PAIRING_REQ:
2363                 reason = smp_cmd_pairing_req(conn, skb);
2364                 break;
2365
2366         case SMP_CMD_PAIRING_FAIL:
2367                 smp_failure(conn, 0);
2368                 err = -EPERM;
2369                 break;
2370
2371         case SMP_CMD_PAIRING_RSP:
2372                 reason = smp_cmd_pairing_rsp(conn, skb);
2373                 break;
2374
2375         case SMP_CMD_SECURITY_REQ:
2376                 reason = smp_cmd_security_req(conn, skb);
2377                 break;
2378
2379         case SMP_CMD_PAIRING_CONFIRM:
2380                 reason = smp_cmd_pairing_confirm(conn, skb);
2381                 break;
2382
2383         case SMP_CMD_PAIRING_RANDOM:
2384                 reason = smp_cmd_pairing_random(conn, skb);
2385                 break;
2386
2387         case SMP_CMD_ENCRYPT_INFO:
2388                 reason = smp_cmd_encrypt_info(conn, skb);
2389                 break;
2390
2391         case SMP_CMD_MASTER_IDENT:
2392                 reason = smp_cmd_master_ident(conn, skb);
2393                 break;
2394
2395         case SMP_CMD_IDENT_INFO:
2396                 reason = smp_cmd_ident_info(conn, skb);
2397                 break;
2398
2399         case SMP_CMD_IDENT_ADDR_INFO:
2400                 reason = smp_cmd_ident_addr_info(conn, skb);
2401                 break;
2402
2403         case SMP_CMD_SIGN_INFO:
2404                 reason = smp_cmd_sign_info(conn, skb);
2405                 break;
2406
2407         case SMP_CMD_PUBLIC_KEY:
2408                 reason = smp_cmd_public_key(conn, skb);
2409                 break;
2410
2411         case SMP_CMD_DHKEY_CHECK:
2412                 reason = smp_cmd_dhkey_check(conn, skb);
2413                 break;
2414
2415         default:
2416                 BT_DBG("Unknown command code 0x%2.2x", code);
2417                 reason = SMP_CMD_NOTSUPP;
2418                 goto done;
2419         }
2420
2421 done:
2422         if (!err) {
2423                 if (reason)
2424                         smp_failure(conn, reason);
2425                 kfree_skb(skb);
2426         }
2427
2428         return err;
2429
2430 drop:
2431         BT_ERR("%s unexpected SMP command 0x%02x from %pMR", hcon->hdev->name,
2432                code, &hcon->dst);
2433         kfree_skb(skb);
2434         return 0;
2435 }
2436
2437 static void smp_teardown_cb(struct l2cap_chan *chan, int err)
2438 {
2439         struct l2cap_conn *conn = chan->conn;
2440
2441         BT_DBG("chan %p", chan);
2442
2443         if (chan->data)
2444                 smp_chan_destroy(conn);
2445
2446         conn->smp = NULL;
2447         l2cap_chan_put(chan);
2448 }
2449
2450 static void smp_resume_cb(struct l2cap_chan *chan)
2451 {
2452         struct smp_chan *smp = chan->data;
2453         struct l2cap_conn *conn = chan->conn;
2454         struct hci_conn *hcon = conn->hcon;
2455
2456         BT_DBG("chan %p", chan);
2457
2458         if (!smp)
2459                 return;
2460
2461         if (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags))
2462                 return;
2463
2464         cancel_delayed_work(&smp->security_timer);
2465
2466         smp_distribute_keys(smp);
2467 }
2468
2469 static void smp_ready_cb(struct l2cap_chan *chan)
2470 {
2471         struct l2cap_conn *conn = chan->conn;
2472
2473         BT_DBG("chan %p", chan);
2474
2475         conn->smp = chan;
2476         l2cap_chan_hold(chan);
2477 }
2478
2479 static int smp_recv_cb(struct l2cap_chan *chan, struct sk_buff *skb)
2480 {
2481         int err;
2482
2483         BT_DBG("chan %p", chan);
2484
2485         err = smp_sig_channel(chan, skb);
2486         if (err) {
2487                 struct smp_chan *smp = chan->data;
2488
2489                 if (smp)
2490                         cancel_delayed_work_sync(&smp->security_timer);
2491
2492                 hci_disconnect(chan->conn->hcon, HCI_ERROR_AUTH_FAILURE);
2493         }
2494
2495         return err;
2496 }
2497
2498 static struct sk_buff *smp_alloc_skb_cb(struct l2cap_chan *chan,
2499                                         unsigned long hdr_len,
2500                                         unsigned long len, int nb)
2501 {
2502         struct sk_buff *skb;
2503
2504         skb = bt_skb_alloc(hdr_len + len, GFP_KERNEL);
2505         if (!skb)
2506                 return ERR_PTR(-ENOMEM);
2507
2508         skb->priority = HCI_PRIO_MAX;
2509         bt_cb(skb)->chan = chan;
2510
2511         return skb;
2512 }
2513
2514 static const struct l2cap_ops smp_chan_ops = {
2515         .name                   = "Security Manager",
2516         .ready                  = smp_ready_cb,
2517         .recv                   = smp_recv_cb,
2518         .alloc_skb              = smp_alloc_skb_cb,
2519         .teardown               = smp_teardown_cb,
2520         .resume                 = smp_resume_cb,
2521
2522         .new_connection         = l2cap_chan_no_new_connection,
2523         .state_change           = l2cap_chan_no_state_change,
2524         .close                  = l2cap_chan_no_close,
2525         .defer                  = l2cap_chan_no_defer,
2526         .suspend                = l2cap_chan_no_suspend,
2527         .set_shutdown           = l2cap_chan_no_set_shutdown,
2528         .get_sndtimeo           = l2cap_chan_no_get_sndtimeo,
2529         .memcpy_fromiovec       = l2cap_chan_no_memcpy_fromiovec,
2530 };
2531
2532 static inline struct l2cap_chan *smp_new_conn_cb(struct l2cap_chan *pchan)
2533 {
2534         struct l2cap_chan *chan;
2535
2536         BT_DBG("pchan %p", pchan);
2537
2538         chan = l2cap_chan_create();
2539         if (!chan)
2540                 return NULL;
2541
2542         chan->chan_type = pchan->chan_type;
2543         chan->ops       = &smp_chan_ops;
2544         chan->scid      = pchan->scid;
2545         chan->dcid      = chan->scid;
2546         chan->imtu      = pchan->imtu;
2547         chan->omtu      = pchan->omtu;
2548         chan->mode      = pchan->mode;
2549
2550         /* Other L2CAP channels may request SMP routines in order to
2551          * change the security level. This means that the SMP channel
2552          * lock must be considered in its own category to avoid lockdep
2553          * warnings.
2554          */
2555         atomic_set(&chan->nesting, L2CAP_NESTING_SMP);
2556
2557         BT_DBG("created chan %p", chan);
2558
2559         return chan;
2560 }
2561
2562 static const struct l2cap_ops smp_root_chan_ops = {
2563         .name                   = "Security Manager Root",
2564         .new_connection         = smp_new_conn_cb,
2565
2566         /* None of these are implemented for the root channel */
2567         .close                  = l2cap_chan_no_close,
2568         .alloc_skb              = l2cap_chan_no_alloc_skb,
2569         .recv                   = l2cap_chan_no_recv,
2570         .state_change           = l2cap_chan_no_state_change,
2571         .teardown               = l2cap_chan_no_teardown,
2572         .ready                  = l2cap_chan_no_ready,
2573         .defer                  = l2cap_chan_no_defer,
2574         .suspend                = l2cap_chan_no_suspend,
2575         .resume                 = l2cap_chan_no_resume,
2576         .set_shutdown           = l2cap_chan_no_set_shutdown,
2577         .get_sndtimeo           = l2cap_chan_no_get_sndtimeo,
2578         .memcpy_fromiovec       = l2cap_chan_no_memcpy_fromiovec,
2579 };
2580
2581 int smp_register(struct hci_dev *hdev)
2582 {
2583         struct l2cap_chan *chan;
2584         struct crypto_blkcipher *tfm_aes;
2585
2586         BT_DBG("%s", hdev->name);
2587
2588         tfm_aes = crypto_alloc_blkcipher("ecb(aes)", 0, 0);
2589         if (IS_ERR(tfm_aes)) {
2590                 int err = PTR_ERR(tfm_aes);
2591                 BT_ERR("Unable to create crypto context");
2592                 return err;
2593         }
2594
2595         chan = l2cap_chan_create();
2596         if (!chan) {
2597                 crypto_free_blkcipher(tfm_aes);
2598                 return -ENOMEM;
2599         }
2600
2601         chan->data = tfm_aes;
2602
2603         l2cap_add_scid(chan, L2CAP_CID_SMP);
2604
2605         l2cap_chan_set_defaults(chan);
2606
2607         bacpy(&chan->src, &hdev->bdaddr);
2608         chan->src_type = BDADDR_LE_PUBLIC;
2609         chan->state = BT_LISTEN;
2610         chan->mode = L2CAP_MODE_BASIC;
2611         chan->imtu = L2CAP_DEFAULT_MTU;
2612         chan->ops = &smp_root_chan_ops;
2613
2614         /* Set correct nesting level for a parent/listening channel */
2615         atomic_set(&chan->nesting, L2CAP_NESTING_PARENT);
2616
2617         hdev->smp_data = chan;
2618
2619         return 0;
2620 }
2621
2622 void smp_unregister(struct hci_dev *hdev)
2623 {
2624         struct l2cap_chan *chan = hdev->smp_data;
2625         struct crypto_blkcipher *tfm_aes;
2626
2627         if (!chan)
2628                 return;
2629
2630         BT_DBG("%s chan %p", hdev->name, chan);
2631
2632         tfm_aes = chan->data;
2633         if (tfm_aes) {
2634                 chan->data = NULL;
2635                 crypto_free_blkcipher(tfm_aes);
2636         }
2637
2638         hdev->smp_data = NULL;
2639         l2cap_chan_put(chan);
2640 }