mirror of https://github.com/ARMmbed/mbed-os.git
[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".pull/5970/head
parent
cf5065c312
commit
412a79d444
|
@ -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);
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue