summaryrefslogtreecommitdiff
path: root/security/nss/lib/freebl/dh.c
blob: aa3a3ee32a1f9d45eac45d56ca13e5cb5078beb0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * Diffie-Hellman parameter generation, key generation, and secret derivation.
 * KEA secret generation and verification.
 */
#ifdef FREEBL_NO_DEPEND
#include "stubs.h"
#endif

#include "prerr.h"
#include "secerr.h"

#include "blapi.h"
#include "blapii.h"
#include "secitem.h"
#include "mpi.h"
#include "mpprime.h"
#include "secmpi.h"

#define KEA_DERIVED_SECRET_LEN 128

/* Lengths are in bytes. */
static unsigned int
dh_GetSecretKeyLen(unsigned int primeLen)
{
    /* Based on Table 2 in NIST SP 800-57. */
    if (primeLen >= 1920) { /* 15360 bits */
        return 64;          /* 512 bits */
    }
    if (primeLen >= 960) { /* 7680 bits */
        return 48;         /* 384 bits */
    }
    if (primeLen >= 384) { /* 3072 bits */
        return 32;         /* 256 bits */
    }
    if (primeLen >= 256) { /* 2048 bits */
        return 28;         /* 224 bits */
    }
    return 20; /* 160 bits */
}

SECStatus
DH_GenParam(int primeLen, DHParams **params)
{
    PLArenaPool *arena;
    DHParams *dhparams;
    unsigned char *ab = NULL;
    mp_int p, q, a, h, psub1, test;
    mp_err err = MP_OKAY;
    SECStatus rv = SECSuccess;
    if (!params || primeLen < 0) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }
    arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
    if (!arena) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return SECFailure;
    }
    dhparams = (DHParams *)PORT_ArenaZAlloc(arena, sizeof(DHParams));
    if (!dhparams) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        PORT_FreeArena(arena, PR_TRUE);
        return SECFailure;
    }
    dhparams->arena = arena;
    MP_DIGITS(&p) = 0;
    MP_DIGITS(&q) = 0;
    MP_DIGITS(&a) = 0;
    MP_DIGITS(&h) = 0;
    MP_DIGITS(&psub1) = 0;
    MP_DIGITS(&test) = 0;
    CHECK_MPI_OK(mp_init(&p));
    CHECK_MPI_OK(mp_init(&q));
    CHECK_MPI_OK(mp_init(&a));
    CHECK_MPI_OK(mp_init(&h));
    CHECK_MPI_OK(mp_init(&psub1));
    CHECK_MPI_OK(mp_init(&test));
    /* generate prime with MPI, uses Miller-Rabin to generate safe prime. */
    CHECK_SEC_OK(generate_prime(&p, primeLen));
    /* construct Sophie-Germain prime q = (p-1)/2. */
    CHECK_MPI_OK(mp_sub_d(&p, 1, &psub1));
    CHECK_MPI_OK(mp_div_2(&psub1, &q));
    /* construct a generator from the prime. */
    ab = PORT_Alloc(primeLen);
    if (!ab) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        rv = SECFailure;
        goto cleanup;
    }
    /* generate a candidate number a in p's field */
    CHECK_SEC_OK(RNG_GenerateGlobalRandomBytes(ab, primeLen));
    CHECK_MPI_OK(mp_read_unsigned_octets(&a, ab, primeLen));
    /* force a < p (note that quot(a/p) <= 1) */
    if (mp_cmp(&a, &p) > 0)
        CHECK_MPI_OK(mp_sub(&a, &p, &a));
    do {
        /* check that a is in the range [2..p-1] */
        if (mp_cmp_d(&a, 2) < 0 || mp_cmp(&a, &psub1) >= 0) {
            /* a is outside of the allowed range.  Set a=3 and keep going. */
            mp_set(&a, 3);
        }
        /* if a**q mod p != 1 then a is a generator */
        CHECK_MPI_OK(mp_exptmod(&a, &q, &p, &test));
        if (mp_cmp_d(&test, 1) != 0)
            break;
        /* increment the candidate and try again. */
        CHECK_MPI_OK(mp_add_d(&a, 1, &a));
    } while (PR_TRUE);
    MPINT_TO_SECITEM(&p, &dhparams->prime, arena);
    MPINT_TO_SECITEM(&a, &dhparams->base, arena);
    *params = dhparams;
