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