Coverage Report

Created: 2025-12-31 06:58

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