Add a HISTORY section to the man page to mention the new flags.
[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-2002 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 #include <stdio.h>
126 #include "ssl_locl.h"
127 #include "kssl_lcl.h"
128 #include <openssl/buffer.h>
129 #include <openssl/rand.h>
130 #include <openssl/objects.h>
131 #include <openssl/evp.h>
132 #include <openssl/md5.h>
133 #include "cryptlib.h"
134
135 static SSL_METHOD *ssl3_get_client_method(int ver);
136 static int ssl3_client_hello(SSL *s);
137 static int ssl3_get_server_hello(SSL *s);
138 static int ssl3_get_certificate_request(SSL *s);
139 static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b);
140 static int ssl3_get_server_done(SSL *s);
141 static int ssl3_send_client_verify(SSL *s);
142 static int ssl3_send_client_certificate(SSL *s);
143 static int ssl3_send_client_key_exchange(SSL *s);
144 static int ssl3_get_key_exchange(SSL *s);
145 static int ssl3_get_server_certificate(SSL *s);
146 static int ssl3_check_cert_and_algorithm(SSL *s);
147
148 #ifndef OPENSSL_NO_ECDH
149 static int curve_id2nid(int curve_id);
150 int check_srvr_ecc_cert_and_alg(X509 *x, SSL_CIPHER *cs);
151 #endif
152
153 static SSL_METHOD *ssl3_get_client_method(int ver)
154         {
155         if (ver == SSL3_VERSION)
156                 return(SSLv3_client_method());
157         else
158                 return(NULL);
159         }
160
161 SSL_METHOD *SSLv3_client_method(void)
162         {
163         static int init=1;
164         static SSL_METHOD SSLv3_client_data;
165
166         if (init)
167                 {
168                 CRYPTO_w_lock(CRYPTO_LOCK_SSL_METHOD);
169
170                 if (init)
171                         {
172                         memcpy((char *)&SSLv3_client_data,(char *)sslv3_base_method(),
173                                 sizeof(SSL_METHOD));
174                         SSLv3_client_data.ssl_connect=ssl3_connect;
175                         SSLv3_client_data.get_ssl_method=ssl3_get_client_method;
176                         init=0;
177                         }
178
179                 CRYPTO_w_unlock(CRYPTO_LOCK_SSL_METHOD);
180                 }
181         return(&SSLv3_client_data);
182         }
183
184 int ssl3_connect(SSL *s)
185         {
186         BUF_MEM *buf;
187         unsigned long Time=time(NULL),l;
188         long num1;
189         void (*cb)(const SSL *ssl,int type,int val)=NULL;
190         int ret= -1;
191         int new_state,state,skip=0;;
192
193         RAND_add(&Time,sizeof(Time),0);
194         ERR_clear_error();
195         clear_sys_error();
196
197         if (s->info_callback != NULL)
198                 cb=s->info_callback;
199         else if (s->ctx->info_callback != NULL)
200                 cb=s->ctx->info_callback;
201         
202         s->in_handshake++;
203         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); 
204
205         for (;;)
206                 {
207                 state=s->state;
208
209                 switch(s->state)
210                         {
211                 case SSL_ST_RENEGOTIATE:
212                         s->new_session=1;
213                         s->state=SSL_ST_CONNECT;
214                         s->ctx->stats.sess_connect_renegotiate++;
215                         /* break */
216                 case SSL_ST_BEFORE:
217                 case SSL_ST_CONNECT:
218                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
219                 case SSL_ST_OK|SSL_ST_CONNECT:
220
221                         s->server=0;
222                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
223
224                         if ((s->version & 0xff00 ) != 0x0300)
225                                 {
226                                 SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
227                                 ret = -1;
228                                 goto end;
229                                 }
230                                 
231                         /* s->version=SSL3_VERSION; */
232                         s->type=SSL_ST_CONNECT;
233
234                         if (s->init_buf == NULL)
235                                 {
236                                 if ((buf=BUF_MEM_new()) == NULL)
237                                         {
238                                         ret= -1;
239                                         goto end;
240                                         }
241                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
242                                         {
243                                         ret= -1;
244                                         goto end;
245                                         }
246                                 s->init_buf=buf;
247                                 }
248
249                         if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
250
251                         /* setup buffing BIO */
252                         if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
253
254                         /* don't push the buffering BIO quite yet */
255
256                         ssl3_init_finished_mac(s);
257
258                         s->state=SSL3_ST_CW_CLNT_HELLO_A;
259                         s->ctx->stats.sess_connect++;
260                         s->init_num=0;
261                         break;
262
263                 case SSL3_ST_CW_CLNT_HELLO_A:
264                 case SSL3_ST_CW_CLNT_HELLO_B:
265
266                         s->shutdown=0;
267                         ret=ssl3_client_hello(s);
268                         if (ret <= 0) goto end;
269                         s->state=SSL3_ST_CR_SRVR_HELLO_A;
270                         s->init_num=0;
271
272                         /* turn on buffering for the next lot of output */
273                         if (s->bbio != s->wbio)
274                                 s->wbio=BIO_push(s->bbio,s->wbio);
275
276                         break;
277
278                 case SSL3_ST_CR_SRVR_HELLO_A:
279                 case SSL3_ST_CR_SRVR_HELLO_B:
280                         ret=ssl3_get_server_hello(s);
281                         if (ret <= 0) goto end;
282                         if (s->hit)
283                                 s->state=SSL3_ST_CR_FINISHED_A;
284                         else
285                                 s->state=SSL3_ST_CR_CERT_A;
286                         s->init_num=0;
287                         break;
288
289                 case SSL3_ST_CR_CERT_A:
290                 case SSL3_ST_CR_CERT_B:
291                         /* Check if it is anon DH/ECDH */
292                         if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
293                                 {
294                                 ret=ssl3_get_server_certificate(s);
295                                 if (ret <= 0) goto end;
296                                 }
297                         else
298                                 skip=1;
299                         s->state=SSL3_ST_CR_KEY_EXCH_A;
300                         s->init_num=0;
301                         break;
302
303                 case SSL3_ST_CR_KEY_EXCH_A:
304                 case SSL3_ST_CR_KEY_EXCH_B:
305                         ret=ssl3_get_key_exchange(s);
306                         if (ret <= 0) goto end;
307                         s->state=SSL3_ST_CR_CERT_REQ_A;
308                         s->init_num=0;
309
310                         /* at this point we check that we have the
311                          * required stuff from the server */
312                         if (!ssl3_check_cert_and_algorithm(s))
313                                 {
314                                 ret= -1;
315                                 goto end;
316                                 }
317                         break;
318
319                 case SSL3_ST_CR_CERT_REQ_A:
320                 case SSL3_ST_CR_CERT_REQ_B:
321                         ret=ssl3_get_certificate_request(s);
322                         if (ret <= 0) goto end;
323                         s->state=SSL3_ST_CR_SRVR_DONE_A;
324                         s->init_num=0;
325                         break;
326
327                 case SSL3_ST_CR_SRVR_DONE_A:
328                 case SSL3_ST_CR_SRVR_DONE_B:
329                         ret=ssl3_get_server_done(s);
330                         if (ret <= 0) goto end;
331                         if (s->s3->tmp.cert_req)
332                                 s->state=SSL3_ST_CW_CERT_A;
333                         else
334                                 s->state=SSL3_ST_CW_KEY_EXCH_A;
335                         s->init_num=0;
336
337                         break;
338
339                 case SSL3_ST_CW_CERT_A:
340                 case SSL3_ST_CW_CERT_B:
341                 case SSL3_ST_CW_CERT_C:
342                 case SSL3_ST_CW_CERT_D:
343                         ret=ssl3_send_client_certificate(s);
344                         if (ret <= 0) goto end;
345                         s->state=SSL3_ST_CW_KEY_EXCH_A;
346                         s->init_num=0;
347                         break;
348
349                 case SSL3_ST_CW_KEY_EXCH_A:
350                 case SSL3_ST_CW_KEY_EXCH_B:
351                         ret=ssl3_send_client_key_exchange(s);
352                         if (ret <= 0) goto end;
353                         l=s->s3->tmp.new_cipher->algorithms;
354                         /* EAY EAY EAY need to check for DH fix cert
355                          * sent back */
356                         /* For TLS, cert_req is set to 2, so a cert chain
357                          * of nothing is sent, but no verify packet is sent */
358                         /* XXX: For now, we do not support client 
359                          * authentication in ECDH cipher suites with
360                          * ECDH (rather than ECDSA) certificates.
361                          * We need to skip the certificate verify 
362                          * message when client's ECDH public key is sent 
363                          * inside the client certificate.
364                          */
365                         if (s->s3->tmp.cert_req == 1)
366                                 {
367                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
368                                 }
369                         else
370                                 {
371                                 s->state=SSL3_ST_CW_CHANGE_A;
372                                 s->s3->change_cipher_spec=0;
373                                 }
374
375                         s->init_num=0;
376                         break;
377
378                 case SSL3_ST_CW_CERT_VRFY_A:
379                 case SSL3_ST_CW_CERT_VRFY_B:
380                         ret=ssl3_send_client_verify(s);
381                         if (ret <= 0) goto end;
382                         s->state=SSL3_ST_CW_CHANGE_A;
383                         s->init_num=0;
384                         s->s3->change_cipher_spec=0;
385                         break;
386
387                 case SSL3_ST_CW_CHANGE_A:
388                 case SSL3_ST_CW_CHANGE_B:
389                         ret=ssl3_send_change_cipher_spec(s,
390                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
391                         if (ret <= 0) goto end;
392                         s->state=SSL3_ST_CW_FINISHED_A;
393                         s->init_num=0;
394
395                         s->session->cipher=s->s3->tmp.new_cipher;
396                         if (s->s3->tmp.new_compression == NULL)
397                                 s->session->compress_meth=0;
398                         else
399                                 s->session->compress_meth=
400                                         s->s3->tmp.new_compression->id;
401                         if (!s->method->ssl3_enc->setup_key_block(s))
402                                 {
403                                 ret= -1;
404                                 goto end;
405                                 }
406
407                         if (!s->method->ssl3_enc->change_cipher_state(s,
408                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
409                                 {
410                                 ret= -1;
411                                 goto end;
412                                 }
413
414                         break;
415
416                 case SSL3_ST_CW_FINISHED_A:
417                 case SSL3_ST_CW_FINISHED_B:
418                         ret=ssl3_send_finished(s,
419                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
420                                 s->method->ssl3_enc->client_finished_label,
421                                 s->method->ssl3_enc->client_finished_label_len);
422                         if (ret <= 0) goto end;
423                         s->state=SSL3_ST_CW_FLUSH;
424
425                         /* clear flags */
426                         s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
427                         if (s->hit)
428                                 {
429                                 s->s3->tmp.next_state=SSL_ST_OK;
430                                 if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
431                                         {
432                                         s->state=SSL_ST_OK;
433                                         s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
434                                         s->s3->delay_buf_pop_ret=0;
435                                         }
436                                 }
437                         else
438                                 {
439                                 s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
440                                 }
441                         s->init_num=0;
442                         break;
443
444                 case SSL3_ST_CR_FINISHED_A:
445                 case SSL3_ST_CR_FINISHED_B:
446
447                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
448                                 SSL3_ST_CR_FINISHED_B);
449                         if (ret <= 0) goto end;
450
451                         if (s->hit)
452                                 s->state=SSL3_ST_CW_CHANGE_A;
453                         else
454                                 s->state=SSL_ST_OK;
455                         s->init_num=0;
456                         break;
457
458                 case SSL3_ST_CW_FLUSH:
459                         /* number of bytes to be flushed */
460                         num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
461                         if (num1 > 0)
462                                 {
463                                 s->rwstate=SSL_WRITING;
464                                 num1=BIO_flush(s->wbio);
465                                 if (num1 <= 0) { ret= -1; goto end; }
466                                 s->rwstate=SSL_NOTHING;
467                                 }
468
469                         s->state=s->s3->tmp.next_state;
470                         break;
471
472                 case SSL_ST_OK:
473                         /* clean a few things up */
474                         ssl3_cleanup_key_block(s);
475
476                         if (s->init_buf != NULL)
477                                 {
478                                 BUF_MEM_free(s->init_buf);
479                                 s->init_buf=NULL;
480                                 }
481
482                         /* If we are not 'joining' the last two packets,
483                          * remove the buffering now */
484                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
485                                 ssl_free_wbio_buffer(s);
486                         /* else do it later in ssl3_write */
487
488                         s->init_num=0;
489                         s->new_session=0;
490
491                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
492                         if (s->hit) s->ctx->stats.sess_hit++;
493
494                         ret=1;
495                         /* s->server=0; */
496                         s->handshake_func=ssl3_connect;
497                         s->ctx->stats.sess_connect_good++;
498
499                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
500
501                         goto end;
502                         /* break; */
503                         
504                 default:
505                         SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);
506                         ret= -1;
507                         goto end;
508                         /* break; */
509                         }
510
511                 /* did we do anything */
512                 if (!s->s3->tmp.reuse_message && !skip)
513                         {
514                         if (s->debug)
515                                 {
516                                 if ((ret=BIO_flush(s->wbio)) <= 0)
517                                         goto end;
518                                 }
519
520                         if ((cb != NULL) && (s->state != state))
521                                 {
522                                 new_state=s->state;
523                                 s->state=state;
524                                 cb(s,SSL_CB_CONNECT_LOOP,1);
525                                 s->state=new_state;
526                                 }
527                         }
528                 skip=0;
529                 }
530 end:
531         s->in_handshake--;
532         if (cb != NULL)
533                 cb(s,SSL_CB_CONNECT_EXIT,ret);
534         return(ret);
535         }
536
537
538 static int ssl3_client_hello(SSL *s)
539         {
540         unsigned char *buf;
541         unsigned char *p,*d;
542         int i,j;
543         unsigned long Time,l;
544         SSL_COMP *comp;
545
546         buf=(unsigned char *)s->init_buf->data;
547         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
548                 {
549                 if ((s->session == NULL) ||
550                         (s->session->ssl_version != s->version) ||
551                         (s->session->not_resumable))
552                         {
553                         if (!ssl_get_new_session(s,0))
554                                 goto err;
555                         }
556                 /* else use the pre-loaded session */
557
558                 p=s->s3->client_random;
559                 Time=time(NULL);                        /* Time */
560                 l2n(Time,p);
561                 RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-sizeof(Time));
562
563                 /* Do the message type and length last */
564                 d=p= &(buf[4]);
565
566                 *(p++)=s->version>>8;
567                 *(p++)=s->version&0xff;
568                 s->client_version=s->version;
569
570                 /* Random stuff */
571                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
572                 p+=SSL3_RANDOM_SIZE;
573
574                 /* Session ID */
575                 if (s->new_session)
576                         i=0;
577                 else
578                         i=s->session->session_id_length;
579                 *(p++)=i;
580                 if (i != 0)
581                         {
582                         if (i > sizeof s->session->session_id)
583                                 {
584                                 SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
585                                 goto err;
586                                 }
587                         memcpy(p,s->session->session_id,i);
588                         p+=i;
589                         }
590                 
591                 /* Ciphers supported */
592                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]));
593                 if (i == 0)
594                         {
595                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
596                         goto err;
597                         }
598                 s2n(i,p);
599                 p+=i;
600
601                 /* COMPRESSION */
602                 if (s->ctx->comp_methods == NULL)
603                         j=0;
604                 else
605                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
606                 *(p++)=1+j;
607                 for (i=0; i<j; i++)
608                         {
609                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
610                         *(p++)=comp->id;
611                         }
612                 *(p++)=0; /* Add the NULL method */
613                 
614                 l=(p-d);
615                 d=buf;
616                 *(d++)=SSL3_MT_CLIENT_HELLO;
617                 l2n3(l,d);
618
619                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
620                 /* number of bytes to write */
621                 s->init_num=p-buf;
622                 s->init_off=0;
623                 }
624
625         /* SSL3_ST_CW_CLNT_HELLO_B */
626         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
627 err:
628         return(-1);
629         }
630
631 static int ssl3_get_server_hello(SSL *s)
632         {
633         STACK_OF(SSL_CIPHER) *sk;
634         SSL_CIPHER *c;
635         unsigned char *p,*d;
636         int i,al,ok;
637         unsigned int j;
638         long n;
639         SSL_COMP *comp;
640
641         n=ssl3_get_message(s,
642                 SSL3_ST_CR_SRVR_HELLO_A,
643                 SSL3_ST_CR_SRVR_HELLO_B,
644                 SSL3_MT_SERVER_HELLO,
645                 300, /* ?? */
646                 &ok);
647
648         if (!ok) return((int)n);
649         d=p=(unsigned char *)s->init_msg;
650
651         if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff)))
652                 {
653                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION);
654                 s->version=(s->version&0xff00)|p[1];
655                 al=SSL_AD_PROTOCOL_VERSION;
656                 goto f_err;
657                 }
658         p+=2;
659
660         /* load the server hello data */
661         /* load the server random */
662         memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE);
663         p+=SSL3_RANDOM_SIZE;
664
665         /* get the session-id */
666         j= *(p++);
667
668         if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE))
669                 {
670                 al=SSL_AD_ILLEGAL_PARAMETER;
671                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG);
672                 goto f_err;
673                 }
674         if (j != 0 && j == s->session->session_id_length
675             && memcmp(p,s->session->session_id,j) == 0)
676             {
677             if(s->sid_ctx_length != s->session->sid_ctx_length
678                || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length))
679                 {
680                 /* actually a client application bug */
681                 al=SSL_AD_ILLEGAL_PARAMETER;
682                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
683                 goto f_err;
684                 }
685             s->hit=1;
686             }
687         else    /* a miss or crap from the other end */
688                 {
689                 /* If we were trying for session-id reuse, make a new
690                  * SSL_SESSION so we don't stuff up other people */
691                 s->hit=0;
692                 if (s->session->session_id_length > 0)
693                         {
694                         if (!ssl_get_new_session(s,0))
695                                 {
696                                 al=SSL_AD_INTERNAL_ERROR;
697                                 goto f_err;
698                                 }
699                         }
700                 s->session->session_id_length=j;
701                 memcpy(s->session->session_id,p,j); /* j could be 0 */
702                 }
703         p+=j;
704         c=ssl_get_cipher_by_char(s,p);
705         if (c == NULL)
706                 {
707                 /* unknown cipher */
708                 al=SSL_AD_ILLEGAL_PARAMETER;
709                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED);
710                 goto f_err;
711                 }
712         p+=ssl_put_cipher_by_char(s,NULL,NULL);
713
714         sk=ssl_get_ciphers_by_id(s);
715         i=sk_SSL_CIPHER_find(sk,c);
716         if (i < 0)
717                 {
718                 /* we did not say we would use this cipher */
719                 al=SSL_AD_ILLEGAL_PARAMETER;
720                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
721                 goto f_err;
722                 }
723
724         if (s->hit && (s->session->cipher != c))
725                 {
726                 if (!(s->options &
727                         SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
728                         {
729                         al=SSL_AD_ILLEGAL_PARAMETER;
730                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
731                         goto f_err;
732                         }
733                 }
734         s->s3->tmp.new_cipher=c;
735
736         /* lets get the compression algorithm */
737         /* COMPRESSION */
738         j= *(p++);
739         if (j == 0)
740                 comp=NULL;
741         else
742                 comp=ssl3_comp_find(s->ctx->comp_methods,j);
743         
744         if ((j != 0) && (comp == NULL))
745                 {
746                 al=SSL_AD_ILLEGAL_PARAMETER;
747                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
748                 goto f_err;
749                 }
750         else
751                 {
752                 s->s3->tmp.new_compression=comp;
753                 }
754
755         if (p != (d+n))
756                 {
757                 /* wrong packet length */
758                 al=SSL_AD_DECODE_ERROR;
759                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH);
760                 goto err;
761                 }
762
763         return(1);
764 f_err:
765         ssl3_send_alert(s,SSL3_AL_FATAL,al);
766 err:
767         return(-1);
768         }
769
770 static int ssl3_get_server_certificate(SSL *s)
771         {
772         int al,i,ok,ret= -1;
773         unsigned long n,nc,llen,l;
774         X509 *x=NULL;
775         unsigned char *p,*d,*q;
776         STACK_OF(X509) *sk=NULL;
777         SESS_CERT *sc;
778         EVP_PKEY *pkey=NULL;
779         int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */
780
781         n=ssl3_get_message(s,
782                 SSL3_ST_CR_CERT_A,
783                 SSL3_ST_CR_CERT_B,
784                 -1,
785                 s->max_cert_list,
786                 &ok);
787
788         if (!ok) return((int)n);
789
790         if (s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE)
791                 {
792                 s->s3->tmp.reuse_message=1;
793                 return(1);
794                 }
795
796         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
797                 {
798                 al=SSL_AD_UNEXPECTED_MESSAGE;
799                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE);
800                 goto f_err;
801                 }
802         d=p=(unsigned char *)s->init_msg;
803
804         if ((sk=sk_X509_new_null()) == NULL)
805                 {
806                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
807                 goto err;
808                 }
809
810         n2l3(p,llen);
811         if (llen+3 != n)
812                 {
813                 al=SSL_AD_DECODE_ERROR;
814                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
815                 goto f_err;
816                 }
817         for (nc=0; nc<llen; )
818                 {
819                 n2l3(p,l);
820                 if ((l+nc+3) > llen)
821                         {
822                         al=SSL_AD_DECODE_ERROR;
823                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
824                         goto f_err;
825                         }
826
827                 q=p;
828                 x=d2i_X509(NULL,&q,l);
829                 if (x == NULL)
830                         {
831                         al=SSL_AD_BAD_CERTIFICATE;
832                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB);
833                         goto f_err;
834                         }
835                 if (q != (p+l))
836                         {
837                         al=SSL_AD_DECODE_ERROR;
838                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
839                         goto f_err;
840                         }
841                 if (!sk_X509_push(sk,x))
842                         {
843                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
844                         goto err;
845                         }
846                 x=NULL;
847                 nc+=l+3;
848                 p=q;
849                 }
850
851         i=ssl_verify_cert_chain(s,sk);
852         if ((s->verify_mode != SSL_VERIFY_NONE) && (!i)
853 #ifndef OPENSSL_NO_KRB5
854                 && (s->s3->tmp.new_cipher->algorithms & (SSL_MKEY_MASK|SSL_AUTH_MASK))
855                 != (SSL_aKRB5|SSL_kKRB5)
856 #endif /* OPENSSL_NO_KRB5 */
857                 )
858                 {
859                 al=ssl_verify_alarm_type(s->verify_result);
860                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
861                 goto f_err; 
862                 }
863         ERR_clear_error(); /* but we keep s->verify_result */
864
865         sc=ssl_sess_cert_new();
866         if (sc == NULL) goto err;
867
868         if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
869         s->session->sess_cert=sc;
870
871         sc->cert_chain=sk;
872         /* Inconsistency alert: cert_chain does include the peer's
873          * certificate, which we don't include in s3_srvr.c */
874         x=sk_X509_value(sk,0);
875         sk=NULL;
876         /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
877
878         pkey=X509_get_pubkey(x);
879
880         /* VRS: allow null cert if auth == KRB5 */
881         need_cert =     ((s->s3->tmp.new_cipher->algorithms
882                         & (SSL_MKEY_MASK|SSL_AUTH_MASK))
883                         == (SSL_aKRB5|SSL_kKRB5))? 0: 1;
884
885 #ifdef KSSL_DEBUG
886         printf("pkey,x = %p, %p\n", pkey,x);
887         printf("ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey));
888         printf("cipher, alg, nc = %s, %lx, %d\n", s->s3->tmp.new_cipher->name,
889                 s->s3->tmp.new_cipher->algorithms, need_cert);
890 #endif    /* KSSL_DEBUG */
891
892         if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey)))
893                 {
894                 x=NULL;
895                 al=SSL3_AL_FATAL;
896                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
897                         SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
898                 goto f_err;
899                 }
900
901         i=ssl_cert_type(x,pkey);
902         if (need_cert && i < 0)
903                 {
904                 x=NULL;
905                 al=SSL3_AL_FATAL;
906                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
907                         SSL_R_UNKNOWN_CERTIFICATE_TYPE);
908                 goto f_err;
909                 }
910
911         if (need_cert)
912                 {
913                 sc->peer_cert_type=i;
914                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
915                 /* Why would the following ever happen?
916                  * We just created sc a couple of lines ago. */
917                 if (sc->peer_pkeys[i].x509 != NULL)
918                         X509_free(sc->peer_pkeys[i].x509);
919                 sc->peer_pkeys[i].x509=x;
920                 sc->peer_key= &(sc->peer_pkeys[i]);
921
922                 if (s->session->peer != NULL)
923                         X509_free(s->session->peer);
924                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
925                 s->session->peer=x;
926                 }
927         else
928                 {
929                 sc->peer_cert_type=i;
930                 sc->peer_key= NULL;
931
932                 if (s->session->peer != NULL)
933                         X509_free(s->session->peer);
934                 s->session->peer=NULL;
935                 }
936         s->session->verify_result = s->verify_result;
937
938         x=NULL;
939         ret=1;
940
941         if (0)
942                 {
943 f_err:
944                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
945                 }
946 err:
947         EVP_PKEY_free(pkey);
948         X509_free(x);
949         sk_X509_pop_free(sk,X509_free);
950         return(ret);
951         }
952
953 static int ssl3_get_key_exchange(SSL *s)
954         {
955 #ifndef OPENSSL_NO_RSA
956         unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];
957 #endif
958         EVP_MD_CTX md_ctx;
959         unsigned char *param,*p;
960         int al,i,j,param_len,ok;
961         long n,alg;
962         EVP_PKEY *pkey=NULL;
963 #ifndef OPENSSL_NO_RSA
964         RSA *rsa=NULL;
965 #endif
966 #ifndef OPENSSL_NO_DH
967         DH *dh=NULL;
968 #endif
969 #ifndef OPENSSL_NO_ECDH
970         EC_KEY *ecdh = NULL;
971         BN_CTX *bn_ctx = NULL;
972         EC_POINT *srvr_ecpoint = NULL;
973         int curve_nid = 0;
974         int encoded_pt_len = 0;
975 #endif
976
977         /* use same message size as in ssl3_get_certificate_request()
978          * as ServerKeyExchange message may be skipped */
979         n=ssl3_get_message(s,
980                 SSL3_ST_CR_KEY_EXCH_A,
981                 SSL3_ST_CR_KEY_EXCH_B,
982                 -1,
983                 s->max_cert_list,
984                 &ok);
985
986         if (!ok) return((int)n);
987
988         if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
989                 {
990                 s->s3->tmp.reuse_message=1;
991                 return(1);
992                 }
993
994         param=p=(unsigned char *)s->init_msg;
995
996         if (s->session->sess_cert != NULL)
997                 {
998 #ifndef OPENSSL_NO_RSA
999                 if (s->session->sess_cert->peer_rsa_tmp != NULL)
1000                         {
1001                         RSA_free(s->session->sess_cert->peer_rsa_tmp);
1002                         s->session->sess_cert->peer_rsa_tmp=NULL;
1003                         }
1004 #endif
1005 #ifndef OPENSSL_NO_DH
1006                 if (s->session->sess_cert->peer_dh_tmp)
1007                         {
1008                         DH_free(s->session->sess_cert->peer_dh_tmp);
1009                         s->session->sess_cert->peer_dh_tmp=NULL;
1010                         }
1011 #endif
1012 #ifndef OPENSSL_NO_ECDH
1013                 if (s->session->sess_cert->peer_ecdh_tmp)
1014                         {
1015                         EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
1016                         s->session->sess_cert->peer_ecdh_tmp=NULL;
1017                         }
1018 #endif
1019                 }
1020         else
1021                 {
1022                 s->session->sess_cert=ssl_sess_cert_new();
1023                 }
1024
1025         param_len=0;
1026         alg=s->s3->tmp.new_cipher->algorithms;
1027         EVP_MD_CTX_init(&md_ctx);
1028
1029 #ifndef OPENSSL_NO_RSA
1030         if (alg & SSL_kRSA)
1031                 {
1032                 if ((rsa=RSA_new()) == NULL)
1033                         {
1034                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1035                         goto err;
1036                         }
1037                 n2s(p,i);
1038                 param_len=i+2;
1039                 if (param_len > n)
1040                         {
1041                         al=SSL_AD_DECODE_ERROR;
1042                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
1043                         goto f_err;
1044                         }
1045                 if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
1046                         {
1047                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1048                         goto err;
1049                         }
1050                 p+=i;
1051
1052                 n2s(p,i);
1053                 param_len+=i+2;
1054                 if (param_len > n)
1055                         {
1056                         al=SSL_AD_DECODE_ERROR;
1057                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
1058                         goto f_err;
1059                         }
1060                 if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
1061                         {
1062                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1063                         goto err;
1064                         }
1065                 p+=i;
1066                 n-=param_len;
1067
1068                 /* this should be because we are using an export cipher */
1069                 if (alg & SSL_aRSA)
1070                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1071                 else
1072                         {
1073                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1074                         goto err;
1075                         }
1076                 s->session->sess_cert->peer_rsa_tmp=rsa;
1077                 rsa=NULL;
1078                 }
1079 #else /* OPENSSL_NO_RSA */
1080         if (0)
1081                 ;
1082 #endif
1083 #ifndef OPENSSL_NO_DH
1084         else if (alg & SSL_kEDH)
1085                 {
1086                 if ((dh=DH_new()) == NULL)
1087                         {
1088                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);
1089                         goto err;
1090                         }
1091                 n2s(p,i);
1092                 param_len=i+2;
1093                 if (param_len > n)
1094                         {
1095                         al=SSL_AD_DECODE_ERROR;
1096                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);
1097                         goto f_err;
1098                         }
1099                 if (!(dh->p=BN_bin2bn(p,i,NULL)))
1100                         {
1101                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1102                         goto err;
1103                         }
1104                 p+=i;
1105
1106                 n2s(p,i);
1107                 param_len+=i+2;
1108                 if (param_len > n)
1109                         {
1110                         al=SSL_AD_DECODE_ERROR;
1111                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);
1112                         goto f_err;
1113                         }
1114                 if (!(dh->g=BN_bin2bn(p,i,NULL)))
1115                         {
1116                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1117                         goto err;
1118                         }
1119                 p+=i;
1120
1121                 n2s(p,i);
1122                 param_len+=i+2;
1123                 if (param_len > n)
1124                         {
1125                         al=SSL_AD_DECODE_ERROR;
1126                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);
1127                         goto f_err;
1128                         }
1129                 if (!(dh->pub_key=BN_bin2bn(p,i,NULL)))
1130                         {
1131                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1132                         goto err;
1133                         }
1134                 p+=i;
1135                 n-=param_len;
1136
1137 #ifndef OPENSSL_NO_RSA
1138                 if (alg & SSL_aRSA)
1139                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1140 #else
1141                 if (0)
1142                         ;
1143 #endif
1144 #ifndef OPENSSL_NO_DSA
1145                 else if (alg & SSL_aDSS)
1146                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1147 #endif
1148                 /* else anonymous DH, so no certificate or pkey. */
1149
1150                 s->session->sess_cert->peer_dh_tmp=dh;
1151                 dh=NULL;
1152                 }
1153         else if ((alg & SSL_kDHr) || (alg & SSL_kDHd))
1154                 {
1155                 al=SSL_AD_ILLEGAL_PARAMETER;
1156                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1157                 goto f_err;
1158                 }
1159 #endif /* !OPENSSL_NO_DH */
1160
1161 #ifndef OPENSSL_NO_ECDH
1162         else if (alg & SSL_kECDHE)
1163                 {
1164                 if ((ecdh=EC_KEY_new()) == NULL)
1165                         {
1166                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1167                         goto err;
1168                         }
1169
1170                 /* Extract elliptic curve parameters and the
1171                  * server's ephemeral ECDH public key.
1172                  * Keep accumulating lengths of various components in
1173                  * param_len and make sure it never exceeds n.
1174                  */
1175
1176                 /* XXX: For now we only support named (not generic) curves
1177                  * and the ECParameters in this case is just two bytes.
1178                  */
1179                 param_len=2;
1180                 if ((param_len > n) ||
1181                     (*p != NAMED_CURVE_TYPE) || 
1182                     ((curve_nid = curve_id2nid(*(p + 1))) == 0)) 
1183                         {
1184                         al=SSL_AD_INTERNAL_ERROR;
1185                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1186                         goto f_err;
1187                         }
1188
1189                 if (!(ecdh->group=EC_GROUP_new_by_nid(curve_nid)))
1190                         {
1191                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1192                         goto err;
1193                         }
1194
1195                 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1196                     (EC_GROUP_get_degree(ecdh->group) > 163))
1197                         {
1198                         al=SSL_AD_EXPORT_RESTRICTION;
1199                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1200                         goto f_err;
1201                         }
1202
1203                 p+=2;
1204
1205                 /* Next, get the encoded ECPoint */
1206                 if (((srvr_ecpoint = EC_POINT_new(ecdh->group)) == NULL) ||
1207                     ((bn_ctx = BN_CTX_new()) == NULL))
1208                         {
1209                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1210                         goto err;
1211                         }
1212
1213                 encoded_pt_len = *p;  /* length of encoded point */
1214                 p+=1;
1215                 param_len += (1 + encoded_pt_len);
1216                 if ((param_len > n) ||
1217                     (EC_POINT_oct2point(ecdh->group, srvr_ecpoint, 
1218                         p, encoded_pt_len, bn_ctx) == 0))
1219                         {
1220                         al=SSL_AD_DECODE_ERROR;
1221                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT);
1222                         goto f_err;
1223                         }
1224
1225                 n-=param_len;
1226                 p+=encoded_pt_len;
1227
1228                 /* The ECC/TLS specification does not mention
1229                  * the use of DSA to sign ECParameters in the server
1230                  * key exchange message. We do support RSA and ECDSA.
1231                  */
1232                 if (0) ;
1233 #ifndef OPENSSL_NO_RSA
1234                 else if (alg & SSL_aRSA)
1235                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1236 #endif
1237 #ifndef OPENSSL_NO_ECDSA
1238                 else if (alg & SSL_aECDSA)
1239                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1240 #endif
1241                 /* else anonymous ECDH, so no certificate or pkey. */
1242                 ecdh->pub_key = srvr_ecpoint;
1243                 s->session->sess_cert->peer_ecdh_tmp=ecdh;
1244                 ecdh=NULL;
1245                 BN_CTX_free(bn_ctx);
1246                 srvr_ecpoint = NULL;
1247                 }
1248         else if (alg & SSL_kECDH)
1249                 {
1250                 al=SSL_AD_UNEXPECTED_MESSAGE;
1251                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
1252                 goto f_err;
1253                 }
1254 #endif /* !OPENSSL_NO_ECDH */
1255         if (alg & SSL_aFZA)
1256                 {
1257                 al=SSL_AD_HANDSHAKE_FAILURE;
1258                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1259                 goto f_err;
1260                 }
1261
1262
1263         /* p points to the next byte, there are 'n' bytes left */
1264
1265         /* if it was signed, check the signature */
1266         if (pkey != NULL)
1267                 {
1268                 n2s(p,i);
1269                 n-=2;
1270                 j=EVP_PKEY_size(pkey);
1271
1272                 if ((i != n) || (n > j) || (n <= 0))
1273                         {
1274                         /* wrong packet length */
1275                         al=SSL_AD_DECODE_ERROR;
1276                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);
1277                         goto f_err;
1278                         }
1279
1280 #ifndef OPENSSL_NO_RSA
1281                 if (pkey->type == EVP_PKEY_RSA)
1282                         {
1283                         int num;
1284
1285                         j=0;
1286                         q=md_buf;
1287                         for (num=2; num > 0; num--)
1288                                 {
1289                                 EVP_DigestInit_ex(&md_ctx,(num == 2)
1290                                         ?s->ctx->md5:s->ctx->sha1, NULL);
1291                                 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1292                                 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1293                                 EVP_DigestUpdate(&md_ctx,param,param_len);
1294                                 EVP_DigestFinal_ex(&md_ctx,q,(unsigned int *)&i);
1295                                 q+=i;
1296                                 j+=i;
1297                                 }
1298                         i=RSA_verify(NID_md5_sha1, md_buf, j, p, n,
1299                                                                 pkey->pkey.rsa);
1300                         if (i < 0)
1301                                 {
1302                                 al=SSL_AD_DECRYPT_ERROR;
1303                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
1304                                 goto f_err;
1305                                 }
1306                         if (i == 0)
1307                                 {
1308                                 /* bad signature */
1309                                 al=SSL_AD_DECRYPT_ERROR;
1310                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1311                                 goto f_err;
1312                                 }
1313                         }
1314                 else
1315 #endif
1316 #ifndef OPENSSL_NO_DSA
1317                         if (pkey->type == EVP_PKEY_DSA)
1318                         {
1319                         /* lets do DSS */
1320                         EVP_VerifyInit_ex(&md_ctx,EVP_dss1(), NULL);
1321                         EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1322                         EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1323                         EVP_VerifyUpdate(&md_ctx,param,param_len);
1324                         if (!EVP_VerifyFinal(&md_ctx,p,(int)n,pkey))
1325                                 {
1326                                 /* bad signature */
1327                                 al=SSL_AD_DECRYPT_ERROR;
1328                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1329                                 goto f_err;
1330                                 }
1331                         }
1332                 else
1333 #endif
1334 #ifndef OPENSSL_NO_ECDSA
1335                         if (pkey->type == EVP_PKEY_EC)
1336                         {
1337                         /* let's do ECDSA */
1338                         EVP_VerifyInit_ex(&md_ctx,EVP_ecdsa(), NULL);
1339                         EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1340                         EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1341                         EVP_VerifyUpdate(&md_ctx,param,param_len);
1342                         if (!EVP_VerifyFinal(&md_ctx,p,(int)n,pkey))
1343                                 {
1344                                 /* bad signature */
1345                                 al=SSL_AD_DECRYPT_ERROR;
1346                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1347                                 goto f_err;
1348                                 }
1349                         }
1350                 else
1351 #endif
1352                         {
1353                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1354                         goto err;
1355                         }
1356                 }
1357         else
1358                 {
1359                 /* still data left over */
1360                 if (!(alg & SSL_aNULL))
1361                         {
1362                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1363                         goto err;
1364                         }
1365                 if (n != 0)
1366                         {
1367                         al=SSL_AD_DECODE_ERROR;
1368                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
1369                         goto f_err;
1370                         }
1371                 }
1372         EVP_PKEY_free(pkey);
1373         EVP_MD_CTX_cleanup(&md_ctx);
1374         return(1);
1375 f_err:
1376         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1377 err:
1378         EVP_PKEY_free(pkey);
1379 #ifndef OPENSSL_NO_RSA
1380         if (rsa != NULL)
1381                 RSA_free(rsa);
1382 #endif
1383 #ifndef OPENSSL_NO_DH
1384         if (dh != NULL)
1385                 DH_free(dh);
1386 #endif
1387 #ifndef OPENSSL_NO_ECDH
1388         BN_CTX_free(bn_ctx);
1389         EC_POINT_free(srvr_ecpoint);
1390         if (ecdh != NULL)
1391                 EC_KEY_free(ecdh);
1392 #endif
1393         EVP_MD_CTX_cleanup(&md_ctx);
1394         return(-1);
1395         }
1396
1397 static int ssl3_get_certificate_request(SSL *s)
1398         {
1399         int ok,ret=0;
1400         unsigned long n,nc,l;
1401         unsigned int llen,ctype_num,i;
1402         X509_NAME *xn=NULL;
1403         unsigned char *p,*d,*q;
1404         STACK_OF(X509_NAME) *ca_sk=NULL;
1405
1406         n=ssl3_get_message(s,
1407                 SSL3_ST_CR_CERT_REQ_A,
1408                 SSL3_ST_CR_CERT_REQ_B,
1409                 -1,
1410                 s->max_cert_list,
1411                 &ok);
1412
1413         if (!ok) return((int)n);
1414
1415         s->s3->tmp.cert_req=0;
1416
1417         if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
1418                 {
1419                 s->s3->tmp.reuse_message=1;
1420                 return(1);
1421                 }
1422
1423         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
1424                 {
1425                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1426                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE);
1427                 goto err;
1428                 }
1429
1430         /* TLS does not like anon-DH with client cert */
1431         if (s->version > SSL3_VERSION)
1432                 {
1433                 l=s->s3->tmp.new_cipher->algorithms;
1434                 if (l & SSL_aNULL)
1435                         {
1436                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1437                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1438                         goto err;
1439                         }
1440                 }
1441
1442         d=p=(unsigned char *)s->init_msg;
1443
1444         if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL)
1445                 {
1446                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1447                 goto err;
1448                 }
1449
1450         /* get the certificate types */
1451         ctype_num= *(p++);
1452         if (ctype_num > SSL3_CT_NUMBER)
1453                 ctype_num=SSL3_CT_NUMBER;
1454         for (i=0; i<ctype_num; i++)
1455                 s->s3->tmp.ctype[i]= p[i];
1456         p+=ctype_num;
1457
1458         /* get the CA RDNs */
1459         n2s(p,llen);
1460 #if 0
1461 {
1462 FILE *out;
1463 out=fopen("/tmp/vsign.der","w");
1464 fwrite(p,1,llen,out);
1465 fclose(out);
1466 }
1467 #endif
1468
1469         if ((llen+ctype_num+2+1) != n)
1470                 {
1471                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1472                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH);
1473                 goto err;
1474                 }
1475
1476         for (nc=0; nc<llen; )
1477                 {
1478                 n2s(p,l);
1479                 if ((l+nc+2) > llen)
1480                         {
1481                         if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
1482                                 goto cont; /* netscape bugs */
1483                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1484                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG);
1485                         goto err;
1486                         }
1487
1488                 q=p;
1489
1490                 if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL)
1491                         {
1492                         /* If netscape tolerance is on, ignore errors */
1493                         if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
1494                                 goto cont;
1495                         else
1496                                 {
1497                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1498                                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB);
1499                                 goto err;
1500                                 }
1501                         }
1502
1503                 if (q != (p+l))
1504                         {
1505                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1506                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH);
1507                         goto err;
1508                         }
1509                 if (!sk_X509_NAME_push(ca_sk,xn))
1510                         {
1511                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1512                         goto err;
1513                         }
1514
1515                 p+=l;
1516                 nc+=l+2;
1517                 }
1518
1519         if (0)
1520                 {
1521 cont:
1522                 ERR_clear_error();
1523                 }
1524
1525         /* we should setup a certificate to return.... */
1526         s->s3->tmp.cert_req=1;
1527         s->s3->tmp.ctype_num=ctype_num;
1528         if (s->s3->tmp.ca_names != NULL)
1529                 sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
1530         s->s3->tmp.ca_names=ca_sk;
1531         ca_sk=NULL;
1532
1533         ret=1;
1534 err:
1535         if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
1536         return(ret);
1537         }
1538
1539 static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1540         {
1541         return(X509_NAME_cmp(*a,*b));
1542         }
1543
1544 static int ssl3_get_server_done(SSL *s)
1545         {
1546         int ok,ret=0;
1547         long n;
1548
1549         n=ssl3_get_message(s,
1550                 SSL3_ST_CR_SRVR_DONE_A,
1551                 SSL3_ST_CR_SRVR_DONE_B,
1552                 SSL3_MT_SERVER_DONE,
1553                 30, /* should be very small, like 0 :-) */
1554                 &ok);
1555
1556         if (!ok) return((int)n);
1557         if (n > 0)
1558                 {
1559                 /* should contain no data */
1560                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1561                 SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH);
1562                 return -1;
1563                 }
1564         ret=1;
1565         return(ret);
1566         }
1567
1568 static int ssl3_send_client_key_exchange(SSL *s)
1569         {
1570         unsigned char *p,*d;
1571         int n;
1572         unsigned long l;
1573 #ifndef OPENSSL_NO_RSA
1574         unsigned char *q;
1575         EVP_PKEY *pkey=NULL;
1576 #endif
1577 #ifndef OPENSSL_NO_KRB5
1578         KSSL_ERR kssl_err;
1579 #endif /* OPENSSL_NO_KRB5 */
1580 #ifndef OPENSSL_NO_ECDH
1581         EC_KEY *clnt_ecdh = NULL;
1582         EC_POINT *srvr_ecpoint = NULL;
1583         EVP_PKEY *srvr_pub_pkey = NULL;
1584         unsigned char *encodedPoint = NULL;
1585         int encoded_pt_len = 0;
1586         BN_CTX * bn_ctx = NULL;
1587 #endif
1588
1589         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
1590                 {
1591                 d=(unsigned char *)s->init_buf->data;
1592                 p= &(d[4]);
1593
1594                 l=s->s3->tmp.new_cipher->algorithms;
1595
1596                 /* Fool emacs indentation */
1597                 if (0) {}
1598 #ifndef OPENSSL_NO_RSA
1599                 else if (l & SSL_kRSA)
1600                         {
1601                         RSA *rsa;
1602                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
1603
1604                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
1605                                 rsa=s->session->sess_cert->peer_rsa_tmp;
1606                         else
1607                                 {
1608                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1609                                 if ((pkey == NULL) ||
1610                                         (pkey->type != EVP_PKEY_RSA) ||
1611                                         (pkey->pkey.rsa == NULL))
1612                                         {
1613                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1614                                         goto err;
1615                                         }
1616                                 rsa=pkey->pkey.rsa;
1617                                 EVP_PKEY_free(pkey);
1618                                 }
1619                                 
1620                         tmp_buf[0]=s->client_version>>8;
1621                         tmp_buf[1]=s->client_version&0xff;
1622                         if (RAND_bytes(&(tmp_buf[2]),SSL_MAX_MASTER_KEY_LENGTH-2) <= 0)
1623                                         goto err;
1624
1625                         s->session->master_key_length=SSL_MAX_MASTER_KEY_LENGTH;
1626
1627                         q=p;
1628                         /* Fix buf for TLS and beyond */
1629                         if (s->version > SSL3_VERSION)
1630                                 p+=2;
1631                         n=RSA_public_encrypt(SSL_MAX_MASTER_KEY_LENGTH,
1632                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
1633 #ifdef PKCS1_CHECK
1634                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
1635                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
1636 #endif
1637                         if (n <= 0)
1638                                 {
1639                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
1640                                 goto err;
1641                                 }
1642
1643                         /* Fix buf for TLS and beyond */
1644                         if (s->version > SSL3_VERSION)
1645                                 {
1646                                 s2n(n,q);
1647                                 n+=2;
1648                                 }
1649
1650                         s->session->master_key_length=
1651                                 s->method->ssl3_enc->generate_master_secret(s,
1652                                         s->session->master_key,
1653                                         tmp_buf,SSL_MAX_MASTER_KEY_LENGTH);
1654                         memset(tmp_buf,0,SSL_MAX_MASTER_KEY_LENGTH);
1655                         }
1656 #endif
1657 #ifndef OPENSSL_NO_KRB5
1658                 else if (l & SSL_kKRB5)
1659                         {
1660                         krb5_error_code krb5rc;
1661                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
1662                         /*  krb5_data   krb5_ap_req;  */
1663                         krb5_data       *enc_ticket;
1664                         krb5_data       authenticator, *authp = NULL;
1665                         EVP_CIPHER_CTX  ciph_ctx;
1666                         EVP_CIPHER      *enc = NULL;
1667                         unsigned char   iv[EVP_MAX_IV_LENGTH];
1668                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
1669                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
1670                                                 + EVP_MAX_IV_LENGTH];
1671                         int             padl, outl = sizeof(epms);
1672
1673                         EVP_CIPHER_CTX_init(&ciph_ctx);
1674
1675 #ifdef KSSL_DEBUG
1676                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
1677                                 l, SSL_kKRB5);
1678 #endif  /* KSSL_DEBUG */
1679
1680                         authp = NULL;
1681 #ifdef KRB5SENDAUTH
1682                         if (KRB5SENDAUTH)  authp = &authenticator;
1683 #endif  /* KRB5SENDAUTH */
1684
1685                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
1686                                 &kssl_err);
1687                         enc = kssl_map_enc(kssl_ctx->enctype);
1688                         if (enc == NULL)
1689                             goto err;
1690 #ifdef KSSL_DEBUG
1691                         {
1692                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
1693                         if (krb5rc && kssl_err.text)
1694                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
1695                         }
1696 #endif  /* KSSL_DEBUG */
1697
1698                         if (krb5rc)
1699                                 {
1700                                 ssl3_send_alert(s,SSL3_AL_FATAL,
1701                                                 SSL_AD_HANDSHAKE_FAILURE);
1702                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
1703                                                 kssl_err.reason);
1704                                 goto err;
1705                                 }
1706
1707                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
1708                         **  in place of RFC 2712 KerberosWrapper, as in:
1709                         **
1710                         **  Send ticket (copy to *p, set n = length)
1711                         **  n = krb5_ap_req.length;
1712                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
1713                         **  if (krb5_ap_req.data)  
1714                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
1715                         **
1716                         **  Now using real RFC 2712 KerberosWrapper
1717                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
1718                         **  Note: 2712 "opaque" types are here replaced
1719                         **  with a 2-byte length followed by the value.
1720                         **  Example:
1721                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
1722                         **  Where "xx xx" = length bytes.  Shown here with
1723                         **  optional authenticator omitted.
1724                         */
1725
1726                         /*  KerberosWrapper.Ticket              */
1727                         s2n(enc_ticket->length,p);
1728                         memcpy(p, enc_ticket->data, enc_ticket->length);
1729                         p+= enc_ticket->length;
1730                         n = enc_ticket->length + 2;
1731
1732                         /*  KerberosWrapper.Authenticator       */
1733                         if (authp  &&  authp->length)  
1734                                 {
1735                                 s2n(authp->length,p);
1736                                 memcpy(p, authp->data, authp->length);
1737                                 p+= authp->length;
1738                                 n+= authp->length + 2;
1739                                 
1740                                 free(authp->data);
1741                                 authp->data = NULL;
1742                                 authp->length = 0;
1743                                 }
1744                         else
1745                                 {
1746                                 s2n(0,p);/*  null authenticator length  */
1747                                 n+=2;
1748                                 }
1749  
1750                         if (RAND_bytes(tmp_buf,SSL_MAX_MASTER_KEY_LENGTH) <= 0)
1751                             goto err;
1752
1753                         /*  20010420 VRS.  Tried it this way; failed.
1754                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
1755                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
1756                         **                              kssl_ctx->length);
1757                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
1758                         */
1759
1760                         memset(iv, 0, EVP_MAX_IV_LENGTH);  /* per RFC 1510 */
1761                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
1762                                 kssl_ctx->key,iv);
1763                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
1764                                 SSL_MAX_MASTER_KEY_LENGTH);
1765                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
1766                         outl += padl;
1767                         if (outl > sizeof epms)
1768                                 {
1769                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1770                                 goto err;
1771                                 }
1772                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
1773
1774                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
1775                         s2n(outl,p);
1776                         memcpy(p, epms, outl);
1777                         p+=outl;
1778                         n+=outl + 2;
1779
1780                         s->session->master_key_length=
1781                                 s->method->ssl3_enc->generate_master_secret(s,
1782                                         s->session->master_key,
1783                                         tmp_buf, SSL_MAX_MASTER_KEY_LENGTH);
1784
1785                         memset(tmp_buf, 0, SSL_MAX_MASTER_KEY_LENGTH);
1786                         memset(epms, 0, outl);
1787                         }
1788 #endif
1789 #ifndef OPENSSL_NO_DH
1790                 else if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1791                         {
1792                         DH *dh_srvr,*dh_clnt;
1793
1794                         if (s->session->sess_cert->peer_dh_tmp != NULL)
1795                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
1796                         else
1797                                 {
1798                                 /* we get them from the cert */
1799                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1800                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
1801                                 goto err;
1802                                 }
1803                         
1804                         /* generate a new random key */
1805                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
1806                                 {
1807                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1808                                 goto err;
1809                                 }
1810                         if (!DH_generate_key(dh_clnt))
1811                                 {
1812                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1813                                 goto err;
1814                                 }
1815
1816                         /* use the 'p' output buffer for the DH key, but
1817                          * make sure to clear it out afterwards */
1818
1819                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
1820
1821                         if (n <= 0)
1822                                 {
1823                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1824                                 goto err;
1825                                 }
1826
1827                         /* generate master key from the result */
1828                         s->session->master_key_length=
1829                                 s->method->ssl3_enc->generate_master_secret(s,
1830                                         s->session->master_key,p,n);
1831                         /* clean up */
1832                         memset(p,0,n);
1833
1834                         /* send off the data */
1835                         n=BN_num_bytes(dh_clnt->pub_key);
1836                         s2n(n,p);
1837                         BN_bn2bin(dh_clnt->pub_key,p);
1838                         n+=2;
1839
1840                         DH_free(dh_clnt);
1841
1842                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
1843                         }
1844 #endif
1845
1846 #ifndef OPENSSL_NO_ECDH 
1847                 else if ((l & SSL_kECDH) || (l & SSL_kECDHE))
1848                         {
1849                         EC_GROUP *srvr_group = NULL;
1850                         int ecdh_clnt_cert = 0;
1851
1852                         /* Did we send out the client's
1853                          * ECDH share for use in premaster
1854                          * computation as part of client certificate?
1855                          * If so, set ecdh_clnt_cert to 1.
1856                          */
1857                         if ((l & SSL_kECDH) && (s->cert != NULL)) 
1858                                 {
1859                                 /* XXX: For now, we do not support client
1860                                  * authentication using ECDH certificates.
1861                                  * To add such support, one needs to add
1862                                  * code that checks for appropriate 
1863                                  * conditions and sets ecdh_clnt_cert to 1.
1864                                  * For example, the cert have an ECC
1865                                  * key on the same curve as the server's
1866                                  * and the key should be authorized for
1867                                  * key agreement.
1868                                  *
1869                                  * One also needs to add code in ssl3_connect
1870                                  * to skip sending the certificate verify
1871                                  * message.
1872                                  *
1873                                  * if ((s->cert->key->privatekey != NULL) &&
1874                                  *     (s->cert->key->privatekey->type ==
1875                                  *      EVP_PKEY_EC) && ...)
1876                                  * ecdh_clnt_cert = 1;
1877                                  */
1878                                 }
1879
1880                         if (s->session->sess_cert->peer_ecdh_tmp != NULL)
1881                                 {
1882                                 srvr_group = s->session->sess_cert-> \
1883                                     peer_ecdh_tmp->group;
1884                                 srvr_ecpoint = s->session->sess_cert-> \
1885                                     peer_ecdh_tmp->pub_key;
1886                                 }
1887                         else
1888                                 {
1889                                 /* Get the Server Public Key from Cert */
1890                                 srvr_pub_pkey = X509_get_pubkey(s->session-> \
1891                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1892                                 if ((srvr_pub_pkey == NULL) ||
1893                                     (srvr_pub_pkey->type != EVP_PKEY_EC) ||
1894                                     (srvr_pub_pkey->pkey.eckey == NULL))
1895                                         {
1896                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
1897                                             ERR_R_INTERNAL_ERROR);
1898                                         goto err;
1899                                         }
1900
1901                                 srvr_group = srvr_pub_pkey->pkey.eckey->group;
1902                                 srvr_ecpoint = 
1903                                     srvr_pub_pkey->pkey.eckey->pub_key;
1904                                 }
1905
1906                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
1907                                 {
1908                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
1909                                     ERR_R_INTERNAL_ERROR);
1910                                 goto err;
1911                                 }
1912
1913                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
1914                                 {
1915                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1916                                 goto err;
1917                                 }
1918
1919                         clnt_ecdh->group = srvr_group;
1920                         if (ecdh_clnt_cert) 
1921                                 { 
1922                                 /* Reuse key info from our certificate
1923                                  * We only need our private key to perform
1924                                  * the ECDH computation.
1925                                  */
1926                                 clnt_ecdh->priv_key = BN_dup(s->cert->key-> \
1927                                     privatekey->pkey.eckey->priv_key);
1928                                 }
1929                         else 
1930                                 {
1931                                 /* Generate a new ECDH key pair */
1932                                 if (!(EC_KEY_generate_key(clnt_ecdh)))
1933                                         {
1934                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1935                                         goto err;
1936                                         }
1937                                 }
1938
1939                         /* use the 'p' output buffer for the ECDH key, but
1940                          * make sure to clear it out afterwards
1941                          */
1942
1943                         n=ECDH_compute_key(p, srvr_ecpoint, clnt_ecdh);
1944                         if (n <= 0)
1945                                 {
1946                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, 
1947                                        ERR_R_ECDH_LIB);
1948                                 goto err;
1949                                 }
1950
1951                         /* generate master key from the result */
1952                         s->session->master_key_length = s->method->ssl3_enc \
1953                             -> generate_master_secret(s, 
1954                                 s->session->master_key,
1955                                 p, n);
1956
1957                         memset(p, 0, n); /* clean up */
1958
1959                         if (ecdh_clnt_cert) 
1960                                 {
1961                                 /* Send empty client key exch message */
1962                                 n = 0;
1963                                 }
1964                         else 
1965                                 {
1966                                 /* First check the size of encoding and
1967                                  * allocate memory accordingly.
1968                                  */
1969                                 encoded_pt_len = 
1970                                     EC_POINT_point2oct(clnt_ecdh->group, 
1971                                         clnt_ecdh->pub_key, 
1972                                         POINT_CONVERSION_UNCOMPRESSED, 
1973                                         NULL, 0, NULL);
1974
1975                                 encodedPoint = (unsigned char *) 
1976                                     OPENSSL_malloc(encoded_pt_len * 
1977                                         sizeof(unsigned char)); 
1978                                 bn_ctx = BN_CTX_new();
1979                                 if ((encodedPoint == NULL) || 
1980                                     (bn_ctx == NULL)) 
1981                                         {
1982                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1983                                         goto err;
1984                                         }
1985
1986                                 /* Encode the public key */
1987                                 n = EC_POINT_point2oct(clnt_ecdh->group, 
1988                                     clnt_ecdh->pub_key, 
1989                                     POINT_CONVERSION_UNCOMPRESSED, 
1990                                     encodedPoint, encoded_pt_len, bn_ctx);
1991
1992                                 *p = n; /* length of encoded point */
1993                                 /* Encoded point will be copied here */
1994                                 p += 1; 
1995                                 /* copy the point */
1996                                 memcpy((unsigned char *)p, encodedPoint, n);
1997                                 /* increment n to account for length field */
1998                                 n += 1; 
1999                                 }
2000
2001                         /* Free allocated memory */
2002                         BN_CTX_free(bn_ctx);
2003                         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2004                         if (clnt_ecdh != NULL) 
2005                                 {
2006                                  /* group is shared */
2007                                  clnt_ecdh->group = NULL; 
2008                                  EC_KEY_free(clnt_ecdh);
2009                                 }
2010                         EVP_PKEY_free(srvr_pub_pkey);
2011                         }
2012 #endif /* !OPENSSL_NO_ECDH */
2013                 else
2014                         {
2015                         ssl3_send_alert(s, SSL3_AL_FATAL,
2016                             SSL_AD_HANDSHAKE_FAILURE);
2017                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2018                             ERR_R_INTERNAL_ERROR);
2019                         goto err;
2020                         }
2021                 
2022                 *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
2023                 l2n3(n,d);
2024
2025                 s->state=SSL3_ST_CW_KEY_EXCH_B;
2026                 /* number of bytes to write */
2027                 s->init_num=n+4;
2028                 s->init_off=0;
2029                 }
2030
2031         /* SSL3_ST_CW_KEY_EXCH_B */
2032         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2033 err:
2034 #ifndef OPENSSL_NO_ECDH
2035         BN_CTX_free(bn_ctx);
2036         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2037         if (clnt_ecdh != NULL) 
2038                 {
2039                 /* group is shared */
2040                 clnt_ecdh->group = NULL; 
2041                 EC_KEY_free(clnt_ecdh);
2042                 }
2043         EVP_PKEY_free(srvr_pub_pkey);
2044 #endif
2045         return(-1);
2046         }
2047
2048 static int ssl3_send_client_verify(SSL *s)
2049         {
2050         unsigned char *p,*d;
2051         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
2052         EVP_PKEY *pkey;
2053 #ifndef OPENSSL_NO_RSA
2054         unsigned u=0;
2055 #endif
2056         unsigned long n;
2057 #ifndef OPENSSL_NO_DSA
2058         int j;
2059 #endif
2060
2061         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
2062                 {
2063                 d=(unsigned char *)s->init_buf->data;
2064                 p= &(d[4]);
2065                 pkey=s->cert->key->privatekey;
2066
2067                 s->method->ssl3_enc->cert_verify_mac(s,&(s->s3->finish_dgst2),
2068                         &(data[MD5_DIGEST_LENGTH]));
2069
2070 #ifndef OPENSSL_NO_RSA
2071                 if (pkey->type == EVP_PKEY_RSA)
2072                         {
2073                         s->method->ssl3_enc->cert_verify_mac(s,
2074                                 &(s->s3->finish_dgst1),&(data[0]));
2075                         if (RSA_sign(NID_md5_sha1, data,
2076                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
2077                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
2078                                 {
2079                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
2080                                 goto err;
2081                                 }
2082                         s2n(u,p);
2083                         n=u+2;
2084                         }
2085                 else
2086 #endif
2087 #ifndef OPENSSL_NO_DSA
2088                         if (pkey->type == EVP_PKEY_DSA)
2089                         {
2090                         if (!DSA_sign(pkey->save_type,
2091                                 &(data[MD5_DIGEST_LENGTH]),
2092                                 SHA_DIGEST_LENGTH,&(p[2]),
2093                                 (unsigned int *)&j,pkey->pkey.dsa))
2094                                 {
2095                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
2096                                 goto err;
2097                                 }
2098                         s2n(j,p);
2099                         n=j+2;
2100                         }
2101                 else
2102 #endif
2103 #ifndef OPENSSL_NO_ECDSA
2104                         if (pkey->type == EVP_PKEY_EC)
2105                         {
2106                         if (!ECDSA_sign(pkey->save_type,
2107                                 &(data[MD5_DIGEST_LENGTH]),
2108                                 SHA_DIGEST_LENGTH,&(p[2]),
2109                                 (unsigned int *)&j,pkey->pkey.eckey))
2110                                 {
2111                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
2112                                     ERR_R_ECDSA_LIB);
2113                                 goto err;
2114                                 }
2115                         s2n(j,p);
2116                         n=j+2;
2117                         }
2118                 else
2119 #endif
2120                         {
2121                         SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
2122                         goto err;
2123                         }
2124                 *(d++)=SSL3_MT_CERTIFICATE_VERIFY;
2125                 l2n3(n,d);
2126
2127                 s->init_num=(int)n+4;
2128                 s->init_off=0;
2129                 }
2130         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2131 err:
2132         return(-1);
2133         }
2134
2135 static int ssl3_send_client_certificate(SSL *s)
2136         {
2137         X509 *x509=NULL;
2138         EVP_PKEY *pkey=NULL;
2139         int i;
2140         unsigned long l;
2141
2142         if (s->state == SSL3_ST_CW_CERT_A)
2143                 {
2144                 if ((s->cert == NULL) ||
2145                         (s->cert->key->x509 == NULL) ||
2146                         (s->cert->key->privatekey == NULL))
2147                         s->state=SSL3_ST_CW_CERT_B;
2148                 else
2149                         s->state=SSL3_ST_CW_CERT_C;
2150                 }
2151
2152         /* We need to get a client cert */
2153         if (s->state == SSL3_ST_CW_CERT_B)
2154                 {
2155                 /* If we get an error, we need to
2156                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
2157                  * We then get retied later */
2158                 i=0;
2159                 if (s->ctx->client_cert_cb != NULL)
2160                         i=s->ctx->client_cert_cb(s,&(x509),&(pkey));
2161                 if (i < 0)
2162                         {
2163                         s->rwstate=SSL_X509_LOOKUP;
2164                         return(-1);
2165                         }
2166                 s->rwstate=SSL_NOTHING;
2167                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
2168                         {
2169                         s->state=SSL3_ST_CW_CERT_B;
2170                         if (    !SSL_use_certificate(s,x509) ||
2171                                 !SSL_use_PrivateKey(s,pkey))
2172                                 i=0;
2173                         }
2174                 else if (i == 1)
2175                         {
2176                         i=0;
2177                         SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2178                         }
2179
2180                 if (x509 != NULL) X509_free(x509);
2181                 if (pkey != NULL) EVP_PKEY_free(pkey);
2182                 if (i == 0)
2183                         {
2184                         if (s->version == SSL3_VERSION)
2185                                 {
2186                                 s->s3->tmp.cert_req=0;
2187                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
2188                                 return(1);
2189                                 }
2190                         else
2191                                 {
2192                                 s->s3->tmp.cert_req=2;
2193                                 }
2194                         }
2195
2196                 /* Ok, we have a cert */
2197                 s->state=SSL3_ST_CW_CERT_C;
2198                 }
2199
2200         if (s->state == SSL3_ST_CW_CERT_C)
2201                 {
2202                 s->state=SSL3_ST_CW_CERT_D;
2203                 l=ssl3_output_cert_chain(s,
2204                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
2205                 s->init_num=(int)l;
2206                 s->init_off=0;
2207                 }
2208         /* SSL3_ST_CW_CERT_D */
2209         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2210         }
2211
2212 #define has_bits(i,m)   (((i)&(m)) == (m))
2213
2214 static int ssl3_check_cert_and_algorithm(SSL *s)
2215         {
2216         int i,idx;
2217         long algs;
2218         EVP_PKEY *pkey=NULL;
2219         SESS_CERT *sc;
2220 #ifndef OPENSSL_NO_RSA
2221         RSA *rsa;
2222 #endif
2223 #ifndef OPENSSL_NO_DH
2224         DH *dh;
2225 #endif
2226
2227         sc=s->session->sess_cert;
2228
2229         if (sc == NULL)
2230                 {
2231                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR);
2232                 goto err;
2233                 }
2234
2235         algs=s->s3->tmp.new_cipher->algorithms;
2236
2237         /* we don't have a certificate */
2238         if (algs & (SSL_aDH|SSL_aNULL|SSL_aKRB5))
2239                 return(1);
2240
2241 #ifndef OPENSSL_NO_RSA
2242         rsa=s->session->sess_cert->peer_rsa_tmp;
2243 #endif
2244 #ifndef OPENSSL_NO_DH
2245         dh=s->session->sess_cert->peer_dh_tmp;
2246 #endif
2247
2248         /* This is the passed certificate */
2249
2250         idx=sc->peer_cert_type;
2251 #ifndef OPENSSL_NO_ECDH
2252         if (idx == SSL_PKEY_ECC)
2253                 {
2254                 if (check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509,
2255                     s->s3->tmp.new_cipher) == 0) 
2256                         { /* check failed */
2257                         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT);
2258                         goto f_err;                     
2259                         }
2260                 else 
2261                         {
2262                         return 1;
2263                         }
2264                 }
2265 #endif
2266         pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
2267         i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
2268         EVP_PKEY_free(pkey);
2269
2270         
2271         /* Check that we have a certificate if we require one */
2272         if ((algs & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
2273                 {
2274                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT);
2275                 goto f_err;
2276                 }
2277 #ifndef OPENSSL_NO_DSA
2278         else if ((algs & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN))
2279                 {
2280                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT);
2281                 goto f_err;
2282                 }
2283 #endif
2284 #ifndef OPENSSL_NO_RSA
2285         if ((algs & SSL_kRSA) &&
2286                 !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
2287                 {
2288                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2289                 goto f_err;
2290                 }
2291 #endif
2292 #ifndef OPENSSL_NO_DH
2293         if ((algs & SSL_kEDH) &&
2294                 !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
2295                 {
2296                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY);
2297                 goto f_err;
2298                 }
2299         else if ((algs & SSL_kDHr) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA))
2300                 {
2301                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT);
2302                 goto f_err;
2303                 }
2304 #ifndef OPENSSL_NO_DSA
2305         else if ((algs & SSL_kDHd) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA))
2306                 {
2307                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT);
2308                 goto f_err;
2309                 }
2310 #endif
2311 #endif
2312
2313         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP))
2314                 {
2315 #ifndef OPENSSL_NO_RSA
2316                 if (algs & SSL_kRSA)
2317                         {
2318                         if (rsa == NULL
2319                             || RSA_size(rsa) > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
2320                                 {
2321                                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
2322                                 goto f_err;
2323                                 }
2324                         }
2325                 else
2326 #endif
2327 #ifndef OPENSSL_NO_DH
2328                         if (algs & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2329                             {
2330                             if (dh == NULL
2331                                 || DH_size(dh) > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
2332                                 {
2333                                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY);
2334                                 goto f_err;
2335                                 }
2336                         }
2337                 else
2338 #endif
2339                         {
2340                         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2341                         goto f_err;
2342                         }
2343                 }
2344         return(1);
2345 f_err:
2346         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
2347 err:
2348         return(0);
2349         }
2350
2351
2352 #ifndef OPENSSL_NO_ECDH
2353 /* This is the complement of nid2curve_id in s3_srvr.c. */
2354 static int curve_id2nid(int curve_id)
2355 {
2356         /* ECC curves from draft-ietf-tls-ecc-01.txt (Mar 15, 2001) */
2357         static int nid_list[26] =
2358         {
2359                 0,
2360                 NID_sect163k1, /* sect163k1 (1) */
2361                 NID_sect163r1, /* sect163r1 (2) */
2362                 NID_sect163r2, /* sect163r2 (3) */
2363                 NID_sect193r1, /* sect193r1 (4) */ 
2364                 NID_sect193r2, /* sect193r2 (5) */ 
2365                 NID_sect233k1, /* sect233k1 (6) */
2366                 NID_sect233r1, /* sect233r1 (7) */ 
2367                 NID_sect239k1, /* sect239k1 (8) */ 
2368                 NID_sect283k1, /* sect283k1 (9) */
2369                 NID_sect283r1, /* sect283r1 (10) */ 
2370                 NID_sect409k1, /* sect409k1 (11) */ 
2371                 NID_sect409r1, /* sect409r1 (12) */
2372                 NID_sect571k1, /* sect571k1 (13) */ 
2373                 NID_sect571r1, /* sect571r1 (14) */ 
2374                 NID_secp160k1, /* secp160k1 (15) */
2375                 NID_secp160r1, /* secp160r1 (16) */ 
2376                 NID_secp160r2, /* secp160r2 (17) */ 
2377                 NID_secp192k1, /* secp192k1 (18) */
2378                 NID_X9_62_prime192v1, /* secp192r1 (19) */ 
2379                 NID_secp224k1, /* secp224k1 (20) */ 
2380                 NID_secp224r1, /* secp224r1 (21) */
2381                 NID_secp256k1, /* secp256k1 (22) */ 
2382                 NID_X9_62_prime256v1, /* secp256r1 (23) */ 
2383                 NID_secp384r1, /* secp384r1 (24) */
2384                 NID_secp521r1  /* secp521r1 (25) */     
2385         };
2386         
2387         if ((curve_id < 1) || (curve_id > 25)) return 0;
2388
2389         return nid_list[curve_id];
2390 }
2391 #endif