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