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 BLE address management.
22  *
23  ******************************************************************************/
24 
25 #include <base/bind.h>
26 #include <string.h>
27 
28 #include "bt_types.h"
29 #include "btu.h"
30 #include "device/include/controller.h"
31 #include "gap_api.h"
32 #include "hcimsgs.h"
33 
34 #include "btm_ble_int.h"
35 #include "main/shim/shim.h"
36 #include "stack/btm/btm_dev.h"
37 #include "stack/crypto_toolbox/crypto_toolbox.h"
38 #include "stack/include/acl_api.h"
39 
40 extern tBTM_CB btm_cb;
41 
42 void btm_ble_set_random_address(const RawAddress& random_bda);
43 
44 /* This function generates Resolvable Private Address (RPA) from Identity
45  * Resolving Key |irk| and |random|*/
generate_rpa_from_irk_and_rand(const Octet16 & irk,BT_OCTET8 random)46 static RawAddress generate_rpa_from_irk_and_rand(const Octet16& irk,
47                                                  BT_OCTET8 random) {
48   random[2] &= (~BLE_RESOLVE_ADDR_MASK);
49   random[2] |= BLE_RESOLVE_ADDR_MSB;
50 
51   RawAddress address;
52   address.address[2] = random[0];
53   address.address[1] = random[1];
54   address.address[0] = random[2];
55 
56   /* encrypt with IRK */
57   Octet16 p = crypto_toolbox::aes_128(irk, random, 3);
58 
59   /* set hash to be LSB of rpAddress */
60   address.address[5] = p[0];
61   address.address[4] = p[1];
62   address.address[3] = p[2];
63   return address;
64 }
65 
btm_ble_refresh_raddr_timer_timeout(UNUSED_ATTR void * data)66 static void btm_ble_refresh_raddr_timer_timeout(UNUSED_ATTR void* data) {
67   if (btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type == BLE_ADDR_RANDOM) {
68     /* refresh the random addr */
69     btm_gen_resolvable_private_addr(base::Bind(&btm_gen_resolve_paddr_low));
70   }
71 }
72 
73 /** This function is called when random address for local controller was
74  * generated */
btm_gen_resolve_paddr_low(const RawAddress & address)75 void btm_gen_resolve_paddr_low(const RawAddress& address) {
76   /* when GD advertising and scanning modules are enabled, set random address
77    * via address manager in GD */
78   if (bluetooth::shim::is_gd_advertising_enabled() &&
79       bluetooth::shim::is_gd_scanning_enabled()) {
80     LOG_INFO("GD advertising and scanning modules are enabled, skip");
81     return;
82   }
83 
84   tBTM_LE_RANDOM_CB* p_cb = &btm_cb.ble_ctr_cb.addr_mgnt_cb;
85   p_cb->private_addr = address;
86 
87   /* set it to controller */
88   btm_ble_set_random_address(p_cb->private_addr);
89 
90   p_cb->own_addr_type = BLE_ADDR_RANDOM;
91 
92   /* start a periodical timer to refresh random addr */
93   uint64_t interval_ms = btm_get_next_private_addrress_interval_ms();
94 #if (BTM_BLE_CONFORMANCE_TESTING == TRUE)
95   interval_ms = btm_cb.ble_ctr_cb.rpa_tout * 1000;
96 #endif
97   alarm_set_on_mloop(p_cb->refresh_raddr_timer, interval_ms,
98                      btm_ble_refresh_raddr_timer_timeout, NULL);
99 }
100 
101 /** This function generate a resolvable private address using local IRK */
btm_gen_resolvable_private_addr(base::Callback<void (const RawAddress &)> cb)102 void btm_gen_resolvable_private_addr(
103     base::Callback<void(const RawAddress&)> cb) {
104   /* generate 3B rand as BD LSB, SRK with it, get BD MSB */
105   btsnd_hcic_ble_rand(base::Bind(
106       [](base::Callback<void(const RawAddress&)> cb, BT_OCTET8 random) {
107         const Octet16& irk = BTM_GetDeviceIDRoot();
108         cb.Run(generate_rpa_from_irk_and_rand(irk, random));
109       },
110       std::move(cb)));
111 }
112 
btm_get_next_private_addrress_interval_ms()113 uint64_t btm_get_next_private_addrress_interval_ms() {
114   /* 7 minutes minimum, 15 minutes maximum for random address refreshing */
115   const uint64_t interval_min_ms = (7 * 60 * 1000);
116   const uint64_t interval_random_part_max_ms = (8 * 60 * 1000);
117 
118   return interval_min_ms + std::rand() % interval_random_part_max_ms;
119 }
120 
121 /*******************************************************************************
122  *  Utility functions for Random address resolving
123  ******************************************************************************/
124 
125 /*******************************************************************************
126  *
127  * Function         btm_ble_init_pseudo_addr
128  *
129  * Description      This function is used to initialize pseudo address.
130  *                  If pseudo address is not available, use dummy address
131  *
132  * Returns          true is updated; false otherwise.
133  *
134  ******************************************************************************/
btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC * p_dev_rec,const RawAddress & new_pseudo_addr)135 bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec,
136                               const RawAddress& new_pseudo_addr) {
137   if (p_dev_rec->ble.pseudo_addr.IsEmpty()) {
138     p_dev_rec->ble.pseudo_addr = new_pseudo_addr;
139     return true;
140   }
141 
142   return false;
143 }
144 
145 /* Return true if given Resolvable Privae Address |rpa| matches Identity
146  * Resolving Key |irk| */
rpa_matches_irk(const RawAddress & rpa,const Octet16 & irk)147 static bool rpa_matches_irk(const RawAddress& rpa, const Octet16& irk) {
148   /* use the 3 MSB of bd address as prand */
149   uint8_t rand[3];
150   rand[0] = rpa.address[2];
151   rand[1] = rpa.address[1];
152   rand[2] = rpa.address[0];
153 
154   /* generate X = E irk(R0, R1, R2) and R is random address 3 LSO */
155   Octet16 x = crypto_toolbox::aes_128(irk, &rand[0], 3);
156 
157   rand[0] = rpa.address[5];
158   rand[1] = rpa.address[4];
159   rand[2] = rpa.address[3];
160 
161   if (memcmp(x.data(), &rand[0], 3) == 0) {
162     // match
163     return true;
164   }
165   // not a match
166   return false;
167 }
168 
169 /** This function checks if a RPA is resolvable by the device key.
170  *  Returns true is resolvable; false otherwise.
171  */
btm_ble_addr_resolvable(const RawAddress & rpa,tBTM_SEC_DEV_REC * p_dev_rec)172 bool btm_ble_addr_resolvable(const RawAddress& rpa,
173                              tBTM_SEC_DEV_REC* p_dev_rec) {
174   if (!BTM_BLE_IS_RESOLVE_BDA(rpa)) return false;
175 
176   if ((p_dev_rec->device_type & BT_DEVICE_TYPE_BLE) &&
177       (p_dev_rec->ble.key_type & BTM_LE_KEY_PID)) {
178     BTM_TRACE_DEBUG("%s try to resolve", __func__);
179 
180     if (rpa_matches_irk(rpa, p_dev_rec->ble.keys.irk)) {
181       btm_ble_init_pseudo_addr(p_dev_rec, rpa);
182       return true;
183     }
184   }
185   return false;
186 }
187 
188 /** This function match the random address to the appointed device record,
189  * starting from calculating IRK. If the record index exceeds the maximum record
190  * number, matching failed and send a callback. */
btm_ble_match_random_bda(void * data,void * context)191 static bool btm_ble_match_random_bda(void* data, void* context) {
192   tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
193   RawAddress* random_bda = static_cast<RawAddress*>(context);
194 
195   if (!(p_dev_rec->device_type & BT_DEVICE_TYPE_BLE) ||
196       !(p_dev_rec->ble.key_type & BTM_LE_KEY_PID))
197     // Match fails preconditions
198     return true;
199 
200   if (rpa_matches_irk(*random_bda, p_dev_rec->ble.keys.irk)) {
201     // Matched
202     return false;
203   }
204 
205   // This item not a match, continue iteration
206   return true;
207 }
208 
209 /** This function is called to resolve a random address.
210  * Returns pointer to the security record of the device whom a random address is
211  * matched to.
212  */
btm_ble_resolve_random_addr(const RawAddress & random_bda)213 tBTM_SEC_DEV_REC* btm_ble_resolve_random_addr(const RawAddress& random_bda) {
214   list_node_t* n = list_foreach(btm_cb.sec_dev_rec, btm_ble_match_random_bda,
215                                 (void*)&random_bda);
216   return (n == nullptr) ? (nullptr)
217                         : (static_cast<tBTM_SEC_DEV_REC*>(list_node(n)));
218 }
219 
220 /*******************************************************************************
221  *  address mapping between pseudo address and real connection address
222  ******************************************************************************/
223 /** Find the security record whose LE identity address is matching */
btm_find_dev_by_identity_addr(const RawAddress & bd_addr,uint8_t addr_type)224 static tBTM_SEC_DEV_REC* btm_find_dev_by_identity_addr(
225     const RawAddress& bd_addr, uint8_t addr_type) {
226   list_node_t* end = list_end(btm_cb.sec_dev_rec);
227   for (list_node_t* node = list_begin(btm_cb.sec_dev_rec); node != end;
228        node = list_next(node)) {
229     tBTM_SEC_DEV_REC* p_dev_rec =
230         static_cast<tBTM_SEC_DEV_REC*>(list_node(node));
231     if (p_dev_rec->ble.identity_address_with_type.bda == bd_addr) {
232       if ((p_dev_rec->ble.identity_address_with_type.type &
233            (~BLE_ADDR_TYPE_ID_BIT)) != (addr_type & (~BLE_ADDR_TYPE_ID_BIT)))
234         BTM_TRACE_WARNING(
235             "%s find pseudo->random match with diff addr type: %d vs %d",
236             __func__, p_dev_rec->ble.identity_address_with_type.type,
237             addr_type);
238 
239       /* found the match */
240       return p_dev_rec;
241     }
242   }
243 
244   return NULL;
245 }
246 
247 /*******************************************************************************
248  *
249  * Function         btm_identity_addr_to_random_pseudo
250  *
251  * Description      This function map a static BD address to a pseudo random
252  *                  address in security database.
253  *
254  ******************************************************************************/
btm_identity_addr_to_random_pseudo(RawAddress * bd_addr,uint8_t * p_addr_type,bool refresh)255 bool btm_identity_addr_to_random_pseudo(RawAddress* bd_addr,
256                                         uint8_t* p_addr_type, bool refresh) {
257   tBTM_SEC_DEV_REC* p_dev_rec =
258       btm_find_dev_by_identity_addr(*bd_addr, *p_addr_type);
259   if (p_dev_rec == nullptr) {
260     return false;
261   }
262 
263   /* evt reported on static address, map static address to random pseudo */
264   /* if RPA offloading is supported, or 4.2 controller, do RPA refresh */
265   if (refresh &&
266       controller_get_interface()->get_ble_resolving_list_max_size() != 0) {
267     btm_ble_read_resolving_list_entry(p_dev_rec);
268   }
269 
270   /* assign the original address to be the current report address */
271   if (!btm_ble_init_pseudo_addr(p_dev_rec, *bd_addr)) {
272     *bd_addr = p_dev_rec->ble.pseudo_addr;
273   }
274 
275   *p_addr_type = p_dev_rec->ble.ble_addr_type;
276   return true;
277 }
278 
btm_identity_addr_to_random_pseudo_from_address_with_type(tBLE_BD_ADDR * address_with_type,bool refresh)279 bool btm_identity_addr_to_random_pseudo_from_address_with_type(
280     tBLE_BD_ADDR* address_with_type, bool refresh) {
281   return btm_identity_addr_to_random_pseudo(
282       &(address_with_type->bda), &(address_with_type->type), refresh);
283 }
284 
285 /*******************************************************************************
286  *
287  * Function         btm_random_pseudo_to_identity_addr
288  *
289  * Description      This function map a random pseudo address to a public
290  *                  address. random_pseudo is input and output parameter
291  *
292  ******************************************************************************/
btm_random_pseudo_to_identity_addr(RawAddress * random_pseudo,uint8_t * p_identity_addr_type)293 bool btm_random_pseudo_to_identity_addr(RawAddress* random_pseudo,
294                                         uint8_t* p_identity_addr_type) {
295   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(*random_pseudo);
296 
297   if (p_dev_rec != NULL) {
298     if (p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT) {
299       *p_identity_addr_type = p_dev_rec->ble.identity_address_with_type.type;
300       *random_pseudo = p_dev_rec->ble.identity_address_with_type.bda;
301       if (controller_get_interface()->supports_ble_privacy())
302         *p_identity_addr_type |= BLE_ADDR_TYPE_ID_BIT;
303       return true;
304     }
305   }
306   return false;
307 }
308 
309 /*******************************************************************************
310  *
311  * Function         btm_ble_refresh_peer_resolvable_private_addr
312  *
313  * Description      This function refresh the currently used resolvable remote
314  *                  private address into security database and set active
315  *                  connection address.
316  *
317  ******************************************************************************/
btm_ble_refresh_peer_resolvable_private_addr(const RawAddress & pseudo_bda,const RawAddress & rpa,tBTM_SEC_BLE::tADDRESS_TYPE rra_type)318 void btm_ble_refresh_peer_resolvable_private_addr(
319     const RawAddress& pseudo_bda, const RawAddress& rpa,
320     tBTM_SEC_BLE::tADDRESS_TYPE rra_type) {
321   tBTM_SEC_DEV_REC* p_sec_rec = btm_find_dev(pseudo_bda);
322   if (p_sec_rec == nullptr) {
323     LOG_WARN("%s No matching known device in record", __func__);
324     return;
325   }
326 
327   p_sec_rec->ble.cur_rand_addr = rpa;
328 
329   if (rra_type == tBTM_SEC_BLE::BTM_BLE_ADDR_PSEUDO) {
330     p_sec_rec->ble.active_addr_type = rpa.IsEmpty()
331                                           ? tBTM_SEC_BLE::BTM_BLE_ADDR_STATIC
332                                           : tBTM_SEC_BLE::BTM_BLE_ADDR_RRA;
333   } else {
334     p_sec_rec->ble.active_addr_type = rra_type;
335   }
336 
337   /* connection refresh remote address */
338   const auto& identity_address = p_sec_rec->ble.identity_address_with_type.bda;
339   auto identity_address_type = p_sec_rec->ble.identity_address_with_type.type;
340 
341   if (!acl_refresh_remote_address(identity_address, identity_address_type,
342                                   p_sec_rec->bd_addr, rra_type, rpa)) {
343     // Try looking up the pseudo random address
344     if (!acl_refresh_remote_address(identity_address, identity_address_type,
345                                     p_sec_rec->ble.pseudo_addr, rra_type,
346                                     rpa)) {
347       LOG_ERROR("%s Unknown device to refresh remote device", __func__);
348     }
349   }
350 }
351