xref: /freebsd/crypto/openssl/ssl/tls13_enc.c (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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 #include <stdlib.h>
11 #include "ssl_local.h"
12 #include "internal/ktls.h"
13 #include "record/record_local.h"
14 #include "internal/cryptlib.h"
15 #include <openssl/evp.h>
16 #include <openssl/kdf.h>
17 #include <openssl/core_names.h>
18 
19 #define TLS13_MAX_LABEL_LEN     249
20 
21 #ifdef CHARSET_EBCDIC
22 static const unsigned char label_prefix[] = { 0x74, 0x6C, 0x73, 0x31, 0x33, 0x20, 0x00 };
23 #else
24 static const unsigned char label_prefix[] = "tls13 ";
25 #endif
26 
27 /*
28  * Given a |secret|; a |label| of length |labellen|; and |data| of length
29  * |datalen| (e.g. typically a hash of the handshake messages), derive a new
30  * secret |outlen| bytes long and store it in the location pointed to be |out|.
31  * The |data| value may be zero length. Any errors will be treated as fatal if
32  * |fatal| is set. Returns 1 on success  0 on failure.
33  */
34 int tls13_hkdf_expand(SSL *s, const EVP_MD *md, const unsigned char *secret,
35                       const unsigned char *label, size_t labellen,
36                       const unsigned char *data, size_t datalen,
37                       unsigned char *out, size_t outlen, int fatal)
38 {
39     EVP_KDF *kdf = EVP_KDF_fetch(s->ctx->libctx, OSSL_KDF_NAME_TLS1_3_KDF,
40                                  s->ctx->propq);
41     EVP_KDF_CTX *kctx;
42     OSSL_PARAM params[7], *p = params;
43     int mode = EVP_PKEY_HKDEF_MODE_EXPAND_ONLY;
44     const char *mdname = EVP_MD_get0_name(md);
45     int ret;
46     size_t hashlen;
47 
48     kctx = EVP_KDF_CTX_new(kdf);
49     EVP_KDF_free(kdf);
50     if (kctx == NULL)
51         return 0;
52 
53     if (labellen > TLS13_MAX_LABEL_LEN) {
54         if (fatal) {
55             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
56         } else {
57             /*
58              * Probably we have been called from SSL_export_keying_material(),
59              * or SSL_export_keying_material_early().
60              */
61             ERR_raise(ERR_LIB_SSL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
62         }
63         EVP_KDF_CTX_free(kctx);
64         return 0;
65     }
66 
67     if ((ret = EVP_MD_get_size(md)) <= 0) {
68         EVP_KDF_CTX_free(kctx);
69         if (fatal)
70             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
71         else
72             ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
73         return 0;
74     }
75     hashlen = (size_t)ret;
76 
77     *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
78     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
79                                             (char *)mdname, 0);
80     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
81                                              (unsigned char *)secret, hashlen);
82     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PREFIX,
83                                              (unsigned char *)label_prefix,
84                                              sizeof(label_prefix) - 1);
85     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_LABEL,
86                                              (unsigned char *)label, labellen);
87     if (data != NULL)
88         *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_DATA,
89                                                  (unsigned char *)data,
90                                                  datalen);
91     *p++ = OSSL_PARAM_construct_end();
92 
93     ret = EVP_KDF_derive(kctx, out, outlen, params) <= 0;
94     EVP_KDF_CTX_free(kctx);
95 
96     if (ret != 0) {
97         if (fatal)
98             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
99         else
100             ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
101     }
102 
103     return ret == 0;
104 }
105 
106 /*
107  * Given a |secret| generate a |key| of length |keylen| bytes. Returns 1 on
108  * success  0 on failure.
109  */
110 int tls13_derive_key(SSL *s, const EVP_MD *md, const unsigned char *secret,
111                      unsigned char *key, size_t keylen)
112 {
113 #ifdef CHARSET_EBCDIC
114   static const unsigned char keylabel[] ={ 0x6B, 0x65, 0x79, 0x00 };
115 #else
116   static const unsigned char keylabel[] = "key";
117 #endif
118 
119     return tls13_hkdf_expand(s, md, secret, keylabel, sizeof(keylabel) - 1,
120                              NULL, 0, key, keylen, 1);
121 }
122 
123 /*
124  * Given a |secret| generate an |iv| of length |ivlen| bytes. Returns 1 on
125  * success  0 on failure.
126  */
127 int tls13_derive_iv(SSL *s, const EVP_MD *md, const unsigned char *secret,
128                     unsigned char *iv, size_t ivlen)
129 {
130 #ifdef CHARSET_EBCDIC
131   static const unsigned char ivlabel[] = { 0x69, 0x76, 0x00 };
132 #else
133   static const unsigned char ivlabel[] = "iv";
134 #endif
135 
136     return tls13_hkdf_expand(s, md, secret, ivlabel, sizeof(ivlabel) - 1,
137                              NULL, 0, iv, ivlen, 1);
138 }
139 
140 int tls13_derive_finishedkey(SSL *s, const EVP_MD *md,
141                              const unsigned char *secret,
142                              unsigned char *fin, size_t finlen)
143 {
144 #ifdef CHARSET_EBCDIC
145   static const unsigned char finishedlabel[] = { 0x66, 0x69, 0x6E, 0x69, 0x73, 0x68, 0x65, 0x64, 0x00 };
146 #else
147   static const unsigned char finishedlabel[] = "finished";
148 #endif
149 
150     return tls13_hkdf_expand(s, md, secret, finishedlabel,
151                              sizeof(finishedlabel) - 1, NULL, 0, fin, finlen, 1);
152 }
153 
154 /*
155  * Given the previous secret |prevsecret| and a new input secret |insecret| of
156  * length |insecretlen|, generate a new secret and store it in the location
157  * pointed to by |outsecret|. Returns 1 on success  0 on failure.
158  */
159 int tls13_generate_secret(SSL *s, const EVP_MD *md,
160                           const unsigned char *prevsecret,
161                           const unsigned char *insecret,
162                           size_t insecretlen,
163                           unsigned char *outsecret)
164 {
165     size_t mdlen;
166     int mdleni;
167     int ret;
168     EVP_KDF *kdf;
169     EVP_KDF_CTX *kctx;
170     OSSL_PARAM params[7], *p = params;
171     int mode = EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY;
172     const char *mdname = EVP_MD_get0_name(md);
173 #ifdef CHARSET_EBCDIC
174     static const char derived_secret_label[] = { 0x64, 0x65, 0x72, 0x69, 0x76, 0x65, 0x64, 0x00 };
175 #else
176     static const char derived_secret_label[] = "derived";
177 #endif
178 
179     kdf = EVP_KDF_fetch(s->ctx->libctx, OSSL_KDF_NAME_TLS1_3_KDF, s->ctx->propq);
180     kctx = EVP_KDF_CTX_new(kdf);
181     EVP_KDF_free(kdf);
182     if (kctx == NULL) {
183         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
184         return 0;
185     }
186 
187     mdleni = EVP_MD_get_size(md);
188     /* Ensure cast to size_t is safe */
189     if (!ossl_assert(mdleni >= 0)) {
190         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
191         EVP_KDF_CTX_free(kctx);
192         return 0;
193     }
194     mdlen = (size_t)mdleni;
195 
196     *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
197     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
198                                             (char *)mdname, 0);
199     if (insecret != NULL)
200         *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
201                                                  (unsigned char *)insecret,
202                                                  insecretlen);
203     if (prevsecret != NULL)
204         *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT,
205                                                  (unsigned char *)prevsecret, mdlen);
206     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PREFIX,
207                                              (unsigned char *)label_prefix,
208                                              sizeof(label_prefix) - 1);
209     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_LABEL,
210                                              (unsigned char *)derived_secret_label,
211                                              sizeof(derived_secret_label) - 1);
212     *p++ = OSSL_PARAM_construct_end();
213 
214     ret = EVP_KDF_derive(kctx, outsecret, mdlen, params) <= 0;
215 
216     if (ret != 0)
217         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
218 
219     EVP_KDF_CTX_free(kctx);
220     return ret == 0;
221 }
222 
223 /*
224  * Given an input secret |insecret| of length |insecretlen| generate the
225  * handshake secret. This requires the early secret to already have been
226  * generated. Returns 1 on success  0 on failure.
227  */
228 int tls13_generate_handshake_secret(SSL *s, const unsigned char *insecret,
229                                 size_t insecretlen)
230 {
231     /* Calls SSLfatal() if required */
232     return tls13_generate_secret(s, ssl_handshake_md(s), s->early_secret,
233                                  insecret, insecretlen,
234                                  (unsigned char *)&s->handshake_secret);
235 }
236 
237 /*
238  * Given the handshake secret |prev| of length |prevlen| generate the master
239  * secret and store its length in |*secret_size|. Returns 1 on success  0 on
240  * failure.
241  */
242 int tls13_generate_master_secret(SSL *s, unsigned char *out,
243                                  unsigned char *prev, size_t prevlen,
244                                  size_t *secret_size)
245 {
246     const EVP_MD *md = ssl_handshake_md(s);
247 
248     *secret_size = EVP_MD_get_size(md);
249     /* Calls SSLfatal() if required */
250     return tls13_generate_secret(s, md, prev, NULL, 0, out);
251 }
252 
253 /*
254  * Generates the mac for the Finished message. Returns the length of the MAC or
255  * 0 on error.
256  */
257 size_t tls13_final_finish_mac(SSL *s, const char *str, size_t slen,
258                              unsigned char *out)
259 {
260     const EVP_MD *md = ssl_handshake_md(s);
261     const char *mdname = EVP_MD_get0_name(md);
262     unsigned char hash[EVP_MAX_MD_SIZE];
263     unsigned char finsecret[EVP_MAX_MD_SIZE];
264     unsigned char *key = NULL;
265     size_t len = 0, hashlen;
266     OSSL_PARAM params[2], *p = params;
267 
268     if (md == NULL)
269         return 0;
270 
271     /* Safe to cast away const here since we're not "getting" any data */
272     if (s->ctx->propq != NULL)
273         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_PROPERTIES,
274                                                 (char *)s->ctx->propq,
275                                                 0);
276     *p = OSSL_PARAM_construct_end();
277 
278     if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen)) {
279         /* SSLfatal() already called */
280         goto err;
281     }
282 
283     if (str == s->method->ssl3_enc->server_finished_label) {
284         key = s->server_finished_secret;
285     } else if (SSL_IS_FIRST_HANDSHAKE(s)) {
286         key = s->client_finished_secret;
287     } else {
288         if (!tls13_derive_finishedkey(s, md,
289                                       s->client_app_traffic_secret,
290                                       finsecret, hashlen))
291             goto err;
292         key = finsecret;
293     }
294 
295     if (!EVP_Q_mac(s->ctx->libctx, "HMAC", s->ctx->propq, mdname,
296                    params, key, hashlen, hash, hashlen,
297                    /* outsize as per sizeof(peer_finish_md) */
298                    out, EVP_MAX_MD_SIZE * 2, &len)) {
299         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
300         goto err;
301     }
302 
303  err:
304     OPENSSL_cleanse(finsecret, sizeof(finsecret));
305     return len;
306 }
307 
308 /*
309  * There isn't really a key block in TLSv1.3, but we still need this function
310  * for initialising the cipher and hash. Returns 1 on success or 0 on failure.
311  */
312 int tls13_setup_key_block(SSL *s)
313 {
314     const EVP_CIPHER *c;
315     const EVP_MD *hash;
316 
317     s->session->cipher = s->s3.tmp.new_cipher;
318     if (!ssl_cipher_get_evp(s->ctx, s->session, &c, &hash, NULL, NULL, NULL,
319                             0)) {
320         /* Error is already recorded */
321         SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
322         return 0;
323     }
324 
325     ssl_evp_cipher_free(s->s3.tmp.new_sym_enc);
326     s->s3.tmp.new_sym_enc = c;
327     ssl_evp_md_free(s->s3.tmp.new_hash);
328     s->s3.tmp.new_hash = hash;
329 
330     return 1;
331 }
332 
333 static int derive_secret_key_and_iv(SSL *s, int sending, const EVP_MD *md,
334                                     const EVP_CIPHER *ciph,
335                                     const unsigned char *insecret,
336                                     const unsigned char *hash,
337                                     const unsigned char *label,
338                                     size_t labellen, unsigned char *secret,
339                                     unsigned char *key, unsigned char *iv,
340                                     EVP_CIPHER_CTX *ciph_ctx)
341 {
342     size_t ivlen, keylen, taglen;
343     int hashleni = EVP_MD_get_size(md);
344     size_t hashlen;
345 
346     /* Ensure cast to size_t is safe */
347     if (!ossl_assert(hashleni >= 0)) {
348         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
349         return 0;
350     }
351     hashlen = (size_t)hashleni;
352 
353     if (!tls13_hkdf_expand(s, md, insecret, label, labellen, hash, hashlen,
354                            secret, hashlen, 1)) {
355         /* SSLfatal() already called */
356         return 0;
357     }
358 
359     keylen = EVP_CIPHER_get_key_length(ciph);
360     if (EVP_CIPHER_get_mode(ciph) == EVP_CIPH_CCM_MODE) {
361         uint32_t algenc;
362 
363         ivlen = EVP_CCM_TLS_IV_LEN;
364         if (s->s3.tmp.new_cipher != NULL) {
365             algenc = s->s3.tmp.new_cipher->algorithm_enc;
366         } else if (s->session->cipher != NULL) {
367             /* We've not selected a cipher yet - we must be doing early data */
368             algenc = s->session->cipher->algorithm_enc;
369         } else if (s->psksession != NULL && s->psksession->cipher != NULL) {
370             /* We must be doing early data with out-of-band PSK */
371             algenc = s->psksession->cipher->algorithm_enc;
372         } else {
373             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
374             return 0;
375         }
376         if (algenc & (SSL_AES128CCM8 | SSL_AES256CCM8))
377             taglen = EVP_CCM8_TLS_TAG_LEN;
378          else
379             taglen = EVP_CCM_TLS_TAG_LEN;
380     } else {
381         ivlen = EVP_CIPHER_get_iv_length(ciph);
382         taglen = 0;
383     }
384 
385     if (!tls13_derive_key(s, md, secret, key, keylen)
386             || !tls13_derive_iv(s, md, secret, iv, ivlen)) {
387         /* SSLfatal() already called */
388         return 0;
389     }
390 
391     if (EVP_CipherInit_ex(ciph_ctx, ciph, NULL, NULL, NULL, sending) <= 0
392         || EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL) <= 0
393         || (taglen != 0 && EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_TAG,
394                                                 taglen, NULL) <= 0)
395         || EVP_CipherInit_ex(ciph_ctx, NULL, NULL, key, NULL, -1) <= 0) {
396         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
397         return 0;
398     }
399 
400     return 1;
401 }
402 
403 int tls13_change_cipher_state(SSL *s, int which)
404 {
405 #ifdef CHARSET_EBCDIC
406   static const unsigned char client_early_traffic[]       = {0x63, 0x20, 0x65, 0x20,       /*traffic*/0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x00};
407   static const unsigned char client_handshake_traffic[]   = {0x63, 0x20, 0x68, 0x73, 0x20, /*traffic*/0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x00};
408   static const unsigned char client_application_traffic[] = {0x63, 0x20, 0x61, 0x70, 0x20, /*traffic*/0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x00};
409   static const unsigned char server_handshake_traffic[]   = {0x73, 0x20, 0x68, 0x73, 0x20, /*traffic*/0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x00};
410   static const unsigned char server_application_traffic[] = {0x73, 0x20, 0x61, 0x70, 0x20, /*traffic*/0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x00};
411   static const unsigned char exporter_master_secret[] = {0x65, 0x78, 0x70, 0x20,                    /* master*/  0x6D, 0x61, 0x73, 0x74, 0x65, 0x72, 0x00};
412   static const unsigned char resumption_master_secret[] = {0x72, 0x65, 0x73, 0x20,                  /* master*/  0x6D, 0x61, 0x73, 0x74, 0x65, 0x72, 0x00};
413   static const unsigned char early_exporter_master_secret[] = {0x65, 0x20, 0x65, 0x78, 0x70, 0x20,  /* master*/  0x6D, 0x61, 0x73, 0x74, 0x65, 0x72, 0x00};
414 #else
415     static const unsigned char client_early_traffic[] = "c e traffic";
416     static const unsigned char client_handshake_traffic[] = "c hs traffic";
417     static const unsigned char client_application_traffic[] = "c ap traffic";
418     static const unsigned char server_handshake_traffic[] = "s hs traffic";
419     static const unsigned char server_application_traffic[] = "s ap traffic";
420     static const unsigned char exporter_master_secret[] = "exp master";
421     static const unsigned char resumption_master_secret[] = "res master";
422     static const unsigned char early_exporter_master_secret[] = "e exp master";
423 #endif
424     unsigned char *iv;
425     unsigned char key[EVP_MAX_KEY_LENGTH];
426     unsigned char secret[EVP_MAX_MD_SIZE];
427     unsigned char hashval[EVP_MAX_MD_SIZE];
428     unsigned char *hash = hashval;
429     unsigned char *insecret;
430     unsigned char *finsecret = NULL;
431     const char *log_label = NULL;
432     EVP_CIPHER_CTX *ciph_ctx;
433     size_t finsecretlen = 0;
434     const unsigned char *label;
435     size_t labellen, hashlen = 0;
436     int ret = 0;
437     const EVP_MD *md = NULL;
438     const EVP_CIPHER *cipher = NULL;
439 #if !defined(OPENSSL_NO_KTLS) && defined(OPENSSL_KTLS_TLS13)
440     ktls_crypto_info_t crypto_info;
441     void *rl_sequence;
442     BIO *bio;
443 #endif
444 
445     if (which & SSL3_CC_READ) {
446         if (s->enc_read_ctx != NULL) {
447             EVP_CIPHER_CTX_reset(s->enc_read_ctx);
448         } else {
449             s->enc_read_ctx = EVP_CIPHER_CTX_new();
450             if (s->enc_read_ctx == NULL) {
451                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
452                 goto err;
453             }
454         }
455         ciph_ctx = s->enc_read_ctx;
456         iv = s->read_iv;
457 
458         RECORD_LAYER_reset_read_sequence(&s->rlayer);
459     } else {
460         s->statem.enc_write_state = ENC_WRITE_STATE_INVALID;
461         if (s->enc_write_ctx != NULL) {
462             EVP_CIPHER_CTX_reset(s->enc_write_ctx);
463         } else {
464             s->enc_write_ctx = EVP_CIPHER_CTX_new();
465             if (s->enc_write_ctx == NULL) {
466                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
467                 goto err;
468             }
469         }
470         ciph_ctx = s->enc_write_ctx;
471         iv = s->write_iv;
472 
473         RECORD_LAYER_reset_write_sequence(&s->rlayer);
474     }
475 
476     if (((which & SSL3_CC_CLIENT) && (which & SSL3_CC_WRITE))
477             || ((which & SSL3_CC_SERVER) && (which & SSL3_CC_READ))) {
478         if (which & SSL3_CC_EARLY) {
479             EVP_MD_CTX *mdctx = NULL;
480             long handlen;
481             void *hdata;
482             unsigned int hashlenui;
483             const SSL_CIPHER *sslcipher = SSL_SESSION_get0_cipher(s->session);
484 
485             insecret = s->early_secret;
486             label = client_early_traffic;
487             labellen = sizeof(client_early_traffic) - 1;
488             log_label = CLIENT_EARLY_LABEL;
489 
490             handlen = BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
491             if (handlen <= 0) {
492                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);
493                 goto err;
494             }
495 
496             if (s->early_data_state == SSL_EARLY_DATA_CONNECTING
497                     && s->max_early_data > 0
498                     && s->session->ext.max_early_data == 0) {
499                 /*
500                  * If we are attempting to send early data, and we've decided to
501                  * actually do it but max_early_data in s->session is 0 then we
502                  * must be using an external PSK.
503                  */
504                 if (!ossl_assert(s->psksession != NULL
505                         && s->max_early_data ==
506                            s->psksession->ext.max_early_data)) {
507                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
508                     goto err;
509                 }
510                 sslcipher = SSL_SESSION_get0_cipher(s->psksession);
511             }
512             if (sslcipher == NULL) {
513                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_PSK);
514                 goto err;
515             }
516 
517             /*
518              * We need to calculate the handshake digest using the digest from
519              * the session. We haven't yet selected our ciphersuite so we can't
520              * use ssl_handshake_md().
521              */
522             mdctx = EVP_MD_CTX_new();
523             if (mdctx == NULL) {
524                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
525                 goto err;
526             }
527 
528             /*
529              * This ups the ref count on cipher so we better make sure we free
530              * it again
531              */
532             if (!ssl_cipher_get_evp_cipher(s->ctx, sslcipher, &cipher)) {
533                 /* Error is already recorded */
534                 SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
535                 EVP_MD_CTX_free(mdctx);
536                 goto err;
537             }
538 
539             md = ssl_md(s->ctx, sslcipher->algorithm2);
540             if (md == NULL || !EVP_DigestInit_ex(mdctx, md, NULL)
541                     || !EVP_DigestUpdate(mdctx, hdata, handlen)
542                     || !EVP_DigestFinal_ex(mdctx, hashval, &hashlenui)) {
543                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
544                 EVP_MD_CTX_free(mdctx);
545                 goto err;
546             }
547             hashlen = hashlenui;
548             EVP_MD_CTX_free(mdctx);
549 
550             if (!tls13_hkdf_expand(s, md, insecret,
551                                    early_exporter_master_secret,
552                                    sizeof(early_exporter_master_secret) - 1,
553                                    hashval, hashlen,
554                                    s->early_exporter_master_secret, hashlen,
555                                    1)) {
556                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
557                 goto err;
558             }
559 
560             if (!ssl_log_secret(s, EARLY_EXPORTER_SECRET_LABEL,
561                                 s->early_exporter_master_secret, hashlen)) {
562                 /* SSLfatal() already called */
563                 goto err;
564             }
565         } else if (which & SSL3_CC_HANDSHAKE) {
566             insecret = s->handshake_secret;
567             finsecret = s->client_finished_secret;
568             finsecretlen = EVP_MD_get_size(ssl_handshake_md(s));
569             label = client_handshake_traffic;
570             labellen = sizeof(client_handshake_traffic) - 1;
571             log_label = CLIENT_HANDSHAKE_LABEL;
572             /*
573              * The handshake hash used for the server read/client write handshake
574              * traffic secret is the same as the hash for the server
575              * write/client read handshake traffic secret. However, if we
576              * processed early data then we delay changing the server
577              * read/client write cipher state until later, and the handshake
578              * hashes have moved on. Therefore we use the value saved earlier
579              * when we did the server write/client read change cipher state.
580              */
581             hash = s->handshake_traffic_hash;
582         } else {
583             insecret = s->master_secret;
584             label = client_application_traffic;
585             labellen = sizeof(client_application_traffic) - 1;
586             log_label = CLIENT_APPLICATION_LABEL;
587             /*
588              * For this we only use the handshake hashes up until the server
589              * Finished hash. We do not include the client's Finished, which is
590              * what ssl_handshake_hash() would give us. Instead we use the
591              * previously saved value.
592              */
593             hash = s->server_finished_hash;
594         }
595     } else {
596         /* Early data never applies to client-read/server-write */
597         if (which & SSL3_CC_HANDSHAKE) {
598             insecret = s->handshake_secret;
599             finsecret = s->server_finished_secret;
600             finsecretlen = EVP_MD_get_size(ssl_handshake_md(s));
601             label = server_handshake_traffic;
602             labellen = sizeof(server_handshake_traffic) - 1;
603             log_label = SERVER_HANDSHAKE_LABEL;
604         } else {
605             insecret = s->master_secret;
606             label = server_application_traffic;
607             labellen = sizeof(server_application_traffic) - 1;
608             log_label = SERVER_APPLICATION_LABEL;
609         }
610     }
611 
612     if (!(which & SSL3_CC_EARLY)) {
613         md = ssl_handshake_md(s);
614         cipher = s->s3.tmp.new_sym_enc;
615         if (!ssl3_digest_cached_records(s, 1)
616                 || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
617             /* SSLfatal() already called */;
618             goto err;
619         }
620     }
621 
622     /*
623      * Save the hash of handshakes up to now for use when we calculate the
624      * client application traffic secret
625      */
626     if (label == server_application_traffic)
627         memcpy(s->server_finished_hash, hashval, hashlen);
628 
629     if (label == server_handshake_traffic)
630         memcpy(s->handshake_traffic_hash, hashval, hashlen);
631 
632     if (label == client_application_traffic) {
633         /*
634          * We also create the resumption master secret, but this time use the
635          * hash for the whole handshake including the Client Finished
636          */
637         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
638                                resumption_master_secret,
639                                sizeof(resumption_master_secret) - 1,
640                                hashval, hashlen, s->resumption_master_secret,
641                                hashlen, 1)) {
642             /* SSLfatal() already called */
643             goto err;
644         }
645     }
646 
647     /* check whether cipher is known */
648     if(!ossl_assert(cipher != NULL))
649         goto err;
650 
651     if (!derive_secret_key_and_iv(s, which & SSL3_CC_WRITE, md, cipher,
652                                   insecret, hash, label, labellen, secret, key,
653                                   iv, ciph_ctx)) {
654         /* SSLfatal() already called */
655         goto err;
656     }
657 
658     if (label == server_application_traffic) {
659         memcpy(s->server_app_traffic_secret, secret, hashlen);
660         /* Now we create the exporter master secret */
661         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
662                                exporter_master_secret,
663                                sizeof(exporter_master_secret) - 1,
664                                hash, hashlen, s->exporter_master_secret,
665                                hashlen, 1)) {
666             /* SSLfatal() already called */
667             goto err;
668         }
669 
670         if (!ssl_log_secret(s, EXPORTER_SECRET_LABEL, s->exporter_master_secret,
671                             hashlen)) {
672             /* SSLfatal() already called */
673             goto err;
674         }
675     } else if (label == client_application_traffic)
676         memcpy(s->client_app_traffic_secret, secret, hashlen);
677 
678     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
679         /* SSLfatal() already called */
680         goto err;
681     }
682 
683     if (finsecret != NULL
684             && !tls13_derive_finishedkey(s, ssl_handshake_md(s), secret,
685                                          finsecret, finsecretlen)) {
686         /* SSLfatal() already called */
687         goto err;
688     }
689 
690     if (!s->server && label == client_early_traffic)
691         s->statem.enc_write_state = ENC_WRITE_STATE_WRITE_PLAIN_ALERTS;
692     else
693         s->statem.enc_write_state = ENC_WRITE_STATE_VALID;
694 #ifndef OPENSSL_NO_KTLS
695 # if defined(OPENSSL_KTLS_TLS13)
696     if (!(which & SSL3_CC_APPLICATION)
697             || (s->options & SSL_OP_ENABLE_KTLS) == 0)
698         goto skip_ktls;
699 
700     /* ktls supports only the maximum fragment size */
701     if (ssl_get_max_send_fragment(s) != SSL3_RT_MAX_PLAIN_LENGTH)
702         goto skip_ktls;
703 
704     /* ktls does not support record padding */
705     if (s->record_padding_cb != NULL)
706         goto skip_ktls;
707 
708     /* check that cipher is supported */
709     if (!ktls_check_supported_cipher(s, cipher, ciph_ctx))
710         goto skip_ktls;
711 
712     if (which & SSL3_CC_WRITE)
713         bio = s->wbio;
714     else
715         bio = s->rbio;
716 
717     if (!ossl_assert(bio != NULL)) {
718         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
719         goto err;
720     }
721 
722     /* All future data will get encrypted by ktls. Flush the BIO or skip ktls */
723     if (which & SSL3_CC_WRITE) {
724         if (BIO_flush(bio) <= 0)
725             goto skip_ktls;
726     }
727 
728     /* configure kernel crypto structure */
729     if (which & SSL3_CC_WRITE)
730         rl_sequence = RECORD_LAYER_get_write_sequence(&s->rlayer);
731     else
732         rl_sequence = RECORD_LAYER_get_read_sequence(&s->rlayer);
733 
734     if (!ktls_configure_crypto(s, cipher, ciph_ctx, rl_sequence, &crypto_info,
735                                which & SSL3_CC_WRITE, iv, key, NULL, 0))
736         goto skip_ktls;
737 
738     /* ktls works with user provided buffers directly */
739     if (BIO_set_ktls(bio, &crypto_info, which & SSL3_CC_WRITE)) {
740         if (which & SSL3_CC_WRITE)
741             ssl3_release_write_buffer(s);
742     }
743 skip_ktls:
744 # endif
745 #endif
746     ret = 1;
747  err:
748     if ((which & SSL3_CC_EARLY) != 0) {
749         /* We up-refed this so now we need to down ref */
750         ssl_evp_cipher_free(cipher);
751     }
752     OPENSSL_cleanse(key, sizeof(key));
753     OPENSSL_cleanse(secret, sizeof(secret));
754     return ret;
755 }
756 
757 int tls13_update_key(SSL *s, int sending)
758 {
759 #ifdef CHARSET_EBCDIC
760   static const unsigned char application_traffic[] = { 0x74, 0x72 ,0x61 ,0x66 ,0x66 ,0x69 ,0x63 ,0x20 ,0x75 ,0x70 ,0x64, 0x00};
761 #else
762   static const unsigned char application_traffic[] = "traffic upd";
763 #endif
764     const EVP_MD *md = ssl_handshake_md(s);
765     size_t hashlen;
766     unsigned char key[EVP_MAX_KEY_LENGTH];
767     unsigned char *insecret, *iv;
768     unsigned char secret[EVP_MAX_MD_SIZE];
769     char *log_label;
770     EVP_CIPHER_CTX *ciph_ctx;
771     int ret = 0, l;
772 
773     if ((l = EVP_MD_get_size(md)) <= 0) {
774         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
775         return 0;
776     }
777     hashlen = (size_t)l;
778 
779     if (s->server == sending)
780         insecret = s->server_app_traffic_secret;
781     else
782         insecret = s->client_app_traffic_secret;
783 
784     if (sending) {
785         s->statem.enc_write_state = ENC_WRITE_STATE_INVALID;
786         iv = s->write_iv;
787         ciph_ctx = s->enc_write_ctx;
788         RECORD_LAYER_reset_write_sequence(&s->rlayer);
789     } else {
790         iv = s->read_iv;
791         ciph_ctx = s->enc_read_ctx;
792         RECORD_LAYER_reset_read_sequence(&s->rlayer);
793     }
794 
795     if (!derive_secret_key_and_iv(s, sending, md,
796                                   s->s3.tmp.new_sym_enc, insecret, NULL,
797                                   application_traffic,
798                                   sizeof(application_traffic) - 1, secret, key,
799                                   iv, ciph_ctx)) {
800         /* SSLfatal() already called */
801         goto err;
802     }
803 
804     memcpy(insecret, secret, hashlen);
805 
806     /* Call Key log on successful traffic secret update */
807     log_label = s->server == sending ? SERVER_APPLICATION_N_LABEL : CLIENT_APPLICATION_N_LABEL;
808     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
809         /* SSLfatal() already called */
810         goto err;
811     }
812 
813     s->statem.enc_write_state = ENC_WRITE_STATE_VALID;
814     ret = 1;
815  err:
816     OPENSSL_cleanse(key, sizeof(key));
817     OPENSSL_cleanse(secret, sizeof(secret));
818     return ret;
819 }
820 
821 int tls13_alert_code(int code)
822 {
823     /* There are 2 additional alerts in TLSv1.3 compared to TLSv1.2 */
824     if (code == SSL_AD_MISSING_EXTENSION || code == SSL_AD_CERTIFICATE_REQUIRED)
825         return code;
826 
827     return tls1_alert_code(code);
828 }
829 
830 int tls13_export_keying_material(SSL *s, unsigned char *out, size_t olen,
831                                  const char *label, size_t llen,
832                                  const unsigned char *context,
833                                  size_t contextlen, int use_context)
834 {
835     unsigned char exportsecret[EVP_MAX_MD_SIZE];
836 #ifdef CHARSET_EBCDIC
837     static const unsigned char exporterlabel[] = {0x65, 0x78, 0x70, 0x6F, 0x72, 0x74, 0x65, 0x72, 0x00};
838 #else
839     static const unsigned char exporterlabel[] = "exporter";
840 #endif
841     unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
842     const EVP_MD *md = ssl_handshake_md(s);
843     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
844     unsigned int hashsize, datalen;
845     int ret = 0;
846 
847     if (ctx == NULL || md == NULL || !ossl_statem_export_allowed(s))
848         goto err;
849 
850     if (!use_context)
851         contextlen = 0;
852 
853     if (EVP_DigestInit_ex(ctx, md, NULL) <= 0
854             || EVP_DigestUpdate(ctx, context, contextlen) <= 0
855             || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
856             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
857             || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
858             || !tls13_hkdf_expand(s, md, s->exporter_master_secret,
859                                   (const unsigned char *)label, llen,
860                                   data, datalen, exportsecret, hashsize, 0)
861             || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
862                                   sizeof(exporterlabel) - 1, hash, hashsize,
863                                   out, olen, 0))
864         goto err;
865 
866     ret = 1;
867  err:
868     EVP_MD_CTX_free(ctx);
869     return ret;
870 }
871 
872 int tls13_export_keying_material_early(SSL *s, unsigned char *out, size_t olen,
873                                        const char *label, size_t llen,
874                                        const unsigned char *context,
875                                        size_t contextlen)
876 {
877 #ifdef CHARSET_EBCDIC
878   static const unsigned char exporterlabel[] = {0x65, 0x78, 0x70, 0x6F, 0x72, 0x74, 0x65, 0x72, 0x00};
879 #else
880   static const unsigned char exporterlabel[] = "exporter";
881 #endif
882     unsigned char exportsecret[EVP_MAX_MD_SIZE];
883     unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
884     const EVP_MD *md;
885     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
886     unsigned int hashsize, datalen;
887     int ret = 0;
888     const SSL_CIPHER *sslcipher;
889 
890     if (ctx == NULL || !ossl_statem_export_early_allowed(s))
891         goto err;
892 
893     if (!s->server && s->max_early_data > 0
894             && s->session->ext.max_early_data == 0)
895         sslcipher = SSL_SESSION_get0_cipher(s->psksession);
896     else
897         sslcipher = SSL_SESSION_get0_cipher(s->session);
898 
899     md = ssl_md(s->ctx, sslcipher->algorithm2);
900 
901     /*
902      * Calculate the hash value and store it in |data|. The reason why
903      * the empty string is used is that the definition of TLS-Exporter
904      * is like so:
905      *
906      * TLS-Exporter(label, context_value, key_length) =
907      *     HKDF-Expand-Label(Derive-Secret(Secret, label, ""),
908      *                       "exporter", Hash(context_value), key_length)
909      *
910      * Derive-Secret(Secret, Label, Messages) =
911      *       HKDF-Expand-Label(Secret, Label,
912      *                         Transcript-Hash(Messages), Hash.length)
913      *
914      * Here Transcript-Hash is the cipher suite hash algorithm.
915      */
916     if (md == NULL
917             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
918             || EVP_DigestUpdate(ctx, context, contextlen) <= 0
919             || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
920             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
921             || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
922             || !tls13_hkdf_expand(s, md, s->early_exporter_master_secret,
923                                   (const unsigned char *)label, llen,
924                                   data, datalen, exportsecret, hashsize, 0)
925             || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
926                                   sizeof(exporterlabel) - 1, hash, hashsize,
927                                   out, olen, 0))
928         goto err;
929 
930     ret = 1;
931  err:
932     EVP_MD_CTX_free(ctx);
933     return ret;
934 }
935