security/nss/lib/freebl/rsa.c

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

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

mercurial