cleanup:
    mp_clear(&p);
    mp_clear(&q);
    mp_clear(&a);
    mp_clear(&h);
    mp_clear(&psub1);
    mp_clear(&test);
    if (ab) {
        PORT_ZFree(ab, primeLen);
    }
    if (err) {
        MP_TO_SEC_ERROR(err);
        rv = SECFailure;
    }
    if (rv != SECSuccess) {
        PORT_FreeArena(arena, PR_TRUE);
    }
    return rv;
}

SECStatus
DH_NewKey(DHParams *params, DHPrivateKey **privKey)
{
    PLArenaPool *arena;
    DHPrivateKey *key;
    mp_int g, xa, p, Ya;
    mp_err err = MP_OKAY;
    SECStatus rv = SECSuccess;
    if (!params || !privKey) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }
    arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
    if (!arena) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return SECFailure;
    }
    key = (DHPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(DHPrivateKey));
    if (!key) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        PORT_FreeArena(arena, PR_TRUE);
        return SECFailure;
    }
    key->arena = arena;
    MP_DIGITS(&g) = 0;
    MP_DIGITS(&xa) = 0;
    MP_DIGITS(&p) = 0;
    MP_DIGITS(&Ya) = 0;
    CHECK_MPI_OK(mp_init(&g));
    CHECK_MPI_OK(mp_init(&xa));
    CHECK_MPI_OK(mp_init(&p));
    CHECK_MPI_OK(mp_init(&Ya));
    /* Set private key's p */
    CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->prime, &params->prime));
    SECITEM_TO_MPINT(key->prime, &p);
    /* Set private key's g */
    CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->base, &params->base));
    SECITEM_TO_MPINT(key->base, &g);
    /* Generate private key xa */
    SECITEM_AllocItem(arena, &key->privateValue,
                      dh_GetSecretKeyLen(params->prime.len));
    CHECK_SEC_OK(RNG_GenerateGlobalRandomBytes(key->privateValue.data,
                                               key->privateValue.len));
    SECITEM_TO_MPINT(key->privateValue, &xa);
    /* xa < p */
    CHECK_MPI_OK(mp_mod(&xa, &p, &xa));
    /* Compute public key Ya = g ** xa mod p */
    CHECK_MPI_OK(mp_exptmod(&g, &xa, &p, &Ya));
    MPINT_TO_SECITEM(&Ya, &key->publicValue, key->arena);
    *privKey = key;
cleanup:
    mp_clear(&g);
    mp_clear(&xa);
    mp_clear(&p);
    mp_clear(&Ya);
    if (err) {
        MP_TO_SEC_ERROR(err);
        rv = SECFailure;
    }
    if (rv) {
        *privKey = NULL;
        PORT_FreeArena(arena, PR_TRUE);
    }
    return rv;
}

