/src/wolfssl-sp-math-all-8bit/wolfcrypt/src/random.c
Line | Count | Source |
1 | | /* random.c |
2 | | * |
3 | | * Copyright (C) 2006-2026 wolfSSL Inc. |
4 | | * |
5 | | * This file is part of wolfSSL. |
6 | | * |
7 | | * wolfSSL is free software; you can redistribute it and/or modify |
8 | | * it under the terms of the GNU General Public License as published by |
9 | | * the Free Software Foundation; either version 3 of the License, or |
10 | | * (at your option) any later version. |
11 | | * |
12 | | * wolfSSL is distributed in the hope that it will be useful, |
13 | | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
14 | | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
15 | | * GNU General Public License for more details. |
16 | | * |
17 | | * You should have received a copy of the GNU General Public License |
18 | | * along with this program; if not, write to the Free Software |
19 | | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA |
20 | | */ |
21 | | |
22 | | /* |
23 | | |
24 | | DESCRIPTION |
25 | | This library contains implementation for the random number generator. |
26 | | |
27 | | */ |
28 | | |
29 | | /* |
30 | | * Random Number Generator Build Options: |
31 | | * |
32 | | * Core RNG: |
33 | | * WC_NO_RNG: Disable RNG support entirely default: off |
34 | | * HAVE_HASHDRBG: Enable Hash-based DRBG (SP 800-90A) default: on |
35 | | * WC_RNG_BLOCKING: Make RNG operations blocking default: off |
36 | | * WC_VERBOSE_RNG: Enable verbose RNG debug output default: off |
37 | | * WC_RNG_SEED_CB: Use custom seed callback function default: off |
38 | | * WC_HAVE_RNG_BANKREF: Enable RNG bank indirect RNG default: off |
39 | | * support |
40 | | * WC_RNG_NO_AUTO_LOCK: Leave out the lock that lets threads default: off |
41 | | * share one WC_RNG (lock on unless set) |
42 | | * WC_RNG_WANT_AUTO_LOCK: Keep that lock even where this build default: off |
43 | | * would otherwise skip it |
44 | | * WC_RNG_AUTOFORK: pthread_atfork handlers so a forked default: on |
45 | | * child can keep using its WC_RNG where found |
46 | | * WOLFSSL_RNG_USE_FULL_SEED: Use full-length seed for DRBG default: off |
47 | | * WOLFSSL_GENSEED_FORTEST: Use deterministic seed for testing default: off |
48 | | * WARNING: not for production use |
49 | | * WOLFSSL_KEEP_RNG_SEED_FD_OPEN: Keep /dev/random fd open default: off |
50 | | * between seed operations |
51 | | * |
52 | | * Custom RNG Sources: |
53 | | * CUSTOM_RAND_GENERATE: Custom random word generator func default: off |
54 | | * CUSTOM_RAND_GENERATE_BLOCK: Custom block random generator default: off |
55 | | * CUSTOM_RAND_GENERATE_SEED: Custom seed generator function default: off |
56 | | * CUSTOM_RAND_GENERATE_SEED_OS: Custom OS-level seed generator default: off |
57 | | * |
58 | | * Entropy Sources: |
59 | | * HAVE_ENTROPY_MEMUSE: Enable memory-use based entropy default: off |
60 | | * source for DRBG seeding |
61 | | * ENTROPY_MEMUSE_FORCE_FAILURE: Force entropy failure (testing) default: off |
62 | | * HAVE_GETRANDOM: Use Linux getrandom() syscall default: auto |
63 | | * WOLFSSL_GETRANDOM: Use getrandom() for seed source default: auto |
64 | | * FORCE_FAILURE_GETRANDOM: Force getrandom failure (testing) default: off |
65 | | * NO_DEV_RANDOM: Don't use /dev/random for seeding default: off |
66 | | * NO_DEV_URANDOM: Don't use /dev/urandom for seeding default: off |
67 | | * WC_RNG_SEED_DEVICE: Device tried before the usual seed default: off |
68 | | * sources. Must be a quoted string, |
69 | | * e.g. -DWC_RNG_SEED_DEVICE='"/dev/hwrng"' |
70 | | * HAVE_INTEL_RDRAND: Use Intel RDRAND instruction default: off |
71 | | * HAVE_INTEL_RDSEED: Use Intel RDSEED instruction default: off |
72 | | * HAVE_AMD_RDSEED: Use AMD RDSEED instruction default: off |
73 | | * IDIRECT_DEV_RANDOM: iDirect custom /dev/random path default: off |
74 | | * WIN_REUSE_CRYPT_HANDLE: Reuse Windows CryptContext handle default: off |
75 | | * |
76 | | * Entropy Tuning (for HAVE_ENTROPY_MEMUSE): |
77 | | * ENTROPY_NUM_UPDATE: Number of updates per sample default: 18 |
78 | | * More updates = better entropy but slower |
79 | | * ENTROPY_NUM_UPDATES_BITS: Bits to represent ENTROPY_NUM_UPDATE default: 5 |
80 | | * = upper(log2(ENTROPY_NUM_UPDATE)) |
81 | | * ENTROPY_NUM_WORDS_BITS: State size as 2^N entries default: 14 |
82 | | * Range: 8-30. Base on cache sizes. |
83 | | * Larger = more cache misses = better entropy |
84 | | * but more static memory usage. |
85 | | * |
86 | | * DRBG Health Tests: |
87 | | * WC_RNG_SEED_APT_CUTOFF: Adaptive proportion test cutoff default: auto |
88 | | * WC_RNG_SEED_APT_WINDOW: Adaptive proportion test window size default: auto |
89 | | * WC_RNG_SEED_RCT_CUTOFF: Repetition count test cutoff default: auto |
90 | | * |
91 | | * Hardware RNG: |
92 | | * STM32_RNG: STM32 hardware RNG default: off |
93 | | * STM32_NUTTX_RNG: STM32 RNG via NuttX default: off |
94 | | * WOLFSSL_STM32F427_RNG: STM32F427 hardware RNG default: off |
95 | | * WOLFSSL_STM32_RNG_NOLIB: STM32 RNG without HAL library default: off |
96 | | * WOLFSSL_PIC32MZ_RNG: PIC32MZ hardware RNG default: off |
97 | | * FREESCALE_RNGA: Freescale RNGA default: off |
98 | | * FREESCALE_K70_RNGA: Freescale K70 RNGA default: off |
99 | | * FREESCALE_RNGB: Freescale RNGB default: off |
100 | | * FREESCALE_KSDK_2_0_RNGA: Freescale KSDK 2.0 RNGA default: off |
101 | | * FREESCALE_KSDK_2_0_TRNG: Freescale KSDK 2.0 TRNG default: off |
102 | | * MAX3266X_RNG: MAX3266X hardware RNG default: off |
103 | | * QAT_ENABLE_RNG: Intel QAT hardware RNG default: off |
104 | | * WOLFSSL_ATECC_RNG: ATECC508/608 hardware RNG default: off |
105 | | * WOLFSSL_SILABS_TRNG: Silicon Labs TRNG default: off |
106 | | * WOLFSSL_SCE_NO_TRNG: Disable Renesas SCE TRNG default: off |
107 | | * WOLFSSL_SCE_TRNG_HANDLE: Renesas SCE TRNG handle default: off |
108 | | * WOLFSSL_SE050_NO_TRNG: Disable SE050 TRNG default: off |
109 | | * WOLFSSL_PSA_NO_RNG: Disable PSA RNG default: off |
110 | | * HAVE_IOTSAFE_HWRNG: IoT-Safe hardware RNG default: off |
111 | | * WOLFSSL_XILINX_CRYPT_VERSAL: Xilinx Versal crypto RNG default: off |
112 | | * WOLFSSL_VA416X0_TRNG: Vorago VA416x0 hardware TRNG default: off |
113 | | * (seeds Hash-DRBG; needs the VA416xx |
114 | | * SDK header va416xx.h on the include |
115 | | * path). See the wc_GenerateSeed() |
116 | | * implementation below for SDK API and |
117 | | * tuning details. |
118 | | */ |
119 | | |
120 | | #define WC_FIPS_LL_CRYPTO |
121 | | #define _WC_BUILDING_RANDOM_C |
122 | | |
123 | | #include <wolfssl/wolfcrypt/libwolfssl_sources.h> |
124 | | |
125 | | /* on HPUX 11 you may need to install /dev/random see |
126 | | http://h20293.www2.hp.com/portal/swdepot/displayProductInfo.do?productNumber=KRNG11I |
127 | | |
128 | | */ |
129 | | #if defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 5 |
130 | | #include <esp_random.h> |
131 | | #endif |
132 | | |
133 | | #if defined(HAVE_FIPS) && \ |
134 | | defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) |
135 | | |
136 | | #if defined(USE_WINDOWS_API) && defined(_MSC_VER) |
137 | | #pragma code_seg(".fipsA$i") |
138 | | #pragma const_seg(".fipsB$i") |
139 | | #endif |
140 | | #endif |
141 | | |
142 | | |
143 | | #include <wolfssl/wolfcrypt/random.h> |
144 | | #ifdef WC_RNG_LOCK_ATFORK |
145 | | #include <errno.h> /* for the fork handlers, whatever the seed source */ |
146 | | #endif |
147 | | #ifdef WC_HAVE_RNG_BANKREF |
148 | | #if defined(HAVE_FIPS) && !defined(WOLFSSL_EXPERIMENTAL_SETTINGS) && \ |
149 | | !defined(WOLFSSL_FIPS_DEV) |
150 | | #error WC_HAVE_RNG_BANKREF is unsupported in FIPS configurations. |
151 | | #endif |
152 | | #include <wolfssl/wolfcrypt/rng_bank.h> |
153 | | #endif |
154 | | #include <wolfssl/wolfcrypt/cpuid.h> |
155 | | |
156 | | #ifndef WC_NO_RNG /* if not FIPS and RNG is disabled then do not compile */ |
157 | | |
158 | | #ifndef NO_SHA256 |
159 | | #include <wolfssl/wolfcrypt/sha256.h> |
160 | | #endif |
161 | | #ifdef WOLFSSL_DRBG_SHA512 |
162 | | #include <wolfssl/wolfcrypt/sha512.h> |
163 | | #endif |
164 | | |
165 | | #ifdef WOLF_CRYPTO_CB |
166 | | #include <wolfssl/wolfcrypt/cryptocb.h> |
167 | | #endif |
168 | | |
169 | | #ifdef NO_INLINE |
170 | | #include <wolfssl/wolfcrypt/misc.h> |
171 | | #else |
172 | | #define WOLFSSL_MISC_INCLUDED |
173 | | #include <wolfcrypt/src/misc.c> |
174 | | #endif |
175 | | |
176 | | #ifdef WC_RNG_HAVE_GLOBAL_FALLBACK_RNG |
177 | | static WC_RNG global_fallback_rng = WC_RNG_STATIC_INITIALIZER; |
178 | | /* global_fallback_rng.lock arbitrates access */ |
179 | | wc_static_assert(WC_RNG_LOCK_FREE == 0); |
180 | | #endif |
181 | | |
182 | | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
183 | | static wolfSSL_Atomic_Uint global_entropy_epoch = WOLFSSL_ATOMIC_INITIALIZER(1U); |
184 | | #endif |
185 | | |
186 | | #if defined(WOLFSSL_SGX) |
187 | | #include <sgx_trts.h> |
188 | | #elif defined(USE_WINDOWS_API) |
189 | | #ifndef _WIN32_WINNT |
190 | | #define _WIN32_WINNT 0x0400 |
191 | | #endif |
192 | | #define _WINSOCKAPI_ /* block inclusion of winsock.h header file */ |
193 | | #include <windows.h> |
194 | | #include <wincrypt.h> |
195 | | #undef _WINSOCKAPI_ /* undefine it for MINGW winsock2.h header file */ |
196 | | #elif defined(FREESCALE_KSDK_2_0_TRNG) |
197 | | #include "fsl_trng.h" |
198 | | #elif defined(FREESCALE_KSDK_2_0_RNGA) |
199 | | #include "fsl_rnga.h" |
200 | | #elif defined(WOLFSSL_WICED) |
201 | | #include "wiced_crypto.h" |
202 | | #elif defined(WOLFSSL_NETBURNER) |
203 | | #include <predef.h> |
204 | | #include <basictypes.h> |
205 | | #include <random.h> |
206 | | #elif defined(WOLFSSL_XILINX_CRYPT_VERSAL) |
207 | | #include "wolfssl/wolfcrypt/port/xilinx/xil-versal-trng.h" |
208 | | #elif defined(WOLFSSL_RPIPICO) |
209 | | #include "wolfssl/wolfcrypt/port/rpi_pico/pico.h" |
210 | | #elif defined(WOLFSSL_C2000_ENTROPY) |
211 | | #include "wolfssl/wolfcrypt/port/ti/ti-c2000-entropy.h" |
212 | | #elif defined(NO_DEV_RANDOM) |
213 | | #elif defined(CUSTOM_RAND_GENERATE) |
214 | | #elif defined(CUSTOM_RAND_GENERATE_BLOCK) |
215 | | #elif defined(CUSTOM_RAND_GENERATE_SEED) |
216 | | #elif defined(WOLFSSL_GENSEED_FORTEST) |
217 | | #elif defined(WOLFSSL_MDK_ARM) |
218 | | #elif defined(WOLFSSL_IAR_ARM) |
219 | | #elif defined(WOLFSSL_ROWLEY_ARM) |
220 | | #elif defined(WOLFSSL_EMBOS) |
221 | | #elif defined(WOLFSSL_DEOS) |
222 | | #elif defined(MICRIUM) |
223 | | #elif defined(WOLFSSL_NUCLEUS) |
224 | | #elif defined(WOLFSSL_PB) |
225 | | #elif defined(WOLFSSL_ZEPHYR) |
226 | | #elif defined(WOLFSSL_TELIT_M2MB) |
227 | | #elif defined(WOLFSSL_RENESAS_TSIP) |
228 | | /* for wc_tsip_GenerateRandBlock */ |
229 | | #include "wolfssl/wolfcrypt/port/Renesas/renesas_tsip_internal.h" |
230 | | #elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_TRNG) |
231 | | #elif defined(WOLFSSL_IMXRT1170_CAAM) |
232 | | #elif defined(CY_USING_HAL) && defined(COMPONENT_WOLFSSL) |
233 | | #include "cyhal_trng.h" /* Infineon/Cypress HAL RNG implementation */ |
234 | | #elif defined(WOLFSSL_MAX3266X) || defined(WOLFSSL_MAX3266X_OLD) |
235 | | #include "wolfssl/wolfcrypt/port/maxim/max3266x.h" |
236 | | #else |
237 | | #include <errno.h> |
238 | | #if defined(WOLFSSL_GETRANDOM) || defined(HAVE_GETRANDOM) |
239 | | #include <sys/random.h> |
240 | | #endif |
241 | | /* include headers that may be needed to get good seed */ |
242 | | #include <fcntl.h> |
243 | | #ifndef EBSNET |
244 | | #include <unistd.h> |
245 | | #endif |
246 | | #endif |
247 | | |
248 | | #if defined(WOLFSSL_TI_AM64X_R5) |
249 | | #include <wolfssl/wolfcrypt/port/ti/ti-sa2ul_r5_port.h> |
250 | | #endif |
251 | | |
252 | | #if defined(WOLFSSL_SILABS_SE_TYPES) |
253 | | #include <wolfssl/wolfcrypt/port/silabs/silabs_random.h> |
254 | | #endif |
255 | | |
256 | | #if defined(WOLFSSL_IOTSAFE) && defined(HAVE_IOTSAFE_HWRNG) |
257 | | #include <wolfssl/wolfcrypt/port/iotsafe/iotsafe.h> |
258 | | #endif |
259 | | |
260 | | #if defined(WOLFSSL_HAVE_PSA) && !defined(WOLFSSL_PSA_NO_RNG) |
261 | | #include <wolfssl/wolfcrypt/port/psa/psa.h> |
262 | | #endif |
263 | | |
264 | | #if FIPS_VERSION3_GE(6,0,0) |
265 | | const unsigned int wolfCrypt_FIPS_drbg_ro_sanity[2] = |
266 | | { 0x1a2b3c4d, 0x00000011 }; |
267 | | int wolfCrypt_FIPS_DRBG_sanity(void) |
268 | | { |
269 | | return 0; |
270 | | } |
271 | | #endif |
272 | | |
273 | | #if defined(HAVE_INTEL_RDRAND) || defined(HAVE_INTEL_RDSEED) || \ |
274 | | defined(HAVE_AMD_RDSEED) |
275 | | static cpuid_flags_t intel_flags = WC_CPUID_INITIALIZER; |
276 | | static void wc_InitRng_IntelRD(void) |
277 | | { |
278 | | cpuid_get_flags_ex(&intel_flags); |
279 | | } |
280 | | #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED) |
281 | | static WC_MAYBE_UNUSED int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, |
282 | | word32 sz); |
283 | | #endif |
284 | | #ifdef HAVE_INTEL_RDRAND |
285 | | static int wc_GenerateRand_IntelRD(OS_Seed* os, byte* output, word32 sz); |
286 | | #endif |
287 | | |
288 | | #ifdef USE_WINDOWS_API |
289 | | #define USE_INTEL_INTRINSICS |
290 | | #elif !defined __GNUC__ || defined __clang__ || __GNUC__ > 4 |
291 | | #define USE_INTEL_INTRINSICS |
292 | | #else |
293 | | #undef USE_INTEL_INTRINSICS |
294 | | #endif |
295 | | |
296 | | #ifdef USE_INTEL_INTRINSICS |
297 | | #include <immintrin.h> |
298 | | /* Before clang 7 or GCC 9, immintrin.h did not define _rdseed64_step() */ |
299 | | #ifndef HAVE_INTEL_RDSEED |
300 | | #elif defined __clang__ && __clang_major__ > 6 |
301 | | #elif !defined __GNUC__ |
302 | | #elif __GNUC__ > 8 |
303 | | #else |
304 | | #ifndef __clang__ |
305 | | #pragma GCC push_options |
306 | | #pragma GCC target("rdseed") |
307 | | #else |
308 | | #define __RDSEED__ |
309 | | #endif |
310 | | #include <x86intrin.h> |
311 | | #ifndef __clang__ |
312 | | #pragma GCC pop_options |
313 | | #endif |
314 | | #endif |
315 | | #endif /* USE_WINDOWS_API */ |
316 | | #endif |
317 | | |
318 | | /* Internal return codes */ |
319 | | enum { |
320 | | DRBG_SUCCESS = 0, |
321 | | DRBG_FAILURE = 1, |
322 | | DRBG_NEED_RESEED = 2, |
323 | | DRBG_CONT_FAILURE = 3, |
324 | | DRBG_NO_SEED_CB = 4 |
325 | | }; |
326 | | |
327 | | /* Numerous existing code points assume DRBG_SUCCESS is 0 -- for now, just |
328 | | * assert safety around that. */ |
329 | | wc_static_assert(DRBG_SUCCESS == 0); |
330 | | |
331 | | #ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES |
332 | | enum { |
333 | | CONST_NUM_ERR_DRBG_FAILURE = DRBG_FAILURE, |
334 | | CONST_NUM_ERR_DRBG_NEED_RESEED = DRBG_NEED_RESEED, |
335 | | CONST_NUM_ERR_DRBG_CONT_FAILURE = DRBG_CONT_FAILURE, |
336 | | CONST_NUM_ERR_DRBG_NO_SEED_CB = DRBG_NO_SEED_CB, |
337 | | CONST_NUM_ERR_WC_DRBG_FAILED = WC_DRBG_FAILED, |
338 | | CONST_NUM_ERR_WC_DRBG_CONT_FAILED = WC_DRBG_CONT_FAILED |
339 | | }; |
340 | | /* DRBG_SUCCESS needs to be macroized to avoid "enumerated and |
341 | | * non-enumerated type in conditional expression" in C++. */ |
342 | | #define DRBG_SUCCESS (byte)DRBG_SUCCESS |
343 | | #define DRBG_FAILURE (byte)WC_ERR_TRACE(DRBG_FAILURE) |
344 | | #define DRBG_NEED_RESEED (byte)WC_ERR_TRACE(DRBG_NEED_RESEED) |
345 | | #define DRBG_CONT_FAILURE (byte)WC_ERR_TRACE(DRBG_CONT_FAILURE) |
346 | | #define DRBG_NO_SEED_CB (byte)WC_ERR_TRACE(DRBG_NO_SEED_CB) |
347 | | #define WC_DRBG_FAILED (byte)WC_ERR_TRACE(WC_DRBG_FAILED) |
348 | | #define WC_DRBG_CONT_FAILED (byte)WC_ERR_TRACE(WC_DRBG_CONT_FAILED) |
349 | | #endif |
350 | | |
351 | | /* RNG health states */ |
352 | 131k | #define DRBG_NOT_INIT WC_DRBG_NOT_INIT |
353 | 62.1k | #define DRBG_OK WC_DRBG_OK |
354 | 1.62k | #define DRBG_FAILED WC_DRBG_FAILED |
355 | 0 | #define DRBG_CONT_FAILED WC_DRBG_CONT_FAILED |
356 | | |
357 | | /* enforcement helper for WC_RNG_LOCK_REQUIRED: instance-consuming public APIs |
358 | | * call this on entry. (WC_RNG_LOCK_ENTROPY_INVALIDATED is deliberately not |
359 | | * enforced here -- see the body.) */ |
360 | | static WC_MAYBE_UNUSED WC_INLINE int rng_lock_required_check(const WC_RNG* rng) |
361 | 460k | { |
362 | 460k | if (rng == NULL) |
363 | 0 | return BAD_FUNC_ARG; |
364 | 460k | #ifndef WC_RNG_HAVE_LOCK |
365 | 460k | return 0; |
366 | | #else /* WC_RNG_HAVE_LOCK */ |
367 | | else { |
368 | | #ifdef WOLFSSL_NO_ATOMICS |
369 | | WC_RNG_lock_t lock_state = rng->lock; |
370 | | #else |
371 | | WC_RNG_lock_arg_t lock_state = WOLFSSL_ATOMIC_LOAD(rng->lock); |
372 | | #endif |
373 | | if ((lock_state & WC_RNG_LOCK_REQUIRED) && |
374 | | (! (lock_state & WC_RNG_LOCK_HELD))) |
375 | | { |
376 | | return OBJECT_NOT_LOCKED_E; |
377 | | } |
378 | | /* WC_RNG_LOCK_ENTROPY_INVALIDATED deliberately does not gate entry |
379 | | * here: on lock-required instances the lock API refuses new leases, and |
380 | | * on unlocked instances the conditions in |
381 | | * wc_RNG_entropy_needs_recovery() force a credited reseed before the |
382 | | * next generate. Refusing here would brick unlocked instances, with no |
383 | | * path to recovery. */ |
384 | | return 0; |
385 | | } |
386 | | #endif /* WC_RNG_HAVE_LOCK */ |
387 | 460k | } |
388 | | |
389 | | /* Read-only accessor for the RNG health status (enum wc_RngHealthState). |
390 | | * Returns the status, or BAD_FUNC_ARG for a NULL rng. */ |
391 | | int wc_RNG_GetStatus(const WC_RNG* rng) |
392 | 0 | { |
393 | 0 | if (rng == NULL) |
394 | 0 | return BAD_FUNC_ARG; |
395 | 0 | return (int)rng->status; |
396 | 0 | } |
397 | | |
398 | | /* Like wc_RNG_GetStatus(), but precomputes an appropriate return code. */ |
399 | 888k | int wc_RNG_Status(const WC_RNG *rng) { |
400 | 888k | if (rng == NULL) |
401 | 0 | return BAD_FUNC_ARG; |
402 | 888k | switch (rng->status) { |
403 | 0 | case WC_DRBG_NOT_INIT: |
404 | 0 | return NOT_READY_E; |
405 | 888k | case WC_DRBG_OK: |
406 | 888k | return 0; |
407 | 0 | case WC_NO_ERR_TRACE(WC_DRBG_FAILED): |
408 | 0 | return RNG_FAILURE_E; |
409 | 0 | case WC_NO_ERR_TRACE(WC_DRBG_CONT_FAILED): |
410 | 0 | return DRBG_CONT_FIPS_E; |
411 | 0 | default: |
412 | 0 | return BAD_FUNC_ARG; |
413 | 888k | } |
414 | | /* not reached */ |
415 | 888k | } |
416 | | |
417 | | /* Returns 1 if rng has an instantiated DRBG, else 0. An in-service WC_RNG can |
418 | | * lack one: _InitRng() in HAVE_INTEL_RDRAND configurations bypasses DRBG |
419 | | * instantiation when the CPU has RDRAND (). */ |
420 | | int wc_RNG_DRBG_Present(const WC_RNG* rng) |
421 | 444k | { |
422 | 444k | if (rng == NULL) |
423 | 0 | return 0; |
424 | 444k | #if defined(HAVE_HASHDRBG) && !defined(NO_SHA256) |
425 | 444k | if ((rng->drbgType == WC_DRBG_SHA256) && (rng->drbg != NULL)) |
426 | 0 | return 1; |
427 | 444k | #endif |
428 | 444k | #if defined(HAVE_HASHDRBG) && defined(WOLFSSL_DRBG_SHA512) |
429 | 444k | if ((rng->drbgType == WC_DRBG_SHA512) && (rng->drbg512 != NULL)) |
430 | 444k | return 1; |
431 | 0 | #endif |
432 | 0 | return 0; |
433 | 444k | } |
434 | | |
435 | | /* Post-init flag policy, shared by wc_RNG_{Set,Clear}Flags(): a flag RMW is |
436 | | * legal only under exclusive ownership -- the same precondition as the |
437 | | * transient RMW in wc_RNG_DRBG_Reseed_Now_Primary() -- and only on the bits |
438 | | * declared mutable (WC_RNG_FLAGS_SETTABLE / _CLEARABLE); the rest are |
439 | | * structural, fixed by init or by the module. */ |
440 | | static int RngFlagsPolicyCheck(const WC_RNG* rng, word32 flags, word32 allowed) |
441 | 0 | { |
442 | 0 | int ret; |
443 | 0 | if (rng == NULL) |
444 | 0 | return BAD_FUNC_ARG; |
445 | 0 | if ((flags == 0) || (flags & ~allowed)) |
446 | 0 | return BAD_FUNC_ARG; |
447 | 0 | ret = rng_lock_required_check(rng); |
448 | 0 | if (ret != 0) |
449 | 0 | return ret; |
450 | | #ifdef WC_RNG_HAVE_LOCK |
451 | | if (! (WOLFSSL_ATOMIC_LOAD(rng->lock) & WC_RNG_LOCK_REQUIRED)) |
452 | | return WRONG_TYPE_OBJECT_E; |
453 | | return 0; |
454 | | #elif !defined(SINGLE_THREADED) |
455 | 0 | return NOT_COMPILED_IN; |
456 | | #else |
457 | | return 0; |
458 | | #endif |
459 | 0 | } |
460 | | |
461 | | int wc_RNG_SetFlags(WC_RNG* rng, word32 flags) |
462 | 0 | { |
463 | 0 | int ret = RngFlagsPolicyCheck(rng, flags, WC_RNG_FLAGS_SETTABLE); |
464 | 0 | if (ret != 0) |
465 | 0 | return ret; |
466 | | /* the two seed-source policies are mutually exclusive. */ |
467 | 0 | if (((flags | rng->flags) & WC_RNG_FLAG_NO_PRIMARY_SEED) && |
468 | 0 | ((flags | rng->flags) & WC_RNG_FLAG_ONLY_PRIMARY_SEED)) |
469 | 0 | { |
470 | 0 | return BAD_FUNC_ARG; |
471 | 0 | } |
472 | | #ifdef WC_RNG_HAVE_RBGC |
473 | | /* _NO_PRIMARY_SEED on an instance with no chain parent to defer to would |
474 | | * leave it with no credited source at all -- same rule as _InitRng(). */ |
475 | | if ((flags & WC_RNG_FLAG_NO_PRIMARY_SEED) && |
476 | | (rng->RBGCStratum == 0)) |
477 | | { |
478 | | return MISSING_RNG_E; |
479 | | } |
480 | | #else |
481 | 0 | if (flags & WC_RNG_FLAG_NO_PRIMARY_SEED) |
482 | 0 | return NOT_COMPILED_IN; |
483 | 0 | #endif |
484 | 0 | rng->flags |= flags; |
485 | 0 | return 0; |
486 | 0 | } |
487 | | |
488 | | int wc_RNG_ClearFlags(WC_RNG* rng, word32 flags) |
489 | 0 | { |
490 | 0 | int ret = RngFlagsPolicyCheck(rng, flags, WC_RNG_FLAGS_CLEARABLE); |
491 | 0 | if (ret != 0) |
492 | 0 | return ret; |
493 | 0 | rng->flags &= ~flags; |
494 | 0 | return 0; |
495 | 0 | } |
496 | | |
497 | | /* Read-only: no ownership precondition (a plain load, like wc_RNG_Status()). |
498 | | * Authoritative under the caller's own lease; otherwise a snapshot. */ |
499 | | int wc_RNG_GetFlags(const WC_RNG* rng, word32 *flags) |
500 | 0 | { |
501 | 0 | if ((rng == NULL) || (flags == NULL)) |
502 | 0 | return BAD_FUNC_ARG; |
503 | 0 | *flags = rng->flags; |
504 | 0 | return 0; |
505 | 0 | } |
506 | | |
507 | | #ifdef WC_RNG_HAVE_POOL |
508 | | static WARN_UNUSED_RESULT int PoolPurge(WC_RNG* rng); |
509 | | |
510 | | /* poolHead = {state:2, epoch:14, pos:16}; poolTail = {0, epoch:14, pos:16}. */ |
511 | | #define WC_RNG_POOL_POS(w) ((word32)((word32)(w) & 0xFFFFU)) |
512 | | #define WC_RNG_POOL_EPOCH(w) ((word32)(((word32)(w) >> 16) & 0x3FFFU)) |
513 | | #define WC_RNG_POOL_PACK(pos, epoch) \ |
514 | | ((WC_ATOMIC_UINT_ARG)((((word32)(pos)) & 0xFFFFU) | \ |
515 | | ((((word32)(epoch)) & 0x3FFFU) << 16))) |
516 | | #define WC_RNG_POOL_STATE_MASK 0xC0000000U |
517 | | #define WC_RNG_POOL_STATE_UNALLOC 0x00000000U |
518 | | #define WC_RNG_POOL_STATE_LIVE 0x40000000U |
519 | | #define WC_RNG_POOL_STATE_CLAIMED 0x80000000U |
520 | | #define WC_RNG_POOL_STATE_TORNDOWN 0xC0000000U |
521 | | #define WC_RNG_POOL_STATE(w) ((WC_ATOMIC_UINT_ARG)(w) & WC_RNG_POOL_STATE_MASK) |
522 | | /* the two sentinels carry no position or epoch */ |
523 | | #define WC_RNG_POOL_HAS_RING(w) \ |
524 | | ((WC_RNG_POOL_STATE(w) == WC_RNG_POOL_STATE_LIVE) || \ |
525 | | (WC_RNG_POOL_STATE(w) == WC_RNG_POOL_STATE_CLAIMED)) |
526 | | |
527 | | #endif |
528 | | |
529 | | static WC_MAYBE_UNUSED int rng_entropy_event_propagate(WC_RNG* rng); |
530 | | |
531 | | /* A seeding operation captures the PID before acquiring material, as it does |
532 | | * the entropy epoch, and stamps the captured value at completion: a fork in |
533 | | * between then leaves a stale stamp for the next propagation to find. */ |
534 | | #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) |
535 | 0 | #define WC_RNG_PID_ARG pid_t |
536 | 0 | #define WC_RNG_GETPID() getpid() |
537 | | #else |
538 | | #define WC_RNG_PID_ARG int |
539 | | #define WC_RNG_GETPID() 0 |
540 | | #endif |
541 | | |
542 | | /* Start NIST DRBG code */ |
543 | | #ifdef HAVE_HASHDRBG |
544 | | |
545 | 0 | #define OUTPUT_BLOCK_LEN (WC_SHA256_DIGEST_SIZE) |
546 | | #define MAX_REQUEST_LEN (0x10000) |
547 | | |
548 | | #ifdef WC_RNG_SEED_CB |
549 | | |
550 | | #ifndef HAVE_FIPS |
551 | | static wc_RngSeed_Cb seedCb = wc_GenerateSeed; |
552 | | #else |
553 | | static wc_RngSeed_Cb seedCb = NULL; |
554 | | #endif |
555 | | |
556 | | int wc_SetSeed_Cb(wc_RngSeed_Cb cb) |
557 | | { |
558 | | seedCb = cb; |
559 | | return 0; |
560 | | } |
561 | | |
562 | | #endif |
563 | | |
564 | 63.4k | #define SEED_SZ WC_DRBG_SEED_SZ |
565 | 63.4k | #define MAX_SEED_SZ WC_DRBG_MAX_SEED_SZ |
566 | | |
567 | | /* Verify max gen block len */ |
568 | | #if RNG_MAX_BLOCK_LEN > MAX_REQUEST_LEN |
569 | | #error RNG_MAX_BLOCK_LEN is larger than NIST DBRG max request length |
570 | | #endif |
571 | | |
572 | | /* the seed device is read through the filesystem API */ |
573 | | #if defined(WC_RNG_SEED_DEVICE) && defined(NO_FILESYSTEM) |
574 | | #error WC_RNG_SEED_DEVICE requires filesystem support |
575 | | #endif |
576 | | |
577 | | enum { |
578 | | drbgInitC = 0, |
579 | | drbgReseed = 1, |
580 | | drbgGenerateW = 2, |
581 | | drbgGenerateH = 3, |
582 | | drbgInitV = 4 |
583 | | }; |
584 | | |
585 | | #ifndef NO_SHA256 |
586 | | typedef struct DRBG_internal DRBG_internal; |
587 | | #endif |
588 | | |
589 | | #ifdef WOLFSSL_DRBG_SHA512 |
590 | | typedef struct DRBG_SHA512_internal DRBG_SHA512_internal; |
591 | | |
592 | | static WARN_UNUSED_RESULT int Hash512_DRBG_Reseed(DRBG_SHA512_internal* drbg, |
593 | | wc_drbg_reseed_ctr_t *reseedCtr, |
594 | | const byte* seed, word32 seedSz, |
595 | | const byte* additional, word32 additionalSz); |
596 | | static WARN_UNUSED_RESULT int Hash512_DRBG_Generate(DRBG_SHA512_internal* drbg, |
597 | | wc_drbg_reseed_ctr_t *reseedCtr, |
598 | | byte* out, word32 outSz, |
599 | | const byte* additional, word32 additionalSz); |
600 | | static WARN_UNUSED_RESULT int Hash512_DRBG_Instantiate( |
601 | | DRBG_SHA512_internal* drbg, |
602 | | wc_drbg_reseed_ctr_t *reseedCtr, |
603 | | const byte* seed, word32 seedSz, |
604 | | const byte* nonce, word32 nonceSz, |
605 | | const byte* perso, word32 persoSz, |
606 | | void* heap, int devId); |
607 | | static int Hash512_DRBG_Uninstantiate(DRBG_SHA512_internal* drbg); |
608 | | #endif |
609 | | |
610 | | /* Runtime DRBG default flavor. This facility provides control over which DRBG |
611 | | * type is used for new WC_RNG instances; it may be switched at runtime |
612 | | * (e.g. NSA Suite 2.0 threads disable SHA-256). _InitRng's choice of DRBG is |
613 | | * determined by getDrbgFlavorFlag() unless overridden by the flags argument, |
614 | | */ |
615 | | #if defined(WOLFSSL_DRBG_SHA512) && !defined(NO_SHA256) && !defined(WOLFSSL_NO_SHA256_DRBG) |
616 | | static wolfSSL_Atomic_Uint DrbgType_mask = |
617 | | WOLFSSL_ATOMIC_INITIALIZER((1U << WC_DRBG_SHA256) | |
618 | | (1U << WC_DRBG_SHA512)); |
619 | | #elif defined(WOLFSSL_DRBG_SHA512) |
620 | | static wolfSSL_Atomic_Uint DrbgType_mask = |
621 | | WOLFSSL_ATOMIC_INITIALIZER(1U << WC_DRBG_SHA512); |
622 | | #elif defined(NO_SHA256) || defined(WOLFSSL_NO_SHA256_DRBG) |
623 | | #error WOLFSSL_NO_SHA256_DRBG requires WOLFSSL_DRBG_SHA512. |
624 | | #else |
625 | | static wolfSSL_Atomic_Uint DrbgType_mask = |
626 | | WOLFSSL_ATOMIC_INITIALIZER(1U << WC_DRBG_SHA256); |
627 | | #endif |
628 | | |
629 | 69.3k | static int getDrbgFlavorFlag(word32 *flags) { |
630 | 69.3k | WC_ATOMIC_UINT_ARG cur_DrbgType_mask = WOLFSSL_ATOMIC_LOAD(DrbgType_mask); |
631 | 69.3k | if (cur_DrbgType_mask & (1U << WC_DRBG_SHA512)) { |
632 | 69.3k | *flags = WC_RNG_INIT_FLAG_DRBG_SHA512; |
633 | 69.3k | return 0; |
634 | 69.3k | } |
635 | 0 | if (cur_DrbgType_mask & (1U << WC_DRBG_SHA256)) { |
636 | 0 | *flags = WC_RNG_INIT_FLAG_DRBG_SHA256; |
637 | 0 | return 0; |
638 | 0 | } |
639 | 0 | return BAD_STATE_E; |
640 | 0 | } |
641 | | |
642 | | #ifndef NO_SHA256 |
643 | | int wc_Sha256Drbg_Disable(void) |
644 | 0 | { |
645 | 0 | #ifdef WOLFSSL_DRBG_SHA512 |
646 | 0 | WC_ATOMIC_UINT_ARG cur_DrbgType_mask; |
647 | 0 | int ret; |
648 | 0 | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&DrbgType_mask, cur_DrbgType_mask, ret) { |
649 | 0 | if (! (cur_DrbgType_mask & (1U << WC_DRBG_SHA512))) |
650 | 0 | return BAD_STATE_E; |
651 | 0 | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
652 | 0 | wolfSSL_Atomic_Uint_CompareExchange, &DrbgType_mask, cur_DrbgType_mask, |
653 | 0 | cur_DrbgType_mask & ~(1U << WC_DRBG_SHA256), ret); |
654 | 0 | } WC_CAS_WITH_RETRY_END; |
655 | 0 | return ret; |
656 | | #else |
657 | | return NOT_COMPILED_IN; |
658 | | #endif |
659 | 0 | } |
660 | | |
661 | | int wc_Sha256Drbg_Enable(void) |
662 | 0 | { |
663 | 0 | WC_ATOMIC_UINT_ARG cur_DrbgType_mask; |
664 | 0 | int ret; |
665 | 0 | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&DrbgType_mask, cur_DrbgType_mask, ret) { |
666 | 0 | if (cur_DrbgType_mask & (1U << WC_DRBG_SHA256)) |
667 | 0 | return 0; |
668 | 0 | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
669 | 0 | wolfSSL_Atomic_Uint_CompareExchange, &DrbgType_mask, cur_DrbgType_mask, |
670 | 0 | cur_DrbgType_mask | (1U << WC_DRBG_SHA256), ret); |
671 | 0 | } WC_CAS_WITH_RETRY_END; |
672 | 0 | return ret; |
673 | 0 | } |
674 | | |
675 | | int wc_Sha256Drbg_IsDisabled(void) |
676 | 0 | { |
677 | 0 | return !(WOLFSSL_ATOMIC_LOAD(DrbgType_mask) & (1U << WC_DRBG_SHA256)); |
678 | 0 | } |
679 | | #else |
680 | | int wc_Sha256Drbg_Disable(void) { return NOT_COMPILED_IN; } |
681 | | int wc_Sha256Drbg_Enable(void) { return 0; } |
682 | | int wc_Sha256Drbg_IsDisabled(void) { return 1; } /* always disabled */ |
683 | | #endif /* !NO_SHA256 */ |
684 | | |
685 | | #ifdef WOLFSSL_DRBG_SHA512 |
686 | | int wc_Sha512Drbg_Disable(void) |
687 | 0 | { |
688 | 0 | #ifndef NO_SHA256 |
689 | 0 | WC_ATOMIC_UINT_ARG cur_DrbgType_mask; |
690 | 0 | int ret; |
691 | 0 | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&DrbgType_mask, cur_DrbgType_mask, ret) { |
692 | 0 | if (! (cur_DrbgType_mask & (1U << WC_DRBG_SHA256))) |
693 | 0 | return BAD_STATE_E; |
694 | 0 | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
695 | 0 | wolfSSL_Atomic_Uint_CompareExchange, &DrbgType_mask, cur_DrbgType_mask, |
696 | 0 | cur_DrbgType_mask & ~(1U << WC_DRBG_SHA512), ret); |
697 | 0 | } WC_CAS_WITH_RETRY_END; |
698 | 0 | return ret; |
699 | | #else |
700 | | return NOT_COMPILED_IN; /* can't disable both */ |
701 | | #endif |
702 | 0 | } |
703 | | |
704 | | int wc_Sha512Drbg_Enable(void) |
705 | 0 | { |
706 | 0 | WC_ATOMIC_UINT_ARG cur_DrbgType_mask; |
707 | 0 | int ret; |
708 | 0 | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&DrbgType_mask, cur_DrbgType_mask, ret) { |
709 | 0 | if (cur_DrbgType_mask & (1U << WC_DRBG_SHA512)) |
710 | 0 | return 0; |
711 | 0 | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
712 | 0 | wolfSSL_Atomic_Uint_CompareExchange, &DrbgType_mask, cur_DrbgType_mask, |
713 | 0 | cur_DrbgType_mask | (1U << WC_DRBG_SHA512), ret); |
714 | 0 | } WC_CAS_WITH_RETRY_END; |
715 | 0 | return ret; |
716 | 0 | } |
717 | | |
718 | | int wc_Sha512Drbg_IsDisabled(void) |
719 | 0 | { |
720 | 0 | return !(WOLFSSL_ATOMIC_LOAD(DrbgType_mask) & (1U << WC_DRBG_SHA512)); |
721 | 0 | } |
722 | | #endif /* WOLFSSL_DRBG_SHA512 */ |
723 | | |
724 | | #ifdef WC_RNG_LOCK_ATFORK |
725 | | /* The lock and its fork handlers live in wc_port.c, outside the FIPS module |
726 | | * boundary. Only the DRBG's reaction to a fork belongs in here. */ |
727 | | static int RngAutoLockInit(WC_RNG* rng) |
728 | 68.0k | { |
729 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
730 | | /* A full mutex instance is locked by its caller for the whole call, so |
731 | | * the automatic lock leaves that instance alone, as it does without the |
732 | | * fork handlers. Such an instance is not fork covered either. */ |
733 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) |
734 | | return 0; |
735 | | #endif |
736 | 68.0k | return wc_ForkLock_New(&rng->autoLock, rng->heap); |
737 | 68.0k | } |
738 | | |
739 | | /* Safe on a zeroed WC_RNG that never got a lock. */ |
740 | | static void RngAutoLockFree(WC_RNG* rng) |
741 | 68.1k | { |
742 | 68.1k | wc_ForkLock_Free(&rng->autoLock); |
743 | 68.1k | } |
744 | | |
745 | | /* The child's stale DRBG state is dealt with by wc_RNG_entropy_needs_recovery() |
746 | | * on the generate path, which the fork handlers require. */ |
747 | | static int RngAutoLockEnter(WC_RNG* rng) |
748 | 444k | { |
749 | 444k | return wc_ForkLock_Enter(rng->autoLock); |
750 | 444k | } |
751 | | |
752 | | static void RngAutoLockExit(WC_RNG* rng) |
753 | 444k | { |
754 | 444k | wc_ForkLock_Exit(rng->autoLock); |
755 | 444k | } |
756 | | #elif defined(WC_RNG_HAVE_AUTO_LOCK) |
757 | | /* Without fork handlers the lock lives in the WC_RNG itself: no heap. */ |
758 | | static int RngAutoLockInit(WC_RNG* rng) |
759 | | { |
760 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
761 | | /* A full mutex instance is locked by its caller, which holds rng->mutex |
762 | | * for the whole call, so the automatic lock leaves that instance alone. */ |
763 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) |
764 | | return 0; |
765 | | #endif |
766 | | if (wc_InitMutex(&rng->mutex) != 0) |
767 | | return BAD_MUTEX_E; |
768 | | rng->autoLockInited = 1; |
769 | | return 0; |
770 | | } |
771 | | |
772 | | /* Safe on a zeroed WC_RNG that never got a lock. */ |
773 | | static void RngAutoLockFree(WC_RNG* rng) |
774 | | { |
775 | | if (rng->autoLockInited) { |
776 | | if (wc_FreeMutex(&rng->mutex) != 0) |
777 | | WOLFSSL_MSG("RNG auto lock: mutex not freed"); |
778 | | rng->autoLockInited = 0; |
779 | | } |
780 | | } |
781 | | |
782 | | /* Cancellation stays off while the lock is held: a reseed reads a device, |
783 | | * which is a cancellation point. wc_port.c owns the platform side. */ |
784 | | static int RngAutoLockEnter(WC_RNG* rng) |
785 | | { |
786 | | int old; |
787 | | if (!rng->autoLockInited) |
788 | | return 0; |
789 | | old = wc_CancelDisable(); |
790 | | if (wc_LockMutex(&rng->mutex) != 0) { |
791 | | wc_CancelRestore(old); |
792 | | return BAD_MUTEX_E; |
793 | | } |
794 | | rng->autoLockCancel = old; |
795 | | return 0; |
796 | | } |
797 | | |
798 | | static void RngAutoLockExit(WC_RNG* rng) |
799 | | { |
800 | | int old; |
801 | | if (!rng->autoLockInited) |
802 | | return; |
803 | | old = rng->autoLockCancel; /* read before the unlock hands the slot on */ |
804 | | if (wc_UnLockMutex(&rng->mutex) != 0) |
805 | | WOLFSSL_MSG("RNG auto lock: mutex not unlocked"); |
806 | | wc_CancelRestore(old); |
807 | | } |
808 | | #else |
809 | | #define RngAutoLockEnter(rng) 0 |
810 | | #define RngAutoLockExit(rng) WC_DO_NOTHING |
811 | | #endif /* WC_RNG_HAVE_AUTO_LOCK */ |
812 | | |
813 | | #ifndef CUSTOM_RAND_GENERATE_BLOCK |
814 | | static WARN_UNUSED_RESULT int wc_RNG_HealthTestLocal(WC_RNG* rng, int reseed, |
815 | | void* heap, int devId); |
816 | | #endif |
817 | | |
818 | | #ifdef WOLFSSL_DRBG_SHA512 |
819 | | static WARN_UNUSED_RESULT int wc_RNG_HealthTest_SHA512_ex_internal( |
820 | | DRBG_SHA512_internal* drbg, |
821 | | int reseed, const byte* nonce, word32 nonceSz, |
822 | | const byte* perso, word32 persoSz, |
823 | | const byte* seedA, word32 seedASz, |
824 | | const byte* seedB, word32 seedBSz, |
825 | | const byte* additionalA, word32 additionalASz, |
826 | | const byte* additionalB, word32 additionalBSz, |
827 | | byte* output, word32 outputSz, |
828 | | void* heap, int devId); |
829 | | #endif |
830 | | |
831 | | /* The SHA-256 Hash_DRBG core (Hash_df, Hash_DRBG_*) operates on |
832 | | * DRBG_internal, which random.h defines only when SHA-256 is compiled in. |
833 | | * Wrap the whole block so a NO_SHA256 + WOLFSSL_DRBG_SHA512 build (the |
834 | | * SHA-512-only DRBG configuration) still compiles. The SHA-512 DRBG core |
835 | | * lives below in its own #ifdef WOLFSSL_DRBG_SHA512 section. */ |
836 | | #ifndef NO_SHA256 |
837 | | |
838 | | /* Hash Derivation Function */ |
839 | | /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ |
840 | | static WARN_UNUSED_RESULT int Hash_df(DRBG_internal* drbg, byte* out, |
841 | | word32 outSz, byte type, |
842 | | const byte* inA, word32 inASz, |
843 | | const byte* inB, word32 inBSz, |
844 | | const byte* inC, word32 inCSz) |
845 | 0 | { |
846 | 0 | int ret = WC_NO_ERR_TRACE(DRBG_FAILURE); |
847 | 0 | byte ctr; |
848 | 0 | word32 i; |
849 | 0 | word32 len; |
850 | 0 | word32 bits = (outSz * 8); |
851 | | #ifdef WOLFSSL_WIDE_BYTE |
852 | | byte bitsBuf[4]; /* the 32-bit length as four big-endian octets */ |
853 | | #endif |
854 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
855 | | wc_Sha256* sha = &drbg->sha256; |
856 | | #else |
857 | 0 | wc_Sha256 sha[1]; |
858 | 0 | #endif |
859 | | #if defined(WOLFSSL_SMALL_STACK_CACHE) |
860 | | byte* digest = drbg->digest_scratch; |
861 | | #elif defined(WOLFSSL_SMALL_STACK) |
862 | | byte* digest; |
863 | | #else |
864 | | byte digest[WC_SHA256_DIGEST_SIZE]; |
865 | | #endif |
866 | |
|
867 | 0 | if (drbg == NULL) { |
868 | 0 | return DRBG_FAILURE; |
869 | 0 | } |
870 | | |
871 | 0 | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
872 | 0 | digest = (byte*)XMALLOC(WC_SHA256_DIGEST_SIZE, drbg->heap, |
873 | 0 | DYNAMIC_TYPE_DIGEST); |
874 | 0 | if (digest == NULL) |
875 | 0 | return DRBG_FAILURE; |
876 | 0 | #endif |
877 | | |
878 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
879 | | /* poison so a missed ForceZero on any path is caught by the check */ |
880 | | XMEMSET(digest, 0xff, WC_SHA256_DIGEST_SIZE); |
881 | | wc_MemZero_Add("Hash_df digest", digest, WC_SHA256_DIGEST_SIZE); |
882 | | #endif |
883 | | |
884 | | #ifdef WOLFSSL_WIDE_BYTE |
885 | | /* A word32 cannot be aliased as an octet stream where a C byte is wider |
886 | | * than 8 bits; emit the length as four big-endian octets (shared helper). */ |
887 | | BytesFromWordsBE32(bitsBuf, &bits, 4); |
888 | | #elif defined(LITTLE_ENDIAN_ORDER) |
889 | 0 | bits = ByteReverseWord32(bits); |
890 | 0 | #endif |
891 | 0 | len = (outSz / OUTPUT_BLOCK_LEN) |
892 | 0 | + ((outSz % OUTPUT_BLOCK_LEN) ? 1 : 0); |
893 | |
|
894 | 0 | ctr = 1; |
895 | 0 | for (i = 0; i < len; i++) { |
896 | 0 | #ifndef WOLFSSL_SMALL_STACK_CACHE |
897 | 0 | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
898 | 0 | ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); |
899 | | #else |
900 | | ret = wc_InitSha256(sha); |
901 | | #endif |
902 | 0 | if (ret != 0) |
903 | 0 | break; |
904 | 0 | #endif |
905 | 0 | ret = wc_Sha256Update(sha, &ctr, sizeof(ctr)); |
906 | 0 | if (ret == 0) { |
907 | 0 | ctr++; |
908 | | #ifdef WOLFSSL_WIDE_BYTE |
909 | | ret = wc_Sha256Update(sha, bitsBuf, sizeof(bitsBuf)); |
910 | | #else |
911 | 0 | ret = wc_Sha256Update(sha, (byte*)&bits, sizeof(bits)); |
912 | 0 | #endif |
913 | 0 | } |
914 | |
|
915 | 0 | if (ret == 0) { |
916 | | /* churning V is the only string that doesn't have the type added */ |
917 | 0 | if (type != drbgInitV) |
918 | 0 | ret = wc_Sha256Update(sha, &type, sizeof(type)); |
919 | 0 | } |
920 | 0 | if (ret == 0) |
921 | 0 | ret = wc_Sha256Update(sha, inA, inASz); |
922 | 0 | if (ret == 0) { |
923 | 0 | if (inB != NULL && inBSz > 0) |
924 | 0 | ret = wc_Sha256Update(sha, inB, inBSz); |
925 | 0 | } |
926 | 0 | if (ret == 0) { |
927 | 0 | if (inC != NULL && inCSz > 0) |
928 | 0 | ret = wc_Sha256Update(sha, inC, inCSz); |
929 | 0 | } |
930 | 0 | if (ret == 0) |
931 | 0 | ret = wc_Sha256Final(sha, digest); |
932 | |
|
933 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
934 | | if (ret != 0) |
935 | | (void)wc_Sha256Reset(sha); |
936 | | #else |
937 | 0 | wc_Sha256Free(sha); |
938 | 0 | #endif |
939 | 0 | if (ret == 0) { |
940 | 0 | if (outSz > OUTPUT_BLOCK_LEN) { |
941 | 0 | XMEMCPY(out, digest, OUTPUT_BLOCK_LEN); |
942 | 0 | outSz -= OUTPUT_BLOCK_LEN; |
943 | 0 | out += OUTPUT_BLOCK_LEN; |
944 | 0 | } |
945 | 0 | else { |
946 | 0 | XMEMCPY(out, digest, outSz); |
947 | 0 | } |
948 | 0 | } |
949 | 0 | else { |
950 | 0 | break; |
951 | 0 | } |
952 | 0 | } |
953 | |
|
954 | 0 | ForceZero(digest, WC_SHA256_DIGEST_SIZE); |
955 | | /* Explicit check only where the buffer is NOT XFREEd (XFREE auto-checks): |
956 | | * the stack build and the small-stack-cache build (drbg member). */ |
957 | | #if (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_SMALL_STACK_CACHE)) && \ |
958 | | defined(WOLFSSL_CHECK_MEM_ZERO) |
959 | | wc_MemZero_Check(digest, WC_SHA256_DIGEST_SIZE); |
960 | | #endif |
961 | |
|
962 | 0 | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
963 | 0 | XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); |
964 | 0 | #endif |
965 | |
|
966 | | #ifdef WC_VERBOSE_RNG |
967 | | if (ret != 0) |
968 | | WOLFSSL_DEBUG_PRINTF("ERROR: %s failed with err = %d", __func__, |
969 | | ret); |
970 | | #endif |
971 | |
|
972 | 0 | return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE; |
973 | 0 | } |
974 | | |
975 | | /* Returns: DRBG_SUCCESS or DRBG_FAILURE. No state mutation on failure. */ |
976 | | static WARN_UNUSED_RESULT int Hash256_DRBG_Reseed(DRBG_internal* drbg, |
977 | | wc_drbg_reseed_ctr_t *reseedCtr, |
978 | | const byte* seed, |
979 | | word32 seedSz, const byte* additional, |
980 | | word32 additionalSz) |
981 | 0 | { |
982 | 0 | int ret; |
983 | 0 | WC_DECLARE_VAR(newV_C, byte, DRBG_SEED_LEN * 2, 0); |
984 | 0 | byte *newV, *newC; |
985 | |
|
986 | 0 | if (drbg == NULL) { |
987 | 0 | return DRBG_FAILURE; |
988 | 0 | } |
989 | | |
990 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
991 | | newV_C = drbg->seed_scratch; |
992 | | #else |
993 | 0 | WC_ALLOC_VAR_EX(newV_C, byte, DRBG_SEED_LEN * 2, drbg->heap, |
994 | 0 | DYNAMIC_TYPE_TMP_BUFFER, return DRBG_FAILURE); |
995 | 0 | #endif |
996 | 0 | XMEMSET(newV_C, 0, DRBG_SEED_LEN * 2); |
997 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
998 | | wc_MemZero_Add("Hash256_DRBG_Reseed newV_C", newV_C, DRBG_SEED_LEN * 2); |
999 | | #endif |
1000 | |
|
1001 | 0 | newV = newV_C; |
1002 | 0 | newC = newV + DRBG_SEED_LEN; |
1003 | |
|
1004 | 0 | ret = Hash_df(drbg, newV, DRBG_SEED_LEN, drbgReseed, |
1005 | 0 | drbg->V, sizeof(drbg->V), seed, seedSz, |
1006 | 0 | additional, additionalSz); |
1007 | 0 | if (ret == DRBG_SUCCESS) { |
1008 | 0 | ret = Hash_df(drbg, newC, DRBG_SEED_LEN, drbgInitC, newV, |
1009 | 0 | DRBG_SEED_LEN, NULL, 0, NULL, 0); |
1010 | 0 | } |
1011 | 0 | if (ret == DRBG_SUCCESS) { |
1012 | 0 | XMEMCPY(drbg->V, newV, DRBG_SEED_LEN); |
1013 | 0 | XMEMCPY(drbg->C, newC, DRBG_SEED_LEN); |
1014 | 0 | *reseedCtr = 1; |
1015 | 0 | } |
1016 | |
|
1017 | 0 | ForceZero(newV_C, DRBG_SEED_LEN * 2); |
1018 | | #if (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_SMALL_STACK_CACHE)) && \ |
1019 | | defined(WOLFSSL_CHECK_MEM_ZERO) |
1020 | | wc_MemZero_Check(newV_C, DRBG_SEED_LEN * 2); |
1021 | | #endif |
1022 | |
|
1023 | 0 | #ifndef WOLFSSL_SMALL_STACK_CACHE |
1024 | 0 | WC_FREE_VAR_EX(newV_C, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
1025 | 0 | #endif |
1026 | |
|
1027 | 0 | return ret; |
1028 | 0 | } |
1029 | | |
1030 | | #endif /* !NO_SHA256 */ |
1031 | | |
1032 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
1033 | | /* Purge the credited next-seed aperture. A plain store would race an in-flight |
1034 | | * producer: the producer's publish must lose against a purge, never the |
1035 | | * reverse, or material generated before a state-invalidation event could |
1036 | | * surface READY after it -- exactly the resurrection the provenance guarantee |
1037 | | * forbids. A producer mid-fill (PRODUCING) owns the buffer, so the purge only |
1038 | | * repaints the sentinel (PRODUCING -> PURGED); the producer's failed |
1039 | | * publish-CAS observes the repaint and reopens the aperture EMPTY (see |
1040 | | * NextSeedProducerRelease()) -- the sentinel alone suppresses the pre-event |
1041 | | * material; abandoned seed-aperture buffers are zeroized as explained below. |
1042 | | * All other states purge directly to EMPTY. (The uncredited stir aperture |
1043 | | * is purged by NextStirPurge(): stirs carry no claims, so resurrection there |
1044 | | * is benign by the three-no-ops doctrine.) |
1045 | | * |
1046 | | * Zeroization doctrine for purges: abandonment here is event-driven (fork, |
1047 | | * VM clone/resume, credited reseed), and the event that abandons bytes in |
1048 | | * this lineage is the same event that created a sibling lineage that may |
1049 | | * consume its identical copy of them. Abandoned-here can be consumed-there, |
1050 | | * so purged material is treated as CSP and wiped -- under ownership only: |
1051 | | * READY or parked-fill words are claimed _CONSUMING first (the same CAS a |
1052 | | * consumer uses; producers claim only non-negative words, so the claim |
1053 | | * cannot collide), then wiped, then reopened EMPTY. A claimed word |
1054 | | * (_PRODUCING or _CONSUMING) is repainted _PURGED instead: the holder |
1055 | | * still owns the buffer, so it is the holder that wipes and reopens -- |
1056 | | * the producer in NextSeedProducerRelease(), the consumer in |
1057 | | * wc_RNG_DRBG_NextSeedNow_Nonce_local()'s failed-release arm. Reopening |
1058 | | * EMPTY from under a live holder would let a producer claim and begin a |
1059 | | * fill that the holder's own trailing wipe then tears. |
1060 | | * The health-test burn arm wipes under its own PRODUCING claim. |
1061 | | */ |
1062 | | static WARN_UNUSED_RESULT int NextSeedPurge(WC_RNG *rng) |
1063 | | { |
1064 | | int ret; |
1065 | | wolfSSL_Atomic_Int *lenp = &rng->nextSeedLen; |
1066 | | WC_ATOMIC_INT_ARG cur_len, want_len; |
1067 | | |
1068 | | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(lenp, cur_len, ret) { |
1069 | | if ((cur_len == WC_DRBG_NEXT_SEED_PURGED) || |
1070 | | (cur_len == WC_DRBG_NEXT_SEED_TORNDOWN)) |
1071 | | { |
1072 | | return ALREADY_E; /* already handed off to the holder's unwind. */ |
1073 | | } |
1074 | | if ((cur_len == WC_DRBG_NEXT_SEED_READY) || (cur_len > 0)) { |
1075 | | /* Published or parked bytes with no owner: claim, wipe as |
1076 | | * owner, reopen. */ |
1077 | | WC_CAS_WITH_RETRY_LOOP_FOREVER(wolfSSL_Atomic_Int_CompareExchange, |
1078 | | lenp, cur_len, |
1079 | | WC_DRBG_NEXT_SEED_CONSUMING, ret); |
1080 | | ForceZero(rng->nextSeed, WC_DRBG_SEED_BUF_SIZE); |
1081 | | /* Reopen by CAS, never by store: a concurrent purge can have |
1082 | | * repainted this claim _PURGED (the reopen is then still ours, |
1083 | | * from _PURGED), and a constructor can have painted it _TORNDOWN |
1084 | | * (the reopen is then its, not ours). */ |
1085 | | { |
1086 | | WC_ATOMIC_INT_ARG expected = WC_DRBG_NEXT_SEED_CONSUMING; |
1087 | | if (! wolfSSL_Atomic_Int_CompareExchange( |
1088 | | lenp, &expected, WC_DRBG_NEXT_SEED_EMPTY)) |
1089 | | { |
1090 | | expected = WC_DRBG_NEXT_SEED_PURGED; |
1091 | | (void)wolfSSL_Atomic_Int_CompareExchange( |
1092 | | lenp, &expected, WC_DRBG_NEXT_SEED_EMPTY); |
1093 | | } |
1094 | | } |
1095 | | } |
1096 | | else { |
1097 | | want_len = ((cur_len == WC_DRBG_NEXT_SEED_PRODUCING) || |
1098 | | (cur_len == WC_DRBG_NEXT_SEED_CONSUMING)) ? |
1099 | | WC_DRBG_NEXT_SEED_PURGED : WC_DRBG_NEXT_SEED_EMPTY; |
1100 | | WC_CAS_WITH_RETRY_LOOP_FOREVER(wolfSSL_Atomic_Int_CompareExchange, |
1101 | | lenp, cur_len, want_len, ret); |
1102 | | } |
1103 | | } WC_CAS_WITH_RETRY_END; |
1104 | | |
1105 | | /* percolate the CAS result -- if the loop was aborted by user logic, the |
1106 | | * caller needs to know that the purge failed. */ |
1107 | | return ret; |
1108 | | } |
1109 | | |
1110 | | /* Release a producer claim (PRODUCING) on the credited aperture, |
1111 | | * installing val (a fill offset, the full length, READY, or EMPTY). |
1112 | | * Returns 0 on release, else BUSY_E: the release CAS can fail for |
1113 | | * exactly one reason -- a concurrent NextSeedPurge() repainted the |
1114 | | * claim PURGED (producers cannot claim a PRODUCING word, consumers |
1115 | | * only exchange from READY, and the purge is the sole writer against |
1116 | | * a claim). The producer's material then predates the invalidation |
1117 | | * event and must not surface: the aperture reopens EMPTY, which is |
1118 | | * the whole suppression -- an EMPTY aperture is never consumed, and |
1119 | | * the next fill overwrites from offset zero. The bytes themselves are |
1120 | | * wiped before the reopen, while this producer still owns the buffer: |
1121 | | * the purge that repainted the claim marks an event that created a |
1122 | | * sibling lineage, and the sibling's copy of a completed fill may be |
1123 | | * consumed there (see the doctrine at NextSeedPurge()). */ |
1124 | | static int NextSeedProducerRelease(wolfSSL_Atomic_Int *lenp, |
1125 | | byte *seed_buf, word32 seed_buf_sz, |
1126 | | WC_ATOMIC_INT_ARG val) |
1127 | | { |
1128 | | /* No epoch check at publish: a fill that straddles an event is caught |
1129 | | * either by a concurrent propagation (NextSeedPurge() overwrites the |
1130 | | * PRODUCING claim, failing this CAS) or, absent one, by the consumer's own |
1131 | | * entry propagation (every writer of rng->entropy_epoch also purges this |
1132 | | * lane, so a stale stamp and a READY pre-event bank cannot coexist with a |
1133 | | * current stamp). |
1134 | | */ |
1135 | | WC_ATOMIC_INT_ARG expected = WC_DRBG_NEXT_SEED_PRODUCING; |
1136 | | if (wolfSSL_Atomic_Int_CompareExchange(lenp, &expected, val)) |
1137 | | return 0; |
1138 | | ForceZero(seed_buf, seed_buf_sz); |
1139 | | expected = WC_DRBG_NEXT_SEED_PURGED; |
1140 | | (void)wolfSSL_Atomic_Int_CompareExchange(lenp, &expected, |
1141 | | WC_DRBG_NEXT_SEED_EMPTY); |
1142 | | return BUSY_E; |
1143 | | } |
1144 | | |
1145 | | /* Purge the uncredited stir accumulator. Claimed CONSUMING first so the wipe |
1146 | | * runs under ownership; a holder's burn-before-release covers the CONSUMING |
1147 | | * case, and a constructor's _TORNDOWN is never claimed or repainted (the |
1148 | | * reopen is its to make). Blind depositors can tear the wipe, which is |
1149 | | * harmless. */ |
1150 | | static WC_MAYBE_UNUSED void NextStirPurge(WC_RNG* rng) |
1151 | | { |
1152 | | WC_ATOMIC_INT_ARG cur; |
1153 | | int ret; |
1154 | | |
1155 | | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&rng->nextStirLen, cur, ret) { |
1156 | | if ((cur == WC_DRBG_NEXT_SEED_CONSUMING) || |
1157 | | (cur == WC_DRBG_NEXT_SEED_TORNDOWN)) |
1158 | | { |
1159 | | return; |
1160 | | } |
1161 | | WC_CAS_WITH_RETRY_LOOP_FOREVER(wolfSSL_Atomic_Int_CompareExchange, |
1162 | | &rng->nextStirLen, cur, |
1163 | | WC_DRBG_NEXT_SEED_CONSUMING, ret); |
1164 | | } WC_CAS_WITH_RETRY_END; |
1165 | | if (ret != 0) { |
1166 | | /* Aborted claim (a port's retry clause): no claim, so no wipe -- |
1167 | | * and no store either, which could repaint a live claim or a |
1168 | | * constructor's _TORNDOWN. The stale fill stands; resurrection |
1169 | | * of uncredited stir material is benign by the three-no-ops |
1170 | | * doctrine, and the next purge or teardown collects it. */ |
1171 | | return; |
1172 | | } |
1173 | | ForceZero(rng->nextStir, (word32)sizeof(rng->nextStir)); |
1174 | | /* Reopen by CAS, never by plain store: a blind depositor can have |
1175 | | * stored a fill length over the claim (discarded, as before -- |
1176 | | * length only; its bytes lie in place until the next wipe or |
1177 | | * full-buffer fold, benign for the uncredited stir), and a |
1178 | | * constructor can have painted the word _TORNDOWN at any point, the |
1179 | | * reopen then being its to make, not ours. */ |
1180 | | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&rng->nextStirLen, cur, ret) { |
1181 | | if (cur == WC_DRBG_NEXT_SEED_TORNDOWN) |
1182 | | return; |
1183 | | WC_CAS_WITH_RETRY_LOOP_FOREVER(wolfSSL_Atomic_Int_CompareExchange, |
1184 | | &rng->nextStirLen, cur, |
1185 | | WC_DRBG_NEXT_SEED_EMPTY, ret); |
1186 | | } WC_CAS_WITH_RETRY_END; |
1187 | | if (ret != 0) { |
1188 | | /* Aborted reopen: leaving the word CONSUMING would silence the |
1189 | | * stir aperture on this instance, so store EMPTY -- the |
1190 | | * _TORNDOWN-repaint risk on this already-exotic path is accepted, |
1191 | | * and teardown's own wipe and sentinel follow regardless. */ |
1192 | | WOLFSSL_ATOMIC_STORE(rng->nextStirLen, WC_DRBG_NEXT_SEED_EMPTY); |
1193 | | } |
1194 | | } |
1195 | | #endif /* WC_RNG_HAVE_NEXT_SEED */ |
1196 | | |
1197 | | /* in_bracketed_consume: nonzero when the caller feeds this reseed from its own |
1198 | | * _CONSUMING claim on the credited aperture (wc_RNG_DRBG_NextSeedNow_Nonce()). |
1199 | | * The invalidated-entry purges below must then exempt that aperture: purging |
1200 | | * it would steal the caller's claim and defeat its release CAS, converting |
1201 | | * the caller's own recovery into a false epoch violation. An external |
1202 | | * (event) purge still repaints the claim, which is exactly what the |
1203 | | * caller's release CAS exists to detect. */ |
1204 | | static WARN_UNUSED_RESULT int Hash_DRBG_Reseed(WC_RNG* rng, const byte* seed, |
1205 | | word32 seedSz, |
1206 | | const byte* additional, word32 additionalSz, |
1207 | | int in_bracketed_consume, |
1208 | | WC_ATOMIC_UINT_ARG cur_epoch, |
1209 | | WC_RNG_PID_ARG my_pid) |
1210 | 0 | { |
1211 | 0 | int ret; |
1212 | | #ifdef WC_RNG_HAVE_LOCK |
1213 | | WC_RNG_lock_arg_t cur_lock; |
1214 | | #endif |
1215 | |
|
1216 | | #ifndef WC_RNG_HAVE_ENTROPY_EPOCH |
1217 | | (void)cur_epoch; |
1218 | | #endif |
1219 | | #if !defined(HAVE_GETPID) || defined(WOLFSSL_NO_GETPID) |
1220 | | (void)my_pid; |
1221 | | #endif |
1222 | |
|
1223 | 0 | if (rng == NULL) |
1224 | 0 | return BAD_FUNC_ARG; |
1225 | | |
1226 | | /* Never allow an undersized seed to clear an invalidated state. */ |
1227 | 0 | if ((seedSz < WC_DRBG_SEED_SZ) && |
1228 | 0 | (wc_RNG_entropy_needs_recovery(rng) != 0)) |
1229 | 0 | { |
1230 | 0 | return BAD_LENGTH_E; |
1231 | 0 | } |
1232 | | |
1233 | | #ifdef WC_RNG_HAVE_LOCK |
1234 | | cur_lock = WOLFSSL_ATOMIC_LOAD(rng->lock); |
1235 | | |
1236 | | /* Iff _ENTROPY_INVALIDATED, assert the _ENTROPY_RECOVERING bit now -- if we |
1237 | | * are re-invalidated in the meantime, it will have been cleared by the |
1238 | | * invalidation at exit time, signaling that we are still invalidated. */ |
1239 | | |
1240 | | WC_CAS_WITH_RETRY_BEGIN(&rng->lock, cur_lock, ret) { |
1241 | | if (! (cur_lock & WC_RNG_LOCK_ENTROPY_INVALIDATED)) { |
1242 | | /* Not invalidated -- no recovery mutex needed. Explicit |
1243 | | * success: BEGIN initializes ret to a failure code. */ |
1244 | | ret = 0; |
1245 | | break; |
1246 | | } |
1247 | | if (cur_lock & WC_RNG_LOCK_ENTROPY_RECOVERING) { |
1248 | | /* Must short-circuit return here, so that we don't improperly clear |
1249 | | * the _RECOVERING bit. */ |
1250 | | return BUSY_E; |
1251 | | } |
1252 | | WC_CAS_WITH_RETRY_LOOP_FOREVER(wolfSSL_Atomic_Uint_CompareExchange, |
1253 | | &rng->lock, cur_lock, |
1254 | | cur_lock | WC_RNG_LOCK_ENTROPY_RECOVERING, |
1255 | | ret); |
1256 | | /* We now have the _RECOVERING mutex -- record that fact. */ |
1257 | | cur_lock |= WC_RNG_LOCK_ENTROPY_RECOVERING; |
1258 | | } WC_CAS_WITH_RETRY_END; |
1259 | | if (ret != 0) { |
1260 | | /* Aborted acquire (a port's retry clause): the lock word is |
1261 | | * untouched and no state has moved -- bail before the purges, |
1262 | | * which must not run unserialized against a concurrent |
1263 | | * recovery. */ |
1264 | | return ret; |
1265 | | } |
1266 | | #endif /* WC_RNG_HAVE_LOCK */ |
1267 | | |
1268 | | #ifdef WC_RNG_HAVE_POOL |
1269 | | /* Purge the pool when recovering from invalidation, or if reseeding without |
1270 | | * locks (i.e. without an internal mechanism for tracking invalidation). |
1271 | | * |
1272 | | * The reseed counter tracks generates since the last reseed, and every |
1273 | | * pooled byte is itself a generate that incremented it. So the pool's |
1274 | | * contents are within the budget the counter enforces -- indeed they were |
1275 | | * authorized by the same accounting that later demanded the |
1276 | | * reseed. Discarding them treats output as retroactively over-budget when |
1277 | | * it was under-budget when produced. |
1278 | | */ |
1279 | | #ifdef WC_RNG_HAVE_LOCK |
1280 | | if ((cur_lock & WC_RNG_LOCK_ENTROPY_INVALIDATED) |
1281 | | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
1282 | | /* An epoch increment not yet propagated to the latch retires |
1283 | | * pre-increment pooled output exactly as a latched event does. If |
1284 | | * !WC_RNG_HAVE_LOCK, we purge unconditionally anyway, no need to check |
1285 | | * the entropy epoch. */ |
1286 | | || (rng->entropy_epoch != cur_epoch) |
1287 | | #endif |
1288 | | ) |
1289 | | #endif |
1290 | | { |
1291 | | ret = PoolPurge(rng); |
1292 | | if ((ret != 0) && |
1293 | | (ret != WC_NO_ERR_TRACE(ALREADY_E))) |
1294 | | { |
1295 | | goto out; |
1296 | | } |
1297 | | } |
1298 | | #endif /* WC_RNG_HAVE_POOL */ |
1299 | | |
1300 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
1301 | | if (! in_bracketed_consume) { |
1302 | | int purge_next_seed = 0; |
1303 | | #ifdef WC_RNG_HAVE_LOCK |
1304 | | if (cur_lock & WC_RNG_LOCK_ENTROPY_INVALIDATED) |
1305 | | purge_next_seed = 1; |
1306 | | #endif |
1307 | | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
1308 | | /* see the pool-purge arm re unpropagated epoch increments */ |
1309 | | if (rng->entropy_epoch != cur_epoch) |
1310 | | purge_next_seed = 1; |
1311 | | #endif |
1312 | | if (purge_next_seed) { |
1313 | | ret = NextSeedPurge(rng); |
1314 | | if ((ret != 0) && |
1315 | | (ret != WC_NO_ERR_TRACE(ALREADY_E))) |
1316 | | { |
1317 | | goto out; |
1318 | | } |
1319 | | /* the uncredited stir aperture is purged too, for provenance |
1320 | | * uniformity; best-effort (an in-flight depositor may |
1321 | | * resurrect a partial fill -- benign, stirs carry no |
1322 | | * divergence burden). */ |
1323 | | NextStirPurge(rng); |
1324 | | } |
1325 | | } |
1326 | | #else |
1327 | 0 | (void)in_bracketed_consume; |
1328 | 0 | #endif |
1329 | |
|
1330 | 0 | #ifndef NO_SHA256 |
1331 | 0 | if (rng->drbgType == WC_DRBG_SHA256) { |
1332 | 0 | DRBG_internal* drbg = (DRBG_internal *)rng->drbg; |
1333 | |
|
1334 | 0 | if (drbg == NULL) { |
1335 | | #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND) |
1336 | | if (IS_INTEL_RDRAND(intel_flags)) { |
1337 | | /* using RDRAND not DRBG, so return success */ |
1338 | | ret = 0; |
1339 | | goto out; |
1340 | | } |
1341 | | #endif |
1342 | 0 | ret = BAD_FUNC_ARG; |
1343 | 0 | goto out; |
1344 | 0 | } |
1345 | | |
1346 | 0 | ret = Hash256_DRBG_Reseed(drbg, &rng->reseedCtr, seed, seedSz, |
1347 | 0 | additional, additionalSz); |
1348 | | #ifdef WC_RNG_DEBUG_STATS |
1349 | | if (ret == 0) { |
1350 | | ++rng->_stats_reseeds; |
1351 | | } |
1352 | | #endif |
1353 | 0 | goto out; |
1354 | 0 | } |
1355 | 0 | #endif |
1356 | | |
1357 | 0 | #ifdef WOLFSSL_DRBG_SHA512 |
1358 | 0 | if (rng->drbgType == WC_DRBG_SHA512) { |
1359 | 0 | DRBG_SHA512_internal* drbg512 = |
1360 | 0 | (DRBG_SHA512_internal *)rng->drbg512; |
1361 | |
|
1362 | 0 | if (drbg512 == NULL) { |
1363 | | #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND) |
1364 | | if (IS_INTEL_RDRAND(intel_flags)) { |
1365 | | /* using RDRAND not DRBG, so return success */ |
1366 | | ret = 0; |
1367 | | goto out; |
1368 | | } |
1369 | | #endif |
1370 | 0 | ret = BAD_FUNC_ARG; |
1371 | 0 | goto out; |
1372 | 0 | } |
1373 | | |
1374 | 0 | ret = Hash512_DRBG_Reseed(drbg512, &rng->reseedCtr, seed, seedSz, |
1375 | 0 | additional, additionalSz); |
1376 | | #ifdef WC_RNG_DEBUG_STATS |
1377 | | if (ret == 0) { |
1378 | | ++rng->_stats_reseeds; |
1379 | | } |
1380 | | #endif |
1381 | 0 | goto out; |
1382 | 0 | } |
1383 | 0 | #endif |
1384 | | |
1385 | | /* No DRBG type matched; if using RDRAND, that's OK */ |
1386 | | #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND) |
1387 | | if (IS_INTEL_RDRAND(intel_flags)) { |
1388 | | /* using RDRAND not DRBG, so return success */ |
1389 | | ret = 0; |
1390 | | goto out; |
1391 | | } |
1392 | | #endif |
1393 | | |
1394 | 0 | ret = WRONG_TYPE_OBJECT_E; |
1395 | |
|
1396 | 0 | out: |
1397 | |
|
1398 | | #ifdef WC_RNG_HAVE_LOCK |
1399 | | /* The _RECOVERING bit functions as a mutex -- if it's set here, *we* |
1400 | | * set it, and must clear it. |
1401 | | * |
1402 | | * If we were invalidated on entry, and reseed succeeded, and provided we |
1403 | | * weren't re-invalidated in the meantime, clear the _INVALIDATED bit |
1404 | | * alongside the _RECOVERING bit. |
1405 | | * |
1406 | | * Otherwise, just clear the _RECOVERING bit (releasing the recovery mutex), |
1407 | | * and return with the success or failure code from above. |
1408 | | * |
1409 | | * With the entropy epoch, the clear additionally requires that the |
1410 | | * caller's capture still be current: the latch vouches that the state |
1411 | | * derives from post-event material, and a capture that predates an |
1412 | | * increment cannot vouch for that. Keeping the latch here is also what |
1413 | | * makes the propagator's latch-then-stamp pair safe against this |
1414 | | * lease-holder: a propagator stamp landing after our (stale) stamp |
1415 | | * below would otherwise leave the instance current-and-unlatched with |
1416 | | * pre-event state -- a persistently lost invalidation. The reseed |
1417 | | * itself stands, and ret is unaffected (callers' bookkeeping proceeds); |
1418 | | * the standing obligation surfaces through PollAndReSeed()'s exit |
1419 | | * verdict and the next wc_RNG_entropy_needs_recovery(). |
1420 | | */ |
1421 | | if ((ret == 0) && (cur_lock & WC_RNG_LOCK_ENTROPY_INVALIDATED) |
1422 | | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
1423 | | && (cur_epoch == WOLFSSL_ATOMIC_LOAD(global_entropy_epoch)) |
1424 | | #endif |
1425 | | ) |
1426 | | { |
1427 | | WC_CAS_WITH_RETRY_BEGIN(&rng->lock, cur_lock, ret) { |
1428 | | if (! (cur_lock & WC_RNG_LOCK_ENTROPY_RECOVERING)) { |
1429 | | ret = NEEDS_RECOVERY_E; |
1430 | | break; |
1431 | | } |
1432 | | /* _ORPHANED clears with the latch: a holder completing a |
1433 | | * recovery is a live holder, whatever a post-fork contender |
1434 | | * concluded before the pid was restamped. */ |
1435 | | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
1436 | | wolfSSL_Atomic_Uint_CompareExchange, &rng->lock, cur_lock, |
1437 | | cur_lock & ~(WC_RNG_LOCK_ENTROPY_INVALIDATED | |
1438 | | WC_RNG_LOCK_ENTROPY_RECOVERING | |
1439 | | WC_RNG_LOCK_ORPHANED), |
1440 | | ret); |
1441 | | } WC_CAS_WITH_RETRY_END; |
1442 | | if ((ret != 0) && (ret != WC_NO_ERR_TRACE(NEEDS_RECOVERY_E))) { |
1443 | | /* Aborted clear (a port's retry clause) strands _RECOVERING with no |
1444 | | * in-band path back: every future recovery would refuse BUSY_E. |
1445 | | * Condemn -- in kernel, DRBG_FAILED has an automated exit (the |
1446 | | * entropy daemon's recovery pass), and the owner can always reinit. |
1447 | | * A wedged mutex bit would have no visible indication that reinit |
1448 | | * is required. |
1449 | | */ |
1450 | | rng->status = DRBG_FAILED; |
1451 | | } |
1452 | | } |
1453 | | else if (cur_lock & WC_RNG_LOCK_ENTROPY_RECOVERING) { |
1454 | | /* ret carries the reseed's status here and must survive, so the |
1455 | | * release gets its own result variable. */ |
1456 | | int release_ret; |
1457 | | WC_CAS_WITH_RETRY_BEGIN(&rng->lock, cur_lock, release_ret) { |
1458 | | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
1459 | | wolfSSL_Atomic_Uint_CompareExchange, &rng->lock, cur_lock, |
1460 | | cur_lock & ~WC_RNG_LOCK_ENTROPY_RECOVERING, release_ret); |
1461 | | } WC_CAS_WITH_RETRY_END; |
1462 | | if (release_ret != 0) { |
1463 | | /* Same stranded-_RECOVERING condemnation as the clear arm |
1464 | | * above; the reseed's own status still wins the return. */ |
1465 | | rng->status = DRBG_FAILED; |
1466 | | if (ret == 0) |
1467 | | ret = release_ret; |
1468 | | } |
1469 | | } |
1470 | | #endif /* WC_RNG_HAVE_LOCK */ |
1471 | |
|
1472 | 0 | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
1473 | 0 | if (ret == 0) |
1474 | 0 | rng->entropy_epoch = cur_epoch; |
1475 | 0 | #endif |
1476 | 0 | #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) |
1477 | 0 | if (ret == 0) |
1478 | 0 | rng->pid = my_pid; |
1479 | 0 | #endif |
1480 | |
|
1481 | 0 | return ret; |
1482 | 0 | } |
1483 | | |
1484 | | int wc_RNG_DRBG_Reseed_Nonce(WC_RNG* rng, const byte* seed, word32 seedSz, |
1485 | | const byte *nonce, word32 nonceSz) |
1486 | 0 | { |
1487 | 0 | int ret; |
1488 | 0 | WC_ATOMIC_UINT_ARG cur_epoch = |
1489 | 0 | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
1490 | 0 | WOLFSSL_ATOMIC_LOAD(global_entropy_epoch) |
1491 | | #else |
1492 | | 0 |
1493 | | #endif |
1494 | 0 | ; |
1495 | 0 | WC_RNG_PID_ARG my_pid = WC_RNG_GETPID(); |
1496 | 0 | if (rng == NULL || seed == NULL) { |
1497 | 0 | return BAD_FUNC_ARG; |
1498 | 0 | } |
1499 | | |
1500 | | /* Hash_df() skips a NULL input regardless of its stated length, so |
1501 | | * without this the caller's additional input would be dropped and |
1502 | | * success reported. Matches _InitRng() and ReseedRBGC(). */ |
1503 | 0 | if ((nonce == NULL) && (nonceSz > 0)) |
1504 | 0 | return BAD_FUNC_ARG; |
1505 | | |
1506 | | #if defined(WC_RNG_HAVE_RBGC) && defined(WC_RNG_RBGC_STRATUM_IMMUTABLE) |
1507 | | /* When build settings forbid updating the RBGC stratum, we must refuse |
1508 | | * here, lest an RNG carrying the vetted ESV provenance marker be reseeded |
1509 | | * with an unvetted user seed. */ |
1510 | | if (rng->RBGCStratum < WC_RNG_RBGC_USER_SEED_STRATUM) |
1511 | | return WRONG_TYPE_OBJECT_E; |
1512 | | #endif |
1513 | | |
1514 | 0 | ret = rng_lock_required_check(rng); |
1515 | 0 | if (ret != 0) |
1516 | 0 | return ret; |
1517 | | |
1518 | | /* These checks read state a generate writes under the lock, so the lock |
1519 | | * comes first. The internal reseed paths already hold it. */ |
1520 | 0 | ret = RngAutoLockEnter(rng); |
1521 | 0 | if (ret != 0) |
1522 | 0 | return ret; |
1523 | | |
1524 | | /* A condemned instance does not accept a credited reseed: DRBG_FAILED's |
1525 | | * designed exit is wc_FreeRng()/wc_InitRng() (or the daemon's recovery |
1526 | | * pass), not in-place resurrection that would reset the counter, purge |
1527 | | * the pool, and clear quarantine on unvetted authority. */ |
1528 | 0 | if (rng->status != DRBG_OK) { |
1529 | 0 | ret = RNG_FAILURE_E; |
1530 | 0 | goto out; |
1531 | 0 | } |
1532 | | |
1533 | 0 | ret = rng_entropy_event_propagate(rng); |
1534 | 0 | if ((ret != 0) && (ret != WC_NO_ERR_TRACE(NEEDS_RECOVERY_E))) |
1535 | 0 | goto out; /* delivery failed: condemned, verdict via |
1536 | | wc_RNG_Status() */ |
1537 | | /* NEEDS_RECOVERY_E is what we're here to discharge. */ |
1538 | | |
1539 | | /* Never allow an undersized seed to clear an invalidated state. Note that |
1540 | | * the user seed is not evaluated by wc_RNG_TestSeed() -- calling |
1541 | | * wc_RNG_TestSeed() is the user's responsibility, and is inapplicable when |
1542 | | * wc_InitRngNonce_UserSeed() and wc_RNG_DRBG_Reseed_Nonce() are called from |
1543 | | * KAT tests, or are seeded by another healthy DRBG. |
1544 | | * |
1545 | | * Historically, wc_RNG_DRBG_Reseed() has never imposed wc_RNG_TestSeed(), |
1546 | | * i.e. it has always succeeded deterministically when passed valid |
1547 | | * arguments. wc_RNG_DRBG_Reseed_Nonce() continues that semantic whether |
1548 | | * called directly or via wc_RNG_DRBG_Reseed(). Novel enforcement here is |
1549 | | * frivolous in any case because wc_InitRngNonce_UserSeed() imposes no |
1550 | | * wc_RNG_TestSeed(). |
1551 | | */ |
1552 | 0 | { |
1553 | 0 | if ((seedSz < WC_DRBG_SEED_SZ) && |
1554 | 0 | ((rng->reseedCtr >= WC_RESEED_INTERVAL) |
1555 | | #ifdef WC_RNG_HAVE_LOCK |
1556 | | || (WOLFSSL_ATOMIC_LOAD(rng->lock) & WC_RNG_LOCK_ENTROPY_INVALIDATED) |
1557 | | #endif |
1558 | 0 | )) |
1559 | 0 | { |
1560 | 0 | ret = BAD_LENGTH_E; |
1561 | 0 | goto out; |
1562 | 0 | } |
1563 | 0 | } |
1564 | | |
1565 | 0 | ret = Hash_DRBG_Reseed(rng, seed, seedSz, nonce, nonceSz, |
1566 | 0 | 0 /* in_bracketed_consume */, cur_epoch, my_pid); |
1567 | 0 | if (ret > 0) /* DRBG-internal code: translate at the API */ |
1568 | 0 | ret = RNG_FAILURE_E; |
1569 | | #if defined(WC_RNG_HAVE_RBGC) && !defined(WC_RNG_RBGC_STRATUM_IMMUTABLE) |
1570 | | if (ret == 0) { |
1571 | | /* User-supplied entropy is of unknown provenance. In RBGC builds, |
1572 | | * represent that fact using WC_RNG_RBGC_USER_SEED_STRATUM, preventing |
1573 | | * confusion with RNGs seeded by the ESV. (When |
1574 | | * WC_RNG_RBGC_STRATUM_IMMUTABLE, user reseeds of instances below the |
1575 | | * sentinel are refused above instead.) */ |
1576 | | rng->RBGCStratum = WC_RNG_RBGC_USER_SEED_STRATUM; |
1577 | | } |
1578 | | #endif |
1579 | |
|
1580 | 0 | out: |
1581 | |
|
1582 | 0 | if (ret == 0) |
1583 | 0 | ret = rng_entropy_event_propagate(rng); |
1584 | |
|
1585 | 0 | RngAutoLockExit(rng); |
1586 | 0 | return ret; |
1587 | 0 | } |
1588 | | |
1589 | 0 | int wc_RNG_DRBG_Reseed(WC_RNG* rng, const byte* seed, word32 seedSz) { |
1590 | 0 | return wc_RNG_DRBG_Reseed_Nonce(rng, seed, seedSz, NULL, 0); |
1591 | 0 | } |
1592 | | |
1593 | | #ifdef WC_RNG_HAVE_RBGC |
1594 | | |
1595 | | int wc_RNG_DRBG_GetRBGCStratum(const WC_RNG* rng) |
1596 | | { |
1597 | | if (rng) |
1598 | | return rng->RBGCStratum; |
1599 | | else |
1600 | | return BAD_FUNC_ARG; |
1601 | | } |
1602 | | |
1603 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
1604 | | int wc_RNG_DRBG_GetNextSeedRBGCStratum(const WC_RNG* rng) |
1605 | | { |
1606 | | int ret = wc_RNG_Status(rng); |
1607 | | if (ret != 0) |
1608 | | return ret; |
1609 | | if (! wc_RNG_DRBG_Present(rng)) |
1610 | | return WRONG_TYPE_OBJECT_E; |
1611 | | |
1612 | | /* Race-free via the NextSeed aperture protocol. If called with rng locked, |
1613 | | * and ->nextSeedLen == WC_DRBG_NEXT_SEED_READY, then competing producers |
1614 | | * and consumers are all excluded, unambiguously marking |
1615 | | * ->nextSeedRBGCStratum as strictly reliable and stable. nextSeedLen |
1616 | | * functions as the synchronizer -- the producer writes |
1617 | | * ->nextSeedRBGCStratum before publishing WC_DRBG_NEXT_SEED_READY to |
1618 | | * nextSeedLen with release semantics. |
1619 | | */ |
1620 | | |
1621 | | if (WOLFSSL_ATOMIC_LOAD(rng->nextSeedLen) != WC_DRBG_NEXT_SEED_READY) |
1622 | | return NOT_READY_E; |
1623 | | else |
1624 | | return rng->nextSeedRBGCStratum; |
1625 | | } |
1626 | | #endif /* WC_RNG_HAVE_NEXT_SEED */ |
1627 | | |
1628 | | #endif /* WC_RNG_HAVE_RBGC */ |
1629 | | |
1630 | | /* Read-only accessor for the DRBG reseed counter: WRONG_TYPE_OBJECT_E when no |
1631 | | * DRBG is instantiated (see wc_RNG_DRBG_Present()), BAD_STATE_E when the DRBG |
1632 | | * is not in service. The read is unleased and advisory: reseedCtr is written |
1633 | | * only under the lease, and a caller without one (e.g. the kernel entropy |
1634 | | * daemon judging a bonus reseed) sees a value that is stale or, on a 32-bit |
1635 | | * target with a 64-bit counter, torn -- costing at worst one spurious or one |
1636 | | * deferred heuristic reseed, never unsound output. Leased callers read |
1637 | | * exactly. */ |
1638 | | int wc_RNG_DRBG_GetReseedCtr(const WC_RNG* rng, |
1639 | | wc_drbg_reseed_ctr_t* reseedCtr) |
1640 | 0 | { |
1641 | 0 | if ((rng == NULL) || (reseedCtr == NULL)) |
1642 | 0 | return BAD_FUNC_ARG; |
1643 | 0 | if (! wc_RNG_DRBG_Present(rng)) |
1644 | 0 | return WRONG_TYPE_OBJECT_E; |
1645 | 0 | if (rng->status != DRBG_OK) |
1646 | 0 | return BAD_STATE_E; |
1647 | 0 | if ((rng->drbgType == WC_DRBG_SHA256) || |
1648 | 0 | (rng->drbgType == WC_DRBG_SHA512)) |
1649 | 0 | { |
1650 | 0 | *reseedCtr = rng->reseedCtr; |
1651 | 0 | return 0; |
1652 | 0 | } |
1653 | 0 | return BAD_FUNC_ARG; |
1654 | 0 | } |
1655 | | |
1656 | | #if defined(WC_RESEED_INTERVAL) && !defined(WORD64_AVAILABLE) |
1657 | | wc_static_assert((WC_RESEED_INTERVAL) <= 0xFFFFFFFFUL); |
1658 | | #endif |
1659 | | |
1660 | | /* Mark rng due for reseed: the next generate operation reseeds from the |
1661 | | * module's built-in or registered seed source before producing output (see also |
1662 | | * wc_RNG_DRBG_Reseed_Now()). This can only shorten the current seed's |
1663 | | * remaining lifetime, never extend it. When no DRBG is instantiated (RDRAND et |
1664 | | * al.) commanded reseed is not supported and the call returns |
1665 | | * WRONG_TYPE_OBJECT_E. */ |
1666 | | /* Every public entry below locks the instance, with a _local core for the |
1667 | | * generate path, which already holds the lock. |
1668 | | * |
1669 | | * Why they lock at all: they mutate the same DRBG state a generate does. |
1670 | | * Unlocked, a second thread reads and writes the reseed counter and the hash |
1671 | | * context mid-update, which ThreadSanitizer reports as a data race: 48 of them |
1672 | | * before this change, none after. Nothing crashes and the output still looks |
1673 | | * random, which is what makes it easy to ship by mistake. |
1674 | | */ |
1675 | | static WARN_UNUSED_RESULT int wc_RNG_DRBG_ScheduleReseed_local(WC_RNG* rng) |
1676 | 0 | { |
1677 | 0 | int ret = wc_RNG_Status(rng); |
1678 | 0 | if (ret != 0) |
1679 | 0 | return ret; |
1680 | | /* No DRBG (RDRAND et al.): nothing to schedule, and success without |
1681 | | * action, as for every seed operation on such an instance -- |
1682 | | * wc_RNG_DRBG_Present() is the caller's disambiguator. */ |
1683 | 0 | if (! wc_RNG_DRBG_Present(rng)) |
1684 | 0 | return 0; |
1685 | 0 | rng->reseedCtr = (wc_drbg_reseed_ctr_t)WC_RESEED_INTERVAL; |
1686 | 0 | return 0; |
1687 | 0 | } |
1688 | | |
1689 | | /* Note, _ScheduleReseed() is racy (best effort) unless the rng is |
1690 | | * WC_RNG_LOCK_REQUIRED (or handled by callers as though _LOCK_REQUIRED) and the |
1691 | | * _ScheduleReseed() caller holds the lock. */ |
1692 | | int wc_RNG_DRBG_ScheduleReseed(WC_RNG* rng) |
1693 | 0 | { |
1694 | 0 | int ret; |
1695 | |
|
1696 | 0 | if (rng == NULL) |
1697 | 0 | return BAD_FUNC_ARG; |
1698 | 0 | ret = RngAutoLockEnter(rng); |
1699 | 0 | if (ret != 0) |
1700 | 0 | return ret; |
1701 | 0 | ret = wc_RNG_DRBG_ScheduleReseed_local(rng); |
1702 | 0 | RngAutoLockExit(rng); |
1703 | 0 | return ret; |
1704 | 0 | } |
1705 | | |
1706 | | /* Generic byte-array helper -- shared by both SHA-256 and SHA-512 DRBG |
1707 | | * cores. Lives outside the NO_SHA256 guard so SHA-512-only builds |
1708 | | * still build. */ |
1709 | | static WC_INLINE void array_add_one(byte* data, word32 dataSz) |
1710 | 653k | { |
1711 | 653k | int i; |
1712 | 653k | for (i = (int)dataSz - 1; i >= 0; i--) { |
1713 | 653k | data[i] = WC_OCTET(data[i] + 1); |
1714 | 653k | if (data[i] != 0) break; |
1715 | 653k | } |
1716 | 653k | } |
1717 | | |
1718 | | #ifndef NO_SHA256 /* re-open SHA-256 Hash_DRBG core */ |
1719 | | |
1720 | | /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ |
1721 | | static WARN_UNUSED_RESULT int Hash_gen(DRBG_internal* drbg, byte* out, |
1722 | | word32 outSz, const byte* V) |
1723 | 0 | { |
1724 | 0 | int ret = WC_NO_ERR_TRACE(DRBG_FAILURE); |
1725 | 0 | word32 i; |
1726 | 0 | word32 len; |
1727 | | #if defined(WOLFSSL_SMALL_STACK_CACHE) |
1728 | | wc_Sha256* sha = &drbg->sha256; |
1729 | | byte* data = drbg->seed_scratch; /* Note, top half of seed_scratch is used |
1730 | | * by Hash_DRBG_Generate(). */ |
1731 | | byte* digest = drbg->digest_scratch; |
1732 | | #elif defined(WOLFSSL_SMALL_STACK) |
1733 | | wc_Sha256 sha[1]; |
1734 | 0 | byte* data = NULL; |
1735 | 0 | byte* digest = NULL; |
1736 | | #else |
1737 | | wc_Sha256 sha[1]; |
1738 | | byte data[DRBG_SEED_LEN]; |
1739 | | byte digest[WC_SHA256_DIGEST_SIZE]; |
1740 | | #endif |
1741 | |
|
1742 | 0 | if (drbg == NULL) { |
1743 | 0 | return DRBG_FAILURE; |
1744 | 0 | } |
1745 | | |
1746 | 0 | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
1747 | 0 | data = (byte*)XMALLOC(DRBG_SEED_LEN, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
1748 | 0 | digest = (byte*)XMALLOC(WC_SHA256_DIGEST_SIZE, drbg->heap, |
1749 | 0 | DYNAMIC_TYPE_DIGEST); |
1750 | 0 | if (data == NULL || digest == NULL) { |
1751 | 0 | XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); |
1752 | 0 | XFREE(data, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
1753 | 0 | return DRBG_FAILURE; |
1754 | 0 | } |
1755 | 0 | #endif |
1756 | | |
1757 | | /* Special case: outSz is 0 and out is NULL (Hash_DRBG_StirGenerate()): run |
1758 | | * a single Hashgen iteration with the block discarded, so the caller gets |
1759 | | * Generate's V-advance side effects without emitting output. This |
1760 | | * preserves standard SP 800-90A sequencing, while presenting call semantics |
1761 | | * that are convenient for the stir. */ |
1762 | 0 | if (outSz == 0) { |
1763 | 0 | outSz = 1; |
1764 | 0 | } |
1765 | |
|
1766 | 0 | len = (outSz / OUTPUT_BLOCK_LEN) + ((outSz % OUTPUT_BLOCK_LEN) ? 1 : 0); |
1767 | |
|
1768 | 0 | XMEMCPY(data, V, DRBG_SEED_LEN); |
1769 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
1770 | | wc_MemZero_Add("Hash_gen data", data, DRBG_SEED_LEN); |
1771 | | #ifndef WOLFSSL_SMALL_STACK_CACHE |
1772 | | /* cached digest is the caller's drbg->digest_scratch, already registered */ |
1773 | | XMEMSET(digest, 0, WC_SHA256_DIGEST_SIZE); |
1774 | | wc_MemZero_Add("Hash_gen digest", digest, WC_SHA256_DIGEST_SIZE); |
1775 | | #endif |
1776 | | #endif |
1777 | 0 | for (i = 0; i < len; i++) { |
1778 | 0 | #ifndef WOLFSSL_SMALL_STACK_CACHE |
1779 | 0 | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
1780 | 0 | ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); |
1781 | | #else |
1782 | | ret = wc_InitSha256(sha); |
1783 | | #endif |
1784 | 0 | if (ret == 0) |
1785 | 0 | #endif |
1786 | 0 | ret = wc_Sha256Update(sha, data, DRBG_SEED_LEN); |
1787 | 0 | if (ret == 0) |
1788 | 0 | ret = wc_Sha256Final(sha, digest); |
1789 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
1790 | | if (ret != 0) |
1791 | | (void)wc_Sha256Reset(sha); |
1792 | | #else |
1793 | 0 | wc_Sha256Free(sha); |
1794 | 0 | #endif |
1795 | |
|
1796 | 0 | if (ret == 0) { |
1797 | 0 | if (out != NULL && outSz != 0) { |
1798 | 0 | if (outSz >= OUTPUT_BLOCK_LEN) { |
1799 | 0 | XMEMCPY(out, digest, OUTPUT_BLOCK_LEN); |
1800 | 0 | outSz -= OUTPUT_BLOCK_LEN; |
1801 | 0 | out += OUTPUT_BLOCK_LEN; |
1802 | 0 | array_add_one(data, DRBG_SEED_LEN); |
1803 | 0 | } |
1804 | 0 | else { |
1805 | 0 | XMEMCPY(out, digest, outSz); |
1806 | 0 | outSz = 0; |
1807 | 0 | } |
1808 | 0 | } |
1809 | 0 | } |
1810 | 0 | else { |
1811 | | /* wc_Sha256Update or wc_Sha256Final returned error */ |
1812 | 0 | break; |
1813 | 0 | } |
1814 | 0 | } |
1815 | 0 | ForceZero(data, DRBG_SEED_LEN); |
1816 | 0 | ForceZero(digest, WC_SHA256_DIGEST_SIZE); |
1817 | | #if (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_SMALL_STACK_CACHE)) && \ |
1818 | | defined(WOLFSSL_CHECK_MEM_ZERO) |
1819 | | wc_MemZero_Check(data, DRBG_SEED_LEN); |
1820 | | #ifndef WOLFSSL_SMALL_STACK_CACHE |
1821 | | wc_MemZero_Check(digest, WC_SHA256_DIGEST_SIZE); |
1822 | | #endif |
1823 | | #endif |
1824 | |
|
1825 | 0 | #ifndef WOLFSSL_SMALL_STACK_CACHE |
1826 | 0 | WC_FREE_VAR_EX(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); |
1827 | 0 | WC_FREE_VAR_EX(data, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
1828 | 0 | #endif |
1829 | |
|
1830 | | #ifdef WC_VERBOSE_RNG |
1831 | | if ((ret != DRBG_SUCCESS) && (ret != WC_NO_ERR_TRACE(DRBG_FAILURE))) { |
1832 | | /* Note, if we're just going to return DRBG_FAILURE to the caller, then |
1833 | | * there's no point printing it out here because (1) the lower-level |
1834 | | * code that was remapped to DRBG_FAILURE already got printed before the |
1835 | | * remapping, so a DRBG_FAILURE message would just be spamming the log, |
1836 | | * and (2) the caller will actually see the DRBG_FAILURE code, and is |
1837 | | * free to (and probably will) log it itself. |
1838 | | */ |
1839 | | WOLFSSL_DEBUG_PRINTF("ERROR: Hash_gen failed with err %d.", ret); |
1840 | | } |
1841 | | #endif |
1842 | |
|
1843 | 0 | return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE; |
1844 | 0 | } |
1845 | | |
1846 | | #endif /* !NO_SHA256 - close to expose array_add to SHA-512 below */ |
1847 | | |
1848 | | /* Generic multi-byte add. Shared by SHA-256 and SHA-512 DRBG cores; |
1849 | | * lives outside the NO_SHA256 guard so SHA-512-only builds still link. */ |
1850 | | static WC_INLINE void array_add(byte* d, word32 dLen, const byte* s, word32 sLen) |
1851 | 1.73M | { |
1852 | 1.73M | if (dLen > 0 && sLen > 0 && dLen >= sLen) { |
1853 | 1.73M | int sIdx, dIdx; |
1854 | 1.73M | word16 carry = 0; |
1855 | | |
1856 | 1.73M | dIdx = (int)dLen - 1; |
1857 | 107M | for (sIdx = (int)sLen - 1; sIdx >= 0; sIdx--) { |
1858 | 106M | carry = (word16)(carry + d[dIdx] + s[sIdx]); |
1859 | 106M | d[dIdx] = WC_OCTET(carry); |
1860 | 106M | carry >>= 8; |
1861 | 106M | dIdx--; |
1862 | 106M | } |
1863 | | |
1864 | 88.6M | for (; dIdx >= 0; dIdx--) { |
1865 | 86.9M | carry = (word16)(carry + d[dIdx]); |
1866 | 86.9M | d[dIdx] = WC_OCTET(carry); |
1867 | 86.9M | carry >>= 8; |
1868 | 86.9M | } |
1869 | 1.73M | } |
1870 | 1.73M | } |
1871 | | |
1872 | | #ifndef NO_SHA256 /* re-open SHA-256 Hash_DRBG core */ |
1873 | | |
1874 | | /* Returns: DRBG_SUCCESS, DRBG_NEED_RESEED, or DRBG_FAILURE. DRBG state is |
1875 | | * always consistent upon return, whether success or failure. */ |
1876 | | static WARN_UNUSED_RESULT int Hash_DRBG_Generate(DRBG_internal* drbg, |
1877 | | wc_drbg_reseed_ctr_t *reseedCtr_ptr, |
1878 | | byte* out, word32 outSz, |
1879 | | const byte* additional, word32 additionalSz) |
1880 | 0 | { |
1881 | 0 | int ret; |
1882 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
1883 | | wc_Sha256* sha = &drbg->sha256; |
1884 | | #else |
1885 | 0 | wc_Sha256 sha[1]; |
1886 | 0 | #endif |
1887 | 0 | byte type; |
1888 | 0 | wc_drbg_reseed_ctr_t reseedCtr; |
1889 | | #ifdef WOLFSSL_WIDE_BYTE |
1890 | | byte ctrBuf[8]; /* reseed counter as big-endian octets */ |
1891 | | #endif |
1892 | 0 | byte *thisV = NULL; |
1893 | 0 | WC_DECLARE_VAR(shadowV, byte, DRBG_SEED_LEN, 0); |
1894 | |
|
1895 | 0 | if ((drbg == NULL) || (reseedCtr_ptr == NULL)) { |
1896 | 0 | return DRBG_FAILURE; |
1897 | 0 | } |
1898 | | |
1899 | 0 | if (*reseedCtr_ptr >= WC_RESEED_INTERVAL) { |
1900 | | #if (defined(DEBUG_WOLFSSL) || defined(DEBUG_DRBG_RESEEDS)) && \ |
1901 | | defined(WOLFSSL_DEBUG_PRINTF) |
1902 | | WOLFSSL_DEBUG_PRINTF("DRBG reseed triggered, reseedCtr == %lu", |
1903 | | (unsigned long)*reseedCtr_ptr); |
1904 | | #endif |
1905 | 0 | return DRBG_NEED_RESEED; |
1906 | 0 | } |
1907 | 0 | else { |
1908 | | #if defined(WOLFSSL_SMALL_STACK_CACHE) |
1909 | | byte* digest = drbg->digest_scratch; |
1910 | | #elif defined(WOLFSSL_SMALL_STACK) |
1911 | 0 | byte* digest = (byte*)XMALLOC(WC_SHA256_DIGEST_SIZE, drbg->heap, |
1912 | 0 | DYNAMIC_TYPE_DIGEST); |
1913 | 0 | if (digest == NULL) |
1914 | 0 | return DRBG_FAILURE; |
1915 | | #else |
1916 | | byte digest[WC_SHA256_DIGEST_SIZE]; |
1917 | | #endif |
1918 | | |
1919 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
1920 | | /* baseline 0 (not 0xff): a pre-write early exit on this path checks |
1921 | | * digest, so it must read zero. Registered across the whole generate; |
1922 | | * every exit below force-zeros+checks (or XFREEs) it. */ |
1923 | | XMEMSET(digest, 0, WC_SHA256_DIGEST_SIZE); |
1924 | | wc_MemZero_Add("Hash_DRBG_Generate digest", digest, |
1925 | | WC_SHA256_DIGEST_SIZE); |
1926 | | #endif |
1927 | | |
1928 | 0 | type = drbgGenerateH; |
1929 | 0 | reseedCtr = *reseedCtr_ptr; |
1930 | | |
1931 | | /* SP 800-90A 10.1.1.4 step 2: if additional_input != Null, |
1932 | | * w = Hash(0x02 || V || additional_input), V = (V + w) mod 2^seedlen */ |
1933 | 0 | if (additional != NULL && additionalSz > 0) { |
1934 | 0 | byte addType = drbgGenerateW; |
1935 | 0 | #ifndef WOLFSSL_SMALL_STACK_CACHE |
1936 | 0 | ret = 0; |
1937 | 0 | WC_ALLOC_VAR_EX(shadowV, byte, DRBG_SEED_LEN, drbg->heap, |
1938 | 0 | DYNAMIC_TYPE_TMP_BUFFER, ret = MEMORY_E); |
1939 | 0 | if (ret == 0) { |
1940 | 0 | thisV = shadowV; |
1941 | 0 | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
1942 | 0 | ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); |
1943 | | #else |
1944 | | ret = wc_InitSha256(sha); |
1945 | | #endif |
1946 | 0 | } |
1947 | |
|
1948 | 0 | if (ret != 0) { |
1949 | 0 | WC_FREE_VAR_EX(shadowV, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
1950 | | /* digest holds only the 0 baseline here (never written) */ |
1951 | | #if (!defined(WOLFSSL_SMALL_STACK) || \ |
1952 | | defined(WOLFSSL_SMALL_STACK_CACHE)) && \ |
1953 | | defined(WOLFSSL_CHECK_MEM_ZERO) |
1954 | | wc_MemZero_Check(digest, WC_SHA256_DIGEST_SIZE); |
1955 | | #endif |
1956 | 0 | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
1957 | 0 | XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); |
1958 | 0 | #endif |
1959 | 0 | return DRBG_FAILURE; |
1960 | 0 | } |
1961 | | #else |
1962 | | (void)shadowV; |
1963 | | /* use the upper half of drbg->seed_scratch -- the lower half is |
1964 | | * used by Hash_gen() for its "data" work buffer. */ |
1965 | | thisV = drbg->seed_scratch + DRBG_SEED_LEN; |
1966 | | ret = 0; |
1967 | | #endif |
1968 | 0 | if (ret == 0) |
1969 | 0 | ret = wc_Sha256Update(sha, &addType, sizeof(addType)); |
1970 | 0 | if (ret == 0) |
1971 | 0 | ret = wc_Sha256Update(sha, drbg->V, sizeof(drbg->V)); |
1972 | 0 | if (ret == 0) |
1973 | 0 | ret = wc_Sha256Update(sha, additional, additionalSz); |
1974 | 0 | if (ret == 0) |
1975 | 0 | ret = wc_Sha256Final(sha, digest); |
1976 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
1977 | | if (ret != 0) |
1978 | | (void)wc_Sha256Reset(sha); |
1979 | | #else |
1980 | 0 | wc_Sha256Free(sha); |
1981 | 0 | #endif |
1982 | 0 | if (ret == 0) { |
1983 | 0 | XMEMCPY(thisV, drbg->V, DRBG_SEED_LEN); |
1984 | 0 | array_add(thisV, DRBG_SEED_LEN, digest, |
1985 | 0 | WC_SHA256_DIGEST_SIZE); |
1986 | 0 | } |
1987 | 0 | else { |
1988 | 0 | WC_FREE_VAR_EX(shadowV, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
1989 | 0 | ForceZero(digest, WC_SHA256_DIGEST_SIZE); |
1990 | | #if (!defined(WOLFSSL_SMALL_STACK) || \ |
1991 | | defined(WOLFSSL_SMALL_STACK_CACHE)) && \ |
1992 | | defined(WOLFSSL_CHECK_MEM_ZERO) |
1993 | | wc_MemZero_Check(digest, WC_SHA256_DIGEST_SIZE); |
1994 | | #endif |
1995 | 0 | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
1996 | 0 | XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); |
1997 | 0 | #endif |
1998 | 0 | return DRBG_FAILURE; |
1999 | 0 | } |
2000 | 0 | } |
2001 | 0 | else { |
2002 | 0 | thisV = drbg->V; |
2003 | 0 | } |
2004 | | |
2005 | 0 | ret = Hash_gen(drbg, out, outSz, thisV); |
2006 | 0 | if (ret == DRBG_SUCCESS) { |
2007 | 0 | #ifndef WOLFSSL_SMALL_STACK_CACHE |
2008 | 0 | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
2009 | 0 | ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); |
2010 | | #else |
2011 | | ret = wc_InitSha256(sha); |
2012 | | #endif |
2013 | 0 | if (ret == 0) |
2014 | 0 | #endif |
2015 | 0 | ret = wc_Sha256Update(sha, &type, sizeof(type)); |
2016 | 0 | if (ret == 0) |
2017 | 0 | ret = wc_Sha256Update(sha, thisV, DRBG_SEED_LEN); |
2018 | 0 | if (ret == 0) |
2019 | 0 | ret = wc_Sha256Final(sha, digest); |
2020 | |
|
2021 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
2022 | | if (ret != 0) |
2023 | | (void)wc_Sha256Reset(sha); |
2024 | | #else |
2025 | 0 | wc_Sha256Free(sha); |
2026 | 0 | #endif |
2027 | |
|
2028 | 0 | if (ret == 0) { |
2029 | | /* No failure possible from here -- commit thisV if needed. */ |
2030 | 0 | if (thisV != drbg->V) |
2031 | 0 | XMEMCPY(drbg->V, thisV, DRBG_SEED_LEN); |
2032 | 0 | array_add(drbg->V, sizeof(drbg->V), digest, WC_SHA256_DIGEST_SIZE); |
2033 | 0 | array_add(drbg->V, sizeof(drbg->V), drbg->C, sizeof(drbg->C)); |
2034 | | #ifdef WOLFSSL_WIDE_BYTE |
2035 | | /* A word cannot be aliased as an octet stream where a C byte is |
2036 | | * wider than 8 bits; add the counter as big-endian octets. */ |
2037 | | #ifdef WORD64_AVAILABLE |
2038 | | BytesFromWordsBE64(ctrBuf, &reseedCtr, 8); |
2039 | | array_add(drbg->V, sizeof(drbg->V), ctrBuf, 8); |
2040 | | #else |
2041 | | BytesFromWordsBE32(ctrBuf, &reseedCtr, 4); |
2042 | | array_add(drbg->V, sizeof(drbg->V), ctrBuf, 4); |
2043 | | #endif |
2044 | | #else |
2045 | 0 | #ifdef LITTLE_ENDIAN_ORDER |
2046 | 0 | #ifdef WORD64_AVAILABLE |
2047 | 0 | reseedCtr = ByteReverseWord64(reseedCtr); |
2048 | | #else |
2049 | | reseedCtr = ByteReverseWord32(reseedCtr); |
2050 | | #endif |
2051 | 0 | #endif |
2052 | 0 | array_add(drbg->V, sizeof(drbg->V), |
2053 | 0 | (byte*)&reseedCtr, sizeof(reseedCtr)); |
2054 | 0 | #endif |
2055 | 0 | ret = DRBG_SUCCESS; |
2056 | 0 | (*reseedCtr_ptr)++; |
2057 | 0 | } |
2058 | | /* else no state mutation, hence no reseed counter increment. */ |
2059 | 0 | } |
2060 | 0 | ForceZero(digest, WC_SHA256_DIGEST_SIZE); |
2061 | | #if (!defined(WOLFSSL_SMALL_STACK) || \ |
2062 | | defined(WOLFSSL_SMALL_STACK_CACHE)) && \ |
2063 | | defined(WOLFSSL_CHECK_MEM_ZERO) |
2064 | | wc_MemZero_Check(digest, WC_SHA256_DIGEST_SIZE); |
2065 | | #endif |
2066 | 0 | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
2067 | 0 | XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); |
2068 | 0 | #endif |
2069 | 0 | } |
2070 | | |
2071 | | #ifdef WC_VERBOSE_RNG |
2072 | | if ((ret != DRBG_SUCCESS) && (ret != WC_NO_ERR_TRACE(DRBG_FAILURE))) { |
2073 | | /* see note above regarding log spam reduction */ |
2074 | | WOLFSSL_DEBUG_PRINTF("ERROR: Hash_DRBG_Generate failed with err %d.", |
2075 | | ret); |
2076 | | } |
2077 | | #endif |
2078 | | |
2079 | 0 | if ((thisV != drbg->V) && (thisV != NULL)) |
2080 | 0 | ForceZero(thisV, DRBG_SEED_LEN); |
2081 | 0 | WC_FREE_VAR_EX(shadowV, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
2082 | |
|
2083 | 0 | if (ret == 0) |
2084 | 0 | return DRBG_SUCCESS; |
2085 | 0 | else { |
2086 | | /* wipe the stranded output, which would otherwise be repeated |
2087 | | * on a subsequent successful call. |
2088 | | */ |
2089 | 0 | ForceZero(out, outSz); |
2090 | 0 | return DRBG_FAILURE; |
2091 | 0 | } |
2092 | 0 | } |
2093 | | |
2094 | | /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ |
2095 | | static WARN_UNUSED_RESULT int Hash_DRBG_Init(DRBG_internal* drbg, |
2096 | | wc_drbg_reseed_ctr_t *reseedCtr, |
2097 | | const byte* seed, word32 seedSz, |
2098 | | const byte* nonce, word32 nonceSz, |
2099 | | const byte* perso, word32 persoSz) |
2100 | 0 | { |
2101 | 0 | if ((seed == NULL) || (reseedCtr == NULL)) |
2102 | 0 | return DRBG_FAILURE; |
2103 | | |
2104 | 0 | if (Hash_df(drbg, drbg->V, sizeof(drbg->V), drbgInitV, seed, seedSz, |
2105 | 0 | nonce, nonceSz, |
2106 | 0 | perso, persoSz) == DRBG_SUCCESS && |
2107 | 0 | Hash_df(drbg, drbg->C, sizeof(drbg->C), drbgInitC, drbg->V, |
2108 | 0 | sizeof(drbg->V), NULL, 0, |
2109 | 0 | NULL, 0) == DRBG_SUCCESS) { |
2110 | |
|
2111 | 0 | *reseedCtr = 1; |
2112 | 0 | return DRBG_SUCCESS; |
2113 | 0 | } |
2114 | 0 | else { |
2115 | 0 | return DRBG_FAILURE; |
2116 | 0 | } |
2117 | 0 | } |
2118 | | |
2119 | | /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ |
2120 | | static WARN_UNUSED_RESULT int Hash_DRBG_Instantiate(DRBG_internal* drbg, |
2121 | | wc_drbg_reseed_ctr_t *reseedCtr, |
2122 | | const byte* seed, word32 seedSz, |
2123 | | const byte* nonce, word32 nonceSz, |
2124 | | const byte* perso, word32 persoSz, |
2125 | | void* heap, int devId) |
2126 | 0 | { |
2127 | 0 | int ret = WC_NO_ERR_TRACE(DRBG_FAILURE); |
2128 | |
|
2129 | 0 | XMEMSET(drbg, 0, sizeof(DRBG_internal)); |
2130 | 0 | drbg->heap = heap; |
2131 | 0 | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
2132 | 0 | drbg->devId = devId; |
2133 | | #else |
2134 | | (void)devId; |
2135 | | #endif |
2136 | |
|
2137 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
2138 | | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
2139 | | ret = wc_InitSha256_ex(&drbg->sha256, drbg->heap, drbg->devId); |
2140 | | #else |
2141 | | ret = wc_InitSha256(&drbg->sha256); |
2142 | | #endif |
2143 | | if (ret != 0) |
2144 | | return ret; |
2145 | | #endif |
2146 | |
|
2147 | 0 | if (seed != NULL) |
2148 | 0 | ret = Hash_DRBG_Init(drbg, reseedCtr, seed, seedSz, nonce, nonceSz, |
2149 | 0 | perso, persoSz); |
2150 | 0 | return ret; |
2151 | 0 | } |
2152 | | |
2153 | | /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ |
2154 | | static int Hash_DRBG_Uninstantiate(DRBG_internal* drbg) |
2155 | 0 | { |
2156 | 0 | word32 i; |
2157 | 0 | int compareSum = 0; |
2158 | 0 | byte* compareDrbg = (byte*)drbg; |
2159 | |
|
2160 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
2161 | | wc_Sha256Free(&drbg->sha256); |
2162 | | #endif |
2163 | |
|
2164 | 0 | ForceZero(drbg, sizeof(DRBG_internal)); |
2165 | |
|
2166 | 0 | for (i = 0; i < sizeof(DRBG_internal); i++) { |
2167 | 0 | compareSum |= compareDrbg[i] ^ 0; |
2168 | 0 | } |
2169 | |
|
2170 | 0 | return (compareSum == 0) ? DRBG_SUCCESS : DRBG_FAILURE; |
2171 | 0 | } |
2172 | | |
2173 | | #endif /* !NO_SHA256 - SHA-256 Hash_DRBG core block */ |
2174 | | |
2175 | | /* ====================================================================== */ |
2176 | | /* SHA-512 Hash_DRBG (SP 800-90A Rev 1, Table 2) */ |
2177 | | /* */ |
2178 | | /* Internal state (V, C): seedlen = 888 bits = 111 bytes each */ |
2179 | | /* Output block length: 512 bits = 64 bytes (WC_SHA512_DIGEST_SIZE) */ |
2180 | | /* Security strength: 256 bits */ |
2181 | | /* */ |
2182 | | /* NOTE: The raw entropy seed gathered at instantiation / reseed is */ |
2183 | | /* WC_DRBG_SEED_SZ (1024 bits in FIPS builds), NOT seedlen. We overseed */ |
2184 | | /* to tolerate weak entropy sources. Hash_df then compresses the seed */ |
2185 | | /* material down to the 888-bit V and derives C from V. See random.h. */ |
2186 | | /* ====================================================================== */ |
2187 | | #ifdef WOLFSSL_DRBG_SHA512 |
2188 | | |
2189 | 4.81M | #define OUTPUT_BLOCK_LEN_SHA512 (WC_SHA512_DIGEST_SIZE) /* 64 bytes */ |
2190 | | |
2191 | | /* Hash Derivation Function using SHA-512 */ |
2192 | | /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ |
2193 | | static WARN_UNUSED_RESULT int Hash512_df(DRBG_SHA512_internal* drbg, byte* out, |
2194 | | word32 outSz, |
2195 | | byte type, |
2196 | | const byte* inA, word32 inASz, |
2197 | | const byte* inB, word32 inBSz, |
2198 | | const byte* inC, word32 inCSz) |
2199 | 250k | { |
2200 | 250k | int ret = WC_NO_ERR_TRACE(DRBG_FAILURE); |
2201 | 250k | byte ctr; |
2202 | 250k | word32 i; |
2203 | 250k | word32 len; |
2204 | 250k | word32 bits = (outSz * 8); |
2205 | | #ifdef WOLFSSL_WIDE_BYTE |
2206 | | byte bitsBuf[4]; /* the 32-bit length as four big-endian octets */ |
2207 | | #endif |
2208 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
2209 | | wc_Sha512* sha = &drbg->sha512; |
2210 | | #else |
2211 | 250k | wc_Sha512 sha[1]; |
2212 | 250k | #endif |
2213 | | #if defined(WOLFSSL_SMALL_STACK_CACHE) |
2214 | | byte* digest = drbg->digest_scratch; |
2215 | | #elif defined(WOLFSSL_SMALL_STACK) |
2216 | | byte* digest; |
2217 | | #else |
2218 | | #if defined(__GNUC__) && !defined(__clang__) && defined(__AVX512F__) |
2219 | | /* Use a jumbo alignment to work around a gcc compiler/optimizer bug that |
2220 | | * assumes AVX512 alignment in an object sized correctly for AVX512 passed |
2221 | | * to builtin memcpy(), which promptly crashes if not thus aligned. |
2222 | | */ |
2223 | | byte digest[WC_SHA512_DIGEST_SIZE] WOLFSSL_ALIGN(WC_SHA512_DIGEST_SIZE); |
2224 | | #else |
2225 | | byte digest[WC_SHA512_DIGEST_SIZE]; |
2226 | | #endif |
2227 | | #endif |
2228 | | |
2229 | 250k | if (drbg == NULL) { |
2230 | 0 | return DRBG_FAILURE; |
2231 | 0 | } |
2232 | | |
2233 | 250k | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
2234 | 250k | digest = (byte*)XMALLOC(WC_SHA512_DIGEST_SIZE, drbg->heap, |
2235 | 250k | DYNAMIC_TYPE_DIGEST); |
2236 | 250k | if (digest == NULL) |
2237 | 185 | return DRBG_FAILURE; |
2238 | 249k | #endif |
2239 | | |
2240 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
2241 | | /* poison so a missed ForceZero on any path is caught by the check */ |
2242 | | XMEMSET(digest, 0xff, WC_SHA512_DIGEST_SIZE); |
2243 | | wc_MemZero_Add("Hash512_df digest", digest, WC_SHA512_DIGEST_SIZE); |
2244 | | #endif |
2245 | | |
2246 | | #ifdef WOLFSSL_WIDE_BYTE |
2247 | | BytesFromWordsBE32(bitsBuf, &bits, 4); /* see Hash_df */ |
2248 | | #elif defined(LITTLE_ENDIAN_ORDER) |
2249 | 249k | bits = ByteReverseWord32(bits); |
2250 | 249k | #endif |
2251 | 249k | len = (outSz / OUTPUT_BLOCK_LEN_SHA512) |
2252 | 249k | + ((outSz % OUTPUT_BLOCK_LEN_SHA512) ? 1 : 0); |
2253 | | |
2254 | 249k | ctr = 1; |
2255 | 749k | for (i = 0; i < len; i++) { |
2256 | 499k | #ifndef WOLFSSL_SMALL_STACK_CACHE |
2257 | 499k | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
2258 | 499k | ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); |
2259 | | #else |
2260 | | ret = wc_InitSha512(sha); |
2261 | | #endif |
2262 | 499k | if (ret != 0) |
2263 | 0 | break; |
2264 | 499k | #endif |
2265 | 499k | ret = wc_Sha512Update(sha, &ctr, sizeof(ctr)); |
2266 | 499k | if (ret == 0) { |
2267 | 499k | ctr++; |
2268 | | #ifdef WOLFSSL_WIDE_BYTE |
2269 | | ret = wc_Sha512Update(sha, bitsBuf, sizeof(bitsBuf)); |
2270 | | #else |
2271 | 499k | ret = wc_Sha512Update(sha, (byte*)&bits, sizeof(bits)); |
2272 | 499k | #endif |
2273 | 499k | } |
2274 | | |
2275 | 499k | if (ret == 0) { |
2276 | | /* churning V is the only string that doesn't have the type added */ |
2277 | 499k | if (type != drbgInitV) |
2278 | 249k | ret = wc_Sha512Update(sha, &type, sizeof(type)); |
2279 | 499k | } |
2280 | 499k | if (ret == 0) |
2281 | 499k | ret = wc_Sha512Update(sha, inA, inASz); |
2282 | 499k | if (ret == 0) { |
2283 | 499k | if (inB != NULL && inBSz > 0) |
2284 | 0 | ret = wc_Sha512Update(sha, inB, inBSz); |
2285 | 499k | } |
2286 | 499k | if (ret == 0) { |
2287 | 499k | if (inC != NULL && inCSz > 0) |
2288 | 0 | ret = wc_Sha512Update(sha, inC, inCSz); |
2289 | 499k | } |
2290 | 499k | if (ret == 0) |
2291 | 499k | ret = wc_Sha512Final(sha, digest); |
2292 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
2293 | | if (ret != 0) |
2294 | | (void)wc_Sha512Reset(sha); |
2295 | | #else |
2296 | 499k | wc_Sha512Free(sha); |
2297 | 499k | #endif |
2298 | 499k | if (ret == 0) { |
2299 | 499k | if (outSz > OUTPUT_BLOCK_LEN_SHA512) { |
2300 | 249k | XMEMCPY(out, digest, OUTPUT_BLOCK_LEN_SHA512); |
2301 | 249k | outSz -= OUTPUT_BLOCK_LEN_SHA512; |
2302 | 249k | out += OUTPUT_BLOCK_LEN_SHA512; |
2303 | 249k | } |
2304 | 249k | else { |
2305 | 249k | XMEMCPY(out, digest, outSz); |
2306 | 249k | } |
2307 | 499k | } |
2308 | 421 | else { |
2309 | 421 | break; |
2310 | 421 | } |
2311 | 499k | } |
2312 | | |
2313 | 249k | ForceZero(digest, WC_SHA512_DIGEST_SIZE); |
2314 | | /* Explicit check only where the buffer is NOT XFREEd (XFREE auto-checks): |
2315 | | * the stack build and the small-stack-cache build (drbg member). */ |
2316 | | #if (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_SMALL_STACK_CACHE)) && \ |
2317 | | defined(WOLFSSL_CHECK_MEM_ZERO) |
2318 | | wc_MemZero_Check(digest, WC_SHA512_DIGEST_SIZE); |
2319 | | #endif |
2320 | | |
2321 | 249k | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
2322 | 249k | XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); |
2323 | 249k | #endif |
2324 | | |
2325 | | #ifdef WC_VERBOSE_RNG |
2326 | | if (ret != 0) |
2327 | | WOLFSSL_DEBUG_PRINTF("ERROR: %s failed with err = %d", __func__, |
2328 | | ret); |
2329 | | #endif |
2330 | | |
2331 | 249k | return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE; |
2332 | 250k | } |
2333 | | |
2334 | | /* Returns: DRBG_SUCCESS or DRBG_FAILURE. No state mutation on failure. */ |
2335 | | static WARN_UNUSED_RESULT int Hash512_DRBG_Reseed(DRBG_SHA512_internal* drbg, |
2336 | | wc_drbg_reseed_ctr_t *reseedCtr, |
2337 | | const byte* seed, word32 seedSz, |
2338 | | const byte* additional, word32 additionalSz) |
2339 | 0 | { |
2340 | 0 | int ret; |
2341 | 0 | WC_DECLARE_VAR(newV_C, byte, DRBG_SHA512_SEED_LEN * 2, 0); |
2342 | 0 | byte *newV, *newC; |
2343 | |
|
2344 | 0 | if (drbg == NULL) { |
2345 | 0 | return DRBG_FAILURE; |
2346 | 0 | } |
2347 | | |
2348 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
2349 | | newV_C = drbg->seed_scratch; |
2350 | | #else |
2351 | 0 | WC_ALLOC_VAR_EX(newV_C, byte, DRBG_SHA512_SEED_LEN * 2, drbg->heap, |
2352 | 0 | DYNAMIC_TYPE_TMP_BUFFER, return DRBG_FAILURE); |
2353 | 0 | #endif |
2354 | 0 | XMEMSET(newV_C, 0, DRBG_SHA512_SEED_LEN * 2); |
2355 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
2356 | | wc_MemZero_Add("Hash512_DRBG_Reseed newV_C", newV_C, |
2357 | | DRBG_SHA512_SEED_LEN * 2); |
2358 | | #endif |
2359 | |
|
2360 | 0 | newV = newV_C; |
2361 | 0 | newC = newV + DRBG_SHA512_SEED_LEN; |
2362 | |
|
2363 | 0 | ret = Hash512_df(drbg, newV, DRBG_SHA512_SEED_LEN, drbgReseed, |
2364 | 0 | drbg->V, sizeof(drbg->V), seed, seedSz, |
2365 | 0 | additional, additionalSz); |
2366 | 0 | if (ret == DRBG_SUCCESS) { |
2367 | 0 | ret = Hash512_df(drbg, newC, DRBG_SHA512_SEED_LEN, drbgInitC, newV, |
2368 | 0 | DRBG_SHA512_SEED_LEN, NULL, 0, |
2369 | 0 | NULL, 0); |
2370 | 0 | } |
2371 | 0 | if (ret == DRBG_SUCCESS) { |
2372 | 0 | XMEMCPY(drbg->V, newV, DRBG_SHA512_SEED_LEN); |
2373 | 0 | XMEMCPY(drbg->C, newC, DRBG_SHA512_SEED_LEN); |
2374 | 0 | *reseedCtr = 1; |
2375 | 0 | } |
2376 | |
|
2377 | 0 | ForceZero(newV_C, DRBG_SHA512_SEED_LEN * 2); |
2378 | | #if (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_SMALL_STACK_CACHE)) && \ |
2379 | | defined(WOLFSSL_CHECK_MEM_ZERO) |
2380 | | wc_MemZero_Check(newV_C, DRBG_SHA512_SEED_LEN * 2); |
2381 | | #endif |
2382 | |
|
2383 | 0 | #ifndef WOLFSSL_SMALL_STACK_CACHE |
2384 | 0 | WC_FREE_VAR_EX(newV_C, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
2385 | 0 | #endif |
2386 | |
|
2387 | 0 | return ret; |
2388 | 0 | } |
2389 | | |
2390 | | /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ |
2391 | | static WARN_UNUSED_RESULT int Hash512_gen(DRBG_SHA512_internal* drbg, |
2392 | | byte* out, word32 outSz, |
2393 | | const byte* V) |
2394 | 560k | { |
2395 | 560k | int ret = WC_NO_ERR_TRACE(DRBG_FAILURE); |
2396 | 560k | word32 i; |
2397 | 560k | word32 len; |
2398 | | #if defined(WOLFSSL_SMALL_STACK_CACHE) |
2399 | | wc_Sha512* sha = &drbg->sha512; |
2400 | | byte* data = drbg->seed_scratch; /* Note, top half of seed_scratch is used |
2401 | | * by Hash_DRBG_Generate(). */ |
2402 | | byte* digest = drbg->digest_scratch; |
2403 | | #elif defined(WOLFSSL_SMALL_STACK) |
2404 | | wc_Sha512 sha[1]; |
2405 | 560k | byte* data = NULL; |
2406 | 560k | byte* digest = NULL; |
2407 | | #else |
2408 | | wc_Sha512 sha[1]; |
2409 | | byte data[DRBG_SHA512_SEED_LEN]; |
2410 | | byte digest[WC_SHA512_DIGEST_SIZE]; |
2411 | | #endif |
2412 | | |
2413 | 560k | if (drbg == NULL) { |
2414 | 0 | return DRBG_FAILURE; |
2415 | 0 | } |
2416 | | |
2417 | 560k | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
2418 | 560k | data = (byte*)XMALLOC(DRBG_SHA512_SEED_LEN, drbg->heap, |
2419 | 560k | DYNAMIC_TYPE_TMP_BUFFER); |
2420 | 560k | digest = (byte*)XMALLOC(WC_SHA512_DIGEST_SIZE, drbg->heap, |
2421 | 560k | DYNAMIC_TYPE_DIGEST); |
2422 | 560k | if (data == NULL || digest == NULL) { |
2423 | 490 | XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); |
2424 | 490 | XFREE(data, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
2425 | 490 | return DRBG_FAILURE; |
2426 | 490 | } |
2427 | 559k | #endif |
2428 | | |
2429 | | /* Special case: outSz is 0 and out is NULL (Hash_DRBG_StirGenerate()): run |
2430 | | * a single Hashgen iteration with the block discarded, so the caller gets |
2431 | | * Generate's V-advance side effects without emitting output. This |
2432 | | * preserves standard SP 800-90A sequencing, while presenting call semantics |
2433 | | * that are convenient for the stir. */ |
2434 | 559k | if (outSz == 0) { |
2435 | 0 | outSz = 1; |
2436 | 0 | } |
2437 | | |
2438 | 559k | len = (outSz / OUTPUT_BLOCK_LEN_SHA512) |
2439 | 559k | + ((outSz % OUTPUT_BLOCK_LEN_SHA512) ? 1 : 0); |
2440 | | |
2441 | 559k | XMEMCPY(data, V, DRBG_SHA512_SEED_LEN); |
2442 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
2443 | | wc_MemZero_Add("Hash512_gen data", data, DRBG_SHA512_SEED_LEN); |
2444 | | #ifndef WOLFSSL_SMALL_STACK_CACHE |
2445 | | wc_MemZero_Add("Hash512_gen digest", digest, WC_SHA512_DIGEST_SIZE); |
2446 | | #endif |
2447 | | #endif |
2448 | 1.57M | for (i = 0; i < len; i++) { |
2449 | 1.01M | #ifndef WOLFSSL_SMALL_STACK_CACHE |
2450 | 1.01M | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
2451 | 1.01M | ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); |
2452 | | #else |
2453 | | ret = wc_InitSha512(sha); |
2454 | | #endif |
2455 | 1.01M | if (ret == 0) |
2456 | 1.01M | #endif |
2457 | 1.01M | ret = wc_Sha512Update(sha, data, DRBG_SHA512_SEED_LEN); |
2458 | 1.01M | if (ret == 0) |
2459 | 1.01M | ret = wc_Sha512Final(sha, digest); |
2460 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
2461 | | if (ret != 0) |
2462 | | (void)wc_Sha512Reset(sha); |
2463 | | #else |
2464 | 1.01M | wc_Sha512Free(sha); |
2465 | 1.01M | #endif |
2466 | | |
2467 | 1.01M | if (ret == 0) { |
2468 | 1.01M | if (out != NULL && outSz != 0) { |
2469 | 1.01M | if (outSz >= OUTPUT_BLOCK_LEN_SHA512) { |
2470 | 593k | XMEMCPY(out, digest, OUTPUT_BLOCK_LEN_SHA512); |
2471 | 593k | outSz -= OUTPUT_BLOCK_LEN_SHA512; |
2472 | 593k | out += OUTPUT_BLOCK_LEN_SHA512; |
2473 | 593k | array_add_one(data, DRBG_SHA512_SEED_LEN); |
2474 | 593k | } |
2475 | 418k | else { |
2476 | 418k | XMEMCPY(out, digest, outSz); |
2477 | 418k | outSz = 0; |
2478 | 418k | } |
2479 | 1.01M | } |
2480 | 1.01M | } |
2481 | 305 | else { |
2482 | 305 | break; |
2483 | 305 | } |
2484 | 1.01M | } |
2485 | 559k | ForceZero(data, DRBG_SHA512_SEED_LEN); |
2486 | 559k | ForceZero(digest, WC_SHA512_DIGEST_SIZE); |
2487 | | #if (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_SMALL_STACK_CACHE)) && \ |
2488 | | defined(WOLFSSL_CHECK_MEM_ZERO) |
2489 | | wc_MemZero_Check(data, DRBG_SHA512_SEED_LEN); |
2490 | | #ifndef WOLFSSL_SMALL_STACK_CACHE |
2491 | | wc_MemZero_Check(digest, WC_SHA512_DIGEST_SIZE); |
2492 | | #endif |
2493 | | #endif |
2494 | | |
2495 | 559k | #ifndef WOLFSSL_SMALL_STACK_CACHE |
2496 | 559k | WC_FREE_VAR_EX(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); |
2497 | 559k | WC_FREE_VAR_EX(data, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
2498 | 559k | #endif |
2499 | | |
2500 | 559k | return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE; |
2501 | 560k | } |
2502 | | |
2503 | | /* Returns: DRBG_SUCCESS, DRBG_NEED_RESEED, or DRBG_FAILURE. DRBG state is |
2504 | | * always consistent upon return, whether success or failure. */ |
2505 | | static WARN_UNUSED_RESULT int Hash512_DRBG_Generate(DRBG_SHA512_internal* drbg, |
2506 | | wc_drbg_reseed_ctr_t *reseedCtr_ptr, |
2507 | | byte* out, word32 outSz, |
2508 | | const byte* additional, word32 additionalSz) |
2509 | 560k | { |
2510 | 560k | int ret; |
2511 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
2512 | | wc_Sha512* sha = &drbg->sha512; |
2513 | | #else |
2514 | 560k | wc_Sha512 sha[1]; |
2515 | 560k | #endif |
2516 | 560k | byte type; |
2517 | 560k | wc_drbg_reseed_ctr_t reseedCtr; |
2518 | | #ifdef WOLFSSL_WIDE_BYTE |
2519 | | byte ctrBuf[8]; /* reseed counter as big-endian octets */ |
2520 | | #endif |
2521 | 560k | byte *thisV = NULL; |
2522 | 560k | WC_DECLARE_VAR(shadowV, byte, DRBG_SHA512_SEED_LEN, 0); |
2523 | | |
2524 | 560k | if (drbg == NULL) { |
2525 | 0 | return DRBG_FAILURE; |
2526 | 0 | } |
2527 | | |
2528 | 560k | if (*reseedCtr_ptr >= WC_RESEED_INTERVAL) { |
2529 | 0 | return DRBG_NEED_RESEED; |
2530 | 0 | } |
2531 | 560k | else { |
2532 | | #if defined(WOLFSSL_SMALL_STACK_CACHE) |
2533 | | byte* digest = drbg->digest_scratch; |
2534 | | #elif defined(WOLFSSL_SMALL_STACK) |
2535 | 560k | byte* digest = (byte*)XMALLOC(WC_SHA512_DIGEST_SIZE, drbg->heap, |
2536 | 560k | DYNAMIC_TYPE_DIGEST); |
2537 | 560k | if (digest == NULL) |
2538 | 297 | return DRBG_FAILURE; |
2539 | | #else |
2540 | | byte digest[WC_SHA512_DIGEST_SIZE]; |
2541 | | #endif |
2542 | | |
2543 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
2544 | | /* baseline 0; registered across the whole generate, force-zeroed and |
2545 | | * checked at the single exit below (all paths funnel there). */ |
2546 | | XMEMSET(digest, 0, WC_SHA512_DIGEST_SIZE); |
2547 | | wc_MemZero_Add("Hash512_DRBG_Generate digest", digest, |
2548 | | WC_SHA512_DIGEST_SIZE); |
2549 | | #endif |
2550 | | |
2551 | 560k | type = drbgGenerateH; |
2552 | 560k | reseedCtr = *reseedCtr_ptr; |
2553 | | |
2554 | | /* SP 800-90A Section 10.1.1.4 step 2: |
2555 | | * If additional_input != Null, w = Hash(0x02 || V || additional_input), |
2556 | | * V = (V + w) mod 2^seedlen */ |
2557 | 560k | ret = DRBG_SUCCESS; |
2558 | 560k | if (additional != NULL && additionalSz > 0) { |
2559 | 0 | byte addType = drbgGenerateW; /* 0x02 */ |
2560 | 0 | #ifndef WOLFSSL_SMALL_STACK_CACHE |
2561 | 0 | ret = 0; |
2562 | 0 | WC_ALLOC_VAR_EX(shadowV, byte, DRBG_SHA512_SEED_LEN, drbg->heap, |
2563 | 0 | DYNAMIC_TYPE_TMP_BUFFER, ret = MEMORY_E); |
2564 | 0 | if (ret == 0) { |
2565 | 0 | thisV = shadowV; |
2566 | 0 | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
2567 | 0 | ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); |
2568 | | #else |
2569 | | ret = wc_InitSha512(sha); |
2570 | | #endif |
2571 | 0 | } |
2572 | |
|
2573 | 0 | if (ret != 0) { |
2574 | 0 | WC_FREE_VAR_EX(shadowV, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
2575 | | /* digest holds only the 0 baseline here (never written) */ |
2576 | | #if (!defined(WOLFSSL_SMALL_STACK) || \ |
2577 | | defined(WOLFSSL_SMALL_STACK_CACHE)) && \ |
2578 | | defined(WOLFSSL_CHECK_MEM_ZERO) |
2579 | | wc_MemZero_Check(digest, WC_SHA512_DIGEST_SIZE); |
2580 | | #endif |
2581 | 0 | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
2582 | 0 | XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); |
2583 | 0 | #endif |
2584 | 0 | return DRBG_FAILURE; |
2585 | 0 | } |
2586 | | #else |
2587 | | (void)shadowV; |
2588 | | /* use the upper half of drbg->seed_scratch -- the lower half is |
2589 | | * used by Hash512_gen() for its "data" work buffer. */ |
2590 | | thisV = drbg->seed_scratch + DRBG_SHA512_SEED_LEN; |
2591 | | ret = 0; |
2592 | | #endif |
2593 | 0 | if (ret == 0) |
2594 | 0 | ret = wc_Sha512Update(sha, &addType, sizeof(addType)); |
2595 | 0 | if (ret == 0) |
2596 | 0 | ret = wc_Sha512Update(sha, drbg->V, sizeof(drbg->V)); |
2597 | 0 | if (ret == 0) |
2598 | 0 | ret = wc_Sha512Update(sha, additional, additionalSz); |
2599 | 0 | if (ret == 0) |
2600 | 0 | ret = wc_Sha512Final(sha, digest); |
2601 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
2602 | | if (ret != 0) |
2603 | | (void)wc_Sha512Reset(sha); |
2604 | | #else |
2605 | 0 | wc_Sha512Free(sha); |
2606 | 0 | #endif |
2607 | 0 | if (ret == 0) { |
2608 | 0 | XMEMCPY(thisV, drbg->V, DRBG_SHA512_SEED_LEN); |
2609 | 0 | array_add(thisV, DRBG_SHA512_SEED_LEN, digest, |
2610 | 0 | WC_SHA512_DIGEST_SIZE); |
2611 | 0 | } |
2612 | 0 | else { |
2613 | 0 | WC_FREE_VAR_EX(shadowV, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
2614 | 0 | ForceZero(digest, WC_SHA512_DIGEST_SIZE); |
2615 | | #if (!defined(WOLFSSL_SMALL_STACK) || \ |
2616 | | defined(WOLFSSL_SMALL_STACK_CACHE)) && \ |
2617 | | defined(WOLFSSL_CHECK_MEM_ZERO) |
2618 | | wc_MemZero_Check(digest, WC_SHA512_DIGEST_SIZE); |
2619 | | #endif |
2620 | 0 | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
2621 | 0 | XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); |
2622 | 0 | #endif |
2623 | 0 | return DRBG_FAILURE; |
2624 | 0 | } |
2625 | 0 | } |
2626 | 560k | else { |
2627 | 560k | thisV = drbg->V; |
2628 | 560k | } |
2629 | | |
2630 | 560k | if (ret == 0) |
2631 | 560k | ret = Hash512_gen(drbg, out, outSz, thisV); |
2632 | 560k | if (ret == DRBG_SUCCESS) { |
2633 | 559k | #ifndef WOLFSSL_SMALL_STACK_CACHE |
2634 | 559k | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
2635 | 559k | ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); |
2636 | | #else |
2637 | | ret = wc_InitSha512(sha); |
2638 | | #endif |
2639 | 559k | if (ret == 0) |
2640 | 559k | #endif |
2641 | 559k | ret = wc_Sha512Update(sha, &type, sizeof(type)); |
2642 | 559k | if (ret == 0) |
2643 | 559k | ret = wc_Sha512Update(sha, thisV, DRBG_SHA512_SEED_LEN); |
2644 | 559k | if (ret == 0) |
2645 | 559k | ret = wc_Sha512Final(sha, digest); |
2646 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
2647 | | if (ret != 0) |
2648 | | (void)wc_Sha512Reset(sha); |
2649 | | #else |
2650 | 559k | wc_Sha512Free(sha); |
2651 | 559k | #endif |
2652 | | |
2653 | 559k | if (ret == 0) { |
2654 | | /* No failure possible from here -- commit thisV if needed. */ |
2655 | 559k | if (thisV != drbg->V) |
2656 | 0 | XMEMCPY(drbg->V, thisV, DRBG_SHA512_SEED_LEN); |
2657 | 559k | array_add(drbg->V, sizeof(drbg->V), digest, |
2658 | 559k | WC_SHA512_DIGEST_SIZE); |
2659 | 559k | array_add(drbg->V, sizeof(drbg->V), drbg->C, sizeof(drbg->C)); |
2660 | | #ifdef WOLFSSL_WIDE_BYTE |
2661 | | /* See Hash_DRBG_Generate. */ |
2662 | | BytesFromWordsBE64(ctrBuf, &reseedCtr, 8); |
2663 | | array_add(drbg->V, sizeof(drbg->V), ctrBuf, 8); |
2664 | | #else |
2665 | 559k | #ifdef LITTLE_ENDIAN_ORDER |
2666 | 559k | reseedCtr = ByteReverseWord64(reseedCtr); |
2667 | 559k | #endif |
2668 | 559k | array_add(drbg->V, sizeof(drbg->V), |
2669 | 559k | (byte*)&reseedCtr, sizeof(reseedCtr)); |
2670 | 559k | #endif |
2671 | 559k | ret = DRBG_SUCCESS; |
2672 | 559k | (*reseedCtr_ptr)++; |
2673 | 559k | } |
2674 | | /* else no state mutation, hence no reseed counter increment. */ |
2675 | 559k | } |
2676 | 560k | ForceZero(digest, WC_SHA512_DIGEST_SIZE); |
2677 | | #if (!defined(WOLFSSL_SMALL_STACK) || \ |
2678 | | defined(WOLFSSL_SMALL_STACK_CACHE)) && \ |
2679 | | defined(WOLFSSL_CHECK_MEM_ZERO) |
2680 | | wc_MemZero_Check(digest, WC_SHA512_DIGEST_SIZE); |
2681 | | #endif |
2682 | 560k | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
2683 | 560k | XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST); |
2684 | 560k | #endif |
2685 | 560k | } |
2686 | | |
2687 | 560k | if ((thisV != drbg->V) && (thisV != NULL)) |
2688 | 0 | ForceZero(thisV, DRBG_SHA512_SEED_LEN); |
2689 | 560k | WC_FREE_VAR_EX(shadowV, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER); |
2690 | | |
2691 | 560k | if (ret == 0) |
2692 | 559k | return DRBG_SUCCESS; |
2693 | 1.02k | else { |
2694 | | /* wipe the stranded output, which would otherwise be repeated |
2695 | | * on a subsequent successful call. |
2696 | | */ |
2697 | 1.02k | ForceZero(out, outSz); |
2698 | 1.02k | return DRBG_FAILURE; |
2699 | 1.02k | } |
2700 | 560k | } |
2701 | | |
2702 | | /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ |
2703 | | static WARN_UNUSED_RESULT int Hash512_DRBG_Init(DRBG_SHA512_internal* drbg, |
2704 | | wc_drbg_reseed_ctr_t *reseedCtr, |
2705 | | const byte* seed, word32 seedSz, |
2706 | | const byte* nonce, word32 nonceSz, |
2707 | | const byte* perso, word32 persoSz) |
2708 | 137k | { |
2709 | 137k | if ((seed == NULL) || (reseedCtr == NULL)) |
2710 | 0 | return DRBG_FAILURE; |
2711 | | |
2712 | 137k | if (Hash512_df(drbg, drbg->V, sizeof(drbg->V), drbgInitV, seed, seedSz, |
2713 | 137k | nonce, nonceSz, |
2714 | 137k | perso, persoSz) == DRBG_SUCCESS && |
2715 | 136k | Hash512_df(drbg, drbg->C, sizeof(drbg->C), drbgInitC, drbg->V, |
2716 | 136k | sizeof(drbg->V), NULL, 0, |
2717 | 136k | NULL, 0) == DRBG_SUCCESS) { |
2718 | | |
2719 | 136k | *reseedCtr = 1; |
2720 | 136k | return DRBG_SUCCESS; |
2721 | 136k | } |
2722 | 606 | else { |
2723 | 606 | return DRBG_FAILURE; |
2724 | 606 | } |
2725 | 137k | } |
2726 | | |
2727 | | /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ |
2728 | | static WARN_UNUSED_RESULT int Hash512_DRBG_Instantiate( |
2729 | | DRBG_SHA512_internal* drbg, |
2730 | | wc_drbg_reseed_ctr_t *reseedCtr, |
2731 | | const byte* seed, word32 seedSz, |
2732 | | const byte* nonce, word32 nonceSz, |
2733 | | const byte* perso, word32 persoSz, |
2734 | | void* heap, int devId) |
2735 | 137k | { |
2736 | 137k | int ret = WC_NO_ERR_TRACE(DRBG_FAILURE); |
2737 | | |
2738 | 137k | XMEMSET(drbg, 0, sizeof(DRBG_SHA512_internal)); |
2739 | 137k | drbg->heap = heap; |
2740 | 137k | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
2741 | 137k | drbg->devId = devId; |
2742 | | #else |
2743 | | (void)devId; |
2744 | | #endif |
2745 | | |
2746 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
2747 | | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
2748 | | ret = wc_InitSha512_ex(&drbg->sha512, drbg->heap, drbg->devId); |
2749 | | #else |
2750 | | ret = wc_InitSha512(&drbg->sha512); |
2751 | | #endif |
2752 | | if (ret != 0) |
2753 | | return ret; |
2754 | | #endif |
2755 | | |
2756 | 137k | if (seed != NULL) |
2757 | 137k | ret = Hash512_DRBG_Init(drbg, reseedCtr, seed, seedSz, nonce, nonceSz, |
2758 | 137k | perso, persoSz); |
2759 | 137k | return ret; |
2760 | 137k | } |
2761 | | |
2762 | | /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ |
2763 | | static int Hash512_DRBG_Uninstantiate(DRBG_SHA512_internal* drbg) |
2764 | 137k | { |
2765 | 137k | word32 i; |
2766 | 137k | int compareSum = 0; |
2767 | 137k | byte* compareDrbg = (byte*)drbg; |
2768 | | |
2769 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
2770 | | wc_Sha512Free(&drbg->sha512); |
2771 | | #endif |
2772 | | |
2773 | 137k | ForceZero(drbg, sizeof(DRBG_SHA512_internal)); |
2774 | | |
2775 | 32.9M | for (i = 0; i < sizeof(DRBG_SHA512_internal); i++) { |
2776 | 32.7M | compareSum |= compareDrbg[i] ^ 0; |
2777 | 32.7M | } |
2778 | | |
2779 | 137k | return (compareSum == 0) ? DRBG_SUCCESS : DRBG_FAILURE; |
2780 | 137k | } |
2781 | | |
2782 | | #endif /* WOLFSSL_DRBG_SHA512 */ |
2783 | | |
2784 | | /* Uncredited stirring, per SP 800-90A 10.1.1.4 generate with additional_input |
2785 | | * (step 2: V += Hash(0x02 || V || additional_input)). The generate is |
2786 | | * zero-length: Hash_gen() and Hash512_gen() run one Hashgen iteration and |
2787 | | * discard the block when outSz is 0, and out is never dereferenced. The |
2788 | | * reseed counter is incremented as for any generate, and quarantine/stratum |
2789 | | * are untouched, so the no-claims doctrine holds as a theorem of the standard |
2790 | | * rather than a property of a custom transition. Refused with the |
2791 | | * wc_RNG_entropy_needs_recovery() verdict (NEEDS_RECOVERY_E) when the |
2792 | | * instance is quarantined, due for a credited reseed, or carries a stale |
2793 | | * entropy epoch, and with NOT_READY_E when the reseed interval trips within |
2794 | | * the call: a generate must not run past the reseed interval, and a stir is |
2795 | | * not the credited reseed that clears it. */ |
2796 | | |
2797 | | static WARN_UNUSED_RESULT int Hash_DRBG_StirGenerate(WC_RNG* rng, |
2798 | | const byte* add, |
2799 | | word32 addSz) |
2800 | 0 | { |
2801 | 0 | int ret; |
2802 | |
|
2803 | 0 | ret = wc_RNG_entropy_needs_recovery(rng); |
2804 | 0 | if (ret != 0) |
2805 | 0 | return ret; |
2806 | | |
2807 | | #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND) |
2808 | | /* As in Hash_DRBG_Reseed(): an RDRAND instantiation has no DRBG state, so |
2809 | | * the material is dropped and success returned. */ |
2810 | | if ((! wc_RNG_DRBG_Present(rng)) && IS_INTEL_RDRAND(intel_flags)) |
2811 | | return 0; |
2812 | | #endif |
2813 | | |
2814 | 0 | ret = WC_NO_ERR_TRACE(RNG_FAILURE_E); |
2815 | 0 | #ifndef NO_SHA256 |
2816 | 0 | if ((rng->drbgType == WC_DRBG_SHA256) && (rng->drbg != NULL)) { |
2817 | 0 | ret = Hash_DRBG_Generate((DRBG_internal *)rng->drbg, &rng->reseedCtr, NULL, 0, |
2818 | 0 | add, addSz); |
2819 | 0 | } |
2820 | 0 | #endif |
2821 | 0 | #ifdef WOLFSSL_DRBG_SHA512 |
2822 | 0 | if ((rng->drbgType == WC_DRBG_SHA512) && (rng->drbg512 != NULL)) { |
2823 | 0 | ret = Hash512_DRBG_Generate((DRBG_SHA512_internal *)rng->drbg512, |
2824 | 0 | &rng->reseedCtr, NULL, 0, add, addSz); |
2825 | 0 | } |
2826 | 0 | #endif |
2827 | | #ifdef WC_RNG_DEBUG_STATS |
2828 | | if (ret == 0) |
2829 | | ++rng->_stats_stirs; /* counts uncredited stir-generates. */ |
2830 | | #endif |
2831 | |
|
2832 | 0 | if (ret == WC_NO_ERR_TRACE(DRBG_NEED_RESEED)) |
2833 | 0 | return NOT_READY_E; |
2834 | 0 | else if (ret > 0) |
2835 | 0 | return RNG_FAILURE_E; |
2836 | 0 | else |
2837 | 0 | return ret; |
2838 | 0 | } |
2839 | | |
2840 | | static WARN_UNUSED_RESULT int wc_RNG_DRBG_Stir_Nonce_local(WC_RNG* rng, |
2841 | | const byte* seed, word32 seedSz, |
2842 | | const byte *nonce, word32 nonceSz) |
2843 | 0 | { |
2844 | 0 | if (rng == NULL || seed == NULL) |
2845 | 0 | return BAD_FUNC_ARG; |
2846 | 0 | if ((nonce == NULL) && (nonceSz != 0)) |
2847 | 0 | return BAD_FUNC_ARG; |
2848 | | |
2849 | 0 | if (rng->status != WC_DRBG_OK) |
2850 | 0 | return RNG_FAILURE_E; |
2851 | | |
2852 | 0 | { |
2853 | 0 | int lock_ret = rng_lock_required_check(rng); |
2854 | 0 | if (lock_ret != 0) |
2855 | 0 | return lock_ret; |
2856 | 0 | } |
2857 | | |
2858 | 0 | { |
2859 | 0 | int ret = Hash_DRBG_StirGenerate(rng, seed, seedSz); |
2860 | 0 | if ((ret == 0) && (nonce != NULL) && (nonceSz > 0)) { |
2861 | | /* Second chunk as its own specified generate: additional |
2862 | | * input is per-call, and chunking beats concatenation |
2863 | | * scratch. */ |
2864 | 0 | ret = Hash_DRBG_StirGenerate(rng, nonce, nonceSz); |
2865 | 0 | } |
2866 | 0 | return ret; |
2867 | 0 | } |
2868 | 0 | } |
2869 | | |
2870 | | int wc_RNG_DRBG_Stir_Nonce(WC_RNG* rng, const byte* seed, word32 seedSz, |
2871 | | const byte *nonce, word32 nonceSz) |
2872 | 0 | { |
2873 | 0 | int ret; |
2874 | |
|
2875 | 0 | if (rng == NULL) |
2876 | 0 | return BAD_FUNC_ARG; |
2877 | 0 | ret = RngAutoLockEnter(rng); |
2878 | 0 | if (ret != 0) |
2879 | 0 | return ret; |
2880 | 0 | ret = wc_RNG_DRBG_Stir_Nonce_local(rng, seed, seedSz, nonce, nonceSz); |
2881 | 0 | RngAutoLockExit(rng); |
2882 | 0 | return ret; |
2883 | 0 | } |
2884 | | |
2885 | | int wc_RNG_DRBG_Stir(WC_RNG* rng, const byte* seed, word32 seedSz) |
2886 | 0 | { |
2887 | 0 | return wc_RNG_DRBG_Stir_Nonce(rng, seed, seedSz, NULL, 0); |
2888 | 0 | } |
2889 | | |
2890 | | /* SP800-90B 4.4 health tests run over conditioned seed material, which makes |
2891 | | * them the developer-defined additional tests 4.3 Req 1c allows: 4.2 puts the |
2892 | | * noise source's own tests in that source, not here. A seed shorter than the |
2893 | | * 512 byte window is one window of its own length, with the cutoff for that |
2894 | | * length. */ |
2895 | | |
2896 | | /* SP800-90B 4.4.1 - Repetition Count Test |
2897 | | * Detects if the noise source becomes "stuck" producing repeated output. |
2898 | | * |
2899 | | * C = 1 + ceil(-log2(alpha) / H) |
2900 | | * For alpha = 2^-30 (false positive probability) and H = 1 (min entropy): |
2901 | | * C = 1 + ceil(30 / 1) = 31 |
2902 | | * |
2903 | | * H = 1 bit per byte is a deliberate floor, recorded in the Security Policy: |
2904 | | * the seed source is a build choice and the module is not told the assessed |
2905 | | * rate of the one in use, so it assumes the weakest. */ |
2906 | | #ifndef WC_RNG_SEED_RCT_CUTOFF |
2907 | 3.47M | #define WC_RNG_SEED_RCT_CUTOFF 31 |
2908 | | #endif |
2909 | | /* The run starts at 1, so a cutoff below 2 fails every seed. */ |
2910 | | #if WC_RNG_SEED_RCT_CUTOFF < 2 |
2911 | | #error WC_RNG_SEED_RCT_CUTOFF must be at least 2 |
2912 | | #endif |
2913 | | |
2914 | | /* SP800-90B 4.4.2 - Adaptive Proportion Test |
2915 | | * Monitors if a particular sample value appears too frequently within a |
2916 | | * window of samples, indicating loss of entropy. |
2917 | | * |
2918 | | * Window size W = 512 for non-binary alphabet (byte values 0-255) |
2919 | | * C = 1 + CRITBINOM(W, 2^(-H), 1-alpha) |
2920 | | * For alpha = 2^-30 and H = 1, W = 512: |
2921 | | * C = 1 + CRITBINOM(512, 0.5, 1-2^-30) = 325 |
2922 | | */ |
2923 | | #ifndef WC_RNG_SEED_APT_WINDOW |
2924 | 136k | #define WC_RNG_SEED_APT_WINDOW 512 |
2925 | | #endif |
2926 | | #if WC_RNG_SEED_APT_WINDOW < 1 |
2927 | | #error WC_RNG_SEED_APT_WINDOW must be at least 1 |
2928 | | #endif |
2929 | | #ifndef WC_RNG_SEED_APT_CUTOFF |
2930 | | /* No caller-supplied cutoff: take one per window size from the table. */ |
2931 | | #define WC_RNG_SEED_APT_CUTOFF_PER_WINDOW |
2932 | | /* The published W = 512 value, kept for readers and for tests. */ |
2933 | | #define WC_RNG_SEED_APT_CUTOFF 325 |
2934 | | #endif |
2935 | | /* Only the tables cap the window; a caller-supplied cutoff has no such |
2936 | | * limit, so this bound belongs to the table build alone. */ |
2937 | | #if defined(WC_RNG_SEED_APT_CUTOFF_PER_WINDOW) && (WC_RNG_SEED_APT_WINDOW > 512) |
2938 | | #error WC_RNG_SEED_APT_WINDOW must be 1 to 512 unless WC_RNG_SEED_APT_CUTOFF is set |
2939 | | #endif |
2940 | | /* A caller-supplied cutoff above the window can never be reached at any seed |
2941 | | * size, so it is refused here. A cutoff the window allows but a given seed |
2942 | | * does not is not a build-time property: the window is min(seedSz, WINDOW) and |
2943 | | * seedSz is the caller's, so that case is left to the runtime skip below. */ |
2944 | | #ifndef WC_RNG_SEED_APT_CUTOFF_PER_WINDOW |
2945 | | #if WC_RNG_SEED_APT_CUTOFF < 2 |
2946 | | #error WC_RNG_SEED_APT_CUTOFF must be at least 2 |
2947 | | #endif |
2948 | | #if WC_RNG_SEED_APT_CUTOFF > WC_RNG_SEED_APT_WINDOW |
2949 | | #error WC_RNG_SEED_APT_CUTOFF exceeds the window and can never fire |
2950 | | #endif |
2951 | | #endif |
2952 | | |
2953 | | #ifdef WC_RNG_SEED_APT_CUTOFF_PER_WINDOW |
2954 | | /* C for every window size, not only 512: a seed shorter than the window is one |
2955 | | * window of its own length, and 325 can never be reached in 132 or 196 bytes. |
2956 | | * 1 + CRITBINOM(W, 2^-H, 1 - alpha), H = 1, alpha = 2^-30, W = 1..512, held as |
2957 | | * the exact distance above W / 2 so a byte covers every window. */ |
2958 | | static const byte aptCutoffDelta[512] = { |
2959 | | 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, |
2960 | | 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 15, 16, 16, |
2961 | | 17, 17, 18, 17, 18, 18, 19, 18, 19, 19, 20, 19, 20, 20, 21, 20, |
2962 | | 21, 21, 22, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 23, 24, 24, |
2963 | | 25, 24, 25, 25, 25, 25, 26, 25, 26, 26, 26, 26, 27, 26, 27, 27, |
2964 | | 28, 27, 28, 28, 28, 28, 29, 28, 29, 29, 29, 29, 30, 29, 30, 29, |
2965 | | 30, 30, 30, 30, 31, 30, 31, 31, 31, 31, 32, 31, 32, 32, 32, 32, |
2966 | | 33, 32, 33, 33, 33, 33, 33, 33, 34, 33, 34, 34, 34, 34, 35, 34, |
2967 | | 35, 34, 35, 35, 35, 35, 36, 35, 36, 36, 36, 36, 36, 36, 37, 36, |
2968 | | 37, 37, 37, 37, 37, 37, 38, 37, 38, 38, 38, 38, 38, 38, 39, 38, |
2969 | | 39, 39, 39, 39, 39, 39, 40, 39, 40, 39, 40, 40, 40, 40, 41, 40, |
2970 | | 41, 40, 41, 41, 41, 41, 41, 41, 42, 41, 42, 42, 42, 42, 42, 42, |
2971 | | 43, 42, 43, 42, 43, 43, 43, 43, 43, 43, 44, 43, 44, 43, 44, 44, |
2972 | | 44, 44, 45, 44, 45, 44, 45, 45, 45, 45, 45, 45, 46, 45, 46, 45, |
2973 | | 46, 46, 46, 46, 46, 46, 47, 46, 47, 46, 47, 47, 47, 47, 47, 47, |
2974 | | 48, 47, 48, 47, 48, 48, 48, 48, 48, 48, 49, 48, 49, 48, 49, 49, |
2975 | | 49, 49, 49, 49, 49, 49, 50, 49, 50, 49, 50, 50, 50, 50, 50, 50, |
2976 | | 51, 50, 51, 50, 51, 51, 51, 51, 51, 51, 52, 51, 52, 51, 52, 51, |
2977 | | 52, 52, 52, 52, 52, 52, 53, 52, 53, 52, 53, 53, 53, 53, 53, 53, |
2978 | | 53, 53, 54, 53, 54, 53, 54, 54, 54, 54, 54, 54, 54, 54, 55, 54, |
2979 | | 55, 54, 55, 55, 55, 55, 55, 55, 56, 55, 56, 55, 56, 55, 56, 56, |
2980 | | 56, 56, 56, 56, 57, 56, 57, 56, 57, 56, 57, 57, 57, 57, 57, 57, |
2981 | | 57, 57, 58, 57, 58, 57, 58, 58, 58, 58, 58, 58, 58, 58, 59, 58, |
2982 | | 59, 58, 59, 58, 59, 59, 59, 59, 59, 59, 60, 59, 60, 59, 60, 59, |
2983 | | 60, 60, 60, 60, 60, 60, 60, 60, 61, 60, 61, 60, 61, 60, 61, 61, |
2984 | | 61, 61, 61, 61, 62, 61, 62, 61, 62, 61, 62, 62, 62, 62, 62, 62, |
2985 | | 62, 62, 63, 62, 63, 62, 63, 62, 63, 63, 63, 63, 63, 63, 63, 63, |
2986 | | 64, 63, 64, 63, 64, 63, 64, 64, 64, 64, 64, 64, 64, 64, 65, 64, |
2987 | | 65, 64, 65, 64, 65, 65, 65, 65, 65, 65, 65, 65, 66, 65, 66, 65, |
2988 | | 66, 65, 66, 66, 66, 66, 66, 66, 66, 66, 67, 66, 67, 66, 67, 66, |
2989 | | 67, 67, 67, 67, 67, 67, 67, 67, 68, 67, 68, 67, 68, 67, 68, 68, |
2990 | | 68, 68, 68, 68, 68, 68, 68, 68, 69, 68, 69, 68, 69, 68, 69, 69 |
2991 | | }; |
2992 | | #define WC_RNG_SEED_APT_CUTOFF_FOR(w) \ |
2993 | 68.1k | (((word32)(w) / 2) + (word32)aptCutoffDelta[(w) - 1]) |
2994 | | |
2995 | | /* Cutoff for the all-values test below, at alpha/256 so that scanning the |
2996 | | * whole alphabet keeps the same 2^-30 budget per window. Same W / 2 delta |
2997 | | * form as the table above. |
2998 | | * 1 + CRITBINOM(W, 2^-H, 1 - alpha/256), H = 1, alpha = 2^-30, W = 1..512. */ |
2999 | | static const byte aptAllCutoffDelta[512] = { |
3000 | | 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, |
3001 | | 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, |
3002 | | 18, 18, 19, 19, 20, 19, 20, 20, 21, 21, 22, 21, 22, 22, 23, 23, |
3003 | | 23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, |
3004 | | 27, 27, 28, 28, 28, 28, 29, 28, 29, 29, 30, 29, 30, 30, 30, 30, |
3005 | | 31, 30, 31, 31, 32, 31, 32, 32, 32, 32, 33, 32, 33, 33, 33, 33, |
3006 | | 34, 34, 34, 34, 35, 34, 35, 35, 35, 35, 36, 35, 36, 36, 36, 36, |
3007 | | 37, 36, 37, 37, 37, 37, 38, 37, 38, 38, 38, 38, 39, 38, 39, 39, |
3008 | | 39, 39, 40, 39, 40, 39, 40, 40, 40, 40, 41, 40, 41, 41, 41, 41, |
3009 | | 42, 41, 42, 42, 42, 42, 42, 42, 43, 42, 43, 43, 43, 43, 44, 43, |
3010 | | 44, 44, 44, 44, 44, 44, 45, 44, 45, 45, 45, 45, 46, 45, 46, 45, |
3011 | | 46, 46, 46, 46, 47, 46, 47, 46, 47, 47, 47, 47, 48, 47, 48, 47, |
3012 | | 48, 48, 48, 48, 49, 48, 49, 48, 49, 49, 49, 49, 50, 49, 50, 49, |
3013 | | 50, 50, 50, 50, 51, 50, 51, 50, 51, 51, 51, 51, 52, 51, 52, 51, |
3014 | | 52, 52, 52, 52, 52, 52, 53, 52, 53, 53, 53, 53, 53, 53, 54, 53, |
3015 | | 54, 53, 54, 54, 54, 54, 54, 54, 55, 54, 55, 55, 55, 55, 55, 55, |
3016 | | 56, 55, 56, 55, 56, 56, 56, 56, 56, 56, 57, 56, 57, 56, 57, 57, |
3017 | | 57, 57, 58, 57, 58, 57, 58, 58, 58, 58, 58, 58, 59, 58, 59, 58, |
3018 | | 59, 59, 59, 59, 59, 59, 60, 59, 60, 59, 60, 60, 60, 60, 60, 60, |
3019 | | 61, 60, 61, 60, 61, 61, 61, 61, 61, 61, 62, 61, 62, 61, 62, 62, |
3020 | | 62, 62, 62, 62, 63, 62, 63, 62, 63, 63, 63, 63, 63, 63, 63, 63, |
3021 | | 64, 63, 64, 63, 64, 64, 64, 64, 64, 64, 65, 64, 65, 64, 65, 65, |
3022 | | 65, 65, 65, 65, 66, 65, 66, 65, 66, 65, 66, 66, 66, 66, 66, 66, |
3023 | | 67, 66, 67, 66, 67, 67, 67, 67, 67, 67, 68, 67, 68, 67, 68, 67, |
3024 | | 68, 68, 68, 68, 68, 68, 69, 68, 69, 68, 69, 69, 69, 69, 69, 69, |
3025 | | 69, 69, 70, 69, 70, 69, 70, 70, 70, 70, 70, 70, 70, 70, 71, 70, |
3026 | | 71, 70, 71, 71, 71, 71, 71, 71, 71, 71, 72, 71, 72, 71, 72, 72, |
3027 | | 72, 72, 72, 72, 72, 72, 73, 72, 73, 72, 73, 73, 73, 73, 73, 73, |
3028 | | 73, 73, 74, 73, 74, 73, 74, 74, 74, 74, 74, 74, 74, 74, 75, 74, |
3029 | | 75, 74, 75, 75, 75, 75, 75, 75, 75, 75, 76, 75, 76, 75, 76, 75, |
3030 | | 76, 76, 76, 76, 76, 76, 77, 76, 77, 76, 77, 76, 77, 77, 77, 77, |
3031 | | 77, 77, 77, 77, 78, 77, 78, 77, 78, 77, 78, 78, 78, 78, 78, 78 |
3032 | | }; |
3033 | | #define WC_RNG_SEED_APT_ALL_CUTOFF_FOR(w) \ |
3034 | 68.1k | (((word32)(w) / 2) + (word32)aptAllCutoffDelta[(w) - 1]) |
3035 | | #else |
3036 | | /* A caller-supplied cutoff is a threshold, so it serves both tests; the |
3037 | | * all-values scan still runs only where its majority precondition holds. */ |
3038 | | #define WC_RNG_SEED_APT_CUTOFF_FOR(w) ((word32)WC_RNG_SEED_APT_CUTOFF) |
3039 | | #define WC_RNG_SEED_APT_ALL_CUTOFF_FOR(w) ((word32)WC_RNG_SEED_APT_CUTOFF) |
3040 | | #endif |
3041 | | |
3042 | | int wc_RNG_TestSeed(const byte* seed, word32 seedSz) |
3043 | 68.1k | { |
3044 | 68.1k | int ret = 0; |
3045 | | |
3046 | 68.1k | word32 i; |
3047 | 68.1k | int rctFailed = 0; |
3048 | 68.1k | int aptFailed = 0; |
3049 | | |
3050 | 68.1k | if (seed == NULL || seedSz < SEED_BLOCK_SZ) { |
3051 | 0 | return BAD_FUNC_ARG; |
3052 | 0 | } |
3053 | | |
3054 | | /* SP800-90B 4.4.1 - Repetition Count Test (RCT) |
3055 | | * Check for consecutive identical bytes that would indicate a stuck |
3056 | | * entropy source. Fail if we see WC_RNG_SEED_RCT_CUTOFF or more |
3057 | | * consecutive identical values. |
3058 | | * |
3059 | | * Constant-time implementation: always process full seed, accumulate |
3060 | | * failure status without early exit to prevent timing side-channels. |
3061 | | */ |
3062 | 68.1k | { |
3063 | 68.1k | int repCount = 1; |
3064 | 68.1k | byte prevByte = seed[0]; |
3065 | | |
3066 | 3.54M | for (i = 1; i < seedSz; i++) { |
3067 | | /* Constant-time: always evaluate both branches effects */ |
3068 | 3.47M | int match = (seed[i] == prevByte); |
3069 | | /* If match, increment count, if not, reset to 1 */ |
3070 | 3.47M | repCount = (match * (repCount + 1)) + (!match * 1); |
3071 | | /* Update prevByte only when not matching (new value) */ |
3072 | 3.47M | prevByte = (byte) ((match * prevByte) + (!match * seed[i])); |
3073 | | /* Accumulate failure flag - once set, stays set */ |
3074 | 3.47M | rctFailed |= (repCount >= WC_RNG_SEED_RCT_CUTOFF); |
3075 | 3.47M | } |
3076 | 68.1k | ForceZero(&prevByte, sizeof(prevByte)); |
3077 | 68.1k | } |
3078 | | |
3079 | | /* SP800-90B 4.4.2 Adaptive Proportion Test: the first byte of each window |
3080 | | * is the reference value, and a window fails when matches reach the cutoff |
3081 | | * for that window size. Windows do not overlap except the last, which |
3082 | | * slides back to full length and so re-judges the bytes it covers; that |
3083 | | * only adds windows, so it can raise the false alarm rate but never mask a |
3084 | | * failure. A frequent value that is not the reference is left to the |
3085 | | * all-values test below. */ |
3086 | 68.1k | { |
3087 | 68.1k | word32 start; |
3088 | 68.1k | word32 window = min(seedSz, (word32)WC_RNG_SEED_APT_WINDOW); |
3089 | 68.1k | word32 cutoff = WC_RNG_SEED_APT_CUTOFF_FOR(window); |
3090 | | |
3091 | | /* A cutoff above the window can never be reached (IG D.K Res 16); that |
3092 | | * is every window under 30 bytes at alpha 2^-30, and such a seed gets |
3093 | | * no APT and rests on the RCT above. */ |
3094 | 68.1k | if (cutoff <= window) { |
3095 | | /* Constant time: every window is scanned in full, no early exit. */ |
3096 | 136k | for (start = 0; start < seedSz; start += window) { |
3097 | 68.1k | word32 matches = 1; |
3098 | 68.1k | byte refByte; |
3099 | | |
3100 | | /* A trailing piece shorter than the window slides back to a |
3101 | | * full window instead of forming a short one. */ |
3102 | 68.1k | if ((seedSz - start) < window) |
3103 | 0 | start = seedSz - window; |
3104 | | |
3105 | 68.1k | refByte = seed[start]; |
3106 | 3.54M | for (i = 1; i < window; i++) { |
3107 | 3.47M | matches += (word32)(seed[start + i] == refByte); |
3108 | 3.47M | } |
3109 | | |
3110 | 68.1k | aptFailed |= (matches >= cutoff); |
3111 | 68.1k | ForceZero(&refByte, sizeof(refByte)); |
3112 | 68.1k | } |
3113 | 68.1k | } |
3114 | 68.1k | } |
3115 | | |
3116 | | /* Additional developer-defined test (SP800-90B 4.3 Req 1c): 4.4.2 watches |
3117 | | * only the window's first byte, this watches whichever value is the |
3118 | | * window's majority, wherever it falls. Its cutoff uses alpha/256 for the |
3119 | | * alphabet, so it catches a near-majority (334 of 512) and not bias in |
3120 | | * general, and it needs a 38 byte window before it can fire at all. */ |
3121 | 68.1k | { |
3122 | 68.1k | word32 start; |
3123 | 68.1k | word32 window = min(seedSz, (word32)WC_RNG_SEED_APT_WINDOW); |
3124 | 68.1k | word32 cutoff = WC_RNG_SEED_APT_ALL_CUTOFF_FOR(window); |
3125 | | |
3126 | 68.1k | if ((cutoff <= window) && (cutoff > (window / 2))) { |
3127 | 136k | for (start = 0; start < seedSz; start += window) { |
3128 | 68.1k | byte cand = 0; |
3129 | 68.1k | word32 votes = 0; |
3130 | 68.1k | word32 count = 0; |
3131 | | |
3132 | 68.1k | if ((seedSz - start) < window) |
3133 | 0 | start = seedSz - window; |
3134 | | |
3135 | | /* A count above half the window makes that value the window's |
3136 | | * majority, which this vote finds without a histogram. */ |
3137 | 3.61M | for (i = 0; i < window; i++) { |
3138 | 3.54M | word32 take = (word32)(votes == 0); |
3139 | 3.54M | word32 same; |
3140 | | |
3141 | 3.54M | cand = (byte)((take * seed[start + i]) + |
3142 | 3.54M | ((1 - take) * cand)); |
3143 | 3.54M | same = (word32)(seed[start + i] == cand); |
3144 | 3.54M | votes = (same * (votes + 1)) + ((1 - same) * (votes - 1)); |
3145 | 3.54M | } |
3146 | | |
3147 | 3.61M | for (i = 0; i < window; i++) { |
3148 | 3.54M | count += (word32)(seed[start + i] == cand); |
3149 | 3.54M | } |
3150 | | |
3151 | 68.1k | aptFailed |= (count >= cutoff); |
3152 | 68.1k | ForceZero(&cand, sizeof(cand)); |
3153 | 68.1k | } |
3154 | 68.1k | } |
3155 | 68.1k | } |
3156 | | |
3157 | | /* Set return code based on accumulated failure flags */ |
3158 | 68.1k | if (rctFailed) { |
3159 | 0 | ret = ENTROPY_RT_E; |
3160 | 0 | } |
3161 | 68.1k | else if (aptFailed) { |
3162 | 0 | ret = ENTROPY_APT_E; |
3163 | 0 | } |
3164 | | |
3165 | 68.1k | return ret; |
3166 | 68.1k | } |
3167 | | #else /* !HAVE_HASHDRBG */ |
3168 | | /* no Hash DRBG, so no lock for the backends to hold */ |
3169 | | #define RngAutoLockEnter(rng) 0 |
3170 | | #define RngAutoLockExit(rng) WC_DO_NOTHING |
3171 | | #endif /* HAVE_HASHDRBG */ |
3172 | | /* End NIST DRBG Code */ |
3173 | | |
3174 | | /* A seed-source verdict at instantiation: the transient codes survive |
3175 | | * verbatim, so a caller that can wait (rng_bank.c's init loop, keyed on the |
3176 | | * same WC_RNG_ERR_IS_TRANSIENT() set) retries rather than giving up on an |
3177 | | * instance the source will serve a moment later; everything else is the |
3178 | | * DRBG's failure, reported as RNG_FAILURE_E. Gated as the caller is: |
3179 | | * DRBG_FAILURE is a Hash_DRBG internal and does not exist without it. */ |
3180 | | #if defined(HAVE_HASHDRBG) && !defined(CUSTOM_RAND_GENERATE_BLOCK) |
3181 | | static int ReseedSourceFailure(int ret) |
3182 | 0 | { |
3183 | 0 | if (WC_RNG_ERR_IS_TRANSIENT(ret)) |
3184 | 0 | return ret; |
3185 | 0 | return DRBG_FAILURE; |
3186 | 0 | } |
3187 | | #endif |
3188 | | |
3189 | | #if defined(WC_RNG_HAVE_LOCK) || defined(WC_RNG_HAVE_POOL) || \ |
3190 | | defined(WC_RNG_HAVE_NEXT_SEED) |
3191 | | |
3192 | | /* The WC_RNG members excluded from RngInitWipe()'s zeroization: the atomic |
3193 | | * words, which can have lease-free concurrent observers (pool collectors, |
3194 | | * blind stir depositors, aperture accessors, lock contenders) and so are |
3195 | | * never XMEMSET(). Each is instead atomically (re)initialized: the |
3196 | | * fixed-initial-value words by RngInitWipe() itself, and the |
3197 | | * _INIT_-flag-contingent words (.lock, .RBGC_refcount) by _InitRng() |
3198 | | * immediately after the wipe. No ordering assumption is made on the |
3199 | | * offsets -- the wipe loop selects each next span by scanning -- and the |
3200 | | * spans need only be non-overlapping. */ |
3201 | | static const struct { |
3202 | | size_t offset; |
3203 | | size_t size; |
3204 | | } wc_rng_wipe_skips[] = { |
3205 | | #ifdef WC_RNG_HAVE_LOCK |
3206 | | { WC_OFFSETOF(WC_RNG, lock), |
3207 | | WC_SIZEOFMEMBER(WC_RNG, lock) }, |
3208 | | #ifdef WC_RNG_HAVE_RBGC |
3209 | | { WC_OFFSETOF(WC_RNG, RBGC_refcount), |
3210 | | WC_SIZEOFMEMBER(WC_RNG, RBGC_refcount) }, |
3211 | | #endif |
3212 | | #endif |
3213 | | #ifdef WC_RNG_HAVE_POOL |
3214 | | { WC_OFFSETOF(WC_RNG, poolHead), |
3215 | | WC_SIZEOFMEMBER(WC_RNG, poolHead) }, |
3216 | | { WC_OFFSETOF(WC_RNG, poolTail), |
3217 | | WC_SIZEOFMEMBER(WC_RNG, poolTail) }, |
3218 | | #endif |
3219 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
3220 | | { WC_OFFSETOF(WC_RNG, nextStirLen), |
3221 | | WC_SIZEOFMEMBER(WC_RNG, nextStirLen) }, |
3222 | | #ifdef HAVE_HASHDRBG |
3223 | | { WC_OFFSETOF(WC_RNG, nextSeedLen), |
3224 | | WC_SIZEOFMEMBER(WC_RNG, nextSeedLen) }, |
3225 | | #endif |
3226 | | #endif |
3227 | | }; |
3228 | | |
3229 | | /* _InitRng()'s zeroization of the target object: wipe everything except the |
3230 | | * atomic words in wc_rng_wipe_skips[], then atomically store the |
3231 | | * fixed-initial-value words. Stores, not wolfSSL_Atomic_*_Init(): the |
3232 | | * excluded words are excluded precisely because lease-free observers can |
3233 | | * race the constructor, and an atomic store is observer-safe where an |
3234 | | * atomic init is not. In particular the pool aperture word never carries a |
3235 | | * ring-bearing value across the transition: a reinstantiation arrives with |
3236 | | * it TORNDOWN, which refuses rings throughout the wipe, until the UNALLOC |
3237 | | * store below reopens allocation. (UNALLOC is the all-zeros word, so a |
3238 | | * memset would in fact land on the right value -- the exclusion stands on |
3239 | | * observer atomicity, not on the value.) |
3240 | | * The flag-contingent words (.lock, .RBGC_refcount) are the caller's to |
3241 | | * initialize -- or, under the _PRESERVE_ flags, to leave exactly as |
3242 | | * found. */ |
3243 | | static void RngInitWipe(WC_RNG* rng) |
3244 | | { |
3245 | | size_t cursor = 0; |
3246 | | |
3247 | | /* mark the apertures unusable unless+until initialization succeeds. */ |
3248 | | #ifdef WC_RNG_HAVE_POOL |
3249 | | WOLFSSL_ATOMIC_STORE(rng->poolHead, WC_RNG_POOL_STATE_TORNDOWN); |
3250 | | WOLFSSL_ATOMIC_STORE(rng->poolTail, WC_RNG_POOL_PACK(0, 0)); |
3251 | | #endif |
3252 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
3253 | | WOLFSSL_ATOMIC_STORE(rng->nextStirLen, WC_DRBG_NEXT_SEED_TORNDOWN); |
3254 | | #ifdef HAVE_HASHDRBG |
3255 | | WOLFSSL_ATOMIC_STORE(rng->nextSeedLen, WC_DRBG_NEXT_SEED_TORNDOWN); |
3256 | | #endif |
3257 | | #endif |
3258 | | |
3259 | | for (;;) { |
3260 | | size_t next = sizeof(*rng); |
3261 | | int idx = -1; |
3262 | | int i; |
3263 | | for (i = 0; |
3264 | | i < (int)(sizeof(wc_rng_wipe_skips) / |
3265 | | sizeof(wc_rng_wipe_skips[0])); |
3266 | | i++) |
3267 | | { |
3268 | | if ((wc_rng_wipe_skips[i].offset >= cursor) && |
3269 | | (wc_rng_wipe_skips[i].offset < next)) |
3270 | | { |
3271 | | next = wc_rng_wipe_skips[i].offset; |
3272 | | idx = i; |
3273 | | } |
3274 | | } |
3275 | | if (next > cursor) |
3276 | | XMEMSET((byte *)rng + cursor, 0, next - cursor); |
3277 | | if (idx < 0) |
3278 | | break; |
3279 | | cursor = wc_rng_wipe_skips[idx].offset + wc_rng_wipe_skips[idx].size; |
3280 | | } |
3281 | | |
3282 | | } |
3283 | | |
3284 | | #else /* no excluded members: the degenerate whole-object wipe */ |
3285 | | |
3286 | 63.4k | #define RngInitWipe(rng) XMEMSET((rng), 0, sizeof(*(rng))) |
3287 | | |
3288 | | #endif |
3289 | | |
3290 | | /* Semantics of "flags": |
3291 | | * |
3292 | | * Security attributes are fixed at instantiation and caller-declared -- the |
3293 | | * constructor never reads the target object. _LOCK_REQUIRED sets the sticky |
3294 | | * WC_RNG_LOCK_REQUIRED latch bit at birth, so there is no reachable state in |
3295 | | * which the instance serves without its lock policy. _LOCK_INITIALLY sets |
3296 | | * WC_RNG_LOCK_HELD at birth: the caller is the lease holder from the first |
3297 | | * instruction -- the flag for constructing into a held lease (a lease-holding |
3298 | | * reinitialization keeps the instance invariantly locked across the reinit), to |
3299 | | * be released by wc_RNG_lock_put() as usual. _USE_FULL_MUTEX layers a blocking |
3300 | | * wolfSSL_Mutex outermost around wc_RNG_lock_get() and wc_RNG_lock_put*() -- |
3301 | | * for user-mode sharing of one instance among threads, where spinning on the |
3302 | | * CAS would be wrong; contending getters sleep in wc_LockMutex(). The inner |
3303 | | * latch (and every other wc_RNG_lock_*() operation) is unchanged. |
3304 | | * NOT_COMPILED_IN unless WC_RNG_HAVE_LOCK_FULL_MUTEX; composes with |
3305 | | * _LOCK_INITIALLY (born held at both layers). wc_FreeRng() releases (if the |
3306 | | * latch is held) and frees the mutex. |
3307 | | */ |
3308 | | static WARN_UNUSED_RESULT int _InitRng(WC_RNG* rng, |
3309 | | const byte* nonce, word32 nonceSz, |
3310 | | const byte *perso, word32 persoSz, |
3311 | | const byte* userSeed, word32 userSeedSz, |
3312 | | void* heap, int devId, WC_RNG* seedRng, word32 flags) |
3313 | 63.4k | { |
3314 | 63.4k | int ret = 0; |
3315 | 63.4k | #if defined(HAVE_HASHDRBG) && !defined(CUSTOM_RAND_GENERATE_BLOCK) |
3316 | | #if !defined(HAVE_FIPS) && defined(WOLFSSL_RNG_USE_FULL_SEED) |
3317 | | word32 seedSz = SEED_SZ; |
3318 | | #else |
3319 | 63.4k | word32 seedSz = SEED_SZ + SEED_BLOCK_SZ; |
3320 | 63.4k | #endif |
3321 | 63.4k | WC_DECLARE_VAR(seed, byte, MAX_SEED_SZ, rng->heap); |
3322 | 63.4k | int drbg_instantiated = 0; |
3323 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
3324 | | int drbg_scratch_instantiated = 0; |
3325 | | #endif |
3326 | 63.4k | #endif |
3327 | | |
3328 | | /* seed-related parameters are consumed only in the seed-acquisition arm; |
3329 | | * cast for configurations that compile that arm out: */ |
3330 | 63.4k | (void)seedRng; |
3331 | | |
3332 | 63.4k | if (rng == NULL) |
3333 | 0 | return BAD_FUNC_ARG; |
3334 | 63.4k | if (userSeed == NULL && userSeedSz != 0) |
3335 | 0 | return BAD_FUNC_ARG; |
3336 | 63.4k | if (nonce == NULL && nonceSz != 0) |
3337 | 0 | return BAD_FUNC_ARG; |
3338 | 63.4k | if (perso == NULL && persoSz != 0) |
3339 | 0 | return BAD_FUNC_ARG; |
3340 | 63.4k | if ((userSeedSz > 0) && (seedRng != NULL)) |
3341 | 0 | return BAD_FUNC_ARG; |
3342 | | |
3343 | 63.4k | if ((flags & (WC_RNG_INIT_FLAG_DRBG_SHA256 | |
3344 | 63.4k | WC_RNG_INIT_FLAG_DRBG_SHA512)) == |
3345 | 63.4k | (WC_RNG_INIT_FLAG_DRBG_SHA256 | WC_RNG_INIT_FLAG_DRBG_SHA512)) |
3346 | 0 | { |
3347 | 0 | return BAD_FUNC_ARG; |
3348 | 0 | } |
3349 | | #ifdef NO_SHA256 |
3350 | | if (flags & WC_RNG_INIT_FLAG_DRBG_SHA256) |
3351 | | return NOT_COMPILED_IN; |
3352 | | #endif |
3353 | | #ifndef WOLFSSL_DRBG_SHA512 |
3354 | | if (flags & WC_RNG_INIT_FLAG_DRBG_SHA512) |
3355 | | return NOT_COMPILED_IN; |
3356 | | #endif |
3357 | | |
3358 | 63.4k | #ifdef HAVE_HASHDRBG |
3359 | 63.4k | if (! (flags & (WC_RNG_INIT_FLAG_DRBG_SHA256 | |
3360 | 63.4k | WC_RNG_INIT_FLAG_DRBG_SHA512))) |
3361 | 63.4k | { |
3362 | 63.4k | word32 flavor_flag; |
3363 | 63.4k | ret = getDrbgFlavorFlag(&flavor_flag); |
3364 | 63.4k | if (ret < 0) |
3365 | 0 | return ret; |
3366 | 63.4k | flags |= flavor_flag; |
3367 | 63.4k | } |
3368 | | #else |
3369 | | if (flags & (WC_RNG_INIT_FLAG_DRBG_SHA256 | |
3370 | | WC_RNG_INIT_FLAG_DRBG_SHA512)) |
3371 | | { |
3372 | | return NOT_COMPILED_IN; |
3373 | | } |
3374 | | #endif |
3375 | | |
3376 | | #ifdef WC_RNG_HAVE_RBGC |
3377 | | #ifdef WC_RNG_HAVE_GLOBAL_FALLBACK_RNG |
3378 | | /* The global fallback RBGC seed source is forbidden as a parent, otherwise |
3379 | | * the wc_RNG_global_fallback_free() in wolfCrypt_Cleanup() might fail. No |
3380 | | * such limitation applies to its explicit use as a root in |
3381 | | * wc_RNG_DRBG_ReseedRBGC() of course (that would rather defeat the |
3382 | | * point). */ |
3383 | | if (seedRng == &global_fallback_rng) |
3384 | | return BAD_FUNC_ARG; |
3385 | | #endif |
3386 | | |
3387 | | #ifdef HAVE_FIPS |
3388 | | /* For FIPS, arrange to persist RBGC lineage, which requires locking on the |
3389 | | * parent. FIPS also forces on WC_RNG_RBGC_STRATUM_IMMUTABLE, so this is a |
3390 | | * coherent picture -- persisted parentage, with immutable strata. */ |
3391 | | if (seedRng != NULL) { |
3392 | | #ifndef WC_RNG_HAVE_LOCK |
3393 | | return NOT_COMPILED_IN; |
3394 | | #else |
3395 | | if (! (WOLFSSL_ATOMIC_LOAD(seedRng->lock) & WC_RNG_LOCK_REQUIRED)) |
3396 | | return WRONG_TYPE_OBJECT_E; |
3397 | | if (seedRng->flags & WC_RNG_FLAG_NO_RBGC_PARENT) |
3398 | | return WRONG_TYPE_OBJECT_E; |
3399 | | #endif |
3400 | | } |
3401 | | #endif |
3402 | | |
3403 | | if ((flags & WC_RNG_INIT_FLAG_NO_PRIMARY_SEED) && |
3404 | | (seedRng == NULL) && (userSeedSz == 0)) |
3405 | | { |
3406 | | return MISSING_RNG_E; |
3407 | | } |
3408 | | #else |
3409 | 63.4k | if (seedRng != NULL) |
3410 | 0 | return NOT_COMPILED_IN; |
3411 | 63.4k | if (flags & WC_RNG_INIT_FLAG_NO_PRIMARY_SEED) |
3412 | 0 | return NOT_COMPILED_IN; |
3413 | 63.4k | #endif |
3414 | | |
3415 | 63.4k | if ((flags & WC_RNG_INIT_FLAG_TEST_USER_SEED) && (userSeedSz == 0)) |
3416 | 0 | return BAD_FUNC_ARG; |
3417 | | |
3418 | 63.4k | #ifdef HAVE_HASHDRBG |
3419 | | /* Backstop only: the strength floors on user seed material are the public |
3420 | | * entry points' (UserSeedSzFloor()), so that the library-internal |
3421 | | * wc_InitRngFixedSeed() is bound by nothing but its own guard. Under |
3422 | | * WC_RNG_INIT_FLAG_TEST_USER_SEED the first SEED_BLOCK_SZ bytes are the |
3423 | | * health-test block, not DRBG input, so a seed of one block or less would |
3424 | | * instantiate on nothing. */ |
3425 | 63.4k | if ((userSeedSz > 0) && (userSeedSz <= SEED_BLOCK_SZ)) |
3426 | 0 | return BAD_LENGTH_E; |
3427 | | #else |
3428 | | (void)userSeed; |
3429 | | (void)userSeedSz; |
3430 | | #endif |
3431 | | |
3432 | 63.4k | if ((flags & WC_RNG_INIT_FLAG_USE_AUTO_LOCK) && |
3433 | 0 | (flags & (WC_RNG_INIT_FLAG_NO_AUTO_LOCK | |
3434 | 0 | WC_RNG_INIT_FLAG_LOCK_REQUIRED | |
3435 | 0 | WC_RNG_INIT_FLAG_USE_FULL_MUTEX))) |
3436 | 0 | { |
3437 | 0 | return BAD_FUNC_ARG; |
3438 | 0 | } |
3439 | 63.4k | #ifndef WC_RNG_HAVE_NEXT_SEED |
3440 | 63.4k | if (flags & WC_RNG_INIT_FLAG_UPGRADE_FROM_NEXT_SEED) |
3441 | 0 | return NOT_COMPILED_IN; |
3442 | 63.4k | #endif |
3443 | 63.4k | #ifndef WC_RNG_HAVE_LOCK |
3444 | 63.4k | if (flags & (WC_RNG_INIT_FLAG_LOCK_INITIALLY | |
3445 | 63.4k | WC_RNG_INIT_FLAG_LOCK_REQUIRED | |
3446 | 63.4k | WC_RNG_INIT_FLAG_PRESERVE_LOCK)) |
3447 | 0 | { |
3448 | 0 | return NOT_COMPILED_IN; |
3449 | 0 | } |
3450 | 63.4k | #endif |
3451 | 63.4k | #ifndef WC_RNG_HAVE_LOCK_FULL_MUTEX |
3452 | 63.4k | if (flags & WC_RNG_INIT_FLAG_USE_FULL_MUTEX) |
3453 | 0 | return NOT_COMPILED_IN; |
3454 | 63.4k | #endif |
3455 | | #ifndef WC_RNG_HAVE_AUTO_LOCK |
3456 | | /* Refuse rather than return an instance the caller believes is locked. |
3457 | | * Turning it off where there is none to turn off stays a no-op. */ |
3458 | | if (flags & WC_RNG_INIT_FLAG_USE_AUTO_LOCK) |
3459 | | return NOT_COMPILED_IN; |
3460 | | #endif |
3461 | | |
3462 | | #ifdef WC_RNG_HAVE_RBGC |
3463 | | if (seedRng != NULL) { |
3464 | | if (seedRng->RBGCStratum >= WC_MAX_SINT_OF(int)) |
3465 | | return SEQ_OVERFLOW_E; |
3466 | | else if (seedRng->RBGCStratum == WC_RNG_RBGC_USER_SEED_STRATUM - 1) |
3467 | | return SEQ_OVERFLOW_E; |
3468 | | } |
3469 | | #endif |
3470 | | |
3471 | | #ifdef WC_RNG_HAVE_LOCK |
3472 | | if (flags & WC_RNG_INIT_FLAG_PRESERVE_LOCK) { |
3473 | | WC_ATOMIC_UINT_ARG cur_lock = WOLFSSL_ATOMIC_LOAD(rng->lock); |
3474 | | if (flags & WC_RNG_INIT_FLAG_LOCK_INITIALLY) |
3475 | | return BAD_FUNC_ARG; |
3476 | | /* The mutex would be born unlocked under a preserved _HELD, so the |
3477 | | * holder's release would unlock a mutex it never took. */ |
3478 | | if (flags & WC_RNG_INIT_FLAG_USE_FULL_MUTEX) |
3479 | | return BAD_FUNC_ARG; |
3480 | | if ((flags & WC_RNG_INIT_FLAG_LOCK_REQUIRED) && |
3481 | | (! (cur_lock & WC_RNG_LOCK_HELD))) |
3482 | | { |
3483 | | return OBJECT_NOT_LOCKED_E; |
3484 | | } |
3485 | | /* when preserving the lock across a reinit, the requirement bits need |
3486 | | * to be self-consistent: */ |
3487 | | if ((cur_lock & WC_RNG_LOCK_REQUIRED) && |
3488 | | (! (flags & WC_RNG_INIT_FLAG_LOCK_REQUIRED))) |
3489 | | { |
3490 | | return UNEXPECTED_STATE_E; |
3491 | | } |
3492 | | if ((flags & WC_RNG_INIT_FLAG_LOCK_REQUIRED) && |
3493 | | (! (cur_lock & WC_RNG_LOCK_REQUIRED))) |
3494 | | { |
3495 | | return UNEXPECTED_STATE_E; |
3496 | | } |
3497 | | |
3498 | | /* state invalidation may be inherited from the previous lock, but needs |
3499 | | * to be cleared unconditionally for the new RNG. Clear rng->status |
3500 | | * before clearing the lock bits, for seamless unusability of the RNG |
3501 | | * unless+until successfully initialized. */ |
3502 | | if (cur_lock & (WC_RNG_LOCK_ENTROPY_INVALIDATED | |
3503 | | WC_RNG_LOCK_ENTROPY_RECOVERING | |
3504 | | WC_RNG_LOCK_ORPHANED)) |
3505 | | { |
3506 | | int cas_ret; |
3507 | | rng->status = WC_DRBG_NOT_INIT; |
3508 | | /* _ORPHANED clears here too: this reinit under the preserved |
3509 | | * hold is the adoption of an orphaned lease. */ |
3510 | | WC_CAS_WITH_RETRY_BEGIN(&rng->lock, cur_lock, cas_ret) { |
3511 | | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
3512 | | wolfSSL_Atomic_Uint_CompareExchange, &rng->lock, cur_lock, |
3513 | | cur_lock & ~(WC_RNG_LOCK_ENTROPY_INVALIDATED | |
3514 | | WC_RNG_LOCK_ENTROPY_RECOVERING | |
3515 | | WC_RNG_LOCK_ORPHANED), |
3516 | | cas_ret); |
3517 | | } WC_CAS_WITH_RETRY_END; |
3518 | | /* An aborted clear leaves the latch: with both bits still set, |
3519 | | * no reseed can ever discharge them (Hash_DRBG_Reseed() refuses |
3520 | | * with BUSY_E), so the reborn instance would be unrecoverable. |
3521 | | * Nothing is mutated yet beyond the status, so refuse. */ |
3522 | | if (cas_ret != 0) |
3523 | | return cas_ret; |
3524 | | } |
3525 | | } |
3526 | | |
3527 | | #endif /* WC_RNG_HAVE_LOCK */ |
3528 | | |
3529 | 63.4k | RngInitWipe(rng); |
3530 | | |
3531 | | #ifdef WC_RNG_HAVE_LOCK |
3532 | | /* .lock is excluded from the wipe (see wc_rng_wipe_skips[]) and |
3533 | | * (re)initializes per the _INIT_ flags: born held, born free, or |
3534 | | * (_PRESERVE_LOCK) left exactly as found. .RBGC_refcount, likewise |
3535 | | * excluded and likewise preserved by _PRESERVE_LOCK, is handled below |
3536 | | * with the other RBGC members. */ |
3537 | | if (flags & WC_RNG_INIT_FLAG_LOCK_INITIALLY) { |
3538 | | word32 initial_flags = |
3539 | | ((flags & WC_RNG_INIT_FLAG_LOCK_REQUIRED) ? |
3540 | | WC_RNG_LOCK_REQUIRED : 0) | |
3541 | | WC_RNG_LOCK_HELD; |
3542 | | #ifdef WC_RNG_DEBUG_STATS |
3543 | | rng->_stats_locks_taken = 1; |
3544 | | #endif |
3545 | | wolfSSL_Atomic_Uint_Init(&rng->lock, initial_flags); |
3546 | | } |
3547 | | else if (! (flags & WC_RNG_INIT_FLAG_PRESERVE_LOCK)) { |
3548 | | wolfSSL_Atomic_Uint_Init( |
3549 | | &rng->lock, |
3550 | | (flags & WC_RNG_INIT_FLAG_LOCK_REQUIRED) |
3551 | | ? WC_RNG_LOCK_REQUIRED |
3552 | | : 0); |
3553 | | } |
3554 | | |
3555 | | #endif /* WC_RNG_HAVE_LOCK */ |
3556 | | |
3557 | | #ifdef WC_RNG_HAVE_RBGC |
3558 | | if (userSeedSz > 0) { |
3559 | | rng->RBGCStratum = WC_RNG_RBGC_USER_SEED_STRATUM; |
3560 | | } |
3561 | | else if (seedRng != NULL) { |
3562 | | rng->RBGCStratum = seedRng->RBGCStratum + 1; |
3563 | | } |
3564 | | else { |
3565 | | rng->RBGCStratum = 0; |
3566 | | } |
3567 | | #ifdef WC_RNG_HAVE_LOCK |
3568 | | /* The refcount is live for exactly as long as the lock word is: a |
3569 | | * reachable instance may have spawned children whose release decrements |
3570 | | * it, so _PRESERVE_LOCK covers both arbitration words. */ |
3571 | | if (! (flags & WC_RNG_INIT_FLAG_PRESERVE_LOCK)) |
3572 | | wolfSSL_Atomic_Uint_Init(&rng->RBGC_refcount, 0); |
3573 | | rng->RBGC_parent = NULL; |
3574 | | #endif |
3575 | | |
3576 | | if (flags & WC_RNG_INIT_FLAG_NO_PRIMARY_SEED) |
3577 | | rng->flags |= WC_RNG_FLAG_NO_PRIMARY_SEED; |
3578 | | #endif |
3579 | | |
3580 | 63.4k | if (flags & WC_RNG_INIT_FLAG_FAIL_FAST) |
3581 | 0 | rng->flags |= WC_RNG_FLAG_FAIL_FAST; |
3582 | | |
3583 | | #ifdef WOLFSSL_HEAP_TEST |
3584 | | rng->heap = (void*)WOLFSSL_HEAP_TEST; |
3585 | | (void)heap; |
3586 | | #else |
3587 | 63.4k | rng->heap = heap; |
3588 | 63.4k | #endif |
3589 | | |
3590 | 63.4k | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
3591 | | /* note this assignment must precede the later seed operation. */ |
3592 | 63.4k | rng->entropy_epoch = WOLFSSL_ATOMIC_LOAD(global_entropy_epoch); |
3593 | 63.4k | #endif |
3594 | | |
3595 | 63.4k | #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) |
3596 | 63.4k | rng->pid = getpid(); |
3597 | 63.4k | #endif |
3598 | 63.4k | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
3599 | 63.4k | rng->devId = devId; |
3600 | 63.4k | #if defined(WOLF_CRYPTO_CB) |
3601 | 63.4k | rng->seed.devId = devId; |
3602 | 63.4k | #endif |
3603 | | #else |
3604 | | (void)devId; |
3605 | | #endif |
3606 | | |
3607 | 63.4k | #ifdef HAVE_HASHDRBG |
3608 | | /* init the DBRG to known values */ |
3609 | 63.4k | #ifndef NO_SHA256 |
3610 | 63.4k | rng->drbg = NULL; |
3611 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
3612 | | rng->drbg_scratch = NULL; |
3613 | | #endif |
3614 | 63.4k | #endif /* !NO_SHA256 */ |
3615 | 63.4k | #ifdef WOLFSSL_DRBG_SHA512 |
3616 | 63.4k | rng->drbg512 = NULL; |
3617 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
3618 | | rng->drbg512_scratch = NULL; |
3619 | | rng->health_check_scratch_512 = NULL; |
3620 | | #endif |
3621 | 63.4k | #endif /* WOLFSSL_DRBG_SHA512 */ |
3622 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
3623 | | #ifndef NO_SHA256 |
3624 | | rng->health_check_scratch = NULL; |
3625 | | #endif /* !NO_SHA256 */ |
3626 | | #endif /* WOLFSSL_SMALL_STACK_CACHE */ |
3627 | 63.4k | rng->status = DRBG_NOT_INIT; |
3628 | | |
3629 | | /* Select DRBG type: prefer SHA-512 unless disabled or not compiled. */ |
3630 | 63.4k | #ifdef WOLFSSL_DRBG_SHA512 |
3631 | 63.4k | if ((flags & WC_RNG_INIT_FLAG_DRBG_SHA512) || |
3632 | 0 | !(flags & WC_RNG_INIT_FLAG_DRBG_SHA256)) |
3633 | 63.4k | { |
3634 | 63.4k | rng->drbgType = WC_DRBG_SHA512; |
3635 | 63.4k | } |
3636 | 0 | else |
3637 | 0 | #endif |
3638 | 0 | #ifndef NO_SHA256 |
3639 | 0 | { |
3640 | 0 | rng->drbgType = WC_DRBG_SHA256; |
3641 | 0 | } |
3642 | | #else /* NO_SHA256 */ |
3643 | | { |
3644 | | return BAD_STATE_E; /* no DRBG available */ |
3645 | | } |
3646 | | #endif /* NO_SHA256 */ |
3647 | | |
3648 | 63.4k | #endif /* HAVE_HASHDRBG */ |
3649 | | |
3650 | | #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND) || \ |
3651 | | defined(HAVE_AMD_RDSEED) |
3652 | | /* init the intel RD seed and/or rand */ |
3653 | | wc_InitRng_IntelRD(); |
3654 | | #endif |
3655 | | |
3656 | | /* configure async RNG source if available */ |
3657 | | #ifdef WOLFSSL_ASYNC_CRYPT |
3658 | | ret = wolfAsync_DevCtxInit(&rng->asyncDev, WOLFSSL_ASYNC_MARKER_RNG, |
3659 | | rng->heap, rng->devId); |
3660 | | if (ret != 0) { |
3661 | | rng->status = DRBG_FAILED; |
3662 | | return ret; |
3663 | | } |
3664 | | #endif |
3665 | | |
3666 | | #ifdef HAVE_INTEL_RDRAND |
3667 | | /* if CPU supports RDRAND, use it directly and bypass DRBG init */ |
3668 | | if (IS_INTEL_RDRAND(intel_flags)) { |
3669 | | /* No DRBG, so nothing for caller-supplied seed material to feed: |
3670 | | * generation would come from RDRAND with the seed silently dropped, |
3671 | | * minting a primary-class (stratum-0) instance the caller believes |
3672 | | * is user-seeded. Refused with the no-DRBG verdict, the instance |
3673 | | * left uninstantiated. */ |
3674 | | if (userSeedSz > 0) |
3675 | | return WRONG_TYPE_OBJECT_E; |
3676 | | #ifdef WC_RNG_HAVE_RBGC |
3677 | | /* undo stratum, if any */ |
3678 | | rng->RBGCStratum = 0; |
3679 | | #endif |
3680 | | /* Aperture reopening is the last act before publication, as below. |
3681 | | * The credited seed aperture stays _TORNDOWN: there is no DRBG to |
3682 | | * reseed and no buffer behind it. The stir aperture reopens, so that |
3683 | | * deposits accumulate and a stir consumes them as the no-op it is on |
3684 | | * an RDRAND instantiation (see Hash_DRBG_StirGenerate()). */ |
3685 | | #ifdef WC_RNG_HAVE_POOL |
3686 | | WOLFSSL_ATOMIC_STORE(rng->poolHead, WC_RNG_POOL_STATE_UNALLOC); |
3687 | | #endif |
3688 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
3689 | | WOLFSSL_ATOMIC_STORE(rng->nextStirLen, WC_DRBG_NEXT_SEED_EMPTY); |
3690 | | #endif |
3691 | | rng->status = DRBG_OK; |
3692 | | return 0; |
3693 | | } |
3694 | | #endif |
3695 | | |
3696 | | #ifdef WOLFSSL_XILINX_CRYPT_VERSAL |
3697 | | ret = wc_VersalTrngInit(nonce, nonceSz); |
3698 | | if (ret) { |
3699 | | rng->status = DRBG_FAILED; |
3700 | | return ret; |
3701 | | } |
3702 | | #endif |
3703 | | |
3704 | | #if defined(WOLFSSL_KEEP_RNG_SEED_FD_OPEN) && !defined(USE_WINDOWS_API) |
3705 | | if (!rng->seed.seedFdOpen) |
3706 | | rng->seed.fd = XBADFD; |
3707 | | #endif |
3708 | | |
3709 | | #ifdef CUSTOM_RAND_GENERATE_BLOCK |
3710 | | ret = 0; /* success */ |
3711 | | #else |
3712 | | |
3713 | | /* not CUSTOM_RAND_GENERATE_BLOCK follows */ |
3714 | 63.4k | #ifdef HAVE_HASHDRBG |
3715 | 63.4k | if (nonceSz == 0) { |
3716 | 63.4k | seedSz = MAX_SEED_SZ; |
3717 | 63.4k | } |
3718 | | |
3719 | 63.4k | #ifndef NO_SHA256 |
3720 | 63.4k | if (rng->drbgType == WC_DRBG_SHA256) { |
3721 | 0 | #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) |
3722 | 0 | rng->drbg = |
3723 | 0 | (struct DRBG*)XMALLOC(sizeof(DRBG_internal), rng->heap, |
3724 | 0 | DYNAMIC_TYPE_RNG); |
3725 | 0 | if (rng->drbg == NULL) { |
3726 | | #if defined(DEBUG_WOLFSSL) |
3727 | | WOLFSSL_MSG_EX("_InitRng XMALLOC failed to allocate %d bytes", |
3728 | | sizeof(DRBG_internal)); |
3729 | | #endif |
3730 | 0 | ret = MEMORY_E; |
3731 | 0 | rng->status = DRBG_FAILED; |
3732 | 0 | } |
3733 | | #else |
3734 | | rng->drbg = (struct DRBG*)&rng->drbg_data; |
3735 | | #endif /* WOLFSSL_NO_MALLOC or WOLFSSL_STATIC_MEMORY */ |
3736 | |
|
3737 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
3738 | | if (ret == 0) { |
3739 | | rng->drbg_scratch = |
3740 | | (DRBG_internal *)XMALLOC(sizeof(DRBG_internal), rng->heap, |
3741 | | DYNAMIC_TYPE_RNG); |
3742 | | if (rng->drbg_scratch == NULL) { |
3743 | | #if defined(DEBUG_WOLFSSL) |
3744 | | WOLFSSL_MSG_EX("_InitRng XMALLOC failed to allocate %d bytes", |
3745 | | sizeof(DRBG_internal)); |
3746 | | #endif |
3747 | | ret = MEMORY_E; |
3748 | | rng->status = DRBG_FAILED; |
3749 | | } |
3750 | | } |
3751 | | |
3752 | | if (ret == 0) { |
3753 | | /* Set before the call, as for drbg_instantiated: a failed |
3754 | | * instantiate still leaves V in the state, and the failure |
3755 | | * arm below must uninstantiate it. (The scratch is |
3756 | | * NULL-seeded, so the stranded state would be a public |
3757 | | * constant -- wiped anyway, for uniformity of the |
3758 | | * invariant.) */ |
3759 | | drbg_scratch_instantiated = 1; |
3760 | | ret = Hash_DRBG_Instantiate((DRBG_internal *)rng->drbg_scratch, |
3761 | | NULL, NULL, 0, NULL, 0, NULL, 0, rng->heap, devId); |
3762 | | } |
3763 | | |
3764 | | if (ret == 0) { |
3765 | | rng->health_check_scratch = |
3766 | | (byte *)XMALLOC(RNG_HEALTH_TEST_CHECK_SIZE, rng->heap, |
3767 | | DYNAMIC_TYPE_TMP_BUFFER); |
3768 | | if (rng->health_check_scratch == NULL) { |
3769 | | ret = MEMORY_E; |
3770 | | rng->status = DRBG_FAILED; |
3771 | | } |
3772 | | } |
3773 | | #endif /* WOLFSSL_SMALL_STACK_CACHE */ |
3774 | 0 | } /* WC_DRBG_SHA256 */ |
3775 | 63.4k | #endif /* !NO_SHA256 */ |
3776 | | |
3777 | 63.4k | #ifdef WOLFSSL_DRBG_SHA512 |
3778 | 63.4k | if (rng->drbgType == WC_DRBG_SHA512) { |
3779 | 63.4k | #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) |
3780 | 63.4k | rng->drbg512 = |
3781 | 63.4k | (struct DRBG_SHA512*)XMALLOC(sizeof(DRBG_SHA512_internal), |
3782 | 63.4k | rng->heap, DYNAMIC_TYPE_RNG); |
3783 | 63.4k | if (rng->drbg512 == NULL) { |
3784 | | #if defined(DEBUG_WOLFSSL) |
3785 | | WOLFSSL_MSG_EX("_InitRng XMALLOC failed to allocate %d bytes", |
3786 | | sizeof(DRBG_SHA512_internal)); |
3787 | | #endif |
3788 | 325 | ret = MEMORY_E; |
3789 | 325 | rng->status = DRBG_FAILED; |
3790 | 325 | } |
3791 | | #else |
3792 | | rng->drbg512 = (struct DRBG_SHA512*)&rng->drbg512_data; |
3793 | | #endif |
3794 | | |
3795 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
3796 | | if (ret == 0) { |
3797 | | rng->drbg512_scratch = |
3798 | | (DRBG_SHA512_internal *)XMALLOC(sizeof(DRBG_SHA512_internal), |
3799 | | rng->heap, DYNAMIC_TYPE_RNG); |
3800 | | if (rng->drbg512_scratch == NULL) { |
3801 | | ret = MEMORY_E; |
3802 | | rng->status = DRBG_FAILED; |
3803 | | } |
3804 | | } |
3805 | | |
3806 | | if (ret == 0) { |
3807 | | /* Set before the call -- see the SHA-256 scratch arm. */ |
3808 | | drbg_scratch_instantiated = 1; |
3809 | | ret = Hash512_DRBG_Instantiate(rng->drbg512_scratch, |
3810 | | NULL, NULL, 0, NULL, 0, NULL, 0, rng->heap, devId); |
3811 | | } |
3812 | | |
3813 | | if (ret == 0) { |
3814 | | rng->health_check_scratch_512 = |
3815 | | (byte *)XMALLOC(RNG_HEALTH_TEST_CHECK_SIZE_SHA512, rng->heap, |
3816 | | DYNAMIC_TYPE_TMP_BUFFER); |
3817 | | if (rng->health_check_scratch_512 == NULL) { |
3818 | | ret = MEMORY_E; |
3819 | | rng->status = DRBG_FAILED; |
3820 | | } |
3821 | | } |
3822 | | #endif /* WOLFSSL_SMALL_STACK_CACHE */ |
3823 | 63.4k | } /* WC_DRBG_SHA512 */ |
3824 | 63.4k | #endif /* WOLFSSL_DRBG_SHA512 */ |
3825 | | |
3826 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
3827 | | if (ret == 0) { |
3828 | | #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) |
3829 | | rng->nextSeed = (byte *)XMALLOC(WC_DRBG_SEED_BUF_SIZE, rng->heap, |
3830 | | DYNAMIC_TYPE_RNG); |
3831 | | if (rng->nextSeed == NULL) { |
3832 | | ret = MEMORY_E; |
3833 | | rng->status = DRBG_FAILED; |
3834 | | } |
3835 | | #else |
3836 | | rng->nextSeed = rng->nextSeed_data; |
3837 | | #endif |
3838 | | } |
3839 | | #endif |
3840 | | |
3841 | 63.4k | if (ret == 0) { |
3842 | 63.0k | ret = wc_RNG_HealthTestLocal(rng, 0, rng->heap, devId); |
3843 | 63.0k | if (ret != 0) { |
3844 | | #if defined(DEBUG_WOLFSSL) |
3845 | | WOLFSSL_MSG_EX("wc_RNG_HealthTestLocal failed err = %d", ret); |
3846 | | #endif |
3847 | 794 | } |
3848 | 63.0k | } |
3849 | | |
3850 | 63.4k | #ifdef WOLFSSL_SMALL_STACK |
3851 | 63.4k | if (ret == 0) { |
3852 | 62.3k | WC_ALLOC_VAR_EX(seed, byte, MAX_SEED_SZ, rng->heap, DYNAMIC_TYPE_SEED, |
3853 | 62.3k | WC_DO_NOTHING); |
3854 | 62.3k | if (seed == NULL) { |
3855 | 12 | ret = MEMORY_E; |
3856 | 12 | rng->status = DRBG_FAILED; |
3857 | 12 | } |
3858 | 62.3k | } |
3859 | 63.4k | #endif |
3860 | | |
3861 | 63.4k | if (ret != 0) { |
3862 | | #if defined(DEBUG_WOLFSSL) |
3863 | | WOLFSSL_MSG_EX("_InitRng failed. err = %d", ret); |
3864 | | #endif |
3865 | 1.13k | } |
3866 | 62.2k | else { |
3867 | 62.2k | if (userSeedSz > 0) { |
3868 | | /* User-seeded instantiation -- no provenance. */ |
3869 | 0 | if (flags & WC_RNG_INIT_FLAG_TEST_USER_SEED) { |
3870 | | /* Verbatim, unpadded, at offset 0, and the supplied length is |
3871 | | * the instantiation length: the material is laid out exactly |
3872 | | * as module-gathered seed material is, so the first |
3873 | | * SEED_BLOCK_SZ bytes are the health-test block, which the |
3874 | | * instantiate below skips (FIPS and non-FULL_SEED builds). |
3875 | | * Material beyond the buffer is not consumed. */ |
3876 | 0 | if (userSeedSz < seedSz) |
3877 | 0 | seedSz = userSeedSz; |
3878 | 0 | XMEMCPY(seed, userSeed, seedSz); |
3879 | 0 | } |
3880 | 0 | else { |
3881 | | /* Zero-padded, with the copy offset equal to the instantiate |
3882 | | * offset: the caller's byte 0 is the DRBG's byte 0, no |
3883 | | * supplied byte is discarded, and no health test runs. */ |
3884 | 0 | XMEMSET(seed, 0, seedSz); |
3885 | | #if !defined(HAVE_FIPS) && defined(WOLFSSL_RNG_USE_FULL_SEED) |
3886 | | XMEMCPY(seed, userSeed, |
3887 | | (userSeedSz > seedSz) ? seedSz : userSeedSz); |
3888 | | #else |
3889 | 0 | XMEMCPY(seed + SEED_BLOCK_SZ, userSeed, |
3890 | 0 | (userSeedSz > (seedSz - SEED_BLOCK_SZ)) |
3891 | 0 | ? |
3892 | 0 | (seedSz - SEED_BLOCK_SZ) |
3893 | 0 | : |
3894 | 0 | userSeedSz); |
3895 | 0 | #endif |
3896 | 0 | } |
3897 | 0 | } |
3898 | 62.2k | else if (seedRng != NULL) { |
3899 | | /* RBGC spawn: draw the seed material from the parent DRBG's |
3900 | | * generate function in place of the module's seed source -- the SP |
3901 | | * 800-90C RBG chain construction. The root DRBG is implicitly |
3902 | | * healthy, so the seed Health test is omitted; all subsequent |
3903 | | * handling (seed byte accounting, instantiate, failure disposition) |
3904 | | * is then identical to the primary seed path. */ |
3905 | 0 | ret = wc_RNG_GenerateBlock(seedRng, seed, seedSz); |
3906 | 0 | } |
3907 | 62.2k | else { |
3908 | | #ifdef WC_RNG_SEED_CB |
3909 | | if (seedCb == NULL) { |
3910 | | ret = DRBG_NO_SEED_CB; |
3911 | | } |
3912 | | else { |
3913 | | ret = seedCb(&rng->seed, seed, seedSz); |
3914 | | #ifdef WC_VERBOSE_RNG |
3915 | | if ((ret != 0) && !WC_RNG_ERR_IS_TRANSIENT(ret) && |
3916 | | (ret != WC_NO_ERR_TRACE(DRBG_NEED_RESEED))) |
3917 | | { |
3918 | | WOLFSSL_DEBUG_PRINTF( |
3919 | | "ERROR: seedCb in _InitRng() failed with err = %d", |
3920 | | ret); |
3921 | | } |
3922 | | #endif |
3923 | | } |
3924 | | #else |
3925 | 62.2k | ret = wc_GenerateSeed(&rng->seed, seed, seedSz); |
3926 | 62.2k | #endif /* WC_RNG_SEED_CB */ |
3927 | 62.2k | if (ret != 0) { |
3928 | | /* A verdict from the source survives here as it does on the |
3929 | | * reseed path, so instantiate and reseed classify it alike. */ |
3930 | 0 | ret = ReseedSourceFailure(ret); |
3931 | 0 | } |
3932 | 62.2k | } |
3933 | | |
3934 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
3935 | | /* seed now holds entropy; register across DRBG instantiation */ |
3936 | | wc_MemZero_Add("_InitRng seed", seed, seedSz); |
3937 | | #endif |
3938 | | |
3939 | 62.2k | if (ret != 0) { |
3940 | | #if defined(DEBUG_WOLFSSL) |
3941 | | WOLFSSL_MSG_EX("Seed generation failed... %d", ret); |
3942 | | #elif defined(WC_VERBOSE_RNG) |
3943 | | if ((! WC_RNG_ERR_IS_TRANSIENT(ret)) && |
3944 | | (ret != WC_NO_ERR_TRACE(DRBG_NEED_RESEED))) |
3945 | | { |
3946 | | WOLFSSL_DEBUG_PRINTF( |
3947 | | "ERROR: seed acquisition in _InitRng() failed with err %d", |
3948 | | ret); |
3949 | | } |
3950 | | #endif |
3951 | 0 | rng->status = DRBG_FAILED; |
3952 | 0 | } |
3953 | | |
3954 | | /* Health-check the primary seed -- RBGC seed is implicitly healthy, |
3955 | | * and a user-supplied seed claims no entropy, so the source health |
3956 | | * tests don't govern it (and would spuriously refuse structured |
3957 | | * material) -- unless the caller asked for them with |
3958 | | * WC_RNG_INIT_FLAG_TEST_USER_SEED, in which case the material is |
3959 | | * judged exactly as the module's own would be. */ |
3960 | | |
3961 | 62.2k | if ((ret == 0) && (seedRng == NULL) && |
3962 | 62.2k | ((userSeedSz == 0) || |
3963 | 0 | (flags & WC_RNG_INIT_FLAG_TEST_USER_SEED))) |
3964 | 62.2k | { |
3965 | 62.2k | ret = wc_RNG_TestSeed(seed, seedSz); |
3966 | | #if defined(DEBUG_WOLFSSL) |
3967 | | if (ret != 0) { |
3968 | | WOLFSSL_MSG_EX("wc_RNG_TestSeed failed... %d", ret); |
3969 | | } |
3970 | | #elif defined(WC_VERBOSE_RNG) |
3971 | | if ((ret != DRBG_SUCCESS) && !WC_RNG_ERR_IS_TRANSIENT(ret)) { |
3972 | | WOLFSSL_DEBUG_PRINTF( |
3973 | | "ERROR: wc_RNG_TestSeed() in _InitRng() returned err %d.", |
3974 | | ret); |
3975 | | } |
3976 | | #endif |
3977 | 62.2k | } |
3978 | | |
3979 | | /* Instantiate the DRBG */ |
3980 | | |
3981 | 62.2k | if (ret == DRBG_SUCCESS) { |
3982 | | /* Set before the call: a failed instantiate still leaves V in |
3983 | | * the state, and the failure arm below must uninstantiate it. */ |
3984 | 62.2k | drbg_instantiated = 1; |
3985 | 62.2k | #ifndef NO_SHA256 |
3986 | 62.2k | if (rng->drbgType == WC_DRBG_SHA256) |
3987 | 0 | ret = Hash_DRBG_Instantiate((DRBG_internal *)rng->drbg, |
3988 | 0 | &rng->reseedCtr, |
3989 | 0 | #if defined(HAVE_FIPS) || !defined(WOLFSSL_RNG_USE_FULL_SEED) |
3990 | 0 | seed + SEED_BLOCK_SZ, seedSz - SEED_BLOCK_SZ, |
3991 | | #else |
3992 | | seed, seedSz, |
3993 | | #endif |
3994 | 0 | nonce, nonceSz, perso, persoSz, rng->heap, devId); |
3995 | 62.2k | #endif |
3996 | 62.2k | #ifdef WOLFSSL_DRBG_SHA512 |
3997 | 62.2k | if (rng->drbgType == WC_DRBG_SHA512) |
3998 | 62.2k | ret = Hash512_DRBG_Instantiate( |
3999 | 62.2k | (DRBG_SHA512_internal *)rng->drbg512, |
4000 | 62.2k | &rng->reseedCtr, |
4001 | 62.2k | #if defined(HAVE_FIPS) || !defined(WOLFSSL_RNG_USE_FULL_SEED) |
4002 | 62.2k | seed + SEED_BLOCK_SZ, seedSz - SEED_BLOCK_SZ, |
4003 | | #else |
4004 | | seed, seedSz, |
4005 | | #endif |
4006 | 62.2k | nonce, nonceSz, perso, persoSz, rng->heap, devId); |
4007 | 62.2k | #endif |
4008 | 62.2k | } |
4009 | 62.2k | } /* ret == 0 */ |
4010 | | |
4011 | | /* Unconditionally burn the seed data. */ |
4012 | | |
4013 | 63.4k | #ifdef WOLFSSL_SMALL_STACK |
4014 | 63.4k | if (seed) |
4015 | 62.2k | #endif |
4016 | 62.2k | { |
4017 | 62.2k | ForceZero(seed, seedSz); |
4018 | | #if !defined(WOLFSSL_SMALL_STACK) && defined(WOLFSSL_CHECK_MEM_ZERO) |
4019 | | /* heap build's WC_FREE_VAR_EX/XFREE auto-checks; stack build needs it */ |
4020 | | wc_MemZero_Check(seed, seedSz); |
4021 | | #endif |
4022 | 62.2k | } |
4023 | 63.4k | WC_FREE_VAR_EX(seed, rng->heap, DYNAMIC_TYPE_SEED); |
4024 | | |
4025 | 63.4k | if (ret == DRBG_SUCCESS) { |
4026 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
4027 | | #ifndef NO_SHA256 |
4028 | | if (rng->drbgType == WC_DRBG_SHA256) { |
4029 | | struct DRBG_internal* drbg = (struct DRBG_internal*)rng->drbg; |
4030 | | wc_MemZero_Add("DRBG V", &drbg->V, sizeof(drbg->V)); |
4031 | | wc_MemZero_Add("DRBG C", &drbg->C, sizeof(drbg->C)); |
4032 | | } |
4033 | | #endif |
4034 | | #endif |
4035 | | |
4036 | | /* rng->status is set to DRBG_OK at the very end, iff nothing goes wrong |
4037 | | * between here and there. */ |
4038 | | |
4039 | 62.1k | ret = 0; |
4040 | 62.1k | } |
4041 | 1.28k | else if (ret == WC_NO_ERR_TRACE(DRBG_CONT_FAILURE)) { |
4042 | 0 | rng->status = DRBG_CONT_FAILED; |
4043 | 0 | ret = DRBG_CONT_FIPS_E; |
4044 | 0 | } |
4045 | 1.28k | else if (ret == WC_NO_ERR_TRACE(DRBG_FAILURE)) { |
4046 | 798 | rng->status = DRBG_FAILED; |
4047 | 798 | ret = RNG_FAILURE_E; |
4048 | 798 | } |
4049 | 487 | else { |
4050 | 487 | rng->status = DRBG_FAILED; |
4051 | 487 | } |
4052 | 63.4k | #endif /* HAVE_HASHDRBG */ |
4053 | 63.4k | #endif /* CUSTOM_RAND_GENERATE_BLOCK */ |
4054 | | |
4055 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
4056 | | if ((ret == 0) && |
4057 | | (flags & WC_RNG_INIT_FLAG_UPGRADE_FROM_NEXT_SEED)) |
4058 | | { |
4059 | | rng->flags |= WC_RNG_FLAG_UPGRADE_FROM_NEXT_SEED; |
4060 | | } |
4061 | | #endif |
4062 | 63.4k | if ((ret == 0) && (flags & WC_RNG_INIT_FLAG_USE_FULL_MUTEX)) { |
4063 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
4064 | | /* deliberately the last init step: no failure path can strand an |
4065 | | * initialized mutex. */ |
4066 | | ret = wc_InitMutex(&rng->mutex); |
4067 | | if (ret == 0) { |
4068 | | rng->flags |= WC_RNG_FLAG_FULL_MUTEX; |
4069 | | if (flags & WC_RNG_INIT_FLAG_LOCK_INITIALLY) { |
4070 | | /* born held at both layers: the constructor's caller holds |
4071 | | * the whole latch, mutex included. */ |
4072 | | ret = wc_LockMutex(&rng->mutex); |
4073 | | if (ret != 0) { |
4074 | | (void)wc_FreeMutex(&rng->mutex); |
4075 | | rng->flags &= ~WC_RNG_FLAG_FULL_MUTEX; |
4076 | | } |
4077 | | } |
4078 | | } |
4079 | | #endif |
4080 | 0 | } |
4081 | | |
4082 | 63.4k | if (ret != 0) { |
4083 | 1.28k | #if defined(HAVE_HASHDRBG) && !defined(CUSTOM_RAND_GENERATE_BLOCK) |
4084 | 1.28k | #ifndef NO_SHA256 |
4085 | 1.28k | if (rng->drbgType == WC_DRBG_SHA256) { |
4086 | 0 | if (drbg_instantiated) { |
4087 | 0 | (void)Hash_DRBG_Uninstantiate( |
4088 | 0 | (DRBG_internal *)rng->drbg); |
4089 | 0 | } |
4090 | 0 | #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) |
4091 | 0 | XFREE(rng->drbg, rng->heap, DYNAMIC_TYPE_RNG); |
4092 | 0 | #endif |
4093 | 0 | rng->drbg = NULL; |
4094 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
4095 | | XFREE(rng->health_check_scratch, rng->heap, |
4096 | | DYNAMIC_TYPE_TMP_BUFFER); |
4097 | | rng->health_check_scratch = NULL; |
4098 | | if (drbg_scratch_instantiated) |
4099 | | (void)Hash_DRBG_Uninstantiate( |
4100 | | (DRBG_internal *)rng->drbg_scratch); |
4101 | | XFREE(rng->drbg_scratch, rng->heap, DYNAMIC_TYPE_RNG); |
4102 | | rng->drbg_scratch = NULL; |
4103 | | #endif /* WOLFSSL_SMALL_STACK_CACHE */ |
4104 | 0 | } |
4105 | 1.28k | #endif /* !NO_SHA256 */ |
4106 | 1.28k | #ifdef WOLFSSL_DRBG_SHA512 |
4107 | 1.28k | if (rng->drbgType == WC_DRBG_SHA512) { |
4108 | 1.28k | if (drbg_instantiated) { |
4109 | 154 | (void)Hash512_DRBG_Uninstantiate( |
4110 | 154 | (DRBG_SHA512_internal *)rng->drbg512); |
4111 | 154 | } |
4112 | 1.28k | #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) |
4113 | 1.28k | XFREE(rng->drbg512, rng->heap, DYNAMIC_TYPE_RNG); |
4114 | 1.28k | #endif |
4115 | 1.28k | rng->drbg512 = NULL; |
4116 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
4117 | | XFREE(rng->health_check_scratch_512, rng->heap, |
4118 | | DYNAMIC_TYPE_TMP_BUFFER); |
4119 | | rng->health_check_scratch_512 = NULL; |
4120 | | if (drbg_scratch_instantiated) |
4121 | | (void)Hash512_DRBG_Uninstantiate(rng->drbg512_scratch); |
4122 | | XFREE(rng->drbg512_scratch, rng->heap, DYNAMIC_TYPE_RNG); |
4123 | | rng->drbg512_scratch = NULL; |
4124 | | #endif /* WOLFSSL_SMALL_STACK_CACHE */ |
4125 | 1.28k | } |
4126 | 1.28k | #endif /* WOLFSSL_DRBG_SHA512 */ |
4127 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
4128 | | #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) |
4129 | | XFREE(rng->nextSeed, rng->heap, DYNAMIC_TYPE_RNG); |
4130 | | #endif |
4131 | | rng->nextSeed = NULL; |
4132 | | #endif |
4133 | 1.28k | #endif /* HAVE_HASHDRBG && !CUSTOM_RAND_GENERATE_BLOCK */ |
4134 | 1.28k | } |
4135 | | |
4136 | 63.4k | #ifdef WC_RNG_HAVE_AUTO_LOCK |
4137 | 63.4k | if ((ret == 0) && |
4138 | 62.1k | ! (flags & (WC_RNG_INIT_FLAG_NO_AUTO_LOCK | |
4139 | 62.1k | WC_RNG_INIT_FLAG_LOCK_REQUIRED | |
4140 | 62.1k | WC_RNG_INIT_FLAG_USE_FULL_MUTEX)) && |
4141 | 0 | (WC_RNG_AUTO_LOCK_DEFAULT || |
4142 | 62.1k | (flags & WC_RNG_INIT_FLAG_USE_AUTO_LOCK))) { |
4143 | 62.1k | ret = RngAutoLockInit(rng); |
4144 | 62.1k | if (ret != 0) { |
4145 | | /* Unpublished instance: no latch needed, and the latch may be |
4146 | | * born held (_LOCK_INITIALLY), which wc_FreeRng() would refuse. */ |
4147 | | #ifdef WC_RNG_HAVE_LOCK |
4148 | | (void)wc_FreeRng_PreLocked(rng); |
4149 | | #else |
4150 | 2 | (void)wc_FreeRng(rng); |
4151 | 2 | #endif |
4152 | 2 | } |
4153 | 62.1k | } |
4154 | 63.4k | #endif |
4155 | | |
4156 | | #if defined(WC_RNG_HAVE_RBGC) && defined(WC_RNG_HAVE_LOCK) |
4157 | | if ((ret == 0) && (seedRng != NULL) && |
4158 | | (WOLFSSL_ATOMIC_LOAD(seedRng->lock) & WC_RNG_LOCK_REQUIRED) && |
4159 | | (! (seedRng->flags & WC_RNG_FLAG_NO_RBGC_PARENT))) |
4160 | | { |
4161 | | (void)wolfSSL_Atomic_Uint_FetchAdd(&seedRng->RBGC_refcount, 1U); |
4162 | | rng->RBGC_parent = seedRng; |
4163 | | } |
4164 | | #endif |
4165 | | |
4166 | 63.4k | if (ret == 0) { |
4167 | | /* open the apertures */ |
4168 | | #ifdef WC_RNG_HAVE_POOL |
4169 | | WOLFSSL_ATOMIC_STORE(rng->poolHead, WC_RNG_POOL_STATE_UNALLOC); |
4170 | | #endif |
4171 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
4172 | | WOLFSSL_ATOMIC_STORE(rng->nextStirLen, WC_DRBG_NEXT_SEED_EMPTY); |
4173 | | #ifdef HAVE_HASHDRBG |
4174 | | WOLFSSL_ATOMIC_STORE(rng->nextSeedLen, WC_DRBG_NEXT_SEED_EMPTY); |
4175 | | #endif |
4176 | | #endif |
4177 | | |
4178 | 62.1k | rng->status = DRBG_OK; |
4179 | 62.1k | } |
4180 | | |
4181 | 63.4k | return ret; |
4182 | 63.4k | } |
4183 | | |
4184 | | |
4185 | | WOLFSSL_ABI |
4186 | | WC_RNG* wc_rng_new(byte* nonce, word32 nonceSz, void* heap) |
4187 | 0 | { |
4188 | 0 | int ret = 0; |
4189 | 0 | WC_RNG* rng = NULL; |
4190 | | |
4191 | | /* Assume if WC_USE_DEVID it is intended for default usage */ |
4192 | | #ifdef WC_USE_DEVID |
4193 | | ret = wc_rng_new_ex(&rng, nonce, nonceSz, heap, WC_USE_DEVID); |
4194 | | #else |
4195 | 0 | ret = wc_rng_new_ex(&rng, nonce, nonceSz, heap, INVALID_DEVID); |
4196 | 0 | #endif |
4197 | |
|
4198 | 0 | if (ret != 0) { |
4199 | 0 | return NULL; |
4200 | 0 | } |
4201 | | |
4202 | 0 | return rng; |
4203 | 0 | } |
4204 | | |
4205 | | |
4206 | | int wc_rng_new_ex(WC_RNG **rng, byte* nonce, word32 nonceSz, |
4207 | | void* heap, int devId) |
4208 | 0 | { |
4209 | 0 | int ret; |
4210 | |
|
4211 | 0 | if (rng == NULL) { |
4212 | 0 | return BAD_FUNC_ARG; |
4213 | 0 | } |
4214 | | |
4215 | 0 | *rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), heap, DYNAMIC_TYPE_RNG); |
4216 | 0 | if (*rng == NULL) { |
4217 | 0 | return MEMORY_E; |
4218 | 0 | } |
4219 | | |
4220 | 0 | ret = _InitRng(*rng, nonce, nonceSz, NULL, 0, NULL, 0, heap, devId, NULL, |
4221 | 0 | WC_RNG_INIT_FLAG_NONE); |
4222 | 0 | if (ret != 0) { |
4223 | 0 | XFREE(*rng, heap, DYNAMIC_TYPE_RNG); |
4224 | 0 | *rng = NULL; |
4225 | 0 | } |
4226 | 0 | else { |
4227 | | /* wc_rng_free() is a void -- no way to cope with STILL_REFERENCED_E. |
4228 | | */ |
4229 | 0 | (*rng)->flags |= WC_RNG_FLAG_NO_RBGC_PARENT; |
4230 | 0 | } |
4231 | |
|
4232 | 0 | return ret; |
4233 | 0 | } |
4234 | | |
4235 | | |
4236 | | WOLFSSL_ABI |
4237 | | void wc_rng_free(WC_RNG* rng) |
4238 | 0 | { |
4239 | 0 | if (rng) { |
4240 | 0 | void* heap = rng->heap; |
4241 | |
|
4242 | 0 | if (wc_FreeRng(rng) == 0) { |
4243 | 0 | ForceZero(rng, sizeof(WC_RNG)); |
4244 | 0 | XFREE(rng, heap, DYNAMIC_TYPE_RNG); |
4245 | 0 | } |
4246 | 0 | else { |
4247 | | /* BUSY_E (a live lease) or STILL_REFERENCED_E (RBGC children |
4248 | | * still pin the shell): zeroing or freeing here would be a |
4249 | | * use-after-free against the lessee's lock word or the |
4250 | | * children's retained parent pointers. The void WOLFSSL_ABI |
4251 | | * signature cannot report, so the allocation is deliberately |
4252 | | * leaked -- the documented worst case. Sensitive state was |
4253 | | * already wiped by wc_FreeRng() in the STILL_REFERENCED_E |
4254 | | * case, and left intact (with the instance) in the BUSY_E |
4255 | | * case. */ |
4256 | | #ifdef WC_VERBOSE_RNG |
4257 | | WOLFSSL_DEBUG_PRINTF( |
4258 | | "wc_rng_free(): wc_FreeRng() failed; leaking the instance " |
4259 | | "rather than freeing referenced memory.\n"); |
4260 | | #endif |
4261 | 0 | } |
4262 | 0 | (void)heap; |
4263 | 0 | } |
4264 | 0 | } |
4265 | | |
4266 | | #ifdef HAVE_HASHDRBG |
4267 | | /* The strength floor on caller-supplied seed material at the public user-seed |
4268 | | * entry points. Without WC_RNG_INIT_FLAG_TEST_USER_SEED every supplied byte |
4269 | | * is DRBG input (the copy offset is the instantiate offset), so the floor is |
4270 | | * the DRBG's own. With it, the first SEED_BLOCK_SZ bytes are the health-test |
4271 | | * block, excluded from DRBG input in FIPS and non-FULL_SEED builds, so the |
4272 | | * floor grows by a block to keep the DRBG's share whole. */ |
4273 | | static WC_INLINE word32 UserSeedSzFloor(word32 flags) |
4274 | 0 | { |
4275 | 0 | #if defined(HAVE_FIPS) || !defined(WOLFSSL_RNG_USE_FULL_SEED) |
4276 | 0 | if (flags & WC_RNG_INIT_FLAG_TEST_USER_SEED) |
4277 | 0 | return (word32)(WC_DRBG_SEED_SZ + SEED_BLOCK_SZ); |
4278 | | #else |
4279 | | (void)flags; |
4280 | | #endif |
4281 | 0 | return (word32)WC_DRBG_SEED_SZ; |
4282 | 0 | } |
4283 | | #endif /* HAVE_HASHDRBG */ |
4284 | | |
4285 | | #if FIPS_VERSION3_GE(7,0,0) && defined(HAVE_HASHDRBG) |
4286 | | /* Start a WC_RNG from a fixed seed so a known answer test gets the same answer |
4287 | | * every time. Library internal; the FIPS self tests are the only caller. The |
4288 | | * seed is health-tested and laid out exactly as module-gathered material |
4289 | | * (WC_RNG_INIT_FLAG_TEST_USER_SEED), and is bound by no strength floor: the |
4290 | | * only requirement is something beyond the test block. */ |
4291 | | int wc_InitRngFixedSeed(WC_RNG* rng, const byte* seed, word32 seedSz) |
4292 | | { |
4293 | | int ret; |
4294 | | |
4295 | | /* The first SEED_BLOCK_SZ bytes are the seed test block, not DRBG input. */ |
4296 | | if ((rng == NULL) || (seed == NULL) || (seedSz <= SEED_BLOCK_SZ) || |
4297 | | (seedSz > MAX_SEED_SZ)) { |
4298 | | return BAD_FUNC_ARG; |
4299 | | } |
4300 | | |
4301 | | ret = _InitRng(rng, NULL, 0, NULL, 0, seed, seedSz, NULL, INVALID_DEVID, |
4302 | | NULL, WC_RNG_INIT_FLAG_TEST_USER_SEED); |
4303 | | /* Backstop: an RDRAND host is refused by _InitRng() itself, but a build |
4304 | | * with another DRBG-less source (CUSTOM_RAND_GENERATE_BLOCK) returns 0 |
4305 | | * with no DRBG and would then generate without the seed. */ |
4306 | | if ((ret == 0) && !wc_RNG_DRBG_Present(rng)) { |
4307 | | (void)wc_FreeRng(rng); |
4308 | | ret = WRONG_TYPE_OBJECT_E; |
4309 | | } |
4310 | | |
4311 | | return ret; |
4312 | | } |
4313 | | #endif /* FIPS_VERSION3_GE(7,0,0) && HAVE_HASHDRBG */ |
4314 | | |
4315 | | WOLFSSL_ABI |
4316 | | int wc_InitRng(WC_RNG* rng) |
4317 | 1.62k | { |
4318 | 1.62k | return _InitRng(rng, NULL, 0, NULL, 0, NULL, 0, NULL, INVALID_DEVID, NULL, |
4319 | 1.62k | WC_RNG_INIT_FLAG_NONE); |
4320 | 1.62k | } |
4321 | | |
4322 | | |
4323 | | int wc_InitRng_ex(WC_RNG* rng, void* heap, int devId) |
4324 | 67.6k | { |
4325 | 67.6k | return _InitRng(rng, NULL, 0, NULL, 0, NULL, 0, heap, devId, NULL, |
4326 | 67.6k | WC_RNG_INIT_FLAG_NONE); |
4327 | 67.6k | } |
4328 | | |
4329 | | |
4330 | | int wc_InitRngNonce(WC_RNG* rng, const byte* nonce, word32 nonceSz) |
4331 | 0 | { |
4332 | 0 | return _InitRng(rng, nonce, nonceSz, NULL, 0, NULL, 0, NULL, INVALID_DEVID, |
4333 | 0 | NULL, WC_RNG_INIT_FLAG_NONE); |
4334 | 0 | } |
4335 | | |
4336 | | |
4337 | | int wc_InitRngNonce_ex(WC_RNG* rng, const byte* nonce, word32 nonceSz, |
4338 | | void* heap, int devId) |
4339 | 0 | { |
4340 | 0 | return _InitRng(rng, nonce, nonceSz, NULL, 0, NULL, 0, heap, devId, NULL, |
4341 | 0 | WC_RNG_INIT_FLAG_NONE); |
4342 | 0 | } |
4343 | | |
4344 | | int wc_InitRng_ex2(WC_RNG* rng, void* heap, int devId, word32 flags) |
4345 | 0 | { |
4346 | 0 | return _InitRng(rng, NULL, 0, NULL, 0, NULL, 0, heap, devId, NULL, flags); |
4347 | 0 | } |
4348 | | |
4349 | | int wc_InitRngNonce_ex2(WC_RNG* rng, const byte* nonce, word32 nonceSz, |
4350 | | const byte *perso, word32 persoSz, |
4351 | | void* heap, int devId, word32 flags) |
4352 | 0 | { |
4353 | 0 | return _InitRng(rng, nonce, nonceSz, perso, persoSz, NULL, 0, |
4354 | 0 | heap, devId, NULL, flags); |
4355 | 0 | } |
4356 | | |
4357 | | int wc_InitRngNonce_UserSeed(WC_RNG* rng, |
4358 | | const byte* seed, word32 seedSz, |
4359 | | const byte* nonce, word32 nonceSz, |
4360 | | const byte *perso, word32 persoSz, |
4361 | | void* heap, int devId, word32 flags) |
4362 | 0 | { |
4363 | 0 | if (seed == NULL) |
4364 | 0 | return BAD_FUNC_ARG; |
4365 | 0 | if (rng == NULL) |
4366 | 0 | return BAD_FUNC_ARG; |
4367 | 0 | if (nonce == NULL && nonceSz != 0) |
4368 | 0 | return BAD_FUNC_ARG; |
4369 | 0 | if (perso == NULL && persoSz != 0) |
4370 | 0 | return BAD_FUNC_ARG; |
4371 | 0 | #ifdef HAVE_HASHDRBG |
4372 | 0 | if (seedSz < UserSeedSzFloor(flags)) |
4373 | 0 | return BAD_LENGTH_E; |
4374 | | #else |
4375 | | (void)seedSz; |
4376 | | #endif |
4377 | 0 | #ifndef WC_RNG_HAVE_RBGC |
4378 | | /* argument-legal calls must be refused if provenance tracking (RBGC) isn't |
4379 | | * available. */ |
4380 | 0 | (void)heap; |
4381 | 0 | (void)devId; |
4382 | 0 | (void)flags; |
4383 | 0 | return NOT_COMPILED_IN; |
4384 | | #else |
4385 | | return _InitRng(rng, nonce, nonceSz, perso, persoSz, seed, seedSz, |
4386 | | heap, devId, NULL, flags); |
4387 | | #endif |
4388 | 0 | } |
4389 | | |
4390 | | static WC_MAYBE_UNUSED int RngGenerateFailure(WC_RNG* rng, int ret) |
4391 | 0 | { |
4392 | 0 | if (! wc_RNG_DRBG_Present(rng)) { |
4393 | 0 | if (ret < 0) |
4394 | 0 | return ret; |
4395 | 0 | else if (ret > 0) |
4396 | 0 | return RNG_FAILURE_E; |
4397 | 0 | else |
4398 | 0 | return WRONG_TYPE_OBJECT_E; |
4399 | 0 | } |
4400 | | |
4401 | | /* DRBG_CONT_FAILURE signals a KAT failure (effectively, runtime detection |
4402 | | * of UB) and is always fatal, ultimately forcing the module into error |
4403 | | * state. */ |
4404 | 0 | if (ret == WC_NO_ERR_TRACE(DRBG_CONT_FAILURE)) { |
4405 | 0 | rng->status = DRBG_CONT_FAILED; |
4406 | 0 | return DRBG_CONT_FIPS_E; |
4407 | 0 | } |
4408 | | |
4409 | | /* BUSY_E and MEMORY_E signify that a context that can't wait (e.g. |
4410 | | * kernel atomic context) encountered a resource that requires waiting -- |
4411 | | * a holder's release, or the allocator's reclaim -- and are |
4412 | | * unconditionally retryable: the same call a moment later succeeds, so |
4413 | | * neither is a verdict on the DRBG, with or without reseed runway. |
4414 | | */ |
4415 | 0 | if ((ret == WC_NO_ERR_TRACE(BUSY_E)) || (ret == WC_NO_ERR_TRACE(MEMORY_E))) |
4416 | 0 | return ret; |
4417 | | |
4418 | 0 | #ifdef HAVE_HASHDRBG |
4419 | | /* Other failures with reseed runway remaining are returned without |
4420 | | * additional action. Internal protocol codes are mapped to NOT_READY_E. |
4421 | | * Typical percolated error here is MEMORY_E. */ |
4422 | 0 | if (rng->reseedCtr < WC_RESEED_INTERVAL) { |
4423 | 0 | if (ret <= 0) |
4424 | 0 | return ret; |
4425 | 0 | else if (ret == WC_NO_ERR_TRACE(DRBG_NEED_RESEED)) |
4426 | 0 | return NEEDS_RECOVERY_E; |
4427 | 0 | else |
4428 | 0 | return NOT_READY_E; |
4429 | 0 | } |
4430 | 0 | #endif |
4431 | | |
4432 | | /* When no reseed runway remains, we condemn the RNG for any failure, even |
4433 | | * retryable ones (except BUSY_E), necessitating full recovery by the |
4434 | | * caller. This is not required by SP-800-90, but is allowed by it, and is |
4435 | | * a useful heuristic. */ |
4436 | 0 | rng->status = DRBG_FAILED; |
4437 | | |
4438 | | /* SP 800-90B RCT and APT failures keep their own code. */ |
4439 | 0 | if ((ret == WC_NO_ERR_TRACE(ENTROPY_RT_E)) || |
4440 | 0 | (ret == WC_NO_ERR_TRACE(ENTROPY_APT_E))) |
4441 | 0 | { |
4442 | 0 | return ret; |
4443 | 0 | } |
4444 | | |
4445 | 0 | return RNG_FAILURE_E; |
4446 | 0 | } |
4447 | | |
4448 | | #ifdef WC_RNG_HAVE_GLOBAL_FALLBACK_RNG |
4449 | | |
4450 | | static int wc_RNG_global_fallback_init_local(const byte* seed, word32 seedSz, |
4451 | | const byte* nonce, word32 nonceSz, |
4452 | | const byte *perso, word32 persoSz, |
4453 | | void* heap, int devId, WC_RNG* seedRng, |
4454 | | word32 flags) |
4455 | | { |
4456 | | /* Unconditional: a standing latch is the usual reason the instance was |
4457 | | * freed, and the reinit below discharges it. */ |
4458 | | int ret = wc_RNG_lock_get_unconditional(&global_fallback_rng); |
4459 | | if (ret != 0) |
4460 | | return ret; |
4461 | | switch (global_fallback_rng.status) { |
4462 | | case WC_DRBG_NOT_INIT: |
4463 | | ret = 0; |
4464 | | break; |
4465 | | case WC_DRBG_OK: |
4466 | | ret = ALREADY_E; |
4467 | | break; |
4468 | | case WC_NO_ERR_TRACE(WC_DRBG_FAILED): |
4469 | | ret = RNG_FAILURE_E; |
4470 | | break; |
4471 | | case WC_NO_ERR_TRACE(WC_DRBG_CONT_FAILED): |
4472 | | ret = DRBG_CONT_FIPS_E; |
4473 | | break; |
4474 | | default: |
4475 | | ret = BAD_FUNC_ARG; |
4476 | | break; |
4477 | | } |
4478 | | if (ret != 0) { |
4479 | | (void)wc_RNG_lock_put(&global_fallback_rng, 0); |
4480 | | return ret; |
4481 | | } |
4482 | | |
4483 | | /* The hold taken above must stay live across the initialization, so the |
4484 | | * continuously asserted _HELD excludes contending callers until the |
4485 | | * explicit _lock_put below. On the first initialization the lock word is |
4486 | | * born here (_LOCK_INITIALLY); on every later one it is preserved |
4487 | | * (_PRESERVE_LOCK), which discharges an inherited latch by CAS at entry |
4488 | | * rather than erasing it: the instance is reachable by lease-free |
4489 | | * invalidation, so an initialized lock word is never reinitialized. */ |
4490 | | ret = _InitRng(&global_fallback_rng, |
4491 | | nonce, nonceSz, perso, persoSz, |
4492 | | seed, seedSz, heap, devId, seedRng, |
4493 | | flags | |
4494 | | WC_RNG_INIT_FLAG_LOCK_REQUIRED | |
4495 | | ((WOLFSSL_ATOMIC_LOAD(global_fallback_rng.lock) & |
4496 | | WC_RNG_LOCK_REQUIRED) ? |
4497 | | WC_RNG_INIT_FLAG_PRESERVE_LOCK : |
4498 | | WC_RNG_INIT_FLAG_LOCK_INITIALLY) |
4499 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
4500 | | | WC_RNG_INIT_FLAG_UPGRADE_FROM_NEXT_SEED |
4501 | | #endif |
4502 | | ); |
4503 | | { |
4504 | | int put_ret = wc_RNG_lock_put(&global_fallback_rng, 0); |
4505 | | if ((ret == 0) && (put_ret != 0)) |
4506 | | ret = put_ret; |
4507 | | } |
4508 | | |
4509 | | return ret; |
4510 | | } |
4511 | | |
4512 | | int wc_RNG_global_fallback_init(const byte* nonce, word32 nonceSz, |
4513 | | const byte *perso, word32 persoSz, |
4514 | | void* heap, int devId, word32 flags) |
4515 | | { |
4516 | | return wc_RNG_global_fallback_init_local(NULL, 0, nonce, nonceSz, |
4517 | | perso, persoSz, heap, devId, |
4518 | | NULL /* seedRng */, flags); |
4519 | | } |
4520 | | |
4521 | | int wc_RNG_global_fallback_init_user_seed(const byte* seed, word32 seedSz, |
4522 | | const byte* nonce, word32 nonceSz, |
4523 | | const byte *perso, word32 persoSz, |
4524 | | void* heap, int devId, word32 flags) |
4525 | | { |
4526 | | if (seed == NULL) |
4527 | | return BAD_FUNC_ARG; |
4528 | | #ifdef HAVE_HASHDRBG |
4529 | | /* as for wc_InitRngNonce_UserSeed(): zero included, so an argument |
4530 | | * mistake can't mint a primary-seeded fallback. */ |
4531 | | if (seedSz < UserSeedSzFloor(flags)) |
4532 | | return BAD_LENGTH_E; |
4533 | | #endif |
4534 | | return wc_RNG_global_fallback_init_local(seed, seedSz, nonce, nonceSz, |
4535 | | perso, persoSz, heap, devId, |
4536 | | NULL /* seedRng */, flags); |
4537 | | } |
4538 | | |
4539 | | /* Note, wc_RNG_global_fallback_get() doesn't lock the RNG, but it does enforce |
4540 | | * that it has been inited, which is therefore only possible with |
4541 | | * wc_RNG_global_fallback_init() or wc_RNG_global_fallback_init_user_seed(). |
4542 | | */ |
4543 | | WOLFSSL_API int wc_RNG_global_fallback_get(WC_RNG **rng) { |
4544 | | int ret; |
4545 | | if (rng == NULL) |
4546 | | return BAD_FUNC_ARG; |
4547 | | ret = wc_RNG_Status(&global_fallback_rng); |
4548 | | if (ret != 0) |
4549 | | return ret; |
4550 | | *rng = &global_fallback_rng; |
4551 | | return 0; |
4552 | | } |
4553 | | |
4554 | | int wc_RNG_global_fallback_free(void) |
4555 | | { |
4556 | | return wc_FreeRng(&global_fallback_rng); |
4557 | | } |
4558 | | |
4559 | | #endif /* WC_RNG_HAVE_GLOBAL_FALLBACK_RNG */ |
4560 | | |
4561 | | #ifdef WC_RNG_HAVE_LOCK |
4562 | | |
4563 | | /* Note, in CAS updates here, the stored value derives only from expected and |
4564 | | * the caller's arguments, never from a prior load. This assures no race with |
4565 | | * unlocked changes to any bits. |
4566 | | */ |
4567 | | |
4568 | | /* The orphan verdict for a held word. A _HELD word carrying _ORPHANED, or |
4569 | | * stamped with another process's pid, was held across a fork() by a holder |
4570 | | * absent here: a thread of the parent, or (by contract, equally void) the |
4571 | | * forking thread itself, which must neither use nor release a lease it held |
4572 | | * across the fork. The first contender to find the stale pid marks the word |
4573 | | * _ORPHANED, so the verdict is sticky after wc_RNG_invalidate_entropy() |
4574 | | * restamps the pid, and -- as the CAS winner, once -- applies the |
4575 | | * invalidation (purge-then-latch) so the aperture cannot serve a |
4576 | | * fork-duplicated seed. Returns OBJECT_ORPHANED_E for an orphan, 0 |
4577 | | * otherwise; *cur_lock is refreshed if the word moved underneath (a release |
4578 | | * by a live holder makes it no orphan, and the caller proceeds on the live |
4579 | | * word). |
4580 | | * |
4581 | | * The verdict licenses nothing to the contender: the instance's owner adopts |
4582 | | * the lease (wc_FreeRng_PreLocked(), then wc_InitRng_ex2() with |
4583 | | * WC_RNG_INIT_FLAG_PRESERVE_LOCK, which clears _ORPHANED with the latch); |
4584 | | * every other caller treats it as BUSY_E with no expectation that the hold |
4585 | | * will clear. A post-fork acquirer that has not yet restamped the pid can |
4586 | | * draw the verdict too; its first use recovers inline (the recovery's exit |
4587 | | * CAS clears _ORPHANED), so the false positive costs nothing. */ |
4588 | | static WC_MAYBE_UNUSED int RngLockOrphanCheck(WC_RNG* rng, |
4589 | | WC_RNG_lock_arg_t* cur_lock) |
4590 | | { |
4591 | | if (! (*cur_lock & WC_RNG_LOCK_HELD)) |
4592 | | return 0; |
4593 | | if (*cur_lock & WC_RNG_LOCK_ORPHANED) |
4594 | | return OBJECT_ORPHANED_E; |
4595 | | #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) |
4596 | | if (rng->pid != getpid()) { |
4597 | | int cas_ret; |
4598 | | /* cas_ret is 0 iff this call landed the mark: _BEGIN seeds it |
4599 | | * nonzero, the breaks below leave it so, and an aborted CAS (a |
4600 | | * port's retry clause) reports its own nonzero code. */ |
4601 | | WC_CAS_WITH_RETRY_BEGIN(&rng->lock, *cur_lock, cas_ret) { |
4602 | | if ((! (*cur_lock & WC_RNG_LOCK_HELD)) || |
4603 | | (*cur_lock & WC_RNG_LOCK_ORPHANED)) |
4604 | | { |
4605 | | /* released meanwhile (a live holder after all), or already |
4606 | | * marked by another contender */ |
4607 | | break; |
4608 | | } |
4609 | | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
4610 | | wolfSSL_Atomic_Uint_CompareExchange, &rng->lock, *cur_lock, |
4611 | | *cur_lock | WC_RNG_LOCK_ORPHANED, cas_ret); |
4612 | | } WC_CAS_WITH_RETRY_END; |
4613 | | if (! (*cur_lock & WC_RNG_LOCK_HELD)) |
4614 | | return 0; |
4615 | | /* The invalidation goes with the mark: ours if we landed it, |
4616 | | * otherwise the marker's (or, after an abort, the next contender's |
4617 | | * -- the stale pid still stands and it will retry). */ |
4618 | | if ((cas_ret == 0) && |
4619 | | (! (*cur_lock & WC_RNG_LOCK_ENTROPY_INVALIDATED))) |
4620 | | { |
4621 | | (void)wc_RNG_invalidate_entropy(rng); |
4622 | | } |
4623 | | return OBJECT_ORPHANED_E; |
4624 | | } |
4625 | | #else |
4626 | | (void)rng; |
4627 | | #endif |
4628 | | return 0; |
4629 | | } |
4630 | | |
4631 | | int wc_RNG_lock_get(WC_RNG* rng, WC_RNG_lock_arg_t extra_bits) |
4632 | | { |
4633 | | WC_RNG_lock_arg_t cur_lock; |
4634 | | |
4635 | | if (rng == NULL) |
4636 | | return BAD_FUNC_ARG; |
4637 | | |
4638 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
4639 | | /* outermost blocking layer, when constructed with _USE_FULL_MUTEX: |
4640 | | * contending getters sleep here rather than seeing BUSY_E. */ |
4641 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) { |
4642 | | if (wc_LockMutex(&rng->mutex) != 0) { |
4643 | | #ifdef WC_RNG_DEBUG_STATS |
4644 | | ++rng->_stats_locks_refused; /* racy */ |
4645 | | #endif |
4646 | | return BAD_MUTEX_E; |
4647 | | } |
4648 | | } |
4649 | | #endif |
4650 | | |
4651 | | /* extra_bits is allowed to assert WC_RNG_LOCK_REQUIRED, which is in the |
4652 | | * reserved section. */ |
4653 | | extra_bits &= ~((1U << WC_RNG_LOCK_EXTRA_SHIFT) - 1U) | |
4654 | | WC_RNG_LOCK_REQUIRED; |
4655 | | |
4656 | | cur_lock = WOLFSSL_ATOMIC_LOAD(rng->lock); |
4657 | | |
4658 | | { |
4659 | | int orphan_ret = RngLockOrphanCheck(rng, &cur_lock); |
4660 | | if (orphan_ret != 0) { |
4661 | | #ifdef WC_RNG_DEBUG_STATS |
4662 | | ++rng->_stats_locks_refused; /* racy */ |
4663 | | #endif |
4664 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
4665 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) |
4666 | | (void)wc_UnLockMutex(&rng->mutex); |
4667 | | #endif |
4668 | | return orphan_ret; |
4669 | | } |
4670 | | } |
4671 | | |
4672 | | if (cur_lock & WC_RNG_LOCK_ENTROPY_INVALIDATED) { |
4673 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
4674 | | WC_ATOMIC_INT_ARG NextSeedCurrent; |
4675 | | if ((rng->flags & WC_RNG_FLAG_UPGRADE_FROM_NEXT_SEED) && |
4676 | | (wc_RNG_DRBG_NextSeedCurrent(rng, &NextSeedCurrent) == 0) && |
4677 | | (NextSeedCurrent == WC_DRBG_NEXT_SEED_READY) |
4678 | | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
4679 | | && (rng->entropy_epoch == WOLFSSL_ATOMIC_LOAD(global_entropy_epoch)) |
4680 | | #endif |
4681 | | #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) |
4682 | | && (rng->pid == getpid()) |
4683 | | #endif |
4684 | | ) |
4685 | | { |
4686 | | /* cheap inline recovery available. */ |
4687 | | } |
4688 | | else |
4689 | | #endif |
4690 | | { |
4691 | | #ifdef WC_RNG_DEBUG_STATS |
4692 | | ++rng->_stats_locks_refused; /* racy */ |
4693 | | #endif |
4694 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
4695 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) |
4696 | | (void)wc_UnLockMutex(&rng->mutex); |
4697 | | #endif |
4698 | | return NEEDS_RECOVERY_E; |
4699 | | } |
4700 | | } |
4701 | | |
4702 | | if ((! (cur_lock & WC_RNG_LOCK_HELD)) && |
4703 | | (wolfSSL_Atomic_Uint_CompareExchange( |
4704 | | &rng->lock, &cur_lock, |
4705 | | cur_lock | WC_RNG_LOCK_HELD | extra_bits))) |
4706 | | { |
4707 | | #ifdef WC_RNG_DEBUG_STATS |
4708 | | ++rng->_stats_locks_taken; |
4709 | | #endif |
4710 | | |
4711 | | /* If we arrived here via _UPGRADE_FROM_NEXT_SEED with a |
4712 | | * pending NextSeed, there is a finite though minuscule chance that a |
4713 | | * second invalidation left the RNG without a banked seed to consume. |
4714 | | * In that case, the holder's generate falls through to the regular |
4715 | | * inline forced-reseed machinery. This is the same outcome as an |
4716 | | * invalidation landing immediately after a successful acquire. |
4717 | | */ |
4718 | | |
4719 | | return 0; |
4720 | | } |
4721 | | |
4722 | | #ifdef WC_RNG_DEBUG_STATS |
4723 | | ++rng->_stats_locks_refused; |
4724 | | #endif |
4725 | | |
4726 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
4727 | | /* CAS failure with the mutex held means a non-mutex claimant holds |
4728 | | * the latch (mixed-discipline use); back out the mutex. */ |
4729 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) |
4730 | | (void)wc_UnLockMutex(&rng->mutex); |
4731 | | #endif |
4732 | | |
4733 | | if (cur_lock & WC_RNG_LOCK_HELD) |
4734 | | return BUSY_E; |
4735 | | else if (cur_lock & WC_RNG_LOCK_ENTROPY_INVALIDATED) |
4736 | | return NEEDS_RECOVERY_E; |
4737 | | else /* not reachable */ |
4738 | | return UNEXPECTED_STATE_E; |
4739 | | } |
4740 | | |
4741 | | int wc_RNG_lock_get_conditional(WC_RNG* rng, |
4742 | | WC_RNG_lock_arg_t expected_extra_bits, |
4743 | | WC_RNG_lock_arg_t want_extra_bits) |
4744 | | { |
4745 | | WC_RNG_lock_arg_t cur_lock, expected; |
4746 | | |
4747 | | if (rng == NULL) |
4748 | | return BAD_FUNC_ARG; |
4749 | | |
4750 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
4751 | | /* outermost blocking layer, when constructed with _USE_FULL_MUTEX: |
4752 | | * contending getters sleep here rather than seeing BUSY_E. */ |
4753 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) { |
4754 | | if (wc_LockMutex(&rng->mutex) != 0) { |
4755 | | #ifdef WC_RNG_DEBUG_STATS |
4756 | | ++rng->_stats_locks_refused; /* racy */ |
4757 | | #endif |
4758 | | return BAD_MUTEX_E; |
4759 | | } |
4760 | | } |
4761 | | #endif |
4762 | | |
4763 | | /* *_extra_bits are allowed to assert WC_RNG_LOCK_REQUIRED, which is in the |
4764 | | * reserved section. Additionally, expected_extra_bits is allowed to |
4765 | | * include WC_RNG_LOCK_ENTROPY_INVALIDATED, for purposes of recovery. */ |
4766 | | expected_extra_bits &= ~((1U << WC_RNG_LOCK_EXTRA_SHIFT) - 1U) | |
4767 | | WC_RNG_LOCK_REQUIRED | WC_RNG_LOCK_ENTROPY_INVALIDATED; |
4768 | | want_extra_bits &= ~((1U << WC_RNG_LOCK_EXTRA_SHIFT) - 1U) | |
4769 | | WC_RNG_LOCK_REQUIRED; |
4770 | | |
4771 | | cur_lock = WOLFSSL_ATOMIC_LOAD(rng->lock); |
4772 | | |
4773 | | { |
4774 | | int orphan_ret = RngLockOrphanCheck(rng, &cur_lock); |
4775 | | if (orphan_ret != 0) { |
4776 | | #ifdef WC_RNG_DEBUG_STATS |
4777 | | ++rng->_stats_locks_refused; /* racy */ |
4778 | | #endif |
4779 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
4780 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) |
4781 | | (void)wc_UnLockMutex(&rng->mutex); |
4782 | | #endif |
4783 | | return orphan_ret; |
4784 | | } |
4785 | | } |
4786 | | |
4787 | | if ((cur_lock & WC_RNG_LOCK_ENTROPY_INVALIDATED) && |
4788 | | (! (expected_extra_bits & WC_RNG_LOCK_ENTROPY_INVALIDATED))) |
4789 | | { |
4790 | | #ifdef WC_RNG_DEBUG_STATS |
4791 | | ++rng->_stats_locks_refused; /* racy */ |
4792 | | #endif |
4793 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
4794 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) |
4795 | | (void)wc_UnLockMutex(&rng->mutex); |
4796 | | #endif |
4797 | | return NEEDS_RECOVERY_E; |
4798 | | } |
4799 | | |
4800 | | expected = (cur_lock & (((1U << WC_RNG_LOCK_EXTRA_SHIFT) - 1U) & |
4801 | | ~(WC_RNG_LOCK_HELD | |
4802 | | WC_RNG_LOCK_ENTROPY_INVALIDATED))) | |
4803 | | expected_extra_bits; |
4804 | | |
4805 | | if ((! (cur_lock & WC_RNG_LOCK_HELD)) && |
4806 | | (wolfSSL_Atomic_Uint_CompareExchange( |
4807 | | &rng->lock, &expected, |
4808 | | expected | WC_RNG_LOCK_HELD | want_extra_bits))) |
4809 | | { |
4810 | | #ifdef WC_RNG_DEBUG_STATS |
4811 | | ++rng->_stats_locks_taken; |
4812 | | #endif |
4813 | | return 0; |
4814 | | } |
4815 | | |
4816 | | #ifdef WC_RNG_DEBUG_STATS |
4817 | | ++rng->_stats_locks_refused; /* racy */ |
4818 | | #endif |
4819 | | |
4820 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
4821 | | /* CAS failure with the mutex held means a non-mutex claimant holds |
4822 | | * the latch (mixed-discipline use); back out the mutex. */ |
4823 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) |
4824 | | (void)wc_UnLockMutex(&rng->mutex); |
4825 | | #endif |
4826 | | |
4827 | | if ((cur_lock & WC_RNG_LOCK_ENTROPY_INVALIDATED) != |
4828 | | (expected & WC_RNG_LOCK_ENTROPY_INVALIDATED)) |
4829 | | { |
4830 | | return NEEDS_RECOVERY_E; |
4831 | | } |
4832 | | else if (expected & WC_RNG_LOCK_HELD) |
4833 | | return BUSY_E; |
4834 | | else |
4835 | | return UNEXPECTED_STATE_E; |
4836 | | } |
4837 | | |
4838 | | /* Trivial lock-getter for internal use: no policy conditions (latched and |
4839 | | * condemned instances are accepted); fails only on contention. */ |
4840 | | int wc_RNG_lock_get_unconditional(WC_RNG* rng) { |
4841 | | WC_RNG_lock_arg_t cur_lock; |
4842 | | if (rng == NULL) |
4843 | | return BAD_FUNC_ARG; |
4844 | | cur_lock = WOLFSSL_ATOMIC_LOAD(rng->lock); |
4845 | | if (cur_lock & WC_RNG_LOCK_HELD) { |
4846 | | int orphan_ret = RngLockOrphanCheck(rng, &cur_lock); |
4847 | | return (orphan_ret != 0) ? orphan_ret : BUSY_E; |
4848 | | } |
4849 | | if (! wolfSSL_Atomic_Uint_CompareExchange( |
4850 | | &rng->lock, &cur_lock, |
4851 | | cur_lock | WC_RNG_LOCK_HELD)) |
4852 | | { |
4853 | | return BUSY_E; |
4854 | | } |
4855 | | return 0; |
4856 | | } |
4857 | | |
4858 | | /* Trivial lock-putter for internal use. WC_RNG_LOCK_HELD is guaranteed set |
4859 | | * here (we hold it, and only the holder clears it), so the subtraction is an |
4860 | | * exact bit-clear with no borrow -- concurrent writes to other bits (e.g. a |
4861 | | * latch arrival) are preserved by the atomic RMW. Do not copy this idiom to |
4862 | | * any bit a leaseless actor can strip (e.g. _ENTROPY_RECOVERING): without the |
4863 | | * guaranteed-set precondition, the subtraction borrows and corrupts the |
4864 | | * word. */ |
4865 | | void wc_RNG_lock_put_unconditional(WC_RNG* rng) { |
4866 | | if (rng == NULL) |
4867 | | return; |
4868 | | (void)wolfSSL_Atomic_Uint_FetchSub(&rng->lock, WC_RNG_LOCK_HELD); |
4869 | | } |
4870 | | |
4871 | | int wc_RNG_lock_put(WC_RNG* rng, WC_RNG_lock_arg_t extra_bits) |
4872 | | { |
4873 | | WC_RNG_lock_arg_t cur_lock, new_lock; |
4874 | | int cas_ret; |
4875 | | if (rng == NULL) |
4876 | | return BAD_FUNC_ARG; |
4877 | | cur_lock = WOLFSSL_ATOMIC_LOAD(rng->lock); |
4878 | | if (! (cur_lock & WC_RNG_LOCK_HELD)) |
4879 | | return OBJECT_NOT_LOCKED_E; |
4880 | | |
4881 | | #ifdef WC_RNG_DEBUG_STATS |
4882 | | ++rng->_stats_locks_released; |
4883 | | #endif |
4884 | | |
4885 | | WC_CAS_WITH_RETRY_BEGIN(&rng->lock, cur_lock, cas_ret) { |
4886 | | /* _ORPHANED clears with _HELD: a release is a live holder's act, so |
4887 | | * a post-fork contender's verdict was premature. */ |
4888 | | new_lock = cur_lock & (((1U << WC_RNG_LOCK_EXTRA_SHIFT) - 1U) & |
4889 | | ~(WC_RNG_LOCK_HELD | WC_RNG_LOCK_ORPHANED)); |
4890 | | /* extra_bits is allowed to assert WC_RNG_LOCK_REQUIRED, which is in the |
4891 | | * reserved section. */ |
4892 | | extra_bits &= ~((1U << WC_RNG_LOCK_EXTRA_SHIFT) - 1U) | |
4893 | | WC_RNG_LOCK_REQUIRED; |
4894 | | new_lock |= extra_bits; |
4895 | | WC_CAS_WITH_RETRY_LOOP_FOREVER(wolfSSL_Atomic_Uint_CompareExchange, |
4896 | | &rng->lock, cur_lock, new_lock, cas_ret); |
4897 | | } WC_CAS_WITH_RETRY_END; |
4898 | | |
4899 | | if (cas_ret != 0) { |
4900 | | /* Aborted release (a port's retry clause): the latch is still ours |
4901 | | * and new_lock was never installed. Keep ownership consistent -- |
4902 | | * mutex included -- and percolate so the caller can retry the |
4903 | | * put. */ |
4904 | | return cas_ret; |
4905 | | } |
4906 | | |
4907 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
4908 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) |
4909 | | (void)wc_UnLockMutex(&rng->mutex); |
4910 | | #endif |
4911 | | |
4912 | | if (new_lock & WC_RNG_LOCK_ENTROPY_INVALIDATED) |
4913 | | return NEEDS_RECOVERY_E; |
4914 | | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
4915 | | /* An increment not yet propagated to this instance is the same obligation |
4916 | | * the latch carries, delivered lazily: report it here so that a holder |
4917 | | * whose last operation straddled the event learns of it at release. The |
4918 | | * read is unleased by design (see rng_entropy_event_propagate()). */ |
4919 | | if (rng->entropy_epoch != WOLFSSL_ATOMIC_LOAD(global_entropy_epoch)) |
4920 | | return NEEDS_RECOVERY_E; |
4921 | | #endif |
4922 | | return 0; |
4923 | | } |
4924 | | |
4925 | | int wc_RNG_lock_put_conditional(WC_RNG* rng, |
4926 | | WC_RNG_lock_arg_t expected_extra_bits, |
4927 | | WC_RNG_lock_arg_t want_extra_bits) |
4928 | | { |
4929 | | int cas_ret; |
4930 | | WC_CAS_WITH_RETRY_EXTRA_DECLS; |
4931 | | WC_RNG_lock_arg_t cur_lock, expected, new_lock; |
4932 | | |
4933 | | if (rng == NULL) |
4934 | | return BAD_FUNC_ARG; |
4935 | | |
4936 | | cur_lock = WOLFSSL_ATOMIC_LOAD(rng->lock); |
4937 | | if (! (cur_lock & WC_RNG_LOCK_HELD)) |
4938 | | return OBJECT_NOT_LOCKED_E; |
4939 | | |
4940 | | #ifdef WC_RNG_DEBUG_STATS |
4941 | | ++rng->_stats_locks_released; |
4942 | | #endif |
4943 | | |
4944 | | /* Note this CAS loop doesn't use WC_CAS_WITH_RETRY_*() (non-conformant code |
4945 | | * pattern), so the WC_CAS_WITH_RETRY_* hook macros are invoked directly. */ |
4946 | | for (;;) { |
4947 | | /* as in wc_RNG_lock_put(), _ORPHANED clears with _HELD */ |
4948 | | new_lock = cur_lock & (((1U << WC_RNG_LOCK_EXTRA_SHIFT) - 1U) & |
4949 | | ~(WC_RNG_LOCK_HELD | WC_RNG_LOCK_ORPHANED)); |
4950 | | /* want_extra_bits is allowed to assert WC_RNG_LOCK_REQUIRED, which is |
4951 | | * in the reserved section. */ |
4952 | | want_extra_bits &= ~((1U << WC_RNG_LOCK_EXTRA_SHIFT) - 1U) | |
4953 | | WC_RNG_LOCK_REQUIRED; |
4954 | | new_lock |= want_extra_bits; |
4955 | | |
4956 | | /* The latch bits (and _ORPHANED, a post-fork contender's mark) are |
4957 | | * transient and lease-free callers may flip them under the holder, |
4958 | | * so they are carried through from the live word rather than |
4959 | | * compared. */ |
4960 | | expected = WC_RNG_LOCK_HELD | expected_extra_bits | |
4961 | | (cur_lock & (WC_RNG_LOCK_ENTROPY_INVALIDATED | |
4962 | | WC_RNG_LOCK_ENTROPY_RECOVERING | |
4963 | | WC_RNG_LOCK_ORPHANED)); |
4964 | | |
4965 | | new_lock |= (expected_extra_bits & WC_RNG_LOCK_REQUIRED) | |
4966 | | (cur_lock & (WC_RNG_LOCK_ENTROPY_INVALIDATED | |
4967 | | WC_RNG_LOCK_ENTROPY_RECOVERING)); |
4968 | | |
4969 | | /* release preserves the sticky bit if the caller reports it held */ |
4970 | | if (wolfSSL_Atomic_Uint_CompareExchange( |
4971 | | &rng->lock, &expected, |
4972 | | new_lock)) |
4973 | | { |
4974 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
4975 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) |
4976 | | (void)wc_UnLockMutex(&rng->mutex); |
4977 | | #endif |
4978 | | if (new_lock & WC_RNG_LOCK_ENTROPY_INVALIDATED) |
4979 | | return NEEDS_RECOVERY_E; |
4980 | | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
4981 | | /* as in wc_RNG_lock_put() */ |
4982 | | if (rng->entropy_epoch != WOLFSSL_ATOMIC_LOAD(global_entropy_epoch)) |
4983 | | return NEEDS_RECOVERY_E; |
4984 | | #endif |
4985 | | return 0; |
4986 | | } |
4987 | | /* Retry only when the mismatch is confined to the transient latch |
4988 | | * bits; a mismatch anywhere else (_HELD, _REQUIRED, the extra |
4989 | | * section) is the caller's error. */ |
4990 | | if ((expected & ~(WC_RNG_LOCK_ENTROPY_INVALIDATED | |
4991 | | WC_RNG_LOCK_ENTROPY_RECOVERING | |
4992 | | WC_RNG_LOCK_ORPHANED)) != |
4993 | | ((WC_RNG_LOCK_HELD | expected_extra_bits) & |
4994 | | ~(WC_RNG_LOCK_ENTROPY_INVALIDATED | |
4995 | | WC_RNG_LOCK_ENTROPY_RECOVERING | |
4996 | | WC_RNG_LOCK_ORPHANED))) |
4997 | | { |
4998 | | break; |
4999 | | } |
5000 | | |
5001 | | cur_lock = expected; |
5002 | | |
5003 | | cas_ret = WC_CAS_WITH_RETRY_FOREVER_CLAUSE; |
5004 | | if (cas_ret != 0) |
5005 | | return cas_ret; |
5006 | | WC_CAS_WITH_RETRY_ITER_CLAUSE(&rng->lock, cur_lock, new_lock, cas_ret); |
5007 | | } |
5008 | | |
5009 | | /* conditional release failed: the caller is still the holder, at both |
5010 | | * layers -- the mutex stays held. */ |
5011 | | |
5012 | | #ifdef WC_RNG_DEBUG_STATS |
5013 | | --rng->_stats_locks_released; |
5014 | | #endif |
5015 | | |
5016 | | return UNEXPECTED_STATE_E; |
5017 | | } |
5018 | | |
5019 | | int wc_RNG_lock_read(const WC_RNG* rng, WC_RNG_lock_arg_t* state) |
5020 | | { |
5021 | | if ((rng == NULL) || (state == NULL)) |
5022 | | return BAD_FUNC_ARG; |
5023 | | *state = WOLFSSL_ATOMIC_LOAD(rng->lock); |
5024 | | return 0; |
5025 | | } |
5026 | | |
5027 | | int wc_RNG_lock_set_extra(WC_RNG* rng, WC_RNG_lock_arg_t extra_bits) |
5028 | | { |
5029 | | WC_RNG_lock_arg_t cur_lock, new_lock; |
5030 | | int cas_ret; |
5031 | | if (rng == NULL) |
5032 | | return BAD_FUNC_ARG; |
5033 | | cur_lock = WOLFSSL_ATOMIC_LOAD(rng->lock); |
5034 | | |
5035 | | WC_CAS_WITH_RETRY_BEGIN(&rng->lock, cur_lock, cas_ret) { |
5036 | | new_lock = cur_lock & ((1U << WC_RNG_LOCK_EXTRA_SHIFT) - 1U); |
5037 | | /* extra_bits is allowed to assert WC_RNG_LOCK_REQUIRED, which is in the |
5038 | | * reserved section. */ |
5039 | | extra_bits &= ~((1U << WC_RNG_LOCK_EXTRA_SHIFT) - 1U) | |
5040 | | WC_RNG_LOCK_REQUIRED; |
5041 | | new_lock |= extra_bits; |
5042 | | |
5043 | | WC_CAS_WITH_RETRY_LOOP_FOREVER(wolfSSL_Atomic_Uint_CompareExchange, |
5044 | | &rng->lock, cur_lock, new_lock, cas_ret); |
5045 | | } WC_CAS_WITH_RETRY_END; |
5046 | | /* 0 unless a port's retry clause aborted; the lock word is then |
5047 | | * untouched, so percolation is the whole handling. */ |
5048 | | return cas_ret; |
5049 | | } |
5050 | | |
5051 | | int wc_RNG_lock_add_extra(WC_RNG* rng, WC_RNG_lock_arg_t extra_bits) |
5052 | | { |
5053 | | WC_RNG_lock_arg_t cur_lock; |
5054 | | int cas_ret; |
5055 | | if (rng == NULL) |
5056 | | return BAD_FUNC_ARG; |
5057 | | cur_lock = WOLFSSL_ATOMIC_LOAD(rng->lock); |
5058 | | |
5059 | | /* extra_bits is allowed to assert WC_RNG_LOCK_REQUIRED, which is in the |
5060 | | * reserved section. */ |
5061 | | extra_bits &= ~((1U << WC_RNG_LOCK_EXTRA_SHIFT) - 1U) | |
5062 | | WC_RNG_LOCK_REQUIRED; |
5063 | | |
5064 | | WC_CAS_WITH_RETRY_BEGIN(&rng->lock, cur_lock, cas_ret) { |
5065 | | WC_CAS_WITH_RETRY_LOOP_FOREVER(wolfSSL_Atomic_Uint_CompareExchange, |
5066 | | &rng->lock, cur_lock, |
5067 | | cur_lock | extra_bits, cas_ret); |
5068 | | } WC_CAS_WITH_RETRY_END; |
5069 | | /* see wc_RNG_lock_set_extra() re nonzero cas_ret. */ |
5070 | | return cas_ret; |
5071 | | } |
5072 | | |
5073 | | int wc_RNG_lock_clear_extra(WC_RNG* rng, WC_RNG_lock_arg_t extra_bits) |
5074 | | { |
5075 | | WC_RNG_lock_arg_t cur_lock; |
5076 | | int cas_ret; |
5077 | | if (rng == NULL) |
5078 | | return BAD_FUNC_ARG; |
5079 | | if (extra_bits & WC_RNG_LOCK_REQUIRED) { |
5080 | | /* WC_RNG_LOCK_REQUIRED is sticky by contract */ |
5081 | | return BAD_FUNC_ARG; |
5082 | | } |
5083 | | cur_lock = WOLFSSL_ATOMIC_LOAD(rng->lock); |
5084 | | |
5085 | | extra_bits &= ~((1U << WC_RNG_LOCK_EXTRA_SHIFT) - 1U); |
5086 | | |
5087 | | WC_CAS_WITH_RETRY_BEGIN(&rng->lock, cur_lock, cas_ret) { |
5088 | | WC_CAS_WITH_RETRY_LOOP_FOREVER(wolfSSL_Atomic_Uint_CompareExchange, |
5089 | | &rng->lock, cur_lock, |
5090 | | cur_lock & ~extra_bits, cas_ret); |
5091 | | } WC_CAS_WITH_RETRY_END; |
5092 | | /* see wc_RNG_lock_set_extra() re nonzero cas_ret. */ |
5093 | | return cas_ret; |
5094 | | } |
5095 | | #endif /* WC_RNG_HAVE_LOCK */ |
5096 | | |
5097 | 0 | WOLFSSL_API int wc_RNG_invalidate_entropy(WC_RNG* rng) { |
5098 | 0 | int ret = 0; |
5099 | 0 | word32 status_at_start; |
5100 | | #ifdef WC_RNG_HAVE_LOCK |
5101 | | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
5102 | | /* Load the event epoch before any purge: an increment mid-delivery leaves |
5103 | | * the stamp stale, forcing a conservative propagation. */ |
5104 | | WC_ATOMIC_UINT_ARG ev_epoch = WOLFSSL_ATOMIC_LOAD(global_entropy_epoch); |
5105 | | #endif |
5106 | | #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) |
5107 | | pid_t my_pid = getpid(); |
5108 | | #endif |
5109 | | #endif |
5110 | |
|
5111 | 0 | if (rng == NULL) |
5112 | 0 | return BAD_FUNC_ARG; |
5113 | | |
5114 | 0 | status_at_start = rng->status; |
5115 | 0 | if (status_at_start == WC_DRBG_NOT_INIT) { |
5116 | | #ifdef WC_RNG_HAVE_LOCK |
5117 | | /* no state to purge, but the lock word is live across a _PRESERVE_LOCK |
5118 | | * reinit and is the record: mark it, so an event that lands mid-reinit |
5119 | | * latches the reborn object. _InitRng() clears an inherited latch |
5120 | | * before it acquires any material, so a latch set before the reinit |
5121 | | * began is discharged by the fresh instantiation, and one set after the |
5122 | | * reinit began survives it, forcing the first generate on the reborn |
5123 | | * instance to reseed. Either way the event is not lost. |
5124 | | */ |
5125 | | goto only_mark_lock_word; |
5126 | | #else |
5127 | | /* not a usable instance, nothing instantiated, nothing to mark stale, |
5128 | | * vacuously complete. */ |
5129 | 0 | return 0; |
5130 | 0 | #endif |
5131 | 0 | } |
5132 | | |
5133 | 0 | #if defined(HAVE_HASHDRBG) && !defined(WC_RNG_HAVE_LOCK) |
5134 | | /* Without the lock facility there is no latch, so a saturated reseedCtr |
5135 | | * (and, if configured, entropy_epoch) is the only way to force invalidation |
5136 | | * semantics on the consumer. With it, the latch asserted below in the |
5137 | | * WC_RNG_HAVE_LOCK CAS is tested by every generate, leased or not, so the |
5138 | | * counter stays what SP 800-90A says it is -- reseed budget -- and |
5139 | | * invalidation never spends runway. Either way the purges here are best |
5140 | | * effort, and are followed by deterministic purges in Hash_DRBG_Reseed() |
5141 | | * |
5142 | | * If a lock is held, the holder will learn of the invalidation no later |
5143 | | * than unlock time (wc_RNG_lock_put() reports both the latch and, with |
5144 | | * the entropy epoch, an unpropagated increment), whereupon it can |
5145 | | * implement its own mitigation strategy. |
5146 | | * |
5147 | | * In practical terms, the holder's first post-invalidation call to |
5148 | | * wc_RNG_GenerateBlock() is likely to detect the invalidation via the |
5149 | | * wc_RNG_entropy_needs_recovery() check in wc_RNG_GenerateBlock(), and |
5150 | | * recover inline. |
5151 | | * |
5152 | | * In either case, the state purges here are best effort, and are followed |
5153 | | * by deterministic purges in Hash_DRBG_Reseed() (the sole recovery path |
5154 | | * from _ENTROPY_INVALIDATED), strictly serialized against concurrent |
5155 | | * recovery attempts. |
5156 | | */ |
5157 | | /* (No DRBG -- direct-RDRAND et al. -- schedules nothing and succeeds: |
5158 | | * nothing whose staleness the mark would record. Any applicable |
5159 | | * auxiliary-state purges below still run.) */ |
5160 | 0 | ret = wc_RNG_DRBG_ScheduleReseed_local(rng); |
5161 | 0 | #endif /* HAVE_HASHDRBG && !WC_RNG_HAVE_LOCK */ |
5162 | |
|
5163 | | #ifdef WC_RNG_HAVE_POOL |
5164 | | { |
5165 | | int ret2 = PoolPurge(rng); |
5166 | | if ((ret2 != 0) && (ret == 0)) |
5167 | | ret = ret2; |
5168 | | } |
5169 | | #endif |
5170 | |
|
5171 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
5172 | | NextStirPurge(rng); |
5173 | | |
5174 | | { |
5175 | | int ret2 = NextSeedPurge(rng); |
5176 | | if ((ret2 != 0) && |
5177 | | (ret2 != WC_NO_ERR_TRACE(ALREADY_E)) && |
5178 | | (ret == 0)) |
5179 | | { |
5180 | | ret = ret2; |
5181 | | } |
5182 | | } |
5183 | | #endif /* WC_RNG_HAVE_NEXT_SEED */ |
5184 | |
|
5185 | | #ifdef WC_RNG_HAVE_LOCK |
5186 | | only_mark_lock_word: |
5187 | | |
5188 | | /* Assert _ENTROPY_INVALIDATED last: latch-after-purge makes the latch a |
5189 | | * provenance marker. Any consumer that observes the latch observes |
5190 | | * post-purge apertures, so a READY it then claims necessarily postdates |
5191 | | * this event; a consumer that raced ahead of the latch loses its claim |
5192 | | * to the purge above and is refused at its release CAS (see |
5193 | | * wc_RNG_DRBG_NextSeedNow_Nonce()); and an event landing mid-reseed |
5194 | | * strips _ENTROPY_RECOVERING here, so the recovery's exit CAS refuses |
5195 | | * the clear. No interleaving recovers from pre-event material. */ |
5196 | | |
5197 | | { |
5198 | | WC_RNG_lock_arg_t cur_lock; |
5199 | | int cas_ret; |
5200 | | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&rng->lock, cur_lock, cas_ret) { |
5201 | | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
5202 | | wolfSSL_Atomic_Uint_CompareExchange, &rng->lock, cur_lock, |
5203 | | (cur_lock & ~WC_RNG_LOCK_ENTROPY_RECOVERING) | |
5204 | | WC_RNG_LOCK_ENTROPY_INVALIDATED, |
5205 | | cas_ret); |
5206 | | } WC_CAS_WITH_RETRY_END; |
5207 | | if ((cas_ret != 0) && (ret == 0)) |
5208 | | ret = cas_ret; |
5209 | | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
5210 | | if (cas_ret == 0) { |
5211 | | /* Stamp the propagated epoch: one increment delivers once, and the |
5212 | | * latch carries the recovery obligation from here (see |
5213 | | * wc_RNG_entropy_needs_recovery()). Plain write, racing a |
5214 | | * lease-holder's own stamp in Hash_DRBG_Reseed(): benign both |
5215 | | * ways -- the loser costs at worst one extra propagation or |
5216 | | * one extra recovery, never unsound output. The member is a |
5217 | | * plain word rather than an atomic by design: some target |
5218 | | * toolchains reject the atomic accessors on a non-atomic struct |
5219 | | * member, the single writer under the lease needs no RMW, and |
5220 | | * leaseless readers tolerate staleness as above. */ |
5221 | | rng->entropy_epoch = ev_epoch; |
5222 | | } |
5223 | | #endif |
5224 | | #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) |
5225 | | if (cas_ret == 0) { |
5226 | | /* Update the PID: one change delivers once, and the latch carries |
5227 | | * the recovery obligation from here. */ |
5228 | | rng->pid = my_pid; |
5229 | | } |
5230 | | #endif |
5231 | | if (cas_ret != 0) { |
5232 | | /* If the latch failed, the RNG must be condemned, because the latch |
5233 | | * is the only race-free mark of invalidation (the reseedCtr is |
5234 | | * subject to lost-update races). DRBG_FAILED is the remaining stop |
5235 | | * no interleaving can lift: sticky until a full recovery. |
5236 | | * |
5237 | | * This is the one leaseless outsider write of DRBG_FAILED; the race |
5238 | | * against a lease-holder is benign both ways (a completing reseed's |
5239 | | * OK overwrite means the state was genuinely re-derived from |
5240 | | * post-event material; a FAILED overwrite of OK costs one spurious |
5241 | | * reinit, never unsound output). In the kernel build, bank |
5242 | | * instances are retired and recovered by the entropy daemon's |
5243 | | * out-of-service pass; a leaf's owner sees hard RNG_FAILURE_E and |
5244 | | * reinitializes. |
5245 | | */ |
5246 | | if (status_at_start != WC_DRBG_NOT_INIT) |
5247 | | rng->status = DRBG_FAILED; |
5248 | | } |
5249 | | } |
5250 | | #else /* !WC_RNG_HAVE_LOCK */ |
5251 | 0 | if ((ret != 0) && (rng->status == DRBG_OK)) { |
5252 | 0 | rng->status = DRBG_FAILED; /* no latch exists, and the purge encountered |
5253 | | * a complication -- shut down the RNG. */ |
5254 | 0 | return RNG_FAILURE_E; |
5255 | 0 | } |
5256 | 0 | #endif /* !WC_RNG_HAVE_LOCK */ |
5257 | | |
5258 | 0 | return ret; |
5259 | 0 | } |
5260 | | |
5261 | | /* Propagate any pending global entropy event (epoch increment or PID change) |
5262 | | * into this instance, converting {stale epoch, unlatched} to {latched, swept}: |
5263 | | * wc_RNG_invalidate_entropy() purges the pool and both apertures, asserts the |
5264 | | * latch last (latch-after-purge), and stamps the propagated epoch, so one |
5265 | | * increment delivers once. Idempotent, and callable without owning the |
5266 | | * instance. Returns 0 when no event is pending; otherwise NEEDS_RECOVERY_E -- |
5267 | | * if delivery failed, the instance was condemned (latch-or-condemn), and that |
5268 | | * verdict surfaces via wc_RNG_Status(). */ |
5269 | | static WC_MAYBE_UNUSED int rng_entropy_event_propagate(WC_RNG* rng) |
5270 | 0 | { |
5271 | 0 | int ret = 0; |
5272 | 0 | if (! wc_RNG_DRBG_Present(rng)) |
5273 | 0 | return 0; |
5274 | 0 | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
5275 | 0 | if (rng->entropy_epoch != WOLFSSL_ATOMIC_LOAD(global_entropy_epoch)) |
5276 | 0 | ret = NEEDS_RECOVERY_E; |
5277 | 0 | #endif |
5278 | 0 | #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) |
5279 | 0 | if (rng->pid != getpid()) |
5280 | 0 | ret = NEEDS_RECOVERY_E; |
5281 | 0 | #endif |
5282 | |
|
5283 | 0 | if (ret == 0) |
5284 | 0 | return 0; |
5285 | | |
5286 | 0 | ret = wc_RNG_invalidate_entropy(rng); |
5287 | 0 | if (ret == 0) |
5288 | 0 | return NEEDS_RECOVERY_E; |
5289 | 0 | else |
5290 | 0 | return ret; |
5291 | 0 | } |
5292 | | |
5293 | 444k | WOLFSSL_API int wc_RNG_entropy_needs_recovery(WC_RNG* rng) { |
5294 | 444k | int ret; |
5295 | 444k | if (rng == NULL) |
5296 | 0 | return BAD_FUNC_ARG; |
5297 | 444k | ret = wc_RNG_Status(rng); |
5298 | 444k | if ((ret != 0) && (ret != WC_NO_ERR_TRACE(NOT_READY_E))) |
5299 | 0 | return ret; |
5300 | 444k | if (! wc_RNG_DRBG_Present(rng)) |
5301 | 0 | return 0; |
5302 | 444k | #if defined(WC_RNG_HAVE_ENTROPY_EPOCH) || \ |
5303 | 444k | (defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID)) |
5304 | | #if defined(WC_RNG_HAVE_LOCK) && defined(HAVE_HASHDRBG) |
5305 | | /* Detection is also delivery: a stale epoch is materialized into the |
5306 | | * latched, swept state here, so that every aperture consulted after a |
5307 | | * nonzero return is post-purge. */ |
5308 | | ret = rng_entropy_event_propagate(rng); |
5309 | | if (ret != 0) |
5310 | | return ret; |
5311 | | #else |
5312 | 444k | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
5313 | 444k | if (rng->entropy_epoch != WOLFSSL_ATOMIC_LOAD(global_entropy_epoch)) |
5314 | 0 | return NEEDS_RECOVERY_E; |
5315 | 444k | #endif |
5316 | 444k | #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) |
5317 | 444k | if (rng->pid != getpid()) |
5318 | 0 | return NEEDS_RECOVERY_E; |
5319 | 444k | #endif |
5320 | 444k | #endif |
5321 | 444k | #endif |
5322 | | #ifdef WC_RNG_HAVE_LOCK |
5323 | | if (WOLFSSL_ATOMIC_LOAD(rng->lock) & WC_RNG_LOCK_ENTROPY_INVALIDATED) |
5324 | | return NEEDS_RECOVERY_E; |
5325 | | #endif |
5326 | 444k | #ifdef HAVE_HASHDRBG |
5327 | 444k | if (rng->reseedCtr >= WC_RESEED_INTERVAL) |
5328 | 0 | return NEEDS_RECOVERY_E; |
5329 | 444k | #endif |
5330 | | |
5331 | 444k | return 0; |
5332 | 444k | } |
5333 | | |
5334 | | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
5335 | 0 | WOLFSSL_API WC_ATOMIC_UINT_ARG wc_RNG_global_invalidate_entropy(void) { |
5336 | 0 | return wolfSSL_Atomic_Uint_AddFetch(&global_entropy_epoch, 1U); |
5337 | 0 | } |
5338 | | |
5339 | 0 | WC_ATOMIC_UINT_ARG wc_RNG_get_global_entropy_epoch(void) { |
5340 | 0 | return WOLFSSL_ATOMIC_LOAD(global_entropy_epoch); |
5341 | 0 | } |
5342 | | #endif |
5343 | | |
5344 | | #ifdef WC_RNG_HAVE_FREE_HOOK |
5345 | | /* This routine is used for mitigation of RNG cloning events, particularly by |
5346 | | * hypervisors. */ |
5347 | | WOLFSSL_API int wc_RNG_register_free_hook(WC_RNG* rng, |
5348 | | wc_RNG_free_hook_cb_t free_hook, |
5349 | | void *arg) |
5350 | | { |
5351 | | if (rng == NULL) |
5352 | | return BAD_FUNC_ARG; |
5353 | | rng->free_hook = free_hook; |
5354 | | rng->free_hook_arg = arg; |
5355 | | return 0; |
5356 | | } |
5357 | | #endif /* WC_RNG_HAVE_FREE_HOOK */ |
5358 | | |
5359 | | #ifdef WC_RNG_HAVE_POOL |
5360 | | |
5361 | | /* In-boundary asynchronous DRBG output pool (wc_RNG_Pool_*()): a circular |
5362 | | * buffer of pre-generated output, held and zeroized under the module's CSP |
5363 | | * discipline and consumed destructively (each delivered or discarded byte |
5364 | | * is burned). |
5365 | | * |
5366 | | * Writer state coherence is enforced with a CAS; reader exclusivity is |
5367 | | * enforced by the umbrella WC_RNG.lock, or absent that, by caller contract. |
5368 | | * |
5369 | | * The reader is lock-free -- two plain loads of {head, epoch} bracketing |
5370 | | * the copy, then a plain store of {tail, epoch} exclusively written by the |
5371 | | * reader. The writer CASes its publication, carrying the epoch it read; a |
5372 | | * purge during its generate results in an epoch mismatch, whereupon BUSY_E |
5373 | | * is returned to the caller. |
5374 | | * |
5375 | | * _Alloc() sizes the ring (2..32767 bytes), with positions running in [0, |
5376 | | * 2*size) and packing into 16 bits. _Collect() tops up the pool from rng's |
5377 | | * own DRBG; _Collect2() tops dest's ring up from an independent src |
5378 | | * instance, generating directly into the free span and publishing with a |
5379 | | * single CAS -- callable WITHOUT any lease on dest (contending writers |
5380 | | * return BUSY_E on CAS failure; the final write of every published byte is |
5381 | | * certified DRBG output). _Extract() (lease-holder only) delivers up to *n |
5382 | | * bytes destructively, burning each byte on the way out, and fails closed |
5383 | | * on an out-of-service DRBG; *n = 0 on empty, for fall-through to a direct |
5384 | | * generate. _Current() reports the published count (racy snapshot). No |
5385 | | * special free API: the ring lives until wc_FreeRng(), eliminating |
5386 | | * deallocation races by construction. |
5387 | | * |
5388 | | * Two words track FIFO state: |
5389 | | * |
5390 | | * poolHead = {head, epoch} written by the writer (publish, CAS) and by |
5391 | | * PoolPurge() (epoch bump, CAS) |
5392 | | * poolTail = {tail, epoch} written by the reader alone, plain store |
5393 | | * |
5394 | | * Position and epoch share one word, so the pairs are always mutually |
5395 | | * consistent -- there is no torn snapshot to reason about. |
5396 | | * |
5397 | | * head and tail are free-running positions in [0, 2*poolSize), advanced by |
5398 | | * conditional subtraction -- no division, and no modulus constraint on |
5399 | | * poolSize. The writer publishes only into free space, so head can never |
5400 | | * pass tail + poolSize and the two can never lap. |
5401 | | * |
5402 | | * wc_RNG_lock_put{,_conditional}() return NEEDS_RECOVERY_E to the reader if |
5403 | | * an invalidation occurred after lock but before release (contingent on |
5404 | | * WC_RNG_HAVE_LOCK). State coherence for the lock-free writers and purgers |
5405 | | * hinges on the CAS and epoch counter protocol in PoolPurge() and |
5406 | | * wc_RNG_Pool_Collect2(). |
5407 | | * |
5408 | | * The reader never writes poolHead and never CASes anything, leveraging |
5409 | | * exclusivity enforced by WC_RNG.lock or arranged by caller contract. It |
5410 | | * brackets its copy with leading and trailing loads of poolHead and |
5411 | | * compares the epoch: a purge that landed anywhere in between is caught, |
5412 | | * providing for early, pre-unlock failure upon invalidation. The epoch is |
5413 | | * 16 bits, so defeating this early failure requires exactly k * 65536 |
5414 | | * purges (k a positive integer) inside one copy-and-burn of at most |
5415 | | * poolSize bytes (implausible). |
5416 | | * |
5417 | | * PoolPurge() bumps epoch and touches nothing else. It does not reset the |
5418 | | * counters: leaving them monotonic keeps the reader's burn span [tail, |
5419 | | * tail+m) and the writer's generate span [head, head+m') disjoint across |
5420 | | * the event, so a purge can never cause one to erase the other's bytes. |
5421 | | * Stale pre-purge material is discarded by the reader instead, which |
5422 | | * resynchronizes tail to head on any epoch change -- whether it observed |
5423 | | * the purge mid-serve or merely arrives afterwards. |
5424 | | * |
5425 | | * The writer still CASes, and its publication carries the epoch it read. A |
5426 | | * purge during its generate makes that CAS fail, and it abandons rather |
5427 | | * than publishing material that predates the event. This protocol is |
5428 | | * airtight in the same sense as the credited next-seed aperture |
5429 | | * (NextSeedPurge()): no invalidation can go unobserved by either side. |
5430 | | * |
5431 | | * Lifecycle is arbitrated by the same word. poolHead carries a 2-bit |
5432 | | * state above the epoch: |
5433 | | * |
5434 | | * LIVE the ring is allocated and idle; |
5435 | | * CLAIMED a party is mutating the buffer or the pointer -- a |
5436 | | * writer across its generate, or _Alloc() across its two |
5437 | | * stores; |
5438 | | * UNALLOC no ring (the sentinel _InitRng() installs, atomically and |
5439 | | * outside its wipe, so the word never transits a forgeable |
5440 | | * LIVE-and-empty 0); |
5441 | | * TORNDOWN freed by wc_FreeRng(); refuses _Alloc() until the next |
5442 | | * _InitRng() installs UNALLOC, so a collector cannot |
5443 | | * re-equip an instance between its free and its wipe. |
5444 | | * |
5445 | | * A writer claims by one CAS at entry (CLAIMED already set: BUSY_E, no |
5446 | | * generate wasted -- writers are mutually exclusive by construction) and |
5447 | | * releases by CAS at every exit. Only PoolPurge() may change the word |
5448 | | * while it is CLAIMED, and it preserves the state bits. wc_FreeRng() |
5449 | | * takes LIVE -> TORNDOWN by one CAS before any irreversible teardown |
5450 | | * step; a held claim makes that CAS fail and wc_FreeRng() returns |
5451 | | * BUSY_E having mutated nothing -- the established "try once, caller |
5452 | | * retries" contract, never a spin (the writer may be a preemptible |
5453 | | * kthread; a spin from atomic context on it is the one spin the kernel |
5454 | | * forbids). The writer's hold is bounded because it generates under |
5455 | | * WC_RNG_FLAG_FAIL_FAST: one Hash_DRBG_Generate(), no in-line reseed. |
5456 | | * Nothing here contends with the reader: the reader never touches the |
5457 | | * state bits, and the extract side of a lock-required instance is the |
5458 | | * lease holder, exactly as before. |
5459 | | */ |
5460 | | |
5461 | | wc_static_assert(sizeof(WC_ATOMIC_UINT_ARG) >= 4); |
5462 | | |
5463 | | /* position -> ring index. Positions run in [0, 2*poolSize). */ |
5464 | | static WC_INLINE word32 PoolAt(word32 pos, word32 poolSize) |
5465 | | { |
5466 | | return (pos >= poolSize) ? (pos - poolSize) : pos; |
5467 | | } |
5468 | | |
5469 | | /* advance a position, wrapping at 2*poolSize. */ |
5470 | | static WC_INLINE word32 PoolAdvance(word32 pos, word32 by, word32 poolSize) |
5471 | | { |
5472 | | word32 lim = poolSize * 2U; |
5473 | | pos += by; |
5474 | | return (pos >= lim) ? (pos - lim) : pos; |
5475 | | } |
5476 | | |
5477 | | static WC_INLINE word32 PoolUsed(word32 head, word32 tail, word32 poolSize) |
5478 | | { |
5479 | | /* Note, the modular subtraction is unambiguous because the only publisher |
5480 | | * (wc_RNG_Pool_Collect2()) carefully bounds itself to the free span, so |
5481 | | * head never passes tail + poolSize. */ |
5482 | | return (head >= tail) ? (head - tail) : (head + (poolSize * 2U) - tail); |
5483 | | } |
5484 | | |
5485 | | /* Wipe the retired span [tail, head): pooled bytes are finished DRBG output |
5486 | | * at rest, and a retiring event (invalidation, fork, credited reseed) has a |
5487 | | * sibling lineage that may serve its identical copy -- CSP by the doctrine |
5488 | | * at NextSeedPurge(). Race-free by ownership: the single reader is the |
5489 | | * only mover of tail, and writers write only past head. */ |
5490 | | static WC_INLINE void PoolWipeRetired(WC_RNG *rng, word32 tail, word32 head) |
5491 | | { |
5492 | | word32 used = PoolUsed(head, tail, (word32)rng->poolSize); |
5493 | | word32 t = (tail >= (word32)rng->poolSize) ? |
5494 | | (tail - (word32)rng->poolSize) : tail; |
5495 | | word32 seg = (word32)rng->poolSize - t; |
5496 | | if (seg > used) |
5497 | | seg = used; |
5498 | | if (seg > 0) |
5499 | | ForceZero(rng->pool + t, seg); |
5500 | | if (used > seg) |
5501 | | ForceZero(rng->pool, used - seg); |
5502 | | } |
5503 | | |
5504 | | /* Retire pooled output: any event after which pre-event bytes must not be |
5505 | | * served -- state invalidation, fork, a credited reseed recovering from |
5506 | | * invalidation, the reader's |
5507 | | * fail-closed path. Bumping epoch is the whole operation; see above for why |
5508 | | * the counters are deliberately left alone. */ |
5509 | | static WARN_UNUSED_RESULT int PoolPurge(WC_RNG* rng) |
5510 | | { |
5511 | | WC_ATOMIC_UINT_ARG cur, want; |
5512 | | int ret; |
5513 | | |
5514 | | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&rng->poolHead, cur, ret) { |
5515 | | if (! WC_RNG_POOL_HAS_RING(cur)) { |
5516 | | /* no ring: nothing to retire */ |
5517 | | ret = 0; |
5518 | | break; |
5519 | | } |
5520 | | /* state bits (a held claim) are preserved: the claimant's release |
5521 | | * CAS then fails on the epoch and it abandons. */ |
5522 | | want = WC_RNG_POOL_STATE(cur) | |
5523 | | WC_RNG_POOL_PACK(WC_RNG_POOL_POS(cur), |
5524 | | WC_RNG_POOL_EPOCH(cur) + 1U); |
5525 | | WC_CAS_WITH_RETRY_LOOP_FOREVER(wolfSSL_Atomic_Uint_CompareExchange, |
5526 | | &rng->poolHead, cur, want, ret); |
5527 | | } WC_CAS_WITH_RETRY_END; |
5528 | | |
5529 | | return ret; |
5530 | | } |
5531 | | |
5532 | | /* Map a non-UNALLOC poolHead state to the code _Alloc() reports for it. */ |
5533 | | static WC_INLINE int PoolAllocRefusal(WC_ATOMIC_UINT_ARG w) |
5534 | | { |
5535 | | if (WC_RNG_POOL_STATE(w) == WC_RNG_POOL_STATE_TORNDOWN) |
5536 | | return BAD_STATE_E; /* freed; awaiting (re)instantiation */ |
5537 | | else |
5538 | | return ALREADY_E; /* LIVE, or CLAIMED by a writer or allocator */ |
5539 | | } |
5540 | | |
5541 | | int wc_RNG_Pool_Alloc(WC_RNG* rng, word32 size) |
5542 | | { |
5543 | | WC_ATOMIC_UINT_ARG cur, want; |
5544 | | byte *buf; |
5545 | | int ret; |
5546 | | |
5547 | | if ((rng == NULL) || (size < 2) || (size > 32767U)) |
5548 | | return BAD_FUNC_ARG; /* halves are word16; current in [0, size] */ |
5549 | | |
5550 | | cur = WOLFSSL_ATOMIC_LOAD(rng->poolHead); |
5551 | | if (WC_RNG_POOL_STATE(cur) != WC_RNG_POOL_STATE_UNALLOC) |
5552 | | return PoolAllocRefusal(cur); |
5553 | | |
5554 | | /* Allocate unclaimed (XMALLOC may sleep), then claim for the two stores. |
5555 | | * A losing allocator frees its own buffer; the winner's pointer is never |
5556 | | * clobbered. */ |
5557 | | buf = (byte*)XMALLOC(size, rng->heap, DYNAMIC_TYPE_RNG); |
5558 | | if (buf == NULL) |
5559 | | return MEMORY_E; |
5560 | | |
5561 | | cur = WC_RNG_POOL_STATE_UNALLOC; |
5562 | | if (! wolfSSL_Atomic_Uint_CompareExchange( |
5563 | | &rng->poolHead, &cur, |
5564 | | WC_RNG_POOL_STATE_CLAIMED | WC_RNG_POOL_PACK(0, 0))) |
5565 | | { |
5566 | | XFREE(buf, rng->heap, DYNAMIC_TYPE_RNG); |
5567 | | return PoolAllocRefusal(cur); |
5568 | | } |
5569 | | |
5570 | | rng->pool = buf; |
5571 | | rng->poolSize = (word16)size; |
5572 | | WOLFSSL_ATOMIC_STORE(rng->poolTail, WC_RNG_POOL_PACK(0, 0)); |
5573 | | |
5574 | | /* publish LIVE. A purge can land while we hold the claim (epoch |
5575 | | * bump, state preserved), so release by CAS loop, carrying whatever |
5576 | | * epoch is there; the ring is empty either way. */ |
5577 | | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&rng->poolHead, cur, ret) { |
5578 | | want = WC_RNG_POOL_STATE_LIVE | |
5579 | | WC_RNG_POOL_PACK(0, WC_RNG_POOL_EPOCH(cur)); |
5580 | | WC_CAS_WITH_RETRY_LOOP_FOREVER(wolfSSL_Atomic_Uint_CompareExchange, |
5581 | | &rng->poolHead, cur, want, ret); |
5582 | | } WC_CAS_WITH_RETRY_END; |
5583 | | if (ret != 0) { |
5584 | | /* unreachable with a forever loop; keep the ring consistent. */ |
5585 | | return ret; |
5586 | | } |
5587 | | /* tail may now trail head's epoch by a purge that landed under the |
5588 | | * claim -- the reader resyncs on its next visit, as for any purge. */ |
5589 | | |
5590 | | return 0; |
5591 | | } |
5592 | | |
5593 | | int wc_RNG_Pool_Collect2(WC_RNG* rng_dest, WC_RNG* rng_src, word32 n) |
5594 | | { |
5595 | | if ((rng_dest == NULL) || (rng_src == NULL)) |
5596 | | return BAD_FUNC_ARG; |
5597 | | |
5598 | | /* The writer holds the dest claim across its generate, so the generate |
5599 | | * must be bounded: it runs under WC_RNG_FLAG_FAIL_FAST on the source (no |
5600 | | * in-line reseed, no KAT), set transiently here if the source does not |
5601 | | * carry it. The transient RMW on src->flags is legal exactly when |
5602 | | * generating from src is: on a lock-required source the caller holds the |
5603 | | * lease (checked here, and again by the generate); on an unlocked source |
5604 | | * the caller's own exclusivity contract covers the generate and covers |
5605 | | * this. Source upkeep is the source owner's job: _Collect2() never |
5606 | | * reseeds it. */ |
5607 | | { |
5608 | | int lock_ret = rng_lock_required_check(rng_src); |
5609 | | if (lock_ret != 0) |
5610 | | return lock_ret; |
5611 | | } |
5612 | | |
5613 | | #ifdef WC_RNG_HAVE_RBGC |
5614 | | /* Pool data is served directly as DRBG output, via wc_RNG_Pool_Extract(). |
5615 | | * To preserve the destination's provenance guarantee (SP 800-90C |
5616 | | * sect. 7.3.1 item 16, no output to a predecessor), the generator stratum |
5617 | | * must not be deeper than the destination stratum. Contrast with stir data |
5618 | | * (wc_RNG_DRBG_ReseedRBGC_local() uncredited path), which has and imparts |
5619 | | * no provenance. */ |
5620 | | if (rng_src->RBGCStratum > rng_dest->RBGCStratum) |
5621 | | return BAD_FUNC_ARG; |
5622 | | |
5623 | | #ifdef HAVE_FIPS |
5624 | | /* When FIPS and rng_src != rng_dest, use a narrowed subset of the |
5625 | | * SP-800-90C RBGC seed source criteria to determine eligibility of |
5626 | | * rng_src */ |
5627 | | if ((rng_src != rng_dest) && (rng_src != rng_dest->RBGC_parent)) { |
5628 | | return WRONG_TYPE_OBJECT_E; |
5629 | | } |
5630 | | #endif /* HAVE_FIPS */ |
5631 | | |
5632 | | #else /* !WC_RNG_HAVE_RBGC */ |
5633 | | |
5634 | | #ifdef HAVE_FIPS |
5635 | | /* No RBGC tree, hence no seed-source relation to validate: only self-pool |
5636 | | * allowed. */ |
5637 | | if (rng_src != rng_dest) |
5638 | | return WRONG_TYPE_OBJECT_E; |
5639 | | #endif /* HAVE_FIPS */ |
5640 | | |
5641 | | #endif /* !WC_RNG_HAVE_RBGC */ |
5642 | | |
5643 | | { |
5644 | | WC_ATOMIC_UINT_ARG snap, cur, want; |
5645 | | word32 head, epoch, tail, free_sz, m, done = 0; |
5646 | | word32 poolSize; |
5647 | | byte *pool; |
5648 | | word32 restore_flag_bits; |
5649 | | int ret; |
5650 | | |
5651 | | WC_ATOMIC_UINT_ARG tw; |
5652 | | |
5653 | | snap = WOLFSSL_ATOMIC_LOAD(rng_dest->poolHead); |
5654 | | if (! WC_RNG_POOL_HAS_RING(snap)) |
5655 | | return BAD_STATE_E; |
5656 | | if (WC_RNG_POOL_STATE(snap) == WC_RNG_POOL_STATE_CLAIMED) |
5657 | | return BUSY_E; /* another writer, or an allocator, is active */ |
5658 | | |
5659 | | if (n == 0) |
5660 | | return 0; |
5661 | | |
5662 | | head = WC_RNG_POOL_POS(snap); |
5663 | | epoch = WC_RNG_POOL_EPOCH(snap); |
5664 | | tw = WOLFSSL_ATOMIC_LOAD(rng_dest->poolTail); |
5665 | | |
5666 | | if (WC_RNG_POOL_EPOCH(tw) != epoch) { |
5667 | | /* A purge landed and the reader has not yet acknowledged it. Its |
5668 | | * resync discards everything published before the purge -- which |
5669 | | * would include anything we published now -- so there is no useful |
5670 | | * work here until a read happens. Reporting NOT_READY_E rather |
5671 | | * than success also keeps a collector that polls fullness from |
5672 | | * spinning: wc_RNG_Pool_Current() reports empty across this |
5673 | | * window, while tail still describes the retired span, so a |
5674 | | * free-span computation from it would say full. Those two |
5675 | | * disagree only here, and only until the reader resyncs. */ |
5676 | | return NOT_READY_E; |
5677 | | } |
5678 | | |
5679 | | tail = WC_RNG_POOL_POS(tw); |
5680 | | |
5681 | | /* Free span from the pre-claim snapshot. Conservative: the reader |
5682 | | * can only enlarge it, and head cannot move under our claim. */ |
5683 | | free_sz = (word32)rng_dest->poolSize |
5684 | | - PoolUsed(head, tail, (word32)rng_dest->poolSize); |
5685 | | if (free_sz == 0) |
5686 | | return 0; /* full: success no-op, no claim taken */ |
5687 | | m = (free_sz > n) ? n : free_sz; |
5688 | | |
5689 | | /* Claim. From here to the release, the pointer and size are stable |
5690 | | * (wc_FreeRng() and _Alloc() refuse while CLAIMED), so snapshot them |
5691 | | * once: a reinstantiation that lands after our release must not be |
5692 | | * able to tear the loop. */ |
5693 | | if (! wolfSSL_Atomic_Uint_CompareExchange( |
5694 | | &rng_dest->poolHead, &snap, |
5695 | | WC_RNG_POOL_STATE_CLAIMED | |
5696 | | WC_RNG_POOL_PACK(WC_RNG_POOL_POS(snap), |
5697 | | WC_RNG_POOL_EPOCH(snap)))) |
5698 | | { |
5699 | | return BUSY_E; /* lost to a writer, an allocator, or a purge */ |
5700 | | } |
5701 | | pool = rng_dest->pool; |
5702 | | poolSize = (word32)rng_dest->poolSize; |
5703 | | |
5704 | | if (! (rng_src->flags & WC_RNG_FLAG_FAIL_FAST)) { |
5705 | | restore_flag_bits = WC_RNG_FLAG_FAIL_FAST; |
5706 | | rng_src->flags |= restore_flag_bits; |
5707 | | } |
5708 | | else |
5709 | | restore_flag_bits = 0U; |
5710 | | |
5711 | | /* generate directly into the unpublished span (up to two contiguous |
5712 | | * segments), then publish the whole of it with one CAS. */ |
5713 | | ret = 0; |
5714 | | while (done < m) { |
5715 | | word32 at = PoolAt(PoolAdvance(head, done, poolSize), poolSize); |
5716 | | word32 chunk = poolSize - at; |
5717 | | if (chunk > m - done) |
5718 | | chunk = m - done; |
5719 | | ret = wc_RNG_GenerateBlock(rng_src, pool + at, chunk); |
5720 | | if (ret != 0) { |
5721 | | /* Abandon in place. The written bytes lie beyond head and |
5722 | | * are therefore unpublished -- benign in-boundary content |
5723 | | * awaiting overwrite. Not burned: the reader's burn span and |
5724 | | * ours are disjoint, and zeroing here would be |
5725 | | * indistinguishable from published zeros to the next writer. */ |
5726 | | break; |
5727 | | } |
5728 | | done += chunk; |
5729 | | } |
5730 | | |
5731 | | if (restore_flag_bits) |
5732 | | rng_src->flags &= ~restore_flag_bits; |
5733 | | |
5734 | | /* Release, on every path. Only PoolPurge() can have moved the word |
5735 | | * while we held the claim, and it preserves the state bits, so the |
5736 | | * loop can only see CLAIMED with our pos and some epoch. Our epoch |
5737 | | * intact and the generate complete: publish. Otherwise the bytes are |
5738 | | * pre-event (or incomplete) and stay unpublished. */ |
5739 | | { |
5740 | | int published = 0; |
5741 | | int cas_ret; |
5742 | | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&rng_dest->poolHead, cur, cas_ret) { |
5743 | | if ((ret == 0) && (WC_RNG_POOL_EPOCH(cur) == epoch)) { |
5744 | | want = WC_RNG_POOL_STATE_LIVE | |
5745 | | WC_RNG_POOL_PACK(PoolAdvance(head, m, poolSize), |
5746 | | epoch); |
5747 | | published = 1; |
5748 | | } |
5749 | | else { |
5750 | | want = WC_RNG_POOL_STATE_LIVE | |
5751 | | WC_RNG_POOL_PACK(WC_RNG_POOL_POS(cur), |
5752 | | WC_RNG_POOL_EPOCH(cur)); |
5753 | | published = 0; |
5754 | | } |
5755 | | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
5756 | | wolfSSL_Atomic_Uint_CompareExchange, |
5757 | | &rng_dest->poolHead, cur, want, cas_ret); |
5758 | | } WC_CAS_WITH_RETRY_END; |
5759 | | if (cas_ret != 0) |
5760 | | return cas_ret; /* unreachable with a forever loop */ |
5761 | | if (ret != 0) |
5762 | | return ret; /* the source's verdict is most salient */ |
5763 | | if (! published) |
5764 | | return BUSY_E; /* a purge landed during the generate */ |
5765 | | } |
5766 | | |
5767 | | return 0; |
5768 | | } |
5769 | | } |
5770 | | |
5771 | | int wc_RNG_Pool_Collect(WC_RNG* rng, word32 n) |
5772 | | { |
5773 | | return wc_RNG_Pool_Collect2(rng, rng, n); |
5774 | | } |
5775 | | |
5776 | | int wc_RNG_Pool_Extract(WC_RNG* rng, byte* out, word32* n) |
5777 | | { |
5778 | | WC_ATOMIC_UINT_ARG w1, w2, tw; |
5779 | | word32 head, epoch, tail, avail, m, done = 0; |
5780 | | int ret; |
5781 | | |
5782 | | if ((rng == NULL) || (out == NULL) || (n == NULL)) |
5783 | | return BAD_FUNC_ARG; |
5784 | | { |
5785 | | int lock_ret = rng_lock_required_check(rng); |
5786 | | if (lock_ret != 0) |
5787 | | return lock_ret; |
5788 | | } |
5789 | | /* The reader never consults or changes the state bits beyond this: on a |
5790 | | * lock-required instance it is the lease holder, and the lease is what |
5791 | | * serializes it against teardown; a claim (writer or allocator) is |
5792 | | * invisible to it by design. */ |
5793 | | if (! WC_RNG_POOL_HAS_RING(WOLFSSL_ATOMIC_LOAD(rng->poolHead))) |
5794 | | return BAD_STATE_E; |
5795 | | |
5796 | | #if defined(HAVE_HASHDRBG) && \ |
5797 | | (defined(WC_RNG_HAVE_ENTROPY_EPOCH) || \ |
5798 | | (defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID))) |
5799 | | /* Propagate any pending epoch increment or PID change before serving: |
5800 | | * pre-increment pooled bytes are pre-event output. We short circuit return |
5801 | | * when a propagation occurs, because NEEDS_RECOVERY_E is the more |
5802 | | * informative error. |
5803 | | */ |
5804 | | ret = rng_entropy_event_propagate(rng); |
5805 | | if (ret != 0) |
5806 | | return ret; |
5807 | | #endif /* HAVE_HASHDRBG && (WC_RNG_HAVE_ENTROPY_EPOCH || HAVE_GETPID) */ |
5808 | | |
5809 | | /* Fail closed: no serving output on behalf of an out-of-service DRBG, and |
5810 | | * its pooled output is unusable material at rest. A writer mid-fill sees |
5811 | | * the epoch move and abandons rather than publishing. */ |
5812 | | if (wc_RNG_DRBG_Present(rng) && (rng->status != DRBG_OK)) { |
5813 | | ret = PoolPurge(rng); |
5814 | | if (ret != 0) |
5815 | | return ret; |
5816 | | /* Reader-owned fail-closed wipe and resync of whatever was |
5817 | | * pending. */ |
5818 | | tw = WOLFSSL_ATOMIC_LOAD(rng->poolTail); |
5819 | | w1 = WOLFSSL_ATOMIC_LOAD(rng->poolHead); |
5820 | | PoolWipeRetired(rng, WC_RNG_POOL_POS(tw), WC_RNG_POOL_POS(w1)); |
5821 | | WOLFSSL_ATOMIC_STORE(rng->poolTail, |
5822 | | WC_RNG_POOL_PACK(WC_RNG_POOL_POS(w1), |
5823 | | WC_RNG_POOL_EPOCH(w1))); |
5824 | | return RNG_FAILURE_E; |
5825 | | } |
5826 | | |
5827 | | tw = WOLFSSL_ATOMIC_LOAD(rng->poolTail); |
5828 | | w1 = WOLFSSL_ATOMIC_LOAD(rng->poolHead); |
5829 | | head = WC_RNG_POOL_POS(w1); |
5830 | | epoch = WC_RNG_POOL_EPOCH(w1); |
5831 | | |
5832 | | if (WC_RNG_POOL_EPOCH(tw) != epoch) { |
5833 | | /* A purge landed since our last visit. Everything published before |
5834 | | * it is retired: resynchronize to head and report empty. Anything |
5835 | | * the writer publishes after this point is post-event and stands. */ |
5836 | | PoolWipeRetired(rng, WC_RNG_POOL_POS(tw), head); |
5837 | | WOLFSSL_ATOMIC_STORE(rng->poolTail, WC_RNG_POOL_PACK(head, epoch)); |
5838 | | #ifdef WC_RNG_DEBUG_STATS |
5839 | | rng->_stats_pool_bytes_missed += *n; |
5840 | | #endif |
5841 | | return NOT_READY_E; |
5842 | | } |
5843 | | |
5844 | | tail = WC_RNG_POOL_POS(tw); |
5845 | | avail = PoolUsed(head, tail, (word32)rng->poolSize); |
5846 | | if (avail == 0) { |
5847 | | #ifdef WC_RNG_DEBUG_STATS |
5848 | | rng->_stats_pool_bytes_missed += *n; |
5849 | | #endif |
5850 | | return NOT_READY_E; |
5851 | | } |
5852 | | m = (avail > *n) ? *n : avail; |
5853 | | |
5854 | | while (done < m) { |
5855 | | word32 at = PoolAt(PoolAdvance(tail, done, (word32)rng->poolSize), |
5856 | | (word32)rng->poolSize); |
5857 | | word32 chunk = (word32)rng->poolSize - at; |
5858 | | if (chunk > m - done) |
5859 | | chunk = m - done; |
5860 | | XMEMCPY(out + done, rng->pool + at, chunk); |
5861 | | /* burn on the way out the door, before the span is republished. |
5862 | | * [tail, tail+m) and the writer's [head, head+m') are disjoint by |
5863 | | * construction, so this can never erase published bytes. */ |
5864 | | ForceZero(rng->pool + at, chunk); |
5865 | | done += chunk; |
5866 | | } |
5867 | | |
5868 | | /* The linearization point. Both loads read head and epoch as one word, |
5869 | | * so a purge anywhere in our window is caught here -- epoch moves and |
5870 | | * never moves back. Our bytes then predate the event and must not be |
5871 | | * served, so discard the whole pre-event span rather than advancing. */ |
5872 | | w2 = WOLFSSL_ATOMIC_LOAD(rng->poolHead); |
5873 | | if (WC_RNG_POOL_EPOCH(w2) != epoch) { |
5874 | | /* We own [tail, old head) exclusively; the purged span is wiped |
5875 | | * before it is skipped. */ |
5876 | | PoolWipeRetired(rng, tail, head); |
5877 | | WOLFSSL_ATOMIC_STORE(rng->poolTail, |
5878 | | WC_RNG_POOL_PACK(WC_RNG_POOL_POS(w2), |
5879 | | WC_RNG_POOL_EPOCH(w2))); |
5880 | | /* The copied bytes predate the event too. */ |
5881 | | ForceZero(out, done); |
5882 | | #ifdef WC_RNG_DEBUG_STATS |
5883 | | rng->_stats_pool_bytes_missed += *n; |
5884 | | #endif |
5885 | | return BUSY_E; |
5886 | | } |
5887 | | |
5888 | | /* Sole writer of poolTail: a plain store, no CAS on the reader path. */ |
5889 | | WOLFSSL_ATOMIC_STORE(rng->poolTail, |
5890 | | WC_RNG_POOL_PACK( |
5891 | | PoolAdvance(tail, m, (word32)rng->poolSize), |
5892 | | epoch)); |
5893 | | |
5894 | | #ifdef WC_RNG_DEBUG_STATS |
5895 | | rng->_stats_pool_bytes_produced += m; |
5896 | | rng->_stats_pool_bytes_missed += *n - m; /* shortfall on partial serve */ |
5897 | | #endif |
5898 | | *n = m; |
5899 | | |
5900 | | return 0; |
5901 | | } |
5902 | | |
5903 | | int wc_RNG_Pool_Current(const WC_RNG* rng, word32* n) |
5904 | | { |
5905 | | if ((rng == NULL) || (n == NULL)) |
5906 | | return BAD_FUNC_ARG; |
5907 | | { |
5908 | | WC_ATOMIC_UINT_ARG w = WOLFSSL_ATOMIC_LOAD(rng->poolHead); |
5909 | | WC_ATOMIC_UINT_ARG tw = WOLFSSL_ATOMIC_LOAD(rng->poolTail); |
5910 | | /* no ring, or a purge not yet observed by the reader (which retires |
5911 | | * everything published before it): report empty. */ |
5912 | | if ((! WC_RNG_POOL_HAS_RING(w)) || |
5913 | | (WC_RNG_POOL_EPOCH(tw) != WC_RNG_POOL_EPOCH(w))) |
5914 | | { |
5915 | | *n = 0; |
5916 | | } |
5917 | | else { |
5918 | | *n = PoolUsed(WC_RNG_POOL_POS(w), WC_RNG_POOL_POS(tw), |
5919 | | (word32)rng->poolSize); |
5920 | | } |
5921 | | } |
5922 | | return 0; |
5923 | | } |
5924 | | #endif /* WC_RNG_HAVE_POOL */ |
5925 | | |
5926 | | #ifdef WC_RNG_HAVE_RBGC |
5927 | | |
5928 | | /* Unified mechanics for the four wc_InitRng*RBGC() APIs: instantiate a child |
5929 | | * DRBG subordinate to parent in an SP 800-90C RBG chain, drawing its seed |
5930 | | * material from parent's generate function in place of the module's seed |
5931 | | * source; every other aspect of instantiation -- seed byte accounting, nonce |
5932 | | * handling, failure disposition -- is _InitRng()'s, identically to |
5933 | | * wc_InitRngNonce_ex() with the omission of health testing, which is |
5934 | | * superfluous when a healthy DRBG generates the seed data. |
5935 | | * |
5936 | | * SP 800-90C accounting: the child's claimable security strength is capped by |
5937 | | * the parent's, and the child has no formal prediction resistance. The child's |
5938 | | * own reseeds default to the module's seed source (the reseed-interval |
5939 | | * backstop, wc_RNG_DRBG_Reseed_Now()); wc_RNG_DRBG_ReseedRBGC() reseeds it from |
5940 | | * a supplied root instead. In configurations with no DRBG (RDRAND et al.), the |
5941 | | * child comes up as _InitRng() dictates for such configurations and the parent |
5942 | | * is not consulted. |
5943 | | * |
5944 | | * Exactly one of new_child_stack (caller-provided WC_RNG, uninitialized) and |
5945 | | * new_child_heap (callee-allocated from parent's heap, to be released with |
5946 | | * wc_rng_free()) must be non-NULL. The caller must hold exclusive access |
5947 | | * to parent for the duration of the call, as for all WC_RNG operations; the |
5948 | | * spawn debits parent's reseed counter by one generate. |
5949 | | */ |
5950 | | static WARN_UNUSED_RESULT int SpawnRngRBGC( |
5951 | | WC_RNG* new_child_stack, WC_RNG** new_child_heap, |
5952 | | WC_RNG* parent, const byte* nonce, word32 nonceSz, |
5953 | | const byte *perso, word32 persoSz, |
5954 | | word32 flags) |
5955 | | { |
5956 | | WC_RNG* child = new_child_stack; |
5957 | | int ret; |
5958 | | |
5959 | | if (parent == NULL) |
5960 | | return BAD_FUNC_ARG; |
5961 | | |
5962 | | if ((new_child_stack == NULL) == (new_child_heap == NULL)) |
5963 | | return BAD_FUNC_ARG; |
5964 | | |
5965 | | if (new_child_stack == parent) |
5966 | | return BAD_FUNC_ARG; |
5967 | | |
5968 | | if ((nonce == NULL) && (nonceSz > 0)) |
5969 | | return BAD_FUNC_ARG; |
5970 | | |
5971 | | if (new_child_heap != NULL) { |
5972 | | *new_child_heap = (WC_RNG*)XMALLOC(sizeof(WC_RNG), parent->heap, |
5973 | | DYNAMIC_TYPE_RNG); |
5974 | | if (*new_child_heap == NULL) |
5975 | | return MEMORY_E; |
5976 | | child = *new_child_heap; |
5977 | | } |
5978 | | |
5979 | | ret = _InitRng(child, nonce, nonceSz, perso, persoSz, NULL, 0, parent->heap, |
5980 | | #if defined(WOLF_CRYPTO_CB) |
5981 | | parent->devId, |
5982 | | #else |
5983 | | INVALID_DEVID, |
5984 | | #endif |
5985 | | parent, flags); |
5986 | | |
5987 | | if (new_child_heap != NULL) { |
5988 | | if (ret == 0) { |
5989 | | /* wc_rng_free() is a void -- no way to cope with |
5990 | | * STILL_REFERENCED_E. */ |
5991 | | child->flags |= WC_RNG_FLAG_NO_RBGC_PARENT; |
5992 | | } |
5993 | | else { |
5994 | | XFREE(child, parent->heap, DYNAMIC_TYPE_RNG); |
5995 | | *new_child_heap = child = NULL; |
5996 | | } |
5997 | | } |
5998 | | |
5999 | | return ret; |
6000 | | } |
6001 | | |
6002 | | int wc_InitRngRBGC(WC_RNG* child, WC_RNG* parent, word32 flags) |
6003 | | { |
6004 | | return SpawnRngRBGC(child, NULL, parent, NULL, 0, NULL, 0, flags); |
6005 | | } |
6006 | | |
6007 | | int wc_InitRngNonceRBGC(WC_RNG* child, WC_RNG* parent, const byte* nonce, |
6008 | | word32 nonceSz, const byte *perso, word32 persoSz, |
6009 | | word32 flags) |
6010 | | { |
6011 | | return SpawnRngRBGC(child, NULL, parent, nonce, nonceSz, perso, persoSz, |
6012 | | flags); |
6013 | | } |
6014 | | |
6015 | | #ifndef WC_NO_CONSTRUCTORS |
6016 | | int wc_InitRngRBGC_New(WC_RNG** child, WC_RNG* parent, word32 flags) |
6017 | | { |
6018 | | return SpawnRngRBGC(NULL, child, parent, NULL, 0, NULL, 0, flags); |
6019 | | } |
6020 | | |
6021 | | int wc_InitRngNonceRBGC_New(WC_RNG** child, WC_RNG* parent, const byte* nonce, |
6022 | | word32 nonceSz, const byte *perso, word32 persoSz, |
6023 | | word32 flags) |
6024 | | { |
6025 | | return SpawnRngRBGC(NULL, child, parent, nonce, nonceSz, perso, persoSz, |
6026 | | flags); |
6027 | | } |
6028 | | #endif /* !WC_NO_CONSTRUCTORS */ |
6029 | | |
6030 | | /* Immediately reseed rng from root's generate output -- the reseed counterpart |
6031 | | * of the wc_InitRng*RBGC() spawn. The reseed counter is reset iff the reseed |
6032 | | * succeeds and credited. The nonce, if any, rides the same reseed derivation |
6033 | | * as (uncredited) additional input. The caller must hold exclusive access to |
6034 | | * BOTH rng and root. On credited success, rng is (or remains) a chain RNG: |
6035 | | * its current seed period is chain-backed, so RBGCStratum is set, and it is not |
6036 | | * usable as a reseed root. |
6037 | | * |
6038 | | * By default, consistent with SP 800-90C 7.1.2.2, reseed by an RBGC root is |
6039 | | * allowed, provided its stratum is less than the child's stratum (no stratum |
6040 | | * downgrade allowed, no cycles possible); build-time option |
6041 | | * WC_RNG_NO_RBGC_RESEED restricts credited reseeds to primary-seeded roots. |
6042 | | * |
6043 | | * Uncredited reseeds by wc_RNG_DRBG_ReseedRBGC_local() are unconditionally |
6044 | | * permitted (these are just stirs). |
6045 | | */ |
6046 | | |
6047 | | /* safe (bounded-at-once) recursion for RBGC reseed. */ |
6048 | | /* NOLINTNEXTLINE(misc-no-recursion) */ |
6049 | | static WARN_UNUSED_RESULT int wc_RNG_DRBG_ReseedRBGC_local( |
6050 | | WC_RNG* rng, WC_RNG* root, |
6051 | | const byte* nonce, word32 nonceSz, |
6052 | | int credited) |
6053 | | { |
6054 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
6055 | | byte *seed = NULL; |
6056 | | #else |
6057 | | byte seed[SEED_SZ]; |
6058 | | #endif |
6059 | | int ret; |
6060 | | WC_ATOMIC_UINT_ARG cur_epoch = |
6061 | | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
6062 | | WOLFSSL_ATOMIC_LOAD(global_entropy_epoch) |
6063 | | #else |
6064 | | 0 |
6065 | | #endif |
6066 | | ; |
6067 | | WC_RNG_PID_ARG my_pid = WC_RNG_GETPID(); |
6068 | | |
6069 | | if ((rng == NULL) || (root == NULL) || (rng == root) || |
6070 | | ((nonce == NULL) && (nonceSz > 0))) |
6071 | | { |
6072 | | return BAD_FUNC_ARG; |
6073 | | } |
6074 | | |
6075 | | #ifdef WC_RNG_RBGC_STRATUM_IMMUTABLE |
6076 | | if (credited && (rng->RBGCStratum == 0)) |
6077 | | return WRONG_TYPE_OBJECT_E; |
6078 | | #endif |
6079 | | |
6080 | | #ifdef HAVE_FIPS |
6081 | | /* SP-800-90C requires that an RBGC seed source be the original parent, or |
6082 | | * in the alternative, "a sibling of the parent, an ancestor, or the initial |
6083 | | * randomness source". We can't safely ascend through multiple links, |
6084 | | * because the tree may have been broken by a wc_FreeRng(), so we use a |
6085 | | * criterion similar to that used in PollAndReSeed() to qualify the |
6086 | | * global_fallback_rng. */ |
6087 | | if (credited && |
6088 | | (rng->RBGC_parent != NULL) && |
6089 | | (rng->RBGC_parent != root) && |
6090 | | ((rng->RBGC_parent->RBGCStratum > 0) || |
6091 | | (root->RBGCStratum > 0))) |
6092 | | { |
6093 | | return WRONG_TYPE_OBJECT_E; |
6094 | | } |
6095 | | #endif |
6096 | | |
6097 | | ret = rng_lock_required_check(rng); |
6098 | | if (ret != 0) |
6099 | | return ret; |
6100 | | |
6101 | | ret = rng_lock_required_check(root); |
6102 | | if (ret != 0) |
6103 | | return ret; |
6104 | | |
6105 | | ret = rng_entropy_event_propagate(rng); |
6106 | | if ((ret != 0) && (ret != WC_NO_ERR_TRACE(NEEDS_RECOVERY_E))) |
6107 | | return ret; /* delivery failed: condemned, verdict via |
6108 | | wc_RNG_Status() */ |
6109 | | /* NEEDS_RECOVERY_E is what we're here to discharge. */ |
6110 | | |
6111 | | if (credited) { |
6112 | | if (root->RBGCStratum >= WC_MAX_SINT_OF(int)) |
6113 | | return SEQ_OVERFLOW_E; |
6114 | | else if (root->RBGCStratum == WC_RNG_RBGC_USER_SEED_STRATUM - 1) |
6115 | | return SEQ_OVERFLOW_E; |
6116 | | } |
6117 | | /* else the RBGC strata are irrelevant -- stir data has no implication of |
6118 | | * provenance, and can legitimately be wall clock time or even strings of |
6119 | | * zeros. */ |
6120 | | |
6121 | | if (credited && (root->RBGCStratum > 0) |
6122 | | #ifndef WC_RNG_NO_RBGC_RESEED |
6123 | | && (root->RBGCStratum >= rng->RBGCStratum) |
6124 | | #else |
6125 | | /* Credited reseed from root only, by policy. */ |
6126 | | #endif |
6127 | | ) |
6128 | | { |
6129 | | return BAD_FUNC_ARG; |
6130 | | } |
6131 | | |
6132 | | ret = wc_RNG_Status(root); |
6133 | | if (ret != 0) |
6134 | | return ret; |
6135 | | |
6136 | | ret = wc_RNG_Status(rng); |
6137 | | if (ret != 0) |
6138 | | return ret; |
6139 | | |
6140 | | if (! wc_RNG_DRBG_Present(rng)) { |
6141 | | return 0; |
6142 | | } |
6143 | | |
6144 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
6145 | | #ifdef WOLFSSL_DRBG_SHA512 |
6146 | | if (rng->drbgType == WC_DRBG_SHA512) { |
6147 | | if (rng->drbg512 == NULL) |
6148 | | return BAD_FUNC_ARG; |
6149 | | seed = ((DRBG_SHA512_internal*)rng->drbg512)->newSeed_buf; |
6150 | | } |
6151 | | #ifndef NO_SHA256 |
6152 | | else |
6153 | | #endif |
6154 | | #endif |
6155 | | #ifndef NO_SHA256 |
6156 | | if (rng->drbgType == WC_DRBG_SHA256) { |
6157 | | if (rng->drbg == NULL) |
6158 | | return BAD_FUNC_ARG; |
6159 | | seed = ((DRBG_internal*)rng->drbg)->newSeed_buf; |
6160 | | } |
6161 | | #endif /* NO_SHA256 */ |
6162 | | |
6163 | | if (seed == NULL) |
6164 | | return WRONG_TYPE_OBJECT_E; |
6165 | | #endif /* WOLFSSL_SMALL_STACK_CACHE */ |
6166 | | |
6167 | | ret = wc_RNG_GenerateBlock(root, seed, SEED_SZ); |
6168 | | if (ret == 0) { |
6169 | | if (credited) { |
6170 | | ret = Hash_DRBG_Reseed(rng, seed, SEED_SZ, nonce, nonceSz, |
6171 | | 0 /* in_bracketed_consume */, cur_epoch, |
6172 | | my_pid); |
6173 | | if (ret > 0) /* DRBG-internal code: translate at the API */ |
6174 | | ret = RNG_FAILURE_E; |
6175 | | if (ret == 0) { |
6176 | | #ifndef WC_RNG_RBGC_STRATUM_IMMUTABLE |
6177 | | rng->RBGCStratum = root->RBGCStratum + 1; |
6178 | | #endif |
6179 | | #ifdef WC_RNG_DEBUG_STATS |
6180 | | ++rng->_stats_RBGC_reseeds; |
6181 | | #endif |
6182 | | } |
6183 | | } |
6184 | | else { |
6185 | | ret = wc_RNG_DRBG_Stir_Nonce_local(rng, seed, SEED_SZ, nonce, |
6186 | | nonceSz); |
6187 | | } |
6188 | | } |
6189 | | ForceZero(seed, SEED_SZ); |
6190 | | |
6191 | | if ((ret == 0) && credited) |
6192 | | ret = rng_entropy_event_propagate(rng); |
6193 | | |
6194 | | return ret; |
6195 | | } |
6196 | | |
6197 | | /* safe (bounded-at-once) recursion for RBGC reseed. */ |
6198 | | /* NOLINTNEXTLINE(misc-no-recursion) */ |
6199 | | int wc_RNG_DRBG_ReseedRBGC(WC_RNG* rng, WC_RNG* root, const byte* nonce, |
6200 | | word32 nonceSz) |
6201 | | { |
6202 | | return wc_RNG_DRBG_ReseedRBGC_local(rng, root, nonce, nonceSz, 1); |
6203 | | } |
6204 | | |
6205 | | int wc_RNG_DRBG_StirRBGC(WC_RNG* rng, WC_RNG* root, |
6206 | | const byte* nonce, word32 nonceSz) |
6207 | | { |
6208 | | return wc_RNG_DRBG_ReseedRBGC_local(rng, root, nonce, nonceSz, 0); |
6209 | | } |
6210 | | |
6211 | | #endif /* WC_RNG_HAVE_RBGC */ |
6212 | | |
6213 | | #if defined(HAVE_HASHDRBG) && !defined(CUSTOM_RAND_GENERATE_BLOCK) |
6214 | | |
6215 | | /* A failed seed source reports DRBG_FAILURE, except an SP 800-90B RCT or APT |
6216 | | * verdict, which keeps its own code so the caller can tell the two apart. */ |
6217 | | /* safe (bounded-at-once) recursion for RBGC reseed. */ |
6218 | | /* NOLINTNEXTLINE(misc-no-recursion) */ |
6219 | | static WARN_UNUSED_RESULT int PollAndReSeed(WC_RNG* rng, const byte* additional, |
6220 | | word32 additionalSz) |
6221 | 0 | { |
6222 | 0 | int ret = WC_NO_ERR_TRACE(DRBG_NEED_RESEED); |
6223 | 0 | WC_ATOMIC_UINT_ARG cur_epoch = |
6224 | 0 | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
6225 | 0 | WOLFSSL_ATOMIC_LOAD(global_entropy_epoch) |
6226 | | #else |
6227 | | 0 |
6228 | | #endif |
6229 | 0 | ; |
6230 | 0 | WC_RNG_PID_ARG my_pid = WC_RNG_GETPID(); |
6231 | 0 | int devId = INVALID_DEVID; |
6232 | 0 | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
6233 | 0 | devId = rng->devId; |
6234 | 0 | #endif |
6235 | |
|
6236 | 0 | ret = rng_entropy_event_propagate(rng); |
6237 | 0 | if ((ret != 0) && (ret != WC_NO_ERR_TRACE(NEEDS_RECOVERY_E))) |
6238 | 0 | return ret; /* delivery failed: condemned, verdict via |
6239 | | wc_RNG_Status() */ |
6240 | | /* NEEDS_RECOVERY_E is what we're here to discharge. */ |
6241 | | |
6242 | 0 | ret = wc_RNG_HealthTestLocal(rng, 1, rng->heap, devId); |
6243 | |
|
6244 | | #if defined(WC_RNG_HAVE_RBGC) && defined(WC_RNG_HAVE_LOCK) |
6245 | | if ((ret == 0) && (rng->RBGCStratum > 0) && |
6246 | | (! (rng->flags & WC_RNG_FLAG_ONLY_PRIMARY_SEED))) |
6247 | | { |
6248 | | if ((wc_RNG_Status(rng->RBGC_parent) == 0) && |
6249 | | (wc_RNG_lock_get(rng->RBGC_parent, 0) == 0)) |
6250 | | { |
6251 | | int put_ret; |
6252 | | ret = wc_RNG_DRBG_ReseedRBGC(rng, rng->RBGC_parent, |
6253 | | additional, additionalSz); |
6254 | | put_ret = wc_RNG_lock_put(rng->RBGC_parent, 0); |
6255 | | if ((put_ret != 0) && (put_ret != WC_NO_ERR_TRACE(NEEDS_RECOVERY_E))) |
6256 | | return put_ret; /* internal failure is most salient */ |
6257 | | if (ret == 0) { |
6258 | | if (put_ret == 0) |
6259 | | goto out; |
6260 | | ret = DRBG_NEED_RESEED; |
6261 | | } |
6262 | | } |
6263 | | if ((wc_RNG_Status(&global_fallback_rng) == 0) && |
6264 | | #ifdef HAVE_FIPS |
6265 | | /* SP-800-90C requires that an alternative randomness source be "a |
6266 | | * sibling of the parent, an ancestor, or the initial randomness |
6267 | | * source". */ |
6268 | | (rng->RBGC_parent != NULL) && |
6269 | | ((global_fallback_rng.RBGCStratum == 0) && |
6270 | | (global_fallback_rng.RBGCStratum == |
6271 | | rng->RBGC_parent->RBGCStratum)) && |
6272 | | #endif |
6273 | | (wc_RNG_lock_get(&global_fallback_rng, 0) == 0)) |
6274 | | { |
6275 | | int put_ret; |
6276 | | ret = wc_RNG_DRBG_ReseedRBGC(rng, &global_fallback_rng, |
6277 | | additional, additionalSz); |
6278 | | put_ret = wc_RNG_lock_put(&global_fallback_rng, 0); |
6279 | | if ((put_ret != 0) && (put_ret != WC_NO_ERR_TRACE(NEEDS_RECOVERY_E))) |
6280 | | return put_ret; /* internal failure is most salient */ |
6281 | | if (ret == 0) { |
6282 | | if (put_ret == 0) |
6283 | | goto out; |
6284 | | ret = DRBG_NEED_RESEED; |
6285 | | } |
6286 | | } |
6287 | | if (rng->flags & WC_RNG_FLAG_NO_PRIMARY_SEED) { |
6288 | | if (ret == 0) |
6289 | | return DRBG_NEED_RESEED; |
6290 | | else |
6291 | | return ret; |
6292 | | } |
6293 | | ret = 0; |
6294 | | } |
6295 | | /* else fall through to primary reseed. */ |
6296 | | #elif defined(WC_RNG_HAVE_RBGC) |
6297 | | /* Without the lock facility there is no retained parent and no fallback |
6298 | | * ladder, so an instance barred from the primary seed source can only |
6299 | | * defer: credited chain maintenance is the caller's own job, via |
6300 | | * wc_RNG_DRBG_ReseedRBGC(). */ |
6301 | | if ((ret == 0) && (rng->RBGCStratum > 0) && |
6302 | | (rng->flags & WC_RNG_FLAG_NO_PRIMARY_SEED)) |
6303 | | { |
6304 | | return DRBG_NEED_RESEED; |
6305 | | } |
6306 | | #endif /* WC_RNG_HAVE_RBGC */ |
6307 | |
|
6308 | 0 | if (ret == 0) { |
6309 | | #if defined(WOLFSSL_SMALL_STACK_CACHE) |
6310 | | byte *newSeed = NULL; |
6311 | | #ifdef WOLFSSL_DRBG_SHA512 |
6312 | | if (rng->drbgType == WC_DRBG_SHA512) { |
6313 | | if (rng->drbg512 == NULL) |
6314 | | ret = BAD_FUNC_ARG; |
6315 | | else { |
6316 | | newSeed = ((DRBG_SHA512_internal*)rng->drbg512)->newSeed_buf; |
6317 | | ret = DRBG_SUCCESS; |
6318 | | } |
6319 | | } |
6320 | | #ifndef NO_SHA256 |
6321 | | else |
6322 | | #endif |
6323 | | #endif |
6324 | | #ifndef NO_SHA256 |
6325 | | { |
6326 | | if (rng->drbg == NULL) |
6327 | | ret = BAD_FUNC_ARG; |
6328 | | else { |
6329 | | newSeed = ((DRBG_internal*)rng->drbg)->newSeed_buf; |
6330 | | ret = DRBG_SUCCESS; |
6331 | | } |
6332 | | } |
6333 | | #endif |
6334 | | #elif defined(WOLFSSL_SMALL_STACK) |
6335 | 0 | byte* newSeed = (byte*)XMALLOC(SEED_SZ + SEED_BLOCK_SZ, rng->heap, |
6336 | 0 | DYNAMIC_TYPE_SEED); |
6337 | 0 | ret = (newSeed == NULL) ? MEMORY_E : DRBG_SUCCESS; |
6338 | | #else |
6339 | | byte newSeed[SEED_SZ + SEED_BLOCK_SZ]; |
6340 | | ret = DRBG_SUCCESS; |
6341 | | #endif |
6342 | 0 | if (ret == DRBG_SUCCESS) { |
6343 | | #ifdef WC_RNG_SEED_CB |
6344 | | if (seedCb == NULL) { |
6345 | | ret = DRBG_NO_SEED_CB; |
6346 | | } |
6347 | | else { |
6348 | | ret = seedCb(&rng->seed, newSeed, SEED_SZ + SEED_BLOCK_SZ); |
6349 | | if (ret != 0) { |
6350 | | #ifdef WC_RNG_DEBUG_STATS |
6351 | | ++rng->_stats_seed_failures; |
6352 | | #endif |
6353 | | #ifdef WC_VERBOSE_RNG |
6354 | | if ((ret != WC_NO_ERR_TRACE(BUSY_E)) && |
6355 | | (ret != WC_NO_ERR_TRACE(MEMORY_E)) && |
6356 | | /* ASN_OCSP_CONFIRM_E here is a nonsense error code used |
6357 | | * by unit tests for forced failures. */ |
6358 | | (ret != WC_NO_ERR_TRACE(ASN_OCSP_CONFIRM_E))) |
6359 | | { |
6360 | | WOLFSSL_DEBUG_PRINTF("ERROR: seedCb() in PollAndReSeed() " |
6361 | | "failed with err %d", ret); |
6362 | | } |
6363 | | #endif |
6364 | | if (ret > 0) /* app callback: keep negative codes */ |
6365 | | ret = DRBG_FAILURE; |
6366 | | } |
6367 | | } |
6368 | | #else |
6369 | 0 | ret = wc_GenerateSeed(&rng->seed, newSeed, |
6370 | 0 | SEED_SZ + SEED_BLOCK_SZ); |
6371 | 0 | if (ret != 0) { |
6372 | | #ifdef WC_RNG_DEBUG_STATS |
6373 | | ++rng->_stats_seed_failures; |
6374 | | #endif |
6375 | | #ifdef WC_VERBOSE_RNG |
6376 | | if ((ret != WC_NO_ERR_TRACE(BUSY_E)) && |
6377 | | (ret != WC_NO_ERR_TRACE(MEMORY_E))) |
6378 | | { |
6379 | | WOLFSSL_DEBUG_PRINTF( |
6380 | | "ERROR: wc_GenerateSeed() in PollAndReSeed() failed with " |
6381 | | "err %d", ret); |
6382 | | } |
6383 | | #endif |
6384 | 0 | } |
6385 | 0 | #endif |
6386 | 0 | } |
6387 | 0 | if (ret == DRBG_SUCCESS) { |
6388 | 0 | ret = wc_RNG_TestSeed(newSeed, SEED_SZ + SEED_BLOCK_SZ); |
6389 | | #ifdef WC_RNG_DEBUG_STATS |
6390 | | if (ret != DRBG_SUCCESS) |
6391 | | ++rng->_stats_seed_failures; |
6392 | | #endif |
6393 | | #ifdef WC_VERBOSE_RNG |
6394 | | if ((ret != DRBG_SUCCESS) && |
6395 | | (ret != WC_NO_ERR_TRACE(ENTROPY_RT_E)) && |
6396 | | (ret != WC_NO_ERR_TRACE(ENTROPY_APT_E))) |
6397 | | { |
6398 | | WOLFSSL_DEBUG_PRINTF( |
6399 | | "ERROR: wc_RNG_TestSeed() in PollAndReSeed() returned " |
6400 | | "err %d.", ret); |
6401 | | } |
6402 | | #endif |
6403 | 0 | } |
6404 | 0 | if (ret == DRBG_SUCCESS) { |
6405 | 0 | ret = Hash_DRBG_Reseed(rng, newSeed + SEED_BLOCK_SZ, SEED_SZ, |
6406 | 0 | additional, additionalSz, |
6407 | 0 | 0 /* in_bracketed_consume */, cur_epoch, |
6408 | 0 | my_pid); |
6409 | |
|
6410 | | #if defined(WC_RNG_HAVE_RBGC) && \ |
6411 | | !defined(WC_RNG_RBGC_STRATUM_IMMUTABLE) |
6412 | | if (ret == 0) |
6413 | | rng->RBGCStratum = 0; |
6414 | | #endif |
6415 | 0 | } |
6416 | 0 | #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_SMALL_STACK_CACHE) |
6417 | 0 | if (newSeed != NULL) { |
6418 | 0 | ForceZero(newSeed, SEED_SZ + SEED_BLOCK_SZ); |
6419 | 0 | } |
6420 | 0 | XFREE(newSeed, rng->heap, DYNAMIC_TYPE_SEED); |
6421 | | #else |
6422 | | /* newSeed is a byte[] in the plain build but a byte* in the |
6423 | | * SMALL_STACK_CACHE build, so use the explicit buffer length (not |
6424 | | * sizeof) to zero the whole reseed entropy buffer in both cases. */ |
6425 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
6426 | | wc_MemZero_Add("PollAndReSeed newSeed", newSeed, |
6427 | | SEED_SZ + SEED_BLOCK_SZ); |
6428 | | #endif |
6429 | | ForceZero(newSeed, SEED_SZ + SEED_BLOCK_SZ); |
6430 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
6431 | | wc_MemZero_Check(newSeed, SEED_SZ + SEED_BLOCK_SZ); |
6432 | | #endif |
6433 | | #endif |
6434 | 0 | } |
6435 | | /* else pass back the failure code from wc_RNG_HealthTestLocal(): |
6436 | | * DRBG_CONT_FAILURE from the KAT means ConstantCompare mismatch, i.e. a |
6437 | | * machinery failure; infrastructure codes (MEMORY_E, or DRBG_FAILURE as the |
6438 | | * internal ops' catch-all) are distinct and retryable. |
6439 | | */ |
6440 | |
|
6441 | | #if defined(WC_RNG_HAVE_RBGC) && defined(WC_RNG_HAVE_LOCK) |
6442 | | out: |
6443 | | #endif |
6444 | |
|
6445 | 0 | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
6446 | 0 | if ((ret == 0) && |
6447 | 0 | (cur_epoch != WOLFSSL_ATOMIC_LOAD(global_entropy_epoch))) |
6448 | 0 | { |
6449 | | /* An event landed between the caller's capture and here: the material |
6450 | | * reseeded is possibly pre-event. The reseed stands (the state is no |
6451 | | * worse than before), but the obligation is not discharged, and |
6452 | | * the caller must not serve from this state. */ |
6453 | 0 | ret = DRBG_NEED_RESEED; |
6454 | 0 | } |
6455 | 0 | #endif |
6456 | |
|
6457 | 0 | #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) |
6458 | 0 | if ((ret == 0) && (my_pid != getpid())) { |
6459 | | /* See note above re epoch. (The stamp itself is Hash_DRBG_Reseed()'s, |
6460 | | * from the same capture.) */ |
6461 | 0 | ret = DRBG_NEED_RESEED; |
6462 | 0 | } |
6463 | 0 | #endif |
6464 | |
|
6465 | 0 | return ret; |
6466 | 0 | } |
6467 | | |
6468 | | /* Immediately reseed rng from the module's built-in or previously registered or |
6469 | | * associated seed source, exactly as the WC_RESEED_INTERVAL backstop does |
6470 | | * during a generate operation, via PollAndReSeed(). The reseed counter is |
6471 | | * reset iff the reseed succeeds. If nonceSz > 0, nonce is incorporated into |
6472 | | * the same reseed derivation as (uncredited) additional input, with the |
6473 | | * semantics of wc_RNG_DRBG_Stir(), in a single state transition. On failure |
6474 | | * the reseed counter is not reset and rng->status is unchanged, unless the DRBG |
6475 | | * is out of reseed runway, or DRBG_CONT_FAILED occurred. |
6476 | | * |
6477 | | * The caller must hold exclusive access to rng, as for all WC_RNG operations. |
6478 | | */ |
6479 | | int wc_RNG_DRBG_Reseed_Now(WC_RNG* rng, const byte* nonce, word32 nonceSz) |
6480 | 0 | { |
6481 | 0 | int ret; |
6482 | |
|
6483 | 0 | if (rng == NULL) |
6484 | 0 | return BAD_FUNC_ARG; |
6485 | 0 | if ((nonce == NULL) && (nonceSz > 0)) |
6486 | 0 | return BAD_FUNC_ARG; |
6487 | 0 | ret = rng_lock_required_check(rng); |
6488 | 0 | if (ret != 0) |
6489 | 0 | return ret; |
6490 | | |
6491 | | /* Not reached from the generate path, so it takes the lock here. The |
6492 | | * checks below read state a generate writes under it, so they follow. */ |
6493 | 0 | ret = RngAutoLockEnter(rng); |
6494 | 0 | if (ret != 0) |
6495 | 0 | return ret; |
6496 | | |
6497 | | /* Mirror wc_RNG_GenerateBlock(): only an in-service DRBG may reseed. */ |
6498 | 0 | ret = wc_RNG_Status(rng); |
6499 | 0 | if (ret != 0) |
6500 | 0 | goto out; |
6501 | | |
6502 | 0 | if (! wc_RNG_DRBG_Present(rng)) { |
6503 | | /* No DRBG instantiated -- nothing to reseed (RDRAND et al.). */ |
6504 | 0 | ret = 0; |
6505 | 0 | goto out; |
6506 | 0 | } |
6507 | | |
6508 | 0 | ret = PollAndReSeed(rng, nonce, nonceSz); |
6509 | 0 | if (ret != DRBG_SUCCESS) |
6510 | 0 | ret = RngGenerateFailure(rng, ret); |
6511 | |
|
6512 | 0 | out: |
6513 | |
|
6514 | 0 | RngAutoLockExit(rng); |
6515 | 0 | return ret; |
6516 | 0 | } |
6517 | | |
6518 | | /* wc_RNG_DRBG_Reseed_Now_Primary() allows SP 800-90A prediction resistant |
6519 | | * constructions even when the underlying RNG was RBGC-initialized. In |
6520 | | * _HAVE_LOCK configurations, the RNG must assert _LOCK_REQUIRED, so that the |
6521 | | * sequence of primary reseed and byte generation is guaranteed atomic. |
6522 | | * Multithreaded configurations without _HAVE_LOCK cannot support PR and the flag |
6523 | | * RMW it requires. */ |
6524 | | int wc_RNG_DRBG_Reseed_Now_Primary(WC_RNG* rng, |
6525 | | const byte* nonce, word32 nonceSz) |
6526 | 0 | { |
6527 | 0 | int ret; |
6528 | 0 | if (rng == NULL) |
6529 | 0 | return BAD_FUNC_ARG; |
6530 | 0 | ret = rng_lock_required_check(rng); |
6531 | 0 | if (ret != 0) |
6532 | 0 | return ret; |
6533 | | #ifdef WC_RNG_HAVE_LOCK |
6534 | | if (! (WOLFSSL_ATOMIC_LOAD(rng->lock) & WC_RNG_LOCK_REQUIRED)) |
6535 | | return WRONG_TYPE_OBJECT_E; |
6536 | | #endif |
6537 | 0 | #if !defined(WC_RNG_HAVE_LOCK) && !defined(SINGLE_THREADED) |
6538 | 0 | (void)nonce; |
6539 | 0 | (void)nonceSz; |
6540 | 0 | return NOT_COMPILED_IN; |
6541 | | #else /* WC_RNG_HAVE_LOCK || SINGLE_THREADED */ |
6542 | | if (rng->flags & WC_RNG_FLAG_NO_PRIMARY_SEED) |
6543 | | return WRONG_TYPE_OBJECT_E; |
6544 | | { |
6545 | | word32 restore_flag_bits; |
6546 | | if (! (rng->flags & WC_RNG_FLAG_ONLY_PRIMARY_SEED)) { |
6547 | | restore_flag_bits = WC_RNG_FLAG_ONLY_PRIMARY_SEED; |
6548 | | rng->flags |= restore_flag_bits; |
6549 | | } |
6550 | | else |
6551 | | restore_flag_bits = 0U; |
6552 | | ret = wc_RNG_DRBG_Reseed_Now(rng, nonce, nonceSz); |
6553 | | if (restore_flag_bits) |
6554 | | rng->flags &= ~restore_flag_bits; |
6555 | | } |
6556 | | return ret; |
6557 | | #endif /* WC_RNG_HAVE_LOCK || SINGLE_THREADED */ |
6558 | 0 | } |
6559 | | |
6560 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
6561 | | |
6562 | | /* Banked-next-seed services. _NextSeedGenerate() banks up to n more |
6563 | | * bytes from the module's seed source (clamped to the space remaining; |
6564 | | * ALREADY_E when the bank is ready or being consumed), health-testing |
6565 | | * and publishing the bank when it completes, burning it on a failed |
6566 | | * health test (ENTROPY_RT_E / ENTROPY_APT_E); a scheduling daemon may |
6567 | | * call it without owning the instance. |
6568 | | * _NextSeedCurrent() reports the raw aperture value (racy snapshot). |
6569 | | * _NextSeedNow() claims a ready bank and performs a source-free |
6570 | | * credited reseed with it -- safe in atomic context -- or returns |
6571 | | * NOT_READY_E when no bank is ready; _NextSeedNow_Nonce() is the same |
6572 | | * with a nonce as uncredited additional input. An instance with no |
6573 | | * DRBG (RDRAND et al.) never opens its seed aperture, and producers |
6574 | | * and consumers alike refuse it with WRONG_TYPE_OBJECT_E. The caller |
6575 | | * must own the instance for _NextSeedNow[_Nonce](). */ |
6576 | | |
6577 | | /* Banked-next-seed protocol. |
6578 | | * |
6579 | | * Entropy is gathered incrementally, in-boundary, from the |
6580 | | * module's seed source by wc_RNG_DRBG_NextSeedGenerate(), and consumed |
6581 | | * (source-free, atomic-context-safe) by wc_RNG_DRBG_NextSeedNow(). |
6582 | | * WC_RNG.nextSeedLen is the hand-off aperture, a wolfSSL_Atomic_Int: values |
6583 | | * in [0, bank length) count banked bytes with no producer in flight; |
6584 | | * _PRODUCING marks a producer's fill claim; _READY marks a complete, |
6585 | | * health-tested bank; _CONSUMING marks exclusive ownership by a consumer (or |
6586 | | * by a purge wiping unowned material); _PURGED marks a live claim repainted |
6587 | | * by an invalidation, which the holder reopens; _TORNDOWN marks an instance |
6588 | | * between teardown and reinitialization, which only a constructor reopens. |
6589 | | * |
6590 | | * Every ownership transition is a CAS: a producer claims a non-negative word |
6591 | | * (_PRODUCING) and releases by CAS to the new fill offset, _READY, or |
6592 | | * _EMPTY; a consumer claims _READY -> _CONSUMING, consumes, zeroizes, and |
6593 | | * releases by CAS to _EMPTY; a purge (NextSeedPurge()) claims unowned |
6594 | | * material _CONSUMING and reopens by CAS, or repaints a live claim _PURGED |
6595 | | * for its holder to unwind. A failed release is information, never |
6596 | | * contention: it proves a purge or a teardown intervened. Gathering draws |
6597 | | * from the configured / installed entropy source directly, never from |
6598 | | * rng->seed, so a producer does not race an owner's own source reseed, and |
6599 | | * touches no other DRBG state. */ |
6600 | | |
6601 | | /* Bank up to n more bytes of seed material from a supplied root RNG into |
6602 | | * rng's next-seed bank. Callable without owning the instance (the scheduling |
6603 | | * daemon's entry point); deliberately independent of rng->status so that |
6604 | | * banking can proceed for any instantiated DRBG. n is clamped to the space |
6605 | | * remaining; a ready or consuming bank is signaled with ALREADY_E. On |
6606 | | * completing the bank, the material is health-tested (wc_RNG_TestSeed()) and |
6607 | | * published; a failed test consumes the material (use-once) and returns the |
6608 | | * test's error, leaving an empty bank for the next cycle. A gather failure |
6609 | | * leaves the partial bank intact for retry. */ |
6610 | | static WARN_UNUSED_RESULT int wc_RNG_DRBG_NextSeedGenerate_local( |
6611 | | WC_RNG* rng, WC_RNG* root, |
6612 | | word32 n) |
6613 | | { |
6614 | | int claim_ret; |
6615 | | WC_ATOMIC_INT_ARG cur; |
6616 | | word32 nextSeedSz = WC_DRBG_SEED_BUF_SIZE; |
6617 | | int ret; |
6618 | | |
6619 | | if ((rng == NULL) || (n == 0) || (rng == root)) |
6620 | | return BAD_FUNC_ARG; |
6621 | | |
6622 | | if (! wc_RNG_DRBG_Present(rng)) |
6623 | | return WRONG_TYPE_OBJECT_E; |
6624 | | |
6625 | | #if defined(WC_RNG_HAVE_RBGC) && defined(WC_RNG_RBGC_STRATUM_IMMUTABLE) |
6626 | | if ((root != NULL) && |
6627 | | (rng->RBGCStratum == 0)) |
6628 | | { |
6629 | | return WRONG_TYPE_OBJECT_E; |
6630 | | } |
6631 | | #endif |
6632 | | |
6633 | | #if defined(WC_RNG_HAVE_ENTROPY_EPOCH) || \ |
6634 | | (defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID)) |
6635 | | ret = rng_entropy_event_propagate(rng); |
6636 | | if ((ret != 0) && (ret != WC_NO_ERR_TRACE(NEEDS_RECOVERY_E))) |
6637 | | return ret; |
6638 | | #endif |
6639 | | |
6640 | | if (root) { |
6641 | | ret = rng_lock_required_check(root); |
6642 | | if (ret != 0) |
6643 | | return ret; |
6644 | | #ifdef WC_RNG_HAVE_RBGC |
6645 | | if ((root->RBGCStratum > 0) |
6646 | | #ifndef WC_RNG_NO_RBGC_RESEED |
6647 | | && (root->RBGCStratum >= rng->RBGCStratum) |
6648 | | #else |
6649 | | /* Credited reseed from root only, by policy. */ |
6650 | | #endif |
6651 | | ) |
6652 | | { |
6653 | | return BAD_FUNC_ARG; |
6654 | | } |
6655 | | |
6656 | | #ifdef HAVE_FIPS |
6657 | | /* SP-800-90C requires that an RBGC seed source be the original parent, or |
6658 | | * in the alternative, "a sibling of the parent, an ancestor, or the initial |
6659 | | * randomness source". We can't safely ascend through multiple links, |
6660 | | * because the tree may have been broken by a wc_FreeRng(), so we use the |
6661 | | * same criterion as wc_RNG_DRBG_ReseedRBGC_local() to qualify the supplied |
6662 | | * root. */ |
6663 | | { |
6664 | | /* One load: reachable from the unowned-caller entry |
6665 | | * (wc_RNG_DRBG_NextSeedGenerate()), where a concurrent |
6666 | | * teardown can CAS-null rng->RBGC_parent between the null |
6667 | | * check and the dereference. */ |
6668 | | WC_RNG * const parent = rng->RBGC_parent; |
6669 | | if ((parent != NULL) && |
6670 | | (parent != root) && |
6671 | | ((parent->RBGCStratum > 0) || |
6672 | | (root->RBGCStratum > 0))) |
6673 | | { |
6674 | | return WRONG_TYPE_OBJECT_E; |
6675 | | } |
6676 | | } |
6677 | | #endif /* HAVE_FIPS */ |
6678 | | |
6679 | | if (root->RBGCStratum >= WC_MAX_SINT_OF(int)) |
6680 | | return SEQ_OVERFLOW_E; |
6681 | | else if (root->RBGCStratum == WC_RNG_RBGC_USER_SEED_STRATUM - 1) |
6682 | | return SEQ_OVERFLOW_E; |
6683 | | #else |
6684 | | return NOT_COMPILED_IN; |
6685 | | #endif |
6686 | | } |
6687 | | |
6688 | | cur = WOLFSSL_ATOMIC_LOAD(rng->nextSeedLen); |
6689 | | { |
6690 | | /* Producer claim: exactly one banker may fill or publish at a |
6691 | | * time. Concurrent fills would be tolerable as BYTES (a torn |
6692 | | * mix is still entropy) but poisonous as CLAIMS: interleaved |
6693 | | * primary/RBGC production could publish material under the |
6694 | | * wrong stratum or health-test disposition. The claim makes |
6695 | | * produce-side exclusivity a CAS, matching the consume side's |
6696 | | * READY -> CONSUMING claim. This lane only: the uncredited |
6697 | | * accumulator above stays multi-writer by design. */ |
6698 | | WC_CAS_WITH_RETRY_BEGIN(&rng->nextSeedLen, cur, claim_ret) { |
6699 | | if ((cur == WC_DRBG_NEXT_SEED_PRODUCING) || |
6700 | | (cur == WC_DRBG_NEXT_SEED_PURGED) || |
6701 | | (cur == WC_DRBG_NEXT_SEED_TORNDOWN)) |
6702 | | { |
6703 | | /* A producer is in flight (or unwinding a purge), or |
6704 | | * the instance is between teardown and reinitialization |
6705 | | * (_TORNDOWN, a constructor's to reopen): retryable on a |
6706 | | * later banking cycle. Traced: the competing producer |
6707 | | * -- typically the entropy daemon -- is the diagnosis a |
6708 | | * surprised caller needs. */ |
6709 | | return BUSY_E; |
6710 | | } |
6711 | | if (cur < 0) { |
6712 | | /* Ready or consuming -- nothing to do. */ |
6713 | | return WC_NO_ERR_TRACE(ALREADY_E); /* not an error */ |
6714 | | } |
6715 | | WC_CAS_WITH_RETRY_LOOP_FOREVER(wolfSSL_Atomic_Int_CompareExchange, |
6716 | | &rng->nextSeedLen, cur, |
6717 | | WC_DRBG_NEXT_SEED_PRODUCING, |
6718 | | claim_ret); |
6719 | | } WC_CAS_WITH_RETRY_END; |
6720 | | if (claim_ret != 0) { |
6721 | | /* Aborted claim (a port's retry clause): nothing claimed, |
6722 | | * nothing moved. Proceeding would fill and adjudicate an |
6723 | | * unclaimed aperture -- the torn-claims disease the |
6724 | | * producer mutex exists to prevent. */ |
6725 | | return claim_ret; |
6726 | | } |
6727 | | if (cur == (WC_ATOMIC_INT_ARG)nextSeedSz) { |
6728 | | /* Complete but unpublished (interrupted between fill |
6729 | | * completion and publication): retry the health test and |
6730 | | * publication below. */ |
6731 | | n = 0; |
6732 | | } |
6733 | | /* From here to release/publication the aperture word is |
6734 | | * PRODUCING; fill progress lives only in the local cur, and |
6735 | | * every exit passes through NextSeedProducerRelease(). */ |
6736 | | } |
6737 | | |
6738 | | if (n > 0) { |
6739 | | #ifdef WC_RNG_HAVE_RBGC |
6740 | | if (root) { |
6741 | | /* If primary seed bytes were carried forward, reset now to avoid |
6742 | | * wc_RNG_TestSeed() at completion. Local only: the word is |
6743 | | * held at PRODUCING. */ |
6744 | | if ((cur > 0) && (rng->nextSeedRBGCStratum == 0)) |
6745 | | cur = 0; |
6746 | | |
6747 | | if (n > nextSeedSz - (word32)cur) |
6748 | | n = nextSeedSz - (word32)cur; |
6749 | | |
6750 | | ret = wc_RNG_GenerateBlock(root, rng->nextSeed + cur, n); |
6751 | | if (ret != 0) { |
6752 | | /* Partial bank preserved -- retry on a later cycle. |
6753 | | * (If a purge landed meanwhile, the release discards |
6754 | | * instead; the draw failure is the more informative |
6755 | | * code and wins over the release's BUSY_E.) |
6756 | | * |
6757 | | * Note, a failed release cannot brick the RNG and needs no |
6758 | | * disposition at the several (void) sites below: its one cause |
6759 | | * is a purge's _PURGED repaint (producers cannot claim a |
6760 | | * PRODUCING word, consumers exchange only from READY, and the |
6761 | | * purge is the sole other writer), and the BUSY arm is its own |
6762 | | * compensation -- it wipes and reopens the aperture EMPTY |
6763 | | * before returning. Afterward the world is fully consistent: |
6764 | | * aperture empty and healthy, rng->status untouched, recovery |
6765 | | * proceeding through the event's normal channels. BUSY_E is |
6766 | | * information, not a condition awaiting action; the caller's |
6767 | | * own error outranks it wherever one is in flight. Cost of |
6768 | | * swallowing it: at worst one silent refill from offset |
6769 | | * zero. |
6770 | | */ |
6771 | | (void)NextSeedProducerRelease(&rng->nextSeedLen, rng->nextSeed, |
6772 | | nextSeedSz, cur); |
6773 | | return ret; |
6774 | | } |
6775 | | |
6776 | | /* If RBGC seed bytes were carried forward, make sure we're |
6777 | | * pessimistic about the RBGC stratum. */ |
6778 | | if ((cur == 0) || (rng->nextSeedRBGCStratum < root->RBGCStratum + 1)) |
6779 | | rng->nextSeedRBGCStratum = root->RBGCStratum + 1; |
6780 | | } |
6781 | | else |
6782 | | #endif /* WC_RNG_HAVE_RBGC */ |
6783 | | { |
6784 | | /* wc_GenerateSeed() must be called completely independent of rng, |
6785 | | * aside from the memory aperture itself. For safety, we pass a |
6786 | | * dummy OS_Seed, which will be ignored by the wc_GenerateSeed() |
6787 | | * typically used in conjunction with WC_RNG_HAVE_NEXT_SEED. |
6788 | | */ |
6789 | | struct OS_Seed os; |
6790 | | |
6791 | | /* Named-member init: layout-proof against OS_Seed growing or |
6792 | | * reordering members under its several config axes. */ |
6793 | | XMEMSET(&os, 0, sizeof(os)); |
6794 | | #ifndef USE_WINDOWS_API |
6795 | | os.fd = -1; |
6796 | | #endif |
6797 | | #ifdef WOLF_CRYPTO_CB |
6798 | | /* devId is config, not state: a callback-only seed source must |
6799 | | * serve the bank the same way it serves wc_InitRng(). */ |
6800 | | os.devId = rng->seed.devId; |
6801 | | #endif |
6802 | | |
6803 | | #ifdef WC_RNG_HAVE_RBGC |
6804 | | /* If RBGC seed bytes were carried forward, reset now to avoid |
6805 | | * intermixture and force wc_RNG_TestSeed() at completion. |
6806 | | * Local only: the word is held at PRODUCING. */ |
6807 | | if ((cur > 0) && (rng->nextSeedRBGCStratum > 0)) |
6808 | | cur = 0; |
6809 | | #endif |
6810 | | |
6811 | | if (n > nextSeedSz - (word32)cur) |
6812 | | n = nextSeedSz - (word32)cur; |
6813 | | |
6814 | | ret = wc_GenerateSeed(&os, rng->nextSeed + cur, n); |
6815 | | if (ret != 0) { |
6816 | | /* Partial bank preserved -- retry on a later cycle. |
6817 | | * (If a purge landed meanwhile, the release discards |
6818 | | * instead; the seed-gather failure is the more |
6819 | | * informative code and wins over the release's |
6820 | | * BUSY_E.) */ |
6821 | | (void)NextSeedProducerRelease(&rng->nextSeedLen, rng->nextSeed, |
6822 | | nextSeedSz, cur); |
6823 | | return ret; |
6824 | | } |
6825 | | |
6826 | | #ifdef WC_RNG_HAVE_RBGC |
6827 | | rng->nextSeedRBGCStratum = 0; |
6828 | | #endif |
6829 | | } |
6830 | | |
6831 | | cur += (int)n; |
6832 | | } |
6833 | | |
6834 | | if (cur < (WC_ATOMIC_INT_ARG)nextSeedSz) { |
6835 | | /* Partial credited fill this call: release the claim back to |
6836 | | * the fill offset for a later cycle to resume. A purge |
6837 | | * meanwhile discards instead, and the release's BUSY_E |
6838 | | * percolates -- returning 0 would claim banked progress the |
6839 | | * purge just evaporated. */ |
6840 | | return NextSeedProducerRelease(&rng->nextSeedLen, rng->nextSeed, |
6841 | | nextSeedSz, cur); |
6842 | | } |
6843 | | |
6844 | | if (cur == (WC_ATOMIC_INT_ARG)nextSeedSz) { |
6845 | | #ifdef WC_RNG_HAVE_RBGC |
6846 | | /* If RBGC bytes were used for the reseed, then we can skip |
6847 | | * wc_RNG_TestSeed(). */ |
6848 | | if (rng->nextSeedRBGCStratum > 0) { |
6849 | | ret = NextSeedProducerRelease(&rng->nextSeedLen, rng->nextSeed, |
6850 | | nextSeedSz, WC_DRBG_NEXT_SEED_READY); |
6851 | | if (ret != 0) { |
6852 | | /* Purged while producing (BUSY_E): nothing banked; |
6853 | | * post-event material wanted. Retryable. */ |
6854 | | return ret; |
6855 | | } |
6856 | | #ifdef WC_RNG_DEBUG_STATS |
6857 | | ++rng->_stats_nextseedsbanked; |
6858 | | #endif |
6859 | | return 0; |
6860 | | } |
6861 | | #endif |
6862 | | /* Bank complete: health-test now, in advance of consumption, so |
6863 | | * that wc_RNG_DRBG_NextSeedNow() is pure computation. */ |
6864 | | ret = wc_RNG_TestSeed(rng->nextSeed, nextSeedSz); |
6865 | | if (ret == 0) { |
6866 | | ret = NextSeedProducerRelease(&rng->nextSeedLen, rng->nextSeed, |
6867 | | nextSeedSz, WC_DRBG_NEXT_SEED_READY); |
6868 | | if (ret != 0) { |
6869 | | /* Purged while producing (BUSY_E): nothing banked; |
6870 | | * post-event material wanted. Retryable. */ |
6871 | | return ret; |
6872 | | } |
6873 | | #ifdef WC_RNG_DEBUG_STATS |
6874 | | ++rng->_stats_nextseedsbanked; |
6875 | | #endif |
6876 | | return 0; |
6877 | | } |
6878 | | else if ((ret == WC_NO_ERR_TRACE(ENTROPY_RT_E)) || |
6879 | | (ret == WC_NO_ERR_TRACE(ENTROPY_APT_E))) |
6880 | | { |
6881 | | /* Use-once: a failed test consumes the material. */ |
6882 | | #ifdef WC_RNG_DEBUG_STATS |
6883 | | ++rng->_stats_seed_failures; |
6884 | | #endif |
6885 | | /* Wiped under the PRODUCING claim: a purge only repaints the |
6886 | | * sentinel, so the buffer is still ours. Burn and purge-discard |
6887 | | * converge on EMPTY, and the health-test failure is the more |
6888 | | * informative code and wins over the release's BUSY_E. */ |
6889 | | ForceZero(rng->nextSeed, nextSeedSz); |
6890 | | (void)NextSeedProducerRelease(&rng->nextSeedLen, rng->nextSeed, |
6891 | | nextSeedSz, WC_DRBG_NEXT_SEED_EMPTY); |
6892 | | |
6893 | | /* The health-test failure belongs to the depositor's seed |
6894 | | * collection, not to the destination RNG. The depositor collects |
6895 | | * via wc_GenerateSeed(), banks into rng's aperture, and tests |
6896 | | * before publishing; on failure the aperture is reset to _EMPTY, |
6897 | | * so nothing untested is ever visible to rng. rng is a passive |
6898 | | * destination here -- it did not consume the material, and its |
6899 | | * state, status and reseed schedule are untouched. Do not mark it |
6900 | | * failed. |
6901 | | * |
6902 | | * PollAndReSeed() looks similar and is not: there, rng is reseeding |
6903 | | * itself from its own seed source, the tested material is on the |
6904 | | * path into its own state, and a failure indeed means that that |
6905 | | * instance's source has failed. DRBG_FAILED is correct there and |
6906 | | * wrong here. Per-instance attribution is meaningful, not |
6907 | | * arbitrary: seed sources are frequently core-local (RDSEED among |
6908 | | * them), so one instance's source can fail while its siblings' are |
6909 | | * healthy. |
6910 | | * |
6911 | | * Bigger picture: An RCT/APT failure is an entropy-source event (SP |
6912 | | * 800-90B 4.4), and wc_RNG_TestSeed's cutoffs carry a designed |
6913 | | * false-positive rate. A terminal response from a thread that is |
6914 | | * not the instance's owner would effectively be a remote kill |
6915 | | * primitive on a tuned statistical alarm. |
6916 | | */ |
6917 | | |
6918 | | return ret; |
6919 | | } |
6920 | | else { |
6921 | | /* Buggy or brokey. Release complete-but-unpublished; the |
6922 | | * material is untested but intact, and a later cycle |
6923 | | * re-adjudicates. The primary error is the more |
6924 | | * informative code and wins over a purge-discard's |
6925 | | * BUSY_E. */ |
6926 | | (void)NextSeedProducerRelease( |
6927 | | &rng->nextSeedLen, rng->nextSeed, |
6928 | | nextSeedSz, (WC_ATOMIC_INT_ARG)nextSeedSz); |
6929 | | return ret; |
6930 | | } |
6931 | | } |
6932 | | |
6933 | | return 0; |
6934 | | } |
6935 | | |
6936 | | int wc_RNG_DRBG_NextSeedGenerate_Primary(WC_RNG* rng, word32 n) { |
6937 | | if (rng == NULL) |
6938 | | return BAD_FUNC_ARG; |
6939 | | if (rng->flags & WC_RNG_FLAG_NO_PRIMARY_SEED) |
6940 | | return WRONG_TYPE_OBJECT_E; |
6941 | | return wc_RNG_DRBG_NextSeedGenerate_local(rng, NULL, n); |
6942 | | } |
6943 | | |
6944 | | #ifdef WC_RNG_HAVE_RBGC |
6945 | | int wc_RNG_DRBG_NextSeedGenerate_RBGC(WC_RNG* rng, WC_RNG *root, word32 n) { |
6946 | | if (root == NULL) |
6947 | | return BAD_FUNC_ARG; |
6948 | | return wc_RNG_DRBG_NextSeedGenerate_local(rng, root, n); |
6949 | | } |
6950 | | #endif |
6951 | | |
6952 | | int wc_RNG_DRBG_NextSeedGenerate(WC_RNG* rng, word32 n) { |
6953 | | if (rng == NULL) |
6954 | | return BAD_FUNC_ARG; |
6955 | | |
6956 | | #if defined(WC_RNG_HAVE_RBGC) && defined(WC_RNG_HAVE_LOCK) |
6957 | | if (rng->RBGCStratum > 0) { |
6958 | | int ret = WC_NO_ERR_TRACE(NEEDS_RECOVERY_E); |
6959 | | int put_ret; |
6960 | | /* Captured once: this entry admits unowned callers by design (a |
6961 | | * scheduling daemon synchronizes through the next-seed aperture, |
6962 | | * not the instance lease), so a concurrent teardown of rng can |
6963 | | * CAS-null rng->RBGC_parent mid-call, and the put below must |
6964 | | * release exactly what the get acquired. Contrast the owned-rng |
6965 | | * reseed paths (PollAndReSeed() et al.): ownership of rng makes |
6966 | | * RBGC_parent stable there, and no capture is used. |
6967 | | * |
6968 | | * Storage lifetime is the usual shell contract: wc_FreeRng() may |
6969 | | * retire parent or child at any time (the shells' words stay live |
6970 | | * and refuse coherently), but free() of either shell requires |
6971 | | * quiescing unowned callers first. Every in-tree parent is a |
6972 | | * bank root or the static global fallback, satisfying this by |
6973 | | * construction. */ |
6974 | | WC_RNG * const parent = rng->RBGC_parent; |
6975 | | if ((wc_RNG_Status(parent) == 0) && |
6976 | | (wc_RNG_lock_get(parent, 0) == 0)) |
6977 | | { |
6978 | | ret = wc_RNG_DRBG_NextSeedGenerate_local(rng, parent, n); |
6979 | | put_ret = wc_RNG_lock_put(parent, 0); |
6980 | | if (put_ret != 0) { |
6981 | | if (put_ret == WC_NO_ERR_TRACE(NEEDS_RECOVERY_E)) { |
6982 | | int purge_ret = NextSeedPurge(rng); |
6983 | | if ((purge_ret != 0) && (purge_ret != WC_NO_ERR_TRACE(ALREADY_E))) |
6984 | | return purge_ret; |
6985 | | } |
6986 | | else |
6987 | | return put_ret; /* internal failure is most salient */ |
6988 | | } |
6989 | | if (ret == 0) { |
6990 | | if (put_ret == 0) |
6991 | | return 0; |
6992 | | else |
6993 | | ret = put_ret; |
6994 | | } |
6995 | | } |
6996 | | if ((wc_RNG_Status(&global_fallback_rng) == 0) && |
6997 | | #ifdef HAVE_FIPS |
6998 | | /* SP-800-90C requires that an alternative randomness source be "a |
6999 | | * sibling of the parent, an ancestor, or the initial randomness |
7000 | | * source". */ |
7001 | | (parent != NULL) && |
7002 | | ((global_fallback_rng.RBGCStratum == 0) && |
7003 | | (global_fallback_rng.RBGCStratum == |
7004 | | parent->RBGCStratum)) && |
7005 | | #endif |
7006 | | (wc_RNG_lock_get(&global_fallback_rng, 0) == 0)) |
7007 | | { |
7008 | | ret = wc_RNG_DRBG_NextSeedGenerate_local(rng, &global_fallback_rng, n); |
7009 | | put_ret = wc_RNG_lock_put(&global_fallback_rng, 0); |
7010 | | if (put_ret != 0) { |
7011 | | if (put_ret == WC_NO_ERR_TRACE(NEEDS_RECOVERY_E)) { |
7012 | | int purge_ret = NextSeedPurge(rng); |
7013 | | if ((purge_ret != 0) && (purge_ret != WC_NO_ERR_TRACE(ALREADY_E))) |
7014 | | return purge_ret; |
7015 | | } |
7016 | | else |
7017 | | return put_ret; /* internal failure is most salient */ |
7018 | | } |
7019 | | if (ret == 0) { |
7020 | | if (put_ret == 0) |
7021 | | return 0; |
7022 | | else |
7023 | | ret = put_ret; |
7024 | | } |
7025 | | } |
7026 | | if (rng->flags & WC_RNG_FLAG_NO_PRIMARY_SEED) |
7027 | | return ret; |
7028 | | } |
7029 | | /* else fall through to primary reseed. */ |
7030 | | #elif defined(WC_RNG_HAVE_RBGC) |
7031 | | /* see PollAndReSeed(): no ladder without the lock facility -- an |
7032 | | * instance barred from the primary seed source defers to the caller's |
7033 | | * own chain maintenance (wc_RNG_DRBG_NextSeedGenerate_RBGC()). */ |
7034 | | if ((rng->RBGCStratum > 0) && |
7035 | | (rng->flags & WC_RNG_FLAG_NO_PRIMARY_SEED)) |
7036 | | { |
7037 | | return NEEDS_RECOVERY_E; |
7038 | | } |
7039 | | #endif /* WC_RNG_HAVE_RBGC */ |
7040 | | |
7041 | | return wc_RNG_DRBG_NextSeedGenerate_local(rng, NULL, n); |
7042 | | } |
7043 | | |
7044 | | /* Report the raw aperture value: a racy snapshot by design. Values in [0, bank |
7045 | | * length) count banked bytes; WC_DRBG_NEXT_SEED_READY and |
7046 | | * WC_DRBG_NEXT_SEED_CONSUMING indicate a ready or in-consumption bank, |
7047 | | * respectively. With no DRBG instantiated, reports WC_DRBG_NEXT_SEED_EMPTY. */ |
7048 | | int wc_RNG_DRBG_NextSeedCurrent(const WC_RNG* rng, WC_ATOMIC_INT_ARG* n) |
7049 | | { |
7050 | | if ((rng == NULL) || (n == NULL)) |
7051 | | return BAD_FUNC_ARG; |
7052 | | *n = WOLFSSL_ATOMIC_LOAD(rng->nextSeedLen); |
7053 | | return 0; |
7054 | | } |
7055 | | |
7056 | | /* Consume a ready next-seed bank in an immediate credited reseed. The caller |
7057 | | * must own the instance. Source-free by construction -- the material was |
7058 | | * gathered from the module's seed source and health-tested at bank time -- so |
7059 | | * consumption is pure computation and safe in atomic context: the one credited |
7060 | | * primary reseed shape with that property. Distinct protocol results: |
7061 | | * NOT_READY_E when no bank is ready (nothing consumed) or when an elective |
7062 | | * redemption failed after consuming the bank (use-once); WRONG_TYPE_OBJECT_E |
7063 | | * when the instance has no DRBG (RDRAND et al.), whose seed aperture never |
7064 | | * opens -- both deliberately loud, so a direct caller must demonstrate it |
7065 | | * understands the instance it holds. (The WC_RNG_BANK_FLAG_CONSUME_NEXT_SEED |
7066 | | * checkout arm is return-agnostic by construction and needs neither.) |
7067 | | * Use-once: the bank is consumed by the |
7068 | | * attempt, success or failure. Note that a banked reseed can never provide SP |
7069 | | * 800-90 prediction resistance (the material predates the request by |
7070 | | * construction); wc_RNG_DRBG_Reseed_Now() remains the live-gather shape. */ |
7071 | | /* safe (bounded-at-once) recursion for RBGC reseed. */ |
7072 | | /* NOLINTNEXTLINE(misc-no-recursion) */ |
7073 | | static WARN_UNUSED_RESULT int wc_RNG_DRBG_NextSeedNow_Nonce_local( |
7074 | | WC_RNG* rng, const byte* nonce, |
7075 | | word32 nonceSz) |
7076 | | { |
7077 | | WC_ATOMIC_INT_ARG expected = WC_DRBG_NEXT_SEED_READY; |
7078 | | int ret; |
7079 | | int devId; |
7080 | | WC_ATOMIC_UINT_ARG cur_epoch = |
7081 | | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
7082 | | WOLFSSL_ATOMIC_LOAD(global_entropy_epoch) |
7083 | | #else |
7084 | | 0 |
7085 | | #endif |
7086 | | ; |
7087 | | WC_RNG_PID_ARG my_pid = WC_RNG_GETPID(); |
7088 | | #ifdef WC_RNG_HAVE_LOCK |
7089 | | wc_drbg_reseed_ctr_t baseline_reseedCtr; |
7090 | | #endif |
7091 | | |
7092 | | if (rng == NULL) |
7093 | | return BAD_FUNC_ARG; |
7094 | | |
7095 | | if ((nonce == NULL) && (nonceSz != 0)) |
7096 | | return BAD_FUNC_ARG; |
7097 | | |
7098 | | ret = rng_lock_required_check(rng); |
7099 | | if (ret != 0) |
7100 | | return ret; |
7101 | | |
7102 | | /* Mirror wc_RNG_GenerateBlock(): only an in-service DRBG may reseed. */ |
7103 | | ret = wc_RNG_Status(rng); |
7104 | | if (ret != 0) |
7105 | | return ret; |
7106 | | |
7107 | | /* No DRBG (RDRAND et al.): no bank ever opens, so this is a refusal, |
7108 | | * not a not-yet -- a consumer polling NOT_READY_E would wait forever. |
7109 | | * (Matches the producer, wc_RNG_DRBG_NextSeedGenerate().) */ |
7110 | | if (! wc_RNG_DRBG_Present(rng)) |
7111 | | return WRONG_TYPE_OBJECT_E; |
7112 | | |
7113 | | #ifdef WC_RNG_HAVE_LOCK |
7114 | | baseline_reseedCtr = rng->reseedCtr; |
7115 | | #endif |
7116 | | |
7117 | | #if defined(WC_RNG_HAVE_ENTROPY_EPOCH) || \ |
7118 | | (defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID)) |
7119 | | /* Propagate any pending invalidation before touching the bank: the |
7120 | | * delivery purges a pre-pivot READY bank. We short circuit return when a |
7121 | | * propagation occurs, because NEEDS_RECOVERY_E is the more informative |
7122 | | * error. |
7123 | | */ |
7124 | | ret = rng_entropy_event_propagate(rng); |
7125 | | if (ret != 0) |
7126 | | return ret; |
7127 | | #endif /* WC_RNG_HAVE_ENTROPY_EPOCH || HAVE_GETPID */ |
7128 | | |
7129 | | #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) |
7130 | | devId = rng->devId; |
7131 | | #else |
7132 | | devId = INVALID_DEVID; |
7133 | | #endif |
7134 | | ret = wc_RNG_HealthTestLocal(rng, 1, rng->heap, devId); |
7135 | | if (ret != 0) { |
7136 | | if (ret == WC_NO_ERR_TRACE(DRBG_CONT_FAILURE)) { |
7137 | | rng->status = DRBG_CONT_FAILED; |
7138 | | return DRBG_CONT_FIPS_E; |
7139 | | } |
7140 | | if (ret > 0) /* protocol-domain catch-all: translate at the API */ |
7141 | | ret = RNG_FAILURE_E; |
7142 | | return ret; |
7143 | | } |
7144 | | |
7145 | | if (! wolfSSL_Atomic_Int_CompareExchange(&rng->nextSeedLen, &expected, |
7146 | | WC_DRBG_NEXT_SEED_CONSUMING)) |
7147 | | { |
7148 | | /* No ready bank -- nothing consumed; reported distinctly. */ |
7149 | | return NOT_READY_E; |
7150 | | } |
7151 | | |
7152 | | /* Identical byte accounting to PollAndReSeed(): the SEED_BLOCK_SZ |
7153 | | * prefix was consumed by the bank-time health testing. */ |
7154 | | ret = Hash_DRBG_Reseed(rng, rng->nextSeed + SEED_BLOCK_SZ, SEED_SZ, |
7155 | | nonce, nonceSz, 1 /* in_bracketed_consume */, |
7156 | | cur_epoch, my_pid); |
7157 | | |
7158 | | /* Use-once: consumed by the attempt, success or not. The scrub must be |
7159 | | * visible before the aperture reopens. */ |
7160 | | ForceZero(rng->nextSeed, WC_DRBG_SEED_BUF_SIZE); |
7161 | | |
7162 | | /* Release by CAS -- one-shot, and its failure is information, not |
7163 | | * contention: only NextSeedPurge() writes over a _CONSUMING claim, so a |
7164 | | * failed release proves an invalidation event landed after this consume |
7165 | | * claimed the material, i.e. the seed just fed to the reseed was banked |
7166 | | * pre-event. The reseed's own latch handling could not see that (an epoch |
7167 | | * crossing shows only at the aperture's claim word, never in the lock |
7168 | | * word), and if it entered invalidated and ran undisturbed it has already |
7169 | | * cleared the latch -- so compensate: re-latch, restore the counter (the |
7170 | | * stale credited reseed reset it, and we restore race-free here, under the |
7171 | | * exclusive lease). Claims (stats, stratum adoption) are made only behind |
7172 | | * a successful release. Do NOT re-run wc_RNG_invalidate_entropy() here: |
7173 | | * the event's purges already ran, and re-purging would discard post-event |
7174 | | * material the banker may have re-banked meanwhile. */ |
7175 | | { |
7176 | | int cas_ret; |
7177 | | WC_ATOMIC_INT_ARG expected_out = WC_DRBG_NEXT_SEED_CONSUMING; |
7178 | | WC_CAS_WITH_RETRY_BEGIN(&rng->nextSeedLen, expected_out, cas_ret) { |
7179 | | WC_CAS_WITH_RETRY_LOOP_UNTIL(wolfSSL_Atomic_Int_CompareExchange, |
7180 | | &rng->nextSeedLen, expected_out, |
7181 | | WC_DRBG_NEXT_SEED_EMPTY, cas_ret, |
7182 | | NEEDS_RECOVERY_E); |
7183 | | } WC_CAS_WITH_RETRY_END; |
7184 | | if (cas_ret != 0) { |
7185 | | /* The purge repainted our claim _PURGED and left the buffer to |
7186 | | * us; it was wiped above, so reopen -- but only from _PURGED. |
7187 | | * Until then producers see _PURGED and back off (BUSY_E), so no |
7188 | | * fill can begin while we still own the buffer; if a constructor |
7189 | | * has since repainted the word _TORNDOWN, the reopen is its to |
7190 | | * make, not ours. */ |
7191 | | { |
7192 | | WC_ATOMIC_INT_ARG expected_purged = WC_DRBG_NEXT_SEED_PURGED; |
7193 | | (void)wolfSSL_Atomic_Int_CompareExchange( |
7194 | | &rng->nextSeedLen, &expected_purged, |
7195 | | WC_DRBG_NEXT_SEED_EMPTY); |
7196 | | } |
7197 | | #ifdef WC_RNG_HAVE_LOCK |
7198 | | { |
7199 | | WC_RNG_lock_arg_t cur_lock; |
7200 | | int relatch_ret; |
7201 | | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&rng->lock, cur_lock, |
7202 | | relatch_ret) { |
7203 | | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
7204 | | wolfSSL_Atomic_Uint_CompareExchange, &rng->lock, |
7205 | | cur_lock, |
7206 | | cur_lock | WC_RNG_LOCK_ENTROPY_INVALIDATED, |
7207 | | relatch_ret); |
7208 | | } WC_CAS_WITH_RETRY_END; |
7209 | | if (relatch_ret != 0) { |
7210 | | /* Aborted re-latch: latch down, counter scheduled. |
7211 | | * Latch-or-condemn (see wc_RNG_invalidate_entropy()): |
7212 | | * condemn. */ |
7213 | | rng->status = DRBG_FAILED; |
7214 | | } |
7215 | | } |
7216 | | /* The reseed is void: restore the budget it reset. The latch |
7217 | | * carries the obligation; the counter stays SP 800-90A budget. */ |
7218 | | rng->reseedCtr = baseline_reseedCtr; |
7219 | | #else |
7220 | | /* No latch: the saturated counter is the sole enforcement. */ |
7221 | | { |
7222 | | int sched_ret = wc_RNG_DRBG_ScheduleReseed_local(rng); |
7223 | | if ((ret == DRBG_SUCCESS) && (sched_ret != 0)) |
7224 | | return sched_ret; |
7225 | | } |
7226 | | #endif |
7227 | | if (ret == DRBG_SUCCESS) { |
7228 | | /* The discarded recovery is the whole story. */ |
7229 | | return cas_ret; |
7230 | | } |
7231 | | /* Else the reseed's own failure is the more informative code: |
7232 | | * fall through to the standard outcome mapping. |
7233 | | * |
7234 | | * Note that the ordering here matters. Without the lock |
7235 | | * facility, the wc_RNG_DRBG_ScheduleReseed() above has just |
7236 | | * saturated the reseed counter, so the failed reseed falls |
7237 | | * through below and the DRBG is condemned by the runway gate. |
7238 | | * This is intentional: an invalidation-crossed failure is never |
7239 | | * elective, and the seed just consumed was banked pre-event, so |
7240 | | * the instance has no trustworthy runway for the gate's leniency |
7241 | | * to protect, and lenient NOT_READY_E here would misreport a |
7242 | | * quarantined instance as merely not-yet-ready. With the lock |
7243 | | * facility the re-upped latch carries the obligation instead, |
7244 | | * the counter is restored to the pre-reseed budget, and the gate |
7245 | | * below judges the failure on that budget; the latch, not the |
7246 | | * counter, is what refuses service. */ |
7247 | | } |
7248 | | else { |
7249 | | #ifdef WC_RNG_DEBUG_STATS |
7250 | | if (ret == 0) { |
7251 | | #ifdef WC_RNG_HAVE_RBGC |
7252 | | if (rng->nextSeedRBGCStratum > 0) |
7253 | | ++rng->_stats_nextseedsRBGC_redeemed; |
7254 | | else |
7255 | | #endif |
7256 | | ++rng->_stats_nextseedsprimary_redeemed; |
7257 | | } |
7258 | | #endif |
7259 | | #ifdef WC_RNG_HAVE_RBGC |
7260 | | if (ret == 0) { |
7261 | | #ifndef WC_RNG_RBGC_STRATUM_IMMUTABLE |
7262 | | rng->RBGCStratum = rng->nextSeedRBGCStratum; |
7263 | | #endif |
7264 | | rng->nextSeedRBGCStratum = 0; |
7265 | | } |
7266 | | #endif |
7267 | | } |
7268 | | } |
7269 | | |
7270 | | if (ret == DRBG_SUCCESS) { |
7271 | | #if defined(WC_RNG_HAVE_ENTROPY_EPOCH) || \ |
7272 | | (defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID)) |
7273 | | /* Double-check that we're still valid, so that the retval is |
7274 | | * accurate. */ |
7275 | | ret = rng_entropy_event_propagate(rng); |
7276 | | #else |
7277 | | ret = 0; |
7278 | | #endif |
7279 | | } |
7280 | | else { |
7281 | | wc_drbg_reseed_ctr_t ctr = WC_RESEED_INTERVAL; |
7282 | | (void)wc_RNG_DRBG_GetReseedCtr(rng, &ctr); |
7283 | | if (ret == WC_NO_ERR_TRACE(DRBG_CONT_FAILURE)) { |
7284 | | /* Not reachable here -- retained only for uniformity with |
7285 | | * wc_RNG_GenerateBlock() and wc_RNG_DRBG_Reseed_Now(). Where |
7286 | | * reachable, the suspect seed was rejected before use, and the DRBG |
7287 | | * state and runway are intact. */ |
7288 | | if (ctr >= WC_RESEED_INTERVAL) { |
7289 | | /* The instance is out of generate runway -- condemn now, matching |
7290 | | * wc_RNG_GenerateBlock()'s behavior for mandatory reseeds. */ |
7291 | | rng->status = DRBG_CONT_FAILED; |
7292 | | } |
7293 | | ret = DRBG_CONT_FIPS_E; |
7294 | | } |
7295 | | else if ((ret == WC_NO_ERR_TRACE(BUSY_E)) || |
7296 | | (ret == WC_NO_ERR_TRACE(MEMORY_E))) |
7297 | | { |
7298 | | /* A resource that requires waiting, in a context that can't: |
7299 | | * unconditionally retryable, runway or no, as in |
7300 | | * RngGenerateFailure(). */ |
7301 | | } |
7302 | | else if (ctr >= WC_RESEED_INTERVAL) { |
7303 | | /* The instance is out of generate runway -- condemn now, matching |
7304 | | * wc_RNG_GenerateBlock()'s behavior for mandatory reseeds. */ |
7305 | | rng->status = DRBG_FAILED; |
7306 | | ret = RNG_FAILURE_E; |
7307 | | } |
7308 | | else { |
7309 | | ret = NOT_READY_E; |
7310 | | } |
7311 | | } |
7312 | | |
7313 | | return ret; |
7314 | | } |
7315 | | |
7316 | | int wc_RNG_DRBG_NextSeedNow_Nonce(WC_RNG* rng, const byte* nonce, |
7317 | | word32 nonceSz) |
7318 | | { |
7319 | | int ret; |
7320 | | |
7321 | | if (rng == NULL) |
7322 | | return BAD_FUNC_ARG; |
7323 | | ret = RngAutoLockEnter(rng); |
7324 | | if (ret != 0) |
7325 | | return ret; |
7326 | | ret = wc_RNG_DRBG_NextSeedNow_Nonce_local(rng, nonce, nonceSz); |
7327 | | RngAutoLockExit(rng); |
7328 | | return ret; |
7329 | | } |
7330 | | |
7331 | | #if defined(WC_RNG_HAVE_NEXT_SEED) && defined(WC_RNG_HAVE_LOCK) && \ |
7332 | | defined(WC_RNG_HAVE_RBGC) |
7333 | | /* For the generate path, which holds the lock already. Guarded to match |
7334 | | * its one call site, which needs the lock and RBGC builds as well. */ |
7335 | | /* safe (bounded-at-once) recursion for RBGC reseed. */ |
7336 | | /* NOLINTNEXTLINE(misc-no-recursion) */ |
7337 | | static WARN_UNUSED_RESULT int wc_RNG_DRBG_NextSeedNow_local(WC_RNG* rng) { |
7338 | | return wc_RNG_DRBG_NextSeedNow_Nonce_local(rng, NULL, 0); |
7339 | | } |
7340 | | #endif |
7341 | | |
7342 | | int wc_RNG_DRBG_NextSeedNow(WC_RNG* rng) { |
7343 | | return wc_RNG_DRBG_NextSeedNow_Nonce(rng, NULL, 0); |
7344 | | } |
7345 | | |
7346 | | /* Deposit raw uncredited stir material into rng's accumulator. Callable from |
7347 | | * any context and without owning the instance: the deposit protocol |
7348 | | * (read-copy-store) is multi-writer-tolerant -- every published span was |
7349 | | * written by its publisher, lost updates merely drop entropy, and interleaved |
7350 | | * fragments of compatible provenance are harmless. A full accumulator |
7351 | | * publishes WC_DRBG_NEXT_SEED_READY (no health test -- no claim is being made) |
7352 | | * and shunts further deposits to xorbuf() until consumed. */ |
7353 | | int wc_RNG_DRBG_NextStirStore(WC_RNG* rng, const byte *nonce, word32 nonceSz) |
7354 | | { |
7355 | | WC_ATOMIC_INT_ARG cur; |
7356 | | |
7357 | | if ((rng == NULL) || (nonce == NULL) || (nonceSz == 0)) |
7358 | | return BAD_FUNC_ARG; |
7359 | | |
7360 | | /* Note, rng need not be locked -- that's the whole point of the |
7361 | | * banked-next-stir aperture protocol. |
7362 | | */ |
7363 | | |
7364 | | cur = WOLFSSL_ATOMIC_LOAD(rng->nextStirLen); |
7365 | | |
7366 | | if ((cur >= 0) && (cur < (WC_ATOMIC_INT_ARG)sizeof(rng->nextStir))) { |
7367 | | word32 fill = (word32)cur; |
7368 | | word32 room = (word32)sizeof(rng->nextStir) - fill; |
7369 | | word32 take = (nonceSz < room) ? nonceSz : room; |
7370 | | |
7371 | | XMEMCPY(rng->nextStir + fill, nonce, take); |
7372 | | fill += take; |
7373 | | if (fill == (word32)sizeof(rng->nextStir)) { |
7374 | | WOLFSSL_ATOMIC_STORE(rng->nextStirLen, WC_DRBG_NEXT_SEED_READY); |
7375 | | #ifdef WC_RNG_DEBUG_STATS |
7376 | | ++rng->_stats_nextstirs_banked; /* racy */ |
7377 | | #endif |
7378 | | nonce += take; |
7379 | | nonceSz -= take; /* spillover falls through to the xorbuf() */ |
7380 | | } |
7381 | | else { |
7382 | | WOLFSSL_ATOMIC_STORE(rng->nextStirLen, |
7383 | | cur + (WC_ATOMIC_INT_ARG)take); |
7384 | | return 0; |
7385 | | } |
7386 | | if (nonceSz == 0) |
7387 | | return 0; |
7388 | | } |
7389 | | |
7390 | | if (nonceSz > (word32)sizeof(rng->nextStir)) |
7391 | | nonceSz = (word32)sizeof(rng->nextStir); |
7392 | | xorbuf(rng->nextStir, nonce, nonceSz); |
7393 | | |
7394 | | return 0; |
7395 | | } |
7396 | | |
7397 | | /* Consume a ready uncredited accumulator in an immediate uncredited |
7398 | | * (stirring) reseed. The caller must own the instance. The credited=0 |
7399 | | * path holds the three no-ops by construction: the reseed counter is not |
7400 | | * reset, WC_RNG_LOCK_ENTROPY_INVALIDATED is not cleared, and RBGCStratum |
7401 | | * is unchanged -- a stir must never masquerade as recovery or promotion. |
7402 | | * Use-once: the material is consumed (accumulation reopens) whether or not |
7403 | | * the reseed succeeds, and the buffer is burned before the reopen (see the |
7404 | | * note at the burn). */ |
7405 | | static WARN_UNUSED_RESULT int wc_RNG_DRBG_NextStirNow_local(WC_RNG* rng) |
7406 | | { |
7407 | | WC_ATOMIC_INT_ARG expected = WC_DRBG_NEXT_SEED_READY; |
7408 | | int ret; |
7409 | | |
7410 | | if (rng == NULL) |
7411 | | return BAD_FUNC_ARG; |
7412 | | |
7413 | | ret = rng_lock_required_check(rng); |
7414 | | if (ret != 0) |
7415 | | return ret; |
7416 | | |
7417 | | /* Mirror wc_RNG_GenerateBlock(): only an in-service DRBG may reseed. */ |
7418 | | ret = wc_RNG_Status(rng); |
7419 | | if (ret != 0) |
7420 | | return ret; |
7421 | | |
7422 | | ret = wc_RNG_entropy_needs_recovery(rng); |
7423 | | if (ret != 0) |
7424 | | return ret; |
7425 | | |
7426 | | if (! wolfSSL_Atomic_Int_CompareExchange(&rng->nextStirLen, &expected, |
7427 | | WC_DRBG_NEXT_SEED_CONSUMING)) |
7428 | | { |
7429 | | /* Accumulator not READY. */ |
7430 | | if (expected < 0) { |
7431 | | /* claimed by a racing consumer. */ |
7432 | | return BUSY_E; |
7433 | | } |
7434 | | else { |
7435 | | /* empty or still accumulating -- nothing consumable yet. */ |
7436 | | return NOT_READY_E; |
7437 | | } |
7438 | | } |
7439 | | |
7440 | | ret = Hash_DRBG_StirGenerate(rng, rng->nextStir, |
7441 | | (word32)sizeof(rng->nextStir)); |
7442 | | |
7443 | | #ifdef WC_RNG_DEBUG_STATS |
7444 | | if (ret == 0) |
7445 | | ++rng->_stats_nextstirs_redeemed; |
7446 | | #endif |
7447 | | |
7448 | | /* Always burn consumed data before releasing it, even if it's uncredited |
7449 | | * noise. Unlike the seed aperture, the stir aperture has no producer |
7450 | | * claim: lease-free depositors xorbuf() into it at any time during |
7451 | | * _CONSUMING, so the burn here can only discard an incoming overflow |
7452 | | * fragment, after the full aperture has already been absorbed by |
7453 | | * the StirGenerate() above. */ |
7454 | | ForceZero(rng->nextStir, (word32)sizeof(rng->nextStir)); |
7455 | | WOLFSSL_ATOMIC_STORE(rng->nextStirLen, WC_DRBG_NEXT_SEED_EMPTY); |
7456 | | |
7457 | | return ret; |
7458 | | } |
7459 | | |
7460 | | int wc_RNG_DRBG_NextStirNow(WC_RNG* rng) |
7461 | | { |
7462 | | int ret; |
7463 | | |
7464 | | if (rng == NULL) |
7465 | | return BAD_FUNC_ARG; |
7466 | | ret = RngAutoLockEnter(rng); |
7467 | | if (ret != 0) |
7468 | | return ret; |
7469 | | ret = wc_RNG_DRBG_NextStirNow_local(rng); |
7470 | | RngAutoLockExit(rng); |
7471 | | return ret; |
7472 | | } |
7473 | | |
7474 | | #endif /* WC_RNG_HAVE_NEXT_SEED */ |
7475 | | |
7476 | | #endif /* HAVE_HASHDRBG */ |
7477 | | |
7478 | | #if defined(HAVE_HASHDRBG) && !defined(CUSTOM_RAND_GENERATE_BLOCK) |
7479 | | /* The WC_RNG_FLAG_FAIL_FAST verdict in place of an in-line reseed: the |
7480 | | * recovery conditions keep NEEDS_RECOVERY_E, the budget reports NOT_READY_E. |
7481 | | * wc_RNG_entropy_needs_recovery() has already delivered any pending epoch |
7482 | | * event (under the lock facility, into the latch), so the latch is |
7483 | | * authoritative there. */ |
7484 | | static WC_INLINE int RngFailFastVerdict(const WC_RNG* rng) |
7485 | 0 | { |
7486 | 0 | (void)rng; |
7487 | | #ifdef WC_RNG_HAVE_LOCK |
7488 | | if (WOLFSSL_ATOMIC_LOAD(rng->lock) & WC_RNG_LOCK_ENTROPY_INVALIDATED) |
7489 | | return NEEDS_RECOVERY_E; |
7490 | | #endif |
7491 | 0 | #ifdef WC_RNG_HAVE_ENTROPY_EPOCH |
7492 | 0 | if (rng->entropy_epoch != WOLFSSL_ATOMIC_LOAD(global_entropy_epoch)) |
7493 | 0 | return NEEDS_RECOVERY_E; |
7494 | 0 | #endif |
7495 | 0 | #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) |
7496 | 0 | if (rng->pid != getpid()) |
7497 | 0 | return NEEDS_RECOVERY_E; |
7498 | 0 | #endif |
7499 | 0 | return NOT_READY_E; |
7500 | 0 | } |
7501 | | #endif |
7502 | | |
7503 | | /* place a generated block in output */ |
7504 | | #ifdef WC_HAVE_RNG_BANKREF |
7505 | | /* safe (bounded-at-once) recursion for RBGC reseed. */ |
7506 | | /* NOLINTNEXTLINE(misc-no-recursion) */ |
7507 | | static WARN_UNUSED_RESULT int wc_local_RNG_GenerateBlock(WC_RNG* rng, |
7508 | | byte* output, |
7509 | | word32 sz) |
7510 | | #else |
7511 | | WOLFSSL_ABI |
7512 | | /* safe (bounded-at-once) recursion for RBGC reseed. */ |
7513 | | /* NOLINTNEXTLINE(misc-no-recursion) */ |
7514 | | int wc_RNG_GenerateBlock(WC_RNG* rng, byte* output, word32 sz) |
7515 | | #endif |
7516 | 451k | { |
7517 | 451k | int ret; |
7518 | | |
7519 | 451k | if (rng == NULL || output == NULL) |
7520 | 0 | return BAD_FUNC_ARG; |
7521 | | |
7522 | 451k | ret = rng_lock_required_check(rng); |
7523 | 451k | if (ret != 0) |
7524 | 0 | return ret; |
7525 | | |
7526 | 451k | if (sz == 0) |
7527 | 192 | return 0; |
7528 | | |
7529 | 451k | #ifdef WOLF_CRYPTO_CB |
7530 | | /* before the lock: a callback may fall back to this same instance */ |
7531 | 451k | #ifndef WOLF_CRYPTO_CB_FIND |
7532 | 451k | if (rng->devId != INVALID_DEVID) |
7533 | 15.5k | #endif |
7534 | 15.5k | { |
7535 | 15.5k | ret = wc_CryptoCb_RandomBlock(rng, output, sz); |
7536 | 15.5k | if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) |
7537 | 15.5k | return ret; |
7538 | | /* fall-through when unavailable */ |
7539 | 15.5k | } |
7540 | 435k | #endif |
7541 | | |
7542 | | /* These read a device, not this instance, so a lock protects nothing here. |
7543 | | * On RDRAND hardware wc_InitRng() creates no lock at all, as tested. */ |
7544 | | #ifdef HAVE_INTEL_RDRAND |
7545 | | if (IS_INTEL_RDRAND(intel_flags)) |
7546 | | return wc_GenerateRand_IntelRD(NULL, output, sz); |
7547 | | #endif |
7548 | | |
7549 | | #if defined(WOLFSSL_SILABS_SE_ACCEL) && defined(WOLFSSL_SILABS_TRNG) |
7550 | | return silabs_GenerateRand(output, sz); |
7551 | | #endif |
7552 | | |
7553 | 435k | ret = RngAutoLockEnter(rng); /* held across every other backend */ |
7554 | 435k | if (ret != 0) |
7555 | 0 | return ret; |
7556 | | |
7557 | | #if defined(WOLFSSL_ASYNC_CRYPT) |
7558 | | if (rng->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RNG) { |
7559 | | /* these are blocking */ |
7560 | | #ifdef HAVE_CAVIUM |
7561 | | ret = NitroxRngGenerateBlock(rng, output, sz); |
7562 | | RngAutoLockExit(rng); |
7563 | | return ret; |
7564 | | #elif defined(HAVE_INTEL_QA) && defined(QAT_ENABLE_RNG) |
7565 | | ret = IntelQaDrbg(&rng->asyncDev, output, sz); |
7566 | | RngAutoLockExit(rng); |
7567 | | return ret; |
7568 | | #else |
7569 | | /* simulator not supported */ |
7570 | | #endif |
7571 | | } |
7572 | | #endif |
7573 | | |
7574 | | #ifdef CUSTOM_RAND_GENERATE_BLOCK |
7575 | | XMEMSET(output, 0, sz); |
7576 | | ret = (int)CUSTOM_RAND_GENERATE_BLOCK(output, sz); |
7577 | | #ifdef WC_VERBOSE_RNG |
7578 | | if (ret != 0) |
7579 | | WOLFSSL_DEBUG_PRINTF( |
7580 | | "ERROR: CUSTOM_RAND_GENERATE_BLOCK failed with err %d.", ret); |
7581 | | #endif |
7582 | | RngAutoLockExit(rng); /* a no-op here today; the gate excludes this build */ |
7583 | | #else |
7584 | | |
7585 | 435k | #ifdef HAVE_HASHDRBG |
7586 | 435k | if (sz > RNG_MAX_BLOCK_LEN) { |
7587 | 0 | RngAutoLockExit(rng); |
7588 | 0 | return BAD_FUNC_ARG; |
7589 | 0 | } |
7590 | | |
7591 | 435k | ret = wc_RNG_Status(rng); |
7592 | 435k | if (ret != 0) { |
7593 | 0 | RngAutoLockExit(rng); |
7594 | 0 | return ret; |
7595 | 0 | } |
7596 | | |
7597 | | #ifdef WC_RNG_DEBUG_STATS |
7598 | | ++rng->_stats_total_requests; |
7599 | | rng->_stats_total_bytes_requested += sz; |
7600 | | #endif |
7601 | | |
7602 | | #if defined(WC_RNG_HAVE_NEXT_SEED) && defined(WC_RNG_HAVE_LOCK) && \ |
7603 | | defined(WC_RNG_HAVE_RBGC) |
7604 | | if (rng->flags & WC_RNG_FLAG_UPGRADE_FROM_NEXT_SEED) { |
7605 | | /* externally-refreshed instance: consume a READY banked seed to |
7606 | | * recover from entropy invalidation (any provenance -- the purge |
7607 | | * in wc_RNG_invalidate_entropy() guarantees a READY seed is |
7608 | | * post-event), or to promote a chain-backed instance to primary |
7609 | | * (the live seed; the stratum label follows only without |
7610 | | * WC_RNG_RBGC_STRATUM_IMMUTABLE). Consumption is a credited |
7611 | | * reseed, clearing the latch and resetting the schedule; failure |
7612 | | * falls through to the ordinary forced-reseed machinery. */ |
7613 | | int banked_stratum = wc_RNG_DRBG_GetNextSeedRBGCStratum(rng); |
7614 | | if (banked_stratum >= 0) { |
7615 | | if (((WOLFSSL_ATOMIC_LOAD(rng->lock) & |
7616 | | WC_RNG_LOCK_ENTROPY_INVALIDATED)) |
7617 | | || |
7618 | | ((rng->RBGCStratum > 0) && (banked_stratum == 0))) |
7619 | | { |
7620 | | ret = wc_RNG_DRBG_NextSeedNow_local(rng); |
7621 | | /* Key the bail on the instance state, not on a list of codes: |
7622 | | * this leg can now also see ENTROPY_RT_E / ENTROPY_APT_E, and |
7623 | | * falling through would let a later generate overwrite ret and |
7624 | | * report success for a call that already condemned the DRBG. */ |
7625 | | if (rng->status != DRBG_OK) { |
7626 | | RngAutoLockExit(rng); |
7627 | | return (ret != 0) ? ret : RNG_FAILURE_E; |
7628 | | } |
7629 | | } |
7630 | | } |
7631 | | } |
7632 | | #endif |
7633 | | |
7634 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
7635 | | /* Universal opportunistic stir: a READY uncredited accumulator is |
7636 | | * consumed by any generate, unconditionally -- stirs are always |
7637 | | * harmless, and are invisible to the credited legs above (no counter |
7638 | | * reset, no flag clear, no stratum change). One relaxed load when |
7639 | | * empty. */ |
7640 | | if (WOLFSSL_ATOMIC_LOAD(rng->nextStirLen) == WC_DRBG_NEXT_SEED_READY) { |
7641 | | int stir_ret = wc_RNG_DRBG_NextStirNow_local(rng); |
7642 | | if (stir_ret == WC_NO_ERR_TRACE(RNG_FAILURE_E)) { |
7643 | | /* The DRBG broke while we were stirring it. */ |
7644 | | RngAutoLockExit(rng); |
7645 | | return stir_ret; |
7646 | | } |
7647 | | } |
7648 | | #endif /* WC_RNG_HAVE_NEXT_SEED */ |
7649 | | |
7650 | 435k | ret = wc_RNG_entropy_needs_recovery(rng); |
7651 | 435k | if (ret == WC_NO_ERR_TRACE(NEEDS_RECOVERY_E)) { |
7652 | 0 | int reseed_ret; |
7653 | 0 | if (rng->flags & WC_RNG_FLAG_FAIL_FAST) { |
7654 | | /* No implicit reseed: report the condition and leave the DRBG as it |
7655 | | * is. Not condemned -- it needs a reseed, but it's already wiped |
7656 | | * by the propagation in wc_RNG_entropy_needs_recovery(), and it's |
7657 | | * otherwise healthy. */ |
7658 | 0 | RngAutoLockExit(rng); |
7659 | 0 | return RngFailFastVerdict(rng); |
7660 | 0 | } |
7661 | 0 | reseed_ret = PollAndReSeed(rng, NULL, 0); |
7662 | 0 | if (reseed_ret != DRBG_SUCCESS) { |
7663 | 0 | reseed_ret = RngGenerateFailure(rng, reseed_ret); |
7664 | 0 | RngAutoLockExit(rng); |
7665 | 0 | return reseed_ret; |
7666 | 0 | } |
7667 | 0 | } |
7668 | 435k | else if (ret != 0) { |
7669 | 0 | RngAutoLockExit(rng); |
7670 | 0 | return ret; |
7671 | 0 | } |
7672 | | |
7673 | 435k | #ifndef NO_SHA256 |
7674 | 435k | if (rng->drbgType == WC_DRBG_SHA256) { |
7675 | 0 | ret = Hash_DRBG_Generate((DRBG_internal *)rng->drbg, &rng->reseedCtr, output, sz, |
7676 | 0 | NULL, 0); |
7677 | 0 | if (ret == WC_NO_ERR_TRACE(DRBG_NEED_RESEED)) { |
7678 | 0 | if (rng->flags & WC_RNG_FLAG_FAIL_FAST) { |
7679 | 0 | RngAutoLockExit(rng); |
7680 | 0 | return RngFailFastVerdict(rng); /* state untouched */ |
7681 | 0 | } |
7682 | 0 | ret = PollAndReSeed(rng, NULL, 0); |
7683 | 0 | if (ret != DRBG_SUCCESS) { |
7684 | 0 | ret = RngGenerateFailure(rng, ret); |
7685 | 0 | } |
7686 | 0 | else { |
7687 | 0 | ret = Hash_DRBG_Generate((DRBG_internal *)rng->drbg, &rng->reseedCtr, output, |
7688 | 0 | sz, NULL, 0); |
7689 | 0 | } |
7690 | 0 | } |
7691 | 0 | } |
7692 | 435k | else |
7693 | 435k | #endif |
7694 | 435k | #ifdef WOLFSSL_DRBG_SHA512 |
7695 | 435k | if (rng->drbgType == WC_DRBG_SHA512) { |
7696 | 435k | ret = Hash512_DRBG_Generate((DRBG_SHA512_internal *)rng->drbg512, &rng->reseedCtr, |
7697 | 435k | output, sz, NULL, 0); |
7698 | 435k | if (ret == WC_NO_ERR_TRACE(DRBG_NEED_RESEED)) { |
7699 | 0 | if (rng->flags & WC_RNG_FLAG_FAIL_FAST) { |
7700 | 0 | RngAutoLockExit(rng); |
7701 | 0 | return RngFailFastVerdict(rng); /* state untouched */ |
7702 | 0 | } |
7703 | 0 | ret = PollAndReSeed(rng, NULL, 0); |
7704 | 0 | if (ret != DRBG_SUCCESS) { |
7705 | 0 | ret = RngGenerateFailure(rng, ret); |
7706 | 0 | } |
7707 | 0 | else { |
7708 | 0 | ret = Hash512_DRBG_Generate( |
7709 | 0 | (DRBG_SHA512_internal *)rng->drbg512, &rng->reseedCtr, output, sz, |
7710 | 0 | NULL, 0); |
7711 | 0 | } |
7712 | 0 | } |
7713 | 435k | } |
7714 | 0 | else |
7715 | 0 | #endif |
7716 | 0 | { |
7717 | 0 | ret = DRBG_FAILURE; |
7718 | 0 | rng->status = DRBG_FAILED; |
7719 | 0 | } |
7720 | | |
7721 | 435k | if (ret == DRBG_SUCCESS) { |
7722 | 434k | ret = 0; |
7723 | | #ifdef WC_RNG_DEBUG_STATS |
7724 | | rng->_stats_total_bytes_produced += sz; |
7725 | | #ifdef WC_RNG_HAVE_RBGC |
7726 | | /* chain-provenance output: generated while chain-backed */ |
7727 | | if (rng->RBGCStratum > 0) |
7728 | | rng->_stats_RBGC_bytes_produced += sz; |
7729 | | #endif |
7730 | | #endif |
7731 | 434k | } |
7732 | 1.13k | else if (ret == WC_NO_ERR_TRACE(DRBG_CONT_FAILURE)) { |
7733 | 0 | ret = DRBG_CONT_FIPS_E; |
7734 | 0 | rng->status = DRBG_CONT_FAILED; |
7735 | 0 | } |
7736 | 1.13k | else { |
7737 | | /* A mandatory reseed above can leave a seed health verdict in ret, and |
7738 | | * that arm has already set rng->status, so keep the SP 800-90B code |
7739 | | * rather than flattening it. Everything else is unchanged: |
7740 | | * Hash_DRBG_Generate() stays self-consistent and can fail for |
7741 | | * retryable causes such as an allocation, so it is not condemned. */ |
7742 | 1.13k | if ((ret != WC_NO_ERR_TRACE(ENTROPY_RT_E)) && |
7743 | 1.13k | (ret != WC_NO_ERR_TRACE(ENTROPY_APT_E))) { |
7744 | 1.13k | ret = RNG_FAILURE_E; |
7745 | 1.13k | } |
7746 | 1.13k | } |
7747 | 435k | RngAutoLockExit(rng); |
7748 | | #else |
7749 | | |
7750 | | /* if we get here then there is an RNG configuration error */ |
7751 | | ret = RNG_FAILURE_E; |
7752 | | RngAutoLockExit(rng); /* a no-op here today; the gate excludes this build */ |
7753 | | |
7754 | | #endif /* HAVE_HASHDRBG */ |
7755 | 435k | #endif /* CUSTOM_RAND_GENERATE_BLOCK */ |
7756 | | |
7757 | 435k | return ret; |
7758 | 435k | } |
7759 | | |
7760 | | #ifdef WC_HAVE_RNG_BANKREF |
7761 | | WOLFSSL_ABI |
7762 | | /* safe (bounded-at-once) recursion for RBGC reseed. */ |
7763 | | /* NOLINTNEXTLINE(misc-no-recursion) */ |
7764 | | int wc_RNG_GenerateBlock(WC_RNG* rng, byte* output, word32 sz) |
7765 | | { |
7766 | | if (rng == NULL) |
7767 | | return BAD_FUNC_ARG; |
7768 | | |
7769 | | { |
7770 | | int lock_ret = rng_lock_required_check(rng); |
7771 | | if (lock_ret != 0) |
7772 | | return lock_ret; |
7773 | | } |
7774 | | |
7775 | | if (rng->flags & WC_RNG_FLAG_BANKREF) { |
7776 | | int ret; |
7777 | | struct wc_rng_bank_inst *bank_inst = NULL; |
7778 | | |
7779 | | ret = wc_local_rng_bank_checkout_for_bankref(rng->bankref, &bank_inst); |
7780 | | if (ret != 0) |
7781 | | return ret; |
7782 | | if (bank_inst == NULL) |
7783 | | return BAD_STATE_E; |
7784 | | ret = wc_local_RNG_GenerateBlock(WC_RNG_BANK_INST_TO_RNG(bank_inst), |
7785 | | output, sz); |
7786 | | { |
7787 | | int checkin_ret = wc_rng_bank_inst_checkin(&bank_inst); |
7788 | | if (checkin_ret != 0) { |
7789 | | #ifdef WC_VERBOSE_RNG |
7790 | | WOLFSSL_DEBUG_PRINTF( |
7791 | | "ERROR: wc_RNG_GenerateBlock() wc_rng_bank_inst_checkin() " |
7792 | | "failed with err %d.", checkin_ret); |
7793 | | #endif |
7794 | | if (ret == 0) |
7795 | | ret = checkin_ret; |
7796 | | } |
7797 | | } |
7798 | | return ret; |
7799 | | } |
7800 | | else |
7801 | | return wc_local_RNG_GenerateBlock(rng, output, sz); |
7802 | | } |
7803 | | #endif |
7804 | | |
7805 | | int wc_RNG_GenerateByte(WC_RNG* rng, byte* b) |
7806 | 0 | { |
7807 | 0 | return wc_RNG_GenerateBlock(rng, b, 1); |
7808 | 0 | } |
7809 | | |
7810 | | #ifdef WC_RNG_HAVE_LOCK |
7811 | | int wc_FreeRng_PreLocked(WC_RNG* rng) |
7812 | | #else |
7813 | | int wc_FreeRng(WC_RNG* rng) |
7814 | | #endif |
7815 | 68.1k | { |
7816 | 68.1k | int ret = 0; |
7817 | | #ifdef WC_RNG_HAVE_POOL |
7818 | | WC_ATOMIC_UINT_ARG starting_poolhead = WC_RNG_POOL_STATE_TORNDOWN; |
7819 | | #endif |
7820 | | |
7821 | 68.1k | if (rng == NULL) |
7822 | 0 | return BAD_FUNC_ARG; |
7823 | | |
7824 | | #ifdef WC_HAVE_RNG_BANKREF |
7825 | | if (rng->flags & WC_RNG_FLAG_BANKREF) |
7826 | | return wc_BankRef_Release(rng); |
7827 | | #endif /* WC_HAVE_RNG_BANKREF */ |
7828 | | |
7829 | | #ifdef WC_RNG_HAVE_LOCK |
7830 | | if ((WOLFSSL_ATOMIC_LOAD(rng->lock) & |
7831 | | (WC_RNG_LOCK_HELD | WC_RNG_LOCK_REQUIRED)) |
7832 | | == WC_RNG_LOCK_REQUIRED) |
7833 | | { |
7834 | | return OBJECT_NOT_LOCKED_E; |
7835 | | } |
7836 | | #endif |
7837 | | |
7838 | | #ifdef WC_RNG_HAVE_POOL |
7839 | | /* Pool take, before any irreversible step: LIVE -> TORNDOWN by one CAS. |
7840 | | * A held claim (a writer across its generate, or an allocator across its |
7841 | | * stores) makes the take fail, and we return BUSY_E having mutated |
7842 | | * nothing -- the "try once, caller retries" contract, never a spin. The |
7843 | | * buffer itself is released below, at the single teardown site; the |
7844 | | * word stays TORNDOWN so no collector can re-equip the instance before |
7845 | | * the next _InitRng() installs UNALLOC. */ |
7846 | | { |
7847 | | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&rng->poolHead, starting_poolhead, ret) { |
7848 | | if (WC_RNG_POOL_STATE(starting_poolhead) == WC_RNG_POOL_STATE_CLAIMED) |
7849 | | return BUSY_E; |
7850 | | if (WC_RNG_POOL_STATE(starting_poolhead) == WC_RNG_POOL_STATE_TORNDOWN) { |
7851 | | ret = 0; |
7852 | | break; |
7853 | | } |
7854 | | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
7855 | | wolfSSL_Atomic_Uint_CompareExchange, &rng->poolHead, |
7856 | | starting_poolhead, |
7857 | | WC_RNG_POOL_STATE_TORNDOWN, |
7858 | | ret); |
7859 | | } WC_CAS_WITH_RETRY_END; |
7860 | | if (ret != 0) |
7861 | | return ret; |
7862 | | } |
7863 | | #endif |
7864 | | |
7865 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
7866 | | /* NextSeed take, same logic as above for the pool, except a refusal |
7867 | | * here must reach the pool-state restore below rather than returning |
7868 | | * directly -- the pool word is already taken. */ |
7869 | | { |
7870 | | WC_ATOMIC_INT_ARG starting_nextseedlen; |
7871 | | WC_CAS_WITH_RETRY_BEGIN_INIT_CUR(&rng->nextSeedLen, starting_nextseedlen, ret) { |
7872 | | if ((starting_nextseedlen == WC_DRBG_NEXT_SEED_CONSUMING) || |
7873 | | (starting_nextseedlen == WC_DRBG_NEXT_SEED_PRODUCING) || |
7874 | | (starting_nextseedlen == WC_DRBG_NEXT_SEED_PURGED)) |
7875 | | { |
7876 | | /* A holder owns the buffer -- for _PURGED, pending its |
7877 | | * unwind (see NextSeedPurge()) -- and the ForceZero of |
7878 | | * rng->nextSeed below must never race it. Refuse, |
7879 | | * mutating nothing on this word. */ |
7880 | | ret = BUSY_E; |
7881 | | break; |
7882 | | } |
7883 | | |
7884 | | if (starting_nextseedlen == WC_DRBG_NEXT_SEED_TORNDOWN) { |
7885 | | ret = 0; |
7886 | | break; |
7887 | | } |
7888 | | WC_CAS_WITH_RETRY_LOOP_FOREVER( |
7889 | | wolfSSL_Atomic_Int_CompareExchange, &rng->nextSeedLen, |
7890 | | starting_nextseedlen, |
7891 | | WC_DRBG_NEXT_SEED_TORNDOWN, |
7892 | | ret); |
7893 | | } WC_CAS_WITH_RETRY_END; |
7894 | | if (ret != 0) { |
7895 | | #ifdef WC_RNG_HAVE_POOL |
7896 | | /* undo pool state mutation, if any, except that it must be emptied |
7897 | | * in case an invalidation arrived during the window while it was |
7898 | | * _TORNDOWN. */ |
7899 | | if (WC_RNG_POOL_STATE(starting_poolhead) == WC_RNG_POOL_STATE_LIVE) { |
7900 | | WOLFSSL_ATOMIC_STORE( |
7901 | | rng->poolHead, |
7902 | | WC_RNG_POOL_STATE(starting_poolhead) | |
7903 | | WC_RNG_POOL_PACK(0, WC_RNG_POOL_EPOCH(starting_poolhead) + 1)); |
7904 | | WOLFSSL_ATOMIC_STORE(rng->poolTail, WC_RNG_POOL_PACK(0, 0)); |
7905 | | } |
7906 | | #endif |
7907 | | return ret; |
7908 | | } |
7909 | | } |
7910 | | #endif |
7911 | | |
7912 | | #if defined(WC_RNG_HAVE_RBGC) && defined(WC_RNG_HAVE_LOCK) |
7913 | | { |
7914 | | WC_RNG *parent = rng->RBGC_parent; |
7915 | | if ((parent != NULL) && wolfSSL_Atomic_Ptr_CompareExchange( |
7916 | | (void * volatile *)&rng->RBGC_parent, (void **)&parent, NULL)) |
7917 | | { |
7918 | | (void)wolfSSL_Atomic_Uint_FetchSub(&parent->RBGC_refcount, 1U); |
7919 | | } |
7920 | | } |
7921 | | #endif |
7922 | | |
7923 | | #ifdef WC_RNG_HAVE_FREE_HOOK |
7924 | | if (rng->free_hook != NULL) { |
7925 | | /* one-shot, cleared before firing: re-entrant frees from the hook |
7926 | | * (not that they would be a good idea) can't loop. */ |
7927 | | wc_RNG_free_hook_cb_t free_hook = rng->free_hook; |
7928 | | rng->free_hook = NULL; |
7929 | | ret = free_hook(rng, rng->free_hook_arg); |
7930 | | rng->free_hook_arg = NULL; |
7931 | | } |
7932 | | #endif |
7933 | | |
7934 | 68.1k | #ifdef WC_RNG_HAVE_AUTO_LOCK |
7935 | 68.1k | RngAutoLockFree(rng); |
7936 | 68.1k | #endif |
7937 | | |
7938 | | #ifdef WC_RNG_HAVE_POOL |
7939 | | /* The transition to TORNDOWN imparts an obligation to wipe and free() the |
7940 | | * pool, which is discharged here. The take above certified that no writer |
7941 | | * or allocator holds the ring, and TORNDOWN refuses any new one, so these |
7942 | | * are plain stores. */ |
7943 | | if ((WC_RNG_POOL_STATE(starting_poolhead) != WC_RNG_POOL_STATE_TORNDOWN) && (rng->pool != NULL)) { |
7944 | | byte *pool_ptr = rng->pool; |
7945 | | ForceZero(pool_ptr, rng->poolSize); |
7946 | | rng->pool = NULL; |
7947 | | XFREE(pool_ptr, rng->heap, DYNAMIC_TYPE_RNG); |
7948 | | rng->poolSize = 0; |
7949 | | WOLFSSL_ATOMIC_STORE(rng->poolTail, WC_RNG_POOL_PACK(0, 0)); |
7950 | | /* poolHead stays TORNDOWN */ |
7951 | | } |
7952 | | #endif |
7953 | | |
7954 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
7955 | | /* single-owner teardown, as for the pool */ |
7956 | | if (rng->nextSeed != NULL) { |
7957 | | ForceZero(rng->nextSeed, WC_DRBG_SEED_BUF_SIZE); |
7958 | | #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) |
7959 | | { |
7960 | | byte *nextSeed_ptr = rng->nextSeed; |
7961 | | rng->nextSeed = NULL; |
7962 | | XFREE(nextSeed_ptr, rng->heap, DYNAMIC_TYPE_RNG); |
7963 | | } |
7964 | | #endif |
7965 | | } |
7966 | | |
7967 | | ForceZero(rng->nextStir, (word32)sizeof(rng->nextStir)); |
7968 | | WOLFSSL_ATOMIC_STORE(rng->nextStirLen, WC_DRBG_NEXT_SEED_TORNDOWN); |
7969 | | #endif |
7970 | | |
7971 | | #if defined(WOLFSSL_ASYNC_CRYPT) |
7972 | | wolfAsync_DevCtxFree(&rng->asyncDev, WOLFSSL_ASYNC_MARKER_RNG); |
7973 | | #endif |
7974 | | |
7975 | 68.1k | #ifdef HAVE_HASHDRBG |
7976 | 68.1k | #ifndef NO_SHA256 |
7977 | 68.1k | if ((rng->drbgType == WC_DRBG_SHA256) && (rng->drbg != NULL)) { |
7978 | 0 | int uninst_ret = Hash_DRBG_Uninstantiate((DRBG_internal *)rng->drbg); |
7979 | 0 | if ((ret == 0) && (uninst_ret != 0)) { |
7980 | 0 | if (uninst_ret < 0) |
7981 | 0 | ret = uninst_ret; |
7982 | 0 | else |
7983 | 0 | ret = RNG_FAILURE_E; |
7984 | 0 | } |
7985 | |
|
7986 | 0 | #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) |
7987 | 0 | { |
7988 | 0 | struct DRBG* drbg_ptr = rng->drbg; |
7989 | 0 | rng->drbg = NULL; |
7990 | 0 | XFREE(drbg_ptr, rng->heap, DYNAMIC_TYPE_RNG); |
7991 | 0 | } |
7992 | | #else |
7993 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
7994 | | wc_MemZero_Check(rng->drbg, sizeof(DRBG_internal)); |
7995 | | #endif |
7996 | | rng->drbg = NULL; |
7997 | | #endif |
7998 | 0 | } |
7999 | | #if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY) |
8000 | | /* A failed instantiate nulls rng->drbg with the state still in here. */ |
8001 | | ForceZero(&rng->drbg_data, sizeof(rng->drbg_data)); |
8002 | | #endif |
8003 | | |
8004 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
8005 | | /* Scratch buffers are tracked independently of rng->drbg so that a |
8006 | | * partial-construction failure path that nulled rng->drbg early |
8007 | | * (or any future restructure that does the same) cannot leak them. |
8008 | | * Free on their own NULL check rather than nesting under drbg. */ |
8009 | | if ((rng->drbgType == WC_DRBG_SHA256) && (rng->drbg_scratch != NULL)) { |
8010 | | int uninst_ret = Hash_DRBG_Uninstantiate((DRBG_internal *)rng->drbg_scratch); |
8011 | | if ((ret == 0) && (uninst_ret != 0)) { |
8012 | | if (uninst_ret < 0) |
8013 | | ret = uninst_ret; |
8014 | | else |
8015 | | ret = RNG_FAILURE_E; |
8016 | | } |
8017 | | { |
8018 | | struct DRBG_internal *drbg_scratch_ptr = rng->drbg_scratch; |
8019 | | rng->drbg_scratch = NULL; |
8020 | | XFREE(drbg_scratch_ptr, rng->heap, DYNAMIC_TYPE_RNG); |
8021 | | } |
8022 | | } |
8023 | | if (rng->health_check_scratch != NULL) { |
8024 | | byte *health_check_scratch_ptr = rng->health_check_scratch; |
8025 | | rng->health_check_scratch = NULL; |
8026 | | XFREE(health_check_scratch_ptr, rng->heap, DYNAMIC_TYPE_TMP_BUFFER); |
8027 | | } |
8028 | | #endif |
8029 | 68.1k | #endif /* !NO_SHA256 */ |
8030 | | |
8031 | 68.1k | #ifdef WOLFSSL_DRBG_SHA512 |
8032 | 68.1k | if ((rng->drbgType == WC_DRBG_SHA512) && (rng->drbg512 != NULL)) { |
8033 | 68.0k | int uninst_ret = Hash512_DRBG_Uninstantiate( |
8034 | 68.0k | (DRBG_SHA512_internal *)rng->drbg512); |
8035 | 68.0k | if ((ret == 0) && (uninst_ret != 0)) { |
8036 | 0 | if (uninst_ret < 0) |
8037 | 0 | ret = uninst_ret; |
8038 | 0 | else |
8039 | 0 | ret = RNG_FAILURE_E; |
8040 | 0 | } |
8041 | | |
8042 | 68.0k | #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) |
8043 | 68.0k | { |
8044 | 68.0k | struct DRBG_SHA512* drbg512_ptr = rng->drbg512; |
8045 | 68.0k | rng->drbg512 = NULL; |
8046 | 68.0k | XFREE(drbg512_ptr, rng->heap, DYNAMIC_TYPE_RNG); |
8047 | 68.0k | } |
8048 | | #else |
8049 | | rng->drbg512 = NULL; |
8050 | | #endif |
8051 | 68.0k | } |
8052 | | #if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY) |
8053 | | ForceZero(&rng->drbg512_data, sizeof(rng->drbg512_data)); |
8054 | | #endif |
8055 | | |
8056 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
8057 | | /* Same independence rationale as the SHA-256 scratch above. */ |
8058 | | if ((rng->drbgType == WC_DRBG_SHA512) && (rng->drbg512_scratch != NULL)) { |
8059 | | int uninst_ret = Hash512_DRBG_Uninstantiate(rng->drbg512_scratch); |
8060 | | if ((ret == 0) && (uninst_ret != 0)) { |
8061 | | if (uninst_ret < 0) |
8062 | | ret = uninst_ret; |
8063 | | else |
8064 | | ret = RNG_FAILURE_E; |
8065 | | } |
8066 | | { |
8067 | | struct DRBG_SHA512_internal *drbg512_scratch_ptr = rng->drbg512_scratch; |
8068 | | rng->drbg512_scratch = NULL; |
8069 | | XFREE(drbg512_scratch_ptr, rng->heap, DYNAMIC_TYPE_RNG); |
8070 | | } |
8071 | | } |
8072 | | if (rng->health_check_scratch_512 != NULL) { |
8073 | | byte *health_check_scratch_512_ptr = rng->health_check_scratch_512; |
8074 | | rng->health_check_scratch_512 = NULL; |
8075 | | XFREE(health_check_scratch_512_ptr, rng->heap, |
8076 | | DYNAMIC_TYPE_TMP_BUFFER); |
8077 | | } |
8078 | | #endif |
8079 | 68.1k | #endif /* WOLFSSL_DRBG_SHA512 */ |
8080 | | |
8081 | 68.1k | rng->status = DRBG_NOT_INIT; |
8082 | 68.1k | #endif /* HAVE_HASHDRBG */ |
8083 | | |
8084 | | #ifdef WOLFSSL_XILINX_CRYPT_VERSAL |
8085 | | /* don't overwrite previously set error */ |
8086 | | if (wc_VersalTrngReset() && !ret) |
8087 | | ret = WC_HW_E; |
8088 | | #endif |
8089 | | |
8090 | | #if defined(WOLFSSL_KEEP_RNG_SEED_FD_OPEN) && defined(XCLOSE) && \ |
8091 | | !defined(USE_WINDOWS_API) |
8092 | | if(rng->seed.seedFdOpen && rng->seed.fd != XBADFD) { |
8093 | | XCLOSE(rng->seed.fd); |
8094 | | rng->seed.fd = XBADFD; |
8095 | | rng->seed.seedFdOpen = 0; |
8096 | | } |
8097 | | #endif |
8098 | | |
8099 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
8100 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) { |
8101 | | /* If the latch is held, the caller is the holder (enforced when |
8102 | | * _LOCK_REQUIRED) and owns the mutex: release it before |
8103 | | * destruction. A free latch means the mutex is unowned. */ |
8104 | | if (WOLFSSL_ATOMIC_LOAD(rng->lock) & WC_RNG_LOCK_HELD) |
8105 | | (void)wc_UnLockMutex(&rng->mutex); |
8106 | | (void)wc_FreeMutex(&rng->mutex); |
8107 | | rng->flags &= ~WC_RNG_FLAG_FULL_MUTEX; |
8108 | | } |
8109 | | #endif |
8110 | | |
8111 | | /* Note, rng->lock and rng->RBGC_refcount must *not* be cleared -- they may |
8112 | | * still be arbitrating access even after wc_FreeRng(). |
8113 | | */ |
8114 | | |
8115 | | #if defined(WC_RNG_HAVE_RBGC) && defined(WC_RNG_HAVE_LOCK) |
8116 | | if ((ret == 0) && |
8117 | | (WOLFSSL_ATOMIC_LOAD(rng->RBGC_refcount) > 0)) |
8118 | | { |
8119 | | ret = STILL_REFERENCED_E; |
8120 | | } |
8121 | | #endif |
8122 | | |
8123 | 68.1k | return ret; |
8124 | 68.1k | } |
8125 | | |
8126 | | #ifdef WC_RNG_HAVE_LOCK |
8127 | | int wc_FreeRng(WC_RNG* rng) |
8128 | | { |
8129 | | int ret = 0; |
8130 | | |
8131 | | if (rng == NULL) |
8132 | | return BAD_FUNC_ARG; |
8133 | | |
8134 | | #ifdef WC_HAVE_RNG_BANKREF |
8135 | | if (rng->flags & WC_RNG_FLAG_BANKREF) |
8136 | | return wc_BankRef_Release(rng); |
8137 | | #endif /* WC_HAVE_RNG_BANKREF */ |
8138 | | |
8139 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
8140 | | /* outermost layer first, as in wc_RNG_lock_get(): _PreLocked() releases |
8141 | | * and frees the mutex on the strength of _HELD, so _HELD must mean the |
8142 | | * mutex is ours. */ |
8143 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) { |
8144 | | if (wc_LockMutex(&rng->mutex) != 0) |
8145 | | return BAD_MUTEX_E; |
8146 | | } |
8147 | | #endif |
8148 | | |
8149 | | ret = wc_RNG_lock_get_unconditional(rng); |
8150 | | if (ret != 0) { |
8151 | | /* deallocating a held RNG induces undefined behavior. must return |
8152 | | * failure. */ |
8153 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
8154 | | if (rng->flags & WC_RNG_FLAG_FULL_MUTEX) |
8155 | | (void)wc_UnLockMutex(&rng->mutex); |
8156 | | #endif |
8157 | | return ret; |
8158 | | } |
8159 | | |
8160 | | ret = wc_FreeRng_PreLocked(rng); |
8161 | | |
8162 | | wc_RNG_lock_put_unconditional(rng); |
8163 | | |
8164 | | #ifdef WC_RNG_HAVE_LOCK_FULL_MUTEX |
8165 | | if ((ret != 0) && (rng->flags & WC_RNG_FLAG_FULL_MUTEX)) |
8166 | | (void)wc_UnLockMutex(&rng->mutex); |
8167 | | #endif |
8168 | | |
8169 | | return ret; |
8170 | | } |
8171 | | #endif /* WC_RNG_HAVE_LOCK */ |
8172 | | |
8173 | | #ifdef HAVE_HASHDRBG |
8174 | | /* The original wc_RNG_HealthTest{,_ex} entry points operate on the SHA-256 |
8175 | | * Hash_DRBG (DRBG_internal). Gate them out under NO_SHA256; SHA-512-only |
8176 | | * builds use wc_RNG_HealthTest_SHA512_ex declared further down. */ |
8177 | | #ifndef NO_SHA256 |
8178 | | int wc_RNG_HealthTest(int reseed, const byte* seedA, word32 seedASz, |
8179 | | const byte* seedB, word32 seedBSz, |
8180 | | byte* output, word32 outputSz) |
8181 | 0 | { |
8182 | 0 | return wc_RNG_HealthTest_ex(reseed, NULL, 0, |
8183 | 0 | seedA, seedASz, seedB, seedBSz, |
8184 | 0 | output, outputSz, |
8185 | 0 | NULL, INVALID_DEVID); |
8186 | 0 | } |
8187 | | |
8188 | | |
8189 | | static WARN_UNUSED_RESULT int wc_RNG_HealthTest_ex_internal(DRBG_internal* drbg, |
8190 | | int reseed, const byte* nonce, word32 nonceSz, |
8191 | | const byte* seedA, word32 seedASz, |
8192 | | const byte* seedB, word32 seedBSz, |
8193 | | byte* output, word32 outputSz, |
8194 | | void* heap, int devId) |
8195 | 0 | { |
8196 | 0 | int ret = WC_NO_ERR_TRACE(DRBG_FAILURE); |
8197 | 0 | wc_drbg_reseed_ctr_t reseedCtr; |
8198 | |
|
8199 | 0 | if (seedA == NULL || output == NULL) { |
8200 | 0 | return BAD_FUNC_ARG; |
8201 | 0 | } |
8202 | | |
8203 | 0 | if (reseed != 0 && seedB == NULL) { |
8204 | 0 | return BAD_FUNC_ARG; |
8205 | 0 | } |
8206 | | |
8207 | 0 | if (outputSz != RNG_HEALTH_TEST_CHECK_SIZE) { |
8208 | 0 | return BAD_FUNC_ARG; |
8209 | 0 | } |
8210 | | |
8211 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
8212 | | (void)heap; |
8213 | | (void)devId; |
8214 | | |
8215 | | if (Hash_DRBG_Init(drbg, &reseedCtr, seedA, seedASz, nonce, nonceSz, |
8216 | | NULL, 0) != 0) { |
8217 | | goto exit_rng_ht; |
8218 | | } |
8219 | | #else |
8220 | 0 | if (Hash_DRBG_Instantiate(drbg, &reseedCtr, seedA, seedASz, nonce, nonceSz, |
8221 | 0 | NULL, 0, heap, devId) != 0) { |
8222 | 0 | goto exit_rng_ht; |
8223 | 0 | } |
8224 | 0 | #endif |
8225 | | |
8226 | 0 | if (reseed) { |
8227 | 0 | if (Hash256_DRBG_Reseed(drbg, &reseedCtr, seedB, seedBSz, NULL, 0) != 0) { |
8228 | 0 | goto exit_rng_ht; |
8229 | 0 | } |
8230 | 0 | } |
8231 | | |
8232 | | /* This call to generate is prescribed by the NIST DRBGVS |
8233 | | * procedure. The results are thrown away. The known |
8234 | | * answer test checks the second block of DRBG out of |
8235 | | * the generator to ensure the internal state is updated |
8236 | | * as expected. */ |
8237 | 0 | if (Hash_DRBG_Generate(drbg, &reseedCtr, output, outputSz, NULL, 0) != 0) { |
8238 | 0 | goto exit_rng_ht; |
8239 | 0 | } |
8240 | | |
8241 | 0 | if (Hash_DRBG_Generate(drbg, &reseedCtr, output, outputSz, NULL, 0) != 0) { |
8242 | 0 | goto exit_rng_ht; |
8243 | 0 | } |
8244 | | |
8245 | | /* Mark success */ |
8246 | 0 | ret = 0; |
8247 | |
|
8248 | 0 | exit_rng_ht: |
8249 | |
|
8250 | 0 | #ifndef WOLFSSL_SMALL_STACK_CACHE |
8251 | | /* This is safe to call even if Hash_DRBG_Instantiate fails */ |
8252 | 0 | { |
8253 | 0 | int uninst_ret = Hash_DRBG_Uninstantiate(drbg); |
8254 | 0 | if ((uninst_ret != 0) && (ret == 0)) |
8255 | 0 | ret = uninst_ret; |
8256 | 0 | } |
8257 | 0 | #endif |
8258 | |
|
8259 | 0 | return ret; |
8260 | 0 | } |
8261 | | |
8262 | | int wc_RNG_HealthTest_ex(int reseed, const byte* nonce, word32 nonceSz, |
8263 | | const byte* seedA, word32 seedASz, |
8264 | | const byte* seedB, word32 seedBSz, |
8265 | | byte* output, word32 outputSz, |
8266 | | void* heap, int devId) |
8267 | 0 | { |
8268 | 0 | int ret = WC_NO_ERR_TRACE(WC_FAILURE); |
8269 | 0 | DRBG_internal* drbg; |
8270 | | #ifndef WOLFSSL_SMALL_STACK |
8271 | | DRBG_internal drbg_var; |
8272 | | #endif |
8273 | |
|
8274 | 0 | #ifdef WOLFSSL_SMALL_STACK |
8275 | 0 | drbg = (DRBG_internal*)XMALLOC(sizeof(DRBG_internal), heap, |
8276 | 0 | DYNAMIC_TYPE_RNG); |
8277 | 0 | if (drbg == NULL) { |
8278 | 0 | return MEMORY_E; |
8279 | 0 | } |
8280 | | #else |
8281 | | drbg = &drbg_var; |
8282 | | #endif |
8283 | | |
8284 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
8285 | | ret = Hash_DRBG_Instantiate(drbg, NULL /* reseedCtr */, |
8286 | | NULL /* seed */, 0, NULL /* nonce */, 0, |
8287 | | NULL /* perso */, 0, heap, devId); |
8288 | | if (ret == 0) |
8289 | | #endif |
8290 | 0 | { |
8291 | 0 | ret = wc_RNG_HealthTest_ex_internal( |
8292 | 0 | drbg, reseed, nonce, nonceSz, seedA, seedASz, |
8293 | 0 | seedB, seedBSz, output, outputSz, heap, devId); |
8294 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
8295 | | { |
8296 | | int uninst_ret = Hash_DRBG_Uninstantiate(drbg); |
8297 | | if ((uninst_ret != 0) && (ret == 0)) |
8298 | | ret = uninst_ret; |
8299 | | } |
8300 | | #endif |
8301 | 0 | } |
8302 | 0 | WC_FREE_VAR_EX(drbg, heap, DYNAMIC_TYPE_RNG); |
8303 | |
|
8304 | 0 | if (ret > 0) { |
8305 | | /* Translate protocol-domain codes at the public boundary; negative |
8306 | | * codes (MEMORY_E, BAD_FUNC_ARG) pass verbatim. */ |
8307 | 0 | ret = WC_FAILURE; |
8308 | 0 | } |
8309 | 0 | return ret; |
8310 | 0 | } |
8311 | | #endif /* !NO_SHA256 - wc_RNG_HealthTest{,_ex,_ex_internal} */ |
8312 | | |
8313 | | |
8314 | | const FLASH_QUALIFIER byte seedA_data[] = { |
8315 | | 0x63, 0x36, 0x33, 0x77, 0xe4, 0x1e, 0x86, 0x46, 0x8d, 0xeb, 0x0a, 0xb4, |
8316 | | 0xa8, 0xed, 0x68, 0x3f, 0x6a, 0x13, 0x4e, 0x47, 0xe0, 0x14, 0xc7, 0x00, |
8317 | | 0x45, 0x4e, 0x81, 0xe9, 0x53, 0x58, 0xa5, 0x69, 0x80, 0x8a, 0xa3, 0x8f, |
8318 | | 0x2a, 0x72, 0xa6, 0x23, 0x59, 0x91, 0x5a, 0x9f, 0x8a, 0x04, 0xca, 0x68 |
8319 | | }; |
8320 | | |
8321 | | const FLASH_QUALIFIER byte reseedSeedA_data[] = { |
8322 | | 0xe6, 0x2b, 0x8a, 0x8e, 0xe8, 0xf1, 0x41, 0xb6, 0x98, 0x05, 0x66, 0xe3, |
8323 | | 0xbf, 0xe3, 0xc0, 0x49, 0x03, 0xda, 0xd4, 0xac, 0x2c, 0xdf, 0x9f, 0x22, |
8324 | | 0x80, 0x01, 0x0a, 0x67, 0x39, 0xbc, 0x83, 0xd3 |
8325 | | }; |
8326 | | |
8327 | | const FLASH_QUALIFIER byte outputA_data[] = { |
8328 | | 0x04, 0xee, 0xc6, 0x3b, 0xb2, 0x31, 0xdf, 0x2c, 0x63, 0x0a, 0x1a, 0xfb, |
8329 | | 0xe7, 0x24, 0x94, 0x9d, 0x00, 0x5a, 0x58, 0x78, 0x51, 0xe1, 0xaa, 0x79, |
8330 | | 0x5e, 0x47, 0x73, 0x47, 0xc8, 0xb0, 0x56, 0x62, 0x1c, 0x18, 0xbd, 0xdc, |
8331 | | 0xdd, 0x8d, 0x99, 0xfc, 0x5f, 0xc2, 0xb9, 0x20, 0x53, 0xd8, 0xcf, 0xac, |
8332 | | 0xfb, 0x0b, 0xb8, 0x83, 0x12, 0x05, 0xfa, 0xd1, 0xdd, 0xd6, 0xc0, 0x71, |
8333 | | 0x31, 0x8a, 0x60, 0x18, 0xf0, 0x3b, 0x73, 0xf5, 0xed, 0xe4, 0xd4, 0xd0, |
8334 | | 0x71, 0xf9, 0xde, 0x03, 0xfd, 0x7a, 0xea, 0x10, 0x5d, 0x92, 0x99, 0xb8, |
8335 | | 0xaf, 0x99, 0xaa, 0x07, 0x5b, 0xdb, 0x4d, 0xb9, 0xaa, 0x28, 0xc1, 0x8d, |
8336 | | 0x17, 0x4b, 0x56, 0xee, 0x2a, 0x01, 0x4d, 0x09, 0x88, 0x96, 0xff, 0x22, |
8337 | | 0x82, 0xc9, 0x55, 0xa8, 0x19, 0x69, 0xe0, 0x69, 0xfa, 0x8c, 0xe0, 0x07, |
8338 | | 0xa1, 0x80, 0x18, 0x3a, 0x07, 0xdf, 0xae, 0x17 |
8339 | | }; |
8340 | | |
8341 | | const FLASH_QUALIFIER byte seedB_data[] = { |
8342 | | 0xa6, 0x5a, 0xd0, 0xf3, 0x45, 0xdb, 0x4e, 0x0e, 0xff, 0xe8, 0x75, 0xc3, |
8343 | | 0xa2, 0xe7, 0x1f, 0x42, 0xc7, 0x12, 0x9d, 0x62, 0x0f, 0xf5, 0xc1, 0x19, |
8344 | | 0xa9, 0xef, 0x55, 0xf0, 0x51, 0x85, 0xe0, 0xfb, /* nonce next */ |
8345 | | 0x85, 0x81, 0xf9, 0x31, 0x75, 0x17, 0x27, 0x6e, 0x06, 0xe9, 0x60, 0x7d, |
8346 | | 0xdb, 0xcb, 0xcc, 0x2e |
8347 | | }; |
8348 | | |
8349 | | const FLASH_QUALIFIER byte outputB_data[] = { |
8350 | | 0xd3, 0xe1, 0x60, 0xc3, 0x5b, 0x99, 0xf3, 0x40, 0xb2, 0x62, 0x82, 0x64, |
8351 | | 0xd1, 0x75, 0x10, 0x60, 0xe0, 0x04, 0x5d, 0xa3, 0x83, 0xff, 0x57, 0xa5, |
8352 | | 0x7d, 0x73, 0xa6, 0x73, 0xd2, 0xb8, 0xd8, 0x0d, 0xaa, 0xf6, 0xa6, 0xc3, |
8353 | | 0x5a, 0x91, 0xbb, 0x45, 0x79, 0xd7, 0x3f, 0xd0, 0xc8, 0xfe, 0xd1, 0x11, |
8354 | | 0xb0, 0x39, 0x13, 0x06, 0x82, 0x8a, 0xdf, 0xed, 0x52, 0x8f, 0x01, 0x81, |
8355 | | 0x21, 0xb3, 0xfe, 0xbd, 0xc3, 0x43, 0xe7, 0x97, 0xb8, 0x7d, 0xbb, 0x63, |
8356 | | 0xdb, 0x13, 0x33, 0xde, 0xd9, 0xd1, 0xec, 0xe1, 0x77, 0xcf, 0xa6, 0xb7, |
8357 | | 0x1f, 0xe8, 0xab, 0x1d, 0xa4, 0x66, 0x24, 0xed, 0x64, 0x15, 0xe5, 0x1c, |
8358 | | 0xcd, 0xe2, 0xc7, 0xca, 0x86, 0xe2, 0x83, 0x99, 0x0e, 0xea, 0xeb, 0x91, |
8359 | | 0x12, 0x04, 0x15, 0x52, 0x8b, 0x22, 0x95, 0x91, 0x02, 0x81, 0xb0, 0x2d, |
8360 | | 0xd4, 0x31, 0xf4, 0xc9, 0xf7, 0x04, 0x27, 0xdf |
8361 | | }; |
8362 | | |
8363 | | |
8364 | | #ifndef CUSTOM_RAND_GENERATE_BLOCK |
8365 | | /* SHA-512 DRBG KAT vectors for local health test. |
8366 | | * Source: NIST CAVP Hash_DRBG.rsp, [SHA-512], PredictionResistance=False, |
8367 | | * EntropyInputLen=256, NonceLen=128, PersonalizationStringLen=0, |
8368 | | * AdditionalInputLen=0, ReturnedBitsLen=2048. */ |
8369 | | #ifdef WOLFSSL_DRBG_SHA512 |
8370 | | |
8371 | | /* Reseed test vectors (COUNT=0 from reseed section) */ |
8372 | | static const byte sha512_seedA_data[] = { |
8373 | | /* EntropyInput (32 bytes) || Nonce (16 bytes) */ |
8374 | | 0x31, 0x44, 0xe1, 0x7a, 0x10, 0xc8, 0x56, 0x12, |
8375 | | 0x97, 0x64, 0xf5, 0x8f, 0xd8, 0xe4, 0x23, 0x10, |
8376 | | 0x20, 0x54, 0x69, 0x96, 0xc0, 0xbf, 0x6c, 0xff, |
8377 | | 0x8e, 0x91, 0xc2, 0x4e, 0xe0, 0x9b, 0xe3, 0x33, |
8378 | | 0xb1, 0x6f, 0xcb, 0x1c, 0xf0, 0xc0, 0x10, 0xf3, |
8379 | | 0x1f, 0xea, 0xb7, 0x33, 0x58, 0x8b, 0x8e, 0x04 |
8380 | | }; |
8381 | | static const byte sha512_reseedSeedA_data[] = { |
8382 | | /* EntropyInputReseed (32 bytes) */ |
8383 | | 0xa0, 0xb3, 0x58, 0x4c, 0x2c, 0x84, 0x12, 0xf6, |
8384 | | 0x18, 0x40, 0x68, 0x34, 0x40, 0x4d, 0x1e, 0xb0, |
8385 | | 0xce, 0x99, 0x9b, 0xa2, 0x89, 0x66, 0x05, 0x4d, |
8386 | | 0x7e, 0x49, 0x7e, 0x0d, 0xb6, 0x08, 0xb9, 0x67 |
8387 | | }; |
8388 | | static const byte sha512_outputA_data[] = { |
8389 | | 0xef, 0xa3, 0x5d, 0xd0, 0x36, 0x2a, 0xdb, 0x76, |
8390 | | 0x26, 0x45, 0x6b, 0x36, 0xfa, 0xc7, 0x4d, 0x3c, |
8391 | | 0x28, 0xd0, 0x1d, 0x92, 0x64, 0x20, 0x27, 0x5a, |
8392 | | 0x28, 0xbe, 0xa9, 0xc9, 0xdd, 0x75, 0x47, 0xc1, |
8393 | | 0x5e, 0x79, 0x31, 0x85, 0x2a, 0xc1, 0x27, 0x70, |
8394 | | 0x76, 0x56, 0x75, 0x35, 0x23, 0x9c, 0x1f, 0x42, |
8395 | | 0x9c, 0x7f, 0x75, 0xcf, 0x74, 0xc2, 0x26, 0x7d, |
8396 | | 0xeb, 0x6a, 0x3e, 0x59, 0x6c, 0xf3, 0x26, 0x15, |
8397 | | 0x6c, 0x79, 0x69, 0x41, 0x28, 0x3b, 0x8d, 0x58, |
8398 | | 0x3f, 0x17, 0x1c, 0x2f, 0x6e, 0x33, 0x23, 0xf7, |
8399 | | 0x55, 0x5e, 0x1b, 0x18, 0x1f, 0xfd, 0xa3, 0x05, |
8400 | | 0x07, 0x21, 0x0c, 0xb1, 0xf5, 0x89, 0xb2, 0x3c, |
8401 | | 0xd7, 0x18, 0x80, 0xfd, 0x44, 0x37, 0x0c, 0xac, |
8402 | | 0xf4, 0x33, 0x75, 0xb0, 0xdb, 0x7e, 0x33, 0x6f, |
8403 | | 0x12, 0xb3, 0x09, 0xbf, 0xd4, 0xf6, 0x10, 0xbb, |
8404 | | 0x8f, 0x20, 0xe1, 0xa1, 0x5e, 0x25, 0x3a, 0x4f, |
8405 | | 0xe5, 0x11, 0xa0, 0x27, 0x96, 0x8d, 0xf0, 0xb1, |
8406 | | 0x05, 0xa1, 0xd7, 0x3a, 0xff, 0x7c, 0x7a, 0x82, |
8407 | | 0x6d, 0x39, 0xf6, 0x40, 0xdf, 0xb8, 0xf5, 0x22, |
8408 | | 0x25, 0x9e, 0xd4, 0x02, 0x28, 0x2e, 0x2c, 0x2e, |
8409 | | 0x9d, 0x3a, 0x49, 0x8f, 0x51, 0x72, 0x5f, 0xe4, |
8410 | | 0x14, 0x1b, 0x06, 0xda, 0x55, 0x98, 0xa4, 0x2a, |
8411 | | 0xc1, 0xe0, 0x49, 0x4e, 0x99, 0x7d, 0x56, 0x6a, |
8412 | | 0x1a, 0x39, 0xb6, 0x76, 0xb9, 0x6a, 0x60, 0x03, |
8413 | | 0xa4, 0xc5, 0xdb, 0x84, 0xf2, 0x46, 0x58, 0x4e, |
8414 | | 0xe6, 0x5a, 0xf7, 0x0f, 0xf2, 0x16, 0x02, 0x78, |
8415 | | 0x16, 0x6d, 0xa1, 0x6d, 0x91, 0xc9, 0xb8, 0xf2, |
8416 | | 0xde, 0xb0, 0x27, 0x51, 0xa1, 0x08, 0x8a, 0xd6, |
8417 | | 0xbe, 0x4e, 0x80, 0xef, 0x96, 0x6e, 0xb7, 0x3e, |
8418 | | 0x66, 0xbc, 0x87, 0xca, 0xd8, 0x7c, 0x77, 0xc0, |
8419 | | 0xb3, 0x4a, 0x21, 0xba, 0x1d, 0xa0, 0xba, 0x6d, |
8420 | | 0x16, 0xca, 0x50, 0x46, 0xdc, 0x4a, 0xbd, 0xa0 |
8421 | | }; |
8422 | | |
8423 | | /* No-reseed test vectors (COUNT=0 from no-reseed section) */ |
8424 | | static const byte sha512_seedB_data[] = { |
8425 | | /* EntropyInput (32 bytes) || Nonce (16 bytes) */ |
8426 | | 0x6b, 0x50, 0xa7, 0xd8, 0xf8, 0xa5, 0x5d, 0x7a, |
8427 | | 0x3d, 0xf8, 0xbb, 0x40, 0xbc, 0xc3, 0xb7, 0x22, |
8428 | | 0xd8, 0x70, 0x8d, 0xe6, 0x7f, 0xda, 0x01, 0x0b, |
8429 | | 0x03, 0xc4, 0xc8, 0x4d, 0x72, 0x09, 0x6f, 0x8c, |
8430 | | 0x3e, 0xc6, 0x49, 0xcc, 0x62, 0x56, 0xd9, 0xfa, |
8431 | | 0x31, 0xdb, 0x7a, 0x29, 0x04, 0xaa, 0xf0, 0x25 |
8432 | | }; |
8433 | | static const byte sha512_outputB_data[] = { |
8434 | | 0x95, 0xb7, 0xf1, 0x7e, 0x98, 0x02, 0xd3, 0x57, |
8435 | | 0x73, 0x92, 0xc6, 0xa9, 0xc0, 0x80, 0x83, 0xb6, |
8436 | | 0x7d, 0xd1, 0x29, 0x22, 0x65, 0xb5, 0xf4, 0x2d, |
8437 | | 0x23, 0x7f, 0x1c, 0x55, 0xbb, 0x9b, 0x10, 0xbf, |
8438 | | 0xcf, 0xd8, 0x2c, 0x77, 0xa3, 0x78, 0xb8, 0x26, |
8439 | | 0x6a, 0x00, 0x99, 0x14, 0x3b, 0x3c, 0x2d, 0x64, |
8440 | | 0x61, 0x1e, 0xee, 0xb6, 0x9a, 0xcd, 0xc0, 0x55, |
8441 | | 0x95, 0x7c, 0x13, 0x9e, 0x8b, 0x19, 0x0c, 0x7a, |
8442 | | 0x06, 0x95, 0x5f, 0x2c, 0x79, 0x7c, 0x27, 0x78, |
8443 | | 0xde, 0x94, 0x03, 0x96, 0xa5, 0x01, 0xf4, 0x0e, |
8444 | | 0x91, 0x39, 0x6a, 0xcf, 0x8d, 0x7e, 0x45, 0xeb, |
8445 | | 0xdb, 0xb5, 0x3b, 0xbf, 0x8c, 0x97, 0x52, 0x30, |
8446 | | 0xd2, 0xf0, 0xff, 0x91, 0x06, 0xc7, 0x61, 0x19, |
8447 | | 0xae, 0x49, 0x8e, 0x7f, 0xbc, 0x03, 0xd9, 0x0f, |
8448 | | 0x8e, 0x4c, 0x51, 0x62, 0x7a, 0xed, 0x5c, 0x8d, |
8449 | | 0x42, 0x63, 0xd5, 0xd2, 0xb9, 0x78, 0x87, 0x3a, |
8450 | | 0x0d, 0xe5, 0x96, 0xee, 0x6d, 0xc7, 0xf7, 0xc2, |
8451 | | 0x9e, 0x37, 0xee, 0xe8, 0xb3, 0x4c, 0x90, 0xdd, |
8452 | | 0x1c, 0xf6, 0xa9, 0xdd, 0xb2, 0x2b, 0x4c, 0xbd, |
8453 | | 0x08, 0x6b, 0x14, 0xb3, 0x5d, 0xe9, 0x3d, 0xa2, |
8454 | | 0xd5, 0xcb, 0x18, 0x06, 0x69, 0x8c, 0xbd, 0x7b, |
8455 | | 0xbb, 0x67, 0xbf, 0xe3, 0xd3, 0x1f, 0xd2, 0xd1, |
8456 | | 0xdb, 0xd2, 0xa1, 0xe0, 0x58, 0xa3, 0xeb, 0x99, |
8457 | | 0xd7, 0xe5, 0x1f, 0x1a, 0x93, 0x8e, 0xed, 0x5e, |
8458 | | 0x1c, 0x1d, 0xe2, 0x3a, 0x6b, 0x43, 0x45, 0xd3, |
8459 | | 0x19, 0x14, 0x09, 0xf9, 0x2f, 0x39, 0xb3, 0x67, |
8460 | | 0x0d, 0x8d, 0xbf, 0xb6, 0x35, 0xd8, 0xe6, 0xa3, |
8461 | | 0x69, 0x32, 0xd8, 0x10, 0x33, 0xd1, 0x44, 0x8d, |
8462 | | 0x63, 0xb4, 0x03, 0xdd, 0xf8, 0x8e, 0x12, 0x1b, |
8463 | | 0x6e, 0x81, 0x9a, 0xc3, 0x81, 0x22, 0x6c, 0x13, |
8464 | | 0x21, 0xe4, 0xb0, 0x86, 0x44, 0xf6, 0x72, 0x7c, |
8465 | | 0x36, 0x8c, 0x5a, 0x9f, 0x7a, 0x4b, 0x3e, 0xe2 |
8466 | | }; |
8467 | | #endif /* WOLFSSL_DRBG_SHA512 */ |
8468 | | |
8469 | | |
8470 | | static int wc_RNG_HealthTestLocal(WC_RNG* rng, int reseed, void* heap, |
8471 | | int devId) |
8472 | 63.0k | { |
8473 | 63.0k | int ret = 0; |
8474 | | |
8475 | 63.0k | #ifdef WOLFSSL_DRBG_SHA512 |
8476 | | /* SHA-512 DRBG health test path */ |
8477 | 63.0k | if (rng->drbgType == WC_DRBG_SHA512) { |
8478 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
8479 | | byte *check512 = rng->health_check_scratch_512; |
8480 | | DRBG_SHA512_internal* drbg512 = rng->drbg512_scratch; |
8481 | | #else |
8482 | 63.0k | WC_DECLARE_VAR(check512, byte, RNG_HEALTH_TEST_CHECK_SIZE_SHA512, 0); |
8483 | 63.0k | WC_DECLARE_VAR(drbg512, DRBG_SHA512_internal, 1, 0); |
8484 | | |
8485 | 63.0k | WC_ALLOC_VAR_EX(check512, byte, RNG_HEALTH_TEST_CHECK_SIZE_SHA512, |
8486 | 63.0k | heap, DYNAMIC_TYPE_TMP_BUFFER, return MEMORY_E); |
8487 | 63.0k | WC_ALLOC_VAR_EX(drbg512, DRBG_SHA512_internal, 1, heap, |
8488 | 63.0k | DYNAMIC_TYPE_TMP_BUFFER, WC_DO_NOTHING); |
8489 | 63.0k | #ifdef WC_DECLARE_VAR_IS_HEAP_ALLOC |
8490 | 63.0k | if (drbg512 == NULL) { |
8491 | 78 | WC_FREE_VAR_EX(check512, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8492 | 78 | return MEMORY_E; |
8493 | 78 | } |
8494 | 62.9k | #endif |
8495 | 62.9k | #endif |
8496 | | |
8497 | 62.9k | if (reseed) { |
8498 | | /* Reseed test with NIST CAVP SHA-512 vectors */ |
8499 | 0 | ret = wc_RNG_HealthTest_SHA512_ex_internal( |
8500 | 0 | drbg512, 1, NULL, 0, NULL, 0, |
8501 | 0 | sha512_seedA_data, sizeof(sha512_seedA_data), |
8502 | 0 | sha512_reseedSeedA_data, |
8503 | 0 | sizeof(sha512_reseedSeedA_data), |
8504 | 0 | NULL, 0, NULL, 0, |
8505 | 0 | check512, RNG_HEALTH_TEST_CHECK_SIZE_SHA512, |
8506 | 0 | heap, devId); |
8507 | 0 | if (ret == 0) { |
8508 | 0 | if (ConstantCompare(check512, sha512_outputA_data, |
8509 | 0 | RNG_HEALTH_TEST_CHECK_SIZE_SHA512) != 0) |
8510 | 0 | ret = DRBG_CONT_FAILURE; |
8511 | 0 | } |
8512 | 0 | } |
8513 | 62.9k | else { |
8514 | | /* No-reseed test with NIST CAVP SHA-512 vectors */ |
8515 | 62.9k | ret = wc_RNG_HealthTest_SHA512_ex_internal( |
8516 | 62.9k | drbg512, 0, NULL, 0, NULL, 0, |
8517 | 62.9k | sha512_seedB_data, sizeof(sha512_seedB_data), |
8518 | 62.9k | NULL, 0, |
8519 | 62.9k | NULL, 0, NULL, 0, |
8520 | 62.9k | check512, RNG_HEALTH_TEST_CHECK_SIZE_SHA512, |
8521 | 62.9k | heap, devId); |
8522 | 62.9k | if (ret == 0) { |
8523 | 62.3k | if (ConstantCompare(check512, sha512_outputB_data, |
8524 | 62.3k | RNG_HEALTH_TEST_CHECK_SIZE_SHA512) != 0) |
8525 | 0 | ret = DRBG_CONT_FAILURE; |
8526 | 62.3k | } |
8527 | 62.9k | } |
8528 | | |
8529 | 62.9k | #ifndef WOLFSSL_SMALL_STACK_CACHE |
8530 | 62.9k | WC_FREE_VAR_EX(check512, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8531 | 62.9k | WC_FREE_VAR_EX(drbg512, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8532 | 62.9k | #endif |
8533 | 62.9k | return ret; |
8534 | 63.0k | } |
8535 | 0 | #endif /* WOLFSSL_DRBG_SHA512 */ |
8536 | | |
8537 | | /* SHA-256 DRBG health test path (original) */ |
8538 | 0 | #ifndef NO_SHA256 |
8539 | 0 | { |
8540 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
8541 | | byte *check = rng->health_check_scratch; |
8542 | | DRBG_internal* drbg = (DRBG_internal *)rng->drbg_scratch; |
8543 | | #else |
8544 | 0 | WC_DECLARE_VAR(check, byte, RNG_HEALTH_TEST_CHECK_SIZE, 0); |
8545 | 0 | WC_DECLARE_VAR(drbg, DRBG_internal, 1, 0); |
8546 | |
|
8547 | 0 | (void)rng; |
8548 | |
|
8549 | 0 | WC_ALLOC_VAR_EX(check, byte, RNG_HEALTH_TEST_CHECK_SIZE, heap, |
8550 | 0 | DYNAMIC_TYPE_TMP_BUFFER, return MEMORY_E); |
8551 | 0 | WC_ALLOC_VAR_EX(drbg, DRBG_internal, 1, heap, |
8552 | 0 | DYNAMIC_TYPE_TMP_BUFFER, WC_DO_NOTHING); |
8553 | 0 | #ifdef WC_DECLARE_VAR_IS_HEAP_ALLOC |
8554 | 0 | if (drbg == NULL) { |
8555 | 0 | WC_FREE_VAR_EX(check, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8556 | 0 | return MEMORY_E; |
8557 | 0 | } |
8558 | 0 | #endif |
8559 | 0 | #endif |
8560 | | |
8561 | 0 | if (reseed) { |
8562 | | #ifdef WOLFSSL_USE_FLASHMEM |
8563 | | byte* seedA = (byte*)XMALLOC(sizeof(seedA_data), heap, |
8564 | | DYNAMIC_TYPE_TMP_BUFFER); |
8565 | | byte* reseedSeedA = (byte*)XMALLOC(sizeof(reseedSeedA_data), heap, |
8566 | | DYNAMIC_TYPE_TMP_BUFFER); |
8567 | | byte* outputA = (byte*)XMALLOC(sizeof(outputA_data), heap, |
8568 | | DYNAMIC_TYPE_TMP_BUFFER); |
8569 | | |
8570 | | if (!seedA || !reseedSeedA || !outputA) { |
8571 | | XFREE(seedA, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8572 | | XFREE(reseedSeedA, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8573 | | XFREE(outputA, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8574 | | ret = MEMORY_E; |
8575 | | } |
8576 | | else { |
8577 | | XMEMCPY_P(seedA, seedA_data, sizeof(seedA_data)); |
8578 | | XMEMCPY_P(reseedSeedA, reseedSeedA_data, sizeof(reseedSeedA_data)); |
8579 | | XMEMCPY_P(outputA, outputA_data, sizeof(outputA_data)); |
8580 | | #else |
8581 | 0 | const byte* seedA = seedA_data; |
8582 | 0 | const byte* reseedSeedA = reseedSeedA_data; |
8583 | 0 | const byte* outputA = outputA_data; |
8584 | 0 | #endif |
8585 | 0 | ret = wc_RNG_HealthTest_ex_internal(drbg, 1, NULL, 0, |
8586 | 0 | seedA, sizeof(seedA_data), |
8587 | 0 | reseedSeedA, sizeof(reseedSeedA_data), |
8588 | 0 | check, RNG_HEALTH_TEST_CHECK_SIZE, |
8589 | 0 | heap, devId); |
8590 | 0 | if (ret == 0) { |
8591 | 0 | if (ConstantCompare(check, outputA, |
8592 | 0 | RNG_HEALTH_TEST_CHECK_SIZE) != 0) |
8593 | 0 | ret = DRBG_CONT_FAILURE; |
8594 | 0 | } |
8595 | |
|
8596 | | #ifdef WOLFSSL_USE_FLASHMEM |
8597 | | XFREE(seedA, NULL, DYNAMIC_TYPE_TMP_BUFFER); |
8598 | | XFREE(reseedSeedA, NULL, DYNAMIC_TYPE_TMP_BUFFER); |
8599 | | XFREE(outputA, NULL, DYNAMIC_TYPE_TMP_BUFFER); |
8600 | | } |
8601 | | #endif |
8602 | 0 | } |
8603 | 0 | else { |
8604 | | #ifdef WOLFSSL_USE_FLASHMEM |
8605 | | byte* seedB = (byte*)XMALLOC(sizeof(seedB_data), heap, |
8606 | | DYNAMIC_TYPE_TMP_BUFFER); |
8607 | | byte* outputB = (byte*)XMALLOC(sizeof(outputB_data), heap, |
8608 | | DYNAMIC_TYPE_TMP_BUFFER); |
8609 | | |
8610 | | if (!seedB || !outputB) { |
8611 | | XFREE(seedB, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8612 | | XFREE(outputB, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8613 | | ret = MEMORY_E; |
8614 | | } |
8615 | | else { |
8616 | | XMEMCPY_P(seedB, seedB_data, sizeof(seedB_data)); |
8617 | | XMEMCPY_P(outputB, outputB_data, sizeof(outputB_data)); |
8618 | | #else |
8619 | 0 | const byte* seedB = seedB_data; |
8620 | 0 | const byte* outputB = outputB_data; |
8621 | 0 | #endif |
8622 | | #if defined(DEBUG_WOLFSSL) |
8623 | | WOLFSSL_MSG_EX("RNG_HEALTH_TEST_CHECK_SIZE = %d", |
8624 | | RNG_HEALTH_TEST_CHECK_SIZE); |
8625 | | WOLFSSL_MSG_EX("sizeof(seedB_data) = %d", |
8626 | | (int)sizeof(outputB_data)); |
8627 | | #endif |
8628 | 0 | ret = wc_RNG_HealthTest_ex_internal(drbg, 0, NULL, 0, |
8629 | 0 | seedB, sizeof(seedB_data), |
8630 | 0 | NULL, 0, |
8631 | 0 | check, RNG_HEALTH_TEST_CHECK_SIZE, |
8632 | 0 | heap, devId); |
8633 | 0 | if (ret != 0) { |
8634 | | #if defined(DEBUG_WOLFSSL) |
8635 | | WOLFSSL_MSG_EX("RNG_HealthTest failed: err = %d", ret); |
8636 | | #endif |
8637 | 0 | } |
8638 | 0 | else { |
8639 | 0 | ret = ConstantCompare(check, outputB, |
8640 | 0 | RNG_HEALTH_TEST_CHECK_SIZE); |
8641 | 0 | if (ret != 0) { |
8642 | | #if defined(DEBUG_WOLFSSL) |
8643 | | WOLFSSL_MSG_EX("Random ConstantCompare failed: err = %d", ret); |
8644 | | #endif |
8645 | 0 | ret = DRBG_CONT_FAILURE; |
8646 | 0 | } |
8647 | 0 | } |
8648 | | |
8649 | | /* The previous test cases use a large seed instead of a seed and nonce. |
8650 | | * seedB is actually from a test case with a seed and nonce, and |
8651 | | * just concatenates them. The pivot point between seed and nonce is |
8652 | | * byte 32, feed them into the health test separately. */ |
8653 | 0 | if (ret == 0) { |
8654 | 0 | ret = wc_RNG_HealthTest_ex_internal(drbg, 0, |
8655 | 0 | seedB + 32, sizeof(seedB_data) - 32, |
8656 | 0 | seedB, 32, |
8657 | 0 | NULL, 0, |
8658 | 0 | check, RNG_HEALTH_TEST_CHECK_SIZE, |
8659 | 0 | heap, devId); |
8660 | 0 | if (ret == 0) { |
8661 | 0 | if (ConstantCompare(check, outputB, sizeof(outputB_data)) != 0) |
8662 | 0 | ret = DRBG_CONT_FAILURE; |
8663 | 0 | } |
8664 | 0 | } |
8665 | |
|
8666 | | #ifdef WOLFSSL_USE_FLASHMEM |
8667 | | XFREE(seedB, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8668 | | XFREE(outputB, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8669 | | } |
8670 | | #endif |
8671 | 0 | } |
8672 | |
|
8673 | 0 | #ifndef WOLFSSL_SMALL_STACK_CACHE |
8674 | 0 | WC_FREE_VAR_EX(check, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8675 | 0 | WC_FREE_VAR_EX(drbg, heap, DYNAMIC_TYPE_TMP_BUFFER); |
8676 | 0 | #endif |
8677 | 0 | } /* SHA-256 path */ |
8678 | 0 | #endif /* !NO_SHA256 */ |
8679 | | |
8680 | 0 | return ret; |
8681 | 0 | } |
8682 | | #endif /* !CUSTOM_RAND_GENERATE_BLOCK */ |
8683 | | |
8684 | | /* ====================================================================== */ |
8685 | | /* SHA-512 Health Test API */ |
8686 | | /* ====================================================================== */ |
8687 | | #ifdef WOLFSSL_DRBG_SHA512 |
8688 | | |
8689 | | static int wc_RNG_HealthTest_SHA512_ex_internal(DRBG_SHA512_internal* drbg, |
8690 | | int reseed, const byte* nonce, word32 nonceSz, |
8691 | | const byte* perso, word32 persoSz, |
8692 | | const byte* seedA, word32 seedASz, |
8693 | | const byte* seedB, word32 seedBSz, |
8694 | | const byte* additionalA, word32 additionalASz, |
8695 | | const byte* additionalB, word32 additionalBSz, |
8696 | | byte* output, word32 outputSz, |
8697 | | void* heap, int devId) |
8698 | 68.8k | { |
8699 | 68.8k | int ret = WC_NO_ERR_TRACE(DRBG_FAILURE); |
8700 | 68.8k | wc_drbg_reseed_ctr_t reseedCtr; |
8701 | | |
8702 | 68.8k | if (seedA == NULL || output == NULL) { |
8703 | 0 | return BAD_FUNC_ARG; |
8704 | 0 | } |
8705 | | |
8706 | 68.8k | if (reseed != 0 && seedB == NULL) { |
8707 | 0 | return BAD_FUNC_ARG; |
8708 | 0 | } |
8709 | | |
8710 | 68.8k | if (outputSz != RNG_HEALTH_TEST_CHECK_SIZE_SHA512) { |
8711 | 0 | return BAD_FUNC_ARG; |
8712 | 0 | } |
8713 | | |
8714 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
8715 | | (void)heap; |
8716 | | (void)devId; |
8717 | | |
8718 | | if (Hash512_DRBG_Init(drbg, &reseedCtr, seedA, seedASz, nonce, nonceSz, |
8719 | | perso, persoSz) != 0) { |
8720 | | goto exit_rng_ht512; |
8721 | | } |
8722 | | #else |
8723 | 68.8k | if (Hash512_DRBG_Instantiate(drbg, &reseedCtr, seedA, seedASz, nonce, nonceSz, |
8724 | 68.8k | perso, persoSz, heap, devId) != 0) { |
8725 | 452 | goto exit_rng_ht512; |
8726 | 452 | } |
8727 | 68.3k | #endif |
8728 | | |
8729 | 68.3k | if (reseed) { |
8730 | 0 | if (Hash512_DRBG_Reseed(drbg, &reseedCtr, seedB, seedBSz, NULL, 0) != 0) |
8731 | 0 | { |
8732 | 0 | goto exit_rng_ht512; |
8733 | 0 | } |
8734 | 0 | } |
8735 | | |
8736 | | /* First generate: output discarded per NIST DRBGVS procedure */ |
8737 | 68.3k | if (Hash512_DRBG_Generate(drbg, &reseedCtr, output, outputSz, |
8738 | 68.3k | additionalA, additionalASz) != 0) { |
8739 | 115 | goto exit_rng_ht512; |
8740 | 115 | } |
8741 | | |
8742 | | /* Second generate: this is the actual test output */ |
8743 | 68.2k | if (Hash512_DRBG_Generate(drbg, &reseedCtr, output, outputSz, |
8744 | 68.2k | additionalB, additionalBSz) != 0) { |
8745 | 77 | goto exit_rng_ht512; |
8746 | 77 | } |
8747 | | |
8748 | 68.1k | ret = 0; |
8749 | | |
8750 | 68.8k | exit_rng_ht512: |
8751 | | |
8752 | 68.8k | #ifndef WOLFSSL_SMALL_STACK_CACHE |
8753 | 68.8k | { |
8754 | 68.8k | int uninst_ret = Hash512_DRBG_Uninstantiate(drbg); |
8755 | 68.8k | if ((uninst_ret != 0) && (ret == 0)) |
8756 | 0 | ret = uninst_ret; |
8757 | 68.8k | } |
8758 | 68.8k | #endif |
8759 | | |
8760 | 68.8k | return ret; |
8761 | 68.1k | } |
8762 | | |
8763 | | |
8764 | | /* Extended API with personalization string and additional input |
8765 | | * for ACVP testing */ |
8766 | | int wc_RNG_HealthTest_SHA512_ex(int reseed, |
8767 | | const byte* nonce, word32 nonceSz, |
8768 | | const byte* persoString, word32 persoStringSz, |
8769 | | const byte* seedA, word32 seedASz, |
8770 | | const byte* seedB, word32 seedBSz, |
8771 | | const byte* additionalA, word32 additionalASz, |
8772 | | const byte* additionalB, word32 additionalBSz, |
8773 | | byte* output, word32 outputSz, |
8774 | | void* heap, int devId) |
8775 | 0 | { |
8776 | 0 | int ret = WC_NO_ERR_TRACE(WC_FAILURE); |
8777 | 0 | DRBG_SHA512_internal* drbg; |
8778 | 0 | wc_drbg_reseed_ctr_t reseedCtr; |
8779 | | #ifndef WOLFSSL_SMALL_STACK |
8780 | | DRBG_SHA512_internal drbg_var; |
8781 | | #endif |
8782 | |
|
8783 | 0 | if (seedA == NULL || output == NULL) { |
8784 | 0 | return BAD_FUNC_ARG; |
8785 | 0 | } |
8786 | | |
8787 | 0 | if (outputSz != RNG_HEALTH_TEST_CHECK_SIZE_SHA512) { |
8788 | 0 | return BAD_FUNC_ARG; |
8789 | 0 | } |
8790 | | |
8791 | 0 | #ifdef WOLFSSL_SMALL_STACK |
8792 | 0 | drbg = (DRBG_SHA512_internal*)XMALLOC(sizeof(DRBG_SHA512_internal), heap, |
8793 | 0 | DYNAMIC_TYPE_RNG); |
8794 | 0 | if (drbg == NULL) { |
8795 | 0 | return MEMORY_E; |
8796 | 0 | } |
8797 | | #else |
8798 | | drbg = &drbg_var; |
8799 | | #endif |
8800 | | |
8801 | | /* SP 800-90A Sec 10.1.1.2: personalization string is concatenated |
8802 | | * with entropy during instantiation via Hash_df. */ |
8803 | 0 | ret = Hash512_DRBG_Instantiate(drbg, &reseedCtr, seedA, seedASz, nonce, nonceSz, |
8804 | 0 | persoString, persoStringSz, heap, devId); |
8805 | 0 | if (ret != 0) { |
8806 | 0 | goto exit_sha512_ex; |
8807 | 0 | } |
8808 | | |
8809 | 0 | if (reseed) { |
8810 | 0 | if (seedB != NULL && seedBSz > 0) { |
8811 | 0 | ret = Hash512_DRBG_Reseed(drbg, &reseedCtr, seedB, seedBSz, NULL, 0); |
8812 | 0 | if (ret != 0) goto exit_sha512_ex; |
8813 | 0 | } |
8814 | 0 | } |
8815 | | |
8816 | | /* First generate (output discarded per NIST procedure) */ |
8817 | 0 | ret = Hash512_DRBG_Generate(drbg, &reseedCtr, output, outputSz, |
8818 | 0 | additionalA, additionalASz); |
8819 | 0 | if (ret != 0) goto exit_sha512_ex; |
8820 | | |
8821 | | /* Second generate (this is the actual output) */ |
8822 | 0 | ret = Hash512_DRBG_Generate(drbg, &reseedCtr, output, outputSz, |
8823 | 0 | additionalB, additionalBSz); |
8824 | |
|
8825 | 0 | exit_sha512_ex: |
8826 | 0 | { |
8827 | 0 | int uninst_ret = Hash512_DRBG_Uninstantiate(drbg); |
8828 | 0 | if ((ret == 0) && (uninst_ret != 0)) |
8829 | 0 | ret = uninst_ret; |
8830 | 0 | } |
8831 | |
|
8832 | 0 | #ifdef WOLFSSL_SMALL_STACK |
8833 | 0 | XFREE(drbg, heap, DYNAMIC_TYPE_RNG); |
8834 | 0 | #endif |
8835 | |
|
8836 | 0 | return (ret <= 0) ? ret : WC_FAILURE; |
8837 | 0 | } |
8838 | | |
8839 | | |
8840 | | /* Simple API matching wc_RNG_HealthTest() pattern - entropy+nonce only */ |
8841 | | int wc_RNG_HealthTest_SHA512(int reseed, |
8842 | | const byte* seedA, word32 seedASz, |
8843 | | const byte* seedB, word32 seedBSz, |
8844 | | byte* output, word32 outputSz) |
8845 | 0 | { |
8846 | 0 | int ret = WC_NO_ERR_TRACE(WC_FAILURE); |
8847 | 0 | DRBG_SHA512_internal* drbg; |
8848 | | #ifndef WOLFSSL_SMALL_STACK |
8849 | | DRBG_SHA512_internal drbg_var; |
8850 | | #endif |
8851 | |
|
8852 | 0 | #ifdef WOLFSSL_SMALL_STACK |
8853 | 0 | drbg = (DRBG_SHA512_internal*)XMALLOC(sizeof(DRBG_SHA512_internal), NULL, |
8854 | 0 | DYNAMIC_TYPE_RNG); |
8855 | 0 | if (drbg == NULL) { |
8856 | 0 | return MEMORY_E; |
8857 | 0 | } |
8858 | | #else |
8859 | | drbg = &drbg_var; |
8860 | | #endif |
8861 | | |
8862 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
8863 | | ret = Hash512_DRBG_Instantiate(drbg, NULL /* reseedCtr */, |
8864 | | NULL /* seed */, 0, NULL /* nonce */, 0, |
8865 | | NULL, 0, NULL, INVALID_DEVID); |
8866 | | if (ret == 0) |
8867 | | #endif |
8868 | 0 | { |
8869 | 0 | ret = wc_RNG_HealthTest_SHA512_ex_internal( |
8870 | 0 | drbg, reseed, NULL, 0, NULL, 0, |
8871 | 0 | seedA, seedASz, seedB, seedBSz, |
8872 | 0 | NULL, 0, NULL, 0, |
8873 | 0 | output, outputSz, NULL, INVALID_DEVID); |
8874 | | #ifdef WOLFSSL_SMALL_STACK_CACHE |
8875 | | { |
8876 | | int uninst_ret = Hash512_DRBG_Uninstantiate(drbg); |
8877 | | if ((ret == 0) && (uninst_ret != 0)) |
8878 | | ret = uninst_ret; |
8879 | | } |
8880 | | #endif |
8881 | 0 | } |
8882 | 0 | WC_FREE_VAR_EX(drbg, NULL, DYNAMIC_TYPE_RNG); |
8883 | |
|
8884 | 0 | if (ret > 0) { |
8885 | | /* Translate protocol-domain codes at the public boundary; negative |
8886 | | * codes (MEMORY_E, BAD_FUNC_ARG) pass verbatim. */ |
8887 | 0 | ret = WC_FAILURE; |
8888 | 0 | } |
8889 | 0 | return ret; |
8890 | 0 | } |
8891 | | |
8892 | | #endif /* WOLFSSL_DRBG_SHA512 */ |
8893 | | |
8894 | | #if !defined(NO_SHA256) && !defined(HAVE_SELFTEST) && \ |
8895 | | (!defined(HAVE_FIPS) || FIPS_VERSION3_GE(7,0,0)) |
8896 | | /* Extended SHA-256 Hash_DRBG health test per SP 800-90A. |
8897 | | * Supports flexible output sizes, prediction resistance, personalization |
8898 | | * strings, and additional input. |
8899 | | * |
8900 | | * predResistance=0: Instantiate(entropyA, nonce, perso) -> |
8901 | | * Reseed(entropyB, additionalReseed) -> |
8902 | | * Gen1(additionalA, discard) -> Gen2(additionalB, keep) |
8903 | | * predResistance=1: Instantiate(entropyA, nonce, perso) -> |
8904 | | * Reseed(entropyB, additionalA)+Gen1(NULL, discard) -> |
8905 | | * Reseed(entropyC, additionalB)+Gen2(NULL, keep) |
8906 | | */ |
8907 | | int wc_RNG_HealthTest_SHA256_ex( |
8908 | | int predResistance, |
8909 | | const byte* nonce, word32 nonceSz, |
8910 | | const byte* persoString, word32 persoStringSz, |
8911 | | const byte* entropyA, word32 entropyASz, |
8912 | | const byte* entropyB, word32 entropyBSz, |
8913 | | const byte* entropyC, word32 entropyCsz, |
8914 | | const byte* additionalA, word32 additionalASz, |
8915 | | const byte* additionalB, word32 additionalBSz, |
8916 | | const byte* additionalReseed, word32 additionalReseedSz, |
8917 | | byte* output, word32 outputSz, |
8918 | | void* heap, int devId) |
8919 | 0 | { |
8920 | 0 | int ret; |
8921 | 0 | DRBG_internal* drbg; |
8922 | 0 | wc_drbg_reseed_ctr_t reseedCtr; |
8923 | | #ifndef WOLFSSL_SMALL_STACK |
8924 | | DRBG_internal drbg_var; |
8925 | | #endif |
8926 | |
|
8927 | 0 | if (entropyA == NULL || output == NULL || outputSz == 0) { |
8928 | 0 | return BAD_FUNC_ARG; |
8929 | 0 | } |
8930 | | |
8931 | 0 | #ifdef WOLFSSL_SMALL_STACK |
8932 | 0 | drbg = (DRBG_internal*)XMALLOC(sizeof(DRBG_internal), heap, |
8933 | 0 | DYNAMIC_TYPE_RNG); |
8934 | 0 | if (drbg == NULL) { |
8935 | 0 | return MEMORY_E; |
8936 | 0 | } |
8937 | | #else |
8938 | | drbg = &drbg_var; |
8939 | | #endif |
8940 | | |
8941 | | /* Instantiate with entropy, nonce, personalization string */ |
8942 | 0 | ret = Hash_DRBG_Instantiate(drbg, &reseedCtr, entropyA, entropyASz, nonce, nonceSz, |
8943 | 0 | persoString, persoStringSz, heap, devId); |
8944 | 0 | if (ret != 0) goto exit_sha256_ex; |
8945 | | |
8946 | 0 | if (predResistance) { |
8947 | | /* Prediction resistance mode per SP 800-90A 9.3.1: |
8948 | | * additional_input is passed to Reseed, Generate gets NULL */ |
8949 | | |
8950 | | /* Reseed 1 with additionalA, then Generate 1 with NULL (discard) */ |
8951 | 0 | if (entropyB != NULL && entropyBSz > 0) { |
8952 | 0 | ret = Hash256_DRBG_Reseed(drbg, &reseedCtr, entropyB, entropyBSz, |
8953 | 0 | additionalA, additionalASz); |
8954 | 0 | if (ret != 0) goto exit_sha256_ex; |
8955 | 0 | } |
8956 | 0 | ret = Hash_DRBG_Generate(drbg, &reseedCtr, output, outputSz, NULL, 0); |
8957 | 0 | if (ret != 0) goto exit_sha256_ex; |
8958 | | |
8959 | | /* Reseed 2 with additionalB, then Generate 2 with NULL (keep) */ |
8960 | 0 | if (entropyC != NULL && entropyCsz > 0) { |
8961 | 0 | ret = Hash256_DRBG_Reseed(drbg, &reseedCtr, entropyC, entropyCsz, |
8962 | 0 | additionalB, additionalBSz); |
8963 | 0 | if (ret != 0) goto exit_sha256_ex; |
8964 | 0 | } |
8965 | 0 | ret = Hash_DRBG_Generate(drbg, &reseedCtr, output, outputSz, NULL, 0); |
8966 | 0 | } |
8967 | 0 | else { |
8968 | | /* Standard mode: explicit reseed, then two generates */ |
8969 | 0 | if (entropyB != NULL && entropyBSz > 0) { |
8970 | 0 | ret = Hash256_DRBG_Reseed(drbg, &reseedCtr, entropyB, entropyBSz, |
8971 | 0 | additionalReseed, additionalReseedSz); |
8972 | 0 | if (ret != 0) goto exit_sha256_ex; |
8973 | 0 | } |
8974 | | |
8975 | | /* Generate 1 (output discarded per NIST DRBGVS procedure) */ |
8976 | 0 | ret = Hash_DRBG_Generate(drbg, &reseedCtr, output, outputSz, |
8977 | 0 | additionalA, additionalASz); |
8978 | 0 | if (ret != 0) goto exit_sha256_ex; |
8979 | | |
8980 | | /* Generate 2 (this is the actual test output) */ |
8981 | 0 | ret = Hash_DRBG_Generate(drbg, &reseedCtr, output, outputSz, |
8982 | 0 | additionalB, additionalBSz); |
8983 | 0 | } |
8984 | | |
8985 | 0 | exit_sha256_ex: |
8986 | 0 | { |
8987 | 0 | int uninst_ret = Hash_DRBG_Uninstantiate(drbg); |
8988 | 0 | if ((uninst_ret != 0) && (ret == 0)) |
8989 | 0 | ret = uninst_ret; |
8990 | 0 | } |
8991 | |
|
8992 | 0 | #ifdef WOLFSSL_SMALL_STACK |
8993 | 0 | XFREE(drbg, heap, DYNAMIC_TYPE_RNG); |
8994 | 0 | #endif |
8995 | |
|
8996 | 0 | return ret <= 0 ? ret : WC_FAILURE; |
8997 | 0 | } |
8998 | | #endif /* !NO_SHA256 && !HAVE_SELFTEST && (!HAVE_FIPS || FIPS v7+) */ |
8999 | | |
9000 | | |
9001 | | #ifdef WOLFSSL_DRBG_SHA512 |
9002 | | /* Extended SHA-512 Hash_DRBG health test per SP 800-90A. |
9003 | | * Supports flexible output sizes and prediction resistance mode. |
9004 | | * |
9005 | | * Per SP 800-90A Section 9.3.1, when prediction resistance is requested, |
9006 | | * the additional_input is consumed by the Reseed step and the subsequent |
9007 | | * Generate uses NULL additional_input. |
9008 | | * |
9009 | | * predResistance=0: Instantiate -> |
9010 | | * Reseed(entropyB, additionalReseed) -> |
9011 | | * Gen1(additionalA, discard) -> Gen2(additionalB, keep) |
9012 | | * predResistance=1: Instantiate -> |
9013 | | * Reseed(entropyB, additionalA)+Gen1(NULL, discard) -> |
9014 | | * Reseed(entropyC, additionalB)+Gen2(NULL, keep) |
9015 | | */ |
9016 | | int wc_RNG_HealthTest_SHA512_ex2( |
9017 | | int predResistance, |
9018 | | const byte* nonce, word32 nonceSz, |
9019 | | const byte* persoString, word32 persoStringSz, |
9020 | | const byte* entropyA, word32 entropyASz, |
9021 | | const byte* entropyB, word32 entropyBSz, |
9022 | | const byte* entropyC, word32 entropyCsz, |
9023 | | const byte* additionalA, word32 additionalASz, |
9024 | | const byte* additionalB, word32 additionalBSz, |
9025 | | const byte* additionalReseed, word32 additionalReseedSz, |
9026 | | byte* output, word32 outputSz, |
9027 | | void* heap, int devId) |
9028 | 0 | { |
9029 | 0 | int ret; |
9030 | 0 | DRBG_SHA512_internal* drbg; |
9031 | 0 | wc_drbg_reseed_ctr_t reseedCtr; |
9032 | | #ifndef WOLFSSL_SMALL_STACK |
9033 | | DRBG_SHA512_internal drbg_var; |
9034 | | #endif |
9035 | |
|
9036 | 0 | if (entropyA == NULL || output == NULL || outputSz == 0) { |
9037 | 0 | return BAD_FUNC_ARG; |
9038 | 0 | } |
9039 | | |
9040 | 0 | #ifdef WOLFSSL_SMALL_STACK |
9041 | 0 | drbg = (DRBG_SHA512_internal*)XMALLOC(sizeof(DRBG_SHA512_internal), heap, |
9042 | 0 | DYNAMIC_TYPE_RNG); |
9043 | 0 | if (drbg == NULL) { |
9044 | 0 | return MEMORY_E; |
9045 | 0 | } |
9046 | | #else |
9047 | | drbg = &drbg_var; |
9048 | | #endif |
9049 | | |
9050 | | /* Instantiate with entropy, nonce, personalization string */ |
9051 | 0 | ret = Hash512_DRBG_Instantiate(drbg, &reseedCtr, entropyA, entropyASz, |
9052 | 0 | nonce, nonceSz, |
9053 | 0 | persoString, persoStringSz, |
9054 | 0 | heap, devId); |
9055 | 0 | if (ret != 0) goto exit_sha512_ex2; |
9056 | | |
9057 | 0 | if (predResistance) { |
9058 | | /* Prediction resistance mode per SP 800-90A 9.3.1: |
9059 | | * additional_input is passed to Reseed, Generate gets NULL */ |
9060 | | |
9061 | | /* Reseed 1 with additionalA, then Generate 1 with NULL (discard) */ |
9062 | 0 | if (entropyB != NULL && entropyBSz > 0) { |
9063 | 0 | ret = Hash512_DRBG_Reseed(drbg, &reseedCtr, entropyB, entropyBSz, |
9064 | 0 | additionalA, additionalASz); |
9065 | 0 | if (ret != 0) goto exit_sha512_ex2; |
9066 | 0 | } |
9067 | 0 | ret = Hash512_DRBG_Generate(drbg, &reseedCtr, output, outputSz, NULL, 0); |
9068 | 0 | if (ret != 0) goto exit_sha512_ex2; |
9069 | | |
9070 | | /* Reseed 2 with additionalB, then Generate 2 with NULL (keep) */ |
9071 | 0 | if (entropyC != NULL && entropyCsz > 0) { |
9072 | 0 | ret = Hash512_DRBG_Reseed(drbg, &reseedCtr, entropyC, entropyCsz, |
9073 | 0 | additionalB, additionalBSz); |
9074 | 0 | if (ret != 0) goto exit_sha512_ex2; |
9075 | 0 | } |
9076 | 0 | ret = Hash512_DRBG_Generate(drbg, &reseedCtr, output, outputSz, NULL, 0); |
9077 | 0 | } |
9078 | 0 | else { |
9079 | | /* Standard mode: explicit reseed, then two generates */ |
9080 | 0 | if (entropyB != NULL && entropyBSz > 0) { |
9081 | 0 | ret = Hash512_DRBG_Reseed(drbg, &reseedCtr, entropyB, entropyBSz, |
9082 | 0 | additionalReseed, additionalReseedSz); |
9083 | 0 | if (ret != 0) goto exit_sha512_ex2; |
9084 | 0 | } |
9085 | | |
9086 | | /* Generate 1 (output discarded per NIST DRBGVS procedure) */ |
9087 | 0 | ret = Hash512_DRBG_Generate(drbg, &reseedCtr, output, outputSz, |
9088 | 0 | additionalA, additionalASz); |
9089 | 0 | if (ret != 0) goto exit_sha512_ex2; |
9090 | | |
9091 | | /* Generate 2 (this is the actual test output) */ |
9092 | 0 | ret = Hash512_DRBG_Generate(drbg, &reseedCtr, output, outputSz, |
9093 | 0 | additionalB, additionalBSz); |
9094 | 0 | } |
9095 | | |
9096 | 0 | exit_sha512_ex2: |
9097 | 0 | { |
9098 | 0 | int uninst_ret = Hash512_DRBG_Uninstantiate(drbg); |
9099 | 0 | if ((ret == 0) && (uninst_ret != 0)) |
9100 | 0 | ret = uninst_ret; |
9101 | 0 | } |
9102 | |
|
9103 | 0 | #ifdef WOLFSSL_SMALL_STACK |
9104 | 0 | XFREE(drbg, heap, DYNAMIC_TYPE_RNG); |
9105 | 0 | #endif |
9106 | |
|
9107 | 0 | return (ret <= 0) ? ret : WC_FAILURE; |
9108 | 0 | } |
9109 | | |
9110 | | #endif /* WOLFSSL_DRBG_SHA512 */ |
9111 | | |
9112 | | #endif /* HAVE_HASHDRBG */ |
9113 | | |
9114 | | |
9115 | | #if defined(HAVE_INTEL_RDRAND) || defined(HAVE_INTEL_RDSEED) || \ |
9116 | | defined(HAVE_AMD_RDSEED) |
9117 | | |
9118 | | #ifdef WOLFSSL_ASYNC_CRYPT |
9119 | | /* need more retries if multiple cores */ |
9120 | | #define INTELRD_RETRY (32 * 8) |
9121 | | #else |
9122 | | #define INTELRD_RETRY 32 |
9123 | | #endif |
9124 | | |
9125 | | #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED) |
9126 | | |
9127 | | #ifndef USE_INTEL_INTRINSICS |
9128 | | |
9129 | | /* return 0 on success */ |
9130 | | static WC_INLINE int IntelRDseed64(word64* seed) |
9131 | | { |
9132 | | unsigned char ok; |
9133 | | |
9134 | | __asm__ volatile("rdseed %0; setc %1":"=r"(*seed), "=qm"(ok)); |
9135 | | return (ok) ? 0 : -1; |
9136 | | } |
9137 | | |
9138 | | #else /* USE_INTEL_INTRINSICS */ |
9139 | | /* The compiler Visual Studio uses does not allow inline assembly. |
9140 | | * It does allow for Intel intrinsic functions. */ |
9141 | | |
9142 | | /* return 0 on success */ |
9143 | | # ifdef __GNUC__ |
9144 | | __attribute__((target("rdseed"))) |
9145 | | # endif |
9146 | | static WC_INLINE int IntelRDseed64(word64* seed) |
9147 | | { |
9148 | | int ok; |
9149 | | |
9150 | | ok = _rdseed64_step((unsigned long long*) seed); |
9151 | | return (ok) ? 0 : -1; |
9152 | | } |
9153 | | |
9154 | | #endif /* USE_INTEL_INTRINSICS */ |
9155 | | |
9156 | | /* return 0 on success */ |
9157 | | static WC_INLINE int IntelRDseed64_r(word64* rnd) |
9158 | | { |
9159 | | int i; |
9160 | | for (i = 0; i < INTELRD_RETRY; i++) { |
9161 | | if (IntelRDseed64(rnd) == 0) |
9162 | | return 0; |
9163 | | } |
9164 | | return NOT_READY_E; |
9165 | | } |
9166 | | |
9167 | | /* return 0 on success */ |
9168 | | static WC_MAYBE_UNUSED int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, |
9169 | | word32 sz) |
9170 | | { |
9171 | | int ret = 0; |
9172 | | word64 rndTmp; |
9173 | | static int rdseed_sanity_status = 0; |
9174 | | word64 rndTmpLocal = 0; |
9175 | | |
9176 | | (void)os; |
9177 | | |
9178 | | if (!IS_INTEL_RDSEED(intel_flags)) |
9179 | | return WC_HW_E; |
9180 | | |
9181 | | /* Note, access to rdseed_sanity_status is benignly racey on multithreaded |
9182 | | * targets. |
9183 | | */ |
9184 | | if (rdseed_sanity_status == 0) { |
9185 | | word64 sanity_word1 = 0, sanity_word2 = 0; |
9186 | | |
9187 | | ret = IntelRDseed64_r(&sanity_word1); |
9188 | | if (ret == 0) |
9189 | | ret = IntelRDseed64_r(&sanity_word2); |
9190 | | if ((ret == 0) && (sanity_word1 == sanity_word2)) { |
9191 | | ret = IntelRDseed64_r(&sanity_word1); |
9192 | | if ((ret == 0) && (sanity_word1 == sanity_word2)) { |
9193 | | #ifdef WC_VERBOSE_RNG |
9194 | | WOLFSSL_DEBUG_PRINTF( |
9195 | | "WARNING: disabling RDSEED due to repeating word 0x%lx -- " |
9196 | | "check CPU microcode version.", sanity_word2); |
9197 | | #endif |
9198 | | rdseed_sanity_status = -1; |
9199 | | ret = WC_HW_E; |
9200 | | } |
9201 | | } |
9202 | | /* Raw source output, used only for the self-check. */ |
9203 | | ForceZero(&sanity_word1, sizeof(sanity_word1)); |
9204 | | ForceZero(&sanity_word2, sizeof(sanity_word2)); |
9205 | | if (ret != 0) |
9206 | | return ret; |
9207 | | |
9208 | | rdseed_sanity_status = 1; |
9209 | | } |
9210 | | else if (rdseed_sanity_status < 0) { |
9211 | | return WC_HW_E; |
9212 | | } |
9213 | | |
9214 | | for (; (sz / sizeof(word64)) > 0; sz -= sizeof(word64), |
9215 | | output += sizeof(word64)) { |
9216 | | ret = IntelRDseed64_r(&rndTmpLocal); |
9217 | | if (ret != 0) { |
9218 | | break; |
9219 | | } |
9220 | | writeUnalignedWord64(output, rndTmpLocal); |
9221 | | } |
9222 | | |
9223 | | ForceZero(&rndTmpLocal, sizeof(rndTmpLocal)); |
9224 | | if (ret != 0) { |
9225 | | return ret; |
9226 | | } |
9227 | | |
9228 | | if (sz == 0) |
9229 | | return 0; |
9230 | | |
9231 | | /* handle unaligned remainder */ |
9232 | | ret = IntelRDseed64_r(&rndTmp); |
9233 | | if (ret != 0) |
9234 | | return ret; |
9235 | | |
9236 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
9237 | | wc_MemZero_Add("wc_GenerateSeed rndTmp", &rndTmp, sizeof(rndTmp)); |
9238 | | #endif |
9239 | | XMEMCPY(output, &rndTmp, sz); |
9240 | | ForceZero(&rndTmp, sizeof(rndTmp)); |
9241 | | #ifdef WOLFSSL_CHECK_MEM_ZERO |
9242 | | wc_MemZero_Check(&rndTmp, sizeof(rndTmp)); |
9243 | | #endif |
9244 | | |
9245 | | return 0; |
9246 | | } |
9247 | | |
9248 | | #endif /* HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */ |
9249 | | |
9250 | | #ifdef HAVE_INTEL_RDRAND |
9251 | | |
9252 | | #ifndef USE_INTEL_INTRINSICS |
9253 | | |
9254 | | /* return 0 on success */ |
9255 | | static WC_INLINE int IntelRDrand64(word64 *rnd) |
9256 | | { |
9257 | | unsigned char ok; |
9258 | | |
9259 | | __asm__ volatile("rdrand %0; setc %1":"=r"(*rnd), "=qm"(ok)); |
9260 | | |
9261 | | return (ok) ? 0 : -1; |
9262 | | } |
9263 | | |
9264 | | #else /* USE_INTEL_INTRINSICS */ |
9265 | | /* The compiler Visual Studio uses does not allow inline assembly. |
9266 | | * It does allow for Intel intrinsic functions. */ |
9267 | | |
9268 | | /* return 0 on success */ |
9269 | | # ifdef __GNUC__ |
9270 | | __attribute__((target("rdrnd"))) |
9271 | | # endif |
9272 | | static WC_INLINE int IntelRDrand64(word64 *rnd) |
9273 | | { |
9274 | | int ok; |
9275 | | |
9276 | | ok = _rdrand64_step((unsigned long long*) rnd); |
9277 | | |
9278 | | return (ok) ? 0 : -1; |
9279 | | } |
9280 | | |
9281 | | #endif /* USE_INTEL_INTRINSICS */ |
9282 | | |
9283 | | /* return 0 on success */ |
9284 | | static WC_INLINE int IntelRDrand64_r(word64 *rnd) |
9285 | | { |
9286 | | int i; |
9287 | | for (i = 0; i < INTELRD_RETRY; i++) { |
9288 | | if (IntelRDrand64(rnd) == 0) |
9289 | | return 0; |
9290 | | } |
9291 | | return -1; |
9292 | | } |
9293 | | |
9294 | | /* return 0 on success */ |
9295 | | static int wc_GenerateRand_IntelRD(OS_Seed* os, byte* output, word32 sz) |
9296 | | { |
9297 | | word64 rndTmp; |
9298 | | int ret = 0; |
9299 | | word64 rndTmpLocal = 0; |
9300 | | |
9301 | | (void)os; |
9302 | | |
9303 | | if (!IS_INTEL_RDRAND(intel_flags)) |
9304 | | return -1; |
9305 | | |
9306 | | for (; (sz / sizeof(word64)) > 0; sz -= sizeof(word64), |
9307 | | output += sizeof(word64)) { |
9308 | | ret = IntelRDrand64_r(&rndTmpLocal); |
9309 | | if (ret != 0) { |
9310 | | break; |
9311 | | } |
9312 | | writeUnalignedWord64(output, rndTmpLocal); |
9313 | | } |
9314 | | |
9315 | | ForceZero(&rndTmpLocal, sizeof(rndTmpLocal)); |
9316 | | if (ret != 0) { |
9317 | | return ret; |
9318 | | } |
9319 | | |
9320 | | if (sz == 0) |
9321 | | return 0; |
9322 | | |
9323 | | /* handle unaligned remainder */ |
9324 | | ret = IntelRDrand64_r(&rndTmp); |
9325 | | if (ret != 0) |
9326 | | return ret; |
9327 | | |
9328 | | XMEMCPY(output, &rndTmp, sz); |
9329 | | ForceZero(&rndTmp, sizeof(rndTmp)); |
9330 | | |
9331 | | return 0; |
9332 | | } |
9333 | | |
9334 | | #endif /* HAVE_INTEL_RDRAND */ |
9335 | | #endif /* HAVE_INTEL_RDRAND || HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */ |
9336 | | |
9337 | | |
9338 | | #ifdef WOLFSSL_NOISE_SRC |
9339 | | |
9340 | | /* Generic SP800-90B noise source. Configuration struct and API: |
9341 | | * wolfssl/wolfcrypt/random.h. |
9342 | | * |
9343 | | * Entropy model. A port supplies raw, unconditioned octets through one |
9344 | | * callback. Each raw bit is credited hmin/100 bits of min-entropy, so a |
9345 | | * full-entropy output octet needs 8 / (hmin/100) raw bits, and margin |
9346 | | * oversamples on top of that; WC_NOISE_RAW_PER_SRC() turns the two into the |
9347 | | * raw octets gathered per conditioner chunk. Only source 0 is budgeted - any |
9348 | | * further source is hashed in as defence in depth, and extra hash input can |
9349 | | * never subtract entropy. |
9350 | | * |
9351 | | * Every gathered octet passes the 4.4.1 Repetition Count Test and the 4.4.2 |
9352 | | * Adaptive Proportion Test before reaching the conditioner, and _Init() runs |
9353 | | * the 4.3 startup test over startupOctets per source first. A failure is |
9354 | | * latched: 4.3/4.4 want a persistent failure state, not a transparent retry, |
9355 | | * because a source that trips and then passes is exactly what continuous |
9356 | | * testing exists to catch. Only _Free() clears it. |
9357 | | * |
9358 | | * Only test verdicts latch - the health tests and the _SelfTest() liveness |
9359 | | * checks. An error from the sample callback propagates unlatched and stays |
9360 | | * retryable: it says the hardware did not answer, not that the noise is bad. |
9361 | | * Either way no output is produced. |
9362 | | * |
9363 | | * Latching is also limited to the credited source. Source 0 carries the whole |
9364 | | * budget, so its failure fails closed. Sources 1.. are unaccounted extra hash |
9365 | | * input, and the cutoffs are derived for source 0's assumed min-entropy rather |
9366 | | * than theirs, so one of them tripping is not evidence the seed is weak - it is |
9367 | | * dropped for the life of the instance (recorded in src->degraded) and stops |
9368 | | * contributing. Output stays fully seeded because the budget never counted |
9369 | | * it, and a source the budget ignores cannot deny service. |
9370 | | * |
9371 | | * Cutoffs belong to the caller and must match the assumed hmin, or they either |
9372 | | * never trip or trip constantly. For H bits of min-entropy per octet at |
9373 | | * alpha = 2^-30: RCT C = 1 + ceil(30/H), APT C = 1 + CRITBINOM(W, 2^-H, |
9374 | | * 1-alpha). |
9375 | | * |
9376 | | * No locking. The instance is caller-owned state, so a port sharing one |
9377 | | * across threads provides its own mutual exclusion. */ |
9378 | | |
9379 | | #ifdef NO_SHA256 |
9380 | | #error "WOLFSSL_NOISE_SRC conditions with SHA-256; do not set NO_SHA256" |
9381 | | #endif |
9382 | | #if WC_NOISE_CHUNK_SZ != WC_SHA256_DIGEST_SIZE |
9383 | | #error "WC_NOISE_CHUNK_SZ must match WC_SHA256_DIGEST_SIZE" |
9384 | | #endif |
9385 | | |
9386 | | /* len raw octets from one source. No health testing - callers that keep the |
9387 | | * data run NoiseSrc_HealthTest() over it. */ |
9388 | | static int NoiseSrc_Gather(wc_NoiseSrc* src, byte* out, word32 len, int srcIdx) |
9389 | | { |
9390 | | word32 i; |
9391 | | int ret; |
9392 | | |
9393 | | for (i = 0; i < len; i++) { |
9394 | | ret = src->sampleCb(src->ctx, srcIdx, &out[i]); |
9395 | | if (ret != 0) { |
9396 | | return ret; |
9397 | | } |
9398 | | /* The contract is raw octets, but where CHAR_BIT != 8 a callback can |
9399 | | * legally leave bits above 0xFF in the cell. Mask here so the |
9400 | | * conditioner sees exactly what the health tests scored - they mask |
9401 | | * already - and no high bits leak into the hash. */ |
9402 | | out[i] = WC_OCTET(out[i]); |
9403 | | } |
9404 | | |
9405 | | return 0; |
9406 | | } |
9407 | | |
9408 | | /* SP800-90B 4.4.1 RCT and 4.4.2 APT over every octet drawn from a source. |
9409 | | * Returns at the offending sample so the rest of the buffer cannot scrub the |
9410 | | * state that detected it, and latches the failure. */ |
9411 | | static int NoiseSrc_HealthTest(wc_NoiseSrc* src, const byte* buf, word32 len, |
9412 | | int srcIdx) |
9413 | | { |
9414 | | wc_NoiseHealth* st; |
9415 | | word32 i; |
9416 | | word16 s; |
9417 | | |
9418 | | if (srcIdx < 0 || srcIdx >= (int)src->numSrc) { |
9419 | | return BAD_FUNC_ARG; |
9420 | | } |
9421 | | st = &src->health[srcIdx]; |
9422 | | |
9423 | | for (i = 0; i < len; i++) { |
9424 | | s = (word16)WC_OCTET(buf[i]); |
9425 | | |
9426 | | if (!st->started) { |
9427 | | st->started = 1; |
9428 | | st->rctLast = s; |
9429 | | st->rctCount = 1; |
9430 | | st->aptRef = s; |
9431 | | st->aptCount = 1; |
9432 | | st->aptPos = 1; |
9433 | | continue; |
9434 | | } |
9435 | | |
9436 | | if (s == st->rctLast) { |
9437 | | st->rctCount++; |
9438 | | if (st->rctCount >= src->rctCutoff) { |
9439 | | if (srcIdx == 0) { |
9440 | | src->failed = ENTROPY_RT_E; |
9441 | | } |
9442 | | return ENTROPY_RT_E; |
9443 | | } |
9444 | | } |
9445 | | else { |
9446 | | st->rctLast = s; |
9447 | | st->rctCount = 1; |
9448 | | } |
9449 | | |
9450 | | if (st->aptPos >= src->aptWindow) { |
9451 | | st->aptRef = s; |
9452 | | st->aptCount = 1; |
9453 | | st->aptPos = 1; |
9454 | | } |
9455 | | else { |
9456 | | if (s == st->aptRef) { |
9457 | | st->aptCount++; |
9458 | | if (st->aptCount >= src->aptCutoff) { |
9459 | | if (srcIdx == 0) { |
9460 | | src->failed = ENTROPY_APT_E; |
9461 | | } |
9462 | | return ENTROPY_APT_E; |
9463 | | } |
9464 | | } |
9465 | | st->aptPos++; |
9466 | | } |
9467 | | } |
9468 | | |
9469 | | return 0; |
9470 | | } |
9471 | | |
9472 | | int wc_NoiseSrc_Init(wc_NoiseSrc* src) |
9473 | | { |
9474 | | word32 done; |
9475 | | word32 take; |
9476 | | word32 need; |
9477 | | int i; |
9478 | | int ret; |
9479 | | |
9480 | | if (src == NULL) { |
9481 | | return BAD_FUNC_ARG; |
9482 | | } |
9483 | | if (src->failed != 0) { |
9484 | | return src->failed; |
9485 | | } |
9486 | | if (src->inited) { |
9487 | | return 0; |
9488 | | } |
9489 | | |
9490 | | if (src->sampleCb == NULL || src->tag == NULL || src->work == NULL) { |
9491 | | return BAD_FUNC_ARG; |
9492 | | } |
9493 | | if (src->numSrc < 1 || src->numSrc > WC_NOISE_SRC_MAX) { |
9494 | | return BAD_FUNC_ARG; |
9495 | | } |
9496 | | if (src->hmin < 1 || src->hmin > 100 || src->margin < 1) { |
9497 | | return BAD_FUNC_ARG; |
9498 | | } |
9499 | | if (src->rctCutoff < 2 || src->aptCutoff < 2 || src->aptWindow < 2) { |
9500 | | return BAD_FUNC_ARG; |
9501 | | } |
9502 | | /* Below one APT window the startup pass never exercises that test. */ |
9503 | | if (src->startupOctets < (word32)src->aptWindow) { |
9504 | | return BAD_FUNC_ARG; |
9505 | | } |
9506 | | |
9507 | | src->rawPerSrc = WC_NOISE_RAW_PER_SRC(src->hmin, src->margin); |
9508 | | need = src->rawPerSrc * (word32)src->numSrc; |
9509 | | if (src->rawPerSrc == 0 || src->workSz < need) { |
9510 | | return BUFFER_E; |
9511 | | } |
9512 | | |
9513 | | XMEMSET(src->health, 0, sizeof(src->health)); |
9514 | | src->chunkCtr = 0; |
9515 | | src->degraded = 0; |
9516 | | |
9517 | | /* SP800-90B 4.3: push startupOctets per source through the continuous |
9518 | | * tests - more than one APT window - before releasing anything. */ |
9519 | | for (i = 0; i < (int)src->numSrc; i++) { |
9520 | | for (done = 0; done < src->startupOctets; done += take) { |
9521 | | take = src->startupOctets - done; |
9522 | | if (take > src->rawPerSrc) { |
9523 | | take = src->rawPerSrc; |
9524 | | } |
9525 | | /* Sampler errors and test verdicts are handled differently, so |
9526 | | * keep them apart: a callback error means the hardware did not |
9527 | | * answer and stays retryable for every source, while only a test |
9528 | | * verdict drops or latches. */ |
9529 | | ret = NoiseSrc_Gather(src, src->work, take, i); |
9530 | | if (ret != 0) { |
9531 | | ForceZero(src->work, src->workSz); |
9532 | | return ret; |
9533 | | } |
9534 | | ret = NoiseSrc_HealthTest(src, src->work, take, i); |
9535 | | if (ret != 0) { |
9536 | | if (i == 0) { |
9537 | | ForceZero(src->work, src->workSz); |
9538 | | return ret; /* credited source: fail closed */ |
9539 | | } |
9540 | | /* Uncredited: drop it and keep going - see the latch policy |
9541 | | * note at the top of this module. */ |
9542 | | src->degraded |= (word16)(1U << i); |
9543 | | ret = 0; |
9544 | | break; |
9545 | | } |
9546 | | } |
9547 | | } |
9548 | | |
9549 | | ForceZero(src->work, src->workSz); |
9550 | | src->inited = 1; |
9551 | | return 0; |
9552 | | } |
9553 | | |
9554 | | void wc_NoiseSrc_Free(wc_NoiseSrc* src) |
9555 | | { |
9556 | | if (src == NULL) { |
9557 | | return; |
9558 | | } |
9559 | | |
9560 | | if (src->work != NULL && src->workSz > 0) { |
9561 | | ForceZero(src->work, src->workSz); |
9562 | | } |
9563 | | ForceZero(src->health, sizeof(src->health)); |
9564 | | src->chunkCtr = 0; |
9565 | | src->failed = 0; |
9566 | | src->degraded = 0; |
9567 | | src->inited = 0; |
9568 | | } |
9569 | | |
9570 | | int wc_NoiseSrc_GetRaw(wc_NoiseSrc* src, byte* output, word32 len, int srcIdx) |
9571 | | { |
9572 | | int ret; |
9573 | | |
9574 | | if (src == NULL || output == NULL) { |
9575 | | return BAD_FUNC_ARG; |
9576 | | } |
9577 | | /* Before _Init(): numSrc is caller configuration, so a bad index need not |
9578 | | * pay for the startup test or burn hardware entropy first. */ |
9579 | | if (srcIdx < 0 || srcIdx >= (int)src->numSrc) { |
9580 | | return BAD_FUNC_ARG; |
9581 | | } |
9582 | | if (src->failed != 0) { |
9583 | | return src->failed; |
9584 | | } |
9585 | | |
9586 | | ret = wc_NoiseSrc_Init(src); |
9587 | | if (ret != 0) { |
9588 | | return ret; |
9589 | | } |
9590 | | |
9591 | | ret = NoiseSrc_Gather(src, output, len, srcIdx); |
9592 | | if (ret != 0) { |
9593 | | ForceZero(output, len); |
9594 | | } |
9595 | | return ret; |
9596 | | } |
9597 | | |
9598 | | int wc_NoiseSrc_GenerateSeed(wc_NoiseSrc* src, byte* output, word32 sz) |
9599 | | { |
9600 | | #ifdef WOLFSSL_SMALL_STACK |
9601 | | wc_Sha256* sha = NULL; |
9602 | | #else |
9603 | | wc_Sha256 sha[1]; |
9604 | | #endif |
9605 | | byte digest[WC_NOISE_CHUNK_SZ]; |
9606 | | byte ctrBuf[4]; |
9607 | | byte* raw; |
9608 | | byte* outStart; |
9609 | | word32 outLen; |
9610 | | word32 take; |
9611 | | word16 contributed; |
9612 | | int i; |
9613 | | int ret; |
9614 | | |
9615 | | if (src == NULL || output == NULL) { |
9616 | | return BAD_FUNC_ARG; |
9617 | | } |
9618 | | if (sz == 0) { |
9619 | | return 0; |
9620 | | } |
9621 | | if (src->failed != 0) { |
9622 | | return src->failed; |
9623 | | } |
9624 | | |
9625 | | /* Kept so a mid-way failure can wipe what already landed: no caller |
9626 | | * should ever see a partially-filled seed buffer. */ |
9627 | | outStart = output; |
9628 | | outLen = sz; |
9629 | | |
9630 | | XMEMSET(digest, 0, sizeof(digest)); |
9631 | | |
9632 | | ret = wc_NoiseSrc_Init(src); |
9633 | | if (ret != 0) { |
9634 | | return ret; |
9635 | | } |
9636 | | |
9637 | | #ifdef WOLFSSL_SMALL_STACK |
9638 | | sha = (wc_Sha256*)XMALLOC(sizeof(wc_Sha256), NULL, DYNAMIC_TYPE_TMP_BUFFER); |
9639 | | if (sha == NULL) { |
9640 | | return MEMORY_E; |
9641 | | } |
9642 | | #endif |
9643 | | |
9644 | | while (sz > 0) { |
9645 | | contributed = 0; |
9646 | | for (i = 0; i < (int)src->numSrc; i++) { |
9647 | | if ((src->degraded & (word16)(1U << i)) != 0) { |
9648 | | continue; /* uncredited source already dropped */ |
9649 | | } |
9650 | | raw = src->work + ((word32)i * src->rawPerSrc); |
9651 | | |
9652 | | /* A sampler error propagates for any source and is retryable; |
9653 | | * only a health-test verdict drops or latches. */ |
9654 | | ret = NoiseSrc_Gather(src, raw, src->rawPerSrc, i); |
9655 | | if (ret != 0) { |
9656 | | goto out; |
9657 | | } |
9658 | | ret = NoiseSrc_HealthTest(src, raw, src->rawPerSrc, i); |
9659 | | if (ret != 0) { |
9660 | | if (i == 0) { |
9661 | | goto out; /* fail closed; HealthTest latched src->failed */ |
9662 | | } |
9663 | | src->degraded |= (word16)(1U << i); |
9664 | | ret = 0; |
9665 | | continue; |
9666 | | } |
9667 | | contributed |= (word16)(1U << i); |
9668 | | } |
9669 | | |
9670 | | ret = wc_InitSha256(sha); |
9671 | | if (ret != 0) { |
9672 | | ForceZero(sha, sizeof(*sha)); |
9673 | | goto out; |
9674 | | } |
9675 | | |
9676 | | src->chunkCtr++; |
9677 | | ctrBuf[0] = WC_OCTET(src->chunkCtr >> 24); |
9678 | | ctrBuf[1] = WC_OCTET(src->chunkCtr >> 16); |
9679 | | ctrBuf[2] = WC_OCTET(src->chunkCtr >> 8); |
9680 | | ctrBuf[3] = WC_OCTET(src->chunkCtr); |
9681 | | |
9682 | | ret = wc_Sha256Update(sha, (const byte*)src->tag, |
9683 | | (word32)XSTRLEN(src->tag)); |
9684 | | if (ret == 0) { |
9685 | | ret = wc_Sha256Update(sha, ctrBuf, (word32)sizeof(ctrBuf)); |
9686 | | } |
9687 | | for (i = 0; (ret == 0) && (i < (int)src->numSrc); i++) { |
9688 | | if ((contributed & (word16)(1U << i)) == 0) { |
9689 | | continue; /* not gathered this chunk - never hash stale data */ |
9690 | | } |
9691 | | raw = src->work + ((word32)i * src->rawPerSrc); |
9692 | | ret = wc_Sha256Update(sha, raw, src->rawPerSrc); |
9693 | | } |
9694 | | if (ret == 0) { |
9695 | | ret = wc_Sha256Final(sha, digest); |
9696 | | } |
9697 | | wc_Sha256Free(sha); |
9698 | | ForceZero(sha, sizeof(*sha)); |
9699 | | if (ret != 0) { |
9700 | | goto out; |
9701 | | } |
9702 | | |
9703 | | take = (sz < (word32)WC_NOISE_CHUNK_SZ) ? sz |
9704 | | : (word32)WC_NOISE_CHUNK_SZ; |
9705 | | XMEMCPY(output, digest, take); |
9706 | | output += take; |
9707 | | sz -= take; |
9708 | | } |
9709 | | |
9710 | | out: |
9711 | | if (ret != 0) { |
9712 | | ForceZero(outStart, outLen); |
9713 | | } |
9714 | | ForceZero(digest, sizeof(digest)); |
9715 | | ForceZero(src->work, src->workSz); |
9716 | | #ifdef WOLFSSL_SMALL_STACK |
9717 | | XFREE(sha, NULL, DYNAMIC_TYPE_TMP_BUFFER); |
9718 | | #endif |
9719 | | return ret; |
9720 | | } |
9721 | | |
9722 | | int wc_NoiseSrc_SelfTest(wc_NoiseSrc* src) |
9723 | | { |
9724 | | /* Tests RAW noise, not conditioned seeds: the hashed chunk counter makes |
9725 | | * two GenerateSeed() outputs differ even with every source dead. */ |
9726 | | byte* a; |
9727 | | byte* b; |
9728 | | word32 len; |
9729 | | word32 i; |
9730 | | byte diff; |
9731 | | int s; |
9732 | | int ret; |
9733 | | |
9734 | | if (src == NULL) { |
9735 | | return BAD_FUNC_ARG; |
9736 | | } |
9737 | | |
9738 | | ret = wc_NoiseSrc_Init(src); |
9739 | | if (ret != 0) { |
9740 | | return ret; |
9741 | | } |
9742 | | |
9743 | | /* Two gathers side by side in the work buffer. */ |
9744 | | len = src->workSz / 2U; |
9745 | | if (len > 64U) { |
9746 | | len = 64U; |
9747 | | } |
9748 | | if (len == 0U) { |
9749 | | return BUFFER_E; |
9750 | | } |
9751 | | a = src->work; |
9752 | | b = src->work + len; |
9753 | | |
9754 | | for (s = 0; s < (int)src->numSrc; s++) { |
9755 | | if ((src->degraded & (word16)(1U << s)) != 0) { |
9756 | | continue; /* already dropped - no point re-testing it */ |
9757 | | } |
9758 | | ret = NoiseSrc_Gather(src, a, len, s); |
9759 | | if (ret == 0) { |
9760 | | ret = NoiseSrc_Gather(src, b, len, s); |
9761 | | } |
9762 | | if (ret != 0) { |
9763 | | break; |
9764 | | } |
9765 | | |
9766 | | /* A source stuck at any constant - including one whose clock was |
9767 | | * never enabled - produces identical gathers. */ |
9768 | | /* ConstantCompare, not XMEMCMP: raw pre-conditioning samples. */ |
9769 | | if (ConstantCompare(a, b, (int)len) == 0) { |
9770 | | ret = ENTROPY_RT_E; |
9771 | | if (s == 0) { |
9772 | | src->failed = ret; |
9773 | | break; |
9774 | | } |
9775 | | src->degraded |= (word16)(1U << s); |
9776 | | ret = 0; |
9777 | | continue; |
9778 | | } |
9779 | | |
9780 | | /* Constant-octet check, accumulated rather than early-exit. */ |
9781 | | diff = 0; |
9782 | | for (i = 1; i < len; i++) { |
9783 | | diff |= (byte)(a[i] ^ a[0]); |
9784 | | } |
9785 | | if (diff == 0) { |
9786 | | ret = ENTROPY_RT_E; |
9787 | | if (s == 0) { |
9788 | | src->failed = ret; |
9789 | | break; |
9790 | | } |
9791 | | src->degraded |= (word16)(1U << s); |
9792 | | ret = 0; |
9793 | | continue; |
9794 | | } |
9795 | | } |
9796 | | |
9797 | | /* A gather error above is deliberately not latched - see the policy note |
9798 | | * at the top of this module. */ |
9799 | | ForceZero(src->work, src->workSz); |
9800 | | |
9801 | | return ret; |
9802 | | } |
9803 | | |
9804 | | #endif /* WOLFSSL_NOISE_SRC */ |
9805 | | |
9806 | | |
9807 | | /* Begin wc_GenerateSeed Implementations */ |
9808 | | #if defined(CUSTOM_RAND_GENERATE_SEED) |
9809 | | |
9810 | | /* Implement your own random generation function |
9811 | | * Return 0 to indicate success |
9812 | | * int rand_gen_seed(byte* output, word32 sz); |
9813 | | * #define CUSTOM_RAND_GENERATE_SEED rand_gen_seed */ |
9814 | | |
9815 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
9816 | | { |
9817 | | (void)os; /* Suppress unused arg warning */ |
9818 | | return CUSTOM_RAND_GENERATE_SEED(output, sz); |
9819 | | } |
9820 | | |
9821 | | #elif defined(CUSTOM_RAND_GENERATE_SEED_OS) |
9822 | | |
9823 | | /* Implement your own random generation function, |
9824 | | * which includes OS_Seed. |
9825 | | * Return 0 to indicate success |
9826 | | * int rand_gen_seed(OS_Seed* os, byte* output, word32 sz); |
9827 | | * #define CUSTOM_RAND_GENERATE_SEED_OS rand_gen_seed */ |
9828 | | |
9829 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
9830 | | { |
9831 | | return CUSTOM_RAND_GENERATE_SEED_OS(os, output, sz); |
9832 | | } |
9833 | | |
9834 | | #elif defined(CUSTOM_RAND_GENERATE) |
9835 | | |
9836 | | /* Implement your own random generation function |
9837 | | * word32 rand_gen(void); |
9838 | | * #define CUSTOM_RAND_GENERATE rand_gen */ |
9839 | | |
9840 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
9841 | | { |
9842 | | word32 i = 0; |
9843 | | |
9844 | | (void)os; |
9845 | | |
9846 | | while (i < sz) |
9847 | | { |
9848 | | /* If not aligned or there is odd/remainder */ |
9849 | | if( (i + sizeof(CUSTOM_RAND_TYPE)) > sz || |
9850 | | ((wc_ptr_t)&output[i] % sizeof(CUSTOM_RAND_TYPE)) != 0 |
9851 | | ) { |
9852 | | /* Single byte at a time */ |
9853 | | output[i++] = (byte)CUSTOM_RAND_GENERATE(); |
9854 | | } |
9855 | | else { |
9856 | | /* Use native 8, 16, 32 or 64 copy instruction */ |
9857 | | *((CUSTOM_RAND_TYPE*)&output[i]) = CUSTOM_RAND_GENERATE(); |
9858 | | i += sizeof(CUSTOM_RAND_TYPE); |
9859 | | } |
9860 | | } |
9861 | | |
9862 | | return 0; |
9863 | | } |
9864 | | |
9865 | | #elif defined(WOLFSSL_SGX) |
9866 | | |
9867 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
9868 | | { |
9869 | | int ret = !SGX_SUCCESS; |
9870 | | int i, read_max = 10; |
9871 | | |
9872 | | for (i = 0; i < read_max && ret != SGX_SUCCESS; i++) { |
9873 | | ret = sgx_read_rand(output, sz); |
9874 | | } |
9875 | | |
9876 | | (void)os; |
9877 | | return (ret == SGX_SUCCESS) ? 0 : 1; |
9878 | | } |
9879 | | |
9880 | | #elif defined(USE_WINDOWS_API) |
9881 | | |
9882 | | #ifdef WIN_REUSE_CRYPT_HANDLE |
9883 | | /* shared crypt handle for RNG use */ |
9884 | | static ProviderHandle gHandle = 0; |
9885 | | |
9886 | | int wc_WinCryptHandleInit(void) |
9887 | | { |
9888 | | int ret = 0; |
9889 | | if (gHandle == 0) { |
9890 | | if(!CryptAcquireContext(&gHandle, 0, 0, PROV_RSA_FULL, |
9891 | | CRYPT_VERIFYCONTEXT)) { |
9892 | | DWORD dw = GetLastError(); |
9893 | | WOLFSSL_MSG("CryptAcquireContext failed!"); |
9894 | | WOLFSSL_ERROR((int)dw); |
9895 | | ret = WINCRYPT_E; |
9896 | | } |
9897 | | } |
9898 | | return ret; |
9899 | | } |
9900 | | |
9901 | | void wc_WinCryptHandleCleanup(void) |
9902 | | { |
9903 | | if (gHandle != 0) { |
9904 | | CryptReleaseContext(gHandle, 0); |
9905 | | gHandle = 0; |
9906 | | } |
9907 | | } |
9908 | | #endif /* WIN_REUSE_CRYPT_HANDLE */ |
9909 | | |
9910 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
9911 | | { |
9912 | | #ifdef WOLF_CRYPTO_CB |
9913 | | int ret; |
9914 | | |
9915 | | if (os != NULL |
9916 | | #ifndef WOLF_CRYPTO_CB_FIND |
9917 | | && os->devId != INVALID_DEVID) |
9918 | | #endif |
9919 | | { |
9920 | | ret = wc_CryptoCb_RandomSeed(os, output, sz); |
9921 | | if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) |
9922 | | return ret; |
9923 | | /* fall-through when unavailable */ |
9924 | | } |
9925 | | #endif |
9926 | | |
9927 | | #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED) |
9928 | | if (IS_INTEL_RDSEED(intel_flags)) { |
9929 | | if (!wc_GenerateSeed_IntelRD(NULL, output, sz)) { |
9930 | | /* success, we're done */ |
9931 | | return 0; |
9932 | | } |
9933 | | #ifdef FORCE_FAILURE_RDSEED |
9934 | | /* don't fall back to CryptoAPI */ |
9935 | | return READ_RAN_E; |
9936 | | #endif |
9937 | | } |
9938 | | #ifdef FORCE_FAILURE_RDSEED |
9939 | | else { |
9940 | | /* Don't fall back to system randomness */ |
9941 | | return MISSING_RNG_E; |
9942 | | } |
9943 | | #endif |
9944 | | #endif /* HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */ |
9945 | | |
9946 | | #ifdef WIN_REUSE_CRYPT_HANDLE |
9947 | | /* Check that handle was initialized. |
9948 | | * Note: initialization should be done through: |
9949 | | * wolfSSL_Init -> wolfCrypt_Init -> wc_WinCryptHandleInit |
9950 | | */ |
9951 | | if (wc_WinCryptHandleInit() != 0) { |
9952 | | return WINCRYPT_E; |
9953 | | } |
9954 | | if (!CryptGenRandom(gHandle, sz, output)) |
9955 | | return CRYPTGEN_E; |
9956 | | #else |
9957 | | if (!CryptAcquireContext(&os->handle, 0, 0, PROV_RSA_FULL, |
9958 | | CRYPT_VERIFYCONTEXT)) { |
9959 | | return WINCRYPT_E; |
9960 | | } |
9961 | | if (!CryptGenRandom(os->handle, sz, output)) { |
9962 | | return CRYPTGEN_E; |
9963 | | } |
9964 | | CryptReleaseContext(os->handle, 0); |
9965 | | os->handle = 0; |
9966 | | #endif |
9967 | | |
9968 | | return 0; |
9969 | | } |
9970 | | |
9971 | | |
9972 | | #elif defined(HAVE_RTP_SYS) || defined(EBSNET) |
9973 | | |
9974 | | #include "rtprand.h" /* rtp_rand () */ |
9975 | | |
9976 | | #if (defined(HAVE_RTP_SYS) || (defined(RTPLATFORM) && (RTPLATFORM != 0))) |
9977 | | #include "rtptime.h" /* rtp_get_system_msec() */ |
9978 | | |
9979 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
9980 | | { |
9981 | | word32 i; |
9982 | | |
9983 | | rtp_srand(rtp_get_system_msec()); |
9984 | | for (i = 0; i < sz; i++ ) { |
9985 | | output[i] = rtp_rand() % 256; |
9986 | | } |
9987 | | |
9988 | | return 0; |
9989 | | } |
9990 | | #else |
9991 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
9992 | | { |
9993 | | word32 i; |
9994 | | KS_SEED(ks_get_ticks()); |
9995 | | |
9996 | | for (i = 0; i < sz; i++ ) { |
9997 | | output[i] = KS_RANDOM() % 256; |
9998 | | } |
9999 | | |
10000 | | return 0; |
10001 | | } |
10002 | | #endif /* defined(HAVE_RTP_SYS) || (defined(RTPLATFORM) && (RTPLATFORM != 0)) */ |
10003 | | |
10004 | | #elif (defined(WOLFSSL_ATMEL) || defined(WOLFSSL_ATECC_RNG)) && \ |
10005 | | !defined(WOLFSSL_PIC32MZ_RNG) |
10006 | | /* enable ATECC RNG unless using PIC32MZ one instead */ |
10007 | | #include <wolfssl/wolfcrypt/port/atmel/atmel.h> |
10008 | | |
10009 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10010 | | { |
10011 | | int ret = 0; |
10012 | | |
10013 | | (void)os; |
10014 | | if (output == NULL) { |
10015 | | return BUFFER_E; |
10016 | | } |
10017 | | |
10018 | | ret = atmel_get_random_number(sz, output); |
10019 | | |
10020 | | return ret; |
10021 | | } |
10022 | | |
10023 | | #elif defined(MICROCHIP_PIC32) || defined(MICROCHIP_MPLAB_HARMONY) |
10024 | | |
10025 | | #ifdef MICROCHIP_MPLAB_HARMONY |
10026 | | #ifdef MICROCHIP_MPLAB_HARMONY_3 |
10027 | | #include "system/time/sys_time.h" |
10028 | | #define PIC32_SEED_COUNT SYS_TIME_CounterGet |
10029 | | #else |
10030 | | #define PIC32_SEED_COUNT _CP0_GET_COUNT |
10031 | | #endif |
10032 | | #else |
10033 | | #if !defined(WOLFSSL_MICROCHIP_PIC32MZ) |
10034 | | #include <peripheral/timer.h> |
10035 | | #endif |
10036 | | extern word32 ReadCoreTimer(void); |
10037 | | #define PIC32_SEED_COUNT ReadCoreTimer |
10038 | | #endif |
10039 | | |
10040 | | #ifdef WOLFSSL_PIC32MZ_RNG |
10041 | | #include "xc.h" |
10042 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10043 | | { |
10044 | | int i; |
10045 | | byte rnd[8]; |
10046 | | word32 *rnd32 = (word32 *)rnd; |
10047 | | word32 size = sz; |
10048 | | byte* op = output; |
10049 | | |
10050 | | #if ((__PIC32_FEATURE_SET0 == 'E') && (__PIC32_FEATURE_SET1 == 'C')) |
10051 | | RNGNUMGEN1 = _CP0_GET_COUNT(); |
10052 | | RNGPOLY1 = _CP0_GET_COUNT(); |
10053 | | RNGPOLY2 = _CP0_GET_COUNT(); |
10054 | | RNGNUMGEN2 = _CP0_GET_COUNT(); |
10055 | | #else |
10056 | | /* All others can be seeded from the TRNG */ |
10057 | | RNGCONbits.TRNGMODE = 1; |
10058 | | RNGCONbits.TRNGEN = 1; |
10059 | | while (RNGCNT < 64); |
10060 | | RNGCONbits.LOAD = 1; |
10061 | | while (RNGCONbits.LOAD == 1); |
10062 | | while (RNGCNT < 64); |
10063 | | RNGPOLY2 = RNGSEED2; |
10064 | | RNGPOLY1 = RNGSEED1; |
10065 | | #endif |
10066 | | |
10067 | | RNGCONbits.PLEN = 0x40; |
10068 | | RNGCONbits.PRNGEN = 1; |
10069 | | for (i=0; i<5; i++) { /* wait for RNGNUMGEN ready */ |
10070 | | volatile int x, y; |
10071 | | x = RNGNUMGEN1; |
10072 | | y = RNGNUMGEN2; |
10073 | | (void)x; |
10074 | | (void)y; |
10075 | | } |
10076 | | do { |
10077 | | rnd32[0] = RNGNUMGEN1; |
10078 | | rnd32[1] = RNGNUMGEN2; |
10079 | | |
10080 | | for(i=0; i<8; i++, op++) { |
10081 | | *op = rnd[i]; |
10082 | | size --; |
10083 | | if(size==0)break; |
10084 | | } |
10085 | | } while(size); |
10086 | | ForceZero(rnd, sizeof(rnd)); |
10087 | | return 0; |
10088 | | } |
10089 | | #else /* WOLFSSL_PIC32MZ_RNG */ |
10090 | | /* uses the core timer, in nanoseconds to seed srand */ |
10091 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10092 | | { |
10093 | | int i; |
10094 | | srand(PIC32_SEED_COUNT() * 25); |
10095 | | |
10096 | | for (i = 0; i < sz; i++ ) { |
10097 | | output[i] = rand() % 256; |
10098 | | if ( (i % 8) == 7) |
10099 | | srand(PIC32_SEED_COUNT() * 25); |
10100 | | } |
10101 | | return 0; |
10102 | | } |
10103 | | #endif /* WOLFSSL_PIC32MZ_RNG */ |
10104 | | |
10105 | | #elif defined(FREESCALE_K70_RNGA) || defined(FREESCALE_RNGA) |
10106 | | /* |
10107 | | * wc_Generates a RNG seed using the Random Number Generator Accelerator |
10108 | | * on the Kinetis K70. Documentation located in Chapter 37 of |
10109 | | * K70 Sub-Family Reference Manual (see Note 3 in the README for link). |
10110 | | */ |
10111 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10112 | | { |
10113 | | word32 i; |
10114 | | |
10115 | | /* turn on RNGA module */ |
10116 | | #if defined(SIM_SCGC3_RNGA_MASK) |
10117 | | SIM_SCGC3 |= SIM_SCGC3_RNGA_MASK; |
10118 | | #endif |
10119 | | #if defined(SIM_SCGC6_RNGA_MASK) |
10120 | | /* additionally needed for at least K64F */ |
10121 | | SIM_SCGC6 |= SIM_SCGC6_RNGA_MASK; |
10122 | | #endif |
10123 | | |
10124 | | /* set SLP bit to 0 - "RNGA is not in sleep mode" */ |
10125 | | RNG_CR &= ~RNG_CR_SLP_MASK; |
10126 | | |
10127 | | /* set HA bit to 1 - "security violations masked" */ |
10128 | | RNG_CR |= RNG_CR_HA_MASK; |
10129 | | |
10130 | | /* set GO bit to 1 - "output register loaded with data" */ |
10131 | | RNG_CR |= RNG_CR_GO_MASK; |
10132 | | |
10133 | | for (i = 0; i < sz; i++) { |
10134 | | |
10135 | | /* wait for RNG FIFO to be full */ |
10136 | | while((RNG_SR & RNG_SR_OREG_LVL(0xF)) == 0) {} |
10137 | | |
10138 | | /* get value */ |
10139 | | output[i] = RNG_OR; |
10140 | | } |
10141 | | |
10142 | | return 0; |
10143 | | } |
10144 | | |
10145 | | #elif defined(FREESCALE_K53_RNGB) || defined(FREESCALE_RNGB) |
10146 | | /* |
10147 | | * wc_Generates a RNG seed using the Random Number Generator (RNGB) |
10148 | | * on the Kinetis K53. Documentation located in Chapter 33 of |
10149 | | * K53 Sub-Family Reference Manual (see note in the README for link). |
10150 | | */ |
10151 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10152 | | { |
10153 | | int i; |
10154 | | |
10155 | | /* turn on RNGB module */ |
10156 | | SIM_SCGC3 |= SIM_SCGC3_RNGB_MASK; |
10157 | | |
10158 | | /* reset RNGB */ |
10159 | | RNG_CMD |= RNG_CMD_SR_MASK; |
10160 | | |
10161 | | /* FIFO generate interrupt, return all zeros on underflow, |
10162 | | * set auto reseed */ |
10163 | | RNG_CR |= (RNG_CR_FUFMOD_MASK | RNG_CR_AR_MASK); |
10164 | | |
10165 | | /* gen seed, clear interrupts, clear errors */ |
10166 | | RNG_CMD |= (RNG_CMD_GS_MASK | RNG_CMD_CI_MASK | RNG_CMD_CE_MASK); |
10167 | | |
10168 | | /* wait for seeding to complete */ |
10169 | | while ((RNG_SR & RNG_SR_SDN_MASK) == 0) {} |
10170 | | |
10171 | | for (i = 0; i < sz; i++) { |
10172 | | |
10173 | | /* wait for a word to be available from FIFO */ |
10174 | | while((RNG_SR & RNG_SR_FIFO_LVL_MASK) == 0) {} |
10175 | | |
10176 | | /* get value */ |
10177 | | output[i] = RNG_OUT; |
10178 | | } |
10179 | | |
10180 | | return 0; |
10181 | | } |
10182 | | |
10183 | | #elif defined(FREESCALE_KSDK_2_0_TRNG) |
10184 | | #ifndef TRNG0 |
10185 | | #define TRNG0 TRNG |
10186 | | #endif |
10187 | | |
10188 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10189 | | { |
10190 | | status_t status; |
10191 | | status = TRNG_GetRandomData(TRNG0, output, sz); |
10192 | | (void)os; |
10193 | | if (status == kStatus_Success) |
10194 | | { |
10195 | | return(0); |
10196 | | } |
10197 | | return RAN_BLOCK_E; |
10198 | | } |
10199 | | |
10200 | | #elif defined(FREESCALE_KSDK_2_0_RNGA) |
10201 | | |
10202 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10203 | | { |
10204 | | status_t status; |
10205 | | status = RNGA_GetRandomData(RNG, output, sz); |
10206 | | (void)os; |
10207 | | if (status == kStatus_Success) |
10208 | | { |
10209 | | return(0); |
10210 | | } |
10211 | | return RAN_BLOCK_E; |
10212 | | } |
10213 | | |
10214 | | |
10215 | | #elif defined(FREESCALE_RNGA) |
10216 | | |
10217 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10218 | | { |
10219 | | status_t status; |
10220 | | status = RNGA_GetRandomData(RNG, output, sz); |
10221 | | (void)os; |
10222 | | if (status == kStatus_Success) |
10223 | | { |
10224 | | return(0); |
10225 | | } |
10226 | | return RAN_BLOCK_E; |
10227 | | } |
10228 | | #elif !defined(WOLFSSL_CAAM) && \ |
10229 | | (defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) || \ |
10230 | | defined(FREESCALE_KSDK_BM) || defined(FREESCALE_FREE_RTOS)) |
10231 | | /* |
10232 | | * Fallback to USE_TEST_GENSEED if a FREESCALE platform did not match any |
10233 | | * of the TRNG/RNGA/RNGB support |
10234 | | */ |
10235 | | #define USE_TEST_GENSEED |
10236 | | |
10237 | | #elif defined(WOLFSSL_SILABS_SE_TYPES) && !defined(WOLFSSL_SILABS_HOST_TEST) |
10238 | | /* Both Silicon Labs ports seed from the SE TRNG. Gated on SE_TYPES, not |
10239 | | * SE_ACCEL, so the crypto callback port seeds too: the SE is the only |
10240 | | * entropy source on the part, so otherwise an RNG built with INVALID_DEVID |
10241 | | * fails with RNG_FAILURE_E and the software fallback path is unusable. |
10242 | | * |
10243 | | * The host compile test is excluded - its shim declines every command, so |
10244 | | * that build must fall through to the host's own entropy source. */ |
10245 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10246 | | { |
10247 | | (void)os; |
10248 | | return silabs_GenerateRand(output, sz); |
10249 | | } |
10250 | | |
10251 | | #elif defined(STM32_RNG) |
10252 | | /* Generate a RNG seed using the hardware random number generator |
10253 | | * on the STM32F2/F4/F7/L4. */ |
10254 | | #include <wolfssl/wolfcrypt/port/st/stm32.h> |
10255 | | /* Pulls in WC_STM32_RNG_CLK_ENABLE for WOLFSSL_STM32_BARE builds */ |
10256 | | #ifdef WC_STM32_RNG_DIAG |
10257 | | /* The WC_STM32_RNG_DIAG paths below use printf(); pull in stdio.h so the |
10258 | | * file compiles on strict C99+ toolchains when diagnostics are enabled. */ |
10259 | | #include <stdio.h> |
10260 | | #endif |
10261 | | |
10262 | | |
10263 | | #ifdef WOLFSSL_STM32_CUBEMX |
10264 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10265 | | { |
10266 | | int ret; |
10267 | | RNG_HandleTypeDef hrng; |
10268 | | word32 i = 0; |
10269 | | (void)os; |
10270 | | |
10271 | | ret = wolfSSL_CryptHwMutexLock(); |
10272 | | if (ret != 0) { |
10273 | | return ret; |
10274 | | } |
10275 | | |
10276 | | /* enable RNG clock source */ |
10277 | | __HAL_RCC_RNG_CLK_ENABLE(); |
10278 | | |
10279 | | /* enable RNG peripheral */ |
10280 | | XMEMSET(&hrng, 0, sizeof(hrng)); |
10281 | | hrng.Instance = RNG; |
10282 | | HAL_RNG_Init(&hrng); |
10283 | | |
10284 | | while (i < sz) { |
10285 | | /* If not aligned or there is odd/remainder */ |
10286 | | if( (i + sizeof(word32)) > sz || |
10287 | | ((wc_ptr_t)&output[i] % sizeof(word32)) != 0 |
10288 | | ) { |
10289 | | /* Single byte at a time */ |
10290 | | uint32_t tmpRng = 0; |
10291 | | if (HAL_RNG_GenerateRandomNumber(&hrng, &tmpRng) != HAL_OK) { |
10292 | | wolfSSL_CryptHwMutexUnLock(); |
10293 | | return RAN_BLOCK_E; |
10294 | | } |
10295 | | output[i++] = (byte)tmpRng; |
10296 | | } |
10297 | | else { |
10298 | | /* Use native 32 instruction */ |
10299 | | if (HAL_RNG_GenerateRandomNumber(&hrng, (uint32_t*)&output[i]) != HAL_OK) { |
10300 | | wolfSSL_CryptHwMutexUnLock(); |
10301 | | return RAN_BLOCK_E; |
10302 | | } |
10303 | | i += sizeof(word32); |
10304 | | } |
10305 | | } |
10306 | | |
10307 | | HAL_RNG_DeInit(&hrng); |
10308 | | |
10309 | | wolfSSL_CryptHwMutexUnLock(); |
10310 | | |
10311 | | return 0; |
10312 | | } |
10313 | | #elif defined(WOLFSSL_STM32F427_RNG) || defined(WOLFSSL_STM32_RNG_NOLIB) \ |
10314 | | || defined(STM32_NUTTX_RNG) |
10315 | | |
10316 | | #ifdef STM32_NUTTX_RNG |
10317 | | #include "hardware/stm32_rng.h" |
10318 | | /* Set CONFIG_STM32U5_RNG in NuttX to enable the RCC */ |
10319 | | #define WC_RNG_CR *((volatile uint32_t*)(STM32_RNG_CR)) |
10320 | | #define WC_RNG_SR *((volatile uint32_t*)(STM32_RNG_SR)) |
10321 | | #define WC_RNG_DR *((volatile uint32_t*)(STM32_RNG_DR)) |
10322 | | #else |
10323 | | /* Comes from "stm32xxxx_hal.h" */ |
10324 | | #define WC_RNG_CR RNG->CR |
10325 | | #define WC_RNG_SR RNG->SR |
10326 | | #define WC_RNG_DR RNG->DR |
10327 | | #endif |
10328 | | |
10329 | | |
10330 | | /* Bounded poll for DRDY, plus recovery from SECS / CECS. The |
10331 | | * unbounded `while (DRDY == 0)` loop in the original code spins |
10332 | | * forever on chips where the RNG kernel clock is unstable |
10333 | | * (e.g. WL55 with RNGSEL = MSI under sustained ECDSA-key-gen |
10334 | | * load), because once the IP latches a Seed-error or Clock- |
10335 | | * error condition it stops asserting DRDY. Per the STM32 RM |
10336 | | * recovery sequence: clear SEIS/CEIS, toggle RNGEN, discard the |
10337 | | * stale words sitting in the RNG output, then retry. */ |
10338 | | #ifndef STM32_BARE_RNG_BYTE_TIMEOUT |
10339 | | #define STM32_BARE_RNG_BYTE_TIMEOUT 0x40000 |
10340 | | #endif |
10341 | | #ifndef STM32_BARE_RNG_MAX_RETRIES |
10342 | | #define STM32_BARE_RNG_MAX_RETRIES 8 |
10343 | | #endif |
10344 | | |
10345 | | /* Bring the direct-register RNG to a producing state: clock enable, the |
10346 | | * new-gen (C5) NIST conditioning under CONDRST on the first call, and |
10347 | | * RNGEN. Mutex-free -- the caller must already hold the crypto HW mutex. |
10348 | | * Shared by wc_GenerateSeed (below) and the SAES self-init path |
10349 | | * (Stm32SaesEnsureRng), so a cold DHUK/SAES operation no longer requires a |
10350 | | * prior wc_InitRng. Returns 0, or RNG_FAILURE_E if the conditioning |
10351 | | * soft-reset never clears. */ |
10352 | | WOLFSSL_LOCAL int wc_stm32_rng_ensure_ready(void) |
10353 | | { |
10354 | | word32 t = 0; |
10355 | | (void)t; |
10356 | | |
10357 | | #ifndef STM32_NUTTX_RNG |
10358 | | /* enable RNG peripheral clock */ |
10359 | | #ifdef WC_STM32_RNG_CLK_ENABLE |
10360 | | WC_STM32_RNG_CLK_ENABLE(); |
10361 | | #else |
10362 | | /* Default for F4/F7/L4/L5/U5/H5/H7 -- RNG on AHB2 */ |
10363 | | RCC->AHB2ENR |= RCC_AHB2ENR_RNGEN; |
10364 | | #endif |
10365 | | #endif |
10366 | | |
10367 | | /* On the new-gen STM32C5 RNG IP the CR register is locked at |
10368 | | * reset (CONFIGLOCK clear, but the IP refuses to produce data |
10369 | | * until a NIST-compliant CONFIG1/2/3 + NSCR + HTCR sequence |
10370 | | * has been written under CONDRST). The HAL ships canonical |
10371 | | * candidate values in the device header (RNG_CAND_NIST_*). |
10372 | | * Detect the family by presence of that symbol -- on chips |
10373 | | * without it (F4/F7/L4/U5/H7/H5/WL/etc.) skip. Do this only |
10374 | | * on the first call (RNGEN clear) so subsequent calls don't |
10375 | | * disturb a running peripheral. */ |
10376 | | #if defined(RNG_CAND_NIST_CR_VALUE) && defined(RNG_CR_CONDRST) && \ |
10377 | | !defined(WC_STM32_RNG_NO_NIST_INIT) |
10378 | | if ((WC_RNG_CR & RNG_CR_RNGEN) == 0U) { |
10379 | | #ifdef RNG_SR_BUSY |
10380 | | /* HAL flow: drain BUSY before writing CR. */ |
10381 | | t = 0; |
10382 | | while ((WC_RNG_SR & RNG_SR_BUSY) != 0U) { |
10383 | | if (++t >= STM32_BARE_RNG_BYTE_TIMEOUT) { |
10384 | | break; |
10385 | | } |
10386 | | } |
10387 | | #endif |
10388 | | WC_RNG_CR = (uint32_t)RNG_CAND_NIST_CR_VALUE | |
10389 | | (uint32_t)RNG_CR_CONDRST; |
10390 | | #ifdef RNG_CAND_NIST_NSCR_VALUE |
10391 | | RNG->NSCR = (uint32_t)RNG_CAND_NIST_NSCR_VALUE; |
10392 | | #endif |
10393 | | #ifdef RNG_CAND_NIST_HTCR_VALUE |
10394 | | RNG->HTCR[0] = (uint32_t)RNG_CAND_NIST_HTCR_VALUE; |
10395 | | #endif |
10396 | | /* Clear CONDRST and wait for the IP to mirror it back. The |
10397 | | * STM32 HAL polls RNG_CR.CONDRST (not SR.BUSY) for completion |
10398 | | * of the conditioning soft-reset; SR.BUSY drops earlier in |
10399 | | * the seed-pull pipeline on at least the C5 IP and reading |
10400 | | * it as "conditioning done" trips a SECS=1 a few microseconds |
10401 | | * later when RNGEN goes high. Bounded so a misconfigured |
10402 | | * kernel clock returns a clean error instead of hanging. */ |
10403 | | WC_RNG_CR &= ~(uint32_t)RNG_CR_CONDRST; |
10404 | | t = 0; |
10405 | | while ((WC_RNG_CR & RNG_CR_CONDRST) != 0U) { |
10406 | | if (++t >= STM32_BARE_RNG_BYTE_TIMEOUT) { |
10407 | | #ifdef WC_STM32_RNG_DIAG |
10408 | | printf("[RNG] CONDRST stuck CR=%08lx SR=%08lx\n", |
10409 | | (unsigned long)WC_RNG_CR, |
10410 | | (unsigned long)WC_RNG_SR); |
10411 | | #endif |
10412 | | return RNG_FAILURE_E; |
10413 | | } |
10414 | | } |
10415 | | #ifdef WC_STM32_RNG_DIAG |
10416 | | printf("[RNG] post-NIST CR=%08lx SR=%08lx t=%lu\n", |
10417 | | (unsigned long)WC_RNG_CR, |
10418 | | (unsigned long)WC_RNG_SR, |
10419 | | (unsigned long)t); |
10420 | | #endif |
10421 | | } |
10422 | | #endif |
10423 | | |
10424 | | /* enable RNG interrupt, set IE bit in RNG->CR register */ |
10425 | | WC_RNG_CR |= RNG_CR_IE; |
10426 | | |
10427 | | /* enable RNG, set RNGEN bit in RNG->CR. Activates RNG, |
10428 | | * RNG_LFSR, and error detector. WC_STM32_RNG_CED_DISABLE |
10429 | | * additionally sets CR.CED=1 to suppress the clock-error |
10430 | | * detection -- the Linux STM32 RNG driver does this and on |
10431 | | * the C5 silicon the CED detector trips on a (perfectly fine) |
10432 | | * 48 MHz kernel clock for reasons unclear in the RM. */ |
10433 | | #ifdef WC_STM32_RNG_CED_DISABLE |
10434 | | WC_RNG_CR |= RNG_CR_RNGEN | RNG_CR_CED; |
10435 | | #else |
10436 | | WC_RNG_CR |= RNG_CR_RNGEN; |
10437 | | #endif |
10438 | | |
10439 | | return 0; |
10440 | | } |
10441 | | |
10442 | | /* Generate a RNG seed using the hardware RNG on the STM32F427 |
10443 | | * directly, following steps outlined in STM32F4 Reference |
10444 | | * Manual (Chapter 24) for STM32F4xx family. */ |
10445 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10446 | | { |
10447 | | int ret; |
10448 | | word32 i; |
10449 | | word32 t; |
10450 | | word32 guard; |
10451 | | word32 retries; |
10452 | | word32 sr; |
10453 | | (void)os; |
10454 | | |
10455 | | ret = wolfSSL_CryptHwMutexLock(); |
10456 | | if (ret != 0) { |
10457 | | return ret; |
10458 | | } |
10459 | | |
10460 | | /* Clock enable + (C5) NIST conditioning + RNGEN, shared with the SAES |
10461 | | * self-init path. Mutex-free helper; we hold the mutex. */ |
10462 | | ret = wc_stm32_rng_ensure_ready(); |
10463 | | if (ret != 0) { |
10464 | | wolfSSL_CryptHwMutexUnLock(); |
10465 | | return ret; |
10466 | | } |
10467 | | |
10468 | | /* (No early SECS/CECS bail here.) The HAL doesn't check error |
10469 | | * status immediately after RNGEN -- the IP needs a few cycles |
10470 | | * after enable for the first seed pull, and a transient SEIS/SECS |
10471 | | * can latch and resolve itself through the auto-reset that the |
10472 | | * retry loop below already handles. Bailing here returned |
10473 | | * RNG_FAILURE_E (-199) on first-init on the STM32C5 silicon. |
10474 | | * NOTE: this branch serves all direct-register STM32 RNG users |
10475 | | * (WOLFSSL_STM32F427_RNG / WOLFSSL_STM32_RNG_NOLIB / STM32_NUTTX_RNG), |
10476 | | * not only the BARE/C5 port, so this bounded-retry + recovery applies |
10477 | | * to every NOLIB family. It is strictly more robust than the old early |
10478 | | * fast-fail: it still returns RNG_FAILURE_E after the retry budget. */ |
10479 | | |
10480 | | for (i = 0; i < sz; i++) { |
10481 | | retries = 0; |
10482 | | for (;;) { |
10483 | | t = 0; |
10484 | | /* Sample SR once before the loop so the post-loop |
10485 | | * happy-path / error checks have a defined value even |
10486 | | * if STM32_BARE_RNG_BYTE_TIMEOUT is configured to 0. */ |
10487 | | sr = WC_RNG_SR; |
10488 | | /* Bounded DRDY poll -- breaks on either DRDY or any |
10489 | | * error indication (SECS/CECS). */ |
10490 | | while (t < STM32_BARE_RNG_BYTE_TIMEOUT) { |
10491 | | sr = WC_RNG_SR; |
10492 | | if ((sr & (RNG_SR_DRDY | RNG_SR_SECS | |
10493 | | RNG_SR_CECS)) != 0U) { |
10494 | | break; |
10495 | | } |
10496 | | t++; |
10497 | | } |
10498 | | |
10499 | | /* Happy path: data ready and no error. */ |
10500 | | if ((sr & RNG_SR_DRDY) != 0U && |
10501 | | (sr & (RNG_SR_SECS | RNG_SR_CECS)) == 0U) { |
10502 | | output[i] = WC_RNG_DR; |
10503 | | break; |
10504 | | } |
10505 | | |
10506 | | /* Either timed out or an error latched. Recover. */ |
10507 | | if (++retries > STM32_BARE_RNG_MAX_RETRIES) { |
10508 | | #ifdef WC_STM32_RNG_DIAG |
10509 | | printf("[RNG] retry max byte=%lu sr=%08lx CR=%08lx\n", |
10510 | | (unsigned long)i, |
10511 | | (unsigned long)sr, |
10512 | | (unsigned long)WC_RNG_CR); |
10513 | | #endif |
10514 | | wolfSSL_CryptHwMutexUnLock(); |
10515 | | return RNG_FAILURE_E; |
10516 | | } |
10517 | | #ifdef WC_STM32_RNG_DIAG |
10518 | | printf("[RNG] retry byte=%lu retries=%lu sr=%08lx\n", |
10519 | | (unsigned long)i, |
10520 | | (unsigned long)retries, |
10521 | | (unsigned long)sr); |
10522 | | #endif |
10523 | | |
10524 | | /* Recovery sequence (per STM32 RM RNG chapter): |
10525 | | * 1. Clear SEIS / CEIS interrupt status by writing 0 |
10526 | | * to those bits. All other SR bits are read-only |
10527 | | * status indicators (DRDY / BUSY / SECS / CECS); |
10528 | | * writing 0 to them has no effect per the RM, so |
10529 | | * a plain 0 write is safe and avoids the |
10530 | | * read-modify-write hitting any reserved bits the |
10531 | | * IP revision may add later. |
10532 | | * 2. Toggle RNGEN off then on to drop any stale |
10533 | | * LFSR state that may be tainted by the error. |
10534 | | * 3. Discard four DR reads to flush the pipeline |
10535 | | * (only meaningful when DRDY is set; otherwise |
10536 | | * the reads are harmless and bounded). The 'guard' |
10537 | | * counter bounds the loop independently of 't' so a |
10538 | | * marginal kernel clock (DRDY stays 0, no error |
10539 | | * latched) cannot spin forever -- it falls through |
10540 | | * to the outer retry/backoff instead of hanging. */ |
10541 | | WC_RNG_SR = 0; |
10542 | | WC_RNG_CR &= ~RNG_CR_RNGEN; |
10543 | | WC_RNG_CR |= RNG_CR_RNGEN; |
10544 | | t = 0; |
10545 | | guard = 0; |
10546 | | while (t < 4U && guard < STM32_BARE_RNG_BYTE_TIMEOUT) { |
10547 | | guard++; |
10548 | | if ((WC_RNG_SR & RNG_SR_DRDY) != 0U) { |
10549 | | (void)WC_RNG_DR; |
10550 | | t++; |
10551 | | } |
10552 | | else if ((WC_RNG_SR & |
10553 | | (RNG_SR_SECS | RNG_SR_CECS)) != 0U) { |
10554 | | /* Clock-error during recovery -- bail and |
10555 | | * let the outer retry handle it. */ |
10556 | | break; |
10557 | | } |
10558 | | } |
10559 | | } |
10560 | | } |
10561 | | |
10562 | | wolfSSL_CryptHwMutexUnLock(); |
10563 | | |
10564 | | return 0; |
10565 | | } |
10566 | | |
10567 | | #else |
10568 | | |
10569 | | /* Generate a RNG seed using the STM32 Standard Peripheral Library */ |
10570 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10571 | | { |
10572 | | int ret; |
10573 | | word32 i; |
10574 | | (void)os; |
10575 | | |
10576 | | ret = wolfSSL_CryptHwMutexLock(); |
10577 | | if (ret != 0) { |
10578 | | return ret; |
10579 | | } |
10580 | | |
10581 | | /* enable RNG clock source */ |
10582 | | RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE); |
10583 | | |
10584 | | /* reset RNG */ |
10585 | | RNG_DeInit(); |
10586 | | |
10587 | | /* enable RNG peripheral */ |
10588 | | RNG_Cmd(ENABLE); |
10589 | | |
10590 | | /* verify no errors with RNG_CLK or Seed */ |
10591 | | if (RNG_GetFlagStatus(RNG_FLAG_SECS | RNG_FLAG_CECS) != RESET) { |
10592 | | wolfSSL_CryptHwMutexUnLock(); |
10593 | | return RNG_FAILURE_E; |
10594 | | } |
10595 | | |
10596 | | for (i = 0; i < sz; i++) { |
10597 | | /* wait until RNG number is ready */ |
10598 | | while (RNG_GetFlagStatus(RNG_FLAG_DRDY) == RESET) { } |
10599 | | |
10600 | | /* get value */ |
10601 | | output[i] = RNG_GetRandomNumber(); |
10602 | | } |
10603 | | |
10604 | | wolfSSL_CryptHwMutexUnLock(); |
10605 | | |
10606 | | return 0; |
10607 | | } |
10608 | | #endif /* WOLFSSL_STM32_CUBEMX */ |
10609 | | |
10610 | | #elif defined(WOLFSSL_TIRTOS) |
10611 | | #warning "potential for not enough entropy, currently being used for testing" |
10612 | | #include <xdc/runtime/Timestamp.h> |
10613 | | #include <stdlib.h> |
10614 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10615 | | { |
10616 | | int i; |
10617 | | srand(xdc_runtime_Timestamp_get32()); |
10618 | | |
10619 | | for (i = 0; i < sz; i++ ) { |
10620 | | output[i] = rand() % 256; |
10621 | | if ((i % 8) == 7) { |
10622 | | srand(xdc_runtime_Timestamp_get32()); |
10623 | | } |
10624 | | } |
10625 | | |
10626 | | return 0; |
10627 | | } |
10628 | | |
10629 | | #elif defined(WOLFSSL_PB) |
10630 | | |
10631 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10632 | | { |
10633 | | word32 i; |
10634 | | for (i = 0; i < sz; i++) |
10635 | | output[i] = UTL_Rand(); |
10636 | | |
10637 | | (void)os; |
10638 | | |
10639 | | return 0; |
10640 | | } |
10641 | | |
10642 | | #elif defined(WOLFSSL_NUCLEUS) |
10643 | | #include "nucleus.h" |
10644 | | #include "kernel/plus_common.h" |
10645 | | |
10646 | | #warning "potential for not enough entropy, currently being used for testing" |
10647 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10648 | | { |
10649 | | int i; |
10650 | | srand(NU_Get_Time_Stamp()); |
10651 | | |
10652 | | for (i = 0; i < sz; i++ ) { |
10653 | | output[i] = rand() % 256; |
10654 | | if ((i % 8) == 7) { |
10655 | | srand(NU_Get_Time_Stamp()); |
10656 | | } |
10657 | | } |
10658 | | |
10659 | | return 0; |
10660 | | } |
10661 | | #elif defined(WOLFSSL_DEOS) && !defined(CUSTOM_RAND_GENERATE) |
10662 | | #include "stdlib.h" |
10663 | | |
10664 | | #warning "potential for not enough entropy, currently being used for testing Deos" |
10665 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10666 | | { |
10667 | | int i; |
10668 | | int seed = XTIME(0); |
10669 | | (void)os; |
10670 | | |
10671 | | for (i = 0; i < sz; i++ ) { |
10672 | | output[i] = rand_r(&seed) % 256; |
10673 | | if ((i % 8) == 7) { |
10674 | | seed = XTIME(0); |
10675 | | rand_r(&seed); |
10676 | | } |
10677 | | } |
10678 | | |
10679 | | return 0; |
10680 | | } |
10681 | | #elif defined(WOLFSSL_VXWORKS) |
10682 | | #ifdef WOLFSSL_VXWORKS_6_x |
10683 | | #include "stdlib.h" |
10684 | | #warning "potential for not enough entropy, currently being used for testing" |
10685 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10686 | | { |
10687 | | int i; |
10688 | | unsigned int seed = (unsigned int)XTIME(0); |
10689 | | (void)os; |
10690 | | |
10691 | | for (i = 0; i < sz; i++ ) { |
10692 | | output[i] = rand_r(&seed) % 256; |
10693 | | if ((i % 8) == 7) { |
10694 | | seed = (unsigned int)XTIME(0); |
10695 | | rand_r(&seed); |
10696 | | } |
10697 | | } |
10698 | | |
10699 | | return 0; |
10700 | | } |
10701 | | #else |
10702 | | #include <randomNumGen.h> |
10703 | | #include <tickLib.h> |
10704 | | |
10705 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) { |
10706 | | STATUS status = ERROR; |
10707 | | RANDOM_NUM_GEN_STATUS r_status = RANDOM_NUM_GEN_ERROR; |
10708 | | _Vx_ticks_t seed = 0; |
10709 | | |
10710 | | #ifdef VXWORKS_SIM |
10711 | | /* cannot generate true entropy with VxWorks simulator */ |
10712 | | #warning "not enough entropy, simulator for testing only" |
10713 | | int i = 0; |
10714 | | |
10715 | | for (i = 0; i < 1000; i++) { |
10716 | | randomAddTimeStamp(); |
10717 | | } |
10718 | | #endif |
10719 | | |
10720 | | /* |
10721 | | wolfSSL can request 52 Bytes of random bytes. We need to add |
10722 | | buffer to the entropy pool to ensure we can get more than 32 Bytes. |
10723 | | Because VxWorks has entropy limits (ENTROPY_MIN and ENTROPY_MAX) |
10724 | | defined as 256 and 1024 bits, see randomSWNumGenLib.c. |
10725 | | |
10726 | | randStatus() can return the following status: |
10727 | | RANDOM_NUM_GEN_NO_ENTROPY when entropy is 0 |
10728 | | RANDOM_NUM_GEN_ERROR, entropy is not initialized |
10729 | | RANDOM_NUM_GEN_NOT_ENOUGH_ENTROPY if entropy < 32 Bytes |
10730 | | RANDOM_NUM_GEN_ENOUGH_ENTROPY if entropy is between 32 and 128 Bytes |
10731 | | RANDOM_NUM_GEN_MAX_ENTROPY if entropy is greater than 128 Bytes |
10732 | | */ |
10733 | | |
10734 | | do { |
10735 | | seed = tickGet(); |
10736 | | status = randAdd(&seed, sizeof(_Vx_ticks_t), 2); |
10737 | | if (status == OK) |
10738 | | r_status = randStatus(); |
10739 | | |
10740 | | } while (r_status != RANDOM_NUM_GEN_MAX_ENTROPY && |
10741 | | r_status != RANDOM_NUM_GEN_ERROR && status == OK); |
10742 | | |
10743 | | if (r_status == RANDOM_NUM_GEN_ERROR) |
10744 | | return RNG_FAILURE_E; |
10745 | | |
10746 | | status = randBytes (output, sz); |
10747 | | |
10748 | | if (status == ERROR) { |
10749 | | return RNG_FAILURE_E; |
10750 | | } |
10751 | | |
10752 | | return 0; |
10753 | | } |
10754 | | #endif |
10755 | | #elif defined(WOLFSSL_NRF51) || defined(WOLFSSL_NRF5x) |
10756 | | #include "app_error.h" |
10757 | | #include "nrf_drv_rng.h" |
10758 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10759 | | { |
10760 | | int remaining = sz, pos = 0; |
10761 | | word32 err_code; |
10762 | | byte available; |
10763 | | static byte initialized = 0; |
10764 | | |
10765 | | (void)os; |
10766 | | |
10767 | | /* Make sure RNG is running */ |
10768 | | if (!initialized) { |
10769 | | err_code = nrf_drv_rng_init(NULL); |
10770 | | if (err_code != NRF_SUCCESS && err_code != NRF_ERROR_INVALID_STATE |
10771 | | #ifdef NRF_ERROR_MODULE_ALREADY_INITIALIZED |
10772 | | && err_code != NRF_ERROR_MODULE_ALREADY_INITIALIZED |
10773 | | #endif |
10774 | | ) { |
10775 | | return -1; |
10776 | | } |
10777 | | initialized = 1; |
10778 | | } |
10779 | | |
10780 | | while (remaining > 0) { |
10781 | | int length; |
10782 | | available = 0; |
10783 | | nrf_drv_rng_bytes_available(&available); /* void func */ |
10784 | | length = (remaining < available) ? remaining : available; |
10785 | | if (length > 0) { |
10786 | | err_code = nrf_drv_rng_rand(&output[pos], length); |
10787 | | if (err_code != NRF_SUCCESS) { |
10788 | | break; |
10789 | | } |
10790 | | remaining -= length; |
10791 | | pos += length; |
10792 | | } |
10793 | | } |
10794 | | |
10795 | | return (err_code == NRF_SUCCESS) ? 0 : -1; |
10796 | | } |
10797 | | |
10798 | | #elif defined(INTIME_RTOS) |
10799 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10800 | | { |
10801 | | uint32_t randval; |
10802 | | word32 len; |
10803 | | |
10804 | | if (output == NULL) { |
10805 | | return BUFFER_E; |
10806 | | } |
10807 | | |
10808 | | #ifdef INTIMEVER |
10809 | | /* If INTIMEVER exists then it is INTIME RTOS v6 or later */ |
10810 | | #define INTIME_RAND_FUNC arc4random |
10811 | | len = 4; |
10812 | | #else |
10813 | | /* v5 and older */ |
10814 | | #define INTIME_RAND_FUNC rand |
10815 | | srand(time(0)); |
10816 | | len = 2; /* don't use all 31 returned bits */ |
10817 | | #endif |
10818 | | |
10819 | | while (sz > 0) { |
10820 | | if (sz < len) |
10821 | | len = sz; |
10822 | | randval = INTIME_RAND_FUNC(); |
10823 | | XMEMCPY(output, &randval, len); |
10824 | | output += len; |
10825 | | sz -= len; |
10826 | | } |
10827 | | (void)os; |
10828 | | |
10829 | | return 0; |
10830 | | } |
10831 | | |
10832 | | #elif defined(WOLFSSL_WICED) |
10833 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10834 | | { |
10835 | | int ret; |
10836 | | (void)os; |
10837 | | |
10838 | | if (output == NULL || UINT16_MAX < sz) { |
10839 | | return BUFFER_E; |
10840 | | } |
10841 | | |
10842 | | if ((ret = wiced_crypto_get_random((void*) output, sz) ) |
10843 | | != WICED_SUCCESS) { |
10844 | | return ret; |
10845 | | } |
10846 | | |
10847 | | return ret; |
10848 | | } |
10849 | | |
10850 | | #elif defined(WOLFSSL_NETBURNER) |
10851 | | #warning using NetBurner pseudo random GetRandomByte for seed |
10852 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10853 | | { |
10854 | | word32 i; |
10855 | | (void)os; |
10856 | | |
10857 | | if (output == NULL) { |
10858 | | return BUFFER_E; |
10859 | | } |
10860 | | |
10861 | | for (i = 0; i < sz; i++) { |
10862 | | output[i] = GetRandomByte(); |
10863 | | |
10864 | | /* check if was a valid random number */ |
10865 | | if (!RandomValid()) |
10866 | | return RNG_FAILURE_E; |
10867 | | } |
10868 | | |
10869 | | return 0; |
10870 | | } |
10871 | | #elif defined(IDIRECT_DEV_RANDOM) |
10872 | | |
10873 | | extern int getRandom( int sz, unsigned char *output ); |
10874 | | |
10875 | | int GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10876 | | { |
10877 | | int num_bytes_returned = 0; |
10878 | | |
10879 | | num_bytes_returned = getRandom( (int) sz, (unsigned char *) output ); |
10880 | | |
10881 | | return 0; |
10882 | | } |
10883 | | |
10884 | | #elif defined(WOLFSSL_CAAM) |
10885 | | |
10886 | | #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h> |
10887 | | |
10888 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10889 | | { |
10890 | | unsigned int args[4] = {0}; |
10891 | | CAAM_BUFFER buf[1]; |
10892 | | int ret = 0; |
10893 | | int times = 1000, i; /* 1000 is an arbitrary number chosen */ |
10894 | | word32 idx = 0; |
10895 | | |
10896 | | (void)os; |
10897 | | |
10898 | | if (output == NULL) { |
10899 | | return BUFFER_E; |
10900 | | } |
10901 | | |
10902 | | /* Check Waiting to make sure entropy is ready */ |
10903 | | for (i = 0; i < times; i++) { |
10904 | | buf[0].BufferType = DataBuffer | LastBuffer; |
10905 | | buf[0].TheAddress = (CAAM_ADDRESS)(output + idx); |
10906 | | buf[0].Length = ((sz - idx) < WC_CAAM_MAX_ENTROPY)? |
10907 | | sz - idx : WC_CAAM_MAX_ENTROPY; |
10908 | | |
10909 | | args[0] = buf[0].Length; |
10910 | | ret = wc_caamAddAndWait(buf, 1, args, CAAM_ENTROPY); |
10911 | | if (ret == 0) { |
10912 | | idx += buf[0].Length; |
10913 | | if (idx == sz) |
10914 | | break; |
10915 | | } |
10916 | | |
10917 | | /* driver could be waiting for entropy */ |
10918 | | if (ret != WC_NO_ERR_TRACE(RAN_BLOCK_E) && ret != 0) { |
10919 | | return ret; |
10920 | | } |
10921 | | #ifndef WOLFSSL_IMXRT1170_CAAM |
10922 | | usleep(100); |
10923 | | #endif |
10924 | | } |
10925 | | |
10926 | | if (i == times && ret != 0) { |
10927 | | return RNG_FAILURE_E; |
10928 | | } |
10929 | | else { /* Success case */ |
10930 | | ret = 0; |
10931 | | } |
10932 | | |
10933 | | return ret; |
10934 | | } |
10935 | | |
10936 | | #elif defined(WOLFSSL_APACHE_MYNEWT) |
10937 | | |
10938 | | #include <stdlib.h> |
10939 | | #include "os/os_time.h" |
10940 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10941 | | { |
10942 | | int i; |
10943 | | srand(os_time_get()); |
10944 | | |
10945 | | for (i = 0; i < sz; i++ ) { |
10946 | | output[i] = rand() % 256; |
10947 | | if ((i % 8) == 7) { |
10948 | | srand(os_time_get()); |
10949 | | } |
10950 | | } |
10951 | | |
10952 | | return 0; |
10953 | | } |
10954 | | |
10955 | | #elif defined(ARDUINO) |
10956 | | |
10957 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
10958 | | { |
10959 | | int ret = 0; |
10960 | | word32 rand; |
10961 | | while (sz > 0) { |
10962 | | word32 len = sizeof(rand); |
10963 | | if (sz < len) |
10964 | | len = sz; |
10965 | | /* Get an Arduino framework random number */ |
10966 | | #if defined(ARDUINO_SAMD_NANO_33_IOT) || \ |
10967 | | defined(ARDUINO_ARCH_RP2040) |
10968 | | /* Known, tested boards working with random() */ |
10969 | | rand = random(); |
10970 | | #elif defined(ARDUINO_SAM_DUE) |
10971 | | /* See: https://github.com/avrxml/asf/tree/master/sam/utils/cmsis/sam3x/include */ |
10972 | | #if defined(__SAM3A4C__) |
10973 | | #ifndef TRNG |
10974 | | #define TRNG (0x400BC000U) |
10975 | | #endif |
10976 | | #elif defined(__SAM3A8C__) |
10977 | | #ifndef TRNG |
10978 | | #define TRNG (0x400BC000U) |
10979 | | #endif |
10980 | | #elif defined(__SAM3X4C__) |
10981 | | #ifndef TRNG |
10982 | | #define TRNG (0x400BC000U) |
10983 | | #endif |
10984 | | #elif defined(__SAM3X4E__) |
10985 | | #ifndef TRNG |
10986 | | #define TRNG (0x400BC000U) |
10987 | | #endif |
10988 | | #elif defined(__SAM3X8C__) |
10989 | | #ifndef TRNG |
10990 | | #define TRNG (0x400BC000U) |
10991 | | #endif |
10992 | | #elif defined(__SAM3X8E__) |
10993 | | /* This is the Arduino Due */ |
10994 | | #ifndef TRNG |
10995 | | #define TRNG (0x400BC000U) |
10996 | | #endif |
10997 | | #elif defined(__SAM3A8H__) |
10998 | | #ifndef TRNG |
10999 | | #define TRNG (0x400BC000U) |
11000 | | #endif |
11001 | | #else |
11002 | | #ifndef TRNG |
11003 | | #error "Unknown TRNG for this device" |
11004 | | #endif |
11005 | | #endif |
11006 | | |
11007 | | srand(analogRead(0)); |
11008 | | rand = trng_read_output_data(TRNG); |
11009 | | #elif defined(__STM32__) |
11010 | | /* TODO: confirm this is proper random number on Arduino STM32 */ |
11011 | | #warning "Not yet tested on STM32 targets" |
11012 | | rand = random(); |
11013 | | #else |
11014 | | /* TODO: Pull requests appreciated for new targets. |
11015 | | * Do *all* other Arduino boards support random()? |
11016 | | * Probably not 100%, but most will likely work: */ |
11017 | | rand = random(); |
11018 | | #endif |
11019 | | |
11020 | | XMEMCPY(output, &rand, len); |
11021 | | output += len; |
11022 | | sz -= len; |
11023 | | } |
11024 | | |
11025 | | return ret; |
11026 | | } |
11027 | | |
11028 | | #elif defined(WOLFSSL_ESPIDF) |
11029 | | |
11030 | | /* Espressif */ |
11031 | | #if defined(WOLFSSL_ESP32) || defined(WOLFSSL_ESPWROOM32SE) |
11032 | | |
11033 | | /* Espressif ESP32 */ |
11034 | | #include <esp_system.h> |
11035 | | #if defined(CONFIG_IDF_TARGET_ESP32S2) || \ |
11036 | | defined(CONFIG_IDF_TARGET_ESP32S3) |
11037 | | #include <esp_random.h> |
11038 | | #endif |
11039 | | |
11040 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11041 | | { |
11042 | | word32 rand; |
11043 | | while (sz > 0) { |
11044 | | word32 len = sizeof(rand); |
11045 | | if (sz < len) |
11046 | | len = sz; |
11047 | | /* Get one random 32-bit word from hw RNG */ |
11048 | | rand = esp_random( ); |
11049 | | XMEMCPY(output, &rand, len); |
11050 | | output += len; |
11051 | | sz -= len; |
11052 | | } |
11053 | | |
11054 | | return 0; |
11055 | | } |
11056 | | |
11057 | | #elif defined(WOLFSSL_ESP8266) |
11058 | | |
11059 | | /* Espressif ESP8266 */ |
11060 | | #include <esp_system.h> |
11061 | | |
11062 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11063 | | { |
11064 | | #if defined(DEBUG_WOLFSSL) |
11065 | | WOLFSSL_ENTER("ESP8266 Random"); |
11066 | | #endif |
11067 | | word32 rand; |
11068 | | while (sz > 0) { |
11069 | | word32 len = sizeof(rand); |
11070 | | if (sz < len) |
11071 | | len = sz; |
11072 | | /* Get one random 32-bit word from hw RNG */ |
11073 | | rand = esp_random( ); |
11074 | | XMEMCPY(output, &rand, len); |
11075 | | output += len; |
11076 | | sz -= len; |
11077 | | } |
11078 | | |
11079 | | return 0; |
11080 | | } |
11081 | | #endif /* end WOLFSSL_ESPIDF */ |
11082 | | |
11083 | | #elif defined(WOLFSSL_LINUXKM) |
11084 | | |
11085 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11086 | | { |
11087 | | (void)os; |
11088 | | int ret = WC_NO_ERR_TRACE(RNG_FAILURE_E); |
11089 | | |
11090 | | #ifdef HAVE_ENTROPY_MEMUSE |
11091 | | if (! WC_CAN_LONG_LOOP()) { |
11092 | | /* The configured primary source cannot run in this context. |
11093 | | * Defer -- BUSY_E is unconditionally retryable from a context |
11094 | | * that can -- rather than fall through to a backup source: the |
11095 | | * fall-through below is for a primary that ran and failed, not |
11096 | | * for one that was never tried, and substituting RDSEED for an |
11097 | | * untried wolfEntropy is a provenance change the caller did not |
11098 | | * ask for (and, under FIPS, a non-validated source). */ |
11099 | | return BUSY_E; |
11100 | | } |
11101 | | ret = wc_Entropy_Get(MAX_ENTROPY_BITS, output, sz); |
11102 | | if (ret == 0) |
11103 | | return 0; |
11104 | | #ifdef ENTROPY_MEMUSE_FORCE_FAILURE |
11105 | | return ret; |
11106 | | #endif |
11107 | | #endif |
11108 | | |
11109 | | #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED) |
11110 | | if (IS_INTEL_RDSEED(intel_flags)) { |
11111 | | ret = wc_GenerateSeed_IntelRD(NULL, output, sz); |
11112 | | if (ret == 0) |
11113 | | return 0; |
11114 | | #ifdef FORCE_FAILURE_RDSEED |
11115 | | return ret; |
11116 | | #endif |
11117 | | } |
11118 | | #ifdef FORCE_FAILURE_RDSEED |
11119 | | else { |
11120 | | /* Don't fall back to get_random_bytes() */ |
11121 | | return MISSING_RNG_E; |
11122 | | } |
11123 | | #endif |
11124 | | #endif /* HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */ |
11125 | | |
11126 | | #ifdef LINUXKM_LKCAPI_REGISTER_HASH_DRBG_DEFAULT |
11127 | | #if !defined(HAVE_ENTROPY_MEMUSE) && \ |
11128 | | !defined(HAVE_INTEL_RDSEED) && \ |
11129 | | !defined(HAVE_AMD_RDSEED) |
11130 | | #error LINUXKM_LKCAPI_REGISTER_HASH_DRBG_DEFAULT requires an intrinsic entropy source. |
11131 | | #else |
11132 | | return ret; |
11133 | | #endif |
11134 | | #else |
11135 | | (void)ret; |
11136 | | |
11137 | | get_random_bytes(output, sz); |
11138 | | return 0; |
11139 | | #endif |
11140 | | } |
11141 | | |
11142 | | #elif defined(WOLFSSL_BSDKM) |
11143 | | #include <sys/random.h> |
11144 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11145 | | { |
11146 | | (void)os; |
11147 | | int ret = WC_NO_ERR_TRACE(RNG_FAILURE_E); |
11148 | | |
11149 | | #ifdef HAVE_ENTROPY_MEMUSE |
11150 | | ret = wc_Entropy_Get(MAX_ENTROPY_BITS, output, sz); |
11151 | | if (ret == 0) { |
11152 | | return 0; |
11153 | | } |
11154 | | #ifdef ENTROPY_MEMUSE_FORCE_FAILURE |
11155 | | /* Don't fallback to /dev/urandom. */ |
11156 | | return ret; |
11157 | | #endif |
11158 | | #endif |
11159 | | |
11160 | | #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED) |
11161 | | if (IS_INTEL_RDSEED(intel_flags)) { |
11162 | | ret = wc_GenerateSeed_IntelRD(NULL, output, sz); |
11163 | | #ifndef FORCE_FAILURE_RDSEED |
11164 | | if (ret == 0) |
11165 | | #endif |
11166 | | { |
11167 | | return ret; |
11168 | | } |
11169 | | } |
11170 | | #ifdef FORCE_FAILURE_RDSEED |
11171 | | else { |
11172 | | /* Don't fall back to arc4random_buf() */ |
11173 | | return MISSING_RNG_E; |
11174 | | } |
11175 | | #endif |
11176 | | #endif /* HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */ |
11177 | | |
11178 | | (void)ret; |
11179 | | |
11180 | | arc4random_buf(output, sz); |
11181 | | return 0; |
11182 | | } |
11183 | | #elif defined(WOLFSSL_RENESAS_TSIP) |
11184 | | |
11185 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11186 | | { |
11187 | | (void)os; |
11188 | | return wc_tsip_GenerateRandBlock(output, sz); |
11189 | | } |
11190 | | |
11191 | | |
11192 | | #elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_TRNG) |
11193 | | #include "hal_data.h" |
11194 | | |
11195 | | #ifndef WOLFSSL_SCE_TRNG_HANDLE |
11196 | | #define WOLFSSL_SCE_TRNG_HANDLE g_sce_trng |
11197 | | #endif |
11198 | | |
11199 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11200 | | { |
11201 | | word32 ret; |
11202 | | word32 blocks; |
11203 | | word32 len = sz; |
11204 | | |
11205 | | ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->open(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl, |
11206 | | WOLFSSL_SCE_TRNG_HANDLE.p_cfg); |
11207 | | if (ret != SSP_SUCCESS && ret != SSP_ERR_CRYPTO_ALREADY_OPEN) { |
11208 | | /* error opening TRNG driver */ |
11209 | | return -1; |
11210 | | } |
11211 | | |
11212 | | blocks = sz / sizeof(word32); |
11213 | | if (blocks > 0) { |
11214 | | ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->read(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl, |
11215 | | (word32*)output, blocks); |
11216 | | if (ret != SSP_SUCCESS) { |
11217 | | return -1; |
11218 | | } |
11219 | | } |
11220 | | |
11221 | | len = len - (blocks * sizeof(word32)); |
11222 | | if (len > 0) { |
11223 | | word32 tmp; |
11224 | | |
11225 | | if (len > sizeof(word32)) { |
11226 | | return -1; |
11227 | | } |
11228 | | ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->read(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl, |
11229 | | (word32*)&tmp, 1); |
11230 | | if (ret != SSP_SUCCESS) { |
11231 | | return -1; |
11232 | | } |
11233 | | XMEMCPY(output + (blocks * sizeof(word32)), (byte*)&tmp, len); |
11234 | | } |
11235 | | |
11236 | | ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->close(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl); |
11237 | | if (ret != SSP_SUCCESS) { |
11238 | | /* error opening TRNG driver */ |
11239 | | return -1; |
11240 | | } |
11241 | | return 0; |
11242 | | } |
11243 | | #elif defined(CUSTOM_RAND_GENERATE_BLOCK) |
11244 | | /* #define CUSTOM_RAND_GENERATE_BLOCK myRngFunc |
11245 | | * extern int myRngFunc(byte* output, word32 sz); |
11246 | | */ |
11247 | | |
11248 | | #elif defined(__MICROBLAZE__) |
11249 | | #warning weak source of entropy |
11250 | | #define LPD_SCNTR_BASE_ADDRESS 0xFF250000 |
11251 | | |
11252 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11253 | | { |
11254 | | word32* cnt; |
11255 | | word32 i; |
11256 | | |
11257 | | /* using current time with srand */ |
11258 | | cnt = (word32*)LPD_SCNTR_BASE_ADDRESS; |
11259 | | srand(*cnt | *(cnt+1)); |
11260 | | |
11261 | | for (i = 0; i < sz; i++) |
11262 | | output[i] = rand(); |
11263 | | |
11264 | | (void)os; |
11265 | | return 0; |
11266 | | } |
11267 | | |
11268 | | #elif defined(WOLFSSL_ZEPHYR) |
11269 | | |
11270 | | #ifdef __has_include |
11271 | | #if __has_include(<zephyr/version.h>) |
11272 | | #include <zephyr/version.h> |
11273 | | #else |
11274 | | #include <version.h> |
11275 | | #endif |
11276 | | #else |
11277 | | #include <version.h> |
11278 | | #endif |
11279 | | |
11280 | | #include <sys/types.h> |
11281 | | |
11282 | | #if KERNEL_VERSION_NUMBER >= 0x30500 |
11283 | | #include <zephyr/random/random.h> |
11284 | | #else |
11285 | | #if KERNEL_VERSION_NUMBER >= 0x30100 |
11286 | | #include <zephyr/random/rand32.h> |
11287 | | #else |
11288 | | #include <random/rand32.h> |
11289 | | #endif |
11290 | | #endif |
11291 | | |
11292 | | #if KERNEL_VERSION_NUMBER >= 0x40300 |
11293 | | #include <time.h> |
11294 | | #elif KERNEL_VERSION_NUMBER >= 0x30100 |
11295 | | #include <zephyr/posix/time.h> |
11296 | | #else |
11297 | | #include <posix/time.h> |
11298 | | #endif |
11299 | | |
11300 | | #if KERNEL_VERSION_NUMBER >= 0x30100 |
11301 | | #include <zephyr/devicetree.h> |
11302 | | #else |
11303 | | #include <devicetree.h> |
11304 | | #endif |
11305 | | |
11306 | | #if defined(CONFIG_ENTROPY_HAS_DRIVER) && DT_HAS_CHOSEN(zephyr_entropy) |
11307 | | #if KERNEL_VERSION_NUMBER >= 0x30100 |
11308 | | #include <zephyr/device.h> |
11309 | | #include <zephyr/drivers/entropy.h> |
11310 | | #else |
11311 | | #include <device.h> |
11312 | | #include <drivers/entropy.h> |
11313 | | #endif |
11314 | | #endif |
11315 | | |
11316 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11317 | | { |
11318 | | /* Seed the DRBG straight from the hardware entropy driver when the platform |
11319 | | * exposes one (a zephyr,entropy chosen node), so wolfCrypt gets |
11320 | | * cryptographic-quality seed material instead of the general-purpose |
11321 | | * sys_rand_get(). A dead source returns an error, which makes wc_InitRng() |
11322 | | * fail (RNG_FAILURE_E) rather than yield weak output. Boards that set |
11323 | | * CONFIG_ENTROPY_HAS_DRIVER without a chosen entropy node fall back to |
11324 | | * sys_rand_get() rather than failing the build. */ |
11325 | | #if defined(CONFIG_ENTROPY_HAS_DRIVER) && DT_HAS_CHOSEN(zephyr_entropy) |
11326 | | const struct device *dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_entropy)); |
11327 | | word32 off = 0; |
11328 | | word32 rem; |
11329 | | uint16_t chunk; |
11330 | | |
11331 | | (void)os; |
11332 | | if (!device_is_ready(dev)) { |
11333 | | return RNG_FAILURE_E; |
11334 | | } |
11335 | | /* entropy_get_entropy() takes a uint16_t length; chunk the request so |
11336 | | * any word32 seed size is honored without silent truncation. */ |
11337 | | while (off < sz) { |
11338 | | rem = sz - off; |
11339 | | chunk = (rem > 0xFFFFU) ? (uint16_t)0xFFFFU : (uint16_t)rem; |
11340 | | if (entropy_get_entropy(dev, (uint8_t *)output + off, chunk) != 0) { |
11341 | | return RNG_FAILURE_E; |
11342 | | } |
11343 | | off += chunk; |
11344 | | } |
11345 | | return 0; |
11346 | | #else |
11347 | | (void)os; |
11348 | | sys_rand_get(output, sz); |
11349 | | return 0; |
11350 | | #endif |
11351 | | } |
11352 | | |
11353 | | #elif defined(WOLFSSL_TELIT_M2MB) |
11354 | | |
11355 | | #include "stdlib.h" |
11356 | | static long get_timestamp(void) { |
11357 | | long myTime = 0; |
11358 | | INT32 fd = m2mb_rtc_open("/dev/rtc0", 0); |
11359 | | if (fd >= 0) { |
11360 | | M2MB_RTC_TIMEVAL_T timeval; |
11361 | | m2mb_rtc_ioctl(fd, M2MB_RTC_IOCTL_GET_TIMEVAL, &timeval); |
11362 | | myTime = timeval.msec; |
11363 | | m2mb_rtc_close(fd); |
11364 | | } |
11365 | | return myTime; |
11366 | | } |
11367 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11368 | | { |
11369 | | int i; |
11370 | | srand(get_timestamp()); |
11371 | | for (i = 0; i < sz; i++ ) { |
11372 | | output[i] = rand() % 256; |
11373 | | if ((i % 8) == 7) { |
11374 | | srand(get_timestamp()); |
11375 | | } |
11376 | | } |
11377 | | return 0; |
11378 | | } |
11379 | | #elif defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_TRNG) |
11380 | | #include <wolfssl/wolfcrypt/port/nxp/se050_port.h> |
11381 | | |
11382 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz){ |
11383 | | (void)os; |
11384 | | |
11385 | | if (output == NULL) { |
11386 | | return BUFFER_E; |
11387 | | } |
11388 | | return se050_get_random_number(sz, output); |
11389 | | } |
11390 | | |
11391 | | #elif defined(WOLFSSL_ELS_PKC) |
11392 | | #include <wolfssl/wolfcrypt/port/nxp/els_pkc_port.h> |
11393 | | |
11394 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11395 | | { |
11396 | | (void)os; |
11397 | | |
11398 | | return wc_ElsPkc_GenerateSeed(output, sz); |
11399 | | } |
11400 | | |
11401 | | #elif defined(WOLFSSL_NXP_RNG_1) |
11402 | | #include "fsl_rng.h" |
11403 | | |
11404 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) { |
11405 | | (void)os; |
11406 | | |
11407 | | if (output == NULL) { |
11408 | | return BUFFER_E; |
11409 | | } |
11410 | | |
11411 | | if (RNG_GetRandomData(RNG, output, sz) != kStatus_Success) |
11412 | | return RNG_FAILURE_E; |
11413 | | |
11414 | | return 0; |
11415 | | } |
11416 | | |
11417 | | #elif defined(WOLFSSL_NUVOTON_TRNG) |
11418 | | /* Nuvoton NuMicro M2354 TRNG, reached through the port's hardware layer so |
11419 | | * that a TrustZone build gets it through the same veneer as everything |
11420 | | * else. See wolfcrypt/src/port/nuvoton/nuvoton_hw.c. |
11421 | | * |
11422 | | * This arm is needed even though the port is a crypto callback device: a |
11423 | | * WC_RNG created with INVALID_DEVID never reaches the callback, and this |
11424 | | * part has no /dev/random to fall back on. */ |
11425 | | #include "wolfcrypt/src/port/nuvoton/nuvoton_hw.h" |
11426 | | |
11427 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11428 | | { |
11429 | | int ret; |
11430 | | |
11431 | | (void)os; |
11432 | | |
11433 | | if (output == NULL || sz == 0) { |
11434 | | return BAD_FUNC_ARG; |
11435 | | } |
11436 | | |
11437 | | /* This is the path a WC_RNG built with INVALID_DEVID takes, so the |
11438 | | * crypto callback device may never have been registered and the CRPT |
11439 | | * clocks and the TRNG may still be down. Bring them up for the call |
11440 | | * and drop the reference afterwards; the init is reference counted, so |
11441 | | * an application that did register keeps its own. */ |
11442 | | ret = wc_nuvoton_hw_init(); |
11443 | | if (ret != 0) { |
11444 | | return ret; |
11445 | | } |
11446 | | |
11447 | | ret = wc_nuvoton_hw_trng(output, sz); |
11448 | | |
11449 | | wc_nuvoton_hw_cleanup(); |
11450 | | |
11451 | | return ret; |
11452 | | } |
11453 | | |
11454 | | #elif defined(WOLFSSL_VA416X0_TRNG) |
11455 | | /* Vorago VA416x0 hardware TRNG (an Arm CryptoCell-style entropy block). |
11456 | | * Used to seed the SP800-90A Hash-DRBG (keep HAVE_HASHDRBG enabled); the |
11457 | | * TRNG yields only ~1.25 kb/s of entropy, so the DRBG expands it. |
11458 | | * |
11459 | | * Build: define WOLFSSL_VA416X0_TRNG, and have the VA416xx SDK header |
11460 | | * "va416xx.h" on the include path (provides VOR_SYSCONFIG / VOR_TRNG and |
11461 | | * the register field macros). There is no SDK HAL driver for the TRNG, so |
11462 | | * it is accessed at the register level below. The tuning macros |
11463 | | * WOLFSSL_VA416X0_TRNG_SAMPLE_CNT, WOLFSSL_VA416X0_TRNG_MAX_RETRY and |
11464 | | * WOLFSSL_VA416X0_TRNG_TIMEOUT have overridable defaults defined below. |
11465 | | * |
11466 | | * Note: the TRNG PERIPHERAL_RESET bit is active low and must be released |
11467 | | * or every TRNG register write is silently ignored. */ |
11468 | | #include "va416xx.h" |
11469 | | |
11470 | | /* Ring-oscillator sample count (must be non-zero). May need tuning on |
11471 | | * hardware: too low results in repeated autocorrelation/CRNGT errors. */ |
11472 | | #ifndef WOLFSSL_VA416X0_TRNG_SAMPLE_CNT |
11473 | | #define WOLFSSL_VA416X0_TRNG_SAMPLE_CNT 1000 |
11474 | | #endif |
11475 | | #ifndef WOLFSSL_VA416X0_TRNG_MAX_RETRY |
11476 | | #define WOLFSSL_VA416X0_TRNG_MAX_RETRY 10 |
11477 | | #endif |
11478 | | /* Max poll iterations waiting for one 192-bit entropy block before |
11479 | | * giving up (guards against a non-responsive TRNG). */ |
11480 | | #ifndef WOLFSSL_VA416X0_TRNG_TIMEOUT |
11481 | | #define WOLFSSL_VA416X0_TRNG_TIMEOUT 1000000 |
11482 | | #endif |
11483 | | #if WOLFSSL_VA416X0_TRNG_SAMPLE_CNT == 0 |
11484 | | #error "WOLFSSL_VA416X0_TRNG_SAMPLE_CNT must be non-zero" |
11485 | | #endif |
11486 | | #if WOLFSSL_VA416X0_TRNG_TIMEOUT == 0 |
11487 | | #error "WOLFSSL_VA416X0_TRNG_TIMEOUT must be non-zero" |
11488 | | #endif |
11489 | | |
11490 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11491 | | { |
11492 | | word32 i; |
11493 | | word32 reg; |
11494 | | word32 chunk; |
11495 | | word32 timeout; |
11496 | | word32 entropy[6]; /* 192-bit entropy holding register */ |
11497 | | int retry; |
11498 | | int ret; |
11499 | | |
11500 | | (void)os; |
11501 | | |
11502 | | if (output == NULL) { |
11503 | | return BUFFER_E; |
11504 | | } |
11505 | | |
11506 | | /* serialize access to the shared TRNG hardware */ |
11507 | | ret = wolfSSL_CryptHwMutexLock(); |
11508 | | if (ret != 0) { |
11509 | | return ret; |
11510 | | } |
11511 | | |
11512 | | /* enable the TRNG peripheral clock and release it from reset (the |
11513 | | * reset bit is active low: 0 = held in reset, 1 = released) */ |
11514 | | VOR_SYSCONFIG->PERIPHERAL_CLK_ENABLE |= |
11515 | | SYSCONFIG_PERIPHERAL_CLK_ENABLE_TRNG_Msk; |
11516 | | VOR_SYSCONFIG->PERIPHERAL_RESET |= |
11517 | | SYSCONFIG_PERIPHERAL_RESET_TRNG_Msk; |
11518 | | |
11519 | | /* mask all interrupts (poll instead) and clear any stale status */ |
11520 | | VOR_TRNG->IMR = TRNG_IMR_EHR_VALID_INT_MASK_Msk | |
11521 | | TRNG_IMR_AUTOCORR_ERR_INT_MASK_Msk | |
11522 | | TRNG_IMR_CRNGT_ERR_INT_MASK_Msk | |
11523 | | TRNG_IMR_VN_ERR_INT_MASK_Msk; |
11524 | | VOR_TRNG->ICR = TRNG_ICR_EHR_VALID_Msk | TRNG_ICR_AUTOCORR_ERR_Msk | |
11525 | | TRNG_ICR_CRNGT_ERR_Msk | TRNG_ICR_VN_ERR_Msk; |
11526 | | |
11527 | | /* CONFIG = 0 sets RND_SRC_SEL = 0, which selects the ring-oscillator |
11528 | | * entropy source (per the VA416x0 reference manual) and clears the |
11529 | | * rest of the register; set the sample rate and keep the health tests |
11530 | | * enabled (no DEBUG_CONTROL bypass) */ |
11531 | | VOR_TRNG->CONFIG = 0; |
11532 | | VOR_TRNG->SAMPLE_CNT1 = WOLFSSL_VA416X0_TRNG_SAMPLE_CNT; |
11533 | | VOR_TRNG->DEBUG_CONTROL = 0; |
11534 | | |
11535 | | for (i = 0; i < sz; ) { |
11536 | | retry = 0; |
11537 | | timeout = WOLFSSL_VA416X0_TRNG_TIMEOUT; |
11538 | | |
11539 | | /* start entropy collection */ |
11540 | | VOR_TRNG->RND_SOURCE_ENABLE = |
11541 | | TRNG_RND_SOURCE_ENABLE_RND_SRC_EN_Msk; |
11542 | | |
11543 | | for (;;) { |
11544 | | reg = VOR_TRNG->ISR; |
11545 | | if ((reg & (TRNG_ISR_AUTOCORR_ERR_Msk | |
11546 | | TRNG_ISR_CRNGT_ERR_Msk | |
11547 | | TRNG_ISR_VN_ERR_Msk)) != 0) { |
11548 | | /* health-test failure: stop, then clear the error flags |
11549 | | * and any latched EHR_VALID so a stale/invalid block is |
11550 | | * not consumed on the next iteration, then re-collect */ |
11551 | | VOR_TRNG->RND_SOURCE_ENABLE = 0; |
11552 | | VOR_TRNG->ICR = TRNG_ICR_EHR_VALID_Msk | |
11553 | | TRNG_ICR_AUTOCORR_ERR_Msk | |
11554 | | TRNG_ICR_CRNGT_ERR_Msk | |
11555 | | TRNG_ICR_VN_ERR_Msk; |
11556 | | if (++retry > WOLFSSL_VA416X0_TRNG_MAX_RETRY) { |
11557 | | ForceZero(entropy, sizeof(entropy)); |
11558 | | wolfSSL_CryptHwMutexUnLock(); |
11559 | | return RNG_FAILURE_E; |
11560 | | } |
11561 | | timeout = WOLFSSL_VA416X0_TRNG_TIMEOUT; |
11562 | | VOR_TRNG->RND_SOURCE_ENABLE = |
11563 | | TRNG_RND_SOURCE_ENABLE_RND_SRC_EN_Msk; |
11564 | | continue; |
11565 | | } |
11566 | | if ((VOR_TRNG->VALID & TRNG_VALID_EHR_VALID_Msk) != 0) { |
11567 | | break; |
11568 | | } |
11569 | | if (--timeout == 0) { |
11570 | | VOR_TRNG->RND_SOURCE_ENABLE = 0; |
11571 | | ForceZero(entropy, sizeof(entropy)); |
11572 | | wolfSSL_CryptHwMutexUnLock(); |
11573 | | return RNG_FAILURE_E; |
11574 | | } |
11575 | | } |
11576 | | |
11577 | | /* read 192 bits of entropy (6 x 32-bit words) */ |
11578 | | entropy[0] = VOR_TRNG->EHR_DATA0; |
11579 | | entropy[1] = VOR_TRNG->EHR_DATA1; |
11580 | | entropy[2] = VOR_TRNG->EHR_DATA2; |
11581 | | entropy[3] = VOR_TRNG->EHR_DATA3; |
11582 | | entropy[4] = VOR_TRNG->EHR_DATA4; |
11583 | | entropy[5] = VOR_TRNG->EHR_DATA5; |
11584 | | |
11585 | | /* reading EHR_DATA clears EHR_VALID; stop the source and ack */ |
11586 | | VOR_TRNG->RND_SOURCE_ENABLE = 0; |
11587 | | VOR_TRNG->ICR = TRNG_ICR_EHR_VALID_Msk; |
11588 | | |
11589 | | chunk = sz - i; |
11590 | | if (chunk > sizeof(entropy)) { |
11591 | | chunk = sizeof(entropy); |
11592 | | } |
11593 | | XMEMCPY(&output[i], (byte*)entropy, chunk); |
11594 | | i += chunk; |
11595 | | } |
11596 | | |
11597 | | ForceZero(entropy, sizeof(entropy)); /* scrub seed material from stack */ |
11598 | | wolfSSL_CryptHwMutexUnLock(); |
11599 | | return 0; |
11600 | | } |
11601 | | |
11602 | | #elif defined(WOLFSSL_C2000_ENTROPY) |
11603 | | /* TI C2000 (C28x) oscillator-jitter entropy source. The part has no |
11604 | | * TRNG; the noise bit is the LSB of a Dual-Clock Comparator measurement, |
11605 | | * oversampled past its measured min-entropy, health-tested per SP800-90B |
11606 | | * 4.4 and SHA-256 conditioned before feeding the Hash-DRBG. |
11607 | | * |
11608 | | * Build: define WOLFSSL_C2000_ENTROPY and add |
11609 | | * wolfcrypt/src/port/ti/ti-c2000-entropy.c with the C2000Ware driverlib |
11610 | | * headers on the include path. Tuning macros, hardware overrides and the |
11611 | | * characterization: wolfssl/wolfcrypt/port/ti/ti-c2000-entropy.h and |
11612 | | * IDE/C2000/README.md. |
11613 | | * |
11614 | | * Blocking by design: ~26 ms per 32-octet chunk per source at the default |
11615 | | * window, ~100 ms for a typical seed, ~420 ms for the one-time startup |
11616 | | * test. Fine at boot, not for a control loop. */ |
11617 | | #if !defined(HAVE_HASHDRBG) |
11618 | | #error "WOLFSSL_C2000_ENTROPY expects HAVE_HASHDRBG to expand the seed" |
11619 | | #endif |
11620 | | |
11621 | | #include <wolfssl/wolfcrypt/port/ti/ti-c2000-entropy.h> |
11622 | | |
11623 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11624 | | { |
11625 | | (void)os; |
11626 | | |
11627 | | if (output == NULL) { |
11628 | | return BUFFER_E; |
11629 | | } |
11630 | | |
11631 | | return wc_c2000_GenerateSeed(output, sz); |
11632 | | } |
11633 | | |
11634 | | #elif defined(DOLPHIN_EMULATOR) || defined (WOLFSSL_NDS) |
11635 | | |
11636 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11637 | | { |
11638 | | word32 i; |
11639 | | (void)os; |
11640 | | srand(time(NULL)); |
11641 | | for (i = 0; i < sz; i++) |
11642 | | output[i] = (byte)rand(); |
11643 | | return 0; |
11644 | | } |
11645 | | #elif defined(WOLFSSL_MAXQ108X) || defined(WOLFSSL_MAXQ1065) |
11646 | | |
11647 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11648 | | { |
11649 | | (void)os; |
11650 | | |
11651 | | return maxq10xx_random(output, sz); |
11652 | | } |
11653 | | #elif defined(MAX3266X_RNG) |
11654 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11655 | | { |
11656 | | int status; |
11657 | | static int initDone = 0; |
11658 | | (void)os; |
11659 | | if (initDone == 0) { |
11660 | | status = wolfSSL_HwRngMutexLock(); |
11661 | | if (status != 0) { |
11662 | | return status; |
11663 | | } |
11664 | | if(MXC_TRNG_HealthTest() != 0) { |
11665 | | #ifdef DEBUG_WOLFSSL |
11666 | | WOLFSSL_MSG("TRNG HW Health Test Failed"); |
11667 | | #endif /* DEBUG_WOLFSSL */ |
11668 | | wolfSSL_HwRngMutexUnLock(); |
11669 | | return WC_HW_E; |
11670 | | } |
11671 | | wolfSSL_HwRngMutexUnLock(); |
11672 | | initDone = 1; |
11673 | | } |
11674 | | return wc_MXC_TRNG_Random(output, sz); |
11675 | | } |
11676 | | |
11677 | | #elif defined(CY_USING_HAL) && defined(COMPONENT_WOLFSSL) |
11678 | | |
11679 | | /* Infineon/Cypress HAL RNG implementation */ |
11680 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11681 | | { |
11682 | | cyhal_trng_t obj; |
11683 | | cy_rslt_t result; |
11684 | | uint32_t val; |
11685 | | word32 i = 0; |
11686 | | |
11687 | | (void)os; |
11688 | | |
11689 | | result = cyhal_trng_init(&obj); |
11690 | | if (result == CY_RSLT_SUCCESS) { |
11691 | | while (i < sz) { |
11692 | | /* If not aligned or there is odd/remainder add single byte */ |
11693 | | if( (i + sizeof(word32)) > sz || |
11694 | | ((wc_ptr_t)&output[i] % sizeof(word32)) != 0 |
11695 | | ) { |
11696 | | val = cyhal_trng_generate(&obj); |
11697 | | output[i++] = (byte)val; |
11698 | | } |
11699 | | else { |
11700 | | /* Use native 32 instruction */ |
11701 | | val = cyhal_trng_generate(&obj); |
11702 | | *((uint32_t*)&output[i]) = val; |
11703 | | i += sizeof(word32); |
11704 | | } |
11705 | | } |
11706 | | cyhal_trng_free(&obj); |
11707 | | } |
11708 | | return 0; |
11709 | | } |
11710 | | |
11711 | | #elif defined(WOLFSSL_SAFERTOS) || defined(WOLFSSL_LEANPSK) || \ |
11712 | | defined(WOLFSSL_IAR_ARM) || defined(WOLFSSL_MDK_ARM) || \ |
11713 | | defined(WOLFSSL_uITRON4) || defined(WOLFSSL_uTKERNEL2) || \ |
11714 | | defined(WOLFSSL_LPC43xx) || defined(NO_STM32_RNG) || \ |
11715 | | defined(MBED) || defined(WOLFSSL_EMBOS) || \ |
11716 | | defined(WOLFSSL_GENSEED_FORTEST) || defined(WOLFSSL_CHIBIOS) || \ |
11717 | | defined(WOLFSSL_CONTIKI) || defined(WOLFSSL_AZSPHERE) |
11718 | | |
11719 | | /* these platforms do not have a default random seed and |
11720 | | you'll need to implement your own wc_GenerateSeed or define via |
11721 | | CUSTOM_RAND_GENERATE_BLOCK */ |
11722 | | |
11723 | | #define USE_TEST_GENSEED |
11724 | | |
11725 | | #elif defined(NO_DEV_RANDOM) |
11726 | | |
11727 | | /* Allow bare-metal targets to use cryptoCb as seed provider */ |
11728 | | #if defined(WOLF_CRYPTO_CB) |
11729 | | |
11730 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11731 | | { |
11732 | | int ret = WC_NO_ERR_TRACE(WC_HW_E); |
11733 | | |
11734 | | #ifndef WOLF_CRYPTO_CB_FIND |
11735 | | if (os->devId != INVALID_DEVID) |
11736 | | #endif |
11737 | | { |
11738 | | ret = wc_CryptoCb_RandomSeed(os, output, sz); |
11739 | | if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) { |
11740 | | ret = WC_HW_E; |
11741 | | } |
11742 | | } |
11743 | | |
11744 | | return ret; |
11745 | | } |
11746 | | |
11747 | | #else /* defined(WOLF_CRYPTO_CB)*/ |
11748 | | |
11749 | | #error "you need to write an os specific wc_GenerateSeed() here" |
11750 | | |
11751 | | /* |
11752 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11753 | | { |
11754 | | return 0; |
11755 | | } |
11756 | | */ |
11757 | | |
11758 | | #endif /* !defined(WOLF_CRYPTO_CB) */ |
11759 | | |
11760 | | #else |
11761 | | |
11762 | | /* may block */ |
11763 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
11764 | 62.2k | { |
11765 | 62.2k | int ret = 0; |
11766 | | /* Same condition as the seed-device block below: with |
11767 | | * ENTROPY_MEMUSE_FORCE_FAILURE the code that uses these is compiled out, |
11768 | | * and declaring them anyway is an unused-variable error under -Werror. */ |
11769 | | #if defined(WC_RNG_SEED_DEVICE) && (!defined(HAVE_ENTROPY_MEMUSE) || \ |
11770 | | !defined(ENTROPY_MEMUSE_FORCE_FAILURE)) |
11771 | | byte* devOut; |
11772 | | word32 devSz; |
11773 | | int devFd; |
11774 | | int devLen; |
11775 | | #endif |
11776 | | |
11777 | | /* Validate output before any entropy backend dereferences it: some |
11778 | | * (e.g. glibc's vDSO getrandom()) fault on a NULL buffer rather than |
11779 | | * returning an error. Mirrors wc_RNG_GenerateBlock's NULL check. */ |
11780 | 62.2k | if (os == NULL || output == NULL) { |
11781 | 0 | return BAD_FUNC_ARG; |
11782 | 0 | } |
11783 | | |
11784 | 62.2k | #ifdef WOLF_CRYPTO_CB |
11785 | 62.2k | #ifndef WOLF_CRYPTO_CB_FIND |
11786 | 62.2k | if (os->devId != INVALID_DEVID) |
11787 | 12 | #endif |
11788 | 12 | { |
11789 | 12 | ret = wc_CryptoCb_RandomSeed(os, output, sz); |
11790 | 12 | if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) |
11791 | 12 | return ret; |
11792 | | /* fall-through when unavailable */ |
11793 | 0 | ret = 0; /* reset error code */ |
11794 | 0 | } |
11795 | 62.2k | #endif |
11796 | | |
11797 | | #ifdef HAVE_ENTROPY_MEMUSE |
11798 | | ret = wc_Entropy_Get(MAX_ENTROPY_BITS, output, sz); |
11799 | | if (ret == 0) { |
11800 | | /* success, we're done */ |
11801 | | return ret; |
11802 | | } |
11803 | | #ifdef ENTROPY_MEMUSE_FORCE_FAILURE |
11804 | | /* Don't fall back to /dev/urandom. */ |
11805 | | return ret; |
11806 | | #else |
11807 | | /* Reset error and fall back to using /dev/urandom. */ |
11808 | | ret = 0; |
11809 | | #endif |
11810 | | #endif |
11811 | | |
11812 | 62.2k | #if !defined(HAVE_ENTROPY_MEMUSE) || !defined(ENTROPY_MEMUSE_FORCE_FAILURE) |
11813 | | |
11814 | | #ifdef WC_RNG_SEED_DEVICE |
11815 | | /* Nominated entropy source, usually a hardware RNG. Best effort: on |
11816 | | * any failure fall through to the default sources below. Those refill |
11817 | | * the whole request from the start, so bytes a partial read left in |
11818 | | * output are overwritten rather than mixed in. */ |
11819 | | devOut = output; |
11820 | | devSz = sz; |
11821 | | devFd = wc_open_cloexec(WC_RNG_SEED_DEVICE, O_RDONLY); |
11822 | | if (devFd != XBADFD) { |
11823 | | while (devSz > 0) { |
11824 | | errno = 0; |
11825 | | devLen = (int)read(devFd, devOut, devSz); |
11826 | | if (devLen < 0) { |
11827 | | if (errno == EINTR) |
11828 | | continue; /* interrupted, read again */ |
11829 | | break; |
11830 | | } |
11831 | | if (devLen == 0) |
11832 | | break; /* at EOF, will never fill the request */ |
11833 | | |
11834 | | devSz -= (word32)devLen; |
11835 | | devOut += devLen; |
11836 | | } |
11837 | | close(devFd); |
11838 | | } |
11839 | | #if defined(DEBUG_WOLFSSL) |
11840 | | if (devSz == 0) |
11841 | | WOLFSSL_MSG("seeded from WC_RNG_SEED_DEVICE."); |
11842 | | else |
11843 | | WOLFSSL_MSG("WC_RNG_SEED_DEVICE unusable, using default."); |
11844 | | #endif /* DEBUG_WOLFSSL */ |
11845 | | if (devSz == 0) { |
11846 | | /* success, we're done */ |
11847 | | return 0; |
11848 | | } |
11849 | | #endif /* WC_RNG_SEED_DEVICE */ |
11850 | | |
11851 | | #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED) |
11852 | | if (IS_INTEL_RDSEED(intel_flags)) { |
11853 | | ret = wc_GenerateSeed_IntelRD(NULL, output, sz); |
11854 | | if (ret == 0) { |
11855 | | /* success, we're done */ |
11856 | | return ret; |
11857 | | } |
11858 | | #ifdef FORCE_FAILURE_RDSEED |
11859 | | /* Don't fall back to /dev/urandom. */ |
11860 | | return ret; |
11861 | | #else |
11862 | | /* Reset error and fall back to using /dev/urandom. */ |
11863 | | ret = 0; |
11864 | | #endif |
11865 | | } |
11866 | | #ifdef FORCE_FAILURE_RDSEED |
11867 | | else { |
11868 | | /* Don't fall back to /dev/urandom */ |
11869 | | return MISSING_RNG_E; |
11870 | | } |
11871 | | #endif |
11872 | | #endif /* HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */ |
11873 | | |
11874 | 62.2k | #if (!defined(HAVE_INTEL_RDSEED) && !defined(HAVE_AMD_RDSEED)) || \ |
11875 | 62.2k | !defined(FORCE_FAILURE_RDSEED) |
11876 | | |
11877 | 62.2k | #if defined(WOLFSSL_GETRANDOM) || defined(HAVE_GETRANDOM) |
11878 | 62.2k | { |
11879 | 62.2k | word32 grSz = sz; |
11880 | 62.2k | byte* grOutput = output; |
11881 | | |
11882 | 124k | while (grSz) { |
11883 | 62.2k | ssize_t len; |
11884 | | |
11885 | 62.2k | errno = 0; |
11886 | 62.2k | len = getrandom(grOutput, grSz, 0); |
11887 | 62.2k | if (len == -1) { |
11888 | 0 | if (errno == EINTR) { |
11889 | | /* interrupted, call getrandom again */ |
11890 | 0 | continue; |
11891 | 0 | } |
11892 | 0 | else { |
11893 | 0 | ret = READ_RAN_E; |
11894 | 0 | } |
11895 | 0 | break; |
11896 | 0 | } |
11897 | | |
11898 | 62.2k | grSz -= (word32)len; |
11899 | 62.2k | grOutput += len; |
11900 | 62.2k | } |
11901 | 62.2k | if (ret == 0) |
11902 | 62.2k | return ret; |
11903 | | #ifdef FORCE_FAILURE_GETRANDOM |
11904 | | /* don't fall back to /dev/urandom */ |
11905 | | return ret; |
11906 | | #elif !defined(NO_FILESYSTEM) |
11907 | | /* reset error and fall back to using /dev/urandom if filesystem |
11908 | | * support is compiled in */ |
11909 | 0 | ret = 0; |
11910 | 0 | #endif |
11911 | 0 | } |
11912 | 0 | #endif |
11913 | | |
11914 | 0 | #ifndef NO_FILESYSTEM |
11915 | | #ifdef WOLFSSL_KEEP_RNG_SEED_FD_OPEN |
11916 | | if (!os->seedFdOpen) |
11917 | | { |
11918 | | os->fd = XBADFD; |
11919 | | #ifndef NO_DEV_URANDOM /* way to disable use of /dev/urandom */ |
11920 | | if (os->fd == XBADFD) { |
11921 | | os->fd = wc_open_cloexec("/dev/urandom", O_RDONLY); |
11922 | | #if defined(DEBUG_WOLFSSL) |
11923 | | if (os->fd != XBADFD) |
11924 | | WOLFSSL_MSG("opened /dev/urandom."); |
11925 | | #endif /* DEBUG_WOLFSSL */ |
11926 | | } |
11927 | | #endif /* NO_DEV_URANDOM */ |
11928 | | if (os->fd == XBADFD) { |
11929 | | /* may still have /dev/random */ |
11930 | | os->fd = wc_open_cloexec("/dev/random", O_RDONLY); |
11931 | | #if defined(DEBUG_WOLFSSL) |
11932 | | if (os->fd != XBADFD) |
11933 | | WOLFSSL_MSG("opened /dev/random."); |
11934 | | #endif /* DEBUG_WOLFSSL */ |
11935 | | if (os->fd == XBADFD) |
11936 | | return OPEN_RAN_E; |
11937 | | os->keepSeedFdOpen = 0; |
11938 | | os->seedFdOpen = 1; |
11939 | | } |
11940 | | else { |
11941 | | os->keepSeedFdOpen = 1; |
11942 | | os->seedFdOpen = 1; |
11943 | | } |
11944 | | } |
11945 | | #else /* WOLFSSL_KEEP_RNG_SEED_FD_OPEN */ |
11946 | 0 | os->fd = XBADFD; |
11947 | 0 | #ifndef NO_DEV_URANDOM /* way to disable use of /dev/urandom */ |
11948 | 0 | if (os->fd == XBADFD) { |
11949 | 0 | os->fd = wc_open_cloexec("/dev/urandom", O_RDONLY); |
11950 | | #if defined(DEBUG_WOLFSSL) |
11951 | | if (os->fd != XBADFD) |
11952 | | WOLFSSL_MSG("opened /dev/urandom."); |
11953 | | #endif /* DEBUG_WOLFSSL */ |
11954 | 0 | } |
11955 | 0 | #endif /* !NO_DEV_URANDOM */ |
11956 | 0 | if (os->fd == XBADFD) { |
11957 | | /* may still have /dev/random */ |
11958 | 0 | os->fd = wc_open_cloexec("/dev/random", O_RDONLY); |
11959 | | #if defined(DEBUG_WOLFSSL) |
11960 | | if (os->fd != XBADFD) |
11961 | | WOLFSSL_MSG("opened /dev/random."); |
11962 | | #endif /* DEBUG_WOLFSSL */ |
11963 | 0 | if (os->fd == XBADFD) |
11964 | 0 | return OPEN_RAN_E; |
11965 | 0 | } |
11966 | 0 | #endif /* WOLFSSL_KEEP_RNG_SEED_FD_OPEN */ |
11967 | | #if defined(DEBUG_WOLFSSL) |
11968 | | WOLFSSL_MSG("rnd read..."); |
11969 | | #endif /* DEBUG_WOLFSSL */ |
11970 | 0 | while (sz) { |
11971 | 0 | int len = (int)read(os->fd, output, sz); |
11972 | | /* EOF never fills the request, don't retry forever */ |
11973 | 0 | if (len <= 0) { |
11974 | 0 | ret = READ_RAN_E; |
11975 | 0 | break; |
11976 | 0 | } |
11977 | | |
11978 | 0 | sz -= (word32)len; |
11979 | 0 | output += len; |
11980 | |
|
11981 | 0 | if (sz) { |
11982 | | #if defined(BLOCKING) || defined(WC_RNG_BLOCKING) |
11983 | | sleep(0); /* context switch */ |
11984 | | #else |
11985 | 0 | ret = RAN_BLOCK_E; |
11986 | 0 | break; |
11987 | 0 | #endif /* BLOCKING || WC_RNG_BLOCKING */ |
11988 | 0 | } |
11989 | 0 | } |
11990 | | #ifdef WOLFSSL_KEEP_RNG_SEED_FD_OPEN |
11991 | | if (!os->keepSeedFdOpen && os->seedFdOpen) |
11992 | | { |
11993 | | close(os->fd); |
11994 | | os->fd = -1; |
11995 | | os->seedFdOpen = 0; |
11996 | | } |
11997 | | #else |
11998 | 0 | close(os->fd); |
11999 | 0 | #endif /* WOLFSSL_KEEP_RNG_SEED_FD_OPEN */ |
12000 | | #else /* NO_FILESYSTEM */ |
12001 | | (void)output; |
12002 | | (void)sz; |
12003 | | ret = NOT_COMPILED_IN; |
12004 | | #endif /* NO_FILESYSTEM */ |
12005 | |
|
12006 | 0 | return ret; |
12007 | |
|
12008 | 0 | #endif /* (!HAVE_INTEL_RDSEED && !HAVE_AMD_RDSEED) || !FORCE_FAILURE_RDSEED */ |
12009 | |
|
12010 | 0 | #endif /*!HAVE_ENTROPY_MEMUSE || !ENTROPY_MEMUSE_FORCE_FAILURE */ |
12011 | |
|
12012 | 0 | } |
12013 | | |
12014 | | #endif |
12015 | | |
12016 | | #ifdef USE_TEST_GENSEED |
12017 | | #if !defined(_MSC_VER) && !defined(__TASKING__) |
12018 | | #warning "write a real random seed!!!!, just for testing now" |
12019 | | #else |
12020 | | #pragma message("Warning: write a real random seed!!!!, just for testing now") |
12021 | | #endif |
12022 | | int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) |
12023 | | { |
12024 | | word32 i; |
12025 | | /* WC_OCTET, not (byte): the cast does not truncate where |
12026 | | * CHAR_BIT != 8, so sz > 256 would emit values above 0xFF. */ |
12027 | | for (i = 0; i < sz; i++ ) |
12028 | | output[i] = WC_OCTET(i); |
12029 | | |
12030 | | (void)os; |
12031 | | |
12032 | | return 0; |
12033 | | } |
12034 | | #endif |
12035 | | /* End wc_GenerateSeed */ |
12036 | | |
12037 | | #if defined(CUSTOM_RAND_GENERATE_BLOCK) && defined(WOLFSSL_KCAPI) |
12038 | | #include <fcntl.h> |
12039 | | int wc_hwrng_generate_block(byte *output, word32 sz) |
12040 | | { |
12041 | | int fd; |
12042 | | int ret = 0; |
12043 | | fd = wc_open_cloexec("/dev/hwrng", O_RDONLY); |
12044 | | if (fd == -1) |
12045 | | return OPEN_RAN_E; |
12046 | | while(sz) |
12047 | | { |
12048 | | int len = (int)read(fd, output, sz); |
12049 | | if (len == -1) |
12050 | | { |
12051 | | ret = READ_RAN_E; |
12052 | | break; |
12053 | | } |
12054 | | sz -= len; |
12055 | | output += len; |
12056 | | } |
12057 | | close(fd); |
12058 | | return ret; |
12059 | | } |
12060 | | #endif |
12061 | | |
12062 | | #ifdef WC_RNG_DEBUG_STATS |
12063 | | |
12064 | | /* Note on WC_RNG_DEBUG_STATS collection points: |
12065 | | * |
12066 | | * Placement doctrine: each counter is maintained at the single funnel that |
12067 | | * owns the distinction it records -- |
12068 | | * |
12069 | | * - reseed counts in Hash_DRBG_Reseed() (every reseed flavor routes |
12070 | | * through it: interval backstop, Reseed_Now, RBGC, banked redemption); |
12071 | | * - request/byte counts in the DRBG arm of wc_RNG_GenerateBlock() |
12072 | | * (hardware-offload arms -- RDRAND, Silabs, async, cryptocb, custom -- |
12073 | | * are deliberately uncounted: these are DRBG-facility statistics); |
12074 | | * - banked-seed redemption provenance in wc_RNG_DRBG_NextSeedNow_Nonce(); |
12075 | | * - seed health failures at the two sites that observe them per-instance |
12076 | | * (PollAndReSeed(), NextSeedGenerate); |
12077 | | * - chain-provenance bytes (RBGC_bytes_produced: output generated while |
12078 | | * the instance's own RBGCStratum > 0) in the same generate funnel; |
12079 | | * - pool byte accounting in wc_RNG_Pool_Extract(), under the consumer's |
12080 | | * instance lock: bytes produced by reading from the pool, and bytes |
12081 | | * requested but not fulfilled (empty-pool and partial-serve shortfall), |
12082 | | * so requested == produced + missed on the capacity paths. The |
12083 | | * failed-DRBG burn path deliberately counts nothing: it is a failure |
12084 | | * event (visible via rng->status), not a capacity signal. |
12085 | | * |
12086 | | * Counters are plain (non-atomic) adds/increments, and update under the owner's |
12087 | | * exclusive access (the lock contract shared by all WC_RNG operations) except |
12088 | | * where labeled racy: those are unreliable under concurrency, by design. Every |
12089 | | * site carries its own #ifdef WC_RNG_DEBUG_STATS gate so the facility is |
12090 | | * removable outright with unifdef. |
12091 | | */ |
12092 | | |
12093 | | WOLFSSL_API int wc_rng_debug_stats_snap(struct wc_rng_debug_stats_snapshot *s, |
12094 | | const WC_RNG *rng) |
12095 | | { |
12096 | | if ((s == NULL) || (rng == NULL)) |
12097 | | return BAD_FUNC_ARG; |
12098 | | |
12099 | | s->_stats_total_bytes_requested = rng->_stats_total_bytes_requested; |
12100 | | s->_stats_total_bytes_produced = rng->_stats_total_bytes_produced; |
12101 | | s->_stats_total_requests = rng->_stats_total_requests; |
12102 | | s->_stats_reseeds = rng->_stats_reseeds; |
12103 | | s->_stats_stirs = rng->_stats_stirs; |
12104 | | s->_stats_seed_failures = rng->_stats_seed_failures; |
12105 | | s->_stats_locks_taken = rng->_stats_locks_taken; |
12106 | | s->_stats_locks_released = rng->_stats_locks_released; |
12107 | | s->_stats_locks_refused = rng->_stats_locks_refused; |
12108 | | #ifdef WC_RNG_HAVE_RBGC |
12109 | | s->_stats_RBGC_bytes_produced = rng->_stats_RBGC_bytes_produced; |
12110 | | s->_stats_RBGC_reseeds = rng->_stats_RBGC_reseeds; |
12111 | | #endif |
12112 | | #ifdef WC_RNG_HAVE_POOL |
12113 | | s->_stats_pool_bytes_produced = rng->_stats_pool_bytes_produced; |
12114 | | s->_stats_pool_bytes_missed = rng->_stats_pool_bytes_missed; |
12115 | | #endif |
12116 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
12117 | | s->_stats_nextseedsprimary_redeemed = rng->_stats_nextseedsprimary_redeemed; |
12118 | | s->_stats_nextseedsRBGC_redeemed = rng->_stats_nextseedsRBGC_redeemed; |
12119 | | s->_stats_nextstirs_redeemed = rng->_stats_nextstirs_redeemed; |
12120 | | s->_stats_nextseedsbanked = rng->_stats_nextseedsbanked; |
12121 | | s->_stats_nextstirs_banked = rng->_stats_nextstirs_banked; |
12122 | | #endif |
12123 | | |
12124 | | return 0; |
12125 | | } |
12126 | | |
12127 | | WOLFSSL_API int wc_rng_debug_stats_restore( |
12128 | | const struct wc_rng_debug_stats_snapshot *s, |
12129 | | WC_RNG *rng) |
12130 | | { |
12131 | | if ((s == NULL) || (rng == NULL)) |
12132 | | return BAD_FUNC_ARG; |
12133 | | |
12134 | | rng->_stats_total_bytes_requested = s->_stats_total_bytes_requested; |
12135 | | rng->_stats_total_bytes_produced = s->_stats_total_bytes_produced; |
12136 | | rng->_stats_total_requests = s->_stats_total_requests; |
12137 | | rng->_stats_reseeds = s->_stats_reseeds; |
12138 | | rng->_stats_stirs = s->_stats_stirs; |
12139 | | rng->_stats_seed_failures = s->_stats_seed_failures; |
12140 | | rng->_stats_locks_taken = s->_stats_locks_taken; |
12141 | | rng->_stats_locks_released = s->_stats_locks_released; |
12142 | | rng->_stats_locks_refused = s->_stats_locks_refused; |
12143 | | #ifdef WC_RNG_HAVE_RBGC |
12144 | | rng->_stats_RBGC_bytes_produced = s->_stats_RBGC_bytes_produced; |
12145 | | rng->_stats_RBGC_reseeds = s->_stats_RBGC_reseeds; |
12146 | | #endif |
12147 | | #ifdef WC_RNG_HAVE_POOL |
12148 | | rng->_stats_pool_bytes_produced = s->_stats_pool_bytes_produced; |
12149 | | rng->_stats_pool_bytes_missed = s->_stats_pool_bytes_missed; |
12150 | | #endif |
12151 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
12152 | | rng->_stats_nextseedsprimary_redeemed = s->_stats_nextseedsprimary_redeemed; |
12153 | | rng->_stats_nextseedsRBGC_redeemed = s->_stats_nextseedsRBGC_redeemed; |
12154 | | rng->_stats_nextstirs_redeemed = s->_stats_nextstirs_redeemed; |
12155 | | rng->_stats_nextseedsbanked = s->_stats_nextseedsbanked; |
12156 | | rng->_stats_nextstirs_banked = s->_stats_nextstirs_banked; |
12157 | | #endif |
12158 | | |
12159 | | return 0; |
12160 | | } |
12161 | | |
12162 | | WOLFSSL_API int wc_rng_debug_stats_sum(struct wc_rng_debug_stats_snapshot *s, |
12163 | | const WC_RNG *rng) |
12164 | | { |
12165 | | if ((s == NULL) || (rng == NULL)) |
12166 | | return BAD_FUNC_ARG; |
12167 | | |
12168 | | s->_stats_total_bytes_requested += rng->_stats_total_bytes_requested; |
12169 | | s->_stats_total_bytes_produced += rng->_stats_total_bytes_produced; |
12170 | | s->_stats_total_requests += rng->_stats_total_requests; |
12171 | | s->_stats_reseeds += rng->_stats_reseeds; |
12172 | | s->_stats_stirs += rng->_stats_stirs; |
12173 | | s->_stats_seed_failures += rng->_stats_seed_failures; |
12174 | | s->_stats_locks_taken += rng->_stats_locks_taken; |
12175 | | s->_stats_locks_released += rng->_stats_locks_released; |
12176 | | s->_stats_locks_refused += rng->_stats_locks_refused; |
12177 | | #ifdef WC_RNG_HAVE_RBGC |
12178 | | s->_stats_RBGC_bytes_produced += rng->_stats_RBGC_bytes_produced; |
12179 | | s->_stats_RBGC_reseeds += rng->_stats_RBGC_reseeds; |
12180 | | #endif |
12181 | | #ifdef WC_RNG_HAVE_POOL |
12182 | | s->_stats_pool_bytes_produced += rng->_stats_pool_bytes_produced; |
12183 | | s->_stats_pool_bytes_missed += rng->_stats_pool_bytes_missed; |
12184 | | #endif |
12185 | | #ifdef WC_RNG_HAVE_NEXT_SEED |
12186 | | s->_stats_nextseedsprimary_redeemed += rng->_stats_nextseedsprimary_redeemed; |
12187 | | s->_stats_nextseedsRBGC_redeemed += rng->_stats_nextseedsRBGC_redeemed; |
12188 | | s->_stats_nextstirs_redeemed += rng->_stats_nextstirs_redeemed; |
12189 | | s->_stats_nextseedsbanked += rng->_stats_nextseedsbanked; |
12190 | | s->_stats_nextstirs_banked += rng->_stats_nextstirs_banked; |
12191 | | #endif |
12192 | | |
12193 | | return 0; |
12194 | | } |
12195 | | |
12196 | | #endif /* WC_RNG_DEBUG_STATS */ |
12197 | | |
12198 | | |
12199 | | #endif /* WC_NO_RNG */ |