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