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