Reorganize local header files
[openssl.git] / test / drbgtest.c
1 /*
2  * Copyright 2011-2018 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
21 #if defined(_WIN32)
22 # include <windows.h>
23 #endif
24
25
26 #if defined(OPENSSL_SYS_UNIX)
27 # include <sys/types.h>
28 # include <sys/wait.h>
29 # include <unistd.h>
30 #endif
31
32 #include "testutil.h"
33 #include "drbgtest.h"
34
35 typedef struct drbg_selftest_data_st {
36     int post;
37     int nid;
38     unsigned int flags;
39
40     /* KAT data for no PR */
41     const unsigned char *entropy;
42     size_t entropylen;
43     const unsigned char *nonce;
44     size_t noncelen;
45     const unsigned char *pers;
46     size_t perslen;
47     const unsigned char *adin;
48     size_t adinlen;
49     const unsigned char *entropyreseed;
50     size_t entropyreseedlen;
51     const unsigned char *adinreseed;
52     size_t adinreseedlen;
53     const unsigned char *adin2;
54     size_t adin2len;
55     const unsigned char *expected;
56     size_t exlen;
57     const unsigned char *kat2;
58     size_t kat2len;
59
60     /* KAT data for PR */
61     const unsigned char *entropy_pr;
62     size_t entropylen_pr;
63     const unsigned char *nonce_pr;
64     size_t noncelen_pr;
65     const unsigned char *pers_pr;
66     size_t perslen_pr;
67     const unsigned char *adin_pr;
68     size_t adinlen_pr;
69     const unsigned char *entropypr_pr;
70     size_t entropyprlen_pr;
71     const unsigned char *ading_pr;
72     size_t adinglen_pr;
73     const unsigned char *entropyg_pr;
74     size_t entropyglen_pr;
75     const unsigned char *kat_pr;
76     size_t katlen_pr;
77     const unsigned char *kat2_pr;
78     size_t kat2len_pr;
79 } DRBG_SELFTEST_DATA;
80
81 #define make_drbg_test_data(nid, flag, pr, post) {\
82     post, nid, flag, \
83     pr##_entropyinput, sizeof(pr##_entropyinput), \
84     pr##_nonce, sizeof(pr##_nonce), \
85     pr##_personalizationstring, sizeof(pr##_personalizationstring), \
86     pr##_additionalinput, sizeof(pr##_additionalinput), \
87     pr##_entropyinputreseed, sizeof(pr##_entropyinputreseed), \
88     pr##_additionalinputreseed, sizeof(pr##_additionalinputreseed), \
89     pr##_additionalinput2, sizeof(pr##_additionalinput2), \
90     pr##_int_returnedbits, sizeof(pr##_int_returnedbits), \
91     pr##_returnedbits, sizeof(pr##_returnedbits), \
92     pr##_pr_entropyinput, sizeof(pr##_pr_entropyinput), \
93     pr##_pr_nonce, sizeof(pr##_pr_nonce), \
94     pr##_pr_personalizationstring, sizeof(pr##_pr_personalizationstring), \
95     pr##_pr_additionalinput, sizeof(pr##_pr_additionalinput), \
96     pr##_pr_entropyinputpr, sizeof(pr##_pr_entropyinputpr), \
97     pr##_pr_additionalinput2, sizeof(pr##_pr_additionalinput2), \
98     pr##_pr_entropyinputpr2, sizeof(pr##_pr_entropyinputpr2), \
99     pr##_pr_int_returnedbits, sizeof(pr##_pr_int_returnedbits), \
100     pr##_pr_returnedbits, sizeof(pr##_pr_returnedbits) \
101     }
102
103 #define make_drbg_test_data_use_df(nid, pr, p) \
104     make_drbg_test_data(nid, 0, pr, p)
105
106 #define make_drbg_test_data_no_df(nid, pr, p)                      \
107     make_drbg_test_data(nid, RAND_DRBG_FLAG_CTR_NO_DF, pr, p)
108
109 #define make_drbg_test_data_hash(nid, pr, p) \
110     make_drbg_test_data(nid, RAND_DRBG_FLAG_HMAC, hmac_##pr, p), \
111     make_drbg_test_data(nid, 0, pr, p)
112
113 static DRBG_SELFTEST_DATA drbg_test[] = {
114 #ifndef FIPS_MODE
115     /* FIPS mode doesn't support CTR DRBG without a derivation function */
116     make_drbg_test_data_no_df (NID_aes_128_ctr, aes_128_no_df,  0),
117     make_drbg_test_data_no_df (NID_aes_192_ctr, aes_192_no_df,  0),
118     make_drbg_test_data_no_df (NID_aes_256_ctr, aes_256_no_df,  1),
119 #endif
120     make_drbg_test_data_use_df(NID_aes_128_ctr, aes_128_use_df, 0),
121     make_drbg_test_data_use_df(NID_aes_192_ctr, aes_192_use_df, 0),
122     make_drbg_test_data_use_df(NID_aes_256_ctr, aes_256_use_df, 1),
123     make_drbg_test_data_hash(NID_sha1, sha1, 0),
124     make_drbg_test_data_hash(NID_sha224, sha224, 0),
125     make_drbg_test_data_hash(NID_sha256, sha256, 1),
126     make_drbg_test_data_hash(NID_sha384, sha384, 0),
127     make_drbg_test_data_hash(NID_sha512, sha512, 0),
128 };
129
130 static int app_data_index;
131
132 /*
133  * Test context data, attached as EXDATA to the RAND_DRBG
134  */
135 typedef struct test_ctx_st {
136     const unsigned char *entropy;
137     size_t entropylen;
138     int entropycnt;
139     const unsigned char *nonce;
140     size_t noncelen;
141     int noncecnt;
142 } TEST_CTX;
143
144 static size_t kat_entropy(RAND_DRBG *drbg, unsigned char **pout,
145                           int entropy, size_t min_len, size_t max_len,
146                           int prediction_resistance)
147 {
148     TEST_CTX *t = (TEST_CTX *)RAND_DRBG_get_ex_data(drbg, app_data_index);
149
150     t->entropycnt++;
151     *pout = (unsigned char *)t->entropy;
152     return t->entropylen;
153 }
154
155 static size_t kat_nonce(RAND_DRBG *drbg, unsigned char **pout,
156                         int entropy, size_t min_len, size_t max_len)
157 {
158     TEST_CTX *t = (TEST_CTX *)RAND_DRBG_get_ex_data(drbg, app_data_index);
159
160     t->noncecnt++;
161     *pout = (unsigned char *)t->nonce;
162     return t->noncelen;
163 }
164
165  /*
166  * Disable CRNG testing if it is enabled.
167  * If the DRBG is ready or in an error state, this means an instantiate cycle
168  * for which the default personalisation string is used.
169  */
170 static int disable_crngt(RAND_DRBG *drbg)
171 {
172     static const char pers[] = DRBG_DEFAULT_PERS_STRING;
173     const int instantiate = drbg->state != DRBG_UNINITIALISED;
174
175     if (drbg->get_entropy != rand_crngt_get_entropy)
176         return 1;
177
178      if ((instantiate && !RAND_DRBG_uninstantiate(drbg))
179         || !TEST_true(RAND_DRBG_set_callbacks(drbg, &rand_drbg_get_entropy,
180                                               &rand_drbg_cleanup_entropy,
181                                               &rand_drbg_get_nonce,
182                                               &rand_drbg_cleanup_nonce))
183         || (instantiate
184             && !RAND_DRBG_instantiate(drbg, (const unsigned char *)pers,
185                                       sizeof(pers) - 1)))
186         return 0;
187     return 1;
188 }
189
190 static int uninstantiate(RAND_DRBG *drbg)
191 {
192     int ret = drbg == NULL ? 1 : RAND_DRBG_uninstantiate(drbg);
193
194     ERR_clear_error();
195     return ret;
196 }
197
198 /*
199  * Do a single KAT test.  Return 0 on failure.
200  */
201 static int single_kat(DRBG_SELFTEST_DATA *td)
202 {
203     RAND_DRBG *drbg = NULL;
204     TEST_CTX t;
205     int failures = 0;
206     unsigned char buff[1024];
207
208     /*
209      * Test without PR: Instantiate DRBG with test entropy, nonce and
210      * personalisation string.
211      */
212     if (!TEST_ptr(drbg = RAND_DRBG_new(td->nid, td->flags, NULL)))
213         return 0;
214     if (!TEST_true(RAND_DRBG_set_callbacks(drbg, kat_entropy, NULL,
215                                            kat_nonce, NULL))
216         || !TEST_true(disable_crngt(drbg))) {
217         failures++;
218         goto err;
219     }
220     memset(&t, 0, sizeof(t));
221     t.entropy = td->entropy;
222     t.entropylen = td->entropylen;
223     t.nonce = td->nonce;
224     t.noncelen = td->noncelen;
225     RAND_DRBG_set_ex_data(drbg, app_data_index, &t);
226
227     if (!TEST_true(RAND_DRBG_instantiate(drbg, td->pers, td->perslen))
228             || !TEST_true(RAND_DRBG_generate(drbg, buff, td->exlen, 0,
229                                              td->adin, td->adinlen))
230             || !TEST_mem_eq(td->expected, td->exlen, buff, td->exlen))
231         failures++;
232
233     /* Reseed DRBG with test entropy and additional input */
234     t.entropy = td->entropyreseed;
235     t.entropylen = td->entropyreseedlen;
236     if (!TEST_true(RAND_DRBG_reseed(drbg, td->adinreseed, td->adinreseedlen, 0)
237             || !TEST_true(RAND_DRBG_generate(drbg, buff, td->kat2len, 0,
238                                              td->adin2, td->adin2len))
239             || !TEST_mem_eq(td->kat2, td->kat2len, buff, td->kat2len)))
240         failures++;
241     uninstantiate(drbg);
242
243     /*
244      * Now test with PR: Instantiate DRBG with test entropy, nonce and
245      * personalisation string.
246      */
247     if (!TEST_true(RAND_DRBG_set(drbg, td->nid, td->flags))
248             || !TEST_true(RAND_DRBG_set_callbacks(drbg, kat_entropy, NULL,
249                                                   kat_nonce, NULL)))
250         failures++;
251     RAND_DRBG_set_ex_data(drbg, app_data_index, &t);
252     t.entropy = td->entropy_pr;
253     t.entropylen = td->entropylen_pr;
254     t.nonce = td->nonce_pr;
255     t.noncelen = td->noncelen_pr;
256     t.entropycnt = 0;
257     t.noncecnt = 0;
258     if (!TEST_true(RAND_DRBG_instantiate(drbg, td->pers_pr, td->perslen_pr)))
259         failures++;
260
261     /*
262      * Now generate with PR: we need to supply entropy as this will
263      * perform a reseed operation.
264      */
265     t.entropy = td->entropypr_pr;
266     t.entropylen = td->entropyprlen_pr;
267     if (!TEST_true(RAND_DRBG_generate(drbg, buff, td->katlen_pr, 1,
268                                       td->adin_pr, td->adinlen_pr))
269             || !TEST_mem_eq(td->kat_pr, td->katlen_pr, buff, td->katlen_pr))
270         failures++;
271
272     /*
273      * Now generate again with PR: supply new entropy again.
274      */
275     t.entropy = td->entropyg_pr;
276     t.entropylen = td->entropyglen_pr;
277
278     if (!TEST_true(RAND_DRBG_generate(drbg, buff, td->kat2len_pr, 1,
279                                       td->ading_pr, td->adinglen_pr))
280                 || !TEST_mem_eq(td->kat2_pr, td->kat2len_pr,
281                                 buff, td->kat2len_pr))
282         failures++;
283
284 err:
285     uninstantiate(drbg);
286     RAND_DRBG_free(drbg);
287     return failures == 0;
288 }
289
290 /*
291  * Initialise a DRBG based on selftest data
292  */
293 static int init(RAND_DRBG *drbg, DRBG_SELFTEST_DATA *td, TEST_CTX *t)
294 {
295     if (!TEST_true(RAND_DRBG_set(drbg, td->nid, td->flags))
296             || !TEST_true(RAND_DRBG_set_callbacks(drbg, kat_entropy, NULL,
297                                                   kat_nonce, NULL)))
298         return 0;
299     RAND_DRBG_set_ex_data(drbg, app_data_index, t);
300     t->entropy = td->entropy;
301     t->entropylen = td->entropylen;
302     t->nonce = td->nonce;
303     t->noncelen = td->noncelen;
304     t->entropycnt = 0;
305     t->noncecnt = 0;
306     return 1;
307 }
308
309 /*
310  * Initialise and instantiate DRBG based on selftest data
311  */
312 static int instantiate(RAND_DRBG *drbg, DRBG_SELFTEST_DATA *td,
313                        TEST_CTX *t)
314 {
315     if (!TEST_true(init(drbg, td, t))
316             || !TEST_true(RAND_DRBG_instantiate(drbg, td->pers, td->perslen)))
317         return 0;
318     return 1;
319 }
320
321 /*
322  * Perform extensive error checking as required by SP800-90.
323  * Induce several failure modes and check an error condition is set.
324  */
325 static int error_check(DRBG_SELFTEST_DATA *td)
326 {
327     static char zero[sizeof(RAND_DRBG)];
328     RAND_DRBG *drbg = NULL;
329     TEST_CTX t;
330     unsigned char buff[1024];
331     unsigned int reseed_counter_tmp;
332     int ret = 0;
333
334     if (!TEST_ptr(drbg = RAND_DRBG_new(td->nid, td->flags, NULL))
335         || !TEST_true(disable_crngt(drbg)))
336         goto err;
337
338     /*
339      * Personalisation string tests
340      */
341
342     /* Test detection of too large personalisation string */
343     if (!init(drbg, td, &t)
344             || RAND_DRBG_instantiate(drbg, td->pers, drbg->max_perslen + 1) > 0)
345         goto err;
346
347     /*
348      * Entropy source tests
349      */
350
351     /* Test entropy source failure detection: i.e. returns no data */
352     t.entropylen = 0;
353     if (TEST_int_le(RAND_DRBG_instantiate(drbg, td->pers, td->perslen), 0))
354         goto err;
355
356     /* Try to generate output from uninstantiated DRBG */
357     if (!TEST_false(RAND_DRBG_generate(drbg, buff, td->exlen, 0,
358                                        td->adin, td->adinlen))
359             || !uninstantiate(drbg))
360         goto err;
361
362     /* Test insufficient entropy */
363     t.entropylen = drbg->min_entropylen - 1;
364     if (!init(drbg, td, &t)
365             || RAND_DRBG_instantiate(drbg, td->pers, td->perslen) > 0
366             || !uninstantiate(drbg))
367         goto err;
368
369     /* Test too much entropy */
370     t.entropylen = drbg->max_entropylen + 1;
371     if (!init(drbg, td, &t)
372             || RAND_DRBG_instantiate(drbg, td->pers, td->perslen) > 0
373             || !uninstantiate(drbg))
374         goto err;
375
376     /*
377      * Nonce tests
378      */
379
380     /* Test too small nonce */
381     if (drbg->min_noncelen) {
382         t.noncelen = drbg->min_noncelen - 1;
383         if (!init(drbg, td, &t)
384                 || RAND_DRBG_instantiate(drbg, td->pers, td->perslen) > 0
385                 || !uninstantiate(drbg))
386             goto err;
387     }
388
389     /* Test too large nonce */
390     if (drbg->max_noncelen) {
391         t.noncelen = drbg->max_noncelen + 1;
392         if (!init(drbg, td, &t)
393                 || RAND_DRBG_instantiate(drbg, td->pers, td->perslen) > 0
394                 || !uninstantiate(drbg))
395             goto err;
396     }
397
398     /* Instantiate with valid data, Check generation is now OK */
399     if (!instantiate(drbg, td, &t)
400             || !TEST_true(RAND_DRBG_generate(drbg, buff, td->exlen, 0,
401                                              td->adin, td->adinlen)))
402         goto err;
403
404     /* Request too much data for one request */
405     if (!TEST_false(RAND_DRBG_generate(drbg, buff, drbg->max_request + 1, 0,
406                                        td->adin, td->adinlen)))
407         goto err;
408
409     /* Try too large additional input */
410     if (!TEST_false(RAND_DRBG_generate(drbg, buff, td->exlen, 0,
411                                        td->adin, drbg->max_adinlen + 1)))
412         goto err;
413
414     /*
415      * Check prediction resistance request fails if entropy source
416      * failure.
417      */
418     t.entropylen = 0;
419     if (TEST_false(RAND_DRBG_generate(drbg, buff, td->exlen, 1,
420                                       td->adin, td->adinlen))
421             || !uninstantiate(drbg))
422         goto err;
423
424     /* Instantiate again with valid data */
425     if (!instantiate(drbg, td, &t))
426         goto err;
427     reseed_counter_tmp = drbg->reseed_gen_counter;
428     drbg->reseed_gen_counter = drbg->reseed_interval;
429
430     /* Generate output and check entropy has been requested for reseed */
431     t.entropycnt = 0;
432     if (!TEST_true(RAND_DRBG_generate(drbg, buff, td->exlen, 0,
433                                       td->adin, td->adinlen))
434             || !TEST_int_eq(t.entropycnt, 1)
435             || !TEST_int_eq(drbg->reseed_gen_counter, reseed_counter_tmp + 1)
436             || !uninstantiate(drbg))
437         goto err;
438
439     /*
440      * Check prediction resistance request fails if entropy source
441      * failure.
442      */
443     t.entropylen = 0;
444     if (!TEST_false(RAND_DRBG_generate(drbg, buff, td->exlen, 1,
445                                        td->adin, td->adinlen))
446             || !uninstantiate(drbg))
447         goto err;
448
449     /* Test reseed counter works */
450     if (!instantiate(drbg, td, &t))
451         goto err;
452     reseed_counter_tmp = drbg->reseed_gen_counter;
453     drbg->reseed_gen_counter = drbg->reseed_interval;
454
455     /* Generate output and check entropy has been requested for reseed */
456     t.entropycnt = 0;
457     if (!TEST_true(RAND_DRBG_generate(drbg, buff, td->exlen, 0,
458                                       td->adin, td->adinlen))
459             || !TEST_int_eq(t.entropycnt, 1)
460             || !TEST_int_eq(drbg->reseed_gen_counter, reseed_counter_tmp + 1)
461             || !uninstantiate(drbg))
462         goto err;
463
464     /*
465      * Explicit reseed tests
466      */
467
468     /* Test explicit reseed with too large additional input */
469     if (!instantiate(drbg, td, &t)
470             || RAND_DRBG_reseed(drbg, td->adin, drbg->max_adinlen + 1, 0) > 0)
471         goto err;
472
473     /* Test explicit reseed with entropy source failure */
474     t.entropylen = 0;
475     if (!TEST_int_le(RAND_DRBG_reseed(drbg, td->adin, td->adinlen, 0), 0)
476             || !uninstantiate(drbg))
477         goto err;
478
479     /* Test explicit reseed with too much entropy */
480     if (!instantiate(drbg, td, &t))
481         goto err;
482     t.entropylen = drbg->max_entropylen + 1;
483     if (!TEST_int_le(RAND_DRBG_reseed(drbg, td->adin, td->adinlen, 0), 0)
484             || !uninstantiate(drbg))
485         goto err;
486
487     /* Test explicit reseed with too little entropy */
488     if (!instantiate(drbg, td, &t))
489         goto err;
490     t.entropylen = drbg->min_entropylen - 1;
491     if (!TEST_int_le(RAND_DRBG_reseed(drbg, td->adin, td->adinlen, 0), 0)
492             || !uninstantiate(drbg))
493         goto err;
494
495     /* Standard says we have to check uninstantiate really zeroes */
496     if (!TEST_mem_eq(zero, sizeof(drbg->data), &drbg->data, sizeof(drbg->data)))
497         goto err;
498
499     ret = 1;
500
501 err:
502     uninstantiate(drbg);
503     RAND_DRBG_free(drbg);
504     return ret;
505 }
506
507 static int test_kats(int i)
508 {
509     DRBG_SELFTEST_DATA *td = &drbg_test[i];
510     int rv = 0;
511
512     if (!single_kat(td))
513         goto err;
514     rv = 1;
515
516 err:
517     return rv;
518 }
519
520 static int test_error_checks(int i)
521 {
522     DRBG_SELFTEST_DATA *td = &drbg_test[i];
523     int rv = 0;
524
525     if (error_check(td))
526         goto err;
527     rv = 1;
528
529 err:
530     return rv;
531 }
532
533 /*
534  * Hook context data, attached as EXDATA to the RAND_DRBG
535  */
536 typedef struct hook_ctx_st {
537     RAND_DRBG *drbg;
538     /*
539      * Currently, all DRBGs use the same get_entropy() callback.
540      * The tests however, don't assume this and store
541      * the original callback for every DRBG separately.
542      */
543     RAND_DRBG_get_entropy_fn get_entropy;
544     /* forces a failure of the get_entropy() call if nonzero */
545     int fail;
546     /* counts successful reseeds */
547     int reseed_count;
548 } HOOK_CTX;
549
550 static HOOK_CTX master_ctx, public_ctx, private_ctx;
551
552 static HOOK_CTX *get_hook_ctx(RAND_DRBG *drbg)
553 {
554     return (HOOK_CTX *)RAND_DRBG_get_ex_data(drbg, app_data_index);
555 }
556
557 /* Intercepts and counts calls to the get_entropy() callback */
558 static size_t get_entropy_hook(RAND_DRBG *drbg, unsigned char **pout,
559                               int entropy, size_t min_len, size_t max_len,
560                               int prediction_resistance)
561 {
562     size_t ret;
563     HOOK_CTX *ctx = get_hook_ctx(drbg);
564
565     if (ctx->fail != 0)
566         return 0;
567
568     ret = ctx->get_entropy(drbg, pout, entropy, min_len, max_len,
569                            prediction_resistance);
570
571     if (ret != 0)
572         ctx->reseed_count++;
573     return ret;
574 }
575
576 /* Installs a hook for the get_entropy() callback of the given drbg */
577 static void hook_drbg(RAND_DRBG *drbg, HOOK_CTX *ctx)
578 {
579     memset(ctx, 0, sizeof(*ctx));
580     ctx->drbg = drbg;
581     ctx->get_entropy = drbg->get_entropy;
582     drbg->get_entropy = get_entropy_hook;
583     RAND_DRBG_set_ex_data(drbg, app_data_index, ctx);
584 }
585
586 /* Installs the hook for the get_entropy() callback of the given drbg */
587 static void unhook_drbg(RAND_DRBG *drbg)
588 {
589     HOOK_CTX *ctx = get_hook_ctx(drbg);
590
591     drbg->get_entropy = ctx->get_entropy;
592     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
593 }
594
595 /* Resets the given hook context */
596 static void reset_hook_ctx(HOOK_CTX *ctx)
597 {
598     ctx->fail = 0;
599     ctx->reseed_count = 0;
600 }
601
602 /* Resets all drbg hook contexts */
603 static void reset_drbg_hook_ctx(void)
604 {
605     reset_hook_ctx(&master_ctx);
606     reset_hook_ctx(&public_ctx);
607     reset_hook_ctx(&private_ctx);
608 }
609
610 /*
611  * Generates random output using RAND_bytes() and RAND_priv_bytes()
612  * and checks whether the three shared DRBGs were reseeded as
613  * expected.
614  *
615  * |expect_success|: expected outcome (as reported by RAND_status())
616  * |master|, |public|, |private|: pointers to the three shared DRBGs
617  * |expect_xxx_reseed| =
618  *       1:  it is expected that the specified DRBG is reseeded
619  *       0:  it is expected that the specified DRBG is not reseeded
620  *      -1:  don't check whether the specified DRBG was reseeded or not
621  * |reseed_time|: if nonzero, used instead of time(NULL) to set the
622  *                |before_reseed| time.
623  */
624 static int test_drbg_reseed(int expect_success,
625                             RAND_DRBG *master,
626                             RAND_DRBG *public,
627                             RAND_DRBG *private,
628                             int expect_master_reseed,
629                             int expect_public_reseed,
630                             int expect_private_reseed,
631                             time_t reseed_time
632                            )
633 {
634     unsigned char buf[32];
635     time_t before_reseed, after_reseed;
636     int expected_state = (expect_success ? DRBG_READY : DRBG_ERROR);
637
638     /*
639      * step 1: check preconditions
640      */
641
642     /* Test whether seed propagation is enabled */
643     if (!TEST_int_ne(master->reseed_prop_counter, 0)
644         || !TEST_int_ne(public->reseed_prop_counter, 0)
645         || !TEST_int_ne(private->reseed_prop_counter, 0))
646         return 0;
647
648     /* Check whether the master DRBG's reseed counter is the largest one */
649     if (!TEST_int_le(public->reseed_prop_counter, master->reseed_prop_counter)
650         || !TEST_int_le(private->reseed_prop_counter, master->reseed_prop_counter))
651         return 0;
652
653     /*
654      * step 2: generate random output
655      */
656
657     if (reseed_time == 0)
658         reseed_time = time(NULL);
659
660     /* Generate random output from the public and private DRBG */
661     before_reseed = expect_master_reseed == 1 ? reseed_time : 0;
662     if (!TEST_int_eq(RAND_bytes(buf, sizeof(buf)), expect_success)
663         || !TEST_int_eq(RAND_priv_bytes(buf, sizeof(buf)), expect_success))
664         return 0;
665     after_reseed = time(NULL);
666
667
668     /*
669      * step 3: check postconditions
670      */
671
672     /* Test whether reseeding succeeded as expected */
673     if (!TEST_int_eq(master->state, expected_state)
674         || !TEST_int_eq(public->state, expected_state)
675         || !TEST_int_eq(private->state, expected_state))
676         return 0;
677
678     if (expect_master_reseed >= 0) {
679         /* Test whether master DRBG was reseeded as expected */
680         if (!TEST_int_eq(master_ctx.reseed_count, expect_master_reseed))
681             return 0;
682     }
683
684     if (expect_public_reseed >= 0) {
685         /* Test whether public DRBG was reseeded as expected */
686         if (!TEST_int_eq(public_ctx.reseed_count, expect_public_reseed))
687             return 0;
688     }
689
690     if (expect_private_reseed >= 0) {
691         /* Test whether public DRBG was reseeded as expected */
692         if (!TEST_int_eq(private_ctx.reseed_count, expect_private_reseed))
693             return 0;
694     }
695
696     if (expect_success == 1) {
697         /* Test whether all three reseed counters are synchronized */
698         if (!TEST_int_eq(public->reseed_prop_counter, master->reseed_prop_counter)
699             || !TEST_int_eq(private->reseed_prop_counter, master->reseed_prop_counter))
700             return 0;
701
702         /* Test whether reseed time of master DRBG is set correctly */
703         if (!TEST_time_t_le(before_reseed, master->reseed_time)
704             || !TEST_time_t_le(master->reseed_time, after_reseed))
705             return 0;
706
707         /* Test whether reseed times of child DRBGs are synchronized with master */
708         if (!TEST_time_t_ge(public->reseed_time, master->reseed_time)
709             || !TEST_time_t_ge(private->reseed_time, master->reseed_time))
710             return 0;
711     } else {
712         ERR_clear_error();
713     }
714
715     return 1;
716 }
717
718
719 #if defined(OPENSSL_SYS_UNIX)
720 /*
721  * Test whether master, public and private DRBG are reseeded after
722  * forking the process.
723  */
724 static int test_drbg_reseed_after_fork(RAND_DRBG *master,
725                                        RAND_DRBG *public,
726                                        RAND_DRBG *private)
727 {
728     pid_t pid;
729     int status=0;
730
731     pid = fork();
732     if (!TEST_int_ge(pid, 0))
733         return 0;
734
735     if (pid > 0) {
736         /* I'm the parent; wait for the child and check its exit code */
737         return TEST_int_eq(waitpid(pid, &status, 0), pid) && TEST_int_eq(status, 0);
738     }
739
740     /* I'm the child; check whether all three DRBGs reseed. */
741     if (!TEST_true(test_drbg_reseed(1, master, public, private, 1, 1, 1, 0)))
742         status = 1;
743
744     /* Remove hooks  */
745     unhook_drbg(master);
746     unhook_drbg(public);
747     unhook_drbg(private);
748     exit(status);
749 }
750 #endif
751
752 /*
753  * Test whether the default rand_method (RAND_OpenSSL()) is
754  * setup correctly, in particular whether reseeding  works
755  * as designed.
756  */
757 static int test_rand_drbg_reseed(void)
758 {
759     RAND_DRBG *master, *public, *private;
760     unsigned char rand_add_buf[256];
761     int rv=0;
762     time_t before_reseed;
763
764     /* Check whether RAND_OpenSSL() is the default method */
765     if (!TEST_ptr_eq(RAND_get_rand_method(), RAND_OpenSSL()))
766         return 0;
767
768     /* All three DRBGs should be non-null */
769     if (!TEST_ptr(master = RAND_DRBG_get0_master())
770         || !TEST_ptr(public = RAND_DRBG_get0_public())
771         || !TEST_ptr(private = RAND_DRBG_get0_private()))
772         return 0;
773
774     /* There should be three distinct DRBGs, two of them chained to master */
775     if (!TEST_ptr_ne(public, private)
776         || !TEST_ptr_ne(public, master)
777         || !TEST_ptr_ne(private, master)
778         || !TEST_ptr_eq(public->parent, master)
779         || !TEST_ptr_eq(private->parent, master))
780         return 0;
781
782     /* Disable CRNG testing for the master DRBG */
783     if (!TEST_true(disable_crngt(master)))
784         return 0;
785
786     /* uninstantiate the three global DRBGs */
787     RAND_DRBG_uninstantiate(private);
788     RAND_DRBG_uninstantiate(public);
789     RAND_DRBG_uninstantiate(master);
790
791
792     /* Install hooks for the following tests */
793     hook_drbg(master,  &master_ctx);
794     hook_drbg(public,  &public_ctx);
795     hook_drbg(private, &private_ctx);
796
797
798     /*
799      * Test initial seeding of shared DRBGs
800      */
801     if (!TEST_true(test_drbg_reseed(1, master, public, private, 1, 1, 1, 0)))
802         goto error;
803     reset_drbg_hook_ctx();
804
805
806     /*
807      * Test initial state of shared DRBGs
808      */
809     if (!TEST_true(test_drbg_reseed(1, master, public, private, 0, 0, 0, 0)))
810         goto error;
811     reset_drbg_hook_ctx();
812
813     /*
814      * Test whether the public and private DRBG are both reseeded when their
815      * reseed counters differ from the master's reseed counter.
816      */
817     master->reseed_prop_counter++;
818     if (!TEST_true(test_drbg_reseed(1, master, public, private, 0, 1, 1, 0)))
819         goto error;
820     reset_drbg_hook_ctx();
821
822     /*
823      * Test whether the public DRBG is reseeded when its reseed counter differs
824      * from the master's reseed counter.
825      */
826     master->reseed_prop_counter++;
827     private->reseed_prop_counter++;
828     if (!TEST_true(test_drbg_reseed(1, master, public, private, 0, 1, 0, 0)))
829         goto error;
830     reset_drbg_hook_ctx();
831
832     /*
833      * Test whether the private DRBG is reseeded when its reseed counter differs
834      * from the master's reseed counter.
835      */
836     master->reseed_prop_counter++;
837     public->reseed_prop_counter++;
838     if (!TEST_true(test_drbg_reseed(1, master, public, private, 0, 0, 1, 0)))
839         goto error;
840     reset_drbg_hook_ctx();
841
842 #if defined(OPENSSL_SYS_UNIX)
843     if (!TEST_true(test_drbg_reseed_after_fork(master, public, private)))
844         goto error;
845 #endif
846
847     /* fill 'randomness' buffer with some arbitrary data */
848     memset(rand_add_buf, 'r', sizeof(rand_add_buf));
849
850 #ifndef FIPS_MODE
851     /*
852      * Test whether all three DRBGs are reseeded by RAND_add().
853      * The before_reseed time has to be measured here and passed into the
854      * test_drbg_reseed() test, because the master DRBG gets already reseeded
855      * in RAND_add(), whence the check for the condition
856      * before_reseed <= master->reseed_time will fail if the time value happens
857      * to increase between the RAND_add() and the test_drbg_reseed() call.
858      */
859     before_reseed = time(NULL);
860     RAND_add(rand_add_buf, sizeof(rand_add_buf), sizeof(rand_add_buf));
861     if (!TEST_true(test_drbg_reseed(1, master, public, private, 1, 1, 1,
862                                     before_reseed)))
863         goto error;
864     reset_drbg_hook_ctx();
865
866
867     /*
868      * Test whether none of the DRBGs is reseed if the master fails to reseed
869      */
870     master_ctx.fail = 1;
871     master->reseed_prop_counter++;
872     RAND_add(rand_add_buf, sizeof(rand_add_buf), sizeof(rand_add_buf));
873     if (!TEST_true(test_drbg_reseed(0, master, public, private, 0, 0, 0, 0)))
874         goto error;
875     reset_drbg_hook_ctx();
876 #else /* FIPS_MODE */
877     /*
878      * In FIPS mode, random data provided by the application via RAND_add()
879      * is not considered a trusted entropy source. It is only treated as
880      * additional_data and no reseeding is forced. This test assures that
881      * no reseeding occurs.
882      */
883     before_reseed = time(NULL);
884     RAND_add(rand_add_buf, sizeof(rand_add_buf), sizeof(rand_add_buf));
885     if (!TEST_true(test_drbg_reseed(1, master, public, private, 0, 0, 0,
886                                     before_reseed)))
887         goto error;
888     reset_drbg_hook_ctx();
889 #endif
890
891     rv = 1;
892
893 error:
894     /* Remove hooks  */
895     unhook_drbg(master);
896     unhook_drbg(public);
897     unhook_drbg(private);
898
899     return rv;
900 }
901
902 #if defined(OPENSSL_THREADS)
903 static int multi_thread_rand_bytes_succeeded = 1;
904 static int multi_thread_rand_priv_bytes_succeeded = 1;
905
906 static void run_multi_thread_test(void)
907 {
908     unsigned char buf[256];
909     time_t start = time(NULL);
910     RAND_DRBG *public = NULL, *private = NULL;
911
912     if (!TEST_ptr(public = RAND_DRBG_get0_public())
913             || !TEST_ptr(private = RAND_DRBG_get0_private())) {
914         multi_thread_rand_bytes_succeeded = 0;
915         return;
916     }
917     RAND_DRBG_set_reseed_time_interval(private, 1);
918     RAND_DRBG_set_reseed_time_interval(public, 1);
919
920     do {
921         if (RAND_bytes(buf, sizeof(buf)) <= 0)
922             multi_thread_rand_bytes_succeeded = 0;
923         if (RAND_priv_bytes(buf, sizeof(buf)) <= 0)
924             multi_thread_rand_priv_bytes_succeeded = 0;
925     }
926     while(time(NULL) - start < 5);
927 }
928
929 # if defined(OPENSSL_SYS_WINDOWS)
930
931 typedef HANDLE thread_t;
932
933 static DWORD WINAPI thread_run(LPVOID arg)
934 {
935     run_multi_thread_test();
936     /*
937      * Because we're linking with a static library, we must stop each
938      * thread explicitly, or so says OPENSSL_thread_stop(3)
939      */
940     OPENSSL_thread_stop();
941     return 0;
942 }
943
944 static int run_thread(thread_t *t)
945 {
946     *t = CreateThread(NULL, 0, thread_run, NULL, 0, NULL);
947     return *t != NULL;
948 }
949
950 static int wait_for_thread(thread_t thread)
951 {
952     return WaitForSingleObject(thread, INFINITE) == 0;
953 }
954
955 # else
956
957 typedef pthread_t thread_t;
958
959 static void *thread_run(void *arg)
960 {
961     run_multi_thread_test();
962     /*
963      * Because we're linking with a static library, we must stop each
964      * thread explicitly, or so says OPENSSL_thread_stop(3)
965      */
966     OPENSSL_thread_stop();
967     return NULL;
968 }
969
970 static int run_thread(thread_t *t)
971 {
972     return pthread_create(t, NULL, thread_run, NULL) == 0;
973 }
974
975 static int wait_for_thread(thread_t thread)
976 {
977     return pthread_join(thread, NULL) == 0;
978 }
979
980 # endif
981
982 /*
983  * The main thread will also run the test, so we'll have THREADS+1 parallel
984  * tests running
985  */
986 # define THREADS 3
987
988 static int test_multi_thread(void)
989 {
990     thread_t t[THREADS];
991     int i;
992
993     for (i = 0; i < THREADS; i++)
994         run_thread(&t[i]);
995     run_multi_thread_test();
996     for (i = 0; i < THREADS; i++)
997         wait_for_thread(t[i]);
998
999     if (!TEST_true(multi_thread_rand_bytes_succeeded))
1000         return 0;
1001     if (!TEST_true(multi_thread_rand_priv_bytes_succeeded))
1002         return 0;
1003
1004     return 1;
1005 }
1006 #endif
1007
1008 /*
1009  * Test that instantiation with RAND_seed() works as expected
1010  *
1011  * If no os entropy source is available then RAND_seed(buffer, bufsize)
1012  * is expected to succeed if and only if the buffer length is at least
1013  * rand_drbg_seedlen(master) bytes.
1014  *
1015  * If an os entropy source is available then RAND_seed(buffer, bufsize)
1016  * is expected to succeed always.
1017  */
1018 static int test_rand_seed(void)
1019 {
1020     RAND_DRBG *master = NULL;
1021     unsigned char rand_buf[256];
1022     size_t rand_buflen;
1023     size_t required_seed_buflen = 0;
1024
1025     if (!TEST_ptr(master = RAND_DRBG_get0_master())
1026         || !TEST_true(disable_crngt(master)))
1027         return 0;
1028
1029 #ifdef OPENSSL_RAND_SEED_NONE
1030     required_seed_buflen = rand_drbg_seedlen(master);
1031 #endif
1032
1033     memset(rand_buf, 0xCD, sizeof(rand_buf));
1034
1035     for ( rand_buflen = 256 ; rand_buflen > 0 ; --rand_buflen ) {
1036         RAND_DRBG_uninstantiate(master);
1037         RAND_seed(rand_buf, rand_buflen);
1038
1039         if (!TEST_int_eq(RAND_status(),
1040                          (rand_buflen >= required_seed_buflen)))
1041             return 0;
1042     }
1043
1044     return 1;
1045 }
1046
1047 /*
1048  * Test that adding additional data with RAND_add() works as expected
1049  * when the master DRBG is instantiated (and below its reseed limit).
1050  *
1051  * This should succeed regardless of whether an os entropy source is
1052  * available or not.
1053  */
1054 static int test_rand_add(void)
1055 {
1056     unsigned char rand_buf[256];
1057     size_t rand_buflen;
1058
1059     memset(rand_buf, 0xCD, sizeof(rand_buf));
1060
1061     /* make sure it's instantiated */
1062     RAND_seed(rand_buf, sizeof(rand_buf));
1063     if (!TEST_true(RAND_status()))
1064         return 0;
1065
1066     for ( rand_buflen = 256 ; rand_buflen > 0 ; --rand_buflen ) {
1067         RAND_add(rand_buf, rand_buflen, 0.0);
1068         if (!TEST_true(RAND_status()))
1069             return 0;
1070     }
1071
1072     return 1;
1073 }
1074
1075 static int test_rand_drbg_prediction_resistance(void)
1076 {
1077     RAND_DRBG *m = NULL, *i = NULL, *s = NULL;
1078     unsigned char buf1[51], buf2[sizeof(buf1)];
1079     int ret = 0, mreseed, ireseed, sreseed;
1080
1081     /* Initialise a three long DRBG chain */
1082     if (!TEST_ptr(m = RAND_DRBG_new(0, 0, NULL))
1083         || !TEST_true(disable_crngt(m))
1084         || !TEST_true(RAND_DRBG_instantiate(m, NULL, 0))
1085         || !TEST_ptr(i = RAND_DRBG_new(0, 0, m))
1086         || !TEST_true(RAND_DRBG_instantiate(i, NULL, 0))
1087         || !TEST_ptr(s = RAND_DRBG_new(0, 0, i))
1088         || !TEST_true(RAND_DRBG_instantiate(s, NULL, 0)))
1089         goto err;
1090
1091     /* During a normal reseed, only the slave DRBG should be reseed */
1092     mreseed = ++m->reseed_prop_counter;
1093     ireseed = ++i->reseed_prop_counter;
1094     sreseed = s->reseed_prop_counter;
1095     if (!TEST_true(RAND_DRBG_reseed(s, NULL, 0, 0))
1096         || !TEST_int_eq(m->reseed_prop_counter, mreseed)
1097         || !TEST_int_eq(i->reseed_prop_counter, ireseed)
1098         || !TEST_int_gt(s->reseed_prop_counter, sreseed))
1099         goto err;
1100
1101     /*
1102      * When prediction resistance is requested, the request should be
1103      * propagated to the master, so that the entire DRBG chain reseeds.
1104      */
1105     sreseed = s->reseed_prop_counter;
1106     if (!TEST_true(RAND_DRBG_reseed(s, NULL, 0, 1))
1107         || !TEST_int_gt(m->reseed_prop_counter, mreseed)
1108         || !TEST_int_gt(i->reseed_prop_counter, ireseed)
1109         || !TEST_int_gt(s->reseed_prop_counter, sreseed))
1110         goto err;
1111
1112     /* During a normal generate, only the slave DRBG should be reseed */
1113     mreseed = ++m->reseed_prop_counter;
1114     ireseed = ++i->reseed_prop_counter;
1115     sreseed = s->reseed_prop_counter;
1116     if (!TEST_true(RAND_DRBG_generate(s, buf1, sizeof(buf1), 0, NULL, 0))
1117         || !TEST_int_eq(m->reseed_prop_counter, mreseed)
1118         || !TEST_int_eq(i->reseed_prop_counter, ireseed)
1119         || !TEST_int_gt(s->reseed_prop_counter, sreseed))
1120         goto err;
1121
1122     /*
1123      * When a prediction resistant generate is requested, the request
1124      * should be propagated to the master, reseeding the entire DRBG chain.
1125      */
1126     sreseed = s->reseed_prop_counter;
1127     if (!TEST_true(RAND_DRBG_generate(s, buf2, sizeof(buf2), 1, NULL, 0))
1128         || !TEST_int_gt(m->reseed_prop_counter, mreseed)
1129         || !TEST_int_gt(i->reseed_prop_counter, ireseed)
1130         || !TEST_int_gt(s->reseed_prop_counter, sreseed)
1131         || !TEST_mem_ne(buf1, sizeof(buf1), buf2, sizeof(buf2)))
1132         goto err;
1133
1134     /* Verify that a normal reseed still only reseeds the slave DRBG */
1135     mreseed = ++m->reseed_prop_counter;
1136     ireseed = ++i->reseed_prop_counter;
1137     sreseed = s->reseed_prop_counter;
1138     if (!TEST_true(RAND_DRBG_reseed(s, NULL, 0, 0))
1139         || !TEST_int_eq(m->reseed_prop_counter, mreseed)
1140         || !TEST_int_eq(i->reseed_prop_counter, ireseed)
1141         || !TEST_int_gt(s->reseed_prop_counter, sreseed))
1142         goto err;
1143
1144     ret = 1;
1145 err:
1146     RAND_DRBG_free(s);
1147     RAND_DRBG_free(i);
1148     RAND_DRBG_free(m);
1149     return ret;
1150 }
1151
1152 static int test_multi_set(void)
1153 {
1154     int rv = 0;
1155     RAND_DRBG *drbg = NULL;
1156
1157     /* init drbg with default CTR initializer */
1158     if (!TEST_ptr(drbg = RAND_DRBG_new(0, 0, NULL))
1159         || !TEST_true(disable_crngt(drbg)))
1160         goto err;
1161     /* change it to use hmac */
1162     if (!TEST_true(RAND_DRBG_set(drbg, NID_sha1, RAND_DRBG_FLAG_HMAC)))
1163         goto err;
1164     /* use same type */
1165     if (!TEST_true(RAND_DRBG_set(drbg, NID_sha1, RAND_DRBG_FLAG_HMAC)))
1166         goto err;
1167     /* change it to use hash */
1168     if (!TEST_true(RAND_DRBG_set(drbg, NID_sha256, 0)))
1169         goto err;
1170     /* use same type */
1171     if (!TEST_true(RAND_DRBG_set(drbg, NID_sha256, 0)))
1172         goto err;
1173     /* change it to use ctr */
1174     if (!TEST_true(RAND_DRBG_set(drbg, NID_aes_192_ctr, 0)))
1175         goto err;
1176     /* use same type */
1177     if (!TEST_true(RAND_DRBG_set(drbg, NID_aes_192_ctr, 0)))
1178         goto err;
1179     if (!TEST_int_gt(RAND_DRBG_instantiate(drbg, NULL, 0), 0))
1180         goto err;
1181
1182     rv = 1;
1183 err:
1184     uninstantiate(drbg);
1185     RAND_DRBG_free(drbg);
1186     return rv;
1187 }
1188
1189 static int test_set_defaults(void)
1190 {
1191     RAND_DRBG *master = NULL, *public = NULL, *private = NULL;
1192
1193            /* Check the default type and flags for master, public and private */
1194     return TEST_ptr(master = RAND_DRBG_get0_master())
1195            && TEST_ptr(public = RAND_DRBG_get0_public())
1196            && TEST_ptr(private = RAND_DRBG_get0_private())
1197            && TEST_int_eq(master->type, RAND_DRBG_TYPE)
1198            && TEST_int_eq(master->flags,
1199                           RAND_DRBG_FLAGS | RAND_DRBG_FLAG_MASTER)
1200            && TEST_int_eq(public->type, RAND_DRBG_TYPE)
1201            && TEST_int_eq(public->flags,
1202                           RAND_DRBG_FLAGS | RAND_DRBG_FLAG_PUBLIC)
1203            && TEST_int_eq(private->type, RAND_DRBG_TYPE)
1204            && TEST_int_eq(private->flags,
1205                           RAND_DRBG_FLAGS | RAND_DRBG_FLAG_PRIVATE)
1206
1207            /* change master DRBG and check again */
1208            && TEST_true(RAND_DRBG_set_defaults(NID_sha256,
1209                                                RAND_DRBG_FLAG_MASTER))
1210            && TEST_true(RAND_DRBG_uninstantiate(master))
1211            && TEST_int_eq(master->type, NID_sha256)
1212            && TEST_int_eq(master->flags, RAND_DRBG_FLAG_MASTER)
1213            && TEST_int_eq(public->type, RAND_DRBG_TYPE)
1214            && TEST_int_eq(public->flags,
1215                           RAND_DRBG_FLAGS | RAND_DRBG_FLAG_PUBLIC)
1216            && TEST_int_eq(private->type, RAND_DRBG_TYPE)
1217            && TEST_int_eq(private->flags,
1218                           RAND_DRBG_FLAGS | RAND_DRBG_FLAG_PRIVATE)
1219            /* change private DRBG and check again */
1220            && TEST_true(RAND_DRBG_set_defaults(NID_sha256,
1221                         RAND_DRBG_FLAG_PRIVATE|RAND_DRBG_FLAG_HMAC))
1222            && TEST_true(RAND_DRBG_uninstantiate(private))
1223            && TEST_int_eq(master->type, NID_sha256)
1224            && TEST_int_eq(master->flags, RAND_DRBG_FLAG_MASTER)
1225            && TEST_int_eq(public->type, RAND_DRBG_TYPE)
1226            && TEST_int_eq(public->flags,
1227                           RAND_DRBG_FLAGS | RAND_DRBG_FLAG_PUBLIC)
1228            && TEST_int_eq(private->type, NID_sha256)
1229            && TEST_int_eq(private->flags,
1230                           RAND_DRBG_FLAG_PRIVATE | RAND_DRBG_FLAG_HMAC)
1231            /* change public DRBG and check again */
1232            && TEST_true(RAND_DRBG_set_defaults(NID_sha1,
1233                                                RAND_DRBG_FLAG_PUBLIC
1234                                                | RAND_DRBG_FLAG_HMAC))
1235            && TEST_true(RAND_DRBG_uninstantiate(public))
1236            && TEST_int_eq(master->type, NID_sha256)
1237            && TEST_int_eq(master->flags, RAND_DRBG_FLAG_MASTER)
1238            && TEST_int_eq(public->type, NID_sha1)
1239            && TEST_int_eq(public->flags,
1240                           RAND_DRBG_FLAG_PUBLIC | RAND_DRBG_FLAG_HMAC)
1241            && TEST_int_eq(private->type, NID_sha256)
1242            && TEST_int_eq(private->flags,
1243                           RAND_DRBG_FLAG_PRIVATE | RAND_DRBG_FLAG_HMAC)
1244            /* Change DRBG defaults and change public and check again */
1245            && TEST_true(RAND_DRBG_set_defaults(NID_sha256, 0))
1246            && TEST_true(RAND_DRBG_uninstantiate(public))
1247            && TEST_int_eq(public->type, NID_sha256)
1248            && TEST_int_eq(public->flags, RAND_DRBG_FLAG_PUBLIC)
1249
1250           /* FIPS mode doesn't support CTR DRBG without a derivation function */
1251 #ifndef FIPS_MODE
1252           /* Change DRBG defaults and change master and check again */
1253            && TEST_true(RAND_DRBG_set_defaults(NID_aes_256_ctr,
1254                                                RAND_DRBG_FLAG_CTR_NO_DF))
1255            && TEST_true(RAND_DRBG_uninstantiate(master))
1256            && TEST_int_eq(master->type, NID_aes_256_ctr)
1257            && TEST_int_eq(master->flags,
1258                           RAND_DRBG_FLAG_MASTER|RAND_DRBG_FLAG_CTR_NO_DF)
1259 #endif
1260            /* Reset back to the standard defaults */
1261            && TEST_true(RAND_DRBG_set_defaults(RAND_DRBG_TYPE,
1262                                                RAND_DRBG_FLAGS
1263                                                | RAND_DRBG_FLAG_MASTER
1264                                                | RAND_DRBG_FLAG_PUBLIC
1265                                                | RAND_DRBG_FLAG_PRIVATE))
1266            && TEST_true(RAND_DRBG_uninstantiate(master))
1267            && TEST_true(RAND_DRBG_uninstantiate(public))
1268            && TEST_true(RAND_DRBG_uninstantiate(private));
1269 }
1270
1271 /*
1272  * A list of the FIPS DRGB types.
1273  * Because of the way HMAC DRGBs are implemented, both the NID and flags
1274  * are required.
1275  */
1276 static const struct s_drgb_types {
1277     int nid;
1278     int flags;
1279 } drgb_types[] = {
1280     { NID_aes_128_ctr,  0                   },
1281     { NID_aes_192_ctr,  0                   },
1282     { NID_aes_256_ctr,  0                   },
1283     { NID_sha1,         0                   },
1284     { NID_sha224,       0                   },
1285     { NID_sha256,       0                   },
1286     { NID_sha384,       0                   },
1287     { NID_sha512,       0                   },
1288     { NID_sha512_224,   0                   },
1289     { NID_sha512_256,   0                   },
1290     { NID_sha3_224,     0                   },
1291     { NID_sha3_256,     0                   },
1292     { NID_sha3_384,     0                   },
1293     { NID_sha3_512,     0                   },
1294     { NID_sha1,         RAND_DRBG_FLAG_HMAC },
1295     { NID_sha224,       RAND_DRBG_FLAG_HMAC },
1296     { NID_sha256,       RAND_DRBG_FLAG_HMAC },
1297     { NID_sha384,       RAND_DRBG_FLAG_HMAC },
1298     { NID_sha512,       RAND_DRBG_FLAG_HMAC },
1299     { NID_sha512_224,   RAND_DRBG_FLAG_HMAC },
1300     { NID_sha512_256,   RAND_DRBG_FLAG_HMAC },
1301     { NID_sha3_224,     RAND_DRBG_FLAG_HMAC },
1302     { NID_sha3_256,     RAND_DRBG_FLAG_HMAC },
1303     { NID_sha3_384,     RAND_DRBG_FLAG_HMAC },
1304     { NID_sha3_512,     RAND_DRBG_FLAG_HMAC },
1305 };
1306
1307 /* Six cases for each covers seed sizes up to 32 bytes */
1308 static const size_t crngt_num_cases = 6;
1309
1310 static size_t crngt_case, crngt_idx;
1311
1312 static int crngt_entropy_cb(OPENSSL_CTX *ctx, RAND_POOL *pool,
1313                             unsigned char *buf, unsigned char *md,
1314                             unsigned int *md_size)
1315 {
1316     size_t i, z;
1317
1318     if (!TEST_int_lt(crngt_idx, crngt_num_cases))
1319         return 0;
1320     /* Generate a block of unique data unless this is the duplication point */
1321     z = crngt_idx++;
1322     if (z > 0 && crngt_case == z)
1323         z--;
1324     for (i = 0; i < CRNGT_BUFSIZ; i++)
1325         buf[i] = (unsigned char)(i + 'A' + z);
1326     return EVP_Digest(buf, CRNGT_BUFSIZ, md, md_size, EVP_sha256(), NULL);
1327 }
1328
1329 static int test_crngt(int n)
1330 {
1331     const struct s_drgb_types *dt = drgb_types + n / crngt_num_cases;
1332     RAND_DRBG *drbg = NULL;
1333     unsigned char buff[100];
1334     size_t ent;
1335     int res = 0;
1336     int expect;
1337     OPENSSL_CTX *ctx = OPENSSL_CTX_new();
1338
1339     if (!TEST_ptr(ctx))
1340         return 0;
1341     if (!TEST_ptr(drbg = RAND_DRBG_new_ex(ctx, dt->nid, dt->flags, NULL)))
1342         goto err;
1343     ent = (drbg->min_entropylen + CRNGT_BUFSIZ - 1) / CRNGT_BUFSIZ;
1344     crngt_case = n % crngt_num_cases;
1345     crngt_idx = 0;
1346     crngt_get_entropy = &crngt_entropy_cb;
1347 #ifndef FIPS_MODE
1348     if (!TEST_true(RAND_DRBG_set_callbacks(drbg, &rand_crngt_get_entropy,
1349                                            &rand_crngt_cleanup_entropy,
1350                                            &rand_drbg_get_nonce,
1351                                            &rand_drbg_cleanup_nonce)))
1352         goto err;
1353 #endif
1354     expect = crngt_case == 0 || crngt_case > ent;
1355     if (!TEST_int_eq(RAND_DRBG_instantiate(drbg, NULL, 0), expect))
1356         goto err;
1357     if (!expect)
1358         goto fin;
1359     if (!TEST_true(RAND_DRBG_generate(drbg, buff, sizeof(buff), 0, NULL, 0)))
1360         goto err;
1361
1362     expect = crngt_case == 0 || crngt_case > 2 * ent;
1363     if (!TEST_int_eq(RAND_DRBG_reseed(drbg, NULL, 0, 0), expect))
1364         goto err;
1365     if (!expect)
1366         goto fin;
1367     if (!TEST_true(RAND_DRBG_generate(drbg, buff, sizeof(buff), 0, NULL, 0)))
1368         goto err;
1369
1370 fin:
1371     res = 1;
1372 err:
1373     if (!res)
1374         TEST_note("DRBG %zd case %zd block %zd", n / crngt_num_cases,
1375                   crngt_case, crngt_idx);
1376     uninstantiate(drbg);
1377     RAND_DRBG_free(drbg);
1378     crngt_get_entropy = &rand_crngt_get_entropy_cb;
1379     OPENSSL_CTX_free(ctx);
1380     return res;
1381 }
1382
1383 int setup_tests(void)
1384 {
1385     app_data_index = RAND_DRBG_get_ex_new_index(0L, NULL, NULL, NULL, NULL);
1386
1387     ADD_ALL_TESTS(test_kats, OSSL_NELEM(drbg_test));
1388     ADD_ALL_TESTS(test_error_checks, OSSL_NELEM(drbg_test));
1389     ADD_TEST(test_rand_drbg_reseed);
1390     ADD_TEST(test_rand_seed);
1391     ADD_TEST(test_rand_add);
1392     ADD_TEST(test_rand_drbg_prediction_resistance);
1393     ADD_TEST(test_multi_set);
1394     ADD_TEST(test_set_defaults);
1395 #if defined(OPENSSL_THREADS)
1396     ADD_TEST(test_multi_thread);
1397 #endif
1398     ADD_ALL_TESTS(test_crngt, crngt_num_cases * OSSL_NELEM(drgb_types));
1399     return 1;
1400 }