Home | History | Annotate | Line # | Download | only in rands
      1 /*
      2  * Copyright 2011-2024 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 <openssl/crypto.h>
     12 #include <openssl/err.h>
     13 #include <openssl/rand.h>
     14 #include <openssl/evp.h>
     15 #include "crypto/rand.h"
     16 #include <openssl/proverr.h>
     17 #include "drbg_local.h"
     18 #include "internal/thread_once.h"
     19 #include "crypto/cryptlib.h"
     20 #include "prov/seeding.h"
     21 #include "crypto/rand_pool.h"
     22 #include "prov/provider_ctx.h"
     23 #include "prov/providercommon.h"
     24 
     25 /*
     26  * Support framework for NIST SP 800-90A DRBG
     27  *
     28  * See manual page PROV_DRBG(7) for a general overview.
     29  *
     30  * The OpenSSL model is to have new and free functions, and that new
     31  * does all initialization.  That is not the NIST model, which has
     32  * instantiation and un-instantiate, and re-use within a new/free
     33  * lifecycle.  (No doubt this comes from the desire to support hardware
     34  * DRBG, where allocation of resources on something like an HSM is
     35  * a much bigger deal than just re-setting an allocated resource.)
     36  */
     37 
     38 /* NIST SP 800-90A DRBG recommends the use of a personalization string. */
     39 static const char ossl_pers_string[] = DRBG_DEFAULT_PERS_STRING;
     40 
     41 static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
     42                                       int function);
     43 
     44 static int rand_drbg_restart(PROV_DRBG *drbg);
     45 
     46 int ossl_drbg_lock(void *vctx)
     47 {
     48     PROV_DRBG *drbg = vctx;
     49 
     50     if (drbg == NULL || drbg->lock == NULL)
     51         return 1;
     52     return CRYPTO_THREAD_write_lock(drbg->lock);
     53 }
     54 
     55 void ossl_drbg_unlock(void *vctx)
     56 {
     57     PROV_DRBG *drbg = vctx;
     58 
     59     if (drbg != NULL && drbg->lock != NULL)
     60         CRYPTO_THREAD_unlock(drbg->lock);
     61 }
     62 
     63 static int ossl_drbg_lock_parent(PROV_DRBG *drbg)
     64 {
     65     void *parent = drbg->parent;
     66 
     67     if (parent != NULL
     68             && drbg->parent_lock != NULL
     69             && !drbg->parent_lock(parent)) {
     70         ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
     71         return 0;
     72     }
     73     return 1;
     74 }
     75 
     76 static void ossl_drbg_unlock_parent(PROV_DRBG *drbg)
     77 {
     78     void *parent = drbg->parent;
     79 
     80     if (parent != NULL && drbg->parent_unlock != NULL)
     81         drbg->parent_unlock(parent);
     82 }
     83 
     84 static int get_parent_strength(PROV_DRBG *drbg, unsigned int *str)
     85 {
     86     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
     87     void *parent = drbg->parent;
     88     int res;
     89 
     90     if (drbg->parent_get_ctx_params == NULL) {
     91         ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_GET_PARENT_STRENGTH);
     92         return 0;
     93     }
     94 
     95     *params = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, str);
     96     if (!ossl_drbg_lock_parent(drbg)) {
     97         ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_LOCK_PARENT);
     98         return 0;
     99     }
    100     res = drbg->parent_get_ctx_params(parent, params);
    101     ossl_drbg_unlock_parent(drbg);
    102     if (!res) {
    103         ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_GET_PARENT_STRENGTH);
    104         return 0;
    105     }
    106     return 1;
    107 }
    108 
    109 static unsigned int get_parent_reseed_count(PROV_DRBG *drbg)
    110 {
    111     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
    112     void *parent = drbg->parent;
    113     unsigned int r = 0;
    114 
    115     *params = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_COUNTER, &r);
    116     if (!ossl_drbg_lock_parent(drbg)) {
    117         ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_LOCK_PARENT);
    118         goto err;
    119     }
    120     if (!drbg->parent_get_ctx_params(parent, params))
    121         r = 0;
    122     ossl_drbg_unlock_parent(drbg);
    123     return r;
    124 
    125  err:
    126     r = tsan_load(&drbg->reseed_counter) - 2;
    127     if (r == 0)
    128         r = UINT_MAX;
    129     return r;
    130 }
    131 
    132 /*
    133  * Implements the get_entropy() callback
    134  *
    135  * If the DRBG has a parent, then the required amount of entropy input
    136  * is fetched using the parent's ossl_prov_drbg_generate().
    137  *
    138  * Otherwise, the entropy is polled from the system entropy sources
    139  * using ossl_pool_acquire_entropy().
    140  *
    141  * If a random pool has been added to the DRBG using RAND_add(), then
    142  * its entropy will be used up first.
    143  */
    144 size_t ossl_drbg_get_seed(void *vdrbg, unsigned char **pout,
    145                           int entropy, size_t min_len,
    146                           size_t max_len, int prediction_resistance,
    147                           const unsigned char *adin, size_t adin_len)
    148 {
    149     PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
    150     size_t bytes_needed;
    151     unsigned char *buffer;
    152 
    153     /* Figure out how many bytes we need */
    154     bytes_needed = entropy >= 0 ? (entropy + 7) / 8 : 0;
    155     if (bytes_needed < min_len)
    156         bytes_needed = min_len;
    157     if (bytes_needed > max_len)
    158         bytes_needed = max_len;
    159 
    160     /* Allocate storage */
    161     buffer = OPENSSL_secure_malloc(bytes_needed);
    162     if (buffer == NULL) {
    163         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
    164         return 0;
    165     }
    166 
    167     /*
    168      * Get random data.  Include our DRBG address as
    169      * additional input, in order to provide a distinction between
    170      * different DRBG child instances.
    171      *
    172      * Note: using the sizeof() operator on a pointer triggers
    173      *       a warning in some static code analyzers, but it's
    174      *       intentional and correct here.
    175      */
    176     if (!ossl_prov_drbg_generate(drbg, buffer, bytes_needed,
    177                                  drbg->strength, prediction_resistance,
    178                                  (unsigned char *)&drbg, sizeof(drbg))) {
    179         OPENSSL_secure_clear_free(buffer, bytes_needed);
    180         ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
    181         return 0;
    182     }
    183     *pout = buffer;
    184     return bytes_needed;
    185 }
    186 
    187 /* Implements the cleanup_entropy() callback */
    188 void ossl_drbg_clear_seed(ossl_unused void *vdrbg,
    189                           unsigned char *out, size_t outlen)
    190 {
    191     OPENSSL_secure_clear_free(out, outlen);
    192 }
    193 
    194 static size_t get_entropy(PROV_DRBG *drbg, unsigned char **pout, int entropy,
    195                           size_t min_len, size_t max_len,
    196                           int prediction_resistance)
    197 {
    198     size_t bytes;
    199     unsigned int p_str;
    200 
    201     if (drbg->parent == NULL)
    202 #ifdef FIPS_MODULE
    203         return ossl_crngt_get_entropy(drbg, pout, entropy, min_len, max_len,
    204                                       prediction_resistance);
    205 #else
    206         /*
    207          * In normal use (i.e. OpenSSL's own uses), this is never called.
    208          * Outside of the FIPS provider, OpenSSL sets its DRBGs up so that
    209          * they always have a parent.  This remains purely for legacy reasons.
    210          */
    211         return ossl_prov_get_entropy(drbg->provctx, pout, entropy, min_len,
    212                                      max_len);
    213 #endif
    214 
    215     if (drbg->parent_get_seed == NULL) {
    216         ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_CANNOT_SUPPLY_ENTROPY_SEED);
    217         return 0;
    218     }
    219     if (!get_parent_strength(drbg, &p_str))
    220         return 0;
    221     if (drbg->strength > p_str) {
    222         /*
    223          * We currently don't support the algorithm from NIST SP 800-90C
    224          * 10.1.2 to use a weaker DRBG as source
    225          */
    226         ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
    227         return 0;
    228     }
    229 
    230     /*
    231      * Our lock is already held, but we need to lock our parent before
    232      * generating bits from it.  Note: taking the lock will be a no-op
    233      * if locking is not required (while drbg->parent->lock == NULL).
    234      */
    235     if (!ossl_drbg_lock_parent(drbg))
    236         return 0;
    237     /*
    238      * Get random data from parent.  Include our DRBG address as
    239      * additional input, in order to provide a distinction between
    240      * different DRBG child instances.
    241      *
    242      * Note: using the sizeof() operator on a pointer triggers
    243      *       a warning in some static code analyzers, but it's
    244      *       intentional and correct here.
    245      */
    246     bytes = drbg->parent_get_seed(drbg->parent, pout, drbg->strength,
    247                                   min_len, max_len, prediction_resistance,
    248                                   (unsigned char *)&drbg, sizeof(drbg));
    249     ossl_drbg_unlock_parent(drbg);
    250     return bytes;
    251 }
    252 
    253 static void cleanup_entropy(PROV_DRBG *drbg, unsigned char *out, size_t outlen)
    254 {
    255     if (drbg->parent == NULL) {
    256 #ifdef FIPS_MODULE
    257         ossl_crngt_cleanup_entropy(drbg, out, outlen);
    258 #else
    259         ossl_prov_cleanup_entropy(drbg->provctx, out, outlen);
    260 #endif
    261     } else if (drbg->parent_clear_seed != NULL) {
    262         if (!ossl_drbg_lock_parent(drbg))
    263             return;
    264         drbg->parent_clear_seed(drbg->parent, out, outlen);
    265         ossl_drbg_unlock_parent(drbg);
    266     }
    267 }
    268 
    269 #ifndef PROV_RAND_GET_RANDOM_NONCE
    270 typedef struct prov_drbg_nonce_global_st {
    271     CRYPTO_RWLOCK *rand_nonce_lock;
    272     int rand_nonce_count;
    273 } PROV_DRBG_NONCE_GLOBAL;
    274 
    275 /*
    276  * drbg_ossl_ctx_new() calls drgb_setup() which calls rand_drbg_get_nonce()
    277  * which needs to get the rand_nonce_lock out of the OSSL_LIB_CTX...but since
    278  * drbg_ossl_ctx_new() hasn't finished running yet we need the rand_nonce_lock
    279  * to be in a different global data object. Otherwise we will go into an
    280  * infinite recursion loop.
    281  */
    282 static void *prov_drbg_nonce_ossl_ctx_new(OSSL_LIB_CTX *libctx)
    283 {
    284     PROV_DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
    285 
    286     if (dngbl == NULL)
    287         return NULL;
    288 
    289     dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
    290     if (dngbl->rand_nonce_lock == NULL) {
    291         OPENSSL_free(dngbl);
    292         return NULL;
    293     }
    294 
    295     return dngbl;
    296 }
    297 
    298 static void prov_drbg_nonce_ossl_ctx_free(void *vdngbl)
    299 {
    300     PROV_DRBG_NONCE_GLOBAL *dngbl = vdngbl;
    301 
    302     if (dngbl == NULL)
    303         return;
    304 
    305     CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
    306 
    307     OPENSSL_free(dngbl);
    308 }
    309 
    310 static const OSSL_LIB_CTX_METHOD drbg_nonce_ossl_ctx_method = {
    311     OSSL_LIB_CTX_METHOD_DEFAULT_PRIORITY,
    312     prov_drbg_nonce_ossl_ctx_new,
    313     prov_drbg_nonce_ossl_ctx_free,
    314 };
    315 
    316 /* Get a nonce from the operating system */
    317 static size_t prov_drbg_get_nonce(PROV_DRBG *drbg, unsigned char **pout,
    318                                   size_t min_len, size_t max_len)
    319 {
    320     size_t ret = 0, n;
    321     unsigned char *buf = NULL;
    322     OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(drbg->provctx);
    323     PROV_DRBG_NONCE_GLOBAL *dngbl
    324         = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_NONCE_INDEX,
    325                                 &drbg_nonce_ossl_ctx_method);
    326     struct {
    327         void *drbg;
    328         int count;
    329     } data;
    330 
    331     if (dngbl == NULL)
    332         return 0;
    333 
    334     if (drbg->parent != NULL && drbg->parent_nonce != NULL) {
    335         n = drbg->parent_nonce(drbg->parent, NULL, 0, drbg->min_noncelen,
    336                                drbg->max_noncelen);
    337         if (n > 0 && (buf = OPENSSL_malloc(n)) != NULL) {
    338             ret = drbg->parent_nonce(drbg->parent, buf, 0,
    339                                      drbg->min_noncelen, drbg->max_noncelen);
    340             if (ret == n) {
    341                 *pout = buf;
    342                 return ret;
    343             }
    344             OPENSSL_free(buf);
    345         }
    346     }
    347 
    348     /* Use the built in nonce source plus some of our specifics */
    349     memset(&data, 0, sizeof(data));
    350     data.drbg = drbg;
    351     CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
    352                       dngbl->rand_nonce_lock);
    353     return ossl_prov_get_nonce(drbg->provctx, pout, min_len, max_len,
    354                                &data, sizeof(data));
    355 }
    356 #endif /* PROV_RAND_GET_RANDOM_NONCE */
    357 
    358 /*
    359  * Instantiate |drbg|, after it has been initialized.  Use |pers| and
    360  * |perslen| as prediction-resistance input.
    361  *
    362  * Requires that drbg->lock is already locked for write, if non-null.
    363  *
    364  * Returns 1 on success, 0 on failure.
    365  */
    366 int ossl_prov_drbg_instantiate(PROV_DRBG *drbg, unsigned int strength,
    367                                int prediction_resistance,
    368                                const unsigned char *pers, size_t perslen)
    369 {
    370     unsigned char *nonce = NULL, *entropy = NULL;
    371     size_t noncelen = 0, entropylen = 0;
    372     size_t min_entropy, min_entropylen, max_entropylen;
    373 
    374     if (strength > drbg->strength) {
    375         ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
    376         goto end;
    377     }
    378     min_entropy = drbg->strength;
    379     min_entropylen = drbg->min_entropylen;
    380     max_entropylen = drbg->max_entropylen;
    381 
    382     if (pers == NULL) {
    383         pers = (const unsigned char *)ossl_pers_string;
    384         perslen = sizeof(ossl_pers_string);
    385     }
    386     if (perslen > drbg->max_perslen) {
    387         ERR_raise(ERR_LIB_PROV, PROV_R_PERSONALISATION_STRING_TOO_LONG);
    388         goto end;
    389     }
    390 
    391     if (drbg->state != EVP_RAND_STATE_UNINITIALISED) {
    392         if (drbg->state == EVP_RAND_STATE_ERROR)
    393             ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
    394         else
    395             ERR_raise(ERR_LIB_PROV, PROV_R_ALREADY_INSTANTIATED);
    396         goto end;
    397     }
    398 
    399     drbg->state = EVP_RAND_STATE_ERROR;
    400 
    401     if (drbg->min_noncelen > 0) {
    402         if (drbg->parent_nonce != NULL) {
    403             noncelen = drbg->parent_nonce(drbg->parent, NULL, drbg->strength,
    404                                           drbg->min_noncelen,
    405                                           drbg->max_noncelen);
    406             if (noncelen == 0) {
    407                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
    408                 goto end;
    409             }
    410             nonce = OPENSSL_malloc(noncelen);
    411             if (nonce == NULL) {
    412                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
    413                 goto end;
    414             }
    415             if (noncelen != drbg->parent_nonce(drbg->parent, nonce,
    416                                                drbg->strength,
    417                                                drbg->min_noncelen,
    418                                                drbg->max_noncelen)) {
    419                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
    420                 goto end;
    421             }
    422 #ifndef PROV_RAND_GET_RANDOM_NONCE
    423         } else if (drbg->parent != NULL) {
    424 #endif
    425             /*
    426              * NIST SP800-90Ar1 section 9.1 says you can combine getting
    427              * the entropy and nonce in 1 call by increasing the entropy
    428              * with 50% and increasing the minimum length to accommodate
    429              * the length of the nonce. We do this in case a nonce is
    430              * required and there is no parental nonce capability.
    431              */
    432             min_entropy += drbg->strength / 2;
    433             min_entropylen += drbg->min_noncelen;
    434             max_entropylen += drbg->max_noncelen;
    435         }
    436 #ifndef PROV_RAND_GET_RANDOM_NONCE
    437         else { /* parent == NULL */
    438             noncelen = prov_drbg_get_nonce(drbg, &nonce, drbg->min_noncelen,
    439                                            drbg->max_noncelen);
    440             if (noncelen < drbg->min_noncelen
    441                     || noncelen > drbg->max_noncelen) {
    442                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
    443                 goto end;
    444             }
    445         }
    446 #endif
    447     }
    448 
    449     drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
    450     if (drbg->reseed_next_counter) {
    451         drbg->reseed_next_counter++;
    452         if (!drbg->reseed_next_counter)
    453             drbg->reseed_next_counter = 1;
    454     }
    455 
    456     entropylen = get_entropy(drbg, &entropy, min_entropy,
    457                              min_entropylen, max_entropylen,
    458                              prediction_resistance);
    459     if (entropylen < min_entropylen
    460             || entropylen > max_entropylen) {
    461         ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
    462         goto end;
    463     }
    464 
    465     if (!drbg->instantiate(drbg, entropy, entropylen, nonce, noncelen,
    466                            pers, perslen)) {
    467         cleanup_entropy(drbg, entropy, entropylen);
    468         ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_INSTANTIATING_DRBG);
    469         goto end;
    470     }
    471     cleanup_entropy(drbg, entropy, entropylen);
    472 
    473     drbg->state = EVP_RAND_STATE_READY;
    474     drbg->generate_counter = 1;
    475     drbg->reseed_time = time(NULL);
    476     tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
    477 
    478  end:
    479     if (nonce != NULL)
    480         ossl_prov_cleanup_nonce(drbg->provctx, nonce, noncelen);
    481     if (drbg->state == EVP_RAND_STATE_READY)
    482         return 1;
    483     return 0;
    484 }
    485 
    486 /*
    487  * Uninstantiate |drbg|. Must be instantiated before it can be used.
    488  *
    489  * Requires that drbg->lock is already locked for write, if non-null.
    490  *
    491  * Returns 1 on success, 0 on failure.
    492  */
    493 int ossl_prov_drbg_uninstantiate(PROV_DRBG *drbg)
    494 {
    495     drbg->state = EVP_RAND_STATE_UNINITIALISED;
    496     return 1;
    497 }
    498 
    499 /*
    500  * Reseed |drbg|, mixing in the specified data
    501  *
    502  * Requires that drbg->lock is already locked for write, if non-null.
    503  *
    504  * Returns 1 on success, 0 on failure.
    505  */
    506 int ossl_prov_drbg_reseed(PROV_DRBG *drbg, int prediction_resistance,
    507                           const unsigned char *ent, size_t ent_len,
    508                           const unsigned char *adin, size_t adinlen)
    509 {
    510     unsigned char *entropy = NULL;
    511     size_t entropylen = 0;
    512 
    513     if (!ossl_prov_is_running())
    514         return 0;
    515 
    516     if (drbg->state != EVP_RAND_STATE_READY) {
    517         /* try to recover from previous errors */
    518         rand_drbg_restart(drbg);
    519 
    520         if (drbg->state == EVP_RAND_STATE_ERROR) {
    521             ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
    522             return 0;
    523         }
    524         if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
    525             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
    526             return 0;
    527         }
    528     }
    529 
    530     if (ent != NULL) {
    531         if (ent_len < drbg->min_entropylen) {
    532             ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_OUT_OF_RANGE);
    533             drbg->state = EVP_RAND_STATE_ERROR;
    534             return 0;
    535         }
    536         if (ent_len > drbg->max_entropylen) {
    537             ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_INPUT_TOO_LONG);
    538             drbg->state = EVP_RAND_STATE_ERROR;
    539             return 0;
    540         }
    541     }
    542 
    543     if (adin == NULL) {
    544         adinlen = 0;
    545     } else if (adinlen > drbg->max_adinlen) {
    546         ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
    547         return 0;
    548     }
    549 
    550     drbg->state = EVP_RAND_STATE_ERROR;
    551 
    552     drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
    553     if (drbg->reseed_next_counter) {
    554         drbg->reseed_next_counter++;
    555         if (!drbg->reseed_next_counter)
    556             drbg->reseed_next_counter = 1;
    557     }
    558 
    559     if (ent != NULL) {
    560 #ifdef FIPS_MODULE
    561         /*
    562          * NIST SP-800-90A mandates that entropy *shall not* be provided
    563          * by the consuming application. Instead the data is added as additional
    564          * input.
    565          *
    566          * (NIST SP-800-90Ar1, Sections 9.1 and 9.2)
    567          */
    568         if (!drbg->reseed(drbg, NULL, 0, ent, ent_len)) {
    569             ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
    570             return 0;
    571         }
    572 #else
    573         if (!drbg->reseed(drbg, ent, ent_len, adin, adinlen)) {
    574             ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
    575             return 0;
    576         }
    577         /* There isn't much point adding the same additional input twice */
    578         adin = NULL;
    579         adinlen = 0;
    580 #endif
    581     }
    582 
    583     /* Reseed using our sources in addition */
    584     entropylen = get_entropy(drbg, &entropy, drbg->strength,
    585                              drbg->min_entropylen, drbg->max_entropylen,
    586                              prediction_resistance);
    587     if (entropylen < drbg->min_entropylen
    588             || entropylen > drbg->max_entropylen) {
    589         ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
    590         goto end;
    591     }
    592 
    593     if (!drbg->reseed(drbg, entropy, entropylen, adin, adinlen))
    594         goto end;
    595 
    596     drbg->state = EVP_RAND_STATE_READY;
    597     drbg->generate_counter = 1;
    598     drbg->reseed_time = time(NULL);
    599     tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
    600     if (drbg->parent != NULL)
    601         drbg->parent_reseed_counter = get_parent_reseed_count(drbg);
    602 
    603  end:
    604     cleanup_entropy(drbg, entropy, entropylen);
    605     if (drbg->state == EVP_RAND_STATE_READY)
    606         return 1;
    607     return 0;
    608 }
    609 
    610 /*
    611  * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
    612  * to or if |prediction_resistance| is set.  Additional input can be
    613  * sent in |adin| and |adinlen|.
    614  *
    615  * Requires that drbg->lock is already locked for write, if non-null.
    616  *
    617  * Returns 1 on success, 0 on failure.
    618  *
    619  */
    620 int ossl_prov_drbg_generate(PROV_DRBG *drbg, unsigned char *out, size_t outlen,
    621                             unsigned int strength, int prediction_resistance,
    622                             const unsigned char *adin, size_t adinlen)
    623 {
    624     int fork_id;
    625     int reseed_required = 0;
    626 
    627     if (!ossl_prov_is_running())
    628         return 0;
    629 
    630     if (drbg->state != EVP_RAND_STATE_READY) {
    631         /* try to recover from previous errors */
    632         rand_drbg_restart(drbg);
    633 
    634         if (drbg->state == EVP_RAND_STATE_ERROR) {
    635             ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
    636             return 0;
    637         }
    638         if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
    639             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
    640             return 0;
    641         }
    642     }
    643     if (strength > drbg->strength) {
    644         ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
    645         return 0;
    646     }
    647 
    648     if (outlen > drbg->max_request) {
    649         ERR_raise(ERR_LIB_PROV, PROV_R_REQUEST_TOO_LARGE_FOR_DRBG);
    650         return 0;
    651     }
    652     if (adinlen > drbg->max_adinlen) {
    653         ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
    654         return 0;
    655     }
    656 
    657     fork_id = openssl_get_fork_id();
    658 
    659     if (drbg->fork_id != fork_id) {
    660         drbg->fork_id = fork_id;
    661         reseed_required = 1;
    662     }
    663 
    664     if (drbg->reseed_interval > 0) {
    665         if (drbg->generate_counter >= drbg->reseed_interval)
    666             reseed_required = 1;
    667     }
    668     if (drbg->reseed_time_interval > 0) {
    669         time_t now = time(NULL);
    670         if (now < drbg->reseed_time
    671             || now - drbg->reseed_time >= drbg->reseed_time_interval)
    672             reseed_required = 1;
    673     }
    674     if (drbg->parent != NULL
    675             && get_parent_reseed_count(drbg) != drbg->parent_reseed_counter)
    676         reseed_required = 1;
    677 
    678     if (reseed_required || prediction_resistance) {
    679         if (!ossl_prov_drbg_reseed(drbg, prediction_resistance, NULL, 0,
    680                                    adin, adinlen)) {
    681             ERR_raise(ERR_LIB_PROV, PROV_R_RESEED_ERROR);
    682             return 0;
    683         }
    684         adin = NULL;
    685         adinlen = 0;
    686     }
    687 
    688     if (!drbg->generate(drbg, out, outlen, adin, adinlen)) {
    689         drbg->state = EVP_RAND_STATE_ERROR;
    690         ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
    691         return 0;
    692     }
    693 
    694     drbg->generate_counter++;
    695 
    696     return 1;
    697 }
    698 
    699 /*
    700  * Restart |drbg|, using the specified entropy or additional input
    701  *
    702  * Tries its best to get the drbg instantiated by all means,
    703  * regardless of its current state.
    704  *
    705  * Optionally, a |buffer| of |len| random bytes can be passed,
    706  * which is assumed to contain at least |entropy| bits of entropy.
    707  *
    708  * If |entropy| > 0, the buffer content is used as entropy input.
    709  *
    710  * If |entropy| == 0, the buffer content is used as additional input
    711  *
    712  * Returns 1 on success, 0 on failure.
    713  *
    714  * This function is used internally only.
    715  */
    716 static int rand_drbg_restart(PROV_DRBG *drbg)
    717 {
    718     /* repair error state */
    719     if (drbg->state == EVP_RAND_STATE_ERROR)
    720         drbg->uninstantiate(drbg);
    721 
    722     /* repair uninitialized state */
    723     if (drbg->state == EVP_RAND_STATE_UNINITIALISED)
    724         /* reinstantiate drbg */
    725         ossl_prov_drbg_instantiate(drbg, drbg->strength, 0, NULL, 0);
    726 
    727     return drbg->state == EVP_RAND_STATE_READY;
    728 }
    729 
    730 /* Provider support from here down */
    731 static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
    732                                       int function)
    733 {
    734     if (dispatch != NULL)
    735         while (dispatch->function_id != 0) {
    736             if (dispatch->function_id == function)
    737                 return dispatch;
    738             dispatch++;
    739         }
    740     return NULL;
    741 }
    742 
    743 int ossl_drbg_enable_locking(void *vctx)
    744 {
    745     PROV_DRBG *drbg = vctx;
    746 
    747     if (drbg != NULL && drbg->lock == NULL) {
    748         if (drbg->parent_enable_locking != NULL)
    749             if (!drbg->parent_enable_locking(drbg->parent)) {
    750                 ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
    751                 return 0;
    752             }
    753         drbg->lock = CRYPTO_THREAD_lock_new();
    754         if (drbg->lock == NULL) {
    755             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_CREATE_LOCK);
    756             return 0;
    757         }
    758     }
    759     return 1;
    760 }
    761 
    762 /*
    763  * Allocate memory and initialize a new DRBG. The DRBG is allocated on
    764  * the secure heap if |secure| is nonzero and the secure heap is enabled.
    765  * The |parent|, if not NULL, will be used as random source for reseeding.
    766  * This also requires the parent's provider context and the parent's lock.
    767  *
    768  * Returns a pointer to the new DRBG instance on success, NULL on failure.
    769  */
    770 PROV_DRBG *ossl_rand_drbg_new
    771     (void *provctx, void *parent, const OSSL_DISPATCH *p_dispatch,
    772      int (*dnew)(PROV_DRBG *ctx),
    773      void (*dfree)(void *vctx),
    774      int (*instantiate)(PROV_DRBG *drbg,
    775                         const unsigned char *entropy, size_t entropylen,
    776                         const unsigned char *nonce, size_t noncelen,
    777                         const unsigned char *pers, size_t perslen),
    778      int (*uninstantiate)(PROV_DRBG *ctx),
    779      int (*reseed)(PROV_DRBG *drbg, const unsigned char *ent, size_t ent_len,
    780                    const unsigned char *adin, size_t adin_len),
    781      int (*generate)(PROV_DRBG *, unsigned char *out, size_t outlen,
    782                      const unsigned char *adin, size_t adin_len))
    783 {
    784     PROV_DRBG *drbg;
    785     unsigned int p_str;
    786     const OSSL_DISPATCH *pfunc;
    787 
    788     if (!ossl_prov_is_running())
    789         return NULL;
    790 
    791     drbg = OPENSSL_zalloc(sizeof(*drbg));
    792     if (drbg == NULL) {
    793         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
    794         return NULL;
    795     }
    796 
    797     drbg->provctx = provctx;
    798     drbg->instantiate = instantiate;
    799     drbg->uninstantiate = uninstantiate;
    800     drbg->reseed = reseed;
    801     drbg->generate = generate;
    802     drbg->fork_id = openssl_get_fork_id();
    803 
    804     /* Extract parent's functions */
    805     drbg->parent = parent;
    806     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_ENABLE_LOCKING)) != NULL)
    807         drbg->parent_enable_locking = OSSL_FUNC_rand_enable_locking(pfunc);
    808     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_LOCK)) != NULL)
    809         drbg->parent_lock = OSSL_FUNC_rand_lock(pfunc);
    810     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_UNLOCK)) != NULL)
    811         drbg->parent_unlock = OSSL_FUNC_rand_unlock(pfunc);
    812     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_CTX_PARAMS)) != NULL)
    813         drbg->parent_get_ctx_params = OSSL_FUNC_rand_get_ctx_params(pfunc);
    814     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_NONCE)) != NULL)
    815         drbg->parent_nonce = OSSL_FUNC_rand_nonce(pfunc);
    816     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_SEED)) != NULL)
    817         drbg->parent_get_seed = OSSL_FUNC_rand_get_seed(pfunc);
    818     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_CLEAR_SEED)) != NULL)
    819         drbg->parent_clear_seed = OSSL_FUNC_rand_clear_seed(pfunc);
    820 
    821     /* Set some default maximums up */
    822     drbg->max_entropylen = DRBG_MAX_LENGTH;
    823     drbg->max_noncelen = DRBG_MAX_LENGTH;
    824     drbg->max_perslen = DRBG_MAX_LENGTH;
    825     drbg->max_adinlen = DRBG_MAX_LENGTH;
    826     drbg->generate_counter = 1;
    827     drbg->reseed_counter = 1;
    828     drbg->reseed_interval = RESEED_INTERVAL;
    829     drbg->reseed_time_interval = TIME_INTERVAL;
    830 
    831     if (!dnew(drbg))
    832         goto err;
    833 
    834     if (parent != NULL) {
    835         if (!get_parent_strength(drbg, &p_str))
    836             goto err;
    837         if (drbg->strength > p_str) {
    838             /*
    839              * We currently don't support the algorithm from NIST SP 800-90C
    840              * 10.1.2 to use a weaker DRBG as source
    841              */
    842             ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
    843             goto err;
    844         }
    845     }
    846 #ifdef TSAN_REQUIRES_LOCKING
    847     if (!ossl_drbg_enable_locking(drbg))
    848         goto err;
    849 #endif
    850     return drbg;
    851 
    852  err:
    853     dfree(drbg);
    854     return NULL;
    855 }
    856 
    857 void ossl_rand_drbg_free(PROV_DRBG *drbg)
    858 {
    859     if (drbg == NULL)
    860         return;
    861 
    862     CRYPTO_THREAD_lock_free(drbg->lock);
    863     OPENSSL_free(drbg);
    864 }
    865 
    866 int ossl_drbg_get_ctx_params(PROV_DRBG *drbg, OSSL_PARAM params[])
    867 {
    868     OSSL_PARAM *p;
    869 
    870     p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE);
    871     if (p != NULL && !OSSL_PARAM_set_int(p, drbg->state))
    872         return 0;
    873 
    874     p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH);
    875     if (p != NULL && !OSSL_PARAM_set_int(p, drbg->strength))
    876         return 0;
    877 
    878     p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST);
    879     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_request))
    880         return 0;
    881 
    882     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_ENTROPYLEN);
    883     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_entropylen))
    884         return 0;
    885 
    886     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ENTROPYLEN);
    887     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_entropylen))
    888         return 0;
    889 
    890     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_NONCELEN);
    891     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_noncelen))
    892         return 0;
    893 
    894     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_NONCELEN);
    895     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_noncelen))
    896         return 0;
    897 
    898     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_PERSLEN);
    899     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_perslen))
    900         return 0;
    901 
    902     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ADINLEN);
    903     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_adinlen))
    904         return 0;
    905 
    906     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
    907     if (p != NULL && !OSSL_PARAM_set_uint(p, drbg->reseed_interval))
    908         return 0;
    909 
    910     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME);
    911     if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time))
    912         return 0;
    913 
    914     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
    915     if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time_interval))
    916         return 0;
    917 
    918     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_COUNTER);
    919     if (p != NULL
    920             && !OSSL_PARAM_set_uint(p, tsan_load(&drbg->reseed_counter)))
    921         return 0;
    922     return 1;
    923 }
    924 
    925 int ossl_drbg_set_ctx_params(PROV_DRBG *drbg, const OSSL_PARAM params[])
    926 {
    927     const OSSL_PARAM *p;
    928 
    929     if (params == NULL)
    930         return 1;
    931 
    932     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
    933     if (p != NULL && !OSSL_PARAM_get_uint(p, &drbg->reseed_interval))
    934         return 0;
    935 
    936     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
    937     if (p != NULL && !OSSL_PARAM_get_time_t(p, &drbg->reseed_time_interval))
    938         return 0;
    939     return 1;
    940 }
    941