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