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 "security/initial_informations.h"
27 #include "security/internal/security_manager_impl.h"
28 #include "security/pairing_handler_le.h"
29 #include "security/security_manager.h"
30 #include "security/ui.h"
31 
32 namespace bluetooth {
33 namespace security {
34 namespace internal {
35 
DispatchPairingHandler(std::shared_ptr<record::SecurityRecord> record,bool locally_initiated)36 void SecurityManagerImpl::DispatchPairingHandler(
37     std::shared_ptr<record::SecurityRecord> record, bool locally_initiated) {
38   common::OnceCallback<void(hci::Address, PairingResultOrFailure)> callback =
39       common::BindOnce(&SecurityManagerImpl::OnPairingHandlerComplete, common::Unretained(this));
40   auto entry = pairing_handler_map_.find(record->GetPseudoAddress().GetAddress());
41   if (entry != pairing_handler_map_.end()) {
42     LOG_WARN("Device already has a pairing handler, and is in the middle of pairing!");
43     return;
44   }
45   std::shared_ptr<pairing::PairingHandler> pairing_handler = nullptr;
46   switch (record->GetPseudoAddress().GetAddressType()) {
47     case hci::AddressType::PUBLIC_DEVICE_ADDRESS: {
48       pairing_handler = std::make_shared<security::pairing::ClassicPairingHandler>(
49           security_manager_channel_,
50           record,
51           security_handler_,
52           std::move(callback),
53           user_interface_,
54           user_interface_handler_,
55           "TODO: grab device name properly");
56       break;
57     }
58     default:
59       ASSERT_LOG(false, "Pairing type %hhu not implemented!", record->GetPseudoAddress().GetAddressType());
60   }
61   auto new_entry = std::pair<hci::Address, std::shared_ptr<pairing::PairingHandler>>(
62       record->GetPseudoAddress().GetAddress(), pairing_handler);
63   pairing_handler_map_.insert(std::move(new_entry));
64   pairing_handler->Initiate(locally_initiated, this->local_io_capability_, this->local_oob_data_present_,
65                             this->local_authentication_requirements_);
66 }
67 
Init()68 void SecurityManagerImpl::Init() {
69   security_manager_channel_->SetChannelListener(this);
70   security_manager_channel_->SendCommand(hci::WriteSimplePairingModeBuilder::Create(hci::Enable::ENABLED));
71   security_manager_channel_->SendCommand(hci::WriteSecureConnectionsHostSupportBuilder::Create(hci::Enable::ENABLED));
72   ASSERT_LOG(storage_module_ != nullptr, "Storage module must not be null!");
73   // TODO(optedoblivion): Populate security record memory map from disk
74 
75   // TODO(b/161543441): read the privacy policy from device-specific configuration, and IRK from config file.
76   hci::LeAddressManager::AddressPolicy address_policy = hci::LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS;
77   hci::AddressWithType address_with_type(hci::Address{}, hci::AddressType::RANDOM_DEVICE_ADDRESS);
78   crypto_toolbox::Octet16 irk = {
79       0x44, 0xfb, 0x4b, 0x8d, 0x6c, 0x58, 0x21, 0x0c, 0xf9, 0x3d, 0xda, 0xf1, 0x64, 0xa3, 0xbb, 0x7f};
80   /* 7 minutes minimum, 15 minutes maximum for random address refreshing */
81   auto minimum_rotation_time = std::chrono::minutes(7);
82   auto maximum_rotation_time = std::chrono::minutes(15);
83 
84   acl_manager_->SetPrivacyPolicyForInitiatorAddress(
85       address_policy, address_with_type, irk, minimum_rotation_time, maximum_rotation_time);
86 }
87 
CreateBond(hci::AddressWithType device)88 void SecurityManagerImpl::CreateBond(hci::AddressWithType device) {
89   auto record = security_database_.FindOrCreate(device);
90   if (record->IsPaired()) {
91     // Bonded means we saved it, but the caller doesn't care
92     // Bonded will always mean paired
93     NotifyDeviceBonded(device);
94   } else {
95     if (!record->IsPairing()) {
96       // Dispatch pairing handler, if we are calling create we are the initiator
97       LOG_WARN("Dispatch #1");
98       DispatchPairingHandler(record, true);
99     }
100   }
101 }
102 
CreateBondLe(hci::AddressWithType address)103 void SecurityManagerImpl::CreateBondLe(hci::AddressWithType address) {
104   auto record = security_database_.FindOrCreate(address);
105   if (record->IsBonded()) {
106     NotifyDeviceBondFailed(address, PairingFailure("Already bonded"));
107     return;
108   }
109 
110   pending_le_pairing_.address_ = address;
111 
112   LeFixedChannelEntry* stored_chan = FindStoredLeChannel(address);
113   if (stored_chan) {
114     // We are already connected
115     ConnectionIsReadyStartPairing(stored_chan);
116     return;
117   }
118 
119   l2cap_manager_le_->ConnectServices(
120       address, common::BindOnce(&SecurityManagerImpl::OnConnectionFailureLe, common::Unretained(this)),
121       security_handler_);
122 }
123 
CancelBond(hci::AddressWithType device)124 void SecurityManagerImpl::CancelBond(hci::AddressWithType device) {
125   auto entry = pairing_handler_map_.find(device.GetAddress());
126   if (entry != pairing_handler_map_.end()) {
127     auto cancel_me = entry->second;
128     pairing_handler_map_.erase(entry);
129     cancel_me->Cancel();
130   }
131 
132   auto record = security_database_.FindOrCreate(device);
133   record->CancelPairing();
134 
135   WipeLePairingHandler();
136 }
137 
RemoveBond(hci::AddressWithType device)138 void SecurityManagerImpl::RemoveBond(hci::AddressWithType device) {
139   CancelBond(device);
140   security_database_.Remove(device);
141   security_manager_channel_->Disconnect(device.GetAddress());
142   // Signal disconnect
143   // Remove security record
144   // Signal Remove from database
145 
146   NotifyDeviceUnbonded(device);
147 }
148 
SetUserInterfaceHandler(UI * user_interface,os::Handler * handler)149 void SecurityManagerImpl::SetUserInterfaceHandler(UI* user_interface, os::Handler* handler) {
150   if (user_interface_ != nullptr || user_interface_handler_ != nullptr) {
151     LOG_ALWAYS_FATAL("Listener has already been registered!");
152   }
153   user_interface_ = user_interface;
154   user_interface_handler_ = handler;
155 }
156 
157 // 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)158 void SecurityManagerImpl::SetLeInitiatorAddressPolicyForTest(
159     hci::LeAddressManager::AddressPolicy address_policy,
160     hci::AddressWithType fixed_address,
161     crypto_toolbox::Octet16 rotation_irk,
162     std::chrono::milliseconds minimum_rotation_time,
163     std::chrono::milliseconds maximum_rotation_time) {
164   acl_manager_->SetPrivacyPolicyForInitiatorAddressForTest(
165       address_policy, fixed_address, rotation_irk, minimum_rotation_time, maximum_rotation_time);
166 }
167 
RegisterCallbackListener(ISecurityManagerListener * listener,os::Handler * handler)168 void SecurityManagerImpl::RegisterCallbackListener(ISecurityManagerListener* listener, os::Handler* handler) {
169   for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
170     if (it->first == listener) {
171       LOG_ALWAYS_FATAL("Listener has already been registered!");
172     }
173   }
174 
175   listeners_.push_back({listener, handler});
176 }
177 
UnregisterCallbackListener(ISecurityManagerListener * listener)178 void SecurityManagerImpl::UnregisterCallbackListener(ISecurityManagerListener* listener) {
179   for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
180     if (it->first == listener) {
181       listeners_.erase(it);
182       return;
183     }
184   }
185 
186   LOG_ALWAYS_FATAL("Listener has not been registered!");
187 }
188 
NotifyDeviceBonded(hci::AddressWithType device)189 void SecurityManagerImpl::NotifyDeviceBonded(hci::AddressWithType device) {
190   for (auto& iter : listeners_) {
191     iter.second->Post(common::Bind(&ISecurityManagerListener::OnDeviceBonded, common::Unretained(iter.first), device));
192   }
193 }
194 
NotifyDeviceBondFailed(hci::AddressWithType device,PairingResultOrFailure status)195 void SecurityManagerImpl::NotifyDeviceBondFailed(hci::AddressWithType device, PairingResultOrFailure status) {
196   for (auto& iter : listeners_) {
197     iter.second->Post(common::Bind(&ISecurityManagerListener::OnDeviceBondFailed, common::Unretained(iter.first),
198                                    device /*, status */));
199   }
200 }
201 
NotifyDeviceUnbonded(hci::AddressWithType device)202 void SecurityManagerImpl::NotifyDeviceUnbonded(hci::AddressWithType device) {
203   for (auto& iter : listeners_) {
204     iter.second->Post(
205         common::Bind(&ISecurityManagerListener::OnDeviceUnbonded, common::Unretained(iter.first), device));
206   }
207   acl_manager_->RemoveDeviceFromConnectList(device);
208 }
209 
NotifyEncryptionStateChanged(hci::EncryptionChangeView encryption_change_view)210 void SecurityManagerImpl::NotifyEncryptionStateChanged(hci::EncryptionChangeView encryption_change_view) {
211   for (auto& iter : listeners_) {
212     iter.second->Post(common::Bind(&ISecurityManagerListener::OnEncryptionStateChanged, common::Unretained(iter.first),
213                                    encryption_change_view));
214   }
215 }
216 
217 template <class T>
HandleEvent(T packet)218 void SecurityManagerImpl::HandleEvent(T packet) {
219   ASSERT(packet.IsValid());
220   auto entry = pairing_handler_map_.find(packet.GetBdAddr());
221 
222   if (entry == pairing_handler_map_.end()) {
223     auto bd_addr = packet.GetBdAddr();
224     auto event_code = packet.GetEventCode();
225 
226     if (event_code != hci::EventCode::LINK_KEY_REQUEST) {
227       LOG_ERROR("No classic pairing handler for device '%s' ready for command %s ", bd_addr.ToString().c_str(),
228                 hci::EventCodeText(event_code).c_str());
229       return;
230     }
231 
232     auto record =
233         security_database_.FindOrCreate(hci::AddressWithType{bd_addr, hci::AddressType::PUBLIC_DEVICE_ADDRESS});
234     LOG_WARN("Dispatch #2");
235     DispatchPairingHandler(record, true);
236     entry = pairing_handler_map_.find(bd_addr);
237   }
238   entry->second->OnReceive(packet);
239 }
240 
OnHciEventReceived(hci::EventPacketView packet)241 void SecurityManagerImpl::OnHciEventReceived(hci::EventPacketView packet) {
242   auto event = hci::EventPacketView::Create(packet);
243   ASSERT_LOG(event.IsValid(), "Received invalid packet");
244   const hci::EventCode code = event.GetEventCode();
245   switch (code) {
246     case hci::EventCode::PIN_CODE_REQUEST:
247       HandleEvent<hci::PinCodeRequestView>(hci::PinCodeRequestView::Create(event));
248       break;
249     case hci::EventCode::LINK_KEY_REQUEST:
250       HandleEvent(hci::LinkKeyRequestView::Create(event));
251       break;
252     case hci::EventCode::LINK_KEY_NOTIFICATION:
253       HandleEvent(hci::LinkKeyNotificationView::Create(event));
254       break;
255     case hci::EventCode::IO_CAPABILITY_REQUEST:
256       HandleEvent(hci::IoCapabilityRequestView::Create(event));
257       break;
258     case hci::EventCode::IO_CAPABILITY_RESPONSE:
259       HandleEvent(hci::IoCapabilityResponseView::Create(event));
260       break;
261     case hci::EventCode::SIMPLE_PAIRING_COMPLETE:
262       HandleEvent(hci::SimplePairingCompleteView::Create(event));
263       break;
264     case hci::EventCode::REMOTE_OOB_DATA_REQUEST:
265       HandleEvent(hci::RemoteOobDataRequestView::Create(event));
266       break;
267     case hci::EventCode::USER_PASSKEY_NOTIFICATION:
268       HandleEvent(hci::UserPasskeyNotificationView::Create(event));
269       break;
270     case hci::EventCode::KEYPRESS_NOTIFICATION:
271       HandleEvent(hci::KeypressNotificationView::Create(event));
272       break;
273     case hci::EventCode::USER_CONFIRMATION_REQUEST:
274       HandleEvent(hci::UserConfirmationRequestView::Create(event));
275       break;
276     case hci::EventCode::USER_PASSKEY_REQUEST:
277       HandleEvent(hci::UserPasskeyRequestView::Create(event));
278       break;
279     case hci::EventCode::REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION:
280       LOG_INFO("Unhandled event: %s", hci::EventCodeText(code).c_str());
281       break;
282 
283     case hci::EventCode::ENCRYPTION_CHANGE: {
284       EncryptionChangeView encryption_change_view = EncryptionChangeView::Create(event);
285       if (!encryption_change_view.IsValid()) {
286         LOG_ERROR("Invalid EncryptionChange packet received");
287         return;
288       }
289       if (encryption_change_view.GetConnectionHandle() == pending_le_pairing_.connection_handle_) {
290         pending_le_pairing_.handler_->OnHciEvent(event);
291         return;
292       }
293       NotifyEncryptionStateChanged(encryption_change_view);
294       break;
295     }
296 
297     default:
298       ASSERT_LOG(false, "Cannot handle received packet: %s", hci::EventCodeText(code).c_str());
299       break;
300   }
301 }
302 
OnConnectionClosed(hci::Address address)303 void SecurityManagerImpl::OnConnectionClosed(hci::Address address) {
304   auto entry = pairing_handler_map_.find(address);
305   if (entry != pairing_handler_map_.end()) {
306     LOG_DEBUG("Cancelling pairing handler for '%s'", address.ToString().c_str());
307     entry->second->Cancel();
308   }
309 }
310 
OnHciLeEvent(hci::LeMetaEventView event)311 void SecurityManagerImpl::OnHciLeEvent(hci::LeMetaEventView event) {
312   // hci::SubeventCode::LONG_TERM_KEY_REQUEST,
313   // hci::SubeventCode::READ_LOCAL_P256_PUBLIC_KEY_COMPLETE,
314   // hci::SubeventCode::GENERATE_DHKEY_COMPLETE,
315   LOG_ERROR("Unhandled HCI LE security event");
316 }
317 
OnPairingPromptAccepted(const bluetooth::hci::AddressWithType & address,bool confirmed)318 void SecurityManagerImpl::OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, bool confirmed) {
319   auto entry = pairing_handler_map_.find(address.GetAddress());
320   if (entry != pairing_handler_map_.end()) {
321     entry->second->OnPairingPromptAccepted(address, confirmed);
322   } else {
323     if (pending_le_pairing_.address_ == address) {
324       pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::PAIRING_ACCEPTED, confirmed);
325     }
326   }
327 }
328 
OnConfirmYesNo(const bluetooth::hci::AddressWithType & address,bool confirmed)329 void SecurityManagerImpl::OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, bool confirmed) {
330   auto entry = pairing_handler_map_.find(address.GetAddress());
331   if (entry != pairing_handler_map_.end()) {
332     entry->second->OnConfirmYesNo(address, confirmed);
333   } else {
334     if (pending_le_pairing_.address_ == address) {
335       pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::CONFIRM_YESNO, confirmed);
336     }
337   }
338 }
339 
OnPasskeyEntry(const bluetooth::hci::AddressWithType & address,uint32_t passkey)340 void SecurityManagerImpl::OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, uint32_t passkey) {
341   auto entry = pairing_handler_map_.find(address.GetAddress());
342   if (entry != pairing_handler_map_.end()) {
343     entry->second->OnPasskeyEntry(address, passkey);
344   } else {
345     if (pending_le_pairing_.address_ == address) {
346       pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::PASSKEY, passkey);
347     }
348   }
349 }
350 
OnPairingHandlerComplete(hci::Address address,PairingResultOrFailure status)351 void SecurityManagerImpl::OnPairingHandlerComplete(hci::Address address, PairingResultOrFailure status) {
352   auto entry = pairing_handler_map_.find(address);
353   if (entry != pairing_handler_map_.end()) {
354     pairing_handler_map_.erase(entry);
355     security_manager_channel_->Release(address);
356   }
357   auto remote = hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS);
358   auto cb_entry = enforce_security_policy_callback_map_.find(remote);
359   if (cb_entry != enforce_security_policy_callback_map_.end()) {
360     this->InternalEnforceSecurityPolicy(remote, cb_entry->second.first, std::move(cb_entry->second.second), false);
361     enforce_security_policy_callback_map_.erase(cb_entry);
362   }
363   if (!std::holds_alternative<PairingFailure>(status)) {
364     NotifyDeviceBonded(remote);
365   } else {
366     NotifyDeviceBondFailed(remote, status);
367   }
368   auto record = this->security_database_.FindOrCreate(remote);
369   record->CancelPairing();
370 }
371 
OnL2capRegistrationCompleteLe(l2cap::le::FixedChannelManager::RegistrationResult result,std::unique_ptr<l2cap::le::FixedChannelService> le_smp_service)372 void SecurityManagerImpl::OnL2capRegistrationCompleteLe(
373     l2cap::le::FixedChannelManager::RegistrationResult result,
374     std::unique_ptr<l2cap::le::FixedChannelService> le_smp_service) {
375   ASSERT_LOG(result == bluetooth::l2cap::le::FixedChannelManager::RegistrationResult::SUCCESS,
376              "Failed to register to LE SMP Fixed Channel Service");
377 }
378 
FindStoredLeChannel(const hci::AddressWithType & device)379 LeFixedChannelEntry* SecurityManagerImpl::FindStoredLeChannel(const hci::AddressWithType& device) {
380   for (LeFixedChannelEntry& storage : all_channels_) {
381     if (storage.channel_->GetDevice() == device) {
382       return &storage;
383     }
384   }
385   return nullptr;
386 }
387 
EraseStoredLeChannel(const hci::AddressWithType & device)388 bool SecurityManagerImpl::EraseStoredLeChannel(const hci::AddressWithType& device) {
389   for (auto it = all_channels_.begin(); it != all_channels_.end(); it++) {
390     if (it->channel_->GetDevice() == device) {
391       all_channels_.erase(it);
392       return true;
393     }
394   }
395   return false;
396 }
397 
OnSmpCommandLe(hci::AddressWithType device)398 void SecurityManagerImpl::OnSmpCommandLe(hci::AddressWithType device) {
399   LeFixedChannelEntry* stored_chan = FindStoredLeChannel(device);
400   if (!stored_chan) {
401     LOG_ALWAYS_FATAL("Received SMP command for unknown channel");
402     return;
403   }
404 
405   std::unique_ptr<l2cap::le::FixedChannel>& channel = stored_chan->channel_;
406 
407   auto packet = channel->GetQueueUpEnd()->TryDequeue();
408   if (!packet) {
409     LOG_ERROR("Received dequeue, but no data ready...");
410     return;
411   }
412 
413   // Pending pairing - pass the data to the handler
414   auto temp_cmd_view = CommandView::Create(*packet);
415   if (pending_le_pairing_.address_ == device) {
416     pending_le_pairing_.handler_->OnCommandView(temp_cmd_view);
417     return;
418   }
419 
420   // no pending pairing attempt
421   if (!temp_cmd_view.IsValid()) {
422     LOG_ERROR("Invalid Command packet");
423     return;
424   }
425 
426   if (temp_cmd_view.GetCode() == Code::SECURITY_REQUEST) {
427     // TODO: either start encryption or pairing
428     LOG_WARN("Unhandled security request!!!");
429     return;
430   }
431 
432   auto my_role = channel->GetLinkOptions()->GetRole();
433   if (temp_cmd_view.GetCode() == Code::PAIRING_REQUEST && my_role == hci::Role::SLAVE) {
434     // TODO: if (pending_le_pairing_) { do not start another }
435 
436     LOG_INFO("start of security request handling!");
437 
438     stored_chan->channel_->Acquire();
439 
440     PairingRequestView pairing_request = PairingRequestView::Create(temp_cmd_view);
441     auto& enqueue_buffer = stored_chan->enqueue_buffer_;
442 
443     std::optional<InitialInformations::out_of_band_data> remote_oob_data = std::nullopt;
444     if (remote_oob_data_address_.has_value() && remote_oob_data_address_.value() == channel->GetDevice())
445       remote_oob_data = InitialInformations::out_of_band_data{.le_sc_c = remote_oob_data_le_sc_c_.value(),
446                                                               .le_sc_r = remote_oob_data_le_sc_r_.value()};
447 
448     // 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
449     // stored
450     pending_le_pairing_.connection_handle_ = channel->GetLinkOptions()->GetHandle();
451     InitialInformations initial_informations{
452         .my_role = my_role,
453         .my_connection_address = channel->GetLinkOptions()->GetLocalAddress(),
454         /*TODO: properly obtain capabilities from device-specific storage*/
455         .myPairingCapabilities = {.io_capability = local_le_io_capability_,
456                                   .oob_data_flag = local_le_oob_data_present_,
457                                   .auth_req = local_le_auth_req_,
458                                   .maximum_encryption_key_size = 16,
459                                   .initiator_key_distribution = 0x07,
460                                   .responder_key_distribution = 0x07},
461         .remotely_initiated = true,
462         .connection_handle = channel->GetLinkOptions()->GetHandle(),
463         .remote_connection_address = channel->GetDevice(),
464         .remote_name = "TODO: grab proper device name in sec mgr",
465         /* contains pairing request, if the pairing was remotely initiated */
466         .pairing_request = pairing_request,
467         .remote_oob_data = remote_oob_data,
468         .my_oob_data = local_le_oob_data_,
469         /* Used by Pairing Handler to present user with requests*/
470         .user_interface = user_interface_,
471         .user_interface_handler = user_interface_handler_,
472 
473         /* HCI interface to use */
474         .le_security_interface = hci_security_interface_le_,
475         .proper_l2cap_interface = enqueue_buffer.get(),
476         .l2cap_handler = security_handler_,
477         /* Callback to execute once the Pairing process is finished */
478         // TODO: make it an common::OnceCallback ?
479         .OnPairingFinished = std::bind(&SecurityManagerImpl::OnPairingFinished, this, std::placeholders::_1),
480     };
481     pending_le_pairing_.address_ = device;
482     pending_le_pairing_.handler_ = std::make_unique<PairingHandlerLe>(PairingHandlerLe::PHASE1, initial_informations);
483   }
484 }
485 
OnConnectionOpenLe(std::unique_ptr<l2cap::le::FixedChannel> channel_param)486 void SecurityManagerImpl::OnConnectionOpenLe(std::unique_ptr<l2cap::le::FixedChannel> channel_param) {
487   auto enqueue_buffer_temp =
488       std::make_unique<os::EnqueueBuffer<packet::BasePacketBuilder>>(channel_param->GetQueueUpEnd());
489 
490   all_channels_.push_back({std::move(channel_param), std::move(enqueue_buffer_temp)});
491   auto& stored_channel = all_channels_.back();
492   auto& channel = stored_channel.channel_;
493 
494   channel->RegisterOnCloseCallback(
495       security_handler_,
496       common::BindOnce(&SecurityManagerImpl::OnConnectionClosedLe, common::Unretained(this), channel->GetDevice()));
497   channel->GetQueueUpEnd()->RegisterDequeue(
498       security_handler_,
499       common::Bind(&SecurityManagerImpl::OnSmpCommandLe, common::Unretained(this), channel->GetDevice()));
500 
501   if (pending_le_pairing_.address_ != channel->GetDevice()) {
502     return;
503   }
504 
505   ConnectionIsReadyStartPairing(&stored_channel);
506 }
507 
ConnectionIsReadyStartPairing(LeFixedChannelEntry * stored_channel)508 void SecurityManagerImpl::ConnectionIsReadyStartPairing(LeFixedChannelEntry* stored_channel) {
509   auto& channel = stored_channel->channel_;
510   auto& enqueue_buffer = stored_channel->enqueue_buffer_;
511 
512   stored_channel->channel_->Acquire();
513 
514   std::optional<InitialInformations::out_of_band_data> remote_oob_data = std::nullopt;
515   if (remote_oob_data_address_.has_value() && remote_oob_data_address_.value() == channel->GetDevice())
516     remote_oob_data = InitialInformations::out_of_band_data{.le_sc_c = remote_oob_data_le_sc_c_.value(),
517                                                             .le_sc_r = remote_oob_data_le_sc_r_.value()};
518 
519   // 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
520   pending_le_pairing_.connection_handle_ = channel->GetLinkOptions()->GetHandle();
521   InitialInformations initial_informations{
522       .my_role = channel->GetLinkOptions()->GetRole(),
523       .my_connection_address = channel->GetLinkOptions()->GetLocalAddress(),
524       /*TODO: properly obtain capabilities from device-specific storage*/
525       .myPairingCapabilities = {.io_capability = local_le_io_capability_,
526                                 .oob_data_flag = local_le_oob_data_present_,
527                                 .auth_req = local_le_auth_req_,
528                                 .maximum_encryption_key_size = 16,
529                                 .initiator_key_distribution = 0x07,
530                                 .responder_key_distribution = 0x07},
531       .remotely_initiated = false,
532       .connection_handle = channel->GetLinkOptions()->GetHandle(),
533       .remote_connection_address = channel->GetDevice(),
534       .remote_name = "TODO: grab proper device name in sec mgr",
535       /* contains pairing request, if the pairing was remotely initiated */
536       .pairing_request = std::nullopt,  // TODO: handle remotely initiated pairing in SecurityManager properly
537       .remote_oob_data = remote_oob_data,
538       .my_oob_data = local_le_oob_data_,
539       /* Used by Pairing Handler to present user with requests*/
540       .user_interface = user_interface_,
541       .user_interface_handler = user_interface_handler_,
542 
543       /* HCI interface to use */
544       .le_security_interface = hci_security_interface_le_,
545       .proper_l2cap_interface = enqueue_buffer.get(),
546       .l2cap_handler = security_handler_,
547       /* Callback to execute once the Pairing process is finished */
548       // TODO: make it an common::OnceCallback ?
549       .OnPairingFinished = std::bind(&SecurityManagerImpl::OnPairingFinished, this, std::placeholders::_1),
550   };
551   pending_le_pairing_.handler_ = std::make_unique<PairingHandlerLe>(PairingHandlerLe::PHASE1, initial_informations);
552 }
553 
OnConnectionClosedLe(hci::AddressWithType address,hci::ErrorCode error_code)554 void SecurityManagerImpl::OnConnectionClosedLe(hci::AddressWithType address, hci::ErrorCode error_code) {
555   if (pending_le_pairing_.address_ != address) {
556     LeFixedChannelEntry* stored_chan = FindStoredLeChannel(address);
557     if (!stored_chan) {
558       LOG_ALWAYS_FATAL("Received connection closed for unknown channel");
559       return;
560     }
561     stored_chan->channel_->GetQueueUpEnd()->UnregisterDequeue();
562     stored_chan->enqueue_buffer_.reset();
563     EraseStoredLeChannel(address);
564     return;
565   }
566   pending_le_pairing_.handler_->SendExitSignal();
567   NotifyDeviceBondFailed(address, PairingFailure("Connection closed"));
568 }
569 
OnConnectionFailureLe(bluetooth::l2cap::le::FixedChannelManager::ConnectionResult result)570 void SecurityManagerImpl::OnConnectionFailureLe(bluetooth::l2cap::le::FixedChannelManager::ConnectionResult result) {
571   if (result.connection_result_code ==
572       bluetooth::l2cap::le::FixedChannelManager::ConnectionResultCode::FAIL_ALL_SERVICES_HAVE_CHANNEL) {
573     // TODO: already connected
574   }
575 
576   // This callback is invoked only for devices we attempted to connect to.
577   NotifyDeviceBondFailed(pending_le_pairing_.address_, PairingFailure("Connection establishment failed"));
578 }
579 
SecurityManagerImpl(os::Handler * security_handler,l2cap::le::L2capLeModule * l2cap_le_module,channel::SecurityManagerChannel * security_manager_channel,hci::HciLayer * hci_layer,hci::AclManager * acl_manager,storage::StorageModule * storage_module)580 SecurityManagerImpl::SecurityManagerImpl(
581     os::Handler* security_handler,
582     l2cap::le::L2capLeModule* l2cap_le_module,
583     channel::SecurityManagerChannel* security_manager_channel,
584     hci::HciLayer* hci_layer,
585     hci::AclManager* acl_manager,
586     storage::StorageModule* storage_module)
587     : security_handler_(security_handler),
588       l2cap_le_module_(l2cap_le_module),
589       l2cap_manager_le_(l2cap_le_module_->GetFixedChannelManager()),
590       hci_security_interface_le_(
591           hci_layer->GetLeSecurityInterface(security_handler_->BindOn(this, &SecurityManagerImpl::OnHciLeEvent))),
592       security_manager_channel_(security_manager_channel),
593       acl_manager_(acl_manager),
594       storage_module_(storage_module) {
595   Init();
596 
597   l2cap_manager_le_->RegisterService(
598       bluetooth::l2cap::kSmpCid,
599       common::BindOnce(&SecurityManagerImpl::OnL2capRegistrationCompleteLe, common::Unretained(this)),
600       common::Bind(&SecurityManagerImpl::OnConnectionOpenLe, common::Unretained(this)), security_handler_);
601 }
602 
OnPairingFinished(security::PairingResultOrFailure pairing_result)603 void SecurityManagerImpl::OnPairingFinished(security::PairingResultOrFailure pairing_result) {
604   LOG_INFO(" ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ Received pairing result");
605 
606   LeFixedChannelEntry* stored_chan = FindStoredLeChannel(pending_le_pairing_.address_);
607   if (stored_chan) {
608     stored_chan->channel_->Release();
609   }
610 
611   if (std::holds_alternative<PairingFailure>(pairing_result)) {
612     PairingFailure failure = std::get<PairingFailure>(pairing_result);
613     LOG_INFO(" ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ failure message: %s",
614              failure.message.c_str());
615     return;
616   }
617 
618   auto result = std::get<PairingResult>(pairing_result);
619   LOG_INFO("Pairing with %s was successful", result.connection_address.ToString().c_str());
620   NotifyDeviceBonded(result.connection_address);
621 
622   security_handler_->CallOn(this, &SecurityManagerImpl::WipeLePairingHandler);
623 }
624 
WipeLePairingHandler()625 void SecurityManagerImpl::WipeLePairingHandler() {
626   pending_le_pairing_.handler_.reset();
627   pending_le_pairing_.connection_handle_ = 0;
628   pending_le_pairing_.address_ = hci::AddressWithType();
629 }
630 
631 // Facade Configuration API functions
SetIoCapability(hci::IoCapability io_capability)632 void SecurityManagerImpl::SetIoCapability(hci::IoCapability io_capability) {
633   this->local_io_capability_ = io_capability;
634 }
635 
SetLeIoCapability(security::IoCapability io_capability)636 void SecurityManagerImpl::SetLeIoCapability(security::IoCapability io_capability) {
637   this->local_le_io_capability_ = io_capability;
638 }
639 
SetLeAuthRequirements(uint8_t auth_req)640 void SecurityManagerImpl::SetLeAuthRequirements(uint8_t auth_req) {
641   this->local_le_auth_req_ = auth_req;
642 }
643 
SetLeOobDataPresent(OobDataFlag data_present)644 void SecurityManagerImpl::SetLeOobDataPresent(OobDataFlag data_present) {
645   this->local_le_oob_data_present_ = data_present;
646 }
647 
GetOutOfBandData(std::array<uint8_t,16> * le_sc_confirmation_value,std::array<uint8_t,16> * le_sc_random_value)648 void SecurityManagerImpl::GetOutOfBandData(
649     std::array<uint8_t, 16>* le_sc_confirmation_value, std::array<uint8_t, 16>* le_sc_random_value) {
650   local_le_oob_data_ = std::make_optional<MyOobData>(PairingHandlerLe::GenerateOobData());
651   *le_sc_confirmation_value = local_le_oob_data_.value().c;
652   *le_sc_random_value = local_le_oob_data_.value().r;
653 }
654 
SetOutOfBandData(hci::AddressWithType remote_address,std::array<uint8_t,16> le_sc_confirmation_value,std::array<uint8_t,16> le_sc_random_value)655 void SecurityManagerImpl::SetOutOfBandData(
656     hci::AddressWithType remote_address,
657     std::array<uint8_t, 16> le_sc_confirmation_value,
658     std::array<uint8_t, 16> le_sc_random_value) {
659   remote_oob_data_address_ = remote_address;
660   remote_oob_data_le_sc_c_ = le_sc_confirmation_value;
661   remote_oob_data_le_sc_r_ = le_sc_random_value;
662 }
663 
SetAuthenticationRequirements(hci::AuthenticationRequirements authentication_requirements)664 void SecurityManagerImpl::SetAuthenticationRequirements(hci::AuthenticationRequirements authentication_requirements) {
665   this->local_authentication_requirements_ = authentication_requirements;
666 }
667 
SetOobDataPresent(hci::OobDataPresent data_present)668 void SecurityManagerImpl::SetOobDataPresent(hci::OobDataPresent data_present) {
669   this->local_oob_data_present_ = data_present;
670 }
671 
InternalEnforceSecurityPolicy(hci::AddressWithType remote,l2cap::classic::SecurityPolicy policy,l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback,bool try_meet_requirements)672 void SecurityManagerImpl::InternalEnforceSecurityPolicy(
673     hci::AddressWithType remote,
674     l2cap::classic::SecurityPolicy policy,
675     l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback,
676     bool try_meet_requirements) {
677   bool result = false;
678   auto record = this->security_database_.FindOrCreate(remote);
679   switch (policy) {
680     case l2cap::classic::SecurityPolicy::BEST:
681     case l2cap::classic::SecurityPolicy::AUTHENTICATED_ENCRYPTED_TRANSPORT:
682       result = record->IsAuthenticated() && record->RequiresMitmProtection() && record->IsEncryptionRequired();
683       break;
684     case l2cap::classic::SecurityPolicy::ENCRYPTED_TRANSPORT:
685       result = record->IsAuthenticated() && record->IsEncryptionRequired();
686       break;
687     case l2cap::classic::SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK:
688       result = true;
689       break;
690   }
691   if (!result && try_meet_requirements) {
692     auto entry = enforce_security_policy_callback_map_.find(remote);
693     if (entry != enforce_security_policy_callback_map_.end()) {
694       LOG_WARN("Callback already pending for remote: '%s' !", remote.ToString().c_str());
695     } else {
696       enforce_security_policy_callback_map_.emplace(
697           remote,
698           std::pair<l2cap::classic::SecurityPolicy, l2cap::classic::SecurityEnforcementInterface::ResultCallback>(
699               policy, std::move(result_callback)));
700       if (!record->IsPairing()) {
701         LOG_WARN("Dispatch #3");
702         DispatchPairingHandler(record, true);
703       }
704     }
705     return;
706   }
707   result_callback.Invoke(result);
708 }
709 
EnforceSecurityPolicy(hci::AddressWithType remote,l2cap::classic::SecurityPolicy policy,l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback)710 void SecurityManagerImpl::EnforceSecurityPolicy(
711     hci::AddressWithType remote,
712     l2cap::classic::SecurityPolicy policy,
713     l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback) {
714   this->InternalEnforceSecurityPolicy(remote, policy, std::move(result_callback), true);
715 }
716 
EnforceLeSecurityPolicy(hci::AddressWithType remote,l2cap::le::SecurityPolicy policy,l2cap::le::SecurityEnforcementInterface::ResultCallback result_callback)717 void SecurityManagerImpl::EnforceLeSecurityPolicy(
718     hci::AddressWithType remote, l2cap::le::SecurityPolicy policy,
719     l2cap::le::SecurityEnforcementInterface::ResultCallback result_callback) {
720   bool result = false;
721   // TODO(jpawlowski): Implement for LE
722   switch (policy) {
723     case l2cap::le::SecurityPolicy::BEST:
724       break;
725     case l2cap::le::SecurityPolicy::AUTHENTICATED_ENCRYPTED_TRANSPORT:
726       break;
727     case l2cap::le::SecurityPolicy::ENCRYPTED_TRANSPORT:
728       break;
729     case l2cap::le::SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK:
730       result = true;
731       break;
732     case l2cap::le::SecurityPolicy::_NOT_FOR_YOU__AUTHENTICATED_PAIRING_WITH_128_BIT_KEY:
733       break;
734     case l2cap::le::SecurityPolicy::_NOT_FOR_YOU__AUTHORIZATION:
735       break;
736   }
737   result_callback.Invoke(result);
738 }
739 }  // namespace internal
740 }  // namespace security
741 }  // namespace bluetooth
742