Don't forget our provider ctx when resetting
[openssl.git] / providers / implementations / kdfs / pbkdf2.c
1 /*
2  * Copyright 2018-2020 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  * HMAC low level APIs are deprecated for public use, but still ok for internal
12  * use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <stdlib.h>
17 #include <stdarg.h>
18 #include <string.h>
19 #include <openssl/hmac.h>
20 #include <openssl/evp.h>
21 #include <openssl/kdf.h>
22 #include <openssl/core_names.h>
23 #include "internal/cryptlib.h"
24 #include "internal/numbers.h"
25 #include "crypto/evp.h"
26 #include "prov/provider_ctx.h"
27 #include "prov/providercommonerr.h"
28 #include "prov/implementations.h"
29 #include "prov/provider_util.h"
30 #include "pbkdf2.h"
31
32 /* Constants specified in SP800-132 */
33 #define KDF_PBKDF2_MIN_KEY_LEN_BITS  112
34 #define KDF_PBKDF2_MAX_KEY_LEN_DIGEST_RATIO 0xFFFFFFFF
35 #define KDF_PBKDF2_MIN_ITERATIONS 1000
36 #define KDF_PBKDF2_MIN_SALT_LEN   (128 / 8)
37
38 static OSSL_FUNC_kdf_newctx_fn kdf_pbkdf2_new;
39 static OSSL_FUNC_kdf_freectx_fn kdf_pbkdf2_free;
40 static OSSL_FUNC_kdf_reset_fn kdf_pbkdf2_reset;
41 static OSSL_FUNC_kdf_derive_fn kdf_pbkdf2_derive;
42 static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_pbkdf2_settable_ctx_params;
43 static OSSL_FUNC_kdf_set_ctx_params_fn kdf_pbkdf2_set_ctx_params;
44
45 static int  pbkdf2_derive(const char *pass, size_t passlen,
46                           const unsigned char *salt, int saltlen, uint64_t iter,
47                           const EVP_MD *digest, unsigned char *key,
48                           size_t keylen, int extra_checks);
49
50 typedef struct {
51     void *provctx;
52     unsigned char *pass;
53     size_t pass_len;
54     unsigned char *salt;
55     size_t salt_len;
56     uint64_t iter;
57     PROV_DIGEST digest;
58     int lower_bound_checks;
59 } KDF_PBKDF2;
60
61 static void kdf_pbkdf2_init(KDF_PBKDF2 *ctx);
62
63 static void *kdf_pbkdf2_new(void *provctx)
64 {
65     KDF_PBKDF2 *ctx;
66
67     ctx = OPENSSL_zalloc(sizeof(*ctx));
68     if (ctx == NULL) {
69         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
70         return NULL;
71     }
72     ctx->provctx = provctx;
73     kdf_pbkdf2_init(ctx);
74     return ctx;
75 }
76
77 static void kdf_pbkdf2_cleanup(KDF_PBKDF2 *ctx)
78 {
79     ossl_prov_digest_reset(&ctx->digest);
80     OPENSSL_free(ctx->salt);
81     OPENSSL_clear_free(ctx->pass, ctx->pass_len);
82     memset(ctx, 0, sizeof(*ctx));
83 }
84
85 static void kdf_pbkdf2_free(void *vctx)
86 {
87     KDF_PBKDF2 *ctx = (KDF_PBKDF2 *)vctx;
88
89     if (ctx != NULL) {
90         kdf_pbkdf2_cleanup(ctx);
91         OPENSSL_free(ctx);
92     }
93 }
94
95 static void kdf_pbkdf2_reset(void *vctx)
96 {
97     KDF_PBKDF2 *ctx = (KDF_PBKDF2 *)vctx;
98     void *provctx = ctx->provctx;
99
100     kdf_pbkdf2_cleanup(ctx);
101     ctx->provctx = provctx;
102     kdf_pbkdf2_init(ctx);
103 }
104
105 static void kdf_pbkdf2_init(KDF_PBKDF2 *ctx)
106 {
107     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
108     OPENSSL_CTX *provctx = PROV_LIBRARY_CONTEXT_OF(ctx->provctx);
109
110     params[0] = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
111                                                  SN_sha1, 0);
112     if (!ossl_prov_digest_load_from_params(&ctx->digest, params, provctx))
113         /* This is an error, but there is no way to indicate such directly */
114         ossl_prov_digest_reset(&ctx->digest);
115     ctx->iter = PKCS5_DEFAULT_ITER;
116     ctx->lower_bound_checks = kdf_pbkdf2_default_checks;
117 }
118
119 static int pbkdf2_set_membuf(unsigned char **buffer, size_t *buflen,
120                              const OSSL_PARAM *p)
121 {
122     OPENSSL_clear_free(*buffer, *buflen);
123     if (p->data_size == 0) {
124         if ((*buffer = OPENSSL_malloc(1)) == NULL) {
125             ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
126             return 0;
127         }
128     } else if (p->data != NULL) {
129         *buffer = NULL;
130         if (!OSSL_PARAM_get_octet_string(p, (void **)buffer, 0, buflen))
131             return 0;
132     }
133     return 1;
134 }
135
136 static int kdf_pbkdf2_derive(void *vctx, unsigned char *key,
137                              size_t keylen)
138 {
139     KDF_PBKDF2 *ctx = (KDF_PBKDF2 *)vctx;
140     const EVP_MD *md = ossl_prov_digest_md(&ctx->digest);
141
142     if (ctx->pass == NULL) {
143         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_PASS);
144         return 0;
145     }
146
147     if (ctx->salt == NULL) {
148         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SALT);
149         return 0;
150     }
151
152     return pbkdf2_derive((char *)ctx->pass, ctx->pass_len,
153                          ctx->salt, ctx->salt_len, ctx->iter,
154                          md, key, keylen, ctx->lower_bound_checks);
155 }
156
157 static int kdf_pbkdf2_set_ctx_params(void *vctx, const OSSL_PARAM params[])
158 {
159     const OSSL_PARAM *p;
160     KDF_PBKDF2 *ctx = vctx;
161     OPENSSL_CTX *provctx = PROV_LIBRARY_CONTEXT_OF(ctx->provctx);
162     int pkcs5;
163     uint64_t iter, min_iter;
164
165     if (!ossl_prov_digest_load_from_params(&ctx->digest, params, provctx))
166         return 0;
167
168     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PKCS5)) != NULL) {
169         if (!OSSL_PARAM_get_int(p, &pkcs5))
170             return 0;
171         ctx->lower_bound_checks = pkcs5 == 0;
172     }
173
174     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PASSWORD)) != NULL)
175         if (!pbkdf2_set_membuf(&ctx->pass, &ctx->pass_len, p))
176             return 0;
177
178     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT)) != NULL) {
179         if (ctx->lower_bound_checks != 0
180             && p->data_size < KDF_PBKDF2_MIN_SALT_LEN) {
181             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_SALT_LENGTH);
182             return 0;
183         }
184         if (!pbkdf2_set_membuf(&ctx->salt, &ctx->salt_len,p))
185             return 0;
186     }
187
188     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_ITER)) != NULL) {
189         if (!OSSL_PARAM_get_uint64(p, &iter))
190             return 0;
191         min_iter = ctx->lower_bound_checks != 0 ? KDF_PBKDF2_MIN_ITERATIONS : 1;
192         if (iter < min_iter) {
193             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_ITERATION_COUNT);
194             return 0;
195         }
196         ctx->iter = iter;
197     }
198     return 1;
199 }
200
201 static const OSSL_PARAM *kdf_pbkdf2_settable_ctx_params(void)
202 {
203     static const OSSL_PARAM known_settable_ctx_params[] = {
204         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
205         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
206         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PASSWORD, NULL, 0),
207         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
208         OSSL_PARAM_uint64(OSSL_KDF_PARAM_ITER, NULL),
209         OSSL_PARAM_int(OSSL_KDF_PARAM_PKCS5, NULL),
210         OSSL_PARAM_END
211     };
212     return known_settable_ctx_params;
213 }
214
215 static int kdf_pbkdf2_get_ctx_params(void *vctx, OSSL_PARAM params[])
216 {
217     OSSL_PARAM *p;
218
219     if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
220         return OSSL_PARAM_set_size_t(p, SIZE_MAX);
221     return -2;
222 }
223
224 static const OSSL_PARAM *kdf_pbkdf2_gettable_ctx_params(void)
225 {
226     static const OSSL_PARAM known_gettable_ctx_params[] = {
227         OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
228         OSSL_PARAM_END
229     };
230     return known_gettable_ctx_params;
231 }
232
233 const OSSL_DISPATCH kdf_pbkdf2_functions[] = {
234     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_pbkdf2_new },
235     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_pbkdf2_free },
236     { OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_pbkdf2_reset },
237     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_pbkdf2_derive },
238     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
239       (void(*)(void))kdf_pbkdf2_settable_ctx_params },
240     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_pbkdf2_set_ctx_params },
241     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
242       (void(*)(void))kdf_pbkdf2_gettable_ctx_params },
243     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_pbkdf2_get_ctx_params },
244     { 0, NULL }
245 };
246
247 /*
248  * This is an implementation of PKCS#5 v2.0 password based encryption key
249  * derivation function PBKDF2. SHA1 version verified against test vectors
250  * posted by Peter Gutmann to the PKCS-TNG mailing list.
251  *
252  * The constraints specified by SP800-132 have been added i.e.
253  *  - Check the range of the key length.
254  *  - Minimum iteration count of 1000.
255  *  - Randomly-generated portion of the salt shall be at least 128 bits.
256  */
257 static int pbkdf2_derive(const char *pass, size_t passlen,
258                          const unsigned char *salt, int saltlen, uint64_t iter,
259                          const EVP_MD *digest, unsigned char *key,
260                          size_t keylen, int lower_bound_checks)
261 {
262     int ret = 0;
263     unsigned char digtmp[EVP_MAX_MD_SIZE], *p, itmp[4];
264     int cplen, k, tkeylen, mdlen;
265     uint64_t j;
266     unsigned long i = 1;
267     HMAC_CTX *hctx_tpl = NULL, *hctx = NULL;
268
269     mdlen = EVP_MD_size(digest);
270     if (mdlen <= 0)
271         return 0;
272
273     /*
274      * This check should always be done because keylen / mdlen >= (2^32 - 1)
275      * results in an overflow of the loop counter 'i'.
276      */
277     if ((keylen / mdlen) >= KDF_PBKDF2_MAX_KEY_LEN_DIGEST_RATIO) {
278         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LEN);
279         return 0;
280     }
281
282     if (lower_bound_checks) {
283         if ((keylen * 8) < KDF_PBKDF2_MIN_KEY_LEN_BITS) {
284             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LEN);
285             return 0;
286         }
287         if (saltlen < KDF_PBKDF2_MIN_SALT_LEN) {
288             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_SALT_LENGTH);
289             return 0;
290         }
291         if (iter < KDF_PBKDF2_MIN_ITERATIONS) {
292             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_ITERATION_COUNT);
293             return 0;
294         }
295     }
296
297     hctx_tpl = HMAC_CTX_new();
298     if (hctx_tpl == NULL)
299         return 0;
300     p = key;
301     tkeylen = keylen;
302     if (!HMAC_Init_ex(hctx_tpl, pass, passlen, digest, NULL))
303         goto err;
304     hctx = HMAC_CTX_new();
305     if (hctx == NULL)
306         goto err;
307     while (tkeylen) {
308         if (tkeylen > mdlen)
309             cplen = mdlen;
310         else
311             cplen = tkeylen;
312         /*
313          * We are unlikely to ever use more than 256 blocks (5120 bits!) but
314          * just in case...
315          */
316         itmp[0] = (unsigned char)((i >> 24) & 0xff);
317         itmp[1] = (unsigned char)((i >> 16) & 0xff);
318         itmp[2] = (unsigned char)((i >> 8) & 0xff);
319         itmp[3] = (unsigned char)(i & 0xff);
320         if (!HMAC_CTX_copy(hctx, hctx_tpl))
321             goto err;
322         if (!HMAC_Update(hctx, salt, saltlen)
323                 || !HMAC_Update(hctx, itmp, 4)
324                 || !HMAC_Final(hctx, digtmp, NULL))
325             goto err;
326         memcpy(p, digtmp, cplen);
327         for (j = 1; j < iter; j++) {
328             if (!HMAC_CTX_copy(hctx, hctx_tpl))
329                 goto err;
330             if (!HMAC_Update(hctx, digtmp, mdlen)
331                     || !HMAC_Final(hctx, digtmp, NULL))
332                 goto err;
333             for (k = 0; k < cplen; k++)
334                 p[k] ^= digtmp[k];
335         }
336         tkeylen -= cplen;
337         i++;
338         p += cplen;
339     }
340     ret = 1;
341
342 err:
343     HMAC_CTX_free(hctx);
344     HMAC_CTX_free(hctx_tpl);
345     return ret;
346 }