Mistake on this page?
Report an issue in GitHub or email us
SecurityManager.h
1 /* mbed Microcontroller Library
2  * Copyright (c) 2006-2020 ARM Limited
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 
19 #ifndef BLE_SECURITY_MANAGER_H_
20 #define BLE_SECURITY_MANAGER_H_
21 
22 #include <cstdint>
23 
24 #include "ble/common/BLETypes.h"
25 #include "ble/common/blecommon.h"
26 #include "ble/common/CallChainOfFunctionPointersWithContext.h"
27 
28 namespace ble {
29 
30 #if !defined(DOXYGEN_ONLY)
31 namespace impl {
32 class SecurityManager;
33 }
34 #endif // !defined(DOXYGEN_ONLY)
35 
36 /**
37  * Overview
38  *
39  * Security Manager is used to provide link security through encryption, signing and authentication
40  * which are made possible by pairing and optionally bonding. Pairing is the process of establishing
41  * and/or exchanging keys used for the current connection. Bonding means saving this information so that
42  * it can later be used after reconnecting without having to pair again. This saves time and power.
43  *
44  * @par Paring
45  *
46  * There are several ways to provide different levels of security during pairing depending on your requirements
47  * and the facilities provided by the application. The process starts with initialising the SecurityManager
48  * with default options for new connections. Some settings can later be changed per link or globally.
49  *
50  * The important settings in the init() function are the MITM requirement and IO capabilities. Man in the
51  * Middle (MITM) protection prevents an attack where one device can impersonate another device by
52  * pairing with both devices at the same time. This protection is achieved by sharing some information
53  * between the devices through some independent channel. The IO capabilities of both devices dictate
54  * what algorithm is used. For details @see BLUETOOTH SPECIFICATION Version 5.0 | Vol 3, Part H - 2.3.5.1.
55  * You can change the IO capabilities after initialisation with setIoCapability(). This will take effect
56  * for all subsequent pairings.
57  *
58  * @par Out of Band data used in pairing
59  *
60  * Sharing this information through IO capabilities means user interaction which limits the degree of
61  * protection due to the limit of the amount of data that we can expect the user to transfer. Another
62  * solution is using OOB (out of band) communication to transfer this data instead which can send much
63  * more data making MITM attack even less likely to succeed. OOB data has to be exchanged by the application
64  * and provided to the Security Manager. Use setOOBDataUsage() to indicate you want to use it. The same call also
65  * allows you to set whether or not the communication channel you are using to transmit the OOB data is
66  * itself secure against MITM protection - this will set the level of the link security achieved using pairing
67  * that uses this data.
68  *
69  * The most secure pairing is provided by Secure Connections which relies on Elliptical Curve Cryptography.
70  * Support for Secure Connections is dependent on both the stack and controller on both sides supporting
71  * it. If either side doesn't support it Legacy Pairing will be used. This is an older standard of pairing.
72  * If higher security is required legacy pairing can be disabled by calling allowLegacyPairing(false);
73  *
74  * @par Signing
75  *
76  * Applications may require a level of security providing confidence that data transfers are coming
77  * from a trusted source. This can be achieved by encrypting the link which also provides added confidentiality.
78  * Encryption is a good choice when a device stays connected but introduces latency due to the need of encrypting the
79  * link if the device only connects periodically to transfer data. If confidentiality is not required data GATT
80  * server may allow writes to happen over an unencrypted link but authenticated by a signature present in each packet.
81  * This signature relies on having sent a signing key to the peer during pairing prior to sending any signed packets.
82  *
83  * @par Persistence of Security information
84  *
85  * Security Manager stores all the data required for its operation on active links. Depending on resources
86  * available on the device it will also attempt to store data for disconnected devices which have bonded to be
87  * reused when reconnected.
88  *
89  * If the application has initialised a filesystem and the Security Manager has been provided with a
90  * filepath during the init() call it may also provide data persistence across resets. This must be enabled by
91  * calling preserveBondingStateOnReset(). Persistence is not guaranteed and may fail if abnormally terminated.
92  * The Security Manager may also fall back to a non-persistent implementation if the resources are too limited.
93  *
94  * @par How to use
95  *
96  * First thing you need to do is to initialise the manager by calling init() with your chosen settings.
97  *
98  * The SecurityManager communicates with your application through events. These will trigger calls in
99  * the EventHandler which you must provide by calling the setSecurityManagerEventHandler() function.
100  *
101  * The most important process is pairing. This may be triggered manually by calling requestPairing() or
102  * may be called as a result of the application requiring encryption by calling setLinkEncryption() or
103  * as a result of the application requiring MITM protection through requestAuthentication().
104  *
105  * All these can be implicitly called by using setLinkSecurity() to conveniently set the required
106  * security for the link. The SecurityManager will trigger all the process required to achieve the set
107  * security level. Security level can only be escalated. Asking the Security Manager for a lower
108  * security level than the existing one will not fail but will result in a event informing the
109  * application through linkEncryptionResult() of the current level (which remains unchanged).
110  *
111  * Depending on the IO capabilities and OOB usage settings different pairing algorithms will be chosen.
112  * They will produce appropriate events which must be handled by your EventHandler. If your event handler
113  * doesn't support all the calls you must not set IO capabilities or set OOB usage in such a way that would
114  * trigger them or else the pairing will fail (usually by timing out).
115  *
116  * The simplest example is a pairing of a device with no IO capabilities and no OOB data available.
117  * With such limited pairing capabilities the "just works" method will be employed. This does not provide
118  * any MITM protection. The pairing (triggered implicitly or called explicitly) will result in an event
119  * being generated on the peer calling pairingRequest(). The event handler must make a decision (either in
120  * the application itself or based on user interaction) whether to accept the pairing and call
121  * accetPairing() or cancelPairing(). The result will be communicated on both peers through an event calling
122  * pairingResult() in the EventHandler.
123  *
124  * @par Sequence diagrams
125  *
126  * Sequence diagram "Just Works" pairing
127  *
128  * \verbatim
129  * /-------- Device 1 ---------\ *----- BLE link -----* /----------- Device 2-----------\
130  *
131  * App EventHandler SecurityManager SecurityManager EventHandler App
132  * | | | | | |
133  * |-------------------> requestPairing() | | |
134  * | | |-----[pairing start]----->| | |
135  * | | | |---------> pairingRequest() -->|
136  * | | | acceptPairing() <--------------------- |
137  * | | |<--[pairing complete]---->| | |
138  * |<- pairingResult() <-------| |---------> pairingResult() --->|
139  * | | | | | |
140  * @endverbatim
141  *
142  * @note the requestPairing() call isn't required to trigger pairing. Pairing will also be triggered
143  * if you request encryption and authentication and no bonding information is available. The sequence will
144  * be the same save for the lack of explicit requestPairing() call.
145  *
146  *
147  * Sequence diagram Encryption request when bonding information is available
148  *
149  * \verbatim
150  * /--------- Device 1 ---------\ *------ BLE link ------* /--------- Device 2 ---------\
151  *
152  * App EventHandler SecurityManager SecurityManager EventHandler App
153  * | | | | | |
154  * |--------------------> setLinkEncryption() | | |
155  * | | |<-[encryption established]->| | |
156  * |<- linkEncryptionResult() <-| |-> linkEncryptionResult() ->|
157  * | | | | | |
158  * @endverbatim
159  *
160  * @note if bonding information is not available, pairing will be triggered
161  *
162  *
163  * Sequence diagram for Secure Connections passkey entry pairing with one device having a display only
164  * and other a keyboard
165  *
166  * \verbatim
167  * /---- Device 1 (keyboard) ---\ *------ BLE link ------* /----- Device 2 (display) ---\
168  *
169  * App EventHandler SecurityManager SecurityManager EventHandler App
170  * | | | | | |
171  * |--------------------> requestPairing() | | |
172  * | | |------[pairing start]------>| | |
173  * | | | |-------> pairingRequest() ->|
174  * | | | acceptPairing() <--------------- |
175  * | | |<---[secure con. pairing]-->| | |
176  * |<- passkeyRequest() <-------| |-------> passkeyDisplay() ->|
177  * | | | | | |
178  *
179  * user reads the passkey on Device 2 and inputs it on Device 1
180  *
181  * | | | | | |
182  * |------------------->passkeyEntered() | | |
183  * | | |<---[pairing complete]----->| | |
184  * |<- pairingResult() <--------| |-------> pairingResult() -->|
185  * | | | | | |
186  * @endverbatim
187  *
188  */
190 {
191 public:
192  /** level of security required from the link by the application */
194  SECURITY_MODE_NO_ACCESS,
195  SECURITY_MODE_ENCRYPTION_OPEN_LINK, /**< Require no protection, open link. */
196  SECURITY_MODE_ENCRYPTION_NO_MITM, /**< Require encryption, but no MITM protection. */
197  SECURITY_MODE_ENCRYPTION_WITH_MITM, /**< Require encryption and MITM protection. */
198  SECURITY_MODE_SIGNED_NO_MITM, /**< Require signing or encryption, but no MITM protection. */
199  SECURITY_MODE_SIGNED_WITH_MITM, /**< Require signing or encryption, and MITM protection. */
200  };
201 
202  /** Input/output capability of the device and application */
204  IO_CAPS_DISPLAY_ONLY = 0x00, /**< Display only. */
205  IO_CAPS_DISPLAY_YESNO = 0x01, /**< Display and yes/no entry. */
206  IO_CAPS_KEYBOARD_ONLY = 0x02, /**< Keyboard only. */
207  IO_CAPS_NONE = 0x03, /**< No I/O capabilities. */
208  IO_CAPS_KEYBOARD_DISPLAY = 0x04, /**< Keyboard and display. */
209  };
210 
211  /** Result of security requests */
213  SEC_STATUS_SUCCESS = 0x00, /**< Procedure completed with success. */
214  SEC_STATUS_TIMEOUT = 0x01, /**< Procedure timed out. */
215  SEC_STATUS_PDU_INVALID = 0x02, /**< Invalid PDU received. */
216  SEC_STATUS_PASSKEY_ENTRY_FAILED = 0x81, /**< Passkey entry failed (user cancelled or other). */
217  SEC_STATUS_OOB_NOT_AVAILABLE = 0x82, /**< Out of Band Key not available. */
218  SEC_STATUS_AUTH_REQ = 0x83, /**< Authentication requirements not met. */
219  SEC_STATUS_CONFIRM_VALUE = 0x84, /**< Confirm value failed. */
220  SEC_STATUS_PAIRING_NOT_SUPP = 0x85, /**< Pairing not supported. */
221  SEC_STATUS_ENC_KEY_SIZE = 0x86, /**< Encryption key size. */
222  SEC_STATUS_SMP_CMD_UNSUPPORTED = 0x87, /**< Unsupported SMP command. */
223  SEC_STATUS_UNSPECIFIED = 0x88, /**< Unspecified reason. */
224  SEC_STATUS_REPEATED_ATTEMPTS = 0x89, /**< Too little time elapsed since last attempt. */
225  SEC_STATUS_INVALID_PARAMS = 0x8A, /**< Invalid parameters. */
226  SEC_STATUS_DHKEY_CHECK_FAILED = 0x8B, /**< DHKey received doesn’t match locally calculated one. */
227  SEC_STATUS_COMPARISON_FAILED = 0x8C, /**< Values in the numeric comparison protocol do not match. */
228  };
229 
230  /**
231  * Declaration of type containing a passkey to be used during pairing. This
232  * is passed into initializeSecurity() to specify a pre-programmed passkey
233  * for authentication instead of generating a random one.
234  */
235  static const unsigned PASSKEY_LEN = 6;
236  typedef uint8_t Passkey_t[PASSKEY_LEN]; /**< 6-digit passkey in ASCII ('0'-'9' digits only). */
237 
240 
241  /** The stack will use these functions to signal events to the application,
242  * subclass to override handlers. Use SecurityManager::setSecurityManagerEventHandler
243  * to set the interface implementation to be used. */
244  class EventHandler {
245  public:
246  ////////////////////////////////////////////////////////////////////////////
247  // Pairing
248  //
249 
250 #if BLE_ROLE_PERIPHERAL
251  /**
252  * Request application to accept or reject pairing. Application should respond by
253  * calling the appropriate function: acceptPairingRequest or cancelPairingRequest
254  *
255  * @param[in] connectionHandle connection connectionHandle
256  */
257  virtual void pairingRequest(ble::connection_handle_t connectionHandle) {
258  (void)connectionHandle;
259  }
260 #endif // BLE_ROLE_PERIPHERAL
261 
262  /**
263  * Indicate to the application that pairing has completed.
264  *
265  * @param[in] connectionHandle connection connectionHandle
266  * @param[in] result result of the pairing indicating success or reason for failure
267  */
268  virtual void pairingResult(ble::connection_handle_t connectionHandle, SecurityCompletionStatus_t result) {
269  (void)connectionHandle;
270  (void)result;
271  }
272 
273  /**
274  * Indicate that a peer address has been saved by the security manager or if we are
275  * bonded to the peer the identity has been retrieved from the database on connection.
276  *
277  * @param[in] connectionHandle Connection handle.
278  * @param[in] peer_address Peer address that has been saved by the security database, NULL it not found.
279  * @param[in] address_is_public Address type, true if public. Invalid if peer_address NULL.
280  */
281  virtual void peerIdentity(ble::connection_handle_t connectionHandle,
282  const address_t *peer_address,
283  bool address_is_public) {
284  (void)connectionHandle;
285  (void)peer_address;
286  (void)address_is_public;
287  }
288 
289  ////////////////////////////////////////////////////////////////////////////
290  // Security
291  //
292 
293  /**
294  * Deliver the requested whitelist to the application.
295  *
296  * @param[in] whitelist pointer to the whitelist filled with entries based on bonding information
297  */
298  virtual void whitelistFromBondTable(::ble::whitelist_t* whitelist) {
299  (void)whitelist;
300  }
301 
302  ////////////////////////////////////////////////////////////////////////////
303  // Encryption
304  //
305 
306  /**
307  * Inform the device of the encryption state of a given link.
308  *
309  * @param[in] connectionHandle connection connectionHandle
310  * @param[in] result encryption state of the link
311  */
313  (void)connectionHandle;
314  (void)result;
315  }
316 
317  ////////////////////////////////////////////////////////////////////////////
318  // MITM
319  //
320 
321  /**
322  * Display the given passkey on the local device.
323  *
324  * @param[in] connectionHandle connection connectionHandle
325  * @param[in] passkey 6 digit passkey to be displayed
326  */
327  virtual void passkeyDisplay(ble::connection_handle_t connectionHandle, const Passkey_t passkey) {
328  (void)connectionHandle;
329  (void)passkey;
330  }
331 
332 #if BLE_FEATURE_SECURE_CONNECTIONS
333  /**
334  * Indicate to the application that a confirmation is required. This is used
335  * when the device does not have a keyboard but has a yes/no button. The device
336  * displays numbers on its display in response to passkeyDisplay and the user
337  * checks if they are the same on both devices. The application should proceed
338  * by supplying the confirmation using the confirmationEntered function.
339  *
340  * @param[in] connectionHandle connection connectionHandle
341  */
342  virtual void confirmationRequest(ble::connection_handle_t connectionHandle) {
343  (void)connectionHandle;
344  }
345 #endif // BLE_FEATURE_SECURE_CONNECTIONS
346 
347  /**
348  * Indicate to the application that a passkey is required. The application should
349  * proceed by supplying the passkey through the passkeyEntered function.
350  *
351  * @param[in] connectionHandle connection connectionHandle
352  */
353  virtual void passkeyRequest(ble::connection_handle_t connectionHandle) {
354  (void)connectionHandle;
355  }
356 
357 #if BLE_FEATURE_SECURE_CONNECTIONS
358  /**
359  * Notify the application that a key was pressed by the peer during passkey entry.
360  *
361  * @param[in] connectionHandle connection connectionHandle
362  * @param[in] keypress type of keypress event
363  */
364  virtual void keypressNotification(ble::connection_handle_t connectionHandle, ble::Keypress_t keypress) {
365  (void)connectionHandle;
366  (void)keypress;
367  }
368 #endif // BLE_FEATURE_SECURE_CONNECTIONS
369 
370  /**
371  * Indicate to the application it needs to return legacy pairing OOB to the stack.
372  *
373  * @param[in] connectionHandle connection connectionHandle
374  */
375  virtual void legacyPairingOobRequest(ble::connection_handle_t connectionHandle) {
376  (void)connectionHandle;
377  }
378 
379  /**
380  * Indicate that the application needs to send legacy pairing OOB data to the peer.
381  *
382  * @param[in] address address that will be used in the pairing
383  * @param[in] temporaryKey temporary key to be used in legacy pairing
384  */
385  virtual void legacyPairingOobGenerated(const ble::address_t *address,
386  const ble::oob_tk_t *temporaryKey) {
387  (void)address;
388  (void)temporaryKey;
389  }
390 
391  /**
392  * Indicate that the application needs to send secure connections OOB data to the peer.
393  *
394  * @param[in] address address that will be used in the pairing
395  * @param[in] random random number used to generate the confirmation
396  * @param[in] confirm confirmation value to be use for authentication
397  * in secure connections pairing
398  */
399  virtual void oobGenerated(const ble::address_t *address,
400  const ble::oob_lesc_value_t *random,
401  const ble::oob_confirm_t *confirm) {
402  (void)address;
403  (void)random;
404  (void)confirm;
405  }
406 
407  ////////////////////////////////////////////////////////////////////////////
408  // Keys
409  //
410 
411 #if BLE_FEATURE_SIGNING
412  /**
413  * Deliver the signing key to the application.
414  *
415  * @param[in] connectionHandle connection connectionHandle
416  * @param[in] csrk signing key, pointer only valid during call
417  * @param[in] authenticated indicates if the signing key is authenticated
418  */
419  virtual void signingKey(ble::connection_handle_t connectionHandle, const ble::csrk_t *csrk, bool authenticated) {
420  (void)connectionHandle;
421  (void)csrk;
422  (void)authenticated;
423  }
424 #endif // BLE_FEATURE_SIGNING
425 
426  /**
427  * Prevent polymorphic deletion and avoid unnecessary virtual destructor
428  * as the SecurityManager class will never delete the instance it contains.
429  */
430  ~EventHandler() = default;
431  };
432 
433  /*
434  * The following functions are meant to be overridden in the platform-specific sub-class.
435  */
436 public:
437  ////////////////////////////////////////////////////////////////////////////
438  // SM lifecycle management
439  //
440 
441  /**
442  * Enable the BLE stack's Security Manager. The Security Manager implements
443  * the actual cryptographic algorithms and protocol exchanges that allow two
444  * devices to securely exchange data and privately detect each other.
445  * Calling this API is a prerequisite for encryption and pairing (bonding).
446  *
447  * @param[in] enableBonding Allow for bonding.
448  * @param[in] requireMITM Require protection for man-in-the-middle attacks.
449  * @param[in] iocaps To specify the I/O capabilities of this peripheral,
450  * such as availability of a display or keyboard, to
451  * support out-of-band exchanges of security data.
452  * @param[in] passkey To specify a static passkey.
453  * @param[in] signing Generate and distribute signing key during pairing
454  * @param[in] dbFilepath Path to the file used to store keys in the filesystem,
455  * if NULL keys will be only stored in memory
456  *
457  *
458  * @return BLE_ERROR_NONE on success.
459  */
460  ble_error_t init(
461  bool enableBonding = true,
462  bool requireMITM = true,
463  SecurityIOCapabilities_t iocaps = IO_CAPS_NONE,
464  const Passkey_t passkey = nullptr,
465  bool signing = true,
466  const char *dbFilepath = nullptr
467  );
468 
469  /**
470  * Change the file used for the security database. If path is invalid or a NULL is passed
471  * keys will only be stored in memory.
472  *
473  * @note This operation is only allowed with no active connections.
474  *
475  * @param[in] dbFilepath Path to the file used to store keys in the filesystem,
476  * if NULL keys will be only stored in memory
477  *
478  * @return BLE_ERROR_NONE on success.
479  */
480  ble_error_t setDatabaseFilepath(const char *dbFilepath = nullptr);
481 
482  /**
483  * Notify all registered onShutdown callbacks that the SecurityManager is
484  * about to be shutdown and clear all SecurityManager state of the
485  * associated object.
486  *
487  * This function is meant to be overridden in the platform-specific
488  * sub-class. Nevertheless, the sub-class is only expected to reset its
489  * state and not the data held in SecurityManager members. This shall be
490  * achieved by a call to SecurityManager::reset() from the sub-class'
491  * reset() implementation.
492  *
493  * @return BLE_ERROR_NONE on success.
494  */
495  ble_error_t reset();
496 
497  /**
498  * Normally all bonding information is lost when device is reset, this requests that the stack
499  * attempts to save the information and reload it during initialisation. This is not guaranteed.
500  *
501  * @param[in] enable if true the stack will attempt to preserve bonding information on reset.
502  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
503  */
504  ble_error_t preserveBondingStateOnReset(bool enable);
505 
506  ////////////////////////////////////////////////////////////////////////////
507  // List management
508  //
509 
510  /**
511  * Delete all peer device context and all related bonding information from
512  * the database within the security manager.
513  *
514  * @retval BLE_ERROR_NONE On success, else an error code indicating reason for failure.
515  * @retval BLE_ERROR_INVALID_STATE If the API is called without module initialization or
516  * application registration.
517  */
518  ble_error_t purgeAllBondingState();
519 
520  /**
521  * Create a list of addresses from all peers in the bond table and generate
522  * an event which returns it as a whitelist. Pass in the container for the whitelist.
523  * This will be returned by the event.
524  *
525  * @param[in] whitelist Preallocated whitelist which will be filled up to its capacity.
526  * If whitelist already contains entries this will be appended to.
527  * Do not access the whitelist until callback has been called,
528  * returning the filled whitelist.
529  *
530  * @retval BLE_ERROR_NONE On success, else an error code indicating reason for failure
531  */
532  ble_error_t generateWhitelistFromBondTable(::ble::whitelist_t *whitelist) const;
533 
534  ////////////////////////////////////////////////////////////////////////////
535  // Pairing
536  //
537 
538 #if BLE_ROLE_CENTRAL
539  /**
540  * Request pairing with the peer. Called by the master.
541  * @note Slave can call requestAuthentication or setLinkEncryption to achieve security.
542  *
543  * @param[in] connectionHandle Handle to identify the connection.
544  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
545  */
546  ble_error_t requestPairing(ble::connection_handle_t connectionHandle);
547 #endif // BLE_ROLE_CENTRAL
548 
549 #if BLE_ROLE_PERIPHERAL
550  /**
551  * Accept the pairing request. Called as a result of pairingRequest being called
552  * on the event handler.
553  *
554  * @param[in] connectionHandle Handle to identify the connection.
555  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
556  */
557  ble_error_t acceptPairingRequest(ble::connection_handle_t connectionHandle);
558 #endif // BLE_ROLE_PERIPHERAL
559 
560  /**
561  * Reject pairing request if the local device is the slave or cancel an outstanding
562  * pairing request if master.
563  *
564  * @param[in] connectionHandle Handle to identify the connection.
565  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
566  */
567  ble_error_t cancelPairingRequest(ble::connection_handle_t connectionHandle);
568 
569  /**
570  * Tell the stack whether the application needs to authorise pairing requests or should
571  * they be automatically accepted.
572  *
573  * @param[in] required If set to true, pairingRequest in the event handler will
574  * will be called and will require an action from the application
575  * to continue with pairing by calling acceptPairingRequest
576  * or cancelPairingRequest if the user wishes to reject it.
577  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
578  */
579  ble_error_t setPairingRequestAuthorisation(bool required = true);
580 
581  /**
582  * Retrieve identity address for the peer on the given connection.
583  *
584  * @param[in] connectionHandle Handle to identify the connection.
585  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
586  */
587  ble_error_t getPeerIdentity(ble::connection_handle_t connectionHandle);
588 
589  ////////////////////////////////////////////////////////////////////////////
590  // Feature support
591  //
592 
593 #if BLE_FEATURE_SECURE_CONNECTIONS
594  /**
595  * Allow of disallow the use of legacy pairing in case the application only wants
596  * to force the use of Secure Connections. If legacy pairing is disallowed and either
597  * side doesn't support Secure Connections the pairing will fail.
598  *
599  * @param[out] allow If true legacy pairing will be used if either side doesn't support Secure Connections.
600  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
601  */
602  ble_error_t allowLegacyPairing(bool allow = true);
603 
604  /**
605  * Check if the Secure Connections feature is supported by the stack and controller.
606  *
607  * @param[out] enabled true if SC are supported
608  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
609  */
610  ble_error_t getSecureConnectionsSupport(bool *enabled);
611 #endif // BLE_FEATURE_SECURE_CONNECTIONS
612 
613  ////////////////////////////////////////////////////////////////////////////
614  // Security settings
615  //
616 
617  /**
618  * Set the IO capability of the local device.
619  *
620  * @param[in] iocaps type of IO capabilities available on the local device
621  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
622  */
623  ble_error_t setIoCapability(SecurityIOCapabilities_t iocaps);
624 
625  /**
626  * Set the passkey that is displayed on the local device instead of using
627  * a randomly generated one
628  *
629  * @param[in] passkey ASCII string of 6 digits
630  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
631  */
632  ble_error_t setDisplayPasskey(const Passkey_t passkey);
633 
634  /**
635  * Set the security mode on a connection. Useful for elevating the security mode
636  * once certain conditions are met, e.g., a particular service is found.
637  *
638  * @param[in] connectionHandle Handle to identify the connection.
639  * @param[in] securityMode Requested security mode.
640  *
641  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
642  */
643  ble_error_t setLinkSecurity(ble::connection_handle_t connectionHandle, SecurityMode_t securityMode);
644 
645  /**
646  * Set whether or not we want to send and receive keypress notifications
647  * during passkey entry.
648  *
649  * @param[in] enabled if true pairing will try to enable keypress notifications
650  * (dependent on other side supporting it)
651  *
652  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
653  */
654  ble_error_t setKeypressNotification(bool enabled = true);
655 
656 #if BLE_FEATURE_SIGNING
657  /**
658  * Request generation and exchange of signing keys so that packet signing can be utilised
659  * on this connection.
660  * @note This does not generate a signingKey event. Use getSigningKey for that.
661  *
662  * @param[in] connectionHandle Handle to identify the connection.
663  * @param[in] enabled If set to true, signing keys will be exchanged
664  * during subsequent pairing.
665  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
666  */
667  ble_error_t enableSigning(ble::connection_handle_t connectionHandle, bool enabled = true);
668 #endif // BLE_FEATURE_SIGNING
669 
670  /**
671  * Give a hint to the stack that the master/slave role might change in the future.
672  *
673  * @param[in] enable If set to true it hints the roles are likely to swap in the future.
674  *
675  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
676  */
677  ble_error_t setHintFutureRoleReversal(bool enable = true);
678 
679  ////////////////////////////////////////////////////////////////////////////
680  // Encryption
681  //
682 
683  /**
684  * Current state of encryption on the link.
685  *
686  * @param[in] connectionHandle Handle to identify the connection.
687  * @param[out] encryption
688  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
689  */
690  ble_error_t getLinkEncryption(ble::connection_handle_t connectionHandle, ble::link_encryption_t *encryption);
691 
692  /**
693  * Enabled or disable encryption on the link. The result of this request will be indicated
694  * by a call to linkEncryptionResult in the event handler when the action is completed.
695  *
696  * @param[in] connectionHandle Handle to identify the connection.
697  * @param[in] encryption encryption state requested
698  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
699  */
700  ble_error_t setLinkEncryption(ble::connection_handle_t connectionHandle, ble::link_encryption_t encryption);
701 
702  /**
703  * Set the requirements for encryption key size. If the peer cannot comply with the requirements
704  * paring will fail.
705  *
706  * @param[in] minimumByteSize Smallest allowed encryption key size in bytes. (no smaller than 7)
707  * @param[in] maximumByteSize Largest allowed encryption key size in bytes. (no larger than 16)
708  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
709  */
710  ble_error_t setEncryptionKeyRequirements(uint8_t minimumByteSize, uint8_t maximumByteSize);
711 
712  /**
713  * Get encryption key size for given connection.
714  *
715  * @param[in] connectionHandle Handle to identify the connection.
716  * @param[out] size Returns the key size in bits.
717  *
718  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
719  */
720  ble_error_t getEncryptionKeySize(
721  connection_handle_t connectionHandle,
722  uint8_t *size
723  );
724 
725  ////////////////////////////////////////////////////////////////////////////
726  // Authentication
727  //
728 
729  /**
730  * Request that the link be authenticated (keys with MITM protection). This might trigger encryption
731  * or pairing/re-pairing. The success will be indicated through an event indicating security level change.
732  *
733  * @param[in] connectionHandle Handle to identify the connection.
734  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
735  */
736  ble_error_t requestAuthentication(ble::connection_handle_t connectionHandle);
737 
738  ////////////////////////////////////////////////////////////////////////////
739  // MITM
740  //
741 
742  /**
743  * Generate OOB data with the given address. If Secure Connections is supported this will
744  * also generate Secure Connections OOB data on top of legacy pairing OOB data. This can be used
745  * to generate such data before the connection takes place.
746  *
747  * In this model the OOB exchange takes place before the devices connect. Devices should establish
748  * communication over another channel and exchange the OOB data. The address provided will be used
749  * by the peer to associate the received data with the address of the device it will then connect
750  * to over BLE.
751  *
752  * @param[in] address The local address you will use in the connection using this OOB data. This
753  * address will be returned along with the rest of the OOB data when generation
754  * is complete. Using an invalid address is illegal.
755  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
756  */
757  ble_error_t generateOOB(const ble::address_t *address);
758 
759  /**
760  * Enable OOB data usage during paring. If Secure Connections is supported enabling useOOB will
761  * generate Secure Connections OOB data through oobGenerated() on top of legacy pairing OOB data.
762  *
763  * You do not have to call this function to return received OOB data. Use legacyPairingOobReceived
764  * or oobReceived to hand it in. This will allow the stack to use it if possible. You only need to
765  * call this function to attempt legacy OOB data exchange after pairing start and to inform
766  * the stack OOB data does not provide MITM protection (by default it is set to provide this).
767  *
768  * In this model the OOB exchange takes places after the devices have connected but possibly
769  * prior to pairing. For secure connections pairing must not be started until after the OOB
770  * data has been sent and/or received. The address in the OOB data generated will match
771  * the original address used to establish the connection and will be used by the peer to
772  * identify which connection the OOB data belongs to.
773  *
774  * @param[in] connectionHandle Handle to identify the connection.
775  * @param[in] useOOB If set to true, authenticate using OOB data.
776  * @param[in] OOBProvidesMITM If set to true keys exchanged during pairing using OOB data
777  * will provide Man-in-the-Middle protection. This indicates that
778  * the form of exchange used by the OOB data itself provides MITM
779  * protection.
780  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
781  */
782  ble_error_t setOOBDataUsage(ble::connection_handle_t connectionHandle, bool useOOB, bool OOBProvidesMITM = true);
783 
784 #if BLE_FEATURE_SECURE_CONNECTIONS
785  /**
786  * Report to the stack if the passkey matches or not. Used during pairing to provide MITM protection.
787  *
788  * @param[in] connectionHandle Handle to identify the connection.
789  * @param[in] confirmation True value indicates the passkey displayed matches.
790  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
791  */
792  ble_error_t confirmationEntered(ble::connection_handle_t connectionHandle, bool confirmation);
793 #endif // BLE_FEATURE_SECURE_CONNECTIONS
794 
795  /**
796  * Supply the stack with the user entered passkey.
797  *
798  * @param[in] connectionHandle Handle to identify the connection.
799  * @param[in] passkey ASCII string of digits entered by the user.
800  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
801  */
802  ble_error_t passkeyEntered(ble::connection_handle_t connectionHandle, Passkey_t passkey);
803 
804 #if BLE_FEATURE_SECURE_CONNECTIONS
805  /**
806  * Send a notification to the peer that the user pressed a key on the local device.
807  * @note This will only be delivered if the keypress notifications have been enabled during pairing.
808  *
809  * @param[in] connectionHandle Handle to identify the connection.
810  * @param[in] keypress Type of keypress event.
811  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
812  */
813  ble_error_t sendKeypressNotification(ble::connection_handle_t connectionHandle, ble::Keypress_t keypress);
814 #endif // BLE_FEATURE_SECURE_CONNECTIONS
815 
816  /**
817  * Supply the stack with the OOB data for legacy connections.
818  *
819  * @param[in] address address of the peer device this data comes from
820  * @param[in] tk pointer to out of band data received containing the temporary key.
821  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
822  */
823  ble_error_t legacyPairingOobReceived(const ble::address_t *address, const ble::oob_tk_t *tk);
824 
825 #if BLE_FEATURE_SECURE_CONNECTIONS
826  /**
827  * Supply the stack with the OOB data for secure connections.
828  *
829  * @param[in] address address of the peer device this data comes from
830  * @param[in] random random number used to generate the confirmation
831  * @param[in] confirm confirmation value to be use for authentication
832  * in secure connections pairing
833  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
834  */
835  ble_error_t oobReceived(const ble::address_t *address, const ble::oob_lesc_value_t *random, const ble::oob_confirm_t *confirm);
836 #endif // BLE_FEATURE_SECURE_CONNECTIONS
837 
838  ////////////////////////////////////////////////////////////////////////////
839  // Keys
840  //
841 
842 #if BLE_FEATURE_SIGNING
843  /**
844  * Retrieves a signing key through a signingKey event.
845  * If a signing key is not present, pairing/authentication will be attempted.
846  * @note This will attempt to retrieve the key even if enableSigning hasn't been called prior to pairing.
847  *
848  * @param[in] connectionHandle Handle to identify the connection.
849  * @param[in] authenticated Whether the signing key needs to be authenticated
850  * (provide MITM protection).
851  *
852  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
853  */
854  ble_error_t getSigningKey(ble::connection_handle_t connectionHandle, bool authenticated);
855 #endif // BLE_FEATURE_SIGNING
856 
857  ////////////////////////////////////////////////////////////////////////////
858  // Privacy
859  //
860 
861 #if BLE_FEATURE_PRIVACY
862  /**
863  * Sets how often the address is rotated when privacy is enabled.
864  *
865  * @param[in] timeout_in_seconds How many seconds to wait before starting generation of a new address.
866  *
867  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
868  */
869  ble_error_t setPrivateAddressTimeout(
870  uint16_t timeout_in_seconds
871  );
872 #endif // BLE_FEATURE_PRIVACY
873 
874  /* Event callback handlers. */
875 public:
876  /**
877  * Setup a callback to be invoked to notify the user application that the
878  * SecurityManager instance is about to shutdown (possibly as a result of a call
879  * to BLE::shutdown()).
880  *
881  * @note It is possible to chain together multiple onShutdown callbacks
882  * (potentially from different modules of an application) to be notified
883  * before the SecurityManager is shutdown.
884  *
885  * @note It is also possible to set up a callback into a member function of
886  * some object.
887  *
888  * @note It is possible to unregister a callback using onShutdown().detach(callback)
889  */
890  void onShutdown(const SecurityManagerShutdownCallback_t& callback);
891 
892  template <typename T>
893  void onShutdown(T *objPtr, void (T::*memberPtr)(const SecurityManager *))
894  {
895  onShutdown({objPtr, memberPtr});
896  }
897 
898  /**
899  * Provide access to the callchain of shutdown event callbacks.
900  * It is possible to register callbacks using onShutdown().add(callback).
901  * It is possible to unregister callbacks using onShutdown().detach(callback).
902  *
903  * @return The shutdown event callbacks chain
904  */
905  SecurityManagerShutdownCallbackChain_t& onShutdown();
906 
907  /**
908  * Assign the event handler implementation that will be used by the stack to signal events
909  * back to the application.
910  *
911  * @param[in] handler Event Handler interface implementation.
912  */
913  void setSecurityManagerEventHandler(EventHandler* handler);
914 
915 public:
916 #if !defined(DOXYGEN_ONLY)
917  /** For backwards compatibility. This enum is now in BLETypes.h
918  * @deprecated use the enum in ble namespace */
919  typedef ble::Keypress_t Keypress_t;
920 
921  SecurityManager(impl::SecurityManager* impl) : impl(impl) {}
922  SecurityManager(const SecurityManager&) = delete;
923  SecurityManager& operator=(const SecurityManager&) = delete;
924 #endif // !defined(DOXYGEN_ONLY)
925 
926 private:
927  impl::SecurityManager *impl;
928 };
929 
930 } // ble
931 
932 /** @deprecated Use the namespaced ble::SecurityManager instead of the global SecurityManager. */
934 
935 #endif /*BLE_SECURITY_MANAGER_H_*/
Function like object adapter over freestanding and member functions.
uintptr_t connection_handle_t
Opaque reference to a connection.
Model fixed size array values.
virtual void passkeyRequest(ble::connection_handle_t connectionHandle)
Indicate to the application that a passkey is required.
virtual void legacyPairingOobRequest(ble::connection_handle_t connectionHandle)
Indicate to the application it needs to return legacy pairing OOB to the stack.
Keypress_t
events sent and received when passkey is being entered
Require encryption, but no MITM protection.
Representation of a whitelist of addresses.
Callback< R(ArgTs...)> callback(R(*func)(ArgTs...)=nullptr) noexcept
Create a callback class with type inferred from the arguments.
Definition: Callback.h:678
MAC address data type.
virtual void pairingRequest(ble::connection_handle_t connectionHandle)
Request application to accept or reject pairing.
virtual void whitelistFromBondTable(::ble::whitelist_t *whitelist)
Deliver the requested whitelist to the application.
SecurityMode_t
level of security required from the link by the application
Require signing or encryption, but no MITM protection.
SecurityIOCapabilities_t
Input/output capability of the device and application.
virtual void keypressNotification(ble::connection_handle_t connectionHandle, ble::Keypress_t keypress)
Notify the application that a key was pressed by the peer during passkey entry.
Require signing or encryption, and MITM protection.
virtual void oobGenerated(const ble::address_t *address, const ble::oob_lesc_value_t *random, const ble::oob_confirm_t *confirm)
Indicate that the application needs to send secure connections OOB data to the peer.
Require encryption and MITM protection.
virtual void linkEncryptionResult(ble::connection_handle_t connectionHandle, ble::link_encryption_t result)
Inform the device of the encryption state of a given link.
SecurityCompletionStatus_t
Result of security requests.
Function like object hosting a list of FunctionPointerWithContext.
virtual void legacyPairingOobGenerated(const ble::address_t *address, const ble::oob_tk_t *temporaryKey)
Indicate that the application needs to send legacy pairing OOB data to the peer.
virtual void signingKey(ble::connection_handle_t connectionHandle, const ble::csrk_t *csrk, bool authenticated)
Deliver the signing key to the application.
virtual void pairingResult(ble::connection_handle_t connectionHandle, SecurityCompletionStatus_t result)
Indicate to the application that pairing has completed.
The stack will use these functions to signal events to the application, subclass to override handlers...
Entry namespace for all BLE API definitions.
virtual void peerIdentity(ble::connection_handle_t connectionHandle, const address_t *peer_address, bool address_is_public)
Indicate that a peer address has been saved by the security manager or if we are bonded to the peer t...
virtual void passkeyDisplay(ble::connection_handle_t connectionHandle, const Passkey_t passkey)
Display the given passkey on the local device.
virtual void confirmationRequest(ble::connection_handle_t connectionHandle)
Indicate to the application that a confirmation is required.
ble_error_t
Error codes for the BLE API.
Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.