From 983503f9eebe668ea2ac214ba4cee40934dcd915 Mon Sep 17 00:00:00 2001 From: Kevin Bracey Date: Tue, 29 Jan 2019 12:45:48 +0200 Subject: [PATCH] Mutex-protect mbedtls_hardware_poll Like all HAL APIs, the calls in trng_api.h are not expected to be thread-safe. All current accesses to the TRNG HAL are currently via `mbedtls_hardware_poll`. Mbed TLS does not currently serialise these calls itself, as `MBEDTLS_THREADING_C` is not enabled. But even if Mbed TLS's own accesses were serialised, there are other direct users of `mbedtls_hardware_poll` such as randLIB, that need to use direct calls due to lack of API to extract entropy from Mbed TLS. As such it makes sense to treat `mbedtls_hardware_poll` as a de facto public Mbed OS API, akin to the C++ veneers on top of the HAL, and add a PlatformMutex there so that it is safe for multithreaded use. --- features/mbedtls/platform/src/{mbed_trng.c => mbed_trng.cpp} | 5 +++++ 1 file changed, 5 insertions(+) rename features/mbedtls/platform/src/{mbed_trng.c => mbed_trng.cpp} (87%) diff --git a/features/mbedtls/platform/src/mbed_trng.c b/features/mbedtls/platform/src/mbed_trng.cpp similarity index 87% rename from features/mbedtls/platform/src/mbed_trng.c rename to features/mbedtls/platform/src/mbed_trng.cpp index d4dd771c01..53c1c21097 100644 --- a/features/mbedtls/platform/src/mbed_trng.c +++ b/features/mbedtls/platform/src/mbed_trng.cpp @@ -17,12 +17,17 @@ #if DEVICE_TRNG #include "hal/trng_api.h" +#include "platform/PlatformMutex.h" +extern "C" int mbedtls_hardware_poll( void *data, unsigned char *output, size_t len, size_t *olen ) { + static PlatformMutex trng_mutex; trng_t trng_obj; + trng_mutex.lock(); trng_init(&trng_obj); int ret = trng_get_bytes(&trng_obj, output, len, olen); trng_free(&trng_obj); + trng_mutex.unlock(); return ret; }