Mbed OS Reference
Loading...
Searching...
No Matches
SecurityManager Class Reference

Overview. More...

#include <SecurityManager.h>

Data Structures

class  EventHandler
 The stack will use these functions to signal events to the application, subclass to override handlers. More...
 

Public Types

enum  SecurityMode_t {
}
 level of security required from the link by the application More...
 
enum  SecurityIOCapabilities_t {
  IO_CAPS_DISPLAY_ONLY = 0x00 , IO_CAPS_DISPLAY_YESNO = 0x01 , IO_CAPS_KEYBOARD_ONLY = 0x02 , IO_CAPS_NONE = 0x03 ,
  IO_CAPS_KEYBOARD_DISPLAY = 0x04
}
 Input/output capability of the device and application. More...
 
enum  SecurityCompletionStatus_t {
  SEC_STATUS_SUCCESS = 0x00 , SEC_STATUS_TIMEOUT = 0x01 , SEC_STATUS_PDU_INVALID = 0x02 , SEC_STATUS_PASSKEY_ENTRY_FAILED = 0x81 ,
  SEC_STATUS_OOB_NOT_AVAILABLE = 0x82 , SEC_STATUS_AUTH_REQ = 0x83 , SEC_STATUS_CONFIRM_VALUE = 0x84 , SEC_STATUS_PAIRING_NOT_SUPP = 0x85 ,
  SEC_STATUS_ENC_KEY_SIZE = 0x86 , SEC_STATUS_SMP_CMD_UNSUPPORTED = 0x87 , SEC_STATUS_UNSPECIFIED = 0x88 , SEC_STATUS_REPEATED_ATTEMPTS = 0x89 ,
  SEC_STATUS_INVALID_PARAMS = 0x8A , SEC_STATUS_DHKEY_CHECK_FAILED = 0x8B , SEC_STATUS_COMPARISON_FAILED = 0x8C
}
 Result of security requests. More...
 
typedef uint8_t Passkey_t[PASSKEY_LEN]
 6-digit passkey in ASCII ('0'-'9' digits only). More...
 

Public Member Functions

ble_error_t init (bool enableBonding=true, bool requireMITM=true, SecurityIOCapabilities_t iocaps=IO_CAPS_NONE, const Passkey_t passkey=nullptr, bool signing=true, const char *dbFilepath=nullptr)
 Enable the BLE stack's Security Manager. More...
 
ble_error_t setDatabaseFilepath (const char *dbFilepath=nullptr)
 Change the file used for the security database. More...
 
ble_error_t reset ()
 Notify all registered onShutdown callbacks that the SecurityManager is about to be shutdown and clear all SecurityManager state of the associated object. More...
 
ble_error_t preserveBondingStateOnReset (bool enable)
 Normally all bonding information is lost when device is reset, this requests that the stack attempts to save the information and reload it during initialisation. More...
 
ble_error_t writeBondingStateToPersistentStorage ()
 Some or all of bonding information may be stored in memory while in use. More...
 
ble_error_t purgeAllBondingState ()
 Delete all peer device context and all related bonding information from the database within the security manager. More...
 
ble_error_t generateWhitelistFromBondTable (::ble::whitelist_t *whitelist) const
 Create a list of addresses from all peers in the bond table and generate an event which returns it as a whitelist. More...
 
ble_error_t requestPairing (ble::connection_handle_t connectionHandle)
 Request pairing with the peer. More...
 
ble_error_t acceptPairingRequest (ble::connection_handle_t connectionHandle)
 Accept the pairing request. More...
 
ble_error_t cancelPairingRequest (ble::connection_handle_t connectionHandle)
 Reject pairing request if the local device is the slave or cancel an outstanding pairing request if master. More...
 
ble_error_t setPairingRequestAuthorisation (bool required=true)
 Tell the stack whether the application needs to authorise pairing requests or should they be automatically accepted. More...
 
ble_error_t getPeerIdentity (ble::connection_handle_t connectionHandle)
 Retrieve identity address for the peer on the given connection. More...
 
ble_error_t allowLegacyPairing (bool allow=true)
 Allow or disallow the use of legacy pairing in case the application only wants to force the use of Secure Connections. More...
 
