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