xref: /freebsd/crypto/openssl/providers/implementations/kdfs/hkdf.c (revision 734e82fe33aa764367791a7d603b383996c6b40b)
1 /*
2  * Copyright 2016-2023 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     return -2;
344 }
345 
346 static const OSSL_PARAM *kdf_hkdf_gettable_ctx_params(ossl_unused void *ctx,
347                                                       ossl_unused void *provctx)
348 {
349     static const OSSL_PARAM known_gettable_ctx_params[] = {
350         OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
351         OSSL_PARAM_END
352     };
353     return known_gettable_ctx_params;
354 }
355 
356 const OSSL_DISPATCH ossl_kdf_hkdf_functions[] = {
357     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_hkdf_new },
358     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_hkdf_free },
359     { OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_hkdf_reset },
360     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_hkdf_derive },
361     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
362       (void(*)(void))kdf_hkdf_settable_ctx_params },
363     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_hkdf_set_ctx_params },
364     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
365       (void(*)(void))kdf_hkdf_gettable_ctx_params },
366     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_hkdf_get_ctx_params },
367     { 0, NULL }
368 };
369 
370 /*
371  * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
372  * Section 2 (https://tools.ietf.org/html/rfc5869#section-2) and
373  * "Cryptographic Extraction and Key Derivation: The HKDF Scheme"
374  * Section 4.2 (https://eprint.iacr.org/2010/264.pdf).
375  *
376  * From the paper:
377  *   The scheme HKDF is specified as:
378  *     HKDF(XTS, SKM, CTXinfo, L) = K(1) | K(2) | ... | K(t)
379  *
380  *     where:
381  *       SKM is source key material
382  *       XTS is extractor salt (which may be null or constant)
383  *       CTXinfo is context information (may be null)
384  *       L is the number of key bits to be produced by KDF
385  *       k is the output length in bits of the hash function used with HMAC
386  *       t = ceil(L/k)
387  *       the value K(t) is truncated to its first d = L mod k bits.
388  *
389  * From RFC 5869:
390  *   2.2.  Step 1: Extract
391  *     HKDF-Extract(salt, IKM) -> PRK
392  *   2.3.  Step 2: Expand
393  *     HKDF-Expand(PRK, info, L) -> OKM
394  */
395 static int HKDF(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
396                 const unsigned char *salt, size_t salt_len,
397                 const unsigned char *ikm, size_t ikm_len,
398                 const unsigned char *info, size_t info_len,
399                 unsigned char *okm, size_t okm_len)
400 {
401     unsigned char prk[EVP_MAX_MD_SIZE];
402     int ret, sz;
403     size_t prk_len;
404 
405     sz = EVP_MD_get_size(evp_md);
406     if (sz < 0)
407         return 0;
408     prk_len = (size_t)sz;
409 
410     /* Step 1: HKDF-Extract(salt, IKM) -> PRK */
411     if (!HKDF_Extract(libctx, evp_md,
412                       salt, salt_len, ikm, ikm_len, prk, prk_len))
413         return 0;
414 
415     /* Step 2: HKDF-Expand(PRK, info, L) -> OKM */
416     ret = HKDF_Expand(evp_md, prk, prk_len, info, info_len, okm, okm_len);
417     OPENSSL_cleanse(prk, sizeof(prk));
418 
419     return ret;
420 }
421 
422 /*
423  * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
424  * Section 2.2 (https://tools.ietf.org/html/rfc5869#section-2.2).
425  *
426  * 2.2.  Step 1: Extract
427  *
428  *   HKDF-Extract(salt, IKM) -> PRK
429  *
430  *   Options:
431  *      Hash     a hash function; HashLen denotes the length of the
432  *               hash function output in octets
433  *
434  *   Inputs:
435  *      salt     optional salt value (a non-secret random value);
436  *               if not provided, it is set to a string of HashLen zeros.
437  *      IKM      input keying material
438  *
439  *   Output:
440  *      PRK      a pseudorandom key (of HashLen octets)
441  *
442  *   The output PRK is calculated as follows:
443  *
444  *   PRK = HMAC-Hash(salt, IKM)
445  */
446 static int HKDF_Extract(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
447                         const unsigned char *salt, size_t salt_len,
448                         const unsigned char *ikm, size_t ikm_len,
449                         unsigned char *prk, size_t prk_len)
450 {
451     int sz = EVP_MD_get_size(evp_md);
452 
453     if (sz < 0)
454         return 0;
455     if (prk_len != (size_t)sz) {
456         ERR_raise(ERR_LIB_PROV, PROV_R_WRONG_OUTPUT_BUFFER_SIZE);
457         return 0;
458     }
459     /* calc: PRK = HMAC-Hash(salt, IKM) */
460     return
461         EVP_Q_mac(libctx, "HMAC", NULL, EVP_MD_get0_name(evp_md), NULL, salt,
462                   salt_len, ikm, ikm_len, prk, EVP_MD_get_size(evp_md), NULL)
463         != NULL;
464 }
465 
466 /*
467  * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
468  * Section 2.3 (https://tools.ietf.org/html/rfc5869#section-2.3).
469  *
470  * 2.3.  Step 2: Expand
471  *
472  *   HKDF-Expand(PRK, info, L) -> OKM
473  *
474  *   Options:
475  *      Hash     a hash function; HashLen denotes the length of the
476  *               hash function output in octets
477  *
478  *   Inputs:
479  *      PRK      a pseudorandom key of at least HashLen octets
480  *               (usually, the output from the extract step)
481  *      info     optional context and application specific information
482  *               (can be a zero-length string)
483  *      L        length of output keying material in octets
484  *               (<= 255*HashLen)
485  *
486  *   Output:
487  *      OKM      output keying material (of L octets)
488  *
489  *   The output OKM is calculated as follows:
490  *
491  *   N = ceil(L/HashLen)
492  *   T = T(1) | T(2) | T(3) | ... | T(N)
493  *   OKM = first L octets of T
494  *
495  *   where:
496  *   T(0) = empty string (zero length)
497  *   T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
498  *   T(2) = HMAC-Hash(PRK, T(1) | info | 0x02)
499  *   T(3) = HMAC-Hash(PRK, T(2) | info | 0x03)
500  *   ...
501  *
502  *   (where the constant concatenated to the end of each T(n) is a
503  *   single octet.)
504  */
505 static int HKDF_Expand(const EVP_MD *evp_md,
506                        const unsigned char *prk, size_t prk_len,
507                        const unsigned char *info, size_t info_len,
508                        unsigned char *okm, size_t okm_len)
509 {
510     HMAC_CTX *hmac;
511     int ret = 0, sz;
512     unsigned int i;
513     unsigned char prev[EVP_MAX_MD_SIZE];
514     size_t done_len = 0, dig_len, n;
515 
516     sz = EVP_MD_get_size(evp_md);
517     if (sz <= 0)
518         return 0;
519     dig_len = (size_t)sz;
520 
521     /* calc: N = ceil(L/HashLen) */
522     n = okm_len / dig_len;
523     if (okm_len % dig_len)
524         n++;
525 
526     if (n > 255 || okm == NULL)
527         return 0;
528 
529     if ((hmac = HMAC_CTX_new()) == NULL)
530         return 0;
531 
532     if (!HMAC_Init_ex(hmac, prk, prk_len, evp_md, NULL))
533         goto err;
534 
535     for (i = 1; i <= n; i++) {
536         size_t copy_len;
537         const unsigned char ctr = i;
538 
539         /* calc: T(i) = HMAC-Hash(PRK, T(i - 1) | info | i) */
540         if (i > 1) {
541             if (!HMAC_Init_ex(hmac, NULL, 0, NULL, NULL))
542                 goto err;
543 
544             if (!HMAC_Update(hmac, prev, dig_len))
545                 goto err;
546         }
547 
548         if (!HMAC_Update(hmac, info, info_len))
549             goto err;
550 
551         if (!HMAC_Update(hmac, &ctr, 1))
552             goto err;
553 
554         if (!HMAC_Final(hmac, prev, NULL))
555             goto err;
556 
557         copy_len = (dig_len > okm_len - done_len) ?
558                        okm_len - done_len :
559                        dig_len;
560 
561         memcpy(okm + done_len, prev, copy_len);
562 
563         done_len += copy_len;
564     }
565     ret = 1;
566 
567  err:
568     OPENSSL_cleanse(prev, sizeof(prev));
569     HMAC_CTX_free(hmac);
570     return ret;
571 }
572 
573 /*
574  * TLS uses slight variations of the above and for FIPS validation purposes,
575  * they need to be present here.
576  * Refer to RFC 8446 section 7 for specific details.
577  */
578 
579 /*
580  * Given a |secret|; a |label| of length |labellen|; and |data| of length
581  * |datalen| (e.g. typically a hash of the handshake messages), derive a new
582  * secret |outlen| bytes long and store it in the location pointed to be |out|.
583  * The |data| value may be zero length. Returns 1 on success and 0 on failure.
584  */
585 static int prov_tls13_hkdf_expand(const EVP_MD *md,
586                                   const unsigned char *key, size_t keylen,
587                                   const unsigned char *prefix, size_t prefixlen,
588                                   const unsigned char *label, size_t labellen,
589                                   const unsigned char *data, size_t datalen,
590                                   unsigned char *out, size_t outlen)
591 {
592     size_t hkdflabellen;
593     unsigned char hkdflabel[HKDF_MAXBUF];
594     WPACKET pkt;
595 
596     /*
597      * 2 bytes for length of derived secret + 1 byte for length of combined
598      * prefix and label + bytes for the label itself + 1 byte length of hash
599      * + bytes for the hash itself.  We've got the maximum the KDF can handle
600      * which should always be sufficient.
601      */
602     if (!WPACKET_init_static_len(&pkt, hkdflabel, sizeof(hkdflabel), 0)
603             || !WPACKET_put_bytes_u16(&pkt, outlen)
604             || !WPACKET_start_sub_packet_u8(&pkt)
605             || !WPACKET_memcpy(&pkt, prefix, prefixlen)
606             || !WPACKET_memcpy(&pkt, label, labellen)
607             || !WPACKET_close(&pkt)
608             || !WPACKET_sub_memcpy_u8(&pkt, data, (data == NULL) ? 0 : datalen)
609             || !WPACKET_get_total_written(&pkt, &hkdflabellen)
610             || !WPACKET_finish(&pkt)) {
611         WPACKET_cleanup(&pkt);
612         return 0;
613     }
614 
615     return HKDF_Expand(md, key, keylen, hkdflabel, hkdflabellen,
616                        out, outlen);
617 }
618 
619 static int prov_tls13_hkdf_generate_secret(OSSL_LIB_CTX *libctx,
620                                            const EVP_MD *md,
621                                            const unsigned char *prevsecret,
622                                            size_t prevsecretlen,
623                                            const unsigned char *insecret,
624                                            size_t insecretlen,
625                                            const unsigned char *prefix,
626                                            size_t prefixlen,
627                                            const unsigned char *label,
628                                            size_t labellen,
629                                            unsigned char *out, size_t outlen)
630 {
631     size_t mdlen;
632     int ret;
633     unsigned char preextractsec[EVP_MAX_MD_SIZE];
634     /* Always filled with zeros */
635     static const unsigned char default_zeros[EVP_MAX_MD_SIZE];
636 
637     ret = EVP_MD_get_size(md);
638     /* Ensure cast to size_t is safe */
639     if (ret <= 0)
640         return 0;
641     mdlen = (size_t)ret;
642 
643     if (insecret == NULL) {
644         insecret = default_zeros;
645         insecretlen = mdlen;
646     }
647     if (prevsecret == NULL) {
648         prevsecret = default_zeros;
649         prevsecretlen = 0;
650     } else {
651         EVP_MD_CTX *mctx = EVP_MD_CTX_new();
652         unsigned char hash[EVP_MAX_MD_SIZE];
653 
654         /* The pre-extract derive step uses a hash of no messages */
655         if (mctx == NULL
656                 || EVP_DigestInit_ex(mctx, md, NULL) <= 0
657                 || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
658             EVP_MD_CTX_free(mctx);
659             return 0;
660         }
661         EVP_MD_CTX_free(mctx);
662 
663         /* Generate the pre-extract secret */
664         if (!prov_tls13_hkdf_expand(md, prevsecret, mdlen,
665                                     prefix, prefixlen, label, labellen,
666                                     hash, mdlen, preextractsec, mdlen))
667             return 0;
668         prevsecret = preextractsec;
669         prevsecretlen = mdlen;
670     }
671 
672     ret = HKDF_Extract(libctx, md, prevsecret, prevsecretlen,
673                        insecret, insecretlen, out, outlen);
674 
675     if (prevsecret == preextractsec)
676         OPENSSL_cleanse(preextractsec, mdlen);
677     return ret;
678 }
679 
680 static int kdf_tls1_3_derive(void *vctx, unsigned char *key, size_t keylen,
681                              const OSSL_PARAM params[])
682 {
683     KDF_HKDF *ctx = (KDF_HKDF *)vctx;
684     const EVP_MD *md;
685 
686     if (!ossl_prov_is_running() || !kdf_tls1_3_set_ctx_params(ctx, params))
687         return 0;
688 
689     md = ossl_prov_digest_md(&ctx->digest);
690     if (md == NULL) {
691         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
692         return 0;
693     }
694 
695     switch (ctx->mode) {
696     default:
697         return 0;
698 
699     case EVP_KDF_HKDF_MODE_EXTRACT_ONLY:
700         return prov_tls13_hkdf_generate_secret(PROV_LIBCTX_OF(ctx->provctx),
701                                                md,
702                                                ctx->salt, ctx->salt_len,
703                                                ctx->key, ctx->key_len,
704                                                ctx->prefix, ctx->prefix_len,
705                                                ctx->label, ctx->label_len,
706                                                key, keylen);
707 
708     case EVP_KDF_HKDF_MODE_EXPAND_ONLY:
709         return prov_tls13_hkdf_expand(md, ctx->key, ctx->key_len,
710                                       ctx->prefix, ctx->prefix_len,
711                                       ctx->label, ctx->label_len,
712                                       ctx->data, ctx->data_len,
713                                       key, keylen);
714     }
715 }
716 
717 static int kdf_tls1_3_set_ctx_params(void *vctx, const OSSL_PARAM params[])
718 {
719     const OSSL_PARAM *p;
720     KDF_HKDF *ctx = vctx;
721 
722     if (params == NULL)
723         return 1;
724 
725     if (!hkdf_common_set_ctx_params(ctx, params))
726         return 0;
727 
728     if (ctx->mode == EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND) {
729         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
730         return 0;
731     }
732 
733     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PREFIX)) != NULL) {
734         OPENSSL_free(ctx->prefix);
735         ctx->prefix = NULL;
736         if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->prefix, 0,
737                                          &ctx->prefix_len))
738             return 0;
739     }
740 
741     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_LABEL)) != NULL) {
742         OPENSSL_free(ctx->label);
743         ctx->label = NULL;
744         if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->label, 0,
745                                          &ctx->label_len))
746             return 0;
747     }
748 
749     OPENSSL_clear_free(ctx->data, ctx->data_len);
750     ctx->data = NULL;
751     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_DATA)) != NULL
752             && !OSSL_PARAM_get_octet_string(p, (void **)&ctx->data, 0,
753                                             &ctx->data_len))
754         return 0;
755     return 1;
756 }
757 
758 static const OSSL_PARAM *kdf_tls1_3_settable_ctx_params(ossl_unused void *ctx,
759                                                         ossl_unused void *provctx)
760 {
761     static const OSSL_PARAM known_settable_ctx_params[] = {
762         HKDF_COMMON_SETTABLES,
763         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PREFIX, NULL, 0),
764         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_LABEL, NULL, 0),
765         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_DATA, NULL, 0),
766         OSSL_PARAM_END
767     };
768     return known_settable_ctx_params;
769 }
770 
771 const OSSL_DISPATCH ossl_kdf_tls1_3_kdf_functions[] = {
772     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_hkdf_new },
773     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_hkdf_free },
774     { OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_hkdf_reset },
775     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_tls1_3_derive },
776     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
777       (void(*)(void))kdf_tls1_3_settable_ctx_params },
778     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_tls1_3_set_ctx_params },
779     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
780       (void(*)(void))kdf_hkdf_gettable_ctx_params },
781     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_hkdf_get_ctx_params },
782     { 0, NULL }
783 };
784