ble_error_t getSecureConnectionsSupport (bool *enabled)
 Check if the Secure Connections feature is supported by the stack and controller. More...
 
ble_error_t setIoCapability (SecurityIOCapabilities_t iocaps)
 Set the IO capability of the local device. More...
 
ble_error_t setDisplayPasskey (const Passkey_t passkey)
 Set the passkey that is displayed on the local device instead of using a randomly generated one. More...
 
ble_error_t setLinkSecurity (ble::connection_handle_t connectionHandle, SecurityMode_t securityMode)
 Set the security mode on a connection. More...
 
ble_error_t setKeypressNotification (bool enabled=true)
 Set whether or not we want to send and receive keypress notifications during passkey entry. More...
 
ble_error_t enableSigning (ble::connection_handle_t connectionHandle, bool enabled=true)
 Request generation and exchange of signing keys so that packet signing can be utilised on this connection. More...
 
ble_error_t setHintFutureRoleReversal (bool enable=true)
 Give a hint to the stack that the master/slave role might change in the future. More...
 
ble_error_t getLinkEncryption (ble::connection_handle_t connectionHandle, ble::link_encryption_t *encryption)
 Current state of encryption on the link. More...
 
ble_error_t setLinkEncryption (ble::connection_handle_t connectionHandle, ble::link_encryption_t encryption)
 Enabled or disable encryption on the link. More...
 
ble_error_t setEncryptionKeyRequirements (uint8_t minimumByteSize, uint8_t maximumByteSize)
 Set the requirements for encryption key size. More...
 
ble_error_t getEncryptionKeySize (connection_handle_t connectionHandle, uint8_t *size)
 Get encryption key size for given connection. More...
 
ble_error_t requestAuthentication (ble::connection_handle_t connectionHandle)
 Request that the link be authenticated (keys with MITM protection). More...
 
ble_error_t generateOOB (const ble::address_t *address)
 Generate OOB data with the given address. More...
 
ble_error_t setOOBDataUsage (ble::connection_handle_t connectionHandle, bool useOOB, bool OOBProvidesMITM=true)
 Enable OOB data usage during paring. More...
 
ble_error_t confirmationEntered (ble::connection_handle_t connectionHandle, bool confirmation)
 Report to the stack if the passkey matches or not. More...
 
ble_error_t passkeyEntered (ble::connection_handle_t connectionHandle, Passkey_t passkey)
 Supply the stack with the user entered passkey. More...
 
ble_error_t sendKeypressNotification (ble::connection_handle_t connectionHandle, ble::Keypress_t keypress)
 Send a notification to the peer that the user pressed a key on the local device. More...
 
ble_error_t legacyPairingOobReceived (const ble::address_t *address, const ble::oob_tk_t *tk)
 Supply the stack with the OOB data for legacy connections. More...
 
ble_error_t oobReceived (const ble::address_t *address, const ble::oob_lesc_value_t *random, const ble::oob_confirm_t *confirm)
 Supply the stack with the OOB data for secure connections. More...
 
ble_error_t getSigningKey (ble::connection_handle_t connectionHandle, bool authenticated)
 Retrieves a signing key through a signingKey event. More...
 
ble_error_t setPrivateAddressTimeout (uint16_t timeout_in_seconds)
 Sets how often the address is rotated when privacy is enabled. More...
 
void onShutdown (const SecurityManagerShutdownCallback_t &callback)
 Setup a callback to be invoked to notify the user application that the SecurityManager instance is about to shutdown (possibly as a result of a call to BLE::shutdown()). More...
 
SecurityManagerShutdownCallbackChain_tonShutdown ()
 Provide access to the callchain of shutdown event callbacks. More...
 
void setSecurityManagerEventHandler (EventHandler *handler)
 Assign the event handler implementation that will be used by the stack to signal events back to the application. More...
 

Static Public Attributes

static const unsigned PASSKEY_LEN = 6
 Declaration of type containing a passkey to be used during pairing. More...
 

Detailed Description

Overview.

Security Manager is used to provide link security through encryption, signing and authentication which are made possible by pairing and optionally bonding. Pairing is the process of establishing and/or exchanging keys used for the current connection. Bonding means saving this information so that it can later be used after reconnecting without having to pair again. This saves time and power.

Paring

