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