s3_clnt.c revision de9675dad342fcf6fe0ed86d083c027e88e44b6b
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 non-RSA PSK */
349			if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
350			    !((s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK) &&
351			      !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kRSA)))
352				{
353				ret=ssl3_get_server_certificate(s);
354				if (ret <= 0) goto end;
355#ifndef OPENSSL_NO_TLSEXT
356				if (s->tlsext_status_expected)
357					s->state=SSL3_ST_CR_CERT_STATUS_A;
358				else
359					s->state=SSL3_ST_CR_KEY_EXCH_A;
360				}
361			else
362				{
363				skip = 1;
364				s->state=SSL3_ST_CR_KEY_EXCH_A;
365				}
366#else
367				}
368			else
369				skip=1;
370
371			s->state=SSL3_ST_CR_KEY_EXCH_A;
372#endif
373			s->init_num=0;
374			break;
375
376		case SSL3_ST_CR_KEY_EXCH_A:
377		case SSL3_ST_CR_KEY_EXCH_B:
378			ret=ssl3_get_key_exchange(s);
379			if (ret <= 0) goto end;
380			s->state=SSL3_ST_CR_CERT_REQ_A;
381			s->init_num=0;
382
383			/* at this point we check that we have the
384			 * required stuff from the server */
385			if (!ssl3_check_cert_and_algorithm(s))
386				{
387				ret= -1;
388				goto end;
389				}
390			break;
391
392		case SSL3_ST_CR_CERT_REQ_A:
393		case SSL3_ST_CR_CERT_REQ_B:
394			ret=ssl3_get_certificate_request(s);
395			if (ret <= 0) goto end;
396			s->state=SSL3_ST_CR_SRVR_DONE_A;
397			s->init_num=0;
398			break;
399
400		case SSL3_ST_CR_SRVR_DONE_A:
401		case SSL3_ST_CR_SRVR_DONE_B:
402			ret=ssl3_get_server_done(s);
403			if (ret <= 0) goto end;
404#ifndef OPENSSL_NO_SRP
405			if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP)
406				{
407				if ((ret = SRP_Calc_A_param(s))<=0)
408					{
409					SSLerr(SSL_F_SSL3_CONNECT,SSL_R_SRP_A_CALC);
410					ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
411					goto end;
412					}
413				}
414#endif
415			if (s->s3->tmp.cert_req)
416				s->state=SSL3_ST_CW_CERT_A;
417			else
418				s->state=SSL3_ST_CW_KEY_EXCH_A;
419			s->init_num=0;
420
421			break;
422
423		case SSL3_ST_CW_CERT_A:
424		case SSL3_ST_CW_CERT_B:
425		case SSL3_ST_CW_CERT_C:
426		case SSL3_ST_CW_CERT_D:
427			ret=ssl3_send_client_certificate(s);
428			if (ret <= 0) goto end;
429			s->state=SSL3_ST_CW_KEY_EXCH_A;
430			s->init_num=0;
431			break;
432
433		case SSL3_ST_CW_KEY_EXCH_A:
434		case SSL3_ST_CW_KEY_EXCH_B:
435			ret=ssl3_send_client_key_exchange(s);
436			if (ret <= 0) goto end;
437			/* EAY EAY EAY need to check for DH fix cert
438			 * sent back */
439			/* For TLS, cert_req is set to 2, so a cert chain
440			 * of nothing is sent, but no verify packet is sent */
441			/* XXX: For now, we do not support client
442			 * authentication in ECDH cipher suites with
443			 * ECDH (rather than ECDSA) certificates.
444			 * We need to skip the certificate verify
445			 * message when client's ECDH public key is sent
446			 * inside the client certificate.
447			 */
448			if (s->s3->tmp.cert_req == 1)
449				{
450				s->state=SSL3_ST_CW_CERT_VRFY_A;
451				}
452			else
453				{
454				s->state=SSL3_ST_CW_CHANGE_A;
455				s->s3->change_cipher_spec=0;
456				}
457			if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
458				{
459				s->state=SSL3_ST_CW_CHANGE_A;
460				s->s3->change_cipher_spec=0;
461				}
462
463			s->init_num=0;
464			break;
465
466		case SSL3_ST_CW_CERT_VRFY_A:
467		case SSL3_ST_CW_CERT_VRFY_B:
468			ret=ssl3_send_client_verify(s);
469			if (ret <= 0) goto end;
470			s->state=SSL3_ST_CW_CHANGE_A;
471			s->init_num=0;
472			s->s3->change_cipher_spec=0;
473			break;
474
475		case SSL3_ST_CW_CHANGE_A:
476		case SSL3_ST_CW_CHANGE_B:
477			ret=ssl3_send_change_cipher_spec(s,
478				SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
479			if (ret <= 0) goto end;
480
481			s->state=SSL3_ST_CW_FINISHED_A;
482#if !defined(OPENSSL_NO_TLSEXT)
483			if (s->s3->tlsext_channel_id_valid)
484				s->state=SSL3_ST_CW_CHANNEL_ID_A;
485# if !defined(OPENSSL_NO_NEXTPROTONEG)
486			if (s->s3->next_proto_neg_seen)
487				s->state=SSL3_ST_CW_NEXT_PROTO_A;
488# endif
489#endif
490			s->init_num=0;
491
492			s->session->cipher=s->s3->tmp.new_cipher;
493#ifdef OPENSSL_NO_COMP
494			s->session->compress_meth=0;
495#else
496			if (s->s3->tmp.new_compression == NULL)
497				s->session->compress_meth=0;
498			else
499				s->session->compress_meth=
500					s->s3->tmp.new_compression->id;
501#endif
502			if (!s->method->ssl3_enc->setup_key_block(s))
503				{
504				ret= -1;
505				goto end;
506				}
507
508			if (!s->method->ssl3_enc->change_cipher_state(s,
509				SSL3_CHANGE_CIPHER_CLIENT_WRITE))
510				{
511				ret= -1;
512				goto end;
513				}
514
515			break;
516
517#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
518		case SSL3_ST_CW_NEXT_PROTO_A:
519		case SSL3_ST_CW_NEXT_PROTO_B:
520			ret=ssl3_send_next_proto(s);
521			if (ret <= 0) goto end;
522			if (s->s3->tlsext_channel_id_valid)
523				s->state=SSL3_ST_CW_CHANNEL_ID_A;
524			else
525				s->state=SSL3_ST_CW_FINISHED_A;
526			break;
527#endif
528
529#if !defined(OPENSSL_NO_TLSEXT)
530		case SSL3_ST_CW_CHANNEL_ID_A:
531		case SSL3_ST_CW_CHANNEL_ID_B:
532			ret=ssl3_send_channel_id(s);
533			if (ret <= 0) goto end;
534			s->state=SSL3_ST_CW_FINISHED_A;
535			break;
536#endif
537
538		case SSL3_ST_CW_FINISHED_A:
539		case SSL3_ST_CW_FINISHED_B:
540			ret=ssl3_send_finished(s,
541				SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
542				s->method->ssl3_enc->client_finished_label,
543				s->method->ssl3_enc->client_finished_label_len);
544			if (ret <= 0) goto end;
545			s->state=SSL3_ST_CW_FLUSH;
546
547			/* clear flags */
548			s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
549			if (s->hit)
550				{
551				s->s3->tmp.next_state=SSL_ST_OK;
552				if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
553					{
554					s->state=SSL_ST_OK;
555					s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
556					s->s3->delay_buf_pop_ret=0;
557					}
558				}
559			else
560				{
561				if ((SSL_get_mode(s) & SSL_MODE_HANDSHAKE_CUTTHROUGH) && SSL_get_cipher_bits(s, NULL) >= 128
562				    && s->s3->previous_server_finished_len == 0 /* no cutthrough on renegotiation (would complicate the state machine) */
563				   )
564					{
565					if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
566						{
567						s->state=SSL3_ST_CUTTHROUGH_COMPLETE;
568						s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
569						s->s3->delay_buf_pop_ret=0;
570						}
571					else
572						{
573						s->s3->tmp.next_state=SSL3_ST_CUTTHROUGH_COMPLETE;
574						}
575					}
576				else
577					{
578#ifndef OPENSSL_NO_TLSEXT
579					/* Allow NewSessionTicket if ticket expected */
580					if (s->tlsext_ticket_expected)
581						s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
582					else
583#endif
584						s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
585					}
586				}
587			s->init_num=0;
588			break;
589
590#ifndef OPENSSL_NO_TLSEXT
591		case SSL3_ST_CR_SESSION_TICKET_A:
592		case SSL3_ST_CR_SESSION_TICKET_B:
593			ret=ssl3_get_new_session_ticket(s);
594			if (ret <= 0) goto end;
595			s->state=SSL3_ST_CR_FINISHED_A;
596			s->init_num=0;
597		break;
598
599		case SSL3_ST_CR_CERT_STATUS_A:
600		case SSL3_ST_CR_CERT_STATUS_B:
601			ret=ssl3_get_cert_status(s);
602			if (ret <= 0) goto end;
603			s->state=SSL3_ST_CR_KEY_EXCH_A;
604			s->init_num=0;
605		break;
606#endif
607
608		case SSL3_ST_CR_FINISHED_A:
609		case SSL3_ST_CR_FINISHED_B:
610
611			ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
612				SSL3_ST_CR_FINISHED_B);
613			if (ret <= 0) goto end;
614
615			if (s->hit)
616				s->state=SSL3_ST_CW_CHANGE_A;
617			else
618				s->state=SSL_ST_OK;
619			s->init_num=0;
620			break;
621
622		case SSL3_ST_CW_FLUSH:
623			s->rwstate=SSL_WRITING;
624			if (BIO_flush(s->wbio) <= 0)
625				{
626				ret= -1;
627				goto end;
628				}
629			s->rwstate=SSL_NOTHING;
630			s->state=s->s3->tmp.next_state;
631			break;
632
633		case SSL3_ST_CUTTHROUGH_COMPLETE:
634#ifndef OPENSSL_NO_TLSEXT
635			/* Allow NewSessionTicket if ticket expected */
636			if (s->tlsext_ticket_expected)
637				s->state=SSL3_ST_CR_SESSION_TICKET_A;
638			else
639#endif
640				s->state=SSL3_ST_CR_FINISHED_A;
641
642			/* SSL_write() will take care of flushing buffered data if
643			 * DELAY_CLIENT_FINISHED is set.
644			 */
645			if (!(s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED))
646				ssl_free_wbio_buffer(s);
647			ret = 1;
648			goto end;
649			/* break; */
650
651		case SSL_ST_OK:
652			/* clean a few things up */
653			ssl3_cleanup_key_block(s);
654
655			if (s->init_buf != NULL)
656				{
657				BUF_MEM_free(s->init_buf);
658				s->init_buf=NULL;
659				}
660
661			/* If we are not 'joining' the last two packets,
662			 * remove the buffering now */
663			if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
664				ssl_free_wbio_buffer(s);
665			/* else do it later in ssl3_write */
666
667			s->init_num=0;
668			s->renegotiate=0;
669			s->new_session=0;
670
671			ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
672			if (s->hit) s->ctx->stats.sess_hit++;
673
674			ret=1;
675			/* s->server=0; */
676			s->handshake_func=ssl3_connect;
677			s->ctx->stats.sess_connect_good++;
678
679			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
680
681			goto end;
682			/* break; */
683
684		default:
685			SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);
686			ret= -1;
687			goto end;
688			/* break; */
689			}
690
691		/* did we do anything */
692		if (!s->s3->tmp.reuse_message && !skip)
693			{
694			if (s->debug)
695				{
696				if ((ret=BIO_flush(s->wbio)) <= 0)
697					goto end;
698				}
699
700			if ((cb != NULL) && (s->state != state))
701				{
702				new_state=s->state;
703				s->state=state;
704				cb(s,SSL_CB_CONNECT_LOOP,1);
705				s->state=new_state;
706				}
707			}
708		skip=0;
709		}
710end:
711	s->in_handshake--;
712	if (buf != NULL)
713		BUF_MEM_free(buf);
714	if (cb != NULL)
715		cb(s,SSL_CB_CONNECT_EXIT,ret);
716	return(ret);
717	}
718
719
720int ssl3_client_hello(SSL *s)
721	{
722	unsigned char *buf;
723	unsigned char *p,*d;
724	int i;
725	unsigned long l;
726#ifndef OPENSSL_NO_COMP
727	int j;
728	SSL_COMP *comp;
729#endif
730
731	buf=(unsigned char *)s->init_buf->data;
732	if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
733		{
734		SSL_SESSION *sess = s->session;
735		if ((sess == NULL) ||
736			(sess->ssl_version != s->version) ||
737#ifdef OPENSSL_NO_TLSEXT
738			!sess->session_id_length ||
739#else
740			(!sess->session_id_length && !sess->tlsext_tick) ||
741#endif
742			(sess->not_resumable))
743			{
744		        if (!s->session_creation_enabled)
745				{
746				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
747				SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED);
748				goto err;
749				}
750			if (!ssl_get_new_session(s,0))
751				goto err;
752			}
753		/* else use the pre-loaded session */
754
755		p=s->s3->client_random;
756
757		if (ssl_fill_hello_random(s, 0, p, SSL3_RANDOM_SIZE) <= 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_auth & SSL_aPSK)
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_a & SSL_aPSK)
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		s->ctx->psk_identity_hint = NULL;
1437		if (i != 0)
1438			{
1439			/* Store PSK identity hint for later use, hint is used
1440			 * in ssl3_send_client_key_exchange.  Assume that the
1441			 * maximum length of a PSK identity hint can be as
1442			 * long as the maximum length of a PSK identity. */
1443			if (i > PSK_MAX_IDENTITY_LEN)
1444				{
1445				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1446					SSL_R_DATA_LENGTH_TOO_LONG);
1447				goto f_err;
1448				}
1449			if (param_len > n)
1450				{
1451				al=SSL_AD_DECODE_ERROR;
1452				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1453					SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
1454				goto f_err;
1455				}
1456			/* If received PSK identity hint contains NULL
1457			 * characters, the hint is truncated from the first
1458			 * NULL. p may not be ending with NULL, so create a
1459			 * NULL-terminated string. */
1460			memcpy(tmp_id_hint, p, i);
1461			memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
1462			if (s->ctx->psk_identity_hint != NULL)
1463				OPENSSL_free(s->ctx->psk_identity_hint);
1464			s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint);
1465			if (s->ctx->psk_identity_hint == NULL)
1466				{
1467				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1468				goto f_err;
1469				}
1470			}
1471		p+=i;
1472		n-=param_len;
1473		}
1474#endif /* !OPENSSL_NO_PSK */
1475
1476	if (0) {}
1477#ifndef OPENSSL_NO_SRP
1478	else if (alg_k & SSL_kSRP)
1479		{
1480		n2s(p,i);
1481		param_len=i+2;
1482		if (param_len > n)
1483			{
1484			al=SSL_AD_DECODE_ERROR;
1485			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH);
1486			goto f_err;
1487			}
1488		if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL)))
1489			{
1490			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1491			goto err;
1492			}
1493		p+=i;
1494
1495		n2s(p,i);
1496		param_len+=i+2;
1497		if (param_len > n)
1498			{
1499			al=SSL_AD_DECODE_ERROR;
1500			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH);
1501			goto f_err;
1502			}
1503		if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL)))
1504			{
1505			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1506			goto err;
1507			}
1508		p+=i;
1509
1510		i = (unsigned int)(p[0]);
1511		p++;
1512		param_len+=i+1;
1513		if (param_len > n)
1514			{
1515			al=SSL_AD_DECODE_ERROR;
1516			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH);
1517			goto f_err;
1518			}
1519		if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL)))
1520			{
1521			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1522			goto err;
1523			}
1524		p+=i;
1525
1526		n2s(p,i);
1527		param_len+=i+2;
1528		if (param_len > n)
1529			{
1530			al=SSL_AD_DECODE_ERROR;
1531			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH);
1532			goto f_err;
1533			}
1534		if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL)))
1535			{
1536			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1537			goto err;
1538			}
1539		p+=i;
1540		n-=param_len;
1541
1542/* We must check if there is a certificate */
1543#ifndef OPENSSL_NO_RSA
1544		if (alg_a & SSL_aRSA)
1545			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1546#else
1547		if (0)
1548			;
1549#endif
1550#ifndef OPENSSL_NO_DSA
1551		else if (alg_a & SSL_aDSS)
1552			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1553#endif
1554		}
1555#endif /* !OPENSSL_NO_SRP */
1556#ifndef OPENSSL_NO_RSA
1557	else if (alg_k & SSL_kRSA)
1558		{
1559		if ((rsa=RSA_new()) == NULL)
1560			{
1561			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1562			goto err;
1563			}
1564		n2s(p,i);
1565		param_len=i+2;
1566		if (param_len > n)
1567			{
1568			al=SSL_AD_DECODE_ERROR;
1569			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
1570			goto f_err;
1571			}
1572		if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
1573			{
1574			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1575			goto err;
1576			}
1577		p+=i;
1578
1579		n2s(p,i);
1580		param_len+=i+2;
1581		if (param_len > n)
1582			{
1583			al=SSL_AD_DECODE_ERROR;
1584			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
1585			goto f_err;
1586			}
1587		if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
1588			{
1589			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1590			goto err;
1591			}
1592		p+=i;
1593		n-=param_len;
1594
1595		/* this should be because we are using an export cipher */
1596		if (alg_a & SSL_aRSA)
1597			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1598		else
1599			{
1600			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1601			goto err;
1602			}
1603		s->session->sess_cert->peer_rsa_tmp=rsa;
1604		rsa=NULL;
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#endif /* !OPENSSL_NO_ECDH */
1787
1788	else if (!(alg_k & SSL_kPSK))
1789		{
1790		al=SSL_AD_UNEXPECTED_MESSAGE;
1791		SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
1792		goto f_err;
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) &&
1899			/* Among PSK ciphers only RSA_PSK needs a public key */
1900			!((alg_a & SSL_aPSK) && !(alg_k & SSL_kRSA)))
1901			{
1902			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1903			goto err;
1904			}
1905		/* still data left over */
1906		if (n != 0)
1907			{
1908			al=SSL_AD_DECODE_ERROR;
1909			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
1910			goto f_err;
1911			}
1912		}
1913	EVP_PKEY_free(pkey);
1914	EVP_MD_CTX_cleanup(&md_ctx);
1915	return(1);
1916f_err:
1917	ssl3_send_alert(s,SSL3_AL_FATAL,al);
1918err:
1919	EVP_PKEY_free(pkey);
1920#ifndef OPENSSL_NO_RSA
1921	if (rsa != NULL)
1922		RSA_free(rsa);
1923#endif
1924#ifndef OPENSSL_NO_DH
1925	if (dh != NULL)
1926		DH_free(dh);
1927#endif
1928#ifndef OPENSSL_NO_ECDH
1929	BN_CTX_free(bn_ctx);
1930	EC_POINT_free(srvr_ecpoint);
1931	if (ecdh != NULL)
1932		EC_KEY_free(ecdh);
1933#endif
1934	EVP_MD_CTX_cleanup(&md_ctx);
1935	return(-1);
1936	}
1937
1938int ssl3_get_certificate_request(SSL *s)
1939	{
1940	int ok,ret=0;
1941	unsigned long n,nc,l;
1942	unsigned int llen, ctype_num,i;
1943	X509_NAME *xn=NULL;
1944	const unsigned char *p,*q;
1945	unsigned char *d;
1946	STACK_OF(X509_NAME) *ca_sk=NULL;
1947
1948	n=s->method->ssl_get_message(s,
1949		SSL3_ST_CR_CERT_REQ_A,
1950		SSL3_ST_CR_CERT_REQ_B,
1951		-1,
1952		s->max_cert_list,
1953		&ok);
1954
1955	if (!ok) return((int)n);
1956
1957	s->s3->tmp.cert_req=0;
1958
1959	if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
1960		{
1961		s->s3->tmp.reuse_message=1;
1962		/* If we get here we don't need any cached handshake records
1963		 * as we wont be doing client auth.
1964		 */
1965		if (s->s3->handshake_buffer)
1966			{
1967			if (!ssl3_digest_cached_records(s))
1968				goto err;
1969			}
1970		return(1);
1971		}
1972
1973	if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
1974		{
1975		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1976		SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE);
1977		goto err;
1978		}
1979
1980	/* TLS does not like anon-DH with client cert */
1981	if (s->version > SSL3_VERSION)
1982		{
1983		if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
1984			{
1985			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1986			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1987			goto err;
1988			}
1989		}
1990
1991	p=d=(unsigned char *)s->init_msg;
1992
1993	if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL)
1994		{
1995		SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1996		goto err;
1997		}
1998
1999	/* get the certificate types */
2000	ctype_num= *(p++);
2001	if (ctype_num > SSL3_CT_NUMBER)
2002		ctype_num=SSL3_CT_NUMBER;
2003	for (i=0; i<ctype_num; i++)
2004		s->s3->tmp.ctype[i]= p[i];
2005	p+=ctype_num;
2006	if (TLS1_get_version(s) >= TLS1_2_VERSION)
2007		{
2008		n2s(p, llen);
2009		/* Check we have enough room for signature algorithms and
2010		 * following length value.
2011		 */
2012		if ((unsigned long)(p - d + llen + 2) > n)
2013			{
2014			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2015			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_DATA_LENGTH_TOO_LONG);
2016			goto err;
2017			}
2018		if (llen & 1)
2019			{
2020			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2021			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2022			goto err;
2023			}
2024		tls1_process_sigalgs(s, p, llen);
2025		p += llen;
2026		}
2027
2028	/* get the CA RDNs */
2029	n2s(p,llen);
2030#if 0
2031{
2032FILE *out;
2033out=fopen("/tmp/vsign.der","w");
2034fwrite(p,1,llen,out);
2035fclose(out);
2036}
2037#endif
2038
2039	if ((unsigned long)(p - d + llen) != n)
2040		{
2041		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2042		SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH);
2043		goto err;
2044		}
2045
2046	for (nc=0; nc<llen; )
2047		{
2048		n2s(p,l);
2049		if ((l+nc+2) > llen)
2050			{
2051			if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2052				goto cont; /* netscape bugs */
2053			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2054			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG);
2055			goto err;
2056			}
2057
2058		q=p;
2059
2060		if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL)
2061			{
2062			/* If netscape tolerance is on, ignore errors */
2063			if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
2064				goto cont;
2065			else
2066				{
2067				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2068				SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB);
2069				goto err;
2070				}
2071			}
2072
2073		if (q != (p+l))
2074			{
2075			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2076			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH);
2077			goto err;
2078			}
2079		if (!sk_X509_NAME_push(ca_sk,xn))
2080			{
2081			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
2082			goto err;
2083			}
2084
2085		p+=l;
2086		nc+=l+2;
2087		}
2088
2089	if (0)
2090		{
2091cont:
2092		ERR_clear_error();
2093		}
2094
2095	/* we should setup a certificate to return.... */
2096	s->s3->tmp.cert_req=1;
2097	s->s3->tmp.ctype_num=ctype_num;
2098	if (s->s3->tmp.ca_names != NULL)
2099		sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
2100	s->s3->tmp.ca_names=ca_sk;
2101	ca_sk=NULL;
2102
2103	ret=1;
2104err:
2105	if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
2106	return(ret);
2107	}
2108
2109static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
2110	{
2111	return(X509_NAME_cmp(*a,*b));
2112	}
2113#ifndef OPENSSL_NO_TLSEXT
2114int ssl3_get_new_session_ticket(SSL *s)
2115	{
2116	int ok,al,ret=0, ticklen;
2117	long n;
2118	const unsigned char *p;
2119	unsigned char *d;
2120
2121	n=s->method->ssl_get_message(s,
2122		SSL3_ST_CR_SESSION_TICKET_A,
2123		SSL3_ST_CR_SESSION_TICKET_B,
2124		-1,
2125		16384,
2126		&ok);
2127
2128	if (!ok)
2129		return((int)n);
2130
2131	if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
2132		{
2133		s->s3->tmp.reuse_message=1;
2134		return(1);
2135		}
2136	if (s->s3->tmp.message_type != SSL3_MT_NEWSESSION_TICKET)
2137		{
2138		al=SSL_AD_UNEXPECTED_MESSAGE;
2139		SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_BAD_MESSAGE_TYPE);
2140		goto f_err;
2141		}
2142	if (n < 6)
2143		{
2144		/* need at least ticket_lifetime_hint + ticket length */
2145		al = SSL_AD_DECODE_ERROR;
2146		SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
2147		goto f_err;
2148		}
2149
2150	p=d=(unsigned char *)s->init_msg;
2151	n2l(p, s->session->tlsext_tick_lifetime_hint);
2152	n2s(p, ticklen);
2153	/* ticket_lifetime_hint + ticket_length + ticket */
2154	if (ticklen + 6 != n)
2155		{
2156		al = SSL_AD_DECODE_ERROR;
2157		SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
2158		goto f_err;
2159		}
2160	if (s->session->tlsext_tick)
2161		{
2162		OPENSSL_free(s->session->tlsext_tick);
2163		s->session->tlsext_ticklen = 0;
2164		}
2165	s->session->tlsext_tick = OPENSSL_malloc(ticklen);
2166	if (!s->session->tlsext_tick)
2167		{
2168		SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,ERR_R_MALLOC_FAILURE);
2169		goto err;
2170		}
2171	memcpy(s->session->tlsext_tick, p, ticklen);
2172	s->session->tlsext_ticklen = ticklen;
2173	/* There are two ways to detect a resumed ticket sesion.
2174	 * One is to set an appropriate session ID and then the server
2175	 * must return a match in ServerHello. This allows the normal
2176	 * client session ID matching to work and we know much
2177	 * earlier that the ticket has been accepted.
2178	 *
2179	 * The other way is to set zero length session ID when the
2180	 * ticket is presented and rely on the handshake to determine
2181	 * session resumption.
2182	 *
2183	 * We choose the former approach because this fits in with
2184	 * assumptions elsewhere in OpenSSL. The session ID is set
2185	 * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
2186	 * ticket.
2187	 */
2188	EVP_Digest(p, ticklen,
2189			s->session->session_id, &s->session->session_id_length,
2190#ifndef OPENSSL_NO_SHA256
2191							EVP_sha256(), NULL);
2192#else
2193							EVP_sha1(), NULL);
2194#endif
2195	ret=1;
2196	return(ret);
2197f_err:
2198	ssl3_send_alert(s,SSL3_AL_FATAL,al);
2199err:
2200	return(-1);
2201	}
2202
2203int ssl3_get_cert_status(SSL *s)
2204	{
2205	int ok, al;
2206	unsigned long resplen,n;
2207	const unsigned char *p;
2208
2209	n=s->method->ssl_get_message(s,
2210		SSL3_ST_CR_CERT_STATUS_A,
2211		SSL3_ST_CR_CERT_STATUS_B,
2212		SSL3_MT_CERTIFICATE_STATUS,
2213		16384,
2214		&ok);
2215
2216	if (!ok) return((int)n);
2217	if (n < 4)
2218		{
2219		/* need at least status type + length */
2220		al = SSL_AD_DECODE_ERROR;
2221		SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
2222		goto f_err;
2223		}
2224	p = (unsigned char *)s->init_msg;
2225	if (*p++ != TLSEXT_STATUSTYPE_ocsp)
2226		{
2227		al = SSL_AD_DECODE_ERROR;
2228		SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_UNSUPPORTED_STATUS_TYPE);
2229		goto f_err;
2230		}
2231	n2l3(p, resplen);
2232	if (resplen + 4 != n)
2233		{
2234		al = SSL_AD_DECODE_ERROR;
2235		SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
2236		goto f_err;
2237		}
2238	if (s->tlsext_ocsp_resp)
2239		OPENSSL_free(s->tlsext_ocsp_resp);
2240	s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
2241	if (!s->tlsext_ocsp_resp)
2242		{
2243		al = SSL_AD_INTERNAL_ERROR;
2244		SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
2245		goto f_err;
2246		}
2247	s->tlsext_ocsp_resplen = resplen;
2248	if (s->ctx->tlsext_status_cb)
2249		{
2250		int ret;
2251		ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2252		if (ret == 0)
2253			{
2254			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2255			SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_INVALID_STATUS_RESPONSE);
2256			goto f_err;
2257			}
2258		if (ret < 0)
2259			{
2260			al = SSL_AD_INTERNAL_ERROR;
2261			SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
2262			goto f_err;
2263			}
2264		}
2265	return 1;
2266f_err:
2267	ssl3_send_alert(s,SSL3_AL_FATAL,al);
2268	return(-1);
2269	}
2270#endif
2271
2272int ssl3_get_server_done(SSL *s)
2273	{
2274	int ok,ret=0;
2275	long n;
2276
2277	n=s->method->ssl_get_message(s,
2278		SSL3_ST_CR_SRVR_DONE_A,
2279		SSL3_ST_CR_SRVR_DONE_B,
2280		SSL3_MT_SERVER_DONE,
2281		30, /* should be very small, like 0 :-) */
2282		&ok);
2283
2284	if (!ok) return((int)n);
2285	if (n > 0)
2286		{
2287		/* should contain no data */
2288		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2289		SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH);
2290		return -1;
2291		}
2292	ret=1;
2293	return(ret);
2294	}
2295
2296
2297int ssl3_send_client_key_exchange(SSL *s)
2298	{
2299	unsigned char *p,*d;
2300	int n;
2301	unsigned long alg_k;
2302	unsigned long alg_a;
2303#ifndef OPENSSL_NO_RSA
2304	unsigned char *q;
2305	EVP_PKEY *pkey=NULL;
2306#endif
2307#ifndef OPENSSL_NO_KRB5
2308	KSSL_ERR kssl_err;
2309#endif /* OPENSSL_NO_KRB5 */
2310#ifndef OPENSSL_NO_ECDH
2311	EC_KEY *clnt_ecdh = NULL;
2312	const EC_POINT *srvr_ecpoint = NULL;
2313	EVP_PKEY *srvr_pub_pkey = NULL;
2314	unsigned char *encodedPoint = NULL;
2315	int encoded_pt_len = 0;
2316	BN_CTX * bn_ctx = NULL;
2317#ifndef OPENSSL_NO_PSK
2318	unsigned int psk_len = 0;
2319	unsigned char psk[PSK_MAX_PSK_LEN];
2320#endif /* OPENSSL_NO_PSK */
2321#endif /* OPENSSL_NO_ECDH */
2322
2323	if (s->state == SSL3_ST_CW_KEY_EXCH_A)
2324		{
2325		d=(unsigned char *)s->init_buf->data;
2326		p= &(d[4]);
2327
2328		alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2329		alg_a=s->s3->tmp.new_cipher->algorithm_auth;
2330
2331#ifndef OPENSSL_NO_PSK
2332		if (alg_a & SSL_aPSK)
2333			{
2334			char identity[PSK_MAX_IDENTITY_LEN];
2335			unsigned char *t = NULL;
2336			unsigned char pre_ms[PSK_MAX_PSK_LEN*2+4];
2337			unsigned int pre_ms_len = 0;
2338			int psk_err = 1;
2339
2340			n = 0;
2341			if (s->psk_client_callback == NULL)
2342				{
2343				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2344					SSL_R_PSK_NO_CLIENT_CB);
2345				goto err;
2346				}
2347
2348			psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
2349				identity, PSK_MAX_IDENTITY_LEN, psk, sizeof(psk));
2350			if (psk_len > PSK_MAX_PSK_LEN)
2351				{
2352				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2353					ERR_R_INTERNAL_ERROR);
2354				goto psk_err;
2355				}
2356			else if (psk_len == 0)
2357				{
2358				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2359					SSL_R_PSK_IDENTITY_NOT_FOUND);
2360				goto psk_err;
2361				}
2362
2363			if (!(alg_k & SSL_kEECDH))
2364				{
2365				/* Create the shared secret now if we're not using ECDHE-PSK.*/
2366				pre_ms_len = 2+psk_len+2+psk_len;
2367				t = pre_ms;
2368				s2n(psk_len, t);
2369				memset(t, 0, psk_len);
2370				t+=psk_len;
2371				s2n(psk_len, t);
2372				memcpy(t, psk, psk_len);
2373
2374				s->session->master_key_length =
2375					s->method->ssl3_enc->generate_master_secret(s,
2376						s->session->master_key,
2377						pre_ms, pre_ms_len);
2378				n = strlen(identity);
2379				s2n(n, p);
2380				memcpy(p, identity, n);
2381				n += 2;
2382				}
2383
2384			if (s->session->psk_identity_hint != NULL)
2385				OPENSSL_free(s->session->psk_identity_hint);
2386			s->session->psk_identity_hint = NULL;
2387			if (s->ctx->psk_identity_hint)
2388				{
2389				s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2390				if (s->ctx->psk_identity_hint != NULL &&
2391					s->session->psk_identity_hint == NULL)
2392					{
2393					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2394						ERR_R_MALLOC_FAILURE);
2395					goto psk_err;
2396					}
2397				}
2398
2399			if (s->session->psk_identity != NULL)
2400				OPENSSL_free(s->session->psk_identity);
2401			s->session->psk_identity = BUF_strdup(identity);
2402			if (s->session->psk_identity == NULL)
2403				{
2404				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2405					ERR_R_MALLOC_FAILURE);
2406				goto psk_err;
2407				}
2408			psk_err = 0;
2409		psk_err:
2410			OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN);
2411			OPENSSL_cleanse(pre_ms, sizeof(pre_ms));
2412			if (psk_err != 0)
2413				{
2414				ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2415				goto err;
2416				}
2417			}
2418#endif
2419		/* Fool emacs indentation */
2420		if (0) {}
2421#ifndef OPENSSL_NO_RSA
2422		else if (alg_k & SSL_kRSA)
2423			{
2424			RSA *rsa;
2425			unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2426
2427			if (s->session->sess_cert->peer_rsa_tmp != NULL)
2428				rsa=s->session->sess_cert->peer_rsa_tmp;
2429			else
2430				{
2431				pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
2432				if ((pkey == NULL) ||
2433					(pkey->type != EVP_PKEY_RSA) ||
2434					(pkey->pkey.rsa == NULL))
2435					{
2436					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2437					goto err;
2438					}
2439				rsa=pkey->pkey.rsa;
2440				EVP_PKEY_free(pkey);
2441				}
2442
2443			tmp_buf[0]=s->client_version>>8;
2444			tmp_buf[1]=s->client_version&0xff;
2445			if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
2446					goto err;
2447
2448			s->session->master_key_length=sizeof tmp_buf;
2449
2450			q=p;
2451			/* Fix buf for TLS and beyond */
2452			if (s->version > SSL3_VERSION)
2453				p+=2;
2454			n=RSA_public_encrypt(sizeof tmp_buf,
2455				tmp_buf,p,rsa,RSA_PKCS1_PADDING);
2456#ifdef PKCS1_CHECK
2457			if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
2458			if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
2459#endif
2460			if (n <= 0)
2461				{
2462				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
2463				goto err;
2464				}
2465
2466			/* Fix buf for TLS and beyond */
2467			if (s->version > SSL3_VERSION)
2468				{
2469				s2n(n,q);
2470				n+=2;
2471				}
2472
2473			s->session->master_key_length=
2474				s->method->ssl3_enc->generate_master_secret(s,
2475					s->session->master_key,
2476					tmp_buf,sizeof tmp_buf);
2477			OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
2478			}
2479#endif
2480#ifndef OPENSSL_NO_KRB5
2481		else if (alg_k & SSL_kKRB5)
2482			{
2483			krb5_error_code	krb5rc;
2484			KSSL_CTX	*kssl_ctx = s->kssl_ctx;
2485			/*  krb5_data	krb5_ap_req;  */
2486			krb5_data	*enc_ticket;
2487			krb5_data	authenticator, *authp = NULL;
2488			EVP_CIPHER_CTX	ciph_ctx;
2489			const EVP_CIPHER *enc = NULL;
2490			unsigned char	iv[EVP_MAX_IV_LENGTH];
2491			unsigned char	tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2492			unsigned char	epms[SSL_MAX_MASTER_KEY_LENGTH
2493						+ EVP_MAX_IV_LENGTH];
2494			int 		padl, outl = sizeof(epms);
2495
2496			EVP_CIPHER_CTX_init(&ciph_ctx);
2497
2498#ifdef KSSL_DEBUG
2499			printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
2500				alg_k, SSL_kKRB5);
2501#endif	/* KSSL_DEBUG */
2502
2503			authp = NULL;
2504#ifdef KRB5SENDAUTH
2505			if (KRB5SENDAUTH)  authp = &authenticator;
2506#endif	/* KRB5SENDAUTH */
2507
2508			krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
2509				&kssl_err);
2510			enc = kssl_map_enc(kssl_ctx->enctype);
2511			if (enc == NULL)
2512			    goto err;
2513#ifdef KSSL_DEBUG
2514			{
2515			printf("kssl_cget_tkt rtn %d\n", krb5rc);
2516			if (krb5rc && kssl_err.text)
2517			  printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
2518			}
2519#endif	/* KSSL_DEBUG */
2520
2521			if (krb5rc)
2522				{
2523				ssl3_send_alert(s,SSL3_AL_FATAL,
2524						SSL_AD_HANDSHAKE_FAILURE);
2525				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2526						kssl_err.reason);
2527				goto err;
2528				}
2529
2530			/*  20010406 VRS - Earlier versions used KRB5 AP_REQ
2531			**  in place of RFC 2712 KerberosWrapper, as in:
2532			**
2533			**  Send ticket (copy to *p, set n = length)
2534			**  n = krb5_ap_req.length;
2535			**  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
2536			**  if (krb5_ap_req.data)
2537			**    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
2538			**
2539			**  Now using real RFC 2712 KerberosWrapper
2540			**  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
2541			**  Note: 2712 "opaque" types are here replaced
2542			**  with a 2-byte length followed by the value.
2543			**  Example:
2544			**  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
2545			**  Where "xx xx" = length bytes.  Shown here with
2546			**  optional authenticator omitted.
2547			*/
2548
2549			/*  KerberosWrapper.Ticket		*/
2550			s2n(enc_ticket->length,p);
2551			memcpy(p, enc_ticket->data, enc_ticket->length);
2552			p+= enc_ticket->length;
2553			n = enc_ticket->length + 2;
2554
2555			/*  KerberosWrapper.Authenticator	*/
2556			if (authp  &&  authp->length)
2557				{
2558				s2n(authp->length,p);
2559				memcpy(p, authp->data, authp->length);
2560				p+= authp->length;
2561				n+= authp->length + 2;
2562
2563				free(authp->data);
2564				authp->data = NULL;
2565				authp->length = 0;
2566				}
2567			else
2568				{
2569				s2n(0,p);/*  null authenticator length	*/
2570				n+=2;
2571				}
2572
2573			    tmp_buf[0]=s->client_version>>8;
2574			    tmp_buf[1]=s->client_version&0xff;
2575			    if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
2576				goto err;
2577
2578			/*  20010420 VRS.  Tried it this way; failed.
2579			**	EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
2580			**	EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
2581			**				kssl_ctx->length);
2582			**	EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
2583			*/
2584
2585			memset(iv, 0, sizeof iv);  /* per RFC 1510 */
2586			EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
2587				kssl_ctx->key,iv);
2588			EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
2589				sizeof tmp_buf);
2590			EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
2591			outl += padl;
2592			if (outl > (int)sizeof epms)
2593				{
2594				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2595				goto err;
2596				}
2597			EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2598
2599			/*  KerberosWrapper.EncryptedPreMasterSecret	*/
2600			s2n(outl,p);
2601			memcpy(p, epms, outl);
2602			p+=outl;
2603			n+=outl + 2;
2604
2605			s->session->master_key_length=
2606				s->method->ssl3_enc->generate_master_secret(s,
2607					s->session->master_key,
2608					tmp_buf, sizeof tmp_buf);
2609
2610			OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2611			OPENSSL_cleanse(epms, outl);
2612			}
2613#endif
2614#ifndef OPENSSL_NO_DH
2615		else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2616			{
2617			DH *dh_srvr,*dh_clnt;
2618
2619			if (s->session->sess_cert == NULL)
2620				{
2621				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2622				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
2623				goto err;
2624				}
2625
2626			if (s->session->sess_cert->peer_dh_tmp != NULL)
2627				dh_srvr=s->session->sess_cert->peer_dh_tmp;
2628			else
2629				{
2630				/* we get them from the cert */
2631				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
2632				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2633				goto err;
2634				}
2635
2636			/* generate a new random key */
2637			if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
2638				{
2639				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2640				goto err;
2641				}
2642			if (!DH_generate_key(dh_clnt))
2643				{
2644				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2645				DH_free(dh_clnt);
2646				goto err;
2647				}
2648
2649			/* use the 'p' output buffer for the DH key, but
2650			 * make sure to clear it out afterwards */
2651
2652			n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
2653
2654			if (n <= 0)
2655				{
2656				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2657				DH_free(dh_clnt);
2658				goto err;
2659				}
2660
2661			/* generate master key from the result */
2662			s->session->master_key_length=
2663				s->method->ssl3_enc->generate_master_secret(s,
2664					s->session->master_key,p,n);
2665			/* clean up */
2666			memset(p,0,n);
2667
2668			/* send off the data */
2669			n=BN_num_bytes(dh_clnt->pub_key);
2670			s2n(n,p);
2671			BN_bn2bin(dh_clnt->pub_key,p);
2672			n+=2;
2673
2674			DH_free(dh_clnt);
2675
2676			/* perhaps clean things up a bit EAY EAY EAY EAY*/
2677			}
2678#endif
2679#ifndef OPENSSL_NO_ECDH
2680		else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
2681			{
2682			const EC_GROUP *srvr_group = NULL;
2683			EC_KEY *tkey;
2684			int ecdh_clnt_cert = 0;
2685			int field_size = 0;
2686#ifndef OPENSSL_NO_PSK
2687			unsigned char *pre_ms;
2688			unsigned char *t;
2689			unsigned int pre_ms_len;
2690			unsigned int i;
2691#endif
2692
2693			/* Did we send out the client's
2694			 * ECDH share for use in premaster
2695			 * computation as part of client certificate?
2696			 * If so, set ecdh_clnt_cert to 1.
2697			 */
2698			if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL))
2699				{
2700				/* XXX: For now, we do not support client
2701				 * authentication using ECDH certificates.
2702				 * To add such support, one needs to add
2703				 * code that checks for appropriate
2704				 * conditions and sets ecdh_clnt_cert to 1.
2705				 * For example, the cert have an ECC
2706				 * key on the same curve as the server's
2707				 * and the key should be authorized for
2708				 * key agreement.
2709				 *
2710				 * One also needs to add code in ssl3_connect
2711				 * to skip sending the certificate verify
2712				 * message.
2713				 *
2714				 * if ((s->cert->key->privatekey != NULL) &&
2715				 *     (s->cert->key->privatekey->type ==
2716				 *      EVP_PKEY_EC) && ...)
2717				 * ecdh_clnt_cert = 1;
2718				 */
2719				}
2720
2721			if (s->session->sess_cert->peer_ecdh_tmp != NULL)
2722				{
2723				tkey = s->session->sess_cert->peer_ecdh_tmp;
2724				}
2725			else
2726				{
2727				/* Get the Server Public Key from Cert */
2728				srvr_pub_pkey = X509_get_pubkey(s->session-> \
2729				    sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
2730				if ((srvr_pub_pkey == NULL) ||
2731				    (srvr_pub_pkey->type != EVP_PKEY_EC) ||
2732				    (srvr_pub_pkey->pkey.ec == NULL))
2733					{
2734					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2735					    ERR_R_INTERNAL_ERROR);
2736					goto err;
2737					}
2738
2739				tkey = srvr_pub_pkey->pkey.ec;
2740				}
2741
2742			srvr_group   = EC_KEY_get0_group(tkey);
2743			srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2744
2745			if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
2746				{
2747				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2748				    ERR_R_INTERNAL_ERROR);
2749				goto err;
2750				}
2751
2752			if ((clnt_ecdh=EC_KEY_new()) == NULL)
2753				{
2754				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2755				goto err;
2756				}
2757
2758			if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
2759				{
2760				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2761				goto err;
2762				}
2763			if (ecdh_clnt_cert)
2764				{
2765				/* Reuse key info from our certificate
2766				 * We only need our private key to perform
2767				 * the ECDH computation.
2768				 */
2769				const BIGNUM *priv_key;
2770				tkey = s->cert->key->privatekey->pkey.ec;
2771				priv_key = EC_KEY_get0_private_key(tkey);
2772				if (priv_key == NULL)
2773					{
2774					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2775					goto err;
2776					}
2777				if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
2778					{
2779					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2780					goto err;
2781					}
2782				}
2783			else
2784				{
2785				/* Generate a new ECDH key pair */
2786				if (!(EC_KEY_generate_key(clnt_ecdh)))
2787					{
2788					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2789					goto err;
2790					}
2791				}
2792
2793			/* use the 'p' output buffer for the ECDH key, but
2794			 * make sure to clear it out afterwards
2795			 */
2796
2797			field_size = EC_GROUP_get_degree(srvr_group);
2798			if (field_size <= 0)
2799				{
2800				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2801				       ERR_R_ECDH_LIB);
2802				goto err;
2803				}
2804			n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
2805			if (n <= 0)
2806				{
2807				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2808				       ERR_R_ECDH_LIB);
2809				goto err;
2810				}
2811
2812#ifndef OPENSSL_NO_PSK
2813			/* ECDHE PSK ciphersuites from RFC 5489 */
2814			if ((alg_a & SSL_aPSK) && psk_len != 0)
2815				{
2816				pre_ms_len = 2+psk_len+2+n;
2817				pre_ms = OPENSSL_malloc(pre_ms_len);
2818				if (pre_ms == NULL)
2819					{
2820					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2821			    		ERR_R_MALLOC_FAILURE);
2822					goto err;
2823					}
2824				memset(pre_ms, 0, pre_ms_len);
2825				t = pre_ms;
2826				s2n(psk_len, t);
2827				memcpy(t, psk, psk_len);
2828				t += psk_len;
2829				s2n(n, t);
2830				memcpy(t, p, n);
2831				s->session->master_key_length = s->method->ssl3_enc \
2832					-> generate_master_secret(s,
2833						s->session->master_key, pre_ms, pre_ms_len);
2834				OPENSSL_cleanse(pre_ms, pre_ms_len);
2835				OPENSSL_free(pre_ms);
2836				}
2837#endif /* OPENSSL_NO_PSK */
2838			if (!(alg_a & SSL_aPSK))
2839				{
2840				/* generate master key from the result */
2841				s->session->master_key_length = s->method->ssl3_enc \
2842					-> generate_master_secret(s,
2843						s->session->master_key, p, n);
2844				}
2845			memset(p, 0, n); /* clean up */
2846			if (ecdh_clnt_cert)
2847				{
2848				/* Send empty client key exch message */
2849				n = 0;
2850				}
2851			else
2852				{
2853				/* First check the size of encoding and
2854				 * allocate memory accordingly.
2855				 */
2856				encoded_pt_len =
2857				    EC_POINT_point2oct(srvr_group,
2858					EC_KEY_get0_public_key(clnt_ecdh),
2859					POINT_CONVERSION_UNCOMPRESSED,
2860					NULL, 0, NULL);
2861
2862				encodedPoint = (unsigned char *)
2863				    OPENSSL_malloc(encoded_pt_len *
2864					sizeof(unsigned char));
2865				bn_ctx = BN_CTX_new();
2866				if ((encodedPoint == NULL) ||
2867				    (bn_ctx == NULL))
2868					{
2869					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2870					goto err;
2871					}
2872
2873				/* Encode the public key */
2874				encoded_pt_len = EC_POINT_point2oct(srvr_group,
2875				    EC_KEY_get0_public_key(clnt_ecdh),
2876				    POINT_CONVERSION_UNCOMPRESSED,
2877				    encodedPoint, encoded_pt_len, bn_ctx);
2878
2879				n = 0;
2880#ifndef OPENSSL_NO_PSK
2881				if ((alg_a & SSL_aPSK) && psk_len != 0)
2882					{
2883					i = strlen(s->session->psk_identity);
2884					s2n(i, p);
2885					memcpy(p, s->session->psk_identity, i);
2886					p += i;
2887					n = i + 2;
2888					}
2889#endif
2890
2891				*p = encoded_pt_len; /* length of encoded point */
2892				/* Encoded point will be copied here */
2893				p += 1;
2894				n += 1;
2895				/* copy the point */
2896				memcpy((unsigned char *)p, encodedPoint, encoded_pt_len);
2897				/* increment n to account for length field */
2898				n += encoded_pt_len;
2899				}
2900
2901			/* Free allocated memory */
2902			BN_CTX_free(bn_ctx);
2903			if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2904			if (clnt_ecdh != NULL)
2905				 EC_KEY_free(clnt_ecdh);
2906			EVP_PKEY_free(srvr_pub_pkey);
2907			}
2908#endif /* !OPENSSL_NO_ECDH */
2909		else if (alg_k & SSL_kGOST)
2910			{
2911			/* GOST key exchange message creation */
2912			EVP_PKEY_CTX *pkey_ctx;
2913			X509 *peer_cert;
2914			size_t msglen;
2915			unsigned int md_len;
2916			int keytype;
2917			unsigned char premaster_secret[32],shared_ukm[32], tmp[256];
2918			EVP_MD_CTX *ukm_hash;
2919			EVP_PKEY *pub_key;
2920
2921			/* Get server sertificate PKEY and create ctx from it */
2922			peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST01)].x509;
2923			if (!peer_cert)
2924				peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST94)].x509;
2925			if (!peer_cert)		{
2926					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2927					goto err;
2928				}
2929
2930			pkey_ctx=EVP_PKEY_CTX_new(pub_key=X509_get_pubkey(peer_cert),NULL);
2931			/* If we have send a certificate, and certificate key
2932
2933			 * parameters match those of server certificate, use
2934			 * certificate key for key exchange
2935			 */
2936
2937			 /* Otherwise, generate ephemeral key pair */
2938
2939			EVP_PKEY_encrypt_init(pkey_ctx);
2940			  /* Generate session key */
2941		    RAND_bytes(premaster_secret,32);
2942			/* If we have client certificate, use its secret as peer key */
2943			if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2944				if (EVP_PKEY_derive_set_peer(pkey_ctx,s->cert->key->privatekey) <=0) {
2945					/* If there was an error - just ignore it. Ephemeral key
2946					* would be used
2947					*/
2948					ERR_clear_error();
2949				}
2950			}
2951			/* Compute shared IV and store it in algorithm-specific
2952			 * context data */
2953			ukm_hash = EVP_MD_CTX_create();
2954			EVP_DigestInit(ukm_hash,EVP_get_digestbynid(NID_id_GostR3411_94));
2955			EVP_DigestUpdate(ukm_hash,s->s3->client_random,SSL3_RANDOM_SIZE);
2956			EVP_DigestUpdate(ukm_hash,s->s3->server_random,SSL3_RANDOM_SIZE);
2957			EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2958			EVP_MD_CTX_destroy(ukm_hash);
2959			if (EVP_PKEY_CTX_ctrl(pkey_ctx,-1,EVP_PKEY_OP_ENCRYPT,EVP_PKEY_CTRL_SET_IV,
2960				8,shared_ukm)<0) {
2961					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2962						SSL_R_LIBRARY_BUG);
2963					goto err;
2964				}
2965			/* Make GOST keytransport blob message */
2966			/*Encapsulate it into sequence */
2967			*(p++)=V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2968			msglen=255;
2969			if (EVP_PKEY_encrypt(pkey_ctx,tmp,&msglen,premaster_secret,32)<0) {
2970			SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2971					SSL_R_LIBRARY_BUG);
2972				goto err;
2973			}
2974			if (msglen >= 0x80)
2975				{
2976				*(p++)=0x81;
2977				*(p++)= msglen & 0xff;
2978				n=msglen+3;
2979				}
2980			else
2981				{
2982				*(p++)= msglen & 0xff;
2983				n=msglen+2;
2984				}
2985			memcpy(p, tmp, msglen);
2986			/* Check if pubkey from client certificate was used */
2987			if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2988				{
2989				/* Set flag "skip certificate verify" */
2990				s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2991				}
2992			EVP_PKEY_CTX_free(pkey_ctx);
2993			s->session->master_key_length=
2994				s->method->ssl3_enc->generate_master_secret(s,
2995					s->session->master_key,premaster_secret,32);
2996			EVP_PKEY_free(pub_key);
2997
2998			}
2999#ifndef OPENSSL_NO_SRP
3000		else if (alg_k & SSL_kSRP)
3001			{
3002			if (s->srp_ctx.A != NULL)
3003				{
3004				/* send off the data */
3005				n=BN_num_bytes(s->srp_ctx.A);
3006				s2n(n,p);
3007				BN_bn2bin(s->srp_ctx.A,p);
3008				n+=2;
3009				}
3010			else
3011				{
3012				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
3013				goto err;
3014				}
3015			if (s->session->srp_username != NULL)
3016				OPENSSL_free(s->session->srp_username);
3017			s->session->srp_username = BUF_strdup(s->srp_ctx.login);
3018			if (s->session->srp_username == NULL)
3019				{
3020				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3021					ERR_R_MALLOC_FAILURE);
3022				goto err;
3023				}
3024
3025			if ((s->session->master_key_length = SRP_generate_client_master_secret(s,s->session->master_key))<0)
3026				{
3027				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
3028				goto err;
3029				}
3030			}
3031#endif
3032		else if (!(alg_k & SSL_kPSK))
3033			{
3034			ssl3_send_alert(s, SSL3_AL_FATAL,
3035			    SSL_AD_HANDSHAKE_FAILURE);
3036			SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3037			    ERR_R_INTERNAL_ERROR);
3038			goto err;
3039			}
3040
3041		*(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
3042		l2n3(n,d);
3043
3044		s->state=SSL3_ST_CW_KEY_EXCH_B;
3045		/* number of bytes to write */
3046		s->init_num=n+4;
3047		s->init_off=0;
3048		}
3049
3050	/* SSL3_ST_CW_KEY_EXCH_B */
3051	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3052err:
3053#ifndef OPENSSL_NO_ECDH
3054	BN_CTX_free(bn_ctx);
3055	if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
3056	if (clnt_ecdh != NULL)
3057		EC_KEY_free(clnt_ecdh);
3058	EVP_PKEY_free(srvr_pub_pkey);
3059#endif
3060	return(-1);
3061	}
3062
3063int ssl3_send_client_verify(SSL *s)
3064	{
3065	unsigned char *p,*d;
3066	unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
3067	EVP_PKEY *pkey;
3068	EVP_PKEY_CTX *pctx=NULL;
3069	EVP_MD_CTX mctx;
3070	unsigned u=0;
3071	unsigned long n;
3072	int j;
3073
3074	EVP_MD_CTX_init(&mctx);
3075
3076	if (s->state == SSL3_ST_CW_CERT_VRFY_A)
3077		{
3078		d=(unsigned char *)s->init_buf->data;
3079		p= &(d[4]);
3080		pkey=s->cert->key->privatekey;
3081/* Create context from key and test if sha1 is allowed as digest */
3082		pctx = EVP_PKEY_CTX_new(pkey,NULL);
3083		EVP_PKEY_sign_init(pctx);
3084		if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1())>0)
3085			{
3086			if (TLS1_get_version(s) < TLS1_2_VERSION)
3087				s->method->ssl3_enc->cert_verify_mac(s,
3088						NID_sha1,
3089						&(data[MD5_DIGEST_LENGTH]));
3090			}
3091		else
3092			{
3093			ERR_clear_error();
3094			}
3095		/* For TLS v1.2 send signature algorithm and signature
3096		 * using agreed digest and cached handshake records.
3097		 */
3098		if (TLS1_get_version(s) >= TLS1_2_VERSION)
3099			{
3100			long hdatalen = 0;
3101			void *hdata;
3102			const EVP_MD *md;
3103			switch (ssl_cert_type(NULL, pkey))
3104				{
3105			case SSL_PKEY_RSA_ENC:
3106				md = s->s3->digest_rsa;
3107				break;
3108			case SSL_PKEY_DSA_SIGN:
3109				md = s->s3->digest_dsa;
3110				break;
3111			case SSL_PKEY_ECC:
3112				md = s->s3->digest_ecdsa;
3113				break;
3114			default:
3115				md = NULL;
3116				}
3117			if (!md)
3118				/* Unlike with the SignatureAlgorithm extension (sent by clients),
3119				 * there are no default algorithms for the CertificateRequest message
3120				 * (sent by servers). However, now that we've sent a certificate
3121				 * for which we don't really know what hash to use for signing, the
3122				 * best we can do is try a default algorithm. */
3123				md = EVP_sha1();
3124			hdatalen = BIO_get_mem_data(s->s3->handshake_buffer,
3125								&hdata);
3126			if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md))
3127				{
3128				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
3129						ERR_R_INTERNAL_ERROR);
3130				goto err;
3131				}
3132			p += 2;
3133#ifdef SSL_DEBUG
3134			fprintf(stderr, "Using TLS 1.2 with client alg %s\n",
3135							EVP_MD_name(md));
3136#endif
3137			if (!EVP_SignInit_ex(&mctx, md, NULL)
3138				|| !EVP_SignUpdate(&mctx, hdata, hdatalen)
3139				|| !EVP_SignFinal(&mctx, p + 2, &u, pkey))
3140				{
3141				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
3142						ERR_R_EVP_LIB);
3143				goto err;
3144				}
3145			s2n(u,p);
3146			n = u + 4;
3147			if (!ssl3_digest_cached_records(s))
3148				goto err;
3149			}
3150		else
3151#ifndef OPENSSL_NO_RSA
3152		if (pkey->type == EVP_PKEY_RSA)
3153			{
3154			s->method->ssl3_enc->cert_verify_mac(s,
3155				NID_md5,
3156			 	&(data[0]));
3157			if (RSA_sign(NID_md5_sha1, data,
3158					 MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
3159					&(p[2]), &u, pkey->pkey.rsa) <= 0 )
3160				{
3161				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
3162				goto err;
3163				}
3164			s2n(u,p);
3165			n=u+2;
3166			}
3167		else
3168#endif
3169#ifndef OPENSSL_NO_DSA
3170			if (pkey->type == EVP_PKEY_DSA)
3171			{
3172			if (!DSA_sign(pkey->save_type,
3173				&(data[MD5_DIGEST_LENGTH]),
3174				SHA_DIGEST_LENGTH,&(p[2]),
3175				(unsigned int *)&j,pkey->pkey.dsa))
3176				{
3177				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
3178				goto err;
3179				}
3180			s2n(j,p);
3181			n=j+2;
3182			}
3183		else
3184#endif
3185#ifndef OPENSSL_NO_ECDSA
3186			if (pkey->type == EVP_PKEY_EC)
3187			{
3188			if (!ECDSA_sign(pkey->save_type,
3189				&(data[MD5_DIGEST_LENGTH]),
3190				SHA_DIGEST_LENGTH,&(p[2]),
3191				(unsigned int *)&j,pkey->pkey.ec))
3192				{
3193				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
3194				    ERR_R_ECDSA_LIB);
3195				goto err;
3196				}
3197			s2n(j,p);
3198			n=j+2;
3199			}
3200		else
3201#endif
3202		if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
3203		{
3204		unsigned char signbuf[64];
3205		int i;
3206		size_t sigsize=64;
3207		s->method->ssl3_enc->cert_verify_mac(s,
3208			NID_id_GostR3411_94,
3209			data);
3210		if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {
3211			SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
3212			ERR_R_INTERNAL_ERROR);
3213			goto err;
3214		}
3215		for (i=63,j=0; i>=0; j++, i--) {
3216			p[2+j]=signbuf[i];
3217		}
3218		s2n(j,p);
3219		n=j+2;
3220		}
3221		else
3222		{
3223			SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
3224			goto err;
3225		}
3226		*(d++)=SSL3_MT_CERTIFICATE_VERIFY;
3227		l2n3(n,d);
3228
3229		s->state=SSL3_ST_CW_CERT_VRFY_B;
3230		s->init_num=(int)n+4;
3231		s->init_off=0;
3232		}
3233	EVP_MD_CTX_cleanup(&mctx);
3234	EVP_PKEY_CTX_free(pctx);
3235	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3236err:
3237	EVP_MD_CTX_cleanup(&mctx);
3238	EVP_PKEY_CTX_free(pctx);
3239	return(-1);
3240	}
3241
3242int ssl3_send_client_certificate(SSL *s)
3243	{
3244	X509 *x509=NULL;
3245	EVP_PKEY *pkey=NULL;
3246	int i;
3247	unsigned long l;
3248
3249	if (s->state ==	SSL3_ST_CW_CERT_A)
3250		{
3251		if ((s->cert == NULL) ||
3252			(s->cert->key->x509 == NULL) ||
3253			(s->cert->key->privatekey == NULL))
3254			s->state=SSL3_ST_CW_CERT_B;
3255		else
3256			s->state=SSL3_ST_CW_CERT_C;
3257		}
3258
3259	/* We need to get a client cert */
3260	if (s->state == SSL3_ST_CW_CERT_B)
3261		{
3262		/* If we get an error, we need to
3263		 * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
3264		 * We then get retied later */
3265		i=0;
3266		i = ssl_do_client_cert_cb(s, &x509, &pkey);
3267		if (i < 0)
3268			{
3269			s->rwstate=SSL_X509_LOOKUP;
3270			return(-1);
3271			}
3272		s->rwstate=SSL_NOTHING;
3273		if ((i == 1) && (pkey != NULL) && (x509 != NULL))
3274			{
3275			s->state=SSL3_ST_CW_CERT_B;
3276			if (	!SSL_use_certificate(s,x509) ||
3277				!SSL_use_PrivateKey(s,pkey))
3278				i=0;
3279			}
3280		else if (i == 1)
3281			{
3282			i=0;
3283			SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
3284			}
3285
3286		if (x509 != NULL) X509_free(x509);
3287		if (pkey != NULL) EVP_PKEY_free(pkey);
3288		if (i == 0)
3289			{
3290			if (s->version == SSL3_VERSION)
3291				{
3292				s->s3->tmp.cert_req=0;
3293				ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
3294				return(1);
3295				}
3296			else
3297				{
3298				s->s3->tmp.cert_req=2;
3299				}
3300			}
3301
3302		/* Ok, we have a cert */
3303		s->state=SSL3_ST_CW_CERT_C;
3304		}
3305
3306	if (s->state == SSL3_ST_CW_CERT_C)
3307		{
3308		s->state=SSL3_ST_CW_CERT_D;
3309		l=ssl3_output_cert_chain(s,
3310			(s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
3311		s->init_num=(int)l;
3312		s->init_off=0;
3313		}
3314	/* SSL3_ST_CW_CERT_D */
3315	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3316	}
3317
3318#define has_bits(i,m)	(((i)&(m)) == (m))
3319
3320int ssl3_check_cert_and_algorithm(SSL *s)
3321	{
3322	int i,idx;
3323	long alg_k,alg_a;
3324	EVP_PKEY *pkey=NULL;
3325	SESS_CERT *sc;
3326#ifndef OPENSSL_NO_RSA
3327	RSA *rsa;
3328#endif
3329#ifndef OPENSSL_NO_DH
3330	DH *dh;
3331#endif
3332
3333	alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
3334	alg_a=s->s3->tmp.new_cipher->algorithm_auth;
3335
3336	/* we don't have a certificate */
3337	if ((alg_a & (SSL_aDH|SSL_aNULL|SSL_aKRB5)) || ((alg_a & SSL_aPSK) && !(alg_k & SSL_kRSA)))
3338		return(1);
3339
3340	sc=s->session->sess_cert;
3341	if (sc == NULL)
3342		{
3343		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR);
3344		goto err;
3345		}
3346
3347#ifndef OPENSSL_NO_RSA
3348	rsa=s->session->sess_cert->peer_rsa_tmp;
3349#endif
3350#ifndef OPENSSL_NO_DH
3351	dh=s->session->sess_cert->peer_dh_tmp;
3352#endif
3353
3354	/* This is the passed certificate */
3355
3356	idx=sc->peer_cert_type;
3357#ifndef OPENSSL_NO_ECDH
3358	if (idx == SSL_PKEY_ECC)
3359		{
3360		if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509,
3361		    						s) == 0)
3362			{ /* check failed */
3363			SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT);
3364			goto f_err;
3365			}
3366		else
3367			{
3368			return 1;
3369			}
3370		}
3371#endif
3372	pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
3373	i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
3374	EVP_PKEY_free(pkey);
3375
3376
3377	/* Check that we have a certificate if we require one */
3378	if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
3379		{
3380		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT);
3381		goto f_err;
3382		}
3383#ifndef OPENSSL_NO_DSA
3384	else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN))
3385		{
3386		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT);
3387		goto f_err;
3388		}
3389#endif
3390#ifndef OPENSSL_NO_RSA
3391	if ((alg_k & SSL_kRSA) &&
3392		!(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
3393		{
3394		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3395		goto f_err;
3396		}
3397#endif
3398#ifndef OPENSSL_NO_DH
3399	if ((alg_k & SSL_kEDH) &&
3400		!(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
3401		{
3402		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY);
3403		goto f_err;
3404		}
3405	else if ((alg_k & SSL_kDHr) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA))
3406		{
3407		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT);
3408		goto f_err;
3409		}
3410#ifndef OPENSSL_NO_DSA
3411	else if ((alg_k & SSL_kDHd) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA))
3412		{
3413		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT);
3414		goto f_err;
3415		}
3416#endif
3417#endif
3418
3419	if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP))
3420		{
3421#ifndef OPENSSL_NO_RSA
3422		if (alg_k & SSL_kRSA)
3423			{
3424			if (rsa == NULL
3425			    || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
3426				{
3427				SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3428				goto f_err;
3429				}
3430			}
3431		else
3432#endif
3433#ifndef OPENSSL_NO_DH
3434			if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
3435			    {
3436			    if (dh == NULL
3437				|| DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
3438				{
3439				SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3440				goto f_err;
3441				}
3442			}
3443		else
3444#endif
3445			{
3446			SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
3447			goto f_err;
3448			}
3449		}
3450	return(1);
3451f_err:
3452	ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
3453err:
3454	return(0);
3455	}
3456
3457#if !defined(OPENSSL_NO_TLSEXT)
3458# if !defined(OPENSSL_NO_NEXTPROTONEG)
3459int ssl3_send_next_proto(SSL *s)
3460	{
3461	unsigned int len, padding_len;
3462	unsigned char *d;
3463
3464	if (s->state == SSL3_ST_CW_NEXT_PROTO_A)
3465		{
3466		len = s->next_proto_negotiated_len;
3467		padding_len = 32 - ((len + 2) % 32);
3468		d = (unsigned char *)s->init_buf->data;
3469		d[4] = len;
3470		memcpy(d + 5, s->next_proto_negotiated, len);
3471		d[5 + len] = padding_len;
3472		memset(d + 6 + len, 0, padding_len);
3473		*(d++)=SSL3_MT_NEXT_PROTO;
3474		l2n3(2 + len + padding_len, d);
3475		s->state = SSL3_ST_CW_NEXT_PROTO_B;
3476		s->init_num = 4 + 2 + len + padding_len;
3477		s->init_off = 0;
3478		}
3479
3480	return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
3481}
3482# endif  /* !OPENSSL_NO_NEXTPROTONEG */
3483
3484int ssl3_send_channel_id(SSL *s)
3485	{
3486	unsigned char *d;
3487	int ret = -1, public_key_len;
3488	EVP_MD_CTX md_ctx;
3489	size_t sig_len;
3490	ECDSA_SIG *sig = NULL;
3491	unsigned char *public_key = NULL, *derp, *der_sig = NULL;
3492
3493	if (s->state != SSL3_ST_CW_CHANNEL_ID_A)
3494		return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
3495
3496	d = (unsigned char *)s->init_buf->data;
3497	*(d++)=SSL3_MT_ENCRYPTED_EXTENSIONS;
3498	l2n3(2 + 2 + TLSEXT_CHANNEL_ID_SIZE, d);
3499	s2n(TLSEXT_TYPE_channel_id, d);
3500	s2n(TLSEXT_CHANNEL_ID_SIZE, d);
3501
3502	EVP_MD_CTX_init(&md_ctx);
3503
3504	public_key_len = i2d_PublicKey(s->tlsext_channel_id_private, NULL);
3505	if (public_key_len <= 0)
3506		{
3507		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,SSL_R_CANNOT_SERIALIZE_PUBLIC_KEY);
3508		goto err;
3509		}
3510	// i2d_PublicKey will produce an ANSI X9.62 public key which, for a
3511	// P-256 key, is 0x04 (meaning uncompressed) followed by the x and y
3512	// field elements as 32-byte, big-endian numbers.
3513	if (public_key_len != 65)
3514		{
3515		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,SSL_R_CHANNEL_ID_NOT_P256);
3516		goto err;
3517		}
3518	public_key = OPENSSL_malloc(public_key_len);
3519	if (!public_key)
3520		{
3521		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,ERR_R_MALLOC_FAILURE);
3522		goto err;
3523		}
3524
3525	derp = public_key;
3526	i2d_PublicKey(s->tlsext_channel_id_private, &derp);
3527
3528	if (EVP_DigestSignInit(&md_ctx, NULL, EVP_sha256(), NULL,
3529			       s->tlsext_channel_id_private) != 1)
3530		{
3531		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,SSL_R_EVP_DIGESTSIGNINIT_FAILED);
3532		goto err;
3533		}
3534
3535	if (!tls1_channel_id_hash(&md_ctx, s))
3536		goto err;
3537
3538	if (!EVP_DigestSignFinal(&md_ctx, NULL, &sig_len))
3539		{
3540		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,SSL_R_EVP_DIGESTSIGNFINAL_FAILED);
3541		goto err;
3542		}
3543
3544	der_sig = OPENSSL_malloc(sig_len);
3545	if (!der_sig)
3546		{
3547		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,ERR_R_MALLOC_FAILURE);
3548		goto err;
3549		}
3550
3551	if (!EVP_DigestSignFinal(&md_ctx, der_sig, &sig_len))
3552		{
3553		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,SSL_R_EVP_DIGESTSIGNFINAL_FAILED);
3554		goto err;
3555		}
3556
3557	derp = der_sig;
3558	sig = d2i_ECDSA_SIG(NULL, (const unsigned char**)&derp, sig_len);
3559	if (sig == NULL)
3560		{
3561		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,SSL_R_D2I_ECDSA_SIG);
3562		goto err;
3563		}
3564
3565	// The first byte of public_key will be 0x4, denoting an uncompressed key.
3566	memcpy(d, public_key + 1, 64);
3567	d += 64;
3568	memset(d, 0, 2 * 32);
3569	BN_bn2bin(sig->r, d + 32 - BN_num_bytes(sig->r));
3570	d += 32;
3571	BN_bn2bin(sig->s, d + 32 - BN_num_bytes(sig->s));
3572	d += 32;
3573
3574	s->state = SSL3_ST_CW_CHANNEL_ID_B;
3575	s->init_num = 4 + 2 + 2 + TLSEXT_CHANNEL_ID_SIZE;
3576	s->init_off = 0;
3577
3578	ret = ssl3_do_write(s, SSL3_RT_HANDSHAKE);
3579
3580err:
3581	EVP_MD_CTX_cleanup(&md_ctx);
3582	if (public_key)
3583		OPENSSL_free(public_key);
3584	if (der_sig)
3585		OPENSSL_free(der_sig);
3586	if (sig)
3587		ECDSA_SIG_free(sig);
3588
3589	return ret;
3590	}
3591#endif  /* !OPENSSL_NO_TLSEXT */
3592
3593/* Check to see if handshake is full or resumed. Usually this is just a
3594 * case of checking to see if a cache hit has occurred. In the case of
3595 * session tickets we have to check the next message to be sure.
3596 */
3597
3598#ifndef OPENSSL_NO_TLSEXT
3599int ssl3_check_finished(SSL *s)
3600	{
3601	int ok;
3602	long n;
3603	/* If we have no ticket it cannot be a resumed session. */
3604	if (!s->session->tlsext_tick)
3605		return 1;
3606	/* this function is called when we really expect a Certificate
3607	 * message, so permit appropriate message length */
3608	n=s->method->ssl_get_message(s,
3609		SSL3_ST_CR_CERT_A,
3610		SSL3_ST_CR_CERT_B,
3611		-1,
3612		s->max_cert_list,
3613		&ok);
3614	if (!ok) return((int)n);
3615	s->s3->tmp.reuse_message = 1;
3616	if ((s->s3->tmp.message_type == SSL3_MT_FINISHED)
3617		|| (s->s3->tmp.message_type == SSL3_MT_NEWSESSION_TICKET))
3618		return 2;
3619
3620	return 1;
3621	}
3622#endif
3623
3624int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3625	{
3626	int i = 0;
3627#ifndef OPENSSL_NO_ENGINE
3628	if (s->ctx->client_cert_engine)
3629		{
3630		i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3631						SSL_get_client_CA_list(s),
3632						px509, ppkey, NULL, NULL, NULL);
3633		if (i != 0)
3634			return i;
3635		}
3636#endif
3637	if (s->ctx->client_cert_cb)
3638		i = s->ctx->client_cert_cb(s,px509,ppkey);
3639	return i;
3640	}
3641