There are several ways to provide different levels of security during pairing depending on your requirements and the facilities provided by the application. The process starts with initialising the SecurityManager with default options for new connections. Some settings can later be changed per link or globally.

The important settings in the init() function are the MITM requirement and IO capabilities. Man in the Middle (MITM) protection prevents an attack where one device can impersonate another device by pairing with both devices at the same time. This protection is achieved by sharing some information between the devices through some independent channel. The IO capabilities of both devices dictate what algorithm is used. For details

See also
BLUETOOTH SPECIFICATION Version 5.0 | Vol 3, Part H - 2.3.5.1. You can change the IO capabilities after initialisation with setIoCapability(). This will take effect for all subsequent pairings.
Out of Band data used in pairing

Sharing this information through IO capabilities means user interaction which limits the degree of protection due to the limit of the amount of data that we can expect the user to transfer. Another solution is using OOB (out of band) communication to transfer this data instead which can send much more data making MITM attack even less likely to succeed. OOB data has to be exchanged by the application and provided to the Security Manager. Use setOOBDataUsage() to indicate you want to use it. The same call also allows you to set whether or not the communication channel you are using to transmit the OOB data is itself secure against MITM protection - this will set the level of the link security achieved using pairing that uses this data.

The most secure pairing is provided by Secure Connections which relies on Elliptical Curve Cryptography. Support for Secure Connections is dependent on both the stack and controller on both sides supporting it. If either side doesn't support it Legacy Pairing will be used. This is an older standard of pairing. If higher security is required legacy pairing can be disabled by calling allowLegacyPairing(false);

Signing

Applications may require a level of security providing confidence that data transfers are coming from a trusted source. This can be achieved by encrypting the link which also provides added confidentiality. Encryption is a good choice when a device stays connected but introduces latency due to the need of encrypting the link if the device only connects periodically to transfer data. If confidentiality is not required data GATT server may allow writes to happen over an unencrypted link but authenticated by a signature present in each packet. This signature relies on having sent a signing key to the peer during pairing prior to sending any signed packets.

Persistence of Security information

Security Manager stores all the data required for its operation on active links. Depending on resources available on the device it will also attempt to store data for disconnected devices which have bonded to be reused when reconnected.

If the application has initialised a filesystem and the Security Manager has been provided with a filepath during the init() call it may also provide data persistence across resets. This must be enabled by calling preserveBondingStateOnReset(). Persistence is not guaranteed and may fail if abnormally terminated. The Security Manager may also fall back to a non-persistent implementation if the resources are too limited.

How to use

First thing you need to do is to initialise the manager by calling init() with your chosen settings.

The SecurityManager communicates with your application through events. These will trigger calls in the EventHandler which you must provide by calling the setSecurityManagerEventHandler() function.

The most important process is pairing. This may be triggered manually by calling requestPairing() or may be called as a result of the application requiring encryption by calling setLinkEncryption() or as a result of the application requiring MITM protection through requestAuthentication().

All these can be implicitly called by using setLinkSecurity() to conveniently set the required security for the link. The SecurityManager will trigger all the process required to achieve the set security level. Security level can only be escalated. Asking the Security Manager for a lower security level than the existing one will not fail but will result in a event informing the application through linkEncryptionResult() of the current level (which remains unchanged).

Depending on the IO capabilities and OOB usage settings different pairing algorithms will be chosen. They will produce appropriate events which must be handled by your EventHandler. If your event handler doesn't support all the calls you must not set IO capabilities or set OOB usage in such a way that would trigger them or else the pairing will fail (usually by timing out).

The simplest example is a pairing of a device with no IO capabilities and no OOB data available. With such limited pairing capabilities the "just works" method will be employed. This does not provide any MITM protection. The pairing (triggered implicitly or called explicitly) will result in an event being generated on the peer calling pairingRequest(). The event handler must make a decision (either in the application itself or based on user interaction) whether to accept the pairing and call accetPairing() or cancelPairing(). The result will be communicated on both peers through an event calling pairingResult() in the EventHandler.

Sequence diagrams

Sequence diagram "Just Works" pairing

