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