Bluetooth: Fix missing hdev locking in smp_cmd_ident_addr_info
[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 "smp.h"
33
34 #define SMP_TIMEOUT     msecs_to_jiffies(30000)
35
36 #define AUTH_REQ_MASK   0x07
37
38 enum {
39         SMP_FLAG_TK_VALID,
40         SMP_FLAG_CFM_PENDING,
41         SMP_FLAG_MITM_AUTH,
42         SMP_FLAG_COMPLETE,
43         SMP_FLAG_INITIATOR,
44 };
45
46 struct smp_chan {
47         struct l2cap_conn *conn;
48         u8              preq[7]; /* SMP Pairing Request */
49         u8              prsp[7]; /* SMP Pairing Response */
50         u8              prnd[16]; /* SMP Pairing Random (local) */
51         u8              rrnd[16]; /* SMP Pairing Random (remote) */
52         u8              pcnf[16]; /* SMP Pairing Confirm */
53         u8              tk[16]; /* SMP Temporary Key */
54         u8              enc_key_size;
55         u8              remote_key_dist;
56         bdaddr_t        id_addr;
57         u8              id_addr_type;
58         u8              irk[16];
59         struct smp_csrk *csrk;
60         struct smp_csrk *slave_csrk;
61         struct smp_ltk  *ltk;
62         struct smp_ltk  *slave_ltk;
63         struct smp_irk  *remote_irk;
64         unsigned long   flags;
65 };
66
67 static inline void swap_buf(const u8 *src, u8 *dst, size_t len)
68 {
69         size_t i;
70
71         for (i = 0; i < len; i++)
72                 dst[len - 1 - i] = src[i];
73 }
74
75 static int smp_e(struct crypto_blkcipher *tfm, const u8 *k, u8 *r)
76 {
77         struct blkcipher_desc desc;
78         struct scatterlist sg;
79         uint8_t tmp[16], data[16];
80         int err;
81
82         if (tfm == NULL) {
83                 BT_ERR("tfm %p", tfm);
84                 return -EINVAL;
85         }
86
87         desc.tfm = tfm;
88         desc.flags = 0;
89
90         /* The most significant octet of key corresponds to k[0] */
91         swap_buf(k, tmp, 16);
92
93         err = crypto_blkcipher_setkey(tfm, tmp, 16);
94         if (err) {
95                 BT_ERR("cipher setkey failed: %d", err);
96                 return err;
97         }
98
99         /* Most significant octet of plaintextData corresponds to data[0] */
100         swap_buf(r, data, 16);
101
102         sg_init_one(&sg, data, 16);
103
104         err = crypto_blkcipher_encrypt(&desc, &sg, &sg, 16);
105         if (err)
106                 BT_ERR("Encrypt data error %d", err);
107
108         /* Most significant octet of encryptedData corresponds to data[0] */
109         swap_buf(data, r, 16);
110
111         return err;
112 }
113
114 static int smp_ah(struct crypto_blkcipher *tfm, u8 irk[16], u8 r[3], u8 res[3])
115 {
116         u8 _res[16];
117         int err;
118
119         /* r' = padding || r */
120         memcpy(_res, r, 3);
121         memset(_res + 3, 0, 13);
122
123         err = smp_e(tfm, irk, _res);
124         if (err) {
125                 BT_ERR("Encrypt error");
126                 return err;
127         }
128
129         /* The output of the random address function ah is:
130          *      ah(h, r) = e(k, r') mod 2^24
131          * The output of the security function e is then truncated to 24 bits
132          * by taking the least significant 24 bits of the output of e as the
133          * result of ah.
134          */
135         memcpy(res, _res, 3);
136
137         return 0;
138 }
139
140 bool smp_irk_matches(struct crypto_blkcipher *tfm, u8 irk[16],
141                      bdaddr_t *bdaddr)
142 {
143         u8 hash[3];
144         int err;
145
146         BT_DBG("RPA %pMR IRK %*phN", bdaddr, 16, irk);
147
148         err = smp_ah(tfm, irk, &bdaddr->b[3], hash);
149         if (err)
150                 return false;
151
152         return !memcmp(bdaddr->b, hash, 3);
153 }
154
155 int smp_generate_rpa(struct crypto_blkcipher *tfm, u8 irk[16], bdaddr_t *rpa)
156 {
157         int err;
158
159         get_random_bytes(&rpa->b[3], 3);
160
161         rpa->b[5] &= 0x3f;      /* Clear two most significant bits */
162         rpa->b[5] |= 0x40;      /* Set second most significant bit */
163
164         err = smp_ah(tfm, irk, &rpa->b[3], rpa->b);
165         if (err < 0)
166                 return err;
167
168         BT_DBG("RPA %pMR", rpa);
169
170         return 0;
171 }
172
173 static int smp_c1(struct crypto_blkcipher *tfm, u8 k[16], u8 r[16],
174                   u8 preq[7], u8 pres[7], u8 _iat, bdaddr_t *ia,
175                   u8 _rat, bdaddr_t *ra, u8 res[16])
176 {
177         u8 p1[16], p2[16];
178         int err;
179
180         memset(p1, 0, 16);
181
182         /* p1 = pres || preq || _rat || _iat */
183         p1[0] = _iat;
184         p1[1] = _rat;
185         memcpy(p1 + 2, preq, 7);
186         memcpy(p1 + 9, pres, 7);
187
188         /* p2 = padding || ia || ra */
189         memcpy(p2, ra, 6);
190         memcpy(p2 + 6, ia, 6);
191         memset(p2 + 12, 0, 4);
192
193         /* res = r XOR p1 */
194         u128_xor((u128 *) res, (u128 *) r, (u128 *) p1);
195
196         /* res = e(k, res) */
197         err = smp_e(tfm, k, res);
198         if (err) {
199                 BT_ERR("Encrypt data error");
200                 return err;
201         }
202
203         /* res = res XOR p2 */
204         u128_xor((u128 *) res, (u128 *) res, (u128 *) p2);
205
206         /* res = e(k, res) */
207         err = smp_e(tfm, k, res);
208         if (err)
209                 BT_ERR("Encrypt data error");
210
211         return err;
212 }
213
214 static int smp_s1(struct crypto_blkcipher *tfm, u8 k[16], u8 r1[16],
215                   u8 r2[16], u8 _r[16])
216 {
217         int err;
218
219         /* Just least significant octets from r1 and r2 are considered */
220         memcpy(_r, r2, 8);
221         memcpy(_r + 8, r1, 8);
222
223         err = smp_e(tfm, k, _r);
224         if (err)
225                 BT_ERR("Encrypt data error");
226
227         return err;
228 }
229
230 static struct sk_buff *smp_build_cmd(struct l2cap_conn *conn, u8 code,
231                                      u16 dlen, void *data)
232 {
233         struct sk_buff *skb;
234         struct l2cap_hdr *lh;
235         int len;
236
237         len = L2CAP_HDR_SIZE + sizeof(code) + dlen;
238
239         if (len > conn->mtu)
240                 return NULL;
241
242         skb = bt_skb_alloc(len, GFP_ATOMIC);
243         if (!skb)
244                 return NULL;
245
246         lh = (struct l2cap_hdr *) skb_put(skb, L2CAP_HDR_SIZE);
247         lh->len = cpu_to_le16(sizeof(code) + dlen);
248         lh->cid = cpu_to_le16(L2CAP_CID_SMP);
249
250         memcpy(skb_put(skb, sizeof(code)), &code, sizeof(code));
251
252         memcpy(skb_put(skb, dlen), data, dlen);
253
254         return skb;
255 }
256
257 static void smp_send_cmd(struct l2cap_conn *conn, u8 code, u16 len, void *data)
258 {
259         struct sk_buff *skb = smp_build_cmd(conn, code, len, data);
260
261         BT_DBG("code 0x%2.2x", code);
262
263         if (!skb)
264                 return;
265
266         skb->priority = HCI_PRIO_MAX;
267         hci_send_acl(conn->hchan, skb, 0);
268
269         cancel_delayed_work_sync(&conn->security_timer);
270         schedule_delayed_work(&conn->security_timer, SMP_TIMEOUT);
271 }
272
273 static __u8 authreq_to_seclevel(__u8 authreq)
274 {
275         if (authreq & SMP_AUTH_MITM)
276                 return BT_SECURITY_HIGH;
277         else
278                 return BT_SECURITY_MEDIUM;
279 }
280
281 static __u8 seclevel_to_authreq(__u8 sec_level)
282 {
283         switch (sec_level) {
284         case BT_SECURITY_HIGH:
285                 return SMP_AUTH_MITM | SMP_AUTH_BONDING;
286         case BT_SECURITY_MEDIUM:
287                 return SMP_AUTH_BONDING;
288         default:
289                 return SMP_AUTH_NONE;
290         }
291 }
292
293 static void build_pairing_cmd(struct l2cap_conn *conn,
294                               struct smp_cmd_pairing *req,
295                               struct smp_cmd_pairing *rsp, __u8 authreq)
296 {
297         struct smp_chan *smp = conn->smp_chan;
298         struct hci_conn *hcon = conn->hcon;
299         struct hci_dev *hdev = hcon->hdev;
300         u8 local_dist = 0, remote_dist = 0;
301
302         if (test_bit(HCI_PAIRABLE, &conn->hcon->hdev->dev_flags)) {
303                 local_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
304                 remote_dist = SMP_DIST_ENC_KEY | SMP_DIST_SIGN;
305                 authreq |= SMP_AUTH_BONDING;
306         } else {
307                 authreq &= ~SMP_AUTH_BONDING;
308         }
309
310         if (test_bit(HCI_RPA_RESOLVING, &hdev->dev_flags))
311                 remote_dist |= SMP_DIST_ID_KEY;
312
313         if (test_bit(HCI_PRIVACY, &hdev->dev_flags))
314                 local_dist |= SMP_DIST_ID_KEY;
315
316         if (rsp == NULL) {
317                 req->io_capability = conn->hcon->io_capability;
318                 req->oob_flag = SMP_OOB_NOT_PRESENT;
319                 req->max_key_size = SMP_MAX_ENC_KEY_SIZE;
320                 req->init_key_dist = local_dist;
321                 req->resp_key_dist = remote_dist;
322                 req->auth_req = (authreq & AUTH_REQ_MASK);
323
324                 smp->remote_key_dist = remote_dist;
325                 return;
326         }
327
328         rsp->io_capability = conn->hcon->io_capability;
329         rsp->oob_flag = SMP_OOB_NOT_PRESENT;
330         rsp->max_key_size = SMP_MAX_ENC_KEY_SIZE;
331         rsp->init_key_dist = req->init_key_dist & remote_dist;
332         rsp->resp_key_dist = req->resp_key_dist & local_dist;
333         rsp->auth_req = (authreq & AUTH_REQ_MASK);
334
335         smp->remote_key_dist = rsp->init_key_dist;
336 }
337
338 static u8 check_enc_key_size(struct l2cap_conn *conn, __u8 max_key_size)
339 {
340         struct smp_chan *smp = conn->smp_chan;
341
342         if ((max_key_size > SMP_MAX_ENC_KEY_SIZE) ||
343             (max_key_size < SMP_MIN_ENC_KEY_SIZE))
344                 return SMP_ENC_KEY_SIZE;
345
346         smp->enc_key_size = max_key_size;
347
348         return 0;
349 }
350
351 static void smp_failure(struct l2cap_conn *conn, u8 reason)
352 {
353         struct hci_conn *hcon = conn->hcon;
354
355         if (reason)
356                 smp_send_cmd(conn, SMP_CMD_PAIRING_FAIL, sizeof(reason),
357                              &reason);
358
359         clear_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags);
360         mgmt_auth_failed(hcon->hdev, &hcon->dst, hcon->type, hcon->dst_type,
361                          HCI_ERROR_AUTH_FAILURE);
362
363         cancel_delayed_work_sync(&conn->security_timer);
364
365         if (test_and_clear_bit(HCI_CONN_LE_SMP_PEND, &hcon->flags))
366                 smp_chan_destroy(conn);
367 }
368
369 #define JUST_WORKS      0x00
370 #define JUST_CFM        0x01
371 #define REQ_PASSKEY     0x02
372 #define CFM_PASSKEY     0x03
373 #define REQ_OOB         0x04
374 #define OVERLAP         0xFF
375
376 static const u8 gen_method[5][5] = {
377         { JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
378         { JUST_WORKS,  JUST_CFM,    REQ_PASSKEY, JUST_WORKS, REQ_PASSKEY },
379         { CFM_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, CFM_PASSKEY },
380         { JUST_WORKS,  JUST_CFM,    JUST_WORKS,  JUST_WORKS, JUST_CFM    },
381         { CFM_PASSKEY, CFM_PASSKEY, REQ_PASSKEY, JUST_WORKS, OVERLAP     },
382 };
383
384 static u8 get_auth_method(struct smp_chan *smp, u8 local_io, u8 remote_io)
385 {
386         /* If either side has unknown io_caps, use JUST WORKS */
387         if (local_io > SMP_IO_KEYBOARD_DISPLAY ||
388             remote_io > SMP_IO_KEYBOARD_DISPLAY)
389                 return JUST_WORKS;
390
391         return gen_method[remote_io][local_io];
392 }
393
394 static int tk_request(struct l2cap_conn *conn, u8 remote_oob, u8 auth,
395                                                 u8 local_io, u8 remote_io)
396 {
397         struct hci_conn *hcon = conn->hcon;
398         struct smp_chan *smp = conn->smp_chan;
399         u8 method;
400         u32 passkey = 0;
401         int ret = 0;
402
403         /* Initialize key for JUST WORKS */
404         memset(smp->tk, 0, sizeof(smp->tk));
405         clear_bit(SMP_FLAG_TK_VALID, &smp->flags);
406
407         BT_DBG("tk_request: auth:%d lcl:%d rem:%d", auth, local_io, remote_io);
408
409         /* If neither side wants MITM, use JUST WORKS */
410         /* Otherwise, look up method from the table */
411         if (!(auth & SMP_AUTH_MITM))
412                 method = JUST_WORKS;
413         else
414                 method = get_auth_method(smp, local_io, remote_io);
415
416         /* If not bonding, don't ask user to confirm a Zero TK */
417         if (!(auth & SMP_AUTH_BONDING) && method == JUST_CFM)
418                 method = JUST_WORKS;
419
420         /* Don't confirm locally initiated pairing attempts */
421         if (method == JUST_CFM && test_bit(SMP_FLAG_INITIATOR, &smp->flags))
422                 method = JUST_WORKS;
423
424         /* If Just Works, Continue with Zero TK */
425         if (method == JUST_WORKS) {
426                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
427                 return 0;
428         }
429
430         /* Not Just Works/Confirm results in MITM Authentication */
431         if (method != JUST_CFM)
432                 set_bit(SMP_FLAG_MITM_AUTH, &smp->flags);
433
434         /* If both devices have Keyoard-Display I/O, the master
435          * Confirms and the slave Enters the passkey.
436          */
437         if (method == OVERLAP) {
438                 if (test_bit(HCI_CONN_MASTER, &hcon->flags))
439                         method = CFM_PASSKEY;
440                 else
441                         method = REQ_PASSKEY;
442         }
443
444         /* Generate random passkey. */
445         if (method == CFM_PASSKEY) {
446                 memset(smp->tk, 0, sizeof(smp->tk));
447                 get_random_bytes(&passkey, sizeof(passkey));
448                 passkey %= 1000000;
449                 put_unaligned_le32(passkey, smp->tk);
450                 BT_DBG("PassKey: %d", passkey);
451                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
452         }
453
454         hci_dev_lock(hcon->hdev);
455
456         if (method == REQ_PASSKEY)
457                 ret = mgmt_user_passkey_request(hcon->hdev, &hcon->dst,
458                                                 hcon->type, hcon->dst_type);
459         else if (method == JUST_CFM)
460                 ret = mgmt_user_confirm_request(hcon->hdev, &hcon->dst,
461                                                 hcon->type, hcon->dst_type,
462                                                 passkey, 1);
463         else
464                 ret = mgmt_user_passkey_notify(hcon->hdev, &hcon->dst,
465                                                 hcon->type, hcon->dst_type,
466                                                 passkey, 0);
467
468         hci_dev_unlock(hcon->hdev);
469
470         return ret;
471 }
472
473 static u8 smp_confirm(struct smp_chan *smp)
474 {
475         struct l2cap_conn *conn = smp->conn;
476         struct hci_dev *hdev = conn->hcon->hdev;
477         struct crypto_blkcipher *tfm = hdev->tfm_aes;
478         struct smp_cmd_pairing_confirm cp;
479         int ret;
480
481         BT_DBG("conn %p", conn);
482
483         /* Prevent mutual access to hdev->tfm_aes */
484         hci_dev_lock(hdev);
485
486         ret = smp_c1(tfm, smp->tk, smp->prnd, smp->preq, smp->prsp,
487                      conn->hcon->init_addr_type, &conn->hcon->init_addr,
488                      conn->hcon->resp_addr_type, &conn->hcon->resp_addr,
489                      cp.confirm_val);
490
491         hci_dev_unlock(hdev);
492
493         if (ret)
494                 return SMP_UNSPECIFIED;
495
496         clear_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
497
498         smp_send_cmd(smp->conn, SMP_CMD_PAIRING_CONFIRM, sizeof(cp), &cp);
499
500         return 0;
501 }
502
503 static u8 smp_random(struct smp_chan *smp)
504 {
505         struct l2cap_conn *conn = smp->conn;
506         struct hci_conn *hcon = conn->hcon;
507         struct hci_dev *hdev = hcon->hdev;
508         struct crypto_blkcipher *tfm = hdev->tfm_aes;
509         u8 confirm[16];
510         int ret;
511
512         if (IS_ERR_OR_NULL(tfm))
513                 return SMP_UNSPECIFIED;
514
515         BT_DBG("conn %p %s", conn, conn->hcon->out ? "master" : "slave");
516
517         /* Prevent mutual access to hdev->tfm_aes */
518         hci_dev_lock(hdev);
519
520         ret = smp_c1(tfm, smp->tk, smp->rrnd, smp->preq, smp->prsp,
521                      hcon->init_addr_type, &hcon->init_addr,
522                      hcon->resp_addr_type, &hcon->resp_addr, confirm);
523
524         hci_dev_unlock(hdev);
525
526         if (ret)
527                 return SMP_UNSPECIFIED;
528
529         if (memcmp(smp->pcnf, confirm, sizeof(smp->pcnf)) != 0) {
530                 BT_ERR("Pairing failed (confirmation values mismatch)");
531                 return SMP_CONFIRM_FAILED;
532         }
533
534         if (hcon->out) {
535                 u8 stk[16];
536                 __le64 rand = 0;
537                 __le16 ediv = 0;
538
539                 smp_s1(tfm, smp->tk, smp->rrnd, smp->prnd, stk);
540
541                 memset(stk + smp->enc_key_size, 0,
542                        SMP_MAX_ENC_KEY_SIZE - smp->enc_key_size);
543
544                 if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags))
545                         return SMP_UNSPECIFIED;
546
547                 hci_le_start_enc(hcon, ediv, rand, stk);
548                 hcon->enc_key_size = smp->enc_key_size;
549         } else {
550                 u8 stk[16], auth;
551                 __le64 rand = 0;
552                 __le16 ediv = 0;
553
554                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
555                              smp->prnd);
556
557                 smp_s1(tfm, smp->tk, smp->prnd, smp->rrnd, stk);
558
559                 memset(stk + smp->enc_key_size, 0,
560                        SMP_MAX_ENC_KEY_SIZE - smp->enc_key_size);
561
562                 if (hcon->pending_sec_level == BT_SECURITY_HIGH)
563                         auth = 1;
564                 else
565                         auth = 0;
566
567                 /* Even though there's no _SLAVE suffix this is the
568                  * slave STK we're adding for later lookup (the master
569                  * STK never needs to be stored).
570                  */
571                 hci_add_ltk(hcon->hdev, &hcon->dst, hcon->dst_type,
572                             SMP_STK, auth, stk, smp->enc_key_size, ediv, rand);
573         }
574
575         return 0;
576 }
577
578 static struct smp_chan *smp_chan_create(struct l2cap_conn *conn)
579 {
580         struct smp_chan *smp;
581
582         smp = kzalloc(sizeof(*smp), GFP_ATOMIC);
583         if (!smp)
584                 return NULL;
585
586         smp->conn = conn;
587         conn->smp_chan = smp;
588         conn->hcon->smp_conn = conn;
589
590         hci_conn_hold(conn->hcon);
591
592         return smp;
593 }
594
595 void smp_chan_destroy(struct l2cap_conn *conn)
596 {
597         struct smp_chan *smp = conn->smp_chan;
598         bool complete;
599
600         BUG_ON(!smp);
601
602         complete = test_bit(SMP_FLAG_COMPLETE, &smp->flags);
603         mgmt_smp_complete(conn->hcon, complete);
604
605         kfree(smp->csrk);
606         kfree(smp->slave_csrk);
607
608         /* If pairing failed clean up any keys we might have */
609         if (!complete) {
610                 if (smp->ltk) {
611                         list_del(&smp->ltk->list);
612                         kfree(smp->ltk);
613                 }
614
615                 if (smp->slave_ltk) {
616                         list_del(&smp->slave_ltk->list);
617                         kfree(smp->slave_ltk);
618                 }
619
620                 if (smp->remote_irk) {
621                         list_del(&smp->remote_irk->list);
622                         kfree(smp->remote_irk);
623                 }
624         }
625
626         kfree(smp);
627         conn->smp_chan = NULL;
628         conn->hcon->smp_conn = NULL;
629         hci_conn_drop(conn->hcon);
630 }
631
632 int smp_user_confirm_reply(struct hci_conn *hcon, u16 mgmt_op, __le32 passkey)
633 {
634         struct l2cap_conn *conn = hcon->smp_conn;
635         struct smp_chan *smp;
636         u32 value;
637
638         BT_DBG("");
639
640         if (!conn)
641                 return -ENOTCONN;
642
643         smp = conn->smp_chan;
644
645         switch (mgmt_op) {
646         case MGMT_OP_USER_PASSKEY_REPLY:
647                 value = le32_to_cpu(passkey);
648                 memset(smp->tk, 0, sizeof(smp->tk));
649                 BT_DBG("PassKey: %d", value);
650                 put_unaligned_le32(value, smp->tk);
651                 /* Fall Through */
652         case MGMT_OP_USER_CONFIRM_REPLY:
653                 set_bit(SMP_FLAG_TK_VALID, &smp->flags);
654                 break;
655         case MGMT_OP_USER_PASSKEY_NEG_REPLY:
656         case MGMT_OP_USER_CONFIRM_NEG_REPLY:
657                 smp_failure(conn, SMP_PASSKEY_ENTRY_FAILED);
658                 return 0;
659         default:
660                 smp_failure(conn, SMP_PASSKEY_ENTRY_FAILED);
661                 return -EOPNOTSUPP;
662         }
663
664         /* If it is our turn to send Pairing Confirm, do so now */
665         if (test_bit(SMP_FLAG_CFM_PENDING, &smp->flags)) {
666                 u8 rsp = smp_confirm(smp);
667                 if (rsp)
668                         smp_failure(conn, rsp);
669         }
670
671         return 0;
672 }
673
674 static u8 smp_cmd_pairing_req(struct l2cap_conn *conn, struct sk_buff *skb)
675 {
676         struct smp_cmd_pairing rsp, *req = (void *) skb->data;
677         struct smp_chan *smp;
678         u8 key_size, auth, sec_level;
679         int ret;
680
681         BT_DBG("conn %p", conn);
682
683         if (skb->len < sizeof(*req))
684                 return SMP_INVALID_PARAMS;
685
686         if (test_bit(HCI_CONN_MASTER, &conn->hcon->flags))
687                 return SMP_CMD_NOTSUPP;
688
689         if (!test_and_set_bit(HCI_CONN_LE_SMP_PEND, &conn->hcon->flags))
690                 smp = smp_chan_create(conn);
691         else
692                 smp = conn->smp_chan;
693
694         if (!smp)
695                 return SMP_UNSPECIFIED;
696
697         smp->preq[0] = SMP_CMD_PAIRING_REQ;
698         memcpy(&smp->preq[1], req, sizeof(*req));
699         skb_pull(skb, sizeof(*req));
700
701         /* We didn't start the pairing, so match remote */
702         auth = req->auth_req;
703
704         sec_level = authreq_to_seclevel(auth);
705         if (sec_level > conn->hcon->pending_sec_level)
706                 conn->hcon->pending_sec_level = sec_level;
707
708         /* If we need MITM check that it can be acheived */
709         if (conn->hcon->pending_sec_level >= BT_SECURITY_HIGH) {
710                 u8 method;
711
712                 method = get_auth_method(smp, conn->hcon->io_capability,
713                                          req->io_capability);
714                 if (method == JUST_WORKS || method == JUST_CFM)
715                         return SMP_AUTH_REQUIREMENTS;
716         }
717
718         build_pairing_cmd(conn, req, &rsp, auth);
719
720         key_size = min(req->max_key_size, rsp.max_key_size);
721         if (check_enc_key_size(conn, key_size))
722                 return SMP_ENC_KEY_SIZE;
723
724         get_random_bytes(smp->prnd, sizeof(smp->prnd));
725
726         smp->prsp[0] = SMP_CMD_PAIRING_RSP;
727         memcpy(&smp->prsp[1], &rsp, sizeof(rsp));
728
729         smp_send_cmd(conn, SMP_CMD_PAIRING_RSP, sizeof(rsp), &rsp);
730
731         /* Request setup of TK */
732         ret = tk_request(conn, 0, auth, rsp.io_capability, req->io_capability);
733         if (ret)
734                 return SMP_UNSPECIFIED;
735
736         clear_bit(SMP_FLAG_INITIATOR, &smp->flags);
737
738         return 0;
739 }
740
741 static u8 smp_cmd_pairing_rsp(struct l2cap_conn *conn, struct sk_buff *skb)
742 {
743         struct smp_cmd_pairing *req, *rsp = (void *) skb->data;
744         struct smp_chan *smp = conn->smp_chan;
745         u8 key_size, auth = SMP_AUTH_NONE;
746         int ret;
747
748         BT_DBG("conn %p", conn);
749
750         if (skb->len < sizeof(*rsp))
751                 return SMP_INVALID_PARAMS;
752
753         if (!test_bit(HCI_CONN_MASTER, &conn->hcon->flags))
754                 return SMP_CMD_NOTSUPP;
755
756         skb_pull(skb, sizeof(*rsp));
757
758         req = (void *) &smp->preq[1];
759
760         key_size = min(req->max_key_size, rsp->max_key_size);
761         if (check_enc_key_size(conn, key_size))
762                 return SMP_ENC_KEY_SIZE;
763
764         /* If we need MITM check that it can be acheived */
765         if (conn->hcon->pending_sec_level >= BT_SECURITY_HIGH) {
766                 u8 method;
767
768                 method = get_auth_method(smp, req->io_capability,
769                                          rsp->io_capability);
770                 if (method == JUST_WORKS || method == JUST_CFM)
771                         return SMP_AUTH_REQUIREMENTS;
772         }
773
774         get_random_bytes(smp->prnd, sizeof(smp->prnd));
775
776         smp->prsp[0] = SMP_CMD_PAIRING_RSP;
777         memcpy(&smp->prsp[1], rsp, sizeof(*rsp));
778
779         /* Update remote key distribution in case the remote cleared
780          * some bits that we had enabled in our request.
781          */
782         smp->remote_key_dist &= rsp->resp_key_dist;
783
784         if ((req->auth_req & SMP_AUTH_BONDING) &&
785             (rsp->auth_req & SMP_AUTH_BONDING))
786                 auth = SMP_AUTH_BONDING;
787
788         auth |= (req->auth_req | rsp->auth_req) & SMP_AUTH_MITM;
789
790         ret = tk_request(conn, 0, auth, req->io_capability, rsp->io_capability);
791         if (ret)
792                 return SMP_UNSPECIFIED;
793
794         set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
795
796         /* Can't compose response until we have been confirmed */
797         if (test_bit(SMP_FLAG_TK_VALID, &smp->flags))
798                 return smp_confirm(smp);
799
800         return 0;
801 }
802
803 static u8 smp_cmd_pairing_confirm(struct l2cap_conn *conn, struct sk_buff *skb)
804 {
805         struct smp_chan *smp = conn->smp_chan;
806
807         BT_DBG("conn %p %s", conn, conn->hcon->out ? "master" : "slave");
808
809         if (skb->len < sizeof(smp->pcnf))
810                 return SMP_INVALID_PARAMS;
811
812         memcpy(smp->pcnf, skb->data, sizeof(smp->pcnf));
813         skb_pull(skb, sizeof(smp->pcnf));
814
815         if (conn->hcon->out)
816                 smp_send_cmd(conn, SMP_CMD_PAIRING_RANDOM, sizeof(smp->prnd),
817                              smp->prnd);
818         else if (test_bit(SMP_FLAG_TK_VALID, &smp->flags))
819                 return smp_confirm(smp);
820         else
821                 set_bit(SMP_FLAG_CFM_PENDING, &smp->flags);
822
823         return 0;
824 }
825
826 static u8 smp_cmd_pairing_random(struct l2cap_conn *conn, struct sk_buff *skb)
827 {
828         struct smp_chan *smp = conn->smp_chan;
829
830         BT_DBG("conn %p", conn);
831
832         if (skb->len < sizeof(smp->rrnd))
833                 return SMP_INVALID_PARAMS;
834
835         memcpy(smp->rrnd, skb->data, sizeof(smp->rrnd));
836         skb_pull(skb, sizeof(smp->rrnd));
837
838         return smp_random(smp);
839 }
840
841 static u8 smp_ltk_encrypt(struct l2cap_conn *conn, u8 sec_level)
842 {
843         struct smp_ltk *key;
844         struct hci_conn *hcon = conn->hcon;
845
846         key = hci_find_ltk_by_addr(hcon->hdev, &hcon->dst, hcon->dst_type,
847                                    hcon->out);
848         if (!key)
849                 return 0;
850
851         if (sec_level > BT_SECURITY_MEDIUM && !key->authenticated)
852                 return 0;
853
854         if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &hcon->flags))
855                 return 1;
856
857         hci_le_start_enc(hcon, key->ediv, key->rand, key->val);
858         hcon->enc_key_size = key->enc_size;
859
860         return 1;
861 }
862
863 static u8 smp_cmd_security_req(struct l2cap_conn *conn, struct sk_buff *skb)
864 {
865         struct smp_cmd_security_req *rp = (void *) skb->data;
866         struct smp_cmd_pairing cp;
867         struct hci_conn *hcon = conn->hcon;
868         struct smp_chan *smp;
869         u8 sec_level;
870
871         BT_DBG("conn %p", conn);
872
873         if (skb->len < sizeof(*rp))
874                 return SMP_INVALID_PARAMS;
875
876         if (!test_bit(HCI_CONN_MASTER, &conn->hcon->flags))
877                 return SMP_CMD_NOTSUPP;
878
879         sec_level = authreq_to_seclevel(rp->auth_req);
880         if (sec_level > hcon->pending_sec_level)
881                 hcon->pending_sec_level = sec_level;
882
883         if (smp_ltk_encrypt(conn, hcon->pending_sec_level))
884                 return 0;
885
886         if (test_and_set_bit(HCI_CONN_LE_SMP_PEND, &hcon->flags))
887                 return 0;
888
889         smp = smp_chan_create(conn);
890         if (!smp)
891                 return SMP_UNSPECIFIED;
892
893         skb_pull(skb, sizeof(*rp));
894
895         memset(&cp, 0, sizeof(cp));
896         build_pairing_cmd(conn, &cp, NULL, rp->auth_req);
897
898         smp->preq[0] = SMP_CMD_PAIRING_REQ;
899         memcpy(&smp->preq[1], &cp, sizeof(cp));
900
901         smp_send_cmd(conn, SMP_CMD_PAIRING_REQ, sizeof(cp), &cp);
902
903         clear_bit(SMP_FLAG_INITIATOR, &smp->flags);
904
905         return 0;
906 }
907
908 bool smp_sufficient_security(struct hci_conn *hcon, u8 sec_level)
909 {
910         if (sec_level == BT_SECURITY_LOW)
911                 return true;
912
913         if (hcon->sec_level >= sec_level)
914                 return true;
915
916         return false;
917 }
918
919 int smp_conn_security(struct hci_conn *hcon, __u8 sec_level)
920 {
921         struct l2cap_conn *conn = hcon->l2cap_data;
922         struct smp_chan *smp;
923         __u8 authreq;
924
925         BT_DBG("conn %p hcon %p level 0x%2.2x", conn, hcon, sec_level);
926
927         /* This may be NULL if there's an unexpected disconnection */
928         if (!conn)
929                 return 1;
930
931         if (!test_bit(HCI_LE_ENABLED, &hcon->hdev->dev_flags))
932                 return 1;
933
934         if (smp_sufficient_security(hcon, sec_level))
935                 return 1;
936
937         if (sec_level > hcon->pending_sec_level)
938                 hcon->pending_sec_level = sec_level;
939
940         if (test_bit(HCI_CONN_MASTER, &hcon->flags))
941                 if (smp_ltk_encrypt(conn, hcon->pending_sec_level))
942                         return 0;
943
944         if (test_and_set_bit(HCI_CONN_LE_SMP_PEND, &hcon->flags))
945                 return 0;
946
947         smp = smp_chan_create(conn);
948         if (!smp)
949                 return 1;
950
951         authreq = seclevel_to_authreq(sec_level);
952
953         /* Require MITM if IO Capability allows or the security level
954          * requires it.
955          */
956         if (hcon->io_capability != HCI_IO_NO_INPUT_OUTPUT ||
957             hcon->pending_sec_level > BT_SECURITY_MEDIUM)
958                 authreq |= SMP_AUTH_MITM;
959
960         if (test_bit(HCI_CONN_MASTER, &hcon->flags)) {
961                 struct smp_cmd_pairing cp;
962
963                 build_pairing_cmd(conn, &cp, NULL, authreq);
964                 smp->preq[0] = SMP_CMD_PAIRING_REQ;
965                 memcpy(&smp->preq[1], &cp, sizeof(cp));
966
967                 smp_send_cmd(conn, SMP_CMD_PAIRING_REQ, sizeof(cp), &cp);
968         } else {
969                 struct smp_cmd_security_req cp;
970                 cp.auth_req = authreq;
971                 smp_send_cmd(conn, SMP_CMD_SECURITY_REQ, sizeof(cp), &cp);
972         }
973
974         set_bit(SMP_FLAG_INITIATOR, &smp->flags);
975
976         return 0;
977 }
978
979 static int smp_cmd_encrypt_info(struct l2cap_conn *conn, struct sk_buff *skb)
980 {
981         struct smp_cmd_encrypt_info *rp = (void *) skb->data;
982         struct smp_chan *smp = conn->smp_chan;
983
984         BT_DBG("conn %p", conn);
985
986         if (skb->len < sizeof(*rp))
987                 return SMP_INVALID_PARAMS;
988
989         /* Ignore this PDU if it wasn't requested */
990         if (!(smp->remote_key_dist & SMP_DIST_ENC_KEY))
991                 return 0;
992
993         skb_pull(skb, sizeof(*rp));
994
995         memcpy(smp->tk, rp->ltk, sizeof(smp->tk));
996
997         return 0;
998 }
999
1000 static int smp_cmd_master_ident(struct l2cap_conn *conn, struct sk_buff *skb)
1001 {
1002         struct smp_cmd_master_ident *rp = (void *) skb->data;
1003         struct smp_chan *smp = conn->smp_chan;
1004         struct hci_dev *hdev = conn->hcon->hdev;
1005         struct hci_conn *hcon = conn->hcon;
1006         struct smp_ltk *ltk;
1007         u8 authenticated;
1008
1009         BT_DBG("conn %p", conn);
1010
1011         if (skb->len < sizeof(*rp))
1012                 return SMP_INVALID_PARAMS;
1013
1014         /* Ignore this PDU if it wasn't requested */
1015         if (!(smp->remote_key_dist & SMP_DIST_ENC_KEY))
1016                 return 0;
1017
1018         /* Mark the information as received */
1019         smp->remote_key_dist &= ~SMP_DIST_ENC_KEY;
1020
1021         skb_pull(skb, sizeof(*rp));
1022
1023         hci_dev_lock(hdev);
1024         authenticated = (hcon->sec_level == BT_SECURITY_HIGH);
1025         ltk = hci_add_ltk(hdev, &hcon->dst, hcon->dst_type, SMP_LTK,
1026                           authenticated, smp->tk, smp->enc_key_size,
1027                           rp->ediv, rp->rand);
1028         smp->ltk = ltk;
1029         if (!(smp->remote_key_dist & SMP_DIST_ID_KEY))
1030                 smp_distribute_keys(conn);
1031         hci_dev_unlock(hdev);
1032
1033         return 0;
1034 }
1035
1036 static int smp_cmd_ident_info(struct l2cap_conn *conn, struct sk_buff *skb)
1037 {
1038         struct smp_cmd_ident_info *info = (void *) skb->data;
1039         struct smp_chan *smp = conn->smp_chan;
1040
1041         BT_DBG("");
1042
1043         if (skb->len < sizeof(*info))
1044                 return SMP_INVALID_PARAMS;
1045
1046         /* Ignore this PDU if it wasn't requested */
1047         if (!(smp->remote_key_dist & SMP_DIST_ID_KEY))
1048                 return 0;
1049
1050         skb_pull(skb, sizeof(*info));
1051
1052         memcpy(smp->irk, info->irk, 16);
1053
1054         return 0;
1055 }
1056
1057 static int smp_cmd_ident_addr_info(struct l2cap_conn *conn,
1058                                    struct sk_buff *skb)
1059 {
1060         struct smp_cmd_ident_addr_info *info = (void *) skb->data;
1061         struct smp_chan *smp = conn->smp_chan;
1062         struct hci_conn *hcon = conn->hcon;
1063         bdaddr_t rpa;
1064
1065         BT_DBG("");
1066
1067         if (skb->len < sizeof(*info))
1068                 return SMP_INVALID_PARAMS;
1069
1070         /* Ignore this PDU if it wasn't requested */
1071         if (!(smp->remote_key_dist & SMP_DIST_ID_KEY))
1072                 return 0;
1073
1074         /* Mark the information as received */
1075         smp->remote_key_dist &= ~SMP_DIST_ID_KEY;
1076
1077         skb_pull(skb, sizeof(*info));
1078
1079         hci_dev_lock(hcon->hdev);
1080
1081         /* Strictly speaking the Core Specification (4.1) allows sending
1082          * an empty address which would force us to rely on just the IRK
1083          * as "identity information". However, since such
1084          * implementations are not known of and in order to not over
1085          * complicate our implementation, simply pretend that we never
1086          * received an IRK for such a device.
1087          */
1088         if (!bacmp(&info->bdaddr, BDADDR_ANY)) {
1089                 BT_ERR("Ignoring IRK with no identity address");
1090                 goto distribute;
1091         }
1092
1093         bacpy(&smp->id_addr, &info->bdaddr);
1094         smp->id_addr_type = info->addr_type;
1095
1096         if (hci_bdaddr_is_rpa(&hcon->dst, hcon->dst_type))
1097                 bacpy(&rpa, &hcon->dst);
1098         else
1099                 bacpy(&rpa, BDADDR_ANY);
1100
1101         smp->remote_irk = hci_add_irk(conn->hcon->hdev, &smp->id_addr,
1102                                       smp->id_addr_type, smp->irk, &rpa);
1103
1104 distribute:
1105         smp_distribute_keys(conn);
1106
1107         hci_dev_unlock(hcon->hdev);
1108
1109         return 0;
1110 }
1111
1112 static int smp_cmd_sign_info(struct l2cap_conn *conn, struct sk_buff *skb)
1113 {
1114         struct smp_cmd_sign_info *rp = (void *) skb->data;
1115         struct smp_chan *smp = conn->smp_chan;
1116         struct hci_dev *hdev = conn->hcon->hdev;
1117         struct smp_csrk *csrk;
1118
1119         BT_DBG("conn %p", conn);
1120
1121         if (skb->len < sizeof(*rp))
1122                 return SMP_INVALID_PARAMS;
1123
1124         /* Ignore this PDU if it wasn't requested */
1125         if (!(smp->remote_key_dist & SMP_DIST_SIGN))
1126                 return 0;
1127
1128         /* Mark the information as received */
1129         smp->remote_key_dist &= ~SMP_DIST_SIGN;
1130
1131         skb_pull(skb, sizeof(*rp));
1132
1133         hci_dev_lock(hdev);
1134         csrk = kzalloc(sizeof(*csrk), GFP_KERNEL);
1135         if (csrk) {
1136                 csrk->master = 0x01;
1137                 memcpy(csrk->val, rp->csrk, sizeof(csrk->val));
1138         }
1139         smp->csrk = csrk;
1140         if (!(smp->remote_key_dist & SMP_DIST_SIGN))
1141                 smp_distribute_keys(conn);
1142         hci_dev_unlock(hdev);
1143
1144         return 0;
1145 }
1146
1147 int smp_sig_channel(struct l2cap_conn *conn, struct sk_buff *skb)
1148 {
1149         struct hci_conn *hcon = conn->hcon;
1150         __u8 code, reason;
1151         int err = 0;
1152
1153         if (hcon->type != LE_LINK) {
1154                 kfree_skb(skb);
1155                 return 0;
1156         }
1157
1158         if (skb->len < 1) {
1159                 kfree_skb(skb);
1160                 return -EILSEQ;
1161         }
1162
1163         if (!test_bit(HCI_LE_ENABLED, &hcon->hdev->dev_flags)) {
1164                 err = -ENOTSUPP;
1165                 reason = SMP_PAIRING_NOTSUPP;
1166                 goto done;
1167         }
1168
1169         code = skb->data[0];
1170         skb_pull(skb, sizeof(code));
1171
1172         /*
1173          * The SMP context must be initialized for all other PDUs except
1174          * pairing and security requests. If we get any other PDU when
1175          * not initialized simply disconnect (done if this function
1176          * returns an error).
1177          */
1178         if (code != SMP_CMD_PAIRING_REQ && code != SMP_CMD_SECURITY_REQ &&
1179             !conn->smp_chan) {
1180                 BT_ERR("Unexpected SMP command 0x%02x. Disconnecting.", code);
1181                 kfree_skb(skb);
1182                 return -ENOTSUPP;
1183         }
1184
1185         switch (code) {
1186         case SMP_CMD_PAIRING_REQ:
1187                 reason = smp_cmd_pairing_req(conn, skb);
1188                 break;
1189
1190         case SMP_CMD_PAIRING_FAIL:
1191                 smp_failure(conn, 0);
1192                 reason = 0;
1193                 err = -EPERM;
1194                 break;
1195
1196         case SMP_CMD_PAIRING_RSP:
1197                 reason = smp_cmd_pairing_rsp(conn, skb);
1198                 break;
1199
1200         case SMP_CMD_SECURITY_REQ:
1201                 reason = smp_cmd_security_req(conn, skb);
1202                 break;
1203
1204         case SMP_CMD_PAIRING_CONFIRM:
1205                 reason = smp_cmd_pairing_confirm(conn, skb);
1206                 break;
1207
1208         case SMP_CMD_PAIRING_RANDOM:
1209                 reason = smp_cmd_pairing_random(conn, skb);
1210                 break;
1211
1212         case SMP_CMD_ENCRYPT_INFO:
1213                 reason = smp_cmd_encrypt_info(conn, skb);
1214                 break;
1215
1216         case SMP_CMD_MASTER_IDENT:
1217                 reason = smp_cmd_master_ident(conn, skb);
1218                 break;
1219
1220         case SMP_CMD_IDENT_INFO:
1221                 reason = smp_cmd_ident_info(conn, skb);
1222                 break;
1223
1224         case SMP_CMD_IDENT_ADDR_INFO:
1225                 reason = smp_cmd_ident_addr_info(conn, skb);
1226                 break;
1227
1228         case SMP_CMD_SIGN_INFO:
1229                 reason = smp_cmd_sign_info(conn, skb);
1230                 break;
1231
1232         default:
1233                 BT_DBG("Unknown command code 0x%2.2x", code);
1234
1235                 reason = SMP_CMD_NOTSUPP;
1236                 err = -EOPNOTSUPP;
1237                 goto done;
1238         }
1239
1240 done:
1241         if (reason)
1242                 smp_failure(conn, reason);
1243
1244         kfree_skb(skb);
1245         return err;
1246 }
1247
1248 static void smp_notify_keys(struct l2cap_conn *conn)
1249 {
1250         struct smp_chan *smp = conn->smp_chan;
1251         struct hci_conn *hcon = conn->hcon;
1252         struct hci_dev *hdev = hcon->hdev;
1253         struct smp_cmd_pairing *req = (void *) &smp->preq[1];
1254         struct smp_cmd_pairing *rsp = (void *) &smp->prsp[1];
1255         bool persistent;
1256
1257         if (smp->remote_irk) {
1258                 mgmt_new_irk(hdev, smp->remote_irk);
1259                 /* Now that user space can be considered to know the
1260                  * identity address track the connection based on it
1261                  * from now on.
1262                  */
1263                 bacpy(&hcon->dst, &smp->remote_irk->bdaddr);
1264                 hcon->dst_type = smp->remote_irk->addr_type;
1265                 l2cap_conn_update_id_addr(hcon);
1266         }
1267
1268         /* The LTKs and CSRKs should be persistent only if both sides
1269          * had the bonding bit set in their authentication requests.
1270          */
1271         persistent = !!((req->auth_req & rsp->auth_req) & SMP_AUTH_BONDING);
1272
1273         if (smp->csrk) {
1274                 smp->csrk->bdaddr_type = hcon->dst_type;
1275                 bacpy(&smp->csrk->bdaddr, &hcon->dst);
1276                 mgmt_new_csrk(hdev, smp->csrk, persistent);
1277         }
1278
1279         if (smp->slave_csrk) {
1280                 smp->slave_csrk->bdaddr_type = hcon->dst_type;
1281                 bacpy(&smp->slave_csrk->bdaddr, &hcon->dst);
1282                 mgmt_new_csrk(hdev, smp->slave_csrk, persistent);
1283         }
1284
1285         if (smp->ltk) {
1286                 smp->ltk->bdaddr_type = hcon->dst_type;
1287                 bacpy(&smp->ltk->bdaddr, &hcon->dst);
1288                 mgmt_new_ltk(hdev, smp->ltk, persistent);
1289         }
1290
1291         if (smp->slave_ltk) {
1292                 smp->slave_ltk->bdaddr_type = hcon->dst_type;
1293                 bacpy(&smp->slave_ltk->bdaddr, &hcon->dst);
1294                 mgmt_new_ltk(hdev, smp->slave_ltk, persistent);
1295         }
1296 }
1297
1298 int smp_distribute_keys(struct l2cap_conn *conn)
1299 {
1300         struct smp_cmd_pairing *req, *rsp;
1301         struct smp_chan *smp = conn->smp_chan;
1302         struct hci_conn *hcon = conn->hcon;
1303         struct hci_dev *hdev = hcon->hdev;
1304         __u8 *keydist;
1305
1306         BT_DBG("conn %p", conn);
1307
1308         if (!test_bit(HCI_CONN_LE_SMP_PEND, &hcon->flags))
1309                 return 0;
1310
1311         rsp = (void *) &smp->prsp[1];
1312
1313         /* The responder sends its keys first */
1314         if (hcon->out && (smp->remote_key_dist & 0x07))
1315                 return 0;
1316
1317         req = (void *) &smp->preq[1];
1318
1319         if (hcon->out) {
1320                 keydist = &rsp->init_key_dist;
1321                 *keydist &= req->init_key_dist;
1322         } else {
1323                 keydist = &rsp->resp_key_dist;
1324                 *keydist &= req->resp_key_dist;
1325         }
1326
1327         BT_DBG("keydist 0x%x", *keydist);
1328
1329         if (*keydist & SMP_DIST_ENC_KEY) {
1330                 struct smp_cmd_encrypt_info enc;
1331                 struct smp_cmd_master_ident ident;
1332                 struct smp_ltk *ltk;
1333                 u8 authenticated;
1334                 __le16 ediv;
1335                 __le64 rand;
1336
1337                 get_random_bytes(enc.ltk, sizeof(enc.ltk));
1338                 get_random_bytes(&ediv, sizeof(ediv));
1339                 get_random_bytes(&rand, sizeof(rand));
1340
1341                 smp_send_cmd(conn, SMP_CMD_ENCRYPT_INFO, sizeof(enc), &enc);
1342
1343                 authenticated = hcon->sec_level == BT_SECURITY_HIGH;
1344                 ltk = hci_add_ltk(hdev, &hcon->dst, hcon->dst_type,
1345                                   SMP_LTK_SLAVE, authenticated, enc.ltk,
1346                                   smp->enc_key_size, ediv, rand);
1347                 smp->slave_ltk = ltk;
1348
1349                 ident.ediv = ediv;
1350                 ident.rand = rand;
1351
1352                 smp_send_cmd(conn, SMP_CMD_MASTER_IDENT, sizeof(ident), &ident);
1353
1354                 *keydist &= ~SMP_DIST_ENC_KEY;
1355         }
1356
1357         if (*keydist & SMP_DIST_ID_KEY) {
1358                 struct smp_cmd_ident_addr_info addrinfo;
1359                 struct smp_cmd_ident_info idinfo;
1360
1361                 memcpy(idinfo.irk, hdev->irk, sizeof(idinfo.irk));
1362
1363                 smp_send_cmd(conn, SMP_CMD_IDENT_INFO, sizeof(idinfo), &idinfo);
1364
1365                 /* The hci_conn contains the local identity address
1366                  * after the connection has been established.
1367                  *
1368                  * This is true even when the connection has been
1369                  * established using a resolvable random address.
1370                  */
1371                 bacpy(&addrinfo.bdaddr, &hcon->src);
1372                 addrinfo.addr_type = hcon->src_type;
1373
1374                 smp_send_cmd(conn, SMP_CMD_IDENT_ADDR_INFO, sizeof(addrinfo),
1375                              &addrinfo);
1376
1377                 *keydist &= ~SMP_DIST_ID_KEY;
1378         }
1379
1380         if (*keydist & SMP_DIST_SIGN) {
1381                 struct smp_cmd_sign_info sign;
1382                 struct smp_csrk *csrk;
1383
1384                 /* Generate a new random key */
1385                 get_random_bytes(sign.csrk, sizeof(sign.csrk));
1386
1387                 csrk = kzalloc(sizeof(*csrk), GFP_KERNEL);
1388                 if (csrk) {
1389                         csrk->master = 0x00;
1390                         memcpy(csrk->val, sign.csrk, sizeof(csrk->val));
1391                 }
1392                 smp->slave_csrk = csrk;
1393
1394                 smp_send_cmd(conn, SMP_CMD_SIGN_INFO, sizeof(sign), &sign);
1395
1396                 *keydist &= ~SMP_DIST_SIGN;
1397         }
1398
1399         /* If there are still keys to be received wait for them */
1400         if ((smp->remote_key_dist & 0x07))
1401                 return 0;
1402
1403         clear_bit(HCI_CONN_LE_SMP_PEND, &hcon->flags);
1404         cancel_delayed_work_sync(&conn->security_timer);
1405         set_bit(SMP_FLAG_COMPLETE, &smp->flags);
1406         smp_notify_keys(conn);
1407
1408         smp_chan_destroy(conn);
1409
1410         return 0;
1411 }