*  /-------- Device 1 ---------\  *----- BLE link -----*  /----------- Device 2-----------\
*
* App  EventHandler      SecurityManager            SecurityManager    EventHandler      App
*  |        |                  |                          |                 |             |
*  |-------------------> requestPairing()                 |                 |             |
*  |        |                  |-----[pairing start]----->|                 |             |
*  |        |                  |                          |---------> pairingRequest() -->|
*  |        |                  |                   acceptPairing() <--------------------- |
*  |        |                  |<--[pairing complete]---->|                 |             |
*  |<- pairingResult() <-------|                          |---------> pairingResult() --->|
*  |        |                  |                          |                 |             |
* 
Note
the requestPairing() call isn't required to trigger pairing. Pairing will also be triggered if you request encryption and authentication and no bonding information is available. The sequence will be the same save for the lack of explicit requestPairing() call.

Sequence diagram Encryption request when bonding information is available

*  /--------- Device 1 ---------\  *------ BLE link ------*  /--------- Device 2 ---------\
*
* App  EventHandler       SecurityManager              SecurityManager   EventHandler    App
*  |       |                    |                            |                |           |
*  |--------------------> setLinkEncryption()                |                |           |
*  |       |                    |<-[encryption established]->|                |           |
*  |<- linkEncryptionResult() <-|                            |-> linkEncryptionResult() ->|
*  |       |                    |                            |                |           |
* 
Note
if bonding information is not available, pairing will be triggered

Sequence diagram for Secure Connections passkey entry pairing with one device having a display only and other a keyboard

*  /---- Device 1 (keyboard) ---\  *------ BLE link ------*  /----- Device 2 (display) ---\
*
* App  EventHandler       SecurityManager              SecurityManager  EventHandler     App
*  |       |                    |                            |               |            |
*  |--------------------> requestPairing()                   |               |            |
*  |        |                   |------[pairing start]------>|               |            |
*  |        |                   |                            |-------> pairingRequest() ->|
*  |        |                   |                        acceptPairing() <--------------- |
*  |        |                   |<---[secure con. pairing]-->|               |            |
*  |<- passkeyRequest() <-------|                            |-------> passkeyDisplay() ->|
*  |        |                   |                            |               |            |
*
*                  user reads the passkey on Device 2 and inputs it on Device 1
*
*  |        |                   |                            |               |            |
*  |------------------->passkeyEntered()                     |               |            |
*  |        |                   |<---[pairing complete]----->|               |            |
*  |<- pairingResult() <--------|                            |-------> pairingResult() -->|
*  |        |                   |                            |               |            |
* 

Definition at line 189 of file SecurityManager.h.

Member Typedef Documentation

◆ Passkey_t

typedef uint8_t Passkey_t[PASSKEY_LEN]

6-digit passkey in ASCII ('0'-'9' digits only).

Definition at line 236 of file SecurityManager.h.

Member Enumeration Documentation

◆ SecurityMode_t

level of security required from the link by the application

Enumerator
SECURITY_MODE_ENCRYPTION_OPEN_LINK 

Require no protection, open link.

SECURITY_MODE_ENCRYPTION_NO_MITM 

Require encryption, but no MITM protection.

SECURITY_MODE_ENCRYPTION_WITH_MITM 

Require encryption and MITM protection.

SECURITY_MODE_SIGNED_NO_MITM 

Require signing or encryption, but no MITM protection.

SECURITY_MODE_SIGNED_WITH_MITM 

Require signing or encryption, and MITM protection.

Definition at line 193 of file SecurityManager.h.

◆ SecurityIOCapabilities_t

Input/output capability of the device and application.

Enumerator
IO_CAPS_DISPLAY_ONLY 

Display only.

IO_CAPS_DISPLAY_YESNO 

Display and yes/no entry.

IO_CAPS_KEYBOARD_ONLY 

Keyboard only.

IO_CAPS_NONE 

No I/O capabilities.

IO_CAPS_KEYBOARD_DISPLAY 

Keyboard and display.

Definition at line 203 of file SecurityManager.h.

◆ SecurityCompletionStatus_t

Result of security requests.

Enumerator
SEC_STATUS_SUCCESS 

Procedure completed with success.

SEC_STATUS_TIMEOUT 

Procedure timed out.

SEC_STATUS_PDU_INVALID 

Invalid PDU received.

SEC_STATUS_PASSKEY_ENTRY_FAILED 

Passkey entry failed (user cancelled or other).

