Mbedtls entropy generation runs forever

492 views Asked by At

I'm trying to write an test function for mbedtls which randomly generates a key for AES encryption. I use the original tutorial Code from mbedtls. My Programm always stops when executing "mbedtls_ctr_drbg_seed()".

About my environmet: Basic Sourcefiles from STM_CUBEmx, Board: ST32F767 Nucleo, Compiling based on Makefile from STM_Cube

  mbedtls_ctr_drbg_context ctr_drbg;

  mbedtls_entropy_context entropy;

  char *pers="anything";    
  int ret;    
  //Start    
  mbedtls_entropy_init(&entropy);    
  debugPrintln("Init entropy done");    
  mbedtls_ctr_drbg_init(&ctr_drbg);    
  debugPrintln("Init ctr_drbg done");    
  if((ret=mbedtls_ctr_drbg_seed(&ctr_drbg,mbedtls_entropy_func,&entropy,(unsigned char *) pers,strlen(pers)))!=0){    
    //Error info    
    debugPrintln("ERROR ctr_drbg_seed ");
    return -1;
  }  
  debugPrintln("Init ctr_drbg_seed done");
  if((ret=mbedtls_ctr_drbg_random(&ctr_drbg,key,32))!=0){
    return -1;
  }

Thank you in advance

2

There are 2 answers

0
M-K On BEST ANSWER

I have found the reason

STM32 Cube MX places the HAL Init function for the RNG after the mbedtls init So when I call mbedtls_ctr_drbg_seed() inside mbedtls_init() the RNG hasn't yet been initialized and it iterates forever inside:

do
{
    if( count++ > ENTROPY_MAX_LOOP )
    {
        ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
        goto exit;
    }

    if( ( ret = entropy_gather_internal( ctx ) ) != 0 )
        goto exit;

    done = 1;
    for( i = 0; i < ctx->source_count; i++ )
        if( ctx->source[i].size < ctx->source[i].threshold )
            done = 0;
}
while( ! done );

Solution

swap the lines

0
Ron Eldor On

From your description, I am assuming that your application is stuck in the call to mbedtls_ctr_drbg_seed(). Most probable reason, IMHO, is in the functionmbedtls_entropy_func():

    do
    {
        if( count++ > ENTROPY_MAX_LOOP )
        {
            ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
            goto exit;
        }

        if( ( ret = entropy_gather_internal( ctx ) ) != 0 )
            goto exit;

        done = 1;
        for( i = 0; i < ctx->source_count; i++ )
            if( ctx->source[i].size < ctx->source[i].threshold )
                done = 0;
    }
    while( ! done );

You should check that your entropy collection increases the collected size, that the threshold is not MAX_INT or something of the sort, and that your hw entropy collector actually returns entropy data.