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