s3_clnt.c revision 127128
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-2002 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#include <stdio.h>
113#include "ssl_locl.h"
114#include "kssl_lcl.h"
115#include <openssl/buffer.h>
116#include <openssl/rand.h>
117#include <openssl/objects.h>
118#include <openssl/evp.h>
119#include <openssl/md5.h>
120
121static SSL_METHOD *ssl3_get_client_method(int ver);
122static int ssl3_client_hello(SSL *s);
123static int ssl3_get_server_hello(SSL *s);
124static int ssl3_get_certificate_request(SSL *s);
125static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b);
126static int ssl3_get_server_done(SSL *s);
127static int ssl3_send_client_verify(SSL *s);
128static int ssl3_send_client_certificate(SSL *s);
129static int ssl3_send_client_key_exchange(SSL *s);
130static int ssl3_get_key_exchange(SSL *s);
131static int ssl3_get_server_certificate(SSL *s);
132static int ssl3_check_cert_and_algorithm(SSL *s);
133static SSL_METHOD *ssl3_get_client_method(int ver)
134	{
135	if (ver == SSL3_VERSION)
136		return(SSLv3_client_method());
137	else
138		return(NULL);
139	}
140
141SSL_METHOD *SSLv3_client_method(void)
142	{
143	static int init=1;
144	static SSL_METHOD SSLv3_client_data;
145
146	if (init)
147		{
148		CRYPTO_w_lock(CRYPTO_LOCK_SSL_METHOD);
149
150		if (init)
151			{
152			memcpy((char *)&SSLv3_client_data,(char *)sslv3_base_method(),
153				sizeof(SSL_METHOD));
154			SSLv3_client_data.ssl_connect=ssl3_connect;
155			SSLv3_client_data.get_ssl_method=ssl3_get_client_method;
156			init=0;
157			}
158
159		CRYPTO_w_unlock(CRYPTO_LOCK_SSL_METHOD);
160		}
161	return(&SSLv3_client_data);
162	}
163
164int ssl3_connect(SSL *s)
165	{
166	BUF_MEM *buf=NULL;
167	unsigned long Time=time(NULL),l;
168	long num1;
169	void (*cb)(const SSL *ssl,int type,int val)=NULL;
170	int ret= -1;
171	int new_state,state,skip=0;;
172
173	RAND_add(&Time,sizeof(Time),0);
174	ERR_clear_error();
175	clear_sys_error();
176
177	if (s->info_callback != NULL)
178		cb=s->info_callback;
179	else if (s->ctx->info_callback != NULL)
180		cb=s->ctx->info_callback;
181
182	s->in_handshake++;
183	if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
184
185	for (;;)
186		{
187		state=s->state;
188
189		switch(s->state)
190			{
191		case SSL_ST_RENEGOTIATE:
192			s->new_session=1;
193			s->state=SSL_ST_CONNECT;
194			s->ctx->stats.sess_connect_renegotiate++;
195			/* break */
196		case SSL_ST_BEFORE:
197		case SSL_ST_CONNECT:
198		case SSL_ST_BEFORE|SSL_ST_CONNECT:
199		case SSL_ST_OK|SSL_ST_CONNECT:
200
201			s->server=0;
202			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
203
204			if ((s->version & 0xff00 ) != 0x0300)
205				{
206				SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
207				ret = -1;
208				goto end;
209				}
210
211			/* s->version=SSL3_VERSION; */
212			s->type=SSL_ST_CONNECT;
213
214			if (s->init_buf == NULL)
215				{
216				if ((buf=BUF_MEM_new()) == NULL)
217					{
218					ret= -1;
219					goto end;
220					}
221				if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
222					{
223					ret= -1;
224					goto end;
225					}
226				s->init_buf=buf;
227				buf=NULL;
228				}
229
230			if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
231
232			/* setup buffing BIO */
233			if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
234
235			/* don't push the buffering BIO quite yet */
236
237			ssl3_init_finished_mac(s);
238
239			s->state=SSL3_ST_CW_CLNT_HELLO_A;
240			s->ctx->stats.sess_connect++;
241			s->init_num=0;
242			break;
243
244		case SSL3_ST_CW_CLNT_HELLO_A:
245		case SSL3_ST_CW_CLNT_HELLO_B:
246
247			s->shutdown=0;
248			ret=ssl3_client_hello(s);
249			if (ret <= 0) goto end;
250			s->state=SSL3_ST_CR_SRVR_HELLO_A;
251			s->init_num=0;
252
253			/* turn on buffering for the next lot of output */
254			if (s->bbio != s->wbio)
255				s->wbio=BIO_push(s->bbio,s->wbio);
256
257			break;
258
259		case SSL3_ST_CR_SRVR_HELLO_A:
260		case SSL3_ST_CR_SRVR_HELLO_B:
261			ret=ssl3_get_server_hello(s);
262			if (ret <= 0) goto end;
263			if (s->hit)
264				s->state=SSL3_ST_CR_FINISHED_A;
265			else
266				s->state=SSL3_ST_CR_CERT_A;
267			s->init_num=0;
268			break;
269
270		case SSL3_ST_CR_CERT_A:
271		case SSL3_ST_CR_CERT_B:
272			/* Check if it is anon DH */
273			if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
274				{
275				ret=ssl3_get_server_certificate(s);
276				if (ret <= 0) goto end;
277				}
278			else
279				skip=1;
280			s->state=SSL3_ST_CR_KEY_EXCH_A;
281			s->init_num=0;
282			break;
283
284		case SSL3_ST_CR_KEY_EXCH_A:
285		case SSL3_ST_CR_KEY_EXCH_B:
286			ret=ssl3_get_key_exchange(s);
287			if (ret <= 0) goto end;
288			s->state=SSL3_ST_CR_CERT_REQ_A;
289			s->init_num=0;
290
291			/* at this point we check that we have the
292			 * required stuff from the server */
293			if (!ssl3_check_cert_and_algorithm(s))
294				{
295				ret= -1;
296				goto end;
297				}
298			break;
299
300		case SSL3_ST_CR_CERT_REQ_A:
301		case SSL3_ST_CR_CERT_REQ_B:
302			ret=ssl3_get_certificate_request(s);
303			if (ret <= 0) goto end;
304			s->state=SSL3_ST_CR_SRVR_DONE_A;
305			s->init_num=0;
306			break;
307
308		case SSL3_ST_CR_SRVR_DONE_A:
309		case SSL3_ST_CR_SRVR_DONE_B:
310			ret=ssl3_get_server_done(s);
311			if (ret <= 0) goto end;
312			if (s->s3->tmp.cert_req)
313				s->state=SSL3_ST_CW_CERT_A;
314			else
315				s->state=SSL3_ST_CW_KEY_EXCH_A;
316			s->init_num=0;
317
318			break;
319
320		case SSL3_ST_CW_CERT_A:
321		case SSL3_ST_CW_CERT_B:
322		case SSL3_ST_CW_CERT_C:
323		case SSL3_ST_CW_CERT_D:
324			ret=ssl3_send_client_certificate(s);
325			if (ret <= 0) goto end;
326			s->state=SSL3_ST_CW_KEY_EXCH_A;
327			s->init_num=0;
328			break;
329
330		case SSL3_ST_CW_KEY_EXCH_A:
331		case SSL3_ST_CW_KEY_EXCH_B:
332			ret=ssl3_send_client_key_exchange(s);
333			if (ret <= 0) goto end;
334			l=s->s3->tmp.new_cipher->algorithms;
335			/* EAY EAY EAY need to check for DH fix cert
336			 * sent back */
337			/* For TLS, cert_req is set to 2, so a cert chain
338			 * of nothing is sent, but no verify packet is sent */
339			if (s->s3->tmp.cert_req == 1)
340				{
341				s->state=SSL3_ST_CW_CERT_VRFY_A;
342				}
343			else
344				{
345				s->state=SSL3_ST_CW_CHANGE_A;
346				s->s3->change_cipher_spec=0;
347				}
348
349			s->init_num=0;
350			break;
351
352		case SSL3_ST_CW_CERT_VRFY_A:
353		case SSL3_ST_CW_CERT_VRFY_B:
354			ret=ssl3_send_client_verify(s);
355			if (ret <= 0) goto end;
356			s->state=SSL3_ST_CW_CHANGE_A;
357			s->init_num=0;
358			s->s3->change_cipher_spec=0;
359			break;
360
361		case SSL3_ST_CW_CHANGE_A:
362		case SSL3_ST_CW_CHANGE_B:
363			ret=ssl3_send_change_cipher_spec(s,
364				SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
365			if (ret <= 0) goto end;
366			s->state=SSL3_ST_CW_FINISHED_A;
367			s->init_num=0;
368
369			s->session->cipher=s->s3->tmp.new_cipher;
370			if (s->s3->tmp.new_compression == NULL)
371				s->session->compress_meth=0;
372			else
373				s->session->compress_meth=
374					s->s3->tmp.new_compression->id;
375			if (!s->method->ssl3_enc->setup_key_block(s))
376				{
377				ret= -1;
378				goto end;
379				}
380
381			if (!s->method->ssl3_enc->change_cipher_state(s,
382				SSL3_CHANGE_CIPHER_CLIENT_WRITE))
383				{
384				ret= -1;
385				goto end;
386				}
387
388			break;
389
390		case SSL3_ST_CW_FINISHED_A:
391		case SSL3_ST_CW_FINISHED_B:
392			ret=ssl3_send_finished(s,
393				SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
394				s->method->ssl3_enc->client_finished_label,
395				s->method->ssl3_enc->client_finished_label_len);
396			if (ret <= 0) goto end;
397			s->state=SSL3_ST_CW_FLUSH;
398
399			/* clear flags */
400			s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
401			if (s->hit)
402				{
403				s->s3->tmp.next_state=SSL_ST_OK;
404				if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
405					{
406					s->state=SSL_ST_OK;
407					s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
408					s->s3->delay_buf_pop_ret=0;
409					}
410				}
411			else
412				{
413				s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
414				}
415			s->init_num=0;
416			break;
417
418		case SSL3_ST_CR_FINISHED_A:
419		case SSL3_ST_CR_FINISHED_B:
420
421			ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
422				SSL3_ST_CR_FINISHED_B);
423			if (ret <= 0) goto end;
424
425			if (s->hit)
426				s->state=SSL3_ST_CW_CHANGE_A;
427			else
428				s->state=SSL_ST_OK;
429			s->init_num=0;
430			break;
431
432		case SSL3_ST_CW_FLUSH:
433			/* number of bytes to be flushed */
434			num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
435			if (num1 > 0)
436				{
437				s->rwstate=SSL_WRITING;
438				num1=BIO_flush(s->wbio);
439				if (num1 <= 0) { ret= -1; goto end; }
440				s->rwstate=SSL_NOTHING;
441				}
442
443			s->state=s->s3->tmp.next_state;
444			break;
445
446		case SSL_ST_OK:
447			/* clean a few things up */
448			ssl3_cleanup_key_block(s);
449
450			if (s->init_buf != NULL)
451				{
452				BUF_MEM_free(s->init_buf);
453				s->init_buf=NULL;
454				}
455
456			/* If we are not 'joining' the last two packets,
457			 * remove the buffering now */
458			if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
459				ssl_free_wbio_buffer(s);
460			/* else do it later in ssl3_write */
461
462			s->init_num=0;
463			s->new_session=0;
464
465			ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
466			if (s->hit) s->ctx->stats.sess_hit++;
467
468			ret=1;
469			/* s->server=0; */
470			s->handshake_func=ssl3_connect;
471			s->ctx->stats.sess_connect_good++;
472
473			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
474
475			goto end;
476			/* break; */
477
478		default:
479			SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);
480			ret= -1;
481			goto end;
482			/* break; */
483			}
484
485		/* did we do anything */
486		if (!s->s3->tmp.reuse_message && !skip)
487			{
488			if (s->debug)
489				{
490				if ((ret=BIO_flush(s->wbio)) <= 0)
491					goto end;
492				}
493
494			if ((cb != NULL) && (s->state != state))
495				{
496				new_state=s->state;
497				s->state=state;
498				cb(s,SSL_CB_CONNECT_LOOP,1);
499				s->state=new_state;
500				}
501			}
502		skip=0;
503		}
504end:
505	s->in_handshake--;
506	if (buf != NULL)
507		BUF_MEM_free(buf);
508	if (cb != NULL)
509		cb(s,SSL_CB_CONNECT_EXIT,ret);
510	return(ret);
511	}
512
513
514static int ssl3_client_hello(SSL *s)
515	{
516	unsigned char *buf;
517	unsigned char *p,*d;
518	int i,j;
519	unsigned long Time,l;
520	SSL_COMP *comp;
521
522	buf=(unsigned char *)s->init_buf->data;
523	if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
524		{
525		if ((s->session == NULL) ||
526			(s->session->ssl_version != s->version) ||
527			(s->session->not_resumable))
528			{
529			if (!ssl_get_new_session(s,0))
530				goto err;
531			}
532		/* else use the pre-loaded session */
533
534		p=s->s3->client_random;
535		Time=time(NULL);			/* Time */
536		l2n(Time,p);
537		RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-sizeof(Time));
538
539		/* Do the message type and length last */
540		d=p= &(buf[4]);
541
542		*(p++)=s->version>>8;
543		*(p++)=s->version&0xff;
544		s->client_version=s->version;
545
546		/* Random stuff */
547		memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
548		p+=SSL3_RANDOM_SIZE;
549
550		/* Session ID */
551		if (s->new_session)
552			i=0;
553		else
554			i=s->session->session_id_length;
555		*(p++)=i;
556		if (i != 0)
557			{
558			if (i > sizeof s->session->session_id)
559				{
560				SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
561				goto err;
562				}
563			memcpy(p,s->session->session_id,i);
564			p+=i;
565			}
566
567		/* Ciphers supported */
568		i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]));
569		if (i == 0)
570			{
571			SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
572			goto err;
573			}
574		s2n(i,p);
575		p+=i;
576
577		/* COMPRESSION */
578		if (s->ctx->comp_methods == NULL)
579			j=0;
580		else
581			j=sk_SSL_COMP_num(s->ctx->comp_methods);
582		*(p++)=1+j;
583		for (i=0; i<j; i++)
584			{
585			comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
586			*(p++)=comp->id;
587			}
588		*(p++)=0; /* Add the NULL method */
589
590		l=(p-d);
591		d=buf;
592		*(d++)=SSL3_MT_CLIENT_HELLO;
593		l2n3(l,d);
594
595		s->state=SSL3_ST_CW_CLNT_HELLO_B;
596		/* number of bytes to write */
597		s->init_num=p-buf;
598		s->init_off=0;
599		}
600
601	/* SSL3_ST_CW_CLNT_HELLO_B */
602	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
603err:
604	return(-1);
605	}
606
607static int ssl3_get_server_hello(SSL *s)
608	{
609	STACK_OF(SSL_CIPHER) *sk;
610	SSL_CIPHER *c;
611	unsigned char *p,*d;
612	int i,al,ok;
613	unsigned int j;
614	long n;
615	SSL_COMP *comp;
616
617	n=ssl3_get_message(s,
618		SSL3_ST_CR_SRVR_HELLO_A,
619		SSL3_ST_CR_SRVR_HELLO_B,
620		SSL3_MT_SERVER_HELLO,
621		300, /* ?? */
622		&ok);
623
624	if (!ok) return((int)n);
625	d=p=(unsigned char *)s->init_msg;
626
627	if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff)))
628		{
629		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION);
630		s->version=(s->version&0xff00)|p[1];
631		al=SSL_AD_PROTOCOL_VERSION;
632		goto f_err;
633		}
634	p+=2;
635
636	/* load the server hello data */
637	/* load the server random */
638	memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE);
639	p+=SSL3_RANDOM_SIZE;
640
641	/* get the session-id */
642	j= *(p++);
643
644	if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE))
645		{
646		al=SSL_AD_ILLEGAL_PARAMETER;
647		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG);
648		goto f_err;
649		}
650
651	if (j != 0 && j == s->session->session_id_length
652	    && memcmp(p,s->session->session_id,j) == 0)
653	    {
654	    if(s->sid_ctx_length != s->session->sid_ctx_length
655	       || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length))
656		{
657		/* actually a client application bug */
658		al=SSL_AD_ILLEGAL_PARAMETER;
659		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
660		goto f_err;
661		}
662	    s->hit=1;
663	    }
664	else	/* a miss or crap from the other end */
665		{
666		/* If we were trying for session-id reuse, make a new
667		 * SSL_SESSION so we don't stuff up other people */
668		s->hit=0;
669		if (s->session->session_id_length > 0)
670			{
671			if (!ssl_get_new_session(s,0))
672				{
673				al=SSL_AD_INTERNAL_ERROR;
674				goto f_err;
675				}
676			}
677		s->session->session_id_length=j;
678		memcpy(s->session->session_id,p,j); /* j could be 0 */
679		}
680	p+=j;
681	c=ssl_get_cipher_by_char(s,p);
682	if (c == NULL)
683		{
684		/* unknown cipher */
685		al=SSL_AD_ILLEGAL_PARAMETER;
686		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED);
687		goto f_err;
688		}
689	p+=ssl_put_cipher_by_char(s,NULL,NULL);
690
691	sk=ssl_get_ciphers_by_id(s);
692	i=sk_SSL_CIPHER_find(sk,c);
693	if (i < 0)
694		{
695		/* we did not say we would use this cipher */
696		al=SSL_AD_ILLEGAL_PARAMETER;
697		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
698		goto f_err;
699		}
700
701	/* Depending on the session caching (internal/external), the cipher
702	   and/or cipher_id values may not be set. Make sure that
703	   cipher_id is set and use it for comparison. */
704	if (s->session->cipher)
705		s->session->cipher_id = s->session->cipher->id;
706	if (s->hit && (s->session->cipher_id != c->id))
707		{
708		if (!(s->options &
709			SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
710			{
711			al=SSL_AD_ILLEGAL_PARAMETER;
712			SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
713			goto f_err;
714			}
715		}
716	s->s3->tmp.new_cipher=c;
717
718	/* lets get the compression algorithm */
719	/* COMPRESSION */
720	j= *(p++);
721	if (j == 0)
722		comp=NULL;
723	else
724		comp=ssl3_comp_find(s->ctx->comp_methods,j);
725
726	if ((j != 0) && (comp == NULL))
727		{
728		al=SSL_AD_ILLEGAL_PARAMETER;
729		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
730		goto f_err;
731		}
732	else
733		{
734		s->s3->tmp.new_compression=comp;
735		}
736
737	if (p != (d+n))
738		{
739		/* wrong packet length */
740		al=SSL_AD_DECODE_ERROR;
741		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH);
742		goto err;
743		}
744
745	return(1);
746f_err:
747	ssl3_send_alert(s,SSL3_AL_FATAL,al);
748err:
749	return(-1);
750	}
751
752static int ssl3_get_server_certificate(SSL *s)
753	{
754	int al,i,ok,ret= -1;
755	unsigned long n,nc,llen,l;
756	X509 *x=NULL;
757	unsigned char *p,*d,*q;
758	STACK_OF(X509) *sk=NULL;
759	SESS_CERT *sc;
760	EVP_PKEY *pkey=NULL;
761        int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */
762
763	n=ssl3_get_message(s,
764		SSL3_ST_CR_CERT_A,
765		SSL3_ST_CR_CERT_B,
766		-1,
767		s->max_cert_list,
768		&ok);
769
770	if (!ok) return((int)n);
771
772	if (s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE)
773		{
774		s->s3->tmp.reuse_message=1;
775		return(1);
776		}
777
778	if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
779		{
780		al=SSL_AD_UNEXPECTED_MESSAGE;
781		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE);
782		goto f_err;
783		}
784	d=p=(unsigned char *)s->init_msg;
785
786	if ((sk=sk_X509_new_null()) == NULL)
787		{
788		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
789		goto err;
790		}
791
792	n2l3(p,llen);
793	if (llen+3 != n)
794		{
795		al=SSL_AD_DECODE_ERROR;
796		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
797		goto f_err;
798		}
799	for (nc=0; nc<llen; )
800		{
801		n2l3(p,l);
802		if ((l+nc+3) > llen)
803			{
804			al=SSL_AD_DECODE_ERROR;
805			SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
806			goto f_err;
807			}
808
809		q=p;
810		x=d2i_X509(NULL,&q,l);
811		if (x == NULL)
812			{
813			al=SSL_AD_BAD_CERTIFICATE;
814			SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB);
815			goto f_err;
816			}
817		if (q != (p+l))
818			{
819			al=SSL_AD_DECODE_ERROR;
820			SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
821			goto f_err;
822			}
823		if (!sk_X509_push(sk,x))
824			{
825			SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
826			goto err;
827			}
828		x=NULL;
829		nc+=l+3;
830		p=q;
831		}
832
833	i=ssl_verify_cert_chain(s,sk);
834	if ((s->verify_mode != SSL_VERIFY_NONE) && (!i)
835#ifndef OPENSSL_NO_KRB5
836                && (s->s3->tmp.new_cipher->algorithms & (SSL_MKEY_MASK|SSL_AUTH_MASK))
837                != (SSL_aKRB5|SSL_kKRB5)
838#endif /* OPENSSL_NO_KRB5 */
839                )
840		{
841		al=ssl_verify_alarm_type(s->verify_result);
842		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
843		goto f_err;
844		}
845	ERR_clear_error(); /* but we keep s->verify_result */
846
847	sc=ssl_sess_cert_new();
848	if (sc == NULL) goto err;
849
850	if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
851	s->session->sess_cert=sc;
852
853	sc->cert_chain=sk;
854	/* Inconsistency alert: cert_chain does include the peer's
855	 * certificate, which we don't include in s3_srvr.c */
856	x=sk_X509_value(sk,0);
857	sk=NULL;
858 	/* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
859
860	pkey=X509_get_pubkey(x);
861
862        /* VRS: allow null cert if auth == KRB5 */
863        need_cert =	((s->s3->tmp.new_cipher->algorithms
864			& (SSL_MKEY_MASK|SSL_AUTH_MASK))
865                        == (SSL_aKRB5|SSL_kKRB5))? 0: 1;
866
867#ifdef KSSL_DEBUG
868	printf("pkey,x = %p, %p\n", pkey,x);
869	printf("ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey));
870	printf("cipher, alg, nc = %s, %lx, %d\n", s->s3->tmp.new_cipher->name,
871                s->s3->tmp.new_cipher->algorithms, need_cert);
872#endif    /* KSSL_DEBUG */
873
874	if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey)))
875		{
876		x=NULL;
877		al=SSL3_AL_FATAL;
878		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
879			SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
880		goto f_err;
881		}
882
883	i=ssl_cert_type(x,pkey);
884	if (need_cert && i < 0)
885		{
886		x=NULL;
887		al=SSL3_AL_FATAL;
888		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
889			SSL_R_UNKNOWN_CERTIFICATE_TYPE);
890		goto f_err;
891		}
892
893        if (need_cert)
894                {
895                sc->peer_cert_type=i;
896                CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
897                /* Why would the following ever happen?
898                 * We just created sc a couple of lines ago. */
899                if (sc->peer_pkeys[i].x509 != NULL)
900                        X509_free(sc->peer_pkeys[i].x509);
901                sc->peer_pkeys[i].x509=x;
902                sc->peer_key= &(sc->peer_pkeys[i]);
903
904                if (s->session->peer != NULL)
905                        X509_free(s->session->peer);
906                CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
907                s->session->peer=x;
908                }
909        else
910                {
911                sc->peer_cert_type=i;
912                sc->peer_key= NULL;
913
914                if (s->session->peer != NULL)
915                        X509_free(s->session->peer);
916                s->session->peer=NULL;
917                }
918	s->session->verify_result = s->verify_result;
919
920	x=NULL;
921	ret=1;
922
923	if (0)
924		{
925f_err:
926		ssl3_send_alert(s,SSL3_AL_FATAL,al);
927		}
928err:
929	EVP_PKEY_free(pkey);
930	X509_free(x);
931	sk_X509_pop_free(sk,X509_free);
932	return(ret);
933	}
934
935static int ssl3_get_key_exchange(SSL *s)
936	{
937#ifndef OPENSSL_NO_RSA
938	unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];
939#endif
940	EVP_MD_CTX md_ctx;
941	unsigned char *param,*p;
942	int al,i,j,param_len,ok;
943	long n,alg;
944	EVP_PKEY *pkey=NULL;
945#ifndef OPENSSL_NO_RSA
946	RSA *rsa=NULL;
947#endif
948#ifndef OPENSSL_NO_DH
949	DH *dh=NULL;
950#endif
951
952	/* use same message size as in ssl3_get_certificate_request()
953	 * as ServerKeyExchange message may be skipped */
954	n=ssl3_get_message(s,
955		SSL3_ST_CR_KEY_EXCH_A,
956		SSL3_ST_CR_KEY_EXCH_B,
957		-1,
958		s->max_cert_list,
959		&ok);
960
961	if (!ok) return((int)n);
962
963	if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
964		{
965		s->s3->tmp.reuse_message=1;
966		return(1);
967		}
968
969	param=p=(unsigned char *)s->init_msg;
970
971	if (s->session->sess_cert != NULL)
972		{
973#ifndef OPENSSL_NO_RSA
974		if (s->session->sess_cert->peer_rsa_tmp != NULL)
975			{
976			RSA_free(s->session->sess_cert->peer_rsa_tmp);
977			s->session->sess_cert->peer_rsa_tmp=NULL;
978			}
979#endif
980#ifndef OPENSSL_NO_DH
981		if (s->session->sess_cert->peer_dh_tmp)
982			{
983			DH_free(s->session->sess_cert->peer_dh_tmp);
984			s->session->sess_cert->peer_dh_tmp=NULL;
985			}
986#endif
987		}
988	else
989		{
990		s->session->sess_cert=ssl_sess_cert_new();
991		}
992
993	param_len=0;
994	alg=s->s3->tmp.new_cipher->algorithms;
995	EVP_MD_CTX_init(&md_ctx);
996
997#ifndef OPENSSL_NO_RSA
998	if (alg & SSL_kRSA)
999		{
1000		if ((rsa=RSA_new()) == NULL)
1001			{
1002			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1003			goto err;
1004			}
1005		n2s(p,i);
1006		param_len=i+2;
1007		if (param_len > n)
1008			{
1009			al=SSL_AD_DECODE_ERROR;
1010			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
1011			goto f_err;
1012			}
1013		if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
1014			{
1015			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1016			goto err;
1017			}
1018		p+=i;
1019
1020		n2s(p,i);
1021		param_len+=i+2;
1022		if (param_len > n)
1023			{
1024			al=SSL_AD_DECODE_ERROR;
1025			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
1026			goto f_err;
1027			}
1028		if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
1029			{
1030			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1031			goto err;
1032			}
1033		p+=i;
1034		n-=param_len;
1035
1036		/* this should be because we are using an export cipher */
1037		if (alg & SSL_aRSA)
1038			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1039		else
1040			{
1041			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1042			goto err;
1043			}
1044		s->session->sess_cert->peer_rsa_tmp=rsa;
1045		rsa=NULL;
1046		}
1047#else /* OPENSSL_NO_RSA */
1048	if (0)
1049		;
1050#endif
1051#ifndef OPENSSL_NO_DH
1052	else if (alg & SSL_kEDH)
1053		{
1054		if ((dh=DH_new()) == NULL)
1055			{
1056			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);
1057			goto err;
1058			}
1059		n2s(p,i);
1060		param_len=i+2;
1061		if (param_len > n)
1062			{
1063			al=SSL_AD_DECODE_ERROR;
1064			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);
1065			goto f_err;
1066			}
1067		if (!(dh->p=BN_bin2bn(p,i,NULL)))
1068			{
1069			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1070			goto err;
1071			}
1072		p+=i;
1073
1074		n2s(p,i);
1075		param_len+=i+2;
1076		if (param_len > n)
1077			{
1078			al=SSL_AD_DECODE_ERROR;
1079			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);
1080			goto f_err;
1081			}
1082		if (!(dh->g=BN_bin2bn(p,i,NULL)))
1083			{
1084			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1085			goto err;
1086			}
1087		p+=i;
1088
1089		n2s(p,i);
1090		param_len+=i+2;
1091		if (param_len > n)
1092			{
1093			al=SSL_AD_DECODE_ERROR;
1094			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);
1095			goto f_err;
1096			}
1097		if (!(dh->pub_key=BN_bin2bn(p,i,NULL)))
1098			{
1099			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1100			goto err;
1101			}
1102		p+=i;
1103		n-=param_len;
1104
1105#ifndef OPENSSL_NO_RSA
1106		if (alg & SSL_aRSA)
1107			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1108#else
1109		if (0)
1110			;
1111#endif
1112#ifndef OPENSSL_NO_DSA
1113		else if (alg & SSL_aDSS)
1114			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1115#endif
1116		/* else anonymous DH, so no certificate or pkey. */
1117
1118		s->session->sess_cert->peer_dh_tmp=dh;
1119		dh=NULL;
1120		}
1121	else if ((alg & SSL_kDHr) || (alg & SSL_kDHd))
1122		{
1123		al=SSL_AD_ILLEGAL_PARAMETER;
1124		SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1125		goto f_err;
1126		}
1127#endif /* !OPENSSL_NO_DH */
1128	if (alg & SSL_aFZA)
1129		{
1130		al=SSL_AD_HANDSHAKE_FAILURE;
1131		SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1132		goto f_err;
1133		}
1134
1135
1136	/* p points to the next byte, there are 'n' bytes left */
1137
1138
1139	/* if it was signed, check the signature */
1140	if (pkey != NULL)
1141		{
1142		n2s(p,i);
1143		n-=2;
1144		j=EVP_PKEY_size(pkey);
1145
1146		if ((i != n) || (n > j) || (n <= 0))
1147			{
1148			/* wrong packet length */
1149			al=SSL_AD_DECODE_ERROR;
1150			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);
1151			goto f_err;
1152			}
1153
1154#ifndef OPENSSL_NO_RSA
1155		if (pkey->type == EVP_PKEY_RSA)
1156			{
1157			int num;
1158
1159			j=0;
1160			q=md_buf;
1161			for (num=2; num > 0; num--)
1162				{
1163				EVP_DigestInit_ex(&md_ctx,(num == 2)
1164					?s->ctx->md5:s->ctx->sha1, NULL);
1165				EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1166				EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1167				EVP_DigestUpdate(&md_ctx,param,param_len);
1168				EVP_DigestFinal_ex(&md_ctx,q,(unsigned int *)&i);
1169				q+=i;
1170				j+=i;
1171				}
1172			i=RSA_verify(NID_md5_sha1, md_buf, j, p, n,
1173								pkey->pkey.rsa);
1174			if (i < 0)
1175				{
1176				al=SSL_AD_DECRYPT_ERROR;
1177				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
1178				goto f_err;
1179				}
1180			if (i == 0)
1181				{
1182				/* bad signature */
1183				al=SSL_AD_DECRYPT_ERROR;
1184				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1185				goto f_err;
1186				}
1187			}
1188		else
1189#endif
1190#ifndef OPENSSL_NO_DSA
1191			if (pkey->type == EVP_PKEY_DSA)
1192			{
1193			/* lets do DSS */
1194			EVP_VerifyInit_ex(&md_ctx,EVP_dss1(), NULL);
1195			EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1196			EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1197			EVP_VerifyUpdate(&md_ctx,param,param_len);
1198			if (!EVP_VerifyFinal(&md_ctx,p,(int)n,pkey))
1199				{
1200				/* bad signature */
1201				al=SSL_AD_DECRYPT_ERROR;
1202				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1203				goto f_err;
1204				}
1205			}
1206		else
1207#endif
1208			{
1209			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1210			goto err;
1211			}
1212		}
1213	else
1214		{
1215		/* still data left over */
1216		if (!(alg & SSL_aNULL))
1217			{
1218			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1219			goto err;
1220			}
1221		if (n != 0)
1222			{
1223			al=SSL_AD_DECODE_ERROR;
1224			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
1225			goto f_err;
1226			}
1227		}
1228	EVP_PKEY_free(pkey);
1229	EVP_MD_CTX_cleanup(&md_ctx);
1230	return(1);
1231f_err:
1232	ssl3_send_alert(s,SSL3_AL_FATAL,al);
1233err:
1234	EVP_PKEY_free(pkey);
1235#ifndef OPENSSL_NO_RSA
1236	if (rsa != NULL)
1237		RSA_free(rsa);
1238#endif
1239#ifndef OPENSSL_NO_DH
1240	if (dh != NULL)
1241		DH_free(dh);
1242#endif
1243	EVP_MD_CTX_cleanup(&md_ctx);
1244	return(-1);
1245	}
1246
1247static int ssl3_get_certificate_request(SSL *s)
1248	{
1249	int ok,ret=0;
1250	unsigned long n,nc,l;
1251	unsigned int llen,ctype_num,i;
1252	X509_NAME *xn=NULL;
1253	unsigned char *p,*d,*q;
1254	STACK_OF(X509_NAME) *ca_sk=NULL;
1255
1256	n=ssl3_get_message(s,
1257		SSL3_ST_CR_CERT_REQ_A,
1258		SSL3_ST_CR_CERT_REQ_B,
1259		-1,
1260		s->max_cert_list,
1261		&ok);
1262
1263	if (!ok) return((int)n);
1264
1265	s->s3->tmp.cert_req=0;
1266
1267	if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
1268		{
1269		s->s3->tmp.reuse_message=1;
1270		return(1);
1271		}
1272
1273	if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
1274		{
1275		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1276		SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE);
1277		goto err;
1278		}
1279
1280	/* TLS does not like anon-DH with client cert */
1281	if (s->version > SSL3_VERSION)
1282		{
1283		l=s->s3->tmp.new_cipher->algorithms;
1284		if (l & SSL_aNULL)
1285			{
1286			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1287			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1288			goto err;
1289			}
1290		}
1291
1292	d=p=(unsigned char *)s->init_msg;
1293
1294	if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL)
1295		{
1296		SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1297		goto err;
1298		}
1299
1300	/* get the certificate types */
1301	ctype_num= *(p++);
1302	if (ctype_num > SSL3_CT_NUMBER)
1303		ctype_num=SSL3_CT_NUMBER;
1304	for (i=0; i<ctype_num; i++)
1305		s->s3->tmp.ctype[i]= p[i];
1306	p+=ctype_num;
1307
1308	/* get the CA RDNs */
1309	n2s(p,llen);
1310#if 0
1311{
1312FILE *out;
1313out=fopen("/tmp/vsign.der","w");
1314fwrite(p,1,llen,out);
1315fclose(out);
1316}
1317#endif
1318
1319	if ((llen+ctype_num+2+1) != n)
1320		{
1321		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1322		SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH);
1323		goto err;
1324		}
1325
1326	for (nc=0; nc<llen; )
1327		{
1328		n2s(p,l);
1329		if ((l+nc+2) > llen)
1330			{
1331			if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
1332				goto cont; /* netscape bugs */
1333			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1334			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG);
1335			goto err;
1336			}
1337
1338		q=p;
1339
1340		if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL)
1341			{
1342			/* If netscape tolerance is on, ignore errors */
1343			if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
1344				goto cont;
1345			else
1346				{
1347				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1348				SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB);
1349				goto err;
1350				}
1351			}
1352
1353		if (q != (p+l))
1354			{
1355			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1356			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH);
1357			goto err;
1358			}
1359		if (!sk_X509_NAME_push(ca_sk,xn))
1360			{
1361			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1362			goto err;
1363			}
1364
1365		p+=l;
1366		nc+=l+2;
1367		}
1368
1369	if (0)
1370		{
1371cont:
1372		ERR_clear_error();
1373		}
1374
1375	/* we should setup a certificate to return.... */
1376	s->s3->tmp.cert_req=1;
1377	s->s3->tmp.ctype_num=ctype_num;
1378	if (s->s3->tmp.ca_names != NULL)
1379		sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
1380	s->s3->tmp.ca_names=ca_sk;
1381	ca_sk=NULL;
1382
1383	ret=1;
1384err:
1385	if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
1386	return(ret);
1387	}
1388
1389static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1390	{
1391	return(X509_NAME_cmp(*a,*b));
1392	}
1393
1394static int ssl3_get_server_done(SSL *s)
1395	{
1396	int ok,ret=0;
1397	long n;
1398
1399	n=ssl3_get_message(s,
1400		SSL3_ST_CR_SRVR_DONE_A,
1401		SSL3_ST_CR_SRVR_DONE_B,
1402		SSL3_MT_SERVER_DONE,
1403		30, /* should be very small, like 0 :-) */
1404		&ok);
1405
1406	if (!ok) return((int)n);
1407	if (n > 0)
1408		{
1409		/* should contain no data */
1410		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1411		SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH);
1412		return -1;
1413		}
1414	ret=1;
1415	return(ret);
1416	}
1417
1418static int ssl3_send_client_key_exchange(SSL *s)
1419	{
1420	unsigned char *p,*d;
1421	int n;
1422	unsigned long l;
1423#ifndef OPENSSL_NO_RSA
1424	unsigned char *q;
1425	EVP_PKEY *pkey=NULL;
1426#endif
1427#ifndef OPENSSL_NO_KRB5
1428        KSSL_ERR kssl_err;
1429#endif /* OPENSSL_NO_KRB5 */
1430
1431	if (s->state == SSL3_ST_CW_KEY_EXCH_A)
1432		{
1433		d=(unsigned char *)s->init_buf->data;
1434		p= &(d[4]);
1435
1436		l=s->s3->tmp.new_cipher->algorithms;
1437
1438                /* Fool emacs indentation */
1439                if (0) {}
1440#ifndef OPENSSL_NO_RSA
1441		else if (l & SSL_kRSA)
1442			{
1443			RSA *rsa;
1444			unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
1445
1446			if (s->session->sess_cert->peer_rsa_tmp != NULL)
1447				rsa=s->session->sess_cert->peer_rsa_tmp;
1448			else
1449				{
1450				pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1451				if ((pkey == NULL) ||
1452					(pkey->type != EVP_PKEY_RSA) ||
1453					(pkey->pkey.rsa == NULL))
1454					{
1455					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1456					goto err;
1457					}
1458				rsa=pkey->pkey.rsa;
1459				EVP_PKEY_free(pkey);
1460				}
1461
1462			tmp_buf[0]=s->client_version>>8;
1463			tmp_buf[1]=s->client_version&0xff;
1464			if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
1465					goto err;
1466
1467			s->session->master_key_length=sizeof tmp_buf;
1468
1469			q=p;
1470			/* Fix buf for TLS and beyond */
1471			if (s->version > SSL3_VERSION)
1472				p+=2;
1473			n=RSA_public_encrypt(sizeof tmp_buf,
1474				tmp_buf,p,rsa,RSA_PKCS1_PADDING);
1475#ifdef PKCS1_CHECK
1476			if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
1477			if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
1478#endif
1479			if (n <= 0)
1480				{
1481				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
1482				goto err;
1483				}
1484
1485			/* Fix buf for TLS and beyond */
1486			if (s->version > SSL3_VERSION)
1487				{
1488				s2n(n,q);
1489				n+=2;
1490				}
1491
1492			s->session->master_key_length=
1493				s->method->ssl3_enc->generate_master_secret(s,
1494					s->session->master_key,
1495					tmp_buf,sizeof tmp_buf);
1496			OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
1497			}
1498#endif
1499#ifndef OPENSSL_NO_KRB5
1500		else if (l & SSL_kKRB5)
1501                        {
1502                        krb5_error_code	krb5rc;
1503                        KSSL_CTX	*kssl_ctx = s->kssl_ctx;
1504                        /*  krb5_data	krb5_ap_req;  */
1505                        krb5_data	*enc_ticket;
1506                        krb5_data	authenticator, *authp = NULL;
1507			EVP_CIPHER_CTX	ciph_ctx;
1508			EVP_CIPHER	*enc = NULL;
1509			unsigned char	iv[EVP_MAX_IV_LENGTH];
1510			unsigned char	tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
1511			unsigned char	epms[SSL_MAX_MASTER_KEY_LENGTH
1512						+ EVP_MAX_IV_LENGTH];
1513			int 		padl, outl = sizeof(epms);
1514
1515			EVP_CIPHER_CTX_init(&ciph_ctx);
1516
1517#ifdef KSSL_DEBUG
1518                        printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
1519                                l, SSL_kKRB5);
1520#endif	/* KSSL_DEBUG */
1521
1522			authp = NULL;
1523#ifdef KRB5SENDAUTH
1524			if (KRB5SENDAUTH)  authp = &authenticator;
1525#endif	/* KRB5SENDAUTH */
1526
1527                        krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
1528				&kssl_err);
1529			enc = kssl_map_enc(kssl_ctx->enctype);
1530                        if (enc == NULL)
1531                            goto err;
1532#ifdef KSSL_DEBUG
1533                        {
1534                        printf("kssl_cget_tkt rtn %d\n", krb5rc);
1535                        if (krb5rc && kssl_err.text)
1536			  printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
1537                        }
1538#endif	/* KSSL_DEBUG */
1539
1540                        if (krb5rc)
1541                                {
1542                                ssl3_send_alert(s,SSL3_AL_FATAL,
1543						SSL_AD_HANDSHAKE_FAILURE);
1544                                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
1545						kssl_err.reason);
1546                                goto err;
1547                                }
1548
1549			/*  20010406 VRS - Earlier versions used KRB5 AP_REQ
1550			**  in place of RFC 2712 KerberosWrapper, as in:
1551			**
1552                        **  Send ticket (copy to *p, set n = length)
1553                        **  n = krb5_ap_req.length;
1554                        **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
1555                        **  if (krb5_ap_req.data)
1556                        **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
1557                        **
1558			**  Now using real RFC 2712 KerberosWrapper
1559			**  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
1560			**  Note: 2712 "opaque" types are here replaced
1561			**  with a 2-byte length followed by the value.
1562			**  Example:
1563			**  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
1564			**  Where "xx xx" = length bytes.  Shown here with
1565			**  optional authenticator omitted.
1566			*/
1567
1568			/*  KerberosWrapper.Ticket		*/
1569			s2n(enc_ticket->length,p);
1570			memcpy(p, enc_ticket->data, enc_ticket->length);
1571			p+= enc_ticket->length;
1572			n = enc_ticket->length + 2;
1573
1574			/*  KerberosWrapper.Authenticator	*/
1575			if (authp  &&  authp->length)
1576				{
1577				s2n(authp->length,p);
1578				memcpy(p, authp->data, authp->length);
1579				p+= authp->length;
1580				n+= authp->length + 2;
1581
1582				free(authp->data);
1583				authp->data = NULL;
1584				authp->length = 0;
1585				}
1586			else
1587				{
1588				s2n(0,p);/*  null authenticator length	*/
1589				n+=2;
1590				}
1591
1592			if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
1593			    goto err;
1594
1595			/*  20010420 VRS.  Tried it this way; failed.
1596			**	EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
1597			**	EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
1598			**				kssl_ctx->length);
1599			**	EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
1600			*/
1601
1602			memset(iv, 0, sizeof iv);  /* per RFC 1510 */
1603			EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
1604				kssl_ctx->key,iv);
1605			EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
1606				sizeof tmp_buf);
1607			EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
1608			outl += padl;
1609			if (outl > sizeof epms)
1610				{
1611				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1612				goto err;
1613				}
1614			EVP_CIPHER_CTX_cleanup(&ciph_ctx);
1615
1616			/*  KerberosWrapper.EncryptedPreMasterSecret	*/
1617			s2n(outl,p);
1618			memcpy(p, epms, outl);
1619			p+=outl;
1620			n+=outl + 2;
1621
1622                        s->session->master_key_length=
1623                                s->method->ssl3_enc->generate_master_secret(s,
1624					s->session->master_key,
1625					tmp_buf, sizeof tmp_buf);
1626
1627			OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
1628			OPENSSL_cleanse(epms, outl);
1629                        }
1630#endif
1631#ifndef OPENSSL_NO_DH
1632		else if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1633			{
1634			DH *dh_srvr,*dh_clnt;
1635
1636			if (s->session->sess_cert->peer_dh_tmp != NULL)
1637				dh_srvr=s->session->sess_cert->peer_dh_tmp;
1638			else
1639				{
1640				/* we get them from the cert */
1641				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1642				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
1643				goto err;
1644				}
1645
1646			/* generate a new random key */
1647			if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
1648				{
1649				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1650				goto err;
1651				}
1652			if (!DH_generate_key(dh_clnt))
1653				{
1654				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1655				goto err;
1656				}
1657
1658			/* use the 'p' output buffer for the DH key, but
1659			 * make sure to clear it out afterwards */
1660
1661			n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
1662
1663			if (n <= 0)
1664				{
1665				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1666				goto err;
1667				}
1668
1669			/* generate master key from the result */
1670			s->session->master_key_length=
1671				s->method->ssl3_enc->generate_master_secret(s,
1672					s->session->master_key,p,n);
1673			/* clean up */
1674			memset(p,0,n);
1675
1676			/* send off the data */
1677			n=BN_num_bytes(dh_clnt->pub_key);
1678			s2n(n,p);
1679			BN_bn2bin(dh_clnt->pub_key,p);
1680			n+=2;
1681
1682			DH_free(dh_clnt);
1683
1684			/* perhaps clean things up a bit EAY EAY EAY EAY*/
1685			}
1686#endif
1687		else
1688			{
1689			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1690			SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1691			goto err;
1692			}
1693
1694		*(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
1695		l2n3(n,d);
1696
1697		s->state=SSL3_ST_CW_KEY_EXCH_B;
1698		/* number of bytes to write */
1699		s->init_num=n+4;
1700		s->init_off=0;
1701		}
1702
1703	/* SSL3_ST_CW_KEY_EXCH_B */
1704	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1705err:
1706	return(-1);
1707	}
1708
1709static int ssl3_send_client_verify(SSL *s)
1710	{
1711	unsigned char *p,*d;
1712	unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1713	EVP_PKEY *pkey;
1714#ifndef OPENSSL_NO_RSA
1715	unsigned u=0;
1716#endif
1717	unsigned long n;
1718#ifndef OPENSSL_NO_DSA
1719	int j;
1720#endif
1721
1722	if (s->state == SSL3_ST_CW_CERT_VRFY_A)
1723		{
1724		d=(unsigned char *)s->init_buf->data;
1725		p= &(d[4]);
1726		pkey=s->cert->key->privatekey;
1727
1728		s->method->ssl3_enc->cert_verify_mac(s,&(s->s3->finish_dgst2),
1729			&(data[MD5_DIGEST_LENGTH]));
1730
1731#ifndef OPENSSL_NO_RSA
1732		if (pkey->type == EVP_PKEY_RSA)
1733			{
1734			s->method->ssl3_enc->cert_verify_mac(s,
1735				&(s->s3->finish_dgst1),&(data[0]));
1736			if (RSA_sign(NID_md5_sha1, data,
1737					 MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
1738					&(p[2]), &u, pkey->pkey.rsa) <= 0 )
1739				{
1740				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
1741				goto err;
1742				}
1743			s2n(u,p);
1744			n=u+2;
1745			}
1746		else
1747#endif
1748#ifndef OPENSSL_NO_DSA
1749			if (pkey->type == EVP_PKEY_DSA)
1750			{
1751			if (!DSA_sign(pkey->save_type,
1752				&(data[MD5_DIGEST_LENGTH]),
1753				SHA_DIGEST_LENGTH,&(p[2]),
1754				(unsigned int *)&j,pkey->pkey.dsa))
1755				{
1756				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
1757				goto err;
1758				}
1759			s2n(j,p);
1760			n=j+2;
1761			}
1762		else
1763#endif
1764			{
1765			SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
1766			goto err;
1767			}
1768		*(d++)=SSL3_MT_CERTIFICATE_VERIFY;
1769		l2n3(n,d);
1770
1771		s->state=SSL3_ST_CW_CERT_VRFY_B;
1772		s->init_num=(int)n+4;
1773		s->init_off=0;
1774		}
1775	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1776err:
1777	return(-1);
1778	}
1779
1780static int ssl3_send_client_certificate(SSL *s)
1781	{
1782	X509 *x509=NULL;
1783	EVP_PKEY *pkey=NULL;
1784	int i;
1785	unsigned long l;
1786
1787	if (s->state ==	SSL3_ST_CW_CERT_A)
1788		{
1789		if ((s->cert == NULL) ||
1790			(s->cert->key->x509 == NULL) ||
1791			(s->cert->key->privatekey == NULL))
1792			s->state=SSL3_ST_CW_CERT_B;
1793		else
1794			s->state=SSL3_ST_CW_CERT_C;
1795		}
1796
1797	/* We need to get a client cert */
1798	if (s->state == SSL3_ST_CW_CERT_B)
1799		{
1800		/* If we get an error, we need to
1801		 * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
1802		 * We then get retied later */
1803		i=0;
1804		if (s->ctx->client_cert_cb != NULL)
1805			i=s->ctx->client_cert_cb(s,&(x509),&(pkey));
1806		if (i < 0)
1807			{
1808			s->rwstate=SSL_X509_LOOKUP;
1809			return(-1);
1810			}
1811		s->rwstate=SSL_NOTHING;
1812		if ((i == 1) && (pkey != NULL) && (x509 != NULL))
1813			{
1814			s->state=SSL3_ST_CW_CERT_B;
1815			if (	!SSL_use_certificate(s,x509) ||
1816				!SSL_use_PrivateKey(s,pkey))
1817				i=0;
1818			}
1819		else if (i == 1)
1820			{
1821			i=0;
1822			SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
1823			}
1824
1825		if (x509 != NULL) X509_free(x509);
1826		if (pkey != NULL) EVP_PKEY_free(pkey);
1827		if (i == 0)
1828			{
1829			if (s->version == SSL3_VERSION)
1830				{
1831				s->s3->tmp.cert_req=0;
1832				ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
1833				return(1);
1834				}
1835			else
1836				{
1837				s->s3->tmp.cert_req=2;
1838				}
1839			}
1840
1841		/* Ok, we have a cert */
1842		s->state=SSL3_ST_CW_CERT_C;
1843		}
1844
1845	if (s->state == SSL3_ST_CW_CERT_C)
1846		{
1847		s->state=SSL3_ST_CW_CERT_D;
1848		l=ssl3_output_cert_chain(s,
1849			(s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
1850		s->init_num=(int)l;
1851		s->init_off=0;
1852		}
1853	/* SSL3_ST_CW_CERT_D */
1854	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1855	}
1856
1857#define has_bits(i,m)	(((i)&(m)) == (m))
1858
1859static int ssl3_check_cert_and_algorithm(SSL *s)
1860	{
1861	int i,idx;
1862	long algs;
1863	EVP_PKEY *pkey=NULL;
1864	SESS_CERT *sc;
1865#ifndef OPENSSL_NO_RSA
1866	RSA *rsa;
1867#endif
1868#ifndef OPENSSL_NO_DH
1869	DH *dh;
1870#endif
1871
1872	sc=s->session->sess_cert;
1873
1874	if (sc == NULL)
1875		{
1876		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR);
1877		goto err;
1878		}
1879
1880	algs=s->s3->tmp.new_cipher->algorithms;
1881
1882	/* we don't have a certificate */
1883	if (algs & (SSL_aDH|SSL_aNULL|SSL_aKRB5))
1884		return(1);
1885
1886#ifndef OPENSSL_NO_RSA
1887	rsa=s->session->sess_cert->peer_rsa_tmp;
1888#endif
1889#ifndef OPENSSL_NO_DH
1890	dh=s->session->sess_cert->peer_dh_tmp;
1891#endif
1892
1893	/* This is the passed certificate */
1894
1895	idx=sc->peer_cert_type;
1896	pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
1897	i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
1898	EVP_PKEY_free(pkey);
1899
1900
1901	/* Check that we have a certificate if we require one */
1902	if ((algs & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
1903		{
1904		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT);
1905		goto f_err;
1906		}
1907#ifndef OPENSSL_NO_DSA
1908	else if ((algs & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN))
1909		{
1910		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT);
1911		goto f_err;
1912		}
1913#endif
1914#ifndef OPENSSL_NO_RSA
1915	if ((algs & SSL_kRSA) &&
1916		!(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
1917		{
1918		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT);
1919		goto f_err;
1920		}
1921#endif
1922#ifndef OPENSSL_NO_DH
1923	if ((algs & SSL_kEDH) &&
1924		!(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
1925		{
1926		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY);
1927		goto f_err;
1928		}
1929	else if ((algs & SSL_kDHr) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA))
1930		{
1931		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT);
1932		goto f_err;
1933		}
1934#ifndef OPENSSL_NO_DSA
1935	else if ((algs & SSL_kDHd) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA))
1936		{
1937		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT);
1938		goto f_err;
1939		}
1940#endif
1941#endif
1942
1943	if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP))
1944		{
1945#ifndef OPENSSL_NO_RSA
1946		if (algs & SSL_kRSA)
1947			{
1948			if (rsa == NULL
1949			    || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
1950				{
1951				SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
1952				goto f_err;
1953				}
1954			}
1955		else
1956#endif
1957#ifndef OPENSSL_NO_DH
1958			if (algs & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1959			    {
1960			    if (dh == NULL
1961				|| DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
1962				{
1963				SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY);
1964				goto f_err;
1965				}
1966			}
1967		else
1968#endif
1969			{
1970			SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1971			goto f_err;
1972			}
1973		}
1974	return(1);
1975f_err:
1976	ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1977err:
1978	return(0);
1979	}
1980
1981