michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: /* michael@0: * RSA key generation, public key op, private key op. michael@0: */ michael@0: #ifdef FREEBL_NO_DEPEND michael@0: #include "stubs.h" michael@0: #endif michael@0: michael@0: #include "secerr.h" michael@0: michael@0: #include "prclist.h" michael@0: #include "nssilock.h" michael@0: #include "prinit.h" michael@0: #include "blapi.h" michael@0: #include "mpi.h" michael@0: #include "mpprime.h" michael@0: #include "mplogic.h" michael@0: #include "secmpi.h" michael@0: #include "secitem.h" michael@0: #include "blapii.h" michael@0: michael@0: /* michael@0: ** Number of times to attempt to generate a prime (p or q) from a random michael@0: ** seed (the seed changes for each iteration). michael@0: */ michael@0: #define MAX_PRIME_GEN_ATTEMPTS 10 michael@0: /* michael@0: ** Number of times to attempt to generate a key. The primes p and q change michael@0: ** for each attempt. michael@0: */ michael@0: #define MAX_KEY_GEN_ATTEMPTS 10 michael@0: michael@0: /* Blinding Parameters max cache size */ michael@0: #define RSA_BLINDING_PARAMS_MAX_CACHE_SIZE 20 michael@0: michael@0: /* exponent should not be greater than modulus */ michael@0: #define BAD_RSA_KEY_SIZE(modLen, expLen) \ michael@0: ((expLen) > (modLen) || (modLen) > RSA_MAX_MODULUS_BITS/8 || \ michael@0: (expLen) > RSA_MAX_EXPONENT_BITS/8) michael@0: michael@0: struct blindingParamsStr; michael@0: typedef struct blindingParamsStr blindingParams; michael@0: michael@0: struct blindingParamsStr { michael@0: blindingParams *next; michael@0: mp_int f, g; /* blinding parameter */ michael@0: int counter; /* number of remaining uses of (f, g) */ michael@0: }; michael@0: michael@0: /* michael@0: ** RSABlindingParamsStr michael@0: ** michael@0: ** For discussion of Paul Kocher's timing attack against an RSA private key michael@0: ** operation, see http://www.cryptography.com/timingattack/paper.html. The michael@0: ** countermeasure to this attack, known as blinding, is also discussed in michael@0: ** the Handbook of Applied Cryptography, 11.118-11.119. michael@0: */ michael@0: struct RSABlindingParamsStr michael@0: { michael@0: /* Blinding-specific parameters */ michael@0: PRCList link; /* link to list of structs */ michael@0: SECItem modulus; /* list element "key" */ michael@0: blindingParams *free, *bp; /* Blinding parameters queue */ michael@0: blindingParams array[RSA_BLINDING_PARAMS_MAX_CACHE_SIZE]; michael@0: }; michael@0: typedef struct RSABlindingParamsStr RSABlindingParams; michael@0: michael@0: /* michael@0: ** RSABlindingParamsListStr michael@0: ** michael@0: ** List of key-specific blinding params. The arena holds the volatile pool michael@0: ** of memory for each entry and the list itself. The lock is for list michael@0: ** operations, in this case insertions and iterations, as well as control michael@0: ** of the counter for each set of blinding parameters. michael@0: */ michael@0: struct RSABlindingParamsListStr michael@0: { michael@0: PZLock *lock; /* Lock for the list */ michael@0: PRCondVar *cVar; /* Condidtion Variable */ michael@0: int waitCount; /* Number of threads waiting on cVar */ michael@0: PRCList head; /* Pointer to the list */ michael@0: }; michael@0: michael@0: /* michael@0: ** The master blinding params list. michael@0: */ michael@0: static struct RSABlindingParamsListStr blindingParamsList = { 0 }; michael@0: michael@0: /* Number of times to reuse (f, g). Suggested by Paul Kocher */ michael@0: #define RSA_BLINDING_PARAMS_MAX_REUSE 50 michael@0: michael@0: /* Global, allows optional use of blinding. On by default. */ michael@0: /* Cannot be changed at the moment, due to thread-safety issues. */ michael@0: static PRBool nssRSAUseBlinding = PR_TRUE; michael@0: michael@0: static SECStatus michael@0: rsa_build_from_primes(const mp_int *p, const mp_int *q, michael@0: mp_int *e, PRBool needPublicExponent, michael@0: mp_int *d, PRBool needPrivateExponent, michael@0: RSAPrivateKey *key, unsigned int keySizeInBits) michael@0: { michael@0: mp_int n, phi; michael@0: mp_int psub1, qsub1, tmp; michael@0: mp_err err = MP_OKAY; michael@0: SECStatus rv = SECSuccess; michael@0: MP_DIGITS(&n) = 0; michael@0: MP_DIGITS(&phi) = 0; michael@0: MP_DIGITS(&psub1) = 0; michael@0: MP_DIGITS(&qsub1) = 0; michael@0: MP_DIGITS(&tmp) = 0; michael@0: CHECK_MPI_OK( mp_init(&n) ); michael@0: CHECK_MPI_OK( mp_init(&phi) ); michael@0: CHECK_MPI_OK( mp_init(&psub1) ); michael@0: CHECK_MPI_OK( mp_init(&qsub1) ); michael@0: CHECK_MPI_OK( mp_init(&tmp) ); michael@0: /* p and q must be distinct. */ michael@0: if (mp_cmp(p, q) == 0) { michael@0: PORT_SetError(SEC_ERROR_NEED_RANDOM); michael@0: rv = SECFailure; michael@0: goto cleanup; michael@0: } michael@0: /* 1. Compute n = p*q */ michael@0: CHECK_MPI_OK( mp_mul(p, q, &n) ); michael@0: /* verify that the modulus has the desired number of bits */ michael@0: if ((unsigned)mpl_significant_bits(&n) != keySizeInBits) { michael@0: PORT_SetError(SEC_ERROR_NEED_RANDOM); michael@0: rv = SECFailure; michael@0: goto cleanup; michael@0: } michael@0: michael@0: /* at least one exponent must be given */ michael@0: PORT_Assert(!(needPublicExponent && needPrivateExponent)); michael@0: michael@0: /* 2. Compute phi = (p-1)*(q-1) */ michael@0: CHECK_MPI_OK( mp_sub_d(p, 1, &psub1) ); michael@0: CHECK_MPI_OK( mp_sub_d(q, 1, &qsub1) ); michael@0: if (needPublicExponent || needPrivateExponent) { michael@0: CHECK_MPI_OK( mp_mul(&psub1, &qsub1, &phi) ); michael@0: /* 3. Compute d = e**-1 mod(phi) */ michael@0: /* or e = d**-1 mod(phi) as necessary */ michael@0: if (needPublicExponent) { michael@0: err = mp_invmod(d, &phi, e); michael@0: } else { michael@0: err = mp_invmod(e, &phi, d); michael@0: } michael@0: } else { michael@0: err = MP_OKAY; michael@0: } michael@0: /* Verify that phi(n) and e have no common divisors */ michael@0: if (err != MP_OKAY) { michael@0: if (err == MP_UNDEF) { michael@0: PORT_SetError(SEC_ERROR_NEED_RANDOM); michael@0: err = MP_OKAY; /* to keep PORT_SetError from being called again */ michael@0: rv = SECFailure; michael@0: } michael@0: goto cleanup; michael@0: } michael@0: michael@0: /* 4. Compute exponent1 = d mod (p-1) */ michael@0: CHECK_MPI_OK( mp_mod(d, &psub1, &tmp) ); michael@0: MPINT_TO_SECITEM(&tmp, &key->exponent1, key->arena); michael@0: /* 5. Compute exponent2 = d mod (q-1) */ michael@0: CHECK_MPI_OK( mp_mod(d, &qsub1, &tmp) ); michael@0: MPINT_TO_SECITEM(&tmp, &key->exponent2, key->arena); michael@0: /* 6. Compute coefficient = q**-1 mod p */ michael@0: CHECK_MPI_OK( mp_invmod(q, p, &tmp) ); michael@0: MPINT_TO_SECITEM(&tmp, &key->coefficient, key->arena); michael@0: michael@0: /* copy our calculated results, overwrite what is there */ michael@0: key->modulus.data = NULL; michael@0: MPINT_TO_SECITEM(&n, &key->modulus, key->arena); michael@0: key->privateExponent.data = NULL; michael@0: MPINT_TO_SECITEM(d, &key->privateExponent, key->arena); michael@0: key->publicExponent.data = NULL; michael@0: MPINT_TO_SECITEM(e, &key->publicExponent, key->arena); michael@0: key->prime1.data = NULL; michael@0: MPINT_TO_SECITEM(p, &key->prime1, key->arena); michael@0: key->prime2.data = NULL; michael@0: MPINT_TO_SECITEM(q, &key->prime2, key->arena); michael@0: cleanup: michael@0: mp_clear(&n); michael@0: mp_clear(&phi); michael@0: mp_clear(&psub1); michael@0: mp_clear(&qsub1); michael@0: mp_clear(&tmp); michael@0: if (err) { michael@0: MP_TO_SEC_ERROR(err); michael@0: rv = SECFailure; michael@0: } michael@0: return rv; michael@0: } michael@0: static SECStatus michael@0: generate_prime(mp_int *prime, int primeLen) michael@0: { michael@0: mp_err err = MP_OKAY; michael@0: SECStatus rv = SECSuccess; michael@0: unsigned long counter = 0; michael@0: int piter; michael@0: unsigned char *pb = NULL; michael@0: pb = PORT_Alloc(primeLen); michael@0: if (!pb) { michael@0: PORT_SetError(SEC_ERROR_NO_MEMORY); michael@0: goto cleanup; michael@0: } michael@0: for (piter = 0; piter < MAX_PRIME_GEN_ATTEMPTS; piter++) { michael@0: CHECK_SEC_OK( RNG_GenerateGlobalRandomBytes(pb, primeLen) ); michael@0: pb[0] |= 0xC0; /* set two high-order bits */ michael@0: pb[primeLen-1] |= 0x01; /* set low-order bit */ michael@0: CHECK_MPI_OK( mp_read_unsigned_octets(prime, pb, primeLen) ); michael@0: err = mpp_make_prime(prime, primeLen * 8, PR_FALSE, &counter); michael@0: if (err != MP_NO) michael@0: goto cleanup; michael@0: /* keep going while err == MP_NO */ michael@0: } michael@0: cleanup: michael@0: if (pb) michael@0: PORT_ZFree(pb, primeLen); michael@0: if (err) { michael@0: MP_TO_SEC_ERROR(err); michael@0: rv = SECFailure; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /* michael@0: ** Generate and return a new RSA public and private key. michael@0: ** Both keys are encoded in a single RSAPrivateKey structure. michael@0: ** "cx" is the random number generator context michael@0: ** "keySizeInBits" is the size of the key to be generated, in bits. michael@0: ** 512, 1024, etc. michael@0: ** "publicExponent" when not NULL is a pointer to some data that michael@0: ** represents the public exponent to use. The data is a byte michael@0: ** encoded integer, in "big endian" order. michael@0: */ michael@0: RSAPrivateKey * michael@0: RSA_NewKey(int keySizeInBits, SECItem *publicExponent) michael@0: { michael@0: unsigned int primeLen; michael@0: mp_int p, q, e, d; michael@0: int kiter; michael@0: mp_err err = MP_OKAY; michael@0: SECStatus rv = SECSuccess; michael@0: int prerr = 0; michael@0: RSAPrivateKey *key = NULL; michael@0: PLArenaPool *arena = NULL; michael@0: /* Require key size to be a multiple of 16 bits. */ michael@0: if (!publicExponent || keySizeInBits % 16 != 0 || michael@0: BAD_RSA_KEY_SIZE(keySizeInBits/8, publicExponent->len)) { michael@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); michael@0: return NULL; michael@0: } michael@0: /* 1. Allocate arena & key */ michael@0: arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE); michael@0: if (!arena) { michael@0: PORT_SetError(SEC_ERROR_NO_MEMORY); michael@0: return NULL; michael@0: } michael@0: key = PORT_ArenaZNew(arena, RSAPrivateKey); michael@0: if (!key) { michael@0: PORT_SetError(SEC_ERROR_NO_MEMORY); michael@0: PORT_FreeArena(arena, PR_TRUE); michael@0: return NULL; michael@0: } michael@0: key->arena = arena; michael@0: /* length of primes p and q (in bytes) */ michael@0: primeLen = keySizeInBits / (2 * PR_BITS_PER_BYTE); michael@0: MP_DIGITS(&p) = 0; michael@0: MP_DIGITS(&q) = 0; michael@0: MP_DIGITS(&e) = 0; michael@0: MP_DIGITS(&d) = 0; michael@0: CHECK_MPI_OK( mp_init(&p) ); michael@0: CHECK_MPI_OK( mp_init(&q) ); michael@0: CHECK_MPI_OK( mp_init(&e) ); michael@0: CHECK_MPI_OK( mp_init(&d) ); michael@0: /* 2. Set the version number (PKCS1 v1.5 says it should be zero) */ michael@0: SECITEM_AllocItem(arena, &key->version, 1); michael@0: key->version.data[0] = 0; michael@0: /* 3. Set the public exponent */ michael@0: SECITEM_TO_MPINT(*publicExponent, &e); michael@0: kiter = 0; michael@0: do { michael@0: prerr = 0; michael@0: PORT_SetError(0); michael@0: CHECK_SEC_OK( generate_prime(&p, primeLen) ); michael@0: CHECK_SEC_OK( generate_prime(&q, primeLen) ); michael@0: /* Assure p > q */ michael@0: /* NOTE: PKCS #1 does not require p > q, and NSS doesn't use any michael@0: * implementation optimization that requires p > q. We can remove michael@0: * this code in the future. michael@0: */ michael@0: if (mp_cmp(&p, &q) < 0) michael@0: mp_exch(&p, &q); michael@0: /* Attempt to use these primes to generate a key */ michael@0: rv = rsa_build_from_primes(&p, &q, michael@0: &e, PR_FALSE, /* needPublicExponent=false */ michael@0: &d, PR_TRUE, /* needPrivateExponent=true */ michael@0: key, keySizeInBits); michael@0: if (rv == SECSuccess) michael@0: break; /* generated two good primes */ michael@0: prerr = PORT_GetError(); michael@0: kiter++; michael@0: /* loop until have primes */ michael@0: } while (prerr == SEC_ERROR_NEED_RANDOM && kiter < MAX_KEY_GEN_ATTEMPTS); michael@0: if (prerr) michael@0: goto cleanup; michael@0: cleanup: michael@0: mp_clear(&p); michael@0: mp_clear(&q); michael@0: mp_clear(&e); michael@0: mp_clear(&d); michael@0: if (err) { michael@0: MP_TO_SEC_ERROR(err); michael@0: rv = SECFailure; michael@0: } michael@0: if (rv && arena) { michael@0: PORT_FreeArena(arena, PR_TRUE); michael@0: key = NULL; michael@0: } michael@0: return key; michael@0: } michael@0: michael@0: mp_err michael@0: rsa_is_prime(mp_int *p) { michael@0: int res; michael@0: michael@0: /* run a Fermat test */ michael@0: res = mpp_fermat(p, 2); michael@0: if (res != MP_OKAY) { michael@0: return res; michael@0: } michael@0: michael@0: /* If that passed, run some Miller-Rabin tests */ michael@0: res = mpp_pprime(p, 2); michael@0: return res; michael@0: } michael@0: michael@0: /* michael@0: * Try to find the two primes based on 2 exponents plus either a prime michael@0: * or a modulus. michael@0: * michael@0: * In: e, d and either p or n (depending on the setting of hasModulus). michael@0: * Out: p,q. michael@0: * michael@0: * Step 1, Since d = e**-1 mod phi, we know that d*e == 1 mod phi, or michael@0: * d*e = 1+k*phi, or d*e-1 = k*phi. since d is less than phi and e is michael@0: * usually less than d, then k must be an integer between e-1 and 1 michael@0: * (probably on the order of e). michael@0: * Step 1a, If we were passed just a prime, we can divide k*phi by that michael@0: * prime-1 and get k*(q-1). This will reduce the size of our division michael@0: * through the rest of the loop. michael@0: * Step 2, Loop through the values k=e-1 to 1 looking for k. k should be on michael@0: * the order or e, and e is typically small. This may take a while for michael@0: * a large random e. We are looking for a k that divides kphi michael@0: * evenly. Once we find a k that divides kphi evenly, we assume it michael@0: * is the true k. It's possible this k is not the 'true' k but has michael@0: * swapped factors of p-1 and/or q-1. Because of this, we michael@0: * tentatively continue Steps 3-6 inside this loop, and may return looking michael@0: * for another k on failure. michael@0: * Step 3, Calculate are tentative phi=kphi/k. Note: real phi is (p-1)*(q-1). michael@0: * Step 4a, if we have a prime, kphi is already k*(q-1), so phi is or tenative michael@0: * q-1. q = phi+1. If k is correct, q should be the right length and michael@0: * prime. michael@0: * Step 4b, It's possible q-1 and k could have swapped factors. We now have a michael@0: * possible solution that meets our criteria. It may not be the only michael@0: * solution, however, so we keep looking. If we find more than one, michael@0: * we will fail since we cannot determine which is the correct michael@0: * solution, and returning the wrong modulus will compromise both michael@0: * moduli. If no other solution is found, we return the unique solution. michael@0: * Step 5a, If we have the modulus (n=pq), then use the following formula to michael@0: * calculate s=(p+q): , phi = (p-1)(q-1) = pq -p-q +1 = n-s+1. so michael@0: * s=n-phi+1. michael@0: * Step 5b, Use n=pq and s=p+q to solve for p and q as follows: michael@0: * since q=s-p, then n=p*(s-p)= sp - p^2, rearranging p^2-s*p+n = 0. michael@0: * from the quadratic equation we have p=1/2*(s+sqrt(s*s-4*n)) and michael@0: * q=1/2*(s-sqrt(s*s-4*n)) if s*s-4*n is a perfect square, we are DONE. michael@0: * If it is not, continue in our look looking for another k. NOTE: the michael@0: * code actually distributes the 1/2 and results in the equations: michael@0: * sqrt = sqrt(s/2*s/2-n), p=s/2+sqrt, q=s/2-sqrt. The algebra saves us michael@0: * and extra divide by 2 and a multiply by 4. michael@0: * michael@0: * This will return p & q. q may be larger than p in the case that p was given michael@0: * and it was the smaller prime. michael@0: */ michael@0: static mp_err michael@0: rsa_get_primes_from_exponents(mp_int *e, mp_int *d, mp_int *p, mp_int *q, michael@0: mp_int *n, PRBool hasModulus, michael@0: unsigned int keySizeInBits) michael@0: { michael@0: mp_int kphi; /* k*phi */ michael@0: mp_int k; /* current guess at 'k' */ michael@0: mp_int phi; /* (p-1)(q-1) */ michael@0: mp_int s; /* p+q/2 (s/2 in the algebra) */ michael@0: mp_int r; /* remainder */ michael@0: mp_int tmp; /* p-1 if p is given, n+1 is modulus is given */ michael@0: mp_int sqrt; /* sqrt(s/2*s/2-n) */ michael@0: mp_err err = MP_OKAY; michael@0: unsigned int order_k; michael@0: michael@0: MP_DIGITS(&kphi) = 0; michael@0: MP_DIGITS(&phi) = 0; michael@0: MP_DIGITS(&s) = 0; michael@0: MP_DIGITS(&k) = 0; michael@0: MP_DIGITS(&r) = 0; michael@0: MP_DIGITS(&tmp) = 0; michael@0: MP_DIGITS(&sqrt) = 0; michael@0: CHECK_MPI_OK( mp_init(&kphi) ); michael@0: CHECK_MPI_OK( mp_init(&phi) ); michael@0: CHECK_MPI_OK( mp_init(&s) ); michael@0: CHECK_MPI_OK( mp_init(&k) ); michael@0: CHECK_MPI_OK( mp_init(&r) ); michael@0: CHECK_MPI_OK( mp_init(&tmp) ); michael@0: CHECK_MPI_OK( mp_init(&sqrt) ); michael@0: michael@0: /* our algorithm looks for a factor k whose maximum size is dependent michael@0: * on the size of our smallest exponent, which had better be the public michael@0: * exponent (if it's the private, the key is vulnerable to a brute force michael@0: * attack). michael@0: * michael@0: * since our factor search is linear, we need to limit the maximum michael@0: * size of the public key. this should not be a problem normally, since michael@0: * public keys are usually small. michael@0: * michael@0: * if we want to handle larger public key sizes, we should have michael@0: * a version which tries to 'completely' factor k*phi (where completely michael@0: * means 'factor into primes, or composites with which are products of michael@0: * large primes). Once we have all the factors, we can sort them out and michael@0: * try different combinations to form our phi. The risk is if (p-1)/2, michael@0: * (q-1)/2, and k are all large primes. In any case if the public key michael@0: * is small (order of 20 some bits), then a linear search for k is michael@0: * manageable. michael@0: */ michael@0: if (mpl_significant_bits(e) > 23) { michael@0: err=MP_RANGE; michael@0: goto cleanup; michael@0: } michael@0: michael@0: /* calculate k*phi = e*d - 1 */ michael@0: CHECK_MPI_OK( mp_mul(e, d, &kphi) ); michael@0: CHECK_MPI_OK( mp_sub_d(&kphi, 1, &kphi) ); michael@0: michael@0: michael@0: /* kphi is (e*d)-1, which is the same as k*(p-1)(q-1) michael@0: * d < (p-1)(q-1), therefor k must be less than e-1 michael@0: * We can narrow down k even more, though. Since p and q are odd and both michael@0: * have their high bit set, then we know that phi must be on order of michael@0: * keySizeBits. michael@0: */ michael@0: order_k = (unsigned)mpl_significant_bits(&kphi) - keySizeInBits; michael@0: michael@0: /* for (k=kinit; order(k) >= order_k; k--) { */ michael@0: /* k=kinit: k can't be bigger than kphi/2^(keySizeInBits -1) */ michael@0: CHECK_MPI_OK( mp_2expt(&k,keySizeInBits-1) ); michael@0: CHECK_MPI_OK( mp_div(&kphi, &k, &k, NULL)); michael@0: if (mp_cmp(&k,e) >= 0) { michael@0: /* also can't be bigger then e-1 */ michael@0: CHECK_MPI_OK( mp_sub_d(e, 1, &k) ); michael@0: } michael@0: michael@0: /* calculate our temp value */ michael@0: /* This saves recalculating this value when the k guess is wrong, which michael@0: * is reasonably frequent. */ michael@0: /* for the modulus case, tmp = n+1 (used to calculate p+q = tmp - phi) */ michael@0: /* for the prime case, tmp = p-1 (used to calculate q-1= phi/tmp) */ michael@0: if (hasModulus) { michael@0: CHECK_MPI_OK( mp_add_d(n, 1, &tmp) ); michael@0: } else { michael@0: CHECK_MPI_OK( mp_sub_d(p, 1, &tmp) ); michael@0: CHECK_MPI_OK(mp_div(&kphi,&tmp,&kphi,&r)); michael@0: if (mp_cmp_z(&r) != 0) { michael@0: /* p-1 doesn't divide kphi, some parameter wasn't correct */ michael@0: err=MP_RANGE; michael@0: goto cleanup; michael@0: } michael@0: mp_zero(q); michael@0: /* kphi is now k*(q-1) */ michael@0: } michael@0: michael@0: /* rest of the for loop */ michael@0: for (; (err == MP_OKAY) && (mpl_significant_bits(&k) >= order_k); michael@0: err = mp_sub_d(&k, 1, &k)) { michael@0: /* looking for k as a factor of kphi */ michael@0: CHECK_MPI_OK(mp_div(&kphi,&k,&phi,&r)); michael@0: if (mp_cmp_z(&r) != 0) { michael@0: /* not a factor, try the next one */ michael@0: continue; michael@0: } michael@0: /* we have a possible phi, see if it works */ michael@0: if (!hasModulus) { michael@0: if ((unsigned)mpl_significant_bits(&phi) != keySizeInBits/2) { michael@0: /* phi is not the right size */ michael@0: continue; michael@0: } michael@0: /* phi should be divisible by 2, since michael@0: * q is odd and phi=(q-1). */ michael@0: if (mpp_divis_d(&phi,2) == MP_NO) { michael@0: /* phi is not divisible by 4 */ michael@0: continue; michael@0: } michael@0: /* we now have a candidate for the second prime */ michael@0: CHECK_MPI_OK(mp_add_d(&phi, 1, &tmp)); michael@0: michael@0: /* check to make sure it is prime */ michael@0: err = rsa_is_prime(&tmp); michael@0: if (err != MP_OKAY) { michael@0: if (err == MP_NO) { michael@0: /* No, then we still have the wrong phi */ michael@0: err = MP_OKAY; michael@0: continue; michael@0: } michael@0: goto cleanup; michael@0: } michael@0: /* michael@0: * It is possible that we have the wrong phi if michael@0: * k_guess*(q_guess-1) = k*(q-1) (k and q-1 have swapped factors). michael@0: * since our q_quess is prime, however. We have found a valid michael@0: * rsa key because: michael@0: * q is the correct order of magnitude. michael@0: * phi = (p-1)(q-1) where p and q are both primes. michael@0: * e*d mod phi = 1. michael@0: * There is no way to know from the info given if this is the michael@0: * original key. We never want to return the wrong key because if michael@0: * two moduli with the same factor is known, then euclid's gcd michael@0: * algorithm can be used to find that factor. Even though the michael@0: * caller didn't pass the original modulus, it doesn't mean the michael@0: * modulus wasn't known or isn't available somewhere. So to be safe michael@0: * if we can't be sure we have the right q, we don't return any. michael@0: * michael@0: * So to make sure we continue looking for other valid q's. If none michael@0: * are found, then we can safely return this one, otherwise we just michael@0: * fail */ michael@0: if (mp_cmp_z(q) != 0) { michael@0: /* this is the second valid q, don't return either, michael@0: * just fail */ michael@0: err = MP_RANGE; michael@0: break; michael@0: } michael@0: /* we only have one q so far, save it and if no others are found, michael@0: * it's safe to return it */ michael@0: CHECK_MPI_OK(mp_copy(&tmp, q)); michael@0: continue; michael@0: } michael@0: /* test our tentative phi */ michael@0: /* phi should be the correct order */ michael@0: if ((unsigned)mpl_significant_bits(&phi) != keySizeInBits) { michael@0: /* phi is not the right size */ michael@0: continue; michael@0: } michael@0: /* phi should be divisible by 4, since michael@0: * p and q are odd and phi=(p-1)(q-1). */ michael@0: if (mpp_divis_d(&phi,4) == MP_NO) { michael@0: /* phi is not divisible by 4 */ michael@0: continue; michael@0: } michael@0: /* n was given, calculate s/2=(p+q)/2 */ michael@0: CHECK_MPI_OK( mp_sub(&tmp, &phi, &s) ); michael@0: CHECK_MPI_OK( mp_div_2(&s, &s) ); michael@0: michael@0: /* calculate sqrt(s/2*s/2-n) */ michael@0: CHECK_MPI_OK(mp_sqr(&s,&sqrt)); michael@0: CHECK_MPI_OK(mp_sub(&sqrt,n,&r)); /* r as a tmp */ michael@0: CHECK_MPI_OK(mp_sqrt(&r,&sqrt)); michael@0: /* make sure it's a perfect square */ michael@0: /* r is our original value we took the square root of */ michael@0: /* q is the square of our tentative square root. They should be equal*/ michael@0: CHECK_MPI_OK(mp_sqr(&sqrt,q)); /* q as a tmp */ michael@0: if (mp_cmp(&r,q) != 0) { michael@0: /* sigh according to the doc, mp_sqrt could return sqrt-1 */ michael@0: CHECK_MPI_OK(mp_add_d(&sqrt,1,&sqrt)); michael@0: CHECK_MPI_OK(mp_sqr(&sqrt,q)); michael@0: if (mp_cmp(&r,q) != 0) { michael@0: /* s*s-n not a perfect square, this phi isn't valid, find * another.*/ michael@0: continue; michael@0: } michael@0: } michael@0: michael@0: /* NOTE: In this case we know we have the one and only answer. michael@0: * "Why?", you ask. Because: michael@0: * 1) n is a composite of two large primes (or it wasn't a michael@0: * valid RSA modulus). michael@0: * 2) If we know any number such that x^2-n is a perfect square michael@0: * and x is not (n+1)/2, then we can calculate 2 non-trivial michael@0: * factors of n. michael@0: * 3) Since we know that n has only 2 non-trivial prime factors, michael@0: * we know the two factors we have are the only possible factors. michael@0: */ michael@0: michael@0: /* Now we are home free to calculate p and q */ michael@0: /* p = s/2 + sqrt, q= s/2 - sqrt */ michael@0: CHECK_MPI_OK(mp_add(&s,&sqrt,p)); michael@0: CHECK_MPI_OK(mp_sub(&s,&sqrt,q)); michael@0: break; michael@0: } michael@0: if ((unsigned)mpl_significant_bits(&k) < order_k) { michael@0: if (hasModulus || (mp_cmp_z(q) == 0)) { michael@0: /* If we get here, something was wrong with the parameters we michael@0: * were given */ michael@0: err = MP_RANGE; michael@0: } michael@0: } michael@0: cleanup: michael@0: mp_clear(&kphi); michael@0: mp_clear(&phi); michael@0: mp_clear(&s); michael@0: mp_clear(&k); michael@0: mp_clear(&r); michael@0: mp_clear(&tmp); michael@0: mp_clear(&sqrt); michael@0: return err; michael@0: } michael@0: michael@0: /* michael@0: * take a private key with only a few elements and fill out the missing pieces. michael@0: * michael@0: * All the entries will be overwritten with data allocated out of the arena michael@0: * If no arena is supplied, one will be created. michael@0: * michael@0: * The following fields must be supplied in order for this function michael@0: * to succeed: michael@0: * one of either publicExponent or privateExponent michael@0: * two more of the following 5 parameters. michael@0: * modulus (n) michael@0: * prime1 (p) michael@0: * prime2 (q) michael@0: * publicExponent (e) michael@0: * privateExponent (d) michael@0: * michael@0: * NOTE: if only the publicExponent, privateExponent, and one prime is given, michael@0: * then there may be more than one RSA key that matches that combination. michael@0: * michael@0: * All parameters will be replaced in the key structure with new parameters michael@0: * Allocated out of the arena. There is no attempt to free the old structures. michael@0: * Prime1 will always be greater than prime2 (even if the caller supplies the michael@0: * smaller prime as prime1 or the larger prime as prime2). The parameters are michael@0: * not overwritten on failure. michael@0: * michael@0: * How it works: michael@0: * We can generate all the parameters from: michael@0: * one of the exponents, plus the two primes. (rsa_build_key_from_primes) * michael@0: * If we are given one of the exponents and both primes, we are done. michael@0: * If we are given one of the exponents, the modulus and one prime, we michael@0: * caclulate the second prime by dividing the modulus by the given michael@0: * prime, giving us and exponent and 2 primes. michael@0: * If we are given 2 exponents and either the modulus or one of the primes michael@0: * we calculate k*phi = d*e-1, where k is an integer less than d which michael@0: * divides d*e-1. We find factor k so we can isolate phi. michael@0: * phi = (p-1)(q-1) michael@0: * If one of the primes are given, we can use phi to find the other prime michael@0: * as follows: q = (phi/(p-1)) + 1. We now have 2 primes and an michael@0: * exponent. (NOTE: if more then one prime meets this condition, the michael@0: * operation will fail. See comments elsewhere in this file about this). michael@0: * If the modulus is given, then we can calculate the sum of the primes michael@0: * as follows: s := (p+q), phi = (p-1)(q-1) = pq -p - q +1, pq = n -> michael@0: * phi = n - s + 1, s = n - phi +1. Now that we have s = p+q and n=pq, michael@0: * we can solve our 2 equations and 2 unknowns as follows: q=s-p -> michael@0: * n=p*(s-p)= sp -p^2 -> p^2-sp+n = 0. Using the quadratic to solve for michael@0: * p, p=1/2*(s+ sqrt(s*s-4*n)) [q=1/2*(s-sqrt(s*s-4*n)]. We again have michael@0: * 2 primes and an exponent. michael@0: * michael@0: */ michael@0: SECStatus michael@0: RSA_PopulatePrivateKey(RSAPrivateKey *key) michael@0: { michael@0: PLArenaPool *arena = NULL; michael@0: PRBool needPublicExponent = PR_TRUE; michael@0: PRBool needPrivateExponent = PR_TRUE; michael@0: PRBool hasModulus = PR_FALSE; michael@0: unsigned int keySizeInBits = 0; michael@0: int prime_count = 0; michael@0: /* standard RSA nominclature */ michael@0: mp_int p, q, e, d, n; michael@0: /* remainder */ michael@0: mp_int r; michael@0: mp_err err = 0; michael@0: SECStatus rv = SECFailure; michael@0: michael@0: MP_DIGITS(&p) = 0; michael@0: MP_DIGITS(&q) = 0; michael@0: MP_DIGITS(&e) = 0; michael@0: MP_DIGITS(&d) = 0; michael@0: MP_DIGITS(&n) = 0; michael@0: MP_DIGITS(&r) = 0; michael@0: CHECK_MPI_OK( mp_init(&p) ); michael@0: CHECK_MPI_OK( mp_init(&q) ); michael@0: CHECK_MPI_OK( mp_init(&e) ); michael@0: CHECK_MPI_OK( mp_init(&d) ); michael@0: CHECK_MPI_OK( mp_init(&n) ); michael@0: CHECK_MPI_OK( mp_init(&r) ); michael@0: michael@0: /* if the key didn't already have an arena, create one. */ michael@0: if (key->arena == NULL) { michael@0: arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE); michael@0: if (!arena) { michael@0: goto cleanup; michael@0: } michael@0: key->arena = arena; michael@0: } michael@0: michael@0: /* load up the known exponents */ michael@0: if (key->publicExponent.data) { michael@0: SECITEM_TO_MPINT(key->publicExponent, &e); michael@0: needPublicExponent = PR_FALSE; michael@0: } michael@0: if (key->privateExponent.data) { michael@0: SECITEM_TO_MPINT(key->privateExponent, &d); michael@0: needPrivateExponent = PR_FALSE; michael@0: } michael@0: if (needPrivateExponent && needPublicExponent) { michael@0: /* Not enough information, we need at least one exponent */ michael@0: err = MP_BADARG; michael@0: goto cleanup; michael@0: } michael@0: michael@0: /* load up the known primes. If only one prime is given, it will be michael@0: * assigned 'p'. Once we have both primes, well make sure p is the larger. michael@0: * The value prime_count tells us howe many we have acquired. michael@0: */ michael@0: if (key->prime1.data) { michael@0: int primeLen = key->prime1.len; michael@0: if (key->prime1.data[0] == 0) { michael@0: primeLen--; michael@0: } michael@0: keySizeInBits = primeLen * 2 * PR_BITS_PER_BYTE; michael@0: SECITEM_TO_MPINT(key->prime1, &p); michael@0: prime_count++; michael@0: } michael@0: if (key->prime2.data) { michael@0: int primeLen = key->prime2.len; michael@0: if (key->prime2.data[0] == 0) { michael@0: primeLen--; michael@0: } michael@0: keySizeInBits = primeLen * 2 * PR_BITS_PER_BYTE; michael@0: SECITEM_TO_MPINT(key->prime2, prime_count ? &q : &p); michael@0: prime_count++; michael@0: } michael@0: /* load up the modulus */ michael@0: if (key->modulus.data) { michael@0: int modLen = key->modulus.len; michael@0: if (key->modulus.data[0] == 0) { michael@0: modLen--; michael@0: } michael@0: keySizeInBits = modLen * PR_BITS_PER_BYTE; michael@0: SECITEM_TO_MPINT(key->modulus, &n); michael@0: hasModulus = PR_TRUE; michael@0: } michael@0: /* if we have the modulus and one prime, calculate the second. */ michael@0: if ((prime_count == 1) && (hasModulus)) { michael@0: mp_div(&n,&p,&q,&r); michael@0: if (mp_cmp_z(&r) != 0) { michael@0: /* p is not a factor or n, fail */ michael@0: err = MP_BADARG; michael@0: goto cleanup; michael@0: } michael@0: prime_count++; michael@0: } michael@0: michael@0: /* If we didn't have enough primes try to calculate the primes from michael@0: * the exponents */ michael@0: if (prime_count < 2) { michael@0: /* if we don't have at least 2 primes at this point, then we need both michael@0: * exponents and one prime or a modulus*/ michael@0: if (!needPublicExponent && !needPrivateExponent && michael@0: ((prime_count > 0) || hasModulus)) { michael@0: CHECK_MPI_OK(rsa_get_primes_from_exponents(&e,&d,&p,&q, michael@0: &n,hasModulus,keySizeInBits)); michael@0: } else { michael@0: /* not enough given parameters to get both primes */ michael@0: err = MP_BADARG; michael@0: goto cleanup; michael@0: } michael@0: } michael@0: michael@0: /* Assure p > q */ michael@0: /* NOTE: PKCS #1 does not require p > q, and NSS doesn't use any michael@0: * implementation optimization that requires p > q. We can remove michael@0: * this code in the future. michael@0: */ michael@0: if (mp_cmp(&p, &q) < 0) michael@0: mp_exch(&p, &q); michael@0: michael@0: /* we now have our 2 primes and at least one exponent, we can fill michael@0: * in the key */ michael@0: rv = rsa_build_from_primes(&p, &q, michael@0: &e, needPublicExponent, michael@0: &d, needPrivateExponent, michael@0: key, keySizeInBits); michael@0: cleanup: michael@0: mp_clear(&p); michael@0: mp_clear(&q); michael@0: mp_clear(&e); michael@0: mp_clear(&d); michael@0: mp_clear(&n); michael@0: mp_clear(&r); michael@0: if (err) { michael@0: MP_TO_SEC_ERROR(err); michael@0: rv = SECFailure; michael@0: } michael@0: if (rv && arena) { michael@0: PORT_FreeArena(arena, PR_TRUE); michael@0: key->arena = NULL; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: static unsigned int michael@0: rsa_modulusLen(SECItem *modulus) michael@0: { michael@0: unsigned char byteZero = modulus->data[0]; michael@0: unsigned int modLen = modulus->len - !byteZero; michael@0: return modLen; michael@0: } michael@0: michael@0: /* michael@0: ** Perform a raw public-key operation michael@0: ** Length of input and output buffers are equal to key's modulus len. michael@0: */ michael@0: SECStatus michael@0: RSA_PublicKeyOp(RSAPublicKey *key, michael@0: unsigned char *output, michael@0: const unsigned char *input) michael@0: { michael@0: unsigned int modLen, expLen, offset; michael@0: mp_int n, e, m, c; michael@0: mp_err err = MP_OKAY; michael@0: SECStatus rv = SECSuccess; michael@0: if (!key || !output || !input) { michael@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); michael@0: return SECFailure; michael@0: } michael@0: MP_DIGITS(&n) = 0; michael@0: MP_DIGITS(&e) = 0; michael@0: MP_DIGITS(&m) = 0; michael@0: MP_DIGITS(&c) = 0; michael@0: CHECK_MPI_OK( mp_init(&n) ); michael@0: CHECK_MPI_OK( mp_init(&e) ); michael@0: CHECK_MPI_OK( mp_init(&m) ); michael@0: CHECK_MPI_OK( mp_init(&c) ); michael@0: modLen = rsa_modulusLen(&key->modulus); michael@0: expLen = rsa_modulusLen(&key->publicExponent); michael@0: /* 1. Obtain public key (n, e) */ michael@0: if (BAD_RSA_KEY_SIZE(modLen, expLen)) { michael@0: PORT_SetError(SEC_ERROR_INVALID_KEY); michael@0: rv = SECFailure; michael@0: goto cleanup; michael@0: } michael@0: SECITEM_TO_MPINT(key->modulus, &n); michael@0: SECITEM_TO_MPINT(key->publicExponent, &e); michael@0: if (e.used > n.used) { michael@0: /* exponent should not be greater than modulus */ michael@0: PORT_SetError(SEC_ERROR_INVALID_KEY); michael@0: rv = SECFailure; michael@0: goto cleanup; michael@0: } michael@0: /* 2. check input out of range (needs to be in range [0..n-1]) */ michael@0: offset = (key->modulus.data[0] == 0) ? 1 : 0; /* may be leading 0 */ michael@0: if (memcmp(input, key->modulus.data + offset, modLen) >= 0) { michael@0: PORT_SetError(SEC_ERROR_INPUT_LEN); michael@0: rv = SECFailure; michael@0: goto cleanup; michael@0: } michael@0: /* 2 bis. Represent message as integer in range [0..n-1] */ michael@0: CHECK_MPI_OK( mp_read_unsigned_octets(&m, input, modLen) ); michael@0: /* 3. Compute c = m**e mod n */ michael@0: #ifdef USE_MPI_EXPT_D michael@0: /* XXX see which is faster */ michael@0: if (MP_USED(&e) == 1) { michael@0: CHECK_MPI_OK( mp_exptmod_d(&m, MP_DIGIT(&e, 0), &n, &c) ); michael@0: } else michael@0: #endif michael@0: CHECK_MPI_OK( mp_exptmod(&m, &e, &n, &c) ); michael@0: /* 4. result c is ciphertext */ michael@0: err = mp_to_fixlen_octets(&c, output, modLen); michael@0: if (err >= 0) err = MP_OKAY; michael@0: cleanup: michael@0: mp_clear(&n); michael@0: mp_clear(&e); michael@0: mp_clear(&m); michael@0: mp_clear(&c); michael@0: if (err) { michael@0: MP_TO_SEC_ERROR(err); michael@0: rv = SECFailure; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /* michael@0: ** RSA Private key operation (no CRT). michael@0: */ michael@0: static SECStatus michael@0: rsa_PrivateKeyOpNoCRT(RSAPrivateKey *key, mp_int *m, mp_int *c, mp_int *n, michael@0: unsigned int modLen) michael@0: { michael@0: mp_int d; michael@0: mp_err err = MP_OKAY; michael@0: SECStatus rv = SECSuccess; michael@0: MP_DIGITS(&d) = 0; michael@0: CHECK_MPI_OK( mp_init(&d) ); michael@0: SECITEM_TO_MPINT(key->privateExponent, &d); michael@0: /* 1. m = c**d mod n */ michael@0: CHECK_MPI_OK( mp_exptmod(c, &d, n, m) ); michael@0: cleanup: michael@0: mp_clear(&d); michael@0: if (err) { michael@0: MP_TO_SEC_ERROR(err); michael@0: rv = SECFailure; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /* michael@0: ** RSA Private key operation using CRT. michael@0: */ michael@0: static SECStatus michael@0: rsa_PrivateKeyOpCRTNoCheck(RSAPrivateKey *key, mp_int *m, mp_int *c) michael@0: { michael@0: mp_int p, q, d_p, d_q, qInv; michael@0: mp_int m1, m2, h, ctmp; michael@0: mp_err err = MP_OKAY; michael@0: SECStatus rv = SECSuccess; michael@0: MP_DIGITS(&p) = 0; michael@0: MP_DIGITS(&q) = 0; michael@0: MP_DIGITS(&d_p) = 0; michael@0: MP_DIGITS(&d_q) = 0; michael@0: MP_DIGITS(&qInv) = 0; michael@0: MP_DIGITS(&m1) = 0; michael@0: MP_DIGITS(&m2) = 0; michael@0: MP_DIGITS(&h) = 0; michael@0: MP_DIGITS(&ctmp) = 0; michael@0: CHECK_MPI_OK( mp_init(&p) ); michael@0: CHECK_MPI_OK( mp_init(&q) ); michael@0: CHECK_MPI_OK( mp_init(&d_p) ); michael@0: CHECK_MPI_OK( mp_init(&d_q) ); michael@0: CHECK_MPI_OK( mp_init(&qInv) ); michael@0: CHECK_MPI_OK( mp_init(&m1) ); michael@0: CHECK_MPI_OK( mp_init(&m2) ); michael@0: CHECK_MPI_OK( mp_init(&h) ); michael@0: CHECK_MPI_OK( mp_init(&ctmp) ); michael@0: /* copy private key parameters into mp integers */ michael@0: SECITEM_TO_MPINT(key->prime1, &p); /* p */ michael@0: SECITEM_TO_MPINT(key->prime2, &q); /* q */ michael@0: SECITEM_TO_MPINT(key->exponent1, &d_p); /* d_p = d mod (p-1) */ michael@0: SECITEM_TO_MPINT(key->exponent2, &d_q); /* d_q = d mod (q-1) */ michael@0: SECITEM_TO_MPINT(key->coefficient, &qInv); /* qInv = q**-1 mod p */ michael@0: /* 1. m1 = c**d_p mod p */ michael@0: CHECK_MPI_OK( mp_mod(c, &p, &ctmp) ); michael@0: CHECK_MPI_OK( mp_exptmod(&ctmp, &d_p, &p, &m1) ); michael@0: /* 2. m2 = c**d_q mod q */ michael@0: CHECK_MPI_OK( mp_mod(c, &q, &ctmp) ); michael@0: CHECK_MPI_OK( mp_exptmod(&ctmp, &d_q, &q, &m2) ); michael@0: /* 3. h = (m1 - m2) * qInv mod p */ michael@0: CHECK_MPI_OK( mp_submod(&m1, &m2, &p, &h) ); michael@0: CHECK_MPI_OK( mp_mulmod(&h, &qInv, &p, &h) ); michael@0: /* 4. m = m2 + h * q */ michael@0: CHECK_MPI_OK( mp_mul(&h, &q, m) ); michael@0: CHECK_MPI_OK( mp_add(m, &m2, m) ); michael@0: cleanup: michael@0: mp_clear(&p); michael@0: mp_clear(&q); michael@0: mp_clear(&d_p); michael@0: mp_clear(&d_q); michael@0: mp_clear(&qInv); michael@0: mp_clear(&m1); michael@0: mp_clear(&m2); michael@0: mp_clear(&h); michael@0: mp_clear(&ctmp); michael@0: if (err) { michael@0: MP_TO_SEC_ERROR(err); michael@0: rv = SECFailure; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /* michael@0: ** An attack against RSA CRT was described by Boneh, DeMillo, and Lipton in: michael@0: ** "On the Importance of Eliminating Errors in Cryptographic Computations", michael@0: ** http://theory.stanford.edu/~dabo/papers/faults.ps.gz michael@0: ** michael@0: ** As a defense against the attack, carry out the private key operation, michael@0: ** followed up with a public key operation to invert the result. michael@0: ** Verify that result against the input. michael@0: */ michael@0: static SECStatus michael@0: rsa_PrivateKeyOpCRTCheckedPubKey(RSAPrivateKey *key, mp_int *m, mp_int *c) michael@0: { michael@0: mp_int n, e, v; michael@0: mp_err err = MP_OKAY; michael@0: SECStatus rv = SECSuccess; michael@0: MP_DIGITS(&n) = 0; michael@0: MP_DIGITS(&e) = 0; michael@0: MP_DIGITS(&v) = 0; michael@0: CHECK_MPI_OK( mp_init(&n) ); michael@0: CHECK_MPI_OK( mp_init(&e) ); michael@0: CHECK_MPI_OK( mp_init(&v) ); michael@0: CHECK_SEC_OK( rsa_PrivateKeyOpCRTNoCheck(key, m, c) ); michael@0: SECITEM_TO_MPINT(key->modulus, &n); michael@0: SECITEM_TO_MPINT(key->publicExponent, &e); michael@0: /* Perform a public key operation v = m ** e mod n */ michael@0: CHECK_MPI_OK( mp_exptmod(m, &e, &n, &v) ); michael@0: if (mp_cmp(&v, c) != 0) { michael@0: rv = SECFailure; michael@0: } michael@0: cleanup: michael@0: mp_clear(&n); michael@0: mp_clear(&e); michael@0: mp_clear(&v); michael@0: if (err) { michael@0: MP_TO_SEC_ERROR(err); michael@0: rv = SECFailure; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: static PRCallOnceType coBPInit = { 0, 0, 0 }; michael@0: static PRStatus michael@0: init_blinding_params_list(void) michael@0: { michael@0: blindingParamsList.lock = PZ_NewLock(nssILockOther); michael@0: if (!blindingParamsList.lock) { michael@0: PORT_SetError(SEC_ERROR_NO_MEMORY); michael@0: return PR_FAILURE; michael@0: } michael@0: blindingParamsList.cVar = PR_NewCondVar( blindingParamsList.lock ); michael@0: if (!blindingParamsList.cVar) { michael@0: PORT_SetError(SEC_ERROR_NO_MEMORY); michael@0: return PR_FAILURE; michael@0: } michael@0: blindingParamsList.waitCount = 0; michael@0: PR_INIT_CLIST(&blindingParamsList.head); michael@0: return PR_SUCCESS; michael@0: } michael@0: michael@0: static SECStatus michael@0: generate_blinding_params(RSAPrivateKey *key, mp_int* f, mp_int* g, mp_int *n, michael@0: unsigned int modLen) michael@0: { michael@0: SECStatus rv = SECSuccess; michael@0: mp_int e, k; michael@0: mp_err err = MP_OKAY; michael@0: unsigned char *kb = NULL; michael@0: michael@0: MP_DIGITS(&e) = 0; michael@0: MP_DIGITS(&k) = 0; michael@0: CHECK_MPI_OK( mp_init(&e) ); michael@0: CHECK_MPI_OK( mp_init(&k) ); michael@0: SECITEM_TO_MPINT(key->publicExponent, &e); michael@0: /* generate random k < n */ michael@0: kb = PORT_Alloc(modLen); michael@0: if (!kb) { michael@0: PORT_SetError(SEC_ERROR_NO_MEMORY); michael@0: goto cleanup; michael@0: } michael@0: CHECK_SEC_OK( RNG_GenerateGlobalRandomBytes(kb, modLen) ); michael@0: CHECK_MPI_OK( mp_read_unsigned_octets(&k, kb, modLen) ); michael@0: /* k < n */ michael@0: CHECK_MPI_OK( mp_mod(&k, n, &k) ); michael@0: /* f = k**e mod n */ michael@0: CHECK_MPI_OK( mp_exptmod(&k, &e, n, f) ); michael@0: /* g = k**-1 mod n */ michael@0: CHECK_MPI_OK( mp_invmod(&k, n, g) ); michael@0: cleanup: michael@0: if (kb) michael@0: PORT_ZFree(kb, modLen); michael@0: mp_clear(&k); michael@0: mp_clear(&e); michael@0: if (err) { michael@0: MP_TO_SEC_ERROR(err); michael@0: rv = SECFailure; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: static SECStatus michael@0: init_blinding_params(RSABlindingParams *rsabp, RSAPrivateKey *key, michael@0: mp_int *n, unsigned int modLen) michael@0: { michael@0: blindingParams * bp = rsabp->array; michael@0: int i = 0; michael@0: michael@0: /* Initialize the list pointer for the element */ michael@0: PR_INIT_CLIST(&rsabp->link); michael@0: for (i = 0; i < RSA_BLINDING_PARAMS_MAX_CACHE_SIZE; ++i, ++bp) { michael@0: bp->next = bp + 1; michael@0: MP_DIGITS(&bp->f) = 0; michael@0: MP_DIGITS(&bp->g) = 0; michael@0: bp->counter = 0; michael@0: } michael@0: /* The last bp->next value was initialized with out michael@0: * of rsabp->array pointer and must be set to NULL michael@0: */ michael@0: rsabp->array[RSA_BLINDING_PARAMS_MAX_CACHE_SIZE - 1].next = NULL; michael@0: michael@0: bp = rsabp->array; michael@0: rsabp->bp = NULL; michael@0: rsabp->free = bp; michael@0: michael@0: /* List elements are keyed using the modulus */ michael@0: SECITEM_CopyItem(NULL, &rsabp->modulus, &key->modulus); michael@0: michael@0: return SECSuccess; michael@0: } michael@0: michael@0: static SECStatus michael@0: get_blinding_params(RSAPrivateKey *key, mp_int *n, unsigned int modLen, michael@0: mp_int *f, mp_int *g) michael@0: { michael@0: RSABlindingParams *rsabp = NULL; michael@0: blindingParams *bpUnlinked = NULL; michael@0: blindingParams *bp; michael@0: PRCList *el; michael@0: SECStatus rv = SECSuccess; michael@0: mp_err err = MP_OKAY; michael@0: int cmp = -1; michael@0: PRBool holdingLock = PR_FALSE; michael@0: michael@0: do { michael@0: if (blindingParamsList.lock == NULL) { michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: /* Acquire the list lock */ michael@0: PZ_Lock(blindingParamsList.lock); michael@0: holdingLock = PR_TRUE; michael@0: michael@0: /* Walk the list looking for the private key */ michael@0: for (el = PR_NEXT_LINK(&blindingParamsList.head); michael@0: el != &blindingParamsList.head; michael@0: el = PR_NEXT_LINK(el)) { michael@0: rsabp = (RSABlindingParams *)el; michael@0: cmp = SECITEM_CompareItem(&rsabp->modulus, &key->modulus); michael@0: if (cmp >= 0) { michael@0: /* The key is found or not in the list. */ michael@0: break; michael@0: } michael@0: } michael@0: michael@0: if (cmp) { michael@0: /* At this point, the key is not in the list. el should point to michael@0: ** the list element before which this key should be inserted. michael@0: */ michael@0: rsabp = PORT_ZNew(RSABlindingParams); michael@0: if (!rsabp) { michael@0: PORT_SetError(SEC_ERROR_NO_MEMORY); michael@0: goto cleanup; michael@0: } michael@0: michael@0: rv = init_blinding_params(rsabp, key, n, modLen); michael@0: if (rv != SECSuccess) { michael@0: PORT_ZFree(rsabp, sizeof(RSABlindingParams)); michael@0: goto cleanup; michael@0: } michael@0: michael@0: /* Insert the new element into the list michael@0: ** If inserting in the middle of the list, el points to the link michael@0: ** to insert before. Otherwise, the link needs to be appended to michael@0: ** the end of the list, which is the same as inserting before the michael@0: ** head (since el would have looped back to the head). michael@0: */ michael@0: PR_INSERT_BEFORE(&rsabp->link, el); michael@0: } michael@0: michael@0: /* We've found (or created) the RSAblindingParams struct for this key. michael@0: * Now, search its list of ready blinding params for a usable one. michael@0: */ michael@0: while (0 != (bp = rsabp->bp)) { michael@0: if (--(bp->counter) > 0) { michael@0: /* Found a match and there are still remaining uses left */ michael@0: /* Return the parameters */ michael@0: CHECK_MPI_OK( mp_copy(&bp->f, f) ); michael@0: CHECK_MPI_OK( mp_copy(&bp->g, g) ); michael@0: michael@0: PZ_Unlock(blindingParamsList.lock); michael@0: return SECSuccess; michael@0: } michael@0: /* exhausted this one, give its values to caller, and michael@0: * then retire it. michael@0: */ michael@0: mp_exch(&bp->f, f); michael@0: mp_exch(&bp->g, g); michael@0: mp_clear( &bp->f ); michael@0: mp_clear( &bp->g ); michael@0: bp->counter = 0; michael@0: /* Move to free list */ michael@0: rsabp->bp = bp->next; michael@0: bp->next = rsabp->free; michael@0: rsabp->free = bp; michael@0: /* In case there're threads waiting for new blinding michael@0: * value - notify 1 thread the value is ready michael@0: */ michael@0: if (blindingParamsList.waitCount > 0) { michael@0: PR_NotifyCondVar( blindingParamsList.cVar ); michael@0: blindingParamsList.waitCount--; michael@0: } michael@0: PZ_Unlock(blindingParamsList.lock); michael@0: return SECSuccess; michael@0: } michael@0: /* We did not find a usable set of blinding params. Can we make one? */ michael@0: /* Find a free bp struct. */ michael@0: if ((bp = rsabp->free) != NULL) { michael@0: /* unlink this bp */ michael@0: rsabp->free = bp->next; michael@0: bp->next = NULL; michael@0: bpUnlinked = bp; /* In case we fail */ michael@0: michael@0: PZ_Unlock(blindingParamsList.lock); michael@0: holdingLock = PR_FALSE; michael@0: /* generate blinding parameter values for the current thread */ michael@0: CHECK_SEC_OK( generate_blinding_params(key, f, g, n, modLen ) ); michael@0: michael@0: /* put the blinding parameter values into cache */ michael@0: CHECK_MPI_OK( mp_init( &bp->f) ); michael@0: CHECK_MPI_OK( mp_init( &bp->g) ); michael@0: CHECK_MPI_OK( mp_copy( f, &bp->f) ); michael@0: CHECK_MPI_OK( mp_copy( g, &bp->g) ); michael@0: michael@0: /* Put this at head of queue of usable params. */ michael@0: PZ_Lock(blindingParamsList.lock); michael@0: holdingLock = PR_TRUE; michael@0: /* initialize RSABlindingParamsStr */ michael@0: bp->counter = RSA_BLINDING_PARAMS_MAX_REUSE; michael@0: bp->next = rsabp->bp; michael@0: rsabp->bp = bp; michael@0: bpUnlinked = NULL; michael@0: /* In case there're threads waiting for new blinding value michael@0: * just notify them the value is ready michael@0: */ michael@0: if (blindingParamsList.waitCount > 0) { michael@0: PR_NotifyAllCondVar( blindingParamsList.cVar ); michael@0: blindingParamsList.waitCount = 0; michael@0: } michael@0: PZ_Unlock(blindingParamsList.lock); michael@0: return SECSuccess; michael@0: } michael@0: /* Here, there are no usable blinding parameters available, michael@0: * and no free bp blocks, presumably because they're all michael@0: * actively having parameters generated for them. michael@0: * So, we need to wait here and not eat up CPU until some michael@0: * change happens. michael@0: */ michael@0: blindingParamsList.waitCount++; michael@0: PR_WaitCondVar( blindingParamsList.cVar, PR_INTERVAL_NO_TIMEOUT ); michael@0: PZ_Unlock(blindingParamsList.lock); michael@0: holdingLock = PR_FALSE; michael@0: } while (1); michael@0: michael@0: cleanup: michael@0: /* It is possible to reach this after the lock is already released. */ michael@0: if (bpUnlinked) { michael@0: if (!holdingLock) { michael@0: PZ_Lock(blindingParamsList.lock); michael@0: holdingLock = PR_TRUE; michael@0: } michael@0: bp = bpUnlinked; michael@0: mp_clear( &bp->f ); michael@0: mp_clear( &bp->g ); michael@0: bp->counter = 0; michael@0: /* Must put the unlinked bp back on the free list */ michael@0: bp->next = rsabp->free; michael@0: rsabp->free = bp; michael@0: } michael@0: if (holdingLock) { michael@0: PZ_Unlock(blindingParamsList.lock); michael@0: holdingLock = PR_FALSE; michael@0: } michael@0: if (err) { michael@0: MP_TO_SEC_ERROR(err); michael@0: } michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* michael@0: ** Perform a raw private-key operation michael@0: ** Length of input and output buffers are equal to key's modulus len. michael@0: */ michael@0: static SECStatus michael@0: rsa_PrivateKeyOp(RSAPrivateKey *key, michael@0: unsigned char *output, michael@0: const unsigned char *input, michael@0: PRBool check) michael@0: { michael@0: unsigned int modLen; michael@0: unsigned int offset; michael@0: SECStatus rv = SECSuccess; michael@0: mp_err err; michael@0: mp_int n, c, m; michael@0: mp_int f, g; michael@0: if (!key || !output || !input) { michael@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); michael@0: return SECFailure; michael@0: } michael@0: /* check input out of range (needs to be in range [0..n-1]) */ michael@0: modLen = rsa_modulusLen(&key->modulus); michael@0: offset = (key->modulus.data[0] == 0) ? 1 : 0; /* may be leading 0 */ michael@0: if (memcmp(input, key->modulus.data + offset, modLen) >= 0) { michael@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); michael@0: return SECFailure; michael@0: } michael@0: MP_DIGITS(&n) = 0; michael@0: MP_DIGITS(&c) = 0; michael@0: MP_DIGITS(&m) = 0; michael@0: MP_DIGITS(&f) = 0; michael@0: MP_DIGITS(&g) = 0; michael@0: CHECK_MPI_OK( mp_init(&n) ); michael@0: CHECK_MPI_OK( mp_init(&c) ); michael@0: CHECK_MPI_OK( mp_init(&m) ); michael@0: CHECK_MPI_OK( mp_init(&f) ); michael@0: CHECK_MPI_OK( mp_init(&g) ); michael@0: SECITEM_TO_MPINT(key->modulus, &n); michael@0: OCTETS_TO_MPINT(input, &c, modLen); michael@0: /* If blinding, compute pre-image of ciphertext by multiplying by michael@0: ** blinding factor michael@0: */ michael@0: if (nssRSAUseBlinding) { michael@0: CHECK_SEC_OK( get_blinding_params(key, &n, modLen, &f, &g) ); michael@0: /* c' = c*f mod n */ michael@0: CHECK_MPI_OK( mp_mulmod(&c, &f, &n, &c) ); michael@0: } michael@0: /* Do the private key operation m = c**d mod n */ michael@0: if ( key->prime1.len == 0 || michael@0: key->prime2.len == 0 || michael@0: key->exponent1.len == 0 || michael@0: key->exponent2.len == 0 || michael@0: key->coefficient.len == 0) { michael@0: CHECK_SEC_OK( rsa_PrivateKeyOpNoCRT(key, &m, &c, &n, modLen) ); michael@0: } else if (check) { michael@0: CHECK_SEC_OK( rsa_PrivateKeyOpCRTCheckedPubKey(key, &m, &c) ); michael@0: } else { michael@0: CHECK_SEC_OK( rsa_PrivateKeyOpCRTNoCheck(key, &m, &c) ); michael@0: } michael@0: /* If blinding, compute post-image of plaintext by multiplying by michael@0: ** blinding factor michael@0: */ michael@0: if (nssRSAUseBlinding) { michael@0: /* m = m'*g mod n */ michael@0: CHECK_MPI_OK( mp_mulmod(&m, &g, &n, &m) ); michael@0: } michael@0: err = mp_to_fixlen_octets(&m, output, modLen); michael@0: if (err >= 0) err = MP_OKAY; michael@0: cleanup: michael@0: mp_clear(&n); michael@0: mp_clear(&c); michael@0: mp_clear(&m); michael@0: mp_clear(&f); michael@0: mp_clear(&g); michael@0: if (err) { michael@0: MP_TO_SEC_ERROR(err); michael@0: rv = SECFailure; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: SECStatus michael@0: RSA_PrivateKeyOp(RSAPrivateKey *key, michael@0: unsigned char *output, michael@0: const unsigned char *input) michael@0: { michael@0: return rsa_PrivateKeyOp(key, output, input, PR_FALSE); michael@0: } michael@0: michael@0: SECStatus michael@0: RSA_PrivateKeyOpDoubleChecked(RSAPrivateKey *key, michael@0: unsigned char *output, michael@0: const unsigned char *input) michael@0: { michael@0: return rsa_PrivateKeyOp(key, output, input, PR_TRUE); michael@0: } michael@0: michael@0: SECStatus michael@0: RSA_PrivateKeyCheck(const RSAPrivateKey *key) michael@0: { michael@0: mp_int p, q, n, psub1, qsub1, e, d, d_p, d_q, qInv, res; michael@0: mp_err err = MP_OKAY; michael@0: SECStatus rv = SECSuccess; michael@0: MP_DIGITS(&p) = 0; michael@0: MP_DIGITS(&q) = 0; michael@0: MP_DIGITS(&n) = 0; michael@0: MP_DIGITS(&psub1)= 0; michael@0: MP_DIGITS(&qsub1)= 0; michael@0: MP_DIGITS(&e) = 0; michael@0: MP_DIGITS(&d) = 0; michael@0: MP_DIGITS(&d_p) = 0; michael@0: MP_DIGITS(&d_q) = 0; michael@0: MP_DIGITS(&qInv) = 0; michael@0: MP_DIGITS(&res) = 0; michael@0: CHECK_MPI_OK( mp_init(&p) ); michael@0: CHECK_MPI_OK( mp_init(&q) ); michael@0: CHECK_MPI_OK( mp_init(&n) ); michael@0: CHECK_MPI_OK( mp_init(&psub1)); michael@0: CHECK_MPI_OK( mp_init(&qsub1)); michael@0: CHECK_MPI_OK( mp_init(&e) ); michael@0: CHECK_MPI_OK( mp_init(&d) ); michael@0: CHECK_MPI_OK( mp_init(&d_p) ); michael@0: CHECK_MPI_OK( mp_init(&d_q) ); michael@0: CHECK_MPI_OK( mp_init(&qInv) ); michael@0: CHECK_MPI_OK( mp_init(&res) ); michael@0: michael@0: if (!key->modulus.data || !key->prime1.data || !key->prime2.data || michael@0: !key->publicExponent.data || !key->privateExponent.data || michael@0: !key->exponent1.data || !key->exponent2.data || michael@0: !key->coefficient.data) { michael@0: /* call RSA_PopulatePrivateKey first, if the application wishes to michael@0: * recover these parameters */ michael@0: err = MP_BADARG; michael@0: goto cleanup; michael@0: } michael@0: michael@0: SECITEM_TO_MPINT(key->modulus, &n); michael@0: SECITEM_TO_MPINT(key->prime1, &p); michael@0: SECITEM_TO_MPINT(key->prime2, &q); michael@0: SECITEM_TO_MPINT(key->publicExponent, &e); michael@0: SECITEM_TO_MPINT(key->privateExponent, &d); michael@0: SECITEM_TO_MPINT(key->exponent1, &d_p); michael@0: SECITEM_TO_MPINT(key->exponent2, &d_q); michael@0: SECITEM_TO_MPINT(key->coefficient, &qInv); michael@0: /* p and q must be distinct. */ michael@0: if (mp_cmp(&p, &q) == 0) { michael@0: rv = SECFailure; michael@0: goto cleanup; michael@0: } michael@0: #define VERIFY_MPI_EQUAL(m1, m2) \ michael@0: if (mp_cmp(m1, m2) != 0) { \ michael@0: rv = SECFailure; \ michael@0: goto cleanup; \ michael@0: } michael@0: #define VERIFY_MPI_EQUAL_1(m) \ michael@0: if (mp_cmp_d(m, 1) != 0) { \ michael@0: rv = SECFailure; \ michael@0: goto cleanup; \ michael@0: } michael@0: /* n == p * q */ michael@0: CHECK_MPI_OK( mp_mul(&p, &q, &res) ); michael@0: VERIFY_MPI_EQUAL(&res, &n); michael@0: /* gcd(e, p-1) == 1 */ michael@0: CHECK_MPI_OK( mp_sub_d(&p, 1, &psub1) ); michael@0: CHECK_MPI_OK( mp_gcd(&e, &psub1, &res) ); michael@0: VERIFY_MPI_EQUAL_1(&res); michael@0: /* gcd(e, q-1) == 1 */ michael@0: CHECK_MPI_OK( mp_sub_d(&q, 1, &qsub1) ); michael@0: CHECK_MPI_OK( mp_gcd(&e, &qsub1, &res) ); michael@0: VERIFY_MPI_EQUAL_1(&res); michael@0: /* d*e == 1 mod p-1 */ michael@0: CHECK_MPI_OK( mp_mulmod(&d, &e, &psub1, &res) ); michael@0: VERIFY_MPI_EQUAL_1(&res); michael@0: /* d*e == 1 mod q-1 */ michael@0: CHECK_MPI_OK( mp_mulmod(&d, &e, &qsub1, &res) ); michael@0: VERIFY_MPI_EQUAL_1(&res); michael@0: /* d_p == d mod p-1 */ michael@0: CHECK_MPI_OK( mp_mod(&d, &psub1, &res) ); michael@0: VERIFY_MPI_EQUAL(&res, &d_p); michael@0: /* d_q == d mod q-1 */ michael@0: CHECK_MPI_OK( mp_mod(&d, &qsub1, &res) ); michael@0: VERIFY_MPI_EQUAL(&res, &d_q); michael@0: /* q * q**-1 == 1 mod p */ michael@0: CHECK_MPI_OK( mp_mulmod(&q, &qInv, &p, &res) ); michael@0: VERIFY_MPI_EQUAL_1(&res); michael@0: michael@0: cleanup: michael@0: mp_clear(&n); michael@0: mp_clear(&p); michael@0: mp_clear(&q); michael@0: mp_clear(&psub1); michael@0: mp_clear(&qsub1); michael@0: mp_clear(&e); michael@0: mp_clear(&d); michael@0: mp_clear(&d_p); michael@0: mp_clear(&d_q); michael@0: mp_clear(&qInv); michael@0: mp_clear(&res); michael@0: if (err) { michael@0: MP_TO_SEC_ERROR(err); michael@0: rv = SECFailure; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: static SECStatus RSA_Init(void) michael@0: { michael@0: if (PR_CallOnce(&coBPInit, init_blinding_params_list) != PR_SUCCESS) { michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: return SECSuccess; michael@0: } michael@0: michael@0: SECStatus BL_Init(void) michael@0: { michael@0: return RSA_Init(); michael@0: } michael@0: michael@0: /* cleanup at shutdown */ michael@0: void RSA_Cleanup(void) michael@0: { michael@0: blindingParams * bp = NULL; michael@0: if (!coBPInit.initialized) michael@0: return; michael@0: michael@0: while (!PR_CLIST_IS_EMPTY(&blindingParamsList.head)) { michael@0: RSABlindingParams *rsabp = michael@0: (RSABlindingParams *)PR_LIST_HEAD(&blindingParamsList.head); michael@0: PR_REMOVE_LINK(&rsabp->link); michael@0: /* clear parameters cache */ michael@0: while (rsabp->bp != NULL) { michael@0: bp = rsabp->bp; michael@0: rsabp->bp = rsabp->bp->next; michael@0: mp_clear( &bp->f ); michael@0: mp_clear( &bp->g ); michael@0: } michael@0: SECITEM_FreeItem(&rsabp->modulus,PR_FALSE); michael@0: PORT_Free(rsabp); michael@0: } michael@0: michael@0: if (blindingParamsList.cVar) { michael@0: PR_DestroyCondVar(blindingParamsList.cVar); michael@0: blindingParamsList.cVar = NULL; michael@0: } michael@0: michael@0: if (blindingParamsList.lock) { michael@0: SKIP_AFTER_FORK(PZ_DestroyLock(blindingParamsList.lock)); michael@0: blindingParamsList.lock = NULL; michael@0: } michael@0: michael@0: coBPInit.initialized = 0; michael@0: coBPInit.inProgress = 0; michael@0: coBPInit.status = 0; michael@0: } michael@0: michael@0: /* michael@0: * need a central place for this function to free up all the memory that michael@0: * free_bl may have allocated along the way. Currently only RSA does this, michael@0: * so I've put it here for now. michael@0: */ michael@0: void BL_Cleanup(void) michael@0: { michael@0: RSA_Cleanup(); michael@0: } michael@0: michael@0: PRBool bl_parentForkedAfterC_Initialize; michael@0: michael@0: /* michael@0: * Set fork flag so it can be tested in SKIP_AFTER_FORK on relevant platforms. michael@0: */ michael@0: void BL_SetForkState(PRBool forked) michael@0: { michael@0: bl_parentForkedAfterC_Initialize = forked; michael@0: } michael@0: