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