Coverage Report

Created: 2023-09-25 06:45

/src/openssl30/crypto/dh/dh_key.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
/*
11
 * DH low level APIs are deprecated for public use, but still ok for
12
 * internal use.
13
 */
14
#include "internal/deprecated.h"
15
16
#include <stdio.h>
17
#include "internal/cryptlib.h"
18
#include "dh_local.h"
19
#include "crypto/bn.h"
20
#include "crypto/dh.h"
21
#include "crypto/security_bits.h"
22
23
#ifdef FIPS_MODULE
24
# define MIN_STRENGTH 112
25
#else
26
0
# define MIN_STRENGTH 80
27
#endif
28
29
static int generate_key(DH *dh);
30
static int dh_bn_mod_exp(const DH *dh, BIGNUM *r,
31
                         const BIGNUM *a, const BIGNUM *p,
32
                         const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
33
static int dh_init(DH *dh);
34
static int dh_finish(DH *dh);
35
36
/*
37
 * See SP800-56Ar3 Section 5.7.1.1
38
 * Finite Field Cryptography Diffie-Hellman (FFC DH) Primitive
39
 */
40
int ossl_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh)
41
1.53k
{
42
1.53k
    BN_CTX *ctx = NULL;
43
1.53k
    BN_MONT_CTX *mont = NULL;
44
1.53k
    BIGNUM *z = NULL, *pminus1;
45
1.53k
    int ret = -1;
46
47
1.53k
    if (BN_num_bits(dh->params.p) > OPENSSL_DH_MAX_MODULUS_BITS) {
48
0
        ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_LARGE);
49
0
        goto err;
50
0
    }
51
52
1.53k
    if (BN_num_bits(dh->params.p) < DH_MIN_MODULUS_BITS) {
53
0
        ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_SMALL);
54
0
        return 0;
55
0
    }
56
57
1.53k
    ctx = BN_CTX_new_ex(dh->libctx);
58
1.53k
    if (ctx == NULL)
59
0
        goto err;
60
1.53k
    BN_CTX_start(ctx);
61
1.53k
    pminus1 = BN_CTX_get(ctx);
62
1.53k
    z = BN_CTX_get(ctx);
63
1.53k
    if (z == NULL)
64
0
        goto err;
65
66
1.53k
    if (dh->priv_key == NULL) {
67
0
        ERR_raise(ERR_LIB_DH, DH_R_NO_PRIVATE_VALUE);
68
0
        goto err;
69
0
    }
70
71
1.53k
    if (dh->flags & DH_FLAG_CACHE_MONT_P) {
72
1.53k
        mont = BN_MONT_CTX_set_locked(&dh->method_mont_p,
73
1.53k
                                      dh->lock, dh->params.p, ctx);
74
1.53k
        BN_set_flags(dh->priv_key, BN_FLG_CONSTTIME);
75
1.53k
        if (!mont)
76
0
            goto err;
77
1.53k
    }
78
79
    /* (Step 1) Z = pub_key^priv_key mod p */
80
1.53k
    if (!dh->meth->bn_mod_exp(dh, z, pub_key, dh->priv_key, dh->params.p, ctx,
81
1.53k
                              mont)) {
82
0
        ERR_raise(ERR_LIB_DH, ERR_R_BN_LIB);
83
0
        goto err;
84
0
    }
85
86
    /* (Step 2) Error if z <= 1 or z = p - 1 */
87
1.53k
    if (BN_copy(pminus1, dh->params.p) == NULL
88
1.53k
        || !BN_sub_word(pminus1, 1)
89
1.53k
        || BN_cmp(z, BN_value_one()) <= 0
90
1.53k
        || BN_cmp(z, pminus1) == 0) {
91
0
        ERR_raise(ERR_LIB_DH, DH_R_INVALID_SECRET);
92
0
        goto err;
93
0
    }
94
95
    /* return the padded key, i.e. same number of bytes as the modulus */
96
1.53k
    ret = BN_bn2binpad(z, key, BN_num_bytes(dh->params.p));
97
1.53k
 err:
98
1.53k
    BN_clear(z); /* (Step 2) destroy intermediate values */
99
1.53k
    BN_CTX_end(ctx);
100
1.53k
    BN_CTX_free(ctx);
101
1.53k
    return ret;
102
1.53k
}
103
104
/*-
105
 * NB: This function is inherently not constant time due to the
106
 * RFC 5246 (8.1.2) padding style that strips leading zero bytes.
107
 */
