1 /******************************************************************************
2 *
3 * Copyright 2018 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 #include "address_obfuscator.h"
20
21 #include <bluetooth/log.h>
22 #include <openssl/hmac.h>
23
24 #include <algorithm>
25
26 #include "internal_include/bt_trace.h"
27 #include "types/raw_address.h"
28
29 namespace bluetooth {
30 namespace common {
31
IsSaltValid(const Octet32 & salt_256bit)32 bool AddressObfuscator::IsSaltValid(const Octet32& salt_256bit) {
33 return !std::all_of(salt_256bit.begin(), salt_256bit.end(),
34 [](uint8_t i) { return i == 0; });
35 }
36
Initialize(const Octet32 & salt_256bit)37 void AddressObfuscator::Initialize(const Octet32& salt_256bit) {
38 std::lock_guard<std::recursive_mutex> lock(instance_mutex_);
39 salt_256bit_ = salt_256bit;
40 }
41
IsInitialized()42 bool AddressObfuscator::IsInitialized() {
43 std::lock_guard<std::recursive_mutex> lock(instance_mutex_);
44 return IsSaltValid(salt_256bit_);
45 }
46
Obfuscate(const RawAddress & address)47 std::string AddressObfuscator::Obfuscate(const RawAddress& address) {
48 std::lock_guard<std::recursive_mutex> lock(instance_mutex_);
49 log::assert_that(IsInitialized(), "assert failed: IsInitialized()");
50 std::array<uint8_t, EVP_MAX_MD_SIZE> result = {};
51 unsigned int out_len = 0;
52 log::assert_that(::HMAC(EVP_sha256(), salt_256bit_.data(),
53 salt_256bit_.size(), address.address, address.kLength,
54 result.data(), &out_len) != nullptr,
55 "assert failed: ::HMAC(EVP_sha256(), salt_256bit_.data(), "
56 "salt_256bit_.size(), address.address, address.kLength, "
57 "result.data(), &out_len) != nullptr");
58 log::assert_that(
59 out_len == static_cast<unsigned int>(kOctet32Length),
60 "assert failed: out_len == static_cast<unsigned int>(kOctet32Length)");
61 return std::string(reinterpret_cast<const char*>(result.data()), out_len);
62 }
63
64 } // namespace common
65 } // namespace bluetooth
66