1/* ssl/s3_clnt.c */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58/* ====================================================================
59 * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 *    notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 *    notice, this list of conditions and the following disclaimer in
70 *    the documentation and/or other materials provided with the
71 *    distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 *    software must display the following acknowledgment:
75 *    "This product includes software developed by the OpenSSL Project
76 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 *    endorse or promote products derived from this software without
80 *    prior written permission. For written permission, please contact
81 *    openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 *    nor may "OpenSSL" appear in their names without prior written
85 *    permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 *    acknowledgment:
89 *    "This product includes software developed by the OpenSSL Project
90 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com).  This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111/* ====================================================================
112 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113 *
114 * Portions of the attached software ("Contribution") are developed by
115 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116 *
117 * The Contribution is licensed pursuant to the OpenSSL open source
118 * license provided above.
119 *
120 * ECC cipher suite support in OpenSSL originally written by
121 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122 *
123 */
124/* ====================================================================
125 * Copyright 2005 Nokia. All rights reserved.
126 *
127 * The portions of the attached software ("Contribution") is developed by
128 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
129 * license.
130 *
131 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133 * support (see RFC 4279) to OpenSSL.
134 *
135 * No patent licenses or other rights except those expressly stated in
136 * the OpenSSL open source license shall be deemed granted or received
137 * expressly, by implication, estoppel, or otherwise.
138 *
139 * No assurances are provided by Nokia that the Contribution does not
140 * infringe the patent or other intellectual property rights of any third
141 * party or that the license provides you with all the necessary rights
142 * to make use of the Contribution.
143 *
144 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
148 * OTHERWISE.
149 */
150
151#include <stdio.h>
152#include "ssl_locl.h"
153#include "kssl_lcl.h"
154#include <openssl/buffer.h>
155#include <openssl/rand.h>
156#include <openssl/objects.h>
157#include <openssl/evp.h>
158#include <openssl/md5.h>
159#ifndef OPENSSL_NO_DH
160#include <openssl/dh.h>
161#endif
162#include <openssl/bn.h>
163#ifndef OPENSSL_NO_ENGINE
164#include <openssl/engine.h>
165#endif
166
167static const SSL_METHOD *ssl3_get_client_method(int ver);
168static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b);
169
170static const SSL_METHOD *ssl3_get_client_method(int ver)
171	{
172	if (ver == SSL3_VERSION)
173		return(SSLv3_client_method());
174	else
175		return(NULL);
176	}
177
178IMPLEMENT_ssl3_meth_func(SSLv3_client_method,
179			ssl_undefined_function,
180			ssl3_connect,
181			ssl3_get_client_method)
182
183int ssl3_connect(SSL *s)
184	{
185	BUF_MEM *buf=NULL;
186	unsigned long Time=(unsigned long)time(NULL);
187	void (*cb)(const SSL *ssl,int type,int val)=NULL;
188	int ret= -1;
189	int new_state,state,skip=0;
190
191	RAND_add(&Time,sizeof(Time),0);
192	ERR_clear_error();
193	clear_sys_error();
194
195	if (s->info_callback != NULL)
196		cb=s->info_callback;
197	else if (s->ctx->info_callback != NULL)
198		cb=s->ctx->info_callback;
199
200	s->in_handshake++;
201	if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
202
203	for (;;)
204		{
205		state=s->state;
206
207		switch(s->state)
208			{
209		case SSL_ST_RENEGOTIATE:
210			s->new_session=1;
211			s->state=SSL_ST_CONNECT;
212			s->ctx->stats.sess_connect_renegotiate++;
213			/* break */
214		case SSL_ST_BEFORE:
215		case SSL_ST_CONNECT:
216		case SSL_ST_BEFORE|SSL_ST_CONNECT:
217		case SSL_ST_OK|SSL_ST_CONNECT:
218
219			s->server=0;
220			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
221
222			if ((s->version & 0xff00 ) != 0x0300)
223				{
224				SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
225				ret = -1;
226				goto end;
227				}
228
229			/* s->version=SSL3_VERSION; */
230			s->type=SSL_ST_CONNECT;
231
232			if (s->init_buf == NULL)
233				{
234				if ((buf=BUF_MEM_new()) == NULL)
235					{
236					ret= -1;
237					goto end;
238					}
239				if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
240					{
241					ret= -1;
242					goto end;
243					}
244				s->init_buf=buf;
245				buf=NULL;
246				}
247
248			if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
249
250			/* setup buffing BIO */
251			if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
252
253			/* don't push the buffering BIO quite yet */
254
255			ssl3_init_finished_mac(s);
256
257			s->state=SSL3_ST_CW_CLNT_HELLO_A;
258			s->ctx->stats.sess_connect++;
259			s->init_num=0;
260			break;
261
262		case SSL3_ST_CW_CLNT_HELLO_A:
263		case SSL3_ST_CW_CLNT_HELLO_B:
264
265			s->shutdown=0;
266			ret=ssl3_client_hello(s);
267			if (ret <= 0) goto end;
268			s->state=SSL3_ST_CR_SRVR_HELLO_A;
269			s->init_num=0;
270
271			/* turn on buffering for the next lot of output */
272			if (s->bbio != s->wbio)
273				s->wbio=BIO_push(s->bbio,s->wbio);
274
275			break;
276
277		case SSL3_ST_CR_SRVR_HELLO_A:
278		case SSL3_ST_CR_SRVR_HELLO_B:
279			ret=ssl3_get_server_hello(s);
280			if (ret <= 0) goto end;
281
282			if (s->hit)
283				{
284				s->state=SSL3_ST_CR_FINISHED_A;
285#ifndef OPENSSL_NO_TLSEXT
286				if (s->tlsext_ticket_expected)
287					{
288					/* receive renewed session ticket */
289					s->state=SSL3_ST_CR_SESSION_TICKET_A;
290					}
291#endif
292				}
293			else
294				s->state=SSL3_ST_CR_CERT_A;
295			s->init_num=0;
296			break;
297
298		case SSL3_ST_CR_CERT_A:
299		case SSL3_ST_CR_CERT_B:
300#ifndef OPENSSL_NO_TLSEXT
301			ret=ssl3_check_finished(s);
302			if (ret <= 0) goto end;
303			if (ret == 2)
304				{
305				s->hit = 1;
306				if (s->tlsext_ticket_expected)
307					s->state=SSL3_ST_CR_SESSION_TICKET_A;
308				else
309					s->state=SSL3_ST_CR_FINISHED_A;
310				s->init_num=0;
311				break;
312				}
313#endif
314			/* Check if it is anon DH/ECDH */
315			/* or PSK */
316			if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
317			    !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
318				{
319				ret=ssl3_get_server_certificate(s);
320				if (ret <= 0) goto end;
321#ifndef OPENSSL_NO_TLSEXT
322				if (s->tlsext_status_expected)
323					s->state=SSL3_ST_CR_CERT_STATUS_A;
324				else
325					s->state=SSL3_ST_CR_KEY_EXCH_A;
326				}
327			else
328				{
329				skip = 1;
330				s->state=SSL3_ST_CR_KEY_EXCH_A;
331				}
332#else
333				}
334			else
335				skip=1;
336
337			s->state=SSL3_ST_CR_KEY_EXCH_A;
338#endif
339			s->init_num=0;
340			break;
341
342		case SSL3_ST_CR_KEY_EXCH_A:
343		case SSL3_ST_CR_KEY_EXCH_B:
344			ret=ssl3_get_key_exchange(s);
345			if (ret <= 0) goto end;
346			s->state=SSL3_ST_CR_CERT_REQ_A;
347			s->init_num=0;
348
349			/* at this point we check that we have the
350			 * required stuff from the server */
351			if (!ssl3_check_cert_and_algorithm(s))
352				{
353				ret= -1;
354				goto end;
355				}
356			break;
357
358		case SSL3_ST_CR_CERT_REQ_A:
359		case SSL3_ST_CR_CERT_REQ_B:
360			ret=ssl3_get_certificate_request(s);
361			if (ret <= 0) goto end;
362			s->state=SSL3_ST_CR_SRVR_DONE_A;
363			s->init_num=0;
364			break;
365
366		case SSL3_ST_CR_SRVR_DONE_A:
367		case SSL3_ST_CR_SRVR_DONE_B:
368			ret=ssl3_get_server_done(s);
369			if (ret <= 0) goto end;
370			if (s->s3->tmp.cert_req)
371				s->state=SSL3_ST_CW_CERT_A;
372			else
373				s->state=SSL3_ST_CW_KEY_EXCH_A;
374			s->init_num=0;
375
376			break;
377
378		case SSL3_ST_CW_CERT_A:
379		case SSL3_ST_CW_CERT_B:
380		case SSL3_ST_CW_CERT_C:
381		case SSL3_ST_CW_CERT_D:
382			ret=ssl3_send_client_certificate(s);
383			if (ret <= 0) goto end;
384			s->state=SSL3_ST_CW_KEY_EXCH_A;
385			s->init_num=0;
386			break;
387
388		case SSL3_ST_CW_KEY_EXCH_A:
389		case SSL3_ST_CW_KEY_EXCH_B:
390			ret=ssl3_send_client_key_exchange(s);
391			if (ret <= 0) goto end;
392			/* EAY EAY EAY need to check for DH fix cert
393			 * sent back */
394			/* For TLS, cert_req is set to 2, so a cert chain
395			 * of nothing is sent, but no verify packet is sent */
396			/* XXX: For now, we do not support client
397			 * authentication in ECDH cipher suites with
398			 * ECDH (rather than ECDSA) certificates.
399			 * We need to skip the certificate verify
400			 * message when client's ECDH public key is sent
401			 * inside the client certificate.
402			 */
403			if (s->s3->tmp.cert_req == 1)
404				{
405				s->state=SSL3_ST_CW_CERT_VRFY_A;
406				}
407			else
408				{
409				s->state=SSL3_ST_CW_CHANGE_A;
410				s->s3->change_cipher_spec=0;
411				}
412			if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
413				{
414				s->state=SSL3_ST_CW_CHANGE_A;
415				s->s3->change_cipher_spec=0;
416				}
417
418			s->init_num=0;
419			break;
420
421		case SSL3_ST_CW_CERT_VRFY_A:
422		case SSL3_ST_CW_CERT_VRFY_B:
423			ret=ssl3_send_client_verify(s);
424			if (ret <= 0) goto end;
425			s->state=SSL3_ST_CW_CHANGE_A;
426			s->init_num=0;
427			s->s3->change_cipher_spec=0;
428			break;
429
430		case SSL3_ST_CW_CHANGE_A:
431		case SSL3_ST_CW_CHANGE_B:
432			ret=ssl3_send_change_cipher_spec(s,
433				SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
434			if (ret <= 0) goto end;
435			s->state=SSL3_ST_CW_FINISHED_A;
436			s->init_num=0;
437
438			s->session->cipher=s->s3->tmp.new_cipher;
439#ifdef OPENSSL_NO_COMP
440			s->session->compress_meth=0;
441#else
442			if (s->s3->tmp.new_compression == NULL)
443				s->session->compress_meth=0;
444			else
445				s->session->compress_meth=
446					s->s3->tmp.new_compression->id;
447#endif
448			if (!s->method->ssl3_enc->setup_key_block(s))
449				{
450				ret= -1;
451				goto end;
452				}
453
454			if (!s->method->ssl3_enc->change_cipher_state(s,
455				SSL3_CHANGE_CIPHER_CLIENT_WRITE))
456				{
457				ret= -1;
458				goto end;
459				}
460
461			break;
462
463		case SSL3_ST_CW_FINISHED_A:
464		case SSL3_ST_CW_FINISHED_B:
465			ret=ssl3_send_finished(s,
466				SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
467				s->method->ssl3_enc->client_finished_label,
468				s->method->ssl3_enc->client_finished_label_len);
469			if (ret <= 0) goto end;
470			s->s3->flags |= SSL3_FLAGS_CCS_OK;
471			s->state=SSL3_ST_CW_FLUSH;
472
473			/* clear flags */
474			s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
475			if (s->hit)
476				{
477				s->s3->tmp.next_state=SSL_ST_OK;
478				if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
479					{
480					s->state=SSL_ST_OK;
481					s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
482					s->s3->delay_buf_pop_ret=0;
483					}
484				}
485			else
486				{
487#ifndef OPENSSL_NO_TLSEXT
488				/* Allow NewSessionTicket if ticket expected */
489				if (s->tlsext_ticket_expected)
490					s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
491				else
492#endif
493
494				s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
495				}
496			s->init_num=0;
497			break;
498
499#ifndef OPENSSL_NO_TLSEXT
500		case SSL3_ST_CR_SESSION_TICKET_A:
501		case SSL3_ST_CR_SESSION_TICKET_B:
502			ret=ssl3_get_new_session_ticket(s);
503			if (ret <= 0) goto end;
504			s->state=SSL3_ST_CR_FINISHED_A;
505			s->init_num=0;
506		break;
507
508		case SSL3_ST_CR_CERT_STATUS_A:
509		case SSL3_ST_CR_CERT_STATUS_B:
510			ret=ssl3_get_cert_status(s);
511			if (ret <= 0) goto end;
512			s->state=SSL3_ST_CR_KEY_EXCH_A;
513			s->init_num=0;
514		break;
515#endif
516
517		case SSL3_ST_CR_FINISHED_A:
518		case SSL3_ST_CR_FINISHED_B:
519
520			s->s3->flags |= SSL3_FLAGS_CCS_OK;
521			ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
522				SSL3_ST_CR_FINISHED_B);
523			if (ret <= 0) goto end;
524
525			if (s->hit)
526				s->state=SSL3_ST_CW_CHANGE_A;
527			else
528				s->state=SSL_ST_OK;
529			s->init_num=0;
530			break;
531
532		case SSL3_ST_CW_FLUSH:
533			s->rwstate=SSL_WRITING;
534			if (BIO_flush(s->wbio) <= 0)
535				{
536				ret= -1;
537				goto end;
538				}
539			s->rwstate=SSL_NOTHING;
540			s->state=s->s3->tmp.next_state;
541			break;
542
543		case SSL_ST_OK:
544			/* clean a few things up */
545			ssl3_cleanup_key_block(s);
546
547			if (s->init_buf != NULL)
548				{
549				BUF_MEM_free(s->init_buf);
550				s->init_buf=NULL;
551				}
552
553			/* If we are not 'joining' the last two packets,
554			 * remove the buffering now */
555			if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
556				ssl_free_wbio_buffer(s);
557			/* else do it later in ssl3_write */
558
559			s->init_num=0;
560			s->new_session=0;
561
562			ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
563			if (s->hit) s->ctx->stats.sess_hit++;
564
565			ret=1;
566			/* s->server=0; */
567			s->handshake_func=ssl3_connect;
568			s->ctx->stats.sess_connect_good++;
569
570			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
571
572			goto end;
573			/* break; */
574
575		default:
576			SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);
577			ret= -1;
578			goto end;
579			/* break; */
580			}
581
582		/* did we do anything */
583		if (!s->s3->tmp.reuse_message && !skip)
584			{
585			if (s->debug)
586				{
587				if ((ret=BIO_flush(s->wbio)) <= 0)
588					goto end;
589				}
590
591			if ((cb != NULL) && (s->state != state))
592				{
593				new_state=s->state;
594				s->state=state;
595				cb(s,SSL_CB_CONNECT_LOOP,1);
596				s->state=new_state;
597				}
598			}
599		skip=0;
600		}
601end:
602	s->in_handshake--;
603	if (buf != NULL)
604		BUF_MEM_free(buf);
605	if (cb != NULL)
606		cb(s,SSL_CB_CONNECT_EXIT,ret);
607	return(ret);
608	}
609
610
611int ssl3_client_hello(SSL *s)
612	{
613	unsigned char *buf;
614	unsigned char *p,*d;
615	int i;
616	unsigned long Time,l;
617#ifndef OPENSSL_NO_COMP
618	int j;
619	SSL_COMP *comp;
620#endif
621
622	buf=(unsigned char *)s->init_buf->data;
623	if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
624		{
625		SSL_SESSION *sess = s->session;
626		if ((sess == NULL) ||
627			(sess->ssl_version != s->version) ||
628#ifdef OPENSSL_NO_TLSEXT
629			!sess->session_id_length ||
630#else
631			(!sess->session_id_length && !sess->tlsext_tick) ||
632#endif
633			(sess->not_resumable))
634			{
635			if (!ssl_get_new_session(s,0))
636				goto err;
637			}
638		/* else use the pre-loaded session */
639
640		p=s->s3->client_random;
641		Time=(unsigned long)time(NULL);			/* Time */
642		l2n(Time,p);
643		if (RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-4) <= 0)
644			goto err;
645
646		/* Do the message type and length last */
647		d=p= &(buf[4]);
648
649		*(p++)=s->version>>8;
650		*(p++)=s->version&0xff;
651		s->client_version=s->version;
652
653		/* Random stuff */
654		memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
655		p+=SSL3_RANDOM_SIZE;
656
657		/* Session ID */
658		if (s->new_session)
659			i=0;
660		else
661			i=s->session->session_id_length;
662		*(p++)=i;
663		if (i != 0)
664			{
665			if (i > (int)sizeof(s->session->session_id))
666				{
667				SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
668				goto err;
669				}
670			memcpy(p,s->session->session_id,i);
671			p+=i;
672			}
673
674		/* Ciphers supported */
675		i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
676		if (i == 0)
677			{
678			SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
679			goto err;
680			}
681		s2n(i,p);
682		p+=i;
683
684		/* COMPRESSION */
685#ifdef OPENSSL_NO_COMP
686		*(p++)=1;
687#else
688
689		if ((s->options & SSL_OP_NO_COMPRESSION)
690					|| !s->ctx->comp_methods)
691			j=0;
692		else
693			j=sk_SSL_COMP_num(s->ctx->comp_methods);
694		*(p++)=1+j;
695		for (i=0; i<j; i++)
696			{
697			comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
698			*(p++)=comp->id;
699			}
700#endif
701		*(p++)=0; /* Add the NULL method */
702
703#ifndef OPENSSL_NO_TLSEXT
704		/* TLS extensions*/
705		if (ssl_prepare_clienthello_tlsext(s) <= 0)
706			{
707			SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);
708			goto err;
709			}
710		if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
711			{
712			SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
713			goto err;
714			}
715#endif
716
717		l=(p-d);
718		d=buf;
719		*(d++)=SSL3_MT_CLIENT_HELLO;
720		l2n3(l,d);
721
722		s->state=SSL3_ST_CW_CLNT_HELLO_B;
723		/* number of bytes to write */
724		s->init_num=p-buf;
725		s->init_off=0;
726		}
727
728	/* SSL3_ST_CW_CLNT_HELLO_B */
729	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
730err:
731	return(-1);
732	}
733
734int ssl3_get_server_hello(SSL *s)
735	{
736	STACK_OF(SSL_CIPHER) *sk;
737	const SSL_CIPHER *c;
738	unsigned char *p,*d;
739	int i,al,ok;
740	unsigned int j;
741	long n;
742#ifndef OPENSSL_NO_COMP
743	SSL_COMP *comp;
744#endif
745
746	n=s->method->ssl_get_message(s,
747		SSL3_ST_CR_SRVR_HELLO_A,
748		SSL3_ST_CR_SRVR_HELLO_B,
749		-1,
750		20000, /* ?? */
751		&ok);
752
753	if (!ok) return((int)n);
754
755	if ( SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER)
756		{
757		if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST)
758			{
759			if ( s->d1->send_cookie == 0)
760				{
761				s->s3->tmp.reuse_message = 1;
762				return 1;
763				}
764			else /* already sent a cookie */
765				{
766				al=SSL_AD_UNEXPECTED_MESSAGE;
767				SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
768				goto f_err;
769				}
770			}
771		}
772
773	if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO)
774		{
775		al=SSL_AD_UNEXPECTED_MESSAGE;
776		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
777		goto f_err;
778		}
779
780	d=p=(unsigned char *)s->init_msg;
781
782	if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff)))
783		{
784		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION);
785		s->version=(s->version&0xff00)|p[1];
786		al=SSL_AD_PROTOCOL_VERSION;
787		goto f_err;
788		}
789	p+=2;
790
791	/* load the server hello data */
792	/* load the server random */
793	memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE);
794	p+=SSL3_RANDOM_SIZE;
795
796	/* get the session-id */
797	j= *(p++);
798
799	if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE))
800		{
801		al=SSL_AD_ILLEGAL_PARAMETER;
802		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG);
803		goto f_err;
804		}
805
806#ifndef OPENSSL_NO_TLSEXT
807	/* check if we want to resume the session based on external pre-shared secret */
808	if (s->version >= TLS1_VERSION && s->tls_session_secret_cb)
809		{
810		SSL_CIPHER *pref_cipher=NULL;
811		s->session->master_key_length=sizeof(s->session->master_key);
812		if (s->tls_session_secret_cb(s, s->session->master_key,
813					     &s->session->master_key_length,
814					     NULL, &pref_cipher,
815					     s->tls_session_secret_cb_arg))
816			{
817			s->session->cipher = pref_cipher ?
818				pref_cipher : ssl_get_cipher_by_char(s, p+j);
819	    		s->s3->flags |= SSL3_FLAGS_CCS_OK;
820			}
821		}
822#endif /* OPENSSL_NO_TLSEXT */
823
824	if (j != 0 && j == s->session->session_id_length
825	    && memcmp(p,s->session->session_id,j) == 0)
826	    {
827	    if(s->sid_ctx_length != s->session->sid_ctx_length
828	       || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length))
829		{
830		/* actually a client application bug */
831		al=SSL_AD_ILLEGAL_PARAMETER;
832		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
833		goto f_err;
834		}
835	    s->s3->flags |= SSL3_FLAGS_CCS_OK;
836	    s->hit=1;
837	    }
838	else	/* a miss or crap from the other end */
839		{
840		/* If we were trying for session-id reuse, make a new
841		 * SSL_SESSION so we don't stuff up other people */
842		s->hit=0;
843		if (s->session->session_id_length > 0)
844			{
845			if (!ssl_get_new_session(s,0))
846				{
847				al=SSL_AD_INTERNAL_ERROR;
848				goto f_err;
849				}
850			}
851		s->session->session_id_length=j;
852		memcpy(s->session->session_id,p,j); /* j could be 0 */
853		}
854	p+=j;
855	c=ssl_get_cipher_by_char(s,p);
856	if (c == NULL)
857		{
858		/* unknown cipher */
859		al=SSL_AD_ILLEGAL_PARAMETER;
860		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED);
861		goto f_err;
862		}
863	p+=ssl_put_cipher_by_char(s,NULL,NULL);
864
865	sk=ssl_get_ciphers_by_id(s);
866	i=sk_SSL_CIPHER_find(sk,c);
867	if (i < 0)
868		{
869		/* we did not say we would use this cipher */
870		al=SSL_AD_ILLEGAL_PARAMETER;
871		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
872		goto f_err;
873		}
874
875	/* Depending on the session caching (internal/external), the cipher
876	   and/or cipher_id values may not be set. Make sure that
877	   cipher_id is set and use it for comparison. */
878	if (s->session->cipher)
879		s->session->cipher_id = s->session->cipher->id;
880	if (s->hit && (s->session->cipher_id != c->id))
881		{
882/* Workaround is now obsolete */
883#if 0
884		if (!(s->options &
885			SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
886#endif
887			{
888			al=SSL_AD_ILLEGAL_PARAMETER;
889			SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
890			goto f_err;
891			}
892		}
893	s->s3->tmp.new_cipher=c;
894	if (!ssl3_digest_cached_records(s))
895		{
896		al = SSL_AD_INTERNAL_ERROR;
897		goto f_err;
898		}
899
900	/* lets get the compression algorithm */
901	/* COMPRESSION */
902#ifdef OPENSSL_NO_COMP
903	if (*(p++) != 0)
904		{
905		al=SSL_AD_ILLEGAL_PARAMETER;
906		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
907		goto f_err;
908		}
909	/* If compression is disabled we'd better not try to resume a session
910	 * using compression.
911	 */
912	if (s->session->compress_meth != 0)
913		{
914		al=SSL_AD_INTERNAL_ERROR;
915		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
916		goto f_err;
917		}
918#else
919	j= *(p++);
920	if (s->hit && j != s->session->compress_meth)
921		{
922		al=SSL_AD_ILLEGAL_PARAMETER;
923		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
924		goto f_err;
925		}
926	if (j == 0)
927		comp=NULL;
928	else if (s->options & SSL_OP_NO_COMPRESSION)
929		{
930		al=SSL_AD_ILLEGAL_PARAMETER;
931		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED);
932		goto f_err;
933		}
934	else
935		comp=ssl3_comp_find(s->ctx->comp_methods,j);
936
937	if ((j != 0) && (comp == NULL))
938		{
939		al=SSL_AD_ILLEGAL_PARAMETER;
940		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
941		goto f_err;
942		}
943	else
944		{
945		s->s3->tmp.new_compression=comp;
946		}
947#endif
948
949#ifndef OPENSSL_NO_TLSEXT
950	/* TLS extensions*/
951	if (s->version >= SSL3_VERSION)
952		{
953		if (!ssl_parse_serverhello_tlsext(s,&p,d,n, &al))
954			{
955			/* 'al' set by ssl_parse_serverhello_tlsext */
956			SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT);
957			goto f_err;
958			}
959		if (ssl_check_serverhello_tlsext(s) <= 0)
960			{
961			SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
962				goto err;
963			}
964		}
965#endif
966
967	if (p != (d+n))
968		{
969		/* wrong packet length */
970		al=SSL_AD_DECODE_ERROR;
971		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH);
972		goto f_err;
973		}
974
975	return(1);
976f_err:
977	ssl3_send_alert(s,SSL3_AL_FATAL,al);
978#ifndef OPENSSL_NO_TLSEXT
979err:
980#endif
981	return(-1);
982	}
983
984int ssl3_get_server_certificate(SSL *s)
985	{
986	int al,i,ok,ret= -1;
987	unsigned long n,nc,llen,l;
988	X509 *x=NULL;
989	const unsigned char *q,*p;
990	unsigned char *d;
991	STACK_OF(X509) *sk=NULL;
992	SESS_CERT *sc;
993	EVP_PKEY *pkey=NULL;
994	int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */
995
996	n=s->method->ssl_get_message(s,
997		SSL3_ST_CR_CERT_A,
998		SSL3_ST_CR_CERT_B,
999		-1,
1000		s->max_cert_list,
1001		&ok);
1002
1003	if (!ok) return((int)n);
1004
1005	if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) ||
1006		((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) &&
1007		(s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)))
1008		{
1009		s->s3->tmp.reuse_message=1;
1010		return(1);
1011		}
1012
1013	if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
1014		{
1015		al=SSL_AD_UNEXPECTED_MESSAGE;
1016		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE);
1017		goto f_err;
1018		}
1019	p=d=(unsigned char *)s->init_msg;
1020
1021	if ((sk=sk_X509_new_null()) == NULL)
1022		{
1023		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1024		goto err;
1025		}
1026
1027	n2l3(p,llen);
1028	if (llen+3 != n)
1029		{
1030		al=SSL_AD_DECODE_ERROR;
1031		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
1032		goto f_err;
1033		}
1034	for (nc=0; nc<llen; )
1035		{
1036		n2l3(p,l);
1037		if ((l+nc+3) > llen)
1038			{
1039			al=SSL_AD_DECODE_ERROR;
1040			SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1041			goto f_err;
1042			}
1043
1044		q=p;
1045		x=d2i_X509(NULL,&q,l);
1046		if (x == NULL)
1047			{
1048			al=SSL_AD_BAD_CERTIFICATE;
1049			SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB);
1050			goto f_err;
1051			}
1052		if (q != (p+l))
1053			{
1054			al=SSL_AD_DECODE_ERROR;
1055			SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1056			goto f_err;
1057			}
1058		if (!sk_X509_push(sk,x))
1059			{
1060			SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1061			goto err;
1062			}
1063		x=NULL;
1064		nc+=l+3;
1065		p=q;
1066		}
1067
1068	i=ssl_verify_cert_chain(s,sk);
1069	if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)
1070#ifndef OPENSSL_NO_KRB5
1071	    && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1072		 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1073#endif /* OPENSSL_NO_KRB5 */
1074		)
1075		{
1076		al=ssl_verify_alarm_type(s->verify_result);
1077		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
1078		goto f_err;
1079		}
1080	ERR_clear_error(); /* but we keep s->verify_result */
1081
1082	sc=ssl_sess_cert_new();
1083	if (sc == NULL) goto err;
1084
1085	if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
1086	s->session->sess_cert=sc;
1087
1088	sc->cert_chain=sk;
1089	/* Inconsistency alert: cert_chain does include the peer's
1090	 * certificate, which we don't include in s3_srvr.c */
1091	x=sk_X509_value(sk,0);
1092	sk=NULL;
1093 	/* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1094
1095	pkey=X509_get_pubkey(x);
1096
1097	/* VRS: allow null cert if auth == KRB5 */
1098	need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1099	            (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1100	            ? 0 : 1;
1101
1102#ifdef KSSL_DEBUG
1103	printf("pkey,x = %p, %p\n", pkey,x);
1104	printf("ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey));
1105	printf("cipher, alg, nc = %s, %lx, %lx, %d\n", s->s3->tmp.new_cipher->name,
1106		s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, need_cert);
1107#endif    /* KSSL_DEBUG */
1108
1109	if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey)))
1110		{
1111		x=NULL;
1112		al=SSL3_AL_FATAL;
1113		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1114			SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1115		goto f_err;
1116		}
1117
1118	i=ssl_cert_type(x,pkey);
1119	if (need_cert && i < 0)
1120		{
1121		x=NULL;
1122		al=SSL3_AL_FATAL;
1123		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1124			SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1125		goto f_err;
1126		}
1127
1128	if (need_cert)
1129		{
1130		sc->peer_cert_type=i;
1131		CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
1132		/* Why would the following ever happen?
1133		 * We just created sc a couple of lines ago. */
1134		if (sc->peer_pkeys[i].x509 != NULL)
1135			X509_free(sc->peer_pkeys[i].x509);
1136		sc->peer_pkeys[i].x509=x;
1137		sc->peer_key= &(sc->peer_pkeys[i]);
1138
1139		if (s->session->peer != NULL)
1140			X509_free(s->session->peer);
1141		CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
1142		s->session->peer=x;
1143		}
1144	else
1145		{
1146		sc->peer_cert_type=i;
1147		sc->peer_key= NULL;
1148
1149		if (s->session->peer != NULL)
1150			X509_free(s->session->peer);
1151		s->session->peer=NULL;
1152		}
1153	s->session->verify_result = s->verify_result;
1154
1155	x=NULL;
1156	ret=1;
1157
1158	if (0)
1159		{
1160f_err:
1161		ssl3_send_alert(s,SSL3_AL_FATAL,al);
1162		}
1163err:
1164	EVP_PKEY_free(pkey);
1165	X509_free(x);
1166	sk_X509_pop_free(sk,X509_free);
1167	return(ret);
1168	}
1169
1170int ssl3_get_key_exchange(SSL *s)
1171	{
1172#ifndef OPENSSL_NO_RSA
1173	unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];
1174#endif
1175	EVP_MD_CTX md_ctx;
1176	unsigned char *param,*p;
1177	int al,j,ok;
1178	long i,param_len,n,alg_k,alg_a;
1179	EVP_PKEY *pkey=NULL;
1180#ifndef OPENSSL_NO_RSA
1181	RSA *rsa=NULL;
1182#endif
1183#ifndef OPENSSL_NO_DH
1184	DH *dh=NULL;
1185#endif
1186#ifndef OPENSSL_NO_ECDH
1187	EC_KEY *ecdh = NULL;
1188	BN_CTX *bn_ctx = NULL;
1189	EC_POINT *srvr_ecpoint = NULL;
1190	int curve_nid = 0;
1191	int encoded_pt_len = 0;
1192#endif
1193
1194	EVP_MD_CTX_init(&md_ctx);
1195
1196	/* use same message size as in ssl3_get_certificate_request()
1197	 * as ServerKeyExchange message may be skipped */
1198	n=s->method->ssl_get_message(s,
1199		SSL3_ST_CR_KEY_EXCH_A,
1200		SSL3_ST_CR_KEY_EXCH_B,
1201		-1,
1202		s->max_cert_list,
1203		&ok);
1204	if (!ok) return((int)n);
1205
1206	alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1207
1208	if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
1209		{
1210		/*
1211		 * Can't skip server key exchange if this is an ephemeral
1212		 * ciphersuite.
1213		 */
1214		if (alg_k & (SSL_kEDH|SSL_kEECDH))
1215			{
1216			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1217			al = SSL_AD_UNEXPECTED_MESSAGE;
1218			goto f_err;
1219			}
1220#ifndef OPENSSL_NO_PSK
1221		/* In plain PSK ciphersuite, ServerKeyExchange can be
1222		   omitted if no identity hint is sent. Set
1223		   session->sess_cert anyway to avoid problems
1224		   later.*/
1225		if (alg_k & SSL_kPSK)
1226			{
1227			s->session->sess_cert=ssl_sess_cert_new();
1228			if (s->ctx->psk_identity_hint)
1229				OPENSSL_free(s->ctx->psk_identity_hint);
1230			s->ctx->psk_identity_hint = NULL;
1231			}
1232#endif
1233		s->s3->tmp.reuse_message=1;
1234		return(1);
1235		}
1236
1237	param=p=(unsigned char *)s->init_msg;
1238	if (s->session->sess_cert != NULL)
1239		{
1240#ifndef OPENSSL_NO_RSA
1241		if (s->session->sess_cert->peer_rsa_tmp != NULL)
1242			{
1243			RSA_free(s->session->sess_cert->peer_rsa_tmp);
1244			s->session->sess_cert->peer_rsa_tmp=NULL;
1245			}
1246#endif
1247#ifndef OPENSSL_NO_DH
1248		if (s->session->sess_cert->peer_dh_tmp)
1249			{
1250			DH_free(s->session->sess_cert->peer_dh_tmp);
1251			s->session->sess_cert->peer_dh_tmp=NULL;
1252			}
1253#endif
1254#ifndef OPENSSL_NO_ECDH
1255		if (s->session->sess_cert->peer_ecdh_tmp)
1256			{
1257			EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
1258			s->session->sess_cert->peer_ecdh_tmp=NULL;
1259			}
1260#endif
1261		}
1262	else
1263		{
1264		s->session->sess_cert=ssl_sess_cert_new();
1265		}
1266
1267	/* Total length of the parameters including the length prefix */
1268	param_len=0;
1269
1270	alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1271
1272	al=SSL_AD_DECODE_ERROR;
1273
1274#ifndef OPENSSL_NO_PSK
1275	if (alg_k & SSL_kPSK)
1276		{
1277		char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1];
1278
1279		param_len = 2;
1280		if (param_len > n)
1281			{
1282			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1283				SSL_R_LENGTH_TOO_SHORT);
1284			goto f_err;
1285			}
1286		n2s(p,i);
1287
1288		/* Store PSK identity hint for later use, hint is used
1289		 * in ssl3_send_client_key_exchange.  Assume that the
1290		 * maximum length of a PSK identity hint can be as
1291		 * long as the maximum length of a PSK identity. */
1292		if (i > PSK_MAX_IDENTITY_LEN)
1293			{
1294			al=SSL_AD_HANDSHAKE_FAILURE;
1295			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1296				SSL_R_DATA_LENGTH_TOO_LONG);
1297			goto f_err;
1298			}
1299		if (i > n - param_len)
1300			{
1301			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1302				SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
1303			goto f_err;
1304			}
1305		param_len += i;
1306
1307		/* If received PSK identity hint contains NULL
1308		 * characters, the hint is truncated from the first
1309		 * NULL. p may not be ending with NULL, so create a
1310		 * NULL-terminated string. */
1311		memcpy(tmp_id_hint, p, i);
1312		memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
1313		if (s->ctx->psk_identity_hint != NULL)
1314			OPENSSL_free(s->ctx->psk_identity_hint);
1315		s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint);
1316		if (s->ctx->psk_identity_hint == NULL)
1317			{
1318			al=SSL_AD_HANDSHAKE_FAILURE;
1319			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1320			goto f_err;
1321			}
1322
1323		p+=i;
1324		n-=param_len;
1325		}
1326	else
1327#endif /* !OPENSSL_NO_PSK */
1328#ifndef OPENSSL_NO_RSA
1329	if (alg_k & SSL_kRSA)
1330		{
1331		/* Temporary RSA keys only allowed in export ciphersuites */
1332		if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher))
1333			{
1334			al=SSL_AD_UNEXPECTED_MESSAGE;
1335			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
1336			goto f_err;
1337			}
1338		if ((rsa=RSA_new()) == NULL)
1339			{
1340			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1341			goto err;
1342			}
1343
1344		param_len = 2;
1345		if (param_len > n)
1346			{
1347			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1348				SSL_R_LENGTH_TOO_SHORT);
1349			goto f_err;
1350			}
1351		n2s(p,i);
1352
1353		if (i > n - param_len)
1354			{
1355			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
1356			goto f_err;
1357			}
1358		param_len += i;
1359
1360		if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
1361			{
1362			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1363			goto err;
1364			}
1365		p+=i;
1366
1367		if (2 > n - param_len)
1368			{
1369			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1370				SSL_R_LENGTH_TOO_SHORT);
1371			goto f_err;
1372			}
1373		param_len += 2;
1374
1375		n2s(p,i);
1376
1377		if (i > n - param_len)
1378			{
1379			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
1380			goto f_err;
1381			}
1382		param_len += i;
1383
1384		if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
1385			{
1386			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1387			goto err;
1388			}
1389		p+=i;
1390		n-=param_len;
1391
1392		/* this should be because we are using an export cipher */
1393		if (alg_a & SSL_aRSA)
1394			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1395		else
1396			{
1397			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1398			goto err;
1399			}
1400		s->session->sess_cert->peer_rsa_tmp=rsa;
1401		rsa=NULL;
1402		}
1403#else /* OPENSSL_NO_RSA */
1404	if (0)
1405		;
1406#endif
1407#ifndef OPENSSL_NO_DH
1408	else if (alg_k & SSL_kEDH)
1409		{
1410		if ((dh=DH_new()) == NULL)
1411			{
1412			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);
1413			goto err;
1414			}
1415
1416		param_len = 2;
1417		if (param_len > n)
1418			{
1419			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1420				SSL_R_LENGTH_TOO_SHORT);
1421			goto f_err;
1422			}
1423		n2s(p,i);
1424
1425		if (i > n - param_len)
1426			{
1427			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);
1428			goto f_err;
1429			}
1430		param_len += i;
1431
1432		if (!(dh->p=BN_bin2bn(p,i,NULL)))
1433			{
1434			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1435			goto err;
1436			}
1437		p+=i;
1438
1439		if (2 > n - param_len)
1440			{
1441			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1442				SSL_R_LENGTH_TOO_SHORT);
1443			goto f_err;
1444			}
1445		param_len += 2;
1446
1447		n2s(p,i);
1448
1449		if (i > n - param_len)
1450			{
1451			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);
1452			goto f_err;
1453			}
1454		param_len += i;
1455
1456		if (!(dh->g=BN_bin2bn(p,i,NULL)))
1457			{
1458			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1459			goto err;
1460			}
1461		p+=i;
1462
1463		if (2 > n - param_len)
1464			{
1465			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1466				SSL_R_LENGTH_TOO_SHORT);
1467			goto f_err;
1468			}
1469		param_len += 2;
1470
1471		n2s(p,i);
1472
1473		if (i > n - param_len)
1474			{
1475			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);
1476			goto f_err;
1477			}
1478		param_len += i;
1479
1480		if (!(dh->pub_key=BN_bin2bn(p,i,NULL)))
1481			{
1482			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1483			goto err;
1484			}
1485		p+=i;
1486		n-=param_len;
1487
1488#ifndef OPENSSL_NO_RSA
1489		if (alg_a & SSL_aRSA)
1490			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1491#else
1492		if (0)
1493			;
1494#endif
1495#ifndef OPENSSL_NO_DSA
1496		else if (alg_a & SSL_aDSS)
1497			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1498#endif
1499		/* else anonymous DH, so no certificate or pkey. */
1500
1501		s->session->sess_cert->peer_dh_tmp=dh;
1502		dh=NULL;
1503		}
1504	else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd))
1505		{
1506		al=SSL_AD_ILLEGAL_PARAMETER;
1507		SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1508		goto f_err;
1509		}
1510#endif /* !OPENSSL_NO_DH */
1511
1512#ifndef OPENSSL_NO_ECDH
1513	else if (alg_k & SSL_kEECDH)
1514		{
1515		EC_GROUP *ngroup;
1516		const EC_GROUP *group;
1517
1518		if ((ecdh=EC_KEY_new()) == NULL)
1519			{
1520			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1521			goto err;
1522			}
1523
1524		/* Extract elliptic curve parameters and the
1525		 * server's ephemeral ECDH public key.
1526		 * Keep accumulating lengths of various components in
1527		 * param_len and make sure it never exceeds n.
1528		 */
1529
1530		/* XXX: For now we only support named (not generic) curves
1531		 * and the ECParameters in this case is just three bytes. We
1532		 * also need one byte for the length of the encoded point
1533		 */
1534		param_len=4;
1535		if (param_len > n)
1536			{
1537			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1538				SSL_R_LENGTH_TOO_SHORT);
1539			goto f_err;
1540			}
1541
1542		if ((*p != NAMED_CURVE_TYPE) ||
1543		    ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0))
1544			{
1545			al=SSL_AD_INTERNAL_ERROR;
1546			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1547			goto f_err;
1548			}
1549
1550		ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1551		if (ngroup == NULL)
1552			{
1553			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1554			goto err;
1555			}
1556		if (EC_KEY_set_group(ecdh, ngroup) == 0)
1557			{
1558			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1559			goto err;
1560			}
1561		EC_GROUP_free(ngroup);
1562
1563		group = EC_KEY_get0_group(ecdh);
1564
1565		if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1566		    (EC_GROUP_get_degree(group) > 163))
1567			{
1568			al=SSL_AD_EXPORT_RESTRICTION;
1569			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1570			goto f_err;
1571			}
1572
1573		p+=3;
1574
1575		/* Next, get the encoded ECPoint */
1576		if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1577		    ((bn_ctx = BN_CTX_new()) == NULL))
1578			{
1579			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1580			goto err;
1581			}
1582
1583		encoded_pt_len = *p;  /* length of encoded point */
1584		p+=1;
1585
1586		if ((encoded_pt_len > n - param_len) ||
1587		    (EC_POINT_oct2point(group, srvr_ecpoint,
1588			p, encoded_pt_len, bn_ctx) == 0))
1589			{
1590			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT);
1591			goto f_err;
1592			}
1593		param_len += encoded_pt_len;
1594
1595		n-=param_len;
1596		p+=encoded_pt_len;
1597
1598		/* The ECC/TLS specification does not mention
1599		 * the use of DSA to sign ECParameters in the server
1600		 * key exchange message. We do support RSA and ECDSA.
1601		 */
1602		if (0) ;
1603#ifndef OPENSSL_NO_RSA
1604		else if (alg_a & SSL_aRSA)
1605			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1606#endif
1607#ifndef OPENSSL_NO_ECDSA
1608		else if (alg_a & SSL_aECDSA)
1609			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1610#endif
1611		/* else anonymous ECDH, so no certificate or pkey. */
1612		EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1613		s->session->sess_cert->peer_ecdh_tmp=ecdh;
1614		ecdh=NULL;
1615		BN_CTX_free(bn_ctx);
1616		bn_ctx = NULL;
1617		EC_POINT_free(srvr_ecpoint);
1618		srvr_ecpoint = NULL;
1619		}
1620	else if (alg_k)
1621		{
1622		al=SSL_AD_UNEXPECTED_MESSAGE;
1623		SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
1624		goto f_err;
1625		}
1626#endif /* !OPENSSL_NO_ECDH */
1627
1628
1629	/* p points to the next byte, there are 'n' bytes left */
1630
1631	/* if it was signed, check the signature */
1632	if (pkey != NULL)
1633		{
1634		n2s(p,i);
1635		n-=2;
1636		j=EVP_PKEY_size(pkey);
1637
1638		/* Check signature length. If n is 0 then signature is empty */
1639		if ((i != n) || (n > j) || (n <= 0))
1640			{
1641			/* wrong packet length */
1642			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);
1643			goto f_err;
1644			}
1645
1646#ifndef OPENSSL_NO_RSA
1647		if (pkey->type == EVP_PKEY_RSA)
1648			{
1649			int num;
1650			unsigned int size;
1651
1652			j=0;
1653			q=md_buf;
1654			for (num=2; num > 0; num--)
1655				{
1656				EVP_DigestInit_ex(&md_ctx,(num == 2)
1657					?s->ctx->md5:s->ctx->sha1, NULL);
1658				EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1659				EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1660				EVP_DigestUpdate(&md_ctx,param,param_len);
1661				EVP_DigestFinal_ex(&md_ctx,q,&size);
1662				q+=size;
1663				j+=size;
1664				}
1665			i=RSA_verify(NID_md5_sha1, md_buf, j, p, n,
1666								pkey->pkey.rsa);
1667			if (i < 0)
1668				{
1669				al=SSL_AD_DECRYPT_ERROR;
1670				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
1671				goto f_err;
1672				}
1673			if (i == 0)
1674				{
1675				/* bad signature */
1676				al=SSL_AD_DECRYPT_ERROR;
1677				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1678				goto f_err;
1679				}
1680			}
1681		else
1682#endif
1683#ifndef OPENSSL_NO_DSA
1684			if (pkey->type == EVP_PKEY_DSA)
1685			{
1686			/* lets do DSS */
1687			EVP_VerifyInit_ex(&md_ctx,EVP_dss1(), NULL);
1688			EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1689			EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1690			EVP_VerifyUpdate(&md_ctx,param,param_len);
1691			if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0)
1692				{
1693				/* bad signature */
1694				al=SSL_AD_DECRYPT_ERROR;
1695				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1696				goto f_err;
1697				}
1698			}
1699		else
1700#endif
1701#ifndef OPENSSL_NO_ECDSA
1702			if (pkey->type == EVP_PKEY_EC)
1703			{
1704			/* let's do ECDSA */
1705			EVP_VerifyInit_ex(&md_ctx,EVP_ecdsa(), NULL);
1706			EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1707			EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1708			EVP_VerifyUpdate(&md_ctx,param,param_len);
1709			if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0)
1710				{
1711				/* bad signature */
1712				al=SSL_AD_DECRYPT_ERROR;
1713				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1714				goto f_err;
1715				}
1716			}
1717		else
1718#endif
1719			{
1720			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1721			goto err;
1722			}
1723		}
1724	else
1725		{
1726		if (!(alg_a & SSL_aNULL) && !(alg_k & SSL_kPSK))
1727			/* aNULL or kPSK do not need public keys */
1728			{
1729			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1730			goto err;
1731			}
1732		/* still data left over */
1733		if (n != 0)
1734			{
1735			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
1736			goto f_err;
1737			}
1738		}
1739	EVP_PKEY_free(pkey);
1740	EVP_MD_CTX_cleanup(&md_ctx);
1741	return(1);
1742f_err:
1743	ssl3_send_alert(s,SSL3_AL_FATAL,al);
1744err:
1745	EVP_PKEY_free(pkey);
1746#ifndef OPENSSL_NO_RSA
1747	if (rsa != NULL)
1748		RSA_free(rsa);
1749#endif
1750#ifndef OPENSSL_NO_DH
1751	if (dh != NULL)
1752		DH_free(dh);
1753#endif
1754#ifndef OPENSSL_NO_ECDH
1755	BN_CTX_free(bn_ctx);
1756	EC_POINT_free(srvr_ecpoint);
1757	if (ecdh != NULL)
1758		EC_KEY_free(ecdh);
1759#endif
1760	EVP_MD_CTX_cleanup(&md_ctx);
1761	return(-1);
1762	}
1763
1764int ssl3_get_certificate_request(SSL *s)
1765	{
1766	int ok,ret=0;
1767	unsigned long n,nc,l;
1768	unsigned int llen,ctype_num,i;
1769	X509_NAME *xn=NULL;
1770	const unsigned char *p,*q;
1771	unsigned char *d;
1772	STACK_OF(X509_NAME) *ca_sk=NULL;
1773
1774	n=s->method->ssl_get_message(s,
1775		SSL3_ST_CR_CERT_REQ_A,
1776		SSL3_ST_CR_CERT_REQ_B,
1777		-1,
1778		s->max_cert_list,
1779		&ok);
1780
1781	if (!ok) return((int)n);
1782
1783	s->s3->tmp.cert_req=0;
1784
1785	if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
1786		{
1787		s->s3->tmp.reuse_message=1;
1788		return(1);
1789		}
1790
1791	if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
1792		{
1793		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1794		SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE);
1795		goto err;
1796		}
1797
1798	/* TLS does not like anon-DH with client cert */
1799	if (s->version > SSL3_VERSION)
1800		{
1801		if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
1802			{
1803			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1804			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1805			goto err;
1806			}
1807		}
1808
1809	p=d=(unsigned char *)s->init_msg;
1810
1811	if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL)
1812		{
1813		SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1814		goto err;
1815		}
1816
1817	/* get the certificate types */
1818	ctype_num= *(p++);
1819	if (ctype_num > SSL3_CT_NUMBER)
1820		ctype_num=SSL3_CT_NUMBER;
1821	for (i=0; i<ctype_num; i++)
1822		s->s3->tmp.ctype[i]= p[i];
1823	p+=ctype_num;
1824
1825	/* get the CA RDNs */
1826	n2s(p,llen);
1827#if 0
1828{
1829FILE *out;
1830out=fopen("/tmp/vsign.der","w");
1831fwrite(p,1,llen,out);
1832fclose(out);
1833}
1834#endif
1835
1836	if ((llen+ctype_num+2+1) != n)
1837		{
1838		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1839		SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH);
1840		goto err;
1841		}
1842
1843	for (nc=0; nc<llen; )
1844		{
1845		n2s(p,l);
1846		if ((l+nc+2) > llen)
1847			{
1848			if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
1849				goto cont; /* netscape bugs */
1850			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1851			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG);
1852			goto err;
1853			}
1854
1855		q=p;
1856
1857		if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL)
1858			{
1859			/* If netscape tolerance is on, ignore errors */
1860			if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
1861				goto cont;
1862			else
1863				{
1864				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1865				SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB);
1866				goto err;
1867				}
1868			}
1869
1870		if (q != (p+l))
1871			{
1872			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1873			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH);
1874			goto err;
1875			}
1876		if (!sk_X509_NAME_push(ca_sk,xn))
1877			{
1878			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1879			goto err;
1880			}
1881
1882		p+=l;
1883		nc+=l+2;
1884		}
1885
1886	if (0)
1887		{
1888cont:
1889		ERR_clear_error();
1890		}
1891
1892	/* we should setup a certificate to return.... */
1893	s->s3->tmp.cert_req=1;
1894	s->s3->tmp.ctype_num=ctype_num;
1895	if (s->s3->tmp.ca_names != NULL)
1896		sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
1897	s->s3->tmp.ca_names=ca_sk;
1898	ca_sk=NULL;
1899
1900	ret=1;
1901err:
1902	if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
1903	return(ret);
1904	}
1905
1906static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1907	{
1908	return(X509_NAME_cmp(*a,*b));
1909	}
1910#ifndef OPENSSL_NO_TLSEXT
1911int ssl3_get_new_session_ticket(SSL *s)
1912	{
1913	int ok,al,ret=0, ticklen;
1914	long n;
1915	const unsigned char *p;
1916	unsigned char *d;
1917
1918	n=s->method->ssl_get_message(s,
1919		SSL3_ST_CR_SESSION_TICKET_A,
1920		SSL3_ST_CR_SESSION_TICKET_B,
1921		-1,
1922		16384,
1923		&ok);
1924
1925	if (!ok)
1926		return((int)n);
1927
1928	if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
1929		{
1930		s->s3->tmp.reuse_message=1;
1931		return(1);
1932		}
1933	if (s->s3->tmp.message_type != SSL3_MT_NEWSESSION_TICKET)
1934		{
1935		al=SSL_AD_UNEXPECTED_MESSAGE;
1936		SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_BAD_MESSAGE_TYPE);
1937		goto f_err;
1938		}
1939	if (n < 6)
1940		{
1941		/* need at least ticket_lifetime_hint + ticket length */
1942		al = SSL_AD_DECODE_ERROR;
1943		SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
1944		goto f_err;
1945		}
1946
1947	p=d=(unsigned char *)s->init_msg;
1948	n2l(p, s->session->tlsext_tick_lifetime_hint);
1949	n2s(p, ticklen);
1950	/* ticket_lifetime_hint + ticket_length + ticket */
1951	if (ticklen + 6 != n)
1952		{
1953		al = SSL_AD_DECODE_ERROR;
1954		SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
1955		goto f_err;
1956		}
1957	if (s->session->tlsext_tick)
1958		{
1959		OPENSSL_free(s->session->tlsext_tick);
1960		s->session->tlsext_ticklen = 0;
1961		}
1962	s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1963	if (!s->session->tlsext_tick)
1964		{
1965		SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,ERR_R_MALLOC_FAILURE);
1966		goto err;
1967		}
1968	memcpy(s->session->tlsext_tick, p, ticklen);
1969	s->session->tlsext_ticklen = ticklen;
1970	/* There are two ways to detect a resumed ticket sesion.
1971	 * One is to set an appropriate session ID and then the server
1972	 * must return a match in ServerHello. This allows the normal
1973	 * client session ID matching to work and we know much
1974	 * earlier that the ticket has been accepted.
1975	 *
1976	 * The other way is to set zero length session ID when the
1977	 * ticket is presented and rely on the handshake to determine
1978	 * session resumption.
1979	 *
1980	 * We choose the former approach because this fits in with
1981	 * assumptions elsewhere in OpenSSL. The session ID is set
1982	 * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
1983	 * ticket.
1984	 */
1985	EVP_Digest(p, ticklen,
1986			s->session->session_id, &s->session->session_id_length,
1987#ifndef OPENSSL_NO_SHA256
1988							EVP_sha256(), NULL);
1989#else
1990							EVP_sha1(), NULL);
1991#endif
1992	ret=1;
1993	return(ret);
1994f_err:
1995	ssl3_send_alert(s,SSL3_AL_FATAL,al);
1996err:
1997	return(-1);
1998	}
1999
2000int ssl3_get_cert_status(SSL *s)
2001	{
2002	int ok, al;
2003	unsigned long resplen,n;
2004	const unsigned char *p;
2005
2006	n=s->method->ssl_get_message(s,
2007		SSL3_ST_CR_CERT_STATUS_A,
2008		SSL3_ST_CR_CERT_STATUS_B,
2009		SSL3_MT_CERTIFICATE_STATUS,
2010		16384,
2011		&ok);
2012
2013	if (!ok) return((int)n);
2014	if (n < 4)
2015		{
2016		/* need at least status type + length */
2017		al = SSL_AD_DECODE_ERROR;
2018		SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
2019		goto f_err;
2020		}
2021	p = (unsigned char *)s->init_msg;
2022	if (*p++ != TLSEXT_STATUSTYPE_ocsp)
2023		{
2024		al = SSL_AD_DECODE_ERROR;
2025		SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_UNSUPPORTED_STATUS_TYPE);
2026		goto f_err;
2027		}
2028	n2l3(p, resplen);
2029	if (resplen + 4 != n)
2030		{
2031		al = SSL_AD_DECODE_ERROR;
2032		SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
2033		goto f_err;
2034		}
2035	if (s->tlsext_ocsp_resp)
2036		OPENSSL_free(s->tlsext_ocsp_resp);
2037	s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
2038	if (!s->tlsext_ocsp_resp)
2039		{
2040		al = SSL_AD_INTERNAL_ERROR;
2041		SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
2042		goto f_err;
2043		}
2044	s->tlsext_ocsp_resplen = resplen;
2045	if (s->ctx->tlsext_status_cb)
2046		{
2047		int ret;
2048		ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2049		if (ret == 0)
2050			{
2051			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2052			SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_INVALID_STATUS_RESPONSE);
2053			goto f_err;
2054			}
2055		if (ret < 0)
2056			{
2057			al = SSL_AD_INTERNAL_ERROR;
2058			SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
2059			goto f_err;
2060			}
2061		}
2062	return 1;
2063f_err:
2064	ssl3_send_alert(s,SSL3_AL_FATAL,al);
2065	return(-1);
2066	}
2067#endif
2068
2069int ssl3_get_server_done(SSL *s)
2070	{
2071	int ok,ret=0;
2072	long n;
2073
2074	n=s->method->ssl_get_message(s,
2075		SSL3_ST_CR_SRVR_DONE_A,
2076		SSL3_ST_CR_SRVR_DONE_B,
2077		SSL3_MT_SERVER_DONE,
2078		30, /* should be very small, like 0 :-) */
2079		&ok);
2080
2081	if (!ok) return((int)n);
2082	if (n > 0)
2083		{
2084		/* should contain no data */
2085		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2086		SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH);
2087		return -1;
2088		}
2089	ret=1;
2090	return(ret);
2091	}
2092
2093
2094int ssl3_send_client_key_exchange(SSL *s)
2095	{
2096	unsigned char *p,*d;
2097	int n;
2098	unsigned long alg_k;
2099#ifndef OPENSSL_NO_RSA
2100	unsigned char *q;
2101	EVP_PKEY *pkey=NULL;
2102#endif
2103#ifndef OPENSSL_NO_KRB5
2104	KSSL_ERR kssl_err;
2105#endif /* OPENSSL_NO_KRB5 */
2106#ifndef OPENSSL_NO_ECDH
2107	EC_KEY *clnt_ecdh = NULL;
2108	const EC_POINT *srvr_ecpoint = NULL;
2109	EVP_PKEY *srvr_pub_pkey = NULL;
2110	unsigned char *encodedPoint = NULL;
2111	int encoded_pt_len = 0;
2112	BN_CTX * bn_ctx = NULL;
2113#endif
2114
2115	if (s->state == SSL3_ST_CW_KEY_EXCH_A)
2116		{
2117		d=(unsigned char *)s->init_buf->data;
2118		p= &(d[4]);
2119
2120		alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2121
2122		/* Fool emacs indentation */
2123		if (0) {}
2124#ifndef OPENSSL_NO_RSA
2125		else if (alg_k & SSL_kRSA)
2126			{
2127			RSA *rsa;
2128			unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2129
2130			if (s->session->sess_cert == NULL)
2131				{
2132				/* We should always have a server certificate with SSL_kRSA. */
2133				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2134				goto err;
2135				}
2136
2137			if (s->session->sess_cert->peer_rsa_tmp != NULL)
2138				rsa=s->session->sess_cert->peer_rsa_tmp;
2139			else
2140				{
2141				pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
2142				if ((pkey == NULL) ||
2143					(pkey->type != EVP_PKEY_RSA) ||
2144					(pkey->pkey.rsa == NULL))
2145					{
2146					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2147					goto err;
2148					}
2149				rsa=pkey->pkey.rsa;
2150				EVP_PKEY_free(pkey);
2151				}
2152
2153			tmp_buf[0]=s->client_version>>8;
2154			tmp_buf[1]=s->client_version&0xff;
2155			if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
2156					goto err;
2157
2158			s->session->master_key_length=sizeof tmp_buf;
2159
2160			q=p;
2161			/* Fix buf for TLS and beyond */
2162			if (s->version > SSL3_VERSION)
2163				p+=2;
2164			n=RSA_public_encrypt(sizeof tmp_buf,
2165				tmp_buf,p,rsa,RSA_PKCS1_PADDING);
2166#ifdef PKCS1_CHECK
2167			if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
2168			if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
2169#endif
2170			if (n <= 0)
2171				{
2172				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
2173				goto err;
2174				}
2175
2176			/* Fix buf for TLS and beyond */
2177			if (s->version > SSL3_VERSION)
2178				{
2179				s2n(n,q);
2180				n+=2;
2181				}
2182
2183			s->session->master_key_length=
2184				s->method->ssl3_enc->generate_master_secret(s,
2185					s->session->master_key,
2186					tmp_buf,sizeof tmp_buf);
2187			OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
2188			}
2189#endif
2190#ifndef OPENSSL_NO_KRB5
2191		else if (alg_k & SSL_kKRB5)
2192			{
2193			krb5_error_code	krb5rc;
2194			KSSL_CTX	*kssl_ctx = s->kssl_ctx;
2195			/*  krb5_data	krb5_ap_req;  */
2196			krb5_data	*enc_ticket;
2197			krb5_data	authenticator, *authp = NULL;
2198			EVP_CIPHER_CTX	ciph_ctx;
2199			const EVP_CIPHER *enc = NULL;
2200			unsigned char	iv[EVP_MAX_IV_LENGTH];
2201			unsigned char	tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2202			unsigned char	epms[SSL_MAX_MASTER_KEY_LENGTH
2203						+ EVP_MAX_IV_LENGTH];
2204			int 		padl, outl = sizeof(epms);
2205
2206			EVP_CIPHER_CTX_init(&ciph_ctx);
2207
2208#ifdef KSSL_DEBUG
2209			printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
2210				alg_k, SSL_kKRB5);
2211#endif	/* KSSL_DEBUG */
2212
2213			authp = NULL;
2214#ifdef KRB5SENDAUTH
2215			if (KRB5SENDAUTH)  authp = &authenticator;
2216#endif	/* KRB5SENDAUTH */
2217
2218			krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
2219				&kssl_err);
2220			enc = kssl_map_enc(kssl_ctx->enctype);
2221			if (enc == NULL)
2222			    goto err;
2223#ifdef KSSL_DEBUG
2224			{
2225			printf("kssl_cget_tkt rtn %d\n", krb5rc);
2226			if (krb5rc && kssl_err.text)
2227			  printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
2228			}
2229#endif	/* KSSL_DEBUG */
2230
2231			if (krb5rc)
2232				{
2233				ssl3_send_alert(s,SSL3_AL_FATAL,
2234						SSL_AD_HANDSHAKE_FAILURE);
2235				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2236						kssl_err.reason);
2237				goto err;
2238				}
2239
2240			/*  20010406 VRS - Earlier versions used KRB5 AP_REQ
2241			**  in place of RFC 2712 KerberosWrapper, as in:
2242			**
2243			**  Send ticket (copy to *p, set n = length)
2244			**  n = krb5_ap_req.length;
2245			**  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
2246			**  if (krb5_ap_req.data)
2247			**    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
2248			**
2249			**  Now using real RFC 2712 KerberosWrapper
2250			**  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
2251			**  Note: 2712 "opaque" types are here replaced
2252			**  with a 2-byte length followed by the value.
2253			**  Example:
2254			**  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
2255			**  Where "xx xx" = length bytes.  Shown here with
2256			**  optional authenticator omitted.
2257			*/
2258
2259			/*  KerberosWrapper.Ticket		*/
2260			s2n(enc_ticket->length,p);
2261			memcpy(p, enc_ticket->data, enc_ticket->length);
2262			p+= enc_ticket->length;
2263			n = enc_ticket->length + 2;
2264
2265			/*  KerberosWrapper.Authenticator	*/
2266			if (authp  &&  authp->length)
2267				{
2268				s2n(authp->length,p);
2269				memcpy(p, authp->data, authp->length);
2270				p+= authp->length;
2271				n+= authp->length + 2;
2272
2273				free(authp->data);
2274				authp->data = NULL;
2275				authp->length = 0;
2276				}
2277			else
2278				{
2279				s2n(0,p);/*  null authenticator length	*/
2280				n+=2;
2281				}
2282
2283			    tmp_buf[0]=s->client_version>>8;
2284			    tmp_buf[1]=s->client_version&0xff;
2285			    if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
2286				goto err;
2287
2288			/*  20010420 VRS.  Tried it this way; failed.
2289			**	EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
2290			**	EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
2291			**				kssl_ctx->length);
2292			**	EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
2293			*/
2294
2295			memset(iv, 0, sizeof iv);  /* per RFC 1510 */
2296			EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
2297				kssl_ctx->key,iv);
2298			EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
2299				sizeof tmp_buf);
2300			EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
2301			outl += padl;
2302			if (outl > (int)sizeof epms)
2303				{
2304				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2305				goto err;
2306				}
2307			EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2308
2309			/*  KerberosWrapper.EncryptedPreMasterSecret	*/
2310			s2n(outl,p);
2311			memcpy(p, epms, outl);
2312			p+=outl;
2313			n+=outl + 2;
2314
2315			s->session->master_key_length=
2316				s->method->ssl3_enc->generate_master_secret(s,
2317					s->session->master_key,
2318					tmp_buf, sizeof tmp_buf);
2319
2320			OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2321			OPENSSL_cleanse(epms, outl);
2322			}
2323#endif
2324#ifndef OPENSSL_NO_DH
2325		else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2326			{
2327			DH *dh_srvr,*dh_clnt;
2328
2329			if (s->session->sess_cert == NULL)
2330				{
2331				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2332				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
2333				goto err;
2334				}
2335
2336			if (s->session->sess_cert->peer_dh_tmp != NULL)
2337				dh_srvr=s->session->sess_cert->peer_dh_tmp;
2338			else
2339				{
2340				/* we get them from the cert */
2341				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
2342				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2343				goto err;
2344				}
2345
2346			/* generate a new random key */
2347			if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
2348				{
2349				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2350				goto err;
2351				}
2352			if (!DH_generate_key(dh_clnt))
2353				{
2354				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2355				DH_free(dh_clnt);
2356				goto err;
2357				}
2358
2359			/* use the 'p' output buffer for the DH key, but
2360			 * make sure to clear it out afterwards */
2361
2362			n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
2363
2364			if (n <= 0)
2365				{
2366				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2367				DH_free(dh_clnt);
2368				goto err;
2369				}
2370
2371			/* generate master key from the result */
2372			s->session->master_key_length=
2373				s->method->ssl3_enc->generate_master_secret(s,
2374					s->session->master_key,p,n);
2375			/* clean up */
2376			memset(p,0,n);
2377
2378			/* send off the data */
2379			n=BN_num_bytes(dh_clnt->pub_key);
2380			s2n(n,p);
2381			BN_bn2bin(dh_clnt->pub_key,p);
2382			n+=2;
2383
2384			DH_free(dh_clnt);
2385
2386			/* perhaps clean things up a bit EAY EAY EAY EAY*/
2387			}
2388#endif
2389
2390#ifndef OPENSSL_NO_ECDH
2391		else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
2392			{
2393			const EC_GROUP *srvr_group = NULL;
2394			EC_KEY *tkey;
2395			int ecdh_clnt_cert = 0;
2396			int field_size = 0;
2397
2398			if (s->session->sess_cert == NULL)
2399				{
2400				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2401				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
2402				goto err;
2403				}
2404
2405			/* Did we send out the client's
2406			 * ECDH share for use in premaster
2407			 * computation as part of client certificate?
2408			 * If so, set ecdh_clnt_cert to 1.
2409			 */
2410			if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL))
2411				{
2412				/* XXX: For now, we do not support client
2413				 * authentication using ECDH certificates.
2414				 * To add such support, one needs to add
2415				 * code that checks for appropriate
2416				 * conditions and sets ecdh_clnt_cert to 1.
2417				 * For example, the cert have an ECC
2418				 * key on the same curve as the server's
2419				 * and the key should be authorized for
2420				 * key agreement.
2421				 *
2422				 * One also needs to add code in ssl3_connect
2423				 * to skip sending the certificate verify
2424				 * message.
2425				 *
2426				 * if ((s->cert->key->privatekey != NULL) &&
2427				 *     (s->cert->key->privatekey->type ==
2428				 *      EVP_PKEY_EC) && ...)
2429				 * ecdh_clnt_cert = 1;
2430				 */
2431				}
2432
2433			if (s->session->sess_cert->peer_ecdh_tmp != NULL)
2434				{
2435				tkey = s->session->sess_cert->peer_ecdh_tmp;
2436				}
2437			else
2438				{
2439				/* Get the Server Public Key from Cert */
2440				srvr_pub_pkey = X509_get_pubkey(s->session-> \
2441				    sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
2442				if ((srvr_pub_pkey == NULL) ||
2443				    (srvr_pub_pkey->type != EVP_PKEY_EC) ||
2444				    (srvr_pub_pkey->pkey.ec == NULL))
2445					{
2446					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2447					    ERR_R_INTERNAL_ERROR);
2448					goto err;
2449					}
2450
2451				tkey = srvr_pub_pkey->pkey.ec;
2452				}
2453
2454			srvr_group   = EC_KEY_get0_group(tkey);
2455			srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2456
2457			if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
2458				{
2459				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2460				    ERR_R_INTERNAL_ERROR);
2461				goto err;
2462				}
2463
2464			if ((clnt_ecdh=EC_KEY_new()) == NULL)
2465				{
2466				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2467				goto err;
2468				}
2469
2470			if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
2471				{
2472				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2473				goto err;
2474				}
2475			if (ecdh_clnt_cert)
2476				{
2477				/* Reuse key info from our certificate
2478				 * We only need our private key to perform
2479				 * the ECDH computation.
2480				 */
2481				const BIGNUM *priv_key;
2482				tkey = s->cert->key->privatekey->pkey.ec;
2483				priv_key = EC_KEY_get0_private_key(tkey);
2484				if (priv_key == NULL)
2485					{
2486					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2487					goto err;
2488					}
2489				if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
2490					{
2491					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2492					goto err;
2493					}
2494				}
2495			else
2496				{
2497				/* Generate a new ECDH key pair */
2498				if (!(EC_KEY_generate_key(clnt_ecdh)))
2499					{
2500					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2501					goto err;
2502					}
2503				}
2504
2505			/* use the 'p' output buffer for the ECDH key, but
2506			 * make sure to clear it out afterwards
2507			 */
2508
2509			field_size = EC_GROUP_get_degree(srvr_group);
2510			if (field_size <= 0)
2511				{
2512				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2513				       ERR_R_ECDH_LIB);
2514				goto err;
2515				}
2516			n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
2517			if (n <= 0)
2518				{
2519				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2520				       ERR_R_ECDH_LIB);
2521				goto err;
2522				}
2523
2524			/* generate master key from the result */
2525			s->session->master_key_length = s->method->ssl3_enc \
2526			    -> generate_master_secret(s,
2527				s->session->master_key,
2528				p, n);
2529
2530			memset(p, 0, n); /* clean up */
2531
2532			if (ecdh_clnt_cert)
2533				{
2534				/* Send empty client key exch message */
2535				n = 0;
2536				}
2537			else
2538				{
2539				/* First check the size of encoding and
2540				 * allocate memory accordingly.
2541				 */
2542				encoded_pt_len =
2543				    EC_POINT_point2oct(srvr_group,
2544					EC_KEY_get0_public_key(clnt_ecdh),
2545					POINT_CONVERSION_UNCOMPRESSED,
2546					NULL, 0, NULL);
2547
2548				encodedPoint = (unsigned char *)
2549				    OPENSSL_malloc(encoded_pt_len *
2550					sizeof(unsigned char));
2551				bn_ctx = BN_CTX_new();
2552				if ((encodedPoint == NULL) ||
2553				    (bn_ctx == NULL))
2554					{
2555					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2556					goto err;
2557					}
2558
2559				/* Encode the public key */
2560				n = EC_POINT_point2oct(srvr_group,
2561				    EC_KEY_get0_public_key(clnt_ecdh),
2562				    POINT_CONVERSION_UNCOMPRESSED,
2563				    encodedPoint, encoded_pt_len, bn_ctx);
2564
2565				*p = n; /* length of encoded point */
2566				/* Encoded point will be copied here */
2567				p += 1;
2568				/* copy the point */
2569				memcpy((unsigned char *)p, encodedPoint, n);
2570				/* increment n to account for length field */
2571				n += 1;
2572				}
2573
2574			/* Free allocated memory */
2575			BN_CTX_free(bn_ctx);
2576			if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2577			if (clnt_ecdh != NULL)
2578				 EC_KEY_free(clnt_ecdh);
2579			EVP_PKEY_free(srvr_pub_pkey);
2580			}
2581#endif /* !OPENSSL_NO_ECDH */
2582		else if (alg_k & SSL_kGOST)
2583			{
2584			/* GOST key exchange message creation */
2585			EVP_PKEY_CTX *pkey_ctx;
2586			X509 *peer_cert;
2587			size_t msglen;
2588			unsigned int md_len;
2589			int keytype;
2590			unsigned char premaster_secret[32],shared_ukm[32], tmp[256];
2591			EVP_MD_CTX *ukm_hash;
2592			EVP_PKEY *pub_key;
2593
2594			/* Get server sertificate PKEY and create ctx from it */
2595			peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST01)].x509;
2596			if (!peer_cert)
2597				peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST94)].x509;
2598			if (!peer_cert)		{
2599					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2600					goto err;
2601				}
2602
2603			pkey_ctx=EVP_PKEY_CTX_new(pub_key=X509_get_pubkey(peer_cert),NULL);
2604			/* If we have send a certificate, and certificate key
2605
2606			 * parameters match those of server certificate, use
2607			 * certificate key for key exchange
2608			 */
2609
2610			 /* Otherwise, generate ephemeral key pair */
2611
2612			EVP_PKEY_encrypt_init(pkey_ctx);
2613			  /* Generate session key */
2614		    RAND_bytes(premaster_secret,32);
2615			/* If we have client certificate, use its secret as peer key */
2616			if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2617				if (EVP_PKEY_derive_set_peer(pkey_ctx,s->cert->key->privatekey) <=0) {
2618					/* If there was an error - just ignore it. Ephemeral key
2619					* would be used
2620					*/
2621					ERR_clear_error();
2622				}
2623			}
2624			/* Compute shared IV and store it in algorithm-specific
2625			 * context data */
2626			ukm_hash = EVP_MD_CTX_create();
2627			EVP_DigestInit(ukm_hash,EVP_get_digestbynid(NID_id_GostR3411_94));
2628			EVP_DigestUpdate(ukm_hash,s->s3->client_random,SSL3_RANDOM_SIZE);
2629			EVP_DigestUpdate(ukm_hash,s->s3->server_random,SSL3_RANDOM_SIZE);
2630			EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2631			EVP_MD_CTX_destroy(ukm_hash);
2632			if (EVP_PKEY_CTX_ctrl(pkey_ctx,-1,EVP_PKEY_OP_ENCRYPT,EVP_PKEY_CTRL_SET_IV,
2633				8,shared_ukm)<0) {
2634					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2635						SSL_R_LIBRARY_BUG);
2636					goto err;
2637				}
2638			/* Make GOST keytransport blob message */
2639			/*Encapsulate it into sequence */
2640			*(p++)=V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2641			msglen=255;
2642			if (EVP_PKEY_encrypt(pkey_ctx,tmp,&msglen,premaster_secret,32)<0) {
2643			SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2644					SSL_R_LIBRARY_BUG);
2645				goto err;
2646			}
2647			if (msglen >= 0x80)
2648				{
2649				*(p++)=0x81;
2650				*(p++)= msglen & 0xff;
2651				n=msglen+3;
2652				}
2653			else
2654				{
2655				*(p++)= msglen & 0xff;
2656				n=msglen+2;
2657				}
2658			memcpy(p, tmp, msglen);
2659			/* Check if pubkey from client certificate was used */
2660			if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2661				{
2662				/* Set flag "skip certificate verify" */
2663				s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2664				}
2665			EVP_PKEY_CTX_free(pkey_ctx);
2666			s->session->master_key_length=
2667				s->method->ssl3_enc->generate_master_secret(s,
2668					s->session->master_key,premaster_secret,32);
2669			EVP_PKEY_free(pub_key);
2670
2671			}
2672#ifndef OPENSSL_NO_PSK
2673		else if (alg_k & SSL_kPSK)
2674			{
2675			/* The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes
2676			 * to return a \0-terminated identity. The last byte
2677			 * is for us for simulating strnlen. */
2678			char identity[PSK_MAX_IDENTITY_LEN + 2];
2679			size_t identity_len;
2680			unsigned char *t = NULL;
2681			unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
2682			unsigned int pre_ms_len = 0, psk_len = 0;
2683			int psk_err = 1;
2684
2685			n = 0;
2686			if (s->psk_client_callback == NULL)
2687				{
2688				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2689					SSL_R_PSK_NO_CLIENT_CB);
2690				goto err;
2691				}
2692
2693			memset(identity, 0, sizeof(identity));
2694			psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
2695				identity, sizeof(identity) - 1,
2696				psk_or_pre_ms, sizeof(psk_or_pre_ms));
2697			if (psk_len > PSK_MAX_PSK_LEN)
2698				{
2699				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2700					ERR_R_INTERNAL_ERROR);
2701				goto psk_err;
2702				}
2703			else if (psk_len == 0)
2704				{
2705				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2706					SSL_R_PSK_IDENTITY_NOT_FOUND);
2707				goto psk_err;
2708				}
2709			identity[PSK_MAX_IDENTITY_LEN + 1] = '\0';
2710			identity_len = strlen(identity);
2711			if (identity_len > PSK_MAX_IDENTITY_LEN)
2712				{
2713				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2714					ERR_R_INTERNAL_ERROR);
2715				goto psk_err;
2716				}
2717			/* create PSK pre_master_secret */
2718			pre_ms_len = 2+psk_len+2+psk_len;
2719			t = psk_or_pre_ms;
2720			memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
2721			s2n(psk_len, t);
2722			memset(t, 0, psk_len);
2723			t+=psk_len;
2724			s2n(psk_len, t);
2725
2726			if (s->session->psk_identity_hint != NULL)
2727				OPENSSL_free(s->session->psk_identity_hint);
2728			s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2729			if (s->ctx->psk_identity_hint != NULL &&
2730				s->session->psk_identity_hint == NULL)
2731				{
2732				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2733					ERR_R_MALLOC_FAILURE);
2734				goto psk_err;
2735				}
2736
2737			if (s->session->psk_identity != NULL)
2738				OPENSSL_free(s->session->psk_identity);
2739			s->session->psk_identity = BUF_strdup(identity);
2740			if (s->session->psk_identity == NULL)
2741				{
2742				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2743					ERR_R_MALLOC_FAILURE);
2744				goto psk_err;
2745				}
2746
2747			s->session->master_key_length =
2748				s->method->ssl3_enc->generate_master_secret(s,
2749					s->session->master_key,
2750					psk_or_pre_ms, pre_ms_len);
2751			s2n(identity_len, p);
2752			memcpy(p, identity, identity_len);
2753			n = 2 + identity_len;
2754			psk_err = 0;
2755		psk_err:
2756			OPENSSL_cleanse(identity, sizeof(identity));
2757			OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2758			if (psk_err != 0)
2759				{
2760				ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2761				goto err;
2762				}
2763			}
2764#endif
2765		else
2766			{
2767			ssl3_send_alert(s, SSL3_AL_FATAL,
2768			    SSL_AD_HANDSHAKE_FAILURE);
2769			SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2770			    ERR_R_INTERNAL_ERROR);
2771			goto err;
2772			}
2773
2774		*(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
2775		l2n3(n,d);
2776
2777		s->state=SSL3_ST_CW_KEY_EXCH_B;
2778		/* number of bytes to write */
2779		s->init_num=n+4;
2780		s->init_off=0;
2781		}
2782
2783	/* SSL3_ST_CW_KEY_EXCH_B */
2784	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2785err:
2786#ifndef OPENSSL_NO_ECDH
2787	BN_CTX_free(bn_ctx);
2788	if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2789	if (clnt_ecdh != NULL)
2790		EC_KEY_free(clnt_ecdh);
2791	EVP_PKEY_free(srvr_pub_pkey);
2792#endif
2793	return(-1);
2794	}
2795
2796int ssl3_send_client_verify(SSL *s)
2797	{
2798	unsigned char *p,*d;
2799	unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
2800	EVP_PKEY *pkey;
2801	EVP_PKEY_CTX *pctx=NULL;
2802#ifndef OPENSSL_NO_RSA
2803	unsigned u=0;
2804#endif
2805	unsigned long n;
2806	int j;
2807
2808	if (s->state == SSL3_ST_CW_CERT_VRFY_A)
2809		{
2810		d=(unsigned char *)s->init_buf->data;
2811		p= &(d[4]);
2812		pkey=s->cert->key->privatekey;
2813/* Create context from key and test if sha1 is allowed as digest */
2814		pctx = EVP_PKEY_CTX_new(pkey,NULL);
2815		EVP_PKEY_sign_init(pctx);
2816		if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1())>0)
2817			{
2818			s->method->ssl3_enc->cert_verify_mac(s,
2819						NID_sha1,
2820						&(data[MD5_DIGEST_LENGTH]));
2821			}
2822		else
2823			{
2824			ERR_clear_error();
2825			}
2826#ifndef OPENSSL_NO_RSA
2827		if (pkey->type == EVP_PKEY_RSA)
2828			{
2829			s->method->ssl3_enc->cert_verify_mac(s,
2830				NID_md5,
2831			 	&(data[0]));
2832			if (RSA_sign(NID_md5_sha1, data,
2833					 MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
2834					&(p[2]), &u, pkey->pkey.rsa) <= 0 )
2835				{
2836				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
2837				goto err;
2838				}
2839			s2n(u,p);
2840			n=u+2;
2841			}
2842		else
2843#endif
2844#ifndef OPENSSL_NO_DSA
2845			if (pkey->type == EVP_PKEY_DSA)
2846			{
2847			if (!DSA_sign(pkey->save_type,
2848				&(data[MD5_DIGEST_LENGTH]),
2849				SHA_DIGEST_LENGTH,&(p[2]),
2850				(unsigned int *)&j,pkey->pkey.dsa))
2851				{
2852				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
2853				goto err;
2854				}
2855			s2n(j,p);
2856			n=j+2;
2857			}
2858		else
2859#endif
2860#ifndef OPENSSL_NO_ECDSA
2861			if (pkey->type == EVP_PKEY_EC)
2862			{
2863			if (!ECDSA_sign(pkey->save_type,
2864				&(data[MD5_DIGEST_LENGTH]),
2865				SHA_DIGEST_LENGTH,&(p[2]),
2866				(unsigned int *)&j,pkey->pkey.ec))
2867				{
2868				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
2869				    ERR_R_ECDSA_LIB);
2870				goto err;
2871				}
2872			s2n(j,p);
2873			n=j+2;
2874			}
2875		else
2876#endif
2877		if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
2878		{
2879		unsigned char signbuf[64];
2880		int i;
2881		size_t sigsize=64;
2882		s->method->ssl3_enc->cert_verify_mac(s,
2883			NID_id_GostR3411_94,
2884			data);
2885		if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {
2886			SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
2887			ERR_R_INTERNAL_ERROR);
2888			goto err;
2889		}
2890		for (i=63,j=0; i>=0; j++, i--) {
2891			p[2+j]=signbuf[i];
2892		}
2893		s2n(j,p);
2894		n=j+2;
2895		}
2896		else
2897		{
2898			SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
2899			goto err;
2900		}
2901		*(d++)=SSL3_MT_CERTIFICATE_VERIFY;
2902		l2n3(n,d);
2903
2904		s->state=SSL3_ST_CW_CERT_VRFY_B;
2905		s->init_num=(int)n+4;
2906		s->init_off=0;
2907		}
2908	EVP_PKEY_CTX_free(pctx);
2909	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2910err:
2911	EVP_PKEY_CTX_free(pctx);
2912	return(-1);
2913	}
2914
2915int ssl3_send_client_certificate(SSL *s)
2916	{
2917	X509 *x509=NULL;
2918	EVP_PKEY *pkey=NULL;
2919	int i;
2920	unsigned long l;
2921
2922	if (s->state ==	SSL3_ST_CW_CERT_A)
2923		{
2924		if ((s->cert == NULL) ||
2925			(s->cert->key->x509 == NULL) ||
2926			(s->cert->key->privatekey == NULL))
2927			s->state=SSL3_ST_CW_CERT_B;
2928		else
2929			s->state=SSL3_ST_CW_CERT_C;
2930		}
2931
2932	/* We need to get a client cert */
2933	if (s->state == SSL3_ST_CW_CERT_B)
2934		{
2935		/* If we get an error, we need to
2936		 * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
2937		 * We then get retied later */
2938		i=0;
2939		i = ssl_do_client_cert_cb(s, &x509, &pkey);
2940		if (i < 0)
2941			{
2942			s->rwstate=SSL_X509_LOOKUP;
2943			return(-1);
2944			}
2945		s->rwstate=SSL_NOTHING;
2946		if ((i == 1) && (pkey != NULL) && (x509 != NULL))
2947			{
2948			s->state=SSL3_ST_CW_CERT_B;
2949			if (	!SSL_use_certificate(s,x509) ||
2950				!SSL_use_PrivateKey(s,pkey))
2951				i=0;
2952			}
2953		else if (i == 1)
2954			{
2955			i=0;
2956			SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2957			}
2958
2959		if (x509 != NULL) X509_free(x509);
2960		if (pkey != NULL) EVP_PKEY_free(pkey);
2961		if (i == 0)
2962			{
2963			if (s->version == SSL3_VERSION)
2964				{
2965				s->s3->tmp.cert_req=0;
2966				ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
2967				return(1);
2968				}
2969			else
2970				{
2971				s->s3->tmp.cert_req=2;
2972				}
2973			}
2974
2975		/* Ok, we have a cert */
2976		s->state=SSL3_ST_CW_CERT_C;
2977		}
2978
2979	if (s->state == SSL3_ST_CW_CERT_C)
2980		{
2981		s->state=SSL3_ST_CW_CERT_D;
2982		l=ssl3_output_cert_chain(s,
2983			(s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
2984		if (!l)
2985			{
2986			SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2987			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
2988			return 0;
2989			}
2990		s->init_num=(int)l;
2991		s->init_off=0;
2992		}
2993	/* SSL3_ST_CW_CERT_D */
2994	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2995	}
2996
2997#define has_bits(i,m)	(((i)&(m)) == (m))
2998
2999int ssl3_check_cert_and_algorithm(SSL *s)
3000	{
3001	int i,idx;
3002	long alg_k,alg_a;
3003	EVP_PKEY *pkey=NULL;
3004	SESS_CERT *sc;
3005#ifndef OPENSSL_NO_RSA
3006	RSA *rsa;
3007#endif
3008#ifndef OPENSSL_NO_DH
3009	DH *dh;
3010#endif
3011
3012	alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
3013	alg_a=s->s3->tmp.new_cipher->algorithm_auth;
3014
3015	/* we don't have a certificate */
3016	if ((alg_a & (SSL_aDH|SSL_aNULL|SSL_aKRB5)) || (alg_k & SSL_kPSK))
3017		return(1);
3018
3019	sc=s->session->sess_cert;
3020	if (sc == NULL)
3021		{
3022		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR);
3023		goto err;
3024		}
3025
3026#ifndef OPENSSL_NO_RSA
3027	rsa=s->session->sess_cert->peer_rsa_tmp;
3028#endif
3029#ifndef OPENSSL_NO_DH
3030	dh=s->session->sess_cert->peer_dh_tmp;
3031#endif
3032
3033	/* This is the passed certificate */
3034
3035	idx=sc->peer_cert_type;
3036#ifndef OPENSSL_NO_ECDH
3037	if (idx == SSL_PKEY_ECC)
3038		{
3039		if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509,
3040		    s->s3->tmp.new_cipher) == 0)
3041			{ /* check failed */
3042			SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT);
3043			goto f_err;
3044			}
3045		else
3046			{
3047			return 1;
3048			}
3049		}
3050#endif
3051	pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
3052	i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
3053	EVP_PKEY_free(pkey);
3054
3055
3056	/* Check that we have a certificate if we require one */
3057	if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
3058		{
3059		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT);
3060		goto f_err;
3061		}
3062#ifndef OPENSSL_NO_DSA
3063	else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN))
3064		{
3065		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT);
3066		goto f_err;
3067		}
3068#endif
3069#ifndef OPENSSL_NO_RSA
3070	if ((alg_k & SSL_kRSA) &&
3071		!(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
3072		{
3073		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3074		goto f_err;
3075		}
3076#endif
3077#ifndef OPENSSL_NO_DH
3078	if ((alg_k & SSL_kEDH) &&
3079		!(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
3080		{
3081		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY);
3082		goto f_err;
3083		}
3084	else if ((alg_k & SSL_kDHr) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA))
3085		{
3086		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT);
3087		goto f_err;
3088		}
3089#ifndef OPENSSL_NO_DSA
3090	else if ((alg_k & SSL_kDHd) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA))
3091		{
3092		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT);
3093		goto f_err;
3094		}
3095#endif
3096#endif
3097
3098	if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP))
3099		{
3100#ifndef OPENSSL_NO_RSA
3101		if (alg_k & SSL_kRSA)
3102			{
3103			if (rsa == NULL
3104			    || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
3105				{
3106				SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3107				goto f_err;
3108				}
3109			}
3110		else
3111#endif
3112#ifndef OPENSSL_NO_DH
3113			if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
3114			    {
3115			    if (dh == NULL
3116				|| DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
3117				{
3118				SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3119				goto f_err;
3120				}
3121			}
3122		else
3123#endif
3124			{
3125			SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
3126			goto f_err;
3127			}
3128		}
3129	return(1);
3130f_err:
3131	ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
3132err:
3133	return(0);
3134	}
3135
3136/* Check to see if handshake is full or resumed. Usually this is just a
3137 * case of checking to see if a cache hit has occurred. In the case of
3138 * session tickets we have to check the next message to be sure.
3139 */
3140
3141#ifndef OPENSSL_NO_TLSEXT
3142int ssl3_check_finished(SSL *s)
3143	{
3144	int ok;
3145	long n;
3146	/* If we have no ticket it cannot be a resumed session. */
3147	if (!s->session->tlsext_tick)
3148		return 1;
3149	/* this function is called when we really expect a Certificate
3150	 * message, so permit appropriate message length */
3151	n=s->method->ssl_get_message(s,
3152		SSL3_ST_CR_CERT_A,
3153		SSL3_ST_CR_CERT_B,
3154		-1,
3155		s->max_cert_list,
3156		&ok);
3157	if (!ok) return((int)n);
3158	s->s3->tmp.reuse_message = 1;
3159	if ((s->s3->tmp.message_type == SSL3_MT_FINISHED)
3160		|| (s->s3->tmp.message_type == SSL3_MT_NEWSESSION_TICKET))
3161		return 2;
3162
3163	return 1;
3164	}
3165#endif
3166
3167int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3168	{
3169	int i = 0;
3170#ifndef OPENSSL_NO_ENGINE
3171	if (s->ctx->client_cert_engine)
3172		{
3173		i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3174						SSL_get_client_CA_list(s),
3175						px509, ppkey, NULL, NULL, NULL);
3176		if (i != 0)
3177			return i;
3178		}
3179#endif
3180	if (s->ctx->client_cert_cb)
3181		i = s->ctx->client_cert_cb(s,px509,ppkey);
3182	return i;
3183	}
3184