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