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