xref: /freebsd/crypto/openssl/providers/implementations/kdfs/hkdf.c (revision 95eb4b873b6a8b527c5bd78d7191975dfca38998)
1 /*
2  * Copyright 2016-2024 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 /*
11  * HMAC low level APIs are deprecated for public use, but still ok for internal
12  * use.
13  */
14 #include "internal/deprecated.h"
15 
16 #include <stdlib.h>
17 #include <stdarg.h>
18 #include <string.h>
19 #include <openssl/hmac.h>
20 #include <openssl/evp.h>
21 #include <openssl/kdf.h>
22 #include <openssl/core_names.h>
23 #include <openssl/proverr.h>
24 #include "internal/cryptlib.h"
25 #include "internal/numbers.h"
26 #include "internal/packet.h"
27 #include "crypto/evp.h"
28 #include "prov/provider_ctx.h"
29 #include "prov/providercommon.h"
30 #include "prov/implementations.h"
31 #include "prov/provider_util.h"
32 #include "e_os.h"
33 
34 #define HKDF_MAXBUF 2048
35 #define HKDF_MAXINFO (32*1024)
36 
37 static OSSL_FUNC_kdf_newctx_fn kdf_hkdf_new;
38 static OSSL_FUNC_kdf_freectx_fn kdf_hkdf_free;
39 static OSSL_FUNC_kdf_reset_fn kdf_hkdf_reset;
40 static OSSL_FUNC_kdf_derive_fn kdf_hkdf_derive;
41 static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_hkdf_settable_ctx_params;
42 static OSSL_FUNC_kdf_set_ctx_params_fn kdf_hkdf_set_ctx_params;
43 static OSSL_FUNC_kdf_gettable_ctx_params_fn kdf_hkdf_gettable_ctx_params;
44 static OSSL_FUNC_kdf_get_ctx_params_fn kdf_hkdf_get_ctx_params;
45 static OSSL_FUNC_kdf_derive_fn kdf_tls1_3_derive;
46 static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_tls1_3_settable_ctx_params;
47 static OSSL_FUNC_kdf_set_ctx_params_fn kdf_tls1_3_set_ctx_params;
48 
49 static int HKDF(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
50                 const unsigned char *salt, size_t salt_len,
51                 const unsigned char *key, size_t key_len,
52                 const unsigned char *info, size_t info_len,
53                 unsigned char *okm, size_t okm_len);
54 static int HKDF_Extract(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
55                         const unsigned char *salt, size_t salt_len,
56                         const unsigned char *ikm, size_t ikm_len,
57                         unsigned char *prk, size_t prk_len);
58 static int HKDF_Expand(const EVP_MD *evp_md,
59                        const unsigned char *prk, size_t prk_len,
60                        const unsigned char *info, size_t info_len,
61                        unsigned char *okm, size_t okm_len);
62 
63 /* Settable context parameters that are common across HKDF and the TLS KDF */
64 #define HKDF_COMMON_SETTABLES                                           \
65         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MODE, NULL, 0),           \
66         OSSL_PARAM_int(OSSL_KDF_PARAM_MODE, NULL),                      \
67         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),     \
68         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),         \
69         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),           \
70         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0)
71 
72 typedef struct {
73     void *provctx;
74     int mode;
75     PROV_DIGEST digest;
76     unsigned char *salt;
77     size_t salt_len;
78     unsigned char *key;
79     size_t key_len;
80     unsigned char *prefix;
81     size_t prefix_len;
82     unsigned char *label;
83     size_t label_len;
84     unsigned char *data;
85     size_t data_len;
86     unsigned char *info;
87     size_t info_len;
88 } KDF_HKDF;
89 
90 static void *kdf_hkdf_new(void *provctx)
91 {
92     KDF_HKDF *ctx;
93 
94     if (!ossl_prov_is_running())
95         return NULL;
96 
97     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL)
98         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
99     else
100         ctx->provctx = provctx;
101     return ctx;
102 }
103 
104 static void kdf_hkdf_free(void *vctx)
105 {
106     KDF_HKDF *ctx = (KDF_HKDF *)vctx;
107 
108     if (ctx != NULL) {
109         kdf_hkdf_reset(ctx);
110         OPENSSL_free(ctx);
111     }
112 }
113 
114 static void kdf_hkdf_reset(void *vctx)
115 {
116     KDF_HKDF *ctx = (KDF_HKDF *)vctx;
117     void *provctx = ctx->provctx;
118 
119     ossl_prov_digest_reset(&ctx->digest);
120     OPENSSL_free(ctx->salt);
121     OPENSSL_free(ctx->prefix);
122     OPENSSL_free(ctx->label);
123     OPENSSL_clear_free(ctx->data, ctx->data_len);
124     OPENSSL_clear_free(ctx->key, ctx->key_len);
125     OPENSSL_clear_free(ctx->info, ctx->info_len);
126     memset(ctx, 0, sizeof(*ctx));
127     ctx->provctx = provctx;
128 }
129 
130 static size_t kdf_hkdf_size(KDF_HKDF *ctx)
131 {
132     int sz;
133     const EVP_MD *md = ossl_prov_digest_md(&ctx->digest);
134 
135     if (ctx->mode != EVP_KDF_HKDF_MODE_EXTRACT_ONLY)
136         return SIZE_MAX;
137 
138     if (md == NULL) {
139         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
140         return 0;
141     }
142     sz = EVP_MD_get_size(md);
143     if (sz < 0)
144         return 0;
145 
146     return sz;
147 }
148 
149 static int kdf_hkdf_derive(void *vctx, unsigned char *key, size_t keylen,
150                            const OSSL_PARAM params[])
151 {
152     KDF_HKDF *ctx = (KDF_HKDF *)vctx;
153     OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
154     const EVP_MD *md;
155 
156     if (!ossl_prov_is_running() || !kdf_hkdf_set_ctx_params(ctx, params))
157         return 0;
158 
159     md = ossl_prov_digest_md(&ctx->digest);
160     if (md == NULL) {
161         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
162         return 0;
163     }
164     if (ctx->key == NULL) {
165         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY);
166         return 0;
167     }
168     if (keylen == 0) {
169         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
170         return 0;
171     }
172 
173     switch (ctx->mode) {
174     case EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND:
175     default:
176         return HKDF(libctx, md, ctx->salt, ctx->salt_len,
177                     ctx->key, ctx->key_len, ctx->info, ctx->info_len, key, keylen);
178 
179     case EVP_KDF_HKDF_MODE_EXTRACT_ONLY:
180         return HKDF_Extract(libctx, md, ctx->salt, ctx->salt_len,
181                             ctx->key, ctx->key_len, key, keylen);
182 
183     case EVP_KDF_HKDF_MODE_EXPAND_ONLY:
184         return HKDF_Expand(md, ctx->key, ctx->key_len, ctx->info,
185                            ctx->info_len, key, keylen);
186     }
187 }
188 
189 static int hkdf_common_set_ctx_params(KDF_HKDF *ctx, const OSSL_PARAM params[])
190 {
191     OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
192     const OSSL_PARAM *p;
193     int n;
194 
195     if (params == NULL)
196         return 1;
197 
198     if (!ossl_prov_digest_load_from_params(&ctx->digest, params, libctx))
199         return 0;
200 
201     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_MODE)) != NULL) {
202         if (p->data_type == OSSL_PARAM_UTF8_STRING) {
203             if (OPENSSL_strcasecmp(p->data, "EXTRACT_AND_EXPAND") == 0) {
204                 ctx->mode = EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND;
205             } else if (OPENSSL_strcasecmp(p->data, "EXTRACT_ONLY") == 0) {
206                 ctx->mode = EVP_KDF_HKDF_MODE_EXTRACT_ONLY;
207             } else if (OPENSSL_strcasecmp(p->data, "EXPAND_ONLY") == 0) {
208                 ctx->mode = EVP_KDF_HKDF_MODE_EXPAND_ONLY;
209             } else {
210                 ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
211                 return 0;
212             }
213         } else if (OSSL_PARAM_get_int(p, &n)) {
214             if (n != EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND
215                 && n != EVP_KDF_HKDF_MODE_EXTRACT_ONLY
216                 && n != EVP_KDF_HKDF_MODE_EXPAND_ONLY) {
217                 ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
218                 return 0;
219             }
220             ctx->mode = n;
221         } else {
222             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
223             return 0;
224         }
225     }
226 
227     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY)) != NULL) {
228         OPENSSL_clear_free(ctx->key, ctx->key_len);
229         ctx->key = NULL;
230         if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->key, 0,
231                                          &ctx->key_len))
232             return 0;
233     }
234 
235     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT)) != NULL) {
236         if (p->data_size != 0 && p->data != NULL) {
237             OPENSSL_free(ctx->salt);
238             ctx->salt = NULL;
239             if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->salt, 0,
240                                              &ctx->salt_len))
241                 return 0;
242         }
243     }
244 
245     return 1;
246 }
247 
248 /*
249  * Use WPACKET to concat one or more OSSL_KDF_PARAM_INFO fields into a fixed
250  * out buffer of size *outlen.
251  * If out is NULL then outlen is used to return the required buffer size.
252  */
253 static int setinfo_fromparams(const OSSL_PARAM *p, unsigned char *out, size_t *outlen)
254 {
255     int ret = 0;
256     WPACKET pkt;
257 
258     if (out == NULL) {
259         if (!WPACKET_init_null(&pkt, 0))
260             return 0;
261     } else {
262         if (!WPACKET_init_static_len(&pkt, out, *outlen, 0))
263             return 0;
264     }
265 
266     for (; p != NULL; p = OSSL_PARAM_locate_const(p + 1, OSSL_KDF_PARAM_INFO)) {
267         if (p->data_type != OSSL_PARAM_OCTET_STRING)
268             goto err;
269         if (p->data != NULL
270                 && p->data_size != 0
271                 && !WPACKET_memcpy(&pkt, p->data, p->data_size))
272             goto err;
273     }
274     if (!WPACKET_get_total_written(&pkt, outlen)
275             || !WPACKET_finish(&pkt))
276         goto err;
277     ret = 1;
278 err:
279     WPACKET_cleanup(&pkt);
280     return ret;
281 }
282 
283 static int kdf_hkdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
284 {
285     const OSSL_PARAM *p;
286     KDF_HKDF *ctx = vctx;
287 
288     if (params == NULL)
289         return 1;
290 
291     if (!hkdf_common_set_ctx_params(ctx, params))
292         return 0;
293 
294     /* The info fields concatenate, so process them all */
295     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_INFO)) != NULL) {
296         size_t sz = 0;
297 
298         /* calculate the total size */
299         if (!setinfo_fromparams(p, NULL, &sz))
300             return 0;
301         if (sz > HKDF_MAXINFO)
302             return 0;
303 
304         OPENSSL_clear_free(ctx->info, ctx->info_len);
305         ctx->info = NULL;
306         if (sz == 0)
307             return 1;
308         /* Alloc the buffer */
309         ctx->info = OPENSSL_malloc(sz);
310         if (ctx->info == NULL)
311             return 0;
312         ctx->info_len = sz;
313         /* Concat one or more OSSL_KDF_PARAM_INFO fields */
314         if (!setinfo_fromparams(p, ctx->info, &sz))
315             return 0;
316     }
317     return 1;
318 }
319 
320 static const OSSL_PARAM *kdf_hkdf_settable_ctx_params(ossl_unused void *ctx,
321                                                       ossl_unused void *provctx)
322 {
323     static const OSSL_PARAM known_settable_ctx_params[] = {
324         HKDF_COMMON_SETTABLES,
325         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_INFO, NULL, 0),
326         OSSL_PARAM_END
327     };
328     return known_settable_ctx_params;
329 }
330 
331 static int kdf_hkdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
332 {
333     KDF_HKDF *ctx = (KDF_HKDF *)vctx;
334     OSSL_PARAM *p;
335 
336     if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL) {
337         size_t sz = kdf_hkdf_size(ctx);
338 
339         if (sz == 0)
340             return 0;
341         return OSSL_PARAM_set_size_t(p, sz);
342     }
343     if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_INFO)) != NULL) {
344         if (ctx->info == NULL || ctx->info_len == 0) {
345             p->return_size = 0;
346             return 1;
347         }
348         return OSSL_PARAM_set_octet_string(p, ctx->info, ctx->info_len);
349     }
350     return -2;
351 }
352 
353 static const OSSL_PARAM *kdf_hkdf_gettable_ctx_params(ossl_unused void *ctx,
354                                                       ossl_unused void *provctx)
355 {
356     static const OSSL_PARAM known_gettable_ctx_params[] = {
357         OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
358         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_INFO, NULL, 0),
359         OSSL_PARAM_END
360     };
361     return known_gettable_ctx_params;
362 }
363 
364 const OSSL_DISPATCH ossl_kdf_hkdf_functions[] = {
365     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_hkdf_new },
366     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_hkdf_free },
367     { OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_hkdf_reset },
368     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_hkdf_derive },
369     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
370       (void(*)(void))kdf_hkdf_settable_ctx_params },
371     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_hkdf_set_ctx_params },
372     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
373       (void(*)(void))kdf_hkdf_gettable_ctx_params },
374     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_hkdf_get_ctx_params },
375     { 0, NULL }
376 };
377 
378 /*
379  * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
380  * Section 2 (https://tools.ietf.org/html/rfc5869#section-2) and
381  * "Cryptographic Extraction and Key Derivation: The HKDF Scheme"
382  * Section 4.2 (https://eprint.iacr.org/2010/264.pdf).
383  *
384  * From the paper:
385  *   The scheme HKDF is specified as:
386  *     HKDF(XTS, SKM, CTXinfo, L) = K(1) | K(2) | ... | K(t)
387  *
388  *     where:
389  *       SKM is source key material
390  *       XTS is extractor salt (which may be null or constant)
391  *       CTXinfo is context information (may be null)
392  *       L is the number of key bits to be produced by KDF
393  *       k is the output length in bits of the hash function used with HMAC
394  *       t = ceil(L/k)
395  *       the value K(t) is truncated to its first d = L mod k bits.
396  *
397  * From RFC 5869:
398  *   2.2.  Step 1: Extract
399  *     HKDF-Extract(salt, IKM) -> PRK
400  *   2.3.  Step 2: Expand
401  *     HKDF-Expand(PRK, info, L) -> OKM
402  */
403 static int HKDF(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
404                 const unsigned char *salt, size_t salt_len,
405                 const unsigned char *ikm, size_t ikm_len,
406                 const unsigned char *info, size_t info_len,
407                 unsigned char *okm, size_t okm_len)
408 {
409     unsigned char prk[EVP_MAX_MD_SIZE];
410     int ret, sz;
411     size_t prk_len;
412 
413     sz = EVP_MD_get_size(evp_md);
414     if (sz < 0)
415         return 0;
416     prk_len = (size_t)sz;
417 
418     /* Step 1: HKDF-Extract(salt, IKM) -> PRK */
419     if (!HKDF_Extract(libctx, evp_md,
420                       salt, salt_len, ikm, ikm_len, prk, prk_len))
421         return 0;
422 
423     /* Step 2: HKDF-Expand(PRK, info, L) -> OKM */
424     ret = HKDF_Expand(evp_md, prk, prk_len, info, info_len, okm, okm_len);
425     OPENSSL_cleanse(prk, sizeof(prk));
426 
427     return ret;
428 }
429 
430 /*
431  * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
432  * Section 2.2 (https://tools.ietf.org/html/rfc5869#section-2.2).
433  *
434  * 2.2.  Step 1: Extract
435  *
436  *   HKDF-Extract(salt, IKM) -> PRK
437  *
438  *   Options:
439  *      Hash     a hash function; HashLen denotes the length of the
440  *               hash function output in octets
441  *
442  *   Inputs:
443  *      salt     optional salt value (a non-secret random value);
444  *               if not provided, it is set to a string of HashLen zeros.
445  *      IKM      input keying material
446  *
447  *   Output:
448  *      PRK      a pseudorandom key (of HashLen octets)
449  *
450  *   The output PRK is calculated as follows:
451  *
452  *   PRK = HMAC-Hash(salt, IKM)
453  */
454 static int HKDF_Extract(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
455                         const unsigned char *salt, size_t salt_len,
456                         const unsigned char *ikm, size_t ikm_len,
457                         unsigned char *prk, size_t prk_len)
458 {
459     int sz = EVP_MD_get_size(evp_md);
460 
461     if (sz < 0)
462         return 0;
463     if (prk_len != (size_t)sz) {
464         ERR_raise(ERR_LIB_PROV, PROV_R_WRONG_OUTPUT_BUFFER_SIZE);
465         return 0;
466     }
467     /* calc: PRK = HMAC-Hash(salt, IKM) */
468     return
469         EVP_Q_mac(libctx, "HMAC", NULL, EVP_MD_get0_name(evp_md), NULL, salt,
470                   salt_len, ikm, ikm_len, prk, EVP_MD_get_size(evp_md), NULL)
471         != NULL;
472 }
473 
474 /*
475  * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
476  * Section 2.3 (https://tools.ietf.org/html/rfc5869#section-2.3).
477  *
478  * 2.3.  Step 2: Expand
479  *
480  *   HKDF-Expand(PRK, info, L) -> OKM
481  *
482  *   Options:
483  *      Hash     a hash function; HashLen denotes the length of the
484  *               hash function output in octets
485  *
486  *   Inputs:
487  *      PRK      a pseudorandom key of at least HashLen octets
488  *               (usually, the output from the extract step)
489  *      info     optional context and application specific information
490  *               (can be a zero-length string)
491  *      L        length of output keying material in octets
492  *               (<= 255*HashLen)
493  *
494  *   Output:
495  *      OKM      output keying material (of L octets)
496  *
497  *   The output OKM is calculated as follows:
498  *
499  *   N = ceil(L/HashLen)
500  *   T = T(1) | T(2) | T(3) | ... | T(N)
501  *   OKM = first L octets of T
502  *
503  *   where:
504  *   T(0) = empty string (zero length)
505  *   T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
506  *   T(2) = HMAC-Hash(PRK, T(1) | info | 0x02)
507  *   T(3) = HMAC-Hash(PRK, T(2) | info | 0x03)
508  *   ...
509  *
510  *   (where the constant concatenated to the end of each T(n) is a
511  *   single octet.)
512  */
513 static int HKDF_Expand(const EVP_MD *evp_md,
514                        const unsigned char *prk, size_t prk_len,
515                        const unsigned char *info, size_t info_len,
516                        unsigned char *okm, size_t okm_len)
517 {
518     HMAC_CTX *hmac;
519     int ret = 0, sz;
520     unsigned int i;
521     unsigned char prev[EVP_MAX_MD_SIZE];
522     size_t done_len = 0, dig_len, n;
523 
524     sz = EVP_MD_get_size(evp_md);
525     if (sz <= 0)
526         return 0;
527     dig_len = (size_t)sz;
528 
529     /* calc: N = ceil(L/HashLen) */
530     n = okm_len / dig_len;
531     if (okm_len % dig_len)
532         n++;
533 
534     if (n > 255 || okm == NULL)
535         return 0;
536 
537     if ((hmac = HMAC_CTX_new()) == NULL)
538         return 0;
539 
540     if (!HMAC_Init_ex(hmac, prk, prk_len, evp_md, NULL))
541         goto err;
542 
543     for (i = 1; i <= n; i++) {
544         size_t copy_len;
545         const unsigned char ctr = i;
546 
547         /* calc: T(i) = HMAC-Hash(PRK, T(i - 1) | info | i) */
548         if (i > 1) {
549             if (!HMAC_Init_ex(hmac, NULL, 0, NULL, NULL))
550                 goto err;
551 
552             if (!HMAC_Update(hmac, prev, dig_len))
553                 goto err;
554         }
555 
556         if (!HMAC_Update(hmac, info, info_len))
557             goto err;
558 
559         if (!HMAC_Update(hmac, &ctr, 1))
560             goto err;
561 
562         if (!HMAC_Final(hmac, prev, NULL))
563             goto err;
564 
565         copy_len = (dig_len > okm_len - done_len) ?
566                        okm_len - done_len :
567                        dig_len;
568 
569         memcpy(okm + done_len, prev, copy_len);
570 
571         done_len += copy_len;
572     }
573     ret = 1;
574 
575  err:
576     OPENSSL_cleanse(prev, sizeof(prev));
577     HMAC_CTX_free(hmac);
578     return ret;
579 }
580 
581 /*
582  * TLS uses slight variations of the above and for FIPS validation purposes,
583  * they need to be present here.
584  * Refer to RFC 8446 section 7 for specific details.
585  */
586 
587 /*
588  * Given a |secret|; a |label| of length |labellen|; and |data| of length
589  * |datalen| (e.g. typically a hash of the handshake messages), derive a new
590  * secret |outlen| bytes long and store it in the location pointed to be |out|.
591  * The |data| value may be zero length. Returns 1 on success and 0 on failure.
592  */
593 static int prov_tls13_hkdf_expand(const EVP_MD *md,
594                                   const unsigned char *key, size_t keylen,
595                                   const unsigned char *prefix, size_t prefixlen,
596                                   const unsigned char *label, size_t labellen,
597                                   const unsigned char *data, size_t datalen,
598                                   unsigned char *out, size_t outlen)
599 {
600     size_t hkdflabellen;
601     unsigned char hkdflabel[HKDF_MAXBUF];
602     WPACKET pkt;
603 
604     /*
605      * 2 bytes for length of derived secret + 1 byte for length of combined
606      * prefix and label + bytes for the label itself + 1 byte length of hash
607      * + bytes for the hash itself.  We've got the maximum the KDF can handle
608      * which should always be sufficient.
609      */
610     if (!WPACKET_init_static_len(&pkt, hkdflabel, sizeof(hkdflabel), 0)
611             || !WPACKET_put_bytes_u16(&pkt, outlen)
612             || !WPACKET_start_sub_packet_u8(&pkt)
613             || !WPACKET_memcpy(&pkt, prefix, prefixlen)
614             || !WPACKET_memcpy(&pkt, label, labellen)
615             || !WPACKET_close(&pkt)
616             || !WPACKET_sub_memcpy_u8(&pkt, data, (data == NULL) ? 0 : datalen)
617             || !WPACKET_get_total_written(&pkt, &hkdflabellen)
618             || !WPACKET_finish(&pkt)) {
619         WPACKET_cleanup(&pkt);
620         return 0;
621     }
622 
623     return HKDF_Expand(md, key, keylen, hkdflabel, hkdflabellen,
624                        out, outlen);
625 }
626 
627 static int prov_tls13_hkdf_generate_secret(OSSL_LIB_CTX *libctx,
628                                            const EVP_MD *md,
629                                            const unsigned char *prevsecret,
630                                            size_t prevsecretlen,
631                                            const unsigned char *insecret,
632                                            size_t insecretlen,
633                                            const unsigned char *prefix,
634                                            size_t prefixlen,
635                                            const unsigned char *label,
636                                            size_t labellen,
637                                            unsigned char *out, size_t outlen)
638 {
639     size_t mdlen;
640     int ret;
641     unsigned char preextractsec[EVP_MAX_MD_SIZE];
642     /* Always filled with zeros */
643     static const unsigned char default_zeros[EVP_MAX_MD_SIZE];
644 
645     ret = EVP_MD_get_size(md);
646     /* Ensure cast to size_t is safe */
647     if (ret <= 0)
648         return 0;
649     mdlen = (size_t)ret;
650 
651     if (insecret == NULL) {
652         insecret = default_zeros;
653         insecretlen = mdlen;
654     }
655     if (prevsecret == NULL) {
656         prevsecret = default_zeros;
657         prevsecretlen = 0;
658     } else {
659         EVP_MD_CTX *mctx = EVP_MD_CTX_new();
660         unsigned char hash[EVP_MAX_MD_SIZE];
661 
662         /* The pre-extract derive step uses a hash of no messages */
663         if (mctx == NULL
664                 || EVP_DigestInit_ex(mctx, md, NULL) <= 0
665                 || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
666             EVP_MD_CTX_free(mctx);
667             return 0;
668         }
669         EVP_MD_CTX_free(mctx);
670 
671         /* Generate the pre-extract secret */
672         if (!prov_tls13_hkdf_expand(md, prevsecret, mdlen,
673                                     prefix, prefixlen, label, labellen,
674                                     hash, mdlen, preextractsec, mdlen))
675             return 0;
676         prevsecret = preextractsec;
677         prevsecretlen = mdlen;
678     }
679 
680     ret = HKDF_Extract(libctx, md, prevsecret, prevsecretlen,
681                        insecret, insecretlen, out, outlen);
682 
683     if (prevsecret == preextractsec)
684         OPENSSL_cleanse(preextractsec, mdlen);
685     return ret;
686 }
687 
688 static int kdf_tls1_3_derive(void *vctx, unsigned char *key, size_t keylen,
689                              const OSSL_PARAM params[])
690 {
691     KDF_HKDF *ctx = (KDF_HKDF *)vctx;
692     const EVP_MD *md;
693 
694     if (!ossl_prov_is_running() || !kdf_tls1_3_set_ctx_params(ctx, params))
695         return 0;
696 
697     md = ossl_prov_digest_md(&ctx->digest);
698     if (md == NULL) {
699         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
700         return 0;
701     }
702 
703     switch (ctx->mode) {
704     default:
705         return 0;
706 
707     case EVP_KDF_HKDF_MODE_EXTRACT_ONLY:
708         return prov_tls13_hkdf_generate_secret(PROV_LIBCTX_OF(ctx->provctx),
709                                                md,
710                                                ctx->salt, ctx->salt_len,
711                                                ctx->key, ctx->key_len,
712                                                ctx->prefix, ctx->prefix_len,
713                                                ctx->label, ctx->label_len,
714                                                key, keylen);
715 
716     case EVP_KDF_HKDF_MODE_EXPAND_ONLY:
717         return prov_tls13_hkdf_expand(md, ctx->key, ctx->key_len,
718                                       ctx->prefix, ctx->prefix_len,
719                                       ctx->label, ctx->label_len,
720                                       ctx->data, ctx->data_len,
721                                       key, keylen);
722     }
723 }
724 
725 static int kdf_tls1_3_set_ctx_params(void *vctx, const OSSL_PARAM params[])
726 {
727     const OSSL_PARAM *p;
728     KDF_HKDF *ctx = vctx;
729 
730     if (params == NULL)
731         return 1;
732 
733     if (!hkdf_common_set_ctx_params(ctx, params))
734         return 0;
735 
736     if (ctx->mode == EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND) {
737         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
738         return 0;
739     }
740 
741     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PREFIX)) != NULL) {
742         OPENSSL_free(ctx->prefix);
743         ctx->prefix = NULL;
744         if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->prefix, 0,
745                                          &ctx->prefix_len))
746             return 0;
747     }
748 
749     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_LABEL)) != NULL) {
750         OPENSSL_free(ctx->label);
751         ctx->label = NULL;
752         if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->label, 0,
753                                          &ctx->label_len))
754             return 0;
755     }
756 
757     OPENSSL_clear_free(ctx->data, ctx->data_len);
758     ctx->data = NULL;
759     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_DATA)) != NULL
760             && !OSSL_PARAM_get_octet_string(p, (void **)&ctx->data, 0,
761                                             &ctx->data_len))
762         return 0;
763     return 1;
764 }
765 
766 static const OSSL_PARAM *kdf_tls1_3_settable_ctx_params(ossl_unused void *ctx,
767                                                         ossl_unused void *provctx)
768 {
769     static const OSSL_PARAM known_settable_ctx_params[] = {
770         HKDF_COMMON_SETTABLES,
771         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PREFIX, NULL, 0),
772         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_LABEL, NULL, 0),
773         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_DATA, NULL, 0),
774         OSSL_PARAM_END
775     };
776     return known_settable_ctx_params;
777 }
778 
779 const OSSL_DISPATCH ossl_kdf_tls1_3_kdf_functions[] = {
780     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_hkdf_new },
781     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_hkdf_free },
782     { OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_hkdf_reset },
783     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_tls1_3_derive },
784     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
785       (void(*)(void))kdf_tls1_3_settable_ctx_params },
786     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_tls1_3_set_ctx_params },
787     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
788       (void(*)(void))kdf_hkdf_gettable_ctx_params },
789     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_hkdf_get_ctx_params },
790     { 0, NULL }
791 };
792