Remove TODO comment from sskdf.c
[openssl.git] / providers / implementations / kdfs / sskdf.c
1 /*
2  * Copyright 2019-2020 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 "internal/cryptlib.h"
46 #include "internal/numbers.h"
47 #include "crypto/evp.h"
48 #include "prov/provider_ctx.h"
49 #include "prov/providercommon.h"
50 #include "prov/providercommonerr.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     OSSL_PARAM params[2], *p = params;
227
228     if (z_len > SSKDF_MAX_INLEN || info_len > SSKDF_MAX_INLEN
229             || derived_key_len > SSKDF_MAX_INLEN
230             || derived_key_len == 0)
231         return 0;
232
233     *p++ = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
234                                              (void *)salt, salt_len);
235     *p = OSSL_PARAM_construct_end();
236
237     if (!EVP_MAC_CTX_set_params(ctx_init, params))
238         goto end;
239
240     if (!kmac_init(ctx_init, kmac_custom, kmac_custom_len, kmac_out_len,
241                    derived_key_len, &kmac_buffer))
242         goto end;
243     if (kmac_buffer != NULL)
244         mac = kmac_buffer;
245
246     if (!EVP_MAC_init(ctx_init))
247         goto end;
248
249     out_len = EVP_MAC_size(ctx_init); /* output size */
250     if (out_len <= 0)
251         goto end;
252     len = derived_key_len;
253
254     for (counter = 1;; counter++) {
255         c[0] = (unsigned char)((counter >> 24) & 0xff);
256         c[1] = (unsigned char)((counter >> 16) & 0xff);
257         c[2] = (unsigned char)((counter >> 8) & 0xff);
258         c[3] = (unsigned char)(counter & 0xff);
259
260         ctx = EVP_MAC_CTX_dup(ctx_init);
261         if (!(ctx != NULL
262                 && EVP_MAC_update(ctx, c, sizeof(c))
263                 && EVP_MAC_update(ctx, z, z_len)
264                 && EVP_MAC_update(ctx, info, info_len)))
265             goto end;
266         if (len >= out_len) {
267             if (!EVP_MAC_final(ctx, out, NULL, len))
268                 goto end;
269             out += out_len;
270             len -= out_len;
271             if (len == 0)
272                 break;
273         } else {
274             if (!EVP_MAC_final(ctx, mac, NULL, len))
275                 goto end;
276             memcpy(out, mac, len);
277             break;
278         }
279         EVP_MAC_CTX_free(ctx);
280         ctx = NULL;
281     }
282     ret = 1;
283 end:
284     if (kmac_buffer != NULL)
285         OPENSSL_clear_free(kmac_buffer, kmac_out_len);
286     else
287         OPENSSL_cleanse(mac_buf, sizeof(mac_buf));
288
289     EVP_MAC_CTX_free(ctx);
290     return ret;
291 }
292
293 static void *sskdf_new(void *provctx)
294 {
295     KDF_SSKDF *ctx;
296
297     if (!ossl_prov_is_running())
298         return NULL;
299
300     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL)
301         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
302     ctx->provctx = provctx;
303     return ctx;
304 }
305
306 static void sskdf_reset(void *vctx)
307 {
308     KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
309     void *provctx = ctx->provctx;
310
311     EVP_MAC_CTX_free(ctx->macctx);
312     ossl_prov_digest_reset(&ctx->digest);
313     OPENSSL_clear_free(ctx->secret, ctx->secret_len);
314     OPENSSL_clear_free(ctx->info, ctx->info_len);
315     OPENSSL_clear_free(ctx->salt, ctx->salt_len);
316     memset(ctx, 0, sizeof(*ctx));
317     ctx->provctx = provctx;
318 }
319
320 static void sskdf_free(void *vctx)
321 {
322     KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
323
324     if (ctx != NULL) {
325         sskdf_reset(ctx);
326         OPENSSL_free(ctx);
327     }
328 }
329
330 static int sskdf_set_buffer(unsigned char **out, size_t *out_len,
331                             const OSSL_PARAM *p)
332 {
333     if (p->data == NULL || p->data_size == 0)
334         return 1;
335     OPENSSL_free(*out);
336     *out = NULL;
337     return OSSL_PARAM_get_octet_string(p, (void **)out, 0, out_len);
338 }
339
340 static size_t sskdf_size(KDF_SSKDF *ctx)
341 {
342     int len;
343     const EVP_MD *md = ossl_prov_digest_md(&ctx->digest);
344
345     if (md == NULL) {
346         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
347         return 0;
348     }
349     len = EVP_MD_size(md);
350     return (len <= 0) ? 0 : (size_t)len;
351 }
352
353 static int sskdf_derive(void *vctx, unsigned char *key, size_t keylen)
354 {
355     KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
356     const EVP_MD *md;
357
358     if (!ossl_prov_is_running())
359         return 0;
360     if (ctx->secret == NULL) {
361         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SECRET);
362         return 0;
363     }
364     md = ossl_prov_digest_md(&ctx->digest);
365
366     if (ctx->macctx != NULL) {
367         /* H(x) = KMAC or H(x) = HMAC */
368         int ret;
369         const unsigned char *custom = NULL;
370         size_t custom_len = 0;
371         int default_salt_len;
372         EVP_MAC *mac = EVP_MAC_CTX_mac(ctx->macctx);
373
374         if (EVP_MAC_is_a(mac, OSSL_MAC_NAME_HMAC)) {
375             /* H(x) = HMAC(x, salt, hash) */
376             if (md == NULL) {
377                 ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
378                 return 0;
379             }
380             default_salt_len = EVP_MD_size(md);
381             if (default_salt_len <= 0)
382                 return 0;
383         } else if (EVP_MAC_is_a(mac, OSSL_MAC_NAME_KMAC128)
384                    || EVP_MAC_is_a(mac, OSSL_MAC_NAME_KMAC256)) {
385             /* H(x) = KMACzzz(x, salt, custom) */
386             custom = kmac_custom_str;
387             custom_len = sizeof(kmac_custom_str);
388             if (EVP_MAC_is_a(mac, OSSL_MAC_NAME_KMAC128))
389                 default_salt_len = SSKDF_KMAC128_DEFAULT_SALT_SIZE;
390             else
391                 default_salt_len = SSKDF_KMAC256_DEFAULT_SALT_SIZE;
392         } else {
393             ERR_raise(ERR_LIB_PROV, PROV_R_UNSUPPORTED_MAC_TYPE);
394             return 0;
395         }
396         /* If no salt is set then use a default_salt of zeros */
397         if (ctx->salt == NULL || ctx->salt_len <= 0) {
398             ctx->salt = OPENSSL_zalloc(default_salt_len);
399             if (ctx->salt == NULL) {
400                 ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
401                 return 0;
402             }
403             ctx->salt_len = default_salt_len;
404         }
405         ret = SSKDF_mac_kdm(ctx->macctx,
406                             custom, custom_len, ctx->out_len,
407                             ctx->salt, ctx->salt_len,
408                             ctx->secret, ctx->secret_len,
409                             ctx->info, ctx->info_len, key, keylen);
410         return ret;
411     } else {
412         /* H(x) = hash */
413         if (md == NULL) {
414             ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
415             return 0;
416         }
417         return SSKDF_hash_kdm(md, ctx->secret, ctx->secret_len,
418                               ctx->info, ctx->info_len, 0, key, keylen);
419     }
420 }
421
422 static int x963kdf_derive(void *vctx, unsigned char *key, size_t keylen)
423 {
424     KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
425     const EVP_MD *md;
426
427     if (!ossl_prov_is_running())
428         return 0;
429
430     if (ctx->secret == NULL) {
431         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SECRET);
432         return 0;
433     }
434
435     if (ctx->macctx != NULL) {
436         ERR_raise(ERR_LIB_PROV, PROV_R_NOT_SUPPORTED);
437         return 0;
438     }
439
440     /* H(x) = hash */
441     md = ossl_prov_digest_md(&ctx->digest);
442     if (md == NULL) {
443         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
444         return 0;
445     }
446
447     return SSKDF_hash_kdm(md, ctx->secret, ctx->secret_len,
448                           ctx->info, ctx->info_len, 1, key, keylen);
449 }
450
451 static int sskdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
452 {
453     const OSSL_PARAM *p;
454     KDF_SSKDF *ctx = vctx;
455     OPENSSL_CTX *libctx = PROV_LIBRARY_CONTEXT_OF(ctx->provctx);
456     size_t sz;
457
458     if (!ossl_prov_digest_load_from_params(&ctx->digest, params, libctx))
459         return 0;
460
461     if (!ossl_prov_macctx_load_from_params(&ctx->macctx, params,
462                                            NULL, NULL, NULL, libctx))
463         return 0;
464
465     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SECRET)) != NULL
466         || (p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY)) != NULL)
467         if (!sskdf_set_buffer(&ctx->secret, &ctx->secret_len, p))
468             return 0;
469
470     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_INFO)) != NULL)
471         if (!sskdf_set_buffer(&ctx->info, &ctx->info_len, p))
472             return 0;
473
474     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT)) != NULL)
475         if (!sskdf_set_buffer(&ctx->salt, &ctx->salt_len, p))
476             return 0;
477
478     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_MAC_SIZE))
479         != NULL) {
480         if (!OSSL_PARAM_get_size_t(p, &sz) || sz == 0)
481             return 0;
482         ctx->out_len = sz;
483     }
484     return 1;
485 }
486
487 static const OSSL_PARAM *sskdf_settable_ctx_params(ossl_unused void *provctx)
488 {
489     static const OSSL_PARAM known_settable_ctx_params[] = {
490         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SECRET, NULL, 0),
491         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),
492         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_INFO, NULL, 0),
493         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
494         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
495         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MAC, NULL, 0),
496         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
497         OSSL_PARAM_size_t(OSSL_KDF_PARAM_MAC_SIZE, NULL),
498         OSSL_PARAM_END
499     };
500     return known_settable_ctx_params;
501 }
502
503 static int sskdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
504 {
505     KDF_SSKDF *ctx = (KDF_SSKDF *)vctx;
506     OSSL_PARAM *p;
507
508     if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
509         return OSSL_PARAM_set_size_t(p, sskdf_size(ctx));
510     return -2;
511 }
512
513 static const OSSL_PARAM *sskdf_gettable_ctx_params(ossl_unused void *provctx)
514 {
515     static const OSSL_PARAM known_gettable_ctx_params[] = {
516         OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
517         OSSL_PARAM_END
518     };
519     return known_gettable_ctx_params;
520 }
521
522 const OSSL_DISPATCH kdf_sskdf_functions[] = {
523     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))sskdf_new },
524     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))sskdf_free },
525     { OSSL_FUNC_KDF_RESET, (void(*)(void))sskdf_reset },
526     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))sskdf_derive },
527     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
528       (void(*)(void))sskdf_settable_ctx_params },
529     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))sskdf_set_ctx_params },
530     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
531       (void(*)(void))sskdf_gettable_ctx_params },
532     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))sskdf_get_ctx_params },
533     { 0, NULL }
534 };
535
536 const OSSL_DISPATCH kdf_x963_kdf_functions[] = {
537     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))sskdf_new },
538     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))sskdf_free },
539     { OSSL_FUNC_KDF_RESET, (void(*)(void))sskdf_reset },
540     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))x963kdf_derive },
541     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
542       (void(*)(void))sskdf_settable_ctx_params },
543     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))sskdf_set_ctx_params },
544     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
545       (void(*)(void))sskdf_gettable_ctx_params },
546     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))sskdf_get_ctx_params },
547     { 0, NULL }
548 };