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