prov: add extra params argument to KDF implementations
[openssl.git] / providers / implementations / kdfs / sskdf.c
1 /*
2  * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2019, Oracle and/or its affiliates.  All rights reserved.
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  * Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
13  * Section 4.1.
14  *
15  * The Single Step KDF algorithm is given by:
16  *
17  * Result(0) = empty bit string (i.e., the null string).
18  * For i = 1 to reps, do the following:
19  *   Increment counter by 1.
20  *   Result(i) = Result(i - 1) || H(counter || Z || FixedInfo).
21  * DKM = LeftmostBits(Result(reps), L))
22  *
23  * NOTES:
24  *   Z is a shared secret required to produce the derived key material.
25  *   counter is a 4 byte buffer.
26  *   FixedInfo is a bit string containing context specific data.
27  *   DKM is the output derived key material.
28  *   L is the required size of the DKM.
29  *   reps = [L / H_outputBits]
30  *   H(x) is the auxiliary function that can be either a hash, HMAC or KMAC.
31  *   H_outputBits is the length of the output of the auxiliary function H(x).
32  *
33  * Currently there is not a comprehensive list of test vectors for this
34  * algorithm, especially for H(x) = HMAC and H(x) = KMAC.
35  * Test vectors for H(x) = Hash are indirectly used by CAVS KAS tests.
36  */
37 #include <stdlib.h>
38 #include <stdarg.h>
39 #include <string.h>
40 #include <openssl/hmac.h>
41 #include <openssl/evp.h>
42 #include <openssl/kdf.h>
43 #include <openssl/core_names.h>
44 #include <openssl/params.h>
45 #include <openssl/proverr.h>
46 #include "internal/cryptlib.h"
47 #include "internal/numbers.h"
48 #include "crypto/evp.h"
49 #include "prov/provider_ctx.h"
50 #include "prov/providercommon.h"
51 #include "prov/implementations.h"
52 #include "prov/provider_util.h"
53
54 typedef struct {
55     void *provctx;
56     EVP_MAC_CTX *macctx;         /* H(x) = HMAC_hash OR H(x) = KMAC */
57     PROV_DIGEST digest;          /* H(x) = hash(x) */
58     unsigned char *secret;
59     size_t secret_len;
60     unsigned char *info;
61     size_t info_len;
62     unsigned char *salt;
63     size_t salt_len;
64     size_t out_len; /* optional KMAC parameter */
65 } KDF_SSKDF;
66
67 #define SSKDF_MAX_INLEN (1<<30)
68 #define SSKDF_KMAC128_DEFAULT_SALT_SIZE (168 - 4)
69 #define SSKDF_KMAC256_DEFAULT_SALT_SIZE (136 - 4)
70
71 /* KMAC uses a Customisation string of 'KDF' */
72 static const unsigned char kmac_custom_str[] = { 0x4B, 0x44, 0x46 };
73
74 static OSSL_FUNC_kdf_newctx_fn sskdf_new;
75 static OSSL_FUNC_kdf_freectx_fn sskdf_free;
76 static OSSL_FUNC_kdf_reset_fn sskdf_reset;
77 static OSSL_FUNC_kdf_derive_fn sskdf_derive;
78 static OSSL_FUNC_kdf_derive_fn x963kdf_derive;
79 static OSSL_FUNC_kdf_settable_ctx_params_fn sskdf_settable_ctx_params;
80 static OSSL_FUNC_kdf_set_ctx_params_fn sskdf_set_ctx_params;
81 static OSSL_FUNC_kdf_gettable_ctx_params_fn sskdf_gettable_ctx_params;
82 static OSSL_FUNC_kdf_get_ctx_params_fn sskdf_get_ctx_params;
83
84 /*
85  * Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
86  * Section 4. One-Step Key Derivation using H(x) = hash(x)
87  * Note: X9.63 also uses this code with the only difference being that the
88  * counter is appended to the secret 'z'.
89  * i.e.
90  *   result[i] = Hash(counter || z || info) for One Step OR
91  *   result[i] = Hash(z || counter || info) for X9.63.
92  */
93 static int SSKDF_hash_kdm(const EVP_MD *kdf_md,
94                           const unsigned char *z, size_t z_len,
95                           const unsigned char *info, size_t info_len,
96                           unsigned int append_ctr,
97                           unsigned char *derived_key, size_t derived_key_len)
98 {
99     int ret = 0, hlen;
100     size_t counter, out_len, len = derived_key_len;
101     unsigned char c[4];
102     unsigned char mac[EVP_MAX_MD_SIZE];
103     unsigned char *out = derived_key;
104     EVP_MD_CTX *ctx = NULL, *ctx_init = NULL;
105
106     if (z_len > SSKDF_MAX_INLEN || info_len > SSKDF_MAX_INLEN
107             || derived_key_len > SSKDF_MAX_INLEN
108             || derived_key_len == 0)
109         return 0;
110
111     hlen = EVP_MD_size(kdf_md);
112     if (hlen <= 0)
113         return 0;
114     out_len = (size_t)hlen;
115
116     ctx = EVP_MD_CTX_create();
117     ctx_init = EVP_MD_CTX_create();
118     if (ctx == NULL || ctx_init == NULL)
119         goto end;
120
121     if (!EVP_DigestInit(ctx_init, kdf_md))
122         goto end;
123
124     for (counter = 1;; counter++) {
125         c[0] = (unsigned char)((counter >> 24) & 0xff);
126         c[1] = (unsigned char)((counter >> 16) & 0xff);
127         c[2] = (unsigned char)((counter >> 8) & 0xff);
128         c[3] = (unsigned char)(counter & 0xff);
129
130         if (!(EVP_MD_CTX_copy_ex(ctx, ctx_init)
131                 && (append_ctr || EVP_DigestUpdate(ctx, c, sizeof(c)))
132                 && EVP_DigestUpdate(ctx, z, z_len)
133                 && (!append_ctr || EVP_DigestUpdate(ctx, c, sizeof(c)))
134                 && EVP_DigestUpdate(ctx, info, info_len)))
135             goto end;
136         if (len >= out_len) {
137             if (!EVP_DigestFinal_ex(ctx, out, NULL))
138                 goto end;
139             out += out_len;
140             len -= out_len;
141             if (len == 0)
142                 break;
143         } else {
144             if (!EVP_DigestFinal_ex(ctx, mac, NULL))
145                 goto end;
146             memcpy(out, mac, len);
147             break;
148         }
149     }
150     ret = 1;
151 end:
152     EVP_MD_CTX_destroy(ctx);
153     EVP_MD_CTX_destroy(ctx_init);
154     OPENSSL_cleanse(mac, sizeof(mac));
155     return ret;
156 }
157
158 static int kmac_init(EVP_MAC_CTX *ctx, const unsigned char *custom,
159                      size_t custom_len, size_t kmac_out_len,
160                      size_t derived_key_len, unsigned char **out)
161 {
162     OSSL_PARAM params[2];
163
164     /* Only KMAC has custom data - so return if not KMAC */
165     if (custom == NULL)
166         return 1;
167
168     params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_CUSTOM,
169                                                   (void *)custom, custom_len);
170     params[1] = OSSL_PARAM_construct_end();
171
172     if (!EVP_MAC_CTX_set_params(ctx, params))
173         return 0;
174
175     /* By default only do one iteration if kmac_out_len is not specified */
176     if (kmac_out_len == 0)
177         kmac_out_len = derived_key_len;
178     /* otherwise check the size is valid */
179     else if (!(kmac_out_len == derived_key_len
180             || kmac_out_len == 20
181             || kmac_out_len == 28
182             || kmac_out_len == 32
183             || kmac_out_len == 48
184             || kmac_out_len == 64))
185         return 0;
186
187     params[0] = OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_SIZE,
188                                             &kmac_out_len);
189
190     if (EVP_MAC_CTX_set_params(ctx, params) <= 0)
191         return 0;
192
193     /*
194      * For kmac the output buffer can be larger than EVP_MAX_MD_SIZE: so
195      * alloc a buffer for this case.
196      */
197     if (kmac_out_len > EVP_MAX_MD_SIZE) {
198         *out = OPENSSL_zalloc(kmac_out_len);
199         if (*out == NULL)
200             return 0;
201     }
202     return 1;
203 }
204
205 /*
206  * Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
207  * Section 4. One-Step Key Derivation using MAC: i.e either
208  *     H(x) = HMAC-hash(salt, x) OR
209  *     H(x) = KMAC#(salt, x, outbits, CustomString='KDF')
210  */
211 static int SSKDF_mac_kdm(EVP_MAC_CTX *ctx_init,
212                          const unsigned char *kmac_custom,
213                          size_t kmac_custom_len, size_t kmac_out_len,
214                          const unsigned char *salt, size_t salt_len,
215                          const unsigned char *z, size_t z_len,
216                          const unsigned char *info, size_t info_len,
217                          unsigned char *derived_key, size_t derived_key_len)
218 {
219     int ret = 0;
220     size_t counter, out_len, len;
221     unsigned char c[4];
222     unsigned char mac_buf[EVP_MAX_MD_SIZE];
223     unsigned char *out = derived_key;
224     EVP_MAC_CTX *ctx = NULL;
225     unsigned char *mac = mac_buf, *kmac_buffer = NULL;
226
227     if (z_len > SSKDF_MAX_INLEN || info_len > SSKDF_MAX_INLEN
228             || derived_key_len > SSKDF_MAX_INLEN
229             || derived_key_len == 0)
230         return 0;
231
232     if (!kmac_init(ctx_init, kmac_custom, kmac_custom_len, kmac_out_len,
233                    derived_key_len, &kmac_buffer))
234         goto end;
235     if (kmac_buffer != NULL)
236         mac = kmac_buffer;
237
238     if (!EVP_MAC_init(ctx_init, salt, salt_len, NULL))
239         goto end;
240
241     out_len = EVP_MAC_CTX_get_mac_size(ctx_init); /* output size */
242     if (out_len <= 0)
243         goto end;
244     len = derived_key_len;
245
246     for (counter = 1;; counter++) {
247         c[0] = (unsigned char)((counter >> 24) & 0xff);
248         c[1] = (unsigned char)((counter >> 16) & 0xff);
249         c[2] = (unsigned char)((counter >> 8) & 0xff);
250         c[3] = (unsigned char)(counter & 0xff);
251
252         ctx = EVP_MAC_CTX_dup(ctx_init);
253         if (!(ctx != NULL
254                 && EVP_MAC_update(ctx, c, sizeof(c))
255                 && EVP_MAC_update(ctx, z, z_len)
256                 && EVP_MAC_update(ctx, info, info_len)))
257             goto end;
258         if (len >= out_len) {
259             if (!EVP_MAC_final(ctx, out, NULL, len))
260                 goto end;
261             out += out_len;
262             len -= out_len;
263             if (len == 0)
264                 break;
265         } else {
266             if (!EVP_MAC_final(ctx, mac, NULL, len))
267                 goto end;
268             memcpy(out, mac, len);
269             break;
270         }
271         EVP_MAC_CTX_free(ctx);
272         ctx = NULL;
273     }
274     ret = 1;
275 end:
276     if (kmac_buffer != NULL)
277         OPENSSL_clear_free(kmac_buffer, kmac_out_len);
278     else
279         OPENSSL_cleanse(mac_buf, sizeof(mac_buf));
280
281     EVP_MAC_CTX_free(ctx);
282     return ret;
283 }
284
285 static void *sskdf_new(void *provctx)
286 {
287     KDF_SSKDF *ctx;
288
289     if (!ossl_prov_is_running())
290         return NULL;
291
292     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL)
293         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
294     ctx->provctx = provctx;
295     return ctx;
296 }
297
298 static void sskdf_reset(void *vctx)
299 {
300     KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
301     void *provctx = ctx->provctx;
302
303     EVP_MAC_CTX_free(ctx->macctx);
304     ossl_prov_digest_reset(&ctx->digest);
305     OPENSSL_clear_free(ctx->secret, ctx->secret_len);
306     OPENSSL_clear_free(ctx->info, ctx->info_len);
307     OPENSSL_clear_free(ctx->salt, ctx->salt_len);
308     memset(ctx, 0, sizeof(*ctx));
309     ctx->provctx = provctx;
310 }
311
312 static void sskdf_free(void *vctx)
313 {
314     KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
315
316     if (ctx != NULL) {
317         sskdf_reset(ctx);
318         OPENSSL_free(ctx);
319     }
320 }
321
322 static int sskdf_set_buffer(unsigned char **out, size_t *out_len,
323                             const OSSL_PARAM *p)
324 {
325     if (p->data == NULL || p->data_size == 0)
326         return 1;
327     OPENSSL_free(*out);
328     *out = NULL;
329     return OSSL_PARAM_get_octet_string(p, (void **)out, 0, out_len);
330 }
331
332 static size_t sskdf_size(KDF_SSKDF *ctx)
333 {
334     int len;
335     const EVP_MD *md = ossl_prov_digest_md(&ctx->digest);
336
337     if (md == NULL) {
338         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
339         return 0;
340     }
341     len = EVP_MD_size(md);
342     return (len <= 0) ? 0 : (size_t)len;
343 }
344
345 static int sskdf_derive(void *vctx, unsigned char *key, size_t keylen,
346                         const OSSL_PARAM params[])
347 {
348     KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
349     const EVP_MD *md;
350
351     if (!ossl_prov_is_running() || !sskdf_set_ctx_params(ctx, params))
352         return 0;
353     if (ctx->secret == NULL) {
354         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SECRET);
355         return 0;
356     }
357     md = ossl_prov_digest_md(&ctx->digest);
358
359     if (ctx->macctx != NULL) {
360         /* H(x) = KMAC or H(x) = HMAC */
361         int ret;
362         const unsigned char *custom = NULL;
363         size_t custom_len = 0;
364         int default_salt_len;
365         EVP_MAC *mac = EVP_MAC_CTX_mac(ctx->macctx);
366
367         if (EVP_MAC_is_a(mac, OSSL_MAC_NAME_HMAC)) {
368             /* H(x) = HMAC(x, salt, hash) */
369             if (md == NULL) {
370                 ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
371                 return 0;
372             }
373             default_salt_len = EVP_MD_size(md);
374             if (default_salt_len <= 0)
375                 return 0;
376         } else if (EVP_MAC_is_a(mac, OSSL_MAC_NAME_KMAC128)
377                    || EVP_MAC_is_a(mac, OSSL_MAC_NAME_KMAC256)) {
378             /* H(x) = KMACzzz(x, salt, custom) */
379             custom = kmac_custom_str;
380             custom_len = sizeof(kmac_custom_str);
381             if (EVP_MAC_is_a(mac, OSSL_MAC_NAME_KMAC128))
382                 default_salt_len = SSKDF_KMAC128_DEFAULT_SALT_SIZE;
383             else
384                 default_salt_len = SSKDF_KMAC256_DEFAULT_SALT_SIZE;
385         } else {
386             ERR_raise(ERR_LIB_PROV, PROV_R_UNSUPPORTED_MAC_TYPE);
387             return 0;
388         }
389         /* If no salt is set then use a default_salt of zeros */
390         if (ctx->salt == NULL || ctx->salt_len <= 0) {
391             ctx->salt = OPENSSL_zalloc(default_salt_len);
392             if (ctx->salt == NULL) {
393                 ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
394                 return 0;
395             }
396             ctx->salt_len = default_salt_len;
397         }
398         ret = SSKDF_mac_kdm(ctx->macctx,
399                             custom, custom_len, ctx->out_len,
400                             ctx->salt, ctx->salt_len,
401                             ctx->secret, ctx->secret_len,
402                             ctx->info, ctx->info_len, key, keylen);
403         return ret;
404     } else {
405         /* H(x) = hash */
406         if (md == NULL) {
407             ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
408             return 0;
409         }
410         return SSKDF_hash_kdm(md, ctx->secret, ctx->secret_len,
411                               ctx->info, ctx->info_len, 0, key, keylen);
412     }
413 }
414
415 static int x963kdf_derive(void *vctx, unsigned char *key, size_t keylen,
416                           const OSSL_PARAM params[])
417 {
418     KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
419     const EVP_MD *md;
420
421     if (!ossl_prov_is_running() || !sskdf_set_ctx_params(ctx, params))
422         return 0;
423
424     if (ctx->secret == NULL) {
425         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SECRET);
426         return 0;
427     }
428
429     if (ctx->macctx != NULL) {
430         ERR_raise(ERR_LIB_PROV, PROV_R_NOT_SUPPORTED);
431         return 0;
432     }
433
434     /* H(x) = hash */
435     md = ossl_prov_digest_md(&ctx->digest);
436     if (md == NULL) {
437         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
438         return 0;
439     }
440
441     return SSKDF_hash_kdm(md, ctx->secret, ctx->secret_len,
442                           ctx->info, ctx->info_len, 1, key, keylen);
443 }
444
445 static int sskdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
446 {
447     const OSSL_PARAM *p;
448     KDF_SSKDF *ctx = vctx;
449     OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
450     size_t sz;
451
452     if (!ossl_prov_digest_load_from_params(&ctx->digest, params, libctx))
453         return 0;
454
455     if (!ossl_prov_macctx_load_from_params(&ctx->macctx, params,
456                                            NULL, NULL, NULL, libctx))
457         return 0;
458
459     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SECRET)) != NULL
460         || (p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY)) != NULL)
461         if (!sskdf_set_buffer(&ctx->secret, &ctx->secret_len, p))
462             return 0;
463
464     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_INFO)) != NULL)
465         if (!sskdf_set_buffer(&ctx->info, &ctx->info_len, p))
466             return 0;
467
468     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT)) != NULL)
469         if (!sskdf_set_buffer(&ctx->salt, &ctx->salt_len, p))
470             return 0;
471
472     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_MAC_SIZE))
473         != NULL) {
474         if (!OSSL_PARAM_get_size_t(p, &sz) || sz == 0)
475             return 0;
476         ctx->out_len = sz;
477     }
478     return 1;
479 }
480
481 static const OSSL_PARAM *sskdf_settable_ctx_params(ossl_unused void *ctx,
482                                                    ossl_unused void *provctx)
483 {
484     static const OSSL_PARAM known_settable_ctx_params[] = {
485         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SECRET, NULL, 0),
486         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),
487         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_INFO, NULL, 0),
488         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
489         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
490         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MAC, NULL, 0),
491         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
492         OSSL_PARAM_size_t(OSSL_KDF_PARAM_MAC_SIZE, NULL),
493         OSSL_PARAM_END
494     };
495     return known_settable_ctx_params;
496 }
497
498 static int sskdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
499 {
500     KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
501     OSSL_PARAM *p;
502
503     if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
504         return OSSL_PARAM_set_size_t(p, sskdf_size(ctx));
505     return -2;
506 }
507
508 static const OSSL_PARAM *sskdf_gettable_ctx_params(ossl_unused void *ctx,
509                                                    ossl_unused void *provctx)
510 {
511     static const OSSL_PARAM known_gettable_ctx_params[] = {
512         OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
513         OSSL_PARAM_END
514     };
515     return known_gettable_ctx_params;
516 }
517
518 const OSSL_DISPATCH ossl_kdf_sskdf_functions[] = {
519     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))sskdf_new },
520     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))sskdf_free },
521     { OSSL_FUNC_KDF_RESET, (void(*)(void))sskdf_reset },
522     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))sskdf_derive },
523     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
524       (void(*)(void))sskdf_settable_ctx_params },
525     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))sskdf_set_ctx_params },
526     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
527       (void(*)(void))sskdf_gettable_ctx_params },
528     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))sskdf_get_ctx_params },
529     { 0, NULL }
530 };
531
532 const OSSL_DISPATCH ossl_kdf_x963_kdf_functions[] = {
533     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))sskdf_new },
534     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))sskdf_free },
535     { OSSL_FUNC_KDF_RESET, (void(*)(void))sskdf_reset },
536     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))x963kdf_derive },
537     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
538       (void(*)(void))sskdf_settable_ctx_params },
539     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))sskdf_set_ctx_params },
540     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
541       (void(*)(void))sskdf_gettable_ctx_params },
542     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))sskdf_get_ctx_params },
543     { 0, NULL }
544 };