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