xref: /btstack/src/ble/le_device_db_tlv.c (revision 046b44372d25c7bd6fe78e5cf6e5176a1979f437)
1 /*
2  * Copyright (C) 2017 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "le_device_db_tlv.c"
39 
40 #include "ble/le_device_db.h"
41 #include "ble/le_device_db_tlv.h"
42 
43 #include "ble/core.h"
44 
45 #include <string.h>
46 #include "btstack_debug.h"
47 
48 // LE Device DB Implementation storing entries in btstack_tlv
49 
50 // Local cache is used to keep track of deleted entries in TLV
51 
52 #define INVALID_ENTRY_ADDR_TYPE 0xff
53 
54 // Single stored entry
55 typedef struct le_device_db_entry_t {
56 
57     uint32_t seq_nr;    // used for "least recently stored" eviction strategy
58 
59     // Identification
60     int addr_type;
61     bd_addr_t addr;
62     sm_key_t irk;
63 
64     // Stored pairing information allows to re-establish an enncrypted connection
65     // with a peripheral that doesn't have any persistent memory
66     sm_key_t ltk;
67     uint16_t ediv;
68     uint8_t  rand[8];
69 
70     uint8_t  key_size;
71     uint8_t  authenticated;
72     uint8_t  authorized;
73     uint8_t  secure_connection;
74 
75 #ifdef ENABLE_LE_SIGNED_WRITE
76     // Signed Writes by remote
77     sm_key_t remote_csrk;
78     uint32_t remote_counter;
79 
80     // Signed Writes by us
81     sm_key_t local_csrk;
82     uint32_t local_counter;
83 #endif
84 
85 } le_device_db_entry_t;
86 
87 
88 #ifndef NVM_NUM_DEVICE_DB_ENTRIES
89 #error "NVM_NUM_DEVICE_DB_ENTRIES not defined, please define in btstack_config.h"
90 #endif
91 
92 #if NVM_NUM_DEVICE_DB_ENTRIES == 0
93 #error "NVM_NUM_DEVICE_DB_ENTRIES must not be 0, please update in btstack_config.h"
94 #endif
95 
96 // only stores if entry present
97 static uint8_t  entry_map[NVM_NUM_DEVICE_DB_ENTRIES];
98 static uint32_t num_valid_entries;
99 
100 static const btstack_tlv_t * le_device_db_tlv_btstack_tlv_impl;
101 static       void *          le_device_db_tlv_btstack_tlv_context;
102 
103 static const char tag_0 = 'B';
104 static const char tag_1 = 'T';
105 static const char tag_2 = 'D';
106 
107 static uint32_t le_device_db_tlv_tag_for_index(uint8_t index){
108     return (tag_0 << 24) | (tag_1 << 16) | (tag_2 << 8) | index;
109 }
110 
111 // @returns success
112 // @param index = entry_pos
113 static int le_device_db_tlv_fetch(int index, le_device_db_entry_t * entry){
114     if (!le_device_db_tlv_btstack_tlv_impl) return 0;
115     if (index < 0 || index >= NVM_NUM_DEVICE_DB_ENTRIES){
116 	    log_error("le_device_db_tlv_fetch called with invalid index %d", index);
117 	    return 0;
118 	}
119     uint32_t tag = le_device_db_tlv_tag_for_index(index);
120     int size = le_device_db_tlv_btstack_tlv_impl->get_tag(le_device_db_tlv_btstack_tlv_context, tag, (uint8_t*) entry, sizeof(le_device_db_entry_t));
121 	return size == sizeof(le_device_db_entry_t);
122 }
123 
124 // @returns success
125 // @param index = entry_pos
126 static int le_device_db_tlv_store(int index, le_device_db_entry_t * entry){
127     if (!le_device_db_tlv_btstack_tlv_impl) return 0;
128     if (index < 0 || index >= NVM_NUM_DEVICE_DB_ENTRIES){
129 	    log_error("le_device_db_tlv_store called with invalid index %d", index);
130 	    return 0;
131 	}
132     uint32_t tag = le_device_db_tlv_tag_for_index(index);
133     le_device_db_tlv_btstack_tlv_impl->store_tag(le_device_db_tlv_btstack_tlv_context, tag, (uint8_t*) entry, sizeof(le_device_db_entry_t));
134 	return 1;
135 }
136 
137 // @param index = entry_pos
138 static int le_device_db_tlv_delete(int index){
139     if (!le_device_db_tlv_btstack_tlv_impl) return 0;
140     if (index < 0 || index >= NVM_NUM_DEVICE_DB_ENTRIES){
141 	    log_error("le_device_db_tlv_delete called with invalid index %d", index);
142 	    return 0;
143 	}
144     uint32_t tag = le_device_db_tlv_tag_for_index(index);
145     le_device_db_tlv_btstack_tlv_impl->delete_tag(le_device_db_tlv_btstack_tlv_context, tag);
146 	return 1;
147 }
148 
149 static void le_device_db_tlv_scan(void){
150     int i;
151     num_valid_entries = 0;
152     memset(entry_map, 0, sizeof(entry_map));
153     for (i=0;i<NVM_NUM_DEVICE_DB_ENTRIES;i++){
154         // lookup entry
155         le_device_db_entry_t entry;
156         if (!le_device_db_tlv_fetch(i, &entry)) continue;
157 
158         entry_map[i] = 1;
159         num_valid_entries++;
160     }
161     log_info("num valid le device entries %u", num_valid_entries);
162 }
163 
164 void le_device_db_init(void){
165     if (!le_device_db_tlv_btstack_tlv_impl) {
166         log_error("btstack_tlv not initialized");
167     }
168 }
169 
170 // not used
171 void le_device_db_set_local_bd_addr(bd_addr_t bd_addr){
172     (void)bd_addr;
173 }
174 
175 // @returns number of device in db
176 int le_device_db_count(void){
177 	return num_valid_entries;
178 }
179 
180 int le_device_db_max_count(void){
181     return NVM_NUM_DEVICE_DB_ENTRIES;
182 }
183 
184 void le_device_db_remove(int index){
185     // check if entry exists
186     if (entry_map[index] == 0) return;
187 
188 	// delete entry in TLV
189 	le_device_db_tlv_delete(index);
190 
191 	// mark as unused
192     entry_map[index] = 0;
193 
194     // keep track
195     num_valid_entries--;
196 }
197 
198 int le_device_db_add(int addr_type, bd_addr_t addr, sm_key_t irk){
199 
200     uint32_t highest_seq_nr = 0;
201     uint32_t lowest_seq_nr  = 0xFFFFFFFF;
202     int index_for_lowest_seq_nr = -1;
203     int index_for_addr  = -1;
204     int index_for_empty = -1;
205 
206 	// find unused entry in the used list
207     int i;
208     for (i=0;i<NVM_NUM_DEVICE_DB_ENTRIES;i++){
209          if (entry_map[i]) {
210             le_device_db_entry_t entry;
211             le_device_db_tlv_fetch(i, &entry);
212             // found addr?
213             if ((memcmp(addr, entry.addr, 6) == 0) && addr_type == entry.addr_type){
214                 index_for_addr = i;
215             }
216             // update highest seq nr
217             if (entry.seq_nr > highest_seq_nr){
218                 highest_seq_nr = entry.seq_nr;
219             }
220             // find entry with lowest seq nr
221             if ((index_for_lowest_seq_nr == -1) || (entry.seq_nr < lowest_seq_nr)){
222                 index_for_lowest_seq_nr = i;
223                 lowest_seq_nr = entry.seq_nr;
224             }
225         } else {
226             index_for_empty = i;
227         }
228     }
229 
230     log_info("index_for_addr %x, index_for_empy %x, index_for_lowest_seq_nr %x", index_for_addr, index_for_empty, index_for_lowest_seq_nr);
231 
232     uint32_t index_to_use = 0;
233     if (index_for_addr >= 0){
234         index_to_use = index_for_addr;
235     } else if (index_for_empty >= 0){
236         index_to_use = index_for_empty;
237     } else if (index_for_lowest_seq_nr >= 0){
238         index_to_use = index_for_lowest_seq_nr;
239     } else {
240         // should not happen
241         return -1;
242     }
243 
244     log_info("new entry for index %u", index_to_use);
245 
246     // store entry at index
247 	le_device_db_entry_t entry;
248     log_info("LE Device DB adding type %u - %s", addr_type, bd_addr_to_str(addr));
249     log_info_key("irk", irk);
250 
251     memset(&entry, 0, sizeof(le_device_db_entry_t));
252 
253     entry.addr_type = addr_type;
254     memcpy(entry.addr, addr, 6);
255     memcpy(entry.irk, irk, 16);
256     entry.seq_nr = highest_seq_nr + 1;
257  #ifdef ENABLE_LE_SIGNED_WRITE
258     entry.remote_counter = 0;
259 #endif
260 
261     // store
262     le_device_db_tlv_store(index_to_use, &entry);
263 
264     // set in entry_mape
265     entry_map[index_to_use] = 1;
266 
267     // keep track - don't increase if old entry found
268     if (index_for_addr < 0){
269         num_valid_entries++;
270     }
271 
272     return index_to_use;
273 }
274 
275 
276 // get device information: addr type and address
277 void le_device_db_info(int index, int * addr_type, bd_addr_t addr, sm_key_t irk){
278 
279 	// fetch entry
280     le_device_db_entry_t entry;
281     int ok = le_device_db_tlv_fetch(index, &entry);
282 
283     // set defaults if not found
284     if (!ok) {
285         memset(&entry, 0, sizeof(le_device_db_entry_t));
286         entry.addr_type = BD_ADDR_TYPE_UNKNOWN;
287     }
288 
289     // setup return values
290     if (addr_type) *addr_type = entry.addr_type;
291     if (addr) memcpy(addr, entry.addr, 6);
292     if (irk) memcpy(irk, entry.irk, 16);
293 }
294 
295 void le_device_db_encryption_set(int index, uint16_t ediv, uint8_t rand[8], sm_key_t ltk, int key_size, int authenticated, int authorized, int secure_connection){
296 
297 	// fetch entry
298 	le_device_db_entry_t entry;
299 	int ok = le_device_db_tlv_fetch(index, &entry);
300 	if (!ok) return;
301 
302 	// update
303     log_info("LE Device DB set encryption for %u, ediv x%04x, key size %u, authenticated %u, authorized %u, secure connection %u",
304         index, ediv, key_size, authenticated, authorized, secure_connection);
305     entry.ediv = ediv;
306     if (rand) memcpy(entry.rand, rand, 8);
307     if (ltk) memcpy(entry.ltk, ltk, 16);
308     entry.key_size = key_size;
309     entry.authenticated = authenticated;
310     entry.authorized = authorized;
311     entry.secure_connection = secure_connection;
312 
313     // store
314     le_device_db_tlv_store(index, &entry);
315 }
316 
317 void le_device_db_encryption_get(int index, uint16_t * ediv, uint8_t rand[8], sm_key_t ltk, int * key_size, int * authenticated, int * authorized, int * secure_connection){
318 
319 	// fetch entry
320 	le_device_db_entry_t entry;
321 	int ok = le_device_db_tlv_fetch(index, &entry);
322 	if (!ok) return;
323 
324 	// update user fields
325     log_info("LE Device DB encryption for %u, ediv x%04x, keysize %u, authenticated %u, authorized %u, secure connection %u",
326         index, entry.ediv, entry.key_size, entry.authenticated, entry.authorized, entry.secure_connection);
327     if (ediv) *ediv = entry.ediv;
328     if (rand) memcpy(rand, entry.rand, 8);
329     if (ltk)  memcpy(ltk, entry.ltk, 16);
330     if (key_size) *key_size = entry.key_size;
331     if (authenticated) *authenticated = entry.authenticated;
332     if (authorized) *authorized = entry.authorized;
333     if (secure_connection) *secure_connection = entry.secure_connection;
334 }
335 
336 #ifdef ENABLE_LE_SIGNED_WRITE
337 
338 // get signature key
339 void le_device_db_remote_csrk_get(int index, sm_key_t csrk){
340 
341 	// fetch entry
342 	le_device_db_entry_t entry;
343 	int ok = le_device_db_tlv_fetch(index, &entry);
344 	if (!ok) return;
345 
346     if (csrk) memcpy(csrk, entry.remote_csrk, 16);
347 }
348 
349 void le_device_db_remote_csrk_set(int index, sm_key_t csrk){
350 
351 	// fetch entry
352 	le_device_db_entry_t entry;
353 	int ok = le_device_db_tlv_fetch(index, &entry);
354 	if (!ok) return;
355 
356     if (!csrk) return;
357 
358     // update
359     memcpy(entry.remote_csrk, csrk, 16);
360 
361     // store
362     le_device_db_tlv_store(index, &entry);
363 }
364 
365 void le_device_db_local_csrk_get(int index, sm_key_t csrk){
366 
367 	// fetch entry
368 	le_device_db_entry_t entry;
369 	int ok = le_device_db_tlv_fetch(index, &entry);
370 	if (!ok) return;
371 
372     if (!csrk) return;
373 
374     // fill
375     memcpy(csrk, entry.local_csrk, 16);
376 }
377 
378 void le_device_db_local_csrk_set(int index, sm_key_t csrk){
379 
380 	// fetch entry
381 	le_device_db_entry_t entry;
382 	int ok = le_device_db_tlv_fetch(index, &entry);
383 	if (!ok) return;
384 
385     if (!csrk) return;
386 
387     // update
388     memcpy(entry.local_csrk, csrk, 16);
389 
390     // store
391     le_device_db_tlv_store(index, &entry);
392 }
393 
394 // query last used/seen signing counter
395 uint32_t le_device_db_remote_counter_get(int index){
396 
397 	// fetch entry
398 	le_device_db_entry_t entry;
399 	int ok = le_device_db_tlv_fetch(index, &entry);
400 	if (!ok) return 0;
401 
402     return entry.remote_counter;
403 }
404 
405 // update signing counter
406 void le_device_db_remote_counter_set(int index, uint32_t counter){
407 
408 	// fetch entry
409 	le_device_db_entry_t entry;
410 	int ok = le_device_db_tlv_fetch(index, &entry);
411 	if (!ok) return;
412 
413     entry.remote_counter = counter;
414 
415     // store
416     le_device_db_tlv_store(index, &entry);
417 }
418 
419 // query last used/seen signing counter
420 uint32_t le_device_db_local_counter_get(int index){
421 
422 	// fetch entry
423 	le_device_db_entry_t entry;
424 	int ok = le_device_db_tlv_fetch(index, &entry);
425 	if (!ok) return 0;
426 
427     return entry.local_counter;
428 }
429 
430 // update signing counter
431 void le_device_db_local_counter_set(int index, uint32_t counter){
432 
433 	// fetch entry
434 	le_device_db_entry_t entry;
435 	int ok = le_device_db_tlv_fetch(index, &entry);
436 	if (!ok) return;
437 
438 	// update
439     entry.local_counter = counter;
440 
441     // store
442     le_device_db_tlv_store(index, &entry);
443 }
444 
445 #endif
446 
447 void le_device_db_dump(void){
448     log_info("LE Device DB dump, devices: %d", le_device_db_count());
449     uint32_t i;
450 
451     for (i=0;i<NVM_NUM_DEVICE_DB_ENTRIES;i++){
452         if (!entry_map[i]) continue;
453 		// fetch entry
454 		le_device_db_entry_t entry;
455 		le_device_db_tlv_fetch(i, &entry);
456         log_info("%u: %u %s", i, entry.addr_type, bd_addr_to_str(entry.addr));
457         log_info_key("irk", entry.irk);
458 #ifdef ENABLE_LE_SIGNED_WRITE
459         log_info_key("local csrk", entry.local_csrk);
460         log_info_key("remote csrk", entry.remote_csrk);
461 #endif
462     }
463 }
464 
465 void le_device_db_tlv_configure(const btstack_tlv_t * btstack_tlv_impl, void * btstack_tlv_context){
466 	le_device_db_tlv_btstack_tlv_impl = btstack_tlv_impl;
467 	le_device_db_tlv_btstack_tlv_context = btstack_tlv_context;
468     le_device_db_tlv_scan();
469 }
470