56f100371d47e89a8265c5161207d2b0de55220b
[openssl.git] / ssl / tls13_enc.c
1 /*
2  * Copyright 2016-2023 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     int md_size;
251
252     md_size = EVP_MD_get_size(md);
253     if (md_size <= 0) {
254         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
255         return 0;
256     }
257     *secret_size = (size_t)md_size;
258     /* Calls SSLfatal() if required */
259     return tls13_generate_secret(s, md, prev, NULL, 0, out);
260 }
261
262 /*
263  * Generates the mac for the Finished message. Returns the length of the MAC or
264  * 0 on error.
265  */
266 size_t tls13_final_finish_mac(SSL_CONNECTION *s, const char *str, size_t slen,
267                              unsigned char *out)
268 {
269     const EVP_MD *md = ssl_handshake_md(s);
270     const char *mdname = EVP_MD_get0_name(md);
271     unsigned char hash[EVP_MAX_MD_SIZE];
272     unsigned char finsecret[EVP_MAX_MD_SIZE];
273     unsigned char *key = NULL;
274     size_t len = 0, hashlen;
275     OSSL_PARAM params[2], *p = params;
276     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
277
278     if (md == NULL)
279         return 0;
280
281     /* Safe to cast away const here since we're not "getting" any data */
282     if (sctx->propq != NULL)
283         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_PROPERTIES,
284                                                 (char *)sctx->propq,
285                                                 0);
286     *p = OSSL_PARAM_construct_end();
287
288     if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen)) {
289         /* SSLfatal() already called */
290         goto err;
291     }
292
293     if (str == SSL_CONNECTION_GET_SSL(s)->method->ssl3_enc->server_finished_label) {
294         key = s->server_finished_secret;
295     } else if (SSL_IS_FIRST_HANDSHAKE(s)) {
296         key = s->client_finished_secret;
297     } else {
298         if (!tls13_derive_finishedkey(s, md,
299                                       s->client_app_traffic_secret,
300                                       finsecret, hashlen))
301             goto err;
302         key = finsecret;
303     }
304
305     if (!EVP_Q_mac(sctx->libctx, "HMAC", sctx->propq, mdname,
306                    params, key, hashlen, hash, hashlen,
307                    /* outsize as per sizeof(peer_finish_md) */
308                    out, EVP_MAX_MD_SIZE * 2, &len)) {
309         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
310         goto err;
311     }
312
313  err:
314     OPENSSL_cleanse(finsecret, sizeof(finsecret));
315     return len;
316 }
317
318 /*
319  * There isn't really a key block in TLSv1.3, but we still need this function
320  * for initialising the cipher and hash. Returns 1 on success or 0 on failure.
321  */
322 int tls13_setup_key_block(SSL_CONNECTION *s)
323 {
324     const EVP_CIPHER *c;
325     const EVP_MD *hash;
326
327     s->session->cipher = s->s3.tmp.new_cipher;
328     if (!ssl_cipher_get_evp(SSL_CONNECTION_GET_CTX(s), s->session, &c, &hash,
329                             NULL, NULL, NULL, 0)) {
330         /* Error is already recorded */
331         SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
332         return 0;
333     }
334
335     ssl_evp_cipher_free(s->s3.tmp.new_sym_enc);
336     s->s3.tmp.new_sym_enc = c;
337     ssl_evp_md_free(s->s3.tmp.new_hash);
338     s->s3.tmp.new_hash = hash;
339
340     return 1;
341 }
342
343 static int derive_secret_key_and_iv(SSL_CONNECTION *s, const EVP_MD *md,
344                                     const EVP_CIPHER *ciph,
345                                     const unsigned char *insecret,
346                                     const unsigned char *hash,
347                                     const unsigned char *label,
348                                     size_t labellen, unsigned char *secret,
349                                     unsigned char *key, size_t *keylen,
350                                     unsigned char *iv, size_t *ivlen,
351                                     size_t *taglen)
352 {
353     int hashleni = EVP_MD_get_size(md);
354     size_t hashlen;
355     int mode;
356
357     /* Ensure cast to size_t is safe */
358     if (!ossl_assert(hashleni >= 0)) {
359         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
360         return 0;
361     }
362     hashlen = (size_t)hashleni;
363
364     if (!tls13_hkdf_expand(s, md, insecret, label, labellen, hash, hashlen,
365                            secret, hashlen, 1)) {
366         /* SSLfatal() already called */
367         return 0;
368     }
369
370     *keylen = EVP_CIPHER_get_key_length(ciph);
371
372     mode = EVP_CIPHER_get_mode(ciph);
373     if (mode == EVP_CIPH_CCM_MODE) {
374         uint32_t algenc;
375
376         *ivlen = EVP_CCM_TLS_IV_LEN;
377         if (s->s3.tmp.new_cipher != NULL) {
378             algenc = s->s3.tmp.new_cipher->algorithm_enc;
379         } else if (s->session->cipher != NULL) {
380             /* We've not selected a cipher yet - we must be doing early data */
381             algenc = s->session->cipher->algorithm_enc;
382         } else if (s->psksession != NULL && s->psksession->cipher != NULL) {
383             /* We must be doing early data with out-of-band PSK */
384             algenc = s->psksession->cipher->algorithm_enc;
385         } else {
386             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
387             return 0;
388         }
389         if (algenc & (SSL_AES128CCM8 | SSL_AES256CCM8))
390             *taglen = EVP_CCM8_TLS_TAG_LEN;
391          else
392             *taglen = EVP_CCM_TLS_TAG_LEN;
393     } else {
394         int iivlen;
395
396         if (mode == EVP_CIPH_GCM_MODE) {
397             *taglen = EVP_GCM_TLS_TAG_LEN;
398         } else {
399             /* CHACHA20P-POLY1305 */
400             *taglen = EVP_CHACHAPOLY_TLS_TAG_LEN;
401         }
402         iivlen = EVP_CIPHER_get_iv_length(ciph);
403         if (iivlen < 0) {
404             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
405             return 0;
406         }
407         *ivlen = iivlen;
408     }
409
410     if (!tls13_derive_key(s, md, secret, key, *keylen)
411             || !tls13_derive_iv(s, md, secret, iv, *ivlen)) {
412         /* SSLfatal() already called */
413         return 0;
414     }
415
416     return 1;
417 }
418
419 int tls13_change_cipher_state(SSL_CONNECTION *s, int which)
420 {
421     /* ASCII: "c e traffic", in hex for EBCDIC compatibility */
422     static const unsigned char client_early_traffic[] = "\x63\x20\x65\x20\x74\x72\x61\x66\x66\x69\x63";
423     /* ASCII: "c hs traffic", in hex for EBCDIC compatibility */
424     static const unsigned char client_handshake_traffic[] = "\x63\x20\x68\x73\x20\x74\x72\x61\x66\x66\x69\x63";
425     /* ASCII: "c ap traffic", in hex for EBCDIC compatibility */
426     static const unsigned char client_application_traffic[] = "\x63\x20\x61\x70\x20\x74\x72\x61\x66\x66\x69\x63";
427     /* ASCII: "s hs traffic", in hex for EBCDIC compatibility */
428     static const unsigned char server_handshake_traffic[] = "\x73\x20\x68\x73\x20\x74\x72\x61\x66\x66\x69\x63";
429     /* ASCII: "s ap traffic", in hex for EBCDIC compatibility */
430     static const unsigned char server_application_traffic[] = "\x73\x20\x61\x70\x20\x74\x72\x61\x66\x66\x69\x63";
431     /* ASCII: "exp master", in hex for EBCDIC compatibility */
432     static const unsigned char exporter_master_secret[] = "\x65\x78\x70\x20\x6D\x61\x73\x74\x65\x72";
433     /* ASCII: "res master", in hex for EBCDIC compatibility */
434     static const unsigned char resumption_master_secret[] = "\x72\x65\x73\x20\x6D\x61\x73\x74\x65\x72";
435     /* ASCII: "e exp master", in hex for EBCDIC compatibility */
436     static const unsigned char early_exporter_master_secret[] = "\x65\x20\x65\x78\x70\x20\x6D\x61\x73\x74\x65\x72";
437     unsigned char iv[EVP_MAX_IV_LENGTH];
438     unsigned char key[EVP_MAX_KEY_LENGTH];
439     unsigned char secret[EVP_MAX_MD_SIZE];
440     unsigned char hashval[EVP_MAX_MD_SIZE];
441     unsigned char *hash = hashval;
442     unsigned char *insecret;
443     unsigned char *finsecret = NULL;
444     const char *log_label = NULL;
445     int finsecretlen = 0;
446     const unsigned char *label;
447     size_t labellen, hashlen = 0;
448     int ret = 0;
449     const EVP_MD *md = NULL;
450     const EVP_CIPHER *cipher = NULL;
451     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
452     size_t keylen, ivlen, taglen;
453     int level;
454     int direction = (which & SSL3_CC_READ) != 0 ? OSSL_RECORD_DIRECTION_READ
455                                                 : OSSL_RECORD_DIRECTION_WRITE;
456
457     if (((which & SSL3_CC_CLIENT) && (which & SSL3_CC_WRITE))
458             || ((which & SSL3_CC_SERVER) && (which & SSL3_CC_READ))) {
459         if (which & SSL3_CC_EARLY) {
460             EVP_MD_CTX *mdctx = NULL;
461             long handlen;
462             void *hdata;
463             unsigned int hashlenui;
464             const SSL_CIPHER *sslcipher = SSL_SESSION_get0_cipher(s->session);
465
466             insecret = s->early_secret;
467             label = client_early_traffic;
468             labellen = sizeof(client_early_traffic) - 1;
469             log_label = CLIENT_EARLY_LABEL;
470
471             handlen = BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
472             if (handlen <= 0) {
473                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);
474                 goto err;
475             }
476
477             if (s->early_data_state == SSL_EARLY_DATA_CONNECTING
478                     && s->max_early_data > 0
479                     && s->session->ext.max_early_data == 0) {
480                 /*
481                  * If we are attempting to send early data, and we've decided to
482                  * actually do it but max_early_data in s->session is 0 then we
483                  * must be using an external PSK.
484                  */
485                 if (!ossl_assert(s->psksession != NULL
486                         && s->max_early_data ==
487                            s->psksession->ext.max_early_data)) {
488                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
489                     goto err;
490                 }
491                 sslcipher = SSL_SESSION_get0_cipher(s->psksession);
492             }
493             if (sslcipher == NULL) {
494                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_PSK);
495                 goto err;
496             }
497
498             /*
499              * We need to calculate the handshake digest using the digest from
500              * the session. We haven't yet selected our ciphersuite so we can't
501              * use ssl_handshake_md().
502              */
503             mdctx = EVP_MD_CTX_new();
504             if (mdctx == NULL) {
505                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
506                 goto err;
507             }
508
509             /*
510              * This ups the ref count on cipher so we better make sure we free
511              * it again
512              */
513             if (!ssl_cipher_get_evp_cipher(sctx, sslcipher, &cipher)) {
514                 /* Error is already recorded */
515                 SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
516                 EVP_MD_CTX_free(mdctx);
517                 goto err;
518             }
519
520             md = ssl_md(sctx, sslcipher->algorithm2);
521             if (md == NULL || !EVP_DigestInit_ex(mdctx, md, NULL)
522                     || !EVP_DigestUpdate(mdctx, hdata, handlen)
523                     || !EVP_DigestFinal_ex(mdctx, hashval, &hashlenui)) {
524                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
525                 EVP_MD_CTX_free(mdctx);
526                 goto err;
527             }
528             hashlen = hashlenui;
529             EVP_MD_CTX_free(mdctx);
530
531             if (!tls13_hkdf_expand(s, md, insecret,
532                                    early_exporter_master_secret,
533                                    sizeof(early_exporter_master_secret) - 1,
534                                    hashval, hashlen,
535                                    s->early_exporter_master_secret, hashlen,
536                                    1)) {
537                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
538                 goto err;
539             }
540
541             if (!ssl_log_secret(s, EARLY_EXPORTER_SECRET_LABEL,
542                                 s->early_exporter_master_secret, hashlen)) {
543                 /* SSLfatal() already called */
544                 goto err;
545             }
546         } else if (which & SSL3_CC_HANDSHAKE) {
547             insecret = s->handshake_secret;
548             finsecret = s->client_finished_secret;
549             finsecretlen = EVP_MD_get_size(ssl_handshake_md(s));
550             if (finsecretlen <= 0) {
551                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
552                 goto err;
553             }
554             label = client_handshake_traffic;
555             labellen = sizeof(client_handshake_traffic) - 1;
556             log_label = CLIENT_HANDSHAKE_LABEL;
557             /*
558              * The handshake hash used for the server read/client write handshake
559              * traffic secret is the same as the hash for the server
560              * write/client read handshake traffic secret. However, if we
561              * processed early data then we delay changing the server
562              * read/client write cipher state until later, and the handshake
563              * hashes have moved on. Therefore we use the value saved earlier
564              * when we did the server write/client read change cipher state.
565              */
566             hash = s->handshake_traffic_hash;
567         } else {
568             insecret = s->master_secret;
569             label = client_application_traffic;
570             labellen = sizeof(client_application_traffic) - 1;
571             log_label = CLIENT_APPLICATION_LABEL;
572             /*
573              * For this we only use the handshake hashes up until the server
574              * Finished hash. We do not include the client's Finished, which is
575              * what ssl_handshake_hash() would give us. Instead we use the
576              * previously saved value.
577              */
578             hash = s->server_finished_hash;
579         }
580     } else {
581         /* Early data never applies to client-read/server-write */
582         if (which & SSL3_CC_HANDSHAKE) {
583             insecret = s->handshake_secret;
584             finsecret = s->server_finished_secret;
585             finsecretlen = EVP_MD_get_size(ssl_handshake_md(s));
586             if (finsecretlen <= 0) {
587                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
588                 goto err;
589             }
590             label = server_handshake_traffic;
591             labellen = sizeof(server_handshake_traffic) - 1;
592             log_label = SERVER_HANDSHAKE_LABEL;
593         } else {
594             insecret = s->master_secret;
595             label = server_application_traffic;
596             labellen = sizeof(server_application_traffic) - 1;
597             log_label = SERVER_APPLICATION_LABEL;
598         }
599     }
600
601     if (!(which & SSL3_CC_EARLY)) {
602         md = ssl_handshake_md(s);
603         cipher = s->s3.tmp.new_sym_enc;
604         if (!ssl3_digest_cached_records(s, 1)
605                 || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
606             /* SSLfatal() already called */;
607             goto err;
608         }
609     }
610
611     /*
612      * Save the hash of handshakes up to now for use when we calculate the
613      * client application traffic secret
614      */
615     if (label == server_application_traffic)
616         memcpy(s->server_finished_hash, hashval, hashlen);
617
618     if (label == server_handshake_traffic)
619         memcpy(s->handshake_traffic_hash, hashval, hashlen);
620
621     if (label == client_application_traffic) {
622         /*
623          * We also create the resumption master secret, but this time use the
624          * hash for the whole handshake including the Client Finished
625          */
626         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
627                                resumption_master_secret,
628                                sizeof(resumption_master_secret) - 1,
629                                hashval, hashlen, s->resumption_master_secret,
630                                hashlen, 1)) {
631             /* SSLfatal() already called */
632             goto err;
633         }
634     }
635
636     /* check whether cipher is known */
637     if (!ossl_assert(cipher != NULL))
638         goto err;
639
640     if (!derive_secret_key_and_iv(s, md, cipher,
641                                   insecret, hash, label, labellen, secret, key,
642                                   &keylen, iv, &ivlen, &taglen)) {
643         /* SSLfatal() already called */
644         goto err;
645     }
646
647     if (label == server_application_traffic) {
648         memcpy(s->server_app_traffic_secret, secret, hashlen);
649         /* Now we create the exporter master secret */
650         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
651                                exporter_master_secret,
652                                sizeof(exporter_master_secret) - 1,
653                                hash, hashlen, s->exporter_master_secret,
654                                hashlen, 1)) {
655             /* SSLfatal() already called */
656             goto err;
657         }
658
659         if (!ssl_log_secret(s, EXPORTER_SECRET_LABEL, s->exporter_master_secret,
660                             hashlen)) {
661             /* SSLfatal() already called */
662             goto err;
663         }
664     } else if (label == client_application_traffic)
665         memcpy(s->client_app_traffic_secret, secret, hashlen);
666
667     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
668         /* SSLfatal() already called */
669         goto err;
670     }
671
672     if (finsecret != NULL
673             && !tls13_derive_finishedkey(s, ssl_handshake_md(s), secret,
674                                          finsecret, (size_t)finsecretlen)) {
675         /* SSLfatal() already called */
676         goto err;
677     }
678
679     if ((which & SSL3_CC_WRITE) != 0) {
680         if (!s->server && label == client_early_traffic)
681             s->rlayer.wrlmethod->set_plain_alerts(s->rlayer.wrl, 1);
682         else
683             s->rlayer.wrlmethod->set_plain_alerts(s->rlayer.wrl, 0);
684     }
685
686     level = (which & SSL3_CC_EARLY) != 0
687             ? OSSL_RECORD_PROTECTION_LEVEL_EARLY
688             : ((which &SSL3_CC_HANDSHAKE) != 0
689                ? OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE
690                : OSSL_RECORD_PROTECTION_LEVEL_APPLICATION);
691
692     if (!ssl_set_new_record_layer(s, s->version,
693                                   direction,
694                                   level, secret, hashlen, key, keylen, iv,
695                                   ivlen, NULL, 0, cipher, taglen, NID_undef,
696                                   NULL, NULL, md)) {
697         /* SSLfatal already called */
698         goto err;
699     }
700
701     ret = 1;
702  err:
703     if ((which & SSL3_CC_EARLY) != 0) {
704         /* We up-refed this so now we need to down ref */
705         ssl_evp_cipher_free(cipher);
706     }
707     OPENSSL_cleanse(key, sizeof(key));
708     OPENSSL_cleanse(secret, sizeof(secret));
709     return ret;
710 }
711
712 int tls13_update_key(SSL_CONNECTION *s, int sending)
713 {
714     /* ASCII: "traffic upd", in hex for EBCDIC compatibility */
715     static const unsigned char application_traffic[] = "\x74\x72\x61\x66\x66\x69\x63\x20\x75\x70\x64";
716     const EVP_MD *md = ssl_handshake_md(s);
717     size_t hashlen;
718     unsigned char key[EVP_MAX_KEY_LENGTH];
719     unsigned char *insecret;
720     unsigned char secret[EVP_MAX_MD_SIZE];
721     char *log_label;
722     size_t keylen, ivlen, taglen;
723     int ret = 0, l;
724     int direction = sending ? OSSL_RECORD_DIRECTION_WRITE
725                             : OSSL_RECORD_DIRECTION_READ;
726     unsigned char iv[EVP_MAX_IV_LENGTH];
727
728     if ((l = EVP_MD_get_size(md)) <= 0) {
729         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
730         return 0;
731     }
732     hashlen = (size_t)l;
733
734     if (s->server == sending)
735         insecret = s->server_app_traffic_secret;
736     else
737         insecret = s->client_app_traffic_secret;
738
739     if (!derive_secret_key_and_iv(s, md,
740                                   s->s3.tmp.new_sym_enc, insecret, NULL,
741                                   application_traffic,
742                                   sizeof(application_traffic) - 1, secret, key,
743                                   &keylen, iv, &ivlen, &taglen)) {
744         /* SSLfatal() already called */
745         goto err;
746     }
747
748     memcpy(insecret, secret, hashlen);
749
750     if (!ssl_set_new_record_layer(s, s->version,
751                             direction,
752                             OSSL_RECORD_PROTECTION_LEVEL_APPLICATION,
753                             insecret, hashlen, key, keylen, iv, ivlen, NULL, 0,
754                             s->s3.tmp.new_sym_enc, taglen, NID_undef, NULL,
755                             NULL, md)) {
756         /* SSLfatal already called */
757         goto err;
758     }
759
760     /* Call Key log on successful traffic secret update */
761     log_label = s->server == sending ? SERVER_APPLICATION_N_LABEL : CLIENT_APPLICATION_N_LABEL;
762     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
763         /* SSLfatal() already called */
764         goto err;
765     }
766     ret = 1;
767  err:
768     OPENSSL_cleanse(key, sizeof(key));
769     OPENSSL_cleanse(secret, sizeof(secret));
770     return ret;
771 }
772
773 int tls13_alert_code(int code)
774 {
775     /* There are 2 additional alerts in TLSv1.3 compared to TLSv1.2 */
776     if (code == SSL_AD_MISSING_EXTENSION || code == SSL_AD_CERTIFICATE_REQUIRED)
777         return code;
778
779     return tls1_alert_code(code);
780 }
781
782 int tls13_export_keying_material(SSL_CONNECTION *s,
783                                  unsigned char *out, size_t olen,
784                                  const char *label, size_t llen,
785                                  const unsigned char *context,
786                                  size_t contextlen, int use_context)
787 {
788     unsigned char exportsecret[EVP_MAX_MD_SIZE];
789     /* ASCII: "exporter", in hex for EBCDIC compatibility */
790     static const unsigned char exporterlabel[] = "\x65\x78\x70\x6F\x72\x74\x65\x72";
791     unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
792     const EVP_MD *md = ssl_handshake_md(s);
793     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
794     unsigned int hashsize, datalen;
795     int ret = 0;
796
797     if (ctx == NULL || md == NULL || !ossl_statem_export_allowed(s))
798         goto err;
799
800     if (!use_context)
801         contextlen = 0;
802
803     if (EVP_DigestInit_ex(ctx, md, NULL) <= 0
804             || EVP_DigestUpdate(ctx, context, contextlen) <= 0
805             || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
806             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
807             || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
808             || !tls13_hkdf_expand(s, md, s->exporter_master_secret,
809                                   (const unsigned char *)label, llen,
810                                   data, datalen, exportsecret, hashsize, 0)
811             || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
812                                   sizeof(exporterlabel) - 1, hash, hashsize,
813                                   out, olen, 0))
814         goto err;
815
816     ret = 1;
817  err:
818     EVP_MD_CTX_free(ctx);
819     return ret;
820 }
821
822 int tls13_export_keying_material_early(SSL_CONNECTION *s,
823                                        unsigned char *out, size_t olen,
824                                        const char *label, size_t llen,
825                                        const unsigned char *context,
826                                        size_t contextlen)
827 {
828     /* ASCII: "exporter", in hex for EBCDIC compatibility */
829     static const unsigned char exporterlabel[] = "\x65\x78\x70\x6F\x72\x74\x65\x72";
830     unsigned char exportsecret[EVP_MAX_MD_SIZE];
831     unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
832     const EVP_MD *md;
833     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
834     unsigned int hashsize, datalen;
835     int ret = 0;
836     const SSL_CIPHER *sslcipher;
837
838     if (ctx == NULL || !ossl_statem_export_early_allowed(s))
839         goto err;
840
841     if (!s->server && s->max_early_data > 0
842             && s->session->ext.max_early_data == 0)
843         sslcipher = SSL_SESSION_get0_cipher(s->psksession);
844     else
845         sslcipher = SSL_SESSION_get0_cipher(s->session);
846
847     md = ssl_md(SSL_CONNECTION_GET_CTX(s), sslcipher->algorithm2);
848
849     /*
850      * Calculate the hash value and store it in |data|. The reason why
851      * the empty string is used is that the definition of TLS-Exporter
852      * is like so:
853      *
854      * TLS-Exporter(label, context_value, key_length) =
855      *     HKDF-Expand-Label(Derive-Secret(Secret, label, ""),
856      *                       "exporter", Hash(context_value), key_length)
857      *
858      * Derive-Secret(Secret, Label, Messages) =
859      *       HKDF-Expand-Label(Secret, Label,
860      *                         Transcript-Hash(Messages), Hash.length)
861      *
862      * Here Transcript-Hash is the cipher suite hash algorithm.
863      */
864     if (md == NULL
865             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
866             || EVP_DigestUpdate(ctx, context, contextlen) <= 0
867             || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
868             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
869             || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
870             || !tls13_hkdf_expand(s, md, s->early_exporter_master_secret,
871                                   (const unsigned char *)label, llen,
872                                   data, datalen, exportsecret, hashsize, 0)
873             || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
874                                   sizeof(exporterlabel) - 1, hash, hashsize,
875                                   out, olen, 0))
876         goto err;
877
878     ret = 1;
879  err:
880     EVP_MD_CTX_free(ctx);
881     return ret;
882 }