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