SECStatus
DH_Derive(SECItem *publicValue,
          SECItem *prime,
          SECItem *privateValue,
          SECItem *derivedSecret,
          unsigned int outBytes)
{
    mp_int p, Xa, Yb, ZZ, psub1;
    mp_err err = MP_OKAY;
    unsigned int len = 0;
    unsigned int nb;
    unsigned char *secret = NULL;
    if (!publicValue || !publicValue->len || !prime || !prime->len ||
        !privateValue || !privateValue->len || !derivedSecret) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }
    memset(derivedSecret, 0, sizeof *derivedSecret);
    MP_DIGITS(&p) = 0;
    MP_DIGITS(&Xa) = 0;
    MP_DIGITS(&Yb) = 0;
    MP_DIGITS(&ZZ) = 0;
    MP_DIGITS(&psub1) = 0;
    CHECK_MPI_OK(mp_init(&p));
    CHECK_MPI_OK(mp_init(&Xa));
    CHECK_MPI_OK(mp_init(&Yb));
    CHECK_MPI_OK(mp_init(&ZZ));
    CHECK_MPI_OK(mp_init(&psub1));
    SECITEM_TO_MPINT(*publicValue, &Yb);
    SECITEM_TO_MPINT(*privateValue, &Xa);
    SECITEM_TO_MPINT(*prime, &p);
    CHECK_MPI_OK(mp_sub_d(&p, 1, &psub1));

    /* We assume that the modulus, p, is a safe prime. That is, p = 2q+1 where
     * q is also a prime. Thus the orders of the subgroups are factors of 2q:
     * namely 1, 2, q and 2q.
     *
     * We check that the peer's public value isn't zero (which isn't in the
     * group), one (subgroup of order one) or p-1 (subgroup of order 2). We
     * also check that the public value is less than p, to avoid being fooled
     * by values like p+1 or 2*p-1.
     *
     * Thus we must be operating in the subgroup of size q or 2q. */
    if (mp_cmp_d(&Yb, 1) <= 0 ||
        mp_cmp(&Yb, &psub1) >= 0) {
        err = MP_BADARG;
        goto cleanup;
    }

    /* ZZ = (Yb)**Xa mod p */
    CHECK_MPI_OK(mp_exptmod(&Yb, &Xa, &p, &ZZ));
    /* number of bytes in the derived secret */
    len = mp_unsigned_octet_size(&ZZ);
    if (len <= 0) {
        err = MP_BADARG;
        goto cleanup;
    }

    /*
     * We check to make sure that ZZ is not equal to 0, 1 or -1 mod p.
     * This helps guard against small subgroup attacks, since an attacker
     * using a subgroup of size N will produce 0, 1 or -1 with probability 1/N.
     * When the protocol is executed within a properly large subgroup, the
     * probability of this result will be negligibly small.  For example,
     * with a safe prime of the form 2q+1, the probability will be 1/q.
     *
     * We return MP_BADARG because this is probably the result of a bad
     * public value or a bad prime having been provided.
     */
    if (mp_cmp_d(&ZZ, 0) == 0 || mp_cmp_d(&ZZ, 1) == 0 ||
        mp_cmp(&ZZ, &psub1) == 0) {
        err = MP_BADARG;
        goto cleanup;
    }

    /* allocate a buffer which can hold the entire derived secret. */
    secret = PORT_Alloc(len);
    if (secret == NULL) {
        err = MP_MEM;
        goto cleanup;
    }
    /* grab the derived secret */
    err = mp_to_unsigned_octets(&ZZ, secret, len);
    if (err >= 0)
        err = MP_OKAY;
    /*
    ** if outBytes is 0 take all of the bytes from the derived secret.
    ** if outBytes is not 0 take exactly outBytes from the derived secret, zero
    ** pad at the beginning if necessary, and truncate beginning bytes
    ** if necessary.
    */
    if (outBytes > 0)
        nb = outBytes;
    else
        nb = len;
    if (SECITEM_AllocItem(NULL, derivedSecret, nb) == NULL) {
        err = MP_MEM;
        goto cleanup;
    }
    if (len < nb) {
        unsigned int offset = nb - len;
        memset(derivedSecret->data, 0, offset);
        memcpy(derivedSecret->data + offset, secret, len);
    } else {
        memcpy(derivedSecret->data, secret + len - nb, nb);
    }
cleanup:
    mp_clear(&p);
    mp_clear(&Xa);
    mp_clear(&Yb);
    mp_clear(&ZZ);
    mp_clear(&psub1);
    if (secret) {
        /* free the buffer allocated for the full secret. */
        PORT_ZFree(secret, len);
    }
    if (err) {
        MP_TO_SEC_ERROR(err);
        if (derivedSecret->data)
            PORT_ZFree(derivedSecret->data, derivedSecret->len);
        return SECFailure;
    }
    return SECSuccess;
}

