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