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