blob: 7a385454145b515fb8bf865a31c87e359628fa67 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
7 *
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14 *
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
56 */
57/* ====================================================================
58 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
59 *
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
62 * are met:
63 *
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
66 *
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
70 * distribution.
71 *
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76 *
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
81 *
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
85 *
86 * 6. Redistributions of any form whatsoever must retain the following
87 * acknowledgment:
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90 *
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
104 *
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com).
108 *
109 */
110/* ====================================================================
111 * Copyright 2005 Nokia. All rights reserved.
112 *
113 * The portions of the attached software ("Contribution") is developed by
114 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
115 * license.
116 *
117 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
118 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
119 * support (see RFC 4279) to OpenSSL.
120 *
121 * No patent licenses or other rights except those expressly stated in
122 * the OpenSSL open source license shall be deemed granted or received
123 * expressly, by implication, estoppel, or otherwise.
124 *
125 * No assurances are provided by Nokia that the Contribution does not
126 * infringe the patent or other intellectual property rights of any third
127 * party or that the license provides you with all the necessary rights
128 * to make use of the Contribution.
129 *
130 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
131 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
132 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
133 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
134 * OTHERWISE. */
135
136#include <stdio.h>
137#include <assert.h>
138
139#include <openssl/comp.h>
140#include <openssl/err.h>
141#include <openssl/evp.h>
142#include <openssl/hmac.h>
143#include <openssl/md5.h>
144#include <openssl/mem.h>
145#include <openssl/obj.h>
146#include <openssl/rand.h>
147
148#include "ssl_locl.h"
149
150/* seed1 through seed5 are virtually concatenated */
151static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
152 int sec_len,
153 const void *seed1, int seed1_len,
154 const void *seed2, int seed2_len,
155 const void *seed3, int seed3_len,
156 const void *seed4, int seed4_len,
157 const void *seed5, int seed5_len,
158 unsigned char *out, int olen)
159 {
160 int chunk;
161 size_t j;
162 EVP_MD_CTX ctx, ctx_tmp, ctx_init;
163 EVP_PKEY *mac_key;
164 unsigned char A1[EVP_MAX_MD_SIZE];
165 size_t A1_len;
166 int ret = 0;
167
168 chunk=EVP_MD_size(md);
169
170 EVP_MD_CTX_init(&ctx);
171 EVP_MD_CTX_init(&ctx_tmp);
172 EVP_MD_CTX_init(&ctx_init);
173 mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
174 if (!mac_key)
175 goto err;
176 if (!EVP_DigestSignInit(&ctx_init,NULL,md, NULL, mac_key))
177 goto err;
178 if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init))
179 goto err;
180 if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
181 goto err;
182 if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
183 goto err;
184 if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
185 goto err;
186 if (seed4 && !EVP_DigestSignUpdate(&ctx,seed4,seed4_len))
187 goto err;
188 if (seed5 && !EVP_DigestSignUpdate(&ctx,seed5,seed5_len))
189 goto err;
190 if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
191 goto err;
192
193 for (;;)
194 {
195 /* Reinit mac contexts */
196 if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init))
197 goto err;
198 if (!EVP_DigestSignUpdate(&ctx,A1,A1_len))
199 goto err;
200 if (olen>chunk && !EVP_MD_CTX_copy_ex(&ctx_tmp,&ctx))
201 goto err;
202 if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
203 goto err;
204 if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
205 goto err;
206 if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
207 goto err;
208 if (seed4 && !EVP_DigestSignUpdate(&ctx,seed4,seed4_len))
209 goto err;
210 if (seed5 && !EVP_DigestSignUpdate(&ctx,seed5,seed5_len))
211 goto err;
212
213 if (olen > chunk)
214 {
215 if (!EVP_DigestSignFinal(&ctx,out,&j))
216 goto err;
217 out+=j;
218 olen-=j;
219 /* calc the next A1 value */
220 if (!EVP_DigestSignFinal(&ctx_tmp,A1,&A1_len))
221 goto err;
222 }
223 else /* last one */
224 {
225 if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
226 goto err;
227 memcpy(out,A1,olen);
228 break;
229 }
230 }
231 ret = 1;
232err:
233 EVP_PKEY_free(mac_key);
234 EVP_MD_CTX_cleanup(&ctx);
235 EVP_MD_CTX_cleanup(&ctx_tmp);
236 EVP_MD_CTX_cleanup(&ctx_init);
237 OPENSSL_cleanse(A1,sizeof(A1));
238 return ret;
239 }
240
241/* seed1 through seed5 are virtually concatenated */
242static int tls1_PRF(long digest_mask,
243 const void *seed1, int seed1_len,
244 const void *seed2, int seed2_len,
245 const void *seed3, int seed3_len,
246 const void *seed4, int seed4_len,
247 const void *seed5, int seed5_len,
248 const unsigned char *sec, int slen,
249 unsigned char *out1,
250 unsigned char *out2, int olen)
251 {
252 int len,i,idx,count;
253 const unsigned char *S1;
254 long m;
255 const EVP_MD *md;
256 int ret = 0;
257
258 /* Count number of digests and partition sec evenly */
259 count=0;
260 for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
261 if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) count++;
262 }
263 len=slen/count;
264 if (count == 1)
265 slen = 0;
266 S1=sec;
267 memset(out1,0,olen);
268 for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
269 if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) {
270 if (!md) {
271 OPENSSL_PUT_ERROR(SSL, tls1_PRF, SSL_R_UNSUPPORTED_DIGEST_TYPE);
272 goto err;
273 }
274 if (!tls1_P_hash(md ,S1,len+(slen&1),
275 seed1,seed1_len,seed2,seed2_len,seed3,seed3_len,seed4,seed4_len,seed5,seed5_len,
276 out2,olen))
277 goto err;
278 S1+=len;
279 for (i=0; i<olen; i++)
280 {
281 out1[i]^=out2[i];
282 }
283 }
284 }
285 ret = 1;
286err:
287 return ret;
288}
289static int tls1_generate_key_block(SSL *s, unsigned char *km,
290 unsigned char *tmp, int num)
291 {
292 int ret;
293 ret = tls1_PRF(ssl_get_algorithm2(s),
294 TLS_MD_KEY_EXPANSION_CONST,TLS_MD_KEY_EXPANSION_CONST_SIZE,
295 s->s3->server_random,SSL3_RANDOM_SIZE,
296 s->s3->client_random,SSL3_RANDOM_SIZE,
297 NULL,0,NULL,0,
298 s->session->master_key,s->session->master_key_length,
299 km,tmp,num);
300#ifdef KSSL_DEBUG
301 printf("tls1_generate_key_block() ==> %d byte master_key =\n\t",
302 s->session->master_key_length);
303 {
304 int i;
305 for (i=0; i < s->session->master_key_length; i++)
306 {
307 printf("%02X", s->session->master_key[i]);
308 }
309 printf("\n"); }
310#endif /* KSSL_DEBUG */
311 return ret;
312 }
313
314int tls1_change_cipher_state(SSL *s, int which)
315 {
316 static const unsigned char empty[]="";
317 unsigned char *p,*mac_secret;
318 unsigned char *exp_label;
319 unsigned char tmp1[EVP_MAX_KEY_LENGTH];
320 unsigned char tmp2[EVP_MAX_KEY_LENGTH];
321 unsigned char iv1[EVP_MAX_IV_LENGTH*2];
322 unsigned char iv2[EVP_MAX_IV_LENGTH*2];
323 unsigned char *ms,*key,*iv;
324 int client_write;
325 EVP_CIPHER_CTX *dd;
326 const EVP_CIPHER *c;
327 const EVP_MD *m;
328 int mac_type;
329 int *mac_secret_size;
330 EVP_MD_CTX *mac_ctx;
331 EVP_PKEY *mac_key;
332 int is_export,n,i,j,k,exp_label_len,cl;
333 int reuse_dd = 0;
334
335 is_export=SSL_C_IS_EXPORT(s->s3->tmp.new_cipher);
336 c=s->s3->tmp.new_sym_enc;
337 m=s->s3->tmp.new_hash;
338 mac_type = s->s3->tmp.new_mac_pkey_type;
339
340#ifdef KSSL_DEBUG
341 printf("tls1_change_cipher_state(which= %d) w/\n", which);
342 printf("\talg= %ld/%ld, comp= %p\n",
343 s->s3->tmp.new_cipher->algorithm_mkey,
344 s->s3->tmp.new_cipher->algorithm_auth,
345 comp);
346 printf("\tevp_cipher == %p ==? &d_cbc_ede_cipher3\n", c);
347 printf("\tevp_cipher: nid, blksz= %d, %d, keylen=%d, ivlen=%d\n",
348 c->nid,c->block_size,c->key_len,c->iv_len);
349 printf("\tkey_block: len= %d, data= ", s->s3->tmp.key_block_length);
350 {
351 int i;
352 for (i=0; i<s->s3->tmp.key_block_length; i++)
353 printf("%02x", s->s3->tmp.key_block[i]); printf("\n");
354 }
355#endif /* KSSL_DEBUG */
356
357 if (which & SSL3_CC_READ)
358 {
359 if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
360 s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
361 else
362 s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
363
364 if (s->enc_read_ctx != NULL)
365 reuse_dd = 1;
366 else if ((s->enc_read_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
367 goto err;
368 else
369 /* make sure it's intialized in case we exit later with an error */
370 EVP_CIPHER_CTX_init(s->enc_read_ctx);
371 dd= s->enc_read_ctx;
372 mac_ctx=ssl_replace_hash(&s->read_hash,NULL);
373 /* this is done by dtls1_reset_seq_numbers for DTLS1_VERSION */
374 if (s->version != DTLS1_VERSION)
375 memset(&(s->s3->read_sequence[0]),0,8);
376 mac_secret= &(s->s3->read_mac_secret[0]);
377 mac_secret_size=&(s->s3->read_mac_secret_size);
378 }
379 else
380 {
381 if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
382 s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
383 else
384 s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
385 if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s))
386 reuse_dd = 1;
387 else if ((s->enc_write_ctx=EVP_CIPHER_CTX_new()) == NULL)
388 goto err;
389 dd= s->enc_write_ctx;
390 if (SSL_IS_DTLS(s))
391 {
392 mac_ctx = EVP_MD_CTX_create();
393 if (!mac_ctx)
394 goto err;
395 s->write_hash = mac_ctx;
396 }
397 else
398 mac_ctx = ssl_replace_hash(&s->write_hash,NULL);
399 /* this is done by dtls1_reset_seq_numbers for DTLS1_VERSION */
400 if (s->version != DTLS1_VERSION)
401 memset(&(s->s3->write_sequence[0]),0,8);
402 mac_secret= &(s->s3->write_mac_secret[0]);
403 mac_secret_size = &(s->s3->write_mac_secret_size);
404 }
405
406 if (reuse_dd)
407 EVP_CIPHER_CTX_cleanup(dd);
408
409 p=s->s3->tmp.key_block;
410 i=*mac_secret_size=s->s3->tmp.new_mac_secret_size;
411
412 cl=EVP_CIPHER_key_length(c);
413 j=is_export ? (cl < SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher) ?
414 cl : SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher)) : cl;
415 /* Was j=(exp)?5:EVP_CIPHER_key_length(c); */
416 /* If GCM mode only part of IV comes from PRF */
417 if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
418 k = EVP_GCM_TLS_FIXED_IV_LEN;
419 else
420 k=EVP_CIPHER_iv_length(c);
421 if ( (which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
422 (which == SSL3_CHANGE_CIPHER_SERVER_READ))
423 {
424 ms= &(p[ 0]); n=i+i;
425 key= &(p[ n]); n+=j+j;
426 iv= &(p[ n]); n+=k+k;
427 exp_label=(unsigned char *)TLS_MD_CLIENT_WRITE_KEY_CONST;
428 exp_label_len=TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE;
429 client_write=1;
430 }
431 else
432 {
433 n=i;
434 ms= &(p[ n]); n+=i+j;
435 key= &(p[ n]); n+=j+k;
436 iv= &(p[ n]); n+=k;
437 exp_label=(unsigned char *)TLS_MD_SERVER_WRITE_KEY_CONST;
438 exp_label_len=TLS_MD_SERVER_WRITE_KEY_CONST_SIZE;
439 client_write=0;
440 }
441
442 if (n > s->s3->tmp.key_block_length)
443 {
444 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
445 goto err2;
446 }
447
448 memcpy(mac_secret,ms,i);
449
450 if (!(EVP_CIPHER_flags(c)&EVP_CIPH_FLAG_AEAD_CIPHER))
451 {
452 mac_key = EVP_PKEY_new_mac_key(mac_type, NULL,
453 mac_secret,*mac_secret_size);
454 EVP_DigestSignInit(mac_ctx,NULL,m,NULL,mac_key);
455 EVP_PKEY_free(mac_key);
456 }
457#ifdef TLS_DEBUG
458printf("which = %04X\nmac key=",which);
459{ int z; for (z=0; z<i; z++) printf("%02X%c",ms[z],((z+1)%16)?' ':'\n'); }
460#endif
461 if (is_export)
462 {
463 /* In here I set both the read and write key/iv to the
464 * same value since only the correct one will be used :-).
465 */
466 if (!tls1_PRF(ssl_get_algorithm2(s),
467 exp_label,exp_label_len,
468 s->s3->client_random,SSL3_RANDOM_SIZE,
469 s->s3->server_random,SSL3_RANDOM_SIZE,
470 NULL,0,NULL,0,
471 key,j,tmp1,tmp2,EVP_CIPHER_key_length(c)))
472 goto err2;
473 key=tmp1;
474
475 if (k > 0)
476 {
477 if (!tls1_PRF(ssl_get_algorithm2(s),
478 TLS_MD_IV_BLOCK_CONST,TLS_MD_IV_BLOCK_CONST_SIZE,
479 s->s3->client_random,SSL3_RANDOM_SIZE,
480 s->s3->server_random,SSL3_RANDOM_SIZE,
481 NULL,0,NULL,0,
482 empty,0,iv1,iv2,k*2))
483 goto err2;
484 if (client_write)
485 iv=iv1;
486 else
487 iv= &(iv1[k]);
488 }
489 }
490
491 s->session->key_arg_length=0;
492#ifdef KSSL_DEBUG
493 {
494 int i;
495 printf("EVP_CipherInit_ex(dd,c,key=,iv=,which)\n");
496 printf("\tkey= "); for (i=0; i<c->key_len; i++) printf("%02x", key[i]);
497 printf("\n");
498 printf("\t iv= "); for (i=0; i<c->iv_len; i++) printf("%02x", iv[i]);
499 printf("\n");
500 }
501#endif /* KSSL_DEBUG */
502
503 if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
504 {
505 EVP_CipherInit_ex(dd,c,NULL,key,NULL,(which & SSL3_CC_WRITE));
506 EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, k, iv);
507 }
508 else
509 EVP_CipherInit_ex(dd,c,NULL,key,iv,(which & SSL3_CC_WRITE));
510
511 /* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
512 if ((EVP_CIPHER_flags(c)&EVP_CIPH_FLAG_AEAD_CIPHER) && *mac_secret_size)
513 EVP_CIPHER_CTX_ctrl(dd,EVP_CTRL_AEAD_SET_MAC_KEY,
514 *mac_secret_size,mac_secret);
515
516#ifdef OPENSSL_SSL_TRACE_CRYPTO
517 if (s->msg_callback)
518 {
519 int wh = which & SSL3_CC_WRITE ? TLS1_RT_CRYPTO_WRITE : 0;
520 if (*mac_secret_size)
521 s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_MAC,
522 mac_secret, *mac_secret_size,
523 s, s->msg_callback_arg);
524 if (c->key_len)
525 s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
526 key, c->key_len,
527 s, s->msg_callback_arg);
528 if (k)
529 {
530 if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
531 wh |= TLS1_RT_CRYPTO_FIXED_IV;
532 else
533 wh |= TLS1_RT_CRYPTO_IV;
534 s->msg_callback(2, s->version, wh, iv, k,
535 s, s->msg_callback_arg);
536 }
537 }
538#endif
539
540#ifdef TLS_DEBUG
541printf("which = %04X\nkey=",which);
542{ int z; for (z=0; z<EVP_CIPHER_key_length(c); z++) printf("%02X%c",key[z],((z+1)%16)?' ':'\n'); }
543printf("\niv=");
544{ int z; for (z=0; z<k; z++) printf("%02X%c",iv[z],((z+1)%16)?' ':'\n'); }
545printf("\n");
546#endif
547
548 OPENSSL_cleanse(tmp1,sizeof(tmp1));
549 OPENSSL_cleanse(tmp2,sizeof(tmp1));
550 OPENSSL_cleanse(iv1,sizeof(iv1));
551 OPENSSL_cleanse(iv2,sizeof(iv2));
552 return(1);
553err:
554 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_MALLOC_FAILURE);
555err2:
556 return(0);
557 }
558
559int tls1_setup_key_block(SSL *s)
560 {
561 unsigned char *p1,*p2=NULL;
562 const EVP_CIPHER *c;
563 const EVP_MD *hash;
564 int num;
565 SSL_COMP *comp;
566 int mac_type= NID_undef,mac_secret_size=0;
567 int ret=0;
568
569#ifdef KSSL_DEBUG
570 printf ("tls1_setup_key_block()\n");
571#endif /* KSSL_DEBUG */
572
573 if (s->s3->tmp.key_block_length != 0)
574 return(1);
575
576 if (!ssl_cipher_get_evp(s->session,&c,&hash,&mac_type,&mac_secret_size,&comp))
577 {
578 OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
579 return(0);
580 }
581
582 s->s3->tmp.new_sym_enc=c;
583 s->s3->tmp.new_hash=hash;
584 s->s3->tmp.new_mac_pkey_type = mac_type;
585 s->s3->tmp.new_mac_secret_size = mac_secret_size;
586 num=EVP_CIPHER_key_length(c)+mac_secret_size+EVP_CIPHER_iv_length(c);
587 num*=2;
588
589 ssl3_cleanup_key_block(s);
590
591 if ((p1=(unsigned char *)OPENSSL_malloc(num)) == NULL)
592 {
593 OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
594 goto err;
595 }
596
597 s->s3->tmp.key_block_length=num;
598 s->s3->tmp.key_block=p1;
599
600 if ((p2=(unsigned char *)OPENSSL_malloc(num)) == NULL)
601 {
602 OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
603 goto err;
604 }
605
606#ifdef TLS_DEBUG
607printf("client random\n");
608{ int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->client_random[z],((z+1)%16)?' ':'\n'); }
609printf("server random\n");
610{ int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->server_random[z],((z+1)%16)?' ':'\n'); }
611printf("pre-master\n");
612{ int z; for (z=0; z<s->session->master_key_length; z++) printf("%02X%c",s->session->master_key[z],((z+1)%16)?' ':'\n'); }
613#endif
614 if (!tls1_generate_key_block(s,p1,p2,num))
615 goto err;
616#ifdef TLS_DEBUG
617printf("\nkey block\n");
618{ int z; for (z=0; z<num; z++) printf("%02X%c",p1[z],((z+1)%16)?' ':'\n'); }
619#endif
620
621 if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
622 && s->method->version <= TLS1_VERSION)
623 {
624 /* enable vulnerability countermeasure for CBC ciphers with
625 * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
626 */
627 s->s3->need_empty_fragments = 1;
628
629 if (s->session->cipher != NULL)
630 {
631 if (s->session->cipher->algorithm_enc == SSL_eNULL)
632 s->s3->need_empty_fragments = 0;
633
634#ifndef OPENSSL_NO_RC4
635 if (s->session->cipher->algorithm_enc == SSL_RC4)
636 s->s3->need_empty_fragments = 0;
637#endif
638 }
639 }
640
641 ret = 1;
642err:
643 if (p2)
644 {
645 OPENSSL_cleanse(p2,num);
646 OPENSSL_free(p2);
647 }
648 return(ret);
649 }
650
651/* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
652 *
653 * Returns:
654 * 0: (in non-constant time) if the record is publically invalid (i.e. too
655 * short etc).
656 * 1: if the record's padding is valid / the encryption was successful.
657 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
658 * an internal error occured.
659 */
660int tls1_enc(SSL *s, int send)
661 {
662 SSL3_RECORD *rec;
663 EVP_CIPHER_CTX *ds;
664 unsigned long l;
665 int bs,i,j,k,pad=0,ret,mac_size=0;
666 const EVP_CIPHER *enc;
667
668 if (send)
669 {
670 ds=s->enc_write_ctx;
671 rec= &(s->s3->wrec);
672 if (s->enc_write_ctx == NULL)
673 enc=NULL;
674 else
675 {
676 int ivlen;
677 enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
678 /* For TLSv1.1 and later explicit IV */
679 if (SSL_USE_EXPLICIT_IV(s)
680 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
681 ivlen = EVP_CIPHER_iv_length(enc);
682 else
683 ivlen = 0;
684 if (ivlen > 1)
685 {
686 if ( rec->data != rec->input)
687 /* we can't write into the input stream:
688 * Can this ever happen?? (steve)
689 */
690 fprintf(stderr,
691 "%s:%d: rec->data != rec->input\n",
692 __FILE__, __LINE__);
693 else if (RAND_bytes(rec->input, ivlen) <= 0)
694 return -1;
695 }
696 }
697 }
698 else
699 {
700 ds=s->enc_read_ctx;
701 rec= &(s->s3->rrec);
702 if (s->enc_read_ctx == NULL)
703 enc=NULL;
704 else
705 enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
706 }
707
708#ifdef KSSL_DEBUG
709 printf("tls1_enc(%d)\n", send);
710#endif /* KSSL_DEBUG */
711
712 if ((s->session == NULL) || (ds == NULL) || (enc == NULL))
713 {
714 memmove(rec->data,rec->input,rec->length);
715 rec->input=rec->data;
716 ret = 1;
717 }
718 else
719 {
720 l=rec->length;
721 bs=EVP_CIPHER_block_size(ds->cipher);
722
723 if (EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_AEAD_CIPHER)
724 {
725 unsigned char buf[13],*seq;
726
727 seq = send?s->s3->write_sequence:s->s3->read_sequence;
728
729 if (SSL_IS_DTLS(s))
730 {
731 unsigned char dtlsseq[9],*p=dtlsseq;
732
733 s2n(send?s->d1->w_epoch:s->d1->r_epoch,p);
734 memcpy(p,&seq[2],6);
735 memcpy(buf,dtlsseq,8);
736 }
737 else
738 {
739 memcpy(buf,seq,8);
740 for (i=7; i>=0; i--) /* increment */
741 {
742 ++seq[i];
743 if (seq[i] != 0) break;
744 }
745 }
746
747 buf[8]=rec->type;
748 buf[9]=(unsigned char)(s->version>>8);
749 buf[10]=(unsigned char)(s->version);
750 buf[11]=rec->length>>8;
751 buf[12]=rec->length&0xff;
752 pad=EVP_CIPHER_CTX_ctrl(ds,EVP_CTRL_AEAD_TLS1_AAD,13,buf);
753 if (send)
754 {
755 l+=pad;
756 rec->length+=pad;
757 }
758 }
759 else if ((bs != 1) && send)
760 {
761 i=bs-((int)l%bs);
762
763 /* Add weird padding of upto 256 bytes */
764
765 /* we need to add 'i' padding bytes of value j */
766 j=i-1;
767 if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG)
768 {
769 if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)
770 j++;
771 }
772 for (k=(int)l; k<(int)(l+i); k++)
773 rec->input[k]=j;
774 l+=i;
775 rec->length+=i;
776 }
777
778#ifdef KSSL_DEBUG
779 {
780 unsigned long ui;
781 printf("EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n",
782 ds,rec->data,rec->input,l);
783 printf("\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%d %d], %d iv_len\n",
784 ds->buf_len, ds->cipher->key_len,
785 DES_KEY_SZ, DES_SCHEDULE_SZ,
786 ds->cipher->iv_len);
787 printf("\t\tIV: ");
788 for (i=0; i<ds->cipher->iv_len; i++) printf("%02X", ds->iv[i]);
789 printf("\n");
790 printf("\trec->input=");
791 for (ui=0; ui<l; ui++) printf(" %02x", rec->input[ui]);
792 printf("\n");
793 }
794#endif /* KSSL_DEBUG */
795
796 if (!send)
797 {
798 if (l == 0 || l%bs != 0)
799 return 0;
800 }
801
802 i = EVP_Cipher(ds,rec->data,rec->input,l);
803 if ((EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_CUSTOM_CIPHER)
804 ?(i<0)
805 :(i==0))
806 return -1; /* AEAD can fail to verify MAC */
807 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send)
808 {
809 rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
810 rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
811 rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
812 }
813
814#ifdef KSSL_DEBUG
815 {
816 unsigned long i;
817 printf("\trec->data=");
818 for (i=0; i<l; i++)
819 printf(" %02x", rec->data[i]); printf("\n");
820 }
821#endif /* KSSL_DEBUG */
822
823 ret = 1;
824 if (EVP_MD_CTX_md(s->read_hash) != NULL)
825 mac_size = EVP_MD_CTX_size(s->read_hash);
826 if ((bs != 1) && !send)
827 ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
828 if (pad && !send)
829 rec->length -= pad;
830 }
831 return ret;
832 }
833
834int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
835 {
836 unsigned int ret;
837 EVP_MD_CTX ctx, *d=NULL;
838 int i;
839
840 if (s->s3->handshake_buffer)
841 if (!ssl3_digest_cached_records(s))
842 return 0;
843
844 for (i=0;i<SSL_MAX_DIGEST;i++)
845 {
846 if (s->s3->handshake_dgst[i]&&EVP_MD_CTX_type(s->s3->handshake_dgst[i])==md_nid)
847 {
848 d=s->s3->handshake_dgst[i];
849 break;
850 }
851 }
852 if (!d) {
853 OPENSSL_PUT_ERROR(SSL, tls1_cert_verify_mac, SSL_R_NO_REQUIRED_DIGEST);
854 return 0;
855 }
856
857 EVP_MD_CTX_init(&ctx);
858 EVP_MD_CTX_copy_ex(&ctx,d);
859 EVP_DigestFinal_ex(&ctx,out,&ret);
860 EVP_MD_CTX_cleanup(&ctx);
861 return((int)ret);
862 }
863
Adam Langley1258b6a2014-06-20 12:00:00 -0700864/* tls1_handshake_digest calculates the current handshake hash and writes it to
865 * |out|, which has space for |out_len| bytes. It returns the number of bytes
866 * written or -1 in the event of an error. This function works on a copy of the
867 * underlying digests so can be called multiple times and prior to the final
868 * update etc. */
869int tls1_handshake_digest(SSL *s, unsigned char *out, size_t out_len)
Adam Langley95c29f32014-06-20 12:00:00 -0700870 {
Adam Langley1258b6a2014-06-20 12:00:00 -0700871 const EVP_MD *md;
Adam Langley95c29f32014-06-20 12:00:00 -0700872 EVP_MD_CTX ctx;
Adam Langley1258b6a2014-06-20 12:00:00 -0700873 int i, err = 0, len = 0;
Adam Langley95c29f32014-06-20 12:00:00 -0700874 long mask;
Adam Langley95c29f32014-06-20 12:00:00 -0700875
876 EVP_MD_CTX_init(&ctx);
877
Adam Langley1258b6a2014-06-20 12:00:00 -0700878 for (i = 0; ssl_get_handshake_digest(i, &mask, &md); i++)
Adam Langley95c29f32014-06-20 12:00:00 -0700879 {
Adam Langley1258b6a2014-06-20 12:00:00 -0700880 int hash_size;
881 unsigned int digest_len;
882 EVP_MD_CTX *hdgst = s->s3->handshake_dgst[i];
883
884 if ((mask & ssl_get_algorithm2(s)) == 0)
885 continue;
886
887 hash_size = EVP_MD_size(md);
888 if (!hdgst || hash_size < 0 || (size_t)hash_size > out_len)
Adam Langley95c29f32014-06-20 12:00:00 -0700889 {
Adam Langley1258b6a2014-06-20 12:00:00 -0700890 err = 1;
891 break;
Adam Langley95c29f32014-06-20 12:00:00 -0700892 }
Adam Langley1258b6a2014-06-20 12:00:00 -0700893
894 if (!EVP_MD_CTX_copy_ex(&ctx, hdgst) ||
895 !EVP_DigestFinal_ex(&ctx, out, &digest_len) ||
896 digest_len != (unsigned int)hash_size) /* internal error */
897 {
898 err = 1;
899 break;
900 }
901 out += digest_len;
902 out_len -= digest_len;
903 len += digest_len;
904 }
905
906 EVP_MD_CTX_cleanup(&ctx);
907
908 if (err != 0)
909 return -1;
910 return len;
911 }
912
913int tls1_final_finish_mac(SSL *s,
914 const char *str, int slen, unsigned char *out)
915 {
916 unsigned char buf[2*EVP_MAX_MD_SIZE];
917 unsigned char buf2[12];
918 int err=0;
919 int digests_len;
920
921 if (s->s3->handshake_buffer)
922 if (!ssl3_digest_cached_records(s))
923 return 0;
924
925 digests_len = tls1_handshake_digest(s, buf, sizeof(buf));
926 if (digests_len < 0)
927 {
928 err = 1;
929 digests_len = 0;
Adam Langley95c29f32014-06-20 12:00:00 -0700930 }
931
932 if (!tls1_PRF(ssl_get_algorithm2(s),
Adam Langley1258b6a2014-06-20 12:00:00 -0700933 str,slen, buf, digests_len, NULL,0, NULL,0, NULL,0,
Adam Langley95c29f32014-06-20 12:00:00 -0700934 s->session->master_key,s->session->master_key_length,
935 out,buf2,sizeof buf2))
936 err = 1;
Adam Langley95c29f32014-06-20 12:00:00 -0700937
938 if (err)
939 return 0;
940 else
941 return sizeof buf2;
942 }
943
944int tls1_mac(SSL *ssl, unsigned char *md, int send)
945 {
946 SSL3_RECORD *rec;
947 unsigned char *seq;
948 EVP_MD_CTX *hash;
949 size_t md_size, orig_len;
950 int i;
951 EVP_MD_CTX hmac, *mac_ctx;
952 unsigned char header[13];
953 int stream_mac = (send?(ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM):(ssl->mac_flags&SSL_MAC_FLAG_READ_MAC_STREAM));
954 int t;
955
956 if (send)
957 {
958 rec= &(ssl->s3->wrec);
959 seq= &(ssl->s3->write_sequence[0]);
960 hash=ssl->write_hash;
961 }
962 else
963 {
964 rec= &(ssl->s3->rrec);
965 seq= &(ssl->s3->read_sequence[0]);
966 hash=ssl->read_hash;
967 }
968
969 t=EVP_MD_CTX_size(hash);
970 assert(t >= 0);
971 md_size=t;
972
973 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
974 if (stream_mac)
975 {
976 mac_ctx = hash;
977 }
978 else
979 {
980 EVP_MD_CTX_copy(&hmac,hash);
981 mac_ctx = &hmac;
982 }
983
984 if (SSL_IS_DTLS(ssl))
985 {
986 unsigned char dtlsseq[8],*p=dtlsseq;
987
988 s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p);
989 memcpy (p,&seq[2],6);
990
991 memcpy(header, dtlsseq, 8);
992 }
993 else
994 memcpy(header, seq, 8);
995
996 /* kludge: tls1_cbc_remove_padding passes padding length in rec->type */
997 orig_len = rec->length+md_size+((unsigned int)rec->type>>8);
998 rec->type &= 0xff;
999
1000 header[8]=rec->type;
1001 header[9]=(unsigned char)(ssl->version>>8);
1002 header[10]=(unsigned char)(ssl->version);
1003 header[11]=(rec->length)>>8;
1004 header[12]=(rec->length)&0xff;
1005
1006 if (!send &&
1007 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1008 ssl3_cbc_record_digest_supported(mac_ctx))
1009 {
1010 /* This is a CBC-encrypted record. We must avoid leaking any
1011 * timing-side channel information about how many blocks of
1012 * data we are hashing because that gives an attacker a
1013 * timing-oracle. */
1014 ssl3_cbc_digest_record(
1015 mac_ctx,
1016 md, &md_size,
1017 header, rec->input,
1018 rec->length + md_size, orig_len,
1019 ssl->s3->read_mac_secret,
1020 ssl->s3->read_mac_secret_size,
1021 0 /* not SSLv3 */);
1022 }
1023 else
1024 {
1025 EVP_DigestSignUpdate(mac_ctx,header,sizeof(header));
1026 EVP_DigestSignUpdate(mac_ctx,rec->input,rec->length);
1027 t=EVP_DigestSignFinal(mac_ctx,md,&md_size);
1028 assert(t > 0);
1029#ifdef OPENSSL_FIPS
1030 if (!send && FIPS_mode())
1031 tls_fips_digest_extra(
1032 ssl->enc_read_ctx,
1033 mac_ctx, rec->input,
1034 rec->length, orig_len);
1035#endif
1036 }
1037
1038 if (!stream_mac)
1039 EVP_MD_CTX_cleanup(&hmac);
1040#ifdef TLS_DEBUG
1041printf("sec=");
1042{unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",mac_sec[z]); printf("\n"); }
1043printf("seq=");
1044{int z; for (z=0; z<8; z++) printf("%02X ",seq[z]); printf("\n"); }
1045printf("buf=");
1046{int z; for (z=0; z<5; z++) printf("%02X ",buf[z]); printf("\n"); }
1047printf("rec=");
1048{unsigned int z; for (z=0; z<rec->length; z++) printf("%02X ",buf[z]); printf("\n"); }
1049#endif
1050
1051 if (!SSL_IS_DTLS(ssl))
1052 {
1053 for (i=7; i>=0; i--)
1054 {
1055 ++seq[i];
1056 if (seq[i] != 0) break;
1057 }
1058 }
1059
1060#ifdef TLS_DEBUG
1061{unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",md[z]); printf("\n"); }
1062#endif
1063 return(md_size);
1064 }
1065
1066int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
1067 int len)
1068 {
1069 unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
1070 const void *co = NULL, *so = NULL;
1071 int col = 0, sol = 0;
1072
1073
1074#ifdef KSSL_DEBUG
1075 printf ("tls1_generate_master_secret(%p,%p, %p, %d)\n", s,out, p,len);
1076#endif /* KSSL_DEBUG */
1077
1078#ifdef TLSEXT_TYPE_opaque_prf_input
1079 if (s->s3->client_opaque_prf_input != NULL && s->s3->server_opaque_prf_input != NULL &&
1080 s->s3->client_opaque_prf_input_len > 0 &&
1081 s->s3->client_opaque_prf_input_len == s->s3->server_opaque_prf_input_len)
1082 {
1083 co = s->s3->client_opaque_prf_input;
1084 col = s->s3->server_opaque_prf_input_len;
1085 so = s->s3->server_opaque_prf_input;
1086 sol = s->s3->client_opaque_prf_input_len; /* must be same as col (see draft-rescorla-tls-opaque-prf-input-00.txt, section 3.1) */
1087 }
1088#endif
1089
1090 tls1_PRF(ssl_get_algorithm2(s),
1091 TLS_MD_MASTER_SECRET_CONST,TLS_MD_MASTER_SECRET_CONST_SIZE,
1092 s->s3->client_random,SSL3_RANDOM_SIZE,
1093 co, col,
1094 s->s3->server_random,SSL3_RANDOM_SIZE,
1095 so, sol,
1096 p,len,
1097 s->session->master_key,buff,sizeof buff);
1098#ifdef SSL_DEBUG
1099 fprintf(stderr, "Premaster Secret:\n");
1100 BIO_dump_fp(stderr, (char *)p, len);
1101 fprintf(stderr, "Client Random:\n");
1102 BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
1103 fprintf(stderr, "Server Random:\n");
1104 BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
1105 fprintf(stderr, "Master Secret:\n");
1106 BIO_dump_fp(stderr, (char *)s->session->master_key, SSL3_MASTER_SECRET_SIZE);
1107#endif
1108
1109#ifdef OPENSSL_SSL_TRACE_CRYPTO
1110 if (s->msg_callback)
1111 {
1112 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
1113 p, len, s, s->msg_callback_arg);
1114 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
1115 s->s3->client_random, SSL3_RANDOM_SIZE,
1116 s, s->msg_callback_arg);
1117 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
1118 s->s3->server_random, SSL3_RANDOM_SIZE,
1119 s, s->msg_callback_arg);
1120 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
1121 s->session->master_key,
1122 SSL3_MASTER_SECRET_SIZE,
1123 s, s->msg_callback_arg);
1124 }
1125#endif
1126
1127#ifdef KSSL_DEBUG
1128 printf ("tls1_generate_master_secret() complete\n");
1129#endif /* KSSL_DEBUG */
1130 return(SSL3_MASTER_SECRET_SIZE);
1131 }
1132
1133int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1134 const char *label, size_t llen, const unsigned char *context,
1135 size_t contextlen, int use_context)
1136 {
1137 unsigned char *buff;
1138 unsigned char *val = NULL;
1139 size_t vallen, currentvalpos;
1140 int rv;
1141
1142#ifdef KSSL_DEBUG
1143 printf ("tls1_export_keying_material(%p,%p,%d,%s,%d,%p,%d)\n", s, out, olen, label, llen, p, plen);
1144#endif /* KSSL_DEBUG */
1145
1146 buff = OPENSSL_malloc(olen);
1147 if (buff == NULL) goto err2;
1148
1149 /* construct PRF arguments
1150 * we construct the PRF argument ourself rather than passing separate
1151 * values into the TLS PRF to ensure that the concatenation of values
1152 * does not create a prohibited label.
1153 */
1154 vallen = llen + SSL3_RANDOM_SIZE * 2;
1155 if (use_context)
1156 {
1157 vallen += 2 + contextlen;
1158 }
1159
1160 val = OPENSSL_malloc(vallen);
1161 if (val == NULL) goto err2;
1162 currentvalpos = 0;
1163 memcpy(val + currentvalpos, (unsigned char *) label, llen);
1164 currentvalpos += llen;
1165 memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
1166 currentvalpos += SSL3_RANDOM_SIZE;
1167 memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
1168 currentvalpos += SSL3_RANDOM_SIZE;
1169
1170 if (use_context)
1171 {
1172 val[currentvalpos] = (contextlen >> 8) & 0xff;
1173 currentvalpos++;
1174 val[currentvalpos] = contextlen & 0xff;
1175 currentvalpos++;
1176 if ((contextlen > 0) || (context != NULL))
1177 {
1178 memcpy(val + currentvalpos, context, contextlen);
1179 }
1180 }
1181
1182 /* disallow prohibited labels
1183 * note that SSL3_RANDOM_SIZE > max(prohibited label len) =
1184 * 15, so size of val > max(prohibited label len) = 15 and the
1185 * comparisons won't have buffer overflow
1186 */
1187 if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
1188 TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0) goto err1;
1189 if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
1190 TLS_MD_SERVER_FINISH_CONST_SIZE) == 0) goto err1;
1191 if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
1192 TLS_MD_MASTER_SECRET_CONST_SIZE) == 0) goto err1;
1193 if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
1194 TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0) goto err1;
1195
1196 rv = tls1_PRF(s->s3->tmp.new_cipher->algorithm2,
1197 val, vallen,
1198 NULL, 0,
1199 NULL, 0,
1200 NULL, 0,
1201 NULL, 0,
1202 s->session->master_key,s->session->master_key_length,
1203 out,buff,olen);
1204
1205#ifdef KSSL_DEBUG
1206 printf ("tls1_export_keying_material() complete\n");
1207#endif /* KSSL_DEBUG */
1208 goto ret;
1209err1:
1210 OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
1211 rv = 0;
1212 goto ret;
1213err2:
1214 OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, ERR_R_MALLOC_FAILURE);
1215 rv = 0;
1216ret:
1217 if (buff != NULL) OPENSSL_free(buff);
1218 if (val != NULL) OPENSSL_free(val);
1219 return(rv);
1220 }
1221
1222int tls1_alert_code(int code)
1223 {
1224 switch (code)
1225 {
1226 case SSL_AD_CLOSE_NOTIFY: return(SSL3_AD_CLOSE_NOTIFY);
1227 case SSL_AD_UNEXPECTED_MESSAGE: return(SSL3_AD_UNEXPECTED_MESSAGE);
1228 case SSL_AD_BAD_RECORD_MAC: return(SSL3_AD_BAD_RECORD_MAC);
1229 case SSL_AD_DECRYPTION_FAILED: return(TLS1_AD_DECRYPTION_FAILED);
1230 case SSL_AD_RECORD_OVERFLOW: return(TLS1_AD_RECORD_OVERFLOW);
1231 case SSL_AD_DECOMPRESSION_FAILURE:return(SSL3_AD_DECOMPRESSION_FAILURE);
1232 case SSL_AD_HANDSHAKE_FAILURE: return(SSL3_AD_HANDSHAKE_FAILURE);
1233 case SSL_AD_NO_CERTIFICATE: return(-1);
1234 case SSL_AD_BAD_CERTIFICATE: return(SSL3_AD_BAD_CERTIFICATE);
1235 case SSL_AD_UNSUPPORTED_CERTIFICATE:return(SSL3_AD_UNSUPPORTED_CERTIFICATE);
1236 case SSL_AD_CERTIFICATE_REVOKED:return(SSL3_AD_CERTIFICATE_REVOKED);
1237 case SSL_AD_CERTIFICATE_EXPIRED:return(SSL3_AD_CERTIFICATE_EXPIRED);
1238 case SSL_AD_CERTIFICATE_UNKNOWN:return(SSL3_AD_CERTIFICATE_UNKNOWN);
1239 case SSL_AD_ILLEGAL_PARAMETER: return(SSL3_AD_ILLEGAL_PARAMETER);
1240 case SSL_AD_UNKNOWN_CA: return(TLS1_AD_UNKNOWN_CA);
1241 case SSL_AD_ACCESS_DENIED: return(TLS1_AD_ACCESS_DENIED);
1242 case SSL_AD_DECODE_ERROR: return(TLS1_AD_DECODE_ERROR);
1243 case SSL_AD_DECRYPT_ERROR: return(TLS1_AD_DECRYPT_ERROR);
1244 case SSL_AD_EXPORT_RESTRICTION: return(TLS1_AD_EXPORT_RESTRICTION);
1245 case SSL_AD_PROTOCOL_VERSION: return(TLS1_AD_PROTOCOL_VERSION);
1246 case SSL_AD_INSUFFICIENT_SECURITY:return(TLS1_AD_INSUFFICIENT_SECURITY);
1247 case SSL_AD_INTERNAL_ERROR: return(TLS1_AD_INTERNAL_ERROR);
1248 case SSL_AD_USER_CANCELLED: return(TLS1_AD_USER_CANCELLED);
1249 case SSL_AD_NO_RENEGOTIATION: return(TLS1_AD_NO_RENEGOTIATION);
1250 case SSL_AD_UNSUPPORTED_EXTENSION: return(TLS1_AD_UNSUPPORTED_EXTENSION);
1251 case SSL_AD_CERTIFICATE_UNOBTAINABLE: return(TLS1_AD_CERTIFICATE_UNOBTAINABLE);
1252 case SSL_AD_UNRECOGNIZED_NAME: return(TLS1_AD_UNRECOGNIZED_NAME);
1253 case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE: return(TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
1254 case SSL_AD_BAD_CERTIFICATE_HASH_VALUE: return(TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
1255 case SSL_AD_UNKNOWN_PSK_IDENTITY:return(TLS1_AD_UNKNOWN_PSK_IDENTITY);
1256#if 0 /* not appropriate for TLS, not used for DTLS */
1257 case DTLS1_AD_MISSING_HANDSHAKE_MESSAGE: return
1258 (DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
1259#endif
1260 default: return(-1);
1261 }
1262 }