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