Coverage Report

Created: 2024-11-21 07:03

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