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