Section 12.20

Mbed TLS

Full name: Mbed TLS, where TLS stands for Transport Layer Security; Mbed is a product name, not an abbreviation.

Definition

Mbed TLS is an open-source C library, small enough for embedded devices, that implements cryptographic algorithms §14.1, X.509 certificates and the TLS (Transport Layer Security) and DTLS (Datagram Transport Layer Security) protocols. TLS protects a network connection against eavesdropping and tampering; DTLS does the same for single packets sent without a connection; X.509 is the standard format for certificates binding a public key to a name. The cryptographic interface follows the PSA (Platform Security Architecture) Cryptography API, a specification from Arm. A configuration header selects, at compile time, the algorithms included.

The idea

A device must compute an HMAC-SHA-256 §5.9 tag, a 32-byte value that only a holder of a secret key can compute over a message: HMAC §5.8 (hash-based message authentication code) is the method, and SHA-256 §5.2 (Secure Hash Algorithm with a 256-bit output) is the hash function inside it. Or the device must open a TLS connection to a server. Code for this written from scratch invites subtle errors, so firmware links a library that has been reviewed and tested for years. Mbed TLS is one widely used choice. It began under the name PolarSSL, which contains SSL (Secure Sockets Layer), the name of the protocol that TLS replaced; Arm acquired it in 2014 and renamed it Mbed TLS in 2015, and it is now developed under the Trusted Firmware open-source project.

The library does not decide what is secure. The guarantee belongs to the algorithm: HMAC-SHA-256 protects exactly the key and the bytes it is given, under the assumptions that the HMAC entry states. A library call realizes that guarantee only when three things hold. The build compiled a correct implementation of the algorithm. The caller passed the intended key and the intended bytes. And the caller acted on the result only after the call reported success; after a failed call, the output buffer may still hold old bytes that look like a tag.

How it works

Parts. Mbed TLS builds three libraries: a cryptography library, an X.509 library that uses it, and a TLS library that uses both.

Configuration. Each algorithm and feature is switched on or off by a preprocessor macro, a name that the C preprocessor checks before compilation, in a configuration header. In the release line 3.6, which has long-term support, the header is include/mbedtls/mbedtls_config.h; for example MBEDTLS_SHA256_C compiles SHA-256, and MBEDTLS_PSA_CRYPTO_C compiles the PSA interface. Defining the macro MBEDTLS_CONFIG_FILE on the compiler’s command line makes the build read another header instead, so the header in the source tree need not be the one that was used. From release 4.0, the cryptography lives in a separate project shipped with Mbed TLS, TF-PSA-Crypto (TF for Trusted Firmware), whose header psa/crypto_config.h holds the cryptography options, such as PSA_WANT_ALG_SHA_256; mbedtls_config.h keeps the X.509 and TLS options. The script scripts/config.py switches options on and off.

Implementations behind one algorithm. The same call can run different code.

Calls for a message authentication code §5.7 (MAC) in the PSA interface, in order:

  1. psa_crypto_init() initializes the library once. Until it succeeds, other calls fail with PSA_ERROR_BAD_STATE.

  2. Key attributes state the key’s type, PSA_KEY_TYPE_HMAC; the one algorithm it may be used with, PSA_ALG_HMAC(PSA_ALG_SHA_256); and its permitted uses, PSA_KEY_USAGE_SIGN_MESSAGE to compute tags and PSA_KEY_USAGE_VERIFY_MESSAGE to check them.

  3. psa_import_key() copies the key bytes into the library and returns a key identifier. The program then refers to the key only by that identifier.

  4. psa_mac_compute() writes a tag into the caller’s buffer and reports its length. psa_mac_verify() recomputes the tag, compares it with a received tag by a constant-time comparison §4.33, one whose running time does not depend on where the two tags differ, and returns PSA_SUCCESS or PSA_ERROR_INVALID_SIGNATURE.

  5. psa_destroy_key() erases the key when it is no longer needed.

Every call returns a status of type psa_status_t: PSA_SUCCESS, which is 0, or a negative error code. The older interface of the 3.x releases, such as mbedtls_md_hmac(), also returns 0 for success and a negative number for failure.

Platform hooks. Random numbers need an entropy §5.26 source, a supply of unpredictable bits. The platform provides it, on a microcontroller §6.1 usually through a hardware random number generator. Memory allocation and the locking between threads can be replaced by platform functions through configuration options.

Worked example

Test case 2 of RFC 4231, which publishes test values for HMAC-SHA-256 [167], uses as the key the 4 bytes of the text Jefe (0x4a 0x65 0x66 0x65) and as the message the 28 bytes of the text what do ya want for nothing?. The program calls psa_crypto_init(), sets the attributes above, imports the 4-byte key and calls psa_mac_compute() with a 32-byte output buffer. The call returns PSA_SUCCESS and a length of 32 bytes, because SHA-256 produces 256/8=32256 / 8 = 32 bytes. The tag is:

5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843

This equals the value printed in RFC 4231. Such a known-answer test, run on the device with the configuration that ships, shows that the compiled implementation computes HMAC-SHA-256 correctly for this input.

