xref: /btstack/src/ble/le_device_db_tlv.c (revision d58a1b5f11ada8ddf896c41fff5a35e7f140c37e)
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     btstack_assert(le_device_db_tlv_btstack_tlv_impl != NULL);
115     btstack_assert(index >= 0);
116     btstack_assert(index < NVM_NUM_DEVICE_DB_ENTRIES);
117 
118     uint32_t tag = le_device_db_tlv_tag_for_index(index);
119     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));
120 	return size == sizeof(le_device_db_entry_t);
121 }
122 
123 // @returns success
124 // @param index = entry_pos
125 static int le_device_db_tlv_store(int index, le_device_db_entry_t * entry){
126     btstack_assert(le_device_db_tlv_btstack_tlv_impl != NULL);
127     btstack_assert(index >= 0);
128     btstack_assert(index < NVM_NUM_DEVICE_DB_ENTRIES);
129 
130     uint32_t tag = le_device_db_tlv_tag_for_index(index);
131     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));
132 	return 1;
133 }
134 
135 // @param index = entry_pos
136 static int le_device_db_tlv_delete(int index){
137     btstack_assert(le_device_db_tlv_btstack_tlv_impl != NULL);
138     btstack_assert(index >= 0);
139     btstack_assert(index < NVM_NUM_DEVICE_DB_ENTRIES);
140 
141     uint32_t tag = le_device_db_tlv_tag_for_index(index);
142     le_device_db_tlv_btstack_tlv_impl->delete_tag(le_device_db_tlv_btstack_tlv_context, tag);
143 	return 1;
144 }
145 
146 static void le_device_db_tlv_scan(void){
147     int i;
148     num_valid_entries = 0;
149     memset(entry_map, 0, sizeof(entry_map));
150     for (i=0;i<NVM_NUM_DEVICE_DB_ENTRIES;i++){
151         // lookup entry
152         le_device_db_entry_t entry;
153         if (!le_device_db_tlv_fetch(i, &entry)) continue;
154 
155         entry_map[i] = 1;
156         num_valid_entries++;
157     }
158     log_info("num valid le device entries %u", num_valid_entries);
159 }
160 
161 void le_device_db_init(void){
162     if (!le_device_db_tlv_btstack_tlv_impl) {
163         log_error("btstack_tlv not initialized");
164     }
165 }
166 
167 // not used
168 void le_device_db_set_local_bd_addr(bd_addr_t bd_addr){
169     (void)bd_addr;
170 }
171 
172 // @returns number of device in db
173 int le_device_db_count(void){
174 	return num_valid_entries;
175 }
176 
177 int le_device_db_max_count(void){
178     return NVM_NUM_DEVICE_DB_ENTRIES;
179 }
180 
181 void le_device_db_remove(int index){
182     // check if entry exists
183     if (entry_map[index] == 0) return;
184 
185 	// delete entry in TLV
186 	le_device_db_tlv_delete(index);
187 
188 	// mark as unused
189     entry_map[index] = 0;
190 
191     // keep track
192     num_valid_entries--;
193 }
194 
195 int le_device_db_add(int addr_type, bd_addr_t addr, sm_key_t irk){
196 
197     uint32_t highest_seq_nr = 0;
198     uint32_t lowest_seq_nr  = 0xFFFFFFFF;
199     int index_for_lowest_seq_nr = -1;
200     int index_for_addr  = -1;
201     int index_for_empty = -1;
202 
203 	// find unused entry in the used list
204     int i;
205     for (i=0;i<NVM_NUM_DEVICE_DB_ENTRIES;i++){
206          if (entry_map[i]) {
207             le_device_db_entry_t entry;
208             le_device_db_tlv_fetch(i, &entry);
209             // found addr?
210             if ((memcmp(addr, entry.addr, 6) == 0) && (addr_type == entry.addr_type)){
211                 index_for_addr = i;
212             }
213             // update highest seq nr
214             if (entry.seq_nr > highest_seq_nr){
215                 highest_seq_nr = entry.seq_nr;
216             }
217             // find entry with lowest seq nr
218             if ((index_for_lowest_seq_nr == -1) || (entry.seq_nr < lowest_seq_nr)){
219                 index_for_lowest_seq_nr = i;
220                 lowest_seq_nr = entry.seq_nr;
221             }
222         } else {
223             index_for_empty = i;
224         }
225     }
226 
227     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);
228 
229     uint32_t index_to_use = 0;
230     if (index_for_addr >= 0){
231         index_to_use = index_for_addr;
232     } else if (index_for_empty >= 0){
233         index_to_use = index_for_empty;
234     } else if (index_for_lowest_seq_nr >= 0){
235         index_to_use = index_for_lowest_seq_nr;
236     } else {
237         // should not happen
238         return -1;
239     }
240 
241     log_info("new entry for index %u", index_to_use);
242 
243     // store entry at index
244 	le_device_db_entry_t entry;
245     log_info("LE Device DB adding type %u - %s", addr_type, bd_addr_to_str(addr));
246     log_info_key("irk", irk);
247 
248     memset(&entry, 0, sizeof(le_device_db_entry_t));
249 
250     entry.addr_type = addr_type;
251     memcpy(entry.addr, addr, 6);
252     memcpy(entry.irk, irk, 16);
253     entry.seq_nr = highest_seq_nr + 1;
254  #ifdef ENABLE_LE_SIGNED_WRITE
255     entry.remote_counter = 0;
256 #endif
257 
258     // store
259     le_device_db_tlv_store(index_to_use, &entry);
260 
261     // set in entry_mape
262     entry_map[index_to_use] = 1;
263 
264     // keep track - don't increase if old entry found
265     if (index_for_addr < 0){
266         num_valid_entries++;
267     }
268 
269     return index_to_use;
270 }
271 
272 
273 // get device information: addr type and address
274 void le_device_db_info(int index, int * addr_type, bd_addr_t addr, sm_key_t irk){
275 
276 	// fetch entry
277     le_device_db_entry_t entry;
278     int ok = le_device_db_tlv_fetch(index, &entry);
279 
280     // set defaults if not found
281     if (!ok) {
282         memset(&entry, 0, sizeof(le_device_db_entry_t));
283         entry.addr_type = BD_ADDR_TYPE_UNKNOWN;
284     }
285 
286     // setup return values
287     if (addr_type) *addr_type = entry.addr_type;
288     if (addr) memcpy(addr, entry.addr, 6);
289     if (irk) memcpy(irk, entry.irk, 16);
290 }
291 
292 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){
293 
294 	// fetch entry
295 	le_device_db_entry_t entry;
296 	int ok = le_device_db_tlv_fetch(index, &entry);
297 	if (!ok) return;
298 
299 	// update
300     log_info("LE Device DB set encryption for %u, ediv x%04x, key size %u, authenticated %u, authorized %u, secure connection %u",
301         index, ediv, key_size, authenticated, authorized, secure_connection);
302     entry.ediv = ediv;
303     if (rand) memcpy(entry.rand, rand, 8);
304     if (ltk) memcpy(entry.ltk, ltk, 16);
305     entry.key_size = key_size;
306     entry.authenticated = authenticated;
307     entry.authorized = authorized;
308     entry.secure_connection = secure_connection;
309 
310     // store
311     le_device_db_tlv_store(index, &entry);
312 }
313 
314 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){
315 
316 	// fetch entry
317 	le_device_db_entry_t entry;
318 	int ok = le_device_db_tlv_fetch(index, &entry);
319 	if (!ok) return;
320 
321 	// update user fields
322     log_info("LE Device DB encryption for %u, ediv x%04x, keysize %u, authenticated %u, authorized %u, secure connection %u",
323         index, entry.ediv, entry.key_size, entry.authenticated, entry.authorized, entry.secure_connection);
324     if (ediv) *ediv = entry.ediv;
325     if (rand) memcpy(rand, entry.rand, 8);
326     if (ltk)  memcpy(ltk, entry.ltk, 16);
327     if (key_size) *key_size = entry.key_size;
328     if (authenticated) *authenticated = entry.authenticated;
329     if (authorized) *authorized = entry.authorized;
330     if (secure_connection) *secure_connection = entry.secure_connection;
331 }
332 
333 #ifdef ENABLE_LE_SIGNED_WRITE
334 
335 // get signature key
336 void le_device_db_remote_csrk_get(int index, sm_key_t csrk){
337 
338 	// fetch entry
339 	le_device_db_entry_t entry;
340 	int ok = le_device_db_tlv_fetch(index, &entry);
341 	if (!ok) return;
342 
343     if (csrk) memcpy(csrk, entry.remote_csrk, 16);
344 }
345 
346 void le_device_db_remote_csrk_set(int index, sm_key_t csrk){
347 
348 	// fetch entry
349 	le_device_db_entry_t entry;
350 	int ok = le_device_db_tlv_fetch(index, &entry);
351 	if (!ok) return;
352 
353     if (!csrk) return;
354 
355     // update
356     memcpy(entry.remote_csrk, csrk, 16);
357 
358     // store
359     le_device_db_tlv_store(index, &entry);
360 }
361 
362 void le_device_db_local_csrk_get(int index, sm_key_t csrk){
363 
364 	// fetch entry
365 	le_device_db_entry_t entry;
366 	int ok = le_device_db_tlv_fetch(index, &entry);
367 	if (!ok) return;
368 
369     if (!csrk) return;
370 
371     // fill
372     memcpy(csrk, entry.local_csrk, 16);
373 }
374 
375 void le_device_db_local_csrk_set(int index, sm_key_t csrk){
376 
377 	// fetch entry
378 	le_device_db_entry_t entry;
379 	int ok = le_device_db_tlv_fetch(index, &entry);
380 	if (!ok) return;
381 
382     if (!csrk) return;
383 
384     // update
385     memcpy(entry.local_csrk, csrk, 16);
386 
387     // store
388     le_device_db_tlv_store(index, &entry);
389 }
390 
391 // query last used/seen signing counter
392 uint32_t le_device_db_remote_counter_get(int index){
393 
394 	// fetch entry
395 	le_device_db_entry_t entry;
396 	int ok = le_device_db_tlv_fetch(index, &entry);
397 	if (!ok) return 0;
398 
399     return entry.remote_counter;
400 }
401 
402 // update signing counter
403 void le_device_db_remote_counter_set(int index, uint32_t counter){
404 
405 	// fetch entry
406 	le_device_db_entry_t entry;
407 	int ok = le_device_db_tlv_fetch(index, &entry);
408 	if (!ok) return;
409 
410     entry.remote_counter = counter;
411 
412     // store
413     le_device_db_tlv_store(index, &entry);
414 }
415 
416 // query last used/seen signing counter
417 uint32_t le_device_db_local_counter_get(int index){
418 
419 	// fetch entry
420 	le_device_db_entry_t entry;
421 	int ok = le_device_db_tlv_fetch(index, &entry);
422 	if (!ok) return 0;
423 
424     return entry.local_counter;
425 }
426 
427 // update signing counter
428 void le_device_db_local_counter_set(int index, uint32_t counter){
429 
430 	// fetch entry
431 	le_device_db_entry_t entry;
432 	int ok = le_device_db_tlv_fetch(index, &entry);
433 	if (!ok) return;
434 
435 	// update
436     entry.local_counter = counter;
437 
438     // store
439     le_device_db_tlv_store(index, &entry);
440 }
441 
442 #endif
443 
444 void le_device_db_dump(void){
445     log_info("LE Device DB dump, devices: %d", le_device_db_count());
446     uint32_t i;
447 
448     for (i=0;i<NVM_NUM_DEVICE_DB_ENTRIES;i++){
449         if (!entry_map[i]) continue;
450 		// fetch entry
451 		le_device_db_entry_t entry;
452 		le_device_db_tlv_fetch(i, &entry);
453         log_info("%u: %u %s", i, entry.addr_type, bd_addr_to_str(entry.addr));
454         log_info_key("irk", entry.irk);
455 #ifdef ENABLE_LE_SIGNED_WRITE
456         log_info_key("local csrk", entry.local_csrk);
457         log_info_key("remote csrk", entry.remote_csrk);
458 #endif
459     }
460 }
461 
462 void le_device_db_tlv_configure(const btstack_tlv_t * btstack_tlv_impl, void * btstack_tlv_context){
463 	le_device_db_tlv_btstack_tlv_impl = btstack_tlv_impl;
464 	le_device_db_tlv_btstack_tlv_context = btstack_tlv_context;
465     le_device_db_tlv_scan();
466 }
467