OSDN Git Service

Merge "packet: Add Packet classes and tests" am: a275910a49
[android-x86/system-bt.git] / stack / smp / smp_utils.cc
1 /******************************************************************************
2  *
3  *  Copyright 1999-2012 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *****************************************************************************/
18
19 /******************************************************************************
20  *
21  *  This file contains functions for the SMP L2CAP utility functions
22  *
23  ******************************************************************************/
24 #include "bt_target.h"
25
26 #include <ctype.h>
27 #include <string.h>
28 #include "bt_types.h"
29 #include "bt_utils.h"
30 #include "btm_ble_api.h"
31 #include "btm_int.h"
32 #include "common/metrics.h"
33 #include "device/include/controller.h"
34 #include "hcidefs.h"
35 #include "l2c_api.h"
36 #include "l2c_int.h"
37 #include "osi/include/osi.h"
38 #include "smp_int.h"
39
40 #define SMP_PAIRING_REQ_SIZE 7
41 #define SMP_CONFIRM_CMD_SIZE (OCTET16_LEN + 1)
42 #define SMP_RAND_CMD_SIZE (OCTET16_LEN + 1)
43 #define SMP_INIT_CMD_SIZE (OCTET16_LEN + 1)
44 #define SMP_ENC_INFO_SIZE (OCTET16_LEN + 1)
45 #define SMP_MASTER_ID_SIZE (BT_OCTET8_LEN + 2 + 1)
46 #define SMP_ID_INFO_SIZE (OCTET16_LEN + 1)
47 #define SMP_ID_ADDR_SIZE (BD_ADDR_LEN + 1 + 1)
48 #define SMP_SIGN_INFO_SIZE (OCTET16_LEN + 1)
49 #define SMP_PAIR_FAIL_SIZE 2
50 #define SMP_SECURITY_REQUEST_SIZE 2
51 #define SMP_PAIR_PUBL_KEY_SIZE (1 /* opcode */ + (2 * BT_OCTET32_LEN))
52 #define SMP_PAIR_COMMITM_SIZE (1 /* opcode */ + OCTET16_LEN /*Commitment*/)
53 #define SMP_PAIR_DHKEY_CHECK_SIZE \
54   (1 /* opcode */ + OCTET16_LEN /*DHKey \
55                                                                    Check*/)
56 #define SMP_PAIR_KEYPR_NOTIF_SIZE (1 /* opcode */ + 1 /*Notif Type*/)
57
58 /* SMP command sizes per spec */
59 static const uint8_t smp_cmd_size_per_spec[] = {
60     0,
61     SMP_PAIRING_REQ_SIZE,      /* 0x01: pairing request */
62     SMP_PAIRING_REQ_SIZE,      /* 0x02: pairing response */
63     SMP_CONFIRM_CMD_SIZE,      /* 0x03: pairing confirm */
64     SMP_RAND_CMD_SIZE,         /* 0x04: pairing random */
65     SMP_PAIR_FAIL_SIZE,        /* 0x05: pairing failed */
66     SMP_ENC_INFO_SIZE,         /* 0x06: encryption information */
67     SMP_MASTER_ID_SIZE,        /* 0x07: master identification */
68     SMP_ID_INFO_SIZE,          /* 0x08: identity information */
69     SMP_ID_ADDR_SIZE,          /* 0x09: identity address information */
70     SMP_SIGN_INFO_SIZE,        /* 0x0A: signing information */
71     SMP_SECURITY_REQUEST_SIZE, /* 0x0B: security request */
72     SMP_PAIR_PUBL_KEY_SIZE,    /* 0x0C: pairing public key */
73     SMP_PAIR_DHKEY_CHECK_SIZE, /* 0x0D: pairing dhkey check */
74     SMP_PAIR_KEYPR_NOTIF_SIZE, /* 0x0E: pairing keypress notification */
75     SMP_PAIR_COMMITM_SIZE      /* 0x0F: pairing commitment */
76 };
77
78 static bool smp_parameter_unconditionally_valid(tSMP_CB* p_cb);
79 static bool smp_parameter_unconditionally_invalid(tSMP_CB* p_cb);
80
81 /* type for SMP command length validation functions */
82 typedef bool (*tSMP_CMD_LEN_VALID)(tSMP_CB* p_cb);
83
84 static bool smp_command_has_valid_fixed_length(tSMP_CB* p_cb);
85
86 static const tSMP_CMD_LEN_VALID smp_cmd_len_is_valid[] = {
87     smp_parameter_unconditionally_invalid,
88     smp_command_has_valid_fixed_length, /* 0x01: pairing request */
89     smp_command_has_valid_fixed_length, /* 0x02: pairing response */
90     smp_command_has_valid_fixed_length, /* 0x03: pairing confirm */
91     smp_command_has_valid_fixed_length, /* 0x04: pairing random */
92     smp_command_has_valid_fixed_length, /* 0x05: pairing failed */
93     smp_command_has_valid_fixed_length, /* 0x06: encryption information */
94     smp_command_has_valid_fixed_length, /* 0x07: master identification */
95     smp_command_has_valid_fixed_length, /* 0x08: identity information */
96     smp_command_has_valid_fixed_length, /* 0x09: identity address information */
97     smp_command_has_valid_fixed_length, /* 0x0A: signing information */
98     smp_command_has_valid_fixed_length, /* 0x0B: security request */
99     smp_command_has_valid_fixed_length, /* 0x0C: pairing public key */
100     smp_command_has_valid_fixed_length, /* 0x0D: pairing dhkey check */
101     smp_command_has_valid_fixed_length, /* 0x0E: pairing keypress notification*/
102     smp_command_has_valid_fixed_length  /* 0x0F: pairing commitment */
103 };
104
105 /* type for SMP command parameter ranges validation functions */
106 typedef bool (*tSMP_CMD_PARAM_RANGES_VALID)(tSMP_CB* p_cb);
107
108 static bool smp_pairing_request_response_parameters_are_valid(tSMP_CB* p_cb);
109 static bool smp_pairing_keypress_notification_is_valid(tSMP_CB* p_cb);
110
111 static const tSMP_CMD_PARAM_RANGES_VALID smp_cmd_param_ranges_are_valid[] = {
112     smp_parameter_unconditionally_invalid,
113     smp_pairing_request_response_parameters_are_valid, /* 0x01: pairing
114                                                           request */
115     smp_pairing_request_response_parameters_are_valid, /* 0x02: pairing
116                                                           response */
117     smp_parameter_unconditionally_valid, /* 0x03: pairing confirm */
118     smp_parameter_unconditionally_valid, /* 0x04: pairing random */
119     smp_parameter_unconditionally_valid, /* 0x05: pairing failed */
120     smp_parameter_unconditionally_valid, /* 0x06: encryption information */
121     smp_parameter_unconditionally_valid, /* 0x07: master identification */
122     smp_parameter_unconditionally_valid, /* 0x08: identity information */
123     smp_parameter_unconditionally_valid, /* 0x09: identity address
124                                             information */
125     smp_parameter_unconditionally_valid, /* 0x0A: signing information */
126     smp_parameter_unconditionally_valid, /* 0x0B: security request */
127     smp_parameter_unconditionally_valid, /* 0x0C: pairing public key */
128     smp_parameter_unconditionally_valid, /* 0x0D: pairing dhkey check */
129     smp_pairing_keypress_notification_is_valid, /* 0x0E: pairing keypress
130                                                    notification */
131     smp_parameter_unconditionally_valid         /* 0x0F: pairing commitment */
132 };
133
134 /* type for action functions */
135 typedef BT_HDR* (*tSMP_CMD_ACT)(uint8_t cmd_code, tSMP_CB* p_cb);
136
137 static BT_HDR* smp_build_pairing_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
138 static BT_HDR* smp_build_confirm_cmd(UNUSED_ATTR uint8_t cmd_code,
139                                      tSMP_CB* p_cb);
140 static BT_HDR* smp_build_rand_cmd(UNUSED_ATTR uint8_t cmd_code, tSMP_CB* p_cb);
141 static BT_HDR* smp_build_pairing_fail(UNUSED_ATTR uint8_t cmd_code,
142                                       tSMP_CB* p_cb);
143 static BT_HDR* smp_build_identity_info_cmd(UNUSED_ATTR uint8_t cmd_code,
144                                            tSMP_CB* p_cb);
145 static BT_HDR* smp_build_encrypt_info_cmd(UNUSED_ATTR uint8_t cmd_code,
146                                           tSMP_CB* p_cb);
147 static BT_HDR* smp_build_security_request(UNUSED_ATTR uint8_t cmd_code,
148                                           tSMP_CB* p_cb);
149 static BT_HDR* smp_build_signing_info_cmd(UNUSED_ATTR uint8_t cmd_code,
150                                           tSMP_CB* p_cb);
151 static BT_HDR* smp_build_master_id_cmd(UNUSED_ATTR uint8_t cmd_code,
152                                        tSMP_CB* p_cb);
153 static BT_HDR* smp_build_id_addr_cmd(UNUSED_ATTR uint8_t cmd_code,
154                                      tSMP_CB* p_cb);
155 static BT_HDR* smp_build_pair_public_key_cmd(UNUSED_ATTR uint8_t cmd_code,
156                                              tSMP_CB* p_cb);
157 static BT_HDR* smp_build_pairing_commitment_cmd(UNUSED_ATTR uint8_t cmd_code,
158                                                 tSMP_CB* p_cb);
159 static BT_HDR* smp_build_pair_dhkey_check_cmd(UNUSED_ATTR uint8_t cmd_code,
160                                               tSMP_CB* p_cb);
161 static BT_HDR* smp_build_pairing_keypress_notification_cmd(
162     UNUSED_ATTR uint8_t cmd_code, tSMP_CB* p_cb);
163
164 static const tSMP_CMD_ACT smp_cmd_build_act[] = {
165     NULL, smp_build_pairing_cmd,    /* 0x01: pairing request */
166     smp_build_pairing_cmd,          /* 0x02: pairing response */
167     smp_build_confirm_cmd,          /* 0x03: pairing confirm */
168     smp_build_rand_cmd,             /* 0x04: pairing random */
169     smp_build_pairing_fail,         /* 0x05: pairing failure */
170     smp_build_encrypt_info_cmd,     /* 0x06: encryption information */
171     smp_build_master_id_cmd,        /* 0x07: master identification */
172     smp_build_identity_info_cmd,    /* 0x08: identity information */
173     smp_build_id_addr_cmd,          /* 0x09: identity address information */
174     smp_build_signing_info_cmd,     /* 0x0A: signing information */
175     smp_build_security_request,     /* 0x0B: security request */
176     smp_build_pair_public_key_cmd,  /* 0x0C: pairing public key */
177     smp_build_pair_dhkey_check_cmd, /* 0x0D: pairing DHKey check */
178     smp_build_pairing_keypress_notification_cmd, /* 0x0E: pairing keypress
179                                                     notification */
180     smp_build_pairing_commitment_cmd             /* 0x0F: pairing commitment */
181 };
182
183 static const uint8_t smp_association_table[2][SMP_IO_CAP_MAX][SMP_IO_CAP_MAX] =
184     {
185         /* display only */ /* Display Yes/No */ /* keyboard only */
186         /* No Input/Output */                   /* keyboard display */
187
188         /* initiator */
189         /* model = tbl[peer_io_caps][loc_io_caps] */
190         /* Display Only */
191         {{SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY,
192           SMP_MODEL_PASSKEY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY},
193
194          /* Display Yes/No */
195          {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY,
196           SMP_MODEL_PASSKEY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY},
197
198          /* Keyboard only */
199          {SMP_MODEL_KEY_NOTIF, SMP_MODEL_KEY_NOTIF, SMP_MODEL_PASSKEY,
200           SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF},
201
202          /* No Input No Output */
203          {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY,
204           SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY,
205           SMP_MODEL_ENCRYPTION_ONLY},
206
207          /* keyboard display */
208          {SMP_MODEL_KEY_NOTIF, SMP_MODEL_KEY_NOTIF, SMP_MODEL_PASSKEY,
209           SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF}},
210
211         /* responder */
212         /* model = tbl[loc_io_caps][peer_io_caps] */
213         /* Display Only */
214         {{SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY,
215           SMP_MODEL_KEY_NOTIF, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF},
216
217          /* Display Yes/No */
218          {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY,
219           SMP_MODEL_KEY_NOTIF, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF},
220
221          /* keyboard only */
222          {SMP_MODEL_PASSKEY, SMP_MODEL_PASSKEY, SMP_MODEL_PASSKEY,
223           SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY},
224
225          /* No Input No Output */
226          {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY,
227           SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY,
228           SMP_MODEL_ENCRYPTION_ONLY},
229
230          /* keyboard display */
231          {SMP_MODEL_PASSKEY, SMP_MODEL_PASSKEY, SMP_MODEL_KEY_NOTIF,
232           SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY}}};
233
234 static const uint8_t
235     smp_association_table_sc[2][SMP_IO_CAP_MAX][SMP_IO_CAP_MAX] = {
236         /* display only */ /* Display Yes/No */ /* keyboard only */
237         /* No InputOutput */                    /* keyboard display */
238
239         /* initiator */
240         /* model = tbl[peer_io_caps][loc_io_caps] */
241
242         /* Display Only */
243         {{SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS,
244           SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_JUSTWORKS,
245           SMP_MODEL_SEC_CONN_PASSKEY_ENT},
246
247          /* Display Yes/No */
248          {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_NUM_COMP,
249           SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_JUSTWORKS,
250           SMP_MODEL_SEC_CONN_NUM_COMP},
251
252          /* keyboard only */
253          {SMP_MODEL_SEC_CONN_PASSKEY_DISP, SMP_MODEL_SEC_CONN_PASSKEY_DISP,
254           SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_JUSTWORKS,
255           SMP_MODEL_SEC_CONN_PASSKEY_DISP},
256
257          /* No Input No Output */
258          {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS,
259           SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS,
260           SMP_MODEL_SEC_CONN_JUSTWORKS},
261
262          /* keyboard display */
263          {SMP_MODEL_SEC_CONN_PASSKEY_DISP, SMP_MODEL_SEC_CONN_NUM_COMP,
264           SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_JUSTWORKS,
265           SMP_MODEL_SEC_CONN_NUM_COMP}},
266
267         /* responder */
268         /* model = tbl[loc_io_caps][peer_io_caps] */
269
270         /* Display Only */
271         {{SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS,
272           SMP_MODEL_SEC_CONN_PASSKEY_DISP, SMP_MODEL_SEC_CONN_JUSTWORKS,
273           SMP_MODEL_SEC_CONN_PASSKEY_DISP},
274
275          /* Display Yes/No */
276          {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_NUM_COMP,
277           SMP_MODEL_SEC_CONN_PASSKEY_DISP, SMP_MODEL_SEC_CONN_JUSTWORKS,
278           SMP_MODEL_SEC_CONN_NUM_COMP},
279
280          /* keyboard only */
281          {SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_PASSKEY_ENT,
282           SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_JUSTWORKS,
283           SMP_MODEL_SEC_CONN_PASSKEY_ENT},
284
285          /* No Input No Output */
286          {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS,
287           SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS,
288           SMP_MODEL_SEC_CONN_JUSTWORKS},
289
290          /* keyboard display */
291          {SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_NUM_COMP,
292           SMP_MODEL_SEC_CONN_PASSKEY_DISP, SMP_MODEL_SEC_CONN_JUSTWORKS,
293           SMP_MODEL_SEC_CONN_NUM_COMP}}};
294
295 static tSMP_ASSO_MODEL smp_select_legacy_association_model(tSMP_CB* p_cb);
296 static tSMP_ASSO_MODEL smp_select_association_model_secure_connections(
297     tSMP_CB* p_cb);
298
299 /**
300  * Log metrics data for SMP command
301  *
302  * @param bd_addr current pairing address
303  * @param is_outgoing whether this command is outgoing
304  * @param p_buf buffer to the beginning of SMP command
305  * @param buf_len length available to read for p_buf
306  */
307 void smp_log_metrics(const RawAddress& bd_addr, bool is_outgoing,
308                      const uint8_t* p_buf, size_t buf_len) {
309   if (buf_len < 1) {
310     LOG(WARNING) << __func__ << ": buffer is too small, size is " << buf_len;
311     return;
312   }
313   uint8_t cmd;
314   STREAM_TO_UINT8(cmd, p_buf);
315   buf_len--;
316   uint8_t failure_reason = 0;
317   if (cmd == SMP_OPCODE_PAIRING_FAILED && buf_len >= 1) {
318     STREAM_TO_UINT8(failure_reason, p_buf);
319   }
320   android::bluetooth::DirectionEnum direction =
321       is_outgoing ? android::bluetooth::DirectionEnum::DIRECTION_OUTGOING
322                   : android::bluetooth::DirectionEnum::DIRECTION_INCOMING;
323   bluetooth::common::LogSmpPairingEvent(bd_addr, cmd, direction,
324                                         failure_reason);
325 }
326
327 /*******************************************************************************
328  *
329  * Function         smp_send_msg_to_L2CAP
330  *
331  * Description      Send message to L2CAP.
332  *
333  ******************************************************************************/
334 bool smp_send_msg_to_L2CAP(const RawAddress& rem_bda, BT_HDR* p_toL2CAP) {
335   uint16_t l2cap_ret;
336   uint16_t fixed_cid = L2CAP_SMP_CID;
337
338   if (smp_cb.smp_over_br) {
339     fixed_cid = L2CAP_SMP_BR_CID;
340   }
341
342   SMP_TRACE_EVENT("%s", __func__);
343   smp_cb.total_tx_unacked += 1;
344
345   smp_log_metrics(rem_bda, true /* outgoing */,
346                   p_toL2CAP->data + p_toL2CAP->offset, p_toL2CAP->len);
347
348   l2cap_ret = L2CA_SendFixedChnlData(fixed_cid, rem_bda, p_toL2CAP);
349   if (l2cap_ret == L2CAP_DW_FAILED) {
350     smp_cb.total_tx_unacked -= 1;
351     SMP_TRACE_ERROR("SMP failed to pass msg to L2CAP");
352     return false;
353   } else
354     return true;
355 }
356
357 /*******************************************************************************
358  *
359  * Function         smp_send_cmd
360  *
361  * Description      send a SMP command on L2CAP channel.
362  *
363  ******************************************************************************/
364 bool smp_send_cmd(uint8_t cmd_code, tSMP_CB* p_cb) {
365   BT_HDR* p_buf;
366   bool sent = false;
367
368   SMP_TRACE_EVENT("%s: on l2cap cmd_code=0x%x, pairing_bda=%s", __func__,
369                   cmd_code, p_cb->pairing_bda.ToString().c_str());
370
371   if (cmd_code <= (SMP_OPCODE_MAX + 1 /* for SMP_OPCODE_PAIR_COMMITM */) &&
372       smp_cmd_build_act[cmd_code] != NULL) {
373     p_buf = (*smp_cmd_build_act[cmd_code])(cmd_code, p_cb);
374
375     if (p_buf != NULL && smp_send_msg_to_L2CAP(p_cb->pairing_bda, p_buf)) {
376       sent = true;
377       alarm_set_on_mloop(p_cb->smp_rsp_timer_ent, SMP_WAIT_FOR_RSP_TIMEOUT_MS,
378                          smp_rsp_timeout, NULL);
379     }
380   }
381
382   if (!sent) {
383     tSMP_INT_DATA smp_int_data;
384     smp_int_data.status = SMP_PAIR_INTERNAL_ERR;
385     if (p_cb->smp_over_br) {
386       smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data);
387     } else {
388       smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
389     }
390   }
391   return sent;
392 }
393
394 /*******************************************************************************
395  *
396  * Function         smp_rsp_timeout
397  *
398  * Description      Called when SMP wait for SMP command response timer expires
399  *
400  * Returns          void
401  *
402  ******************************************************************************/
403 void smp_rsp_timeout(UNUSED_ATTR void* data) {
404   tSMP_CB* p_cb = &smp_cb;
405
406   SMP_TRACE_EVENT("%s state:%d br_state:%d", __func__, p_cb->state,
407                   p_cb->br_state);
408
409   tSMP_INT_DATA smp_int_data;
410   smp_int_data.status = SMP_RSP_TIMEOUT;
411   if (p_cb->smp_over_br) {
412     smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data);
413   } else {
414     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
415   }
416 }
417
418 /*******************************************************************************
419  *
420  * Function         smp_delayed_auth_complete_timeout
421  *
422  * Description      Called when no pairing failed command received within
423  *                  timeout period.
424  *
425  * Returns          void
426  *
427  ******************************************************************************/
428 void smp_delayed_auth_complete_timeout(UNUSED_ATTR void* data) {
429   /*
430    * Waited for potential pair failure. Send SMP_AUTH_CMPL_EVT if
431    * the state is still in bond pending.
432    */
433   if (smp_get_state() == SMP_STATE_BOND_PENDING) {
434     SMP_TRACE_EVENT("%s sending delayed auth complete.", __func__);
435     tSMP_INT_DATA smp_int_data;
436     smp_int_data.status = SMP_SUCCESS;
437     smp_sm_event(&smp_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
438   }
439 }
440
441 /*******************************************************************************
442  *
443  * Function         smp_build_pairing_req_cmd
444  *
445  * Description      Build pairing request command.
446  *
447  ******************************************************************************/
448 BT_HDR* smp_build_pairing_cmd(uint8_t cmd_code, tSMP_CB* p_cb) {
449   uint8_t* p;
450   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIRING_REQ_SIZE +
451                                       L2CAP_MIN_OFFSET);
452
453   SMP_TRACE_EVENT("%s", __func__);
454
455   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
456   UINT8_TO_STREAM(p, cmd_code);
457   UINT8_TO_STREAM(p, p_cb->local_io_capability);
458   UINT8_TO_STREAM(p, p_cb->loc_oob_flag);
459   UINT8_TO_STREAM(p, p_cb->loc_auth_req);
460   UINT8_TO_STREAM(p, p_cb->loc_enc_size);
461   UINT8_TO_STREAM(p, p_cb->local_i_key);
462   UINT8_TO_STREAM(p, p_cb->local_r_key);
463
464   p_buf->offset = L2CAP_MIN_OFFSET;
465   /* 1B ERR_RSP op code + 1B cmd_op_code + 2B handle + 1B status */
466   p_buf->len = SMP_PAIRING_REQ_SIZE;
467
468   return p_buf;
469 }
470
471 /*******************************************************************************
472  *
473  * Function         smp_build_confirm_cmd
474  *
475  * Description      Build confirm request command.
476  *
477  ******************************************************************************/
478 static BT_HDR* smp_build_confirm_cmd(UNUSED_ATTR uint8_t cmd_code,
479                                      tSMP_CB* p_cb) {
480   uint8_t* p;
481   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_CONFIRM_CMD_SIZE +
482                                       L2CAP_MIN_OFFSET);
483
484   SMP_TRACE_EVENT("%s", __func__);
485
486   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
487
488   UINT8_TO_STREAM(p, SMP_OPCODE_CONFIRM);
489   ARRAY_TO_STREAM(p, p_cb->confirm, OCTET16_LEN);
490
491   p_buf->offset = L2CAP_MIN_OFFSET;
492   p_buf->len = SMP_CONFIRM_CMD_SIZE;
493
494   return p_buf;
495 }
496
497 /*******************************************************************************
498  *
499  * Function         smp_build_rand_cmd
500  *
501  * Description      Build Random command.
502  *
503  ******************************************************************************/
504 static BT_HDR* smp_build_rand_cmd(UNUSED_ATTR uint8_t cmd_code, tSMP_CB* p_cb) {
505   uint8_t* p;
506   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_RAND_CMD_SIZE +
507                                       L2CAP_MIN_OFFSET);
508
509   SMP_TRACE_EVENT("%s", __func__);
510
511   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
512   UINT8_TO_STREAM(p, SMP_OPCODE_RAND);
513   ARRAY_TO_STREAM(p, p_cb->rand, OCTET16_LEN);
514
515   p_buf->offset = L2CAP_MIN_OFFSET;
516   p_buf->len = SMP_RAND_CMD_SIZE;
517
518   return p_buf;
519 }
520
521 /*******************************************************************************
522  *
523  * Function         smp_build_encrypt_info_cmd
524  *
525  * Description      Build security information command.
526  *
527  ******************************************************************************/
528 static BT_HDR* smp_build_encrypt_info_cmd(UNUSED_ATTR uint8_t cmd_code,
529                                           tSMP_CB* p_cb) {
530   uint8_t* p;
531   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_ENC_INFO_SIZE +
532                                       L2CAP_MIN_OFFSET);
533
534   SMP_TRACE_EVENT("%s", __func__);
535
536   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
537   UINT8_TO_STREAM(p, SMP_OPCODE_ENCRYPT_INFO);
538   ARRAY_TO_STREAM(p, p_cb->ltk, OCTET16_LEN);
539
540   p_buf->offset = L2CAP_MIN_OFFSET;
541   p_buf->len = SMP_ENC_INFO_SIZE;
542
543   return p_buf;
544 }
545
546 /*******************************************************************************
547  *
548  * Function         smp_build_master_id_cmd
549  *
550  * Description      Build security information command.
551  *
552  ******************************************************************************/
553 static BT_HDR* smp_build_master_id_cmd(UNUSED_ATTR uint8_t cmd_code,
554                                        tSMP_CB* p_cb) {
555   uint8_t* p;
556   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_MASTER_ID_SIZE +
557                                       L2CAP_MIN_OFFSET);
558
559   SMP_TRACE_EVENT("%s", __func__);
560
561   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
562   UINT8_TO_STREAM(p, SMP_OPCODE_MASTER_ID);
563   UINT16_TO_STREAM(p, p_cb->ediv);
564   ARRAY_TO_STREAM(p, p_cb->enc_rand, BT_OCTET8_LEN);
565
566   p_buf->offset = L2CAP_MIN_OFFSET;
567   p_buf->len = SMP_MASTER_ID_SIZE;
568
569   return p_buf;
570 }
571
572 /*******************************************************************************
573  *
574  * Function         smp_build_identity_info_cmd
575  *
576  * Description      Build identity information command.
577  *
578  ******************************************************************************/
579 static BT_HDR* smp_build_identity_info_cmd(UNUSED_ATTR uint8_t cmd_code,
580                                            UNUSED_ATTR tSMP_CB* p_cb) {
581   uint8_t* p;
582   BT_HDR* p_buf =
583       (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_ID_INFO_SIZE + L2CAP_MIN_OFFSET);
584
585   SMP_TRACE_EVENT("%s", __func__);
586
587   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
588
589   const Octet16& irk = BTM_GetDeviceIDRoot();
590
591   UINT8_TO_STREAM(p, SMP_OPCODE_IDENTITY_INFO);
592   ARRAY_TO_STREAM(p, irk.data(), OCTET16_LEN);
593
594   p_buf->offset = L2CAP_MIN_OFFSET;
595   p_buf->len = SMP_ID_INFO_SIZE;
596
597   return p_buf;
598 }
599
600 /*******************************************************************************
601  *
602  * Function         smp_build_id_addr_cmd
603  *
604  * Description      Build identity address information command.
605  *
606  ******************************************************************************/
607 static BT_HDR* smp_build_id_addr_cmd(UNUSED_ATTR uint8_t cmd_code,
608                                      UNUSED_ATTR tSMP_CB* p_cb) {
609   uint8_t* p;
610   BT_HDR* p_buf =
611       (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_ID_ADDR_SIZE + L2CAP_MIN_OFFSET);
612
613   SMP_TRACE_EVENT("%s", __func__);
614
615   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
616   UINT8_TO_STREAM(p, SMP_OPCODE_ID_ADDR);
617   UINT8_TO_STREAM(p, 0);
618   BDADDR_TO_STREAM(p, *controller_get_interface()->get_address());
619
620   p_buf->offset = L2CAP_MIN_OFFSET;
621   p_buf->len = SMP_ID_ADDR_SIZE;
622
623   return p_buf;
624 }
625
626 /*******************************************************************************
627  *
628  * Function         smp_build_signing_info_cmd
629  *
630  * Description      Build signing information command.
631  *
632  ******************************************************************************/
633 static BT_HDR* smp_build_signing_info_cmd(UNUSED_ATTR uint8_t cmd_code,
634                                           tSMP_CB* p_cb) {
635   uint8_t* p;
636   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_SIGN_INFO_SIZE +
637                                       L2CAP_MIN_OFFSET);
638
639   SMP_TRACE_EVENT("%s", __func__);
640
641   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
642   UINT8_TO_STREAM(p, SMP_OPCODE_SIGN_INFO);
643   ARRAY_TO_STREAM(p, p_cb->csrk, OCTET16_LEN);
644
645   p_buf->offset = L2CAP_MIN_OFFSET;
646   p_buf->len = SMP_SIGN_INFO_SIZE;
647
648   return p_buf;
649 }
650
651 /*******************************************************************************
652  *
653  * Function         smp_build_pairing_fail
654  *
655  * Description      Build Pairing Fail command.
656  *
657  ******************************************************************************/
658 static BT_HDR* smp_build_pairing_fail(UNUSED_ATTR uint8_t cmd_code,
659                                       tSMP_CB* p_cb) {
660   uint8_t* p;
661   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_FAIL_SIZE +
662                                       L2CAP_MIN_OFFSET);
663
664   SMP_TRACE_EVENT("%s", __func__);
665
666   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
667   UINT8_TO_STREAM(p, SMP_OPCODE_PAIRING_FAILED);
668   UINT8_TO_STREAM(p, p_cb->failure);
669
670   p_buf->offset = L2CAP_MIN_OFFSET;
671   p_buf->len = SMP_PAIR_FAIL_SIZE;
672
673   return p_buf;
674 }
675
676 /*******************************************************************************
677  *
678  * Function         smp_build_security_request
679  *
680  * Description      Build security request command.
681  *
682  ******************************************************************************/
683 static BT_HDR* smp_build_security_request(UNUSED_ATTR uint8_t cmd_code,
684                                           tSMP_CB* p_cb) {
685   uint8_t* p;
686   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + 2 + L2CAP_MIN_OFFSET);
687
688   SMP_TRACE_EVENT("%s", __func__);
689
690   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
691   UINT8_TO_STREAM(p, SMP_OPCODE_SEC_REQ);
692   UINT8_TO_STREAM(p, p_cb->loc_auth_req);
693
694   p_buf->offset = L2CAP_MIN_OFFSET;
695   p_buf->len = SMP_SECURITY_REQUEST_SIZE;
696
697   SMP_TRACE_EVENT("opcode=%d auth_req=0x%x", SMP_OPCODE_SEC_REQ,
698                   p_cb->loc_auth_req);
699
700   return p_buf;
701 }
702
703 /*******************************************************************************
704  *
705  * Function         smp_build_pair_public_key_cmd
706  *
707  * Description      Build pairing public key command.
708  *
709  ******************************************************************************/
710 static BT_HDR* smp_build_pair_public_key_cmd(UNUSED_ATTR uint8_t cmd_code,
711                                              tSMP_CB* p_cb) {
712   uint8_t* p;
713   uint8_t publ_key[2 * BT_OCTET32_LEN];
714   uint8_t* p_publ_key = publ_key;
715   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_PUBL_KEY_SIZE +
716                                       L2CAP_MIN_OFFSET);
717
718   SMP_TRACE_EVENT("%s", __func__);
719
720   memcpy(p_publ_key, p_cb->loc_publ_key.x, BT_OCTET32_LEN);
721   memcpy(p_publ_key + BT_OCTET32_LEN, p_cb->loc_publ_key.y, BT_OCTET32_LEN);
722
723   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
724   UINT8_TO_STREAM(p, SMP_OPCODE_PAIR_PUBLIC_KEY);
725   ARRAY_TO_STREAM(p, p_publ_key, 2 * BT_OCTET32_LEN);
726
727   p_buf->offset = L2CAP_MIN_OFFSET;
728   p_buf->len = SMP_PAIR_PUBL_KEY_SIZE;
729
730   return p_buf;
731 }
732
733 /*******************************************************************************
734  *
735  * Function         smp_build_pairing_commitment_cmd
736  *
737  * Description      Build pairing commitment command.
738  *
739  ******************************************************************************/
740 static BT_HDR* smp_build_pairing_commitment_cmd(UNUSED_ATTR uint8_t cmd_code,
741                                                 tSMP_CB* p_cb) {
742   uint8_t* p;
743   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_COMMITM_SIZE +
744                                       L2CAP_MIN_OFFSET);
745
746   SMP_TRACE_EVENT("%s", __func__);
747
748   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
749   UINT8_TO_STREAM(p, SMP_OPCODE_CONFIRM);
750   ARRAY_TO_STREAM(p, p_cb->commitment, OCTET16_LEN);
751
752   p_buf->offset = L2CAP_MIN_OFFSET;
753   p_buf->len = SMP_PAIR_COMMITM_SIZE;
754
755   return p_buf;
756 }
757
758 /*******************************************************************************
759  *
760  * Function         smp_build_pair_dhkey_check_cmd
761  *
762  * Description      Build pairing DHKey check command.
763  *
764  ******************************************************************************/
765 static BT_HDR* smp_build_pair_dhkey_check_cmd(UNUSED_ATTR uint8_t cmd_code,
766                                               tSMP_CB* p_cb) {
767   uint8_t* p;
768   BT_HDR* p_buf = (BT_HDR*)osi_malloc(
769       sizeof(BT_HDR) + SMP_PAIR_DHKEY_CHECK_SIZE + L2CAP_MIN_OFFSET);
770
771   SMP_TRACE_EVENT("%s", __func__);
772
773   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
774   UINT8_TO_STREAM(p, SMP_OPCODE_PAIR_DHKEY_CHECK);
775   ARRAY_TO_STREAM(p, p_cb->dhkey_check, OCTET16_LEN);
776
777   p_buf->offset = L2CAP_MIN_OFFSET;
778   p_buf->len = SMP_PAIR_DHKEY_CHECK_SIZE;
779
780   return p_buf;
781 }
782
783 /*******************************************************************************
784  *
785  * Function         smp_build_pairing_keypress_notification_cmd
786  *
787  * Description      Build keypress notification command.
788  *
789  ******************************************************************************/
790 static BT_HDR* smp_build_pairing_keypress_notification_cmd(
791     UNUSED_ATTR uint8_t cmd_code, tSMP_CB* p_cb) {
792   uint8_t* p;
793   BT_HDR* p_buf = (BT_HDR*)osi_malloc(
794       sizeof(BT_HDR) + SMP_PAIR_KEYPR_NOTIF_SIZE + L2CAP_MIN_OFFSET);
795
796   SMP_TRACE_EVENT("%s", __func__);
797
798   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
799   UINT8_TO_STREAM(p, SMP_OPCODE_PAIR_KEYPR_NOTIF);
800   UINT8_TO_STREAM(p, p_cb->local_keypress_notification);
801
802   p_buf->offset = L2CAP_MIN_OFFSET;
803   p_buf->len = SMP_PAIR_KEYPR_NOTIF_SIZE;
804
805   return p_buf;
806 }
807
808 /** This function is called to convert a 6 to 16 digits numeric character string
809  * into SMP TK. */
810 void smp_convert_string_to_tk(Octet16* tk, uint32_t passkey) {
811   uint8_t* p = tk->data();
812   tSMP_KEY key;
813   SMP_TRACE_EVENT("smp_convert_string_to_tk");
814   UINT32_TO_STREAM(p, passkey);
815
816   key.key_type = SMP_KEY_TYPE_TK;
817   key.p_data = tk->data();
818
819   tSMP_INT_DATA smp_int_data;
820   smp_int_data.key = key;
821   smp_sm_event(&smp_cb, SMP_KEY_READY_EVT, &smp_int_data);
822 }
823
824 /** This function is called to mask off the encryption key based on the maximum
825  * encryption key size. */
826 void smp_mask_enc_key(uint8_t loc_enc_size, Octet16* p_data) {
827   SMP_TRACE_EVENT("smp_mask_enc_key");
828   if (loc_enc_size < OCTET16_LEN) {
829     for (; loc_enc_size < OCTET16_LEN; loc_enc_size++)
830       (*p_data)[loc_enc_size] = 0;
831   }
832   return;
833 }
834
835 /** utility function to do an biteise exclusive-OR of two bit strings of the
836  * length of OCTET16_LEN. Result is stored in first argument.
837  */
838 void smp_xor_128(Octet16* a, const Octet16& b) {
839   CHECK(a);
840   uint8_t i, *aa = a->data();
841   const uint8_t* bb = b.data();
842
843   for (i = 0; i < OCTET16_LEN; i++) {
844     aa[i] = aa[i] ^ bb[i];
845   }
846 }
847
848 /*******************************************************************************
849  *
850  * Function         smp_cb_cleanup
851  *
852  * Description      Clean up SMP control block
853  *
854  * Returns          void
855  *
856  ******************************************************************************/
857 void smp_cb_cleanup(tSMP_CB* p_cb) {
858   tSMP_CALLBACK* p_callback = p_cb->p_callback;
859   uint8_t trace_level = p_cb->trace_level;
860   alarm_t* smp_rsp_timer_ent = p_cb->smp_rsp_timer_ent;
861   alarm_t* delayed_auth_timer_ent = p_cb->delayed_auth_timer_ent;
862
863   SMP_TRACE_EVENT("smp_cb_cleanup");
864
865   alarm_cancel(p_cb->smp_rsp_timer_ent);
866   alarm_cancel(p_cb->delayed_auth_timer_ent);
867   memset(p_cb, 0, sizeof(tSMP_CB));
868   p_cb->p_callback = p_callback;
869   p_cb->trace_level = trace_level;
870   p_cb->smp_rsp_timer_ent = smp_rsp_timer_ent;
871   p_cb->delayed_auth_timer_ent = delayed_auth_timer_ent;
872 }
873
874 /*******************************************************************************
875  *
876  * Function         smp_remove_fixed_channel
877  *
878  * Description      This function is called to remove the fixed channel
879  *
880  * Returns          void
881  *
882  ******************************************************************************/
883 void smp_remove_fixed_channel(tSMP_CB* p_cb) {
884   SMP_TRACE_DEBUG("%s", __func__);
885
886   if (p_cb->smp_over_br)
887     L2CA_RemoveFixedChnl(L2CAP_SMP_BR_CID, p_cb->pairing_bda);
888   else
889     L2CA_RemoveFixedChnl(L2CAP_SMP_CID, p_cb->pairing_bda);
890 }
891
892 /*******************************************************************************
893  *
894  * Function         smp_reset_control_value
895  *
896  * Description      This function is called to reset the control block value
897  *                  when the pairing procedure finished.
898  *
899  *
900  * Returns          void
901  *
902  ******************************************************************************/
903 void smp_reset_control_value(tSMP_CB* p_cb) {
904   SMP_TRACE_EVENT("%s", __func__);
905
906   alarm_cancel(p_cb->smp_rsp_timer_ent);
907   p_cb->flags = 0;
908   /* set the link idle timer to drop the link when pairing is done
909      usually service discovery will follow authentication complete, to avoid
910      racing condition for a link down/up, set link idle timer to be
911      SMP_LINK_TOUT_MIN to guarantee SMP key exchange */
912   L2CA_SetIdleTimeoutByBdAddr(p_cb->pairing_bda, SMP_LINK_TOUT_MIN,
913                               BT_TRANSPORT_LE);
914
915   /* We can tell L2CAP to remove the fixed channel (if it has one) */
916   smp_remove_fixed_channel(p_cb);
917   smp_cb_cleanup(p_cb);
918 }
919
920 /*******************************************************************************
921  *
922  * Function         smp_proc_pairing_cmpl
923  *
924  * Description      This function is called to process pairing complete
925  *
926  *
927  * Returns          void
928  *
929  ******************************************************************************/
930 void smp_proc_pairing_cmpl(tSMP_CB* p_cb) {
931   tSMP_EVT_DATA evt_data = {0};
932   tSMP_CALLBACK* p_callback = p_cb->p_callback;
933
934   SMP_TRACE_DEBUG("%s: pairing_bda=%s", __func__,
935                   p_cb->pairing_bda.ToString().c_str());
936
937   evt_data.cmplt.reason = p_cb->status;
938   evt_data.cmplt.smp_over_br = p_cb->smp_over_br;
939
940   if (p_cb->status == SMP_SUCCESS) evt_data.cmplt.sec_level = p_cb->sec_level;
941
942   evt_data.cmplt.is_pair_cancel = false;
943
944   if (p_cb->is_pair_cancel) evt_data.cmplt.is_pair_cancel = true;
945
946   SMP_TRACE_DEBUG("send SMP_COMPLT_EVT reason=0x%0x sec_level=0x%0x",
947                   evt_data.cmplt.reason, evt_data.cmplt.sec_level);
948
949   RawAddress pairing_bda = p_cb->pairing_bda;
950
951   smp_reset_control_value(p_cb);
952
953   if (p_callback) (*p_callback)(SMP_COMPLT_EVT, pairing_bda, &evt_data);
954 }
955
956 /*******************************************************************************
957  *
958  * Function         smp_command_has_invalid_parameters
959  *
960  * Description      Checks if the received SMP command has invalid parameters
961  *                  i.e. if the command length is valid and the command
962  *                  parameters are inside specified range.
963  *                  It returns true if the command has invalid parameters.
964  *
965  * Returns          true if the command has invalid parameters, false otherwise.
966  *
967  ******************************************************************************/
968 bool smp_command_has_invalid_parameters(tSMP_CB* p_cb) {
969   uint8_t cmd_code = p_cb->rcvd_cmd_code;
970
971   if ((cmd_code > (SMP_OPCODE_MAX + 1 /* for SMP_OPCODE_PAIR_COMMITM */)) ||
972       (cmd_code < SMP_OPCODE_MIN)) {
973     SMP_TRACE_WARNING("%s: Received command with RESERVED code 0x%02x",
974                       __func__, cmd_code);
975     return true;
976   }
977
978   if (!(*smp_cmd_len_is_valid[cmd_code])(p_cb)) {
979     SMP_TRACE_WARNING("%s: Command length not valid for cmd_code 0x%02x",
980                       __func__, cmd_code);
981     return true;
982   }
983
984   if (!(*smp_cmd_param_ranges_are_valid[cmd_code])(p_cb)) {
985     SMP_TRACE_WARNING("%s: Parameter ranges not valid code 0x%02x", __func__,
986                       cmd_code);
987     return true;
988   }
989
990   return false;
991 }
992
993 /*******************************************************************************
994  *
995  * Function         smp_command_has_valid_fixed_length
996  *
997  * Description      Checks if the received command size is equal to the size
998  *                  according to specs.
999  *
1000  * Returns          true if the command size is as expected, false otherwise.
1001  *
1002  * Note             The command is expected to have fixed length.
1003  ******************************************************************************/
1004 bool smp_command_has_valid_fixed_length(tSMP_CB* p_cb) {
1005   uint8_t cmd_code = p_cb->rcvd_cmd_code;
1006
1007   SMP_TRACE_DEBUG("%s for cmd code 0x%02x", __func__, cmd_code);
1008
1009   if (p_cb->rcvd_cmd_len != smp_cmd_size_per_spec[cmd_code]) {
1010     SMP_TRACE_WARNING(
1011         "Rcvd from the peer cmd 0x%02x with invalid length "
1012         "0x%02x (per spec the length is 0x%02x).",
1013         cmd_code, p_cb->rcvd_cmd_len, smp_cmd_size_per_spec[cmd_code]);
1014     return false;
1015   }
1016
1017   return true;
1018 }
1019
1020 /*******************************************************************************
1021  *
1022  * Function         smp_pairing_request_response_parameters_are_valid
1023  *
1024  * Description      Validates parameter ranges in the received SMP command
1025  *                  pairing request or pairing response.
1026  *                  The parameters to validate:
1027  *                  IO capability,
1028  *                  OOB data flag,
1029  *                  Bonding_flags in AuthReq
1030  *                  Maximum encryption key size.
1031  *                  Returns false if at least one of these parameters is out of
1032  *                  range.
1033  *
1034  ******************************************************************************/
1035 bool smp_pairing_request_response_parameters_are_valid(tSMP_CB* p_cb) {
1036   uint8_t io_caps = p_cb->peer_io_caps;
1037   uint8_t oob_flag = p_cb->peer_oob_flag;
1038   uint8_t bond_flag =
1039       p_cb->peer_auth_req & 0x03;  // 0x03 is gen bond with appropriate mask
1040   uint8_t enc_size = p_cb->peer_enc_size;
1041
1042   SMP_TRACE_DEBUG("%s for cmd code 0x%02x", __func__, p_cb->rcvd_cmd_code);
1043
1044   if (io_caps >= BTM_IO_CAP_MAX) {
1045     SMP_TRACE_WARNING(
1046         "Rcvd from the peer cmd 0x%02x with IO Capability "
1047         "value (0x%02x) out of range).",
1048         p_cb->rcvd_cmd_code, io_caps);
1049     return false;
1050   }
1051
1052   if (!((oob_flag == SMP_OOB_NONE) || (oob_flag == SMP_OOB_PRESENT))) {
1053     SMP_TRACE_WARNING(
1054         "Rcvd from the peer cmd 0x%02x with OOB data flag value "
1055         "(0x%02x) out of range).",
1056         p_cb->rcvd_cmd_code, oob_flag);
1057     return false;
1058   }
1059
1060   if (!((bond_flag == SMP_AUTH_NO_BOND) || (bond_flag == SMP_AUTH_BOND))) {
1061     SMP_TRACE_WARNING(
1062         "Rcvd from the peer cmd 0x%02x with Bonding_Flags value (0x%02x) "
1063         "out of range).",
1064         p_cb->rcvd_cmd_code, bond_flag);
1065     return false;
1066   }
1067
1068   if ((enc_size < SMP_ENCR_KEY_SIZE_MIN) ||
1069       (enc_size > SMP_ENCR_KEY_SIZE_MAX)) {
1070     SMP_TRACE_WARNING(
1071         "Rcvd from the peer cmd 0x%02x with Maximum Encryption "
1072         "Key value (0x%02x) out of range).",
1073         p_cb->rcvd_cmd_code, enc_size);
1074     return false;
1075   }
1076
1077   return true;
1078 }
1079
1080 /*******************************************************************************
1081  *
1082  * Function         smp_pairing_keypress_notification_is_valid
1083  *
1084  * Description      Validates Notification Type parameter range in the received
1085  *                  SMP command pairing keypress notification.
1086  *                  Returns false if this parameter is out of range.
1087  *
1088  ******************************************************************************/
1089 bool smp_pairing_keypress_notification_is_valid(tSMP_CB* p_cb) {
1090   tBTM_SP_KEY_TYPE keypress_notification = p_cb->peer_keypress_notification;
1091
1092   SMP_TRACE_DEBUG("%s for cmd code 0x%02x", __func__, p_cb->rcvd_cmd_code);
1093
1094   if (keypress_notification >= BTM_SP_KEY_OUT_OF_RANGE) {
1095     SMP_TRACE_WARNING(
1096         "Rcvd from the peer cmd 0x%02x with Pairing Keypress "
1097         "Notification value (0x%02x) out of range).",
1098         p_cb->rcvd_cmd_code, keypress_notification);
1099     return false;
1100   }
1101
1102   return true;
1103 }
1104
1105 /*******************************************************************************
1106  *
1107  * Function         smp_parameter_unconditionally_valid
1108  *
1109  * Description      Always returns true.
1110  *
1111  ******************************************************************************/
1112 bool smp_parameter_unconditionally_valid(UNUSED_ATTR tSMP_CB* p_cb) {
1113   return true;
1114 }
1115
1116 /*******************************************************************************
1117  *
1118  * Function         smp_parameter_unconditionally_invalid
1119  *
1120  * Description      Always returns false.
1121  *
1122  ******************************************************************************/
1123 bool smp_parameter_unconditionally_invalid(UNUSED_ATTR tSMP_CB* p_cb) {
1124   return false;
1125 }
1126
1127 /*******************************************************************************
1128  *
1129  * Function         smp_reject_unexpected_pairing_command
1130  *
1131  * Description      send pairing failure to an unexpected pairing command during
1132  *                  an active pairing process.
1133  *
1134  * Returns          void
1135  *
1136  ******************************************************************************/
1137 void smp_reject_unexpected_pairing_command(const RawAddress& bd_addr) {
1138   uint8_t* p;
1139   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_FAIL_SIZE +
1140                                       L2CAP_MIN_OFFSET);
1141
1142   SMP_TRACE_DEBUG("%s", __func__);
1143
1144   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
1145   UINT8_TO_STREAM(p, SMP_OPCODE_PAIRING_FAILED);
1146   UINT8_TO_STREAM(p, SMP_PAIR_NOT_SUPPORT);
1147
1148   p_buf->offset = L2CAP_MIN_OFFSET;
1149   p_buf->len = SMP_PAIR_FAIL_SIZE;
1150
1151   smp_send_msg_to_L2CAP(bd_addr, p_buf);
1152 }
1153
1154 /*******************************************************************************
1155  * Function         smp_select_association_model
1156  *
1157  * Description      This function selects association model to use for STK
1158  *                  generation. Selection is based on both sides' io capability,
1159  *                  oob data flag and authentication request.
1160  *
1161  * Note             If Secure Connections Only mode is required locally then we
1162  *                  come to this point only if both sides support Secure
1163  *                  Connections mode, i.e.
1164  *                  if p_cb->secure_connections_only_mode_required = true
1165  *                  then we come to this point only if
1166  *                      (p_cb->peer_auth_req & SMP_SC_SUPPORT_BIT) ==
1167  *                      (p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT) ==
1168  *                      SMP_SC_SUPPORT_BIT
1169  *
1170  ******************************************************************************/
1171 tSMP_ASSO_MODEL smp_select_association_model(tSMP_CB* p_cb) {
1172   tSMP_ASSO_MODEL model = SMP_MODEL_OUT_OF_RANGE;
1173   p_cb->le_secure_connections_mode_is_used = false;
1174
1175   SMP_TRACE_EVENT("%s", __func__);
1176   SMP_TRACE_DEBUG("%s p_cb->peer_io_caps = %d p_cb->local_io_capability = %d",
1177                   __func__, p_cb->peer_io_caps, p_cb->local_io_capability);
1178   SMP_TRACE_DEBUG("%s p_cb->peer_oob_flag = %d p_cb->loc_oob_flag = %d",
1179                   __func__, p_cb->peer_oob_flag, p_cb->loc_oob_flag);
1180   SMP_TRACE_DEBUG("%s p_cb->peer_auth_req = 0x%02x p_cb->loc_auth_req = 0x%02x",
1181                   __func__, p_cb->peer_auth_req, p_cb->loc_auth_req);
1182   SMP_TRACE_DEBUG(
1183       "%s p_cb->secure_connections_only_mode_required = %s", __func__,
1184       p_cb->secure_connections_only_mode_required ? "true" : "false");
1185
1186   if ((p_cb->peer_auth_req & SMP_SC_SUPPORT_BIT) &&
1187       (p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT)) {
1188     p_cb->le_secure_connections_mode_is_used = true;
1189   }
1190
1191   if ((p_cb->peer_auth_req & SMP_H7_SUPPORT_BIT) &&
1192       (p_cb->loc_auth_req & SMP_H7_SUPPORT_BIT)) {
1193     p_cb->key_derivation_h7_used = TRUE;
1194   }
1195
1196   SMP_TRACE_DEBUG("use_sc_process = %d, h7 use = %d",
1197                   p_cb->le_secure_connections_mode_is_used,
1198                   p_cb->key_derivation_h7_used);
1199
1200   if (p_cb->le_secure_connections_mode_is_used) {
1201     model = smp_select_association_model_secure_connections(p_cb);
1202   } else {
1203     model = smp_select_legacy_association_model(p_cb);
1204   }
1205   return model;
1206 }
1207
1208 /*******************************************************************************
1209  * Function         smp_select_legacy_association_model
1210  *
1211  * Description      This function is called to select association mode if at
1212  *                  least one side doesn't support secure connections.
1213  *
1214  ******************************************************************************/
1215 tSMP_ASSO_MODEL smp_select_legacy_association_model(tSMP_CB* p_cb) {
1216   tSMP_ASSO_MODEL model = SMP_MODEL_OUT_OF_RANGE;
1217
1218   SMP_TRACE_DEBUG("%s", __func__);
1219   /* if OOB data is present on both devices, then use OOB association model */
1220   if (p_cb->peer_oob_flag == SMP_OOB_PRESENT &&
1221       p_cb->loc_oob_flag == SMP_OOB_PRESENT)
1222     return SMP_MODEL_OOB;
1223
1224   /* else if neither device requires MITM, then use Just Works association model
1225    */
1226   if (SMP_NO_MITM_REQUIRED(p_cb->peer_auth_req) &&
1227       SMP_NO_MITM_REQUIRED(p_cb->loc_auth_req))
1228     return SMP_MODEL_ENCRYPTION_ONLY;
1229
1230   /* otherwise use IO capability to select association model */
1231   if (p_cb->peer_io_caps < SMP_IO_CAP_MAX &&
1232       p_cb->local_io_capability < SMP_IO_CAP_MAX) {
1233     if (p_cb->role == HCI_ROLE_MASTER) {
1234       model = smp_association_table[p_cb->role][p_cb->peer_io_caps]
1235                                    [p_cb->local_io_capability];
1236     } else {
1237       model = smp_association_table[p_cb->role][p_cb->local_io_capability]
1238                                    [p_cb->peer_io_caps];
1239     }
1240   }
1241
1242   return model;
1243 }
1244
1245 /*******************************************************************************
1246  * Function         smp_select_association_model_secure_connections
1247  *
1248  * Description      This function is called to select association mode if both
1249  *                  sides support secure connections.
1250  *
1251  ******************************************************************************/
1252 tSMP_ASSO_MODEL smp_select_association_model_secure_connections(tSMP_CB* p_cb) {
1253   tSMP_ASSO_MODEL model = SMP_MODEL_OUT_OF_RANGE;
1254
1255   SMP_TRACE_DEBUG("%s", __func__);
1256   /* if OOB data is present on at least one device, then use OOB association
1257    * model */
1258   if (p_cb->peer_oob_flag == SMP_OOB_PRESENT ||
1259       p_cb->loc_oob_flag == SMP_OOB_PRESENT)
1260     return SMP_MODEL_SEC_CONN_OOB;
1261
1262   /* else if neither device requires MITM, then use Just Works association model
1263    */
1264   if (SMP_NO_MITM_REQUIRED(p_cb->peer_auth_req) &&
1265       SMP_NO_MITM_REQUIRED(p_cb->loc_auth_req))
1266     return SMP_MODEL_SEC_CONN_JUSTWORKS;
1267
1268   /* otherwise use IO capability to select association model */
1269   if (p_cb->peer_io_caps < SMP_IO_CAP_MAX &&
1270       p_cb->local_io_capability < SMP_IO_CAP_MAX) {
1271     if (p_cb->role == HCI_ROLE_MASTER) {
1272       model = smp_association_table_sc[p_cb->role][p_cb->peer_io_caps]
1273                                       [p_cb->local_io_capability];
1274     } else {
1275       model = smp_association_table_sc[p_cb->role][p_cb->local_io_capability]
1276                                       [p_cb->peer_io_caps];
1277     }
1278   }
1279
1280   return model;
1281 }
1282
1283 /*******************************************************************************
1284  * Function         smp_reverse_array
1285  *
1286  * Description      This function reverses array bytes
1287  *
1288  ******************************************************************************/
1289 void smp_reverse_array(uint8_t* arr, uint8_t len) {
1290   uint8_t i = 0, tmp;
1291
1292   SMP_TRACE_DEBUG("smp_reverse_array");
1293
1294   for (i = 0; i < len / 2; i++) {
1295     tmp = arr[i];
1296     arr[i] = arr[len - 1 - i];
1297     arr[len - 1 - i] = tmp;
1298   }
1299 }
1300
1301 /*******************************************************************************
1302  * Function         smp_calculate_random_input
1303  *
1304  * Description      This function returns random input value to be used in
1305  *                  commitment calculation for SC passkey entry association mode
1306  *                  (if bit["round"] in "random" array == 1 then returns 0x81
1307  *                   else returns 0x80).
1308  *
1309  * Returns          ri value
1310  *
1311  ******************************************************************************/
1312 uint8_t smp_calculate_random_input(uint8_t* random, uint8_t round) {
1313   uint8_t i = round / 8;
1314   uint8_t j = round % 8;
1315   uint8_t ri;
1316
1317   SMP_TRACE_DEBUG("random: 0x%02x, round: %d, i: %d, j: %d", random[i], round,
1318                   i, j);
1319   ri = ((random[i] >> j) & 1) | 0x80;
1320   SMP_TRACE_DEBUG("%s ri=0x%02x", __func__, ri);
1321   return ri;
1322 }
1323
1324 /*******************************************************************************
1325  * Function         smp_collect_local_io_capabilities
1326  *
1327  * Description      This function puts into IOcap array local device
1328  *                  IOCapability, OOB data, AuthReq.
1329  *
1330  * Returns          void
1331  *
1332  ******************************************************************************/
1333 void smp_collect_local_io_capabilities(uint8_t* iocap, tSMP_CB* p_cb) {
1334   SMP_TRACE_DEBUG("%s", __func__);
1335
1336   iocap[0] = p_cb->local_io_capability;
1337   iocap[1] = p_cb->loc_oob_flag;
1338   iocap[2] = p_cb->loc_auth_req;
1339 }
1340
1341 /*******************************************************************************
1342  * Function         smp_collect_peer_io_capabilities
1343  *
1344  * Description      This function puts into IOcap array peer device
1345  *                  IOCapability, OOB data, AuthReq.
1346  *
1347  * Returns          void
1348  *
1349  ******************************************************************************/
1350 void smp_collect_peer_io_capabilities(uint8_t* iocap, tSMP_CB* p_cb) {
1351   SMP_TRACE_DEBUG("%s", __func__);
1352
1353   iocap[0] = p_cb->peer_io_caps;
1354   iocap[1] = p_cb->peer_oob_flag;
1355   iocap[2] = p_cb->peer_auth_req;
1356 }
1357
1358 /*******************************************************************************
1359  * Function         smp_collect_local_ble_address
1360  *
1361  * Description      Put the the local device LE address into the le_addr array:
1362  *                  le_addr[0-5] = local BD ADDR,
1363  *                  le_addr[6] = local le address type (PUBLIC/RANDOM).
1364  *
1365  * Returns          void
1366  *
1367  ******************************************************************************/
1368 void smp_collect_local_ble_address(uint8_t* le_addr, tSMP_CB* p_cb) {
1369   tBLE_ADDR_TYPE addr_type = 0;
1370   RawAddress bda;
1371   uint8_t* p = le_addr;
1372
1373   SMP_TRACE_DEBUG("%s", __func__);
1374
1375   BTM_ReadConnectionAddr(p_cb->pairing_bda, bda, &addr_type);
1376   BDADDR_TO_STREAM(p, bda);
1377   UINT8_TO_STREAM(p, addr_type);
1378 }
1379
1380 /*******************************************************************************
1381  * Function         smp_collect_peer_ble_address
1382  *
1383  * Description      Put the peer device LE addr into the le_addr array:
1384  *                  le_addr[0-5] = peer BD ADDR,
1385  *                  le_addr[6] = peer le address type (PUBLIC/RANDOM).
1386  *
1387  * Returns          void
1388  *
1389  ******************************************************************************/
1390 void smp_collect_peer_ble_address(uint8_t* le_addr, tSMP_CB* p_cb) {
1391   tBLE_ADDR_TYPE addr_type = 0;
1392   RawAddress bda;
1393   uint8_t* p = le_addr;
1394
1395   SMP_TRACE_DEBUG("%s", __func__);
1396
1397   if (!BTM_ReadRemoteConnectionAddr(p_cb->pairing_bda, bda, &addr_type)) {
1398     SMP_TRACE_ERROR(
1399         "can not collect peer le addr information for unknown device");
1400     return;
1401   }
1402
1403   BDADDR_TO_STREAM(p, bda);
1404   UINT8_TO_STREAM(p, addr_type);
1405 }
1406
1407 /*******************************************************************************
1408  * Function         smp_check_commitment
1409  *
1410  * Description      This function compares peer commitment values:
1411  *                  - expected (i.e. calculated locally),
1412  *                  - received from the peer.
1413  *
1414  * Returns          true  if the values are the same
1415  *                  false otherwise
1416  *
1417  ******************************************************************************/
1418 bool smp_check_commitment(tSMP_CB* p_cb) {
1419
1420   SMP_TRACE_DEBUG("%s", __func__);
1421
1422   Octet16 expected = smp_calculate_peer_commitment(p_cb);
1423   print128(expected, (const uint8_t*)"calculated peer commitment");
1424   print128(p_cb->remote_commitment, (const uint8_t*)"received peer commitment");
1425
1426   if (memcmp(p_cb->remote_commitment.data(), expected.data(), OCTET16_LEN)) {
1427     SMP_TRACE_WARNING("%s: Commitment check fails", __func__);
1428     return false;
1429   }
1430
1431   SMP_TRACE_DEBUG("%s: Commitment check succeeds", __func__);
1432   return true;
1433 }
1434
1435 /*******************************************************************************
1436  *
1437  * Function         smp_save_secure_connections_long_term_key
1438  *
1439  * Description      The function saves SC LTK as BLE key for future use as local
1440  *                  and/or peer key.
1441  *
1442  * Returns          void
1443  *
1444  ******************************************************************************/
1445 void smp_save_secure_connections_long_term_key(tSMP_CB* p_cb) {
1446   tBTM_LE_LENC_KEYS lle_key;
1447   tBTM_LE_PENC_KEYS ple_key;
1448
1449   SMP_TRACE_DEBUG("%s-Save LTK as local LTK key", __func__);
1450   lle_key.ltk = p_cb->ltk;
1451   lle_key.div = 0;
1452   lle_key.key_size = p_cb->loc_enc_size;
1453   lle_key.sec_level = p_cb->sec_level;
1454   btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_LENC,
1455                       (tBTM_LE_KEY_VALUE*)&lle_key, true);
1456
1457   SMP_TRACE_DEBUG("%s-Save LTK as peer LTK key", __func__);
1458   ple_key.ediv = 0;
1459   memset(ple_key.rand, 0, BT_OCTET8_LEN);
1460   ple_key.ltk = p_cb->ltk;
1461   ple_key.sec_level = p_cb->sec_level;
1462   ple_key.key_size = p_cb->loc_enc_size;
1463   btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PENC,
1464                       (tBTM_LE_KEY_VALUE*)&ple_key, true);
1465 }
1466
1467 /** The function calculates MacKey and LTK and saves them in CB. To calculate
1468  * MacKey and LTK it calls smp_calc_f5(...). MacKey is used in dhkey
1469  * calculation, LTK is used to encrypt the link. */
1470 void smp_calculate_f5_mackey_and_long_term_key(tSMP_CB* p_cb) {
1471   uint8_t a[7];
1472   uint8_t b[7];
1473   Octet16 na;
1474   Octet16 nb;
1475
1476   SMP_TRACE_DEBUG("%s", __func__);
1477
1478   if (p_cb->role == HCI_ROLE_MASTER) {
1479     smp_collect_local_ble_address(a, p_cb);
1480     smp_collect_peer_ble_address(b, p_cb);
1481     na = p_cb->rand;
1482     nb = p_cb->rrand;
1483   } else {
1484     smp_collect_local_ble_address(b, p_cb);
1485     smp_collect_peer_ble_address(a, p_cb);
1486     na = p_cb->rrand;
1487     nb = p_cb->rand;
1488   }
1489
1490   crypto_toolbox::f5(p_cb->dhkey, na, nb, a, b, &p_cb->mac_key, &p_cb->ltk);
1491
1492   SMP_TRACE_EVENT("%s is completed", __func__);
1493 }
1494
1495 /*******************************************************************************
1496  *
1497  * Function         smp_request_oob_data
1498  *
1499  * Description      Requests application to provide OOB data.
1500  *
1501  * Returns          true - OOB data has to be provided by application
1502  *                  false - otherwise (unexpected)
1503  *
1504  ******************************************************************************/
1505 bool smp_request_oob_data(tSMP_CB* p_cb) {
1506   tSMP_OOB_DATA_TYPE req_oob_type = SMP_OOB_INVALID_TYPE;
1507
1508   SMP_TRACE_DEBUG("%s", __func__);
1509
1510   if (p_cb->peer_oob_flag == SMP_OOB_PRESENT &&
1511       p_cb->loc_oob_flag == SMP_OOB_PRESENT) {
1512     /* both local and peer rcvd data OOB */
1513     req_oob_type = SMP_OOB_BOTH;
1514   } else if (p_cb->peer_oob_flag == SMP_OOB_PRESENT) {
1515     /* peer rcvd OOB local data, local didn't receive OOB peer data */
1516     req_oob_type = SMP_OOB_LOCAL;
1517   } else if (p_cb->loc_oob_flag == SMP_OOB_PRESENT) {
1518     req_oob_type = SMP_OOB_PEER;
1519   }
1520
1521   SMP_TRACE_DEBUG("req_oob_type = %d", req_oob_type);
1522
1523   if (req_oob_type == SMP_OOB_INVALID_TYPE) return false;
1524
1525   p_cb->req_oob_type = req_oob_type;
1526   p_cb->cb_evt = SMP_SC_OOB_REQ_EVT;
1527   tSMP_INT_DATA smp_int_data;
1528   smp_int_data.req_oob_type = req_oob_type;
1529   smp_sm_event(p_cb, SMP_TK_REQ_EVT, &smp_int_data);
1530
1531   return true;
1532 }
1533
1534 void print128(const Octet16& x, const uint8_t* key_name) {
1535   if (VLOG_IS_ON(2) && DLOG_IS_ON(INFO)) {
1536     uint8_t* p = (uint8_t*)x.data();
1537
1538     DVLOG(2) << key_name << " (MSB ~ LSB) = ";
1539     for (int i = 0; i < 4; i++) {
1540       DVLOG(2) << +p[OCTET16_LEN - i * 4 - 1] << +p[OCTET16_LEN - i * 4 - 2]
1541                << +p[OCTET16_LEN - i * 4 - 3] << +p[OCTET16_LEN - i * 4 - 4];
1542     }
1543   }
1544 }