xref: /freebsd/crypto/openssl/ssl/tls13_enc.c (revision cc9e6590773dba57440750c124173ed531349a06)
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     BIO *bio;
475 #endif
476 
477     if (which & SSL3_CC_READ) {
478         if (s->enc_read_ctx != NULL) {
479             EVP_CIPHER_CTX_reset(s->enc_read_ctx);
480         } else {
481             s->enc_read_ctx = EVP_CIPHER_CTX_new();
482             if (s->enc_read_ctx == NULL) {
483                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
484                          SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
485                 goto err;
486             }
487         }
488         ciph_ctx = s->enc_read_ctx;
489         iv = s->read_iv;
490 
491         RECORD_LAYER_reset_read_sequence(&s->rlayer);
492     } else {
493         s->statem.enc_write_state = ENC_WRITE_STATE_INVALID;
494         if (s->enc_write_ctx != NULL) {
495             EVP_CIPHER_CTX_reset(s->enc_write_ctx);
496         } else {
497             s->enc_write_ctx = EVP_CIPHER_CTX_new();
498             if (s->enc_write_ctx == NULL) {
499                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
500                          SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
501                 goto err;
502             }
503         }
504         ciph_ctx = s->enc_write_ctx;
505         iv = s->write_iv;
506 
507         RECORD_LAYER_reset_write_sequence(&s->rlayer);
508     }
509 
510     if (((which & SSL3_CC_CLIENT) && (which & SSL3_CC_WRITE))
511             || ((which & SSL3_CC_SERVER) && (which & SSL3_CC_READ))) {
512         if (which & SSL3_CC_EARLY) {
513             EVP_MD_CTX *mdctx = NULL;
514             long handlen;
515             void *hdata;
516             unsigned int hashlenui;
517             const SSL_CIPHER *sslcipher = SSL_SESSION_get0_cipher(s->session);
518 
519             insecret = s->early_secret;
520             label = client_early_traffic;
521             labellen = sizeof(client_early_traffic) - 1;
522             log_label = CLIENT_EARLY_LABEL;
523 
524             handlen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
525             if (handlen <= 0) {
526                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
527                          SSL_F_TLS13_CHANGE_CIPHER_STATE,
528                          SSL_R_BAD_HANDSHAKE_LENGTH);
529                 goto err;
530             }
531 
532             if (s->early_data_state == SSL_EARLY_DATA_CONNECTING
533                     && s->max_early_data > 0
534                     && s->session->ext.max_early_data == 0) {
535                 /*
536                  * If we are attempting to send early data, and we've decided to
537                  * actually do it but max_early_data in s->session is 0 then we
538                  * must be using an external PSK.
539                  */
540                 if (!ossl_assert(s->psksession != NULL
541                         && s->max_early_data ==
542                            s->psksession->ext.max_early_data)) {
543                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
544                              SSL_F_TLS13_CHANGE_CIPHER_STATE,
545                              ERR_R_INTERNAL_ERROR);
546                     goto err;
547                 }
548                 sslcipher = SSL_SESSION_get0_cipher(s->psksession);
549             }
550             if (sslcipher == NULL) {
551                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
552                          SSL_F_TLS13_CHANGE_CIPHER_STATE, SSL_R_BAD_PSK);
553                 goto err;
554             }
555 
556             /*
557              * We need to calculate the handshake digest using the digest from
558              * the session. We haven't yet selected our ciphersuite so we can't
559              * use ssl_handshake_md().
560              */
561             mdctx = EVP_MD_CTX_new();
562             if (mdctx == NULL) {
563                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
564                          SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
565                 goto err;
566             }
567             cipher = EVP_get_cipherbynid(SSL_CIPHER_get_cipher_nid(sslcipher));
568             md = ssl_md(sslcipher->algorithm2);
569             if (md == NULL || !EVP_DigestInit_ex(mdctx, md, NULL)
570                     || !EVP_DigestUpdate(mdctx, hdata, handlen)
571                     || !EVP_DigestFinal_ex(mdctx, hashval, &hashlenui)) {
572                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
573                          SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
574                 EVP_MD_CTX_free(mdctx);
575                 goto err;
576             }
577             hashlen = hashlenui;
578             EVP_MD_CTX_free(mdctx);
579 
580             if (!tls13_hkdf_expand(s, md, insecret,
581                                    early_exporter_master_secret,
582                                    sizeof(early_exporter_master_secret) - 1,
583                                    hashval, hashlen,
584                                    s->early_exporter_master_secret, hashlen,
585                                    1)) {
586                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
587                          SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
588                 goto err;
589             }
590 
591             if (!ssl_log_secret(s, EARLY_EXPORTER_SECRET_LABEL,
592                                 s->early_exporter_master_secret, hashlen)) {
593                 /* SSLfatal() already called */
594                 goto err;
595             }
596         } else if (which & SSL3_CC_HANDSHAKE) {
597             insecret = s->handshake_secret;
598             finsecret = s->client_finished_secret;
599             finsecretlen = EVP_MD_size(ssl_handshake_md(s));
600             label = client_handshake_traffic;
601             labellen = sizeof(client_handshake_traffic) - 1;
602             log_label = CLIENT_HANDSHAKE_LABEL;
603             /*
604              * The handshake hash used for the server read/client write handshake
605              * traffic secret is the same as the hash for the server
606              * write/client read handshake traffic secret. However, if we
607              * processed early data then we delay changing the server
608              * read/client write cipher state until later, and the handshake
609              * hashes have moved on. Therefore we use the value saved earlier
610              * when we did the server write/client read change cipher state.
611              */
612             hash = s->handshake_traffic_hash;
613         } else {
614             insecret = s->master_secret;
615             label = client_application_traffic;
616             labellen = sizeof(client_application_traffic) - 1;
617             log_label = CLIENT_APPLICATION_LABEL;
618             /*
619              * For this we only use the handshake hashes up until the server
620              * Finished hash. We do not include the client's Finished, which is
621              * what ssl_handshake_hash() would give us. Instead we use the
622              * previously saved value.
623              */
624             hash = s->server_finished_hash;
625         }
626     } else {
627         /* Early data never applies to client-read/server-write */
628         if (which & SSL3_CC_HANDSHAKE) {
629             insecret = s->handshake_secret;
630             finsecret = s->server_finished_secret;
631             finsecretlen = EVP_MD_size(ssl_handshake_md(s));
632             label = server_handshake_traffic;
633             labellen = sizeof(server_handshake_traffic) - 1;
634             log_label = SERVER_HANDSHAKE_LABEL;
635         } else {
636             insecret = s->master_secret;
637             label = server_application_traffic;
638             labellen = sizeof(server_application_traffic) - 1;
639             log_label = SERVER_APPLICATION_LABEL;
640         }
641     }
642 
643     if (!(which & SSL3_CC_EARLY)) {
644         md = ssl_handshake_md(s);
645         cipher = s->s3->tmp.new_sym_enc;
646         if (!ssl3_digest_cached_records(s, 1)
647                 || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
648             /* SSLfatal() already called */;
649             goto err;
650         }
651     }
652 
653     /*
654      * Save the hash of handshakes up to now for use when we calculate the
655      * client application traffic secret
656      */
657     if (label == server_application_traffic)
658         memcpy(s->server_finished_hash, hashval, hashlen);
659 
660     if (label == server_handshake_traffic)
661         memcpy(s->handshake_traffic_hash, hashval, hashlen);
662 
663     if (label == client_application_traffic) {
664         /*
665          * We also create the resumption master secret, but this time use the
666          * hash for the whole handshake including the Client Finished
667          */
668         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
669                                resumption_master_secret,
670                                sizeof(resumption_master_secret) - 1,
671                                hashval, hashlen, s->resumption_master_secret,
672                                hashlen, 1)) {
673             /* SSLfatal() already called */
674             goto err;
675         }
676     }
677 
678     /* check whether cipher is known */
679     if(!ossl_assert(cipher != NULL))
680         goto err;
681 
682     if (!derive_secret_key_and_iv(s, which & SSL3_CC_WRITE, md, cipher,
683                                   insecret, hash, label, labellen, secret, key,
684                                   iv, ciph_ctx)) {
685         /* SSLfatal() already called */
686         goto err;
687     }
688 
689     if (label == server_application_traffic) {
690         memcpy(s->server_app_traffic_secret, secret, hashlen);
691         /* Now we create the exporter master secret */
692         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
693                                exporter_master_secret,
694                                sizeof(exporter_master_secret) - 1,
695                                hash, hashlen, s->exporter_master_secret,
696                                hashlen, 1)) {
697             /* SSLfatal() already called */
698             goto err;
699         }
700 
701         if (!ssl_log_secret(s, EXPORTER_SECRET_LABEL, s->exporter_master_secret,
702                             hashlen)) {
703             /* SSLfatal() already called */
704             goto err;
705         }
706     } else if (label == client_application_traffic)
707         memcpy(s->client_app_traffic_secret, secret, hashlen);
708 
709     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
710         /* SSLfatal() already called */
711         goto err;
712     }
713 
714     if (finsecret != NULL
715             && !tls13_derive_finishedkey(s, ssl_handshake_md(s), secret,
716                                          finsecret, finsecretlen)) {
717         /* SSLfatal() already called */
718         goto err;
719     }
720 
721     if (!s->server && label == client_early_traffic)
722         s->statem.enc_write_state = ENC_WRITE_STATE_WRITE_PLAIN_ALERTS;
723     else
724         s->statem.enc_write_state = ENC_WRITE_STATE_VALID;
725 #ifndef OPENSSL_NO_KTLS
726 # if defined(OPENSSL_KTLS_TLS13)
727     if (!(which & SSL3_CC_WRITE)
728             || !(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     bio = s->wbio;
745 
746     if (!ossl_assert(bio != NULL)) {
747         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_CHANGE_CIPHER_STATE,
748                  ERR_R_INTERNAL_ERROR);
749         goto err;
750     }
751 
752     /* All future data will get encrypted by ktls. Flush the BIO or skip ktls */
753     if (BIO_flush(bio) <= 0)
754         goto skip_ktls;
755 
756     /* configure kernel crypto structure */
757     if (!ktls_configure_crypto(s, cipher, ciph_ctx,
758                                RECORD_LAYER_get_write_sequence(&s->rlayer),
759                                &crypto_info, NULL, iv, key, NULL, 0))
760         goto skip_ktls;
761 
762     /* ktls works with user provided buffers directly */
763     if (BIO_set_ktls(bio, &crypto_info, which & SSL3_CC_WRITE))
764         ssl3_release_write_buffer(s);
765 skip_ktls:
766 # endif
767 #endif
768     ret = 1;
769  err:
770     OPENSSL_cleanse(key, sizeof(key));
771     OPENSSL_cleanse(secret, sizeof(secret));
772     return ret;
773 }
774 
775 int tls13_update_key(SSL *s, int sending)
776 {
777 #ifdef CHARSET_EBCDIC
778   static const unsigned char application_traffic[] = { 0x74, 0x72 ,0x61 ,0x66 ,0x66 ,0x69 ,0x63 ,0x20 ,0x75 ,0x70 ,0x64, 0x00};
779 #else
780   static const unsigned char application_traffic[] = "traffic upd";
781 #endif
782     const EVP_MD *md = ssl_handshake_md(s);
783     size_t hashlen = EVP_MD_size(md);
784     unsigned char key[EVP_MAX_KEY_LENGTH];
785     unsigned char *insecret, *iv;
786     unsigned char secret[EVP_MAX_MD_SIZE];
787     EVP_CIPHER_CTX *ciph_ctx;
788     int ret = 0;
789 
790     if (s->server == sending)
791         insecret = s->server_app_traffic_secret;
792     else
793         insecret = s->client_app_traffic_secret;
794 
795     if (sending) {
796         s->statem.enc_write_state = ENC_WRITE_STATE_INVALID;
797         iv = s->write_iv;
798         ciph_ctx = s->enc_write_ctx;
799         RECORD_LAYER_reset_write_sequence(&s->rlayer);
800     } else {
801         iv = s->read_iv;
802         ciph_ctx = s->enc_read_ctx;
803         RECORD_LAYER_reset_read_sequence(&s->rlayer);
804     }
805 
806     if (!derive_secret_key_and_iv(s, sending, ssl_handshake_md(s),
807                                   s->s3->tmp.new_sym_enc, insecret, NULL,
808                                   application_traffic,
809                                   sizeof(application_traffic) - 1, secret, key,
810                                   iv, ciph_ctx)) {
811         /* SSLfatal() already called */
812         goto err;
813     }
814 
815     memcpy(insecret, secret, hashlen);
816 
817     s->statem.enc_write_state = ENC_WRITE_STATE_VALID;
818     ret = 1;
819  err:
820     OPENSSL_cleanse(key, sizeof(key));
821     OPENSSL_cleanse(secret, sizeof(secret));
822     return ret;
823 }
824 
825 int tls13_alert_code(int code)
826 {
827     /* There are 2 additional alerts in TLSv1.3 compared to TLSv1.2 */
828     if (code == SSL_AD_MISSING_EXTENSION || code == SSL_AD_CERTIFICATE_REQUIRED)
829         return code;
830 
831     return tls1_alert_code(code);
832 }
833 
834 int tls13_export_keying_material(SSL *s, unsigned char *out, size_t olen,
835                                  const char *label, size_t llen,
836                                  const unsigned char *context,
837                                  size_t contextlen, int use_context)
838 {
839     unsigned char exportsecret[EVP_MAX_MD_SIZE];
840 #ifdef CHARSET_EBCDIC
841     static const unsigned char exporterlabel[] = {0x65, 0x78, 0x70, 0x6F, 0x72, 0x74, 0x65, 0x72, 0x00};
842 #else
843     static const unsigned char exporterlabel[] = "exporter";
844 #endif
845     unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
846     const EVP_MD *md = ssl_handshake_md(s);
847     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
848     unsigned int hashsize, datalen;
849     int ret = 0;
850 
851     if (ctx == NULL || !ossl_statem_export_allowed(s))
852         goto err;
853 
854     if (!use_context)
855         contextlen = 0;
856 
857     if (EVP_DigestInit_ex(ctx, md, NULL) <= 0
858             || EVP_DigestUpdate(ctx, context, contextlen) <= 0
859             || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
860             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
861             || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
862             || !tls13_hkdf_expand(s, md, s->exporter_master_secret,
863                                   (const unsigned char *)label, llen,
864                                   data, datalen, exportsecret, hashsize, 0)
865             || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
866                                   sizeof(exporterlabel) - 1, hash, hashsize,
867                                   out, olen, 0))
868         goto err;
869 
870     ret = 1;
871  err:
872     EVP_MD_CTX_free(ctx);
873     return ret;
874 }
875 
876 int tls13_export_keying_material_early(SSL *s, unsigned char *out, size_t olen,
877                                        const char *label, size_t llen,
878                                        const unsigned char *context,
879                                        size_t contextlen)
880 {
881 #ifdef CHARSET_EBCDIC
882   static const unsigned char exporterlabel[] = {0x65, 0x78, 0x70, 0x6F, 0x72, 0x74, 0x65, 0x72, 0x00};
883 #else
884   static const unsigned char exporterlabel[] = "exporter";
885 #endif
886     unsigned char exportsecret[EVP_MAX_MD_SIZE];
887     unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
888     const EVP_MD *md;
889     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
890     unsigned int hashsize, datalen;
891     int ret = 0;
892     const SSL_CIPHER *sslcipher;
893 
894     if (ctx == NULL || !ossl_statem_export_early_allowed(s))
895         goto err;
896 
897     if (!s->server && s->max_early_data > 0
898             && s->session->ext.max_early_data == 0)
899         sslcipher = SSL_SESSION_get0_cipher(s->psksession);
900     else
901         sslcipher = SSL_SESSION_get0_cipher(s->session);
902 
903     md = ssl_md(sslcipher->algorithm2);
904 
905     /*
906      * Calculate the hash value and store it in |data|. The reason why
907      * the empty string is used is that the definition of TLS-Exporter
908      * is like so:
909      *
910      * TLS-Exporter(label, context_value, key_length) =
911      *     HKDF-Expand-Label(Derive-Secret(Secret, label, ""),
912      *                       "exporter", Hash(context_value), key_length)
913      *
914      * Derive-Secret(Secret, Label, Messages) =
915      *       HKDF-Expand-Label(Secret, Label,
916      *                         Transcript-Hash(Messages), Hash.length)
917      *
918      * Here Transcript-Hash is the cipher suite hash algorithm.
919      */
920     if (EVP_DigestInit_ex(ctx, md, NULL) <= 0
921             || EVP_DigestUpdate(ctx, context, contextlen) <= 0
922             || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
923             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
924             || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
925             || !tls13_hkdf_expand(s, md, s->early_exporter_master_secret,
926                                   (const unsigned char *)label, llen,
927                                   data, datalen, exportsecret, hashsize, 0)
928             || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
929                                   sizeof(exporterlabel) - 1, hash, hashsize,
930                                   out, olen, 0))
931         goto err;
932 
933     ret = 1;
934  err:
935     EVP_MD_CTX_free(ctx);
936     return ret;
937 }
938