Changing one thing at a time shows the error contract.

The receiving device checks a tag with:

status = psa_mac_verify(key, alg, msg, msg_len, tag, 32);
if (status != PSA_SUCCESS) reject();

This accepts only on success. A tempting wrong version rejects only on one status and accepts every other:

if (status == PSA_ERROR_INVALID_SIGNATURE) reject();

On a device where initialization failed, every message then gets PSA_ERROR_BAD_STATE and is accepted, forged or not: the check fails open, letting everything through when it cannot run. Testing for the one success value makes the check fail closed §1.13.

Stated precisely

For HMAC with SHA-256, the contract of psa_mac_compute() is as follows. If it returns PSA_SUCCESS, the first mac_length bytes of the output buffer, which are 32 bytes, equal the HMAC-SHA-256 tag of MM under the key KK, as RFC 2104 and FIPS 198-1 define it [8, 313]. Here KK is the key that the identifier refers to, and MM is exactly the input_length bytes at input. If the call returns anything else, no tag was produced, and neither the buffer nor the length may be used. psa_mac_verify() returns PSA_SUCCESS only if the received tag equals the computed one; every other status means “not verified”.

The security of the tag rests on assumptions that the library cannot check:

  1. the key is secret and was chosen at random from enough possible values that guessing is infeasible;

  2. HMAC with SHA-256 is a secure message authentication code, as the HMAC entry states;

  3. the compiled implementation, software or driver, computes the function correctly, which a known-answer test confirms only for its sample inputs, and does not reveal the key through its timing or power use;

  4. the caller passed the intended bytes, including every field the receiver relies on, and treats only PSA_SUCCESS as success.

Which implementation runs is decided at build time by four things: the library’s version, the configuration header that the compiler actually read, the platform’s alternative implementations and PSA drivers, and the linker’s §12.4 choice of object files. The source text of a call shows none of them.

Limits and common mistakes

Mbed TLS authenticates exactly the bytes it is given. A field left out of the message, such as a counter or the receiver’s identity, is not protected, as the HMAC-SHA-256 entry explains.

The error contract lives in the return values, and ignoring one is a common failure, as the worked example shows.

The same function name can run different code in two builds. Check the configuration and the linker’s map file, the report of which object file supplied each function, and run known-answer tests on the device. In the 3.x releases, enabling MBEDTLS_SELF_TEST compiles self-test functions such as mbedtls_sha256_self_test().

Constant time is a property of the compiled code, not of the interface. psa_mac_verify() compares tags in constant time, but whether other code paths reveal secrets through their timing depends on the compiler, the driver and the hardware, and must be checked on the device.

Key generation, TLS and many signature schemes §5.14 need random numbers from a cryptographically secure pseudorandom number generator §5.27 (CSPRNG), seeded from an entropy source. A device without a real entropy source cannot generate secret keys safely, whatever library it uses.

Secrets must be erased. Destroy keys with psa_destroy_key() and overwrite other copies of secrets in RAM, for example with mbedtls_platform_zeroize(), which the compiler does not remove as a useless store.

Interfaces change across major releases. Release 3.0 changed many function signatures and made most structure fields private; release 4.0 moved the cryptography into TF-PSA-Crypto and made the PSA interface the main way to use it. Code written for one release line may not compile against another.

Questions answered

Which primitive implementation, backend, and error contract are actually compiled?

The compiled primitive implementation, backend and error contract are the ones that the build’s actual Mbed TLS version, configuration header and platform drivers selected; they are found from the build’s records and by tests on the device, not from the source code of the calls. A primitive is a basic cryptographic algorithm such as SHA-256 or HMAC (hash-based message authentication code); the backend is the code that computes it, which is the library’s own software, a platform replacement or a hardware driver; the error contract is the set of status values a call can return and what each means for the caller. To establish them:

  1. Version: the macro MBEDTLS_VERSION_STRING in the headers that the build included, or the library’s version function at run time.

  2. Configuration: the compiler command lines, especially a -D option that defines MBEDTLS_CONFIG_FILE, and the header they name; from release 4.0 also TF-PSA-Crypto’s psa/crypto_config.h.

  3. Backend: the alternative-implementation macros and PSA driver options in that configuration, and the linker’s map file, which shows which object file supplied each cryptographic function.

  4. Behavior: a known-answer test on the device, such as RFC 4231 test case 2 for HMAC-SHA-256.

  5. Error contract: the interface documentation of that version. In the PSA interface PSA_SUCCESS, which is 0, is the only success, and the caller must reject on every other value.

The package name Mbed TLS alone shows neither which algorithm code was compiled nor that any verification succeeded.

Related entries: HMAC (§5.8), Authenticated encryption (AEAD) (§5.16), CSPRNG (§5.27), Authentication coverage (§5.41), Linker (§12.4), HMAC-SHA-256 (§5.9), Fail closed (§1.13), Fail open (§1.14), Secret zeroization (§5.37), Constant-time cryptographic implementation (§5.36), Secure element (§5.38). Further reading: [8, 122, 167, 313].