Coverage Report

Created: 2026-10-28 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl36/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
5.38k
{
42
5.38k
    BN_CTX *ctx = NULL;
43
5.38k
    BN_MONT_CTX *mont = NULL;
44
5.38k
    BIGNUM *z = NULL, *pminus1;
45
5.38k
    int ret = -1;
46
47
5.38k
    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
5.38k
    if (dh->params.q != NULL
53
1.33k
        && 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
5.38k
    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
5.38k
    ctx = BN_CTX_new_ex(dh->libctx);
64
5.38k
    if (ctx == NULL)
65
0
        goto err;
66
5.38k
    BN_CTX_start(ctx);
67
5.38k
    pminus1 = BN_CTX_get(ctx);
68
5.38k
    z = BN_CTX_get(ctx);
69
5.38k
    if (z == NULL)
70
0
        goto err;
71
72
5.38k
    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
5.38k
    if (dh->flags & DH_FLAG_CACHE_MONT_P) {
78
5.38k
        mont = BN_MONT_CTX_set_locked(&dh->method_mont_p,
79
5.38k
            dh->lock, dh->params.p, ctx);
80
5.38k
        BN_set_flags(dh->priv_key, BN_FLG_CONSTTIME);
81
5.38k
        if (!mont)
82
0
            goto err;
83
5.38k
    }
84
85
    /* (Step 1) Z = pub_key^priv_key mod p */
86
5.38k
    if (!dh->meth->bn_mod_exp(dh, z, pub_key, dh->priv_key, dh->params.p, ctx,
87
5.38k
            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
5.38k
    if (BN_copy(pminus1, dh->params.p) == NULL
94
5.38k
        || !BN_sub_word(pminus1, 1)
95
5.38k
        || BN_cmp(z, BN_value_one()) <= 0
96
5.38k
        || 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
5.38k
    ret = BN_bn2binpad(z, key, BN_num_bytes(dh->params.p));
103
5.38k
err:
104
5.38k
    BN_clear(z); /* (Step 2) destroy intermediate values */
105
5.38k
    BN_CTX_end(ctx);
106
5.38k
    BN_CTX_free(ctx);
107
5.38k
    return ret;
108
5.38k
}
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
5.25k
{
116
5.25k
    int ret = 0, i;
117
5.25k
    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
5.25k
    ret = dh->meth->compute_key(key, pub_key, dh);
124
5.25k
#endif
125
5.25k
    if (ret <= 0)
126
0
        return ret;
127
128
    /* count leading zero bytes, yet still touch all bytes */
129
1.26M
    for (i = 0; i < ret; i++) {
130
1.26M
        mask &= !key[i];
131
1.26M
        npad += mask;
132
1.26M
    }
133
134
    /* unpad key */
135
5.25k
    ret -= npad;
136
    /* key-dependent memory access, potentially leaking npad / ret */
137
5.25k
    memmove(key, key + npad, ret);
138
    /* key-dependent memory access, potentially leaking npad / ret */
139
5.25k
    memset(key + ret, 0, npad);
140
141
5.25k
    return ret;
142
5.25k
}
143
144
int DH_compute_key_padded(unsigned char *key, const BIGNUM *pub_key, DH *dh)
145
132
{
146
132
    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
132
    rv = dh->meth->compute_key(key, pub_key, dh);
153
132
#endif
154
132
    if (rv <= 0)
155
0
        return rv;
156
132
    pad = BN_num_bytes(dh->params.p) - rv;
157
    /* pad is constant (zero) unless compute_key is external */
158
132
    if (pad > 0) {
159
0
        memmove(key + pad, key, rv);
160
0
        memset(key, 0, pad);
161
0
    }
162
132
    return rv + pad;
163
132
}
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
9.07k
{
181
9.07k
    return &dh_ossl;
182
9.07k
}
183
184
const DH_METHOD *DH_get_default_method(void)
185
354k
{
186
354k
    return default_DH_method;
187
354k
}
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
11.9k
{
193
#ifdef S390X_MOD_EXP
194
    return s390x_mod_exp(r, a, p, m, ctx, m_ctx);
195
#else
196
11.9k
    return BN_mod_exp_mont(r, a, p, m, ctx, m_ctx);
197
11.9k
#endif
198
11.9k
}
199
200
static int dh_init(DH *dh)
201
354k
{
202
354k
    dh->flags |= DH_FLAG_CACHE_MONT_P;
203
354k
    dh->dirty_cnt++;
204
354k
    return 1;
205
354k
}
206
207
static int dh_finish(DH *dh)
208
354k
{
209
354k
    BN_MONT_CTX_free(dh->method_mont_p);
210
354k
    dh->method_mont_p = NULL;
211
354k
    return 1;
212
354k
}
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
6.58k
{
223
#ifdef FIPS_MODULE
224
    return generate_key(dh);
225
#else
226
6.58k
    return dh->meth->generate_key(dh);
227
6.58k
#endif
228
6.58k
}
229
230
int ossl_dh_generate_public_key(BN_CTX *ctx, const DH *dh,
231
    const BIGNUM *priv_key, BIGNUM *pub_key)
232
6.53k
{
233
6.53k
    int ret = 0;
234
6.53k
    BIGNUM *prk = BN_new();
235
6.53k
    BN_MONT_CTX *mont = NULL;
236
237
6.53k
    if (prk == NULL)
238
0
        return 0;
239
240
6.53k
    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
6.53k
        BN_MONT_CTX **pmont = (BN_MONT_CTX **)&dh->method_mont_p;
249
250
6.53k
        mont = BN_MONT_CTX_set_locked(pmont, dh->lock, dh->params.p, ctx);
251
6.53k
        if (mont == NULL)
252
20
            goto err;
253
6.53k
    }
254
6.51k
    BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME);
255
256
    /* pub_key = g^priv_key mod p */
257
6.51k
    if (!dh->meth->bn_mod_exp(dh, pub_key, dh->params.g, prk, dh->params.p,
258
6.51k
            ctx, mont))
259
0
        goto err;
260
6.51k
    ret = 1;
261
6.53k
err:
262
6.53k
    BN_clear_free(prk);
263
6.53k
    return ret;
264
6.51k
}
265
266
static int generate_key(DH *dh)
267
6.58k
{
268
6.58k
    int ok = 0;
269
6.58k
    int generate_new_key = 0;
270
6.58k
#ifndef FIPS_MODULE
271
6.58k
    int l;
272
6.58k
#endif
273
6.58k
    BN_CTX *ctx = NULL;
274
6.58k
    BIGNUM *pub_key = NULL, *priv_key = NULL;
275
276
6.58k
    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
6.58k
    if (dh->params.q != NULL
282
2.53k
        && 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
6.58k
    if (BN_num_bits(dh->params.p) < DH_MIN_MODULUS_BITS) {
288
50
        ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_SMALL);
289
50
        return 0;
290
50
    }
291
292
6.53k
    ctx = BN_CTX_new_ex(dh->libctx);
293
6.53k
    if (ctx == NULL)
294
0
        goto err;
295
296
6.53k
    if (dh->priv_key == NULL) {
297
6.39k
        priv_key = BN_secure_new();
298
6.39k
        if (priv_key == NULL)
299
0
            goto err;
300
6.39k
        generate_new_key = 1;
301
6.39k
    } else {
302
146
        priv_key = dh->priv_key;
303
146
    }
304
305
6.53k
    if (dh->pub_key == NULL) {
306
6.53k
        pub_key = BN_new();
307
6.53k
        if (pub_key == NULL)
308
0
            goto err;
309
6.53k
    } else {
310
0
        pub_key = dh->pub_key;
311
0
    }
312
6.53k
    if (generate_new_key) {
313
        /* Is it an approved safe prime ?*/
314
6.39k
        if (DH_get_nid(dh) != NID_undef) {
315
2.34k
            int max_strength = ossl_ifc_ffc_compute_security_bits(BN_num_bits(dh->params.p));
316
317
2.34k
            if (dh->params.q == NULL
318
2.34k
                || dh->length > BN_num_bits(dh->params.q))
319
0
                goto err;
320
            /* dh->length = maximum bit length of generated private key */
321
2.34k
            if (!ossl_ffc_generate_private_key(ctx, &dh->params, dh->length,
322
2.34k
                    max_strength, priv_key))
323
0
                goto err;
324
4.05k
        } else {
325
#ifdef FIPS_MODULE
326
            if (dh->params.q == NULL)
327
                goto err;
328
#else
329
4.05k
            if (dh->params.q == NULL) {
330
                /* secret exponent length, must satisfy 2^l < (p-1)/2 */
331
4.05k
                l = BN_num_bits(dh->params.p);
332
4.05k
                if (dh->length >= l)
333
0
                    goto err;
334
4.05k
                l -= 2;
335
4.05k
                if (dh->length != 0 && dh->length < l)
336
0
                    l = dh->length;
337
4.05k
                if (!BN_priv_rand_ex(priv_key, l, BN_RAND_TOP_ONE,
338
4.05k
                        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
4.05k
                if (BN_is_word(dh->params.g, DH_GENERATOR_2)
345
347
                    && !BN_is_bit_set(dh->params.p, 2)) {
346
                    /* clear bit 0, since it won't be a secret anyway */
347
238
                    if (!BN_clear_bit(priv_key, 0))
348
0
                        goto err;
349
238
                }
350
4.05k
            } 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
4.05k
        }
369
6.39k
    }
370
371
6.53k
    if (!ossl_dh_generate_public_key(ctx, dh, priv_key, pub_key))
372
20
        goto err;
373
374
6.51k
    dh->pub_key = pub_key;
375
6.51k
    dh->priv_key = priv_key;
376
6.51k
    dh->dirty_cnt++;
377
6.51k
    ok = 1;
378
6.53k
err:
379
6.53k
    if (ok != 1)
380
6.53k
        ERR_raise(ERR_LIB_DH, ERR_R_BN_LIB);
381
382
6.53k
    if (pub_key != dh->pub_key)
383
20
        BN_free(pub_key);
384
6.53k
    if (priv_key != dh->priv_key)
385
0
        BN_free(priv_key);
386
6.53k
    BN_CTX_free(ctx);
387
6.53k
    return ok;
388
6.51k
}
389
390
int ossl_dh_buf2key(DH *dh, const unsigned char *buf, size_t len)
391
1.40k
{
392
1.40k
    int err_reason = DH_R_BN_ERROR;
393
1.40k
    BIGNUM *pubkey = NULL;
394
1.40k
    const BIGNUM *p;
395
1.40k
    int ret;
396
397
1.40k
    if (len > INT_MAX || (pubkey = BN_bin2bn(buf, (int)len, NULL)) == NULL)
398
0
        goto err;
399
1.40k
    DH_get0_pqg(dh, &p, NULL, NULL);
400
1.40k
    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
1.40k
    if (!ossl_dh_check_pub_key_partial(dh, pubkey, &ret)) {
406
39
        err_reason = DH_R_INVALID_PUBKEY;
407
39
        goto err;
408
39
    }
409
1.36k
    if (DH_set0_key(dh, pubkey, NULL) != 1)
410
0
        goto err;
411
1.36k
    return 1;
412
39
err:
413
39
    ERR_raise(ERR_LIB_DH, err_reason);
414
39
    BN_free(pubkey);
415
39
    return 0;
416
1.36k
}
417
418
size_t ossl_dh_key2buf(const DH *dh, unsigned char **pbuf_out, size_t size,
419
    int alloc)
420
9.04k
{
421
9.04k
    const BIGNUM *pubkey;
422
9.04k
    unsigned char *pbuf = NULL;
423
9.04k
    const BIGNUM *p;
424
9.04k
    int p_size;
425
426
9.04k
    DH_get0_pqg(dh, &p, NULL, NULL);
427
9.04k
    DH_get0_key(dh, &pubkey, NULL);
428
9.04k
    if (p == NULL || pubkey == NULL
429
9.04k
        || (p_size = BN_num_bytes(p)) == 0
430
9.04k
        || BN_num_bytes(pubkey) == 0) {
431
0
        ERR_raise(ERR_LIB_DH, DH_R_INVALID_PUBKEY);
432
0
        return 0;
433
0
    }
434
9.04k
    if (pbuf_out != NULL && (alloc || *pbuf_out != NULL)) {
435
4.52k
        if (!alloc) {
436
4.52k
            if (size >= (size_t)p_size)
437
4.52k
                pbuf = *pbuf_out;
438
4.52k
            if (pbuf == NULL)
439
4.52k
                ERR_raise(ERR_LIB_DH, DH_R_INVALID_SIZE);
440
4.52k
        } else {
441
0
            pbuf = OPENSSL_malloc(p_size);
442
0
        }
443
444
        /* Errors raised above */
445
4.52k
        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
4.52k
        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
4.52k
        *pbuf_out = pbuf;
458
4.52k
    }
459
9.04k
    return p_size;
460
9.04k
}