1 /******************************************************************************
2 *
3 * Copyright 2014 Google, Inc.
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 #define LOG_TAG "bt_btif_config"
20
21 #include "btif_config.h"
22
23 #include <base/logging.h>
24 #include <ctype.h>
25 #include <openssl/rand.h>
26 #include <openssl/sha.h>
27 #include <private/android_filesystem_config.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <time.h>
31 #include <unistd.h>
32 #include <mutex>
33 #include <sstream>
34 #include <string>
35
36 #include "bt_types.h"
37 #include "btcore/include/module.h"
38 #include "btif_api.h"
39 #include "btif_common.h"
40 #include "btif_config_transcode.h"
41 #include "btif_keystore.h"
42 #include "btif_util.h"
43 #include "common/address_obfuscator.h"
44 #include "osi/include/alarm.h"
45 #include "osi/include/allocator.h"
46 #include "osi/include/compat.h"
47 #include "osi/include/config.h"
48 #include "osi/include/log.h"
49 #include "osi/include/osi.h"
50 #include "osi/include/properties.h"
51
52 #define BT_CONFIG_SOURCE_TAG_NUM 1010001
53
54 #define INFO_SECTION "Info"
55 #define FILE_TIMESTAMP "TimeCreated"
56 #define FILE_SOURCE "FileSource"
57 #define TIME_STRING_LENGTH sizeof("YYYY-MM-DD HH:MM:SS")
58 #define DISABLED "disabled"
59 static const char* TIME_STRING_FORMAT = "%Y-%m-%d %H:%M:%S";
60
61 constexpr int kBufferSize = 400 * 10; // initial file is ~400B
62
use_key_attestation()63 static bool use_key_attestation() {
64 return getuid() == AID_BLUETOOTH && is_single_user_mode();
65 }
66
67 #define BT_CONFIG_METRICS_SECTION "Metrics"
68 #define BT_CONFIG_METRICS_SALT_256BIT "Salt256Bit"
69 using bluetooth::BtifKeystore;
70 using bluetooth::common::AddressObfuscator;
71
72 // TODO(armansito): Find a better way than searching by a hardcoded path.
73 #if defined(OS_GENERIC)
74 static const char* CONFIG_FILE_PATH = "bt_config.conf";
75 static const char* CONFIG_BACKUP_PATH = "bt_config.bak";
76 static const char* CONFIG_LEGACY_FILE_PATH = "bt_config.xml";
77 #else // !defined(OS_GENERIC)
78 static const char* CONFIG_FILE_PATH = "/data/misc/bluedroid/bt_config.conf";
79 static const char* CONFIG_BACKUP_PATH = "/data/misc/bluedroid/bt_config.bak";
80 static const char* CONFIG_FILE_CHECKSUM_PATH = "/data/misc/bluedroid/bt_config.conf.encrypted-checksum";
81 static const char* CONFIG_BACKUP_CHECKSUM_PATH = "/data/misc/bluedroid/bt_config.bak.encrypted-checksum";
82 static const char* CONFIG_LEGACY_FILE_PATH =
83 "/data/misc/bluedroid/bt_config.xml";
84 #endif // defined(OS_GENERIC)
85 static const uint64_t CONFIG_SETTLE_PERIOD_MS = 3000;
86
87 static void timer_config_save_cb(void* data);
88 static void btif_config_write(uint16_t event, char* p_param);
89 static bool is_factory_reset(void);
90 static void delete_config_files(void);
91 static void btif_config_remove_unpaired(config_t* config);
92 static void btif_config_remove_restricted(config_t* config);
93 static std::unique_ptr<config_t> btif_config_open(const char* filename, const char* checksum_filename);
94
95 // Key attestation
96 static std::string hash_file(const char* filename);
97 static std::string read_checksum_file(const char* filename);
98 static void write_checksum_file(const char* filename, const std::string& hash);
99
100 static enum ConfigSource {
101 NOT_LOADED,
102 ORIGINAL,
103 BACKUP,
104 LEGACY,
105 NEW_FILE,
106 RESET
107 } btif_config_source = NOT_LOADED;
108
109 static int btif_config_devices_loaded = -1;
110 static char btif_config_time_created[TIME_STRING_LENGTH];
111
112 // TODO(zachoverflow): Move these two functions out, because they are too
113 // specific for this file
114 // {grumpy-cat/no, monty-python/you-make-me-sad}
btif_get_device_type(const RawAddress & bda,int * p_device_type)115 bool btif_get_device_type(const RawAddress& bda, int* p_device_type) {
116 if (p_device_type == NULL) return false;
117
118 std::string addrstr = bda.ToString();
119 const char* bd_addr_str = addrstr.c_str();
120
121 if (!btif_config_get_int(bd_addr_str, "DevType", p_device_type)) return false;
122
123 LOG_DEBUG(LOG_TAG, "%s: Device [%s] type %d", __func__, bd_addr_str,
124 *p_device_type);
125 return true;
126 }
127
btif_get_address_type(const RawAddress & bda,int * p_addr_type)128 bool btif_get_address_type(const RawAddress& bda, int* p_addr_type) {
129 if (p_addr_type == NULL) return false;
130
131 std::string addrstr = bda.ToString();
132 const char* bd_addr_str = addrstr.c_str();
133
134 if (!btif_config_get_int(bd_addr_str, "AddrType", p_addr_type)) return false;
135
136 LOG_DEBUG(LOG_TAG, "%s: Device [%s] address type %d", __func__, bd_addr_str,
137 *p_addr_type);
138 return true;
139 }
140
141 /**
142 * Read metrics salt from config file, if salt is invalid or does not exist,
143 * generate new one and save it to config
144 */
read_or_set_metrics_salt()145 static void read_or_set_metrics_salt() {
146 AddressObfuscator::Octet32 metrics_salt = {};
147 size_t metrics_salt_length = metrics_salt.size();
148 if (!btif_config_get_bin(BT_CONFIG_METRICS_SECTION,
149 BT_CONFIG_METRICS_SALT_256BIT, metrics_salt.data(),
150 &metrics_salt_length)) {
151 LOG(WARNING) << __func__ << ": Failed to read metrics salt from config";
152 // Invalidate salt
153 metrics_salt.fill(0);
154 }
155 if (metrics_salt_length != metrics_salt.size()) {
156 LOG(ERROR) << __func__ << ": Metrics salt length incorrect, "
157 << metrics_salt_length << " instead of " << metrics_salt.size();
158 // Invalidate salt
159 metrics_salt.fill(0);
160 }
161 if (!AddressObfuscator::IsSaltValid(metrics_salt)) {
162 LOG(INFO) << __func__ << ": Metrics salt is not invalid, creating new one";
163 if (RAND_bytes(metrics_salt.data(), metrics_salt.size()) != 1) {
164 LOG(FATAL) << __func__ << "Failed to generate salt for metrics";
165 }
166 if (!btif_config_set_bin(BT_CONFIG_METRICS_SECTION,
167 BT_CONFIG_METRICS_SALT_256BIT, metrics_salt.data(),
168 metrics_salt.size())) {
169 LOG(FATAL) << __func__ << "Failed to write metrics salt to config";
170 }
171 }
172 AddressObfuscator::GetInstance()->Initialize(metrics_salt);
173 }
174
175 static std::recursive_mutex config_lock; // protects operations on |config|.
176 static std::unique_ptr<config_t> config;
177 static alarm_t* config_timer;
178
179 static BtifKeystore btif_keystore(new keystore::KeystoreClientImpl);
180
181 // Module lifecycle functions
182
init(void)183 static future_t* init(void) {
184 std::unique_lock<std::recursive_mutex> lock(config_lock);
185
186 if (is_factory_reset() ||
187 (use_key_attestation() && !btif_keystore.DoesKeyExist()))
188 delete_config_files();
189
190 std::string file_source;
191
192 config = btif_config_open(CONFIG_FILE_PATH, CONFIG_FILE_CHECKSUM_PATH);
193 btif_config_source = ORIGINAL;
194 if (!config) {
195 LOG_WARN(LOG_TAG, "%s unable to load config file: %s; using backup.",
196 __func__, CONFIG_FILE_PATH);
197 remove(CONFIG_FILE_CHECKSUM_PATH);
198 config = btif_config_open(CONFIG_BACKUP_PATH, CONFIG_BACKUP_CHECKSUM_PATH);
199 btif_config_source = BACKUP;
200 file_source = "Backup";
201 }
202 if (!config) {
203 LOG_WARN(LOG_TAG,
204 "%s unable to load backup; attempting to transcode legacy file.",
205 __func__);
206 remove(CONFIG_BACKUP_CHECKSUM_PATH);
207 config = btif_config_transcode(CONFIG_LEGACY_FILE_PATH);
208 btif_config_source = LEGACY;
209 file_source = "Legacy";
210 }
211 if (!config) {
212 LOG_ERROR(LOG_TAG,
213 "%s unable to transcode legacy file; creating empty config.",
214 __func__);
215 config = config_new_empty();
216 btif_config_source = NEW_FILE;
217 file_source = "Empty";
218 }
219
220 if (!file_source.empty())
221 config_set_string(config.get(), INFO_SECTION, FILE_SOURCE, file_source);
222
223 btif_config_remove_unpaired(config.get());
224
225 // Cleanup temporary pairings if we have left guest mode
226 if (!is_restricted_mode()) btif_config_remove_restricted(config.get());
227
228 // Read or set config file creation timestamp
229 const std::string* time_str;
230 time_str = config_get_string(*config, INFO_SECTION, FILE_TIMESTAMP, NULL);
231 if (time_str != NULL) {
232 strlcpy(btif_config_time_created, time_str->c_str(), TIME_STRING_LENGTH);
233 } else {
234 time_t current_time = time(NULL);
235 struct tm* time_created = localtime(¤t_time);
236 strftime(btif_config_time_created, TIME_STRING_LENGTH, TIME_STRING_FORMAT,
237 time_created);
238 config_set_string(config.get(), INFO_SECTION, FILE_TIMESTAMP,
239 btif_config_time_created);
240 }
241
242 // Read or set metrics 256 bit hashing salt
243 read_or_set_metrics_salt();
244
245 // TODO(sharvil): use a non-wake alarm for this once we have
246 // API support for it. There's no need to wake the system to
247 // write back to disk.
248 config_timer = alarm_new("btif.config");
249 if (!config_timer) {
250 LOG_ERROR(LOG_TAG, "%s unable to create alarm.", __func__);
251 goto error;
252 }
253
254 LOG_EVENT_INT(BT_CONFIG_SOURCE_TAG_NUM, btif_config_source);
255
256 return future_new_immediate(FUTURE_SUCCESS);
257
258 error:
259 alarm_free(config_timer);
260 config.reset();
261 config_timer = NULL;
262 btif_config_source = NOT_LOADED;
263 return future_new_immediate(FUTURE_FAIL);
264 }
265
btif_config_open(const char * filename,const char * checksum_filename)266 static std::unique_ptr<config_t> btif_config_open(const char* filename, const char* checksum_filename) {
267 // START KEY ATTESTATION
268 // Get hash of current file
269 std::string current_hash = hash_file(filename);
270 // Get stored hash
271 std::string stored_hash = read_checksum_file(checksum_filename);
272 if (stored_hash.empty()) {
273 LOG(ERROR) << __func__ << ": stored_hash=<empty>";
274 if (!current_hash.empty()) {
275 write_checksum_file(checksum_filename, current_hash);
276 stored_hash = read_checksum_file(checksum_filename);
277 }
278 }
279 // Compare hashes
280 if (current_hash != stored_hash) {
281 return nullptr;
282 }
283 // END KEY ATTESTATION
284
285 std::unique_ptr<config_t> config = config_new(filename);
286 if (!config) return nullptr;
287
288 if (!config_has_section(*config, "Adapter")) {
289 LOG_ERROR(LOG_TAG, "Config is missing adapter section");
290 return nullptr;
291 }
292
293 return config;
294 }
295
shut_down(void)296 static future_t* shut_down(void) {
297 btif_config_flush();
298 return future_new_immediate(FUTURE_SUCCESS);
299 }
300
clean_up(void)301 static future_t* clean_up(void) {
302 btif_config_flush();
303
304 alarm_free(config_timer);
305 config_timer = NULL;
306
307 std::unique_lock<std::recursive_mutex> lock(config_lock);
308 config.reset();
309 return future_new_immediate(FUTURE_SUCCESS);
310 }
311
312 EXPORT_SYMBOL module_t btif_config_module = {.name = BTIF_CONFIG_MODULE,
313 .init = init,
314 .start_up = NULL,
315 .shut_down = shut_down,
316 .clean_up = clean_up};
317
btif_config_has_section(const char * section)318 bool btif_config_has_section(const char* section) {
319 CHECK(config != NULL);
320 CHECK(section != NULL);
321
322 std::unique_lock<std::recursive_mutex> lock(config_lock);
323 return config_has_section(*config, section);
324 }
325
btif_config_exist(const std::string & section,const std::string & key)326 bool btif_config_exist(const std::string& section, const std::string& key) {
327 CHECK(config != NULL);
328
329 std::unique_lock<std::recursive_mutex> lock(config_lock);
330 return config_has_key(*config, section, key);
331 }
332
btif_config_get_int(const std::string & section,const std::string & key,int * value)333 bool btif_config_get_int(const std::string& section, const std::string& key,
334 int* value) {
335 CHECK(config != NULL);
336 CHECK(value != NULL);
337
338 std::unique_lock<std::recursive_mutex> lock(config_lock);
339 bool ret = config_has_key(*config, section, key);
340 if (ret) *value = config_get_int(*config, section, key, *value);
341
342 return ret;
343 }
344
btif_config_set_int(const std::string & section,const std::string & key,int value)345 bool btif_config_set_int(const std::string& section, const std::string& key,
346 int value) {
347 CHECK(config != NULL);
348
349 std::unique_lock<std::recursive_mutex> lock(config_lock);
350 config_set_int(config.get(), section, key, value);
351
352 return true;
353 }
354
btif_config_get_uint64(const std::string & section,const std::string & key,uint64_t * value)355 bool btif_config_get_uint64(const std::string& section, const std::string& key,
356 uint64_t* value) {
357 CHECK(config != NULL);
358 CHECK(value != NULL);
359
360 std::unique_lock<std::recursive_mutex> lock(config_lock);
361 bool ret = config_has_key(*config, section, key);
362 if (ret) *value = config_get_uint64(*config, section, key, *value);
363
364 return ret;
365 }
366
btif_config_set_uint64(const std::string & section,const std::string & key,uint64_t value)367 bool btif_config_set_uint64(const std::string& section, const std::string& key,
368 uint64_t value) {
369 CHECK(config != NULL);
370
371 std::unique_lock<std::recursive_mutex> lock(config_lock);
372 config_set_uint64(config.get(), section, key, value);
373
374 return true;
375 }
376
btif_config_get_str(const std::string & section,const std::string & key,char * value,int * size_bytes)377 bool btif_config_get_str(const std::string& section, const std::string& key,
378 char* value, int* size_bytes) {
379 CHECK(config != NULL);
380 CHECK(value != NULL);
381 CHECK(size_bytes != NULL);
382
383 {
384 std::unique_lock<std::recursive_mutex> lock(config_lock);
385 const std::string* stored_value =
386 config_get_string(*config, section, key, NULL);
387 if (!stored_value) return false;
388 strlcpy(value, stored_value->c_str(), *size_bytes);
389 }
390
391 *size_bytes = strlen(value) + 1;
392 return true;
393 }
394
btif_config_set_str(const std::string & section,const std::string & key,const std::string & value)395 bool btif_config_set_str(const std::string& section, const std::string& key,
396 const std::string& value) {
397 CHECK(config != NULL);
398
399 std::unique_lock<std::recursive_mutex> lock(config_lock);
400 config_set_string(config.get(), section, key, value);
401 return true;
402 }
403
btif_config_get_bin(const std::string & section,const std::string & key,uint8_t * value,size_t * length)404 bool btif_config_get_bin(const std::string& section, const std::string& key,
405 uint8_t* value, size_t* length) {
406 CHECK(config != NULL);
407 CHECK(value != NULL);
408 CHECK(length != NULL);
409
410 std::unique_lock<std::recursive_mutex> lock(config_lock);
411 const std::string* value_str = config_get_string(*config, section, key, NULL);
412
413 if (!value_str) {
414 VLOG(1) << __func__ << ": cannot find string for section " << section
415 << ", key " << key;
416 return false;
417 }
418
419 size_t value_len = value_str->length();
420 if ((value_len % 2) != 0 || *length < (value_len / 2)) {
421 LOG(WARNING) << ": value size not divisible by 2, size is " << value_len;
422 return false;
423 }
424
425 for (size_t i = 0; i < value_len; ++i)
426 if (!isxdigit(value_str->c_str()[i])) {
427 LOG(WARNING) << ": value is not hex digit";
428 return false;
429 }
430
431 const char* ptr = value_str->c_str();
432 for (*length = 0; *ptr; ptr += 2, *length += 1)
433 sscanf(ptr, "%02hhx", &value[*length]);
434
435 return true;
436 }
437
btif_config_get_bin_length(const std::string & section,const std::string & key)438 size_t btif_config_get_bin_length(const std::string& section,
439 const std::string& key) {
440 CHECK(config != NULL);
441
442 std::unique_lock<std::recursive_mutex> lock(config_lock);
443 const std::string* value_str = config_get_string(*config, section, key, NULL);
444 if (!value_str) return 0;
445
446 size_t value_len = value_str->length();
447 return ((value_len % 2) != 0) ? 0 : (value_len / 2);
448 }
449
btif_config_set_bin(const std::string & section,const std::string & key,const uint8_t * value,size_t length)450 bool btif_config_set_bin(const std::string& section, const std::string& key,
451 const uint8_t* value, size_t length) {
452 const char* lookup = "0123456789abcdef";
453
454 CHECK(config != NULL);
455
456 if (length > 0) CHECK(value != NULL);
457
458 size_t max_value = ((size_t)-1);
459 if (((max_value - 1) / 2) < length) {
460 LOG(ERROR) << __func__ << ": length too long";
461 return false;
462 }
463
464 char* str = (char*)osi_calloc(length * 2 + 1);
465
466 for (size_t i = 0; i < length; ++i) {
467 str[(i * 2) + 0] = lookup[(value[i] >> 4) & 0x0F];
468 str[(i * 2) + 1] = lookup[value[i] & 0x0F];
469 }
470
471 {
472 std::unique_lock<std::recursive_mutex> lock(config_lock);
473 config_set_string(config.get(), section, key, str);
474 }
475
476 osi_free(str);
477 return true;
478 }
479
btif_config_sections()480 std::list<section_t>& btif_config_sections() { return config->sections; }
481
btif_config_remove(const std::string & section,const std::string & key)482 bool btif_config_remove(const std::string& section, const std::string& key) {
483 CHECK(config != NULL);
484
485 std::unique_lock<std::recursive_mutex> lock(config_lock);
486 return config_remove_key(config.get(), section, key);
487 }
488
btif_config_save(void)489 void btif_config_save(void) {
490 CHECK(config != NULL);
491 CHECK(config_timer != NULL);
492
493 alarm_set(config_timer, CONFIG_SETTLE_PERIOD_MS, timer_config_save_cb, NULL);
494 }
495
btif_config_flush(void)496 void btif_config_flush(void) {
497 CHECK(config != NULL);
498 CHECK(config_timer != NULL);
499
500 alarm_cancel(config_timer);
501 btif_config_write(0, NULL);
502 }
503
btif_config_clear(void)504 bool btif_config_clear(void) {
505 CHECK(config != NULL);
506 CHECK(config_timer != NULL);
507
508 alarm_cancel(config_timer);
509
510 std::unique_lock<std::recursive_mutex> lock(config_lock);
511
512 config = config_new_empty();
513
514 bool ret = config_save(*config, CONFIG_FILE_PATH);
515 btif_config_source = RESET;
516
517 // Save encrypted hash
518 std::string current_hash = hash_file(CONFIG_FILE_PATH);
519 if (!current_hash.empty()) {
520 write_checksum_file(CONFIG_FILE_CHECKSUM_PATH, current_hash);
521 }
522
523 return ret;
524 }
525
timer_config_save_cb(UNUSED_ATTR void * data)526 static void timer_config_save_cb(UNUSED_ATTR void* data) {
527 // Moving file I/O to btif context instead of timer callback because
528 // it usually takes a lot of time to be completed, introducing
529 // delays during A2DP playback causing blips or choppiness.
530 btif_transfer_context(btif_config_write, 0, NULL, 0, NULL);
531 }
532
btif_config_write(UNUSED_ATTR uint16_t event,UNUSED_ATTR char * p_param)533 static void btif_config_write(UNUSED_ATTR uint16_t event,
534 UNUSED_ATTR char* p_param) {
535 CHECK(config != NULL);
536 CHECK(config_timer != NULL);
537
538 std::unique_lock<std::recursive_mutex> lock(config_lock);
539 rename(CONFIG_FILE_PATH, CONFIG_BACKUP_PATH);
540 rename(CONFIG_FILE_CHECKSUM_PATH, CONFIG_BACKUP_CHECKSUM_PATH);
541 std::unique_ptr<config_t> config_paired = config_new_clone(*config);
542 btif_config_remove_unpaired(config_paired.get());
543 config_save(*config_paired, CONFIG_FILE_PATH);
544 // Save hash
545 std::string current_hash = hash_file(CONFIG_FILE_PATH);
546 if (!current_hash.empty()) {
547 write_checksum_file(CONFIG_FILE_CHECKSUM_PATH, current_hash);
548 }
549 }
550
btif_config_remove_unpaired(config_t * conf)551 static void btif_config_remove_unpaired(config_t* conf) {
552 CHECK(conf != NULL);
553 int paired_devices = 0;
554
555 // The paired config used to carry information about
556 // discovered devices during regular inquiry scans.
557 // We remove these now and cache them in memory instead.
558 for (auto it = conf->sections.begin(); it != conf->sections.end();) {
559 std::string& section = it->name;
560 if (RawAddress::IsValidAddress(section)) {
561 // TODO: config_has_key loop thorugh all data, maybe just make it so we
562 // loop just once ?
563 if (!config_has_key(*conf, section, "LinkKey") &&
564 !config_has_key(*conf, section, "LE_KEY_PENC") &&
565 !config_has_key(*conf, section, "LE_KEY_PID") &&
566 !config_has_key(*conf, section, "LE_KEY_PCSRK") &&
567 !config_has_key(*conf, section, "LE_KEY_LENC") &&
568 !config_has_key(*conf, section, "LE_KEY_LCSRK")) {
569 it = conf->sections.erase(it);
570 continue;
571 }
572 paired_devices++;
573 }
574 it++;
575 }
576
577 // should only happen once, at initial load time
578 if (btif_config_devices_loaded == -1)
579 btif_config_devices_loaded = paired_devices;
580 }
581
btif_debug_config_dump(int fd)582 void btif_debug_config_dump(int fd) {
583 dprintf(fd, "\nBluetooth Config:\n");
584
585 dprintf(fd, " Config Source: ");
586 switch (btif_config_source) {
587 case NOT_LOADED:
588 dprintf(fd, "Not loaded\n");
589 break;
590 case ORIGINAL:
591 dprintf(fd, "Original file\n");
592 break;
593 case BACKUP:
594 dprintf(fd, "Backup file\n");
595 break;
596 case LEGACY:
597 dprintf(fd, "Legacy file\n");
598 break;
599 case NEW_FILE:
600 dprintf(fd, "New file\n");
601 break;
602 case RESET:
603 dprintf(fd, "Reset file\n");
604 break;
605 }
606
607 std::string original = "Original";
608 dprintf(fd, " Devices loaded: %d\n", btif_config_devices_loaded);
609 dprintf(fd, " File created/tagged: %s\n", btif_config_time_created);
610 dprintf(fd, " File source: %s\n",
611 config_get_string(*config, INFO_SECTION, FILE_SOURCE, &original)
612 ->c_str());
613 }
614
btif_config_remove_restricted(config_t * config)615 static void btif_config_remove_restricted(config_t* config) {
616 CHECK(config != NULL);
617
618 for (auto it = config->sections.begin(); it != config->sections.end();) {
619 const std::string& section = it->name;
620 if (RawAddress::IsValidAddress(section) &&
621 config_has_key(*config, section, "Restricted")) {
622 BTIF_TRACE_DEBUG("%s: Removing restricted device %s", __func__,
623 section.c_str());
624 it = config->sections.erase(it);
625 continue;
626 }
627 it++;
628 }
629 }
630
is_factory_reset(void)631 static bool is_factory_reset(void) {
632 char factory_reset[PROPERTY_VALUE_MAX] = {0};
633 osi_property_get("persist.bluetooth.factoryreset", factory_reset, "false");
634 return strncmp(factory_reset, "true", 4) == 0;
635 }
636
delete_config_files(void)637 static void delete_config_files(void) {
638 remove(CONFIG_FILE_PATH);
639 remove(CONFIG_BACKUP_PATH);
640 remove(CONFIG_FILE_CHECKSUM_PATH);
641 remove(CONFIG_BACKUP_CHECKSUM_PATH);
642 osi_property_set("persist.bluetooth.factoryreset", "false");
643 }
644
hash_file(const char * filename)645 static std::string hash_file(const char* filename) {
646 if (!use_key_attestation()) {
647 LOG(INFO) << __func__ << ": Disabled for multi-user";
648 return DISABLED;
649 }
650 FILE* fp = fopen(filename, "rb");
651 if (!fp) {
652 LOG(ERROR) << __func__ << ": unable to open config file: '" << filename
653 << "': " << strerror(errno);
654 return "";
655 }
656 uint8_t hash[SHA256_DIGEST_LENGTH];
657 SHA256_CTX sha256;
658 SHA256_Init(&sha256);
659 std::array<std::byte, kBufferSize> buffer;
660 int bytes_read = 0;
661 while ((bytes_read = fread(buffer.data(), 1, buffer.size(), fp))) {
662 SHA256_Update(&sha256, buffer.data(), bytes_read);
663 }
664 SHA256_Final(hash, &sha256);
665 std::stringstream ss;
666 for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
667 ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
668 }
669 fclose(fp);
670 return ss.str();
671 }
672
read_checksum_file(const char * checksum_filename)673 static std::string read_checksum_file(const char* checksum_filename) {
674 if (!use_key_attestation()) {
675 LOG(INFO) << __func__ << ": Disabled for multi-user";
676 return DISABLED;
677 }
678 std::string encrypted_hash = checksum_read(checksum_filename);
679 if (encrypted_hash.empty()) {
680 LOG(INFO) << __func__ << ": read empty hash.";
681 return "";
682 }
683 return btif_keystore.Decrypt(encrypted_hash);
684 }
685
write_checksum_file(const char * checksum_filename,const std::string & hash)686 static void write_checksum_file(const char* checksum_filename,
687 const std::string& hash) {
688 if (!use_key_attestation()) {
689 LOG(INFO) << __func__
690 << ": Disabled for multi-user, since config changed removing "
691 "checksums.";
692 remove(CONFIG_FILE_CHECKSUM_PATH);
693 remove(CONFIG_BACKUP_CHECKSUM_PATH);
694 return;
695 }
696 std::string encrypted_checksum = btif_keystore.Encrypt(hash, 0);
697 CHECK(!encrypted_checksum.empty())
698 << __func__ << ": Failed encrypting checksum";
699 CHECK(checksum_save(encrypted_checksum, checksum_filename))
700 << __func__ << ": Failed to save checksum!";
701 }
702