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