• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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(record::SecurityRecord & record,bool locally_initiated,hci::AuthenticationRequirements authentication_requirements)36 void SecurityManagerImpl::DispatchPairingHandler(record::SecurityRecord& record, bool locally_initiated,
37                                                  hci::AuthenticationRequirements authentication_requirements) {
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       std::shared_ptr<record::SecurityRecord> record_copy =
49           std::make_shared<record::SecurityRecord>(record.GetPseudoAddress());
50       pairing_handler = std::make_shared<security::pairing::ClassicPairingHandler>(
51           l2cap_classic_module_->GetFixedChannelManager(), security_manager_channel_, record_copy, security_handler_,
52           std::move(callback), user_interface_, user_interface_handler_, "TODO: grab device name properly");
53       break;
54     }
55     default:
56       ASSERT_LOG(false, "Pairing type %hhu not implemented!", record.GetPseudoAddress().GetAddressType());
57   }
58   auto new_entry = std::pair<hci::Address, std::shared_ptr<pairing::PairingHandler>>(
59       record.GetPseudoAddress().GetAddress(), pairing_handler);
60   pairing_handler_map_.insert(std::move(new_entry));
61   pairing_handler->Initiate(locally_initiated, pairing::kDefaultIoCapability, pairing::kDefaultOobDataPresent,
62                             authentication_requirements);
63 }
64 
Init()65 void SecurityManagerImpl::Init() {
66   security_manager_channel_->SetChannelListener(this);
67   security_manager_channel_->SendCommand(hci::WriteSimplePairingModeBuilder::Create(hci::Enable::ENABLED));
68   security_manager_channel_->SendCommand(hci::WriteSecureConnectionsHostSupportBuilder::Create(hci::Enable::ENABLED));
69   // TODO(optedoblivion): Populate security record memory map from disk
70 }
71 
CreateBond(hci::AddressWithType device)72 void SecurityManagerImpl::CreateBond(hci::AddressWithType device) {
73   record::SecurityRecord& record = security_database_.FindOrCreate(device);
74   if (record.IsBonded()) {
75     NotifyDeviceBonded(device);
76   } else {
77     // Dispatch pairing handler, if we are calling create we are the initiator
78     DispatchPairingHandler(record, true, pairing::kDefaultAuthenticationRequirements);
79   }
80 }
81 
CreateBondLe(hci::AddressWithType address)82 void SecurityManagerImpl::CreateBondLe(hci::AddressWithType address) {
83   record::SecurityRecord& record = security_database_.FindOrCreate(address);
84   if (record.IsBonded()) {
85     NotifyDeviceBondFailed(address, PairingFailure("Already bonded"));
86     return;
87   }
88 
89   pending_le_pairing_.address_ = address;
90 
91   l2cap_manager_le_->ConnectServices(
92       address, common::BindOnce(&SecurityManagerImpl::OnConnectionFailureLe, common::Unretained(this)),
93       security_handler_);
94 }
95 
CancelBond(hci::AddressWithType device)96 void SecurityManagerImpl::CancelBond(hci::AddressWithType device) {
97   auto entry = pairing_handler_map_.find(device.GetAddress());
98   if (entry != pairing_handler_map_.end()) {
99     auto cancel_me = entry->second;
100     pairing_handler_map_.erase(entry);
101     cancel_me->Cancel();
102   }
103 }
104 
RemoveBond(hci::AddressWithType device)105 void SecurityManagerImpl::RemoveBond(hci::AddressWithType device) {
106   CancelBond(device);
107   security_database_.Remove(device);
108   // Signal disconnect
109   // Remove security record
110   // Signal Remove from database
111 }
112 
SetUserInterfaceHandler(UI * user_interface,os::Handler * handler)113 void SecurityManagerImpl::SetUserInterfaceHandler(UI* user_interface, os::Handler* handler) {
114   if (user_interface_ != nullptr || user_interface_handler_ != nullptr) {
115     LOG_ALWAYS_FATAL("Listener has already been registered!");
116   }
117   user_interface_ = user_interface;
118   user_interface_handler_ = handler;
119 }
120 
RegisterCallbackListener(ISecurityManagerListener * listener,os::Handler * handler)121 void SecurityManagerImpl::RegisterCallbackListener(ISecurityManagerListener* listener, os::Handler* handler) {
122   for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
123     if (it->first == listener) {
124       LOG_ALWAYS_FATAL("Listener has already been registered!");
125     }
126   }
127 
128   listeners_.push_back({listener, handler});
129 }
130 
UnregisterCallbackListener(ISecurityManagerListener * listener)131 void SecurityManagerImpl::UnregisterCallbackListener(ISecurityManagerListener* listener) {
132   for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
133     if (it->first == listener) {
134       listeners_.erase(it);
135       return;
136     }
137   }
138 
139   LOG_ALWAYS_FATAL("Listener has not been registered!");
140 }
141 
NotifyDeviceBonded(hci::AddressWithType device)142 void SecurityManagerImpl::NotifyDeviceBonded(hci::AddressWithType device) {
143   for (auto& iter : listeners_) {
144     iter.second->Post(common::Bind(&ISecurityManagerListener::OnDeviceBonded, common::Unretained(iter.first), device));
145   }
146 }
147 
NotifyDeviceBondFailed(hci::AddressWithType device,PairingResultOrFailure status)148 void SecurityManagerImpl::NotifyDeviceBondFailed(hci::AddressWithType device, PairingResultOrFailure status) {
149   for (auto& iter : listeners_) {
150     iter.second->Post(common::Bind(&ISecurityManagerListener::OnDeviceBondFailed, common::Unretained(iter.first),
151                                    device /*, status */));
152   }
153 }
154 
NotifyDeviceUnbonded(hci::AddressWithType device)155 void SecurityManagerImpl::NotifyDeviceUnbonded(hci::AddressWithType device) {
156   for (auto& iter : listeners_) {
157     iter.second->Post(
158         common::Bind(&ISecurityManagerListener::OnDeviceUnbonded, common::Unretained(iter.first), device));
159   }
160 }
161 
162 template <class T>
HandleEvent(T packet)163 void SecurityManagerImpl::HandleEvent(T packet) {
164   ASSERT(packet.IsValid());
165   auto entry = pairing_handler_map_.find(packet.GetBdAddr());
166 
167   if (entry == pairing_handler_map_.end()) {
168     auto bd_addr = packet.GetBdAddr();
169     auto event_code = packet.GetEventCode();
170     auto event = hci::EventPacketView::Create(std::move(packet));
171     ASSERT_LOG(event.IsValid(), "Received invalid packet");
172 
173     const hci::EventCode code = event.GetEventCode();
174     if (code != hci::EventCode::LINK_KEY_REQUEST) {
175       LOG_ERROR("No classic pairing handler for device '%s' ready for command %s ", bd_addr.ToString().c_str(),
176                 hci::EventCodeText(event_code).c_str());
177       return;
178     }
179 
180     auto record =
181         security_database_.FindOrCreate(hci::AddressWithType{bd_addr, hci::AddressType::PUBLIC_DEVICE_ADDRESS});
182     auto authentication_requirements = hci::AuthenticationRequirements::NO_BONDING;
183     DispatchPairingHandler(record, true, authentication_requirements);
184     entry = pairing_handler_map_.find(bd_addr);
185   }
186   entry->second->OnReceive(packet);
187 }
188 
OnHciEventReceived(hci::EventPacketView packet)189 void SecurityManagerImpl::OnHciEventReceived(hci::EventPacketView packet) {
190   auto event = hci::EventPacketView::Create(packet);
191   ASSERT_LOG(event.IsValid(), "Received invalid packet");
192   const hci::EventCode code = event.GetEventCode();
193   switch (code) {
194     case hci::EventCode::PIN_CODE_REQUEST:
195       HandleEvent<hci::PinCodeRequestView>(hci::PinCodeRequestView::Create(event));
196       break;
197     case hci::EventCode::LINK_KEY_REQUEST:
198       HandleEvent(hci::LinkKeyRequestView::Create(event));
199       break;
200     case hci::EventCode::LINK_KEY_NOTIFICATION:
201       HandleEvent(hci::LinkKeyNotificationView::Create(event));
202       break;
203     case hci::EventCode::IO_CAPABILITY_REQUEST:
204       HandleEvent(hci::IoCapabilityRequestView::Create(event));
205       break;
206     case hci::EventCode::IO_CAPABILITY_RESPONSE:
207       HandleEvent(hci::IoCapabilityResponseView::Create(event));
208       break;
209     case hci::EventCode::SIMPLE_PAIRING_COMPLETE:
210       HandleEvent(hci::SimplePairingCompleteView::Create(event));
211       break;
212     case hci::EventCode::REMOTE_OOB_DATA_REQUEST:
213       HandleEvent(hci::RemoteOobDataRequestView::Create(event));
214       break;
215     case hci::EventCode::USER_PASSKEY_NOTIFICATION:
216       HandleEvent(hci::UserPasskeyNotificationView::Create(event));
217       break;
218     case hci::EventCode::KEYPRESS_NOTIFICATION:
219       HandleEvent(hci::KeypressNotificationView::Create(event));
220       break;
221     case hci::EventCode::USER_CONFIRMATION_REQUEST:
222       HandleEvent(hci::UserConfirmationRequestView::Create(event));
223       break;
224     case hci::EventCode::USER_PASSKEY_REQUEST:
225       HandleEvent(hci::UserPasskeyRequestView::Create(event));
226       break;
227     case hci::EventCode::REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION:
228       LOG_INFO("Unhandled event: %s", hci::EventCodeText(code).c_str());
229       break;
230 
231     case hci::EventCode::ENCRYPTION_CHANGE: {
232       EncryptionChangeView enc_chg_packet = EncryptionChangeView::Create(event);
233       if (!enc_chg_packet.IsValid()) {
234         LOG_ERROR("Invalid EncryptionChange packet received");
235         return;
236       }
237       if (enc_chg_packet.GetConnectionHandle() == pending_le_pairing_.connection_handle_) {
238         pending_le_pairing_.handler_->OnHciEvent(event);
239         return;
240       }
241       break;
242     }
243 
244     default:
245       ASSERT_LOG(false, "Cannot handle received packet: %s", hci::EventCodeText(code).c_str());
246       break;
247   }
248 }
249 
OnHciLeEvent(hci::LeMetaEventView event)250 void SecurityManagerImpl::OnHciLeEvent(hci::LeMetaEventView event) {
251   // hci::SubeventCode::LONG_TERM_KEY_REQUEST,
252   // hci::SubeventCode::READ_LOCAL_P256_PUBLIC_KEY_COMPLETE,
253   // hci::SubeventCode::GENERATE_DHKEY_COMPLETE,
254   LOG_ERROR("Unhandled HCI LE security event");
255 }
256 
OnPairingPromptAccepted(const bluetooth::hci::AddressWithType & address,bool confirmed)257 void SecurityManagerImpl::OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, bool confirmed) {
258   auto entry = pairing_handler_map_.find(address.GetAddress());
259   if (entry != pairing_handler_map_.end()) {
260     entry->second->OnPairingPromptAccepted(address, confirmed);
261   } else {
262     pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::PAIRING_ACCEPTED, confirmed);
263   }
264 }
265 
OnConfirmYesNo(const bluetooth::hci::AddressWithType & address,bool confirmed)266 void SecurityManagerImpl::OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, bool confirmed) {
267   auto entry = pairing_handler_map_.find(address.GetAddress());
268   if (entry != pairing_handler_map_.end()) {
269     entry->second->OnConfirmYesNo(address, confirmed);
270   } else {
271     if (pending_le_pairing_.address_ == address) {
272       pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::CONFIRM_YESNO, confirmed);
273     }
274   }
275 }
276 
OnPasskeyEntry(const bluetooth::hci::AddressWithType & address,uint32_t passkey)277 void SecurityManagerImpl::OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, uint32_t passkey) {
278   auto entry = pairing_handler_map_.find(address.GetAddress());
279   if (entry != pairing_handler_map_.end()) {
280     entry->second->OnPasskeyEntry(address, passkey);
281   } else {
282     if (pending_le_pairing_.address_ == address) {
283       pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::PASSKEY, passkey);
284     }
285   }
286 }
287 
OnPairingHandlerComplete(hci::Address address,PairingResultOrFailure status)288 void SecurityManagerImpl::OnPairingHandlerComplete(hci::Address address, PairingResultOrFailure status) {
289   auto entry = pairing_handler_map_.find(address);
290   if (entry != pairing_handler_map_.end()) {
291     pairing_handler_map_.erase(entry);
292   }
293   if (!std::holds_alternative<PairingFailure>(status)) {
294     NotifyDeviceBonded(hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS));
295   } else {
296     NotifyDeviceBondFailed(hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS), status);
297   }
298 }
299 
OnL2capRegistrationCompleteLe(l2cap::le::FixedChannelManager::RegistrationResult result,std::unique_ptr<l2cap::le::FixedChannelService> le_smp_service)300 void SecurityManagerImpl::OnL2capRegistrationCompleteLe(
301     l2cap::le::FixedChannelManager::RegistrationResult result,
302     std::unique_ptr<l2cap::le::FixedChannelService> le_smp_service) {
303   ASSERT_LOG(result == bluetooth::l2cap::le::FixedChannelManager::RegistrationResult::SUCCESS,
304              "Failed to register to LE SMP Fixed Channel Service");
305 }
306 
OnSmpCommandLe()307 void SecurityManagerImpl::OnSmpCommandLe() {
308   auto packet = pending_le_pairing_.channel_->GetQueueUpEnd()->TryDequeue();
309   if (!packet) LOG_ERROR("Received dequeue, but no data ready...");
310 
311   auto temp_cmd_view = CommandView::Create(*packet);
312   pending_le_pairing_.handler_->OnCommandView(temp_cmd_view);
313 }
314 
OnConnectionOpenLe(std::unique_ptr<l2cap::le::FixedChannel> channel)315 void SecurityManagerImpl::OnConnectionOpenLe(std::unique_ptr<l2cap::le::FixedChannel> channel) {
316   if (pending_le_pairing_.address_ != channel->GetDevice()) {
317     return;
318   }
319   pending_le_pairing_.channel_ = std::move(channel);
320   pending_le_pairing_.channel_->RegisterOnCloseCallback(
321       security_handler_, common::BindOnce(&SecurityManagerImpl::OnConnectionClosedLe, common::Unretained(this),
322                                           pending_le_pairing_.channel_->GetDevice()));
323   // TODO: this enqueue buffer must be stored together with pairing_handler, and we must make sure it doesn't go out of
324   // scope while the pairing happens
325   pending_le_pairing_.enqueue_buffer_ =
326       std::make_unique<os::EnqueueBuffer<packet::BasePacketBuilder>>(pending_le_pairing_.channel_->GetQueueUpEnd());
327   pending_le_pairing_.channel_->GetQueueUpEnd()->RegisterDequeue(
328       security_handler_, common::Bind(&SecurityManagerImpl::OnSmpCommandLe, common::Unretained(this)));
329 
330   // 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
331   pending_le_pairing_.connection_handle_ = pending_le_pairing_.channel_->GetAclConnection()->GetHandle();
332   InitialInformations initial_informations{
333       .my_role = pending_le_pairing_.channel_->GetAclConnection()->GetRole(),
334       .my_connection_address = {hci::Address{{0x00, 0x11, 0xFF, 0xFF, 0x33, 0x22}} /*TODO: obtain my address*/,
335                                 hci::AddressType::RANDOM_DEVICE_ADDRESS},
336       /*TODO: properly obtain capabilities from device-specific storage*/
337       .myPairingCapabilities = {.io_capability = IoCapability::KEYBOARD_DISPLAY,
338                                 .oob_data_flag = OobDataFlag::NOT_PRESENT,
339                                 .auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc,
340                                 .maximum_encryption_key_size = 16,
341                                 .initiator_key_distribution = 0x07,
342                                 .responder_key_distribution = 0x07},
343       .remotely_initiated = false,
344       .connection_handle = pending_le_pairing_.channel_->GetAclConnection()->GetHandle(),
345       .remote_connection_address = pending_le_pairing_.channel_->GetDevice(),
346       .remote_name = "TODO: grab proper device name in sec mgr",
347       /* contains pairing request, if the pairing was remotely initiated */
348       .pairing_request = std::nullopt,  // TODO: handle remotely initiated pairing in SecurityManager properly
349       .remote_oob_data = std::nullopt,  // TODO:
350       .my_oob_data = std::nullopt,      // TODO:
351       /* Used by Pairing Handler to present user with requests*/
352       .user_interface = user_interface_,
353       .user_interface_handler = user_interface_handler_,
354 
355       /* HCI interface to use */
356       .le_security_interface = hci_security_interface_le_,
357       .proper_l2cap_interface = pending_le_pairing_.enqueue_buffer_.get(),
358       .l2cap_handler = security_handler_,
359       /* Callback to execute once the Pairing process is finished */
360       // TODO: make it an common::OnceCallback ?
361       .OnPairingFinished = std::bind(&SecurityManagerImpl::OnPairingFinished, this, std::placeholders::_1),
362   };
363   pending_le_pairing_.handler_ = std::make_unique<PairingHandlerLe>(PairingHandlerLe::PHASE1, initial_informations);
364 }
365 
OnConnectionClosedLe(hci::AddressWithType address,hci::ErrorCode error_code)366 void SecurityManagerImpl::OnConnectionClosedLe(hci::AddressWithType address, hci::ErrorCode error_code) {
367   if (pending_le_pairing_.address_ != address) {
368     return;
369   }
370   pending_le_pairing_.handler_->SendExitSignal();
371   NotifyDeviceBondFailed(address, PairingFailure("Connection closed"));
372 }
373 
OnConnectionFailureLe(bluetooth::l2cap::le::FixedChannelManager::ConnectionResult result)374 void SecurityManagerImpl::OnConnectionFailureLe(bluetooth::l2cap::le::FixedChannelManager::ConnectionResult result) {
375   if (result.connection_result_code ==
376       bluetooth::l2cap::le::FixedChannelManager::ConnectionResultCode::FAIL_ALL_SERVICES_HAVE_CHANNEL) {
377     // TODO: already connected
378   }
379 
380   // This callback is invoked only for devices we attempted to connect to.
381   NotifyDeviceBondFailed(pending_le_pairing_.address_, PairingFailure("Connection establishment failed"));
382 }
383 
SecurityManagerImpl(os::Handler * security_handler,l2cap::le::L2capLeModule * l2cap_le_module,l2cap::classic::L2capClassicModule * l2cap_classic_module,channel::SecurityManagerChannel * security_manager_channel,hci::HciLayer * hci_layer)384 SecurityManagerImpl::SecurityManagerImpl(os::Handler* security_handler, l2cap::le::L2capLeModule* l2cap_le_module,
385                                          l2cap::classic::L2capClassicModule* l2cap_classic_module,
386                                          channel::SecurityManagerChannel* security_manager_channel,
387                                          hci::HciLayer* hci_layer)
388     : security_handler_(security_handler), l2cap_le_module_(l2cap_le_module),
389       l2cap_classic_module_(l2cap_classic_module), l2cap_manager_le_(l2cap_le_module_->GetFixedChannelManager()),
390       hci_security_interface_le_(hci_layer->GetLeSecurityInterface(
391           common::Bind(&SecurityManagerImpl::OnHciLeEvent, common::Unretained(this)), security_handler)),
392       security_manager_channel_(security_manager_channel) {
393   Init();
394   l2cap_manager_le_->RegisterService(
395       bluetooth::l2cap::kSmpCid, {},
396       common::BindOnce(&SecurityManagerImpl::OnL2capRegistrationCompleteLe, common::Unretained(this)),
397       common::Bind(&SecurityManagerImpl::OnConnectionOpenLe, common::Unretained(this)), security_handler_);
398 }
399 
OnPairingFinished(security::PairingResultOrFailure pairing_result)400 void SecurityManagerImpl::OnPairingFinished(security::PairingResultOrFailure pairing_result) {
401   LOG_INFO(" ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ Received pairing result");
402 
403   if (std::holds_alternative<PairingFailure>(pairing_result)) {
404     PairingFailure failure = std::get<PairingFailure>(pairing_result);
405     LOG_INFO(" ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ failure message: %s",
406              failure.message.c_str());
407     return;
408   }
409 
410   LOG_INFO("Pairing with %s was successfull",
411            std::get<PairingResult>(pairing_result).connection_address.ToString().c_str());
412 }
413 
414 }  // namespace internal
415 }  // namespace security
416 }  // namespace bluetooth
417