Typo.
[oweals/openssl.git] / ssl / s3_clnt.c
1 /* ssl/s3_clnt.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include <stdio.h>
113 #include "ssl_locl.h"
114 #include "kssl_lcl.h"
115 #include <openssl/buffer.h>
116 #include <openssl/rand.h>
117 #include <openssl/objects.h>
118 #include <openssl/evp.h>
119 #include <openssl/md5.h>
120 #include "cryptlib.h"
121
122 static SSL_METHOD *ssl3_get_client_method(int ver);
123 static int ssl3_client_hello(SSL *s);
124 static int ssl3_get_server_hello(SSL *s);
125 static int ssl3_get_certificate_request(SSL *s);
126 static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b);
127 static int ssl3_get_server_done(SSL *s);
128 static int ssl3_send_client_verify(SSL *s);
129 static int ssl3_send_client_certificate(SSL *s);
130 static int ssl3_send_client_key_exchange(SSL *s);
131 static int ssl3_get_key_exchange(SSL *s);
132 static int ssl3_get_server_certificate(SSL *s);
133 static int ssl3_check_cert_and_algorithm(SSL *s);
134 static SSL_METHOD *ssl3_get_client_method(int ver)
135         {
136         if (ver == SSL3_VERSION)
137                 return(SSLv3_client_method());
138         else
139                 return(NULL);
140         }
141
142 SSL_METHOD *SSLv3_client_method(void)
143         {
144         static int init=1;
145         static SSL_METHOD SSLv3_client_data;
146
147         if (init)
148                 {
149                 CRYPTO_w_lock(CRYPTO_LOCK_SSL_METHOD);
150
151                 if (init)
152                         {
153                         memcpy((char *)&SSLv3_client_data,(char *)sslv3_base_method(),
154                                 sizeof(SSL_METHOD));
155                         SSLv3_client_data.ssl_connect=ssl3_connect;
156                         SSLv3_client_data.get_ssl_method=ssl3_get_client_method;
157                         init=0;
158                         }
159
160                 CRYPTO_w_unlock(CRYPTO_LOCK_SSL_METHOD);
161                 }
162         return(&SSLv3_client_data);
163         }
164
165 int ssl3_connect(SSL *s)
166         {
167         BUF_MEM *buf=NULL;
168         unsigned long Time=time(NULL),l;
169         long num1;
170         void (*cb)(const SSL *ssl,int type,int val)=NULL;
171         int ret= -1;
172         int new_state,state,skip=0;;
173
174         RAND_add(&Time,sizeof(Time),0);
175         ERR_clear_error();
176         clear_sys_error();
177
178         if (s->info_callback != NULL)
179                 cb=s->info_callback;
180         else if (s->ctx->info_callback != NULL)
181                 cb=s->ctx->info_callback;
182         
183         s->in_handshake++;
184         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); 
185
186         for (;;)
187                 {
188                 state=s->state;
189
190                 switch(s->state)
191                         {
192                 case SSL_ST_RENEGOTIATE:
193                         s->new_session=1;
194                         s->state=SSL_ST_CONNECT;
195                         s->ctx->stats.sess_connect_renegotiate++;
196                         /* break */
197                 case SSL_ST_BEFORE:
198                 case SSL_ST_CONNECT:
199                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
200                 case SSL_ST_OK|SSL_ST_CONNECT:
201
202                         s->server=0;
203                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
204
205                         if ((s->version & 0xff00 ) != 0x0300)
206                                 {
207                                 SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
208                                 ret = -1;
209                                 goto end;
210                                 }
211                                 
212                         /* s->version=SSL3_VERSION; */
213                         s->type=SSL_ST_CONNECT;
214
215                         if (s->init_buf == NULL)
216                                 {
217                                 if ((buf=BUF_MEM_new()) == NULL)
218                                         {
219                                         ret= -1;
220                                         goto end;
221                                         }
222                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
223                                         {
224                                         ret= -1;
225                                         goto end;
226                                         }
227                                 s->init_buf=buf;
228                                 buf=NULL;
229                                 }
230
231                         if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
232
233                         /* setup buffing BIO */
234                         if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
235
236                         /* don't push the buffering BIO quite yet */
237
238                         ssl3_init_finished_mac(s);
239
240                         s->state=SSL3_ST_CW_CLNT_HELLO_A;
241                         s->ctx->stats.sess_connect++;
242                         s->init_num=0;
243                         break;
244
245                 case SSL3_ST_CW_CLNT_HELLO_A:
246                 case SSL3_ST_CW_CLNT_HELLO_B:
247
248                         s->shutdown=0;
249                         ret=ssl3_client_hello(s);
250                         if (ret <= 0) goto end;
251                         s->state=SSL3_ST_CR_SRVR_HELLO_A;
252                         s->init_num=0;
253
254                         /* turn on buffering for the next lot of output */
255                         if (s->bbio != s->wbio)
256                                 s->wbio=BIO_push(s->bbio,s->wbio);
257
258                         break;
259
260                 case SSL3_ST_CR_SRVR_HELLO_A:
261                 case SSL3_ST_CR_SRVR_HELLO_B:
262                         ret=ssl3_get_server_hello(s);
263                         if (ret <= 0) goto end;
264                         if (s->hit)
265                                 s->state=SSL3_ST_CR_FINISHED_A;
266                         else
267                                 s->state=SSL3_ST_CR_CERT_A;
268                         s->init_num=0;
269                         break;
270
271                 case SSL3_ST_CR_CERT_A:
272                 case SSL3_ST_CR_CERT_B:
273                         /* Check if it is anon DH */
274                         if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
275                                 {
276                                 ret=ssl3_get_server_certificate(s);
277                                 if (ret <= 0) goto end;
278                                 }
279                         else
280                                 skip=1;
281                         s->state=SSL3_ST_CR_KEY_EXCH_A;
282                         s->init_num=0;
283                         break;
284
285                 case SSL3_ST_CR_KEY_EXCH_A:
286                 case SSL3_ST_CR_KEY_EXCH_B:
287                         ret=ssl3_get_key_exchange(s);
288                         if (ret <= 0) goto end;
289                         s->state=SSL3_ST_CR_CERT_REQ_A;
290                         s->init_num=0;
291
292                         /* at this point we check that we have the
293                          * required stuff from the server */
294                         if (!ssl3_check_cert_and_algorithm(s))
295                                 {
296                                 ret= -1;
297                                 goto end;
298                                 }
299                         break;
300
301                 case SSL3_ST_CR_CERT_REQ_A:
302                 case SSL3_ST_CR_CERT_REQ_B:
303                         ret=ssl3_get_certificate_request(s);
304                         if (ret <= 0) goto end;
305                         s->state=SSL3_ST_CR_SRVR_DONE_A;
306                         s->init_num=0;
307                         break;
308
309                 case SSL3_ST_CR_SRVR_DONE_A:
310                 case SSL3_ST_CR_SRVR_DONE_B:
311                         ret=ssl3_get_server_done(s);
312                         if (ret <= 0) goto end;
313                         if (s->s3->tmp.cert_req)
314                                 s->state=SSL3_ST_CW_CERT_A;
315                         else
316                                 s->state=SSL3_ST_CW_KEY_EXCH_A;
317                         s->init_num=0;
318
319                         break;
320
321                 case SSL3_ST_CW_CERT_A:
322                 case SSL3_ST_CW_CERT_B:
323                 case SSL3_ST_CW_CERT_C:
324                 case SSL3_ST_CW_CERT_D:
325                         ret=ssl3_send_client_certificate(s);
326                         if (ret <= 0) goto end;
327                         s->state=SSL3_ST_CW_KEY_EXCH_A;
328                         s->init_num=0;
329                         break;
330
331                 case SSL3_ST_CW_KEY_EXCH_A:
332                 case SSL3_ST_CW_KEY_EXCH_B:
333                         ret=ssl3_send_client_key_exchange(s);
334                         if (ret <= 0) goto end;
335                         l=s->s3->tmp.new_cipher->algorithms;
336                         /* EAY EAY EAY need to check for DH fix cert
337                          * sent back */
338                         /* For TLS, cert_req is set to 2, so a cert chain
339                          * of nothing is sent, but no verify packet is sent */
340                         if (s->s3->tmp.cert_req == 1)
341                                 {
342                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
343                                 }
344                         else
345                                 {
346                                 s->state=SSL3_ST_CW_CHANGE_A;
347                                 s->s3->change_cipher_spec=0;
348                                 }
349
350                         s->init_num=0;
351                         break;
352
353                 case SSL3_ST_CW_CERT_VRFY_A:
354                 case SSL3_ST_CW_CERT_VRFY_B:
355                         ret=ssl3_send_client_verify(s);
356                         if (ret <= 0) goto end;
357                         s->state=SSL3_ST_CW_CHANGE_A;
358                         s->init_num=0;
359                         s->s3->change_cipher_spec=0;
360                         break;
361
362                 case SSL3_ST_CW_CHANGE_A:
363                 case SSL3_ST_CW_CHANGE_B:
364                         ret=ssl3_send_change_cipher_spec(s,
365                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
366                         if (ret <= 0) goto end;
367                         s->state=SSL3_ST_CW_FINISHED_A;
368                         s->init_num=0;
369
370                         s->session->cipher=s->s3->tmp.new_cipher;
371                         if (s->s3->tmp.new_compression == NULL)
372                                 s->session->compress_meth=0;
373                         else
374                                 s->session->compress_meth=
375                                         s->s3->tmp.new_compression->id;
376                         if (!s->method->ssl3_enc->setup_key_block(s))
377                                 {
378                                 ret= -1;
379                                 goto end;
380                                 }
381
382                         if (!s->method->ssl3_enc->change_cipher_state(s,
383                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
384                                 {
385                                 ret= -1;
386                                 goto end;
387                                 }
388
389                         break;
390
391                 case SSL3_ST_CW_FINISHED_A:
392                 case SSL3_ST_CW_FINISHED_B:
393                         ret=ssl3_send_finished(s,
394                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
395                                 s->method->ssl3_enc->client_finished_label,
396                                 s->method->ssl3_enc->client_finished_label_len);
397                         if (ret <= 0) goto end;
398                         s->state=SSL3_ST_CW_FLUSH;
399
400                         /* clear flags */
401                         s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
402                         if (s->hit)
403                                 {
404                                 s->s3->tmp.next_state=SSL_ST_OK;
405                                 if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
406                                         {
407                                         s->state=SSL_ST_OK;
408                                         s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
409                                         s->s3->delay_buf_pop_ret=0;
410                                         }
411                                 }
412                         else
413                                 {
414                                 s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
415                                 }
416                         s->init_num=0;
417                         break;
418
419                 case SSL3_ST_CR_FINISHED_A:
420                 case SSL3_ST_CR_FINISHED_B:
421
422                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
423                                 SSL3_ST_CR_FINISHED_B);
424                         if (ret <= 0) goto end;
425
426                         if (s->hit)
427                                 s->state=SSL3_ST_CW_CHANGE_A;
428                         else
429                                 s->state=SSL_ST_OK;
430                         s->init_num=0;
431                         break;
432
433                 case SSL3_ST_CW_FLUSH:
434                         /* number of bytes to be flushed */
435                         num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
436                         if (num1 > 0)
437                                 {
438                                 s->rwstate=SSL_WRITING;
439                                 num1=BIO_flush(s->wbio);
440                                 if (num1 <= 0) { ret= -1; goto end; }
441                                 s->rwstate=SSL_NOTHING;
442                                 }
443
444                         s->state=s->s3->tmp.next_state;
445                         break;
446
447                 case SSL_ST_OK:
448                         /* clean a few things up */
449                         ssl3_cleanup_key_block(s);
450
451                         if (s->init_buf != NULL)
452                                 {
453                                 BUF_MEM_free(s->init_buf);
454                                 s->init_buf=NULL;
455                                 }
456
457                         /* If we are not 'joining' the last two packets,
458                          * remove the buffering now */
459                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
460                                 ssl_free_wbio_buffer(s);
461                         /* else do it later in ssl3_write */
462
463                         s->init_num=0;
464                         s->new_session=0;
465
466                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
467                         if (s->hit) s->ctx->stats.sess_hit++;
468
469                         ret=1;
470                         /* s->server=0; */
471                         s->handshake_func=ssl3_connect;
472                         s->ctx->stats.sess_connect_good++;
473
474                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
475
476                         goto end;
477                         /* break; */
478                         
479                 default:
480                         SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);
481                         ret= -1;
482                         goto end;
483                         /* break; */
484                         }
485
486                 /* did we do anything */
487                 if (!s->s3->tmp.reuse_message && !skip)
488                         {
489                         if (s->debug)
490                                 {
491                                 if ((ret=BIO_flush(s->wbio)) <= 0)
492                                         goto end;
493                                 }
494
495                         if ((cb != NULL) && (s->state != state))
496                                 {
497                                 new_state=s->state;
498                                 s->state=state;
499                                 cb(s,SSL_CB_CONNECT_LOOP,1);
500                                 s->state=new_state;
501                                 }
502                         }
503                 skip=0;
504                 }
505 end:
506         s->in_handshake--;
507         if (buf != NULL)
508                 BUF_MEM_free(buf);
509         if (cb != NULL)
510                 cb(s,SSL_CB_CONNECT_EXIT,ret);
511         return(ret);
512         }
513
514
515 static int ssl3_client_hello(SSL *s)
516         {
517         unsigned char *buf;
518         unsigned char *p,*d;
519         int i,j;
520         unsigned long Time,l;
521         SSL_COMP *comp;
522
523         buf=(unsigned char *)s->init_buf->data;
524         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
525                 {
526                 if ((s->session == NULL) ||
527                         (s->session->ssl_version != s->version) ||
528                         (s->session->not_resumable))
529                         {
530                         if (!ssl_get_new_session(s,0))
531                                 goto err;
532                         }
533                 /* else use the pre-loaded session */
534
535                 p=s->s3->client_random;
536                 Time=time(NULL);                        /* Time */
537                 l2n(Time,p);
538                 RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-sizeof(Time));
539
540                 /* Do the message type and length last */
541                 d=p= &(buf[4]);
542
543                 *(p++)=s->version>>8;
544                 *(p++)=s->version&0xff;
545                 s->client_version=s->version;
546
547                 /* Random stuff */
548                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
549                 p+=SSL3_RANDOM_SIZE;
550
551                 /* Session ID */
552                 if (s->new_session)
553                         i=0;
554                 else
555                         i=s->session->session_id_length;
556                 *(p++)=i;
557                 if (i != 0)
558                         {
559                         if (i > sizeof s->session->session_id)
560                                 {
561                                 SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
562                                 goto err;
563                                 }
564                         memcpy(p,s->session->session_id,i);
565                         p+=i;
566                         }
567                 
568                 /* Ciphers supported */
569                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]));
570                 if (i == 0)
571                         {
572                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
573                         goto err;
574                         }
575                 s2n(i,p);
576                 p+=i;
577
578                 /* COMPRESSION */
579                 if (s->ctx->comp_methods == NULL)
580                         j=0;
581                 else
582                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
583                 *(p++)=1+j;
584                 for (i=0; i<j; i++)
585                         {
586                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
587                         *(p++)=comp->id;
588                         }
589                 *(p++)=0; /* Add the NULL method */
590                 
591                 l=(p-d);
592                 d=buf;
593                 *(d++)=SSL3_MT_CLIENT_HELLO;
594                 l2n3(l,d);
595
596                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
597                 /* number of bytes to write */
598                 s->init_num=p-buf;
599                 s->init_off=0;
600                 }
601
602         /* SSL3_ST_CW_CLNT_HELLO_B */
603         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
604 err:
605         return(-1);
606         }
607
608 static int ssl3_get_server_hello(SSL *s)
609         {
610         STACK_OF(SSL_CIPHER) *sk;
611         SSL_CIPHER *c;
612         unsigned char *p,*d;
613         int i,al,ok;
614         unsigned int j;
615         long n;
616         SSL_COMP *comp;
617
618         n=ssl3_get_message(s,
619                 SSL3_ST_CR_SRVR_HELLO_A,
620                 SSL3_ST_CR_SRVR_HELLO_B,
621                 SSL3_MT_SERVER_HELLO,
622                 300, /* ?? */
623                 &ok);
624
625         if (!ok) return((int)n);
626         d=p=(unsigned char *)s->init_msg;
627
628         if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff)))
629                 {
630                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION);
631                 s->version=(s->version&0xff00)|p[1];
632                 al=SSL_AD_PROTOCOL_VERSION;
633                 goto f_err;
634                 }
635         p+=2;
636
637         /* load the server hello data */
638         /* load the server random */
639         memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE);
640         p+=SSL3_RANDOM_SIZE;
641
642         /* get the session-id */
643         j= *(p++);
644
645         if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE))
646                 {
647                 al=SSL_AD_ILLEGAL_PARAMETER;
648                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG);
649                 goto f_err;
650                 }
651
652         if (j != 0 && j == s->session->session_id_length
653             && memcmp(p,s->session->session_id,j) == 0)
654             {
655             if(s->sid_ctx_length != s->session->sid_ctx_length
656                || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length))
657                 {
658                 /* actually a client application bug */
659                 al=SSL_AD_ILLEGAL_PARAMETER;
660                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
661                 goto f_err;
662                 }
663             s->hit=1;
664             }
665         else    /* a miss or crap from the other end */
666                 {
667                 /* If we were trying for session-id reuse, make a new
668                  * SSL_SESSION so we don't stuff up other people */
669                 s->hit=0;
670                 if (s->session->session_id_length > 0)
671                         {
672                         if (!ssl_get_new_session(s,0))
673                                 {
674                                 al=SSL_AD_INTERNAL_ERROR;
675                                 goto f_err;
676                                 }
677                         }
678                 s->session->session_id_length=j;
679                 memcpy(s->session->session_id,p,j); /* j could be 0 */
680                 }
681         p+=j;
682         c=ssl_get_cipher_by_char(s,p);
683         if (c == NULL)
684                 {
685                 /* unknown cipher */
686                 al=SSL_AD_ILLEGAL_PARAMETER;
687                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED);
688                 goto f_err;
689                 }
690         p+=ssl_put_cipher_by_char(s,NULL,NULL);
691
692         sk=ssl_get_ciphers_by_id(s);
693         i=sk_SSL_CIPHER_find(sk,c);
694         if (i < 0)
695                 {
696                 /* we did not say we would use this cipher */
697                 al=SSL_AD_ILLEGAL_PARAMETER;
698                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
699                 goto f_err;
700                 }
701
702         /* Depending on the session caching (internal/external), the cipher
703            and/or cipher_id values may not be set. Make sure that
704            cipher_id is set and use it for comparison. */
705         if (s->session->cipher)
706                 s->session->cipher_id = s->session->cipher->id;
707         if (s->hit && (s->session->cipher_id != c->id))
708                 {
709                 if (!(s->options &
710                         SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
711                         {
712                         al=SSL_AD_ILLEGAL_PARAMETER;
713                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
714                         goto f_err;
715                         }
716                 }
717         s->s3->tmp.new_cipher=c;
718
719         /* lets get the compression algorithm */
720         /* COMPRESSION */
721         j= *(p++);
722         if (j == 0)
723                 comp=NULL;
724         else
725                 comp=ssl3_comp_find(s->ctx->comp_methods,j);
726         
727         if ((j != 0) && (comp == NULL))
728                 {
729                 al=SSL_AD_ILLEGAL_PARAMETER;
730                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
731                 goto f_err;
732                 }
733         else
734                 {
735                 s->s3->tmp.new_compression=comp;
736                 }
737
738         if (p != (d+n))
739                 {
740                 /* wrong packet length */
741                 al=SSL_AD_DECODE_ERROR;
742                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH);
743                 goto err;
744                 }
745
746         return(1);
747 f_err:
748         ssl3_send_alert(s,SSL3_AL_FATAL,al);
749 err:
750         return(-1);
751         }
752
753 static int ssl3_get_server_certificate(SSL *s)
754         {
755         int al,i,ok,ret= -1;
756         unsigned long n,nc,llen,l;
757         X509 *x=NULL;
758         unsigned char *p,*d,*q;
759         STACK_OF(X509) *sk=NULL;
760         SESS_CERT *sc;
761         EVP_PKEY *pkey=NULL;
762         int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */
763
764         n=ssl3_get_message(s,
765                 SSL3_ST_CR_CERT_A,
766                 SSL3_ST_CR_CERT_B,
767                 -1,
768                 s->max_cert_list,
769                 &ok);
770
771         if (!ok) return((int)n);
772
773         if (s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE)
774                 {
775                 s->s3->tmp.reuse_message=1;
776                 return(1);
777                 }
778
779         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
780                 {
781                 al=SSL_AD_UNEXPECTED_MESSAGE;
782                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE);
783                 goto f_err;
784                 }
785         d=p=(unsigned char *)s->init_msg;
786
787         if ((sk=sk_X509_new_null()) == NULL)
788                 {
789                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
790                 goto err;
791                 }
792
793         n2l3(p,llen);
794         if (llen+3 != n)
795                 {
796                 al=SSL_AD_DECODE_ERROR;
797                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
798                 goto f_err;
799                 }
800         for (nc=0; nc<llen; )
801                 {
802                 n2l3(p,l);
803                 if ((l+nc+3) > llen)
804                         {
805                         al=SSL_AD_DECODE_ERROR;
806                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
807                         goto f_err;
808                         }
809
810                 q=p;
811                 x=d2i_X509(NULL,&q,l);
812                 if (x == NULL)
813                         {
814                         al=SSL_AD_BAD_CERTIFICATE;
815                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB);
816                         goto f_err;
817                         }
818                 if (q != (p+l))
819                         {
820                         al=SSL_AD_DECODE_ERROR;
821                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
822                         goto f_err;
823                         }
824                 if (!sk_X509_push(sk,x))
825                         {
826                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
827                         goto err;
828                         }
829                 x=NULL;
830                 nc+=l+3;
831                 p=q;
832                 }
833
834         i=ssl_verify_cert_chain(s,sk);
835         if ((s->verify_mode != SSL_VERIFY_NONE) && (!i)
836 #ifndef OPENSSL_NO_KRB5
837                 && (s->s3->tmp.new_cipher->algorithms & (SSL_MKEY_MASK|SSL_AUTH_MASK))
838                 != (SSL_aKRB5|SSL_kKRB5)
839 #endif /* OPENSSL_NO_KRB5 */
840                 )
841                 {
842                 al=ssl_verify_alarm_type(s->verify_result);
843                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
844                 goto f_err; 
845                 }
846         ERR_clear_error(); /* but we keep s->verify_result */
847
848         sc=ssl_sess_cert_new();
849         if (sc == NULL) goto err;
850
851         if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
852         s->session->sess_cert=sc;
853
854         sc->cert_chain=sk;
855         /* Inconsistency alert: cert_chain does include the peer's
856          * certificate, which we don't include in s3_srvr.c */
857         x=sk_X509_value(sk,0);
858         sk=NULL;
859         /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
860
861         pkey=X509_get_pubkey(x);
862
863         /* VRS: allow null cert if auth == KRB5 */
864         need_cert =     ((s->s3->tmp.new_cipher->algorithms
865                         & (SSL_MKEY_MASK|SSL_AUTH_MASK))
866                         == (SSL_aKRB5|SSL_kKRB5))? 0: 1;
867
868 #ifdef KSSL_DEBUG
869         printf("pkey,x = %p, %p\n", pkey,x);
870         printf("ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey));
871         printf("cipher, alg, nc = %s, %lx, %d\n", s->s3->tmp.new_cipher->name,
872                 s->s3->tmp.new_cipher->algorithms, need_cert);
873 #endif    /* KSSL_DEBUG */
874
875         if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey)))
876                 {
877                 x=NULL;
878                 al=SSL3_AL_FATAL;
879                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
880                         SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
881                 goto f_err;
882                 }
883
884         i=ssl_cert_type(x,pkey);
885         if (need_cert && i < 0)
886                 {
887                 x=NULL;
888                 al=SSL3_AL_FATAL;
889                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
890                         SSL_R_UNKNOWN_CERTIFICATE_TYPE);
891                 goto f_err;
892                 }
893
894         if (need_cert)
895                 {
896                 sc->peer_cert_type=i;
897                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
898                 /* Why would the following ever happen?
899                  * We just created sc a couple of lines ago. */
900                 if (sc->peer_pkeys[i].x509 != NULL)
901                         X509_free(sc->peer_pkeys[i].x509);
902                 sc->peer_pkeys[i].x509=x;
903                 sc->peer_key= &(sc->peer_pkeys[i]);
904
905                 if (s->session->peer != NULL)
906                         X509_free(s->session->peer);
907                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
908                 s->session->peer=x;
909                 }
910         else
911                 {
912                 sc->peer_cert_type=i;
913                 sc->peer_key= NULL;
914
915                 if (s->session->peer != NULL)
916                         X509_free(s->session->peer);
917                 s->session->peer=NULL;
918                 }
919         s->session->verify_result = s->verify_result;
920
921         x=NULL;
922         ret=1;
923
924         if (0)
925                 {
926 f_err:
927                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
928                 }
929 err:
930         EVP_PKEY_free(pkey);
931         X509_free(x);
932         sk_X509_pop_free(sk,X509_free);
933         return(ret);
934         }
935
936 static int ssl3_get_key_exchange(SSL *s)
937         {
938 #ifndef OPENSSL_NO_RSA
939         unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];
940 #endif
941         EVP_MD_CTX md_ctx;
942         unsigned char *param,*p;
943         int al,i,j,param_len,ok;
944         long n,alg;
945         EVP_PKEY *pkey=NULL;
946 #ifndef OPENSSL_NO_RSA
947         RSA *rsa=NULL;
948 #endif
949 #ifndef OPENSSL_NO_DH
950         DH *dh=NULL;
951 #endif
952
953         /* use same message size as in ssl3_get_certificate_request()
954          * as ServerKeyExchange message may be skipped */
955         n=ssl3_get_message(s,
956                 SSL3_ST_CR_KEY_EXCH_A,
957                 SSL3_ST_CR_KEY_EXCH_B,
958                 -1,
959                 s->max_cert_list,
960                 &ok);
961
962         if (!ok) return((int)n);
963
964         if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
965                 {
966                 s->s3->tmp.reuse_message=1;
967                 return(1);
968                 }
969
970         param=p=(unsigned char *)s->init_msg;
971
972         if (s->session->sess_cert != NULL)
973                 {
974 #ifndef OPENSSL_NO_RSA
975                 if (s->session->sess_cert->peer_rsa_tmp != NULL)
976                         {
977                         RSA_free(s->session->sess_cert->peer_rsa_tmp);
978                         s->session->sess_cert->peer_rsa_tmp=NULL;
979                         }
980 #endif
981 #ifndef OPENSSL_NO_DH
982                 if (s->session->sess_cert->peer_dh_tmp)
983                         {
984                         DH_free(s->session->sess_cert->peer_dh_tmp);
985                         s->session->sess_cert->peer_dh_tmp=NULL;
986                         }
987 #endif
988                 }
989         else
990                 {
991                 s->session->sess_cert=ssl_sess_cert_new();
992                 }
993
994         param_len=0;
995         alg=s->s3->tmp.new_cipher->algorithms;
996         EVP_MD_CTX_init(&md_ctx);
997
998 #ifndef OPENSSL_NO_RSA
999         if (alg & SSL_kRSA)
1000                 {
1001                 if ((rsa=RSA_new()) == NULL)
1002                         {
1003                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1004                         goto err;
1005                         }
1006                 n2s(p,i);
1007                 param_len=i+2;
1008                 if (param_len > n)
1009                         {
1010                         al=SSL_AD_DECODE_ERROR;
1011                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
1012                         goto f_err;
1013                         }
1014                 if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
1015                         {
1016                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1017                         goto err;
1018                         }
1019                 p+=i;
1020
1021                 n2s(p,i);
1022                 param_len+=i+2;
1023                 if (param_len > n)
1024                         {
1025                         al=SSL_AD_DECODE_ERROR;
1026                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
1027                         goto f_err;
1028                         }
1029                 if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
1030                         {
1031                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1032                         goto err;
1033                         }
1034                 p+=i;
1035                 n-=param_len;
1036
1037                 /* this should be because we are using an export cipher */
1038                 if (alg & SSL_aRSA)
1039                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1040                 else
1041                         {
1042                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1043                         goto err;
1044                         }
1045                 s->session->sess_cert->peer_rsa_tmp=rsa;
1046                 rsa=NULL;
1047                 }
1048 #else /* OPENSSL_NO_RSA */
1049         if (0)
1050                 ;
1051 #endif
1052 #ifndef OPENSSL_NO_DH
1053         else if (alg & SSL_kEDH)
1054                 {
1055                 if ((dh=DH_new()) == NULL)
1056                         {
1057                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);
1058                         goto err;
1059                         }
1060                 n2s(p,i);
1061                 param_len=i+2;
1062                 if (param_len > n)
1063                         {
1064                         al=SSL_AD_DECODE_ERROR;
1065                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);
1066                         goto f_err;
1067                         }
1068                 if (!(dh->p=BN_bin2bn(p,i,NULL)))
1069                         {
1070                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1071                         goto err;
1072                         }
1073                 p+=i;
1074
1075                 n2s(p,i);
1076                 param_len+=i+2;
1077                 if (param_len > n)
1078                         {
1079                         al=SSL_AD_DECODE_ERROR;
1080                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);
1081                         goto f_err;
1082                         }
1083                 if (!(dh->g=BN_bin2bn(p,i,NULL)))
1084                         {
1085                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1086                         goto err;
1087                         }
1088                 p+=i;
1089
1090                 n2s(p,i);
1091                 param_len+=i+2;
1092                 if (param_len > n)
1093                         {
1094                         al=SSL_AD_DECODE_ERROR;
1095                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);
1096                         goto f_err;
1097                         }
1098                 if (!(dh->pub_key=BN_bin2bn(p,i,NULL)))
1099                         {
1100                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1101                         goto err;
1102                         }
1103                 p+=i;
1104                 n-=param_len;
1105
1106 #ifndef OPENSSL_NO_RSA
1107                 if (alg & SSL_aRSA)
1108                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1109 #else
1110                 if (0)
1111                         ;
1112 #endif
1113 #ifndef OPENSSL_NO_DSA
1114                 else if (alg & SSL_aDSS)
1115                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1116 #endif
1117                 /* else anonymous DH, so no certificate or pkey. */
1118
1119                 s->session->sess_cert->peer_dh_tmp=dh;
1120                 dh=NULL;
1121                 }
1122         else if ((alg & SSL_kDHr) || (alg & SSL_kDHd))
1123                 {
1124                 al=SSL_AD_ILLEGAL_PARAMETER;
1125                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1126                 goto f_err;
1127                 }
1128 #endif /* !OPENSSL_NO_DH */
1129         if (alg & SSL_aFZA)
1130                 {
1131                 al=SSL_AD_HANDSHAKE_FAILURE;
1132                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1133                 goto f_err;
1134                 }
1135
1136
1137         /* p points to the next byte, there are 'n' bytes left */
1138
1139
1140         /* if it was signed, check the signature */
1141         if (pkey != NULL)
1142                 {
1143                 n2s(p,i);
1144                 n-=2;
1145                 j=EVP_PKEY_size(pkey);
1146
1147                 if ((i != n) || (n > j) || (n <= 0))
1148                         {
1149                         /* wrong packet length */
1150                         al=SSL_AD_DECODE_ERROR;
1151                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);
1152                         goto f_err;
1153                         }
1154
1155 #ifndef OPENSSL_NO_RSA
1156                 if (pkey->type == EVP_PKEY_RSA)
1157                         {
1158                         int num;
1159
1160                         j=0;
1161                         q=md_buf;
1162                         for (num=2; num > 0; num--)
1163                                 {
1164                                 EVP_DigestInit_ex(&md_ctx,(num == 2)
1165                                         ?s->ctx->md5:s->ctx->sha1, NULL);
1166                                 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1167                                 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1168                                 EVP_DigestUpdate(&md_ctx,param,param_len);
1169                                 EVP_DigestFinal_ex(&md_ctx,q,(unsigned int *)&i);
1170                                 q+=i;
1171                                 j+=i;
1172                                 }
1173                         i=RSA_verify(NID_md5_sha1, md_buf, j, p, n,
1174                                                                 pkey->pkey.rsa);
1175                         if (i < 0)
1176                                 {
1177                                 al=SSL_AD_DECRYPT_ERROR;
1178                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
1179                                 goto f_err;
1180                                 }
1181                         if (i == 0)
1182                                 {
1183                                 /* bad signature */
1184                                 al=SSL_AD_DECRYPT_ERROR;
1185                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1186                                 goto f_err;
1187                                 }
1188                         }
1189                 else
1190 #endif
1191 #ifndef OPENSSL_NO_DSA
1192                         if (pkey->type == EVP_PKEY_DSA)
1193                         {
1194                         /* lets do DSS */
1195                         EVP_VerifyInit_ex(&md_ctx,EVP_dss1(), NULL);
1196                         EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1197                         EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1198                         EVP_VerifyUpdate(&md_ctx,param,param_len);
1199                         if (!EVP_VerifyFinal(&md_ctx,p,(int)n,pkey))
1200                                 {
1201                                 /* bad signature */
1202                                 al=SSL_AD_DECRYPT_ERROR;
1203                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1204                                 goto f_err;
1205                                 }
1206                         }
1207                 else
1208 #endif
1209                         {
1210                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1211                         goto err;
1212                         }
1213                 }
1214         else
1215                 {
1216                 /* still data left over */
1217                 if (!(alg & SSL_aNULL))
1218                         {
1219                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1220                         goto err;
1221                         }
1222                 if (n != 0)
1223                         {
1224                         al=SSL_AD_DECODE_ERROR;
1225                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
1226                         goto f_err;
1227                         }
1228                 }
1229         EVP_PKEY_free(pkey);
1230         EVP_MD_CTX_cleanup(&md_ctx);
1231         return(1);
1232 f_err:
1233         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1234 err:
1235         EVP_PKEY_free(pkey);
1236 #ifndef OPENSSL_NO_RSA
1237         if (rsa != NULL)
1238                 RSA_free(rsa);
1239 #endif
1240 #ifndef OPENSSL_NO_DH
1241         if (dh != NULL)
1242                 DH_free(dh);
1243 #endif
1244         EVP_MD_CTX_cleanup(&md_ctx);
1245         return(-1);
1246         }
1247
1248 static int ssl3_get_certificate_request(SSL *s)
1249         {
1250         int ok,ret=0;
1251         unsigned long n,nc,l;
1252         unsigned int llen,ctype_num,i;
1253         X509_NAME *xn=NULL;
1254         unsigned char *p,*d,*q;
1255         STACK_OF(X509_NAME) *ca_sk=NULL;
1256
1257         n=ssl3_get_message(s,
1258                 SSL3_ST_CR_CERT_REQ_A,
1259                 SSL3_ST_CR_CERT_REQ_B,
1260                 -1,
1261                 s->max_cert_list,
1262                 &ok);
1263
1264         if (!ok) return((int)n);
1265
1266         s->s3->tmp.cert_req=0;
1267
1268         if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
1269                 {
1270                 s->s3->tmp.reuse_message=1;
1271                 return(1);
1272                 }
1273
1274         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
1275                 {
1276                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1277                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE);
1278                 goto err;
1279                 }
1280
1281         /* TLS does not like anon-DH with client cert */
1282         if (s->version > SSL3_VERSION)
1283                 {
1284                 l=s->s3->tmp.new_cipher->algorithms;
1285                 if (l & SSL_aNULL)
1286                         {
1287                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1288                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1289                         goto err;
1290                         }
1291                 }
1292
1293         d=p=(unsigned char *)s->init_msg;
1294
1295         if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL)
1296                 {
1297                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1298                 goto err;
1299                 }
1300
1301         /* get the certificate types */
1302         ctype_num= *(p++);
1303         if (ctype_num > SSL3_CT_NUMBER)
1304                 ctype_num=SSL3_CT_NUMBER;
1305         for (i=0; i<ctype_num; i++)
1306                 s->s3->tmp.ctype[i]= p[i];
1307         p+=ctype_num;
1308
1309         /* get the CA RDNs */
1310         n2s(p,llen);
1311 #if 0
1312 {
1313 FILE *out;
1314 out=fopen("/tmp/vsign.der","w");
1315 fwrite(p,1,llen,out);
1316 fclose(out);
1317 }
1318 #endif
1319
1320         if ((llen+ctype_num+2+1) != n)
1321                 {
1322                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1323                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH);
1324                 goto err;
1325                 }
1326
1327         for (nc=0; nc<llen; )
1328                 {
1329                 n2s(p,l);
1330                 if ((l+nc+2) > llen)
1331                         {
1332                         if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
1333                                 goto cont; /* netscape bugs */
1334                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1335                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG);
1336                         goto err;
1337                         }
1338
1339                 q=p;
1340
1341                 if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL)
1342                         {
1343                         /* If netscape tolerance is on, ignore errors */
1344                         if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
1345                                 goto cont;
1346                         else
1347                                 {
1348                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1349                                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB);
1350                                 goto err;
1351                                 }
1352                         }
1353
1354                 if (q != (p+l))
1355                         {
1356                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1357                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH);
1358                         goto err;
1359                         }
1360                 if (!sk_X509_NAME_push(ca_sk,xn))
1361                         {
1362                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1363                         goto err;
1364                         }
1365
1366                 p+=l;
1367                 nc+=l+2;
1368                 }
1369
1370         if (0)
1371                 {
1372 cont:
1373                 ERR_clear_error();
1374                 }
1375
1376         /* we should setup a certificate to return.... */
1377         s->s3->tmp.cert_req=1;
1378         s->s3->tmp.ctype_num=ctype_num;
1379         if (s->s3->tmp.ca_names != NULL)
1380                 sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
1381         s->s3->tmp.ca_names=ca_sk;
1382         ca_sk=NULL;
1383
1384         ret=1;
1385 err:
1386         if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
1387         return(ret);
1388         }
1389
1390 static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1391         {
1392         return(X509_NAME_cmp(*a,*b));
1393         }
1394
1395 static int ssl3_get_server_done(SSL *s)
1396         {
1397         int ok,ret=0;
1398         long n;
1399
1400         n=ssl3_get_message(s,
1401                 SSL3_ST_CR_SRVR_DONE_A,
1402                 SSL3_ST_CR_SRVR_DONE_B,
1403                 SSL3_MT_SERVER_DONE,
1404                 30, /* should be very small, like 0 :-) */
1405                 &ok);
1406
1407         if (!ok) return((int)n);
1408         if (n > 0)
1409                 {
1410                 /* should contain no data */
1411                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1412                 SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH);
1413                 return -1;
1414                 }
1415         ret=1;
1416         return(ret);
1417         }
1418
1419 static int ssl3_send_client_key_exchange(SSL *s)
1420         {
1421         unsigned char *p,*d;
1422         int n;
1423         unsigned long l;
1424 #ifndef OPENSSL_NO_RSA
1425         unsigned char *q;
1426         EVP_PKEY *pkey=NULL;
1427 #endif
1428 #ifndef OPENSSL_NO_KRB5
1429         KSSL_ERR kssl_err;
1430 #endif /* OPENSSL_NO_KRB5 */
1431
1432         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
1433                 {
1434                 d=(unsigned char *)s->init_buf->data;
1435                 p= &(d[4]);
1436
1437                 l=s->s3->tmp.new_cipher->algorithms;
1438
1439                 /* Fool emacs indentation */
1440                 if (0) {}
1441 #ifndef OPENSSL_NO_RSA
1442                 else if (l & SSL_kRSA)
1443                         {
1444                         RSA *rsa;
1445                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
1446
1447                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
1448                                 rsa=s->session->sess_cert->peer_rsa_tmp;
1449                         else
1450                                 {
1451                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1452                                 if ((pkey == NULL) ||
1453                                         (pkey->type != EVP_PKEY_RSA) ||
1454                                         (pkey->pkey.rsa == NULL))
1455                                         {
1456                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1457                                         goto err;
1458                                         }
1459                                 rsa=pkey->pkey.rsa;
1460                                 EVP_PKEY_free(pkey);
1461                                 }
1462                                 
1463                         tmp_buf[0]=s->client_version>>8;
1464                         tmp_buf[1]=s->client_version&0xff;
1465                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
1466                                         goto err;
1467
1468                         s->session->master_key_length=sizeof tmp_buf;
1469
1470                         q=p;
1471                         /* Fix buf for TLS and beyond */
1472                         if (s->version > SSL3_VERSION)
1473                                 p+=2;
1474                         n=RSA_public_encrypt(sizeof tmp_buf,
1475                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
1476 #ifdef PKCS1_CHECK
1477                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
1478                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
1479 #endif
1480                         if (n <= 0)
1481                                 {
1482                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
1483                                 goto err;
1484                                 }
1485
1486                         /* Fix buf for TLS and beyond */
1487                         if (s->version > SSL3_VERSION)
1488                                 {
1489                                 s2n(n,q);
1490                                 n+=2;
1491                                 }
1492
1493                         s->session->master_key_length=
1494                                 s->method->ssl3_enc->generate_master_secret(s,
1495                                         s->session->master_key,
1496                                         tmp_buf,sizeof tmp_buf);
1497                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
1498                         }
1499 #endif
1500 #ifndef OPENSSL_NO_KRB5
1501                 else if (l & SSL_kKRB5)
1502                         {
1503                         krb5_error_code krb5rc;
1504                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
1505                         /*  krb5_data   krb5_ap_req;  */
1506                         krb5_data       *enc_ticket;
1507                         krb5_data       authenticator, *authp = NULL;
1508                         EVP_CIPHER_CTX  ciph_ctx;
1509                         EVP_CIPHER      *enc = NULL;
1510                         unsigned char   iv[EVP_MAX_IV_LENGTH];
1511                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
1512                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
1513                                                 + EVP_MAX_IV_LENGTH];
1514                         int             padl, outl = sizeof(epms);
1515
1516                         EVP_CIPHER_CTX_init(&ciph_ctx);
1517
1518 #ifdef KSSL_DEBUG
1519                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
1520                                 l, SSL_kKRB5);
1521 #endif  /* KSSL_DEBUG */
1522
1523                         authp = NULL;
1524 #ifdef KRB5SENDAUTH
1525                         if (KRB5SENDAUTH)  authp = &authenticator;
1526 #endif  /* KRB5SENDAUTH */
1527
1528                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
1529                                 &kssl_err);
1530                         enc = kssl_map_enc(kssl_ctx->enctype);
1531                         if (enc == NULL)
1532                             goto err;
1533 #ifdef KSSL_DEBUG
1534                         {
1535                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
1536                         if (krb5rc && kssl_err.text)
1537                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
1538                         }
1539 #endif  /* KSSL_DEBUG */
1540
1541                         if (krb5rc)
1542                                 {
1543                                 ssl3_send_alert(s,SSL3_AL_FATAL,
1544                                                 SSL_AD_HANDSHAKE_FAILURE);
1545                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
1546                                                 kssl_err.reason);
1547                                 goto err;
1548                                 }
1549
1550                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
1551                         **  in place of RFC 2712 KerberosWrapper, as in:
1552                         **
1553                         **  Send ticket (copy to *p, set n = length)
1554                         **  n = krb5_ap_req.length;
1555                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
1556                         **  if (krb5_ap_req.data)  
1557                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
1558                         **
1559                         **  Now using real RFC 2712 KerberosWrapper
1560                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
1561                         **  Note: 2712 "opaque" types are here replaced
1562                         **  with a 2-byte length followed by the value.
1563                         **  Example:
1564                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
1565                         **  Where "xx xx" = length bytes.  Shown here with
1566                         **  optional authenticator omitted.
1567                         */
1568
1569                         /*  KerberosWrapper.Ticket              */
1570                         s2n(enc_ticket->length,p);
1571                         memcpy(p, enc_ticket->data, enc_ticket->length);
1572                         p+= enc_ticket->length;
1573                         n = enc_ticket->length + 2;
1574
1575                         /*  KerberosWrapper.Authenticator       */
1576                         if (authp  &&  authp->length)  
1577                                 {
1578                                 s2n(authp->length,p);
1579                                 memcpy(p, authp->data, authp->length);
1580                                 p+= authp->length;
1581                                 n+= authp->length + 2;
1582                                 
1583                                 free(authp->data);
1584                                 authp->data = NULL;
1585                                 authp->length = 0;
1586                                 }
1587                         else
1588                                 {
1589                                 s2n(0,p);/*  null authenticator length  */
1590                                 n+=2;
1591                                 }
1592  
1593                         if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
1594                             goto err;
1595
1596                         /*  20010420 VRS.  Tried it this way; failed.
1597                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
1598                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
1599                         **                              kssl_ctx->length);
1600                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
1601                         */
1602
1603                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
1604                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
1605                                 kssl_ctx->key,iv);
1606                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
1607                                 sizeof tmp_buf);
1608                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
1609                         outl += padl;
1610                         if (outl > sizeof epms)
1611                                 {
1612                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1613                                 goto err;
1614                                 }
1615                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
1616
1617                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
1618                         s2n(outl,p);
1619                         memcpy(p, epms, outl);
1620                         p+=outl;
1621                         n+=outl + 2;
1622
1623                         s->session->master_key_length=
1624                                 s->method->ssl3_enc->generate_master_secret(s,
1625                                         s->session->master_key,
1626                                         tmp_buf, sizeof tmp_buf);
1627
1628                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
1629                         OPENSSL_cleanse(epms, outl);
1630                         }
1631 #endif
1632 #ifndef OPENSSL_NO_DH
1633                 else if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1634                         {
1635                         DH *dh_srvr,*dh_clnt;
1636
1637                         if (s->session->sess_cert->peer_dh_tmp != NULL)
1638                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
1639                         else
1640                                 {
1641                                 /* we get them from the cert */
1642                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1643                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
1644                                 goto err;
1645                                 }
1646                         
1647                         /* generate a new random key */
1648                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
1649                                 {
1650                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1651                                 goto err;
1652                                 }
1653                         if (!DH_generate_key(dh_clnt))
1654                                 {
1655                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1656                                 goto err;
1657                                 }
1658
1659                         /* use the 'p' output buffer for the DH key, but
1660                          * make sure to clear it out afterwards */
1661
1662                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
1663
1664                         if (n <= 0)
1665                                 {
1666                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1667                                 goto err;
1668                                 }
1669
1670                         /* generate master key from the result */
1671                         s->session->master_key_length=
1672                                 s->method->ssl3_enc->generate_master_secret(s,
1673                                         s->session->master_key,p,n);
1674                         /* clean up */
1675                         memset(p,0,n);
1676
1677                         /* send off the data */
1678                         n=BN_num_bytes(dh_clnt->pub_key);
1679                         s2n(n,p);
1680                         BN_bn2bin(dh_clnt->pub_key,p);
1681                         n+=2;
1682
1683                         DH_free(dh_clnt);
1684
1685                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
1686                         }
1687 #endif
1688                 else
1689                         {
1690                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1691                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1692                         goto err;
1693                         }
1694                 
1695                 *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
1696                 l2n3(n,d);
1697
1698                 s->state=SSL3_ST_CW_KEY_EXCH_B;
1699                 /* number of bytes to write */
1700                 s->init_num=n+4;
1701                 s->init_off=0;
1702                 }
1703
1704         /* SSL3_ST_CW_KEY_EXCH_B */
1705         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1706 err:
1707         return(-1);
1708         }
1709
1710 static int ssl3_send_client_verify(SSL *s)
1711         {
1712         unsigned char *p,*d;
1713         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1714         EVP_PKEY *pkey;
1715 #ifndef OPENSSL_NO_RSA
1716         unsigned u=0;
1717 #endif
1718         unsigned long n;
1719 #ifndef OPENSSL_NO_DSA
1720         int j;
1721 #endif
1722
1723         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
1724                 {
1725                 d=(unsigned char *)s->init_buf->data;
1726                 p= &(d[4]);
1727                 pkey=s->cert->key->privatekey;
1728
1729                 s->method->ssl3_enc->cert_verify_mac(s,&(s->s3->finish_dgst2),
1730                         &(data[MD5_DIGEST_LENGTH]));
1731
1732 #ifndef OPENSSL_NO_RSA
1733                 if (pkey->type == EVP_PKEY_RSA)
1734                         {
1735                         s->method->ssl3_enc->cert_verify_mac(s,
1736                                 &(s->s3->finish_dgst1),&(data[0]));
1737                         if (RSA_sign(NID_md5_sha1, data,
1738                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
1739                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
1740                                 {
1741                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
1742                                 goto err;
1743                                 }
1744                         s2n(u,p);
1745                         n=u+2;
1746                         }
1747                 else
1748 #endif
1749 #ifndef OPENSSL_NO_DSA
1750                         if (pkey->type == EVP_PKEY_DSA)
1751                         {
1752                         if (!DSA_sign(pkey->save_type,
1753                                 &(data[MD5_DIGEST_LENGTH]),
1754                                 SHA_DIGEST_LENGTH,&(p[2]),
1755                                 (unsigned int *)&j,pkey->pkey.dsa))
1756                                 {
1757                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
1758                                 goto err;
1759                                 }
1760                         s2n(j,p);
1761                         n=j+2;
1762                         }
1763                 else
1764 #endif
1765                         {
1766                         SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
1767                         goto err;
1768                         }
1769                 *(d++)=SSL3_MT_CERTIFICATE_VERIFY;
1770                 l2n3(n,d);
1771
1772                 s->init_num=(int)n+4;
1773                 s->init_off=0;
1774                 }
1775         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1776 err:
1777         return(-1);
1778         }
1779
1780 static int ssl3_send_client_certificate(SSL *s)
1781         {
1782         X509 *x509=NULL;
1783         EVP_PKEY *pkey=NULL;
1784         int i;
1785         unsigned long l;
1786
1787         if (s->state == SSL3_ST_CW_CERT_A)
1788                 {
1789                 if ((s->cert == NULL) ||
1790                         (s->cert->key->x509 == NULL) ||
1791                         (s->cert->key->privatekey == NULL))
1792                         s->state=SSL3_ST_CW_CERT_B;
1793                 else
1794                         s->state=SSL3_ST_CW_CERT_C;
1795                 }
1796
1797         /* We need to get a client cert */
1798         if (s->state == SSL3_ST_CW_CERT_B)
1799                 {
1800                 /* If we get an error, we need to
1801                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
1802                  * We then get retied later */
1803                 i=0;
1804                 if (s->ctx->client_cert_cb != NULL)
1805                         i=s->ctx->client_cert_cb(s,&(x509),&(pkey));
1806                 if (i < 0)
1807                         {
1808                         s->rwstate=SSL_X509_LOOKUP;
1809                         return(-1);
1810                         }
1811                 s->rwstate=SSL_NOTHING;
1812                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
1813                         {
1814                         s->state=SSL3_ST_CW_CERT_B;
1815                         if (    !SSL_use_certificate(s,x509) ||
1816                                 !SSL_use_PrivateKey(s,pkey))
1817                                 i=0;
1818                         }
1819                 else if (i == 1)
1820                         {
1821                         i=0;
1822                         SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
1823                         }
1824
1825                 if (x509 != NULL) X509_free(x509);
1826                 if (pkey != NULL) EVP_PKEY_free(pkey);
1827                 if (i == 0)
1828                         {
1829                         if (s->version == SSL3_VERSION)
1830                                 {
1831                                 s->s3->tmp.cert_req=0;
1832                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
1833                                 return(1);
1834                                 }
1835                         else
1836                                 {
1837                                 s->s3->tmp.cert_req=2;
1838                                 }
1839                         }
1840
1841                 /* Ok, we have a cert */
1842                 s->state=SSL3_ST_CW_CERT_C;
1843                 }
1844
1845         if (s->state == SSL3_ST_CW_CERT_C)
1846                 {
1847                 s->state=SSL3_ST_CW_CERT_D;
1848                 l=ssl3_output_cert_chain(s,
1849                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
1850                 s->init_num=(int)l;
1851                 s->init_off=0;
1852                 }
1853         /* SSL3_ST_CW_CERT_D */
1854         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1855         }
1856
1857 #define has_bits(i,m)   (((i)&(m)) == (m))
1858
1859 static int ssl3_check_cert_and_algorithm(SSL *s)
1860         {
1861         int i,idx;
1862         long algs;
1863         EVP_PKEY *pkey=NULL;
1864         SESS_CERT *sc;
1865 #ifndef OPENSSL_NO_RSA
1866         RSA *rsa;
1867 #endif
1868 #ifndef OPENSSL_NO_DH
1869         DH *dh;
1870 #endif
1871
1872         sc=s->session->sess_cert;
1873
1874         if (sc == NULL)
1875                 {
1876                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR);
1877                 goto err;
1878                 }
1879
1880         algs=s->s3->tmp.new_cipher->algorithms;
1881
1882         /* we don't have a certificate */
1883         if (algs & (SSL_aDH|SSL_aNULL|SSL_aKRB5))
1884                 return(1);
1885
1886 #ifndef OPENSSL_NO_RSA
1887         rsa=s->session->sess_cert->peer_rsa_tmp;
1888 #endif
1889 #ifndef OPENSSL_NO_DH
1890         dh=s->session->sess_cert->peer_dh_tmp;
1891 #endif
1892
1893         /* This is the passed certificate */
1894
1895         idx=sc->peer_cert_type;
1896         pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
1897         i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
1898         EVP_PKEY_free(pkey);
1899
1900         
1901         /* Check that we have a certificate if we require one */
1902         if ((algs & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
1903                 {
1904                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT);
1905                 goto f_err;
1906                 }
1907 #ifndef OPENSSL_NO_DSA
1908         else if ((algs & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN))
1909                 {
1910                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT);
1911                 goto f_err;
1912                 }
1913 #endif
1914 #ifndef OPENSSL_NO_RSA
1915         if ((algs & SSL_kRSA) &&
1916                 !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
1917                 {
1918                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT);
1919                 goto f_err;
1920                 }
1921 #endif
1922 #ifndef OPENSSL_NO_DH
1923         if ((algs & SSL_kEDH) &&
1924                 !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
1925                 {
1926                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY);
1927                 goto f_err;
1928                 }
1929         else if ((algs & SSL_kDHr) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA))
1930                 {
1931                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT);
1932                 goto f_err;
1933                 }
1934 #ifndef OPENSSL_NO_DSA
1935         else if ((algs & SSL_kDHd) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA))
1936                 {
1937                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT);
1938                 goto f_err;
1939                 }
1940 #endif
1941 #endif
1942
1943         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP))
1944                 {
1945 #ifndef OPENSSL_NO_RSA
1946                 if (algs & SSL_kRSA)
1947                         {
1948                         if (rsa == NULL
1949                             || RSA_size(rsa) > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
1950                                 {
1951                                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
1952                                 goto f_err;
1953                                 }
1954                         }
1955                 else
1956 #endif
1957 #ifndef OPENSSL_NO_DH
1958                         if (algs & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1959                             {
1960                             if (dh == NULL
1961                                 || DH_size(dh) > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
1962                                 {
1963                                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY);
1964                                 goto f_err;
1965                                 }
1966                         }
1967                 else
1968 #endif
1969                         {
1970                         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1971                         goto f_err;
1972                         }
1973                 }
1974         return(1);
1975 f_err:
1976         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1977 err:
1978         return(0);
1979         }
1980