tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

drbg.c (38762B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 
      5 #ifdef FREEBL_NO_DEPEND
      6 #include "stubs.h"
      7 #endif
      8 
      9 #include "prerror.h"
     10 #include "secerr.h"
     11 
     12 #include "prtypes.h"
     13 #include "prinit.h"
     14 #include "blapi.h"
     15 #include "blapii.h"
     16 #include "nssilock.h"
     17 #include "secitem.h"
     18 #include "sha_fast.h"
     19 #include "sha256.h"
     20 #include "secrng.h" /* for RNG_SystemRNG() */
     21 #include "secmpi.h"
     22 
     23 /* PRNG_SEEDLEN defined in NIST SP 800-90 section 10.1
     24 * for SHA-1, SHA-224, and SHA-256 it's 440 bits.
     25 * for SHA-384 and SHA-512 it's 888 bits */
     26 #define PRNG_SEEDLEN (440 / PR_BITS_PER_BYTE)
     27 #define PRNG_MAX_ADDITIONAL_BYTES PR_INT64(0x100000000)
     28 /* 2^35 bits or 2^32 bytes */
     29 #define PRNG_MAX_REQUEST_SIZE 0x10000             /* 2^19 bits or 2^16 bytes */
     30 #define PRNG_ADDITONAL_DATA_CACHE_SIZE (8 * 1024) /* must be less than          \
     31                                                   *  PRNG_MAX_ADDITIONAL_BYTES \
     32                                                   */
     33 #define PRNG_ENTROPY_BLOCK_SIZE SHA256_LENGTH
     34 
     35 /* RESEED_COUNT is how many calls to the prng before we need to reseed
     36 * under normal NIST rules, you must return an error. In the NSS case, we
     37 * self-reseed with RNG_SystemRNG(). Count can be a large number. For code
     38 * simplicity, we specify count with 2 components: RESEED_BYTE (which is
     39 * the same as LOG256(RESEED_COUNT)) and RESEED_VALUE (which is the same as
     40 * RESEED_COUNT / (256 ^ RESEED_BYTE)). Another way to look at this is
     41 * RESEED_COUNT = RESEED_VALUE * (256 ^ RESEED_BYTE). For Hash based DRBG
     42 * we use the maximum count value, 2^48, or RESEED_BYTE=6 and RESEED_VALUE=1
     43 */
     44 #define RESEED_BYTE 6
     45 #define RESEED_VALUE 1
     46 
     47 #define PRNG_RESET_RESEED_COUNT(rng)                                    \
     48    PORT_Memset((rng)->reseed_counter, 0, sizeof(rng)->reseed_counter); \
     49    (rng)->reseed_counter[RESEED_BYTE] = 1;
     50 
     51 /*
     52 * The actual values of this enum are specified in SP 800-90, 10.1.1.*
     53 * The spec does not name the types, it only uses bare values
     54 */
     55 typedef enum {
     56    prngCGenerateType = 0,      /* used when creating a new 'C' */
     57    prngReseedType = 1,         /* used in reseeding */
     58    prngAdditionalDataType = 2, /* used in mixing additional data */
     59    prngGenerateByteType = 3    /* used when mixing internal state while
     60                                 * generating bytes */
     61 } prngVTypes;
     62 
     63 /*
     64 * Global RNG context
     65 */
     66 struct RNGContextStr {
     67    PZLock *lock; /* Lock to serialize access to global rng */
     68    /*
     69     * NOTE, a number of steps in the drbg algorithm need to hash
     70     * V_type || V. The code, therefore, depends on the V array following
     71     * immediately after V_type to avoid extra copies. To accomplish this
     72     * in a way that compiliers can't perturb, we declare V_type and V
     73     * as a V_Data array and reference them by macros */
     74    PRUint8 V_Data[PRNG_SEEDLEN + 1]; /* internal state variables */
     75 #define V_type V_Data[0]
     76 #define V(rng) (((rng)->V_Data) + 1)
     77 #define VSize(rng) ((sizeof(rng)->V_Data) - 1)
     78    PRUint8 C[PRNG_SEEDLEN]; /* internal state variables */
     79    /* If we get calls for the PRNG to return less than the length of our
     80     * hash, we extend the request for a full hash (since we'll be doing
     81     * the full hash anyway). Future requests for random numbers are fulfilled
     82     * from the remainder of the bytes we generated. Requests for bytes longer
     83     * than the hash size are fulfilled directly from the HashGen function
     84     * of the random number generator. */
     85    PRUint8 reseed_counter[RESEED_BYTE + 1]; /* number of requests since the
     86                                              * last reseed. Need only be
     87                                              * big enough to hold the whole
     88                                              * reseed count */
     89    PRUint8 data[SHA256_LENGTH];             /* when we request less than a block
     90                                              * save the rest of the rng output for
     91                                              * another partial block */
     92    PRUint8 dataAvail;                       /* # bytes of output available in our cache,
     93                                              * [0...SHA256_LENGTH] */
     94    /* store additional data that has been shovelled off to us by
     95     * RNG_RandomUpdate. */
     96    PRUint8 additionalDataCache[PRNG_ADDITONAL_DATA_CACHE_SIZE];
     97    PRUint32 additionalAvail;
     98    PRBool isValid;   /* false if RNG reaches an invalid state */
     99    PRBool isKatTest; /* true if running NIST PRNG KAT tests */
    100    /* for continuous entropy check */
    101    PRUint8 previousEntropyHash[SHA256_LENGTH];
    102 };
    103 
    104 typedef struct RNGContextStr RNGContext;
    105 static RNGContext *globalrng = NULL;
    106 static RNGContext theGlobalRng;
    107 
    108 /*
    109 * The next several functions are derived from the NIST SP 800-90
    110 * spec. In these functions, an attempt was made to use names consistent
    111 * with the names in the spec, even if they differ from normal NSS usage.
    112 */
    113 
    114 /*
    115 * Hash Derive function defined in NISP SP 800-90 Section 10.4.1.
    116 * This function is used in the Instantiate and Reseed functions.
    117 *
    118 * NOTE: requested_bytes cannot overlap with input_string_1 or input_string_2.
    119 * input_string_1 and input_string_2 are logically concatentated.
    120 * input_string_1 must be supplied.
    121 * if input_string_2 is not supplied, NULL should be passed for this parameter.
    122 */
    123 static SECStatus
    124 prng_Hash_df(PRUint8 *requested_bytes, unsigned int no_of_bytes_to_return,
    125             const PRUint8 *input_string_1, unsigned int input_string_1_len,
    126             const PRUint8 *input_string_2, unsigned int input_string_2_len)
    127 {
    128    SHA256Context ctx;
    129    PRUint32 tmp;
    130    PRUint8 counter;
    131 
    132    tmp = SHA_HTONL(no_of_bytes_to_return * 8);
    133 
    134    for (counter = 1; no_of_bytes_to_return > 0; counter++) {
    135        unsigned int hash_return_len;
    136        SHA256_Begin(&ctx);
    137        SHA256_Update(&ctx, &counter, 1);
    138        SHA256_Update(&ctx, (unsigned char *)&tmp, sizeof(tmp));
    139        SHA256_Update(&ctx, input_string_1, input_string_1_len);
    140        if (input_string_2) {
    141            SHA256_Update(&ctx, input_string_2, input_string_2_len);
    142        }
    143        SHA256_End(&ctx, requested_bytes, &hash_return_len,
    144                   no_of_bytes_to_return);
    145        requested_bytes += hash_return_len;
    146        no_of_bytes_to_return -= hash_return_len;
    147    }
    148    SHA256_DestroyContext(&ctx, PR_FALSE);
    149    return SECSuccess;
    150 }
    151 
    152 /*
    153 * Hash_DRBG Instantiate NIST SP 800-90 10.1.1.2
    154 *
    155 * NOTE: bytes & len are entropy || nonce || personalization_string. In
    156 * normal operation, NSS calculates them all together in a single call.
    157 */
    158 static SECStatus
    159 prng_instantiate(RNGContext *rng, const PRUint8 *bytes, unsigned int len)
    160 {
    161    if (!rng->isKatTest && len < PRNG_SEEDLEN) {
    162        /* If the seedlen is too small, it's probably because we failed to get
    163         * enough random data.
    164         * This is stricter than NIST SP800-90A requires. Don't enforce it for
    165         * tests. */
    166        PORT_SetError(SEC_ERROR_NEED_RANDOM);
    167        return SECFailure;
    168    }
    169    prng_Hash_df(V(rng), VSize(rng), bytes, len, NULL, 0);
    170    rng->V_type = prngCGenerateType;
    171    prng_Hash_df(rng->C, sizeof(rng->C), rng->V_Data, sizeof(rng->V_Data),
    172                 NULL, 0);
    173    PRNG_RESET_RESEED_COUNT(rng)
    174    return SECSuccess;
    175 }
    176 
    177 static PRCallOnceType coRNGInitEntropy;
    178 
    179 static PRStatus
    180 prng_initEntropy(void)
    181 {
    182    size_t length;
    183    PRUint8 block[PRNG_ENTROPY_BLOCK_SIZE];
    184    SHA256Context ctx;
    185 
    186    /* For FIPS 140-2 4.9.2 continuous random number generator test,
    187     * fetch the initial entropy from the system RNG and keep it for
    188     * later comparison. */
    189    length = RNG_SystemRNG(block, sizeof(block));
    190    if (length == 0) {
    191        return PR_FAILURE; /* error is already set */
    192    }
    193    PORT_Assert(length == sizeof(block));
    194 
    195    /* Store the hash of the entropy block rather than the block
    196     * itself for backward secrecy. */
    197    SHA256_Begin(&ctx);
    198    SHA256_Update(&ctx, block, sizeof(block));
    199    SHA256_End(&ctx, globalrng->previousEntropyHash, NULL,
    200               sizeof(globalrng->previousEntropyHash));
    201    PORT_SafeZero(block, sizeof(block));
    202    SHA256_DestroyContext(&ctx, PR_FALSE);
    203    return PR_SUCCESS;
    204 }
    205 
    206 static SECStatus
    207 prng_getEntropy(PRUint8 *buffer, size_t requestLength)
    208 {
    209    size_t total = 0;
    210    PRUint8 block[PRNG_ENTROPY_BLOCK_SIZE];
    211    PRUint8 hash[SHA256_LENGTH];
    212    SHA256Context ctx;
    213    SECStatus rv = SECSuccess;
    214 
    215    if (PR_CallOnce(&coRNGInitEntropy, prng_initEntropy) != PR_SUCCESS) {
    216        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    217        return SECFailure;
    218    }
    219 
    220    /* For FIPS 140-2 4.9.2 continuous random generator test,
    221     * iteratively fetch fixed sized blocks from the system and
    222     * compare consecutive blocks. */
    223    while (total < requestLength) {
    224        size_t length = RNG_SystemRNG(block, sizeof(block));
    225        if (length == 0) {
    226            rv = SECFailure; /* error is already set */
    227            goto out;
    228        }
    229        PORT_Assert(length == sizeof(block));
    230 
    231        /* Store the hash of the entropy block rather than the block
    232         * itself for backward secrecy. */
    233        SHA256_Begin(&ctx);
    234        SHA256_Update(&ctx, block, sizeof(block));
    235        SHA256_End(&ctx, hash, NULL, sizeof(hash));
    236 
    237        if (PORT_Memcmp(globalrng->previousEntropyHash, hash, sizeof(hash)) == 0) {
    238            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    239            rv = SECFailure;
    240            goto out;
    241        }
    242        PORT_Memcpy(globalrng->previousEntropyHash, hash, sizeof(hash));
    243        length = PR_MIN(requestLength - total, sizeof(block));
    244        PORT_Memcpy(buffer, block, length);
    245        total += length;
    246        buffer += length;
    247    }
    248 
    249 out:
    250    PORT_SafeZero(hash, sizeof(hash));
    251    PORT_SafeZero(block, sizeof(block));
    252    return rv;
    253 }
    254 
    255 /*
    256 * Update the global random number generator with more seeding
    257 * material. Use the Hash_DRBG reseed algorithm from NIST SP-800-90
    258 * section 10.1.1.3
    259 *
    260 * If entropy is NULL, it is fetched from the noise generator.
    261 */
    262 static SECStatus
    263 prng_reseed(RNGContext *rng, const PRUint8 *entropy, unsigned int entropy_len,
    264            const PRUint8 *additional_input, unsigned int additional_input_len)
    265 {
    266    PRUint8 noiseData[(sizeof(rng->V_Data)) + PRNG_SEEDLEN];
    267    PRUint8 *noise = &noiseData[0];
    268    SECStatus rv;
    269 
    270    /* if entropy wasn't supplied, fetch it. (normal operation case) */
    271    if (entropy == NULL) {
    272        entropy_len = PRNG_SEEDLEN;
    273        rv = prng_getEntropy(&noiseData[sizeof(rng->V_Data)], entropy_len);
    274        if (rv != SECSuccess) {
    275            return SECFailure; /* error is already set */
    276        }
    277    } else {
    278        /* NOTE: this code is only available for testing, not to applications */
    279        /* if entropy was too big for the stack variable, get it from malloc */
    280        if (entropy_len > PRNG_SEEDLEN) {
    281            noise = PORT_Alloc(entropy_len + (sizeof(rng->V_Data)));
    282            if (noise == NULL) {
    283                return SECFailure;
    284            }
    285        }
    286        PORT_Memcpy(&noise[sizeof(rng->V_Data)], entropy, entropy_len);
    287    }
    288 
    289    if (entropy_len < 256 / PR_BITS_PER_BYTE) {
    290        /* noise == &noiseData[0] at this point, so nothing to free */
    291        PORT_SetError(SEC_ERROR_NEED_RANDOM);
    292        return SECFailure;
    293    }
    294 
    295    rng->V_type = prngReseedType;
    296    PORT_Memcpy(noise, rng->V_Data, sizeof(rng->V_Data));
    297    prng_Hash_df(V(rng), VSize(rng), noise, (sizeof(rng->V_Data)) + entropy_len,
    298                 additional_input, additional_input_len);
    299    /* clear potential CSP */
    300    PORT_Memset(noise, 0, (sizeof(rng->V_Data)) + entropy_len);
    301    rng->V_type = prngCGenerateType;
    302    prng_Hash_df(rng->C, sizeof(rng->C), rng->V_Data, sizeof(rng->V_Data),
    303                 NULL, 0);
    304    PRNG_RESET_RESEED_COUNT(rng)
    305 
    306    if (noise != &noiseData[0]) {
    307        PORT_Free(noise);
    308    }
    309    return SECSuccess;
    310 }
    311 
    312 /*
    313 * SP 800-90 requires we rerun our health tests on reseed
    314 */
    315 static SECStatus
    316 prng_reseed_test(RNGContext *rng, const PRUint8 *entropy,
    317                 unsigned int entropy_len, const PRUint8 *additional_input,
    318                 unsigned int additional_input_len)
    319 {
    320    SECStatus rv;
    321 
    322    /* do health checks in FIPS mode */
    323    rv = PRNGTEST_RunHealthTests();
    324    if (rv != SECSuccess) {
    325        /* error set by PRNGTEST_RunHealTests() */
    326        rng->isValid = PR_FALSE;
    327        return SECFailure;
    328    }
    329    return prng_reseed(rng, entropy, entropy_len,
    330                       additional_input, additional_input_len);
    331 }
    332 
    333 /*
    334 * build some fast inline functions for adding.
    335 */
    336 #define PRNG_ADD_CARRY_ONLY(dest, start, carry)    \
    337    {                                              \
    338        int k1;                                    \
    339        for (k1 = start; carry && k1 >= 0; k1--) { \
    340            carry = !(++dest[k1]);                 \
    341        }                                          \
    342    }
    343 
    344 /*
    345 * NOTE: dest must be an array for the following to work.
    346 */
    347 #define PRNG_ADD_BITS(dest, dest_len, add, len, carry)               \
    348    carry = 0;                                                       \
    349    PORT_Assert((dest_len) >= (len));                                \
    350    {                                                                \
    351        int k1, k2;                                                  \
    352        for (k1 = dest_len - 1, k2 = len - 1; k2 >= 0; --k1, --k2) { \
    353            carry += dest[k1] + add[k2];                             \
    354            dest[k1] = (PRUint8)carry;                               \
    355            carry >>= 8;                                             \
    356        }                                                            \
    357    }
    358 
    359 #define PRNG_ADD_BITS_AND_CARRY(dest, dest_len, add, len, carry) \
    360    PRNG_ADD_BITS(dest, dest_len, add, len, carry)               \
    361    PRNG_ADD_CARRY_ONLY(dest, dest_len - len - 1, carry)
    362 
    363 /*
    364 * This function expands the internal state of the prng to fulfill any number
    365 * of bytes we need for this request. We only use this call if we need more
    366 * than can be supplied by a single call to SHA256_HashBuf.
    367 *
    368 * This function is specified in NIST SP 800-90 section 10.1.1.4, Hashgen
    369 */
    370 static void
    371 prng_Hashgen(RNGContext *rng, PRUint8 *returned_bytes,
    372             unsigned int no_of_returned_bytes)
    373 {
    374    PRUint8 data[VSize(rng)];
    375    PRUint8 thisHash[SHA256_LENGTH];
    376 
    377    PORT_Memcpy(data, V(rng), VSize(rng));
    378    while (no_of_returned_bytes) {
    379        SHA256Context ctx;
    380        unsigned int len;
    381        unsigned int carry;
    382 
    383        SHA256_Begin(&ctx);
    384        SHA256_Update(&ctx, data, sizeof(data));
    385        SHA256_End(&ctx, thisHash, &len, SHA256_LENGTH);
    386        if (no_of_returned_bytes < SHA256_LENGTH) {
    387            len = no_of_returned_bytes;
    388        }
    389        PORT_Memcpy(returned_bytes, thisHash, len);
    390        returned_bytes += len;
    391        no_of_returned_bytes -= len;
    392        /* The carry parameter is a bool (increment or not).
    393         * This increments data if no_of_returned_bytes is not zero */
    394        carry = no_of_returned_bytes;
    395        PRNG_ADD_CARRY_ONLY(data, (sizeof(data)) - 1, carry);
    396        SHA256_DestroyContext(&ctx, PR_FALSE);
    397    }
    398    PORT_SafeZero(data, sizeof(data));
    399    PORT_SafeZero(thisHash, sizeof(thisHash));
    400 }
    401 
    402 /*
    403 * Generates new random bytes and advances the internal prng state.
    404 * additional bytes are only used in algorithm testing.
    405 *
    406 * This function is specified in NIST SP 800-90 section 10.1.1.4
    407 */
    408 static SECStatus
    409 prng_generateNewBytes(RNGContext *rng,
    410                      PRUint8 *returned_bytes, unsigned int no_of_returned_bytes,
    411                      const PRUint8 *additional_input,
    412                      unsigned int additional_input_len)
    413 {
    414    PRUint8 H[SHA256_LENGTH]; /* both H and w since they
    415                               * aren't used concurrently */
    416    unsigned int carry;
    417 
    418    if (!rng->isValid) {
    419        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    420        return SECFailure;
    421    }
    422    /* This code only triggers during tests, normal
    423     * prng operation does not use additional_input */
    424    if (additional_input) {
    425        SHA256Context ctx;
    426 /* NIST SP 800-90 defines two temporaries in their calculations,
    427 * w and H. These temporaries are the same lengths, and used
    428 * at different times, so we use the following macro to collapse
    429 * them to the same variable, but keeping their unique names for
    430 * easy comparison to the spec */
    431 #define w H
    432        rng->V_type = prngAdditionalDataType;
    433        SHA256_Begin(&ctx);
    434        SHA256_Update(&ctx, rng->V_Data, sizeof(rng->V_Data));
    435        SHA256_Update(&ctx, additional_input, additional_input_len);
    436        SHA256_End(&ctx, w, NULL, sizeof(w));
    437        PRNG_ADD_BITS_AND_CARRY(V(rng), VSize(rng), w, sizeof(w), carry)
    438        PORT_Memset(w, 0, sizeof(w));
    439        SHA256_DestroyContext(&ctx, PR_FALSE);
    440 #undef w
    441    }
    442 
    443    if (no_of_returned_bytes == SHA256_LENGTH) {
    444        /* short_cut to hashbuf and a couple of copies and clears */
    445        SHA256_HashBuf(returned_bytes, V(rng), VSize(rng));
    446    } else {
    447        prng_Hashgen(rng, returned_bytes, no_of_returned_bytes);
    448    }
    449    /* advance our internal state... */
    450    rng->V_type = prngGenerateByteType;
    451    SHA256_HashBuf(H, rng->V_Data, sizeof(rng->V_Data));
    452    PRNG_ADD_BITS_AND_CARRY(V(rng), VSize(rng), H, sizeof(H), carry)
    453    PRNG_ADD_BITS(V(rng), VSize(rng), rng->C, sizeof(rng->C), carry);
    454    PRNG_ADD_BITS_AND_CARRY(V(rng), VSize(rng), rng->reseed_counter,
    455                            sizeof(rng->reseed_counter), carry)
    456    carry = 1;
    457    PRNG_ADD_CARRY_ONLY(rng->reseed_counter, (sizeof(rng->reseed_counter)) - 1, carry);
    458 
    459    /* if the prng failed, don't return any output, signal softoken */
    460    PORT_SafeZero(H, sizeof(H));
    461    if (!rng->isValid) {
    462        PORT_Memset(returned_bytes, 0, no_of_returned_bytes);
    463        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    464        return SECFailure;
    465    }
    466    return SECSuccess;
    467 }
    468 
    469 /* Use NSPR to prevent RNG_RNGInit from being called from separate
    470 * threads, creating a race condition.
    471 */
    472 static const PRCallOnceType pristineCallOnce;
    473 static PRCallOnceType coRNGInit;
    474 static PRStatus
    475 rng_init(void)
    476 {
    477    PRUint8 bytes[PRNG_SEEDLEN * 2]; /* entropy + nonce */
    478    SECStatus rv = SECSuccess;
    479 
    480    if (globalrng == NULL) {
    481        /* bytes needs to have enough space to hold
    482         * a SHA256 hash value. Blow up at compile time if this isn't true */
    483        PR_STATIC_ASSERT(sizeof(bytes) >= SHA256_LENGTH);
    484        /* create a new global RNG context */
    485        globalrng = &theGlobalRng;
    486        PORT_Assert(NULL == globalrng->lock);
    487        /* create a lock for it */
    488        globalrng->lock = PZ_NewLock(nssILockOther);
    489        if (globalrng->lock == NULL) {
    490            globalrng = NULL;
    491            PORT_SetError(PR_OUT_OF_MEMORY_ERROR);
    492            return PR_FAILURE;
    493        }
    494 
    495        /* Try to get some seed data for the RNG */
    496        rv = prng_getEntropy(bytes, sizeof(bytes));
    497        if (rv == SECSuccess) {
    498            /* if this is our first call,  instantiate, otherwise reseed
    499             * prng_instantiate gets a new clean state, we want to mix
    500             * any previous entropy we may have collected */
    501            if (V(globalrng)[0] == 0) {
    502                rv = prng_instantiate(globalrng, bytes, sizeof(bytes));
    503            } else {
    504                rv = prng_reseed_test(globalrng, bytes, sizeof(bytes), NULL, 0);
    505            }
    506            memset(bytes, 0, sizeof(bytes));
    507        } else {
    508            PZ_DestroyLock(globalrng->lock);
    509            globalrng->lock = NULL;
    510            globalrng = NULL;
    511            return PR_FAILURE;
    512        }
    513        if (rv != SECSuccess) {
    514            return PR_FAILURE;
    515        }
    516 
    517        /* the RNG is in a valid state */
    518        globalrng->isValid = PR_TRUE;
    519        globalrng->isKatTest = PR_FALSE;
    520 
    521        /* fetch one random value so that we can populate rng->oldV for our
    522         * continous random number test. */
    523        prng_generateNewBytes(globalrng, bytes, SHA256_LENGTH, NULL, 0);
    524 
    525        /* Fetch more entropy into the PRNG */
    526        RNG_SystemInfoForRNG();
    527    }
    528    return PR_SUCCESS;
    529 }
    530 
    531 /*
    532 * Clean up the global RNG context
    533 */
    534 static void
    535 prng_freeRNGContext(RNGContext *rng)
    536 {
    537    PRUint8 inputhash[VSize(rng) + (sizeof(rng->C))];
    538 
    539    /* destroy context lock */
    540    SKIP_AFTER_FORK(PZ_DestroyLock(globalrng->lock));
    541 
    542    /* zero global RNG context except for C & V to preserve entropy */
    543    prng_Hash_df(inputhash, sizeof(rng->C), rng->C, sizeof(rng->C), NULL, 0);
    544    prng_Hash_df(&inputhash[sizeof(rng->C)], VSize(rng), V(rng), VSize(rng),
    545                 NULL, 0);
    546    memset(rng, 0, sizeof(*rng));
    547    memcpy(rng->C, inputhash, sizeof(rng->C));
    548    memcpy(V(rng), &inputhash[sizeof(rng->C)], VSize(rng));
    549 
    550    memset(inputhash, 0, sizeof(inputhash));
    551 }
    552 
    553 /*
    554 * Public functions
    555 */
    556 
    557 /*
    558 * Initialize the global RNG context and give it some seed input taken
    559 * from the system.  This function is thread-safe and will only allow
    560 * the global context to be initialized once.  The seed input is likely
    561 * small, so it is imperative that RNG_RandomUpdate() be called with
    562 * additional seed data before the generator is used.  A good way to
    563 * provide the generator with additional entropy is to call
    564 * RNG_SystemInfoForRNG().  Note that C_Initialize() does exactly that.
    565 */
    566 SECStatus
    567 RNG_RNGInit(void)
    568 {
    569    /* Allow only one call to initialize the context */
    570    PR_CallOnce(&coRNGInit, rng_init);
    571    /* Make sure there is a context */
    572    return (globalrng != NULL) ? SECSuccess : SECFailure;
    573 }
    574 
    575 /*
    576 ** Update the global random number generator with more seeding
    577 ** material.
    578 */
    579 SECStatus
    580 RNG_RandomUpdate(const void *data, size_t bytes)
    581 {
    582    SECStatus rv;
    583 
    584    /* Make sure our assumption that size_t is unsigned is true */
    585    PR_STATIC_ASSERT(((size_t)-1) > (size_t)1);
    586 
    587 #if defined(NS_PTR_GT_32) || (defined(NSS_USE_64) && !defined(NS_PTR_LE_32))
    588    /*
    589     * NIST 800-90 requires us to verify our inputs. This value can
    590     * come from the application, so we need to make sure it's within the
    591     * spec. The spec says it must be less than 2^32 bytes (2^35 bits).
    592     * This can only happen if size_t is greater than 32 bits (i.e. on
    593     * most 64 bit platforms). The 90% case (perhaps 100% case), size_t
    594     * is less than or equal to 32 bits if the platform is not 64 bits, and
    595     * greater than 32 bits if it is a 64 bit platform. The corner
    596     * cases are handled with explicit defines NS_PTR_GT_32 and NS_PTR_LE_32.
    597     *
    598     * In general, neither NS_PTR_GT_32 nor NS_PTR_LE_32 will need to be
    599     * defined. If you trip over the next two size ASSERTS at compile time,
    600     * you will need to define them for your platform.
    601     *
    602     * if 'sizeof(size_t) > 4' is triggered it means that we were expecting
    603     *   sizeof(size_t) to be greater than 4, but it wasn't. Setting
    604     *   NS_PTR_LE_32 will correct that mistake.
    605     *
    606     * if 'sizeof(size_t) <= 4' is triggered, it means that we were expecting
    607     *   sizeof(size_t) to be less than or equal to 4, but it wasn't. Setting
    608     *   NS_PTR_GT_32 will correct that mistake.
    609     */
    610 
    611    PR_STATIC_ASSERT(sizeof(size_t) > 4);
    612 
    613    if (bytes > (size_t)PRNG_MAX_ADDITIONAL_BYTES) {
    614        bytes = PRNG_MAX_ADDITIONAL_BYTES;
    615    }
    616 #else
    617    PR_STATIC_ASSERT(sizeof(size_t) <= 4);
    618 #endif
    619 
    620    PZ_Lock(globalrng->lock);
    621    /* if we're passed more than our additionalDataCache, simply
    622     * call reseed with that data */
    623    if (bytes > sizeof(globalrng->additionalDataCache)) {
    624        rv = prng_reseed_test(globalrng, NULL, 0, data, (unsigned int)bytes);
    625        /* if we aren't going to fill or overflow the buffer, just cache it */
    626    } else if (bytes < ((sizeof(globalrng->additionalDataCache)) - globalrng->additionalAvail)) {
    627        PORT_Memcpy(globalrng->additionalDataCache + globalrng->additionalAvail,
    628                    data, bytes);
    629        globalrng->additionalAvail += (PRUint32)bytes;
    630        rv = SECSuccess;
    631    } else {
    632        /* we are going to fill or overflow the buffer. In this case we will
    633         * fill the entropy buffer, reseed with it, start a new buffer with the
    634         * remainder. We know the remainder will fit in the buffer because
    635         * we already handled the case where bytes > the size of the buffer.
    636         */
    637        size_t bufRemain = (sizeof(globalrng->additionalDataCache)) - globalrng->additionalAvail;
    638        /* fill the rest of the buffer */
    639        if (bufRemain) {
    640            PORT_Memcpy(globalrng->additionalDataCache + globalrng->additionalAvail,
    641                        data, bufRemain);
    642            data = ((unsigned char *)data) + bufRemain;
    643            bytes -= bufRemain;
    644        }
    645        /* reseed from buffer */
    646        rv = prng_reseed_test(globalrng, NULL, 0,
    647                              globalrng->additionalDataCache,
    648                              sizeof(globalrng->additionalDataCache));
    649 
    650        /* copy the rest into the cache */
    651        PORT_Memcpy(globalrng->additionalDataCache, data, bytes);
    652        globalrng->additionalAvail = (PRUint32)bytes;
    653    }
    654 
    655    PZ_Unlock(globalrng->lock);
    656    return rv;
    657 }
    658 
    659 /*
    660 ** Generate some random bytes, using the global random number generator
    661 ** object.
    662 */
    663 static SECStatus
    664 prng_GenerateGlobalRandomBytes(RNGContext *rng,
    665                               void *dest, size_t len)
    666 {
    667    SECStatus rv = SECSuccess;
    668    PRUint8 *output = dest;
    669    /* check for a valid global RNG context */
    670    PORT_Assert(rng != NULL);
    671    if (rng == NULL) {
    672        PORT_SetError(SEC_ERROR_INVALID_ARGS);
    673        return SECFailure;
    674    }
    675    /* FIPS limits the amount of entropy available in a single request */
    676    if (len > PRNG_MAX_REQUEST_SIZE) {
    677        PORT_SetError(SEC_ERROR_INVALID_ARGS);
    678        return SECFailure;
    679    }
    680    /* --- LOCKED --- */
    681    PZ_Lock(rng->lock);
    682    /* Check the amount of seed data in the generator.  If not enough,
    683     * don't produce any data.
    684     */
    685    if (rng->reseed_counter[0] >= RESEED_VALUE) {
    686        rv = prng_reseed_test(rng, NULL, 0, NULL, 0);
    687        PZ_Unlock(rng->lock);
    688        if (rv != SECSuccess) {
    689            return rv;
    690        }
    691        RNG_SystemInfoForRNG();
    692        PZ_Lock(rng->lock);
    693    }
    694    /*
    695     * see if we have enough bytes to fulfill the request.
    696     */
    697    if (len <= rng->dataAvail) {
    698        memcpy(output, rng->data + ((sizeof(rng->data)) - rng->dataAvail), len);
    699        memset(rng->data + ((sizeof(rng->data)) - rng->dataAvail), 0, len);
    700        rng->dataAvail -= len;
    701        rv = SECSuccess;
    702        /* if we are asking for a small number of bytes, cache the rest of
    703         * the bytes */
    704    } else if (len < sizeof(rng->data)) {
    705        rv = prng_generateNewBytes(rng, rng->data, sizeof(rng->data),
    706                                   rng->additionalAvail ? rng->additionalDataCache : NULL,
    707                                   rng->additionalAvail);
    708        rng->additionalAvail = 0;
    709        if (rv == SECSuccess) {
    710            memcpy(output, rng->data, len);
    711            memset(rng->data, 0, len);
    712            rng->dataAvail = (sizeof(rng->data)) - len;
    713        }
    714        /* we are asking for lots of bytes, just ask the generator to pass them */
    715    } else {
    716        rv = prng_generateNewBytes(rng, output, len,
    717                                   rng->additionalAvail ? rng->additionalDataCache : NULL,
    718                                   rng->additionalAvail);
    719        rng->additionalAvail = 0;
    720    }
    721    PZ_Unlock(rng->lock);
    722    /* --- UNLOCKED --- */
    723    return rv;
    724 }
    725 
    726 /*
    727 ** Generate some random bytes, using the global random number generator
    728 ** object.
    729 */
    730 SECStatus
    731 RNG_GenerateGlobalRandomBytes(void *dest, size_t len)
    732 {
    733    return prng_GenerateGlobalRandomBytes(globalrng, dest, len);
    734 }
    735 
    736 void
    737 RNG_RNGShutdown(void)
    738 {
    739    /* check for a valid global RNG context */
    740    PORT_Assert(globalrng != NULL);
    741    if (globalrng == NULL) {
    742        /* Should set a "not initialized" error code. */
    743        PORT_SetError(SEC_ERROR_NO_MEMORY);
    744        return;
    745    }
    746    /* clear */
    747    prng_freeRNGContext(globalrng);
    748    globalrng = NULL;
    749    /* reset the callonce struct to allow a new call to RNG_RNGInit() */
    750    coRNGInit = pristineCallOnce;
    751 }
    752 
    753 /*
    754 * Test case interface. used by fips testing and power on self test
    755 */
    756 /* make sure the test context is separate from the global context, This
    757 * allows us to test the internal random number generator without losing
    758 * entropy we may have previously collected. */
    759 RNGContext testContext;
    760 
    761 SECStatus
    762 PRNGTEST_Instantiate_Kat(const PRUint8 *entropy, unsigned int entropy_len,
    763                         const PRUint8 *nonce, unsigned int nonce_len,
    764                         const PRUint8 *personal_string, unsigned int ps_len)
    765 {
    766    testContext.isKatTest = PR_TRUE;
    767    return PRNGTEST_Instantiate(entropy, entropy_len,
    768                                nonce, nonce_len,
    769                                personal_string, ps_len);
    770 }
    771 
    772 /*
    773 * Test vector API. Use NIST SP 800-90 general interface so one of the
    774 * other NIST SP 800-90 algorithms may be used in the future.
    775 */
    776 SECStatus
    777 PRNGTEST_Instantiate(const PRUint8 *entropy, unsigned int entropy_len,
    778                     const PRUint8 *nonce, unsigned int nonce_len,
    779                     const PRUint8 *personal_string, unsigned int ps_len)
    780 {
    781    int bytes_len = entropy_len + nonce_len + ps_len;
    782    PRUint8 *bytes = NULL;
    783    SECStatus rv;
    784 
    785    if (entropy_len < 256 / PR_BITS_PER_BYTE) {
    786        PORT_SetError(SEC_ERROR_NEED_RANDOM);
    787        return SECFailure;
    788    }
    789 
    790    bytes = PORT_Alloc(bytes_len);
    791    if (bytes == NULL) {
    792        PORT_SetError(SEC_ERROR_NO_MEMORY);
    793        return SECFailure;
    794    }
    795    /* concatenate the various inputs, internally NSS only instantiates with
    796     * a single long string */
    797    PORT_Memcpy(bytes, entropy, entropy_len);
    798    if (nonce) {
    799        PORT_Memcpy(&bytes[entropy_len], nonce, nonce_len);
    800    } else {
    801        PORT_Assert(nonce_len == 0);
    802    }
    803    if (personal_string) {
    804        PORT_Memcpy(&bytes[entropy_len + nonce_len], personal_string, ps_len);
    805    } else {
    806        PORT_Assert(ps_len == 0);
    807    }
    808    rv = prng_instantiate(&testContext, bytes, bytes_len);
    809    PORT_ZFree(bytes, bytes_len);
    810    if (rv == SECFailure) {
    811        return SECFailure;
    812    }
    813    testContext.isValid = PR_TRUE;
    814    return SECSuccess;
    815 }
    816 
    817 SECStatus
    818 PRNGTEST_Reseed(const PRUint8 *entropy, unsigned int entropy_len,
    819                const PRUint8 *additional, unsigned int additional_len)
    820 {
    821    if (!testContext.isValid) {
    822        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    823        return SECFailure;
    824    }
    825    /* This magic input tells us to set the reseed count to it's max count,
    826     * so we can simulate PRNGTEST_Generate reaching max reseed count */
    827    if ((entropy == NULL) && (entropy_len == 0) &&
    828        (additional == NULL) && (additional_len == 0)) {
    829        testContext.reseed_counter[0] = RESEED_VALUE;
    830        return SECSuccess;
    831    }
    832    return prng_reseed(&testContext, entropy, entropy_len, additional,
    833                       additional_len);
    834 }
    835 
    836 SECStatus
    837 PRNGTEST_Generate(PRUint8 *bytes, unsigned int bytes_len,
    838                  const PRUint8 *additional, unsigned int additional_len)
    839 {
    840    SECStatus rv;
    841    if (!testContext.isValid) {
    842        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    843        return SECFailure;
    844    }
    845    /* replicate reseed test from prng_GenerateGlobalRandomBytes */
    846    if (testContext.reseed_counter[0] >= RESEED_VALUE) {
    847        rv = prng_reseed(&testContext, NULL, 0, NULL, 0);
    848        if (rv != SECSuccess) {
    849            return rv;
    850        }
    851    }
    852    return prng_generateNewBytes(&testContext, bytes, bytes_len,
    853                                 additional, additional_len);
    854 }
    855 
    856 SECStatus
    857 PRNGTEST_Uninstantiate()
    858 {
    859    if (!testContext.isValid) {
    860        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    861        return SECFailure;
    862    }
    863    PORT_Memset(&testContext, 0, sizeof(testContext));
    864    return SECSuccess;
    865 }
    866 
    867 SECStatus
    868 PRNGTEST_RunHealthTests()
    869 {
    870    static const PRUint8 entropy[] = {
    871        0x8e, 0x9c, 0x0d, 0x25, 0x75, 0x22, 0x04, 0xf9,
    872        0xc5, 0x79, 0x10, 0x8b, 0x23, 0x79, 0x37, 0x14,
    873        0x9f, 0x2c, 0xc7, 0x0b, 0x39, 0xf8, 0xee, 0xef,
    874        0x95, 0x0c, 0x97, 0x59, 0xfc, 0x0a, 0x85, 0x41,
    875        0x76, 0x9d, 0x6d, 0x67, 0x00, 0x4e, 0x19, 0x12,
    876        0x02, 0x16, 0x53, 0xea, 0xf2, 0x73, 0xd7, 0xd6,
    877        0x7f, 0x7e, 0xc8, 0xae, 0x9c, 0x09, 0x99, 0x7d,
    878        0xbb, 0x9e, 0x48, 0x7f, 0xbb, 0x96, 0x46, 0xb3,
    879        0x03, 0x75, 0xf8, 0xc8, 0x69, 0x45, 0x3f, 0x97,
    880        0x5e, 0x2e, 0x48, 0xe1, 0x5d, 0x58, 0x97, 0x4c
    881    };
    882    static const PRUint8 rng_known_result[] = {
    883        0x16, 0xe1, 0x8c, 0x57, 0x21, 0xd8, 0xf1, 0x7e,
    884        0x5a, 0xa0, 0x16, 0x0b, 0x7e, 0xa6, 0x25, 0xb4,
    885        0x24, 0x19, 0xdb, 0x54, 0xfa, 0x35, 0x13, 0x66,
    886        0xbb, 0xaa, 0x2a, 0x1b, 0x22, 0x33, 0x2e, 0x4a,
    887        0x14, 0x07, 0x9d, 0x52, 0xfc, 0x73, 0x61, 0x48,
    888        0xac, 0xc1, 0x22, 0xfc, 0xa4, 0xfc, 0xac, 0xa4,
    889        0xdb, 0xda, 0x5b, 0x27, 0x33, 0xc4, 0xb3
    890    };
    891    static const PRUint8 reseed_entropy[] = {
    892        0xc6, 0x0b, 0x0a, 0x30, 0x67, 0x07, 0xf4, 0xe2,
    893        0x24, 0xa7, 0x51, 0x6f, 0x5f, 0x85, 0x3e, 0x5d,
    894        0x67, 0x97, 0xb8, 0x3b, 0x30, 0x9c, 0x7a, 0xb1,
    895        0x52, 0xc6, 0x1b, 0xc9, 0x46, 0xa8, 0x62, 0x79
    896    };
    897    static const PRUint8 additional_input[] = {
    898        0x86, 0x82, 0x28, 0x98, 0xe7, 0xcb, 0x01, 0x14,
    899        0xae, 0x87, 0x4b, 0x1d, 0x99, 0x1b, 0xc7, 0x41,
    900        0x33, 0xff, 0x33, 0x66, 0x40, 0x95, 0x54, 0xc6,
    901        0x67, 0x4d, 0x40, 0x2a, 0x1f, 0xf9, 0xeb, 0x65
    902    };
    903    static const PRUint8 rng_reseed_result[] = {
    904        0x02, 0x0c, 0xc6, 0x17, 0x86, 0x49, 0xba, 0xc4,
    905        0x7b, 0x71, 0x35, 0x05, 0xf0, 0xdb, 0x4a, 0xc2,
    906        0x2c, 0x38, 0xc1, 0xa4, 0x42, 0xe5, 0x46, 0x4a,
    907        0x7d, 0xf0, 0xbe, 0x47, 0x88, 0xb8, 0x0e, 0xc6,
    908        0x25, 0x2b, 0x1d, 0x13, 0xef, 0xa6, 0x87, 0x96,
    909        0xa3, 0x7d, 0x5b, 0x80, 0xc2, 0x38, 0x76, 0x61,
    910        0xc7, 0x80, 0x5d, 0x0f, 0x05, 0x76, 0x85
    911    };
    912    static const PRUint8 rng_no_reseed_result[] = {
    913        0xc4, 0x40, 0x41, 0x8c, 0xbf, 0x2f, 0x70, 0x23,
    914        0x88, 0xf2, 0x7b, 0x30, 0xc3, 0xca, 0x1e, 0xf3,
    915        0xef, 0x53, 0x81, 0x5d, 0x30, 0xed, 0x4c, 0xf1,
    916        0xff, 0x89, 0xa5, 0xee, 0x92, 0xf8, 0xc0, 0x0f,
    917        0x88, 0x53, 0xdf, 0xb6, 0x76, 0xf0, 0xaa, 0xd3,
    918        0x2e, 0x1d, 0x64, 0x37, 0x3e, 0xe8, 0x4a, 0x02,
    919        0xff, 0x0a, 0x7f, 0xe5, 0xe9, 0x2b, 0x6d
    920    };
    921 
    922    SECStatus rng_status = SECSuccess;
    923    PR_STATIC_ASSERT(sizeof(rng_known_result) >= sizeof(rng_reseed_result));
    924    PRUint8 result[sizeof(rng_known_result)];
    925 
    926    /********************************************/
    927    /*   First test instantiate error path.     */
    928    /*   In this case we supply enough entropy, */
    929    /*   but not enough seed. This will trigger */
    930    /*   the code that checks for a entropy     */
    931    /*   source failure.                        */
    932    /********************************************/
    933    rng_status = PRNGTEST_Instantiate(entropy, 256 / PR_BITS_PER_BYTE,
    934                                      NULL, 0, NULL, 0);
    935    if (rng_status == SECSuccess) {
    936        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    937        return SECFailure;
    938    }
    939    if (PORT_GetError() != SEC_ERROR_NEED_RANDOM) {
    940        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    941        return SECFailure;
    942    }
    943    /* we failed with the proper error code, we can continue */
    944 
    945    /********************************************/
    946    /* Generate random bytes with a known seed. */
    947    /********************************************/
    948    rng_status = PRNGTEST_Instantiate(entropy, sizeof(entropy),
    949                                      NULL, 0, NULL, 0);
    950    if (rng_status != SECSuccess) {
    951        /* Error set by PRNGTEST_Instantiate */
    952        return SECFailure;
    953    }
    954    rng_status = PRNGTEST_Generate(result, sizeof(rng_known_result), NULL, 0);
    955    if ((rng_status != SECSuccess) ||
    956        (PORT_Memcmp(result, rng_known_result,
    957                     sizeof(rng_known_result)) != 0)) {
    958        PRNGTEST_Uninstantiate();
    959        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    960        return SECFailure;
    961    }
    962    rng_status = PRNGTEST_Reseed(reseed_entropy, sizeof(reseed_entropy),
    963                                 additional_input, sizeof(additional_input));
    964    if (rng_status != SECSuccess) {
    965        /* Error set by PRNG_Reseed */
    966        PRNGTEST_Uninstantiate();
    967        return SECFailure;
    968    }
    969    rng_status = PRNGTEST_Generate(result, sizeof(rng_reseed_result), NULL, 0);
    970    if ((rng_status != SECSuccess) ||
    971        (PORT_Memcmp(result, rng_reseed_result,
    972                     sizeof(rng_reseed_result)) != 0)) {
    973        PRNGTEST_Uninstantiate();
    974        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    975        return SECFailure;
    976    }
    977    /* This magic forces the reseed count to it's max count, so we can see if
    978     * PRNGTEST_Generate will actually when it reaches it's count */
    979    rng_status = PRNGTEST_Reseed(NULL, 0, NULL, 0);
    980    if (rng_status != SECSuccess) {
    981        PRNGTEST_Uninstantiate();
    982        /* Error set by PRNG_Reseed */
    983        return SECFailure;
    984    }
    985    /* This generate should now reseed */
    986    rng_status = PRNGTEST_Generate(result, sizeof(rng_reseed_result), NULL, 0);
    987    if ((rng_status != SECSuccess) ||
    988        /* NOTE we fail if the result is equal to the no_reseed_result.
    989         * no_reseed_result is the value we would have gotten if we didn't
    990         * do an automatic reseed in PRNGTEST_Generate */
    991        (PORT_Memcmp(result, rng_no_reseed_result,
    992                     sizeof(rng_no_reseed_result)) == 0)) {
    993        PRNGTEST_Uninstantiate();
    994        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
    995        return SECFailure;
    996    }
    997    /* make sure reseed fails when we don't supply enough entropy */
    998    rng_status = PRNGTEST_Reseed(reseed_entropy, 4, NULL, 0);
    999    if (rng_status == SECSuccess) {
   1000        PRNGTEST_Uninstantiate();
   1001        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1002        return SECFailure;
   1003    }
   1004    if (PORT_GetError() != SEC_ERROR_NEED_RANDOM) {
   1005        PRNGTEST_Uninstantiate();
   1006        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1007        return SECFailure;
   1008    }
   1009    rng_status = PRNGTEST_Uninstantiate();
   1010    if (rng_status != SECSuccess) {
   1011        /* Error set by PRNG_Uninstantiate */
   1012        return rng_status;
   1013    }
   1014    /* make sure uninstantiate fails if the contest is not initiated (also tests
   1015     * if the context was cleared in the previous Uninstantiate) */
   1016    rng_status = PRNGTEST_Uninstantiate();
   1017    if (rng_status == SECSuccess) {
   1018        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1019        return SECFailure;
   1020    }
   1021    if (PORT_GetError() != SEC_ERROR_LIBRARY_FAILURE) {
   1022        return rng_status;
   1023    }
   1024 
   1025    return SECSuccess;
   1026 }