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