Coverage Report

Created: 2026-10-13 06:23

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