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