Coverage Report

Created: 2025-08-28 07:07

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