s_client.pod: Fix grammar in NOTES section.
[openssl.git] / test / drbgtest.c
1 /*
2  * Copyright 2011-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <string.h>
11 #include "internal/nelem.h"
12 #include <openssl/crypto.h>
13 #include <openssl/err.h>
14 #include <openssl/rand.h>
15 #include <openssl/obj_mac.h>
16 #include <openssl/evp.h>
17 #include <openssl/aes.h>
18 #include "../crypto/rand/rand_local.h"
19 #include "../include/crypto/rand.h"
20 #include "../include/crypto/evp.h"
21 #include "../providers/implementations/rands/drbg_local.h"
22 #include "../crypto/evp/evp_local.h"
23
24 #if defined(_WIN32)
25 # include <windows.h>
26 #endif
27
28 #if defined(__TANDEM)
29 # if defined(OPENSSL_TANDEM_FLOSS)
30 #  include <floss.h(floss_fork)>
31 # endif
32 #endif
33
34 #if defined(OPENSSL_SYS_UNIX)
35 # include <sys/types.h>
36 # include <sys/wait.h>
37 # include <unistd.h>
38 #endif
39
40 #include "testutil.h"
41 #include "drbgtest.h"
42
43 /*
44  * DRBG generate wrappers
45  */
46 static int gen_bytes(EVP_RAND_CTX *drbg, unsigned char *buf, int num)
47 {
48     const RAND_METHOD *meth = RAND_get_rand_method();
49
50     if (meth != NULL && meth != RAND_OpenSSL()) {
51         if (meth->bytes != NULL)
52             return meth->bytes(buf, num);
53         return -1;
54     }
55
56     if (drbg != NULL)
57         return EVP_RAND_generate(drbg, buf, num, 0, 0, NULL, 0);
58     return 0;
59 }
60
61 static int rand_bytes(unsigned char *buf, int num)
62 {
63     return gen_bytes(RAND_get0_public(NULL), buf, num);
64 }
65
66 static int rand_priv_bytes(unsigned char *buf, int num)
67 {
68     return gen_bytes(RAND_get0_private(NULL), buf, num);
69 }
70
71
72 /* size of random output generated in test_drbg_reseed() */
73 #define RANDOM_SIZE 16
74
75 /*
76  * DRBG query functions
77  */
78 static int state(EVP_RAND_CTX *drbg)
79 {
80     return EVP_RAND_state(drbg);
81 }
82
83 static unsigned int query_rand_uint(EVP_RAND_CTX *drbg, const char *name)
84 {
85     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
86     unsigned int n;
87
88     *params = OSSL_PARAM_construct_uint(name, &n);
89     if (EVP_RAND_get_ctx_params(drbg, params))
90         return n;
91     return 0;
92 }
93
94 #define DRBG_UINT(name)                                 \
95     static unsigned int name(EVP_RAND_CTX *drbg)        \
96     {                                                   \
97         return query_rand_uint(drbg, #name);            \
98     }
99 DRBG_UINT(reseed_counter)
100
101 static PROV_DRBG *prov_rand(EVP_RAND_CTX *drbg)
102 {
103     return (PROV_DRBG *)drbg->data;
104 }
105
106 static void set_reseed_counter(EVP_RAND_CTX *drbg, unsigned int n)
107 {
108     PROV_DRBG *p = prov_rand(drbg);
109
110     p->reseed_counter = n;
111 }
112
113 static void inc_reseed_counter(EVP_RAND_CTX *drbg)
114 {
115     set_reseed_counter(drbg, reseed_counter(drbg) + 1);
116 }
117
118 static time_t reseed_time(EVP_RAND_CTX *drbg)
119 {
120     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
121     time_t t;
122
123     *params = OSSL_PARAM_construct_time_t(OSSL_DRBG_PARAM_RESEED_TIME, &t);
124     if (EVP_RAND_get_ctx_params(drbg, params))
125         return t;
126     return 0;
127 }
128
129 /*
130  * When building the FIPS module, it isn't possible to disable the continuous
131  * RNG tests.  Tests that require this are skipped.
132  */
133 static int crngt_skip(void)
134 {
135 #ifdef FIPS_MODULE
136     return 1;
137 #else
138     return 0;
139 #endif
140 }
141
142  /*
143  * Disable CRNG testing if it is enabled.
144  * This stub remains to indicate the calling locations where it is necessary.
145  * Once the RNG infrastructure is able to disable these tests, it should be
146  * reconstituted.
147  */
148 static int disable_crngt(EVP_RAND_CTX *drbg)
149 {
150     return 1;
151 }
152
153 /*
154  * Generates random output using rand_bytes() and rand_priv_bytes()
155  * and checks whether the three shared DRBGs were reseeded as
156  * expected.
157  *
158  * |expect_success|: expected outcome (as reported by RAND_status())
159  * |primary|, |public|, |private|: pointers to the three shared DRBGs
160  * |public_random|, |private_random|: generated random output
161  * |expect_xxx_reseed| =
162  *       1:  it is expected that the specified DRBG is reseeded
163  *       0:  it is expected that the specified DRBG is not reseeded
164  *      -1:  don't check whether the specified DRBG was reseeded or not
165  * |reseed_when|: if nonzero, used instead of time(NULL) to set the
166  *                |before_reseed| time.
167  */
168 static int test_drbg_reseed(int expect_success,
169                             EVP_RAND_CTX *primary,
170                             EVP_RAND_CTX *public,
171                             EVP_RAND_CTX *private,
172                             unsigned char *public_random,
173                             unsigned char *private_random,
174                             int expect_primary_reseed,
175                             int expect_public_reseed,
176                             int expect_private_reseed,
177                             time_t reseed_when
178                            )
179 {
180     time_t before_reseed, after_reseed;
181     int expected_state = (expect_success ? DRBG_READY : DRBG_ERROR);
182     unsigned int primary_reseed, public_reseed, private_reseed;
183     unsigned char dummy[RANDOM_SIZE];
184
185     if (public_random == NULL)
186         public_random = dummy;
187
188     if (private_random == NULL)
189         private_random = dummy;
190
191     /*
192      * step 1: check preconditions
193      */
194
195     /* Test whether seed propagation is enabled */
196     if (!TEST_int_ne(primary_reseed = reseed_counter(primary), 0)
197         || !TEST_int_ne(public_reseed = reseed_counter(public), 0)
198         || !TEST_int_ne(private_reseed = reseed_counter(private), 0))
199         return 0;
200
201     /*
202      * step 2: generate random output
203      */
204
205     if (reseed_when == 0)
206         reseed_when = time(NULL);
207
208     /* Generate random output from the public and private DRBG */
209     before_reseed = expect_primary_reseed == 1 ? reseed_when : 0;
210     if (!TEST_int_eq(rand_bytes((unsigned char*)public_random,
211                                 RANDOM_SIZE), expect_success)
212         || !TEST_int_eq(rand_priv_bytes((unsigned char*) private_random,
213                                         RANDOM_SIZE), expect_success))
214         return 0;
215     after_reseed = time(NULL);
216
217
218     /*
219      * step 3: check postconditions
220      */
221
222     /* Test whether reseeding succeeded as expected */
223     if (!TEST_int_eq(state(primary), expected_state)
224         || !TEST_int_eq(state(public), expected_state)
225         || !TEST_int_eq(state(private), expected_state))
226         return 0;
227
228     if (expect_primary_reseed >= 0) {
229         /* Test whether primary DRBG was reseeded as expected */
230         if (!TEST_int_ge(reseed_counter(primary), primary_reseed))
231             return 0;
232     }
233
234     if (expect_public_reseed >= 0) {
235         /* Test whether public DRBG was reseeded as expected */
236         if (!TEST_int_ge(reseed_counter(public), public_reseed)
237                 || !TEST_uint_ge(reseed_counter(public),
238                                  reseed_counter(primary)))
239             return 0;
240     }
241
242     if (expect_private_reseed >= 0) {
243         /* Test whether public DRBG was reseeded as expected */
244         if (!TEST_int_ge(reseed_counter(private), private_reseed)
245                 || !TEST_uint_ge(reseed_counter(private),
246                                  reseed_counter(primary)))
247             return 0;
248     }
249
250     if (expect_success == 1) {
251         /* Test whether reseed time of primary DRBG is set correctly */
252         if (!TEST_time_t_le(before_reseed, reseed_time(primary))
253             || !TEST_time_t_le(reseed_time(primary), after_reseed))
254             return 0;
255
256         /* Test whether reseed times of child DRBGs are synchronized with primary */
257         if (!TEST_time_t_ge(reseed_time(public), reseed_time(primary))
258             || !TEST_time_t_ge(reseed_time(private), reseed_time(primary)))
259             return 0;
260     } else {
261         ERR_clear_error();
262     }
263
264     return 1;
265 }
266
267
268 #if defined(OPENSSL_SYS_UNIX)
269 /* number of children to fork */
270 #define DRBG_FORK_COUNT 9
271 /* two results per child, two for the parent */
272 #define DRBG_FORK_RESULT_COUNT (2 * (DRBG_FORK_COUNT + 1))
273
274 typedef struct drbg_fork_result_st {
275
276     unsigned char random[RANDOM_SIZE]; /* random output */
277
278     int pindex;               /* process index (0: parent, 1,2,3...: children)*/
279     pid_t pid;                /* process id */
280     int private;              /* true if the private drbg was used */
281     char name[10];            /* 'parent' resp. 'child 1', 'child 2', ... */
282 } drbg_fork_result;
283
284 /*
285  * Sort the drbg_fork_result entries in lexicographical order
286  *
287  * This simplifies finding duplicate random output and makes
288  * the printout in case of an error more readable.
289  */
290 static int compare_drbg_fork_result(const void * left, const void * right)
291 {
292     int result;
293     const drbg_fork_result *l = left;
294     const drbg_fork_result *r = right;
295
296     /* separate public and private results */
297     result = l->private - r->private;
298
299     if (result == 0)
300         result = memcmp(l->random, r->random, RANDOM_SIZE);
301
302     if (result == 0)
303         result = l->pindex - r->pindex;
304
305     return result;
306 }
307
308 /*
309  * Sort two-byte chunks of random data
310  *
311  * Used for finding collisions in two-byte chunks
312  */
313 static int compare_rand_chunk(const void * left, const void * right)
314 {
315     return memcmp(left, right, 2);
316 }
317
318 /*
319  * Test whether primary, public and private DRBG are reseeded
320  * in the child after forking the process. Collect the random
321  * output of the public and private DRBG and send it back to
322  * the parent process.
323  */
324 static int test_drbg_reseed_in_child(EVP_RAND_CTX *primary,
325                                      EVP_RAND_CTX *public,
326                                      EVP_RAND_CTX *private,
327                                      drbg_fork_result result[2])
328 {
329     int rv = 0, status;
330     int fd[2];
331     pid_t pid;
332     unsigned char random[2 * RANDOM_SIZE];
333
334     if (!TEST_int_ge(pipe(fd), 0))
335         return 0;
336
337     if (!TEST_int_ge(pid = fork(), 0)) {
338         close(fd[0]);
339         close(fd[1]);
340         return 0;
341     } else if (pid > 0) {
342
343         /* I'm the parent; close the write end */
344         close(fd[1]);
345
346         /* wait for children to terminate and collect their random output */
347         if (TEST_int_eq(waitpid(pid, &status, 0), pid)
348             && TEST_int_eq(status, 0)
349             && TEST_true(read(fd[0], &random[0], sizeof(random))
350                           == sizeof(random))) {
351
352             /* random output of public drbg */
353             result[0].pid = pid;
354             result[0].private = 0;
355             memcpy(result[0].random, &random[0], RANDOM_SIZE);
356
357             /* random output of private drbg */
358             result[1].pid = pid;
359             result[1].private = 1;
360             memcpy(result[1].random, &random[RANDOM_SIZE], RANDOM_SIZE);
361
362             rv = 1;
363         }
364
365         /* close the read end */
366         close(fd[0]);
367
368         return rv;
369
370     } else {
371
372         /* I'm the child; close the read end */
373         close(fd[0]);
374
375         /* check whether all three DRBGs reseed and send output to parent */
376         if (TEST_true(test_drbg_reseed(1, primary, public, private,
377                                         &random[0], &random[RANDOM_SIZE],
378                                        1, 1, 1, 0))
379             && TEST_true(write(fd[1], random, sizeof(random))
380                          == sizeof(random))) {
381
382             rv = 1;
383         }
384
385         /* close the write end */
386         close(fd[1]);
387
388         /* convert boolean to exit code */
389         exit(rv == 0);
390     }
391 }
392
393 static int test_rand_reseed_on_fork(EVP_RAND_CTX *primary,
394                                     EVP_RAND_CTX *public,
395                                     EVP_RAND_CTX *private)
396 {
397     unsigned int i;
398     pid_t pid = getpid();
399     int verbose = (getenv("V") != NULL);
400     int success = 1;
401     int duplicate[2] = {0, 0};
402     unsigned char random[2 * RANDOM_SIZE];
403     unsigned char sample[DRBG_FORK_RESULT_COUNT * RANDOM_SIZE];
404     unsigned char *psample = &sample[0];
405     drbg_fork_result result[DRBG_FORK_RESULT_COUNT];
406     drbg_fork_result *presult = &result[2];
407
408     memset(&result,  0, sizeof(result));
409
410     for (i = 1 ; i <= DRBG_FORK_COUNT ; ++i) {
411
412         presult[0].pindex = presult[1].pindex = i;
413
414         sprintf(presult[0].name, "child %d", i);
415         strcpy(presult[1].name, presult[0].name);
416
417         /* collect the random output of the children */
418         if (!TEST_true(test_drbg_reseed_in_child(primary,
419                                                  public,
420                                                  private,
421                                                  presult)))
422             return 0;
423
424         presult += 2;
425     }
426
427     /* collect the random output of the parent */
428     if (!TEST_true(test_drbg_reseed(1,
429                                     primary, public, private,
430                                     &random[0], &random[RANDOM_SIZE],
431                                     0, 0, 0, 0)))
432         return 0;
433
434     strcpy(result[0].name, "parent");
435     strcpy(result[1].name, "parent");
436
437     /* output of public drbg */
438     result[0].pid = pid;
439     result[0].private = 0;
440     memcpy(result[0].random, &random[0], RANDOM_SIZE);
441
442     /* output of private drbg */
443     result[1].pid = pid;
444     result[1].private = 1;
445     memcpy(result[1].random, &random[RANDOM_SIZE], RANDOM_SIZE);
446
447     /* collect all sampled random data in a single buffer */
448     for (i = 0 ; i < DRBG_FORK_RESULT_COUNT ; ++i) {
449         memcpy(psample, &result[i].random[0], RANDOM_SIZE);
450         psample += RANDOM_SIZE;
451     }
452
453     /* sort the results... */
454     qsort(result, DRBG_FORK_RESULT_COUNT, sizeof(drbg_fork_result),
455           compare_drbg_fork_result);
456
457     /* ...and count duplicate prefixes by looking at the first byte only */
458     for (i = 1 ; i < DRBG_FORK_RESULT_COUNT ; ++i) {
459         if (result[i].random[0] == result[i-1].random[0]) {
460             /* count public and private duplicates separately */
461             ++duplicate[result[i].private];
462         }
463     }
464
465     if (duplicate[0] >= DRBG_FORK_COUNT - 1) {
466         /* just too many duplicates to be a coincidence */
467         TEST_note("ERROR: %d duplicate prefixes in public random output", duplicate[0]);
468         success = 0;
469     }
470
471     if (duplicate[1] >= DRBG_FORK_COUNT - 1) {
472         /* just too many duplicates to be a coincidence */
473         TEST_note("ERROR: %d duplicate prefixes in private random output", duplicate[1]);
474         success = 0;
475     }
476
477     duplicate[0] = 0;
478
479     /* sort the two-byte chunks... */
480     qsort(sample, sizeof(sample)/2, 2, compare_rand_chunk);
481
482     /* ...and count duplicate chunks */
483     for (i = 2, psample = sample + 2 ; i < sizeof(sample) ; i += 2, psample += 2) {
484         if (compare_rand_chunk(psample - 2, psample) == 0)
485             ++duplicate[0];
486     }
487
488     if (duplicate[0] >= DRBG_FORK_COUNT - 1) {
489         /* just too many duplicates to be a coincidence */
490         TEST_note("ERROR: %d duplicate chunks in random output", duplicate[0]);
491         success = 0;
492     }
493
494     if (verbose || !success) {
495
496         for (i = 0 ; i < DRBG_FORK_RESULT_COUNT ; ++i) {
497             char *rand_hex = OPENSSL_buf2hexstr(result[i].random, RANDOM_SIZE);
498
499             TEST_note("    random: %s, pid: %d (%s, %s)",
500                       rand_hex,
501                       result[i].pid,
502                       result[i].name,
503                       result[i].private ? "private" : "public"
504                       );
505
506             OPENSSL_free(rand_hex);
507         }
508     }
509
510     return success;
511 }
512
513 static int test_rand_fork_safety(int i)
514 {
515     int success = 1;
516     unsigned char random[1];
517     EVP_RAND_CTX *primary, *public, *private;
518
519     /* All three DRBGs should be non-null */
520     if (!TEST_ptr(primary = RAND_get0_primary(NULL))
521         || !TEST_ptr(public = RAND_get0_public(NULL))
522         || !TEST_ptr(private = RAND_get0_private(NULL)))
523         return 0;
524
525     /* run the actual test */
526     if (!TEST_true(test_rand_reseed_on_fork(primary, public, private)))
527         success = 0;
528
529     /* request a single byte from each of the DRBGs before the next run */
530     if (!TEST_true(RAND_bytes(random, 1) && RAND_priv_bytes(random, 1)))
531         success = 0;
532
533     return success;
534 }
535 #endif
536
537 /*
538  * Test whether the default rand_method (RAND_OpenSSL()) is
539  * setup correctly, in particular whether reseeding  works
540  * as designed.
541  */
542 static int test_rand_reseed(void)
543 {
544     EVP_RAND_CTX *primary, *public, *private;
545     unsigned char rand_add_buf[256];
546     int rv = 0;
547     time_t before_reseed;
548
549     if (crngt_skip())
550         return TEST_skip("CRNGT cannot be disabled");
551
552     /* Check whether RAND_OpenSSL() is the default method */
553     if (!TEST_ptr_eq(RAND_get_rand_method(), RAND_OpenSSL()))
554         return 0;
555
556     /* All three DRBGs should be non-null */
557     if (!TEST_ptr(primary = RAND_get0_primary(NULL))
558         || !TEST_ptr(public = RAND_get0_public(NULL))
559         || !TEST_ptr(private = RAND_get0_private(NULL)))
560         return 0;
561
562     /* There should be three distinct DRBGs, two of them chained to primary */
563     if (!TEST_ptr_ne(public, private)
564         || !TEST_ptr_ne(public, primary)
565         || !TEST_ptr_ne(private, primary)
566         || !TEST_ptr_eq(prov_rand(public)->parent, prov_rand(primary))
567         || !TEST_ptr_eq(prov_rand(private)->parent, prov_rand(primary)))
568         return 0;
569
570     /* Disable CRNG testing for the primary DRBG */
571     if (!TEST_true(disable_crngt(primary)))
572         return 0;
573
574     /* uninstantiate the three global DRBGs */
575     EVP_RAND_uninstantiate(primary);
576     EVP_RAND_uninstantiate(private);
577     EVP_RAND_uninstantiate(public);
578
579
580     /*
581      * Test initial seeding of shared DRBGs
582      */
583     if (!TEST_true(test_drbg_reseed(1,
584                                     primary, public, private,
585                                     NULL, NULL,
586                                     1, 1, 1, 0)))
587         goto error;
588
589
590     /*
591      * Test initial state of shared DRBGs
592      */
593     if (!TEST_true(test_drbg_reseed(1,
594                                     primary, public, private,
595                                     NULL, NULL,
596                                     0, 0, 0, 0)))
597         goto error;
598
599     /*
600      * Test whether the public and private DRBG are both reseeded when their
601      * reseed counters differ from the primary's reseed counter.
602      */
603     inc_reseed_counter(primary);
604     if (!TEST_true(test_drbg_reseed(1,
605                                     primary, public, private,
606                                     NULL, NULL,
607                                     0, 1, 1, 0)))
608         goto error;
609
610     /*
611      * Test whether the public DRBG is reseeded when its reseed counter differs
612      * from the primary's reseed counter.
613      */
614     inc_reseed_counter(primary);
615     inc_reseed_counter(private);
616     if (!TEST_true(test_drbg_reseed(1,
617                                     primary, public, private,
618                                     NULL, NULL,
619                                     0, 1, 0, 0)))
620         goto error;
621
622     /*
623      * Test whether the private DRBG is reseeded when its reseed counter differs
624      * from the primary's reseed counter.
625      */
626     inc_reseed_counter(primary);
627     inc_reseed_counter(public);
628     if (!TEST_true(test_drbg_reseed(1,
629                                     primary, public, private,
630                                     NULL, NULL,
631                                     0, 0, 1, 0)))
632         goto error;
633
634     /* fill 'randomness' buffer with some arbitrary data */
635     memset(rand_add_buf, 'r', sizeof(rand_add_buf));
636
637 #ifndef FIPS_MODULE
638     /*
639      * Test whether all three DRBGs are reseeded by RAND_add().
640      * The before_reseed time has to be measured here and passed into the
641      * test_drbg_reseed() test, because the primary DRBG gets already reseeded
642      * in RAND_add(), whence the check for the condition
643      * before_reseed <= reseed_time(primary) will fail if the time value happens
644      * to increase between the RAND_add() and the test_drbg_reseed() call.
645      */
646     before_reseed = time(NULL);
647     RAND_add(rand_add_buf, sizeof(rand_add_buf), sizeof(rand_add_buf));
648     if (!TEST_true(test_drbg_reseed(1,
649                                     primary, public, private,
650                                     NULL, NULL,
651                                     1, 1, 1,
652                                     before_reseed)))
653         goto error;
654 #else /* FIPS_MODULE */
655     /*
656      * In FIPS mode, random data provided by the application via RAND_add()
657      * is not considered a trusted entropy source. It is only treated as
658      * additional_data and no reseeding is forced. This test assures that
659      * no reseeding occurs.
660      */
661     before_reseed = time(NULL);
662     RAND_add(rand_add_buf, sizeof(rand_add_buf), sizeof(rand_add_buf));
663     if (!TEST_true(test_drbg_reseed(1,
664                                     primary, public, private,
665                                     NULL, NULL,
666                                     0, 0, 0,
667                                     before_reseed)))
668         goto error;
669 #endif
670
671     rv = 1;
672
673 error:
674    return rv;
675 }
676
677 #if defined(OPENSSL_THREADS)
678 static int multi_thread_rand_bytes_succeeded = 1;
679 static int multi_thread_rand_priv_bytes_succeeded = 1;
680
681 static int set_reseed_time_interval(EVP_RAND_CTX *drbg, int t)
682 {
683     OSSL_PARAM params[2];
684
685     params[0] = OSSL_PARAM_construct_int(OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL,
686                                          &t);
687     params[1] = OSSL_PARAM_construct_end();
688     return EVP_RAND_set_ctx_params(drbg, params);
689 }
690
691 static void run_multi_thread_test(void)
692 {
693     unsigned char buf[256];
694     time_t start = time(NULL);
695     EVP_RAND_CTX *public = NULL, *private = NULL;
696
697     if (!TEST_ptr(public = RAND_get0_public(NULL))
698             || !TEST_ptr(private = RAND_get0_private(NULL))
699             || !TEST_true(set_reseed_time_interval(private, 1))
700             || !TEST_true(set_reseed_time_interval(public, 1))) {
701         multi_thread_rand_bytes_succeeded = 0;
702         return;
703     }
704
705     do {
706         if (rand_bytes(buf, sizeof(buf)) <= 0)
707             multi_thread_rand_bytes_succeeded = 0;
708         if (rand_priv_bytes(buf, sizeof(buf)) <= 0)
709             multi_thread_rand_priv_bytes_succeeded = 0;
710     }
711     while (time(NULL) - start < 5);
712 }
713
714 # if defined(OPENSSL_SYS_WINDOWS)
715
716 typedef HANDLE thread_t;
717
718 static DWORD WINAPI thread_run(LPVOID arg)
719 {
720     run_multi_thread_test();
721     /*
722      * Because we're linking with a static library, we must stop each
723      * thread explicitly, or so says OPENSSL_thread_stop(3)
724      */
725     OPENSSL_thread_stop();
726     return 0;
727 }
728
729 static int run_thread(thread_t *t)
730 {
731     *t = CreateThread(NULL, 0, thread_run, NULL, 0, NULL);
732     return *t != NULL;
733 }
734
735 static int wait_for_thread(thread_t thread)
736 {
737     return WaitForSingleObject(thread, INFINITE) == 0;
738 }
739
740 # else
741
742 typedef pthread_t thread_t;
743
744 static void *thread_run(void *arg)
745 {
746     run_multi_thread_test();
747     /*
748      * Because we're linking with a static library, we must stop each
749      * thread explicitly, or so says OPENSSL_thread_stop(3)
750      */
751     OPENSSL_thread_stop();
752     return NULL;
753 }
754
755 static int run_thread(thread_t *t)
756 {
757     return pthread_create(t, NULL, thread_run, NULL) == 0;
758 }
759
760 static int wait_for_thread(thread_t thread)
761 {
762     return pthread_join(thread, NULL) == 0;
763 }
764
765 # endif
766
767 /*
768  * The main thread will also run the test, so we'll have THREADS+1 parallel
769  * tests running
770  */
771 # define THREADS 3
772
773 static int test_multi_thread(void)
774 {
775     thread_t t[THREADS];
776     int i;
777
778     for (i = 0; i < THREADS; i++)
779         run_thread(&t[i]);
780     run_multi_thread_test();
781     for (i = 0; i < THREADS; i++)
782         wait_for_thread(t[i]);
783
784     if (!TEST_true(multi_thread_rand_bytes_succeeded))
785         return 0;
786     if (!TEST_true(multi_thread_rand_priv_bytes_succeeded))
787         return 0;
788
789     return 1;
790 }
791 #endif
792
793 static EVP_RAND_CTX *new_drbg(EVP_RAND_CTX *parent)
794 {
795     OSSL_PARAM params[2];
796     EVP_RAND *rand = NULL;
797     EVP_RAND_CTX *drbg = NULL;
798
799     params[0] = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_CIPHER,
800                                                  "AES-256-CTR", 0);
801     params[1] = OSSL_PARAM_construct_end();
802
803     if (!TEST_ptr(rand = EVP_RAND_fetch(NULL, "CTR-DRBG", NULL))
804             || !TEST_ptr(drbg = EVP_RAND_CTX_new(rand, parent))
805             || !TEST_true(EVP_RAND_set_ctx_params(drbg, params))) {
806         EVP_RAND_CTX_free(drbg);
807         drbg = NULL;
808     }
809     EVP_RAND_free(rand);
810     return drbg;
811 }
812
813 static int test_rand_prediction_resistance(void)
814 {
815     EVP_RAND_CTX *x = NULL, *y = NULL, *z = NULL;
816     unsigned char buf1[51], buf2[sizeof(buf1)];
817     int ret = 0, xreseed, yreseed, zreseed;
818
819     if (crngt_skip())
820         return TEST_skip("CRNGT cannot be disabled");
821
822     /* Initialise a three long DRBG chain */
823     if (!TEST_ptr(x = new_drbg(NULL))
824         || !TEST_true(disable_crngt(x))
825         || !TEST_true(EVP_RAND_instantiate(x, 0, 0, NULL, 0))
826         || !TEST_ptr(y = new_drbg(x))
827         || !TEST_true(EVP_RAND_instantiate(y, 0, 0, NULL, 0))
828         || !TEST_ptr(z = new_drbg(y))
829         || !TEST_true(EVP_RAND_instantiate(z, 0, 0, NULL, 0)))
830         goto err;
831
832     /*
833      * During a normal reseed, only the last DRBG in the chain should
834      * be reseeded.
835      */
836     inc_reseed_counter(y);
837     xreseed = reseed_counter(x);
838     yreseed = reseed_counter(y);
839     zreseed = reseed_counter(z);
840     if (!TEST_true(EVP_RAND_reseed(z, 0, NULL, 0, NULL, 0))
841         || !TEST_int_eq(reseed_counter(x), xreseed)
842         || !TEST_int_eq(reseed_counter(y), yreseed)
843         || !TEST_int_gt(reseed_counter(z), zreseed))
844         goto err;
845
846     /*
847      * When prediction resistance is requested, the request should be
848      * propagated to the primary, so that the entire DRBG chain reseeds.
849      */
850     zreseed = reseed_counter(z);
851     if (!TEST_true(EVP_RAND_reseed(z, 1, NULL, 0, NULL, 0))
852         || !TEST_int_gt(reseed_counter(x), xreseed)
853         || !TEST_int_gt(reseed_counter(y), yreseed)
854         || !TEST_int_gt(reseed_counter(z), zreseed))
855         goto err;
856
857     /*
858      * During a normal generate, only the last DRBG should be reseed */
859     inc_reseed_counter(y);
860     xreseed = reseed_counter(x);
861     yreseed = reseed_counter(y);
862     zreseed = reseed_counter(z);
863     if (!TEST_true(EVP_RAND_generate(z, buf1, sizeof(buf1), 0, 0, NULL, 0))
864         || !TEST_int_eq(reseed_counter(x), xreseed)
865         || !TEST_int_eq(reseed_counter(y), yreseed)
866         || !TEST_int_gt(reseed_counter(z), zreseed))
867         goto err;
868
869     /*
870      * When a prediction resistant generate is requested, the request
871      * should be propagated to the primary, reseeding the entire DRBG chain.
872      */
873     zreseed = reseed_counter(z);
874     if (!TEST_true(EVP_RAND_generate(z, buf2, sizeof(buf2), 0, 1, NULL, 0))
875         || !TEST_int_gt(reseed_counter(x), xreseed)
876         || !TEST_int_gt(reseed_counter(y), yreseed)
877         || !TEST_int_gt(reseed_counter(z), zreseed)
878         || !TEST_mem_ne(buf1, sizeof(buf1), buf2, sizeof(buf2)))
879         goto err;
880
881     /* Verify that a normal reseed still only reseeds the last DRBG */
882     inc_reseed_counter(y);
883     xreseed = reseed_counter(x);
884     yreseed = reseed_counter(y);
885     zreseed = reseed_counter(z);
886     if (!TEST_true(EVP_RAND_reseed(z, 0, NULL, 0, NULL, 0))
887         || !TEST_int_eq(reseed_counter(x), xreseed)
888         || !TEST_int_eq(reseed_counter(y), yreseed)
889         || !TEST_int_gt(reseed_counter(z), zreseed))
890         goto err;
891
892     ret = 1;
893 err:
894     EVP_RAND_CTX_free(z);
895     EVP_RAND_CTX_free(y);
896     EVP_RAND_CTX_free(x);
897     return ret;
898 }
899
900 int setup_tests(void)
901 {
902     ADD_TEST(test_rand_reseed);
903 #if defined(OPENSSL_SYS_UNIX)
904     ADD_ALL_TESTS(test_rand_fork_safety, RANDOM_SIZE);
905 #endif
906     ADD_TEST(test_rand_prediction_resistance);
907 #if defined(OPENSSL_THREADS)
908     ADD_TEST(test_multi_thread);
909 #endif
910     return 1;
911 }