1/*
2 * Copyright 2018-2024 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{-
10use OpenSSL::paramnames qw(produce_param_decoder);
11-}
12
13/*
14 * HMAC low level APIs are deprecated for public use, but still ok for internal
15 * use.
16 */
17#include "internal/deprecated.h"
18
19#include <stdlib.h>
20#include <stdarg.h>
21#include <string.h>
22#include <openssl/hmac.h>
23#include <openssl/evp.h>
24#include <openssl/kdf.h>
25#include <openssl/core_names.h>
26#include <openssl/proverr.h>
27#include "internal/cryptlib.h"
28#include "internal/numbers.h"
29#include "crypto/evp.h"
30#include "prov/provider_ctx.h"
31#include "prov/providercommon.h"
32#include "prov/implementations.h"
33#include "prov/provider_util.h"
34#include "prov/securitycheck.h"
35
36/* Constants specified in SP800-132 */
37#define KDF_PBKDF2_MIN_KEY_LEN_BITS 112
38#define KDF_PBKDF2_MAX_KEY_LEN_DIGEST_RATIO 0xFFFFFFFF
39#define KDF_PBKDF2_MIN_ITERATIONS 1000
40#define KDF_PBKDF2_MIN_SALT_LEN   (128 / 8)
41
42static OSSL_FUNC_kdf_newctx_fn kdf_pbkdf2_new;
43static OSSL_FUNC_kdf_dupctx_fn kdf_pbkdf2_dup;
44static OSSL_FUNC_kdf_freectx_fn kdf_pbkdf2_free;
45static OSSL_FUNC_kdf_reset_fn kdf_pbkdf2_reset;
46static OSSL_FUNC_kdf_derive_fn kdf_pbkdf2_derive;
47static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_pbkdf2_settable_ctx_params;
48static OSSL_FUNC_kdf_set_ctx_params_fn kdf_pbkdf2_set_ctx_params;
49static OSSL_FUNC_kdf_gettable_ctx_params_fn kdf_pbkdf2_gettable_ctx_params;
50static OSSL_FUNC_kdf_get_ctx_params_fn kdf_pbkdf2_get_ctx_params;
51
52typedef struct {
53    void *provctx;
54    unsigned char *pass;
55    size_t pass_len;
56    unsigned char *salt;
57    size_t salt_len;
58    uint64_t iter;
59    PROV_DIGEST digest;
60    int lower_bound_checks;
61    OSSL_FIPS_IND_DECLARE
62} KDF_PBKDF2;
63
64static int pbkdf2_derive(KDF_PBKDF2 *ctx, const char *pass, size_t passlen,
65                         const unsigned char *salt, int saltlen, uint64_t iter,
66                         const EVP_MD *digest, unsigned char *key,
67                         size_t keylen, int lower_bound_checks);
68
69static void kdf_pbkdf2_init(KDF_PBKDF2 *ctx);
70
71static void *kdf_pbkdf2_new_no_init(void *provctx)
72{
73    KDF_PBKDF2 *ctx;
74
75    if (!ossl_prov_is_running())
76        return NULL;
77
78    ctx = OPENSSL_zalloc(sizeof(*ctx));
79    if (ctx == NULL)
80        return NULL;
81    ctx->provctx = provctx;
82    OSSL_FIPS_IND_INIT(ctx);
83    return ctx;
84}
85
86static void *kdf_pbkdf2_new(void *provctx)
87{
88    KDF_PBKDF2 *ctx = kdf_pbkdf2_new_no_init(provctx);
89
90    if (ctx != NULL)
91        kdf_pbkdf2_init(ctx);
92    return ctx;
93}
94
95static void kdf_pbkdf2_cleanup(KDF_PBKDF2 *ctx)
96{
97    ossl_prov_digest_reset(&ctx->digest);
98#ifdef OPENSSL_PEDANTIC_ZEROIZATION
99    OPENSSL_clear_free(ctx->salt, ctx->salt_len);
100#else
101    OPENSSL_free(ctx->salt);
102#endif
103    OPENSSL_clear_free(ctx->pass, ctx->pass_len);
104    memset(ctx, 0, sizeof(*ctx));
105}
106
107static void kdf_pbkdf2_free(void *vctx)
108{
109    KDF_PBKDF2 *ctx = (KDF_PBKDF2 *)vctx;
110
111    if (ctx != NULL) {
112        kdf_pbkdf2_cleanup(ctx);
113        OPENSSL_free(ctx);
114    }
115}
116
117static void kdf_pbkdf2_reset(void *vctx)
118{
119    KDF_PBKDF2 *ctx = (KDF_PBKDF2 *)vctx;
120    void *provctx = ctx->provctx;
121
122    kdf_pbkdf2_cleanup(ctx);
123    ctx->provctx = provctx;
124    kdf_pbkdf2_init(ctx);
125}
126
127static void *kdf_pbkdf2_dup(void *vctx)
128{
129    const KDF_PBKDF2 *src = (const KDF_PBKDF2 *)vctx;
130    KDF_PBKDF2 *dest;
131
132    /* We need a new PBKDF2 object but uninitialised since we're filling it */
133    dest = kdf_pbkdf2_new_no_init(src->provctx);
134    if (dest != NULL) {
135        if (!ossl_prov_memdup(src->salt, src->salt_len,
136                              &dest->salt, &dest->salt_len)
137                || !ossl_prov_memdup(src->pass, src->pass_len,
138                                     &dest->pass, &dest->pass_len)
139                || !ossl_prov_digest_copy(&dest->digest, &src->digest))
140            goto err;
141        dest->iter = src->iter;
142        dest->lower_bound_checks = src->lower_bound_checks;
143        OSSL_FIPS_IND_COPY(dest, src)
144    }
145    return dest;
146
147 err:
148    kdf_pbkdf2_free(dest);
149    return NULL;
150}
151
152static void kdf_pbkdf2_init(KDF_PBKDF2 *ctx)
153{
154    OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
155    OSSL_LIB_CTX *provctx = PROV_LIBCTX_OF(ctx->provctx);
156
157    params[0] = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
158                                                 SN_sha1, 0);
159    if (!ossl_prov_digest_load_from_params(&ctx->digest, params, provctx))
160        /* This is an error, but there is no way to indicate such directly */
161        ossl_prov_digest_reset(&ctx->digest);
162    ctx->iter = PKCS5_DEFAULT_ITER;
163#ifdef FIPS_MODULE
164    ctx->lower_bound_checks = 1;
165#else
166    ctx->lower_bound_checks = 0;
167#endif
168}
169
170static int pbkdf2_set_membuf(unsigned char **buffer, size_t *buflen,
171                             const OSSL_PARAM *p)
172{
173    OPENSSL_clear_free(*buffer, *buflen);
174    *buffer = NULL;
175    *buflen = 0;
176
177    if (p->data_size == 0) {
178        if ((*buffer = OPENSSL_malloc(1)) == NULL)
179            return 0;
180    } else if (p->data != NULL) {
181        if (!OSSL_PARAM_get_octet_string(p, (void **)buffer, 0, buflen))
182            return 0;
183    }
184    return 1;
185}
186
187static int pbkdf2_lower_bound_check_passed(int saltlen, uint64_t iter,
188                                           size_t keylen, int *error,
189                                           const char **desc)
190{
191    if ((keylen * 8) < KDF_PBKDF2_MIN_KEY_LEN_BITS) {
192        *error = PROV_R_KEY_SIZE_TOO_SMALL;
193        if (desc != NULL)
194            *desc = "Key size";
195        return 0;
196    }
197    if (saltlen < KDF_PBKDF2_MIN_SALT_LEN) {
198        *error = PROV_R_INVALID_SALT_LENGTH;
199        if (desc != NULL)
200            *desc = "Salt size";
201        return 0;
202    }
203    if (iter < KDF_PBKDF2_MIN_ITERATIONS) {
204        *error = PROV_R_INVALID_ITERATION_COUNT;
205        if (desc != NULL)
206            *desc = "Iteration count";
207        return 0;
208    }
209
210    return 1;
211}
212
213#ifdef FIPS_MODULE
214static int fips_lower_bound_check_passed(KDF_PBKDF2 *ctx, int saltlen,
215                                         uint64_t iter, size_t keylen)
216{
217    OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
218    int error = 0;
219    const char *desc = NULL;
220    int approved = pbkdf2_lower_bound_check_passed(saltlen, iter, keylen,
221                                                   &error, &desc);
222
223    if (!approved) {
224        if (!OSSL_FIPS_IND_ON_UNAPPROVED(ctx, OSSL_FIPS_IND_SETTABLE0, libctx,
225                                         "PBKDF2", desc,
226                                         ossl_fips_config_pbkdf2_lower_bound_check)) {
227            ERR_raise(ERR_LIB_PROV, error);
228            return 0;
229        }
230    }
231    return 1;
232}
233#endif
234
235static int lower_bound_check_passed(KDF_PBKDF2 *ctx, int saltlen, uint64_t iter,
236                                    size_t keylen, int lower_bound_checks)
237{
238#ifdef FIPS_MODULE
239    if (!fips_lower_bound_check_passed(ctx, saltlen, iter, keylen))
240        return 0;
241#else
242    if (lower_bound_checks) {
243        int error = 0;
244        int passed = pbkdf2_lower_bound_check_passed(saltlen, iter, keylen,
245                                                     &error, NULL);
246
247        if (!passed) {
248            ERR_raise(ERR_LIB_PROV, error);
249            return 0;
250        }
251    } else if (iter < 1) {
252        ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_ITERATION_COUNT);
253        return 0;
254    }
255#endif
256
257    return 1;
258}
259
260static int kdf_pbkdf2_derive(void *vctx, unsigned char *key, size_t keylen,
261                             const OSSL_PARAM params[])
262{
263    KDF_PBKDF2 *ctx = (KDF_PBKDF2 *)vctx;
264    const EVP_MD *md;
265
266    if (!ossl_prov_is_running() || !kdf_pbkdf2_set_ctx_params(ctx, params))
267        return 0;
268
269    if (ctx->pass == NULL) {
270        ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_PASS);
271        return 0;
272    }
273
274    if (ctx->salt == NULL) {
275        ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SALT);
276        return 0;
277    }
278
279    md = ossl_prov_digest_md(&ctx->digest);
280    return pbkdf2_derive(ctx, (char *)ctx->pass, ctx->pass_len,
281                         ctx->salt, (int)ctx->salt_len, ctx->iter,
282                         md, key, keylen, ctx->lower_bound_checks);
283}
284
285{- produce_param_decoder('pbkdf2_set_ctx_params',
286                         (['KDF_PARAM_PROPERTIES',  'propq',    'utf8_string'],
287                          ['ALG_PARAM_ENGINE',      'engine',   'utf8_string', 'hidden'],
288                          ['KDF_PARAM_DIGEST',      'digest',   'utf8_string'],
289                          ['KDF_PARAM_PASSWORD',    'pw',       'octet_string'],
290                          ['KDF_PARAM_SALT',        'salt',     'octet_string'],
291                          ['KDF_PARAM_ITER',        'iter',     'uint64'],
292                          ['KDF_PARAM_PKCS5',       'pkcs5',    'int'],
293                         )); -}
294
295static int kdf_pbkdf2_set_ctx_params(void *vctx, const OSSL_PARAM params[])
296{
297    struct pbkdf2_set_ctx_params_st p;
298    KDF_PBKDF2 *ctx = vctx;
299    OSSL_LIB_CTX *provctx;
300    int pkcs5;
301    uint64_t iter;
302    const EVP_MD *md;
303
304    if (ctx == NULL || !pbkdf2_set_ctx_params_decoder(params, &p))
305        return 0;
306
307    provctx = PROV_LIBCTX_OF(ctx->provctx);
308
309    if (p.digest != NULL) {
310        if (!ossl_prov_digest_load(&ctx->digest, p.digest,
311                                   p.propq, p.engine, provctx))
312            return 0;
313        md = ossl_prov_digest_md(&ctx->digest);
314        if (EVP_MD_xof(md)) {
315            ERR_raise(ERR_LIB_PROV, PROV_R_XOF_DIGESTS_NOT_ALLOWED);
316            return 0;
317        }
318    }
319
320    if (p.pkcs5 != NULL) {
321        if (!OSSL_PARAM_get_int(p.pkcs5, &pkcs5))
322            return 0;
323        ctx->lower_bound_checks = pkcs5 == 0;
324#ifdef FIPS_MODULE
325        ossl_FIPS_IND_set_settable(OSSL_FIPS_IND_GET(ctx),
326                                   OSSL_FIPS_IND_SETTABLE0,
327                                   ctx->lower_bound_checks);
328#endif
329    }
330
331    if (p.pw != NULL && !pbkdf2_set_membuf(&ctx->pass, &ctx->pass_len, p.pw))
332            return 0;
333
334    if (p.salt != NULL) {
335        if (!lower_bound_check_passed(ctx, (int)p.salt->data_size, UINT64_MAX, SIZE_MAX,
336                                      ctx->lower_bound_checks))
337            return 0;
338        if (!pbkdf2_set_membuf(&ctx->salt, &ctx->salt_len, p.salt))
339            return 0;
340    }
341
342    if (p.iter != NULL) {
343        if (!OSSL_PARAM_get_uint64(p.iter, &iter))
344            return 0;
345        if (!lower_bound_check_passed(ctx, INT_MAX, iter, SIZE_MAX,
346                                      ctx->lower_bound_checks))
347            return 0;
348        ctx->iter = iter;
349    }
350    return 1;
351}
352
353static const OSSL_PARAM *kdf_pbkdf2_settable_ctx_params(ossl_unused void *ctx,
354                                                        ossl_unused void *p_ctx)
355{
356    return pbkdf2_set_ctx_params_list;
357}
358
359{- produce_param_decoder('pbkdf2_get_ctx_params',
360                         (['KDF_PARAM_SIZE',                    'size', 'size_t'],
361                          ['KDF_PARAM_FIPS_APPROVED_INDICATOR', 'ind',  'int', 'fips'],
362                         )); -}
363
364static int kdf_pbkdf2_get_ctx_params(void *vctx, OSSL_PARAM params[])
365{
366    KDF_PBKDF2 *ctx = vctx;
367    struct pbkdf2_get_ctx_params_st p;
368
369    if (ctx == NULL || !pbkdf2_get_ctx_params_decoder(params, &p))
370        return 0;
371
372    if (p.size != NULL && !OSSL_PARAM_set_size_t(p.size, SIZE_MAX))
373            return 0;
374
375    if (!OSSL_FIPS_IND_GET_CTX_FROM_PARAM(ctx, p.ind))
376        return 0;
377    return 1;
378}
379
380static const OSSL_PARAM *kdf_pbkdf2_gettable_ctx_params(ossl_unused void *ctx,
381                                                        ossl_unused void *p_ctx)
382{
383    return pbkdf2_get_ctx_params_list;
384}
385
386const OSSL_DISPATCH ossl_kdf_pbkdf2_functions[] = {
387    { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_pbkdf2_new },
388    { OSSL_FUNC_KDF_DUPCTX, (void(*)(void))kdf_pbkdf2_dup },
389    { OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_pbkdf2_free },
390    { OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_pbkdf2_reset },
391    { OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_pbkdf2_derive },
392    { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
393      (void(*)(void))kdf_pbkdf2_settable_ctx_params },
394    { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_pbkdf2_set_ctx_params },
395    { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
396      (void(*)(void))kdf_pbkdf2_gettable_ctx_params },
397    { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_pbkdf2_get_ctx_params },
398    OSSL_DISPATCH_END
399};
400
401/*
402 * This is an implementation of PKCS#5 v2.0 password based encryption key
403 * derivation function PBKDF2. SHA1 version verified against test vectors
404 * posted by Peter Gutmann to the PKCS-TNG mailing list.
405 *
406 * The constraints specified by SP800-132 have been added i.e.
407 *  - Check the range of the key length.
408 *  - Minimum iteration count of 1000.
409 *  - Randomly-generated portion of the salt shall be at least 128 bits.
410 */
411static int pbkdf2_derive(KDF_PBKDF2 *ctx, const char *pass, size_t passlen,
412                         const unsigned char *salt, int saltlen, uint64_t iter,
413                         const EVP_MD *digest, unsigned char *key,
414                         size_t keylen, int lower_bound_checks)
415{
416    int ret = 0;
417    unsigned char digtmp[EVP_MAX_MD_SIZE], *p, itmp[4];
418    int cplen, k, tkeylen, mdlen;
419    uint64_t j;
420    unsigned long i = 1;
421    HMAC_CTX *hctx_tpl = NULL, *hctx = NULL;
422
423    mdlen = EVP_MD_get_size(digest);
424    if (mdlen <= 0)
425        return 0;
426
427    /*
428     * This check should always be done because keylen / mdlen >= (2^32 - 1)
429     * results in an overflow of the loop counter 'i'.
430     */
431    if ((keylen / mdlen) >= KDF_PBKDF2_MAX_KEY_LEN_DIGEST_RATIO) {
432        ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
433        return 0;
434    }
435
436    if (!lower_bound_check_passed(ctx, saltlen, iter, keylen, lower_bound_checks))
437        return 0;
438
439    hctx_tpl = HMAC_CTX_new();
440    if (hctx_tpl == NULL)
441        return 0;
442    p = key;
443    tkeylen = (int)keylen;
444    if (!HMAC_Init_ex(hctx_tpl, pass, (int)passlen, digest, NULL))
445        goto err;
446    hctx = HMAC_CTX_new();
447    if (hctx == NULL)
448        goto err;
449    while (tkeylen) {
450        if (tkeylen > mdlen)
451            cplen = mdlen;
452        else
453            cplen = tkeylen;
454        /*
455         * We are unlikely to ever use more than 256 blocks (5120 bits!) but
456         * just in case...
457         */
458        itmp[0] = (unsigned char)((i >> 24) & 0xff);
459        itmp[1] = (unsigned char)((i >> 16) & 0xff);
460        itmp[2] = (unsigned char)((i >> 8) & 0xff);
461        itmp[3] = (unsigned char)(i & 0xff);
462        if (!HMAC_CTX_copy(hctx, hctx_tpl))
463            goto err;
464        if (!HMAC_Update(hctx, salt, saltlen)
465                || !HMAC_Update(hctx, itmp, 4)
466                || !HMAC_Final(hctx, digtmp, NULL))
467            goto err;
468        memcpy(p, digtmp, cplen);
469        for (j = 1; j < iter; j++) {
470            if (!HMAC_CTX_copy(hctx, hctx_tpl))
471                goto err;
472            if (!HMAC_Update(hctx, digtmp, mdlen)
473                    || !HMAC_Final(hctx, digtmp, NULL))
474                goto err;
475            for (k = 0; k < cplen; k++)
476                p[k] ^= digtmp[k];
477        }
478        tkeylen -= cplen;
479        i++;
480        p += cplen;
481    }
482    ret = 1;
483
484err:
485    HMAC_CTX_free(hctx);
486    HMAC_CTX_free(hctx_tpl);
487    return ret;
488}
489