Coverage Report

Created: 2025-08-18 06:34

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