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