rename MIN() macro
[openssl.git] / providers / implementations / kdfs / kbkdf.c
1 /*
2  * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright 2019 Red Hat, Inc.
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 /*
12  * This implements https://csrc.nist.gov/publications/detail/sp/800-108/final
13  * section 5.1 ("counter mode") and section 5.2 ("feedback mode") in both HMAC
14  * and CMAC.  That document does not name the KDFs it defines; the name is
15  * derived from
16  * https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/Key-Derivation
17  *
18  * Note that section 5.3 ("double-pipeline mode") is not implemented, though
19  * it would be possible to do so in the future.
20  *
21  * These versions all assume the counter is used.  It would be relatively
22  * straightforward to expose a configuration handle should the need arise.
23  *
24  * Variable names attempt to match those of SP800-108.
25  */
26
27 #include <stdarg.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include <openssl/core_names.h>
32 #include <openssl/evp.h>
33 #include <openssl/hmac.h>
34 #include <openssl/kdf.h>
35 #include <openssl/params.h>
36 #include <openssl/proverr.h>
37
38 #include "internal/cryptlib.h"
39 #include "crypto/evp.h"
40 #include "internal/numbers.h"
41 #include "internal/endian.h"
42 #include "prov/implementations.h"
43 #include "prov/provider_ctx.h"
44 #include "prov/provider_util.h"
45 #include "prov/providercommon.h"
46
47 #include "e_os.h"
48
49 #define ossl_min(a, b) ((a) < (b)) ? (a) : (b)
50
51 typedef enum {
52     COUNTER = 0,
53     FEEDBACK
54 } kbkdf_mode;
55
56 /* Our context structure. */
57 typedef struct {
58     void *provctx;
59     kbkdf_mode mode;
60     EVP_MAC_CTX *ctx_init;
61
62     /* Names are lowercased versions of those found in SP800-108. */
63     int r;
64     unsigned char *ki;
65     size_t ki_len;
66     unsigned char *label;
67     size_t label_len;
68     unsigned char *context;
69     size_t context_len;
70     unsigned char *iv;
71     size_t iv_len;
72     int use_l;
73     int use_separator;
74 } KBKDF;
75
76 /* Definitions needed for typechecking. */
77 static OSSL_FUNC_kdf_newctx_fn kbkdf_new;
78 static OSSL_FUNC_kdf_freectx_fn kbkdf_free;
79 static OSSL_FUNC_kdf_reset_fn kbkdf_reset;
80 static OSSL_FUNC_kdf_derive_fn kbkdf_derive;
81 static OSSL_FUNC_kdf_settable_ctx_params_fn kbkdf_settable_ctx_params;
82 static OSSL_FUNC_kdf_set_ctx_params_fn kbkdf_set_ctx_params;
83 static OSSL_FUNC_kdf_gettable_ctx_params_fn kbkdf_gettable_ctx_params;
84 static OSSL_FUNC_kdf_get_ctx_params_fn kbkdf_get_ctx_params;
85
86 /* Not all platforms have htobe32(). */
87 static uint32_t be32(uint32_t host)
88 {
89     uint32_t big = 0;
90     DECLARE_IS_ENDIAN;
91
92     if (!IS_LITTLE_ENDIAN)
93         return host;
94
95     big |= (host & 0xff000000) >> 24;
96     big |= (host & 0x00ff0000) >> 8;
97     big |= (host & 0x0000ff00) << 8;
98     big |= (host & 0x000000ff) << 24;
99     return big;
100 }
101
102 static void init(KBKDF *ctx)
103 {
104     ctx->r = 32;
105     ctx->use_l = 1;
106     ctx->use_separator = 1;
107 }
108
109 static void *kbkdf_new(void *provctx)
110 {
111     KBKDF *ctx;
112
113     if (!ossl_prov_is_running())
114         return NULL;
115
116     ctx = OPENSSL_zalloc(sizeof(*ctx));
117     if (ctx == NULL) {
118         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
119         return NULL;
120     }
121
122     ctx->provctx = provctx;
123     init(ctx);
124     return ctx;
125 }
126
127 static void kbkdf_free(void *vctx)
128 {
129     KBKDF *ctx = (KBKDF *)vctx;
130
131     if (ctx != NULL) {
132         kbkdf_reset(ctx);
133         OPENSSL_free(ctx);
134     }
135 }
136
137 static void kbkdf_reset(void *vctx)
138 {
139     KBKDF *ctx = (KBKDF *)vctx;
140     void *provctx = ctx->provctx;
141
142     EVP_MAC_CTX_free(ctx->ctx_init);
143     OPENSSL_clear_free(ctx->context, ctx->context_len);
144     OPENSSL_clear_free(ctx->label, ctx->label_len);
145     OPENSSL_clear_free(ctx->ki, ctx->ki_len);
146     OPENSSL_clear_free(ctx->iv, ctx->iv_len);
147     memset(ctx, 0, sizeof(*ctx));
148     ctx->provctx = provctx;
149     init(ctx);
150 }
151
152 /* SP800-108 section 5.1 or section 5.2 depending on mode. */
153 static int derive(EVP_MAC_CTX *ctx_init, kbkdf_mode mode, unsigned char *iv,
154                   size_t iv_len, unsigned char *label, size_t label_len,
155                   unsigned char *context, size_t context_len,
156                   unsigned char *k_i, size_t h, uint32_t l, int has_separator,
157                   unsigned char *ko, size_t ko_len, int r)
158 {
159     int ret = 0;
160     EVP_MAC_CTX *ctx = NULL;
161     size_t written = 0, to_write, k_i_len = iv_len;
162     const unsigned char zero = 0;
163     uint32_t counter, i;
164     /*
165      * From SP800-108:
166      * The fixed input data is a concatenation of a Label,
167      * a separation indicator 0x00, the Context, and L.
168      * One or more of these fixed input data fields may be omitted.
169      *
170      * has_separator == 0 means that the separator is omitted.
171      * Passing a value of l == 0 means that L is omitted.
172      * The Context and L are omitted automatically if a NULL buffer is passed.
173      */
174     int has_l = (l != 0);
175
176     /* Setup K(0) for feedback mode. */
177     if (iv_len > 0)
178         memcpy(k_i, iv, iv_len);
179
180     for (counter = 1; written < ko_len; counter++) {
181         i = be32(counter);
182
183         ctx = EVP_MAC_CTX_dup(ctx_init);
184         if (ctx == NULL)
185             goto done;
186
187         /* Perform feedback, if appropriate. */
188         if (mode == FEEDBACK && !EVP_MAC_update(ctx, k_i, k_i_len))
189             goto done;
190
191         if (!EVP_MAC_update(ctx, 4 - (r / 8) + (unsigned char *)&i, r / 8)
192             || !EVP_MAC_update(ctx, label, label_len)
193             || (has_separator && !EVP_MAC_update(ctx, &zero, 1))
194             || !EVP_MAC_update(ctx, context, context_len)
195             || (has_l && !EVP_MAC_update(ctx, (unsigned char *)&l, 4))
196             || !EVP_MAC_final(ctx, k_i, NULL, h))
197             goto done;
198
199         to_write = ko_len - written;
200         memcpy(ko + written, k_i, ossl_min(to_write, h));
201         written += h;
202
203         k_i_len = h;
204         EVP_MAC_CTX_free(ctx);
205         ctx = NULL;
206     }
207
208     ret = 1;
209 done:
210     EVP_MAC_CTX_free(ctx);
211     return ret;
212 }
213
214 static int kbkdf_derive(void *vctx, unsigned char *key, size_t keylen,
215                         const OSSL_PARAM params[])
216 {
217     KBKDF *ctx = (KBKDF *)vctx;
218     int ret = 0;
219     unsigned char *k_i = NULL;
220     uint32_t l = 0;
221     size_t h = 0;
222     uint64_t counter_max;
223
224     if (!ossl_prov_is_running() || !kbkdf_set_ctx_params(ctx, params))
225         return 0;
226
227     /* label, context, and iv are permitted to be empty.  Check everything
228      * else. */
229     if (ctx->ctx_init == NULL) {
230         if (ctx->ki_len == 0 || ctx->ki == NULL) {
231             ERR_raise(ERR_LIB_PROV, PROV_R_NO_KEY_SET);
232             return 0;
233         }
234         /* Could either be missing MAC or missing message digest or missing
235          * cipher - arbitrarily, I pick this one. */
236         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MAC);
237         return 0;
238     }
239
240     /* Fail if the output length is zero */
241     if (keylen == 0) {
242         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
243         return 0;
244     }
245
246     h = EVP_MAC_CTX_get_mac_size(ctx->ctx_init);
247     if (h == 0)
248         goto done;
249     if (ctx->iv_len != 0 && ctx->iv_len != h) {
250         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_SEED_LENGTH);
251         goto done;
252     }
253
254     if (ctx->mode == COUNTER) {
255         /* Fail if keylen is too large for r */
256         counter_max = (uint64_t)1 << (uint64_t)ctx->r;
257         if ((uint64_t)(keylen / h) >= counter_max) {
258             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
259             goto done;
260         }
261     }
262
263     if (ctx->use_l != 0)
264         l = be32(keylen * 8);
265
266     k_i = OPENSSL_zalloc(h);
267     if (k_i == NULL)
268         goto done;
269
270     ret = derive(ctx->ctx_init, ctx->mode, ctx->iv, ctx->iv_len, ctx->label,
271                  ctx->label_len, ctx->context, ctx->context_len, k_i, h, l,
272                  ctx->use_separator, key, keylen, ctx->r);
273 done:
274     if (ret != 1)
275         OPENSSL_cleanse(key, keylen);
276     OPENSSL_clear_free(k_i, h);
277     return ret;
278 }
279
280 static int kbkdf_set_buffer(unsigned char **out, size_t *out_len,
281                             const OSSL_PARAM *p)
282 {
283     if (p->data == NULL || p->data_size == 0)
284         return 1;
285
286     OPENSSL_clear_free(*out, *out_len);
287     *out = NULL;
288     return OSSL_PARAM_get_octet_string(p, (void **)out, 0, out_len);
289 }
290
291 static int kbkdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
292 {
293     KBKDF *ctx = (KBKDF *)vctx;
294     OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
295     const OSSL_PARAM *p;
296
297     if (params == NULL)
298         return 1;
299
300     if (!ossl_prov_macctx_load_from_params(&ctx->ctx_init, params, NULL,
301                                            NULL, NULL, libctx))
302         return 0;
303     else if (ctx->ctx_init != NULL
304              && !EVP_MAC_is_a(EVP_MAC_CTX_get0_mac(ctx->ctx_init),
305                               OSSL_MAC_NAME_HMAC)
306              && !EVP_MAC_is_a(EVP_MAC_CTX_get0_mac(ctx->ctx_init),
307                               OSSL_MAC_NAME_CMAC)) {
308         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MAC);
309         return 0;
310     }
311
312     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_MODE);
313     if (p != NULL && strncasecmp("counter", p->data, p->data_size) == 0) {
314         ctx->mode = COUNTER;
315     } else if (p != NULL
316                && strncasecmp("feedback", p->data, p->data_size) == 0) {
317         ctx->mode = FEEDBACK;
318     } else if (p != NULL) {
319         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
320         return 0;
321     }
322
323     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY);
324     if (p != NULL && !kbkdf_set_buffer(&ctx->ki, &ctx->ki_len, p))
325         return 0;
326
327     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT);
328     if (p != NULL && !kbkdf_set_buffer(&ctx->label, &ctx->label_len, p))
329         return 0;
330
331     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_INFO);
332     if (p != NULL && !kbkdf_set_buffer(&ctx->context, &ctx->context_len, p))
333         return 0;
334
335     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SEED);
336     if (p != NULL && !kbkdf_set_buffer(&ctx->iv, &ctx->iv_len, p))
337         return 0;
338
339     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KBKDF_USE_L);
340     if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->use_l))
341         return 0;
342
343     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KBKDF_R);
344     if (p != NULL) {
345         int new_r = 0;
346
347         if (!OSSL_PARAM_get_int(p, &new_r))
348             return 0;
349         if (new_r != 8 && new_r != 16 && new_r != 24 && new_r != 32)
350             return 0;
351         ctx->r = new_r;
352     }
353
354     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KBKDF_USE_SEPARATOR);
355     if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->use_separator))
356         return 0;
357
358     /* Set up digest context, if we can. */
359     if (ctx->ctx_init != NULL && ctx->ki_len != 0
360             && !EVP_MAC_init(ctx->ctx_init, ctx->ki, ctx->ki_len, NULL))
361             return 0;
362     return 1;
363 }
364
365 static const OSSL_PARAM *kbkdf_settable_ctx_params(ossl_unused void *ctx,
366                                                    ossl_unused void *provctx)
367 {
368     static const OSSL_PARAM known_settable_ctx_params[] = {
369         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_INFO, NULL, 0),
370         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
371         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),
372         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SEED, NULL, 0),
373         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
374         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_CIPHER, NULL, 0),
375         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MAC, NULL, 0),
376         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MODE, NULL, 0),
377         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
378         OSSL_PARAM_int(OSSL_KDF_PARAM_KBKDF_USE_L, NULL),
379         OSSL_PARAM_int(OSSL_KDF_PARAM_KBKDF_USE_SEPARATOR, NULL),
380         OSSL_PARAM_int(OSSL_KDF_PARAM_KBKDF_R, NULL),
381         OSSL_PARAM_END,
382     };
383     return known_settable_ctx_params;
384 }
385
386 static int kbkdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
387 {
388     OSSL_PARAM *p;
389
390     p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE);
391     if (p == NULL)
392         return -2;
393
394     /* KBKDF can produce results as large as you like. */
395     return OSSL_PARAM_set_size_t(p, SIZE_MAX);
396 }
397
398 static const OSSL_PARAM *kbkdf_gettable_ctx_params(ossl_unused void *ctx,
399                                                    ossl_unused void *provctx)
400 {
401     static const OSSL_PARAM known_gettable_ctx_params[] =
402         { OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL), OSSL_PARAM_END };
403     return known_gettable_ctx_params;
404 }
405
406 const OSSL_DISPATCH ossl_kdf_kbkdf_functions[] = {
407     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kbkdf_new },
408     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))kbkdf_free },
409     { OSSL_FUNC_KDF_RESET, (void(*)(void))kbkdf_reset },
410     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))kbkdf_derive },
411     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
412       (void(*)(void))kbkdf_settable_ctx_params },
413     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kbkdf_set_ctx_params },
414     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
415       (void(*)(void))kbkdf_gettable_ctx_params },
416     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kbkdf_get_ctx_params },
417     { 0, NULL },
418 };