From 412a79d4445b4567431c57698fe7b5b723aa5f50 Mon Sep 17 00:00:00 2001 From: TomoYamanaka Date: Tue, 30 Jan 2018 18:17:40 +0900 Subject: [PATCH] [RZ_A1LU] Fix TRNG function Related to the review of #5857, I fixed the TRNG function for GR-LYCHEE. - I modified to zeroize "recv_data" before the function return. - I added the processing that check the return value of I2C.read function. If return value is error, "output" is zeroized before function return. - In trng_get_bytes_esp32 function, there is a time lag in the period from ESP32 reset to start working, error may occur when "Write" is called. Thus, I added a retry counter due to address this concern. There is not this counter for "Read" since it is called after "Write". --- .../TARGET_GR_LYCHEE/trng_api_esp32.cpp | 40 +++++++++++++------ 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/targets/TARGET_RENESAS/TARGET_RZ_A1XX/TARGET_GR_LYCHEE/trng_api_esp32.cpp b/targets/TARGET_RENESAS/TARGET_RZ_A1XX/TARGET_GR_LYCHEE/trng_api_esp32.cpp index f690b6c8de..07d9e86376 100644 --- a/targets/TARGET_RENESAS/TARGET_RZ_A1XX/TARGET_GR_LYCHEE/trng_api_esp32.cpp +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1XX/TARGET_GR_LYCHEE/trng_api_esp32.cpp @@ -19,6 +19,12 @@ #include "platform/mbed_wait_api.h" #define ESP32_I2C_ADDR (0x28<<1) +#define RETRY_CNT_MAX (20) + +/* Implementation that should never be optimized out by the compiler */ +static void mbedtls_zeroize( void *v, size_t n ) { + volatile unsigned char *p = (unsigned char *)v; while( n-- ) *p++ = 0; +} extern "C" void trng_init_esp32(void) { @@ -59,27 +65,35 @@ extern "C" int trng_get_bytes_esp32(uint8_t *output, size_t length, size_t *outp char recv_data[4]; size_t idx = 0; int i; - int err_cnt = 0; + int retry_cnt = 0; - while (idx < length) { + if ((output == NULL) || (output_length == NULL)) { + return -1; + } + + while ((retry_cnt < RETRY_CNT_MAX) && (idx < length)) { send_data[0] = 0; - ret = mI2c.write(ESP32_I2C_ADDR, send_data, 1); + ret = mI2c.write(ESP32_I2C_ADDR, send_data, sizeof(send_data)); if (ret == 0) { - mI2c.read(ESP32_I2C_ADDR, recv_data, sizeof(recv_data)); - for (i = 0; (i < 4) && (idx < length); i++) { - output[idx++] = recv_data[i]; - } - } else { - err_cnt++; - if (err_cnt >= 20) { - break; + ret = mI2c.read(ESP32_I2C_ADDR, recv_data, sizeof(recv_data)); + if (ret == 0) { + for (i = 0; (i < sizeof(recv_data)) && (idx < length); i++) { + output[idx++] = recv_data[i]; + } } + } + if (ret != 0) { + retry_cnt++; wait_ms(100); } } - if (output_length != NULL) { - *output_length = idx; + if (retry_cnt >= RETRY_CNT_MAX) { + idx = 0; + mbedtls_zeroize(output, length); } + *output_length = idx; + + mbedtls_zeroize(recv_data, sizeof(recv_data)); return (idx != 0 ? 0 : -1); }