OSSL_PARAM_construct_utf8_string computes the string length.
[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, 0);
227     }
228     params[params_n++] =
229         OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (void *)salt,
230                                           salt_len);
231     params[params_n] = OSSL_PARAM_construct_end();
232
233     if (!EVP_MAC_CTX_set_params(ctx_init, params))
234         goto end;
235
236     if (!kmac_init(ctx_init, kmac_custom, kmac_custom_len, kmac_out_len,
237                    derived_key_len, &kmac_buffer))
238         goto end;
239     if (kmac_buffer != NULL)
240         mac = kmac_buffer;
241
242     if (!EVP_MAC_init(ctx_init))
243         goto end;
244
245     out_len = EVP_MAC_size(ctx_init); /* output size */
246     if (out_len <= 0)
247         goto end;
248     len = derived_key_len;
249
250     for (counter = 1;; counter++) {
251         c[0] = (unsigned char)((counter >> 24) & 0xff);
252         c[1] = (unsigned char)((counter >> 16) & 0xff);
253         c[2] = (unsigned char)((counter >> 8) & 0xff);
254         c[3] = (unsigned char)(counter & 0xff);
255
256         ctx = EVP_MAC_CTX_dup(ctx_init);
257         if (!(ctx != NULL
258                 && EVP_MAC_update(ctx, c, sizeof(c))
259                 && EVP_MAC_update(ctx, z, z_len)
260                 && EVP_MAC_update(ctx, info, info_len)))
261             goto end;
262         if (len >= out_len) {
263             if (!EVP_MAC_final(ctx, out, NULL, len))
264                 goto end;
265             out += out_len;
266             len -= out_len;
267             if (len == 0)
268                 break;
269         } else {
270             if (!EVP_MAC_final(ctx, mac, NULL, len))
271                 goto end;
272             memcpy(out, mac, len);
273             break;
274         }
275         EVP_MAC_CTX_free(ctx);
276         ctx = NULL;
277     }
278     ret = 1;
279 end:
280     if (kmac_buffer != NULL)
281         OPENSSL_clear_free(kmac_buffer, kmac_out_len);
282     else
283         OPENSSL_cleanse(mac_buf, sizeof(mac_buf));
284
285     EVP_MAC_CTX_free(ctx);
286     EVP_MAC_CTX_free(ctx_init);
287     return ret;
288 }
289
290 static EVP_KDF_IMPL *sskdf_new(void)
291 {
292     EVP_KDF_IMPL *impl;
293
294     if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
295         KDFerr(KDF_F_SSKDF_NEW, ERR_R_MALLOC_FAILURE);
296     return impl;
297 }
298
299 static void sskdf_reset(EVP_KDF_IMPL *impl)
300 {
301     OPENSSL_clear_free(impl->secret, impl->secret_len);
302     OPENSSL_clear_free(impl->info, impl->info_len);
303     OPENSSL_clear_free(impl->salt, impl->salt_len);
304     EVP_MAC_free(impl->mac);
305 #if 0                    /* TODO(3.0) When we switch to fetched MDs */
306     EVP_MD_meth_free(impl->md);
307 #endif
308     memset(impl, 0, sizeof(*impl));
309 }
310
311 static void sskdf_free(EVP_KDF_IMPL *impl)
312 {
313     sskdf_reset(impl);
314     OPENSSL_free(impl);
315 }
316
317 static int sskdf_set_buffer(va_list args, unsigned char **out, size_t *out_len)
318 {
319     const unsigned char *p;
320     size_t len;
321
322     p = va_arg(args, const unsigned char *);
323     len = va_arg(args, size_t);
324     if (len == 0 || p == NULL)
325         return 1;
326
327     OPENSSL_free(*out);
328     *out = OPENSSL_memdup(p, len);
329     if (*out == NULL)
330         return 0;
331
332     *out_len = len;
333     return 1;
334 }
335
336 static int sskdf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
337 {
338     const EVP_MD *md;
339
340     switch (cmd) {
341     case EVP_KDF_CTRL_SET_KEY:
342         return sskdf_set_buffer(args, &impl->secret, &impl->secret_len);
343
344     case EVP_KDF_CTRL_SET_SSKDF_INFO:
345         return sskdf_set_buffer(args, &impl->info, &impl->info_len);
346
347     case EVP_KDF_CTRL_SET_MD:
348         md = va_arg(args, const EVP_MD *);
349         if (md == NULL)
350             return 0;
351
352 #if 0                    /* TODO(3.0) When we switch to fetched MDs */
353         EVP_MD_meth_free(impl->md);
354 #endif
355         impl->md = md;
356         return 1;
357
358     case EVP_KDF_CTRL_SET_MAC:
359         {
360             const char *name;
361             EVP_MAC *mac;
362
363             name = va_arg(args, const char *);
364             if (name == NULL)
365                 return 0;
366
367             EVP_MAC_free(impl->mac);
368             impl->mac = NULL;
369
370             /*
371              * TODO(3.0) add support for OPENSSL_CTX and properties in KDFs
372              */
373             mac = EVP_MAC_fetch(NULL, name, NULL);
374             if (mac == NULL)
375                 return 0;
376
377             impl->mac = mac;
378             return 1;
379         }
380     case EVP_KDF_CTRL_SET_SALT:
381         return sskdf_set_buffer(args, &impl->salt, &impl->salt_len);
382
383     case EVP_KDF_CTRL_SET_MAC_SIZE:
384         impl->out_len = va_arg(args, size_t);
385         return 1;
386
387     default:
388         return -2;
389     }
390 }
391
392 static int sskdf_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
393                           const char *value)
394 {
395     if (strcmp(type, "secret") == 0 || strcmp(type, "key") == 0)
396          return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_KEY,
397                              value);
398
399     if (strcmp(type, "hexsecret") == 0 || strcmp(type, "hexkey") == 0)
400         return kdf_hex2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_KEY,
401                             value);
402
403     if (strcmp(type, "info") == 0)
404         return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SSKDF_INFO,
405                             value);
406
407     if (strcmp(type, "hexinfo") == 0)
408         return kdf_hex2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SSKDF_INFO,
409                             value);
410
411     if (strcmp(type, "digest") == 0)
412         return kdf_md2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
413
414     if (strcmp(type, "mac") == 0)
415         return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_MAC, value);
416
417     if (strcmp(type, "salt") == 0)
418         return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
419
420     if (strcmp(type, "hexsalt") == 0)
421         return kdf_hex2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
422
423
424     if (strcmp(type, "maclen") == 0) {
425         int val = atoi(value);
426         if (val < 0) {
427             KDFerr(KDF_F_SSKDF_CTRL_STR, KDF_R_VALUE_ERROR);
428             return 0;
429         }
430         return call_ctrl(sskdf_ctrl, impl, EVP_KDF_CTRL_SET_MAC_SIZE,
431                          (size_t)val);
432     }
433     return -2;
434 }
435
436 static size_t sskdf_size(EVP_KDF_IMPL *impl)
437 {
438     int len;
439
440     if (impl->md == NULL) {
441         KDFerr(KDF_F_SSKDF_SIZE, KDF_R_MISSING_MESSAGE_DIGEST);
442         return 0;
443     }
444     len = EVP_MD_size(impl->md);
445     return (len <= 0) ? 0 : (size_t)len;
446 }
447
448 static int sskdf_derive(EVP_KDF_IMPL *impl, unsigned char *key, size_t keylen)
449 {
450     if (impl->secret == NULL) {
451         KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_MISSING_SECRET);
452         return 0;
453     }
454
455     if (impl->mac != NULL) {
456         /* H(x) = KMAC or H(x) = HMAC */
457         int ret;
458         const unsigned char *custom = NULL;
459         size_t custom_len = 0;
460         const char *macname;
461         int default_salt_len;
462
463         /*
464          * TODO(3.0) investigate the necessity to have all these controls.
465          * Why does KMAC require a salt length that's shorter than the MD
466          * block size?
467          */
468         macname = EVP_MAC_name(impl->mac);
469         if (strcmp(macname, OSSL_MAC_NAME_HMAC) == 0) {
470             /* H(x) = HMAC(x, salt, hash) */
471             if (impl->md == NULL) {
472                 KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
473                 return 0;
474             }
475             default_salt_len = EVP_MD_block_size(impl->md);
476             if (default_salt_len <= 0)
477                 return 0;
478         } else if (strcmp(macname, OSSL_MAC_NAME_KMAC128) == 0
479                    || strcmp(macname, OSSL_MAC_NAME_KMAC256) == 0) {
480             /* H(x) = KMACzzz(x, salt, custom) */
481             custom = kmac_custom_str;
482             custom_len = sizeof(kmac_custom_str);
483             if (strcmp(macname, OSSL_MAC_NAME_KMAC128) == 0)
484                 default_salt_len = SSKDF_KMAC128_DEFAULT_SALT_SIZE;
485             else
486                 default_salt_len = SSKDF_KMAC256_DEFAULT_SALT_SIZE;
487         } else {
488             KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_UNSUPPORTED_MAC_TYPE);
489             return 0;
490         }
491         /* If no salt is set then use a default_salt of zeros */
492         if (impl->salt == NULL || impl->salt_len <= 0) {
493             impl->salt = OPENSSL_zalloc(default_salt_len);
494             if (impl->salt == NULL) {
495                 KDFerr(KDF_F_SSKDF_DERIVE, ERR_R_MALLOC_FAILURE);
496                 return 0;
497             }
498             impl->salt_len = default_salt_len;
499         }
500         ret = SSKDF_mac_kdm(impl->mac, impl->md,
501                             custom, custom_len, impl->out_len,
502                             impl->salt, impl->salt_len,
503                             impl->secret, impl->secret_len,
504                             impl->info, impl->info_len, key, keylen);
505         return ret;
506     } else {
507         /* H(x) = hash */
508         if (impl->md == NULL) {
509             KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
510             return 0;
511         }
512         return SSKDF_hash_kdm(impl->md, impl->secret, impl->secret_len,
513                               impl->info, impl->info_len, 0, key, keylen);
514     }
515 }
516
517 static int x963kdf_derive(EVP_KDF_IMPL *impl, unsigned char *key, size_t keylen)
518 {
519     if (impl->secret == NULL) {
520         KDFerr(KDF_F_X963KDF_DERIVE, KDF_R_MISSING_SECRET);
521         return 0;
522     }
523
524     if (impl->mac != NULL) {
525         KDFerr(KDF_F_X963KDF_DERIVE, KDF_R_NOT_SUPPORTED);
526         return 0;
527     } else {
528         /* H(x) = hash */
529         if (impl->md == NULL) {
530             KDFerr(KDF_F_X963KDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
531             return 0;
532         }
533         return SSKDF_hash_kdm(impl->md, impl->secret, impl->secret_len,
534                               impl->info, impl->info_len, 1, key, keylen);
535     }
536 }
537
538 const EVP_KDF ss_kdf_meth = {
539     EVP_KDF_SS,
540     sskdf_new,
541     sskdf_free,
542     sskdf_reset,
543     sskdf_ctrl,
544     sskdf_ctrl_str,
545     sskdf_size,
546     sskdf_derive
547 };
548
549 const EVP_KDF x963_kdf_meth = {
550     EVP_KDF_X963,
551     sskdf_new,
552     sskdf_free,
553     sskdf_reset,
554     sskdf_ctrl,
555     sskdf_ctrl_str,
556     sskdf_size,
557     x963kdf_derive
558 };