xref: /freebsd/crypto/openssl/ssl/t1_enc.c (revision a90b9d0159070121c221b966469c3e36d912bf82)
1 /*
2  * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright 2005 Nokia. All rights reserved.
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10 
11 #include <stdio.h>
12 #include "ssl_local.h"
13 #include "record/record_local.h"
14 #include "internal/ktls.h"
15 #include "internal/cryptlib.h"
16 #include <openssl/comp.h>
17 #include <openssl/evp.h>
18 #include <openssl/kdf.h>
19 #include <openssl/rand.h>
20 #include <openssl/obj_mac.h>
21 #include <openssl/core_names.h>
22 #include <openssl/trace.h>
23 
24 /* seed1 through seed5 are concatenated */
25 static int tls1_PRF(SSL *s,
26                     const void *seed1, size_t seed1_len,
27                     const void *seed2, size_t seed2_len,
28                     const void *seed3, size_t seed3_len,
29                     const void *seed4, size_t seed4_len,
30                     const void *seed5, size_t seed5_len,
31                     const unsigned char *sec, size_t slen,
32                     unsigned char *out, size_t olen, int fatal)
33 {
34     const EVP_MD *md = ssl_prf_md(s);
35     EVP_KDF *kdf;
36     EVP_KDF_CTX *kctx = NULL;
37     OSSL_PARAM params[8], *p = params;
38     const char *mdname;
39 
40     if (md == NULL) {
41         /* Should never happen */
42         if (fatal)
43             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
44         else
45             ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
46         return 0;
47     }
48     kdf = EVP_KDF_fetch(s->ctx->libctx, OSSL_KDF_NAME_TLS1_PRF, s->ctx->propq);
49     if (kdf == NULL)
50         goto err;
51     kctx = EVP_KDF_CTX_new(kdf);
52     EVP_KDF_free(kdf);
53     if (kctx == NULL)
54         goto err;
55     mdname = EVP_MD_get0_name(md);
56     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
57                                             (char *)mdname, 0);
58     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SECRET,
59                                              (unsigned char *)sec,
60                                              (size_t)slen);
61     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SEED,
62                                              (void *)seed1, (size_t)seed1_len);
63     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SEED,
64                                              (void *)seed2, (size_t)seed2_len);
65     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SEED,
66                                              (void *)seed3, (size_t)seed3_len);
67     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SEED,
68                                              (void *)seed4, (size_t)seed4_len);
69     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SEED,
70                                              (void *)seed5, (size_t)seed5_len);
71     *p = OSSL_PARAM_construct_end();
72     if (EVP_KDF_derive(kctx, out, olen, params)) {
73         EVP_KDF_CTX_free(kctx);
74         return 1;
75     }
76 
77  err:
78     if (fatal)
79         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
80     else
81         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
82     EVP_KDF_CTX_free(kctx);
83     return 0;
84 }
85 
86 static int tls1_generate_key_block(SSL *s, unsigned char *km, size_t num)
87 {
88     int ret;
89 
90     /* Calls SSLfatal() as required */
91     ret = tls1_PRF(s,
92                    TLS_MD_KEY_EXPANSION_CONST,
93                    TLS_MD_KEY_EXPANSION_CONST_SIZE, s->s3.server_random,
94                    SSL3_RANDOM_SIZE, s->s3.client_random, SSL3_RANDOM_SIZE,
95                    NULL, 0, NULL, 0, s->session->master_key,
96                    s->session->master_key_length, km, num, 1);
97 
98     return ret;
99 }
100 
101 int tls_provider_set_tls_params(SSL *s, EVP_CIPHER_CTX *ctx,
102                                 const EVP_CIPHER *ciph,
103                                 const EVP_MD *md)
104 {
105     /*
106      * Provided cipher, the TLS padding/MAC removal is performed provider
107      * side so we need to tell the ctx about our TLS version and mac size
108      */
109     OSSL_PARAM params[3], *pprm = params;
110     size_t macsize = 0;
111     int imacsize = -1;
112 
113     if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
114                /*
115                 * We look at s->ext.use_etm instead of SSL_READ_ETM() or
116                 * SSL_WRITE_ETM() because this test applies to both reading
117                 * and writing.
118                 */
119             && !s->ext.use_etm)
120         imacsize = EVP_MD_get_size(md);
121     if (imacsize >= 0)
122         macsize = (size_t)imacsize;
123 
124     *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
125                                        &s->version);
126     *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
127                                           &macsize);
128     *pprm = OSSL_PARAM_construct_end();
129 
130     if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
131         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
132         return 0;
133     }
134 
135     return 1;
136 }
137 
138 
139 static int tls_iv_length_within_key_block(const EVP_CIPHER *c)
140 {
141     /* If GCM/CCM mode only part of IV comes from PRF */
142     if (EVP_CIPHER_get_mode(c) == EVP_CIPH_GCM_MODE)
143         return EVP_GCM_TLS_FIXED_IV_LEN;
144     else if (EVP_CIPHER_get_mode(c) == EVP_CIPH_CCM_MODE)
145         return EVP_CCM_TLS_FIXED_IV_LEN;
146     else
147         return EVP_CIPHER_get_iv_length(c);
148 }
149 
150 int tls1_change_cipher_state(SSL *s, int which)
151 {
152     unsigned char *p, *mac_secret;
153     unsigned char *ms, *key, *iv;
154     EVP_CIPHER_CTX *dd;
155     const EVP_CIPHER *c;
156 #ifndef OPENSSL_NO_COMP
157     const SSL_COMP *comp;
158 #endif
159     const EVP_MD *m;
160     int mac_type;
161     size_t *mac_secret_size;
162     EVP_MD_CTX *mac_ctx;
163     EVP_PKEY *mac_key;
164     size_t n, i, j, k, cl;
165     int reuse_dd = 0;
166 #ifndef OPENSSL_NO_KTLS
167     ktls_crypto_info_t crypto_info;
168     void *rl_sequence;
169     BIO *bio;
170 #endif
171 
172     c = s->s3.tmp.new_sym_enc;
173     m = s->s3.tmp.new_hash;
174     mac_type = s->s3.tmp.new_mac_pkey_type;
175 #ifndef OPENSSL_NO_COMP
176     comp = s->s3.tmp.new_compression;
177 #endif
178 
179     if (which & SSL3_CC_READ) {
180         if (s->ext.use_etm)
181             s->s3.flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC_READ;
182         else
183             s->s3.flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC_READ;
184 
185         if (s->s3.tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
186             s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
187         else
188             s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
189 
190         if (s->s3.tmp.new_cipher->algorithm2 & TLS1_TLSTREE)
191             s->mac_flags |= SSL_MAC_FLAG_READ_MAC_TLSTREE;
192         else
193             s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_TLSTREE;
194 
195         if (s->enc_read_ctx != NULL) {
196             reuse_dd = 1;
197         } else if ((s->enc_read_ctx = EVP_CIPHER_CTX_new()) == NULL) {
198             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
199             goto err;
200         } else {
201             /*
202              * make sure it's initialised in case we exit later with an error
203              */
204             EVP_CIPHER_CTX_reset(s->enc_read_ctx);
205         }
206         dd = s->enc_read_ctx;
207         mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
208         if (mac_ctx == NULL) {
209             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
210             goto err;
211         }
212 #ifndef OPENSSL_NO_COMP
213         COMP_CTX_free(s->expand);
214         s->expand = NULL;
215         if (comp != NULL) {
216             s->expand = COMP_CTX_new(comp->method);
217             if (s->expand == NULL) {
218                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
219                          SSL_R_COMPRESSION_LIBRARY_ERROR);
220                 goto err;
221             }
222         }
223 #endif
224         /*
225          * this is done by dtls1_reset_seq_numbers for DTLS
226          */
227         if (!SSL_IS_DTLS(s))
228             RECORD_LAYER_reset_read_sequence(&s->rlayer);
229         mac_secret = &(s->s3.read_mac_secret[0]);
230         mac_secret_size = &(s->s3.read_mac_secret_size);
231     } else {
232         s->statem.enc_write_state = ENC_WRITE_STATE_INVALID;
233         if (s->ext.use_etm)
234             s->s3.flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC_WRITE;
235         else
236             s->s3.flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC_WRITE;
237 
238         if (s->s3.tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
239             s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
240         else
241             s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
242 
243         if (s->s3.tmp.new_cipher->algorithm2 & TLS1_TLSTREE)
244             s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_TLSTREE;
245         else
246             s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_TLSTREE;
247         if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s)) {
248             reuse_dd = 1;
249         } else if ((s->enc_write_ctx = EVP_CIPHER_CTX_new()) == NULL) {
250             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
251             goto err;
252         }
253         dd = s->enc_write_ctx;
254         if (SSL_IS_DTLS(s)) {
255             mac_ctx = EVP_MD_CTX_new();
256             if (mac_ctx == NULL) {
257                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
258                 goto err;
259             }
260             s->write_hash = mac_ctx;
261         } else {
262             mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
263             if (mac_ctx == NULL) {
264                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
265                 goto err;
266             }
267         }
268 #ifndef OPENSSL_NO_COMP
269         COMP_CTX_free(s->compress);
270         s->compress = NULL;
271         if (comp != NULL) {
272             s->compress = COMP_CTX_new(comp->method);
273             if (s->compress == NULL) {
274                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
275                          SSL_R_COMPRESSION_LIBRARY_ERROR);
276                 goto err;
277             }
278         }
279 #endif
280         /*
281          * this is done by dtls1_reset_seq_numbers for DTLS
282          */
283         if (!SSL_IS_DTLS(s))
284             RECORD_LAYER_reset_write_sequence(&s->rlayer);
285         mac_secret = &(s->s3.write_mac_secret[0]);
286         mac_secret_size = &(s->s3.write_mac_secret_size);
287     }
288 
289     if (reuse_dd)
290         EVP_CIPHER_CTX_reset(dd);
291 
292     p = s->s3.tmp.key_block;
293     i = *mac_secret_size = s->s3.tmp.new_mac_secret_size;
294 
295     cl = EVP_CIPHER_get_key_length(c);
296     j = cl;
297     k = tls_iv_length_within_key_block(c);
298     if ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
299         (which == SSL3_CHANGE_CIPHER_SERVER_READ)) {
300         ms = &(p[0]);
301         n = i + i;
302         key = &(p[n]);
303         n += j + j;
304         iv = &(p[n]);
305         n += k + k;
306     } else {
307         n = i;
308         ms = &(p[n]);
309         n += i + j;
310         key = &(p[n]);
311         n += j + k;
312         iv = &(p[n]);
313         n += k;
314     }
315 
316     if (n > s->s3.tmp.key_block_length) {
317         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
318         goto err;
319     }
320 
321     memcpy(mac_secret, ms, i);
322 
323     if (!(EVP_CIPHER_get_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER)) {
324         if (mac_type == EVP_PKEY_HMAC) {
325             mac_key = EVP_PKEY_new_raw_private_key_ex(s->ctx->libctx, "HMAC",
326                                                       s->ctx->propq, mac_secret,
327                                                       *mac_secret_size);
328         } else {
329             /*
330              * If its not HMAC then the only other types of MAC we support are
331              * the GOST MACs, so we need to use the old style way of creating
332              * a MAC key.
333              */
334             mac_key = EVP_PKEY_new_mac_key(mac_type, NULL, mac_secret,
335                                            (int)*mac_secret_size);
336         }
337         if (mac_key == NULL
338             || EVP_DigestSignInit_ex(mac_ctx, NULL, EVP_MD_get0_name(m),
339                                      s->ctx->libctx, s->ctx->propq, mac_key,
340                                      NULL) <= 0) {
341             EVP_PKEY_free(mac_key);
342             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
343             goto err;
344         }
345         EVP_PKEY_free(mac_key);
346     }
347 
348     OSSL_TRACE_BEGIN(TLS) {
349         BIO_printf(trc_out, "which = %04X, mac key:\n", which);
350         BIO_dump_indent(trc_out, ms, i, 4);
351     } OSSL_TRACE_END(TLS);
352 
353     if (EVP_CIPHER_get_mode(c) == EVP_CIPH_GCM_MODE) {
354         if (!EVP_CipherInit_ex(dd, c, NULL, key, NULL, (which & SSL3_CC_WRITE))
355             || EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, (int)k,
356                                     iv) <= 0) {
357             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
358             goto err;
359         }
360     } else if (EVP_CIPHER_get_mode(c) == EVP_CIPH_CCM_MODE) {
361         int taglen;
362         if (s->s3.tmp.
363             new_cipher->algorithm_enc & (SSL_AES128CCM8 | SSL_AES256CCM8))
364             taglen = EVP_CCM8_TLS_TAG_LEN;
365         else
366             taglen = EVP_CCM_TLS_TAG_LEN;
367         if (!EVP_CipherInit_ex(dd, c, NULL, NULL, NULL, (which & SSL3_CC_WRITE))
368             || (EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_IVLEN, 12, NULL) <= 0)
369             || (EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_TAG, taglen, NULL) <= 0)
370             || (EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_CCM_SET_IV_FIXED, (int)k, iv) <= 0)
371             || !EVP_CipherInit_ex(dd, NULL, NULL, key, NULL, -1)) {
372             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
373             goto err;
374         }
375     } else {
376         if (!EVP_CipherInit_ex(dd, c, NULL, key, iv, (which & SSL3_CC_WRITE))) {
377             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
378             goto err;
379         }
380     }
381     /* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
382     if ((EVP_CIPHER_get_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER)
383         && *mac_secret_size
384         && EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_MAC_KEY,
385                                 (int)*mac_secret_size, mac_secret) <= 0) {
386         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
387         goto err;
388     }
389 
390     /*
391      * The cipher we actually ended up using in the EVP_CIPHER_CTX may be
392      * different to that in c if we have an ENGINE in use
393      */
394     if (EVP_CIPHER_get0_provider(EVP_CIPHER_CTX_get0_cipher(dd)) != NULL
395             && !tls_provider_set_tls_params(s, dd, c, m)) {
396         /* SSLfatal already called */
397         goto err;
398     }
399 
400 #ifndef OPENSSL_NO_KTLS
401     if (s->compress || (s->options & SSL_OP_ENABLE_KTLS) == 0)
402         goto skip_ktls;
403 
404     /* ktls supports only the maximum fragment size */
405     if (ssl_get_max_send_fragment(s) != SSL3_RT_MAX_PLAIN_LENGTH)
406         goto skip_ktls;
407 
408     /* check that cipher is supported */
409     if (!ktls_check_supported_cipher(s, c, dd))
410         goto skip_ktls;
411 
412     if (which & SSL3_CC_WRITE)
413         bio = s->wbio;
414     else
415         bio = s->rbio;
416 
417     if (!ossl_assert(bio != NULL)) {
418         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
419         goto err;
420     }
421 
422     /* All future data will get encrypted by ktls. Flush the BIO or skip ktls */
423     if (which & SSL3_CC_WRITE) {
424        if (BIO_flush(bio) <= 0)
425            goto skip_ktls;
426     }
427 
428     /* ktls doesn't support renegotiation */
429     if ((BIO_get_ktls_send(s->wbio) && (which & SSL3_CC_WRITE)) ||
430         (BIO_get_ktls_recv(s->rbio) && (which & SSL3_CC_READ))) {
431         SSLfatal(s, SSL_AD_NO_RENEGOTIATION, ERR_R_INTERNAL_ERROR);
432         goto err;
433     }
434 
435     if (which & SSL3_CC_WRITE)
436         rl_sequence = RECORD_LAYER_get_write_sequence(&s->rlayer);
437     else
438         rl_sequence = RECORD_LAYER_get_read_sequence(&s->rlayer);
439 
440     if (!ktls_configure_crypto(s, c, dd, rl_sequence, &crypto_info,
441                                which & SSL3_CC_WRITE, iv, key, ms,
442                                *mac_secret_size))
443         goto skip_ktls;
444 
445     /* ktls works with user provided buffers directly */
446     if (BIO_set_ktls(bio, &crypto_info, which & SSL3_CC_WRITE)) {
447         if (which & SSL3_CC_WRITE)
448             ssl3_release_write_buffer(s);
449         SSL_set_options(s, SSL_OP_NO_RENEGOTIATION);
450     }
451 
452  skip_ktls:
453 #endif                          /* OPENSSL_NO_KTLS */
454     s->statem.enc_write_state = ENC_WRITE_STATE_VALID;
455 
456     OSSL_TRACE_BEGIN(TLS) {
457         BIO_printf(trc_out, "which = %04X, key:\n", which);
458         BIO_dump_indent(trc_out, key, EVP_CIPHER_get_key_length(c), 4);
459         BIO_printf(trc_out, "iv:\n");
460         BIO_dump_indent(trc_out, iv, k, 4);
461     } OSSL_TRACE_END(TLS);
462 
463     return 1;
464  err:
465     return 0;
466 }
467 
468 int tls1_setup_key_block(SSL *s)
469 {
470     unsigned char *p;
471     const EVP_CIPHER *c;
472     const EVP_MD *hash;
473     SSL_COMP *comp;
474     int mac_type = NID_undef;
475     size_t num, mac_secret_size = 0;
476     int ret = 0;
477 
478     if (s->s3.tmp.key_block_length != 0)
479         return 1;
480 
481     if (!ssl_cipher_get_evp(s->ctx, s->session, &c, &hash, &mac_type,
482                             &mac_secret_size, &comp, s->ext.use_etm)) {
483         /* Error is already recorded */
484         SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
485         return 0;
486     }
487 
488     ssl_evp_cipher_free(s->s3.tmp.new_sym_enc);
489     s->s3.tmp.new_sym_enc = c;
490     ssl_evp_md_free(s->s3.tmp.new_hash);
491     s->s3.tmp.new_hash = hash;
492     s->s3.tmp.new_mac_pkey_type = mac_type;
493     s->s3.tmp.new_mac_secret_size = mac_secret_size;
494     num = mac_secret_size + EVP_CIPHER_get_key_length(c)
495           + tls_iv_length_within_key_block(c);
496     num *= 2;
497 
498     ssl3_cleanup_key_block(s);
499 
500     if ((p = OPENSSL_malloc(num)) == NULL) {
501         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
502         goto err;
503     }
504 
505     s->s3.tmp.key_block_length = num;
506     s->s3.tmp.key_block = p;
507 
508     OSSL_TRACE_BEGIN(TLS) {
509         BIO_printf(trc_out, "key block length: %zu\n", num);
510         BIO_printf(trc_out, "client random\n");
511         BIO_dump_indent(trc_out, s->s3.client_random, SSL3_RANDOM_SIZE, 4);
512         BIO_printf(trc_out, "server random\n");
513         BIO_dump_indent(trc_out, s->s3.server_random, SSL3_RANDOM_SIZE, 4);
514         BIO_printf(trc_out, "master key\n");
515         BIO_dump_indent(trc_out,
516                         s->session->master_key,
517                         s->session->master_key_length, 4);
518     } OSSL_TRACE_END(TLS);
519 
520     if (!tls1_generate_key_block(s, p, num)) {
521         /* SSLfatal() already called */
522         goto err;
523     }
524 
525     OSSL_TRACE_BEGIN(TLS) {
526         BIO_printf(trc_out, "key block\n");
527         BIO_dump_indent(trc_out, p, num, 4);
528     } OSSL_TRACE_END(TLS);
529 
530     if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
531         && s->method->version <= TLS1_VERSION) {
532         /*
533          * enable vulnerability countermeasure for CBC ciphers with known-IV
534          * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
535          */
536         s->s3.need_empty_fragments = 1;
537 
538         if (s->session->cipher != NULL) {
539             if (s->session->cipher->algorithm_enc == SSL_eNULL)
540                 s->s3.need_empty_fragments = 0;
541 
542             if (s->session->cipher->algorithm_enc == SSL_RC4)
543                 s->s3.need_empty_fragments = 0;
544         }
545     }
546 
547     ret = 1;
548  err:
549     return ret;
550 }
551 
552 size_t tls1_final_finish_mac(SSL *s, const char *str, size_t slen,
553                              unsigned char *out)
554 {
555     size_t hashlen;
556     unsigned char hash[EVP_MAX_MD_SIZE];
557     size_t finished_size = TLS1_FINISH_MAC_LENGTH;
558 
559     if (s->s3.tmp.new_cipher->algorithm_mkey & SSL_kGOST18)
560         finished_size = 32;
561 
562     if (!ssl3_digest_cached_records(s, 0)) {
563         /* SSLfatal() already called */
564         return 0;
565     }
566 
567     if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen)) {
568         /* SSLfatal() already called */
569         return 0;
570     }
571 
572     if (!tls1_PRF(s, str, slen, hash, hashlen, NULL, 0, NULL, 0, NULL, 0,
573                   s->session->master_key, s->session->master_key_length,
574                   out, finished_size, 1)) {
575         /* SSLfatal() already called */
576         return 0;
577     }
578     OPENSSL_cleanse(hash, hashlen);
579     return finished_size;
580 }
581 
582 int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
583                                 size_t len, size_t *secret_size)
584 {
585     if (s->session->flags & SSL_SESS_FLAG_EXTMS) {
586         unsigned char hash[EVP_MAX_MD_SIZE * 2];
587         size_t hashlen;
588         /*
589          * Digest cached records keeping record buffer (if present): this won't
590          * affect client auth because we're freezing the buffer at the same
591          * point (after client key exchange and before certificate verify)
592          */
593         if (!ssl3_digest_cached_records(s, 1)
594                 || !ssl_handshake_hash(s, hash, sizeof(hash), &hashlen)) {
595             /* SSLfatal() already called */
596             return 0;
597         }
598         OSSL_TRACE_BEGIN(TLS) {
599             BIO_printf(trc_out, "Handshake hashes:\n");
600             BIO_dump(trc_out, (char *)hash, hashlen);
601         } OSSL_TRACE_END(TLS);
602         if (!tls1_PRF(s,
603                       TLS_MD_EXTENDED_MASTER_SECRET_CONST,
604                       TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE,
605                       hash, hashlen,
606                       NULL, 0,
607                       NULL, 0,
608                       NULL, 0, p, len, out,
609                       SSL3_MASTER_SECRET_SIZE, 1)) {
610             /* SSLfatal() already called */
611             return 0;
612         }
613         OPENSSL_cleanse(hash, hashlen);
614     } else {
615         if (!tls1_PRF(s,
616                       TLS_MD_MASTER_SECRET_CONST,
617                       TLS_MD_MASTER_SECRET_CONST_SIZE,
618                       s->s3.client_random, SSL3_RANDOM_SIZE,
619                       NULL, 0,
620                       s->s3.server_random, SSL3_RANDOM_SIZE,
621                       NULL, 0, p, len, out,
622                       SSL3_MASTER_SECRET_SIZE, 1)) {
623            /* SSLfatal() already called */
624             return 0;
625         }
626     }
627 
628     OSSL_TRACE_BEGIN(TLS) {
629         BIO_printf(trc_out, "Premaster Secret:\n");
630         BIO_dump_indent(trc_out, p, len, 4);
631         BIO_printf(trc_out, "Client Random:\n");
632         BIO_dump_indent(trc_out, s->s3.client_random, SSL3_RANDOM_SIZE, 4);
633         BIO_printf(trc_out, "Server Random:\n");
634         BIO_dump_indent(trc_out, s->s3.server_random, SSL3_RANDOM_SIZE, 4);
635         BIO_printf(trc_out, "Master Secret:\n");
636         BIO_dump_indent(trc_out,
637                         s->session->master_key,
638                         SSL3_MASTER_SECRET_SIZE, 4);
639     } OSSL_TRACE_END(TLS);
640 
641     *secret_size = SSL3_MASTER_SECRET_SIZE;
642     return 1;
643 }
644 
645 int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
646                                 const char *label, size_t llen,
647                                 const unsigned char *context,
648                                 size_t contextlen, int use_context)
649 {
650     unsigned char *val = NULL;
651     size_t vallen = 0, currentvalpos;
652     int rv;
653 
654     /*
655      * construct PRF arguments we construct the PRF argument ourself rather
656      * than passing separate values into the TLS PRF to ensure that the
657      * concatenation of values does not create a prohibited label.
658      */
659     vallen = llen + SSL3_RANDOM_SIZE * 2;
660     if (use_context) {
661         vallen += 2 + contextlen;
662     }
663 
664     val = OPENSSL_malloc(vallen);
665     if (val == NULL)
666         goto err2;
667     currentvalpos = 0;
668     memcpy(val + currentvalpos, (unsigned char *)label, llen);
669     currentvalpos += llen;
670     memcpy(val + currentvalpos, s->s3.client_random, SSL3_RANDOM_SIZE);
671     currentvalpos += SSL3_RANDOM_SIZE;
672     memcpy(val + currentvalpos, s->s3.server_random, SSL3_RANDOM_SIZE);
673     currentvalpos += SSL3_RANDOM_SIZE;
674 
675     if (use_context) {
676         val[currentvalpos] = (contextlen >> 8) & 0xff;
677         currentvalpos++;
678         val[currentvalpos] = contextlen & 0xff;
679         currentvalpos++;
680         if ((contextlen > 0) || (context != NULL)) {
681             memcpy(val + currentvalpos, context, contextlen);
682         }
683     }
684 
685     /*
686      * disallow prohibited labels note that SSL3_RANDOM_SIZE > max(prohibited
687      * label len) = 15, so size of val > max(prohibited label len) = 15 and
688      * the comparisons won't have buffer overflow
689      */
690     if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
691                TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0)
692         goto err1;
693     if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
694                TLS_MD_SERVER_FINISH_CONST_SIZE) == 0)
695         goto err1;
696     if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
697                TLS_MD_MASTER_SECRET_CONST_SIZE) == 0)
698         goto err1;
699     if (memcmp(val, TLS_MD_EXTENDED_MASTER_SECRET_CONST,
700                TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE) == 0)
701         goto err1;
702     if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
703                TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0)
704         goto err1;
705 
706     rv = tls1_PRF(s,
707                   val, vallen,
708                   NULL, 0,
709                   NULL, 0,
710                   NULL, 0,
711                   NULL, 0,
712                   s->session->master_key, s->session->master_key_length,
713                   out, olen, 0);
714 
715     goto ret;
716  err1:
717     ERR_raise(ERR_LIB_SSL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
718     rv = 0;
719     goto ret;
720  err2:
721     ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
722     rv = 0;
723  ret:
724     OPENSSL_clear_free(val, vallen);
725     return rv;
726 }
727 
728 int tls1_alert_code(int code)
729 {
730     switch (code) {
731     case SSL_AD_CLOSE_NOTIFY:
732         return SSL3_AD_CLOSE_NOTIFY;
733     case SSL_AD_UNEXPECTED_MESSAGE:
734         return SSL3_AD_UNEXPECTED_MESSAGE;
735     case SSL_AD_BAD_RECORD_MAC:
736         return SSL3_AD_BAD_RECORD_MAC;
737     case SSL_AD_DECRYPTION_FAILED:
738         return TLS1_AD_DECRYPTION_FAILED;
739     case SSL_AD_RECORD_OVERFLOW:
740         return TLS1_AD_RECORD_OVERFLOW;
741     case SSL_AD_DECOMPRESSION_FAILURE:
742         return SSL3_AD_DECOMPRESSION_FAILURE;
743     case SSL_AD_HANDSHAKE_FAILURE:
744         return SSL3_AD_HANDSHAKE_FAILURE;
745     case SSL_AD_NO_CERTIFICATE:
746         return -1;
747     case SSL_AD_BAD_CERTIFICATE:
748         return SSL3_AD_BAD_CERTIFICATE;
749     case SSL_AD_UNSUPPORTED_CERTIFICATE:
750         return SSL3_AD_UNSUPPORTED_CERTIFICATE;
751     case SSL_AD_CERTIFICATE_REVOKED:
752         return SSL3_AD_CERTIFICATE_REVOKED;
753     case SSL_AD_CERTIFICATE_EXPIRED:
754         return SSL3_AD_CERTIFICATE_EXPIRED;
755     case SSL_AD_CERTIFICATE_UNKNOWN:
756         return SSL3_AD_CERTIFICATE_UNKNOWN;
757     case SSL_AD_ILLEGAL_PARAMETER:
758         return SSL3_AD_ILLEGAL_PARAMETER;
759     case SSL_AD_UNKNOWN_CA:
760         return TLS1_AD_UNKNOWN_CA;
761     case SSL_AD_ACCESS_DENIED:
762         return TLS1_AD_ACCESS_DENIED;
763     case SSL_AD_DECODE_ERROR:
764         return TLS1_AD_DECODE_ERROR;
765     case SSL_AD_DECRYPT_ERROR:
766         return TLS1_AD_DECRYPT_ERROR;
767     case SSL_AD_EXPORT_RESTRICTION:
768         return TLS1_AD_EXPORT_RESTRICTION;
769     case SSL_AD_PROTOCOL_VERSION:
770         return TLS1_AD_PROTOCOL_VERSION;
771     case SSL_AD_INSUFFICIENT_SECURITY:
772         return TLS1_AD_INSUFFICIENT_SECURITY;
773     case SSL_AD_INTERNAL_ERROR:
774         return TLS1_AD_INTERNAL_ERROR;
775     case SSL_AD_USER_CANCELLED:
776         return TLS1_AD_USER_CANCELLED;
777     case SSL_AD_NO_RENEGOTIATION:
778         return TLS1_AD_NO_RENEGOTIATION;
779     case SSL_AD_UNSUPPORTED_EXTENSION:
780         return TLS1_AD_UNSUPPORTED_EXTENSION;
781     case SSL_AD_CERTIFICATE_UNOBTAINABLE:
782         return TLS1_AD_CERTIFICATE_UNOBTAINABLE;
783     case SSL_AD_UNRECOGNIZED_NAME:
784         return TLS1_AD_UNRECOGNIZED_NAME;
785     case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
786         return TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
787     case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
788         return TLS1_AD_BAD_CERTIFICATE_HASH_VALUE;
789     case SSL_AD_UNKNOWN_PSK_IDENTITY:
790         return TLS1_AD_UNKNOWN_PSK_IDENTITY;
791     case SSL_AD_INAPPROPRIATE_FALLBACK:
792         return TLS1_AD_INAPPROPRIATE_FALLBACK;
793     case SSL_AD_NO_APPLICATION_PROTOCOL:
794         return TLS1_AD_NO_APPLICATION_PROTOCOL;
795     case SSL_AD_CERTIFICATE_REQUIRED:
796         return SSL_AD_HANDSHAKE_FAILURE;
797     case TLS13_AD_MISSING_EXTENSION:
798         return SSL_AD_HANDSHAKE_FAILURE;
799     default:
800         return -1;
801     }
802 }
803