1 /* 2 * Copyright 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <storage/storage_module.h> 20 #include <unordered_map> 21 #include <utility> 22 23 #include "hci/acl_manager.h" 24 #include "hci/controller.h" 25 #include "l2cap/classic/security_enforcement_interface.h" 26 #include "l2cap/le/l2cap_le_module.h" 27 #include "l2cap/le/security_enforcement_interface.h" 28 #include "neighbor/name_db.h" 29 #include "os/handler.h" 30 #include "security/channel/security_manager_channel.h" 31 #include "security/initial_informations.h" 32 #include "security/pairing/classic_pairing_handler.h" 33 #include "security/pairing/oob_data.h" 34 #include "security/pairing_handler_le.h" 35 #include "security/record/security_record.h" 36 #include "security/record/security_record_database.h" 37 38 namespace bluetooth { 39 namespace security { 40 41 class ISecurityManagerListener; 42 43 static constexpr hci::IoCapability kDefaultIoCapability = hci::IoCapability::DISPLAY_YES_NO; 44 static constexpr hci::AuthenticationRequirements kDefaultAuthenticationRequirements = 45 hci::AuthenticationRequirements::GENERAL_BONDING; 46 47 namespace internal { 48 49 static constexpr uint16_t kInvalidConnectionHandle = 0xFFFF; 50 51 struct LeFixedChannelEntry { 52 std::unique_ptr<l2cap::le::FixedChannel> channel_; 53 std::unique_ptr<os::EnqueueBuffer<packet::BasePacketBuilder>> enqueue_buffer_; 54 }; 55 56 class SecurityManagerImpl : public channel::ISecurityManagerChannelListener, public UICallbacks { 57 public: 58 explicit SecurityManagerImpl( 59 os::Handler* security_handler, 60 l2cap::le::L2capLeModule* l2cap_le_module, 61 channel::SecurityManagerChannel* security_manager_channel, 62 hci::HciLayer* hci_layer, 63 hci::AclManager* acl_manager, 64 hci::Controller* controller, 65 storage::StorageModule* storage_module, 66 neighbor::NameDbModule* name_db_module); 67 ~SecurityManagerImpl()68 ~SecurityManagerImpl() { 69 /* L2CAP layer doesn't guarantee to send the registered OnCloseCallback during shutdown. Cleanup the remaining 70 * queues to prevent crashes */ 71 for (auto& stored_chan : all_channels_) { 72 stored_chan.channel_->GetQueueUpEnd()->UnregisterDequeue(); 73 stored_chan.enqueue_buffer_.reset(); 74 } 75 } 76 77 // All APIs must be invoked in SM layer handler 78 79 /** 80 * Initialize the security record map from an internal device database. 81 */ 82 void Init(); 83 84 /** 85 * Initiates bond over Classic transport with device, if not bonded yet. 86 * 87 * @param address device address we want to bond with 88 */ 89 void CreateBond(hci::AddressWithType address); 90 91 /** 92 * Initiates bond over Classic transport with device, if not bonded yet. 93 * 94 * Allows for OobData to be passed in for use while pairing 95 * 96 * @param address device address we want to bond with 97 * @param remote_p192_oob_data P192 data given to the stack 98 * @param remote_p256_oob_data P256 data given to the stack 99 */ 100 void CreateBondOutOfBand( 101 hci::AddressWithType address, pairing::OobData remote_p192_oob_data, pairing::OobData remote_p256_oob_data); 102 103 /** 104 * Initiates bond over Low Energy transport with device, if not bonded yet. 105 * 106 * @param address device address we want to bond with 107 */ 108 void CreateBondLe(hci::AddressWithType address); 109 110 /* void CreateBond(std::shared_ptr<hci::LeDevice> device); */ 111 112 /** 113 * Cancels the pairing process for this device. 114 * 115 * @param device pointer to device with which we want to cancel our bond 116 */ 117 void CancelBond(hci::AddressWithType device); 118 119 /* void CancelBond(std::shared_ptr<hci::LeDevice> device); */ 120 121 /** 122 * Disassociates the device and removes the persistent LTK 123 * 124 * @param device pointer to device we want to forget 125 * @return true if removed 126 */ 127 void RemoveBond(hci::AddressWithType device); 128 129 /* void RemoveBond(std::shared_ptr<hci::LeDevice> device); */ 130 131 /** 132 * Register Security UI handler, for handling prompts around the Pairing process. 133 */ 134 void SetUserInterfaceHandler(UI* user_interface, os::Handler* handler); 135 136 /** 137 * Specify the initiator address policy used for LE transport. Can only be called once. 138 */ 139 void SetLeInitiatorAddressPolicyForTest( 140 hci::LeAddressManager::AddressPolicy address_policy, 141 hci::AddressWithType fixed_address, 142 crypto_toolbox::Octet16 rotation_irk, 143 std::chrono::milliseconds minimum_rotation_time, 144 std::chrono::milliseconds maximum_rotation_time); 145 146 /** 147 * Register to listen for callback events from SecurityManager 148 * 149 * @param listener ISecurityManagerListener instance to handle callbacks 150 */ 151 void RegisterCallbackListener(ISecurityManagerListener* listener, os::Handler* handler); 152 153 /** 154 * Unregister listener for callback events from SecurityManager 155 * 156 * @param listener ISecurityManagerListener instance to unregister 157 */ 158 void UnregisterCallbackListener(ISecurityManagerListener* listener); 159 160 /** 161 * Handle the events sent back from HCI that we care about 162 * 163 * @param packet data received from HCI 164 */ 165 void OnHciEventReceived(hci::EventView packet) override; 166 167 /** 168 * When a conncetion closes we should clean up the pairing handler 169 * 170 * @param address Remote address 171 */ 172 void OnConnectionClosed(hci::Address address) override; 173 174 /** 175 * Pairing handler has finished or cancelled 176 * 177 * @param address address for pairing handler 178 * @param status status from SimplePairingComplete or other error code 179 */ 180 void OnPairingHandlerComplete(hci::Address address, PairingResultOrFailure status); 181 182 // UICallbacks implementation 183 void OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, bool confirmed) override; 184 void OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, bool confirmed) override; 185 void OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, uint32_t passkey) override; 186 void OnPinEntry(const bluetooth::hci::AddressWithType& address, std::vector<uint8_t> pin) override; 187 188 // Facade Configuration API functions 189 using FacadeDisconnectCallback = common::Callback<void(bluetooth::hci::AddressWithType)>; 190 void SetDisconnectCallback(FacadeDisconnectCallback callback); 191 void SetIoCapability(hci::IoCapability io_capability); 192 void SetAuthenticationRequirements(hci::AuthenticationRequirements authentication_requirements); 193 void GetOutOfBandData(channel::SecurityCommandStatusCallback callback); 194 void SetLeIoCapability(security::IoCapability io_capability); 195 void SetLeAuthRequirements(uint8_t auth_req); 196 void SetLeMaximumEncryptionKeySize(uint8_t maximum_encryption_key_size); 197 void SetLeOobDataPresent(OobDataFlag data_present); 198 void GetLeOutOfBandData(std::array<uint8_t, 16>* confirmation_value, std::array<uint8_t, 16>* random_value); 199 void SetOutOfBandData( 200 hci::AddressWithType remote_address, 201 std::array<uint8_t, 16> confirmation_value, 202 std::array<uint8_t, 16> random_value); 203 204 void EnforceSecurityPolicy(hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy, 205 l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback); 206 void EnforceLeSecurityPolicy(hci::AddressWithType remote, l2cap::le::SecurityPolicy policy, 207 l2cap::le::SecurityEnforcementInterface::ResultCallback result_callback); 208 protected: 209 std::vector<std::pair<ISecurityManagerListener*, os::Handler*>> listeners_; 210 UI* user_interface_ = nullptr; 211 os::Handler* user_interface_handler_ = nullptr; 212 213 void NotifyDeviceBonded(hci::AddressWithType device); 214 void NotifyDeviceBondFailed(hci::AddressWithType device, PairingFailure status); 215 void NotifyDeviceUnbonded(hci::AddressWithType device); 216 void NotifyEncryptionStateChanged(hci::EncryptionChangeView encryption_change_view); 217 218 private: 219 template <class T> 220 void HandleEvent(T packet); 221 222 void DispatchPairingHandler( 223 std::shared_ptr<record::SecurityRecord> record, 224 bool locally_initiated, 225 hci::IoCapability io_capability, 226 hci::AuthenticationRequirements auth_requirements, 227 pairing::OobData remote_p192_oob_data_, 228 pairing::OobData remote_p256_oob_data_); 229 void OnL2capRegistrationCompleteLe(l2cap::le::FixedChannelManager::RegistrationResult result, 230 std::unique_ptr<l2cap::le::FixedChannelService> le_smp_service); 231 void OnSmpCommandLe(hci::AddressWithType device); 232 void OnConnectionOpenLe(std::unique_ptr<l2cap::le::FixedChannel> channel); 233 void OnConnectionClosedLe(hci::AddressWithType address, hci::ErrorCode error_code); 234 void OnConnectionFailureLe(bluetooth::l2cap::le::FixedChannelManager::ConnectionResult result); 235 void OnPairingFinished(bluetooth::security::PairingResultOrFailure pairing_result); 236 void OnHciLeEvent(hci::LeMetaEventView event); 237 LeFixedChannelEntry* FindStoredLeChannel(const hci::AddressWithType& device); 238 LeFixedChannelEntry* FindStoredLeChannel(uint8_t connection_handle); 239 bool EraseStoredLeChannel(const hci::AddressWithType& device); 240 void InternalEnforceSecurityPolicy( 241 hci::AddressWithType remote, 242 l2cap::classic::SecurityPolicy policy, 243 l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback); 244 void UpdateLinkSecurityCondition(hci::AddressWithType remote); 245 bool IsSecurityRequirementSatisfied(hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy); 246 void ConnectionIsReadyStartPairing(LeFixedChannelEntry* stored_channel); 247 void WipeLePairingHandler(); 248 249 os::Handler* security_handler_ __attribute__((unused)); 250 l2cap::le::L2capLeModule* l2cap_le_module_ __attribute__((unused)); 251 std::unique_ptr<l2cap::le::FixedChannelManager> l2cap_manager_le_; 252 hci::LeSecurityInterface* hci_security_interface_le_ __attribute__((unused)); 253 channel::SecurityManagerChannel* security_manager_channel_; 254 hci::AclManager* acl_manager_; 255 hci::Controller* controller_; 256 storage::StorageModule* storage_module_ __attribute__((unused)); 257 record::SecurityRecordStorage security_record_storage_; 258 record::SecurityRecordDatabase security_database_; 259 neighbor::NameDbModule* name_db_module_; 260 std::unordered_map<hci::Address, std::shared_ptr<pairing::PairingHandler>> pairing_handler_map_; 261 hci::IoCapability local_io_capability_ = kDefaultIoCapability; 262 hci::AuthenticationRequirements local_authentication_requirements_ = kDefaultAuthenticationRequirements; 263 security::IoCapability local_le_io_capability_ = security::IoCapability::KEYBOARD_DISPLAY; 264 uint8_t local_le_auth_req_ = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc; 265 uint8_t local_maximum_encryption_key_size_ = 0x10; 266 OobDataFlag local_le_oob_data_present_ = OobDataFlag::NOT_PRESENT; 267 std::optional<MyOobData> local_le_oob_data_; 268 std::optional<hci::AddressWithType> remote_oob_data_address_; 269 std::optional<crypto_toolbox::Octet16> remote_oob_data_le_sc_c_; 270 std::optional<crypto_toolbox::Octet16> remote_oob_data_le_sc_r_; 271 std::optional<FacadeDisconnectCallback> facade_disconnect_callback_; 272 hci::AddressWithType local_identity_address_; 273 crypto_toolbox::Octet16 local_identity_resolving_key_; 274 275 struct PendingSecurityEnforcementEntry { 276 l2cap::classic::SecurityPolicy policy_; 277 l2cap::classic::SecurityEnforcementInterface::ResultCallback callback_; 278 }; 279 std::unordered_map<hci::AddressWithType, PendingSecurityEnforcementEntry> enforce_security_policy_callback_map_; 280 281 struct { 282 hci::AddressWithType address_; 283 uint16_t connection_handle_{kInvalidConnectionHandle}; 284 std::unique_ptr<PairingHandlerLe> handler_; 285 } pending_le_pairing_; 286 287 std::list<LeFixedChannelEntry> all_channels_; 288 }; 289 } // namespace internal 290 } // namespace security 291 } // namespace bluetooth 292