SECStatus
KEA_Derive(SECItem *prime,
           SECItem *public1,
           SECItem *public2,
           SECItem *private1,
           SECItem *private2,
           SECItem *derivedSecret)
{
    mp_int p, Y, R, r, x, t, u, w;
    mp_err err;
    unsigned char *secret = NULL;
    unsigned int len = 0, offset;
    if (!prime || !public1 || !public2 || !private1 || !private2 ||
        !derivedSecret) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }
    memset(derivedSecret, 0, sizeof *derivedSecret);
    MP_DIGITS(&p) = 0;
    MP_DIGITS(&Y) = 0;
    MP_DIGITS(&R) = 0;
    MP_DIGITS(&r) = 0;
    MP_DIGITS(&x) = 0;
    MP_DIGITS(&t) = 0;
    MP_DIGITS(&u) = 0;
    MP_DIGITS(&w) = 0;
    CHECK_MPI_OK(mp_init(&p));
    CHECK_MPI_OK(mp_init(&Y));
    CHECK_MPI_OK(mp_init(&R));
    CHECK_MPI_OK(mp_init(&r));
    CHECK_MPI_OK(mp_init(&x));
    CHECK_MPI_OK(mp_init(&t));
    CHECK_MPI_OK(mp_init(&u));
    CHECK_MPI_OK(mp_init(&w));
    SECITEM_TO_MPINT(*prime, &p);
    SECITEM_TO_MPINT(*public1, &Y);
    SECITEM_TO_MPINT(*public2, &R);
    SECITEM_TO_MPINT(*private1, &r);
    SECITEM_TO_MPINT(*private2, &x);
    /* t = DH(Y, r, p) = Y ** r mod p */
    CHECK_MPI_OK(mp_exptmod(&Y, &r, &p, &t));
    /* u = DH(R, x, p) = R ** x mod p */
    CHECK_MPI_OK(mp_exptmod(&R, &x, &p, &u));
    /* w = (t + u) mod p */
    CHECK_MPI_OK(mp_addmod(&t, &u, &p, &w));
    /* allocate a buffer for the full derived secret */
    len = mp_unsigned_octet_size(&w);
    secret = PORT_Alloc(len);
    if (secret == NULL) {
        err = MP_MEM;
        goto cleanup;
    }
    /* grab the secret */
    err = mp_to_unsigned_octets(&w, secret, len);
    if (err > 0)
        err = MP_OKAY;
    /* allocate output buffer */
    if (SECITEM_AllocItem(NULL, derivedSecret, KEA_DERIVED_SECRET_LEN) == NULL) {
        err = MP_MEM;
        goto cleanup;
    }
    memset(derivedSecret->data, 0, derivedSecret->len);
    /* copy in the 128 lsb of the secret */
    if (len >= KEA_DERIVED_SECRET_LEN) {
        memcpy(derivedSecret->data, secret + (len - KEA_DERIVED_SECRET_LEN),
               KEA_DERIVED_SECRET_LEN);
    } else {
        offset = KEA_DERIVED_SECRET_LEN - len;
        memcpy(derivedSecret->data + offset, secret, len);
    }
cleanup:
    mp_clear(&p);
    mp_clear(&Y);
    mp_clear(&R);
    mp_clear(&r);
    mp_clear(&x);
    mp_clear(&t);
    mp_clear(&u);
    mp_clear(&w);
    if (secret)
        PORT_ZFree(secret, len);
    if (err) {
        MP_TO_SEC_ERROR(err);
        if (derivedSecret->data)
            PORT_ZFree(derivedSecret->data, derivedSecret->len);
        return SECFailure;
    }
    return SECSuccess;
}

/* Test counts based on the fact the prime and subprime
 * were given to us */
static int
dh_prime_testcount(int prime_length)
{
    if (prime_length < 1024) {
        return 50;
    } else if (prime_length < 2048) {
        return 40;
    } else if (prime_length < 3072) {
        return 56;
    }
    return 64;
}

PRBool
KEA_PrimeCheck(SECItem *prime)
{
    mp_int p;
    mp_err err = 0;
    MP_DIGITS(&p) = 0;
    CHECK_MPI_OK(mp_init(&p));
    SECITEM_TO_MPINT(*prime, &p);
    CHECK_MPI_OK(mpp_pprime(&p, dh_prime_testcount(prime->len)));
cleanup:
    mp_clear(&p);
    return err ? PR_FALSE : PR_TRUE;
}

PRBool
KEA_Verify(SECItem *Y, SECItem *prime, SECItem *subPrime)
{
    mp_int p, q, y, r;
    mp_err err;
    int cmp = 1; /* default is false */
    if (!Y || !prime || !subPrime) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }
    MP_DIGITS(&p) = 0;
    MP_DIGITS(&q) = 0;
    MP_DIGITS(&y) = 0;
    MP_DIGITS(&r) = 0;
    CHECK_MPI_OK(mp_init(&p));
    CHECK_MPI_OK(mp_init(&q));
    CHECK_MPI_OK(mp_init(&y));
    CHECK_MPI_OK(mp_init(&r));
    SECITEM_TO_MPINT(*prime, &p);
    SECITEM_TO_MPINT(*subPrime, &q);
    SECITEM_TO_MPINT(*Y, &y);
    /* compute r = y**q mod p */
    CHECK_MPI_OK(mp_exptmod(&y, &q, &p, &r));
    /* compare to 1 */
    cmp = mp_cmp_d(&r, 1);
cleanup:
    mp_clear(&p);
    mp_clear(&q);
    mp_clear(&y);
    mp_clear(&r);
    if (err) {
        MP_TO_SEC_ERROR(err);
        return PR_FALSE;
    }
    return (cmp == 0) ? PR_TRUE : PR_FALSE;
}