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