-
Notifications
You must be signed in to change notification settings - Fork 801
/
random.c
3930 lines (3334 loc) · 109 KB
/
random.c
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-2023 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 2 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.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <wolfssl/wolfcrypt/settings.h>
#include <wolfssl/wolfcrypt/error-crypt.h>
#if defined(DEBUG_WOLFSSL)
#include <wolfssl/wolfcrypt/logging.h>
#endif
/* 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$c")
#pragma const_seg(".fipsB$c")
#endif
#endif
#include <wolfssl/wolfcrypt/random.h>
#include <wolfssl/wolfcrypt/cpuid.h>
#ifdef HAVE_ENTROPY_MEMUSE
#include <wolfssl/wolfcrypt/sha3.h>
#if defined(__APPLE__) || defined(__MACH__)
#include <mach/mach_time.h>
#endif
#endif
#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
#include <windows.h>
#include <wincrypt.h>
#elif defined(HAVE_WNR)
#include <wnr.h>
#include <wolfssl/wolfcrypt/logging.h>
wolfSSL_Mutex wnr_mutex; /* global netRandom mutex */
int wnr_timeout = 0; /* entropy timeout, milliseconds */
int wnr_mutex_init = 0; /* flag for mutex init */
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(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_SCE) && !defined(WOLFSSL_SCE_NO_TRNG)
#elif defined(WOLFSSL_IMXRT1170_CAAM)
#elif defined(WOLFSSL_GETRANDOM)
#include <errno.h>
#include <sys/random.h>
#else
/* 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 defined(HAVE_INTEL_RDRAND) || defined(HAVE_INTEL_RDSEED) || \
defined(HAVE_AMD_RDSEED)
static word32 intel_flags = 0;
static void wc_InitRng_IntelRD(void)
{
intel_flags = cpuid_get_flags();
}
#if (defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED)) && \
!defined(WOLFSSL_LINUXKM)
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)
#define RESEED_INTERVAL WC_RESEED_INTERVAL
/* The security strength for the RNG is the target number of bits of
* entropy you are looking for in a seed. */
#ifndef RNG_SECURITY_STRENGTH
/* SHA-256 requires a minimum of 256-bits of entropy. */
#define RNG_SECURITY_STRENGTH (256)
#endif
#ifndef ENTROPY_SCALE_FACTOR
/* The entropy scale factor should be the whole number inverse of the
* minimum bits of entropy per bit of NDRNG output. */
#if defined(HAVE_ENTROPY_MEMUSE)
/* Full strength, conditioned entropy is requested of MemUse Entropy. */
#if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
(HAVE_FIPS_VERSION >= 2)
#define ENTROPY_SCALE_FACTOR (4)
#else
#define ENTROPY_SCALE_FACTOR (1)
#endif
#elif defined(HAVE_AMD_RDSEED)
/* This will yield a SEED_SZ of 16kb. Since nonceSz will be 0,
* we'll add an additional 8kb on top. */
#define ENTROPY_SCALE_FACTOR (512)
#elif defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND)
/* The value of 2 applies to Intel's RDSEED which provides about
* 0.5 bits minimum of entropy per bit. The value of 4 gives a
* conservative margin for FIPS. */
#if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
(HAVE_FIPS_VERSION >= 2)
#define ENTROPY_SCALE_FACTOR (2*4)
#else
/* Not FIPS, but Intel RDSEED, only double. */
#define ENTROPY_SCALE_FACTOR (2)
#endif
#elif defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
(HAVE_FIPS_VERSION >= 2)
/* If doing a FIPS build without a specific scale factor, default
* to 4. This will give 1024 bits of entropy. More is better, but
* more is also slower. */
#define ENTROPY_SCALE_FACTOR (4)
#else
/* Setting the default to 1. */
#define ENTROPY_SCALE_FACTOR (1)
#endif
#endif
#ifndef SEED_BLOCK_SZ
/* The seed block size, is the size of the output of the underlying NDRNG.
* This value is used for testing the output of the NDRNG. */
#if defined(HAVE_AMD_RDSEED)
/* AMD's RDSEED instruction works in 128-bit blocks read 64-bits
* at a time. */
#define SEED_BLOCK_SZ (sizeof(word64)*2)
#elif defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND)
/* RDSEED outputs in blocks of 64-bits. */
#define SEED_BLOCK_SZ sizeof(word64)
#else
/* Setting the default to 4. */
#define SEED_BLOCK_SZ 4
#endif
#endif
#define SEED_SZ (RNG_SECURITY_STRENGTH*ENTROPY_SCALE_FACTOR/8)
/* The maximum seed size will be the seed size plus a seed block for the
* test, and an additional half of the seed size. This additional half
* is in case the user does not supply a nonce. A nonce will be obtained
* from the NDRNG. */
#define MAX_SEED_SZ (SEED_SZ + SEED_SZ/2 + SEED_BLOCK_SZ)
#ifdef WC_RNG_SEED_CB
static wc_RngSeed_Cb seedCb = NULL;
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 0
#define DRBG_OK 1
#define DRBG_FAILED 2
#define DRBG_CONT_FAILED 3
#define RNG_HEALTH_TEST_CHECK_SIZE (WC_SHA256_DIGEST_SIZE * 4)
/* 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(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
#ifdef WOLFSSL_SMALL_STACK
byte* digest;
#else
byte digest[WC_SHA256_DIGEST_SIZE];
#endif
if (drbg == NULL) {
return DRBG_FAILURE;
}
#ifdef WOLFSSL_SMALL_STACK
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);
#ifdef WOLFSSL_SMALL_STACK
XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST);
#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;
#ifdef WOLFSSL_SMALL_STACK
byte* newV;
#else
byte newV[DRBG_SEED_LEN];
#endif
if (drbg == NULL) {
return DRBG_FAILURE;
}
#ifdef WOLFSSL_SMALL_STACK
newV = (byte*)XMALLOC(DRBG_SEED_LEN, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER);
if (newV == NULL) {
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;
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(newV, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER);
#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;
#ifdef WOLFSSL_SMALL_STACK
byte* data;
byte* digest;
#else
byte data[DRBG_SEED_LEN];
byte digest[WC_SHA256_DIGEST_SIZE];
#endif
word32 i;
word32 len;
#ifdef WOLFSSL_SMALL_STACK_CACHE
wc_Sha256* sha = &drbg->sha256;
#else
wc_Sha256 sha[1];
#endif
if (drbg == NULL) {
return DRBG_FAILURE;
}
#ifdef WOLFSSL_SMALL_STACK
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);
#ifdef WOLFSSL_SMALL_STACK
XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST);
XFREE(data, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER);
#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)(d[dIdx] + s[sIdx]);
d[dIdx] = (byte)carry;
carry >>= 8;
dIdx--;
}
for (; dIdx >= 0; dIdx--) {
carry += (word16)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;
word32 reseedCtr;
if (drbg == NULL) {
return DRBG_FAILURE;
}
if (drbg->reseedCtr == RESEED_INTERVAL) {
return DRBG_NEED_RESEED;
}
else {
#ifndef WOLFSSL_SMALL_STACK
byte digest[WC_SHA256_DIGEST_SIZE];
#else
byte* digest = (byte*)XMALLOC(WC_SHA256_DIGEST_SIZE, drbg->heap,
DYNAMIC_TYPE_DIGEST);
if (digest == NULL)
return DRBG_FAILURE;
#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
reseedCtr = ByteReverseWord32(reseedCtr);
#endif
array_add(drbg->V, sizeof(drbg->V),
(byte*)&reseedCtr, sizeof(reseedCtr));
ret = DRBG_SUCCESS;
}
drbg->reseedCtr++;
}
ForceZero(digest, WC_SHA256_DIGEST_SIZE);
#ifdef WOLFSSL_SMALL_STACK
XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST);
#endif
}
return (ret == 0) ? DRBG_SUCCESS : 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 (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;
ret = DRBG_SUCCESS;
}
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;
}
int wc_RNG_TestSeed(const byte* seed, word32 seedSz)
{
int ret = 0;
/* Check the seed for duplicate words. */
word32 seedIdx = 0;
word32 scratchSz = min(SEED_BLOCK_SZ, seedSz - SEED_BLOCK_SZ);
while (seedIdx < seedSz - SEED_BLOCK_SZ) {
if (ConstantCompare(seed + seedIdx,
seed + seedIdx + scratchSz,
(int)scratchSz) == 0) {
ret = DRBG_CONT_FAILURE;
}
seedIdx += SEED_BLOCK_SZ;
scratchSz = min(SEED_BLOCK_SZ, (seedSz - seedIdx));
}
return ret;
}
#endif /* HAVE_HASHDRBG */
/* End NIST DRBG Code */
#ifdef HAVE_ENTROPY_MEMUSE
/* Define ENTROPY_MEMUSE_THREAD to force use of counter in a new thread.
* Only do this when high resolution timer not otherwise available.
*/
/* Number of bytes that will hold the maximum entropy bits. */
#define MAX_ENTROPY_BYTES (MAX_ENTROPY_BITS / 8)
/* Number of bits stored for one sample. */
#define ENTROPY_BITS_USED 8
/* Minimum entropy from a sample. */
#define ENTROPY_MIN 1
/* Number of extra samples to ensure full entropy. */
#define ENTROPY_EXTRA 64
/* Maximum number of bytes to sample to produce max entropy. */
#define MAX_NOISE_CNT (MAX_ENTROPY_BITS * 8 + ENTROPY_EXTRA)
/* MemUse entropy global state initialized. */
static int entropy_memuse_initialized = 0;
/* Global SHA-3 object used for conditioning entropy and creating noise. */
static wc_Sha3 entropyHash;
/* Reset the health tests. */
static void Entropy_HealthTest_Reset(void);
#if !defined(ENTROPY_MEMUSE_THREAD) && \
(defined(__x86_64__) || defined(__i386__))
/* Get the high resolution time counter.
*
* @return 64-bit count of CPU cycles.
*/
static WC_INLINE word64 Entropy_TimeHiRes(void)
{
unsigned int lo_c, hi_c;
__asm__ __volatile__ (
"rdtsc"
: "=a"(lo_c), "=d"(hi_c) /* out */
: "a"(0) /* in */
: "%ebx", "%ecx"); /* clobber */
return ((word64)lo_c) | (((word64)hi_c) << 32);
}
#elif !defined(ENTROPY_MEMUSE_THREAD) && \
(defined(__APPLE__) || defined(__MACH__))
/* Get the high resolution time counter.
*
* @return 64-bit time in nanoseconds.
*/
static WC_INLINE word64 Entropy_TimeHiRes(void)
{
return mach_absolute_time();
}
#elif !defined(ENTROPY_MEMUSE_THREAD) && defined(__aarch64__)
/* Get the high resolution time counter.
*
* @return 64-bit timer count.
*/
static WC_INLINE word64 Entropy_TimeHiRes(void)
{
word64 cnt;
__asm__ __volatile__ (
"mrs %[cnt], cntvct_el0"
: [cnt] "=r"(cnt)
:
:
);
return cnt;
}
#elif !defined(ENTROPY_MEMUSE_THREAD) && defined(__MICROBLAZE__)
#define LPD_SCNTR_BASE_ADDRESS 0xFF250000
/* Get the high resolution time counter.
* Collect ticks from LPD_SCNTR
* @return 64-bit tick count.
*/
static WC_INLINE word64 Entropy_TimeHiRes(void)
{
word64 cnt;
word32 *ptr;
ptr = (word32*)LPD_SCNTR_BASE_ADDRESS;
cnt = *(ptr+1);
cnt = cnt << 32;
cnt |= *ptr;
return cnt;
}
#elif !defined(ENTROPY_MEMUSE_THREAD) && (_POSIX_C_SOURCE >= 199309L)
/* Get the high resolution time counter.
*
* @return 64-bit time that is the nanoseconds of current time.
*/
static WC_INLINE word64 Entropy_TimeHiRes(void)
{
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
return now.tv_nsec;
}
#elif defined(_WIN32) /* USE_WINDOWS_API */
/* Get the high resolution time counter.
*
* @return 64-bit timer
*/
static WC_INLINE word64 Entropy_TimeHiRes(void)
{
LARGE_INTEGER count;
QueryPerformanceCounter(&count);
return (word64)(count.QuadPart);
}
#elif defined(WOLFSSL_THREAD_NO_JOIN)
/* Start and stop thread that counts as a proxy for time counter. */
#define ENTROPY_MEMUSE_THREADED
/* Data for entropy thread. */
typedef struct ENTROPY_THREAD_DATA {
/* Current counter - proxy for time. */
word64 counter;
/* Whether to stop thread. */
int stop;
} ENTROPY_THREAD_DATA;
/* Track whether entropy thread has been started already. */
static int entropy_thread_started = 0;
/* Data for thread to update/observer. */
static volatile ENTROPY_THREAD_DATA entropy_thread_data = { 0, 0 };
/* Get the high resolution time counter. Counter incremented in thread.
*
* @return 64-bit counter.
*/
static WC_INLINE word64 Entropy_TimeHiRes(void)
{
/* Return counter update in thread. */
return entropy_thread_data.counter;
}
/* Thread that increments counter while not told to stop.
*
* @param [in,out] args Entropy data including: counter and stop flag.
* @return NULL always.
*/
static THREAD_RETURN WOLFSSL_THREAD_NO_JOIN Entropy_IncCounter(void* args)
{
(void)args;
/* Keep going until caller tells us to stop and exit. */
while (!entropy_thread_data.stop) {
/* Increment counter acting as high resolution timer. */
entropy_thread_data.counter++;
}
#ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
fprintf(stderr, "EXITING ENTROPY COUNTER THREAD\n");
#endif
/* Exit from thread. */
WOLFSSL_RETURN_FROM_THREAD(0);
}
/* Start a thread that increments counter if not one already.
*
* Won't start a new thread if one already running.
* Waits for thread to start by waiting for counter to have incremented.
*
* @return 0 on success.
* @return Negative on failure.
*/
static int Entropy_StartThread(void)
{
int ret = 0;
/* Only continue if we haven't started a thread. */
if (!entropy_thread_started) {
/* Get counter before starting thread. */
word64 start_counter = entropy_thread_data.counter;
/* In case of restarting thread, set stop indicator to false. */
entropy_thread_data.stop = 0;
#ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
fprintf(stderr, "STARTING ENTROPY COUNTER THREAD\n");
#endif
/* Create a thread that increments the counter in the data. */
/* Thread resources to be disposed of. */
ret = wolfSSL_NewThreadNoJoin(Entropy_IncCounter, NULL);
if (ret == 0) {
/* Wait for the counter to increase indicating thread started. */
while (entropy_thread_data.counter == start_counter) {
sched_yield();
}
}
entropy_thread_started = (ret == 0);
}
return ret;
}
/* Tell thread to stop and wait for it to complete.
*
* Called by wolfCrypt_Cleanup().
*/
static void Entropy_StopThread(void)
{
/* Only stop a thread if one is running. */
if (entropy_thread_started) {
/* Tell thread to stop. */
entropy_thread_data.stop = 1;
/* Stopped thread so no thread started anymore. */
entropy_thread_started = 0;
}
}
/* end if defined(HAVE_PTHREAD) */
#else
#error "No high precision time available for MemUse Entropy."
#endif
#ifndef ENTROPY_NUM_WORDS_BITS
/* Number of bits to count of 64-bit words in state. */
#define ENTROPY_NUM_WORDS_BITS 14
#endif
/* Floor of 8 yields pool of 256x 64-bit word samples
* 9 -> 512x 64-bit word samples
* 10 -> 1,024x 64-bit word samples
* 11 -> 2,048x 64-bit word samples
* 12 -> 4,096x 64-bit word samples
* 13 -> 8,192x 64-bit word samples
* 14 -> 16,384x 64-bit word samples
* 15 -> 32,768x 64-bit word samples
* ... doubling every time up to a maximum of:
* 30 -> 1,073,741,824x 64-bit word samples
* 1 billion+ samples should be more then sufficient for any use-case
*/
#if ENTROPY_NUM_WORDS_BITS < 8
#error "ENTROPY_NUM_WORDS_BITS must be 8 or more"
#elif ENTROPY_NUM_WORDS_BITS > 30
#error "ENTROPY_NUM_WORDS_BITS must be less than 31"
#endif
/* Number of 64-bit words in state. */
#define ENTROPY_NUM_WORDS (1 << ENTROPY_NUM_WORDS_BITS)
/* Size of one block of 64-bit words. */
#define ENTROPY_BLOCK_SZ (ENTROPY_NUM_WORDS_BITS - 8)
#ifndef ENTROPY_NUM_UPDATES
/* Number of times to update random blocks.
* Less than 2^ENTROPY_BLOCK_SZ (default: 2^6 = 64).