Coverage Report

Created: 2026-09-12 06:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl40/crypto/dh/dh_key.c
Line
Count
Source
1
/*
2
 * Copyright 1995-2025 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
3.66k
{
42
3.66k
    BN_CTX *ctx = NULL;
43
3.66k
    BN_MONT_CTX *mont = NULL;
44
3.66k
    BIGNUM *z = NULL, *pminus1;
45
3.66k
    int ret = -1;
46
47
3.66k
    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
3.66k
    if (dh->params.q != NULL
53
505
        && 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
3.66k
    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
3.66k
    ctx = BN_CTX_new_ex(dh->libctx);
64
3.66k
    if (ctx == NULL)
65
0
        goto err;
66
3.66k
    BN_CTX_start(ctx);
67
3.66k
    pminus1 = BN_CTX_get(ctx);
68
3.66k
    z = BN_CTX_get(ctx);
69
3.66k
    if (z == NULL)
70
0
        goto err;
71
72
3.66k
    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
3.66k
    if (dh->flags & DH_FLAG_CACHE_MONT_P) {
78
3.66k
        mont = BN_MONT_CTX_set_locked(&dh->method_mont_p,
79
3.66k
            dh->lock, dh->params.p, ctx);
80
3.66k
        BN_set_flags(dh->priv_key, BN_FLG_CONSTTIME);
81
3.66k
        if (!mont)
82
0
            goto err;
83
3.66k
    }
84
85
    /* (Step 1) Z = pub_key^priv_key mod p */