SEC_STATUS_OOB_NOT_AVAILABLE 

Out of Band Key not available.

SEC_STATUS_AUTH_REQ 

Authentication requirements not met.

SEC_STATUS_CONFIRM_VALUE 

Confirm value failed.

SEC_STATUS_PAIRING_NOT_SUPP 

Pairing not supported.


SEC_STATUS_ENC_KEY_SIZE 

Encryption key size.

SEC_STATUS_SMP_CMD_UNSUPPORTED 

Unsupported SMP command.

SEC_STATUS_UNSPECIFIED 

Unspecified reason.

SEC_STATUS_REPEATED_ATTEMPTS 

Too little time elapsed since last attempt.

SEC_STATUS_INVALID_PARAMS 

Invalid parameters.

SEC_STATUS_DHKEY_CHECK_FAILED 

DHKey received doesn’t match locally calculated one.

SEC_STATUS_COMPARISON_FAILED 

Values in the numeric comparison protocol do not match.

Definition at line 212 of file SecurityManager.h.

Member Function Documentation

◆ init()

ble_error_t init ( bool  enableBonding = true,
bool  requireMITM = true,
SecurityIOCapabilities_t  iocaps = IO_CAPS_NONE,
const Passkey_t  passkey = nullptr,
bool  signing = true,
const char *  dbFilepath = nullptr 
)

Enable the BLE stack's Security Manager.

The Security Manager implements the actual cryptographic algorithms and protocol exchanges that allow two devices to securely exchange data and privately detect each other. Calling this API is a prerequisite for encryption and pairing (bonding).

Parameters
[in]enableBondingAllow for bonding.
[in]requireMITMRequire protection for man-in-the-middle attacks.
[in]iocapsTo specify the I/O capabilities of this peripheral, such as availability of a display or keyboard, to support out-of-band exchanges of security data.
[in]passkeyTo specify a static passkey.
[in]signingGenerate and distribute signing key during pairing
[in]dbFilepathPath to the file used to store keys in the filesystem, if NULL keys will be only stored in memory
Returns
BLE_ERROR_NONE on success.

◆ setDatabaseFilepath()

ble_error_t setDatabaseFilepath ( const char *  dbFilepath = nullptr)

Change the file used for the security database.

If path is invalid or a NULL is passed keys will only be stored in memory.

Note
This operation is only allowed with no active connections.
Parameters
[in]dbFilepathPath to the file used to store keys in the filesystem, if NULL keys will be only stored in memory
Returns
BLE_ERROR_NONE on success.

◆ reset()

ble_error_t reset ( )

Notify all registered onShutdown callbacks that the SecurityManager is about to be shutdown and clear all SecurityManager state of the associated object.

This function is meant to be overridden in the platform-specific sub-class. Nevertheless, the sub-class is only expected to reset its state and not the data held in SecurityManager members. This shall be achieved by a call to SecurityManager::reset() from the sub-class' reset() implementation.

Returns
BLE_ERROR_NONE on success.

◆ preserveBondingStateOnReset()

ble_error_t preserveBondingStateOnReset ( bool  enable)

Normally all bonding information is lost when device is reset, this requests that the stack attempts to save the information and reload it during initialisation.

This is not guaranteed.

Note
This option is itself saved together with bonding data. When data is read after reset, the state of this option decides if data should be restored. If this option has not been saved the data will not be restored even if partial data is present.
Parameters
[in]enableif true the stack will attempt to preserve bonding information on reset.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ writeBondingStateToPersistentStorage()

ble_error_t writeBondingStateToPersistentStorage ( )

Some or all of bonding information may be stored in memory while in use.

This will write bonding data to persistent storage. This will have no effect if no persistent storage is enabled.

Note
This implicitly also calls preserveBondingStateOnReset(true) inside.
Depending on the driver used to implement the storage solution used this may be a disruptive operation and may cause active connections to drop due to failed processing deadlines.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ purgeAllBondingState()

ble_error_t purgeAllBondingState ( )

Delete all peer device context and all related bonding information from the database within the security manager.

Return values
BLE_ERROR_NONEOn success, else an error code indicating reason for failure.
BLE_ERROR_INVALID_STATEIf the API is called without module initialization or application registration.

◆ generateWhitelistFromBondTable()

