forked from wolfSSL/wolfssl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom.c
More file actions
3900 lines (3322 loc) · 110 KB
/
random.c
File metadata and controls
3900 lines (3322 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* random.c
*
* Copyright (C) 2006-2025 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* wolfSSL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
/*
DESCRIPTION
This library contains implementation for the random number generator.
*/
/* Possible defines:
* ENTROPY_NUM_UPDATE default: 18
* Number of updates to perform. A hash is created and memory accessed
* based on the hash values in each update of a sample.
* More updates will result in better entropy quality but longer sample
* times.
* ENTROPY_NUM_UPDATES_BITS default: 5
* Number of bits needed to represent ENTROPY_NUM_UPDATE.
* = upper(log2(ENTROPY_NUM_UPDATE))
* ENTROPY_NUM_WORDS_BITS default: 14
* State has 2^ENTROPY_NUMN_WORDS_BITS entries. Range: 8-30
* The value should be based on the cache sizes.
* Use a value that is at least as large as the L1 cache if possible.
* The higher the value, the more likely there will be cache misses and
* better the entropy quality.
* A larger value will use more static memory.
*/
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
/* on HPUX 11 you may need to install /dev/random see
http://h20293.www2.hp.com/portal/swdepot/displayProductInfo.do?productNumber=KRNG11I
*/
#if defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 5
#include <esp_random.h>
#endif
#if defined(HAVE_FIPS) && \
defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)
/* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
#define FIPS_NO_WRAPPERS
#ifdef USE_WINDOWS_API
#pragma code_seg(".fipsA$i")
#pragma const_seg(".fipsB$i")
#endif
#endif
#include <wolfssl/wolfcrypt/random.h>
#ifdef WC_RNG_BANK_SUPPORT
#include <wolfssl/wolfcrypt/rng_bank.h>
#endif
#include <wolfssl/wolfcrypt/cpuid.h>
#ifndef WC_NO_RNG /* if not FIPS and RNG is disabled then do not compile */
#include <wolfssl/wolfcrypt/sha256.h>
#ifdef WOLF_CRYPTO_CB
#include <wolfssl/wolfcrypt/cryptocb.h>
#endif
#ifdef NO_INLINE
#include <wolfssl/wolfcrypt/misc.h>
#else
#define WOLFSSL_MISC_INCLUDED
#include <wolfcrypt/src/misc.c>
#endif
#if defined(WOLFSSL_SGX)
#include <sgx_trts.h>
#elif defined(USE_WINDOWS_API)
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0400
#endif
#define _WINSOCKAPI_ /* block inclusion of winsock.h header file */
#include <windows.h>
#include <wincrypt.h>
#undef _WINSOCKAPI_ /* undefine it for MINGW winsock2.h header file */
#elif defined(HAVE_WNR)
#include <wnr.h>
wolfSSL_Mutex wnr_mutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(wnr_mutex); /* global netRandom mutex */
int wnr_timeout = 0; /* entropy timeout, milliseconds */
#ifndef WOLFSSL_MUTEX_INITIALIZER
int wnr_mutex_inited = 0; /* flag for mutex init */
#endif
int wnr_inited = 0; /* flag for whether wc_InitNetRandom() has been called */
wnr_context* wnr_ctx; /* global netRandom context */
#elif defined(FREESCALE_KSDK_2_0_TRNG)
#include "fsl_trng.h"
#elif defined(FREESCALE_KSDK_2_0_RNGA)
#include "fsl_rnga.h"
#elif defined(WOLFSSL_WICED)
#include "wiced_crypto.h"
#elif defined(WOLFSSL_NETBURNER)
#include <predef.h>
#include <basictypes.h>
#include <random.h>
#elif defined(WOLFSSL_XILINX_CRYPT_VERSAL)
#include "wolfssl/wolfcrypt/port/xilinx/xil-versal-trng.h"
#elif defined(WOLFSSL_RPIPICO)
#include "wolfssl/wolfcrypt/port/rpi_pico/pico.h"
#elif defined(NO_DEV_RANDOM)
#elif defined(CUSTOM_RAND_GENERATE)
#elif defined(CUSTOM_RAND_GENERATE_BLOCK)
#elif defined(CUSTOM_RAND_GENERATE_SEED)
#elif defined(WOLFSSL_GENSEED_FORTEST)
#elif defined(WOLFSSL_MDK_ARM)
#elif defined(WOLFSSL_IAR_ARM)
#elif defined(WOLFSSL_ROWLEY_ARM)
#elif defined(WOLFSSL_EMBOS)
#elif defined(WOLFSSL_DEOS)
#elif defined(MICRIUM)
#elif defined(WOLFSSL_NUCLEUS)
#elif defined(WOLFSSL_PB)
#elif defined(WOLFSSL_ZEPHYR)
#elif defined(WOLFSSL_TELIT_M2MB)
#elif defined(WOLFSSL_RENESAS_TSIP)
/* for wc_tsip_GenerateRandBlock */
#include "wolfssl/wolfcrypt/port/Renesas/renesas_tsip_internal.h"
#elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_TRNG)
#elif defined(WOLFSSL_IMXRT1170_CAAM)
#elif defined(CY_USING_HAL) && defined(COMPONENT_WOLFSSL)
#include "cyhal_trng.h" /* Infineon/Cypress HAL RNG implementation */
#elif defined(WOLFSSL_MAX3266X) || defined(WOLFSSL_MAX3266X_OLD)
#include "wolfssl/wolfcrypt/port/maxim/max3266x.h"
#else
#if defined(WOLFSSL_GETRANDOM) || defined(HAVE_GETRANDOM)
#include <errno.h>
#include <sys/random.h>
#endif
/* include headers that may be needed to get good seed */
#include <fcntl.h>
#ifndef EBSNET
#include <unistd.h>
#endif
#endif
#if defined(WOLFSSL_SILABS_SE_ACCEL)
#include <wolfssl/wolfcrypt/port/silabs/silabs_random.h>
#endif
#if defined(WOLFSSL_IOTSAFE) && defined(HAVE_IOTSAFE_HWRNG)
#include <wolfssl/wolfcrypt/port/iotsafe/iotsafe.h>
#endif
#if defined(WOLFSSL_HAVE_PSA) && !defined(WOLFSSL_PSA_NO_RNG)
#include <wolfssl/wolfcrypt/port/psa/psa.h>
#endif
#if FIPS_VERSION3_GE(6,0,0)
const unsigned int wolfCrypt_FIPS_drbg_ro_sanity[2] =
{ 0x1a2b3c4d, 0x00000011 };
int wolfCrypt_FIPS_DRBG_sanity(void)
{
return 0;
}
#endif
#if defined(HAVE_INTEL_RDRAND) || defined(HAVE_INTEL_RDSEED) || \
defined(HAVE_AMD_RDSEED)
static cpuid_flags_t intel_flags = WC_CPUID_INITIALIZER;
static void wc_InitRng_IntelRD(void)
{
cpuid_get_flags_ex(&intel_flags);
}
#if defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED)
static int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, word32 sz);
#endif
#ifdef HAVE_INTEL_RDRAND
static int wc_GenerateRand_IntelRD(OS_Seed* os, byte* output, word32 sz);
#endif
#ifdef USE_WINDOWS_API
#define USE_INTEL_INTRINSICS
#elif !defined __GNUC__ || defined __clang__ || __GNUC__ > 4
#define USE_INTEL_INTRINSICS
#else
#undef USE_INTEL_INTRINSICS
#endif
#ifdef USE_INTEL_INTRINSICS
#include <immintrin.h>
/* Before clang 7 or GCC 9, immintrin.h did not define _rdseed64_step() */
#ifndef HAVE_INTEL_RDSEED
#elif defined __clang__ && __clang_major__ > 6
#elif !defined __GNUC__
#elif __GNUC__ > 8
#else
#ifndef __clang__
#pragma GCC push_options
#pragma GCC target("rdseed")
#else
#define __RDSEED__
#endif
#include <x86intrin.h>
#ifndef __clang__
#pragma GCC pop_options
#endif
#endif
#endif /* USE_WINDOWS_API */
#endif
/* Start NIST DRBG code */
#ifdef HAVE_HASHDRBG
#define OUTPUT_BLOCK_LEN (WC_SHA256_DIGEST_SIZE)
#define MAX_REQUEST_LEN (0x10000)
#ifdef WC_RNG_SEED_CB
#ifndef HAVE_FIPS
static wc_RngSeed_Cb seedCb = wc_GenerateSeed;
#else
static wc_RngSeed_Cb seedCb = NULL;
#endif
int wc_SetSeed_Cb(wc_RngSeed_Cb cb)
{
seedCb = cb;
return 0;
}
#endif
/* Internal return codes */
#define DRBG_SUCCESS 0
#define DRBG_FAILURE 1
#define DRBG_NEED_RESEED 2
#define DRBG_CONT_FAILURE 3
#define DRBG_NO_SEED_CB 4
/* RNG health states */
#define DRBG_NOT_INIT WC_DRBG_NOT_INIT
#define DRBG_OK WC_DRBG_OK
#define DRBG_FAILED WC_DRBG_FAILED
#define DRBG_CONT_FAILED WC_DRBG_CONT_FAILED
#define SEED_SZ WC_DRBG_SEED_SZ
#define MAX_SEED_SZ WC_DRBG_MAX_SEED_SZ
/* Verify max gen block len */
#if RNG_MAX_BLOCK_LEN > MAX_REQUEST_LEN
#error RNG_MAX_BLOCK_LEN is larger than NIST DBRG max request length
#endif
enum {
drbgInitC = 0,
drbgReseed = 1,
drbgGenerateW = 2,
drbgGenerateH = 3,
drbgInitV = 4
};
typedef struct DRBG_internal DRBG_internal;
static int wc_RNG_HealthTestLocal(WC_RNG* rng, int reseed, void* heap,
int devId);
/* Hash Derivation Function */
/* Returns: DRBG_SUCCESS or DRBG_FAILURE */
static int Hash_df(DRBG_internal* drbg, byte* out, word32 outSz, byte type,
const byte* inA, word32 inASz,
const byte* inB, word32 inBSz)
{
int ret = DRBG_FAILURE;
byte ctr;
word32 i;
word32 len;
word32 bits = (outSz * 8); /* reverse byte order */
#ifdef WOLFSSL_SMALL_STACK_CACHE
wc_Sha256* sha = &drbg->sha256;
#else
wc_Sha256 sha[1];
#endif
#if defined(WOLFSSL_SMALL_STACK_CACHE)
byte* digest = drbg->digest_scratch;
#elif defined(WOLFSSL_SMALL_STACK)
byte* digest;
#else
byte digest[WC_SHA256_DIGEST_SIZE];
#endif
if (drbg == NULL) {
return DRBG_FAILURE;
}
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE)
digest = (byte*)XMALLOC(WC_SHA256_DIGEST_SIZE, drbg->heap,
DYNAMIC_TYPE_DIGEST);
if (digest == NULL)
return DRBG_FAILURE;
#endif
#ifdef LITTLE_ENDIAN_ORDER
bits = ByteReverseWord32(bits);
#endif
len = (outSz / OUTPUT_BLOCK_LEN)
+ ((outSz % OUTPUT_BLOCK_LEN) ? 1 : 0);
ctr = 1;
for (i = 0; i < len; i++) {
#ifndef WOLFSSL_SMALL_STACK_CACHE
#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId);
#else
ret = wc_InitSha256(sha);
#endif
if (ret != 0)
break;
#endif
ret = wc_Sha256Update(sha, &ctr, sizeof(ctr));
if (ret == 0) {
ctr++;
ret = wc_Sha256Update(sha, (byte*)&bits, sizeof(bits));
}
if (ret == 0) {
/* churning V is the only string that doesn't have the type added */
if (type != drbgInitV)
ret = wc_Sha256Update(sha, &type, sizeof(type));
}
if (ret == 0)
ret = wc_Sha256Update(sha, inA, inASz);
if (ret == 0) {
if (inB != NULL && inBSz > 0)
ret = wc_Sha256Update(sha, inB, inBSz);
}
if (ret == 0)
ret = wc_Sha256Final(sha, digest);
#ifndef WOLFSSL_SMALL_STACK_CACHE
wc_Sha256Free(sha);
#endif
if (ret == 0) {
if (outSz > OUTPUT_BLOCK_LEN) {
XMEMCPY(out, digest, OUTPUT_BLOCK_LEN);
outSz -= OUTPUT_BLOCK_LEN;
out += OUTPUT_BLOCK_LEN;
}
else {
XMEMCPY(out, digest, outSz);
}
}
}
ForceZero(digest, WC_SHA256_DIGEST_SIZE);
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE)
XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST);
#endif
#ifdef WC_VERBOSE_RNG
if (ret != 0)
WOLFSSL_DEBUG_PRINTF("ERROR: %s failed with err = %d", __FUNCTION__,
ret);
#endif
return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
}
/* Returns: DRBG_SUCCESS or DRBG_FAILURE */
static int Hash_DRBG_Reseed(DRBG_internal* drbg, const byte* seed, word32 seedSz)
{
int ret;
WC_DECLARE_VAR(newV, byte, DRBG_SEED_LEN, 0);
if (drbg == NULL) {
return DRBG_FAILURE;
}
#ifdef WOLFSSL_SMALL_STACK_CACHE
newV = drbg->seed_scratch;
#else
WC_ALLOC_VAR_EX(newV, byte, DRBG_SEED_LEN, drbg->heap,
DYNAMIC_TYPE_TMP_BUFFER, return MEMORY_E);
#endif
XMEMSET(newV, 0, DRBG_SEED_LEN);
ret = Hash_df(drbg, newV, DRBG_SEED_LEN, drbgReseed,
drbg->V, sizeof(drbg->V), seed, seedSz);
if (ret == DRBG_SUCCESS) {
XMEMCPY(drbg->V, newV, sizeof(drbg->V));
ForceZero(newV, DRBG_SEED_LEN);
ret = Hash_df(drbg, drbg->C, sizeof(drbg->C), drbgInitC, drbg->V,
sizeof(drbg->V), NULL, 0);
}
if (ret == DRBG_SUCCESS) {
drbg->reseedCtr = 1;
}
#ifndef WOLFSSL_SMALL_STACK_CACHE
WC_FREE_VAR_EX(newV, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
#ifdef WC_VERBOSE_RNG
if (ret != 0)
WOLFSSL_DEBUG_PRINTF("ERROR: Hash_DRBG_Reseed failed with err %d.",
ret);
#endif
return ret;
}
/* Returns: DRBG_SUCCESS and DRBG_FAILURE or BAD_FUNC_ARG on fail */
int wc_RNG_DRBG_Reseed(WC_RNG* rng, const byte* seed, word32 seedSz)
{
if (rng == NULL || seed == NULL) {
return BAD_FUNC_ARG;
}
if (rng->drbg == NULL) {
#if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND)
if (IS_INTEL_RDRAND(intel_flags)) {
/* using RDRAND not DRBG, so return success */
return 0;
}
return BAD_FUNC_ARG;
#endif
}
return Hash_DRBG_Reseed((DRBG_internal *)rng->drbg, seed, seedSz);
}
static WC_INLINE void array_add_one(byte* data, word32 dataSz)
{
int i;
for (i = (int)dataSz - 1; i >= 0; i--) {
data[i]++;
if (data[i] != 0) break;
}
}
/* Returns: DRBG_SUCCESS or DRBG_FAILURE */
static int Hash_gen(DRBG_internal* drbg, byte* out, word32 outSz, const byte* V)
{
int ret = DRBG_FAILURE;
word32 i;
word32 len;
#if defined(WOLFSSL_SMALL_STACK_CACHE)
wc_Sha256* sha = &drbg->sha256;
byte* data = drbg->seed_scratch;
byte* digest = drbg->digest_scratch;
#elif defined(WOLFSSL_SMALL_STACK)
wc_Sha256 sha[1];
byte* data = NULL;
byte* digest = NULL;
#else
wc_Sha256 sha[1];
byte data[DRBG_SEED_LEN];
byte digest[WC_SHA256_DIGEST_SIZE];
#endif
if (drbg == NULL) {
return DRBG_FAILURE;
}
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE)
data = (byte*)XMALLOC(DRBG_SEED_LEN, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER);
digest = (byte*)XMALLOC(WC_SHA256_DIGEST_SIZE, drbg->heap,
DYNAMIC_TYPE_DIGEST);
if (data == NULL || digest == NULL) {
XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST);
XFREE(data, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER);
return DRBG_FAILURE;
}
#endif
/* Special case: outSz is 0 and out is NULL. wc_Generate a block to save for
* the continuous test. */
if (outSz == 0) {
outSz = 1;
}
len = (outSz / OUTPUT_BLOCK_LEN) + ((outSz % OUTPUT_BLOCK_LEN) ? 1 : 0);
XMEMCPY(data, V, DRBG_SEED_LEN);
for (i = 0; i < len; i++) {
#ifndef WOLFSSL_SMALL_STACK_CACHE
#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId);
#else
ret = wc_InitSha256(sha);
#endif
if (ret == 0)
#endif
ret = wc_Sha256Update(sha, data, DRBG_SEED_LEN);
if (ret == 0)
ret = wc_Sha256Final(sha, digest);
#ifndef WOLFSSL_SMALL_STACK_CACHE
wc_Sha256Free(sha);
#endif
if (ret == 0) {
if (out != NULL && outSz != 0) {
if (outSz >= OUTPUT_BLOCK_LEN) {
XMEMCPY(out, digest, OUTPUT_BLOCK_LEN);
outSz -= OUTPUT_BLOCK_LEN;
out += OUTPUT_BLOCK_LEN;
array_add_one(data, DRBG_SEED_LEN);
}
else {
XMEMCPY(out, digest, outSz);
outSz = 0;
}
}
}
else {
/* wc_Sha256Update or wc_Sha256Final returned error */
break;
}
}
ForceZero(data, DRBG_SEED_LEN);
#ifndef WOLFSSL_SMALL_STACK_CACHE
WC_FREE_VAR_EX(digest, drbg->heap, DYNAMIC_TYPE_DIGEST);
WC_FREE_VAR_EX(data, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
#ifdef WC_VERBOSE_RNG
if ((ret != DRBG_SUCCESS) && (ret != DRBG_FAILURE)) {
/* Note, if we're just going to return DRBG_FAILURE to the caller, then
* there's no point printing it out here because (1) the lower-level
* code that was remapped to DRBG_FAILURE already got printed before the
* remapping, so a DRBG_FAILURE message would just be spamming the log,
* and (2) the caller will actually see the DRBG_FAILURE code, and is
* free to (and probably will) log it itself.
*/
WOLFSSL_DEBUG_PRINTF("ERROR: Hash_gen failed with err %d.", ret);
}
#endif
return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
}
static WC_INLINE void array_add(byte* d, word32 dLen, const byte* s, word32 sLen)
{
if (dLen > 0 && sLen > 0 && dLen >= sLen) {
int sIdx, dIdx;
word16 carry = 0;
dIdx = (int)dLen - 1;
for (sIdx = (int)sLen - 1; sIdx >= 0; sIdx--) {
carry = (word16)(carry + d[dIdx] + s[sIdx]);
d[dIdx] = (byte)carry;
carry >>= 8;
dIdx--;
}
for (; dIdx >= 0; dIdx--) {
carry = (word16)(carry + d[dIdx]);
d[dIdx] = (byte)carry;
carry >>= 8;
}
}
}
/* Returns: DRBG_SUCCESS, DRBG_NEED_RESEED, or DRBG_FAILURE */
static int Hash_DRBG_Generate(DRBG_internal* drbg, byte* out, word32 outSz)
{
int ret;
#ifdef WOLFSSL_SMALL_STACK_CACHE
wc_Sha256* sha = &drbg->sha256;
#else
wc_Sha256 sha[1];
#endif
byte type;
#ifdef WORD64_AVAILABLE
word64 reseedCtr;
#else
word32 reseedCtr;
#endif
if (drbg == NULL) {
return DRBG_FAILURE;
}
if (drbg->reseedCtr >= WC_RESEED_INTERVAL) {
#if (defined(DEBUG_WOLFSSL) || defined(DEBUG_DRBG_RESEEDS)) && \
defined(WOLFSSL_DEBUG_PRINTF)
WOLFSSL_DEBUG_PRINTF("DRBG reseed triggered, reseedCtr == %lu",
(unsigned long)drbg->reseedCtr);
#endif
return DRBG_NEED_RESEED;
}
else {
#if defined(WOLFSSL_SMALL_STACK_CACHE)
byte* digest = drbg->digest_scratch;
#elif defined(WOLFSSL_SMALL_STACK)
byte* digest = (byte*)XMALLOC(WC_SHA256_DIGEST_SIZE, drbg->heap,
DYNAMIC_TYPE_DIGEST);
if (digest == NULL)
return DRBG_FAILURE;
#else
byte digest[WC_SHA256_DIGEST_SIZE];
#endif
type = drbgGenerateH;
reseedCtr = drbg->reseedCtr;
ret = Hash_gen(drbg, out, outSz, drbg->V);
if (ret == DRBG_SUCCESS) {
#ifndef WOLFSSL_SMALL_STACK_CACHE
#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId);
#else
ret = wc_InitSha256(sha);
#endif
if (ret == 0)
#endif
ret = wc_Sha256Update(sha, &type, sizeof(type));
if (ret == 0)
ret = wc_Sha256Update(sha, drbg->V, sizeof(drbg->V));
if (ret == 0)
ret = wc_Sha256Final(sha, digest);
#ifndef WOLFSSL_SMALL_STACK_CACHE
wc_Sha256Free(sha);
#endif
if (ret == 0) {
array_add(drbg->V, sizeof(drbg->V), digest, WC_SHA256_DIGEST_SIZE);
array_add(drbg->V, sizeof(drbg->V), drbg->C, sizeof(drbg->C));
#ifdef LITTLE_ENDIAN_ORDER
#ifdef WORD64_AVAILABLE
reseedCtr = ByteReverseWord64(reseedCtr);
#else
reseedCtr = ByteReverseWord32(reseedCtr);
#endif
#endif
array_add(drbg->V, sizeof(drbg->V),
(byte*)&reseedCtr, sizeof(reseedCtr));
ret = DRBG_SUCCESS;
}
drbg->reseedCtr++;
}
ForceZero(digest, WC_SHA256_DIGEST_SIZE);
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE)
XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST);
#endif
}
#ifdef WC_VERBOSE_RNG
if ((ret != DRBG_SUCCESS) && (ret != DRBG_FAILURE)) {
/* see note above regarding log spam reduction */
WOLFSSL_DEBUG_PRINTF("ERROR: Hash_DRBG_Generate failed with err %d.",
ret);
}
#endif
return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
}
/* Returns: DRBG_SUCCESS or DRBG_FAILURE */
static int Hash_DRBG_Init(DRBG_internal* drbg, const byte* seed, word32 seedSz,
const byte* nonce, word32 nonceSz)
{
if (seed == NULL)
return DRBG_FAILURE;
if (Hash_df(drbg, drbg->V, sizeof(drbg->V), drbgInitV, seed, seedSz,
nonce, nonceSz) == DRBG_SUCCESS &&
Hash_df(drbg, drbg->C, sizeof(drbg->C), drbgInitC, drbg->V,
sizeof(drbg->V), NULL, 0) == DRBG_SUCCESS) {
drbg->reseedCtr = 1;
return DRBG_SUCCESS;
}
else {
return DRBG_FAILURE;
}
}
/* Returns: DRBG_SUCCESS or DRBG_FAILURE */
static int Hash_DRBG_Instantiate(DRBG_internal* drbg, const byte* seed, word32 seedSz,
const byte* nonce, word32 nonceSz,
void* heap, int devId)
{
int ret = DRBG_FAILURE;
XMEMSET(drbg, 0, sizeof(DRBG_internal));
drbg->heap = heap;
#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
drbg->devId = devId;
#else
(void)devId;
#endif
#ifdef WOLFSSL_SMALL_STACK_CACHE
#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
ret = wc_InitSha256_ex(&drbg->sha256, drbg->heap, drbg->devId);
#else
ret = wc_InitSha256(&drbg->sha256);
#endif
if (ret != 0)
return ret;
#endif
if (seed != NULL)
ret = Hash_DRBG_Init(drbg, seed, seedSz, nonce, nonceSz);
return ret;
}
/* Returns: DRBG_SUCCESS or DRBG_FAILURE */
static int Hash_DRBG_Uninstantiate(DRBG_internal* drbg)
{
word32 i;
int compareSum = 0;
byte* compareDrbg = (byte*)drbg;
#ifdef WOLFSSL_SMALL_STACK_CACHE
wc_Sha256Free(&drbg->sha256);
#endif
ForceZero(drbg, sizeof(DRBG_internal));
for (i = 0; i < sizeof(DRBG_internal); i++) {
compareSum |= compareDrbg[i] ^ 0;
}
return (compareSum == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
}
/* FIPS 140-3 IG 10.3.A / SP800-90B Health Tests for Seed Data
*
* These tests replace the older FIPS 140-2 Continuous Random Number Generator
* Test (CRNGT) with more mathematically robust statistical tests per
* ISO 19790 / SP800-90B requirements.
*
* When HAVE_ENTROPY_MEMUSE is defined, the wolfentropy.c jitter-based TRNG
* performs another set of these health tests, but those are on the noise not
* the conditioned output so we still need to retest here even in that case
* to evaluate the conditioned output for the same behavior. These tests ensure
* the seed data meets basic entropy requirements regardless of the source.
*/
/* SP800-90B 4.4.1 - Repetition Count Test
* Detects if the noise source becomes "stuck" producing repeated output.
*
* C = 1 + ceil(-log2(alpha) / H)
* For alpha = 2^-30 (false positive probability) and H = 1 (min entropy):
* C = 1 + ceil(30 / 1) = 31
*/
#ifndef WC_RNG_SEED_RCT_CUTOFF
#define WC_RNG_SEED_RCT_CUTOFF 31
#endif
/* SP800-90B 4.4.2 - Adaptive Proportion Test
* Monitors if a particular sample value appears too frequently within a
* window of samples, indicating loss of entropy.
*
* Window size W = 512 for non-binary alphabet (byte values 0-255)
* C = 1 + CRITBINOM(W, 2^(-H), 1-alpha)
* For alpha = 2^-30 and H = 1, W = 512:
* C = 1 + CRITBINOM(512, 0.5, 1-2^-30) = 325
*/
#ifndef WC_RNG_SEED_APT_WINDOW
#define WC_RNG_SEED_APT_WINDOW 512
#endif
#ifndef WC_RNG_SEED_APT_CUTOFF
#define WC_RNG_SEED_APT_CUTOFF 325
#endif
int wc_RNG_TestSeed(const byte* seed, word32 seedSz)
{
int ret = 0;
word32 i;
int rctFailed = 0;
int aptFailed = 0;
if (seed == NULL || seedSz < SEED_BLOCK_SZ) {
return BAD_FUNC_ARG;
}
/* SP800-90B 4.4.1 - Repetition Count Test (RCT)
* Check for consecutive identical bytes that would indicate a stuck
* entropy source. Fail if we see WC_RNG_SEED_RCT_CUTOFF or more
* consecutive identical values.
*
* Constant-time implementation: always process full seed, accumulate
* failure status without early exit to prevent timing side-channels.
*/
{
int repCount = 1;
byte prevByte = seed[0];
for (i = 1; i < seedSz; i++) {
/* Constant-time: always evaluate both branches effects */
int match = (seed[i] == prevByte);
/* If match, increment count, if not, reset to 1 */
repCount = (match * (repCount + 1)) + (!match * 1);
/* Update prevByte only when not matching (new value) */
prevByte = (byte) ((match * prevByte) + (!match * seed[i]));
/* Accumulate failure flag - once set, stays set */
rctFailed |= (repCount >= WC_RNG_SEED_RCT_CUTOFF);
}
}
/* SP800-90B 4.4.2 - Adaptive Proportion Test (APT)
* Check that no single byte value appears too frequently within
* a sliding window. This detects bias in the entropy source.
*
* For seeds smaller than the window size, we test the entire seed.
* For larger seeds, we use a sliding window approach.
*
* Constant-time implementation: always process full seed and check
* all counts to prevent timing side-channels.
*/
{
word16 byteCounts[MAX_ENTROPY_BITS];
word32 windowSize = min(seedSz, (word32)WC_RNG_SEED_APT_WINDOW);
word32 windowStart = 0;
word32 newIdx;
XMEMSET(byteCounts, 0, sizeof(byteCounts));
/* Initialize counts for first window */
for (i = 0; i < windowSize; i++) {
byteCounts[seed[i]]++;
}
/* Check first window - scan all 256 counts */
for (i = 0; i < MAX_ENTROPY_BITS; i++) {
aptFailed |= (byteCounts[i] >= WC_RNG_SEED_APT_CUTOFF);
}
/* Slide window through remaining seed data */
while ((windowStart + windowSize) < seedSz) {
/* Remove byte leaving the window */
byteCounts[seed[windowStart]]--;
windowStart++;
/* Add byte entering the window */
newIdx = windowStart + windowSize - 1;
byteCounts[seed[newIdx]]++;
/* Accumulate failure flag for new byte's count */
aptFailed |= (byteCounts[seed[newIdx]] >= WC_RNG_SEED_APT_CUTOFF);
}
}
/* Set return code based on accumulated failure flags */
if (rctFailed) {
ret = ENTROPY_RT_E;
}
else if (aptFailed) {
ret = ENTROPY_APT_E;
}
return ret;
}
#endif /* HAVE_HASHDRBG */
/* End NIST DRBG Code */
static int _InitRng(WC_RNG* rng, byte* nonce, word32 nonceSz,
void* heap, int devId)
{
int ret = 0;
#ifdef HAVE_HASHDRBG
#if !defined(HAVE_FIPS) && defined(WOLFSSL_RNG_USE_FULL_SEED)
word32 seedSz = SEED_SZ;
#else
word32 seedSz = SEED_SZ + SEED_BLOCK_SZ;
WC_DECLARE_VAR(seed, byte, MAX_SEED_SZ, rng->heap);
#ifdef WOLFSSL_SMALL_STACK_CACHE
int drbg_scratch_instantiated = 0;
#endif
#endif
#endif
(void)nonce;
(void)nonceSz;
if (rng == NULL)
return BAD_FUNC_ARG;
if (nonce == NULL && nonceSz != 0)
return BAD_FUNC_ARG;
XMEMSET(rng, 0, sizeof(*rng));
#ifdef WOLFSSL_HEAP_TEST
rng->heap = (void*)WOLFSSL_HEAP_TEST;
(void)heap;
#else
rng->heap = heap;
#endif
#if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID)
rng->pid = getpid();
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
rng->devId = devId;
#if defined(WOLF_CRYPTO_CB)
rng->seed.devId = devId;
#endif
#else
(void)devId;
#endif
#ifdef HAVE_HASHDRBG
/* init the DBRG to known values */
rng->drbg = NULL;
#ifdef WOLFSSL_SMALL_STACK_CACHE
rng->drbg_scratch = NULL;
#endif
rng->status = DRBG_NOT_INIT;
#endif
#if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND) || \
defined(HAVE_AMD_RDSEED)
/* init the intel RD seed and/or rand */
wc_InitRng_IntelRD();
#endif
/* configure async RNG source if available */
#ifdef WOLFSSL_ASYNC_CRYPT
ret = wolfAsync_DevCtxInit(&rng->asyncDev, WOLFSSL_ASYNC_MARKER_RNG,
rng->heap, rng->devId);
if (ret != 0) {
#ifdef HAVE_HASHDRBG
rng->status = DRBG_OK;
#endif
return ret;
}
#endif
#ifdef HAVE_INTEL_RDRAND
/* if CPU supports RDRAND, use it directly and by-pass DRBG init */
if (IS_INTEL_RDRAND(intel_flags)) {
#ifdef HAVE_HASHDRBG
rng->status = DRBG_OK;
#endif
return 0;
}
#endif
#ifdef WOLFSSL_XILINX_CRYPT_VERSAL
ret = wc_VersalTrngInit(nonce, nonceSz);
if (ret) {
#ifdef HAVE_HASHDRBG
rng->status = DRBG_OK;
#endif
return ret;
}
#endif
#if defined(WOLFSSL_KEEP_RNG_SEED_FD_OPEN) && !defined(USE_WINDOWS_API)
if (!rng->seed.seedFdOpen)
rng->seed.fd = XBADFD;
#endif
#ifdef CUSTOM_RAND_GENERATE_BLOCK
ret = 0; /* success */
#else
/* not CUSTOM_RAND_GENERATE_BLOCK follows */
#ifdef HAVE_HASHDRBG
if (nonceSz == 0) {
seedSz = MAX_SEED_SZ;
}
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
rng->drbg =
(struct DRBG*)XMALLOC(sizeof(DRBG_internal), rng->heap,
DYNAMIC_TYPE_RNG);
if (rng->drbg == NULL) {
#if defined(DEBUG_WOLFSSL)
WOLFSSL_MSG_EX("_InitRng XMALLOC failed to allocate %d bytes",
sizeof(DRBG_internal));
#endif
ret = MEMORY_E;
rng->status = DRBG_FAILED;
}
#else