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