ble_error_t generateWhitelistFromBondTable ( ::ble::whitelist_t whitelist) const

Create a list of addresses from all peers in the bond table and generate an event which returns it as a whitelist.

Pass in the container for the whitelist. This will be returned by the event.

Parameters
[in]whitelistPreallocated whitelist which will be filled up to its capacity. If whitelist already contains entries this will be appended to. Do not access the whitelist until callback has been called, returning the filled whitelist.
Return values
BLE_ERROR_NONEOn success, else an error code indicating reason for failure

◆ requestPairing()

ble_error_t requestPairing ( ble::connection_handle_t  connectionHandle)

Request pairing with the peer.

Called by the master.

Note
Slave can call requestAuthentication or setLinkEncryption to achieve security.
Parameters
[in]connectionHandleHandle to identify the connection.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::pairingResult()

◆ acceptPairingRequest()

ble_error_t acceptPairingRequest ( ble::connection_handle_t  connectionHandle)

Accept the pairing request.

Called as a result of pairingRequest being called on the event handler.

Parameters
[in]connectionHandleHandle to identify the connection.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::pairingRequest()

◆ cancelPairingRequest()

ble_error_t cancelPairingRequest ( ble::connection_handle_t  connectionHandle)

Reject pairing request if the local device is the slave or cancel an outstanding pairing request if master.

Parameters
[in]connectionHandleHandle to identify the connection.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::pairingRequest()

◆ setPairingRequestAuthorisation()

ble_error_t setPairingRequestAuthorisation ( bool  required = true)

Tell the stack whether the application needs to authorise pairing requests or should they be automatically accepted.

Parameters
[in]requiredIf set to true, pairingRequest in the event handler will will be called and will require an action from the application to continue with pairing by calling acceptPairingRequest or cancelPairingRequest if the user wishes to reject it.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::pairingRequest()
EventHandler::acceptPairingRequest()
EventHandler::cancelPairingRequest()

◆ getPeerIdentity()

ble_error_t getPeerIdentity ( ble::connection_handle_t  connectionHandle)

Retrieve identity address for the peer on the given connection.

Parameters
[in]connectionHandleHandle to identify the connection.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::peerIdentity()

◆ allowLegacyPairing()

ble_error_t allowLegacyPairing ( bool  allow = true)

Allow or disallow the use of legacy pairing in case the application only wants to force the use of Secure Connections.

If legacy pairing is disallowed and either side doesn't support Secure Connections the pairing will fail.

Parameters
[out]allowIf true legacy pairing will be used if either side doesn't support Secure Connections.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ getSecureConnectionsSupport()

ble_error_t getSecureConnectionsSupport ( bool *  enabled)

Check if the Secure Connections feature is supported by the stack and controller.

Parameters
[out]enabledtrue if SC are supported
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ setIoCapability()

ble_error_t setIoCapability ( SecurityIOCapabilities_t  iocaps)

Set the IO capability of the local device.

Parameters
[in]iocapstype of IO capabilities available on the local device
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ setDisplayPasskey()

ble_error_t setDisplayPasskey ( const Passkey_t  passkey)

Set the passkey that is displayed on the local device instead of using a randomly generated one.

This will be used during pairing

Parameters
[in]passkeyASCII string of 6 digits
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::passkeyRequest() - this will be called on the peer which will have to use passkeyEntered() to send this passkey back to us.

◆ setLinkSecurity()

ble_error_t setLinkSecurity ( ble::connection_handle_t  connectionHandle,
SecurityMode_t  securityMode 
)

Set the security mode on a connection.

Useful for elevating the security mode once certain conditions are met, e.g., a particular service is found. This call is a request for the stack to take appropriate action and may result in (re)pairing or encryption. Wait for events in your registered EventHandler.

Parameters
[in]connectionHandleHandle to identify the connection.
[in]securityModeRequested security mode.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::linkEncryptionResult()
EventHandler::pairingResult()

◆ setKeypressNotification()

ble_error_t setKeypressNotification ( bool  enabled = true)

Set whether or not we want to send and receive keypress notifications during passkey entry.

Parameters
[in]enabledif true pairing will try to enable keypress notifications (dependent on other side supporting it)
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ enableSigning()

