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