86
3.66k
    if (!dh->meth->bn_mod_exp(dh, z, pub_key, dh->priv_key, dh->params.p, ctx,
87
3.66k
            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
3.66k
    if (BN_copy(pminus1, dh->params.p) == NULL
94
3.66k
        || !BN_sub_word(pminus1, 1)
95
3.66k
        || BN_cmp(z, BN_value_one()) <= 0
96
3.66k
        || 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
3.66k
    ret = BN_bn2binpad(z, key, BN_num_bytes(dh->params.p));
103
3.66k
err:
104
3.66k
    BN_clear(z); /* (Step 2) destroy intermediate values */
105
3.66k
    BN_CTX_end(ctx);
106
3.66k
    BN_CTX_free(ctx);
107
3.66k
    return ret;
108
3.66k
}
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
3.54k
{
116
3.54k
    int ret = 0, i;
117
3.54k
    volatile int 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
3.54k
    ret = dh->meth->compute_key(key, pub_key, dh);
124
3.54k
#endif
125
3.54k
    if (ret <= 0)
126
0
        return ret;
127
128
    /* count leading zero bytes, yet still touch all bytes */
129
814k
    for (i = 0; i < ret; i++) {
130
810k
        mask &= !key[i];
131
810k
        npad += mask;
132
810k
    }
133
134
    /* unpad key */
135
3.54k
    ret -= npad;
136
    /* key-dependent memory access, potentially leaking npad / ret */
137
3.54k
    memmove(key, key + npad, ret);
138
    /* key-dependent memory access, potentially leaking npad / ret */
139
3.54k
    memset(key + ret, 0, npad);
140
141
3.54k
    return ret;
142
3.54k
}
143
144
int DH_compute_key_padded(unsigned char *key, const BIGNUM *pub_key, DH *dh)
145
123
{
146
123
    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
123
    rv = dh->meth->compute_key(key, pub_key, dh);
153
123
#endif
154
123
    if (rv <= 0)
155
0
        return rv;
156
123
    pad = BN_num_bytes(dh->params.p) - rv;
157
    /* pad is constant (zero) unless compute_key is external */
158
123
    if (pad > 0) {
159
0
        memmove(key + pad, key, rv);
160
0
        memset(key, 0, pad);
161
0
    }
162
123
    return rv + pad;
163
123
}
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
7.42k
{
181
7.42k
    return &dh_ossl;
182
7.42k
}
183
184
const DH_METHOD *DH_get_default_method(void)
185
273k
{
186
273k
    return default_DH_method;
187
273k
}
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
7.84k
{
193
#ifdef S390X_MOD_EXP
194
    return s390x_mod_exp(r, a, p, m, ctx, m_ctx);
195
#else
196
7.84k
    return BN_mod_exp_mont(r, a, p, m, ctx, m_ctx);
197
7.84k
#endif
198
7.84k
}
199
200
static int dh_init(DH *dh)
201
273k
{
202
273k
    dh->flags |= DH_FLAG_CACHE_MONT_P;
203
273k
    dh->dirty_cnt++;
204
273k
    return 1;
205
273k
}
206
207
static int dh_finish(DH *dh)
208
273k
{
209
273k
    BN_MONT_CTX_free(dh->method_mont_p);
210
273k
    dh->method_mont_p = NULL;
211
273k
    return 1;
212
273k
}
213
214
#ifndef FIPS_MODULE
215
void DH_set_default_method(const DH_METHOD *meth)
216
0
{
217
0
    default_DH_method = meth;
218
0
}
219
#endif /* FIPS_MODULE */
220
221
int DH_generate_key(DH *dh)
222
4.22k
{
223
#ifdef FIPS_MODULE
224
    return generate_key(dh);
225
#else
226
4.22k
    return dh->meth->generate_key(dh);
227
4.22k
#endif
228
4.22k
}
229
230
int ossl_dh_generate_public_key(BN_CTX *ctx, const DH *dh,
231
    const BIGNUM *priv_key, BIGNUM *pub_key)
232
4.19k
{
233
4.19k
    int ret = 0;
234
4.19k
    BIGNUM *prk = BN_new();
235
4.19k
    BN_MONT_CTX *mont = NULL;
236
237
4.19k
    if (prk == NULL)
238
0
        return 0;
239
240
4.19k
    if (dh->flags & DH_FLAG_CACHE_MONT_P) {
241
        /*
242
         * We take the input DH as const, but we lie, because in some cases we
243
         * want to get a hold of its Montgomery context.
244
         *
245
         * We cast to remove the const qualifier in this case, it should be
246
         * fine...
247
         */
248
4.19k
        BN_MONT_CTX **pmont = (BN_MONT_CTX **)&dh->method_mont_p;
249
250
4.19k
        mont = BN_MONT_CTX_set_locked(pmont, dh->lock, dh->params.p, ctx);
251
4.19k
        if (mont == NULL)
252
15
            goto err;
253
4.19k
    }
254
4.17k
    BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME);
255
256
    /* pub_key = g^priv_key mod p */
257
4.17k
    if (!dh->meth->bn_mod_exp(dh, pub_key, dh->params.g, prk, dh->params.p,
258
4.17k
            ctx, mont))
259
0
        goto err;
260
4.17k
    ret = 1;
261
4.19k
err:
262
4.19k
    BN_clear_free(prk);
263
4.19k
    return ret;
264
4.17k
}
265
266
static int generate_key(DH *dh)
267
4.22k
{
268
4.22k
    int ok = 0;
269
4.22k
    int generate_new_key = 0;
270
4.22k
#ifndef FIPS_MODULE
271
4.22k
    int l;
272
4.22k
#endif
273
4.22k
    BN_CTX *ctx = NULL;
274
4.22k
    BIGNUM *pub_key = NULL, *priv_key = NULL;
275
276
4.22k
    if (BN_num_bits(dh->params.p) > OPENSSL_DH_MAX_MODULUS_BITS) {
277
0
        ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_LARGE);
278
0
        return 0;
279
0
    }
280
281
4.22k
    if (dh->params.q != NULL
282
1.06k
        && BN_num_bits(dh->params.q) > OPENSSL_DH_MAX_MODULUS_BITS) {
283
0
        ERR_raise(ERR_LIB_DH, DH_R_Q_TOO_LARGE);
284
0
        return 0;
285
0
    }
286
287
4.22k
    if (BN_num_bits(dh->params.p) < DH_MIN_MODULUS_BITS) {
288
34
        ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_SMALL);
289
34
        return 0;
290
34
    }
