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