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