tor-browser

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

rsa.c (56663B)


      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 /*
      6 * RSA key generation, public key op, private key op.
      7 */
      8 #ifdef FREEBL_NO_DEPEND
      9 #include "stubs.h"
     10 #endif
     11 
     12 #include "secerr.h"
     13 
     14 #include "prclist.h"
     15 #include "nssilock.h"
     16 #include "prinit.h"
     17 #include "blapi.h"
     18 #include "mpi.h"
     19 #include "mpprime.h"
     20 #include "mplogic.h"
     21 #include "secmpi.h"
     22 #include "secitem.h"
     23 #include "blapii.h"
     24 
     25 /* The minimal required randomness is 64 bits */
     26 /* EXP_BLINDING_RANDOMNESS_LEN is the length of the randomness in mp_digits */
     27 /* for 32 bits platforts it is 2 mp_digits (= 2 * 32 bits), for 64 bits it is equal to 128 bits */
     28 #define EXP_BLINDING_RANDOMNESS_LEN ((128 + MP_DIGIT_BIT - 1) / MP_DIGIT_BIT)
     29 #define EXP_BLINDING_RANDOMNESS_LEN_BYTES (EXP_BLINDING_RANDOMNESS_LEN * sizeof(mp_digit))
     30 
     31 /*
     32 ** Number of times to attempt to generate a prime (p or q) from a random
     33 ** seed (the seed changes for each iteration).
     34 */
     35 #define MAX_PRIME_GEN_ATTEMPTS 10
     36 /*
     37 ** Number of times to attempt to generate a key.  The primes p and q change
     38 ** for each attempt.
     39 */
     40 #define MAX_KEY_GEN_ATTEMPTS 10
     41 
     42 /* Blinding Parameters max cache size  */
     43 #define RSA_BLINDING_PARAMS_MAX_CACHE_SIZE 20
     44 
     45 /* exponent should not be greater than modulus */
     46 #define BAD_RSA_KEY_SIZE(modLen, expLen)                           \
     47    ((expLen) > (modLen) || (modLen) > RSA_MAX_MODULUS_BITS / 8 || \
     48     (expLen) > RSA_MAX_EXPONENT_BITS / 8)
     49 
     50 struct blindingParamsStr;
     51 typedef struct blindingParamsStr blindingParams;
     52 
     53 struct blindingParamsStr {
     54    blindingParams *next;
     55    mp_int f, g; /* blinding parameter                 */
     56    int counter; /* number of remaining uses of (f, g) */
     57 };
     58 
     59 /*
     60 ** RSABlindingParamsStr
     61 **
     62 ** For discussion of Paul Kocher's timing attack against an RSA private key
     63 ** operation, see http://www.cryptography.com/timingattack/paper.html.  The
     64 ** countermeasure to this attack, known as blinding, is also discussed in
     65 ** the Handbook of Applied Cryptography, 11.118-11.119.
     66 */
     67 struct RSABlindingParamsStr {
     68    /* Blinding-specific parameters */
     69    PRCList link;              /* link to list of structs            */
     70    SECItem modulus;           /* list element "key"                 */
     71    blindingParams *free, *bp; /* Blinding parameters queue          */
     72    blindingParams array[RSA_BLINDING_PARAMS_MAX_CACHE_SIZE];
     73    /* precalculate montegomery reduction value */
     74    mp_digit n0i; /* n0i = -( n & MP_DIGIT) ** -1 mod mp_RADIX */
     75 };
     76 typedef struct RSABlindingParamsStr RSABlindingParams;
     77 
     78 /*
     79 ** RSABlindingParamsListStr
     80 **
     81 ** List of key-specific blinding params.  The arena holds the volatile pool
     82 ** of memory for each entry and the list itself.  The lock is for list
     83 ** operations, in this case insertions and iterations, as well as control
     84 ** of the counter for each set of blinding parameters.
     85 */
     86 struct RSABlindingParamsListStr {
     87    PZLock *lock;    /* Lock for the list   */
     88    PRCondVar *cVar; /* Condidtion Variable */
     89    int waitCount;   /* Number of threads waiting on cVar */
     90    PRCList head;    /* Pointer to the list */
     91 };
     92 
     93 /*
     94 ** The master blinding params list.
     95 */
     96 static struct RSABlindingParamsListStr blindingParamsList = { 0 };
     97 
     98 /* Number of times to reuse (f, g).  Suggested by Paul Kocher */
     99 #define RSA_BLINDING_PARAMS_MAX_REUSE 50
    100 
    101 /* Global, allows optional use of blinding.  On by default. */
    102 /* Cannot be changed at the moment, due to thread-safety issues. */
    103 static const PRBool nssRSAUseBlinding = PR_TRUE;
    104 
    105 static SECStatus
    106 rsa_build_from_primes(const mp_int *p, const mp_int *q,
    107                      mp_int *e, PRBool needPublicExponent,
    108                      mp_int *d, PRBool needPrivateExponent,
    109                      RSAPrivateKey *key, unsigned int keySizeInBits)
    110 {
    111    mp_int n, phi;
    112    mp_int psub1, qsub1, tmp;
    113    mp_err err = MP_OKAY;
    114    SECStatus rv = SECSuccess;
    115    MP_DIGITS(&n) = 0;
    116    MP_DIGITS(&phi) = 0;
    117    MP_DIGITS(&psub1) = 0;
    118    MP_DIGITS(&qsub1) = 0;
    119    MP_DIGITS(&tmp) = 0;
    120    CHECK_MPI_OK(mp_init(&n));
    121    CHECK_MPI_OK(mp_init(&phi));
    122    CHECK_MPI_OK(mp_init(&psub1));
    123    CHECK_MPI_OK(mp_init(&qsub1));
    124    CHECK_MPI_OK(mp_init(&tmp));
    125    /* p and q must be distinct. */
    126    if (mp_cmp(p, q) == 0) {
    127        PORT_SetError(SEC_ERROR_NEED_RANDOM);
    128        rv = SECFailure;
    129        goto cleanup;
    130    }
    131    /* 1.  Compute n = p*q */
    132    CHECK_MPI_OK(mp_mul(p, q, &n));
    133    /*     verify that the modulus has the desired number of bits */
    134    if ((unsigned)mpl_significant_bits(&n) != keySizeInBits) {
    135        PORT_SetError(SEC_ERROR_NEED_RANDOM);
    136        rv = SECFailure;
    137        goto cleanup;
    138    }
    139 
    140    /* at least one exponent must be given */
    141    PORT_Assert(!(needPublicExponent && needPrivateExponent));
    142 
    143    /* 2.  Compute phi = lcm((p-1),(q-1)) */
    144    CHECK_MPI_OK(mp_sub_d(p, 1, &psub1));
    145    CHECK_MPI_OK(mp_sub_d(q, 1, &qsub1));
    146    CHECK_MPI_OK(mp_lcm(&psub1, &qsub1, &phi));
    147    if (needPublicExponent || needPrivateExponent) {
    148        /* 3.  Compute d = e**-1 mod(phi) */
    149        /*     or      e = d**-1 mod(phi) as necessary */
    150        if (needPublicExponent) {
    151            err = mp_invmod(d, &phi, e);
    152        } else {
    153            err = mp_invmod(e, &phi, d);
    154        }
    155    } else {
    156        err = MP_OKAY;
    157    }
    158    /*     Verify that phi(n) and e have no common divisors */
    159    if (err != MP_OKAY) {
    160        if (err == MP_UNDEF) {
    161            PORT_SetError(SEC_ERROR_NEED_RANDOM);
    162            err = MP_OKAY; /* to keep PORT_SetError from being called again */
    163            rv = SECFailure;
    164        }
    165        goto cleanup;
    166    }
    167 
    168    /* make sure we weren't passed in a d or e = 1 mod phi */
    169    /* just need to check d, because if one is = 1 mod phi, they both are */
    170    CHECK_MPI_OK(mp_mod(d, &phi, &tmp));
    171    if (mp_cmp_d(&tmp, 1) == MP_EQ) {
    172        PORT_SetError(SEC_ERROR_INVALID_ARGS);
    173        rv = SECFailure;
    174        goto cleanup;
    175    }
    176 
    177    /* 4.  Compute exponent1 = d mod (p-1) */
    178    CHECK_MPI_OK(mp_mod(d, &psub1, &tmp));
    179    MPINT_TO_SECITEM(&tmp, &key->exponent1, key->arena);
    180    /* 5.  Compute exponent2 = d mod (q-1) */
    181    CHECK_MPI_OK(mp_mod(d, &qsub1, &tmp));
    182    MPINT_TO_SECITEM(&tmp, &key->exponent2, key->arena);
    183    /* 6.  Compute coefficient = q**-1 mod p */
    184    CHECK_MPI_OK(mp_invmod(q, p, &tmp));
    185    MPINT_TO_SECITEM(&tmp, &key->coefficient, key->arena);
    186 
    187    /* copy our calculated results, overwrite what is there */
    188    key->modulus.data = NULL;
    189    MPINT_TO_SECITEM(&n, &key->modulus, key->arena);
    190    key->privateExponent.data = NULL;
    191    MPINT_TO_SECITEM(d, &key->privateExponent, key->arena);
    192    key->publicExponent.data = NULL;
    193    MPINT_TO_SECITEM(e, &key->publicExponent, key->arena);
    194    key->prime1.data = NULL;
    195    MPINT_TO_SECITEM(p, &key->prime1, key->arena);
    196    key->prime2.data = NULL;
    197    MPINT_TO_SECITEM(q, &key->prime2, key->arena);
    198 cleanup:
    199    mp_clear(&n);
    200    mp_clear(&phi);
    201    mp_clear(&psub1);
    202    mp_clear(&qsub1);
    203    mp_clear(&tmp);
    204    if (err) {
    205        MP_TO_SEC_ERROR(err);
    206        rv = SECFailure;
    207    }
    208    return rv;
    209 }
    210 
    211 SECStatus
    212 generate_prime(mp_int *prime, int primeLen)
    213 {
    214    mp_err err = MP_OKAY;
    215    SECStatus rv = SECSuccess;
    216    int piter;
    217    unsigned char *pb = NULL;
    218    pb = PORT_Alloc(primeLen);
    219    if (!pb) {
    220        PORT_SetError(SEC_ERROR_NO_MEMORY);
    221        goto cleanup;
    222    }
    223    for (piter = 0; piter < MAX_PRIME_GEN_ATTEMPTS; piter++) {
    224        CHECK_SEC_OK(RNG_GenerateGlobalRandomBytes(pb, primeLen));
    225        pb[0] |= 0xC0;            /* set two high-order bits */
    226        pb[primeLen - 1] |= 0x01; /* set low-order bit       */
    227        CHECK_MPI_OK(mp_read_unsigned_octets(prime, pb, primeLen));
    228        err = mpp_make_prime_secure(prime, primeLen * 8, PR_FALSE);
    229        if (err != MP_NO)
    230            goto cleanup;
    231        /* keep going while err == MP_NO */
    232    }
    233 cleanup:
    234    if (pb)
    235        PORT_ZFree(pb, primeLen);
    236    if (err) {
    237        MP_TO_SEC_ERROR(err);
    238        rv = SECFailure;
    239    }
    240    return rv;
    241 }
    242 
    243 /*
    244 *  make sure the key components meet fips186 requirements.
    245 */
    246 static PRBool
    247 rsa_fips186_verify(mp_int *p, mp_int *q, mp_int *d, int keySizeInBits)
    248 {
    249    mp_int pq_diff;
    250    mp_err err = MP_OKAY;
    251    PRBool ret = PR_FALSE;
    252 
    253    if (keySizeInBits < 250) {
    254        /* not a valid FIPS length, no point in our other tests */
    255        /* if you are here, and in FIPS mode, you are outside the security
    256         * policy */
    257        return PR_TRUE;
    258    }
    259 
    260    /* p & q are already known to be greater then sqrt(2)*2^(keySize/2-1) */
    261    /* we also know that gcd(p-1,e) = 1 and gcd(q-1,e) = 1 because the
    262     * mp_invmod() function will fail. */
    263    /* now check p-q > 2^(keysize/2-100) */
    264    MP_DIGITS(&pq_diff) = 0;
    265    CHECK_MPI_OK(mp_init(&pq_diff));
    266    /* NSS always has p > q, so we know pq_diff is positive */
    267    CHECK_MPI_OK(mp_sub(p, q, &pq_diff));
    268    if ((unsigned)mpl_significant_bits(&pq_diff) < (keySizeInBits / 2 - 100)) {
    269        goto cleanup;
    270    }
    271    /* now verify d is large enough*/
    272    if ((unsigned)mpl_significant_bits(d) < (keySizeInBits / 2)) {
    273        goto cleanup;
    274    }
    275    ret = PR_TRUE;
    276 
    277 cleanup:
    278    mp_clear(&pq_diff);
    279    return ret;
    280 }
    281 
    282 /*
    283 ** Generate and return a new RSA public and private key.
    284 **  Both keys are encoded in a single RSAPrivateKey structure.
    285 **  "cx" is the random number generator context
    286 **  "keySizeInBits" is the size of the key to be generated, in bits.
    287 **     512, 1024, etc.
    288 **  "publicExponent" when not NULL is a pointer to some data that
    289 **     represents the public exponent to use. The data is a byte
    290 **     encoded integer, in "big endian" order.
    291 */
    292 RSAPrivateKey *
    293 RSA_NewKey(int keySizeInBits, SECItem *publicExponent)
    294 {
    295    unsigned int primeLen;
    296    mp_int p = { 0, 0, 0, NULL };
    297    mp_int q = { 0, 0, 0, NULL };
    298    mp_int e = { 0, 0, 0, NULL };
    299    mp_int d = { 0, 0, 0, NULL };
    300    int kiter;
    301    int max_attempts;
    302    mp_err err = MP_OKAY;
    303    SECStatus rv = SECSuccess;
    304    int prerr = 0;
    305    RSAPrivateKey *key = NULL;
    306    PLArenaPool *arena = NULL;
    307    /* Require key size to be a multiple of 16 bits. */
    308    if (!publicExponent || keySizeInBits % 16 != 0 ||
    309        BAD_RSA_KEY_SIZE((unsigned int)keySizeInBits / 8, publicExponent->len)) {
    310        PORT_SetError(SEC_ERROR_INVALID_ARGS);
    311        return NULL;
    312    }
    313    /* 1.  Set the public exponent and check if it's uneven and greater than 2.*/
    314    MP_DIGITS(&e) = 0;
    315    CHECK_MPI_OK(mp_init(&e));
    316    SECITEM_TO_MPINT(*publicExponent, &e);
    317    if (mp_iseven(&e) || !(mp_cmp_d(&e, 2) > 0)) {
    318        PORT_SetError(SEC_ERROR_INVALID_ARGS);
    319        goto cleanup;
    320    }
    321 #ifndef NSS_FIPS_DISABLED
    322    /* Check that the exponent is not smaller than 65537  */
    323    if (mp_cmp_d(&e, 0x10001) < 0) {
    324        PORT_SetError(SEC_ERROR_INVALID_ARGS);
    325        goto cleanup;
    326    }
    327 #endif
    328 
    329    /* 2. Allocate arena & key */
    330    arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
    331    if (!arena) {
    332        PORT_SetError(SEC_ERROR_NO_MEMORY);
    333        goto cleanup;
    334    }
    335    key = PORT_ArenaZNew(arena, RSAPrivateKey);
    336    if (!key) {
    337        PORT_SetError(SEC_ERROR_NO_MEMORY);
    338        goto cleanup;
    339    }
    340    key->arena = arena;
    341    /* length of primes p and q (in bytes) */
    342    primeLen = keySizeInBits / (2 * PR_BITS_PER_BYTE);
    343    MP_DIGITS(&p) = 0;
    344    MP_DIGITS(&q) = 0;
    345    MP_DIGITS(&d) = 0;
    346    CHECK_MPI_OK(mp_init(&p));
    347    CHECK_MPI_OK(mp_init(&q));
    348    CHECK_MPI_OK(mp_init(&d));
    349    /* 3.  Set the version number (PKCS1 v1.5 says it should be zero) */
    350    SECITEM_AllocItem(arena, &key->version, 1);
    351    key->version.data[0] = 0;
    352 
    353    kiter = 0;
    354    max_attempts = 5 * (keySizeInBits / 2); /* FIPS 186-4 B.3.3 steps 4.7 and 5.8 */
    355    do {
    356        PORT_SetError(0);
    357        CHECK_SEC_OK(generate_prime(&p, primeLen));
    358        CHECK_SEC_OK(generate_prime(&q, primeLen));
    359        /* Assure p > q */
    360        /* NOTE: PKCS #1 does not require p > q, and NSS doesn't use any
    361         * implementation optimization that requires p > q. We can remove
    362         * this code in the future.
    363         */
    364        if (mp_cmp(&p, &q) < 0)
    365            mp_exch(&p, &q);
    366        /* Attempt to use these primes to generate a key */
    367        rv = rsa_build_from_primes(&p, &q,
    368                                   &e, PR_FALSE, /* needPublicExponent=false */
    369                                   &d, PR_TRUE,  /* needPrivateExponent=true */
    370                                   key, keySizeInBits);
    371        if (rv == SECSuccess) {
    372            if (rsa_fips186_verify(&p, &q, &d, keySizeInBits)) {
    373                break;
    374            }
    375            prerr = SEC_ERROR_NEED_RANDOM; /* retry with different values */
    376        } else {
    377            prerr = PORT_GetError();
    378        }
    379        kiter++;
    380        /* loop until have primes */
    381    } while (prerr == SEC_ERROR_NEED_RANDOM && kiter < max_attempts);
    382 
    383 cleanup:
    384    mp_clear(&p);
    385    mp_clear(&q);
    386    mp_clear(&e);
    387    mp_clear(&d);
    388    if (err) {
    389        MP_TO_SEC_ERROR(err);
    390        rv = SECFailure;
    391    }
    392    if (rv && arena) {
    393        PORT_FreeArena(arena, PR_TRUE);
    394        key = NULL;
    395    }
    396    return key;
    397 }
    398 
    399 mp_err
    400 rsa_is_prime(mp_int *p)
    401 {
    402    int res;
    403 
    404    /* run a Fermat test */
    405    res = mpp_fermat(p, 2);
    406    if (res != MP_OKAY) {
    407        return res;
    408    }
    409 
    410    /* If that passed, run some Miller-Rabin tests */
    411    res = mpp_pprime_secure(p, 2);
    412    return res;
    413 }
    414 
    415 /*
    416 * Factorize a RSA modulus n into p and q by using the exponents e and d.
    417 *
    418 * In: e, d, n
    419 * Out: p, q
    420 *
    421 * See Handbook of Applied Cryptography, 8.2.2(i).
    422 *
    423 * The algorithm is probabilistic, it is run 64 times and each run has a 50%
    424 * chance of succeeding with a runtime of O(log(e*d)).
    425 *
    426 * The returned p might be smaller than q.
    427 */
    428 static mp_err
    429 rsa_factorize_n_from_exponents(mp_int *e, mp_int *d, mp_int *p, mp_int *q,
    430                               mp_int *n)
    431 {
    432    /* lambda is the private modulus: e*d = 1 mod lambda */
    433    /* so: e*d - 1 = k*lambda = t*2^s where t is odd */
    434    mp_int klambda;
    435    mp_int t, onetwentyeight;
    436    unsigned long s = 0;
    437    unsigned long i;
    438 
    439    /* cand = a^(t * 2^i) mod n, next_cand = a^(t * 2^(i+1)) mod n */
    440    mp_int a;
    441    mp_int cand;
    442    mp_int next_cand;
    443 
    444    mp_int n_minus_one;
    445    mp_err err = MP_OKAY;
    446 
    447    MP_DIGITS(&klambda) = 0;
    448    MP_DIGITS(&t) = 0;
    449    MP_DIGITS(&a) = 0;
    450    MP_DIGITS(&cand) = 0;
    451    MP_DIGITS(&n_minus_one) = 0;
    452    MP_DIGITS(&next_cand) = 0;
    453    MP_DIGITS(&onetwentyeight) = 0;
    454    CHECK_MPI_OK(mp_init(&klambda));
    455    CHECK_MPI_OK(mp_init(&t));
    456    CHECK_MPI_OK(mp_init(&a));
    457    CHECK_MPI_OK(mp_init(&cand));
    458    CHECK_MPI_OK(mp_init(&n_minus_one));
    459    CHECK_MPI_OK(mp_init(&next_cand));
    460    CHECK_MPI_OK(mp_init(&onetwentyeight));
    461 
    462    mp_set_int(&onetwentyeight, 128);
    463 
    464    /* calculate k*lambda = e*d - 1 */
    465    CHECK_MPI_OK(mp_mul(e, d, &klambda));
    466    CHECK_MPI_OK(mp_sub_d(&klambda, 1, &klambda));
    467 
    468    /* factorize klambda into t*2^s */
    469    CHECK_MPI_OK(mp_copy(&klambda, &t));
    470    while (mpp_divis_d(&t, 2) == MP_YES) {
    471        CHECK_MPI_OK(mp_div_2(&t, &t));
    472        s += 1;
    473    }
    474 
    475    /* precompute n_minus_one = n - 1 */
    476    CHECK_MPI_OK(mp_copy(n, &n_minus_one));
    477    CHECK_MPI_OK(mp_sub_d(&n_minus_one, 1, &n_minus_one));
    478 
    479    /* pick random bases a, each one has a 50% leading to a factorization */
    480    CHECK_MPI_OK(mp_set_int(&a, 2));
    481    /* The following is equivalent to for (a=2, a <= 128, a+=2) */
    482    while (mp_cmp(&a, &onetwentyeight) <= 0) {
    483        /* compute the base cand = a^(t * 2^0) [i = 0] */
    484        CHECK_MPI_OK(mp_exptmod(&a, &t, n, &cand));
    485 
    486        for (i = 0; i < s; i++) {
    487            /* condition 1: skip the base if we hit a trivial factor of n */
    488            if (mp_cmp(&cand, &n_minus_one) == 0 || mp_cmp_d(&cand, 1) == 0) {
    489                break;
    490            }
    491 
    492            /* increase i in a^(t * 2^i) by squaring the number */
    493            CHECK_MPI_OK(mp_exptmod_d(&cand, 2, n, &next_cand));
    494 
    495            /* condition 2: a^(t * 2^(i+1)) = 1 mod n */
    496            if (mp_cmp_d(&next_cand, 1) == 0) {
    497                /* conditions verified, gcd(a^(t * 2^i) - 1, n) is a factor */
    498                CHECK_MPI_OK(mp_sub_d(&cand, 1, &cand));
    499                CHECK_MPI_OK(mp_gcd(&cand, n, p));
    500                if (mp_cmp_d(p, 1) == 0) {
    501                    CHECK_MPI_OK(mp_add_d(&cand, 1, &cand));
    502                    break;
    503                }
    504                CHECK_MPI_OK(mp_div(n, p, q, NULL));
    505                goto cleanup;
    506            }
    507            CHECK_MPI_OK(mp_copy(&next_cand, &cand));
    508        }
    509 
    510        CHECK_MPI_OK(mp_add_d(&a, 2, &a));
    511    }
    512 
    513    /* if we reach here it's likely (2^64 - 1 / 2^64) that d is wrong */
    514    err = MP_RANGE;
    515 
    516 cleanup:
    517    mp_clear(&klambda);
    518    mp_clear(&t);
    519    mp_clear(&a);
    520    mp_clear(&cand);
    521    mp_clear(&n_minus_one);
    522    mp_clear(&next_cand);
    523    mp_clear(&onetwentyeight);
    524    return err;
    525 }
    526 
    527 /*
    528 * Try to find the two primes based on 2 exponents plus a prime.
    529 *
    530 * In: e, d and p.
    531 * Out: p,q.
    532 *
    533 * Step 1, Since d = e**-1 mod phi, we know that d*e == 1 mod phi, or
    534 *  d*e = 1+k*phi, or d*e-1 = k*phi. since d is less than phi and e is
    535 *  usually less than d, then k must be an integer between e-1 and 1
    536 *  (probably on the order of e).
    537 * Step 1a, We can divide k*phi by prime-1 and get k*(q-1). This will reduce
    538 *      the size of our division through the rest of the loop.
    539 * Step 2, Loop through the values k=e-1 to 1 looking for k. k should be on
    540 *  the order or e, and e is typically small. This may take a while for
    541 *  a large random e. We are looking for a k that divides kphi
    542 *  evenly. Once we find a k that divides kphi evenly, we assume it
    543 *  is the true k. It's possible this k is not the 'true' k but has
    544 *  swapped factors of p-1 and/or q-1. Because of this, we
    545 *  tentatively continue Steps 3-6 inside this loop, and may return looking
    546 *  for another k on failure.
    547 * Step 3, Calculate our tentative phi=kphi/k. Note: real phi is (p-1)*(q-1).
    548 * Step 4a, kphi is k*(q-1), so phi is our tenative q-1. q = phi+1.
    549 *      If k is correct, q should be the right length and prime.
    550 * Step 4b, It's possible q-1 and k could have swapped factors. We now have a
    551 *  possible solution that meets our criteria. It may not be the only
    552 *      solution, however, so we keep looking. If we find more than one,
    553 *      we will fail since we cannot determine which is the correct
    554 *      solution, and returning the wrong modulus will compromise both
    555 *      moduli. If no other solution is found, we return the unique solution.
    556 *
    557 * This will return p & q. q may be larger than p in the case that p was given
    558 * and it was the smaller prime.
    559 */
    560 static mp_err
    561 rsa_get_prime_from_exponents(mp_int *e, mp_int *d, mp_int *p, mp_int *q,
    562                             mp_int *n, unsigned int keySizeInBits)
    563 {
    564    mp_int kphi; /* k*phi */
    565    mp_int k;    /* current guess at 'k' */
    566    mp_int phi;  /* (p-1)(q-1) */
    567    mp_int r;    /* remainder */
    568    mp_int tmp;  /* p-1 if p is given */
    569    mp_err err = MP_OKAY;
    570    unsigned int order_k;
    571 
    572    MP_DIGITS(&kphi) = 0;
    573    MP_DIGITS(&phi) = 0;
    574    MP_DIGITS(&k) = 0;
    575    MP_DIGITS(&r) = 0;
    576    MP_DIGITS(&tmp) = 0;
    577    CHECK_MPI_OK(mp_init(&kphi));
    578    CHECK_MPI_OK(mp_init(&phi));
    579    CHECK_MPI_OK(mp_init(&k));
    580    CHECK_MPI_OK(mp_init(&r));
    581    CHECK_MPI_OK(mp_init(&tmp));
    582 
    583    /* our algorithm looks for a factor k whose maximum size is dependent
    584     * on the size of our smallest exponent, which had better be the public
    585     * exponent (if it's the private, the key is vulnerable to a brute force
    586     * attack).
    587     *
    588     * since our factor search is linear, we need to limit the maximum
    589     * size of the public key. this should not be a problem normally, since
    590     * public keys are usually small.
    591     *
    592     * if we want to handle larger public key sizes, we should have
    593     * a version which tries to 'completely' factor k*phi (where completely
    594     * means 'factor into primes, or composites with which are products of
    595     * large primes). Once we have all the factors, we can sort them out and
    596     * try different combinations to form our phi. The risk is if (p-1)/2,
    597     * (q-1)/2, and k are all large primes. In any case if the public key
    598     * is small (order of 20 some bits), then a linear search for k is
    599     * manageable.
    600     */
    601    if (mpl_significant_bits(e) > 23) {
    602        err = MP_RANGE;
    603        goto cleanup;
    604    }
    605 
    606    /* calculate k*phi = e*d - 1 */
    607    CHECK_MPI_OK(mp_mul(e, d, &kphi));
    608    CHECK_MPI_OK(mp_sub_d(&kphi, 1, &kphi));
    609 
    610    /* kphi is (e*d)-1, which is the same as k*(p-1)(q-1)
    611     * d < (p-1)(q-1), therefor k must be less than e-1
    612     * We can narrow down k even more, though. Since p and q are odd and both
    613     * have their high bit set, then we know that phi must be on order of
    614     * keySizeBits.
    615     */
    616    order_k = (unsigned)mpl_significant_bits(&kphi) - keySizeInBits;
    617 
    618    if (order_k <= 1) {
    619        err = MP_RANGE;
    620        goto cleanup;
    621    }
    622 
    623    /* for (k=kinit; order(k) >= order_k; k--) { */
    624    /* k=kinit: k can't be bigger than  kphi/2^(keySizeInBits -1) */
    625    CHECK_MPI_OK(mp_2expt(&k, keySizeInBits - 1));
    626    CHECK_MPI_OK(mp_div(&kphi, &k, &k, NULL));
    627    if (mp_cmp(&k, e) >= 0) {
    628        /* also can't be bigger then e-1 */
    629        CHECK_MPI_OK(mp_sub_d(e, 1, &k));
    630    }
    631 
    632    /* calculate our temp value */
    633    /* This saves recalculating this value when the k guess is wrong, which
    634     * is reasonably frequent. */
    635    /* tmp = p-1 (used to calculate q-1= phi/tmp) */
    636    CHECK_MPI_OK(mp_sub_d(p, 1, &tmp));
    637    CHECK_MPI_OK(mp_div(&kphi, &tmp, &kphi, &r));
    638    if (mp_cmp_z(&r) != 0) {
    639        /* p-1 doesn't divide kphi, some parameter wasn't correct */
    640        err = MP_RANGE;
    641        goto cleanup;
    642    }
    643    mp_zero(q);
    644    /* kphi is now k*(q-1) */
    645 
    646    /* rest of the for loop */
    647    for (; (err == MP_OKAY) && (mpl_significant_bits(&k) >= order_k);
    648         err = mp_sub_d(&k, 1, &k)) {
    649        CHECK_MPI_OK(err);
    650        /* looking for k as a factor of kphi */
    651        CHECK_MPI_OK(mp_div(&kphi, &k, &phi, &r));
    652        if (mp_cmp_z(&r) != 0) {
    653            /* not a factor, try the next one */
    654            continue;
    655        }
    656        /* we have a possible phi, see if it works */
    657        if ((unsigned)mpl_significant_bits(&phi) != keySizeInBits / 2) {
    658            /* phi is not the right size */
    659            continue;
    660        }
    661        /* phi should be divisible by 2, since
    662         * q is odd and phi=(q-1). */
    663        if (mpp_divis_d(&phi, 2) == MP_NO) {
    664            /* phi is not divisible by 4 */
    665            continue;
    666        }
    667        /* we now have a candidate for the second prime */
    668        CHECK_MPI_OK(mp_add_d(&phi, 1, &tmp));
    669 
    670        /* check to make sure it is prime */
    671        err = rsa_is_prime(&tmp);
    672        if (err != MP_OKAY) {
    673            if (err == MP_NO) {
    674                /* No, then we still have the wrong phi */
    675                continue;
    676            }
    677            goto cleanup;
    678        }
    679        /*
    680         * It is possible that we have the wrong phi if
    681         * k_guess*(q_guess-1) = k*(q-1) (k and q-1 have swapped factors).
    682         * since our q_quess is prime, however. We have found a valid
    683         * rsa key because:
    684         *   q is the correct order of magnitude.
    685         *   phi = (p-1)(q-1) where p and q are both primes.
    686         *   e*d mod phi = 1.
    687         * There is no way to know from the info given if this is the
    688         * original key. We never want to return the wrong key because if
    689         * two moduli with the same factor is known, then euclid's gcd
    690         * algorithm can be used to find that factor. Even though the
    691         * caller didn't pass the original modulus, it doesn't mean the
    692         * modulus wasn't known or isn't available somewhere. So to be safe
    693         * if we can't be sure we have the right q, we don't return any.
    694         *
    695         * So to make sure we continue looking for other valid q's. If none
    696         * are found, then we can safely return this one, otherwise we just
    697         * fail */
    698        if (mp_cmp_z(q) != 0) {
    699            /* this is the second valid q, don't return either,
    700             * just fail */
    701            err = MP_RANGE;
    702            break;
    703        }
    704        /* we only have one q so far, save it and if no others are found,
    705         * it's safe to return it */
    706        CHECK_MPI_OK(mp_copy(&tmp, q));
    707        continue;
    708    }
    709    if ((unsigned)mpl_significant_bits(&k) < order_k) {
    710        if (mp_cmp_z(q) == 0) {
    711            /* If we get here, something was wrong with the parameters we
    712             * were given */
    713            err = MP_RANGE;
    714        }
    715    }
    716 cleanup:
    717    mp_clear(&kphi);
    718    mp_clear(&phi);
    719    mp_clear(&k);
    720    mp_clear(&r);
    721    mp_clear(&tmp);
    722    return err;
    723 }
    724 
    725 /*
    726 * take a private key with only a few elements and fill out the missing pieces.
    727 *
    728 * All the entries will be overwritten with data allocated out of the arena
    729 * If no arena is supplied, one will be created.
    730 *
    731 * The following fields must be supplied in order for this function
    732 * to succeed:
    733 *   one of either publicExponent or privateExponent
    734 *   two more of the following 5 parameters.
    735 *      modulus (n)
    736 *      prime1  (p)
    737 *      prime2  (q)
    738 *      publicExponent (e)
    739 *      privateExponent (d)
    740 *
    741 * NOTE: if only the publicExponent, privateExponent, and one prime is given,
    742 * then there may be more than one RSA key that matches that combination.
    743 *
    744 * All parameters will be replaced in the key structure with new parameters
    745 * Allocated out of the arena. There is no attempt to free the old structures.
    746 * Prime1 will always be greater than prime2 (even if the caller supplies the
    747 * smaller prime as prime1 or the larger prime as prime2). The parameters are
    748 * not overwritten on failure.
    749 *
    750 *  How it works:
    751 *     We can generate all the parameters from one of the exponents, plus the
    752 *        two primes. (rsa_build_key_from_primes)
    753 *     If we are given one of the exponents and both primes, we are done.
    754 *     If we are given one of the exponents, the modulus and one prime, we
    755 *        caclulate the second prime by dividing the modulus by the given
    756 *        prime, giving us an exponent and 2 primes.
    757 *     If we are given 2 exponents and one of the primes we calculate
    758 *        k*phi = d*e-1, where k is an integer less than d which
    759 *        divides d*e-1. We find factor k so we can isolate phi.
    760 *            phi = (p-1)(q-1)
    761 *        We can use phi to find the other prime as follows:
    762 *        q = (phi/(p-1)) + 1. We now have 2 primes and an exponent.
    763 *        (NOTE: if more then one prime meets this condition, the operation
    764 *        will fail. See comments elsewhere in this file about this).
    765 *        (rsa_get_prime_from_exponents)
    766 *     If we are given 2 exponents and the modulus we factor the modulus to
    767 *        get the 2 missing primes (rsa_factorize_n_from_exponents)
    768 *
    769 */
    770 SECStatus
    771 RSA_PopulatePrivateKey(RSAPrivateKey *key)
    772 {
    773    PLArenaPool *arena = NULL;
    774    PRBool needPublicExponent = PR_TRUE;
    775    PRBool needPrivateExponent = PR_TRUE;
    776    PRBool hasModulus = PR_FALSE;
    777    unsigned int keySizeInBits = 0;
    778    int prime_count = 0;
    779    /* standard RSA nominclature */
    780    mp_int p, q, e, d, n;
    781    /* remainder */
    782    mp_int r;
    783    mp_err err = 0;
    784    SECStatus rv = SECFailure;
    785 
    786    MP_DIGITS(&p) = 0;
    787    MP_DIGITS(&q) = 0;
    788    MP_DIGITS(&e) = 0;
    789    MP_DIGITS(&d) = 0;
    790    MP_DIGITS(&n) = 0;
    791    MP_DIGITS(&r) = 0;
    792    CHECK_MPI_OK(mp_init(&p));
    793    CHECK_MPI_OK(mp_init(&q));
    794    CHECK_MPI_OK(mp_init(&e));
    795    CHECK_MPI_OK(mp_init(&d));
    796    CHECK_MPI_OK(mp_init(&n));
    797    CHECK_MPI_OK(mp_init(&r));
    798 
    799    /* if the key didn't already have an arena, create one. */
    800    if (key->arena == NULL) {
    801        arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
    802        if (!arena) {
    803            goto cleanup;
    804        }
    805        key->arena = arena;
    806    }
    807 
    808    /* load up the known exponents */
    809    if (key->publicExponent.data) {
    810        SECITEM_TO_MPINT(key->publicExponent, &e);
    811        needPublicExponent = PR_FALSE;
    812    }
    813    if (key->privateExponent.data) {
    814        SECITEM_TO_MPINT(key->privateExponent, &d);
    815        needPrivateExponent = PR_FALSE;
    816    }
    817    if (needPrivateExponent && needPublicExponent) {
    818        /* Not enough information, we need at least one exponent */
    819        err = MP_BADARG;
    820        goto cleanup;
    821    }
    822 
    823    /* load up the known primes. If only one prime is given, it will be
    824     * assigned 'p'. Once we have both primes, well make sure p is the larger.
    825     * The value prime_count tells us howe many we have acquired.
    826     */
    827    if (key->prime1.data) {
    828        int primeLen = key->prime1.len;
    829        if (key->prime1.data[0] == 0) {
    830            primeLen--;
    831        }
    832        keySizeInBits = primeLen * 2 * PR_BITS_PER_BYTE;
    833        SECITEM_TO_MPINT(key->prime1, &p);
    834        prime_count++;
    835    }
    836    if (key->prime2.data) {
    837        int primeLen = key->prime2.len;
    838        if (key->prime2.data[0] == 0) {
    839            primeLen--;
    840        }
    841        keySizeInBits = primeLen * 2 * PR_BITS_PER_BYTE;
    842        SECITEM_TO_MPINT(key->prime2, prime_count ? &q : &p);
    843        prime_count++;
    844    }
    845    /* load up the modulus */
    846    if (key->modulus.data) {
    847        int modLen = key->modulus.len;
    848        if (key->modulus.data[0] == 0) {
    849            modLen--;
    850        }
    851        keySizeInBits = modLen * PR_BITS_PER_BYTE;
    852        SECITEM_TO_MPINT(key->modulus, &n);
    853        hasModulus = PR_TRUE;
    854    }
    855    /* if we have the modulus and one prime, calculate the second. */
    856    if ((prime_count == 1) && (hasModulus)) {
    857        if (mp_div(&n, &p, &q, &r) != MP_OKAY || mp_cmp_z(&r) != 0) {
    858            /* p is not a factor or n, fail */
    859            err = MP_BADARG;
    860            goto cleanup;
    861        }
    862        prime_count++;
    863    }
    864 
    865    /* If we didn't have enough primes try to calculate the primes from
    866     * the exponents */
    867    if (prime_count < 2) {
    868        /* if we don't have at least 2 primes at this point, then we need both
    869         * exponents and one prime or a modulus*/
    870        if (!needPublicExponent && !needPrivateExponent &&
    871            (prime_count > 0)) {
    872            CHECK_MPI_OK(rsa_get_prime_from_exponents(&e, &d, &p, &q, &n,
    873                                                      keySizeInBits));
    874        } else if (!needPublicExponent && !needPrivateExponent && hasModulus) {
    875            CHECK_MPI_OK(rsa_factorize_n_from_exponents(&e, &d, &p, &q, &n));
    876        } else {
    877            /* not enough given parameters to get both primes */
    878            err = MP_BADARG;
    879            goto cleanup;
    880        }
    881    }
    882 
    883    /* Assure p > q */
    884    /* NOTE: PKCS #1 does not require p > q, and NSS doesn't use any
    885     * implementation optimization that requires p > q. We can remove
    886     * this code in the future.
    887     */
    888    if (mp_cmp(&p, &q) < 0)
    889        mp_exch(&p, &q);
    890 
    891    /* we now have our 2 primes and at least one exponent, we can fill
    892     * in the key */
    893    rv = rsa_build_from_primes(&p, &q,
    894                               &e, needPublicExponent,
    895                               &d, needPrivateExponent,
    896                               key, keySizeInBits);
    897 cleanup:
    898    mp_clear(&p);
    899    mp_clear(&q);
    900    mp_clear(&e);
    901    mp_clear(&d);
    902    mp_clear(&n);
    903    mp_clear(&r);
    904    if (err) {
    905        MP_TO_SEC_ERROR(err);
    906        rv = SECFailure;
    907    }
    908    if (rv && arena) {
    909        PORT_FreeArena(arena, PR_TRUE);
    910        key->arena = NULL;
    911    }
    912    return rv;
    913 }
    914 
    915 static unsigned int
    916 rsa_modulusLen(SECItem *modulus)
    917 {
    918    if (modulus->len == 0) {
    919        return 0;
    920    };
    921    unsigned char byteZero = modulus->data[0];
    922    unsigned int modLen = modulus->len - !byteZero;
    923    return modLen;
    924 }
    925 
    926 /*
    927 ** Perform a raw public-key operation
    928 **  Length of input and output buffers are equal to key's modulus len.
    929 */
    930 SECStatus
    931 RSA_PublicKeyOp(RSAPublicKey *key,
    932                unsigned char *output,
    933                const unsigned char *input)
    934 {
    935    unsigned int modLen, expLen, offset;
    936    mp_int n, e, m, c;
    937    mp_err err = MP_OKAY;
    938    SECStatus rv = SECSuccess;
    939    if (!key || !output || !input) {
    940        PORT_SetError(SEC_ERROR_INVALID_ARGS);
    941        return SECFailure;
    942    }
    943    MP_DIGITS(&n) = 0;
    944    MP_DIGITS(&e) = 0;
    945    MP_DIGITS(&m) = 0;
    946    MP_DIGITS(&c) = 0;
    947    CHECK_MPI_OK(mp_init(&n));
    948    CHECK_MPI_OK(mp_init(&e));
    949    CHECK_MPI_OK(mp_init(&m));
    950    CHECK_MPI_OK(mp_init(&c));
    951    modLen = rsa_modulusLen(&key->modulus);
    952    expLen = rsa_modulusLen(&key->publicExponent);
    953 
    954    if (modLen == 0) {
    955        PORT_SetError(SEC_ERROR_INVALID_ARGS);
    956        rv = SECFailure;
    957        goto cleanup;
    958    }
    959 
    960    /* 1.  Obtain public key (n, e) */
    961    if (BAD_RSA_KEY_SIZE(modLen, expLen)) {
    962        PORT_SetError(SEC_ERROR_INVALID_KEY);
    963        rv = SECFailure;
    964        goto cleanup;
    965    }
    966    SECITEM_TO_MPINT(key->modulus, &n);
    967    SECITEM_TO_MPINT(key->publicExponent, &e);
    968    if (e.used > n.used) {
    969        /* exponent should not be greater than modulus */
    970        PORT_SetError(SEC_ERROR_INVALID_KEY);
    971        rv = SECFailure;
    972        goto cleanup;
    973    }
    974    /* 2. check input out of range (needs to be in range [0..n-1]) */
    975    offset = (key->modulus.data[0] == 0) ? 1 : 0; /* may be leading 0 */
    976    if (memcmp(input, key->modulus.data + offset, modLen) >= 0) {
    977        PORT_SetError(SEC_ERROR_INPUT_LEN);
    978        rv = SECFailure;
    979        goto cleanup;
    980    }
    981    /* 2 bis.  Represent message as integer in range [0..n-1] */
    982    CHECK_MPI_OK(mp_read_unsigned_octets(&m, input, modLen));
    983 /* 3.  Compute c = m**e mod n */
    984 #ifdef USE_MPI_EXPT_D
    985    /* XXX see which is faster */
    986    if (MP_USED(&e) == 1) {
    987        CHECK_MPI_OK(mp_exptmod_d(&m, MP_DIGIT(&e, 0), &n, &c));
    988    } else
    989 #endif
    990        CHECK_MPI_OK(mp_exptmod(&m, &e, &n, &c));
    991    /* 4.  result c is ciphertext */
    992    err = mp_to_fixlen_octets(&c, output, modLen);
    993    if (err >= 0)
    994        err = MP_OKAY;
    995 cleanup:
    996    mp_clear(&n);
    997    mp_clear(&e);
    998    mp_clear(&m);
    999    mp_clear(&c);
   1000    if (err) {
   1001        MP_TO_SEC_ERROR(err);
   1002        rv = SECFailure;
   1003    }
   1004    return rv;
   1005 }
   1006 
   1007 /*
   1008 **  RSA Private key operation (no CRT).
   1009 */
   1010 static SECStatus
   1011 rsa_PrivateKeyOpNoCRT(RSAPrivateKey *key, mp_int *m, mp_int *c, mp_int *n,
   1012                      unsigned int modLen)
   1013 {
   1014    mp_int d;
   1015    mp_err err = MP_OKAY;
   1016    SECStatus rv = SECSuccess;
   1017    MP_DIGITS(&d) = 0;
   1018    CHECK_MPI_OK(mp_init(&d));
   1019    SECITEM_TO_MPINT(key->privateExponent, &d);
   1020    /* 1. m = c**d mod n */
   1021    CHECK_MPI_OK(mp_exptmod(c, &d, n, m));
   1022 cleanup:
   1023    mp_clear(&d);
   1024    if (err) {
   1025        MP_TO_SEC_ERROR(err);
   1026        rv = SECFailure;
   1027    }
   1028    return rv;
   1029 }
   1030 
   1031 /*
   1032 **  RSA Private key operation using CRT.
   1033 */
   1034 static SECStatus
   1035 rsa_PrivateKeyOpCRTNoCheck(RSAPrivateKey *key, mp_int *m, mp_int *c)
   1036 {
   1037    mp_int p, q, d_p, d_q, qInv;
   1038    /*
   1039            The length of the randomness comes from the papers:
   1040            https://link.springer.com/chapter/10.1007/978-3-642-29912-4_7
   1041            https://link.springer.com/chapter/10.1007/978-3-642-21554-4_5.
   1042        */
   1043    mp_int blinding_dp, blinding_dq, r1, r2;
   1044    unsigned char random_block[EXP_BLINDING_RANDOMNESS_LEN_BYTES];
   1045    mp_int m1, m2, h, ctmp;
   1046    mp_err err = MP_OKAY;
   1047    SECStatus rv = SECSuccess;
   1048    MP_DIGITS(&p) = 0;
   1049    MP_DIGITS(&q) = 0;
   1050    MP_DIGITS(&d_p) = 0;
   1051    MP_DIGITS(&d_q) = 0;
   1052    MP_DIGITS(&qInv) = 0;
   1053    MP_DIGITS(&m1) = 0;
   1054    MP_DIGITS(&m2) = 0;
   1055    MP_DIGITS(&h) = 0;
   1056    MP_DIGITS(&ctmp) = 0;
   1057    MP_DIGITS(&blinding_dp) = 0;
   1058    MP_DIGITS(&blinding_dq) = 0;
   1059    MP_DIGITS(&r1) = 0;
   1060    MP_DIGITS(&r2) = 0;
   1061 
   1062    CHECK_MPI_OK(mp_init(&p));
   1063    CHECK_MPI_OK(mp_init(&q));
   1064    CHECK_MPI_OK(mp_init(&d_p));
   1065    CHECK_MPI_OK(mp_init(&d_q));
   1066    CHECK_MPI_OK(mp_init(&qInv));
   1067    CHECK_MPI_OK(mp_init(&m1));
   1068    CHECK_MPI_OK(mp_init(&m2));
   1069    CHECK_MPI_OK(mp_init(&h));
   1070    CHECK_MPI_OK(mp_init(&ctmp));
   1071    CHECK_MPI_OK(mp_init(&blinding_dp));
   1072    CHECK_MPI_OK(mp_init(&blinding_dq));
   1073    CHECK_MPI_OK(mp_init_size(&r1, EXP_BLINDING_RANDOMNESS_LEN));
   1074    CHECK_MPI_OK(mp_init_size(&r2, EXP_BLINDING_RANDOMNESS_LEN));
   1075 
   1076    /* copy private key parameters into mp integers */
   1077    SECITEM_TO_MPINT(key->prime1, &p);         /* p */
   1078    SECITEM_TO_MPINT(key->prime2, &q);         /* q */
   1079    SECITEM_TO_MPINT(key->exponent1, &d_p);    /* d_p  = d mod (p-1) */
   1080    SECITEM_TO_MPINT(key->exponent2, &d_q);    /* d_q  = d mod (q-1) */
   1081    SECITEM_TO_MPINT(key->coefficient, &qInv); /* qInv = q**-1 mod p */
   1082 
   1083    // blinding_dp = 1
   1084    CHECK_MPI_OK(mp_set_int(&blinding_dp, 1));
   1085    // blinding_dp = p - 1
   1086    CHECK_MPI_OK(mp_sub(&p, &blinding_dp, &blinding_dp));
   1087    // generating a random value
   1088    RNG_GenerateGlobalRandomBytes(random_block, EXP_BLINDING_RANDOMNESS_LEN_BYTES);
   1089    MP_USED(&r1) = EXP_BLINDING_RANDOMNESS_LEN;
   1090    memcpy(MP_DIGITS(&r1), random_block, sizeof(random_block));
   1091    // blinding_dp = random * (p - 1)
   1092    CHECK_MPI_OK(mp_mul(&blinding_dp, &r1, &blinding_dp));
   1093    // d_p = d_p + random * (p - 1)
   1094    CHECK_MPI_OK(mp_add(&d_p, &blinding_dp, &d_p));
   1095 
   1096    // blinding_dq = 1
   1097    CHECK_MPI_OK(mp_set_int(&blinding_dq, 1));
   1098    // blinding_dq = q - 1
   1099    CHECK_MPI_OK(mp_sub(&q, &blinding_dq, &blinding_dq));
   1100    // generating a random value
   1101    RNG_GenerateGlobalRandomBytes(random_block, EXP_BLINDING_RANDOMNESS_LEN_BYTES);
   1102    memcpy(MP_DIGITS(&r2), random_block, sizeof(random_block));
   1103    MP_USED(&r2) = EXP_BLINDING_RANDOMNESS_LEN;
   1104    // blinding_dq = random * (q - 1)
   1105    CHECK_MPI_OK(mp_mul(&blinding_dq, &r2, &blinding_dq));
   1106    // d_q = d_q + random * (q-1)
   1107    CHECK_MPI_OK(mp_add(&d_q, &blinding_dq, &d_q));
   1108 
   1109    /* 1. m1 = c**d_p mod p */
   1110    CHECK_MPI_OK(mp_mod(c, &p, &ctmp));
   1111    CHECK_MPI_OK(mp_exptmod(&ctmp, &d_p, &p, &m1));
   1112    /* 2. m2 = c**d_q mod q */
   1113    CHECK_MPI_OK(mp_mod(c, &q, &ctmp));
   1114    CHECK_MPI_OK(mp_exptmod(&ctmp, &d_q, &q, &m2));
   1115    /* 3.  h = (m1 - m2) * qInv mod p */
   1116    CHECK_MPI_OK(mp_submod(&m1, &m2, &p, &h));
   1117    CHECK_MPI_OK(mp_mulmod(&h, &qInv, &p, &h));
   1118    /* 4.  m = m2 + h * q */
   1119    CHECK_MPI_OK(mp_mul(&h, &q, m));
   1120    CHECK_MPI_OK(mp_add(m, &m2, m));
   1121 cleanup:
   1122    mp_clear(&p);
   1123    mp_clear(&q);
   1124    mp_clear(&d_p);
   1125    mp_clear(&d_q);
   1126    mp_clear(&qInv);
   1127    mp_clear(&m1);
   1128    mp_clear(&m2);
   1129    mp_clear(&h);
   1130    mp_clear(&ctmp);
   1131    mp_clear(&blinding_dp);
   1132    mp_clear(&blinding_dq);
   1133    mp_clear(&r1);
   1134    mp_clear(&r2);
   1135    if (err) {
   1136        MP_TO_SEC_ERROR(err);
   1137        rv = SECFailure;
   1138    }
   1139    return rv;
   1140 }
   1141 
   1142 /*
   1143 ** An attack against RSA CRT was described by Boneh, DeMillo, and Lipton in:
   1144 ** "On the Importance of Eliminating Errors in Cryptographic Computations",
   1145 ** http://theory.stanford.edu/~dabo/papers/faults.ps.gz
   1146 **
   1147 ** As a defense against the attack, carry out the private key operation,
   1148 ** followed up with a public key operation to invert the result.
   1149 ** Verify that result against the input.
   1150 */
   1151 static SECStatus
   1152 rsa_PrivateKeyOpCRTCheckedPubKey(RSAPrivateKey *key, mp_int *m, mp_int *c)
   1153 {
   1154    mp_int n, e, v;
   1155    mp_err err = MP_OKAY;
   1156    SECStatus rv = SECSuccess;
   1157    MP_DIGITS(&n) = 0;
   1158    MP_DIGITS(&e) = 0;
   1159    MP_DIGITS(&v) = 0;
   1160    CHECK_MPI_OK(mp_init(&n));
   1161    CHECK_MPI_OK(mp_init(&e));
   1162    CHECK_MPI_OK(mp_init(&v));
   1163    CHECK_SEC_OK(rsa_PrivateKeyOpCRTNoCheck(key, m, c));
   1164    SECITEM_TO_MPINT(key->modulus, &n);
   1165    SECITEM_TO_MPINT(key->publicExponent, &e);
   1166    /* Perform a public key operation v = m ** e mod n */
   1167    CHECK_MPI_OK(mp_exptmod(m, &e, &n, &v));
   1168    if (mp_cmp(&v, c) != 0) {
   1169        /* this error triggers a fips fatal error lock */
   1170        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1171        rv = SECFailure;
   1172    }
   1173 cleanup:
   1174    mp_clear(&n);
   1175    mp_clear(&e);
   1176    mp_clear(&v);
   1177    if (err) {
   1178        MP_TO_SEC_ERROR(err);
   1179        rv = SECFailure;
   1180    }
   1181    return rv;
   1182 }
   1183 
   1184 static PRCallOnceType coBPInit = { 0, 0, 0 };
   1185 static PRStatus
   1186 init_blinding_params_list(void)
   1187 {
   1188    blindingParamsList.lock = PZ_NewLock(nssILockOther);
   1189    if (!blindingParamsList.lock) {
   1190        PORT_SetError(SEC_ERROR_NO_MEMORY);
   1191        return PR_FAILURE;
   1192    }
   1193    blindingParamsList.cVar = PR_NewCondVar(blindingParamsList.lock);
   1194    if (!blindingParamsList.cVar) {
   1195        PORT_SetError(SEC_ERROR_NO_MEMORY);
   1196        return PR_FAILURE;
   1197    }
   1198    blindingParamsList.waitCount = 0;
   1199    PR_INIT_CLIST(&blindingParamsList.head);
   1200    return PR_SUCCESS;
   1201 }
   1202 
   1203 static SECStatus
   1204 generate_blinding_params(RSAPrivateKey *key, mp_int *f, mp_int *g, mp_int *n,
   1205                         unsigned int modLen)
   1206 {
   1207    SECStatus rv = SECSuccess;
   1208    mp_int e, k;
   1209    mp_err err = MP_OKAY;
   1210    unsigned char *kb = NULL;
   1211 
   1212    MP_DIGITS(&e) = 0;
   1213    MP_DIGITS(&k) = 0;
   1214    CHECK_MPI_OK(mp_init(&e));
   1215    CHECK_MPI_OK(mp_init(&k));
   1216    SECITEM_TO_MPINT(key->publicExponent, &e);
   1217    /* generate random k < n */
   1218    kb = PORT_Alloc(modLen);
   1219    if (!kb) {
   1220        PORT_SetError(SEC_ERROR_NO_MEMORY);
   1221        goto cleanup;
   1222    }
   1223    CHECK_SEC_OK(RNG_GenerateGlobalRandomBytes(kb, modLen));
   1224    CHECK_MPI_OK(mp_read_unsigned_octets(&k, kb, modLen));
   1225    /* k < n */
   1226    CHECK_MPI_OK(mp_mod(&k, n, &k));
   1227    /* f = k**e mod n */
   1228    CHECK_MPI_OK(mp_exptmod(&k, &e, n, f));
   1229    /* g = k**-1 mod n */
   1230    CHECK_MPI_OK(mp_invmod(&k, n, g));
   1231    /* g in montgomery form.. */
   1232    CHECK_MPI_OK(mp_to_mont(g, n, g));
   1233 cleanup:
   1234    if (kb)
   1235        PORT_ZFree(kb, modLen);
   1236    mp_clear(&k);
   1237    mp_clear(&e);
   1238    if (err) {
   1239        MP_TO_SEC_ERROR(err);
   1240        rv = SECFailure;
   1241    }
   1242    return rv;
   1243 }
   1244 
   1245 static SECStatus
   1246 init_blinding_params(RSABlindingParams *rsabp, RSAPrivateKey *key,
   1247                     mp_int *n, unsigned int modLen)
   1248 {
   1249    blindingParams *bp = rsabp->array;
   1250    int i = 0;
   1251 
   1252    /* Initialize the list pointer for the element */
   1253    PR_INIT_CLIST(&rsabp->link);
   1254    for (i = 0; i < RSA_BLINDING_PARAMS_MAX_CACHE_SIZE; ++i, ++bp) {
   1255        bp->next = bp + 1;
   1256        MP_DIGITS(&bp->f) = 0;
   1257        MP_DIGITS(&bp->g) = 0;
   1258        bp->counter = 0;
   1259    }
   1260    /* The last bp->next value was initialized with out
   1261     * of rsabp->array pointer and must be set to NULL
   1262     */
   1263    rsabp->array[RSA_BLINDING_PARAMS_MAX_CACHE_SIZE - 1].next = NULL;
   1264 
   1265    bp = rsabp->array;
   1266    rsabp->bp = NULL;
   1267    rsabp->free = bp;
   1268 
   1269    /* precalculate montgomery reduction parameter */
   1270    rsabp->n0i = mp_calculate_mont_n0i(n);
   1271 
   1272    /* List elements are keyed using the modulus */
   1273    return SECITEM_CopyItem(NULL, &rsabp->modulus, &key->modulus);
   1274 }
   1275 
   1276 static SECStatus
   1277 get_blinding_params(RSAPrivateKey *key, mp_int *n, unsigned int modLen,
   1278                    mp_int *f, mp_int *g, mp_digit *n0i)
   1279 {
   1280    RSABlindingParams *rsabp = NULL;
   1281    blindingParams *bpUnlinked = NULL;
   1282    blindingParams *bp;
   1283    PRCList *el;
   1284    SECStatus rv = SECSuccess;
   1285    mp_err err = MP_OKAY;
   1286    int cmp = -1;
   1287    PRBool holdingLock = PR_FALSE;
   1288 
   1289    do {
   1290        if (blindingParamsList.lock == NULL) {
   1291            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1292            return SECFailure;
   1293        }
   1294        /* Acquire the list lock */
   1295        PZ_Lock(blindingParamsList.lock);
   1296        holdingLock = PR_TRUE;
   1297 
   1298        /* Walk the list looking for the private key */
   1299        for (el = PR_NEXT_LINK(&blindingParamsList.head);
   1300             el != &blindingParamsList.head;
   1301             el = PR_NEXT_LINK(el)) {
   1302            rsabp = (RSABlindingParams *)el;
   1303            cmp = SECITEM_CompareItem(&rsabp->modulus, &key->modulus);
   1304            if (cmp >= 0) {
   1305                /* The key is found or not in the list. */
   1306                break;
   1307            }
   1308        }
   1309 
   1310        if (cmp) {
   1311            /* At this point, the key is not in the list.  el should point to
   1312            ** the list element before which this key should be inserted.
   1313            */
   1314            rsabp = PORT_ZNew(RSABlindingParams);
   1315            if (!rsabp) {
   1316                PORT_SetError(SEC_ERROR_NO_MEMORY);
   1317                goto cleanup;
   1318            }
   1319 
   1320            rv = init_blinding_params(rsabp, key, n, modLen);
   1321            if (rv != SECSuccess) {
   1322                PORT_ZFree(rsabp, sizeof(RSABlindingParams));
   1323                goto cleanup;
   1324            }
   1325 
   1326            /* Insert the new element into the list
   1327            ** If inserting in the middle of the list, el points to the link
   1328            ** to insert before.  Otherwise, the link needs to be appended to
   1329            ** the end of the list, which is the same as inserting before the
   1330            ** head (since el would have looped back to the head).
   1331            */
   1332            PR_INSERT_BEFORE(&rsabp->link, el);
   1333        }
   1334 
   1335        /* We've found (or created) the RSAblindingParams struct for this key.
   1336         * Now, search its list of ready blinding params for a usable one.
   1337         */
   1338        *n0i = rsabp->n0i;
   1339        while (0 != (bp = rsabp->bp)) {
   1340 #ifdef UNSAFE_FUZZER_MODE
   1341            /* Found a match and there are still remaining uses left */
   1342            /* Return the parameters */
   1343            CHECK_MPI_OK(mp_copy(&bp->f, f));
   1344            CHECK_MPI_OK(mp_copy(&bp->g, g));
   1345 
   1346            PZ_Unlock(blindingParamsList.lock);
   1347            return SECSuccess;
   1348 #else
   1349            if (--(bp->counter) > 0) {
   1350                /* Found a match and there are still remaining uses left */
   1351                /* Return the parameters */
   1352                CHECK_MPI_OK(mp_copy(&bp->f, f));
   1353                CHECK_MPI_OK(mp_copy(&bp->g, g));
   1354 
   1355                PZ_Unlock(blindingParamsList.lock);
   1356                return SECSuccess;
   1357            }
   1358            /* exhausted this one, give its values to caller, and
   1359             * then retire it.
   1360             */
   1361            mp_exch(&bp->f, f);
   1362            mp_exch(&bp->g, g);
   1363            mp_clear(&bp->f);
   1364            mp_clear(&bp->g);
   1365            bp->counter = 0;
   1366            /* Move to free list */
   1367            rsabp->bp = bp->next;
   1368            bp->next = rsabp->free;
   1369            rsabp->free = bp;
   1370            /* In case there're threads waiting for new blinding
   1371             * value - notify 1 thread the value is ready
   1372             */
   1373            if (blindingParamsList.waitCount > 0) {
   1374                PR_NotifyCondVar(blindingParamsList.cVar);
   1375                blindingParamsList.waitCount--;
   1376            }
   1377            PZ_Unlock(blindingParamsList.lock);
   1378            return SECSuccess;
   1379 #endif
   1380        }
   1381        /* We did not find a usable set of blinding params.  Can we make one? */
   1382        /* Find a free bp struct. */
   1383        if ((bp = rsabp->free) != NULL) {
   1384            /* unlink this bp */
   1385            rsabp->free = bp->next;
   1386            bp->next = NULL;
   1387            bpUnlinked = bp; /* In case we fail */
   1388 
   1389            PZ_Unlock(blindingParamsList.lock);
   1390            holdingLock = PR_FALSE;
   1391            /* generate blinding parameter values for the current thread */
   1392            CHECK_SEC_OK(generate_blinding_params(key, f, g, n, modLen));
   1393 
   1394            /* put the blinding parameter values into cache */
   1395            CHECK_MPI_OK(mp_init(&bp->f));
   1396            CHECK_MPI_OK(mp_init(&bp->g));
   1397            CHECK_MPI_OK(mp_copy(f, &bp->f));
   1398            CHECK_MPI_OK(mp_copy(g, &bp->g));
   1399 
   1400            /* Put this at head of queue of usable params. */
   1401            PZ_Lock(blindingParamsList.lock);
   1402            holdingLock = PR_TRUE;
   1403            (void)holdingLock;
   1404            /* initialize RSABlindingParamsStr */
   1405            bp->counter = RSA_BLINDING_PARAMS_MAX_REUSE;
   1406            bp->next = rsabp->bp;
   1407            rsabp->bp = bp;
   1408            bpUnlinked = NULL;
   1409            /* In case there're threads waiting for new blinding value
   1410             * just notify them the value is ready
   1411             */
   1412            if (blindingParamsList.waitCount > 0) {
   1413                PR_NotifyAllCondVar(blindingParamsList.cVar);
   1414                blindingParamsList.waitCount = 0;
   1415            }
   1416            PZ_Unlock(blindingParamsList.lock);
   1417            return SECSuccess;
   1418        }
   1419        /* Here, there are no usable blinding parameters available,
   1420         * and no free bp blocks, presumably because they're all
   1421         * actively having parameters generated for them.
   1422         * So, we need to wait here and not eat up CPU until some
   1423         * change happens.
   1424         */
   1425        blindingParamsList.waitCount++;
   1426        PR_WaitCondVar(blindingParamsList.cVar, PR_INTERVAL_NO_TIMEOUT);
   1427        PZ_Unlock(blindingParamsList.lock);
   1428        holdingLock = PR_FALSE;
   1429        (void)holdingLock;
   1430    } while (1);
   1431 
   1432 cleanup:
   1433    /* It is possible to reach this after the lock is already released.  */
   1434    if (bpUnlinked) {
   1435        if (!holdingLock) {
   1436            PZ_Lock(blindingParamsList.lock);
   1437            holdingLock = PR_TRUE;
   1438        }
   1439        bp = bpUnlinked;
   1440        mp_clear(&bp->f);
   1441        mp_clear(&bp->g);
   1442        bp->counter = 0;
   1443        /* Must put the unlinked bp back on the free list */
   1444        bp->next = rsabp->free;
   1445        rsabp->free = bp;
   1446    }
   1447    if (holdingLock) {
   1448        PZ_Unlock(blindingParamsList.lock);
   1449    }
   1450    if (err) {
   1451        MP_TO_SEC_ERROR(err);
   1452    }
   1453    *n0i = 0;
   1454    return SECFailure;
   1455 }
   1456 
   1457 /*
   1458 ** Perform a raw private-key operation
   1459 **  Length of input and output buffers are equal to key's modulus len.
   1460 */
   1461 static SECStatus
   1462 rsa_PrivateKeyOp(RSAPrivateKey *key,
   1463                 unsigned char *output,
   1464                 const unsigned char *input,
   1465                 PRBool check)
   1466 {
   1467    unsigned int modLen;
   1468    unsigned int offset;
   1469    SECStatus rv = SECSuccess;
   1470    mp_err err;
   1471    mp_int n, c, m;
   1472    mp_int f, g;
   1473    mp_digit n0i;
   1474    if (!key || !output || !input) {
   1475        PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1476        return SECFailure;
   1477    }
   1478    /* check input out of range (needs to be in range [0..n-1]) */
   1479    modLen = rsa_modulusLen(&key->modulus);
   1480    if (modLen == 0) {
   1481        PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1482        return SECFailure;
   1483    }
   1484    offset = (key->modulus.data[0] == 0) ? 1 : 0; /* may be leading 0 */
   1485    if (memcmp(input, key->modulus.data + offset, modLen) >= 0) {
   1486        PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1487        return SECFailure;
   1488    }
   1489    MP_DIGITS(&n) = 0;
   1490    MP_DIGITS(&c) = 0;
   1491    MP_DIGITS(&m) = 0;
   1492    MP_DIGITS(&f) = 0;
   1493    MP_DIGITS(&g) = 0;
   1494    CHECK_MPI_OK(mp_init(&n));
   1495    CHECK_MPI_OK(mp_init(&c));
   1496    CHECK_MPI_OK(mp_init(&m));
   1497    CHECK_MPI_OK(mp_init(&f));
   1498    CHECK_MPI_OK(mp_init(&g));
   1499    SECITEM_TO_MPINT(key->modulus, &n);
   1500    OCTETS_TO_MPINT(input, &c, modLen);
   1501    /* If blinding, compute pre-image of ciphertext by multiplying by
   1502    ** blinding factor
   1503    */
   1504    if (nssRSAUseBlinding) {
   1505        CHECK_SEC_OK(get_blinding_params(key, &n, modLen, &f, &g, &n0i));
   1506        /* c' = c*f mod n */
   1507        CHECK_MPI_OK(mp_mulmod(&c, &f, &n, &c));
   1508    }
   1509    /* Do the private key operation m = c**d mod n */
   1510    if (key->prime1.len == 0 ||
   1511        key->prime2.len == 0 ||
   1512        key->exponent1.len == 0 ||
   1513        key->exponent2.len == 0 ||
   1514        key->coefficient.len == 0) {
   1515        CHECK_SEC_OK(rsa_PrivateKeyOpNoCRT(key, &m, &c, &n, modLen));
   1516    } else if (check) {
   1517        CHECK_SEC_OK(rsa_PrivateKeyOpCRTCheckedPubKey(key, &m, &c));
   1518    } else {
   1519        CHECK_SEC_OK(rsa_PrivateKeyOpCRTNoCheck(key, &m, &c));
   1520    }
   1521    /* If blinding, compute post-image of plaintext by multiplying by
   1522    ** blinding factor
   1523    */
   1524    if (nssRSAUseBlinding) {
   1525        /* m = m'*g mod n */
   1526        CHECK_MPI_OK(mp_mulmontmodCT(&m, &g, &n, n0i, &m));
   1527    }
   1528    err = mp_to_fixlen_octets(&m, output, modLen);
   1529    if (err >= 0)
   1530        err = MP_OKAY;
   1531 cleanup:
   1532    mp_clear(&n);
   1533    mp_clear(&c);
   1534    mp_clear(&m);
   1535    mp_clear(&f);
   1536    mp_clear(&g);
   1537    if (err) {
   1538        MP_TO_SEC_ERROR(err);
   1539        rv = SECFailure;
   1540    }
   1541    return rv;
   1542 }
   1543 
   1544 SECStatus
   1545 RSA_PrivateKeyOp(RSAPrivateKey *key,
   1546                 unsigned char *output,
   1547                 const unsigned char *input)
   1548 {
   1549    return rsa_PrivateKeyOp(key, output, input, PR_FALSE);
   1550 }
   1551 
   1552 SECStatus
   1553 RSA_PrivateKeyOpDoubleChecked(RSAPrivateKey *key,
   1554                              unsigned char *output,
   1555                              const unsigned char *input)
   1556 {
   1557    return rsa_PrivateKeyOp(key, output, input, PR_TRUE);
   1558 }
   1559 
   1560 SECStatus
   1561 RSA_PrivateKeyCheck(const RSAPrivateKey *key)
   1562 {
   1563    mp_int p, q, n, psub1, qsub1, e, d, d_p, d_q, qInv, res;
   1564    mp_err err = MP_OKAY;
   1565    SECStatus rv = SECSuccess;
   1566    MP_DIGITS(&p) = 0;
   1567    MP_DIGITS(&q) = 0;
   1568    MP_DIGITS(&n) = 0;
   1569    MP_DIGITS(&psub1) = 0;
   1570    MP_DIGITS(&qsub1) = 0;
   1571    MP_DIGITS(&e) = 0;
   1572    MP_DIGITS(&d) = 0;
   1573    MP_DIGITS(&d_p) = 0;
   1574    MP_DIGITS(&d_q) = 0;
   1575    MP_DIGITS(&qInv) = 0;
   1576    MP_DIGITS(&res) = 0;
   1577    CHECK_MPI_OK(mp_init(&p));
   1578    CHECK_MPI_OK(mp_init(&q));
   1579    CHECK_MPI_OK(mp_init(&n));
   1580    CHECK_MPI_OK(mp_init(&psub1));
   1581    CHECK_MPI_OK(mp_init(&qsub1));
   1582    CHECK_MPI_OK(mp_init(&e));
   1583    CHECK_MPI_OK(mp_init(&d));
   1584    CHECK_MPI_OK(mp_init(&d_p));
   1585    CHECK_MPI_OK(mp_init(&d_q));
   1586    CHECK_MPI_OK(mp_init(&qInv));
   1587    CHECK_MPI_OK(mp_init(&res));
   1588 
   1589    if (!key->modulus.data || !key->prime1.data || !key->prime2.data ||
   1590        !key->publicExponent.data || !key->privateExponent.data ||
   1591        !key->exponent1.data || !key->exponent2.data ||
   1592        !key->coefficient.data) {
   1593        /* call RSA_PopulatePrivateKey first, if the application wishes to
   1594         * recover these parameters */
   1595        err = MP_BADARG;
   1596        goto cleanup;
   1597    }
   1598 
   1599    SECITEM_TO_MPINT(key->modulus, &n);
   1600    SECITEM_TO_MPINT(key->prime1, &p);
   1601    SECITEM_TO_MPINT(key->prime2, &q);
   1602    SECITEM_TO_MPINT(key->publicExponent, &e);
   1603    SECITEM_TO_MPINT(key->privateExponent, &d);
   1604    SECITEM_TO_MPINT(key->exponent1, &d_p);
   1605    SECITEM_TO_MPINT(key->exponent2, &d_q);
   1606    SECITEM_TO_MPINT(key->coefficient, &qInv);
   1607    /* p and q must be distinct. */
   1608    if (mp_cmp(&p, &q) == 0) {
   1609        rv = SECFailure;
   1610        goto cleanup;
   1611    }
   1612 #define VERIFY_MPI_EQUAL(m1, m2) \
   1613    if (mp_cmp(m1, m2) != 0) {   \
   1614        rv = SECFailure;         \
   1615        goto cleanup;            \
   1616    }
   1617 #define VERIFY_MPI_EQUAL_1(m)  \
   1618    if (mp_cmp_d(m, 1) != 0) { \
   1619        rv = SECFailure;       \
   1620        goto cleanup;          \
   1621    }
   1622    /* n == p * q */
   1623    CHECK_MPI_OK(mp_mul(&p, &q, &res));
   1624    VERIFY_MPI_EQUAL(&res, &n);
   1625    /* gcd(e, p-1) == 1 */
   1626    CHECK_MPI_OK(mp_sub_d(&p, 1, &psub1));
   1627    CHECK_MPI_OK(mp_gcd(&e, &psub1, &res));
   1628    VERIFY_MPI_EQUAL_1(&res);
   1629    /* gcd(e, q-1) == 1 */
   1630    CHECK_MPI_OK(mp_sub_d(&q, 1, &qsub1));
   1631    CHECK_MPI_OK(mp_gcd(&e, &qsub1, &res));
   1632    VERIFY_MPI_EQUAL_1(&res);
   1633    /* d*e == 1 mod p-1 */
   1634    CHECK_MPI_OK(mp_mulmod(&d, &e, &psub1, &res));
   1635    VERIFY_MPI_EQUAL_1(&res);
   1636    /* d*e == 1 mod q-1 */
   1637    CHECK_MPI_OK(mp_mulmod(&d, &e, &qsub1, &res));
   1638    VERIFY_MPI_EQUAL_1(&res);
   1639    /* d_p == d mod p-1 */
   1640    CHECK_MPI_OK(mp_mod(&d, &psub1, &res));
   1641    VERIFY_MPI_EQUAL(&res, &d_p);
   1642    /* d_q == d mod q-1 */
   1643    CHECK_MPI_OK(mp_mod(&d, &qsub1, &res));
   1644    VERIFY_MPI_EQUAL(&res, &d_q);
   1645    /* q * q**-1 == 1 mod p */
   1646    CHECK_MPI_OK(mp_mulmod(&q, &qInv, &p, &res));
   1647    VERIFY_MPI_EQUAL_1(&res);
   1648 
   1649 cleanup:
   1650    mp_clear(&n);
   1651    mp_clear(&p);
   1652    mp_clear(&q);
   1653    mp_clear(&psub1);
   1654    mp_clear(&qsub1);
   1655    mp_clear(&e);
   1656    mp_clear(&d);
   1657    mp_clear(&d_p);
   1658    mp_clear(&d_q);
   1659    mp_clear(&qInv);
   1660    mp_clear(&res);
   1661    if (err) {
   1662        MP_TO_SEC_ERROR(err);
   1663        rv = SECFailure;
   1664    }
   1665    return rv;
   1666 }
   1667 
   1668 SECStatus
   1669 RSA_Init(void)
   1670 {
   1671    if (PR_CallOnce(&coBPInit, init_blinding_params_list) != PR_SUCCESS) {
   1672        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1673        return SECFailure;
   1674    }
   1675    return SECSuccess;
   1676 }
   1677 
   1678 /* cleanup at shutdown */
   1679 void
   1680 RSA_Cleanup(void)
   1681 {
   1682    blindingParams *bp = NULL;
   1683    if (!coBPInit.initialized)
   1684        return;
   1685 
   1686    while (!PR_CLIST_IS_EMPTY(&blindingParamsList.head)) {
   1687        RSABlindingParams *rsabp =
   1688            (RSABlindingParams *)PR_LIST_HEAD(&blindingParamsList.head);
   1689        PR_REMOVE_LINK(&rsabp->link);
   1690        /* clear parameters cache */
   1691        while (rsabp->bp != NULL) {
   1692            bp = rsabp->bp;
   1693            rsabp->bp = rsabp->bp->next;
   1694            mp_clear(&bp->f);
   1695            mp_clear(&bp->g);
   1696        }
   1697        SECITEM_ZfreeItem(&rsabp->modulus, PR_FALSE);
   1698        PORT_Free(rsabp);
   1699    }
   1700 
   1701    if (blindingParamsList.cVar) {
   1702        PR_DestroyCondVar(blindingParamsList.cVar);
   1703        blindingParamsList.cVar = NULL;
   1704    }
   1705 
   1706    if (blindingParamsList.lock) {
   1707        SKIP_AFTER_FORK(PZ_DestroyLock(blindingParamsList.lock));
   1708        blindingParamsList.lock = NULL;
   1709    }
   1710 
   1711    coBPInit.initialized = 0;
   1712    coBPInit.inProgress = 0;
   1713    coBPInit.status = 0;
   1714 }
   1715 
   1716 /*
   1717 * need a central place for this function to free up all the memory that
   1718 * free_bl may have allocated along the way. Currently only RSA does this,
   1719 * so I've put it here for now.
   1720 */
   1721 void
   1722 BL_Cleanup(void)
   1723 {
   1724    RSA_Cleanup();
   1725 }
   1726 
   1727 PRBool bl_parentForkedAfterC_Initialize;
   1728 
   1729 /*
   1730 * Set fork flag so it can be tested in SKIP_AFTER_FORK on relevant platforms.
   1731 */
   1732 void
   1733 BL_SetForkState(PRBool forked)
   1734 {
   1735    bl_parentForkedAfterC_Initialize = forked;
   1736 }