1 /*
2  *
3  *  Copyright 2019 The Android Open Source Project
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 #include "security_manager_impl.h"
19 
20 #include <iostream>
21 
22 #include "common/bind.h"
23 #include "crypto_toolbox/crypto_toolbox.h"
24 #include "hci/address_with_type.h"
25 #include "os/log.h"
26 #include "os/rand.h"
27 #include "security/initial_informations.h"
28 #include "security/internal/security_manager_impl.h"
29 #include "security/pairing_handler_le.h"
30 #include "security/security_manager.h"
31 #include "security/ui.h"
32 
33 namespace bluetooth {
34 namespace security {
35 namespace internal {
36 
DispatchPairingHandler(std::shared_ptr<record::SecurityRecord> record,bool locally_initiated,hci::IoCapability io_capability,hci::AuthenticationRequirements auth_requirements,pairing::OobData remote_p192_oob_data,pairing::OobData remote_p256_oob_data)37 void SecurityManagerImpl::DispatchPairingHandler(
38     std::shared_ptr<record::SecurityRecord> record,
39     bool locally_initiated,
40     hci::IoCapability io_capability,
41     hci::AuthenticationRequirements auth_requirements,
42     pairing::OobData remote_p192_oob_data,
43     pairing::OobData remote_p256_oob_data) {
44   common::OnceCallback<void(hci::Address, PairingResultOrFailure)> callback =
45       common::BindOnce(&SecurityManagerImpl::OnPairingHandlerComplete, common::Unretained(this));
46   auto entry = pairing_handler_map_.find(record->GetPseudoAddress()->GetAddress());
47   if (entry != pairing_handler_map_.end()) {
48     LOG_WARN("Device already has a pairing handler, and is in the middle of pairing!");
49     return;
50   }
51   std::shared_ptr<pairing::PairingHandler> pairing_handler = nullptr;
52   switch (record->GetPseudoAddress()->GetAddressType()) {
53     case hci::AddressType::PUBLIC_DEVICE_ADDRESS: {
54       pairing_handler = std::make_shared<security::pairing::ClassicPairingHandler>(
55           security_manager_channel_,
56           record,
57           security_handler_,
58           std::move(callback),
59           user_interface_,
60           user_interface_handler_,
61           record->GetPseudoAddress()->ToString(),
62           name_db_module_);
63       break;
64     }
65     default:
66       ASSERT_LOG(false, "Pairing type %hhu not implemented!", record->GetPseudoAddress()->GetAddressType());
67   }
68   auto new_entry = std::pair<hci::Address, std::shared_ptr<pairing::PairingHandler>>(
69       record->GetPseudoAddress()->GetAddress(), pairing_handler);
70   pairing_handler_map_.insert(std::move(new_entry));
71   pairing_handler->Initiate(
72       locally_initiated, io_capability, auth_requirements, remote_p192_oob_data, remote_p256_oob_data);
73 }
74 
Init()75 void SecurityManagerImpl::Init() {
76   security_manager_channel_->SetChannelListener(this);
77   security_manager_channel_->SendCommand(hci::WriteSimplePairingModeBuilder::Create(hci::Enable::ENABLED));
78   security_manager_channel_->SendCommand(hci::WriteSecureConnectionsHostSupportBuilder::Create(hci::Enable::ENABLED));
79 
80   ASSERT_LOG(storage_module_ != nullptr, "Storage module must not be null!");
81   security_database_.LoadRecordsFromStorage();
82 
83   storage::AdapterConfig adapter_config = storage_module_->GetAdapterConfig();
84   if (!adapter_config.GetLeIdentityResolvingKey()) {
85     auto mutation = storage_module_->Modify();
86     mutation.Add(adapter_config.SetLeIdentityResolvingKey(bluetooth::os::GenerateRandom<16>()));
87     mutation.Commit();
88   }
89 
90   Address controllerAddress = controller_->GetMacAddress();
91   if (!adapter_config.GetAddress() || adapter_config.GetAddress().value() != controllerAddress) {
92     auto mutation = storage_module_->Modify();
93     mutation.Add(adapter_config.SetAddress(controllerAddress));
94     mutation.Commit();
95   }
96 
97   local_identity_address_ =
98       hci::AddressWithType(adapter_config.GetAddress().value(), hci::AddressType::PUBLIC_DEVICE_ADDRESS);
99   local_identity_resolving_key_ = adapter_config.GetLeIdentityResolvingKey().value().bytes;
100 
101   hci::LeAddressManager::AddressPolicy address_policy = hci::LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS;
102   hci::AddressWithType address_with_type(hci::Address{}, hci::AddressType::RANDOM_DEVICE_ADDRESS);
103 
104   /* 7 minutes minimum, 15 minutes maximum for random address refreshing */
105   auto minimum_rotation_time = std::chrono::minutes(7);
106   auto maximum_rotation_time = std::chrono::minutes(15);
107 
108   acl_manager_->SetPrivacyPolicyForInitiatorAddress(
109       address_policy, address_with_type, minimum_rotation_time, maximum_rotation_time);
110 }
111 
CreateBond(hci::AddressWithType device)112 void SecurityManagerImpl::CreateBond(hci::AddressWithType device) {
113   this->CreateBondOutOfBand(device, pairing::OobData(), pairing::OobData());
114 }
115 
CreateBondOutOfBand(hci::AddressWithType device,pairing::OobData remote_p192_oob_data,pairing::OobData remote_p256_oob_data)116 void SecurityManagerImpl::CreateBondOutOfBand(
117     hci::AddressWithType device, pairing::OobData remote_p192_oob_data, pairing::OobData remote_p256_oob_data) {
118   auto record = security_database_.FindOrCreate(device);
119   if (record->IsPaired()) {
120     // Bonded means we saved it, but the caller doesn't care
121     // Bonded will always mean paired
122     NotifyDeviceBonded(device);
123   } else {
124     if (!record->IsPairing()) {
125       // Dispatch pairing handler, if we are calling create we are the initiator
126       LOG_WARN("Dispatch #1");
127       DispatchPairingHandler(
128           record,
129           true,
130           this->local_io_capability_,
131           this->local_authentication_requirements_,
132           remote_p192_oob_data,
133           remote_p256_oob_data);
134     }
135   }
136 }
137 
CreateBondLe(hci::AddressWithType address)138 void SecurityManagerImpl::CreateBondLe(hci::AddressWithType address) {
139   auto record = security_database_.FindOrCreate(address);
140   if (record->IsPaired()) {
141     NotifyDeviceBondFailed(address, PairingFailure("Already bonded"));
142     return;
143   }
144 
145   pending_le_pairing_.address_ = address;
146 
147   LeFixedChannelEntry* stored_chan = FindStoredLeChannel(address);
148   if (stored_chan) {
149     // We are already connected
150     ConnectionIsReadyStartPairing(stored_chan);
151     return;
152   }
153 
154   l2cap_manager_le_->ConnectServices(
155       address, common::BindOnce(&SecurityManagerImpl::OnConnectionFailureLe, common::Unretained(this)),
156       security_handler_);
157 }
158 
CancelBond(hci::AddressWithType device)159 void SecurityManagerImpl::CancelBond(hci::AddressWithType device) {
160   auto entry = pairing_handler_map_.find(device.GetAddress());
161   if (entry != pairing_handler_map_.end()) {
162     auto cancel_me = entry->second;
163     pairing_handler_map_.erase(entry);
164     cancel_me->Cancel();
165   }
166 
167   auto record = security_database_.FindOrCreate(device);
168   record->CancelPairing();
169 
170   WipeLePairingHandler();
171 }
172 
RemoveBond(hci::AddressWithType device)173 void SecurityManagerImpl::RemoveBond(hci::AddressWithType device) {
174   CancelBond(device);
175   security_manager_channel_->Disconnect(device.GetAddress());
176   security_database_.Remove(device);
177   security_manager_channel_->SendCommand(hci::DeleteStoredLinkKeyBuilder::Create(
178       device.GetAddress(), hci::DeleteStoredLinkKeyDeleteAllFlag::SPECIFIED_BD_ADDR));
179   NotifyDeviceUnbonded(device);
180 }
181 
SetUserInterfaceHandler(UI * user_interface,os::Handler * handler)182 void SecurityManagerImpl::SetUserInterfaceHandler(UI* user_interface, os::Handler* handler) {
183   if (user_interface_ != nullptr || user_interface_handler_ != nullptr) {
184     LOG_ALWAYS_FATAL("Listener has already been registered!");
185   }
186   user_interface_ = user_interface;
187   user_interface_handler_ = handler;
188 }
189 
190 // TODO(jpawlowski): remove once we have config file abstraction in cert tests
SetLeInitiatorAddressPolicyForTest(hci::LeAddressManager::AddressPolicy address_policy,hci::AddressWithType fixed_address,crypto_toolbox::Octet16 rotation_irk,std::chrono::milliseconds minimum_rotation_time,std::chrono::milliseconds maximum_rotation_time)191 void SecurityManagerImpl::SetLeInitiatorAddressPolicyForTest(
192     hci::LeAddressManager::AddressPolicy address_policy,
193     hci::AddressWithType fixed_address,
194     crypto_toolbox::Octet16 rotation_irk,
195     std::chrono::milliseconds minimum_rotation_time,
196     std::chrono::milliseconds maximum_rotation_time) {
197   acl_manager_->SetPrivacyPolicyForInitiatorAddressForTest(
198       address_policy, fixed_address, rotation_irk, minimum_rotation_time, maximum_rotation_time);
199 }
200 
RegisterCallbackListener(ISecurityManagerListener * listener,os::Handler * handler)201 void SecurityManagerImpl::RegisterCallbackListener(ISecurityManagerListener* listener, os::Handler* handler) {
202   for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
203     if (it->first == listener) {
204       LOG_ALWAYS_FATAL("Listener has already been registered!");
205     }
206   }
207 
208   listeners_.push_back({listener, handler});
209 }
210 
UnregisterCallbackListener(ISecurityManagerListener * listener)211 void SecurityManagerImpl::UnregisterCallbackListener(ISecurityManagerListener* listener) {
212   for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
213     if (it->first == listener) {
214       listeners_.erase(it);
215       return;
216     }
217   }
218 
219   LOG_ALWAYS_FATAL("Listener has not been registered!");
220 }
221 
NotifyDeviceBonded(hci::AddressWithType device)222 void SecurityManagerImpl::NotifyDeviceBonded(hci::AddressWithType device) {
223   for (auto& iter : listeners_) {
224     iter.second->Post(common::Bind(&ISecurityManagerListener::OnDeviceBonded, common::Unretained(iter.first), device));
225   }
226 }
227 
NotifyDeviceBondFailed(hci::AddressWithType device,PairingFailure status)228 void SecurityManagerImpl::NotifyDeviceBondFailed(hci::AddressWithType device, PairingFailure status) {
229   for (auto& iter : listeners_) {
230     iter.second->Post(
231         common::Bind(&ISecurityManagerListener::OnDeviceBondFailed, common::Unretained(iter.first), device, status));
232   }
233 }
234 
NotifyDeviceUnbonded(hci::AddressWithType device)235 void SecurityManagerImpl::NotifyDeviceUnbonded(hci::AddressWithType device) {
236   for (auto& iter : listeners_) {
237     iter.second->Post(
238         common::Bind(&ISecurityManagerListener::OnDeviceUnbonded, common::Unretained(iter.first), device));
239   }
240   acl_manager_->RemoveDeviceFromConnectList(device);
241 }
242 
NotifyEncryptionStateChanged(hci::EncryptionChangeView encryption_change_view)243 void SecurityManagerImpl::NotifyEncryptionStateChanged(hci::EncryptionChangeView encryption_change_view) {
244   for (auto& iter : listeners_) {
245     iter.second->Post(common::Bind(&ISecurityManagerListener::OnEncryptionStateChanged, common::Unretained(iter.first),
246                                    encryption_change_view));
247   }
248 }
249 
250 template <class T>
HandleEvent(T packet)251 void SecurityManagerImpl::HandleEvent(T packet) {
252   ASSERT(packet.IsValid());
253   auto entry = pairing_handler_map_.find(packet.GetBdAddr());
254 
255   if (entry == pairing_handler_map_.end()) {
256     auto bd_addr = packet.GetBdAddr();
257     auto event_code = packet.GetEventCode();
258 
259     if (event_code != hci::EventCode::LINK_KEY_REQUEST && event_code != hci::EventCode::PIN_CODE_REQUEST &&
260         event_code != hci::EventCode::IO_CAPABILITY_RESPONSE) {
261       LOG_ERROR("No classic pairing handler for device '%s' ready for command %s ", bd_addr.ToString().c_str(),
262                 hci::EventCodeText(event_code).c_str());
263       return;
264     }
265 
266     auto device = storage_module_->GetDeviceByClassicMacAddress(bd_addr);
267 
268     auto record =
269         security_database_.FindOrCreate(hci::AddressWithType{bd_addr, hci::AddressType::PUBLIC_DEVICE_ADDRESS});
270     LOG_WARN("Dispatch #2");
271     DispatchPairingHandler(
272         record,
273         false,
274         this->local_io_capability_,
275         this->local_authentication_requirements_,
276         pairing::OobData(),
277         pairing::OobData());
278     entry = pairing_handler_map_.find(bd_addr);
279   }
280   entry->second->OnReceive(packet);
281 }
282 
OnHciEventReceived(hci::EventView packet)283 void SecurityManagerImpl::OnHciEventReceived(hci::EventView packet) {
284   auto event = hci::EventView::Create(packet);
285   ASSERT_LOG(event.IsValid(), "Received invalid packet");
286   const hci::EventCode code = event.GetEventCode();
287   switch (code) {
288     case hci::EventCode::PIN_CODE_REQUEST:
289       HandleEvent<hci::PinCodeRequestView>(hci::PinCodeRequestView::Create(event));
290       break;
291     case hci::EventCode::LINK_KEY_REQUEST:
292       HandleEvent(hci::LinkKeyRequestView::Create(event));
293       break;
294     case hci::EventCode::LINK_KEY_NOTIFICATION:
295       HandleEvent(hci::LinkKeyNotificationView::Create(event));
296       break;
297     case hci::EventCode::IO_CAPABILITY_REQUEST:
298       HandleEvent(hci::IoCapabilityRequestView::Create(event));
299       break;
300     case hci::EventCode::IO_CAPABILITY_RESPONSE:
301       HandleEvent(hci::IoCapabilityResponseView::Create(event));
302       break;
303     case hci::EventCode::SIMPLE_PAIRING_COMPLETE:
304       HandleEvent(hci::SimplePairingCompleteView::Create(event));
305       break;
306     case hci::EventCode::REMOTE_OOB_DATA_REQUEST:
307       HandleEvent(hci::RemoteOobDataRequestView::Create(event));
308       break;
309     case hci::EventCode::USER_PASSKEY_NOTIFICATION:
310       HandleEvent(hci::UserPasskeyNotificationView::Create(event));
311       break;
312     case hci::EventCode::KEYPRESS_NOTIFICATION:
313       HandleEvent(hci::KeypressNotificationView::Create(event));
314       break;
315     case hci::EventCode::USER_CONFIRMATION_REQUEST:
316       HandleEvent(hci::UserConfirmationRequestView::Create(event));
317       break;
318     case hci::EventCode::USER_PASSKEY_REQUEST:
319       HandleEvent(hci::UserPasskeyRequestView::Create(event));
320       break;
321     case hci::EventCode::REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION:
322       LOG_INFO("Unhandled event: %s", hci::EventCodeText(code).c_str());
323       break;
324 
325     case hci::EventCode::ENCRYPTION_CHANGE: {
326       EncryptionChangeView encryption_change_view = EncryptionChangeView::Create(event);
327       if (!encryption_change_view.IsValid()) {
328         LOG_ERROR("Invalid EncryptionChange packet received");
329         return;
330       }
331       if (encryption_change_view.GetConnectionHandle() == pending_le_pairing_.connection_handle_) {
332         pending_le_pairing_.handler_->OnHciEvent(event);
333         return;
334       }
335       NotifyEncryptionStateChanged(encryption_change_view);
336       break;
337     }
338 
339     default:
340       ASSERT_LOG(false, "Cannot handle received packet: %s", hci::EventCodeText(code).c_str());
341       break;
342   }
343 }
344 
OnConnectionClosed(hci::Address address)345 void SecurityManagerImpl::OnConnectionClosed(hci::Address address) {
346   auto entry = pairing_handler_map_.find(address);
347   if (entry != pairing_handler_map_.end()) {
348     LOG_INFO("Cancelling pairing handler for '%s'", address.ToString().c_str());
349     entry->second->Cancel();
350   }
351   auto record = security_database_.FindOrCreate(hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS));
352   if (record->IsTemporary()) {
353     security_database_.Remove(hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS));
354   }
355   if (this->facade_disconnect_callback_) {
356     this->security_handler_->Call(
357         *this->facade_disconnect_callback_, hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS));
358   }
359 }
360 
OnHciLeEvent(hci::LeMetaEventView event)361 void SecurityManagerImpl::OnHciLeEvent(hci::LeMetaEventView event) {
362   hci::SubeventCode code = event.GetSubeventCode();
363 
364   if (code == hci::SubeventCode::LONG_TERM_KEY_REQUEST) {
365     hci::LeLongTermKeyRequestView le_long_term_key_request_view = hci::LeLongTermKeyRequestView::Create(event);
366     if (!le_long_term_key_request_view.IsValid()) {
367       LOG_ERROR("Invalid LeLongTermKeyRequestView packet received");
368       return;
369     }
370 
371     if (le_long_term_key_request_view.GetConnectionHandle() == pending_le_pairing_.connection_handle_) {
372       pending_le_pairing_.handler_->OnHciLeEvent(event);
373       return;
374     }
375 
376     LOG_INFO("Unhandled HCI LE security event, code %s", hci::SubeventCodeText(code).c_str());
377     return;
378   }
379 
380   // hci::SubeventCode::READ_LOCAL_P256_PUBLIC_KEY_COMPLETE,
381   // hci::SubeventCode::GENERATE_DHKEY_COMPLETE,
382   LOG_ERROR("Unhandled HCI LE security event, code %s", hci::SubeventCodeText(code).c_str());
383 }
384 
OnPairingPromptAccepted(const bluetooth::hci::AddressWithType & address,bool confirmed)385 void SecurityManagerImpl::OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, bool confirmed) {
386   auto entry = pairing_handler_map_.find(address.GetAddress());
387   if (entry != pairing_handler_map_.end()) {
388     entry->second->OnPairingPromptAccepted(address, confirmed);
389   } else {
390     if (pending_le_pairing_.address_ == address) {
391       pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::PAIRING_ACCEPTED, confirmed);
392     }
393   }
394 }
395 
OnConfirmYesNo(const bluetooth::hci::AddressWithType & address,bool confirmed)396 void SecurityManagerImpl::OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, bool confirmed) {
397   auto entry = pairing_handler_map_.find(address.GetAddress());
398   if (entry != pairing_handler_map_.end()) {
399     entry->second->OnConfirmYesNo(address, confirmed);
400   } else {
401     if (pending_le_pairing_.address_ == address) {
402       pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::CONFIRM_YESNO, confirmed);
403     }
404   }
405 }
406 
OnPasskeyEntry(const bluetooth::hci::AddressWithType & address,uint32_t passkey)407 void SecurityManagerImpl::OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, uint32_t passkey) {
408   auto entry = pairing_handler_map_.find(address.GetAddress());
409   if (entry != pairing_handler_map_.end()) {
410     entry->second->OnPasskeyEntry(address, passkey);
411   } else {
412     if (pending_le_pairing_.address_ == address) {
413       pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::PASSKEY, passkey);
414     }
415   }
416 }
417 
OnPinEntry(const bluetooth::hci::AddressWithType & address,std::vector<uint8_t> pin)418 void SecurityManagerImpl::OnPinEntry(const bluetooth::hci::AddressWithType& address, std::vector<uint8_t> pin) {
419   auto entry = pairing_handler_map_.find(address.GetAddress());
420   if (entry != pairing_handler_map_.end()) {
421     LOG_INFO("PIN for %s", address.ToString().c_str());
422     entry->second->OnPinEntry(address, pin);
423   } else {
424     LOG_WARN("No handler found for PIN for %s", address.ToString().c_str());
425     // TODO(jpawlowski): Implement LE version
426   }
427 }
428 
OnPairingHandlerComplete(hci::Address address,PairingResultOrFailure status)429 void SecurityManagerImpl::OnPairingHandlerComplete(hci::Address address, PairingResultOrFailure status) {
430   auto entry = pairing_handler_map_.find(address);
431   if (entry != pairing_handler_map_.end()) {
432     pairing_handler_map_.erase(entry);
433     security_manager_channel_->Release(address);
434   }
435   auto remote = hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS);
436   if (!std::holds_alternative<PairingFailure>(status)) {
437     NotifyDeviceBonded(remote);
438   } else {
439     NotifyDeviceBondFailed(remote, std::get<PairingFailure>(status));
440   }
441   auto record = this->security_database_.FindOrCreate(remote);
442   record->CancelPairing();
443   security_database_.SaveRecordsToStorage();
444   // Only call update link if we need to
445   auto policy_callback_entry = enforce_security_policy_callback_map_.find(remote);
446   if (policy_callback_entry != enforce_security_policy_callback_map_.end()) {
447     UpdateLinkSecurityCondition(remote);
448   }
449 }
450 
OnL2capRegistrationCompleteLe(l2cap::le::FixedChannelManager::RegistrationResult result,std::unique_ptr<l2cap::le::FixedChannelService> le_smp_service)451 void SecurityManagerImpl::OnL2capRegistrationCompleteLe(
452     l2cap::le::FixedChannelManager::RegistrationResult result,
453     std::unique_ptr<l2cap::le::FixedChannelService> le_smp_service) {
454   ASSERT_LOG(result == bluetooth::l2cap::le::FixedChannelManager::RegistrationResult::SUCCESS,
455              "Failed to register to LE SMP Fixed Channel Service");
456 }
457 
FindStoredLeChannel(const hci::AddressWithType & device)458 LeFixedChannelEntry* SecurityManagerImpl::FindStoredLeChannel(const hci::AddressWithType& device) {
459   for (LeFixedChannelEntry& storage : all_channels_) {
460     if (storage.channel_->GetDevice() == device) {
461       return &storage;
462     }
463   }
464   return nullptr;
465 }
466 
EraseStoredLeChannel(const hci::AddressWithType & device)467 bool SecurityManagerImpl::EraseStoredLeChannel(const hci::AddressWithType& device) {
468   for (auto it = all_channels_.begin(); it != all_channels_.end(); it++) {
469     if (it->channel_->GetDevice() == device) {
470       all_channels_.erase(it);
471       return true;
472     }
473   }
474   return false;
475 }
476 
OnSmpCommandLe(hci::AddressWithType device)477 void SecurityManagerImpl::OnSmpCommandLe(hci::AddressWithType device) {
478   LeFixedChannelEntry* stored_chan = FindStoredLeChannel(device);
479   if (!stored_chan) {
480     LOG_ALWAYS_FATAL("Received SMP command for unknown channel");
481     return;
482   }
483 
484   std::unique_ptr<l2cap::le::FixedChannel>& channel = stored_chan->channel_;
485 
486   auto packet = channel->GetQueueUpEnd()->TryDequeue();
487   if (!packet) {
488     LOG_ERROR("Received dequeue, but no data ready...");
489     return;
490   }
491 
492   // Pending pairing - pass the data to the handler
493   auto temp_cmd_view = CommandView::Create(*packet);
494   if (pending_le_pairing_.address_ == device) {
495     pending_le_pairing_.handler_->OnCommandView(temp_cmd_view);
496     return;
497   }
498 
499   // no pending pairing attempt
500   if (!temp_cmd_view.IsValid()) {
501     LOG_ERROR("Invalid Command packet");
502     return;
503   }
504 
505   if (temp_cmd_view.GetCode() == Code::SECURITY_REQUEST) {
506     // TODO: either start encryption or pairing
507     LOG_WARN("Unhandled security request!!!");
508     return;
509   }
510 
511   auto my_role = channel->GetLinkOptions()->GetRole();
512   if (temp_cmd_view.GetCode() == Code::PAIRING_REQUEST && my_role == hci::Role::PERIPHERAL) {
513     // TODO: if (pending_le_pairing_) { do not start another }
514 
515     LOG_INFO("start of security request handling!");
516 
517     stored_chan->channel_->Acquire();
518 
519     PairingRequestView pairing_request = PairingRequestView::Create(temp_cmd_view);
520     auto& enqueue_buffer = stored_chan->enqueue_buffer_;
521 
522     std::optional<InitialInformations::out_of_band_data> remote_oob_data = std::nullopt;
523     if (remote_oob_data_address_.has_value() && remote_oob_data_address_.value() == channel->GetDevice())
524       remote_oob_data = InitialInformations::out_of_band_data{.le_sc_c = remote_oob_data_le_sc_c_.value(),
525                                                               .le_sc_r = remote_oob_data_le_sc_r_.value()};
526 
527     // TODO: this doesn't have to be a unique ptr, if there is a way to properly std::move it into place where it's
528     // stored
529     pending_le_pairing_.connection_handle_ = channel->GetLinkOptions()->GetHandle();
530     InitialInformations initial_informations{
531         .my_role = my_role,
532         .my_connection_address = channel->GetLinkOptions()->GetLocalAddress(),
533         .my_identity_address = local_identity_address_,
534         .my_identity_resolving_key = local_identity_resolving_key_,
535         /*TODO: properly obtain capabilities from device-specific storage*/
536         .myPairingCapabilities = {.io_capability = local_le_io_capability_,
537                                   .oob_data_flag = local_le_oob_data_present_,
538                                   .auth_req = local_le_auth_req_,
539                                   .maximum_encryption_key_size = local_maximum_encryption_key_size_,
540                                   .initiator_key_distribution = 0x07,
541                                   .responder_key_distribution = 0x07},
542         .remotely_initiated = true,
543         .connection_handle = channel->GetLinkOptions()->GetHandle(),
544         .remote_connection_address = channel->GetDevice(),
545         .remote_name = "TODO: grab proper device name in sec mgr",
546         /* contains pairing request, if the pairing was remotely initiated */
547         .pairing_request = pairing_request,
548         .remote_oob_data = remote_oob_data,
549         .my_oob_data = local_le_oob_data_,
550         /* Used by Pairing Handler to present user with requests*/
551         .user_interface = user_interface_,
552         .user_interface_handler = user_interface_handler_,
553 
554         /* HCI interface to use */
555         .le_security_interface = hci_security_interface_le_,
556         .proper_l2cap_interface = enqueue_buffer.get(),
557         .l2cap_handler = security_handler_,
558         /* Callback to execute once the Pairing process is finished */
559         // TODO: make it an common::OnceCallback ?
560         .OnPairingFinished = std::bind(&SecurityManagerImpl::OnPairingFinished, this, std::placeholders::_1),
561     };
562     pending_le_pairing_.address_ = device;
563     pending_le_pairing_.handler_ = std::make_unique<PairingHandlerLe>(PairingHandlerLe::PHASE1, initial_informations);
564   }
565 }
566 
OnConnectionOpenLe(std::unique_ptr<l2cap::le::FixedChannel> channel_param)567 void SecurityManagerImpl::OnConnectionOpenLe(std::unique_ptr<l2cap::le::FixedChannel> channel_param) {
568   auto enqueue_buffer_temp =
569       std::make_unique<os::EnqueueBuffer<packet::BasePacketBuilder>>(channel_param->GetQueueUpEnd());
570 
571   all_channels_.push_back({std::move(channel_param), std::move(enqueue_buffer_temp)});
572   auto& stored_channel = all_channels_.back();
573   auto& channel = stored_channel.channel_;
574 
575   channel->RegisterOnCloseCallback(
576       security_handler_,
577       common::BindOnce(&SecurityManagerImpl::OnConnectionClosedLe, common::Unretained(this), channel->GetDevice()));
578   channel->GetQueueUpEnd()->RegisterDequeue(
579       security_handler_,
580       common::Bind(&SecurityManagerImpl::OnSmpCommandLe, common::Unretained(this), channel->GetDevice()));
581 
582   if (pending_le_pairing_.address_ != channel->GetDevice()) {
583     return;
584   }
585 
586   ConnectionIsReadyStartPairing(&stored_channel);
587 }
588 
ConnectionIsReadyStartPairing(LeFixedChannelEntry * stored_channel)589 void SecurityManagerImpl::ConnectionIsReadyStartPairing(LeFixedChannelEntry* stored_channel) {
590   auto& channel = stored_channel->channel_;
591   auto& enqueue_buffer = stored_channel->enqueue_buffer_;
592 
593   stored_channel->channel_->Acquire();
594 
595   std::optional<InitialInformations::out_of_band_data> remote_oob_data = std::nullopt;
596   if (remote_oob_data_address_.has_value() && remote_oob_data_address_.value() == channel->GetDevice())
597     remote_oob_data = InitialInformations::out_of_band_data{.le_sc_c = remote_oob_data_le_sc_c_.value(),
598                                                             .le_sc_r = remote_oob_data_le_sc_r_.value()};
599 
600   // TODO: this doesn't have to be a unique ptr, if there is a way to properly std::move it into place where it's stored
601   pending_le_pairing_.connection_handle_ = channel->GetLinkOptions()->GetHandle();
602   InitialInformations initial_informations{
603       .my_role = channel->GetLinkOptions()->GetRole(),
604       .my_connection_address = channel->GetLinkOptions()->GetLocalAddress(),
605       .my_identity_address = local_identity_address_,
606       .my_identity_resolving_key = local_identity_resolving_key_,
607       /*TODO: properly obtain capabilities from device-specific storage*/
608       .myPairingCapabilities = {.io_capability = local_le_io_capability_,
609                                 .oob_data_flag = local_le_oob_data_present_,
610                                 .auth_req = local_le_auth_req_,
611                                 .maximum_encryption_key_size = local_maximum_encryption_key_size_,
612                                 .initiator_key_distribution = 0x07,
613                                 .responder_key_distribution = 0x07},
614       .remotely_initiated = false,
615       .connection_handle = channel->GetLinkOptions()->GetHandle(),
616       .remote_connection_address = channel->GetDevice(),
617       .remote_name = "TODO: grab proper device name in sec mgr",
618       /* contains pairing request, if the pairing was remotely initiated */
619       .pairing_request = std::nullopt,  // TODO: handle remotely initiated pairing in SecurityManager properly
620       .remote_oob_data = remote_oob_data,
621       .my_oob_data = local_le_oob_data_,
622       /* Used by Pairing Handler to present user with requests*/
623       .user_interface = user_interface_,
624       .user_interface_handler = user_interface_handler_,
625 
626       /* HCI interface to use */
627       .le_security_interface = hci_security_interface_le_,
628       .proper_l2cap_interface = enqueue_buffer.get(),
629       .l2cap_handler = security_handler_,
630       /* Callback to execute once the Pairing process is finished */
631       // TODO: make it an common::OnceCallback ?
632       .OnPairingFinished = std::bind(&SecurityManagerImpl::OnPairingFinished, this, std::placeholders::_1),
633   };
634   pending_le_pairing_.handler_ = std::make_unique<PairingHandlerLe>(PairingHandlerLe::PHASE1, initial_informations);
635 }
636 
OnConnectionClosedLe(hci::AddressWithType address,hci::ErrorCode error_code)637 void SecurityManagerImpl::OnConnectionClosedLe(hci::AddressWithType address, hci::ErrorCode error_code) {
638   if (pending_le_pairing_.address_ != address) {
639     LeFixedChannelEntry* stored_chan = FindStoredLeChannel(address);
640     if (!stored_chan) {
641       LOG_ALWAYS_FATAL("Received connection closed for unknown channel");
642       return;
643     }
644     stored_chan->channel_->GetQueueUpEnd()->UnregisterDequeue();
645     stored_chan->enqueue_buffer_.reset();
646     EraseStoredLeChannel(address);
647     return;
648   }
649   pending_le_pairing_.handler_->SendExitSignal();
650   NotifyDeviceBondFailed(address, PairingFailure("Connection closed"));
651 }
652 
OnConnectionFailureLe(bluetooth::l2cap::le::FixedChannelManager::ConnectionResult result)653 void SecurityManagerImpl::OnConnectionFailureLe(bluetooth::l2cap::le::FixedChannelManager::ConnectionResult result) {
654   if (result.connection_result_code ==
655       bluetooth::l2cap::le::FixedChannelManager::ConnectionResultCode::FAIL_ALL_SERVICES_HAVE_CHANNEL) {
656     // TODO: already connected
657   }
658 
659   // This callback is invoked only for devices we attempted to connect to.
660   NotifyDeviceBondFailed(pending_le_pairing_.address_, PairingFailure("Connection establishment failed"));
661 }
662 
SecurityManagerImpl(os::Handler * security_handler,l2cap::le::L2capLeModule * l2cap_le_module,channel::SecurityManagerChannel * security_manager_channel,hci::HciLayer * hci_layer,hci::AclManager * acl_manager,hci::Controller * controller,storage::StorageModule * storage_module,neighbor::NameDbModule * name_db_module)663 SecurityManagerImpl::SecurityManagerImpl(
664     os::Handler* security_handler,
665     l2cap::le::L2capLeModule* l2cap_le_module,
666     channel::SecurityManagerChannel* security_manager_channel,
667     hci::HciLayer* hci_layer,
668     hci::AclManager* acl_manager,
669     hci::Controller* controller,
670     storage::StorageModule* storage_module,
671     neighbor::NameDbModule* name_db_module)
672     : security_handler_(security_handler),
673       l2cap_le_module_(l2cap_le_module),
674       l2cap_manager_le_(l2cap_le_module_->GetFixedChannelManager()),
675       hci_security_interface_le_(
676           hci_layer->GetLeSecurityInterface(security_handler_->BindOn(this, &SecurityManagerImpl::OnHciLeEvent))),
677       security_manager_channel_(security_manager_channel),
678       acl_manager_(acl_manager),
679       controller_(controller),
680       storage_module_(storage_module),
681       security_record_storage_(storage_module, security_handler),
682       security_database_(security_record_storage_),
683       name_db_module_(name_db_module) {
684   Init();
685 
686   l2cap_manager_le_->RegisterService(
687       bluetooth::l2cap::kSmpCid,
688       common::BindOnce(&SecurityManagerImpl::OnL2capRegistrationCompleteLe, common::Unretained(this)),
689       common::Bind(&SecurityManagerImpl::OnConnectionOpenLe, common::Unretained(this)), security_handler_);
690 }
691 
OnPairingFinished(security::PairingResultOrFailure pairing_result)692 void SecurityManagerImpl::OnPairingFinished(security::PairingResultOrFailure pairing_result) {
693   LOG_INFO(" ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ Received pairing result");
694 
695   LeFixedChannelEntry* stored_chan = FindStoredLeChannel(pending_le_pairing_.address_);
696   if (stored_chan) {
697     stored_chan->channel_->Release();
698   }
699 
700   if (std::holds_alternative<PairingFailure>(pairing_result)) {
701     PairingFailure failure = std::get<PairingFailure>(pairing_result);
702     LOG_INFO(" ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ failure message: %s",
703              failure.message.c_str());
704     NotifyDeviceBondFailed(stored_chan->channel_->GetDevice(), failure);
705     return;
706   }
707 
708   auto result = std::get<PairingResult>(pairing_result);
709   LOG_INFO("Pairing with %s was successful", result.connection_address.ToString().c_str());
710 
711   // TODO: ensure that the security level is not weaker than what we already have.
712   auto record = this->security_database_.FindOrCreate(result.connection_address);
713   record->identity_address_ = result.distributed_keys.remote_identity_address;
714   record->remote_ltk = result.distributed_keys.remote_ltk;
715   record->key_size = result.key_size;
716   record->security_level = result.security_level;
717   record->remote_ediv = result.distributed_keys.remote_ediv;
718   record->remote_rand = result.distributed_keys.remote_rand;
719   record->remote_irk = result.distributed_keys.remote_irk;
720   record->remote_signature_key = result.distributed_keys.remote_signature_key;
721   if (result.distributed_keys.remote_link_key)
722     record->SetLinkKey(*result.distributed_keys.remote_link_key, hci::KeyType::AUTHENTICATED_P256);
723   security_database_.SaveRecordsToStorage();
724 
725   NotifyDeviceBonded(result.connection_address);
726   // We also notify bond complete using identity address. That's what old stack used to do.
727   if (result.distributed_keys.remote_identity_address)
728     NotifyDeviceBonded(*result.distributed_keys.remote_identity_address);
729 
730   security_handler_->CallOn(this, &SecurityManagerImpl::WipeLePairingHandler);
731 }
732 
WipeLePairingHandler()733 void SecurityManagerImpl::WipeLePairingHandler() {
734   pending_le_pairing_.handler_.reset();
735   pending_le_pairing_.connection_handle_ = 0;
736   pending_le_pairing_.address_ = hci::AddressWithType();
737 }
738 
739 // Facade Configuration API functions
SetDisconnectCallback(FacadeDisconnectCallback callback)740 void SecurityManagerImpl::SetDisconnectCallback(FacadeDisconnectCallback callback) {
741   this->facade_disconnect_callback_ = std::make_optional<FacadeDisconnectCallback>(callback);
742 }
743 
SetIoCapability(hci::IoCapability io_capability)744 void SecurityManagerImpl::SetIoCapability(hci::IoCapability io_capability) {
745   this->local_io_capability_ = io_capability;
746 }
747 
SetLeIoCapability(security::IoCapability io_capability)748 void SecurityManagerImpl::SetLeIoCapability(security::IoCapability io_capability) {
749   this->local_le_io_capability_ = io_capability;
750 }
751 
SetLeAuthRequirements(uint8_t auth_req)752 void SecurityManagerImpl::SetLeAuthRequirements(uint8_t auth_req) {
753   this->local_le_auth_req_ = auth_req;
754 }
755 
SetLeMaximumEncryptionKeySize(uint8_t maximum_encryption_key_size)756 void SecurityManagerImpl::SetLeMaximumEncryptionKeySize(uint8_t maximum_encryption_key_size) {
757   this->local_maximum_encryption_key_size_ = maximum_encryption_key_size;
758 }
759 
SetLeOobDataPresent(OobDataFlag data_present)760 void SecurityManagerImpl::SetLeOobDataPresent(OobDataFlag data_present) {
761   this->local_le_oob_data_present_ = data_present;
762 }
763 
GetOutOfBandData(channel::SecurityCommandStatusCallback callback)764 void SecurityManagerImpl::GetOutOfBandData(channel::SecurityCommandStatusCallback callback) {
765   this->security_manager_channel_->SendCommand(
766       hci::ReadLocalOobDataBuilder::Create(), std::forward<channel::SecurityCommandStatusCallback>(callback));
767 }
768 
GetLeOutOfBandData(std::array<uint8_t,16> * confirmation_value,std::array<uint8_t,16> * random_value)769 void SecurityManagerImpl::GetLeOutOfBandData(
770     std::array<uint8_t, 16>* confirmation_value, std::array<uint8_t, 16>* random_value) {
771   local_le_oob_data_ = std::make_optional<MyOobData>(PairingHandlerLe::GenerateOobData());
772   *confirmation_value = local_le_oob_data_.value().c;
773   *random_value = local_le_oob_data_.value().r;
774 }
775 
SetOutOfBandData(hci::AddressWithType remote_address,std::array<uint8_t,16> confirmation_value,std::array<uint8_t,16> random_value)776 void SecurityManagerImpl::SetOutOfBandData(
777     hci::AddressWithType remote_address,
778     std::array<uint8_t, 16> confirmation_value,
779     std::array<uint8_t, 16> random_value) {
780   remote_oob_data_address_ = remote_address;
781   remote_oob_data_le_sc_c_ = confirmation_value;
782   remote_oob_data_le_sc_r_ = random_value;
783 }
784 
SetAuthenticationRequirements(hci::AuthenticationRequirements authentication_requirements)785 void SecurityManagerImpl::SetAuthenticationRequirements(hci::AuthenticationRequirements authentication_requirements) {
786   this->local_authentication_requirements_ = authentication_requirements;
787 }
788 
InternalEnforceSecurityPolicy(hci::AddressWithType remote,l2cap::classic::SecurityPolicy policy,l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback)789 void SecurityManagerImpl::InternalEnforceSecurityPolicy(
790     hci::AddressWithType remote,
791     l2cap::classic::SecurityPolicy policy,
792     l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback) {
793   if (IsSecurityRequirementSatisfied(remote, policy)) {
794     // Notify client immediately if already satisfied
795     std::move(result_callback).Invoke(true);
796     return;
797   }
798 
799   // At this point we don't meet the security requirements; must pair
800   auto record = this->security_database_.FindOrCreate(remote);
801   hci::AuthenticationRequirements authentication_requirements = kDefaultAuthenticationRequirements;
802   enforce_security_policy_callback_map_[remote] = {policy, std::move(result_callback)};
803 
804   switch (policy) {
805     case l2cap::classic::SecurityPolicy::BEST:
806     case l2cap::classic::SecurityPolicy::AUTHENTICATED_ENCRYPTED_TRANSPORT:
807       // Force MITM requirement locally
808       authentication_requirements = hci::AuthenticationRequirements::GENERAL_BONDING_MITM_PROTECTION;
809       break;
810     case l2cap::classic::SecurityPolicy::ENCRYPTED_TRANSPORT:
811       authentication_requirements = hci::AuthenticationRequirements::GENERAL_BONDING;
812       break;
813     default:
814       // I could hear the voice of Myles, "This should be an ASSERT!"
815       ASSERT_LOG(false, "Unreachable code path");
816       return;
817   }
818 
819   LOG_WARN("Dispatch #3");
820   DispatchPairingHandler(
821       record,
822       true,
823       this->local_io_capability_,
824       std::as_const(authentication_requirements),
825       pairing::OobData(),
826       pairing::OobData());
827 }
828 
UpdateLinkSecurityCondition(hci::AddressWithType remote)829 void SecurityManagerImpl::UpdateLinkSecurityCondition(hci::AddressWithType remote) {
830   auto entry = enforce_security_policy_callback_map_.find(remote);
831   if (entry == enforce_security_policy_callback_map_.end()) {
832     LOG_ERROR("No L2CAP security policy callback pending for %s", remote.ToString().c_str());
833     return;
834   }
835   std::move(entry->second.callback_).Invoke(IsSecurityRequirementSatisfied(remote, entry->second.policy_));
836   enforce_security_policy_callback_map_.erase(entry);
837 }
838 
IsSecurityRequirementSatisfied(hci::AddressWithType remote,l2cap::classic::SecurityPolicy policy)839 bool SecurityManagerImpl::IsSecurityRequirementSatisfied(
840     hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy) {
841   auto record = security_database_.FindOrCreate(remote);
842   switch (policy) {
843     case l2cap::classic::SecurityPolicy::BEST:
844     case l2cap::classic::SecurityPolicy::AUTHENTICATED_ENCRYPTED_TRANSPORT:
845       return (record->IsPaired() && record->IsAuthenticated());
846     case l2cap::classic::SecurityPolicy::ENCRYPTED_TRANSPORT:
847       return record->IsPaired();
848     default:
849       return true;
850   }
851 }
852 
EnforceSecurityPolicy(hci::AddressWithType remote,l2cap::classic::SecurityPolicy policy,l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback)853 void SecurityManagerImpl::EnforceSecurityPolicy(
854     hci::AddressWithType remote,
855     l2cap::classic::SecurityPolicy policy,
856     l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback) {
857   LOG_INFO("Attempting to enforce security policy");
858   auto record = security_database_.FindOrCreate(remote);
859   if (!record->IsPairing()) {
860     this->InternalEnforceSecurityPolicy(remote, policy, std::move(result_callback));
861   }
862 }
863 
EnforceLeSecurityPolicy(hci::AddressWithType remote,l2cap::le::SecurityPolicy policy,l2cap::le::SecurityEnforcementInterface::ResultCallback result_callback)864 void SecurityManagerImpl::EnforceLeSecurityPolicy(
865     hci::AddressWithType remote, l2cap::le::SecurityPolicy policy,
866     l2cap::le::SecurityEnforcementInterface::ResultCallback result_callback) {
867   bool result = false;
868   // TODO(jpawlowski): Implement for LE
869   switch (policy) {
870     case l2cap::le::SecurityPolicy::BEST:
871       break;
872     case l2cap::le::SecurityPolicy::AUTHENTICATED_ENCRYPTED_TRANSPORT:
873       break;
874     case l2cap::le::SecurityPolicy::ENCRYPTED_TRANSPORT:
875       break;
876     case l2cap::le::SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK:
877       result = true;
878       break;
879     case l2cap::le::SecurityPolicy::_NOT_FOR_YOU__AUTHENTICATED_PAIRING_WITH_128_BIT_KEY:
880       break;
881     case l2cap::le::SecurityPolicy::_NOT_FOR_YOU__AUTHORIZATION:
882       break;
883   }
884   result_callback.Invoke(result);
885 }
886 }  // namespace internal
887 }  // namespace security
888 }  // namespace bluetooth
889