291
292
4.19k
    ctx = BN_CTX_new_ex(dh->libctx);
293
4.19k
    if (ctx == NULL)
294
0
        goto err;
295
296
4.19k
    if (dh->priv_key == NULL) {
297
4.06k
        priv_key = BN_secure_new();
298
4.06k
        if (priv_key == NULL)
299
0
            goto err;
300
4.06k
        generate_new_key = 1;
301
4.06k
    } else {
302
126
        priv_key = dh->priv_key;
303
126
    }
304
305
4.19k
    if (dh->pub_key == NULL) {
306
4.19k
        pub_key = BN_new();
307
4.19k
        if (pub_key == NULL)
308
0
            goto err;
309
4.19k
    } else {
310
0
        pub_key = dh->pub_key;
311
0
    }
312
4.19k
    if (generate_new_key) {
313
        /* Is it an approved safe prime ?*/
314
4.06k
        if (DH_get_nid(dh) != NID_undef) {
315
909
            int max_strength = ossl_ifc_ffc_compute_security_bits(BN_num_bits(dh->params.p));
316
317
909
            if (dh->params.q == NULL
318
909
                || dh->length > BN_num_bits(dh->params.q))
319
0
                goto err;
320
            /* dh->length = maximum bit length of generated private key */
321
909
            if (!ossl_ffc_generate_private_key(ctx, &dh->params, dh->length,
322
909
                    max_strength, priv_key))
323
0
                goto err;
324
3.15k
        } else {
325
#ifdef FIPS_MODULE
326
            if (dh->params.q == NULL)
327
                goto err;
328
#else
329
3.15k
            if (dh->params.q == NULL) {
330
                /* secret exponent length, must satisfy 2^l < (p-1)/2 */
331
3.15k
                l = BN_num_bits(dh->params.p);
332
3.15k
                if (dh->length >= l)
333
0
                    goto err;
334
3.15k
                l -= 2;
335
3.15k
                if (dh->length != 0 && dh->length < l)
336
0
                    l = dh->length;
337
3.15k
                if (!BN_priv_rand_ex(priv_key, l, BN_RAND_TOP_ONE,
338
3.15k
                        BN_RAND_BOTTOM_ANY, 0, ctx))
339
0
                    goto err;
340
                /*
341
                 * We handle just one known case where g is a quadratic non-residue:
342
                 * for g = 2: p % 8 == 3
343
                 */
344
3.15k
                if (BN_is_word(dh->params.g, DH_GENERATOR_2)
345
263
                    && !BN_is_bit_set(dh->params.p, 2)) {
346
                    /* clear bit 0, since it won't be a secret anyway */
347
218
                    if (!BN_clear_bit(priv_key, 0))
348
0
                        goto err;
349
218
                }
350
3.15k
            } else
351
0
#endif
352
0
            {
353
                /* Do a partial check for invalid p, q, g */
354
0
                if (!ossl_ffc_params_simple_validate(dh->libctx, &dh->params,
355
0
                        FFC_PARAM_TYPE_DH, NULL))
356
0
                    goto err;
357
                /*
358
                 * For FFC FIPS 186-4 keygen
359
                 * security strength s = 112,
360
                 * Max Private key size N = len(q)
361
                 */
362
0
                if (!ossl_ffc_generate_private_key(ctx, &dh->params,
363
0
                        BN_num_bits(dh->params.q),
364
0
                        MIN_STRENGTH,
365
0
                        priv_key))
366
0
                    goto err;
367
0
            }
368
3.15k
        }
369
4.06k
    }
370
371
4.19k
    if (!ossl_dh_generate_public_key(ctx, dh, priv_key, pub_key))
372
15
        goto err;
373
374
4.17k
    dh->pub_key = pub_key;
375
4.17k
    dh->priv_key = priv_key;
376
4.17k
    dh->dirty_cnt++;
