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