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