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