xref: /freebsd/crypto/openssl/ssl/t1_enc.c (revision f61e92ca5a23450bc28169bbdd71d7674df98c19)
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)
366         goto skip_ktls;
367 
368     if (((which & SSL3_CC_READ) && (s->mode & SSL_MODE_NO_KTLS_RX))
369         || ((which & SSL3_CC_WRITE) && (s->mode & SSL_MODE_NO_KTLS_TX)))
370         goto skip_ktls;
371 
372     /* ktls supports only the maximum fragment size */
373     if (ssl_get_max_send_fragment(s) != SSL3_RT_MAX_PLAIN_LENGTH)
374         goto skip_ktls;
375 
376     /* check that cipher is supported */
377     if (!ktls_check_supported_cipher(s, c, dd))
378         goto skip_ktls;
379 
380     if (which & SSL3_CC_WRITE)
381         bio = s->wbio;
382     else
383         bio = s->rbio;
384 
385     if (!ossl_assert(bio != NULL)) {
386         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_CHANGE_CIPHER_STATE,
387                  ERR_R_INTERNAL_ERROR);
388         goto err;
389     }
390 
391     /* All future data will get encrypted by ktls. Flush the BIO or skip ktls */
392     if (which & SSL3_CC_WRITE) {
393        if (BIO_flush(bio) <= 0)
394            goto skip_ktls;
395     }
396 
397     /* ktls doesn't support renegotiation */
398     if ((BIO_get_ktls_send(s->wbio) && (which & SSL3_CC_WRITE)) ||
399         (BIO_get_ktls_recv(s->rbio) && (which & SSL3_CC_READ))) {
400         SSLfatal(s, SSL_AD_NO_RENEGOTIATION, SSL_F_TLS1_CHANGE_CIPHER_STATE,
401                  ERR_R_INTERNAL_ERROR);
402         goto err;
403     }
404 
405     if (which & SSL3_CC_WRITE)
406         rl_sequence = RECORD_LAYER_get_write_sequence(&s->rlayer);
407     else
408         rl_sequence = RECORD_LAYER_get_read_sequence(&s->rlayer);
409 
410     if (!ktls_configure_crypto(s, c, dd, rl_sequence, &crypto_info, &rec_seq,
411                                iv, key, ms, *mac_secret_size))
412         goto skip_ktls;
413 
414     if (which & SSL3_CC_READ) {
415 # ifndef OPENSSL_NO_KTLS_RX
416         count_unprocessed = count_unprocessed_records(s);
417         if (count_unprocessed < 0)
418             goto skip_ktls;
419 
420         /* increment the crypto_info record sequence */
421         while (count_unprocessed) {
422             for (bit = 7; bit >= 0; bit--) { /* increment */
423                 ++rec_seq[bit];
424                 if (rec_seq[bit] != 0)
425                     break;
426             }
427             count_unprocessed--;
428         }
429 # else
430         goto skip_ktls;
431 # endif
432     }
433 
434     /* ktls works with user provided buffers directly */
435     if (BIO_set_ktls(bio, &crypto_info, which & SSL3_CC_WRITE)) {
436         if (which & SSL3_CC_WRITE)
437             ssl3_release_write_buffer(s);
438         SSL_set_options(s, SSL_OP_NO_RENEGOTIATION);
439     }
440 
441  skip_ktls:
442 #endif                          /* OPENSSL_NO_KTLS */
443     s->statem.enc_write_state = ENC_WRITE_STATE_VALID;
444 
445 #ifdef SSL_DEBUG
446     printf("which = %04X\nkey=", which);
447     {
448         int z;
449         for (z = 0; z < EVP_CIPHER_key_length(c); z++)
450             printf("%02X%c", key[z], ((z + 1) % 16) ? ' ' : '\n');
451     }
452     printf("\niv=");
453     {
454         size_t z;
455         for (z = 0; z < k; z++)
456             printf("%02X%c", iv[z], ((z + 1) % 16) ? ' ' : '\n');
457     }
458     printf("\n");
459 #endif
460 
461     return 1;
462  err:
463     return 0;
464 }
465 
466 int tls1_setup_key_block(SSL *s)
467 {
468     unsigned char *p;
469     const EVP_CIPHER *c;
470     const EVP_MD *hash;
471     SSL_COMP *comp;
472     int mac_type = NID_undef;
473     size_t num, mac_secret_size = 0;
474     int ret = 0;
475 
476     if (s->s3->tmp.key_block_length != 0)
477         return 1;
478 
479     if (!ssl_cipher_get_evp(s->session, &c, &hash, &mac_type, &mac_secret_size,
480                             &comp, s->ext.use_etm)) {
481         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_SETUP_KEY_BLOCK,
482                  SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
483         return 0;
484     }
485 
486     s->s3->tmp.new_sym_enc = c;
487     s->s3->tmp.new_hash = hash;
488     s->s3->tmp.new_mac_pkey_type = mac_type;
489     s->s3->tmp.new_mac_secret_size = mac_secret_size;
490     num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c);
491     num *= 2;
492 
493     ssl3_cleanup_key_block(s);
494 
495     if ((p = OPENSSL_malloc(num)) == NULL) {
496         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_SETUP_KEY_BLOCK,
497                  ERR_R_MALLOC_FAILURE);
498         goto err;
499     }
500 
501     s->s3->tmp.key_block_length = num;
502     s->s3->tmp.key_block = p;
503 
504 #ifdef SSL_DEBUG
505     printf("client random\n");
506     {
507         int z;
508         for (z = 0; z < SSL3_RANDOM_SIZE; z++)
509             printf("%02X%c", s->s3->client_random[z],
510                    ((z + 1) % 16) ? ' ' : '\n');
511     }
512     printf("server random\n");
513     {
514         int z;
515         for (z = 0; z < SSL3_RANDOM_SIZE; z++)
516             printf("%02X%c", s->s3->server_random[z],
517                    ((z + 1) % 16) ? ' ' : '\n');
518     }
519     printf("master key\n");
520     {
521         size_t z;
522         for (z = 0; z < s->session->master_key_length; z++)
523             printf("%02X%c", s->session->master_key[z],
524                    ((z + 1) % 16) ? ' ' : '\n');
525     }
526 #endif
527     if (!tls1_generate_key_block(s, p, num)) {
528         /* SSLfatal() already called */
529         goto err;
530     }
531 #ifdef SSL_DEBUG
532     printf("\nkey block\n");
533     {
534         size_t z;
535         for (z = 0; z < num; z++)
536             printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n');
537     }
538 #endif
539 
540     if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
541         && s->method->version <= TLS1_VERSION) {
542         /*
543          * enable vulnerability countermeasure for CBC ciphers with known-IV
544          * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
545          */
546         s->s3->need_empty_fragments = 1;
547 
548         if (s->session->cipher != NULL) {
549             if (s->session->cipher->algorithm_enc == SSL_eNULL)
550                 s->s3->need_empty_fragments = 0;
551 
552 #ifndef OPENSSL_NO_RC4
553             if (s->session->cipher->algorithm_enc == SSL_RC4)
554                 s->s3->need_empty_fragments = 0;
555 #endif
556         }
557     }
558 
559     ret = 1;
560  err:
561     return ret;
562 }
563 
564 size_t tls1_final_finish_mac(SSL *s, const char *str, size_t slen,
565                              unsigned char *out)
566 {
567     size_t hashlen;
568     unsigned char hash[EVP_MAX_MD_SIZE];
569 
570     if (!ssl3_digest_cached_records(s, 0)) {
571         /* SSLfatal() already called */
572         return 0;
573     }
574 
575     if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen)) {
576         /* SSLfatal() already called */
577         return 0;
578     }
579 
580     if (!tls1_PRF(s, str, slen, hash, hashlen, NULL, 0, NULL, 0, NULL, 0,
581                   s->session->master_key, s->session->master_key_length,
582                   out, TLS1_FINISH_MAC_LENGTH, 1)) {
583         /* SSLfatal() already called */
584         return 0;
585     }
586     OPENSSL_cleanse(hash, hashlen);
587     return TLS1_FINISH_MAC_LENGTH;
588 }
589 
590 int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
591                                 size_t len, size_t *secret_size)
592 {
593     if (s->session->flags & SSL_SESS_FLAG_EXTMS) {
594         unsigned char hash[EVP_MAX_MD_SIZE * 2];
595         size_t hashlen;
596         /*
597          * Digest cached records keeping record buffer (if present): this won't
598          * affect client auth because we're freezing the buffer at the same
599          * point (after client key exchange and before certificate verify)
600          */
601         if (!ssl3_digest_cached_records(s, 1)
602                 || !ssl_handshake_hash(s, hash, sizeof(hash), &hashlen)) {
603             /* SSLfatal() already called */
604             return 0;
605         }
606 #ifdef SSL_DEBUG
607         fprintf(stderr, "Handshake hashes:\n");
608         BIO_dump_fp(stderr, (char *)hash, hashlen);
609 #endif
610         if (!tls1_PRF(s,
611                       TLS_MD_EXTENDED_MASTER_SECRET_CONST,
612                       TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE,
613                       hash, hashlen,
614                       NULL, 0,
615                       NULL, 0,
616                       NULL, 0, p, len, out,
617                       SSL3_MASTER_SECRET_SIZE, 1)) {
618             /* SSLfatal() already called */
619             return 0;
620         }
621         OPENSSL_cleanse(hash, hashlen);
622     } else {
623         if (!tls1_PRF(s,
624                       TLS_MD_MASTER_SECRET_CONST,
625                       TLS_MD_MASTER_SECRET_CONST_SIZE,
626                       s->s3->client_random, SSL3_RANDOM_SIZE,
627                       NULL, 0,
628                       s->s3->server_random, SSL3_RANDOM_SIZE,
629                       NULL, 0, p, len, out,
630                       SSL3_MASTER_SECRET_SIZE, 1)) {
631            /* SSLfatal() already called */
632             return 0;
633         }
634     }
635 #ifdef SSL_DEBUG
636     fprintf(stderr, "Premaster Secret:\n");
637     BIO_dump_fp(stderr, (char *)p, len);
638     fprintf(stderr, "Client Random:\n");
639     BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
640     fprintf(stderr, "Server Random:\n");
641     BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
642     fprintf(stderr, "Master Secret:\n");
643     BIO_dump_fp(stderr, (char *)s->session->master_key,
644                 SSL3_MASTER_SECRET_SIZE);
645 #endif
646 
647     *secret_size = SSL3_MASTER_SECRET_SIZE;
648     return 1;
649 }
650 
651 int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
652                                 const char *label, size_t llen,
653                                 const unsigned char *context,
654                                 size_t contextlen, int use_context)
655 {
656     unsigned char *val = NULL;
657     size_t vallen = 0, currentvalpos;
658     int rv;
659 
660     /*
661      * construct PRF arguments we construct the PRF argument ourself rather
662      * than passing separate values into the TLS PRF to ensure that the
663      * concatenation of values does not create a prohibited label.
664      */
665     vallen = llen + SSL3_RANDOM_SIZE * 2;
666     if (use_context) {
667         vallen += 2 + contextlen;
668     }
669 
670     val = OPENSSL_malloc(vallen);
671     if (val == NULL)
672         goto err2;
673     currentvalpos = 0;
674     memcpy(val + currentvalpos, (unsigned char *)label, llen);
675     currentvalpos += llen;
676     memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
677     currentvalpos += SSL3_RANDOM_SIZE;
678     memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
679     currentvalpos += SSL3_RANDOM_SIZE;
680 
681     if (use_context) {
682         val[currentvalpos] = (contextlen >> 8) & 0xff;
683         currentvalpos++;
684         val[currentvalpos] = contextlen & 0xff;
685         currentvalpos++;
686         if ((contextlen > 0) || (context != NULL)) {
687             memcpy(val + currentvalpos, context, contextlen);
688         }
689     }
690 
691     /*
692      * disallow prohibited labels note that SSL3_RANDOM_SIZE > max(prohibited
693      * label len) = 15, so size of val > max(prohibited label len) = 15 and
694      * the comparisons won't have buffer overflow
695      */
696     if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
697                TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0)
698         goto err1;
699     if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
700                TLS_MD_SERVER_FINISH_CONST_SIZE) == 0)
701         goto err1;
702     if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
703                TLS_MD_MASTER_SECRET_CONST_SIZE) == 0)
704         goto err1;
705     if (memcmp(val, TLS_MD_EXTENDED_MASTER_SECRET_CONST,
706                TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE) == 0)
707         goto err1;
708     if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
709                TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0)
710         goto err1;
711 
712     rv = tls1_PRF(s,
713                   val, vallen,
714                   NULL, 0,
715                   NULL, 0,
716                   NULL, 0,
717                   NULL, 0,
718                   s->session->master_key, s->session->master_key_length,
719                   out, olen, 0);
720 
721     goto ret;
722  err1:
723     SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
724     rv = 0;
725     goto ret;
726  err2:
727     SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE);
728     rv = 0;
729  ret:
730     OPENSSL_clear_free(val, vallen);
731     return rv;
732 }
733 
734 int tls1_alert_code(int code)
735 {
736     switch (code) {
737     case SSL_AD_CLOSE_NOTIFY:
738         return SSL3_AD_CLOSE_NOTIFY;
739     case SSL_AD_UNEXPECTED_MESSAGE:
740         return SSL3_AD_UNEXPECTED_MESSAGE;
741     case SSL_AD_BAD_RECORD_MAC:
742         return SSL3_AD_BAD_RECORD_MAC;
743     case SSL_AD_DECRYPTION_FAILED:
744         return TLS1_AD_DECRYPTION_FAILED;
745     case SSL_AD_RECORD_OVERFLOW:
746         return TLS1_AD_RECORD_OVERFLOW;
747     case SSL_AD_DECOMPRESSION_FAILURE:
748         return SSL3_AD_DECOMPRESSION_FAILURE;
749     case SSL_AD_HANDSHAKE_FAILURE:
750         return SSL3_AD_HANDSHAKE_FAILURE;
751     case SSL_AD_NO_CERTIFICATE:
752         return -1;
753     case SSL_AD_BAD_CERTIFICATE:
754         return SSL3_AD_BAD_CERTIFICATE;
755     case SSL_AD_UNSUPPORTED_CERTIFICATE:
756         return SSL3_AD_UNSUPPORTED_CERTIFICATE;
757     case SSL_AD_CERTIFICATE_REVOKED:
758         return SSL3_AD_CERTIFICATE_REVOKED;
759     case SSL_AD_CERTIFICATE_EXPIRED:
760         return SSL3_AD_CERTIFICATE_EXPIRED;
761     case SSL_AD_CERTIFICATE_UNKNOWN:
762         return SSL3_AD_CERTIFICATE_UNKNOWN;
763     case SSL_AD_ILLEGAL_PARAMETER:
764         return SSL3_AD_ILLEGAL_PARAMETER;
765     case SSL_AD_UNKNOWN_CA:
766         return TLS1_AD_UNKNOWN_CA;
767     case SSL_AD_ACCESS_DENIED:
768         return TLS1_AD_ACCESS_DENIED;
769     case SSL_AD_DECODE_ERROR:
770         return TLS1_AD_DECODE_ERROR;
771     case SSL_AD_DECRYPT_ERROR:
772         return TLS1_AD_DECRYPT_ERROR;
773     case SSL_AD_EXPORT_RESTRICTION:
774         return TLS1_AD_EXPORT_RESTRICTION;
775     case SSL_AD_PROTOCOL_VERSION:
776         return TLS1_AD_PROTOCOL_VERSION;
777     case SSL_AD_INSUFFICIENT_SECURITY:
778         return TLS1_AD_INSUFFICIENT_SECURITY;
779     case SSL_AD_INTERNAL_ERROR:
780         return TLS1_AD_INTERNAL_ERROR;
781     case SSL_AD_USER_CANCELLED:
782         return TLS1_AD_USER_CANCELLED;
783     case SSL_AD_NO_RENEGOTIATION:
784         return TLS1_AD_NO_RENEGOTIATION;
785     case SSL_AD_UNSUPPORTED_EXTENSION:
786         return TLS1_AD_UNSUPPORTED_EXTENSION;
787     case SSL_AD_CERTIFICATE_UNOBTAINABLE:
788         return TLS1_AD_CERTIFICATE_UNOBTAINABLE;
789     case SSL_AD_UNRECOGNIZED_NAME:
790         return TLS1_AD_UNRECOGNIZED_NAME;
791     case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
792         return TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
793     case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
794         return TLS1_AD_BAD_CERTIFICATE_HASH_VALUE;
795     case SSL_AD_UNKNOWN_PSK_IDENTITY:
796         return TLS1_AD_UNKNOWN_PSK_IDENTITY;
797     case SSL_AD_INAPPROPRIATE_FALLBACK:
798         return TLS1_AD_INAPPROPRIATE_FALLBACK;
799     case SSL_AD_NO_APPLICATION_PROTOCOL:
800         return TLS1_AD_NO_APPLICATION_PROTOCOL;
801     case SSL_AD_CERTIFICATE_REQUIRED:
802         return SSL_AD_HANDSHAKE_FAILURE;
803     default:
804         return -1;
805     }
806 }
807