evp_fetch.c: Check meth_id instead of name_id
[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  */
31 int tls13_hkdf_expand(SSL *s, const EVP_MD *md, const unsigned char *secret,
32                       const unsigned char *label, size_t labellen,
33                       const unsigned char *data, size_t datalen,
34                       unsigned char *out, size_t outlen, int fatal)
35 {
36     EVP_KDF *kdf = EVP_KDF_fetch(s->ctx->libctx, OSSL_KDF_NAME_TLS1_3_KDF,
37                                  s->ctx->propq);
38     EVP_KDF_CTX *kctx;
39     OSSL_PARAM params[7], *p = params;
40     int mode = EVP_PKEY_HKDEF_MODE_EXPAND_ONLY;
41     const char *mdname = EVP_MD_get0_name(md);
42     int ret;
43     size_t hashlen;
44
45     kctx = EVP_KDF_CTX_new(kdf);
46     EVP_KDF_free(kdf);
47     if (kctx == NULL)
48         return 0;
49
50     if (labellen > TLS13_MAX_LABEL_LEN) {
51         if (fatal) {
52             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
53         } else {
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 (fatal)
67             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
68         else
69             ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
70         return 0;
71     }
72     hashlen = (size_t)ret;
73
74     *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
75     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
76                                             (char *)mdname, 0);
77     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
78                                              (unsigned char *)secret, hashlen);
79     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PREFIX,
80                                              (unsigned char *)label_prefix,
81                                              sizeof(label_prefix) - 1);
82     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_LABEL,
83                                              (unsigned char *)label, labellen);
84     if (data != NULL)
85         *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_DATA,
86                                                  (unsigned char *)data,
87                                                  datalen);
88     *p++ = OSSL_PARAM_construct_end();
89
90     ret = EVP_KDF_derive(kctx, out, outlen, params) <= 0;
91     EVP_KDF_CTX_free(kctx);
92
93     if (ret != 0) {
94         if (fatal)
95             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
96         else
97             ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
98     }
99
100     return ret == 0;
101 }
102
103 /*
104  * Given a |secret| generate a |key| of length |keylen| bytes. Returns 1 on
105  * success  0 on failure.
106  */
107 int tls13_derive_key(SSL *s, const EVP_MD *md, const unsigned char *secret,
108                      unsigned char *key, size_t keylen)
109 {
110     /* ASCII: "key", in hex for EBCDIC compatibility */
111     static const unsigned char keylabel[] = "\x6B\x65\x79";
112
113     return tls13_hkdf_expand(s, md, secret, keylabel, sizeof(keylabel) - 1,
114                              NULL, 0, key, keylen, 1);
115 }
116
117 /*
118  * Given a |secret| generate an |iv| of length |ivlen| bytes. Returns 1 on
119  * success  0 on failure.
120  */
121 int tls13_derive_iv(SSL *s, const EVP_MD *md, const unsigned char *secret,
122                     unsigned char *iv, size_t ivlen)
123 {
124     /* ASCII: "iv", in hex for EBCDIC compatibility */
125     static const unsigned char ivlabel[] = "\x69\x76";
126
127     return tls13_hkdf_expand(s, md, secret, ivlabel, sizeof(ivlabel) - 1,
128                              NULL, 0, iv, ivlen, 1);
129 }
130
131 int tls13_derive_finishedkey(SSL *s, const EVP_MD *md,
132                              const unsigned char *secret,
133                              unsigned char *fin, size_t finlen)
134 {
135     /* ASCII: "finished", in hex for EBCDIC compatibility */
136     static const unsigned char finishedlabel[] = "\x66\x69\x6E\x69\x73\x68\x65\x64";
137
138     return tls13_hkdf_expand(s, md, secret, finishedlabel,
139                              sizeof(finishedlabel) - 1, NULL, 0, fin, finlen, 1);
140 }
141
142 /*
143  * Given the previous secret |prevsecret| and a new input secret |insecret| of
144  * length |insecretlen|, generate a new secret and store it in the location
145  * pointed to by |outsecret|. Returns 1 on success  0 on failure.
146  */
147 int tls13_generate_secret(SSL *s, const EVP_MD *md,
148                           const unsigned char *prevsecret,
149                           const unsigned char *insecret,
150                           size_t insecretlen,
151                           unsigned char *outsecret)
152 {
153     size_t mdlen;
154     int mdleni;
155     int ret;
156     EVP_KDF *kdf;
157     EVP_KDF_CTX *kctx;
158     OSSL_PARAM params[7], *p = params;
159     int mode = EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY;
160     const char *mdname = EVP_MD_get0_name(md);
161     /* ASCII: "derived", in hex for EBCDIC compatibility */
162     static const char derived_secret_label[] = "\x64\x65\x72\x69\x76\x65\x64";
163
164     kdf = EVP_KDF_fetch(s->ctx->libctx, OSSL_KDF_NAME_TLS1_3_KDF, s->ctx->propq);
165     kctx = EVP_KDF_CTX_new(kdf);
166     EVP_KDF_free(kdf);
167     if (kctx == NULL) {
168         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
169         return 0;
170     }
171
172     mdleni = EVP_MD_get_size(md);
173     /* Ensure cast to size_t is safe */
174     if (!ossl_assert(mdleni >= 0)) {
175         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
176         EVP_KDF_CTX_free(kctx);
177         return 0;
178     }
179     mdlen = (size_t)mdleni;
180
181     *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
182     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
183                                             (char *)mdname, 0);
184     if (insecret != NULL)
185         *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
186                                                  (unsigned char *)insecret,
187                                                  insecretlen);
188     if (prevsecret != NULL)
189         *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT,
190                                                  (unsigned char *)prevsecret, mdlen);
191     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PREFIX,
192                                              (unsigned char *)label_prefix,
193                                              sizeof(label_prefix) - 1);
194     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_LABEL,
195                                              (unsigned char *)derived_secret_label,
196                                              sizeof(derived_secret_label) - 1);
197     *p++ = OSSL_PARAM_construct_end();
198
199     ret = EVP_KDF_derive(kctx, outsecret, mdlen, params) <= 0;
200
201     if (ret != 0)
202         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
203
204     EVP_KDF_CTX_free(kctx);
205     return ret == 0;
206 }
207
208 /*
209  * Given an input secret |insecret| of length |insecretlen| generate the
210  * handshake secret. This requires the early secret to already have been
211  * generated. Returns 1 on success  0 on failure.
212  */
213 int tls13_generate_handshake_secret(SSL *s, const unsigned char *insecret,
214                                 size_t insecretlen)
215 {
216     /* Calls SSLfatal() if required */
217     return tls13_generate_secret(s, ssl_handshake_md(s), s->early_secret,
218                                  insecret, insecretlen,
219                                  (unsigned char *)&s->handshake_secret);
220 }
221
222 /*
223  * Given the handshake secret |prev| of length |prevlen| generate the master
224  * secret and store its length in |*secret_size|. Returns 1 on success  0 on
225  * failure.
226  */
227 int tls13_generate_master_secret(SSL *s, unsigned char *out,
228                                  unsigned char *prev, size_t prevlen,
229                                  size_t *secret_size)
230 {
231     const EVP_MD *md = ssl_handshake_md(s);
232
233     *secret_size = EVP_MD_get_size(md);
234     /* Calls SSLfatal() if required */
235     return tls13_generate_secret(s, md, prev, NULL, 0, out);
236 }
237
238 /*
239  * Generates the mac for the Finished message. Returns the length of the MAC or
240  * 0 on error.
241  */
242 size_t tls13_final_finish_mac(SSL *s, const char *str, size_t slen,
243                              unsigned char *out)
244 {
245     const EVP_MD *md = ssl_handshake_md(s);
246     const char *mdname = EVP_MD_get0_name(md);
247     unsigned char hash[EVP_MAX_MD_SIZE];
248     unsigned char finsecret[EVP_MAX_MD_SIZE];
249     unsigned char *key = NULL;
250     size_t len = 0, hashlen;
251     OSSL_PARAM params[2], *p = params;
252
253     if (md == NULL)
254         return 0;
255
256     /* Safe to cast away const here since we're not "getting" any data */
257     if (s->ctx->propq != NULL)
258         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_PROPERTIES,
259                                                 (char *)s->ctx->propq,
260                                                 0);
261     *p = OSSL_PARAM_construct_end();
262
263     if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen)) {
264         /* SSLfatal() already called */
265         goto err;
266     }
267
268     if (str == s->method->ssl3_enc->server_finished_label) {
269         key = s->server_finished_secret;
270     } else if (SSL_IS_FIRST_HANDSHAKE(s)) {
271         key = s->client_finished_secret;
272     } else {
273         if (!tls13_derive_finishedkey(s, md,
274                                       s->client_app_traffic_secret,
275                                       finsecret, hashlen))
276             goto err;
277         key = finsecret;
278     }
279
280     if (!EVP_Q_mac(s->ctx->libctx, "HMAC", s->ctx->propq, mdname,
281                    params, key, hashlen, hash, hashlen,
282                    /* outsize as per sizeof(peer_finish_md) */
283                    out, EVP_MAX_MD_SIZE * 2, &len)) {
284         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
285         goto err;
286     }
287
288  err:
289     OPENSSL_cleanse(finsecret, sizeof(finsecret));
290     return len;
291 }
292
293 /*
294  * There isn't really a key block in TLSv1.3, but we still need this function
295  * for initialising the cipher and hash. Returns 1 on success or 0 on failure.
296  */
297 int tls13_setup_key_block(SSL *s)
298 {
299     const EVP_CIPHER *c;
300     const EVP_MD *hash;
301
302     s->session->cipher = s->s3.tmp.new_cipher;
303     if (!ssl_cipher_get_evp(s->ctx, s->session, &c, &hash, NULL, NULL, NULL,
304                             0)) {
305         /* Error is already recorded */
306         SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
307         return 0;
308     }
309
310     ssl_evp_cipher_free(s->s3.tmp.new_sym_enc);
311     s->s3.tmp.new_sym_enc = c;
312     ssl_evp_md_free(s->s3.tmp.new_hash);
313     s->s3.tmp.new_hash = hash;
314
315     return 1;
316 }
317
318 static int derive_secret_key_and_iv(SSL *s, int sending, const EVP_MD *md,
319                                     const EVP_CIPHER *ciph,
320                                     const unsigned char *insecret,
321                                     const unsigned char *hash,
322                                     const unsigned char *label,
323                                     size_t labellen, unsigned char *secret,
324                                     unsigned char *key, unsigned char *iv,
325                                     EVP_CIPHER_CTX *ciph_ctx)
326 {
327     size_t ivlen, keylen, taglen;
328     int hashleni = EVP_MD_get_size(md);
329     size_t hashlen;
330
331     /* Ensure cast to size_t is safe */
332     if (!ossl_assert(hashleni >= 0)) {
333         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
334         return 0;
335     }
336     hashlen = (size_t)hashleni;
337
338     if (!tls13_hkdf_expand(s, md, insecret, label, labellen, hash, hashlen,
339                            secret, hashlen, 1)) {
340         /* SSLfatal() already called */
341         return 0;
342     }
343
344     keylen = EVP_CIPHER_get_key_length(ciph);
345     if (EVP_CIPHER_get_mode(ciph) == EVP_CIPH_CCM_MODE) {
346         uint32_t algenc;
347
348         ivlen = EVP_CCM_TLS_IV_LEN;
349         if (s->s3.tmp.new_cipher != NULL) {
350             algenc = s->s3.tmp.new_cipher->algorithm_enc;
351         } else if (s->session->cipher != NULL) {
352             /* We've not selected a cipher yet - we must be doing early data */
353             algenc = s->session->cipher->algorithm_enc;
354         } else if (s->psksession != NULL && s->psksession->cipher != NULL) {
355             /* We must be doing early data with out-of-band PSK */
356             algenc = s->psksession->cipher->algorithm_enc;
357         } else {
358             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
359             return 0;
360         }
361         if (algenc & (SSL_AES128CCM8 | SSL_AES256CCM8))
362             taglen = EVP_CCM8_TLS_TAG_LEN;
363          else
364             taglen = EVP_CCM_TLS_TAG_LEN;
365     } else {
366         ivlen = EVP_CIPHER_get_iv_length(ciph);
367         taglen = 0;
368     }
369
370     if (!tls13_derive_key(s, md, secret, key, keylen)
371             || !tls13_derive_iv(s, md, secret, iv, ivlen)) {
372         /* SSLfatal() already called */
373         return 0;
374     }
375
376     if (EVP_CipherInit_ex(ciph_ctx, ciph, NULL, NULL, NULL, sending) <= 0
377         || EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL) <= 0
378         || (taglen != 0 && EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_TAG,
379                                                 taglen, NULL) <= 0)
380         || EVP_CipherInit_ex(ciph_ctx, NULL, NULL, key, NULL, -1) <= 0) {
381         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
382         return 0;
383     }
384
385     return 1;
386 }
387
388 int tls13_change_cipher_state(SSL *s, int which)
389 {
390     /* ASCII: "c e traffic", in hex for EBCDIC compatibility */
391     static const unsigned char client_early_traffic[] = "\x63\x20\x65\x20\x74\x72\x61\x66\x66\x69\x63";
392     /* ASCII: "c hs traffic", in hex for EBCDIC compatibility */
393     static const unsigned char client_handshake_traffic[] = "\x63\x20\x68\x73\x20\x74\x72\x61\x66\x66\x69\x63";
394     /* ASCII: "c ap traffic", in hex for EBCDIC compatibility */
395     static const unsigned char client_application_traffic[] = "\x63\x20\x61\x70\x20\x74\x72\x61\x66\x66\x69\x63";
396     /* ASCII: "s hs traffic", in hex for EBCDIC compatibility */
397     static const unsigned char server_handshake_traffic[] = "\x73\x20\x68\x73\x20\x74\x72\x61\x66\x66\x69\x63";
398     /* ASCII: "s ap traffic", in hex for EBCDIC compatibility */
399     static const unsigned char server_application_traffic[] = "\x73\x20\x61\x70\x20\x74\x72\x61\x66\x66\x69\x63";
400     /* ASCII: "exp master", in hex for EBCDIC compatibility */
401     static const unsigned char exporter_master_secret[] = "\x65\x78\x70\x20\x6D\x61\x73\x74\x65\x72";
402     /* ASCII: "res master", in hex for EBCDIC compatibility */
403     static const unsigned char resumption_master_secret[] = "\x72\x65\x73\x20\x6D\x61\x73\x74\x65\x72";
404     /* ASCII: "e exp master", in hex for EBCDIC compatibility */
405     static const unsigned char early_exporter_master_secret[] = "\x65\x20\x65\x78\x70\x20\x6D\x61\x73\x74\x65\x72";
406     unsigned char *iv;
407     unsigned char key[EVP_MAX_KEY_LENGTH];
408     unsigned char secret[EVP_MAX_MD_SIZE];
409     unsigned char hashval[EVP_MAX_MD_SIZE];
410     unsigned char *hash = hashval;
411     unsigned char *insecret;
412     unsigned char *finsecret = NULL;
413     const char *log_label = NULL;
414     EVP_CIPHER_CTX *ciph_ctx;
415     size_t finsecretlen = 0;
416     const unsigned char *label;
417     size_t labellen, hashlen = 0;
418     int ret = 0;
419     const EVP_MD *md = NULL;
420     const EVP_CIPHER *cipher = NULL;
421 #if !defined(OPENSSL_NO_KTLS) && defined(OPENSSL_KTLS_TLS13)
422     ktls_crypto_info_t crypto_info;
423     BIO *bio;
424 #endif
425
426     if (which & SSL3_CC_READ) {
427         if (s->enc_read_ctx != NULL) {
428             EVP_CIPHER_CTX_reset(s->enc_read_ctx);
429         } else {
430             s->enc_read_ctx = EVP_CIPHER_CTX_new();
431             if (s->enc_read_ctx == NULL) {
432                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
433                 goto err;
434             }
435         }
436         ciph_ctx = s->enc_read_ctx;
437         iv = s->read_iv;
438
439         RECORD_LAYER_reset_read_sequence(&s->rlayer);
440     } else {
441         s->statem.enc_write_state = ENC_WRITE_STATE_INVALID;
442         if (s->enc_write_ctx != NULL) {
443             EVP_CIPHER_CTX_reset(s->enc_write_ctx);
444         } else {
445             s->enc_write_ctx = EVP_CIPHER_CTX_new();
446             if (s->enc_write_ctx == NULL) {
447                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
448                 goto err;
449             }
450         }
451         ciph_ctx = s->enc_write_ctx;
452         iv = s->write_iv;
453
454         RECORD_LAYER_reset_write_sequence(&s->rlayer);
455     }
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_MALLOC_FAILURE);
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(s->ctx, 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(s->ctx, 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             label = client_handshake_traffic;
551             labellen = sizeof(client_handshake_traffic) - 1;
552             log_label = CLIENT_HANDSHAKE_LABEL;
553             /*
554              * The handshake hash used for the server read/client write handshake
555              * traffic secret is the same as the hash for the server
556              * write/client read handshake traffic secret. However, if we
557              * processed early data then we delay changing the server
558              * read/client write cipher state until later, and the handshake
559              * hashes have moved on. Therefore we use the value saved earlier
560              * when we did the server write/client read change cipher state.
561              */
562             hash = s->handshake_traffic_hash;
563         } else {
564             insecret = s->master_secret;
565             label = client_application_traffic;
566             labellen = sizeof(client_application_traffic) - 1;
567             log_label = CLIENT_APPLICATION_LABEL;
568             /*
569              * For this we only use the handshake hashes up until the server
570              * Finished hash. We do not include the client's Finished, which is
571              * what ssl_handshake_hash() would give us. Instead we use the
572              * previously saved value.
573              */
574             hash = s->server_finished_hash;
575         }
576     } else {
577         /* Early data never applies to client-read/server-write */
578         if (which & SSL3_CC_HANDSHAKE) {
579             insecret = s->handshake_secret;
580             finsecret = s->server_finished_secret;
581             finsecretlen = EVP_MD_get_size(ssl_handshake_md(s));
582             label = server_handshake_traffic;
583             labellen = sizeof(server_handshake_traffic) - 1;
584             log_label = SERVER_HANDSHAKE_LABEL;
585         } else {
586             insecret = s->master_secret;
587             label = server_application_traffic;
588             labellen = sizeof(server_application_traffic) - 1;
589             log_label = SERVER_APPLICATION_LABEL;
590         }
591     }
592
593     if (!(which & SSL3_CC_EARLY)) {
594         md = ssl_handshake_md(s);
595         cipher = s->s3.tmp.new_sym_enc;
596         if (!ssl3_digest_cached_records(s, 1)
597                 || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
598             /* SSLfatal() already called */;
599             goto err;
600         }
601     }
602
603     /*
604      * Save the hash of handshakes up to now for use when we calculate the
605      * client application traffic secret
606      */
607     if (label == server_application_traffic)
608         memcpy(s->server_finished_hash, hashval, hashlen);
609
610     if (label == server_handshake_traffic)
611         memcpy(s->handshake_traffic_hash, hashval, hashlen);
612
613     if (label == client_application_traffic) {
614         /*
615          * We also create the resumption master secret, but this time use the
616          * hash for the whole handshake including the Client Finished
617          */
618         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
619                                resumption_master_secret,
620                                sizeof(resumption_master_secret) - 1,
621                                hashval, hashlen, s->resumption_master_secret,
622                                hashlen, 1)) {
623             /* SSLfatal() already called */
624             goto err;
625         }
626     }
627
628     /* check whether cipher is known */
629     if(!ossl_assert(cipher != NULL))
630         goto err;
631
632     if (!derive_secret_key_and_iv(s, which & SSL3_CC_WRITE, md, cipher,
633                                   insecret, hash, label, labellen, secret, key,
634                                   iv, ciph_ctx)) {
635         /* SSLfatal() already called */
636         goto err;
637     }
638
639     if (label == server_application_traffic) {
640         memcpy(s->server_app_traffic_secret, secret, hashlen);
641         /* Now we create the exporter master secret */
642         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
643                                exporter_master_secret,
644                                sizeof(exporter_master_secret) - 1,
645                                hash, hashlen, s->exporter_master_secret,
646                                hashlen, 1)) {
647             /* SSLfatal() already called */
648             goto err;
649         }
650
651         if (!ssl_log_secret(s, EXPORTER_SECRET_LABEL, s->exporter_master_secret,
652                             hashlen)) {
653             /* SSLfatal() already called */
654             goto err;
655         }
656     } else if (label == client_application_traffic)
657         memcpy(s->client_app_traffic_secret, secret, hashlen);
658
659     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
660         /* SSLfatal() already called */
661         goto err;
662     }
663
664     if (finsecret != NULL
665             && !tls13_derive_finishedkey(s, ssl_handshake_md(s), secret,
666                                          finsecret, finsecretlen)) {
667         /* SSLfatal() already called */
668         goto err;
669     }
670
671     if (!s->server && label == client_early_traffic)
672         s->statem.enc_write_state = ENC_WRITE_STATE_WRITE_PLAIN_ALERTS;
673     else
674         s->statem.enc_write_state = ENC_WRITE_STATE_VALID;
675 #ifndef OPENSSL_NO_KTLS
676 # if defined(OPENSSL_KTLS_TLS13)
677     if (!(which & SSL3_CC_WRITE)
678             || !(which & SSL3_CC_APPLICATION)
679             || (s->options & SSL_OP_ENABLE_KTLS) == 0)
680         goto skip_ktls;
681
682     /* ktls supports only the maximum fragment size */
683     if (ssl_get_max_send_fragment(s) != SSL3_RT_MAX_PLAIN_LENGTH)
684         goto skip_ktls;
685
686     /* ktls does not support record padding */
687     if (s->record_padding_cb != NULL)
688         goto skip_ktls;
689
690     /* check that cipher is supported */
691     if (!ktls_check_supported_cipher(s, cipher, ciph_ctx))
692         goto skip_ktls;
693
694     bio = s->wbio;
695
696     if (!ossl_assert(bio != NULL)) {
697         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
698         goto err;
699     }
700
701     /* All future data will get encrypted by ktls. Flush the BIO or skip ktls */
702     if (BIO_flush(bio) <= 0)
703         goto skip_ktls;
704
705     /* configure kernel crypto structure */
706     if (!ktls_configure_crypto(s, cipher, ciph_ctx,
707                                RECORD_LAYER_get_write_sequence(&s->rlayer),
708                                &crypto_info, NULL, iv, key, NULL, 0))
709         goto skip_ktls;
710
711     /* ktls works with user provided buffers directly */
712     if (BIO_set_ktls(bio, &crypto_info, which & SSL3_CC_WRITE))
713         ssl3_release_write_buffer(s);
714 skip_ktls:
715 # endif
716 #endif
717     ret = 1;
718  err:
719     if ((which & SSL3_CC_EARLY) != 0) {
720         /* We up-refed this so now we need to down ref */
721         ssl_evp_cipher_free(cipher);
722     }
723     OPENSSL_cleanse(key, sizeof(key));
724     OPENSSL_cleanse(secret, sizeof(secret));
725     return ret;
726 }
727
728 int tls13_update_key(SSL *s, int sending)
729 {
730     /* ASCII: "traffic upd", in hex for EBCDIC compatibility */
731     static const unsigned char application_traffic[] = "\x74\x72\x61\x66\x66\x69\x63\x20\x75\x70\x64";
732     const EVP_MD *md = ssl_handshake_md(s);
733     size_t hashlen;
734     unsigned char key[EVP_MAX_KEY_LENGTH];
735     unsigned char *insecret, *iv;
736     unsigned char secret[EVP_MAX_MD_SIZE];
737     char *log_label;
738     EVP_CIPHER_CTX *ciph_ctx;
739     int ret = 0, l;
740
741     if ((l = EVP_MD_get_size(md)) <= 0) {
742         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
743         return 0;
744     }
745     hashlen = (size_t)l;
746
747     if (s->server == sending)
748         insecret = s->server_app_traffic_secret;
749     else
750         insecret = s->client_app_traffic_secret;
751
752     if (sending) {
753         s->statem.enc_write_state = ENC_WRITE_STATE_INVALID;
754         iv = s->write_iv;
755         ciph_ctx = s->enc_write_ctx;
756         RECORD_LAYER_reset_write_sequence(&s->rlayer);
757     } else {
758         iv = s->read_iv;
759         ciph_ctx = s->enc_read_ctx;
760         RECORD_LAYER_reset_read_sequence(&s->rlayer);
761     }
762
763     if (!derive_secret_key_and_iv(s, sending, md,
764                                   s->s3.tmp.new_sym_enc, insecret, NULL,
765                                   application_traffic,
766                                   sizeof(application_traffic) - 1, secret, key,
767                                   iv, ciph_ctx)) {
768         /* SSLfatal() already called */
769         goto err;
770     }
771
772     memcpy(insecret, secret, hashlen);
773
774     /* Call Key log on successful traffic secret update */
775     log_label = s->server == sending ? SERVER_APPLICATION_N_LABEL : CLIENT_APPLICATION_N_LABEL;
776     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
777         /* SSLfatal() already called */
778         goto err;
779     }
780
781     s->statem.enc_write_state = ENC_WRITE_STATE_VALID;
782     ret = 1;
783  err:
784     OPENSSL_cleanse(key, sizeof(key));
785     OPENSSL_cleanse(secret, sizeof(secret));
786     return ret;
787 }
788
789 int tls13_alert_code(int code)
790 {
791     /* There are 2 additional alerts in TLSv1.3 compared to TLSv1.2 */
792     if (code == SSL_AD_MISSING_EXTENSION || code == SSL_AD_CERTIFICATE_REQUIRED)
793         return code;
794
795     return tls1_alert_code(code);
796 }
797
798 int tls13_export_keying_material(SSL *s, unsigned char *out, size_t olen,
799                                  const char *label, size_t llen,
800                                  const unsigned char *context,
801                                  size_t contextlen, int use_context)
802 {
803     unsigned char exportsecret[EVP_MAX_MD_SIZE];
804     /* ASCII: "exporter", in hex for EBCDIC compatibility */
805     static const unsigned char exporterlabel[] = "\x65\x78\x70\x6F\x72\x74\x65\x72";
806     unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
807     const EVP_MD *md = ssl_handshake_md(s);
808     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
809     unsigned int hashsize, datalen;
810     int ret = 0;
811
812     if (ctx == NULL || md == NULL || !ossl_statem_export_allowed(s))
813         goto err;
814
815     if (!use_context)
816         contextlen = 0;
817
818     if (EVP_DigestInit_ex(ctx, md, NULL) <= 0
819             || EVP_DigestUpdate(ctx, context, contextlen) <= 0
820             || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
821             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
822             || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
823             || !tls13_hkdf_expand(s, md, s->exporter_master_secret,
824                                   (const unsigned char *)label, llen,
825                                   data, datalen, exportsecret, hashsize, 0)
826             || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
827                                   sizeof(exporterlabel) - 1, hash, hashsize,
828                                   out, olen, 0))
829         goto err;
830
831     ret = 1;
832  err:
833     EVP_MD_CTX_free(ctx);
834     return ret;
835 }
836
837 int tls13_export_keying_material_early(SSL *s, unsigned char *out, size_t olen,
838                                        const char *label, size_t llen,
839                                        const unsigned char *context,
840                                        size_t contextlen)
841 {
842     /* ASCII: "exporter", in hex for EBCDIC compatibility */
843     static const unsigned char exporterlabel[] = "\x65\x78\x70\x6F\x72\x74\x65\x72";
844     unsigned char exportsecret[EVP_MAX_MD_SIZE];
845     unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
846     const EVP_MD *md;
847     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
848     unsigned int hashsize, datalen;
849     int ret = 0;
850     const SSL_CIPHER *sslcipher;
851
852     if (ctx == NULL || !ossl_statem_export_early_allowed(s))
853         goto err;
854
855     if (!s->server && s->max_early_data > 0
856             && s->session->ext.max_early_data == 0)
857         sslcipher = SSL_SESSION_get0_cipher(s->psksession);
858     else
859         sslcipher = SSL_SESSION_get0_cipher(s->session);
860
861     md = ssl_md(s->ctx, sslcipher->algorithm2);
862
863     /*
864      * Calculate the hash value and store it in |data|. The reason why
865      * the empty string is used is that the definition of TLS-Exporter
866      * is like so:
867      *
868      * TLS-Exporter(label, context_value, key_length) =
869      *     HKDF-Expand-Label(Derive-Secret(Secret, label, ""),
870      *                       "exporter", Hash(context_value), key_length)
871      *
872      * Derive-Secret(Secret, Label, Messages) =
873      *       HKDF-Expand-Label(Secret, Label,
874      *                         Transcript-Hash(Messages), Hash.length)
875      *
876      * Here Transcript-Hash is the cipher suite hash algorithm.
877      */
878     if (md == NULL
879             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
880             || EVP_DigestUpdate(ctx, context, contextlen) <= 0
881             || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
882             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
883             || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
884             || !tls13_hkdf_expand(s, md, s->early_exporter_master_secret,
885                                   (const unsigned char *)label, llen,
886                                   data, datalen, exportsecret, hashsize, 0)
887             || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
888                                   sizeof(exporterlabel) - 1, hash, hashsize,
889                                   out, olen, 0))
890         goto err;
891
892     ret = 1;
893  err:
894     EVP_MD_CTX_free(ctx);
895     return ret;
896 }