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

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