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