108
int DH_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh)
109
2.45k
{
110
2.45k
    int ret = 0, i;
111
2.45k
    volatile size_t npad = 0, mask = 1;
112
113
    /* compute the key; ret is constant unless compute_key is external */
114
#ifdef FIPS_MODULE
115
    ret = ossl_dh_compute_key(key, pub_key, dh);
116
#else
117
2.45k
    ret = dh->meth->compute_key(key, pub_key, dh);
118
2.45k
#endif
119
2.45k
    if (ret <= 0)
120
13
        return ret;
121
122
    /* count leading zero bytes, yet still touch all bytes */
123
628k
    for (i = 0; i < ret; i++) {
124
625k
        mask &= !key[i];
125
625k
        npad += mask;
126
625k
    }
127
128
    /* unpad key */
129
2.43k
    ret -= npad;
130
    /* key-dependent memory access, potentially leaking npad / ret */
131
2.43k
    memmove(key, key + npad, ret);
132
    /* key-dependent memory access, potentially leaking npad / ret */
133
2.43k
    memset(key + ret, 0, npad);
134
135
2.43k
    return ret;
136
2.45k
}
137
138
int DH_compute_key_padded(unsigned char *key, const BIGNUM *pub_key, DH *dh)
139
0
{
140
0
    int rv, pad;
141
142
    /* rv is constant unless compute_key is external */
143
#ifdef FIPS_MODULE
144
    rv = ossl_dh_compute_key(key, pub_key, dh);
145
#else
146
0
    rv = dh->meth->compute_key(key, pub_key, dh);
147
0
#endif
148
0
    if (rv <= 0)
149
0
        return rv;
150
0
    pad = BN_num_bytes(dh->params.p) - rv;
151
    /* pad is constant (zero) unless compute_key is external */
152
0
    if (pad > 0) {
153
0
        memmove(key + pad, key, rv);
154
0
        memset(key, 0, pad);
155
0
    }
156
0
    return rv + pad;
157
0
}
158
159
static DH_METHOD dh_ossl = {
160
    "OpenSSL DH Method",
161
    generate_key,
162
    ossl_dh_compute_key,
163
    dh_bn_mod_exp,
164
    dh_init,
165
    dh_finish,
166
    DH_FLAG_FIPS_METHOD,
167
    NULL,
168
    NULL
169
};
170
171
static const DH_METHOD *default_DH_method = &dh_ossl;
172
173
const DH_METHOD *DH_OpenSSL(void)
174
8.60k
{
175
8.60k
    return &dh_ossl;
176
8.60k
}
177
178
const DH_METHOD *DH_get_default_method(void)
179
156k
{
180
156k
    return default_DH_method;
181
156k
}
182
183
static int dh_bn_mod_exp(const DH *dh, BIGNUM *r,
184
                         const BIGNUM *a, const BIGNUM *p,
185
                         const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
186
5.17k
{
187
5.17k
    return BN_mod_exp_mont(r, a, p, m, ctx, m_ctx);
188
5.17k
}
189
190
static int dh_init(DH *dh)
191
156k
{
192
156k
    dh->flags |= DH_FLAG_CACHE_MONT_P;
193
156k
    ossl_ffc_params_init(&dh->params);
194
156k
    dh->dirty_cnt++;
195
156k
    return 1;
196
156k
}
197
198
static int dh_finish(DH *dh)
199
156k
{
200
156k
    BN_MONT_CTX_free(dh->method_mont_p);
201
156k
    return 1;
202
156k
}
203
204
#ifndef FIPS_MODULE
205
void DH_set_default_method(const DH_METHOD *meth)
206
0
{
207
0
    default_DH_method = meth;
208
0
}
209
#endif /* FIPS_MODULE */
210
211
int DH_generate_key(DH *dh)
212
2.74k
{
213
#ifdef FIPS_MODULE
214
    return generate_key(dh);
215
#else
216
2.74k
    return dh->meth->generate_key(dh);
217
2.74k
#endif
218
2.74k
}
219
220
int ossl_dh_generate_public_key(BN_CTX *ctx, const DH *dh,
221
                                const BIGNUM *priv_key, BIGNUM *pub_key)
222
1.82k
{
223
1.82k
    int ret = 0;
224
1.82k
    BIGNUM *prk = BN_new();
225
1.82k
    BN_MONT_CTX *mont = NULL;
226
227
1.82k
    if (prk == NULL)
228
0
        return 0;
229
230
1.82k
    if (dh->flags & DH_FLAG_CACHE_MONT_P) {
231
        /*
232
         * We take the input DH as const, but we lie, because in some cases we
233
         * want to get a hold of its Montgomery context.
234
         *
235
         * We cast to remove the const qualifier in this case, it should be
236
         * fine...
237
         */
238
1.82k
        BN_MONT_CTX **pmont = (BN_MONT_CTX **)&dh->method_mont_p;
239
240
1.82k
        mont = BN_MONT_CTX_set_locked(pmont, dh->lock, dh->params.p, ctx);
241
1.82k
        if (mont == NULL)
242
3
            goto err;
243
1.82k
    }
244
1.82k
    BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME);
245
246
    /* pub_key = g^priv_key mod p */
247
1.82k
    if (!dh->meth->bn_mod_exp(dh, pub_key, dh->params.g, prk, dh->params.p,
248
1.82k
                              ctx, mont))
249
0
        goto err;
250
1.82k
    ret = 1;
251
1.82k
err:
252
1.82k
    BN_clear_free(prk);
253
1.82k
    return ret;
254
1.82k
}
255
256
static int generate_key(DH *dh)
257
1.83k
{
258
1.83k
    int ok = 0;
259
1.83k
    int generate_new_key = 0;
260
1.83k
#ifndef FIPS_MODULE
261
1.83k
    unsigned l;
262
1.83k
#endif
263
1.83k
    BN_CTX *ctx = NULL;
264
1.83k
    BIGNUM *pub_key = NULL, *priv_key = NULL;
265
266
1.83k
    if (BN_num_bits(dh->params.p) > OPENSSL_DH_MAX_MODULUS_BITS) {
267
0
        ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_LARGE);
268
0
        return 0;
269
0
    }