ble_error_t enableSigning ( ble::connection_handle_t  connectionHandle,
bool  enabled = true 
)

Request generation and exchange of signing keys so that packet signing can be utilised on this connection.

Note
This does not generate a signingKey event. Use getSigningKey for that.
Parameters
[in]connectionHandleHandle to identify the connection.
[in]enabledIf set to true, signing keys will be exchanged during subsequent pairing.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ setHintFutureRoleReversal()

ble_error_t setHintFutureRoleReversal ( bool  enable = true)

Give a hint to the stack that the master/slave role might change in the future.

Parameters
[in]enableIf set to true it hints the roles are likely to swap in the future.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ getLinkEncryption()

ble_error_t getLinkEncryption ( ble::connection_handle_t  connectionHandle,
ble::link_encryption_t encryption 
)

Current state of encryption on the link.

Parameters
[in]connectionHandleHandle to identify the connection.
[out]encryption
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ setLinkEncryption()

ble_error_t setLinkEncryption ( ble::connection_handle_t  connectionHandle,
ble::link_encryption_t  encryption 
)

Enabled or disable encryption on the link.

The result of this request will be indicated by a call to linkEncryptionResult in the event handler when the action is completed.

Parameters
[in]connectionHandleHandle to identify the connection.
[in]encryptionencryption state requested
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::linkEncryptionResult()

◆ setEncryptionKeyRequirements()

ble_error_t setEncryptionKeyRequirements ( uint8_t  minimumByteSize,
uint8_t  maximumByteSize 
)

Set the requirements for encryption key size.

If the peer cannot comply with the requirements paring will fail.

Parameters
[in]minimumByteSizeSmallest allowed encryption key size in bytes. (no smaller than 7)
[in]maximumByteSizeLargest allowed encryption key size in bytes. (no larger than 16)
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ getEncryptionKeySize()

ble_error_t getEncryptionKeySize ( connection_handle_t  connectionHandle,
uint8_t *  size 
)

Get encryption key size for given connection.

Parameters
[in]connectionHandleHandle to identify the connection.
[out]sizeReturns the key size in bits.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ requestAuthentication()

ble_error_t requestAuthentication ( ble::connection_handle_t  connectionHandle)

Request that the link be authenticated (keys with MITM protection).

This might trigger encryption or pairing/re-pairing. The success will be indicated through an event indicating security level change.

Parameters
[in]connectionHandleHandle to identify the connection.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::linkEncryptionResult()
EventHandler::pairingResult()

◆ generateOOB()

ble_error_t generateOOB ( const ble::address_t address)

Generate OOB data with the given address.

If Secure Connections is supported this will also generate Secure Connections OOB data on top of legacy pairing OOB data. This can be used to generate such data before the connection takes place.

In this model the OOB exchange takes place before the devices connect. Devices should establish communication over another channel and exchange the OOB data. The address provided will be used by the peer to associate the received data with the address of the device it will then connect to over BLE.

Parameters
[in]addressThe local address you will use in the connection using this OOB data. This address will be returned along with the rest of the OOB data when generation is complete. Using an invalid address is illegal.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::oobGenerated()

◆ setOOBDataUsage()

ble_error_t setOOBDataUsage ( ble::connection_handle_t  connectionHandle,
bool  useOOB,
bool  OOBProvidesMITM = true 
)

Enable OOB data usage during paring.

If Secure Connections is supported enabling useOOB will generate Secure Connections OOB data through oobGenerated() on top of legacy pairing OOB data.

You do not have to call this function to return received OOB data. Use legacyPairingOobReceived or oobReceived to hand it in. This will allow the stack to use it if possible. You only need to call this function to attempt legacy OOB data exchange after pairing start and to inform the stack OOB data does not provide MITM protection (by default it is set to provide this).

In this model the OOB exchange takes places after the devices have connected but possibly prior to pairing. For secure connections pairing must not be started until after the OOB data has been sent and/or received. The address in the OOB data generated will match the original address used to establish the connection and will be used by the peer to identify which connection the OOB data belongs to.

Parameters
[in]connectionHandleHandle to identify the connection.
[in]useOOBIf set to true, authenticate using OOB data.
[in]OOBProvidesMITMIf set to true keys exchanged during pairing using OOB data will provide Man-in-the-Middle protection. This indicates that the form of exchange used by the OOB data itself provides MITM protection.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ confirmationEntered()

