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(), [](uint8_t i) { return i == 0; });
34 }
35 
Initialize(const Octet32 & salt_256bit)36 void AddressObfuscator::Initialize(const Octet32& salt_256bit) {
37   std::lock_guard<std::recursive_mutex> lock(instance_mutex_);
38   salt_256bit_ = salt_256bit;
39 }
40 
IsInitialized()41 bool AddressObfuscator::IsInitialized() {
42   std::lock_guard<std::recursive_mutex> lock(instance_mutex_);
43   return IsSaltValid(salt_256bit_);
44 }
45 
Obfuscate(const RawAddress & address)46 std::string AddressObfuscator::Obfuscate(const RawAddress& address) {
47   std::lock_guard<std::recursive_mutex> lock(instance_mutex_);
48   log::assert_that(IsInitialized(), "assert failed: IsInitialized()");
49   std::array<uint8_t, EVP_MAX_MD_SIZE> result = {};
50   unsigned int out_len = 0;
51   log::assert_that(::HMAC(EVP_sha256(), salt_256bit_.data(), salt_256bit_.size(), address.address,
52                           address.kLength, result.data(), &out_len) != nullptr,
53                    "assert failed: ::HMAC(EVP_sha256(), salt_256bit_.data(), "
54                    "salt_256bit_.size(), address.address, address.kLength, "
55                    "result.data(), &out_len) != nullptr");
56   log::assert_that(out_len == static_cast<unsigned int>(kOctet32Length),
57                    "assert failed: out_len == static_cast<unsigned int>(kOctet32Length)");
58   return std::string(reinterpret_cast<const char*>(result.data()), out_len);
59 }
60 
61 }  // namespace common
62 }  // namespace bluetooth
63