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