ble_error_t confirmationEntered ( ble::connection_handle_t  connectionHandle,
bool  confirmation 
)

Report to the stack if the passkey matches or not.

Used during pairing to provide MITM protection.

Parameters
[in]connectionHandleHandle to identify the connection.
[in]confirmationTrue value indicates the passkey displayed matches.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::confirmationRequest()

◆ passkeyEntered()

ble_error_t passkeyEntered ( ble::connection_handle_t  connectionHandle,
Passkey_t  passkey 
)

Supply the stack with the user entered passkey.

Parameters
[in]connectionHandleHandle to identify the connection.
[in]passkeyASCII string of digits entered by the user.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::passkeyRequest()

◆ sendKeypressNotification()

ble_error_t sendKeypressNotification ( ble::connection_handle_t  connectionHandle,
ble::Keypress_t  keypress 
)

Send a notification to the peer that the user pressed a key on the local device.

Note
This will only be delivered if the keypress notifications have been enabled during pairing.
Parameters
[in]connectionHandleHandle to identify the connection.
[in]keypressType of keypress event.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::keypressNotification() - this will be trigger on the peer

◆ legacyPairingOobReceived()

ble_error_t legacyPairingOobReceived ( const ble::address_t address,
const ble::oob_tk_t tk 
)

Supply the stack with the OOB data for legacy connections.

Parameters
[in]addressaddress of the peer device this data comes from
[in]tkpointer to out of band data received containing the temporary key.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
legacyPairingOobRequest

◆ oobReceived()

ble_error_t oobReceived ( const ble::address_t address,
const ble::oob_lesc_value_t random,
const ble::oob_confirm_t confirm 
)

Supply the stack with the OOB data for secure connections.

This data is generated on the peer and is received through another communication channel.

Parameters
[in]addressaddress of the peer device this data comes from
[in]randomrandom number used to generate the confirmation
[in]confirmconfirmation value to be use for authentication in secure connections pairing
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ getSigningKey()

ble_error_t getSigningKey ( ble::connection_handle_t  connectionHandle,
bool  authenticated 
)

Retrieves a signing key through a signingKey event.

If a signing key is not present, pairing/authentication will be attempted.

Note
This will attempt to retrieve the key even if enableSigning hasn't been called prior to pairing.
Parameters
[in]connectionHandleHandle to identify the connection.
[in]authenticatedWhether the signing key needs to be authenticated (provide MITM protection).
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.
See also
EventHandler::signingKey()

◆ setPrivateAddressTimeout()

ble_error_t setPrivateAddressTimeout ( uint16_t  timeout_in_seconds)

Sets how often the address is rotated when privacy is enabled.

Parameters
[in]timeout_in_secondsHow many seconds to wait before starting generation of a new address.
Returns
BLE_ERROR_NONE or appropriate error code indicating the failure reason.

◆ onShutdown() [1/2]

void onShutdown ( const SecurityManagerShutdownCallback_t callback)

Setup a callback to be invoked to notify the user application that the SecurityManager instance is about to shutdown (possibly as a result of a call to BLE::shutdown()).

Note
It is possible to chain together multiple onShutdown callbacks (potentially from different modules of an application) to be notified before the SecurityManager is shutdown.
It is also possible to set up a callback into a member function of some object.
It is possible to unregister a callback using onShutdown().detach(callback)

◆ onShutdown() [2/2]

Provide access to the callchain of shutdown event callbacks.

It is possible to register callbacks using onShutdown().add(callback). It is possible to unregister callbacks using onShutdown().detach(callback).

Returns
The shutdown event callbacks chain

◆ setSecurityManagerEventHandler()

void setSecurityManagerEventHandler ( EventHandler handler)

Assign the event handler implementation that will be used by the stack to signal events back to the application.

Parameters
[in]handlerEvent Handler interface implementation.

Field Documentation

◆ PASSKEY_LEN

const unsigned PASSKEY_LEN = 6
static

Declaration of type containing a passkey to be used during pairing.

This is passed into initializeSecurity() to specify a pre-programmed passkey for authentication instead of generating a random one.

Definition at line 235 of file SecurityManager.h.