Get rid of the diversity of names for MAC parameters
[openssl.git] / crypto / kdf / sskdf.c
1 /*
2  * Copyright 2019 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/evp_int.h"
47 #include "kdf_local.h"
48
49 struct evp_kdf_impl_st {
50     EVP_MAC *mac;       /* H(x) = HMAC_hash OR H(x) = KMAC */
51     const EVP_MD *md;   /* H(x) = hash OR when H(x) = HMAC_hash */
52     unsigned char *secret;
53     size_t secret_len;
54     unsigned char *info;
55     size_t info_len;
56     unsigned char *salt;
57     size_t salt_len;
58     size_t out_len; /* optional KMAC parameter */
59 };
60
61 #define SSKDF_MAX_INLEN (1<<30)
62 #define SSKDF_KMAC128_DEFAULT_SALT_SIZE (168 - 4)
63 #define SSKDF_KMAC256_DEFAULT_SALT_SIZE (136 - 4)
64
65 /* KMAC uses a Customisation string of 'KDF' */
66 static const unsigned char kmac_custom_str[] = { 0x4B, 0x44, 0x46 };
67
68 /*
69  * Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
70  * Section 4. One-Step Key Derivation using H(x) = hash(x)
71  * Note: X9.63 also uses this code with the only difference being that the
72  * counter is appended to the secret 'z'.
73  * i.e.
74  *   result[i] = Hash(counter || z || info) for One Step OR
75  *   result[i] = Hash(z || counter || info) for X9.63.
76  */
77 static int SSKDF_hash_kdm(const EVP_MD *kdf_md,
78                           const unsigned char *z, size_t z_len,
79                           const unsigned char *info, size_t info_len,
80                           unsigned int append_ctr,
81                           unsigned char *derived_key, size_t derived_key_len)
82 {
83     int ret = 0, hlen;
84     size_t counter, out_len, len = derived_key_len;
85     unsigned char c[4];
86     unsigned char mac[EVP_MAX_MD_SIZE];
87     unsigned char *out = derived_key;
88     EVP_MD_CTX *ctx = NULL, *ctx_init = NULL;
89
90     if (z_len > SSKDF_MAX_INLEN || info_len > SSKDF_MAX_INLEN
91             || derived_key_len > SSKDF_MAX_INLEN
92             || derived_key_len == 0)
93         return 0;
94
95     hlen = EVP_MD_size(kdf_md);
96     if (hlen <= 0)
97         return 0;
98     out_len = (size_t)hlen;
99
100     ctx = EVP_MD_CTX_create();
101     ctx_init = EVP_MD_CTX_create();
102     if (ctx == NULL || ctx_init == NULL)
103         goto end;
104
105     if (!EVP_DigestInit(ctx_init, kdf_md))
106         goto end;
107
108     for (counter = 1;; counter++) {
109         c[0] = (unsigned char)((counter >> 24) & 0xff);
110         c[1] = (unsigned char)((counter >> 16) & 0xff);
111         c[2] = (unsigned char)((counter >> 8) & 0xff);
112         c[3] = (unsigned char)(counter & 0xff);
113
114         if (!(EVP_MD_CTX_copy_ex(ctx, ctx_init)
115                 && (append_ctr || EVP_DigestUpdate(ctx, c, sizeof(c)))
116                 && EVP_DigestUpdate(ctx, z, z_len)
117                 && (!append_ctr || EVP_DigestUpdate(ctx, c, sizeof(c)))
118                 && EVP_DigestUpdate(ctx, info, info_len)))
119             goto end;
120         if (len >= out_len) {
121             if (!EVP_DigestFinal_ex(ctx, out, NULL))
122                 goto end;
123             out += out_len;
124             len -= out_len;
125             if (len == 0)
126                 break;
127         } else {
128             if (!EVP_DigestFinal_ex(ctx, mac, NULL))
129                 goto end;
130             memcpy(out, mac, len);
131             break;
132         }
133     }
134     ret = 1;
135 end:
136     EVP_MD_CTX_destroy(ctx);
137     EVP_MD_CTX_destroy(ctx_init);
138     OPENSSL_cleanse(mac, sizeof(mac));
139     return ret;
140 }
141
142 static int kmac_init(EVP_MAC_CTX *ctx, const unsigned char *custom,
143                      size_t custom_len, size_t kmac_out_len,
144                      size_t derived_key_len, unsigned char **out)
145 {
146     OSSL_PARAM params[2];
147
148     /* Only KMAC has custom data - so return if not KMAC */
149     if (custom == NULL)
150         return 1;
151
152     params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_CUSTOM,
153                                                   (void *)custom, custom_len);
154     params[1] = OSSL_PARAM_construct_end();
155
156     if (!EVP_MAC_CTX_set_params(ctx, params))
157         return 0;
158
159     /* By default only do one iteration if kmac_out_len is not specified */
160     if (kmac_out_len == 0)
161         kmac_out_len = derived_key_len;
162     /* otherwise check the size is valid */
163     else if (!(kmac_out_len == derived_key_len
164             || kmac_out_len == 20
165             || kmac_out_len == 28
166             || kmac_out_len == 32
167             || kmac_out_len == 48
168             || kmac_out_len == 64))
169         return 0;
170
171     params[0] = OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_SIZE,
172                                             &kmac_out_len);
173
174     if (EVP_MAC_CTX_set_params(ctx, params) <= 0)
175         return 0;
176
177     /*
178      * For kmac the output buffer can be larger than EVP_MAX_MD_SIZE: so
179      * alloc a buffer for this case.
180      */
181     if (kmac_out_len > EVP_MAX_MD_SIZE) {
182         *out = OPENSSL_zalloc(kmac_out_len);
183         if (*out == NULL)
184             return 0;
185     }
186     return 1;
187 }
188
189 /*
190  * Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
191  * Section 4. One-Step Key Derivation using MAC: i.e either
192  *     H(x) = HMAC-hash(salt, x) OR
193  *     H(x) = KMAC#(salt, x, outbits, CustomString='KDF')
194  */
195 static int SSKDF_mac_kdm(EVP_MAC *kdf_mac, const EVP_MD *hmac_md,
196                          const unsigned char *kmac_custom,
197                          size_t kmac_custom_len, size_t kmac_out_len,
198                          const unsigned char *salt, size_t salt_len,
199                          const unsigned char *z, size_t z_len,
200                          const unsigned char *info, size_t info_len,
201                          unsigned char *derived_key, size_t derived_key_len)
202 {
203     int ret = 0;
204     size_t counter, out_len, len;
205     unsigned char c[4];
206     unsigned char mac_buf[EVP_MAX_MD_SIZE];
207     unsigned char *out = derived_key;
208     EVP_MAC_CTX *ctx = NULL, *ctx_init = NULL;
209     unsigned char *mac = mac_buf, *kmac_buffer = NULL;
210     OSSL_PARAM params[3];
211     size_t params_n = 0;
212
213     if (z_len > SSKDF_MAX_INLEN || info_len > SSKDF_MAX_INLEN
214             || derived_key_len > SSKDF_MAX_INLEN
215             || derived_key_len == 0)
216         return 0;
217
218     ctx_init = EVP_MAC_CTX_new(kdf_mac);
219     if (ctx_init == NULL)
220         goto end;
221
222     if (hmac_md != NULL) {
223         const char *mdname = EVP_MD_name(hmac_md);
224         params[params_n++] =
225             OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
226                                              (char *)mdname,
227                                              strlen(mdname) + 1);
228     }
229     params[params_n++] =
230         OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (void *)salt,
231                                           salt_len);
232     params[params_n] = OSSL_PARAM_construct_end();
233
234     if (!EVP_MAC_CTX_set_params(ctx_init, params))
235         goto end;
236
237     if (!kmac_init(ctx_init, kmac_custom, kmac_custom_len, kmac_out_len,
238                    derived_key_len, &kmac_buffer))
239         goto end;
240     if (kmac_buffer != NULL)
241         mac = kmac_buffer;
242
243     if (!EVP_MAC_init(ctx_init))
244         goto end;
245
246     out_len = EVP_MAC_size(ctx_init); /* output size */
247     if (out_len <= 0)
248         goto end;
249     len = derived_key_len;
250
251     for (counter = 1;; counter++) {
252         c[0] = (unsigned char)((counter >> 24) & 0xff);
253         c[1] = (unsigned char)((counter >> 16) & 0xff);
254         c[2] = (unsigned char)((counter >> 8) & 0xff);
255         c[3] = (unsigned char)(counter & 0xff);
256
257         ctx = EVP_MAC_CTX_dup(ctx_init);
258         if (!(ctx != NULL
259                 && EVP_MAC_update(ctx, c, sizeof(c))
260                 && EVP_MAC_update(ctx, z, z_len)
261                 && EVP_MAC_update(ctx, info, info_len)))
262             goto end;
263         if (len >= out_len) {
264             if (!EVP_MAC_final(ctx, out, NULL, len))
265                 goto end;
266             out += out_len;
267             len -= out_len;
268             if (len == 0)
269                 break;
270         } else {
271             if (!EVP_MAC_final(ctx, mac, NULL, len))
272                 goto end;
273             memcpy(out, mac, len);
274             break;
275         }
276         EVP_MAC_CTX_free(ctx);
277         ctx = NULL;
278     }
279     ret = 1;
280 end:
281     if (kmac_buffer != NULL)
282         OPENSSL_clear_free(kmac_buffer, kmac_out_len);
283     else
284         OPENSSL_cleanse(mac_buf, sizeof(mac_buf));
285
286     EVP_MAC_CTX_free(ctx);
287     EVP_MAC_CTX_free(ctx_init);
288     return ret;
289 }
290
291 static EVP_KDF_IMPL *sskdf_new(void)
292 {
293     EVP_KDF_IMPL *impl;
294
295     if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
296         KDFerr(KDF_F_SSKDF_NEW, ERR_R_MALLOC_FAILURE);
297     return impl;
298 }
299
300 static void sskdf_reset(EVP_KDF_IMPL *impl)
301 {
302     OPENSSL_clear_free(impl->secret, impl->secret_len);
303     OPENSSL_clear_free(impl->info, impl->info_len);
304     OPENSSL_clear_free(impl->salt, impl->salt_len);
305     EVP_MAC_free(impl->mac);
306 #if 0                    /* TODO(3.0) When we switch to fetched MDs */
307     EVP_MD_meth_free(impl->md);
308 #endif
309     memset(impl, 0, sizeof(*impl));
310 }
311
312 static void sskdf_free(EVP_KDF_IMPL *impl)
313 {
314     sskdf_reset(impl);
315     OPENSSL_free(impl);
316 }
317
318 static int sskdf_set_buffer(va_list args, unsigned char **out, size_t *out_len)
319 {
320     const unsigned char *p;
321     size_t len;
322
323     p = va_arg(args, const unsigned char *);
324     len = va_arg(args, size_t);
325     if (len == 0 || p == NULL)
326         return 1;
327
328     OPENSSL_free(*out);
329     *out = OPENSSL_memdup(p, len);
330     if (*out == NULL)
331         return 0;
332
333     *out_len = len;
334     return 1;
335 }
336
337 static int sskdf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
338 {
339     const EVP_MD *md;
340
341     switch (cmd) {
342     case EVP_KDF_CTRL_SET_KEY:
343         return sskdf_set_buffer(args, &impl->secret, &impl->secret_len);
344
345     case EVP_KDF_CTRL_SET_SSKDF_INFO:
346         return sskdf_set_buffer(args, &impl->info, &impl->info_len);
347
348     case EVP_KDF_CTRL_SET_MD:
349         md = va_arg(args, const EVP_MD *);
350         if (md == NULL)
351             return 0;
352
353 #if 0                    /* TODO(3.0) When we switch to fetched MDs */
354         EVP_MD_meth_free(impl->md);
355 #endif
356         impl->md = md;
357         return 1;
358
359     case EVP_KDF_CTRL_SET_MAC:
360         {
361             const char *name;
362             EVP_MAC *mac;
363
364             name = va_arg(args, const char *);
365             if (name == NULL)
366                 return 0;
367
368             EVP_MAC_free(impl->mac);
369             impl->mac = NULL;
370
371             /*
372              * TODO(3.0) add support for OPENSSL_CTX and properties in KDFs
373              */
374             mac = EVP_MAC_fetch(NULL, name, NULL);
375             if (mac == NULL)
376                 return 0;
377
378             impl->mac = mac;
379             return 1;
380         }
381     case EVP_KDF_CTRL_SET_SALT:
382         return sskdf_set_buffer(args, &impl->salt, &impl->salt_len);
383
384     case EVP_KDF_CTRL_SET_MAC_SIZE:
385         impl->out_len = va_arg(args, size_t);
386         return 1;
387
388     default:
389         return -2;
390     }
391 }
392
393 static int sskdf_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
394                           const char *value)
395 {
396     if (strcmp(type, "secret") == 0 || strcmp(type, "key") == 0)
397          return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_KEY,
398                              value);
399
400     if (strcmp(type, "hexsecret") == 0 || strcmp(type, "hexkey") == 0)
401         return kdf_hex2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_KEY,
402                             value);
403
404     if (strcmp(type, "info") == 0)
405         return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SSKDF_INFO,
406                             value);
407
408     if (strcmp(type, "hexinfo") == 0)
409         return kdf_hex2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SSKDF_INFO,
410                             value);
411
412     if (strcmp(type, "digest") == 0)
413         return kdf_md2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
414
415     if (strcmp(type, "mac") == 0)
416         return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_MAC, value);
417
418     if (strcmp(type, "salt") == 0)
419         return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
420
421     if (strcmp(type, "hexsalt") == 0)
422         return kdf_hex2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
423
424
425     if (strcmp(type, "maclen") == 0) {
426         int val = atoi(value);
427         if (val < 0) {
428             KDFerr(KDF_F_SSKDF_CTRL_STR, KDF_R_VALUE_ERROR);
429             return 0;
430         }
431         return call_ctrl(sskdf_ctrl, impl, EVP_KDF_CTRL_SET_MAC_SIZE,
432                          (size_t)val);
433     }
434     return -2;
435 }
436
437 static size_t sskdf_size(EVP_KDF_IMPL *impl)
438 {
439     int len;
440
441     if (impl->md == NULL) {
442         KDFerr(KDF_F_SSKDF_SIZE, KDF_R_MISSING_MESSAGE_DIGEST);
443         return 0;
444     }
445     len = EVP_MD_size(impl->md);
446     return (len <= 0) ? 0 : (size_t)len;
447 }
448
449 static int sskdf_derive(EVP_KDF_IMPL *impl, unsigned char *key, size_t keylen)
450 {
451     if (impl->secret == NULL) {
452         KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_MISSING_SECRET);
453         return 0;
454     }
455
456     if (impl->mac != NULL) {
457         /* H(x) = KMAC or H(x) = HMAC */
458         int ret;
459         const unsigned char *custom = NULL;
460         size_t custom_len = 0;
461         const char *macname;
462         int default_salt_len;
463
464         /*
465          * TODO(3.0) investigate the necessity to have all these controls.
466          * Why does KMAC require a salt length that's shorter than the MD
467          * block size?
468          */
469         macname = EVP_MAC_name(impl->mac);
470         if (strcmp(macname, OSSL_MAC_NAME_HMAC) == 0) {
471             /* H(x) = HMAC(x, salt, hash) */
472             if (impl->md == NULL) {
473                 KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
474                 return 0;
475             }
476             default_salt_len = EVP_MD_block_size(impl->md);
477             if (default_salt_len <= 0)
478                 return 0;
479         } else if (strcmp(macname, OSSL_MAC_NAME_KMAC128) == 0
480                    || strcmp(macname, OSSL_MAC_NAME_KMAC256) == 0) {
481             /* H(x) = KMACzzz(x, salt, custom) */
482             custom = kmac_custom_str;
483             custom_len = sizeof(kmac_custom_str);
484             if (strcmp(macname, OSSL_MAC_NAME_KMAC128) == 0)
485                 default_salt_len = SSKDF_KMAC128_DEFAULT_SALT_SIZE;
486             else
487                 default_salt_len = SSKDF_KMAC256_DEFAULT_SALT_SIZE;
488         } else {
489             KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_UNSUPPORTED_MAC_TYPE);
490             return 0;
491         }
492         /* If no salt is set then use a default_salt of zeros */
493         if (impl->salt == NULL || impl->salt_len <= 0) {
494             impl->salt = OPENSSL_zalloc(default_salt_len);
495             if (impl->salt == NULL) {
496                 KDFerr(KDF_F_SSKDF_DERIVE, ERR_R_MALLOC_FAILURE);
497                 return 0;
498             }
499             impl->salt_len = default_salt_len;
500         }
501         ret = SSKDF_mac_kdm(impl->mac, impl->md,
502                             custom, custom_len, impl->out_len,
503                             impl->salt, impl->salt_len,
504                             impl->secret, impl->secret_len,
505                             impl->info, impl->info_len, key, keylen);
506         return ret;
507     } else {
508         /* H(x) = hash */
509         if (impl->md == NULL) {
510             KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
511             return 0;
512         }
513         return SSKDF_hash_kdm(impl->md, impl->secret, impl->secret_len,
514                               impl->info, impl->info_len, 0, key, keylen);
515     }
516 }
517
518 static int x963kdf_derive(EVP_KDF_IMPL *impl, unsigned char *key, size_t keylen)
519 {
520     if (impl->secret == NULL) {
521         KDFerr(KDF_F_X963KDF_DERIVE, KDF_R_MISSING_SECRET);
522         return 0;
523     }
524
525     if (impl->mac != NULL) {
526         KDFerr(KDF_F_X963KDF_DERIVE, KDF_R_NOT_SUPPORTED);
527         return 0;
528     } else {
529         /* H(x) = hash */
530         if (impl->md == NULL) {
531             KDFerr(KDF_F_X963KDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
532             return 0;
533         }
534         return SSKDF_hash_kdm(impl->md, impl->secret, impl->secret_len,
535                               impl->info, impl->info_len, 1, key, keylen);
536     }
537 }
538
539 const EVP_KDF ss_kdf_meth = {
540     EVP_KDF_SS,
541     sskdf_new,
542     sskdf_free,
543     sskdf_reset,
544     sskdf_ctrl,
545     sskdf_ctrl_str,
546     sskdf_size,
547     sskdf_derive
548 };
549
550 const EVP_KDF x963_kdf_meth = {
551     EVP_KDF_X963,
552     sskdf_new,
553     sskdf_free,
554     sskdf_reset,
555     sskdf_ctrl,
556     sskdf_ctrl_str,
557     sskdf_size,
558     x963kdf_derive
559 };