270
271
1.83k
    if (BN_num_bits(dh->params.p) < DH_MIN_MODULUS_BITS) {
272
4
        ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_SMALL);
273
4
        return 0;
274
4
    }
275
276
1.82k
    ctx = BN_CTX_new_ex(dh->libctx);
277
1.82k
    if (ctx == NULL)
278
0
        goto err;
279
280
1.82k
    if (dh->priv_key == NULL) {
281
1.79k
        priv_key = BN_secure_new();
282
1.79k
        if (priv_key == NULL)
283
0
            goto err;
284
1.79k
        generate_new_key = 1;
285
1.79k
    } else {
286
33
        priv_key = dh->priv_key;
287
33
    }
288
289
1.82k
    if (dh->pub_key == NULL) {
290
1.82k
        pub_key = BN_new();
291
1.82k
        if (pub_key == NULL)
292
0
            goto err;
293
1.82k
    } else {
294
0
        pub_key = dh->pub_key;
295
0
    }
296
1.82k
    if (generate_new_key) {
297
        /* Is it an approved safe prime ?*/
298
1.79k
        if (DH_get_nid(dh) != NID_undef) {
299
505
            int max_strength =
300
505
                    ossl_ifc_ffc_compute_security_bits(BN_num_bits(dh->params.p));
301
302
505
            if (dh->params.q == NULL
303
505
                || dh->length > BN_num_bits(dh->params.q))
304
0
                goto err;
305
            /* dh->length = maximum bit length of generated private key */
306
505
            if (!ossl_ffc_generate_private_key(ctx, &dh->params, dh->length,
307
505
                                               max_strength, priv_key))
308
0
                goto err;
309
1.28k
        } else {
310
#ifdef FIPS_MODULE
311
            if (dh->params.q == NULL)
312
                goto err;
313
#else
314
1.28k
            if (dh->params.q == NULL) {
315
                /* secret exponent length, must satisfy 2^(l-1) <= p */
316
1.28k
                if (dh->length != 0
317
1.28k
                    && dh->length >= BN_num_bits(dh->params.p))
318
0
                    goto err;
319
1.28k
                l = dh->length ? dh->length : BN_num_bits(dh->params.p) - 1;
320
1.28k
                if (!BN_priv_rand_ex(priv_key, l, BN_RAND_TOP_ONE,
321
1.28k
                                     BN_RAND_BOTTOM_ANY, 0, ctx))
322
0
                    goto err;
323
                /*
324
                 * We handle just one known case where g is a quadratic non-residue:
325
                 * for g = 2: p % 8 == 3
326
                 */
327
1.28k
                if (BN_is_word(dh->params.g, DH_GENERATOR_2)
328
1.28k
                    && !BN_is_bit_set(dh->params.p, 2)) {
329
                    /* clear bit 0, since it won't be a secret anyway */
330
75
                    if (!BN_clear_bit(priv_key, 0))
331
0
                        goto err;
332
75
                }
333
1.28k
            } else
334
0
#endif
335
0
            {
336
                /* Do a partial check for invalid p, q, g */
337
0
                if (!ossl_ffc_params_simple_validate(dh->libctx, &dh->params,
338
0
                                                     FFC_PARAM_TYPE_DH, NULL))
339
0
                    goto err;
340
                /*
341
                 * For FFC FIPS 186-4 keygen
342
                 * security strength s = 112,
343
                 * Max Private key size N = len(q)
344
                 */
345
0
                if (!ossl_ffc_generate_private_key(ctx, &dh->params,
346
0
                                                   BN_num_bits(dh->params.q),
347
0
                                                   MIN_STRENGTH,
348
0
                                                   priv_key))
349
0
                    goto err;
350
0
            }
351
1.28k
        }
352
1.79k
    }
