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