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