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