Rename some occurrences of 'library_context' and 'lib_ctx' to 'libctx'
[openssl.git] / providers / implementations / kdfs / kbkdf.c
1 /*
2  * Copyright 2019-2020 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
37 #include "internal/cryptlib.h"
38 #include "crypto/evp.h"
39 #include "internal/numbers.h"
40 #include "internal/endian.h"
41 #include "prov/implementations.h"
42 #include "prov/provider_ctx.h"
43 #include "prov/provider_util.h"
44 #include "prov/providercommon.h"
45 #include "prov/providercommonerr.h"
46
47 #include "e_os.h"
48
49 #define 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     unsigned char *ki;
64     size_t ki_len;
65     unsigned char *label;
66     size_t label_len;
67     unsigned char *context;
68     size_t context_len;
69     unsigned char *iv;
70     size_t iv_len;
71 } KBKDF;
72
73 /* Definitions needed for typechecking. */
74 static OSSL_FUNC_kdf_newctx_fn kbkdf_new;
75 static OSSL_FUNC_kdf_freectx_fn kbkdf_free;
76 static OSSL_FUNC_kdf_reset_fn kbkdf_reset;
77 static OSSL_FUNC_kdf_derive_fn kbkdf_derive;
78 static OSSL_FUNC_kdf_settable_ctx_params_fn kbkdf_settable_ctx_params;
79 static OSSL_FUNC_kdf_set_ctx_params_fn kbkdf_set_ctx_params;
80 static OSSL_FUNC_kdf_gettable_ctx_params_fn kbkdf_gettable_ctx_params;
81 static OSSL_FUNC_kdf_get_ctx_params_fn kbkdf_get_ctx_params;
82
83 /* Not all platforms have htobe32(). */
84 static uint32_t be32(uint32_t host)
85 {
86     uint32_t big = 0;
87     DECLARE_IS_ENDIAN;
88
89     if (!IS_LITTLE_ENDIAN)
90         return host;
91
92     big |= (host & 0xff000000) >> 24;
93     big |= (host & 0x00ff0000) >> 8;
94     big |= (host & 0x0000ff00) << 8;
95     big |= (host & 0x000000ff) << 24;
96     return big;
97 }
98
99 static void *kbkdf_new(void *provctx)
100 {
101     KBKDF *ctx;
102
103     if (!ossl_prov_is_running())
104         return NULL;
105
106     ctx = OPENSSL_zalloc(sizeof(*ctx));
107     if (ctx == NULL) {
108         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
109         return NULL;
110     }
111
112     ctx->provctx = provctx;
113     return ctx;
114 }
115
116 static void kbkdf_free(void *vctx)
117 {
118     KBKDF *ctx = (KBKDF *)vctx;
119
120     if (ctx != NULL) {
121         kbkdf_reset(ctx);
122         OPENSSL_free(ctx);
123     }
124 }
125
126 static void kbkdf_reset(void *vctx)
127 {
128     KBKDF *ctx = (KBKDF *)vctx;
129     void *provctx = ctx->provctx;
130
131     EVP_MAC_CTX_free(ctx->ctx_init);
132     OPENSSL_clear_free(ctx->context, ctx->context_len);
133     OPENSSL_clear_free(ctx->label, ctx->label_len);
134     OPENSSL_clear_free(ctx->ki, ctx->ki_len);
135     OPENSSL_clear_free(ctx->iv, ctx->iv_len);
136     memset(ctx, 0, sizeof(*ctx));
137     ctx->provctx = provctx;
138 }
139
140 /* SP800-108 section 5.1 or section 5.2 depending on mode. */
141 static int derive(EVP_MAC_CTX *ctx_init, kbkdf_mode mode, unsigned char *iv,
142                   size_t iv_len, unsigned char *label, size_t label_len,
143                   unsigned char *context, size_t context_len,
144                   unsigned char *k_i, size_t h, uint32_t l, unsigned char *ko,
145                   size_t ko_len)
146 {
147     int ret = 0;
148     EVP_MAC_CTX *ctx = NULL;
149     size_t written = 0, to_write, k_i_len = iv_len;
150     const unsigned char zero = 0;
151     uint32_t counter, i;
152
153     /* Setup K(0) for feedback mode. */
154     if (iv_len > 0)
155         memcpy(k_i, iv, iv_len);
156
157     for (counter = 1; written < ko_len; counter++) {
158         i = be32(counter);
159
160         ctx = EVP_MAC_CTX_dup(ctx_init);
161         if (ctx == NULL)
162             goto done;
163
164         /* Perform feedback, if appropriate. */
165         if (mode == FEEDBACK && !EVP_MAC_update(ctx, k_i, k_i_len))
166             goto done;
167
168         if (!EVP_MAC_update(ctx, (unsigned char *)&i, 4)
169             || !EVP_MAC_update(ctx, label, label_len)
170             || !EVP_MAC_update(ctx, &zero, 1)
171             || !EVP_MAC_update(ctx, context, context_len)
172             || !EVP_MAC_update(ctx, (unsigned char *)&l, 4)
173             || !EVP_MAC_final(ctx, k_i, NULL, h))
174             goto done;
175
176         to_write = ko_len - written;
177         memcpy(ko + written, k_i, MIN(to_write, h));
178         written += h;
179
180         k_i_len = h;
181         EVP_MAC_CTX_free(ctx);
182         ctx = NULL;
183     }
184
185     ret = 1;
186 done:
187     EVP_MAC_CTX_free(ctx);
188     return ret;
189 }
190
191 static int kbkdf_derive(void *vctx, unsigned char *key, size_t keylen)
192 {
193     KBKDF *ctx = (KBKDF *)vctx;
194     int ret = 0;
195     unsigned char *k_i = NULL;
196     uint32_t l = be32(keylen * 8);
197     size_t h = 0;
198
199     if (!ossl_prov_is_running())
200         return 0;
201
202     /* label, context, and iv are permitted to be empty.  Check everything
203      * else. */
204     if (ctx->ctx_init == NULL) {
205         if (ctx->ki_len == 0 || ctx->ki == NULL) {
206             ERR_raise(ERR_LIB_PROV, PROV_R_NO_KEY_SET);
207             return 0;
208         }
209         /* Could either be missing MAC or missing message digest or missing
210          * cipher - arbitrarily, I pick this one. */
211         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MAC);
212         return 0;
213     }
214
215     /* Fail if the output length is zero */
216     if (keylen == 0) {
217         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
218         return 0;
219     }
220
221     h = EVP_MAC_size(ctx->ctx_init);
222     if (h == 0)
223         goto done;
224     if (ctx->iv_len != 0 && ctx->iv_len != h) {
225         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_SEED_LENGTH);
226         goto done;
227     }
228
229     k_i = OPENSSL_zalloc(h);
230     if (k_i == NULL)
231         goto done;
232
233     ret = derive(ctx->ctx_init, ctx->mode, ctx->iv, ctx->iv_len, ctx->label,
234                  ctx->label_len, ctx->context, ctx->context_len, k_i, h, l,
235                  key, keylen);
236 done:
237     if (ret != 1)
238         OPENSSL_cleanse(key, keylen);
239     OPENSSL_clear_free(k_i, h);
240     return ret;
241 }
242
243 static int kbkdf_set_buffer(unsigned char **out, size_t *out_len,
244                             const OSSL_PARAM *p)
245 {
246     if (p->data == NULL || p->data_size == 0)
247         return 1;
248
249     OPENSSL_clear_free(*out, *out_len);
250     *out = NULL;
251     return OSSL_PARAM_get_octet_string(p, (void **)out, 0, out_len);
252 }
253
254 static int kbkdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
255 {
256     KBKDF *ctx = (KBKDF *)vctx;
257     OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
258     const OSSL_PARAM *p;
259     OSSL_PARAM mparams[2];
260
261     if (!ossl_prov_macctx_load_from_params(&ctx->ctx_init, params, NULL,
262                                            NULL, NULL, libctx))
263         return 0;
264     else if (ctx->ctx_init != NULL
265              && !EVP_MAC_is_a(EVP_MAC_CTX_mac(ctx->ctx_init),
266                               OSSL_MAC_NAME_HMAC)
267              && !EVP_MAC_is_a(EVP_MAC_CTX_mac(ctx->ctx_init),
268                               OSSL_MAC_NAME_CMAC)) {
269         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MAC);
270         return 0;
271     }
272
273     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_MODE);
274     if (p != NULL && strncasecmp("counter", p->data, p->data_size) == 0) {
275         ctx->mode = COUNTER;
276     } else if (p != NULL
277                && strncasecmp("feedback", p->data, p->data_size) == 0) {
278         ctx->mode = FEEDBACK;
279     } else if (p != NULL) {
280         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
281         return 0;
282     }
283
284     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY);
285     if (p != NULL && !kbkdf_set_buffer(&ctx->ki, &ctx->ki_len, p))
286         return 0;
287
288     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT);
289     if (p != NULL && !kbkdf_set_buffer(&ctx->label, &ctx->label_len, p))
290         return 0;
291
292     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_INFO);
293     if (p != NULL && !kbkdf_set_buffer(&ctx->context, &ctx->context_len, p))
294         return 0;
295
296     p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SEED);
297     if (p != NULL && !kbkdf_set_buffer(&ctx->iv, &ctx->iv_len, p))
298         return 0;
299
300     /* Set up digest context, if we can. */
301     if (ctx->ctx_init != NULL && ctx->ki_len != 0) {
302         mparams[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
303                                                        ctx->ki, ctx->ki_len);
304         mparams[1] = OSSL_PARAM_construct_end();
305
306         if (!EVP_MAC_CTX_set_params(ctx->ctx_init, mparams)
307             || !EVP_MAC_init(ctx->ctx_init))
308             return 0;
309     }
310
311     return 1;
312 }
313
314 static const OSSL_PARAM *kbkdf_settable_ctx_params(ossl_unused void *provctx)
315 {
316     static const OSSL_PARAM known_settable_ctx_params[] = {
317         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_INFO, NULL, 0),
318         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
319         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),
320         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SEED, NULL, 0),
321         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
322         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_CIPHER, NULL, 0),
323         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MAC, NULL, 0),
324         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MODE, NULL, 0),
325
326         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
327         OSSL_PARAM_END,
328     };
329     return known_settable_ctx_params;
330 }
331
332 static int kbkdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
333 {
334     OSSL_PARAM *p;
335
336     p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE);
337     if (p == NULL)
338         return -2;
339
340     /* KBKDF can produce results as large as you like. */
341     return OSSL_PARAM_set_size_t(p, SIZE_MAX);
342 }
343
344 static const OSSL_PARAM *kbkdf_gettable_ctx_params(ossl_unused void *provctx)
345 {
346     static const OSSL_PARAM known_gettable_ctx_params[] =
347         { OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL), OSSL_PARAM_END };
348     return known_gettable_ctx_params;
349 }
350
351 const OSSL_DISPATCH ossl_kdf_kbkdf_functions[] = {
352     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kbkdf_new },
353     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))kbkdf_free },
354     { OSSL_FUNC_KDF_RESET, (void(*)(void))kbkdf_reset },
355     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))kbkdf_derive },
356     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
357       (void(*)(void))kbkdf_settable_ctx_params },
358     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kbkdf_set_ctx_params },
359     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
360       (void(*)(void))kbkdf_gettable_ctx_params },
361     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kbkdf_get_ctx_params },
362     { 0, NULL },
363 };