353
354
1.82k
    if (!ossl_dh_generate_public_key(ctx, dh, priv_key, pub_key))
355
3
        goto err;
356
357
1.82k
    dh->pub_key = pub_key;
358
1.82k
    dh->priv_key = priv_key;
359
1.82k
    dh->dirty_cnt++;
360
1.82k
    ok = 1;
361
1.82k
 err:
362
1.82k
    if (ok != 1)
363
1.82k
        ERR_raise(ERR_LIB_DH, ERR_R_BN_LIB);
364
365
1.82k
    if (pub_key != dh->pub_key)
366
3
        BN_free(pub_key);
367
1.82k
    if (priv_key != dh->priv_key)
368
0
        BN_free(priv_key);
369
1.82k
    BN_CTX_free(ctx);
370
1.82k
    return ok;
371
1.82k
}
372
373
int ossl_dh_buf2key(DH *dh, const unsigned char *buf, size_t len)
374
606
{
375
606
    int err_reason = DH_R_BN_ERROR;
376
606
    BIGNUM *pubkey = NULL;
377
606
    const BIGNUM *p;
378
606
    int ret;
379
380
606
    if ((pubkey = BN_bin2bn(buf, len, NULL)) == NULL)
381
0
        goto err;
382
606
    DH_get0_pqg(dh, &p, NULL, NULL);
383
606
    if (p == NULL || BN_num_bytes(p) == 0) {
384
0
        err_reason = DH_R_NO_PARAMETERS_SET;
385
0
        goto err;
386
0
    }
387
    /* Prevent small subgroup attacks per RFC 8446 Section 4.2.8.1 */
388
606
    if (!ossl_dh_check_pub_key_partial(dh, pubkey, &ret)) {
389
5
        err_reason = DH_R_INVALID_PUBKEY;
390
5
        goto err;
391
5
    }
392
601
    if (DH_set0_key(dh, pubkey, NULL) != 1)
393
0
        goto err;
394
601
    return 1;
395
5
err:
396
5
    ERR_raise(ERR_LIB_DH, err_reason);
397
5
    BN_free(pubkey);
398
5
    return 0;
399
601
}
400
401
size_t ossl_dh_key2buf(const DH *dh, unsigned char **pbuf_out, size_t size,
402
                       int alloc)
403
1.19k
{
404
1.19k
    const BIGNUM *pubkey;
405
1.19k
    unsigned char *pbuf = NULL;
406
1.19k
    const BIGNUM *p;
407
1.19k
    int p_size;
408
409
1.19k
    DH_get0_pqg(dh, &p, NULL, NULL);
410
1.19k
    DH_get0_key(dh, &pubkey, NULL);
411
1.19k
    if (p == NULL || pubkey == NULL
412
1.19k
            || (p_size = BN_num_bytes(p)) == 0
413
1.19k
            || BN_num_bytes(pubkey) == 0) {
414
0
        ERR_raise(ERR_LIB_DH, DH_R_INVALID_PUBKEY);
415
0
        return 0;
416
0
    }
417
1.19k
    if (pbuf_out != NULL && (alloc || *pbuf_out != NULL)) {
418
595
        if (!alloc) {
419
595
            if (size >= (size_t)p_size)
420
595
                pbuf = *pbuf_out;
421
595
        } else {
422
0
            pbuf = OPENSSL_malloc(p_size);
423
0
        }
424
425
595
        if (pbuf == NULL) {
426
0
            ERR_raise(ERR_LIB_DH, ERR_R_MALLOC_FAILURE);
427
0
            return 0;
428
0
        }
429
        /*
430
         * As per Section 4.2.8.1 of RFC 8446 left pad public
431
         * key with zeros to the size of p
432
         */
433
595
        if (BN_bn2binpad(pubkey, pbuf, p_size) < 0) {
434
0
            if (alloc)
435
0
                OPENSSL_free(pbuf);
436
0
            ERR_raise(ERR_LIB_DH, DH_R_BN_ERROR);
437
0
            return 0;
438
0
        }
439
595
        *pbuf_out = pbuf;
440
595
    }
441
1.19k
    return p_size;
442
1.19k
}