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