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