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