377
4.17k
    ok = 1;
378
4.19k
err:
379
4.19k
    if (ok != 1)
380
4.19k
        ERR_raise(ERR_LIB_DH, ERR_R_BN_LIB);
381
382
4.19k
    if (pub_key != dh->pub_key)
383
15
        BN_free(pub_key);
384
4.19k
    if (priv_key != dh->priv_key)
385
0
        BN_free(priv_key);
386
4.19k
    BN_CTX_free(ctx);
387
4.19k
    return ok;
388
4.17k
}
389
390
int ossl_dh_buf2key(DH *dh, const unsigned char *buf, size_t len)
391
505
{
392
505
    int err_reason = DH_R_BN_ERROR;
393
505
    BIGNUM *pubkey = NULL;
394
505
    const BIGNUM *p;
395
505
    int ret;
396
397
505
    if (len > INT_MAX || (pubkey = BN_bin2bn(buf, (int)len, NULL)) == NULL)
398
0
        goto err;
399
505
    DH_get0_pqg(dh, &p, NULL, NULL);
400
505
    if (p == NULL || BN_num_bytes(p) == 0) {
401
0
        err_reason = DH_R_NO_PARAMETERS_SET;
402
0
        goto err;
403
0
    }
404
    /* Prevent small subgroup attacks per RFC 8446 Section 4.2.8.1 */
405
505
    if (!ossl_dh_check_pub_key_partial(dh, pubkey, &ret)) {
406
21
        err_reason = DH_R_INVALID_PUBKEY;
407
21
        goto err;
408
21
    }
409
484
    if (DH_set0_key(dh, pubkey, NULL) != 1)
410
0
        goto err;
411
484
    return 1;
412
21
err:
413
21
    ERR_raise(ERR_LIB_DH, err_reason);
414
21
    BN_free(pubkey);
415
21
    return 0;
416
484
}
417
418
size_t ossl_dh_key2buf(const DH *dh, unsigned char **pbuf_out, size_t size,
419
    int alloc)
420
7.12k
{
421
7.12k
    const BIGNUM *pubkey;
422
7.12k
    unsigned char *pbuf = NULL;
423
7.12k
    const BIGNUM *p;
424
7.12k
    int p_size;
425
426
7.12k
    DH_get0_pqg(dh, &p, NULL, NULL);
427
7.12k
    DH_get0_key(dh, &pubkey, NULL);
428
7.12k
    if (p == NULL || pubkey == NULL
429
7.12k
        || (p_size = BN_num_bytes(p)) == 0
430
7.12k
        || BN_num_bytes(pubkey) == 0) {
431
0
        ERR_raise(ERR_LIB_DH, DH_R_INVALID_PUBKEY);
432
0
        return 0;
433
0
    }
434
7.12k
    if (pbuf_out != NULL && (alloc || *pbuf_out != NULL)) {
435
3.56k
        if (!alloc) {
436
3.56k
            if (size >= (size_t)p_size)
437
3.56k
                pbuf = *pbuf_out;
438
3.56k
            if (pbuf == NULL)
439
3.56k
                ERR_raise(ERR_LIB_DH, DH_R_INVALID_SIZE);
440
3.56k
        } else {
441
0
            pbuf = OPENSSL_malloc(p_size);
442
0
        }
443
444
        /* Errors raised above */
445
3.56k
        if (pbuf == NULL)
446
0
            return 0;
447
        /*
448
         * As per Section 4.2.8.1 of RFC 8446 left pad public
449
         * key with zeros to the size of p
450
         */
451
3.56k
        if (BN_bn2binpad(pubkey, pbuf, p_size) < 0) {
452
0
            if (alloc)
453
0
                OPENSSL_free(pbuf);
454
0
            ERR_raise(ERR_LIB_DH, DH_R_BN_ERROR);
455
0
            return 0;
456
0
        }
457
3.56k
        *pbuf_out = pbuf;
458
3.56k
    }
459
7.12k
    return p_size;
460
7.12k
}