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_ENTROPY_FILE_IO_ERROR;
475     FILE *f;
476     unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
477 
478     if( ( f = fopen( path, "wb" ) ) == NULL )
479         return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR );
480 
481     if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
482         goto exit;
483 
484     if( fwrite( buf, 1, MBEDTLS_ENTROPY_BLOCK_SIZE, f ) != MBEDTLS_ENTROPY_BLOCK_SIZE )
485     {
486         ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
487         goto exit;
488     }
489 
490     ret = 0;
491 
492 exit:
493     mbedtls_platform_zeroize( buf, sizeof( buf ) );
494 
495     fclose( f );
496     return( ret );
497 }
498 
mbedtls_entropy_update_seed_file(mbedtls_entropy_context * ctx,const char * path)499 int mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *path )
500 {
501     int ret = 0;
502     FILE *f;
503     size_t n;
504     unsigned char buf[ MBEDTLS_ENTROPY_MAX_SEED_SIZE ];
505 
506     if( ( f = fopen( path, "rb" ) ) == NULL )
507         return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR );
508 
509     fseek( f, 0, SEEK_END );
510     n = (size_t) ftell( f );
511     fseek( f, 0, SEEK_SET );
512 
513     if( n > MBEDTLS_ENTROPY_MAX_SEED_SIZE )
514         n = MBEDTLS_ENTROPY_MAX_SEED_SIZE;
515 
516     if( fread( buf, 1, n, f ) != n )
517         ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
518     else
519         ret = mbedtls_entropy_update_manual( ctx, buf, n );
520 
521     fclose( f );
522 
523     mbedtls_platform_zeroize( buf, sizeof( buf ) );
524 
525     if( ret != 0 )
526         return( ret );
527 
528     return( mbedtls_entropy_write_seed_file( ctx, path ) );
529 }
530 #endif /* MBEDTLS_FS_IO */
531 
532 #if defined(MBEDTLS_SELF_TEST)
533 #if !defined(MBEDTLS_TEST_NULL_ENTROPY)
534 /*
535  * Dummy source function
536  */
entropy_dummy_source(void * data,unsigned char * output,size_t len,size_t * olen)537 static int entropy_dummy_source( void *data, unsigned char *output,
538                                  size_t len, size_t *olen )
539 {
540     ((void) data);
541 
542     memset( output, 0x2a, len );
543     *olen = len;
544 
545     return( 0 );
546 }
547 #endif /* !MBEDTLS_TEST_NULL_ENTROPY */
548 
549 #if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
550 
mbedtls_entropy_source_self_test_gather(unsigned char * buf,size_t buf_len)551 static int mbedtls_entropy_source_self_test_gather( unsigned char *buf, size_t buf_len )
552 {
553     int ret = 0;
554     size_t entropy_len = 0;
555     size_t olen = 0;
556     size_t attempts = buf_len;
557 
558     while( attempts > 0 && entropy_len < buf_len )
559     {
560         if( ( ret = mbedtls_hardware_poll( NULL, buf + entropy_len,
561             buf_len - entropy_len, &olen ) ) != 0 )
562             return( ret );
563 
564         entropy_len += olen;
565         attempts--;
566     }
567 
568     if( entropy_len < buf_len )
569     {
570         ret = 1;
571     }
572 
573     return( ret );
574 }
575 
576 
mbedtls_entropy_source_self_test_check_bits(const unsigned char * buf,size_t buf_len)577 static int mbedtls_entropy_source_self_test_check_bits( const unsigned char *buf,
578                                                         size_t buf_len )
579 {
580     unsigned char set= 0xFF;
581     unsigned char unset = 0x00;
582     size_t i;
583 
584     for( i = 0; i < buf_len; i++ )
585     {
586         set &= buf[i];
587         unset |= buf[i];
588     }
589 
590     return( set == 0xFF || unset == 0x00 );
591 }
592 
593 /*
594  * A test to ensure hat the entropy sources are functioning correctly
595  * and there is no obvious failure. The test performs the following checks:
596  *  - The entropy source is not providing only 0s (all bits unset) or 1s (all
597  *    bits set).
598  *  - The entropy source is not providing values in a pattern. Because the
599  *    hardware could be providing data in an arbitrary length, this check polls
600  *    the hardware entropy source twice and compares the result to ensure they
601  *    are not equal.
602  *  - The error code returned by the entropy source is not an error.
603  */
mbedtls_entropy_source_self_test(int verbose)604 int mbedtls_entropy_source_self_test( int verbose )
605 {
606     int ret = 0;
607     unsigned char buf0[2 * sizeof( unsigned long long int )];
608     unsigned char buf1[2 * sizeof( unsigned long long int )];
609 
610     if( verbose != 0 )
611         mbedtls_printf( "  ENTROPY_BIAS test: " );
612 
613     memset( buf0, 0x00, sizeof( buf0 ) );
614     memset( buf1, 0x00, sizeof( buf1 ) );
615 
616     if( ( ret = mbedtls_entropy_source_self_test_gather( buf0, sizeof( buf0 ) ) ) != 0 )
617         goto cleanup;
618     if( ( ret = mbedtls_entropy_source_self_test_gather( buf1, sizeof( buf1 ) ) ) != 0 )
619         goto cleanup;
620 
621     /* Make sure that the returned values are not all 0 or 1 */
622     if( ( ret = mbedtls_entropy_source_self_test_check_bits( buf0, sizeof( buf0 ) ) ) != 0 )
623         goto cleanup;
624     if( ( ret = mbedtls_entropy_source_self_test_check_bits( buf1, sizeof( buf1 ) ) ) != 0 )
625         goto cleanup;
626 
627     /* Make sure that the entropy source is not returning values in a
628      * pattern */
629     ret = memcmp( buf0, buf1, sizeof( buf0 ) ) == 0;
630 
631 cleanup:
632     if( verbose != 0 )
633     {
634         if( ret != 0 )
635             mbedtls_printf( "failed\n" );
636         else
637             mbedtls_printf( "passed\n" );
638 
639         mbedtls_printf( "\n" );
640     }
641 
642     return( ret != 0 );
643 }
644 
645 #endif /* MBEDTLS_ENTROPY_HARDWARE_ALT */
646 
647 /*
648  * The actual entropy quality is hard to test, but we can at least
649  * test that the functions don't cause errors and write the correct
650  * amount of data to buffers.
651  */
mbedtls_entropy_self_test(int verbose)652 int mbedtls_entropy_self_test( int verbose )
653 {
654     int ret = 1;
655 #if !defined(MBEDTLS_TEST_NULL_ENTROPY)
656     mbedtls_entropy_context ctx;
657     unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };
658     unsigned char acc[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };
659     size_t i, j;
660 #endif /* !MBEDTLS_TEST_NULL_ENTROPY */
661 
662     if( verbose != 0 )
663         mbedtls_printf( "  ENTROPY test: " );
664 
665 #if !defined(MBEDTLS_TEST_NULL_ENTROPY)
666     mbedtls_entropy_init( &ctx );
667 
668     /* First do a gather to make sure we have default sources */
669     if( ( ret = mbedtls_entropy_gather( &ctx ) ) != 0 )
670         goto cleanup;
671 
672     ret = mbedtls_entropy_add_source( &ctx, entropy_dummy_source, NULL, 16,
673                                       MBEDTLS_ENTROPY_SOURCE_WEAK );
674     if( ret != 0 )
675         goto cleanup;
676 
677     if( ( ret = mbedtls_entropy_update_manual( &ctx, buf, sizeof buf ) ) != 0 )
678         goto cleanup;
679 
680     /*
681      * To test that mbedtls_entropy_func writes correct number of bytes:
682      * - use the whole buffer and rely on ASan to detect overruns
683      * - collect entropy 8 times and OR the result in an accumulator:
684      *   any byte should then be 0 with probably 2^(-64), so requiring
685      *   each of the 32 or 64 bytes to be non-zero has a false failure rate
686      *   of at most 2^(-58) which is acceptable.
687      */
688     for( i = 0; i < 8; i++ )
689     {
690         if( ( ret = mbedtls_entropy_func( &ctx, buf, sizeof( buf ) ) ) != 0 )
691             goto cleanup;
692 
693         for( j = 0; j < sizeof( buf ); j++ )
694             acc[j] |= buf[j];
695     }
696 
697     for( j = 0; j < sizeof( buf ); j++ )
698     {
699         if( acc[j] == 0 )
700         {
701             ret = 1;
702             goto cleanup;
703         }
704     }
705 
706 #if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
707     if( ( ret = mbedtls_entropy_source_self_test( 0 ) ) != 0 )
708         goto cleanup;
709 #endif
710 
711 cleanup:
712     mbedtls_entropy_free( &ctx );
713 #endif /* !MBEDTLS_TEST_NULL_ENTROPY */
714 
715     if( verbose != 0 )
716     {
717         if( ret != 0 )
718             mbedtls_printf( "failed\n" );
719         else
720             mbedtls_printf( "passed\n" );
721 
722         mbedtls_printf( "\n" );
723     }
724 
725     return( ret != 0 );
726 }
727 #endif /* MBEDTLS_SELF_TEST */
728 
729 #endif /* MBEDTLS_ENTROPY_C */
730