1 /*
2  *  Entropy accumulator implementation
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 
20 #include "common.h"
21 
22 #if defined(MBEDTLS_ENTROPY_C)
23 
24 #if defined(MBEDTLS_TEST_NULL_ENTROPY)
25 #warning "**** WARNING!  MBEDTLS_TEST_NULL_ENTROPY defined! "
26 #warning "**** THIS BUILD HAS NO DEFINED ENTROPY SOURCES "
27 #warning "**** THIS BUILD IS *NOT* SUITABLE FOR PRODUCTION USE "
28 #endif
29 
30 #include "mbedtls/entropy.h"
31 #include "mbedtls/entropy_poll.h"
32 #include "mbedtls/platform_util.h"
33 #include "mbedtls/error.h"
34 
35 #include <string.h>
36 
37 #if defined(MBEDTLS_FS_IO)
38 #include <stdio.h>
39 #endif
40 
41 #if defined(MBEDTLS_ENTROPY_NV_SEED)
42 #include "mbedtls/platform.h"
43 #endif
44 
45 #if defined(MBEDTLS_SELF_TEST)
46 #if defined(MBEDTLS_PLATFORM_C)
47 #include "mbedtls/platform.h"
48 #else
49 #include <stdio.h>
50 #define mbedtls_printf     printf
51 #endif /* MBEDTLS_PLATFORM_C */
52 #endif /* MBEDTLS_SELF_TEST */
53 
54 #if defined(MBEDTLS_HAVEGE_C)
55 #include "mbedtls/havege.h"
56 #endif
57 
58 #define ENTROPY_MAX_LOOP    256     /**< Maximum amount to loop before error */
59 
mbedtls_entropy_init(mbedtls_entropy_context * ctx)60 void mbedtls_entropy_init( mbedtls_entropy_context *ctx )
61 {
62     ctx->source_count = 0;
63     memset( ctx->source, 0, sizeof( ctx->source ) );
64 
65 #if defined(MBEDTLS_THREADING_C)
66     mbedtls_mutex_init( &ctx->mutex );
67 #endif
68 
69     ctx->accumulator_started = 0;
70 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
71     mbedtls_sha512_init( &ctx->accumulator );
72 #else
73     mbedtls_sha256_init( &ctx->accumulator );
74 #endif
75 #if defined(MBEDTLS_HAVEGE_C)
76     mbedtls_havege_init( &ctx->havege_data );
77 #endif
78 
79     /* Reminder: Update ENTROPY_HAVE_STRONG in the test files
80      *           when adding more strong entropy sources here. */
81 
82 #if defined(MBEDTLS_TEST_NULL_ENTROPY)
83     mbedtls_entropy_add_source( ctx, mbedtls_null_entropy_poll, NULL,
84                                 1, MBEDTLS_ENTROPY_SOURCE_STRONG );
85 #endif
86 
87 #if !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)
88 #if !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
89     mbedtls_entropy_add_source( ctx, mbedtls_platform_entropy_poll, NULL,
90                                 MBEDTLS_ENTROPY_MIN_PLATFORM,
91                                 MBEDTLS_ENTROPY_SOURCE_STRONG );
92 #endif
93 #if defined(MBEDTLS_TIMING_C)
94     mbedtls_entropy_add_source( ctx, mbedtls_hardclock_poll, NULL,
95                                 MBEDTLS_ENTROPY_MIN_HARDCLOCK,
96                                 MBEDTLS_ENTROPY_SOURCE_WEAK );
97 #endif
98 #if defined(MBEDTLS_HAVEGE_C)
99     mbedtls_entropy_add_source( ctx, mbedtls_havege_poll, &ctx->havege_data,
100                                 MBEDTLS_ENTROPY_MIN_HAVEGE,
101                                 MBEDTLS_ENTROPY_SOURCE_STRONG );
102 #endif
103 #if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
104     mbedtls_entropy_add_source( ctx, mbedtls_hardware_poll, NULL,
105                                 MBEDTLS_ENTROPY_MIN_HARDWARE,
106                                 MBEDTLS_ENTROPY_SOURCE_STRONG );
107 #endif
108 #if defined(MBEDTLS_ENTROPY_NV_SEED)
109     mbedtls_entropy_add_source( ctx, mbedtls_nv_seed_poll, NULL,
110                                 MBEDTLS_ENTROPY_BLOCK_SIZE,
111                                 MBEDTLS_ENTROPY_SOURCE_STRONG );
112     ctx->initial_entropy_run = 0;
113 #endif
114 #endif /* MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES */
115 }
116 
mbedtls_entropy_free(mbedtls_entropy_context * ctx)117 void mbedtls_entropy_free( mbedtls_entropy_context *ctx )
118 {
119     /* If the context was already free, don't call free() again.
120      * This is important for mutexes which don't allow double-free. */
121     if( ctx->accumulator_started == -1 )
122         return;
123 
124 #if defined(MBEDTLS_HAVEGE_C)
125     mbedtls_havege_free( &ctx->havege_data );
126 #endif
127 #if defined(MBEDTLS_THREADING_C)
128     mbedtls_mutex_free( &ctx->mutex );
129 #endif
130 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
131     mbedtls_sha512_free( &ctx->accumulator );
132 #else
133     mbedtls_sha256_free( &ctx->accumulator );
134 #endif
135 #if defined(MBEDTLS_ENTROPY_NV_SEED)
136     ctx->initial_entropy_run = 0;
137 #endif
138     ctx->source_count = 0;
139     mbedtls_platform_zeroize( ctx->source, sizeof( ctx->source ) );
140     ctx->accumulator_started = -1;
141 }
142 
mbedtls_entropy_add_source(mbedtls_entropy_context * ctx,mbedtls_entropy_f_source_ptr f_source,void * p_source,size_t threshold,int strong)143 int mbedtls_entropy_add_source( mbedtls_entropy_context *ctx,
144                         mbedtls_entropy_f_source_ptr f_source, void *p_source,
145                         size_t threshold, int strong )
146 {
147     int idx, ret = 0;
148 
149 #if defined(MBEDTLS_THREADING_C)
150     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
151         return( ret );
152 #endif
153 
154     idx = ctx->source_count;
155     if( idx >= MBEDTLS_ENTROPY_MAX_SOURCES )
156     {
157         ret = MBEDTLS_ERR_ENTROPY_MAX_SOURCES;
158         goto exit;
159     }
160 
161     ctx->source[idx].f_source  = f_source;
162     ctx->source[idx].p_source  = p_source;
163     ctx->source[idx].threshold = threshold;
164     ctx->source[idx].strong    = strong;
165 
166     ctx->source_count++;
167 
168 exit:
169 #if defined(MBEDTLS_THREADING_C)
170     if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
171         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
172 #endif
173 
174     return( ret );
175 }
176 
177 /*
178  * Entropy accumulator update
179  */
entropy_update(mbedtls_entropy_context * ctx,unsigned char source_id,const unsigned char * data,size_t len)180 static int entropy_update( mbedtls_entropy_context *ctx, unsigned char source_id,
181                            const unsigned char *data, size_t len )
182 {
183     unsigned char header[2];
184     unsigned char tmp[MBEDTLS_ENTROPY_BLOCK_SIZE];
185     size_t use_len = len;
186     const unsigned char *p = data;
187     int ret = 0;
188 
189     if( use_len > MBEDTLS_ENTROPY_BLOCK_SIZE )
190     {
191 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
192         if( ( ret = mbedtls_sha512_ret( data, len, tmp, 0 ) ) != 0 )
193             goto cleanup;
194 #else
195         if( ( ret = mbedtls_sha256_ret( data, len, tmp, 0 ) ) != 0 )
196             goto cleanup;
197 #endif
198         p = tmp;
199         use_len = MBEDTLS_ENTROPY_BLOCK_SIZE;
200     }
201 
202     header[0] = source_id;
203     header[1] = use_len & 0xFF;
204 
205     /*
206      * Start the accumulator if this has not already happened. Note that
207      * it is sufficient to start the accumulator here only because all calls to
208      * gather entropy eventually execute this code.
209      */
210 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
211     if( ctx->accumulator_started == 0 &&
212         ( ret = mbedtls_sha512_starts_ret( &ctx->accumulator, 0 ) ) != 0 )
213         goto cleanup;
214     else
215         ctx->accumulator_started = 1;
216     if( ( ret = mbedtls_sha512_update_ret( &ctx->accumulator, header, 2 ) ) != 0 )
217         goto cleanup;
218     ret = mbedtls_sha512_update_ret( &ctx->accumulator, p, use_len );
219 #else
220     if( ctx->accumulator_started == 0 &&
221         ( ret = mbedtls_sha256_starts_ret( &ctx->accumulator, 0 ) ) != 0 )
222         goto cleanup;
223     else
224         ctx->accumulator_started = 1;
225     if( ( ret = mbedtls_sha256_update_ret( &ctx->accumulator, header, 2 ) ) != 0 )
226         goto cleanup;
227     ret = mbedtls_sha256_update_ret( &ctx->accumulator, p, use_len );
228 #endif
229 
230 cleanup:
231     mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
232 
233     return( ret );
234 }
235 
mbedtls_entropy_update_manual(mbedtls_entropy_context * ctx,const unsigned char * data,size_t len)236 int mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx,
237                            const unsigned char *data, size_t len )
238 {
239     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
240 
241 #if defined(MBEDTLS_THREADING_C)
242     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
243         return( ret );
244 #endif
245 
246     ret = entropy_update( ctx, MBEDTLS_ENTROPY_SOURCE_MANUAL, data, len );
247 
248 #if defined(MBEDTLS_THREADING_C)
249     if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
250         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
251 #endif
252 
253     return( ret );
254 }
255 
256 /*
257  * Run through the different sources to add entropy to our accumulator
258  */
entropy_gather_internal(mbedtls_entropy_context * ctx)259 static int entropy_gather_internal( mbedtls_entropy_context *ctx )
260 {
261     int ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
262     int i;
263     int have_one_strong = 0;
264     unsigned char buf[MBEDTLS_ENTROPY_MAX_GATHER];
265     size_t olen;
266 
267     if( ctx->source_count == 0 )
268         return( MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED );
269 
270     /*
271      * Run through our entropy sources
272      */
273     for( i = 0; i < ctx->source_count; i++ )
274     {
275         if( ctx->source[i].strong == MBEDTLS_ENTROPY_SOURCE_STRONG )
276             have_one_strong = 1;
277 
278         olen = 0;
279         if( ( ret = ctx->source[i].f_source( ctx->source[i].p_source,
280                         buf, MBEDTLS_ENTROPY_MAX_GATHER, &olen ) ) != 0 )
281         {
282             goto cleanup;
283         }
284 
285         /*
286          * Add if we actually gathered something
287          */
288         if( olen > 0 )
289         {
290             if( ( ret = entropy_update( ctx, (unsigned char) i,
291                                         buf, olen ) ) != 0 )
292                 return( ret );
293             ctx->source[i].size += olen;
294         }
295     }
296 
297     if( have_one_strong == 0 )
298         ret = MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE;
299 
300 cleanup:
301     mbedtls_platform_zeroize( buf, sizeof( buf ) );
302 
303     return( ret );
304 }
305 
306 /*
307  * Thread-safe wrapper for entropy_gather_internal()
308  */
mbedtls_entropy_gather(mbedtls_entropy_context * ctx)309 int mbedtls_entropy_gather( mbedtls_entropy_context *ctx )
310 {
311     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
312 
313 #if defined(MBEDTLS_THREADING_C)
314     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
315         return( ret );
316 #endif
317 
318     ret = entropy_gather_internal( ctx );
319 
320 #if defined(MBEDTLS_THREADING_C)
321     if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
322         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
323 #endif
324 
325     return( ret );
326 }
327 
mbedtls_entropy_func(void * data,unsigned char * output,size_t len)328 int mbedtls_entropy_func( void *data, unsigned char *output, size_t len )
329 {
330     int ret, count = 0, i, thresholds_reached;
331     size_t strong_size;
332     mbedtls_entropy_context *ctx = (mbedtls_entropy_context *) data;
333     unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
334 
335     if( len > MBEDTLS_ENTROPY_BLOCK_SIZE )
336         return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
337 
338 #if defined(MBEDTLS_ENTROPY_NV_SEED)
339     /* Update the NV entropy seed before generating any entropy for outside
340      * use.
341      */
342     if( ctx->initial_entropy_run == 0 )
343     {
344         ctx->initial_entropy_run = 1;
345         if( ( ret = mbedtls_entropy_update_nv_seed( ctx ) ) != 0 )
346             return( ret );
347     }
348 #endif
349 
350 #if defined(MBEDTLS_THREADING_C)
351     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
352         return( ret );
353 #endif
354 
355     /*
356      * Always gather extra entropy before a call
357      */
358     do
359     {
360         if( count++ > ENTROPY_MAX_LOOP )
361         {
362             ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
363             goto exit;
364         }
365 
366         if( ( ret = entropy_gather_internal( ctx ) ) != 0 )
367             goto exit;
368 
369         thresholds_reached = 1;
370         strong_size = 0;
371         for( i = 0; i < ctx->source_count; i++ )
372         {
373             if( ctx->source[i].size < ctx->source[i].threshold )
374                 thresholds_reached = 0;
375             if( ctx->source[i].strong == MBEDTLS_ENTROPY_SOURCE_STRONG )
376                 strong_size += ctx->source[i].size;
377         }
378     }
379     while( ! thresholds_reached || strong_size < MBEDTLS_ENTROPY_BLOCK_SIZE );
380 
381     memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
382 
383 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
384     /*
385      * Note that at this stage it is assumed that the accumulator was started
386      * in a previous call to entropy_update(). If this is not guaranteed, the
387      * code below will fail.
388      */
389     if( ( ret = mbedtls_sha512_finish_ret( &ctx->accumulator, buf ) ) != 0 )
390         goto exit;
391 
392     /*
393      * Reset accumulator and counters and recycle existing entropy
394      */
395     mbedtls_sha512_free( &ctx->accumulator );
396     mbedtls_sha512_init( &ctx->accumulator );
397     if( ( ret = mbedtls_sha512_starts_ret( &ctx->accumulator, 0 ) ) != 0 )
398         goto exit;
399     if( ( ret = mbedtls_sha512_update_ret( &ctx->accumulator, buf,
400                                            MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
401         goto exit;
402 
403     /*
404      * Perform second SHA-512 on entropy
405      */
406     if( ( ret = mbedtls_sha512_ret( buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
407                                     buf, 0 ) ) != 0 )
408         goto exit;
409 #else /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
410     if( ( ret = mbedtls_sha256_finish_ret( &ctx->accumulator, buf ) ) != 0 )
411         goto exit;
412 
413     /*
414      * Reset accumulator and counters and recycle existing entropy
415      */
416     mbedtls_sha256_free( &ctx->accumulator );
417     mbedtls_sha256_init( &ctx->accumulator );
418     if( ( ret = mbedtls_sha256_starts_ret( &ctx->accumulator, 0 ) ) != 0 )
419         goto exit;
420     if( ( ret = mbedtls_sha256_update_ret( &ctx->accumulator, buf,
421                                            MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
422         goto exit;
423 
424     /*
425      * Perform second SHA-256 on entropy
426      */
427     if( ( ret = mbedtls_sha256_ret( buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
428                                     buf, 0 ) ) != 0 )
429         goto exit;
430 #endif /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
431 
432     for( i = 0; i < ctx->source_count; i++ )
433         ctx->source[i].size = 0;
434 
435     memcpy( output, buf, len );
436 
437     ret = 0;
438 
439 exit:
440     mbedtls_platform_zeroize( buf, sizeof( buf ) );
441 
442 #if defined(MBEDTLS_THREADING_C)
443     if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
444         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
445 #endif
446 
447     return( ret );
448 }
449 
450 #if defined(MBEDTLS_ENTROPY_NV_SEED)
mbedtls_entropy_update_nv_seed(mbedtls_entropy_context * ctx)451 int mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx )
452 {
453     int ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
454     unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
455 
456     /* Read new seed  and write it to NV */
457     if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
458         return( ret );
459 
460     if( mbedtls_nv_seed_write( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) < 0 )
461         return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR );
462 
463     /* Manually update the remaining stream with a separator value to diverge */
464     memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
465     ret = mbedtls_entropy_update_manual( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE );
466 
467     return( ret );
468 }
469 #endif /* MBEDTLS_ENTROPY_NV_SEED */
470 
471 #if defined(MBEDTLS_FS_IO)
mbedtls_entropy_write_seed_file(mbedtls_entropy_context * ctx,const char * path)472 int mbedtls_entropy_write_seed_file( mbedtls_entropy_context *ctx, const char *path )
473 {
474     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
475     FILE *f = NULL;
476     unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
477 
478     if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
479     {
480         ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
481         goto exit;
482     }
483 
484     if( ( f = fopen( path, "wb" ) ) == NULL )
485     {
486         ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
487         goto exit;
488     }
489 
490     if( fwrite( buf, 1, MBEDTLS_ENTROPY_BLOCK_SIZE, f ) != MBEDTLS_ENTROPY_BLOCK_SIZE )
491     {
492         ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
493         goto exit;
494     }
495 
496     ret = 0;
497 
498 exit:
499     mbedtls_platform_zeroize( buf, sizeof( buf ) );
500 
501     if( f != NULL )
502         fclose( f );
503 
504     return( ret );
505 }
506 
mbedtls_entropy_update_seed_file(mbedtls_entropy_context * ctx,const char * path)507 int mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *path )
508 {
509     int ret = 0;
510     FILE *f;
511     size_t n;
512     unsigned char buf[ MBEDTLS_ENTROPY_MAX_SEED_SIZE ];
513 
514     if( ( f = fopen( path, "rb" ) ) == NULL )
515         return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR );
516 
517     fseek( f, 0, SEEK_END );
518     n = (size_t) ftell( f );
519     fseek( f, 0, SEEK_SET );
520 
521     if( n > MBEDTLS_ENTROPY_MAX_SEED_SIZE )
522         n = MBEDTLS_ENTROPY_MAX_SEED_SIZE;
523 
524     if( fread( buf, 1, n, f ) != n )
525         ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
526     else
527         ret = mbedtls_entropy_update_manual( ctx, buf, n );
528 
529     fclose( f );
530 
531     mbedtls_platform_zeroize( buf, sizeof( buf ) );
532 
533     if( ret != 0 )
534         return( ret );
535 
536     return( mbedtls_entropy_write_seed_file( ctx, path ) );
537 }
538 #endif /* MBEDTLS_FS_IO */
539 
540 #if defined(MBEDTLS_SELF_TEST)
541 #if !defined(MBEDTLS_TEST_NULL_ENTROPY)
542 /*
543  * Dummy source function
544  */
entropy_dummy_source(void * data,unsigned char * output,size_t len,size_t * olen)545 static int entropy_dummy_source( void *data, unsigned char *output,
546                                  size_t len, size_t *olen )
547 {
548     ((void) data);
549 
550     memset( output, 0x2a, len );
551     *olen = len;
552 
553     return( 0 );
554 }
555 #endif /* !MBEDTLS_TEST_NULL_ENTROPY */
556 
557 #if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
558 
mbedtls_entropy_source_self_test_gather(unsigned char * buf,size_t buf_len)559 static int mbedtls_entropy_source_self_test_gather( unsigned char *buf, size_t buf_len )
560 {
561     int ret = 0;
562     size_t entropy_len = 0;
563     size_t olen = 0;
564     size_t attempts = buf_len;
565 
566     while( attempts > 0 && entropy_len < buf_len )
567     {
568         if( ( ret = mbedtls_hardware_poll( NULL, buf + entropy_len,
569             buf_len - entropy_len, &olen ) ) != 0 )
570             return( ret );
571 
572         entropy_len += olen;
573         attempts--;
574     }
575 
576     if( entropy_len < buf_len )
577     {
578         ret = 1;
579     }
580 
581     return( ret );
582 }
583 
584 
mbedtls_entropy_source_self_test_check_bits(const unsigned char * buf,size_t buf_len)585 static int mbedtls_entropy_source_self_test_check_bits( const unsigned char *buf,
586                                                         size_t buf_len )
587 {
588     unsigned char set= 0xFF;
589     unsigned char unset = 0x00;
590     size_t i;
591 
592     for( i = 0; i < buf_len; i++ )
593     {
594         set &= buf[i];
595         unset |= buf[i];
596     }
597 
598     return( set == 0xFF || unset == 0x00 );
599 }
600 
601 /*
602  * A test to ensure hat the entropy sources are functioning correctly
603  * and there is no obvious failure. The test performs the following checks:
604  *  - The entropy source is not providing only 0s (all bits unset) or 1s (all
605  *    bits set).
606  *  - The entropy source is not providing values in a pattern. Because the
607  *    hardware could be providing data in an arbitrary length, this check polls
608  *    the hardware entropy source twice and compares the result to ensure they
609  *    are not equal.
610  *  - The error code returned by the entropy source is not an error.
611  */
mbedtls_entropy_source_self_test(int verbose)612 int mbedtls_entropy_source_self_test( int verbose )
613 {
614     int ret = 0;
615     unsigned char buf0[2 * sizeof( unsigned long long int )];
616     unsigned char buf1[2 * sizeof( unsigned long long int )];
617 
618     if( verbose != 0 )
619         mbedtls_printf( "  ENTROPY_BIAS test: " );
620 
621     memset( buf0, 0x00, sizeof( buf0 ) );
622     memset( buf1, 0x00, sizeof( buf1 ) );
623 
624     if( ( ret = mbedtls_entropy_source_self_test_gather( buf0, sizeof( buf0 ) ) ) != 0 )
625         goto cleanup;
626     if( ( ret = mbedtls_entropy_source_self_test_gather( buf1, sizeof( buf1 ) ) ) != 0 )
627         goto cleanup;
628 
629     /* Make sure that the returned values are not all 0 or 1 */
630     if( ( ret = mbedtls_entropy_source_self_test_check_bits( buf0, sizeof( buf0 ) ) ) != 0 )
631         goto cleanup;
632     if( ( ret = mbedtls_entropy_source_self_test_check_bits( buf1, sizeof( buf1 ) ) ) != 0 )
633         goto cleanup;
634 
635     /* Make sure that the entropy source is not returning values in a
636      * pattern */
637     ret = memcmp( buf0, buf1, sizeof( buf0 ) ) == 0;
638 
639 cleanup:
640     if( verbose != 0 )
641     {
642         if( ret != 0 )
643             mbedtls_printf( "failed\n" );
644         else
645             mbedtls_printf( "passed\n" );
646 
647         mbedtls_printf( "\n" );
648     }
649 
650     return( ret != 0 );
651 }
652 
653 #endif /* MBEDTLS_ENTROPY_HARDWARE_ALT */
654 
655 /*
656  * The actual entropy quality is hard to test, but we can at least
657  * test that the functions don't cause errors and write the correct
658  * amount of data to buffers.
659  */
mbedtls_entropy_self_test(int verbose)660 int mbedtls_entropy_self_test( int verbose )
661 {
662     int ret = 1;
663 #if !defined(MBEDTLS_TEST_NULL_ENTROPY)
664     mbedtls_entropy_context ctx;
665     unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };
666     unsigned char acc[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };
667     size_t i, j;
668 #endif /* !MBEDTLS_TEST_NULL_ENTROPY */
669 
670     if( verbose != 0 )
671         mbedtls_printf( "  ENTROPY test: " );
672 
673 #if !defined(MBEDTLS_TEST_NULL_ENTROPY)
674     mbedtls_entropy_init( &ctx );
675 
676     /* First do a gather to make sure we have default sources */
677     if( ( ret = mbedtls_entropy_gather( &ctx ) ) != 0 )
678         goto cleanup;
679 
680     ret = mbedtls_entropy_add_source( &ctx, entropy_dummy_source, NULL, 16,
681                                       MBEDTLS_ENTROPY_SOURCE_WEAK );
682     if( ret != 0 )
683         goto cleanup;
684 
685     if( ( ret = mbedtls_entropy_update_manual( &ctx, buf, sizeof buf ) ) != 0 )
686         goto cleanup;
687 
688     /*
689      * To test that mbedtls_entropy_func writes correct number of bytes:
690      * - use the whole buffer and rely on ASan to detect overruns
691      * - collect entropy 8 times and OR the result in an accumulator:
692      *   any byte should then be 0 with probably 2^(-64), so requiring
693      *   each of the 32 or 64 bytes to be non-zero has a false failure rate
694      *   of at most 2^(-58) which is acceptable.
695      */
696     for( i = 0; i < 8; i++ )
697     {
698         if( ( ret = mbedtls_entropy_func( &ctx, buf, sizeof( buf ) ) ) != 0 )
699             goto cleanup;
700 
701         for( j = 0; j < sizeof( buf ); j++ )
702             acc[j] |= buf[j];
703     }
704 
705     for( j = 0; j < sizeof( buf ); j++ )
706     {
707         if( acc[j] == 0 )
708         {
709             ret = 1;
710             goto cleanup;
711         }
712     }
713 
714 #if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
715     if( ( ret = mbedtls_entropy_source_self_test( 0 ) ) != 0 )
716         goto cleanup;
717 #endif
718 
719 cleanup:
720     mbedtls_entropy_free( &ctx );
721 #endif /* !MBEDTLS_TEST_NULL_ENTROPY */
722 
723     if( verbose != 0 )
724     {
725         if( ret != 0 )
726             mbedtls_printf( "failed\n" );
727         else
728             mbedtls_printf( "passed\n" );
729 
730         mbedtls_printf( "\n" );
731     }
732 
733     return( ret != 0 );
734 }
735 #endif /* MBEDTLS_SELF_TEST */
736 
737 #endif /* MBEDTLS_ENTROPY_C */
738