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