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 #if BLE_PASSKEY_DISPLAY_REVERSED_DIGITS_DEPRECATION
328  MBED_DEPRECATED_SINCE("mbed-os-6.8.0", "This returns the passkey in reverse order. Please set the config option ble.ble-passkey-display-reversed-digits-deprecation in your mbed_app.json override section to false. This will then return the passkey in the correct order.")
329 #endif // BLE_PASSKEY_DISPLAY_REVERSED_DIGITS_DEPRECATION
330  virtual void passkeyDisplay(ble::connection_handle_t connectionHandle, const Passkey_t passkey) {
331  (void)connectionHandle;
332  (void)passkey;
333  }
334 
335 #if BLE_FEATURE_SECURE_CONNECTIONS
336  /**
337  * Indicate to the application that a confirmation is required. This is used
338  * when the device does not have a keyboard but has a yes/no button. The device
339  * displays numbers on its display in response to passkeyDisplay and the user
340  * checks if they are the same on both devices. The application should proceed
341  * by supplying the confirmation using the confirmationEntered function.
342  *
343  * @param[in] connectionHandle connection connectionHandle
344  */
345  virtual void confirmationRequest(ble::connection_handle_t connectionHandle) {
346  (void)connectionHandle;
347  }
348 #endif // BLE_FEATURE_SECURE_CONNECTIONS
349 
350  /**
351  * Indicate to the application that a passkey is required. The application should
352  * proceed by supplying the passkey through the passkeyEntered function.
353  *
354  * @param[in] connectionHandle connection connectionHandle
355  */
356  virtual void passkeyRequest(ble::connection_handle_t connectionHandle) {
357  (void)connectionHandle;
358  }
359 
360 #if BLE_FEATURE_SECURE_CONNECTIONS
361  /**
362  * Notify the application that a key was pressed by the peer during passkey entry.
363  *
364  * @param[in] connectionHandle connection connectionHandle
365  * @param[in] keypress type of keypress event
366  */
367  virtual void keypressNotification(ble::connection_handle_t connectionHandle, ble::Keypress_t keypress) {
368  (void)connectionHandle;
369  (void)keypress;
370  }
371 #endif // BLE_FEATURE_SECURE_CONNECTIONS
372 
373  /**
374  * Indicate to the application it needs to return legacy pairing OOB to the stack.
375  *
376  * @param[in] connectionHandle connection connectionHandle
377  */
378  virtual void legacyPairingOobRequest(ble::connection_handle_t connectionHandle) {
379  (void)connectionHandle;
380  }
381 
382  /**
383  * Indicate that the application needs to send legacy pairing OOB data to the peer.
384  *
385  * @param[in] address address that will be used in the pairing
386  * @param[in] temporaryKey temporary key to be used in legacy pairing
387  */
388  virtual void legacyPairingOobGenerated(const ble::address_t *address,
389  const ble::oob_tk_t *temporaryKey) {
390  (void)address;
391  (void)temporaryKey;
392  }
393 
394  /**
395  * Indicate that the application needs to send secure connections OOB data to the peer.
396  *
397  * @param[in] address address that will be used in the pairing
398  * @param[in] random random number used to generate the confirmation
399  * @param[in] confirm confirmation value to be use for authentication
400  * in secure connections pairing
401  */
402  virtual void oobGenerated(const ble::address_t *address,
403  const ble::oob_lesc_value_t *random,
404  const ble::oob_confirm_t *confirm) {
405  (void)address;
406  (void)random;
407  (void)confirm;
408  }
409 
410  ////////////////////////////////////////////////////////////////////////////
411  // Keys
412  //
413 
414 #if BLE_FEATURE_SIGNING
415  /**
416  * Deliver the signing key to the application.
417  *
418  * @param[in] connectionHandle connection connectionHandle
419  * @param[in] csrk signing key, pointer only valid during call
420  * @param[in] authenticated indicates if the signing key is authenticated
421  */
422  virtual void signingKey(ble::connection_handle_t connectionHandle, const ble::csrk_t *csrk, bool authenticated) {
423  (void)connectionHandle;
424  (void)csrk;
425  (void)authenticated;
426  }
427 #endif // BLE_FEATURE_SIGNING
428 
429  /**
430  * Prevent polymorphic deletion and avoid unnecessary virtual destructor
431  * as the SecurityManager class will never delete the instance it contains.
432  */
433  ~EventHandler() = default;
434  };
435 
436  /*
437  * The following functions are meant to be overridden in the platform-specific sub-class.
438  */
439 public:
440  ////////////////////////////////////////////////////////////////////////////
441  // SM lifecycle management
442  //
443 
444  /**
445  * Enable the BLE stack's Security Manager. The Security Manager implements
446  * the actual cryptographic algorithms and protocol exchanges that allow two
447  * devices to securely exchange data and privately detect each other.
448  * Calling this API is a prerequisite for encryption and pairing (bonding).
449  *
450  * @param[in] enableBonding Allow for bonding.
451  * @param[in] requireMITM Require protection for man-in-the-middle attacks.
452  * @param[in] iocaps To specify the I/O capabilities of this peripheral,
453  * such as availability of a display or keyboard, to
454  * support out-of-band exchanges of security data.
455  * @param[in] passkey To specify a static passkey.
456  * @param[in] signing Generate and distribute signing key during pairing
457  * @param[in] dbFilepath Path to the file used to store keys in the filesystem,
458  * if NULL keys will be only stored in memory
459  *
460  *
461  * @return BLE_ERROR_NONE on success.
462  */
463  ble_error_t init(
464  bool enableBonding = true,
465  bool requireMITM = true,
466  SecurityIOCapabilities_t iocaps = IO_CAPS_NONE,
467  const Passkey_t passkey = nullptr,
468  bool signing = true,
469  const char *dbFilepath = nullptr
470  );
471 
472  /**
473  * Change the file used for the security database. If path is invalid or a NULL is passed
474  * keys will only be stored in memory.
475  *
476  * @note This operation is only allowed with no active connections.
477  *
478  * @param[in] dbFilepath Path to the file used to store keys in the filesystem,
479  * if NULL keys will be only stored in memory
480  *
481  * @return BLE_ERROR_NONE on success.
482  */
483  ble_error_t setDatabaseFilepath(const char *dbFilepath = nullptr);
484 
485  /**
486  * Notify all registered onShutdown callbacks that the SecurityManager is
487  * about to be shutdown and clear all SecurityManager state of the
488  * associated object.
489  *
490  * This function is meant to be overridden in the platform-specific
491  * sub-class. Nevertheless, the sub-class is only expected to reset its
492  * state and not the data held in SecurityManager members. This shall be
493  * achieved by a call to SecurityManager::reset() from the sub-class'
494  * reset() implementation.
495  *
496  * @return BLE_ERROR_NONE on success.
497  */
498  ble_error_t reset();
499 
500  /**
501  * Normally all bonding information is lost when device is reset, this requests that the stack
502  * attempts to save the information and reload it during initialisation. This is not guaranteed.
503  *
504  * @param[in] enable if true the stack will attempt to preserve bonding information on reset.
505  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
506  */
507  ble_error_t preserveBondingStateOnReset(bool enable);
508 
509  ////////////////////////////////////////////////////////////////////////////
510  // List management
511  //
512 
513  /**
514  * Delete all peer device context and all related bonding information from
515  * the database within the security manager.
516  *
517  * @retval BLE_ERROR_NONE On success, else an error code indicating reason for failure.
518  * @retval BLE_ERROR_INVALID_STATE If the API is called without module initialization or
519  * application registration.
520  */
521  ble_error_t purgeAllBondingState();
522 
523  /**
524  * Create a list of addresses from all peers in the bond table and generate
525  * an event which returns it as a whitelist. Pass in the container for the whitelist.
526  * This will be returned by the event.
527  *
528  * @param[in] whitelist Preallocated whitelist which will be filled up to its capacity.
529  * If whitelist already contains entries this will be appended to.
530  * Do not access the whitelist until callback has been called,
531  * returning the filled whitelist.
532  *
533  * @retval BLE_ERROR_NONE On success, else an error code indicating reason for failure
534  */
535  ble_error_t generateWhitelistFromBondTable(::ble::whitelist_t *whitelist) const;
536 
537  ////////////////////////////////////////////////////////////////////////////
538  // Pairing
539  //
540 
541 #if BLE_ROLE_CENTRAL
542  /**
543  * Request pairing with the peer. Called by the master.
544  * @note Slave can call requestAuthentication or setLinkEncryption to achieve security.
545  *
546  * @param[in] connectionHandle Handle to identify the connection.
547  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
548  */
549  ble_error_t requestPairing(ble::connection_handle_t connectionHandle);
550 #endif // BLE_ROLE_CENTRAL
551 
552 #if BLE_ROLE_PERIPHERAL
553  /**
554  * Accept the pairing request. Called as a result of pairingRequest being called
555  * on the event handler.
556  *
557  * @param[in] connectionHandle Handle to identify the connection.
558  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
559  */
560  ble_error_t acceptPairingRequest(ble::connection_handle_t connectionHandle);
561 #endif // BLE_ROLE_PERIPHERAL
562 
563  /**
564  * Reject pairing request if the local device is the slave or cancel an outstanding
565  * pairing request if master.
566  *
567  * @param[in] connectionHandle Handle to identify the connection.
568  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
569  */
570  ble_error_t cancelPairingRequest(ble::connection_handle_t connectionHandle);
571 
572  /**
573  * Tell the stack whether the application needs to authorise pairing requests or should
574  * they be automatically accepted.
575  *
576  * @param[in] required If set to true, pairingRequest in the event handler will
577  * will be called and will require an action from the application
578  * to continue with pairing by calling acceptPairingRequest
579  * or cancelPairingRequest if the user wishes to reject it.
580  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
581  */
582  ble_error_t setPairingRequestAuthorisation(bool required = true);
583 
584  /**
585  * Retrieve identity address for the peer on the given connection.
586  *
587  * @param[in] connectionHandle Handle to identify the connection.
588  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
589  */
590  ble_error_t getPeerIdentity(ble::connection_handle_t connectionHandle);
591 
592  ////////////////////////////////////////////////////////////////////////////
593  // Feature support
594  //
595 
596 #if BLE_FEATURE_SECURE_CONNECTIONS
597  /**
598  * Allow of disallow the use of legacy pairing in case the application only wants
599  * to force the use of Secure Connections. If legacy pairing is disallowed and either
600  * side doesn't support Secure Connections the pairing will fail.
601  *
602  * @param[out] allow If true legacy pairing will be used if either side doesn't support Secure Connections.
603  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
604  */
605  ble_error_t allowLegacyPairing(bool allow = true);
606 
607  /**
608  * Check if the Secure Connections feature is supported by the stack and controller.
609  *
610  * @param[out] enabled true if SC are supported
611  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
612  */
613  ble_error_t getSecureConnectionsSupport(bool *enabled);
614 #endif // BLE_FEATURE_SECURE_CONNECTIONS
615 
616  ////////////////////////////////////////////////////////////////////////////
617  // Security settings
618  //
619 
620  /**
621  * Set the IO capability of the local device.
622  *
623  * @param[in] iocaps type of IO capabilities available on the local device
624  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
625  */
626  ble_error_t setIoCapability(SecurityIOCapabilities_t iocaps);
627 
628  /**
629  * Set the passkey that is displayed on the local device instead of using
630  * a randomly generated one
631  *
632  * @param[in] passkey ASCII string of 6 digits
633  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
634  */
635  ble_error_t setDisplayPasskey(const Passkey_t passkey);
636 
637  /**
638  * Set the security mode on a connection. Useful for elevating the security mode
639  * once certain conditions are met, e.g., a particular service is found.
640  *
641  * @param[in] connectionHandle Handle to identify the connection.
642  * @param[in] securityMode Requested security mode.
643  *
644  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
645  */
646  ble_error_t setLinkSecurity(ble::connection_handle_t connectionHandle, SecurityMode_t securityMode);
647 
648  /**
649  * Set whether or not we want to send and receive keypress notifications
650  * during passkey entry.
651  *
652  * @param[in] enabled if true pairing will try to enable keypress notifications
653  * (dependent on other side supporting it)
654  *
655  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
656  */
657  ble_error_t setKeypressNotification(bool enabled = true);
658 
659 #if BLE_FEATURE_SIGNING
660  /**
661  * Request generation and exchange of signing keys so that packet signing can be utilised
662  * on this connection.
663  * @note This does not generate a signingKey event. Use getSigningKey for that.
664  *
665  * @param[in] connectionHandle Handle to identify the connection.
666  * @param[in] enabled If set to true, signing keys will be exchanged
667  * during subsequent pairing.
668  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
669  */
670  ble_error_t enableSigning(ble::connection_handle_t connectionHandle, bool enabled = true);
671 #endif // BLE_FEATURE_SIGNING
672 
673  /**
674  * Give a hint to the stack that the master/slave role might change in the future.
675  *
676  * @param[in] enable If set to true it hints the roles are likely to swap in the future.
677  *
678  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
679  */
680  ble_error_t setHintFutureRoleReversal(bool enable = true);
681 
682  ////////////////////////////////////////////////////////////////////////////
683  // Encryption
684  //
685 
686  /**
687  * Current state of encryption on the link.
688  *
689  * @param[in] connectionHandle Handle to identify the connection.
690  * @param[out] encryption
691  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
692  */
693  ble_error_t getLinkEncryption(ble::connection_handle_t connectionHandle, ble::link_encryption_t *encryption);
694 
695  /**
696  * Enabled or disable encryption on the link. The result of this request will be indicated
697  * by a call to linkEncryptionResult in the event handler when the action is completed.
698  *
699  * @param[in] connectionHandle Handle to identify the connection.
700  * @param[in] encryption encryption state requested
701  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
702  */
703  ble_error_t setLinkEncryption(ble::connection_handle_t connectionHandle, ble::link_encryption_t encryption);
704 
705  /**
706  * Set the requirements for encryption key size. If the peer cannot comply with the requirements
707  * paring will fail.
708  *
709  * @param[in] minimumByteSize Smallest allowed encryption key size in bytes. (no smaller than 7)
710  * @param[in] maximumByteSize Largest allowed encryption key size in bytes. (no larger than 16)
711  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
712  */
713  ble_error_t setEncryptionKeyRequirements(uint8_t minimumByteSize, uint8_t maximumByteSize);
714 
715  /**
716  * Get encryption key size for given connection.
717  *
718  * @param[in] connectionHandle Handle to identify the connection.
719  * @param[out] size Returns the key size in bits.
720  *
721  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
722  */
723  ble_error_t getEncryptionKeySize(
724  connection_handle_t connectionHandle,
725  uint8_t *size
726  );
727 
728  ////////////////////////////////////////////////////////////////////////////
729  // Authentication
730  //
731 
732  /**
733  * Request that the link be authenticated (keys with MITM protection). This might trigger encryption
734  * or pairing/re-pairing. The success will be indicated through an event indicating security level change.
735  *
736  * @param[in] connectionHandle Handle to identify the connection.
737  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
738  */
739  ble_error_t requestAuthentication(ble::connection_handle_t connectionHandle);
740 
741  ////////////////////////////////////////////////////////////////////////////
742  // MITM
743  //
744 
745  /**
746  * Generate OOB data with the given address. If Secure Connections is supported this will
747  * also generate Secure Connections OOB data on top of legacy pairing OOB data. This can be used
748  * to generate such data before the connection takes place.
749  *
750  * In this model the OOB exchange takes place before the devices connect. Devices should establish
751  * communication over another channel and exchange the OOB data. The address provided will be used
752  * by the peer to associate the received data with the address of the device it will then connect
753  * to over BLE.
754  *
755  * @param[in] address The local address you will use in the connection using this OOB data. This
756  * address will be returned along with the rest of the OOB data when generation
757  * is complete. Using an invalid address is illegal.
758  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
759  */
760  ble_error_t generateOOB(const ble::address_t *address);
761 
762  /**
763  * Enable OOB data usage during paring. If Secure Connections is supported enabling useOOB will
764  * generate Secure Connections OOB data through oobGenerated() on top of legacy pairing OOB data.
765  *
766  * You do not have to call this function to return received OOB data. Use legacyPairingOobReceived
767  * or oobReceived to hand it in. This will allow the stack to use it if possible. You only need to
768  * call this function to attempt legacy OOB data exchange after pairing start and to inform
769  * the stack OOB data does not provide MITM protection (by default it is set to provide this).
770  *
771  * In this model the OOB exchange takes places after the devices have connected but possibly
772  * prior to pairing. For secure connections pairing must not be started until after the OOB
773  * data has been sent and/or received. The address in the OOB data generated will match
774  * the original address used to establish the connection and will be used by the peer to
775  * identify which connection the OOB data belongs to.
776  *
777  * @param[in] connectionHandle Handle to identify the connection.
778  * @param[in] useOOB If set to true, authenticate using OOB data.
779  * @param[in] OOBProvidesMITM If set to true keys exchanged during pairing using OOB data
780  * will provide Man-in-the-Middle protection. This indicates that
781  * the form of exchange used by the OOB data itself provides MITM
782  * protection.
783  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
784  */
785  ble_error_t setOOBDataUsage(ble::connection_handle_t connectionHandle, bool useOOB, bool OOBProvidesMITM = true);
786 
787 #if BLE_FEATURE_SECURE_CONNECTIONS
788  /**
789  * Report to the stack if the passkey matches or not. Used during pairing to provide MITM protection.
790  *
791  * @param[in] connectionHandle Handle to identify the connection.
792  * @param[in] confirmation True value indicates the passkey displayed matches.
793  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
794  */
795  ble_error_t confirmationEntered(ble::connection_handle_t connectionHandle, bool confirmation);
796 #endif // BLE_FEATURE_SECURE_CONNECTIONS
797 
798  /**
799  * Supply the stack with the user entered passkey.
800  *
801  * @param[in] connectionHandle Handle to identify the connection.
802  * @param[in] passkey ASCII string of digits entered by the user.
803  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
804  */
805  ble_error_t passkeyEntered(ble::connection_handle_t connectionHandle, Passkey_t passkey);
806 
807 #if BLE_FEATURE_SECURE_CONNECTIONS
808  /**
809  * Send a notification to the peer that the user pressed a key on the local device.
810  * @note This will only be delivered if the keypress notifications have been enabled during pairing.
811  *
812  * @param[in] connectionHandle Handle to identify the connection.
813  * @param[in] keypress Type of keypress event.
814  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
815  */
816  ble_error_t sendKeypressNotification(ble::connection_handle_t connectionHandle, ble::Keypress_t keypress);
817 #endif // BLE_FEATURE_SECURE_CONNECTIONS
818 
819  /**
820  * Supply the stack with the OOB data for legacy connections.
821  *
822  * @param[in] address address of the peer device this data comes from
823  * @param[in] tk pointer to out of band data received containing the temporary key.
824  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
825  */
826  ble_error_t legacyPairingOobReceived(const ble::address_t *address, const ble::oob_tk_t *tk);
827 
828 #if BLE_FEATURE_SECURE_CONNECTIONS
829  /**
830  * Supply the stack with the OOB data for secure connections.
831  *
832  * @param[in] address address of the peer device this data comes from
833  * @param[in] random random number used to generate the confirmation
834  * @param[in] confirm confirmation value to be use for authentication
835  * in secure connections pairing
836  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
837  */
838  ble_error_t oobReceived(const ble::address_t *address, const ble::oob_lesc_value_t *random, const ble::oob_confirm_t *confirm);
839 #endif // BLE_FEATURE_SECURE_CONNECTIONS
840 
841  ////////////////////////////////////////////////////////////////////////////
842  // Keys
843  //
844 
845 #if BLE_FEATURE_SIGNING
846  /**
847  * Retrieves a signing key through a signingKey event.
848  * If a signing key is not present, pairing/authentication will be attempted.
849  * @note This will attempt to retrieve the key even if enableSigning hasn't been called prior to pairing.
850  *
851  * @param[in] connectionHandle Handle to identify the connection.
852  * @param[in] authenticated Whether the signing key needs to be authenticated
853  * (provide MITM protection).
854  *
855  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
856  */
857  ble_error_t getSigningKey(ble::connection_handle_t connectionHandle, bool authenticated);
858 #endif // BLE_FEATURE_SIGNING
859 
860  ////////////////////////////////////////////////////////////////////////////
861  // Privacy
862  //
863 
864 #if BLE_FEATURE_PRIVACY
865  /**
866  * Sets how often the address is rotated when privacy is enabled.
867  *
868  * @param[in] timeout_in_seconds How many seconds to wait before starting generation of a new address.
869  *
870  * @return BLE_ERROR_NONE or appropriate error code indicating the failure reason.
871  */
872  ble_error_t setPrivateAddressTimeout(
873  uint16_t timeout_in_seconds
874  );
875 #endif // BLE_FEATURE_PRIVACY
876 
877  /* Event callback handlers. */
878 public:
879  /**
880  * Setup a callback to be invoked to notify the user application that the
881  * SecurityManager instance is about to shutdown (possibly as a result of a call
882  * to BLE::shutdown()).
883  *
884  * @note It is possible to chain together multiple onShutdown callbacks
885  * (potentially from different modules of an application) to be notified
886  * before the SecurityManager is shutdown.
887  *
888  * @note It is also possible to set up a callback into a member function of
889  * some object.
890  *
891  * @note It is possible to unregister a callback using onShutdown().detach(callback)
892  */
893  void onShutdown(const SecurityManagerShutdownCallback_t& callback);
894 
895  template <typename T>
896  void onShutdown(T *objPtr, void (T::*memberPtr)(const SecurityManager *))
897  {
898  onShutdown({objPtr, memberPtr});
899  }
900 
901  /**
902  * Provide access to the callchain of shutdown event callbacks.
903  * It is possible to register callbacks using onShutdown().add(callback).
904  * It is possible to unregister callbacks using onShutdown().detach(callback).
905  *
906  * @return The shutdown event callbacks chain
907  */
908  SecurityManagerShutdownCallbackChain_t& onShutdown();
909 
910  /**
911  * Assign the event handler implementation that will be used by the stack to signal events
912  * back to the application.
913  *
914  * @param[in] handler Event Handler interface implementation.
915  */
916  void setSecurityManagerEventHandler(EventHandler* handler);
917 
918 public:
919 #if !defined(DOXYGEN_ONLY)
920  /** For backwards compatibility. This enum is now in BLETypes.h
921  * @deprecated use the enum in ble namespace */
922  typedef ble::Keypress_t Keypress_t;
923 
924  SecurityManager(impl::SecurityManager* impl) : impl(impl) {}
925  SecurityManager(const SecurityManager&) = delete;
926  SecurityManager& operator=(const SecurityManager&) = delete;
927 #endif // !defined(DOXYGEN_ONLY)
928 
929 private:
930  impl::SecurityManager *impl;
931 };
932 
933 } // ble
934 
935 /** @deprecated Use the namespaced ble::SecurityManager instead of the global SecurityManager. */
937 
938 #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.
#define MBED_DEPRECATED_SINCE(D, M)
MBED_DEPRECATED("message string") Mark a function declaration as deprecated, if it used then a warnin...
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.