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 "prov/securitycheck.h"
33 #include "internal/e_os.h"
34 #include "internal/params.h"
35 
36 #define HKDF_MAXBUF 2048
37 #define HKDF_MAXINFO (32*1024)
38 
39 static OSSL_FUNC_kdf_newctx_fn kdf_hkdf_new;
40 static OSSL_FUNC_kdf_dupctx_fn kdf_hkdf_dup;
41 static OSSL_FUNC_kdf_freectx_fn kdf_hkdf_free;
42 static OSSL_FUNC_kdf_reset_fn kdf_hkdf_reset;
43 static OSSL_FUNC_kdf_derive_fn kdf_hkdf_derive;
44 static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_hkdf_settable_ctx_params;
45 static OSSL_FUNC_kdf_set_ctx_params_fn kdf_hkdf_set_ctx_params;
46 static OSSL_FUNC_kdf_gettable_ctx_params_fn kdf_hkdf_gettable_ctx_params;
47 static OSSL_FUNC_kdf_get_ctx_params_fn kdf_hkdf_get_ctx_params;
48 static OSSL_FUNC_kdf_derive_fn kdf_tls1_3_derive;
49 static OSSL_FUNC_kdf_settable_ctx_params_fn kdf_tls1_3_settable_ctx_params;
50 static OSSL_FUNC_kdf_set_ctx_params_fn kdf_tls1_3_set_ctx_params;
51 static OSSL_FUNC_kdf_gettable_ctx_params_fn kdf_tls1_3_gettable_ctx_params;
52 static OSSL_FUNC_kdf_get_ctx_params_fn kdf_tls1_3_get_ctx_params;
53 
54 static int HKDF(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
55                 const unsigned char *salt, size_t salt_len,
56                 const unsigned char *key, size_t key_len,
57                 const unsigned char *info, size_t info_len,
58                 unsigned char *okm, size_t okm_len);
59 static int HKDF_Extract(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
60                         const unsigned char *salt, size_t salt_len,
61                         const unsigned char *ikm, size_t ikm_len,
62                         unsigned char *prk, size_t prk_len);
63 static int HKDF_Expand(const EVP_MD *evp_md,
64                        const unsigned char *prk, size_t prk_len,
65                        const unsigned char *info, size_t info_len,
66                        unsigned char *okm, size_t okm_len);
67 
68 /* Settable context parameters that are common across HKDF and the TLS KDF */
69 #define HKDF_COMMON_SETTABLES                                       \
70     OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_MODE, NULL, 0),           \
71     OSSL_PARAM_int(OSSL_KDF_PARAM_MODE, NULL),                      \
72     OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),     \
73     OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),         \
74     OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),           \
75     OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0)
76 
77 /* Gettable context parameters that are common across HKDF and the TLS KDF */
78 #define HKDF_COMMON_GETTABLES                                       \
79     OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),                   \
80     OSSL_PARAM_octet_string(OSSL_KDF_PARAM_INFO, NULL, 0)
81 
82 typedef struct {
83     void *provctx;
84     int mode;
85     PROV_DIGEST digest;
86     unsigned char *salt;
87     size_t salt_len;
88     unsigned char *key;
89     size_t key_len;
90     unsigned char *prefix;
91     size_t prefix_len;
92     unsigned char *label;
93     size_t label_len;
94     unsigned char *data;
95     size_t data_len;
96     unsigned char *info;
97     size_t info_len;
98     OSSL_FIPS_IND_DECLARE
99 } KDF_HKDF;
100 
kdf_hkdf_new(void * provctx)101 static void *kdf_hkdf_new(void *provctx)
102 {
103     KDF_HKDF *ctx;
104 
105     if (!ossl_prov_is_running())
106         return NULL;
107 
108     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) != NULL) {
109         ctx->provctx = provctx;
110         OSSL_FIPS_IND_INIT(ctx)
111     }
112     return ctx;
113 }
114 
kdf_hkdf_free(void * vctx)115 static void kdf_hkdf_free(void *vctx)
116 {
117     KDF_HKDF *ctx = (KDF_HKDF *)vctx;
118 
119     if (ctx != NULL) {
120         kdf_hkdf_reset(ctx);
121         OPENSSL_free(ctx);
122     }
123 }
124 
kdf_hkdf_reset(void * vctx)125 static void kdf_hkdf_reset(void *vctx)
126 {
127     KDF_HKDF *ctx = (KDF_HKDF *)vctx;
128     void *provctx = ctx->provctx;
129 
130     ossl_prov_digest_reset(&ctx->digest);
131 #ifdef FIPS_MODULE
132     OPENSSL_clear_free(ctx->salt, ctx->salt_len);
133 #else
134     OPENSSL_free(ctx->salt);
135 #endif
136     OPENSSL_free(ctx->prefix);
137     OPENSSL_free(ctx->label);
138     OPENSSL_clear_free(ctx->data, ctx->data_len);
139     OPENSSL_clear_free(ctx->key, ctx->key_len);
140     OPENSSL_clear_free(ctx->info, ctx->info_len);
141     memset(ctx, 0, sizeof(*ctx));
142     ctx->provctx = provctx;
143 }
144 
kdf_hkdf_dup(void * vctx)145 static void *kdf_hkdf_dup(void *vctx)
146 {
147     const KDF_HKDF *src = (const KDF_HKDF *)vctx;
148     KDF_HKDF *dest;
149 
150     dest = kdf_hkdf_new(src->provctx);
151     if (dest != NULL) {
152         if (!ossl_prov_memdup(src->salt, src->salt_len, &dest->salt,
153                               &dest->salt_len)
154                 || !ossl_prov_memdup(src->key, src->key_len,
155                                      &dest->key , &dest->key_len)
156                 || !ossl_prov_memdup(src->prefix, src->prefix_len,
157                                      &dest->prefix, &dest->prefix_len)
158                 || !ossl_prov_memdup(src->label, src->label_len,
159                                      &dest->label, &dest->label_len)
160                 || !ossl_prov_memdup(src->data, src->data_len,
161                                      &dest->data, &dest->data_len)
162                 || !ossl_prov_memdup(src->info, src->info_len,
163                                      &dest->info, &dest->info_len)
164                 || !ossl_prov_digest_copy(&dest->digest, &src->digest))
165             goto err;
166         dest->mode = src->mode;
167         OSSL_FIPS_IND_COPY(dest, src)
168     }
169     return dest;
170 
171  err:
172     kdf_hkdf_free(dest);
173     return NULL;
174 }
175 
kdf_hkdf_size(KDF_HKDF * ctx)176 static size_t kdf_hkdf_size(KDF_HKDF *ctx)
177 {
178     int sz;
179     const EVP_MD *md = ossl_prov_digest_md(&ctx->digest);
180 
181     if (ctx->mode != EVP_KDF_HKDF_MODE_EXTRACT_ONLY)
182         return SIZE_MAX;
183 
184     if (md == NULL) {
185         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
186         return 0;
187     }
188     sz = EVP_MD_get_size(md);
189     if (sz <= 0)
190         return 0;
191 
192     return sz;
193 }
194 
195 #ifdef FIPS_MODULE
fips_hkdf_key_check_passed(KDF_HKDF * ctx)196 static int fips_hkdf_key_check_passed(KDF_HKDF *ctx)
197 {
198     OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
199     int key_approved = ossl_kdf_check_key_size(ctx->key_len);
200 
201     if (!key_approved) {
202         if (!OSSL_FIPS_IND_ON_UNAPPROVED(ctx, OSSL_FIPS_IND_SETTABLE0,
203                                          libctx, "HKDF", "Key size",
204                                          ossl_fips_config_hkdf_key_check)) {
205             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
206             return 0;
207         }
208     }
209     return 1;
210 }
211 #endif
212 
kdf_hkdf_derive(void * vctx,unsigned char * key,size_t keylen,const OSSL_PARAM params[])213 static int kdf_hkdf_derive(void *vctx, unsigned char *key, size_t keylen,
214                            const OSSL_PARAM params[])
215 {
216     KDF_HKDF *ctx = (KDF_HKDF *)vctx;
217     OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
218     const EVP_MD *md;
219 
220     if (!ossl_prov_is_running() || !kdf_hkdf_set_ctx_params(ctx, params))
221         return 0;
222 
223     md = ossl_prov_digest_md(&ctx->digest);
224     if (md == NULL) {
225         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
226         return 0;
227     }
228     if (ctx->key == NULL) {
229         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY);
230         return 0;
231     }
232     if (keylen == 0) {
233         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
234         return 0;
235     }
236 
237     switch (ctx->mode) {
238     case EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND:
239     default:
240         return HKDF(libctx, md, ctx->salt, ctx->salt_len,
241                     ctx->key, ctx->key_len, ctx->info, ctx->info_len, key, keylen);
242 
243     case EVP_KDF_HKDF_MODE_EXTRACT_ONLY:
244         return HKDF_Extract(libctx, md, ctx->salt, ctx->salt_len,
245                             ctx->key, ctx->key_len, key, keylen);
246 
247     case EVP_KDF_HKDF_MODE_EXPAND_ONLY:
248         return HKDF_Expand(md, ctx->key, ctx->key_len, ctx->info,
249                            ctx->info_len, key, keylen);
250     }
251 }
252 
hkdf_common_set_ctx_params(KDF_HKDF * ctx,const OSSL_PARAM params[])253 static int hkdf_common_set_ctx_params(KDF_HKDF *ctx, const OSSL_PARAM params[])
254 {
255     OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
256     const OSSL_PARAM *p;
257     int n;
258 
259     if (ossl_param_is_empty(params))
260         return 1;
261 
262     if (OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_DIGEST) != NULL) {
263         const EVP_MD *md = NULL;
264 
265         if (!ossl_prov_digest_load_from_params(&ctx->digest, params, libctx))
266             return 0;
267 
268         md = ossl_prov_digest_md(&ctx->digest);
269         if (EVP_MD_xof(md)) {
270             ERR_raise(ERR_LIB_PROV, PROV_R_XOF_DIGESTS_NOT_ALLOWED);
271             return 0;
272         }
273     }
274 
275     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_MODE)) != NULL) {
276         if (p->data_type == OSSL_PARAM_UTF8_STRING) {
277             if (OPENSSL_strcasecmp(p->data, "EXTRACT_AND_EXPAND") == 0) {
278                 ctx->mode = EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND;
279             } else if (OPENSSL_strcasecmp(p->data, "EXTRACT_ONLY") == 0) {
280                 ctx->mode = EVP_KDF_HKDF_MODE_EXTRACT_ONLY;
281             } else if (OPENSSL_strcasecmp(p->data, "EXPAND_ONLY") == 0) {
282                 ctx->mode = EVP_KDF_HKDF_MODE_EXPAND_ONLY;
283             } else {
284                 ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
285                 return 0;
286             }
287         } else if (OSSL_PARAM_get_int(p, &n)) {
288             if (n != EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND
289                 && n != EVP_KDF_HKDF_MODE_EXTRACT_ONLY
290                 && n != EVP_KDF_HKDF_MODE_EXPAND_ONLY) {
291                 ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
292                 return 0;
293             }
294             ctx->mode = n;
295         } else {
296             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
297             return 0;
298         }
299     }
300 
301     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY)) != NULL) {
302         OPENSSL_clear_free(ctx->key, ctx->key_len);
303         ctx->key = NULL;
304         if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->key, 0,
305                                          &ctx->key_len))
306             return 0;
307     }
308 
309     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT)) != NULL) {
310         if (p->data_size != 0 && p->data != NULL) {
311             OPENSSL_free(ctx->salt);
312             ctx->salt = NULL;
313             if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->salt, 0,
314                                              &ctx->salt_len))
315                 return 0;
316         }
317     }
318 
319     return 1;
320 }
321 
kdf_hkdf_set_ctx_params(void * vctx,const OSSL_PARAM params[])322 static int kdf_hkdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
323 {
324     KDF_HKDF *ctx = vctx;
325 
326     if (ossl_param_is_empty(params))
327         return 1;
328 
329     if (!OSSL_FIPS_IND_SET_CTX_PARAM(ctx, OSSL_FIPS_IND_SETTABLE0, params,
330                                      OSSL_KDF_PARAM_FIPS_KEY_CHECK))
331         return 0;
332 
333     if (!hkdf_common_set_ctx_params(ctx, params))
334         return 0;
335 
336     if (ossl_param_get1_concat_octet_string(params, OSSL_KDF_PARAM_INFO,
337                                             &ctx->info, &ctx->info_len,
338                                             HKDF_MAXINFO) == 0)
339         return 0;
340 
341 #ifdef FIPS_MODULE
342     if (OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY) != NULL)
343         if (!fips_hkdf_key_check_passed(ctx))
344             return 0;
345 #endif
346 
347     return 1;
348 }
349 
kdf_hkdf_settable_ctx_params(ossl_unused void * ctx,ossl_unused void * provctx)350 static const OSSL_PARAM *kdf_hkdf_settable_ctx_params(ossl_unused void *ctx,
351                                                       ossl_unused void *provctx)
352 {
353     static const OSSL_PARAM known_settable_ctx_params[] = {
354         HKDF_COMMON_SETTABLES,
355         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_INFO, NULL, 0),
356         OSSL_FIPS_IND_SETTABLE_CTX_PARAM(OSSL_KDF_PARAM_FIPS_KEY_CHECK)
357         OSSL_PARAM_END
358     };
359     return known_settable_ctx_params;
360 }
361 
hkdf_common_get_ctx_params(KDF_HKDF * ctx,OSSL_PARAM params[])362 static int hkdf_common_get_ctx_params(KDF_HKDF *ctx, OSSL_PARAM params[])
363 {
364     OSSL_PARAM *p;
365 
366     if (ossl_param_is_empty(params))
367         return 1;
368 
369     if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL) {
370         size_t sz = kdf_hkdf_size(ctx);
371 
372         if (sz == 0)
373             return 0;
374         if (!OSSL_PARAM_set_size_t(p, sz))
375             return 0;
376     }
377 
378     if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_INFO)) != NULL) {
379         if (ctx->info == NULL || ctx->info_len == 0)
380             p->return_size = 0;
381         else if (!OSSL_PARAM_set_octet_string(p, ctx->info, ctx->info_len))
382             return 0;
383     }
384 
385     return 1;
386 }
387 
kdf_hkdf_get_ctx_params(void * vctx,OSSL_PARAM params[])388 static int kdf_hkdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
389 {
390     KDF_HKDF *ctx = (KDF_HKDF *)vctx;
391 
392     if (ossl_param_is_empty(params))
393         return 1;
394 
395     if (!hkdf_common_get_ctx_params(ctx, params))
396         return 0;
397 
398     if (!OSSL_FIPS_IND_GET_CTX_PARAM(ctx, params))
399         return 0;
400 
401     return 1;
402 }
403 
kdf_hkdf_gettable_ctx_params(ossl_unused void * ctx,ossl_unused void * provctx)404 static const OSSL_PARAM *kdf_hkdf_gettable_ctx_params(ossl_unused void *ctx,
405                                                       ossl_unused void *provctx)
406 {
407     static const OSSL_PARAM known_gettable_ctx_params[] = {
408         HKDF_COMMON_GETTABLES,
409         OSSL_FIPS_IND_GETTABLE_CTX_PARAM()
410         OSSL_PARAM_END
411     };
412     return known_gettable_ctx_params;
413 }
414 
415 const OSSL_DISPATCH ossl_kdf_hkdf_functions[] = {
416     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_hkdf_new },
417     { OSSL_FUNC_KDF_DUPCTX, (void(*)(void))kdf_hkdf_dup },
418     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_hkdf_free },
419     { OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_hkdf_reset },
420     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_hkdf_derive },
421     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
422       (void(*)(void))kdf_hkdf_settable_ctx_params },
423     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_hkdf_set_ctx_params },
424     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
425       (void(*)(void))kdf_hkdf_gettable_ctx_params },
426     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_hkdf_get_ctx_params },
427     OSSL_DISPATCH_END
428 };
429 
430 /*
431  * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
432  * Section 2 (https://tools.ietf.org/html/rfc5869#section-2) and
433  * "Cryptographic Extraction and Key Derivation: The HKDF Scheme"
434  * Section 4.2 (https://eprint.iacr.org/2010/264.pdf).
435  *
436  * From the paper:
437  *   The scheme HKDF is specified as:
438  *     HKDF(XTS, SKM, CTXinfo, L) = K(1) | K(2) | ... | K(t)
439  *
440  *     where:
441  *       SKM is source key material
442  *       XTS is extractor salt (which may be null or constant)
443  *       CTXinfo is context information (may be null)
444  *       L is the number of key bits to be produced by KDF
445  *       k is the output length in bits of the hash function used with HMAC
446  *       t = ceil(L/k)
447  *       the value K(t) is truncated to its first d = L mod k bits.
448  *
449  * From RFC 5869:
450  *   2.2.  Step 1: Extract
451  *     HKDF-Extract(salt, IKM) -> PRK
452  *   2.3.  Step 2: Expand
453  *     HKDF-Expand(PRK, info, L) -> OKM
454  */
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)455 static int HKDF(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
456                 const unsigned char *salt, size_t salt_len,
457                 const unsigned char *ikm, size_t ikm_len,
458                 const unsigned char *info, size_t info_len,
459                 unsigned char *okm, size_t okm_len)
460 {
461     unsigned char prk[EVP_MAX_MD_SIZE];
462     int ret, sz;
463     size_t prk_len;
464 
465     sz = EVP_MD_get_size(evp_md);
466     if (sz <= 0)
467         return 0;
468     prk_len = (size_t)sz;
469 
470     /* Step 1: HKDF-Extract(salt, IKM) -> PRK */
471     if (!HKDF_Extract(libctx, evp_md,
472                       salt, salt_len, ikm, ikm_len, prk, prk_len))
473         return 0;
474 
475     /* Step 2: HKDF-Expand(PRK, info, L) -> OKM */
476     ret = HKDF_Expand(evp_md, prk, prk_len, info, info_len, okm, okm_len);
477     OPENSSL_cleanse(prk, sizeof(prk));
478 
479     return ret;
480 }
481 
482 /*
483  * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
484  * Section 2.2 (https://tools.ietf.org/html/rfc5869#section-2.2).
485  *
486  * 2.2.  Step 1: Extract
487  *
488  *   HKDF-Extract(salt, IKM) -> PRK
489  *
490  *   Options:
491  *      Hash     a hash function; HashLen denotes the length of the
492  *               hash function output in octets
493  *
494  *   Inputs:
495  *      salt     optional salt value (a non-secret random value);
496  *               if not provided, it is set to a string of HashLen zeros.
497  *      IKM      input keying material
498  *
499  *   Output:
500  *      PRK      a pseudorandom key (of HashLen octets)
501  *
502  *   The output PRK is calculated as follows:
503  *
504  *   PRK = HMAC-Hash(salt, IKM)
505  */
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)506 static int HKDF_Extract(OSSL_LIB_CTX *libctx, const EVP_MD *evp_md,
507                         const unsigned char *salt, size_t salt_len,
508                         const unsigned char *ikm, size_t ikm_len,
509                         unsigned char *prk, size_t prk_len)
510 {
511     int sz = EVP_MD_get_size(evp_md);
512 
513     if (sz <= 0)
514         return 0;
515     if (prk_len != (size_t)sz) {
516         ERR_raise(ERR_LIB_PROV, PROV_R_WRONG_OUTPUT_BUFFER_SIZE);
517         return 0;
518     }
519     /* calc: PRK = HMAC-Hash(salt, IKM) */
520     return
521         EVP_Q_mac(libctx, "HMAC", NULL, EVP_MD_get0_name(evp_md), NULL, salt,
522                   salt_len, ikm, ikm_len, prk, EVP_MD_get_size(evp_md), NULL)
523         != NULL;
524 }
525 
526 /*
527  * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
528  * Section 2.3 (https://tools.ietf.org/html/rfc5869#section-2.3).
529  *
530  * 2.3.  Step 2: Expand
531  *
532  *   HKDF-Expand(PRK, info, L) -> OKM
533  *
534  *   Options:
535  *      Hash     a hash function; HashLen denotes the length of the
536  *               hash function output in octets
537  *
538  *   Inputs:
539  *      PRK      a pseudorandom key of at least HashLen octets
540  *               (usually, the output from the extract step)
541  *      info     optional context and application specific information
542  *               (can be a zero-length string)
543  *      L        length of output keying material in octets
544  *               (<= 255*HashLen)
545  *
546  *   Output:
547  *      OKM      output keying material (of L octets)
548  *
549  *   The output OKM is calculated as follows:
550  *
551  *   N = ceil(L/HashLen)
552  *   T = T(1) | T(2) | T(3) | ... | T(N)
553  *   OKM = first L octets of T
554  *
555  *   where:
556  *   T(0) = empty string (zero length)
557  *   T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
558  *   T(2) = HMAC-Hash(PRK, T(1) | info | 0x02)
559  *   T(3) = HMAC-Hash(PRK, T(2) | info | 0x03)
560  *   ...
561  *
562  *   (where the constant concatenated to the end of each T(n) is a
563  *   single octet.)
564  */
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)565 static int HKDF_Expand(const EVP_MD *evp_md,
566                        const unsigned char *prk, size_t prk_len,
567                        const unsigned char *info, size_t info_len,
568                        unsigned char *okm, size_t okm_len)
569 {
570     HMAC_CTX *hmac;
571     int ret = 0, sz;
572     unsigned int i;
573     unsigned char prev[EVP_MAX_MD_SIZE];
574     size_t done_len = 0, dig_len, n;
575 
576     sz = EVP_MD_get_size(evp_md);
577     if (sz <= 0)
578         return 0;
579     dig_len = (size_t)sz;
580 
581     /* calc: N = ceil(L/HashLen) */
582     n = okm_len / dig_len;
583     if (okm_len % dig_len)
584         n++;
585 
586     if (n > 255 || okm == NULL)
587         return 0;
588 
589     if ((hmac = HMAC_CTX_new()) == NULL)
590         return 0;
591 
592     if (!HMAC_Init_ex(hmac, prk, prk_len, evp_md, NULL))
593         goto err;
594 
595     for (i = 1; i <= n; i++) {
596         size_t copy_len;
597         const unsigned char ctr = i;
598 
599         /* calc: T(i) = HMAC-Hash(PRK, T(i - 1) | info | i) */
600         if (i > 1) {
601             if (!HMAC_Init_ex(hmac, NULL, 0, NULL, NULL))
602                 goto err;
603 
604             if (!HMAC_Update(hmac, prev, dig_len))
605                 goto err;
606         }
607 
608         if (!HMAC_Update(hmac, info, info_len))
609             goto err;
610 
611         if (!HMAC_Update(hmac, &ctr, 1))
612             goto err;
613 
614         if (!HMAC_Final(hmac, prev, NULL))
615             goto err;
616 
617         copy_len = (dig_len > okm_len - done_len) ?
618                        okm_len - done_len :
619                        dig_len;
620 
621         memcpy(okm + done_len, prev, copy_len);
622 
623         done_len += copy_len;
624     }
625     ret = 1;
626 
627  err:
628     OPENSSL_cleanse(prev, sizeof(prev));
629     HMAC_CTX_free(hmac);
630     return ret;
631 }
632 
633 /*
634  * TLS uses slight variations of the above and for FIPS validation purposes,
635  * they need to be present here.
636  * Refer to RFC 8446 section 7 for specific details.
637  */
638 
639 /*
640  * Given a |secret|; a |label| of length |labellen|; and |data| of length
641  * |datalen| (e.g. typically a hash of the handshake messages), derive a new
642  * secret |outlen| bytes long and store it in the location pointed to be |out|.
643  * The |data| value may be zero length. Returns 1 on success and 0 on failure.
644  */
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)645 static int prov_tls13_hkdf_expand(const EVP_MD *md,
646                                   const unsigned char *key, size_t keylen,
647                                   const unsigned char *prefix, size_t prefixlen,
648                                   const unsigned char *label, size_t labellen,
649                                   const unsigned char *data, size_t datalen,
650                                   unsigned char *out, size_t outlen)
651 {
652     size_t hkdflabellen;
653     unsigned char hkdflabel[HKDF_MAXBUF];
654     WPACKET pkt;
655 
656     /*
657      * 2 bytes for length of derived secret + 1 byte for length of combined
658      * prefix and label + bytes for the label itself + 1 byte length of hash
659      * + bytes for the hash itself.  We've got the maximum the KDF can handle
660      * which should always be sufficient.
661      */
662     if (!WPACKET_init_static_len(&pkt, hkdflabel, sizeof(hkdflabel), 0)
663             || !WPACKET_put_bytes_u16(&pkt, outlen)
664             || !WPACKET_start_sub_packet_u8(&pkt)
665             || !WPACKET_memcpy(&pkt, prefix, prefixlen)
666             || !WPACKET_memcpy(&pkt, label, labellen)
667             || !WPACKET_close(&pkt)
668             || !WPACKET_sub_memcpy_u8(&pkt, data, (data == NULL) ? 0 : datalen)
669             || !WPACKET_get_total_written(&pkt, &hkdflabellen)
670             || !WPACKET_finish(&pkt)) {
671         WPACKET_cleanup(&pkt);
672         return 0;
673     }
674 
675     return HKDF_Expand(md, key, keylen, hkdflabel, hkdflabellen,
676                        out, outlen);
677 }
678 
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)679 static int prov_tls13_hkdf_generate_secret(OSSL_LIB_CTX *libctx,
680                                            const EVP_MD *md,
681                                            const unsigned char *prevsecret,
682                                            size_t prevsecretlen,
683                                            const unsigned char *insecret,
684                                            size_t insecretlen,
685                                            const unsigned char *prefix,
686                                            size_t prefixlen,
687                                            const unsigned char *label,
688                                            size_t labellen,
689                                            unsigned char *out, size_t outlen)
690 {
691     size_t mdlen;
692     int ret;
693     unsigned char preextractsec[EVP_MAX_MD_SIZE];
694     /* Always filled with zeros */
695     static const unsigned char default_zeros[EVP_MAX_MD_SIZE];
696 
697     ret = EVP_MD_get_size(md);
698     /* Ensure cast to size_t is safe */
699     if (ret <= 0)
700         return 0;
701     mdlen = (size_t)ret;
702 
703     if (insecret == NULL) {
704         insecret = default_zeros;
705         insecretlen = mdlen;
706     }
707     if (prevsecret == NULL) {
708         prevsecret = default_zeros;
709         prevsecretlen = mdlen;
710     } else {
711         EVP_MD_CTX *mctx = EVP_MD_CTX_new();
712         unsigned char hash[EVP_MAX_MD_SIZE];
713 
714         /* The pre-extract derive step uses a hash of no messages */
715         if (mctx == NULL
716                 || EVP_DigestInit_ex(mctx, md, NULL) <= 0
717                 || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
718             EVP_MD_CTX_free(mctx);
719             return 0;
720         }
721         EVP_MD_CTX_free(mctx);
722 
723         /* Generate the pre-extract secret */
724         if (!prov_tls13_hkdf_expand(md, prevsecret, prevsecretlen,
725                                     prefix, prefixlen, label, labellen,
726                                     hash, mdlen, preextractsec, mdlen))
727             return 0;
728         prevsecret = preextractsec;
729         prevsecretlen = mdlen;
730     }
731 
732     ret = HKDF_Extract(libctx, md, prevsecret, prevsecretlen,
733                        insecret, insecretlen, out, outlen);
734 
735     if (prevsecret == preextractsec)
736         OPENSSL_cleanse(preextractsec, mdlen);
737     return ret;
738 }
739 
740 #ifdef FIPS_MODULE
fips_tls1_3_digest_check_passed(KDF_HKDF * ctx,const EVP_MD * md)741 static int fips_tls1_3_digest_check_passed(KDF_HKDF *ctx, const EVP_MD *md)
742 {
743     OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
744     /*
745      * Perform digest check
746      *
747      * According to RFC 8446 appendix B.4, the valid hash functions are
748      * specified in FIPS 180-4. However, it only lists SHA2-256 and SHA2-384 in
749      * the table. ACVP also only lists the same set of hash functions.
750      */
751     int digest_unapproved = !EVP_MD_is_a(md, SN_sha256)
752         && !EVP_MD_is_a(md, SN_sha384);
753 
754     if (digest_unapproved) {
755         if (!OSSL_FIPS_IND_ON_UNAPPROVED(ctx, OSSL_FIPS_IND_SETTABLE0,
756                                          libctx, "TLS13 KDF", "Digest",
757                                          ossl_fips_config_tls13_kdf_digest_check)) {
758             ERR_raise(ERR_LIB_PROV, PROV_R_DIGEST_NOT_ALLOWED);
759             return 0;
760         }
761     }
762     return 1;
763 }
764 
765 /*
766  * Calculate the correct length of the secret key.
767  *
768  * RFC 8446:
769  *   If a given secret is not available, then the 0-value consisting of a
770  *   string of Hash.length bytes set to zeros is used.
771  */
fips_tls1_3_key_size(KDF_HKDF * ctx)772 static size_t fips_tls1_3_key_size(KDF_HKDF *ctx)
773 {
774     const EVP_MD *md = ossl_prov_digest_md(&ctx->digest);
775     size_t key_size = 0;
776 
777     if (ctx->key != NULL)
778         key_size = ctx->key_len;
779     else if (md != NULL)
780         key_size = EVP_MD_size(md);
781 
782     return key_size;
783 }
784 
fips_tls1_3_key_check_passed(KDF_HKDF * ctx)785 static int fips_tls1_3_key_check_passed(KDF_HKDF *ctx)
786 {
787     OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(ctx->provctx);
788     int key_approved = ossl_kdf_check_key_size(fips_tls1_3_key_size(ctx));
789 
790     if (!key_approved) {
791         if (!OSSL_FIPS_IND_ON_UNAPPROVED(ctx, OSSL_FIPS_IND_SETTABLE1,
792                                          libctx, "TLS13 KDF", "Key size",
793                                          ossl_fips_config_tls13_kdf_key_check)) {
794             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
795             return 0;
796         }
797     }
798     return 1;
799 }
800 #endif
801 
kdf_tls1_3_derive(void * vctx,unsigned char * key,size_t keylen,const OSSL_PARAM params[])802 static int kdf_tls1_3_derive(void *vctx, unsigned char *key, size_t keylen,
803                              const OSSL_PARAM params[])
804 {
805     KDF_HKDF *ctx = (KDF_HKDF *)vctx;
806     const EVP_MD *md;
807 
808     if (!ossl_prov_is_running() || !kdf_tls1_3_set_ctx_params(ctx, params))
809         return 0;
810 
811     md = ossl_prov_digest_md(&ctx->digest);
812     if (md == NULL) {
813         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
814         return 0;
815     }
816 
817     switch (ctx->mode) {
818     default:
819         return 0;
820 
821     case EVP_KDF_HKDF_MODE_EXTRACT_ONLY:
822         return prov_tls13_hkdf_generate_secret(PROV_LIBCTX_OF(ctx->provctx),
823                                                md,
824                                                ctx->salt, ctx->salt_len,
825                                                ctx->key, ctx->key_len,
826                                                ctx->prefix, ctx->prefix_len,
827                                                ctx->label, ctx->label_len,
828                                                key, keylen);
829 
830     case EVP_KDF_HKDF_MODE_EXPAND_ONLY:
831         return prov_tls13_hkdf_expand(md, ctx->key, ctx->key_len,
832                                       ctx->prefix, ctx->prefix_len,
833                                       ctx->label, ctx->label_len,
834                                       ctx->data, ctx->data_len,
835                                       key, keylen);
836     }
837 }
838 
kdf_tls1_3_set_ctx_params(void * vctx,const OSSL_PARAM params[])839 static int kdf_tls1_3_set_ctx_params(void *vctx, const OSSL_PARAM params[])
840 {
841     const OSSL_PARAM *p;
842     KDF_HKDF *ctx = vctx;
843 
844     if (ossl_param_is_empty(params))
845         return 1;
846 
847     if (!OSSL_FIPS_IND_SET_CTX_PARAM(ctx, OSSL_FIPS_IND_SETTABLE0, params,
848                                      OSSL_KDF_PARAM_FIPS_DIGEST_CHECK))
849         return 0;
850     if (!OSSL_FIPS_IND_SET_CTX_PARAM(ctx, OSSL_FIPS_IND_SETTABLE1, params,
851                                      OSSL_KDF_PARAM_FIPS_KEY_CHECK))
852         return 0;
853 
854     if (!hkdf_common_set_ctx_params(ctx, params))
855         return 0;
856 
857     if (ctx->mode == EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND) {
858         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
859         return 0;
860     }
861 
862     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PREFIX)) != NULL) {
863         OPENSSL_free(ctx->prefix);
864         ctx->prefix = NULL;
865         if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->prefix, 0,
866                                          &ctx->prefix_len))
867             return 0;
868     }
869 
870     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_LABEL)) != NULL) {
871         OPENSSL_free(ctx->label);
872         ctx->label = NULL;
873         if (!OSSL_PARAM_get_octet_string(p, (void **)&ctx->label, 0,
874                                          &ctx->label_len))
875             return 0;
876     }
877 
878     OPENSSL_clear_free(ctx->data, ctx->data_len);
879     ctx->data = NULL;
880     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_DATA)) != NULL
881             && !OSSL_PARAM_get_octet_string(p, (void **)&ctx->data, 0,
882                                             &ctx->data_len))
883         return 0;
884 
885 #ifdef FIPS_MODULE
886     if (OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_DIGEST) != NULL) {
887         const EVP_MD *md = ossl_prov_digest_md(&ctx->digest);
888 
889         if (!fips_tls1_3_digest_check_passed(ctx, md))
890             return 0;
891     }
892 
893     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY)) != NULL)
894         if (!fips_tls1_3_key_check_passed(ctx))
895             return 0;
896 #endif
897 
898     return 1;
899 }
900 
kdf_tls1_3_settable_ctx_params(ossl_unused void * ctx,ossl_unused void * provctx)901 static const OSSL_PARAM *kdf_tls1_3_settable_ctx_params(ossl_unused void *ctx,
902                                                         ossl_unused void *provctx)
903 {
904     static const OSSL_PARAM known_settable_ctx_params[] = {
905         HKDF_COMMON_SETTABLES,
906         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PREFIX, NULL, 0),
907         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_LABEL, NULL, 0),
908         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_DATA, NULL, 0),
909         OSSL_FIPS_IND_SETTABLE_CTX_PARAM(OSSL_KDF_PARAM_FIPS_DIGEST_CHECK)
910         OSSL_FIPS_IND_SETTABLE_CTX_PARAM(OSSL_KDF_PARAM_FIPS_KEY_CHECK)
911         OSSL_PARAM_END
912     };
913     return known_settable_ctx_params;
914 }
915 
kdf_tls1_3_get_ctx_params(void * vctx,OSSL_PARAM params[])916 static int kdf_tls1_3_get_ctx_params(void *vctx, OSSL_PARAM params[])
917 {
918     KDF_HKDF *ctx = (KDF_HKDF *)vctx;
919 
920     if (ossl_param_is_empty(params))
921         return 1;
922 
923     if (!hkdf_common_get_ctx_params(ctx, params))
924         return 0;
925 
926     if (!OSSL_FIPS_IND_GET_CTX_PARAM(ctx, params))
927         return 0;
928 
929     return 1;
930 }
931 
kdf_tls1_3_gettable_ctx_params(ossl_unused void * ctx,ossl_unused void * provctx)932 static const OSSL_PARAM *kdf_tls1_3_gettable_ctx_params(ossl_unused void *ctx,
933                                                         ossl_unused void *provctx)
934 {
935     static const OSSL_PARAM known_gettable_ctx_params[] = {
936         HKDF_COMMON_GETTABLES,
937         OSSL_FIPS_IND_GETTABLE_CTX_PARAM()
938         OSSL_PARAM_END
939     };
940     return known_gettable_ctx_params;
941 }
942 
943 const OSSL_DISPATCH ossl_kdf_tls1_3_kdf_functions[] = {
944     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_hkdf_new },
945     { OSSL_FUNC_KDF_DUPCTX, (void(*)(void))kdf_hkdf_dup },
946     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_hkdf_free },
947     { OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_hkdf_reset },
948     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_tls1_3_derive },
949     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
950       (void(*)(void))kdf_tls1_3_settable_ctx_params },
951     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_tls1_3_set_ctx_params },
952     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
953       (void(*)(void))kdf_tls1_3_gettable_ctx_params },
954     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_tls1_3_get_ctx_params },
955     OSSL_DISPATCH_END
956 };
957