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