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