Various cleanups and fixed by Marc and Ralf to start the OpenTLS project
[openssl.git] / ssl / s2_srvr.c
1 /* ssl/s2_srvr.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 "bio.h"
61 #include "rand.h"
62 #include "objects.h"
63 #include "ssl_locl.h"
64 #include "evp.h"
65
66 #ifndef NOPROTO
67 static int get_client_master_key(SSL *s);
68 static int get_client_hello(SSL *s);
69 static int server_hello(SSL *s); 
70 static int get_client_finished(SSL *s);
71 static int server_verify(SSL *s);
72 static int server_finish(SSL *s);
73 static int request_certificate(SSL *s);
74 static int ssl_rsa_private_decrypt(CERT *c, int len, unsigned char *from,
75         unsigned char *to,int padding);
76 #else
77 static int get_client_master_key();
78 static int get_client_hello();
79 static int server_hello(); 
80 static int get_client_finished();
81 static int server_verify();
82 static int server_finish();
83 static int request_certificate();
84 static int ssl_rsa_private_decrypt();
85 #endif
86
87 #define BREAK   break
88
89 static SSL_METHOD *ssl2_get_server_method(ver)
90 int ver;
91         {
92         if (ver == SSL2_VERSION)
93                 return(SSLv2_server_method());
94         else
95                 return(NULL);
96         }
97
98 SSL_METHOD *SSLv2_server_method()
99         {
100         static int init=1;
101         static SSL_METHOD SSLv2_server_data;
102
103         if (init)
104                 {
105                 init=0;
106                 memcpy((char *)&SSLv2_server_data,(char *)sslv2_base_method(),
107                         sizeof(SSL_METHOD));
108                 SSLv2_server_data.ssl_accept=ssl2_accept;
109                 SSLv2_server_data.get_ssl_method=ssl2_get_server_method;
110                 }
111         return(&SSLv2_server_data);
112         }
113
114 int ssl2_accept(s)
115 SSL *s;
116         {
117         unsigned long l=time(NULL);
118         BUF_MEM *buf=NULL;
119         int ret= -1;
120         long num1;
121         void (*cb)()=NULL;
122         int new_state,state;
123
124         RAND_seed((unsigned char *)&l,sizeof(l));
125         ERR_clear_error();
126         clear_sys_error();
127
128         if (s->info_callback != NULL)
129                 cb=s->info_callback;
130         else if (s->ctx->info_callback != NULL)
131                 cb=s->ctx->info_callback;
132
133         /* init things to blank */
134         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
135         s->in_handshake++;
136
137         if (((s->session == NULL) || (s->session->cert == NULL)) &&
138                 (s->cert == NULL))
139                 {
140                 SSLerr(SSL_F_SSL2_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
141                 return(-1);
142                 }
143
144         clear_sys_error();
145         for (;;)
146                 {
147                 state=s->state;
148
149                 switch (s->state)
150                         {
151                 case SSL_ST_BEFORE:
152                 case SSL_ST_ACCEPT:
153                 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
154                 case SSL_ST_OK|SSL_ST_ACCEPT:
155
156                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
157
158                         s->version=SSL2_VERSION;
159                         s->type=SSL_ST_ACCEPT;
160
161                         buf=s->init_buf;
162                         if ((buf == NULL) && ((buf=BUF_MEM_new()) == NULL))
163                                 { ret= -1; goto end; }
164                         if (!BUF_MEM_grow(buf,(int)
165                                 SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
166                                 { ret= -1; goto end; }
167                         s->init_buf=buf;
168                         s->init_num=0;
169                         s->ctx->sess_accept++;
170                         s->handshake_func=ssl2_accept;
171                         s->state=SSL2_ST_GET_CLIENT_HELLO_A;
172                         BREAK;
173
174                 case SSL2_ST_GET_CLIENT_HELLO_A:
175                 case SSL2_ST_GET_CLIENT_HELLO_B:
176                 case SSL2_ST_GET_CLIENT_HELLO_C:
177                         s->shutdown=0;
178                         ret=get_client_hello(s);
179                         if (ret <= 0) goto end;
180                         s->init_num=0;
181                         s->state=SSL2_ST_SEND_SERVER_HELLO_A;
182                         BREAK;
183
184                 case SSL2_ST_SEND_SERVER_HELLO_A:
185                 case SSL2_ST_SEND_SERVER_HELLO_B:
186                         ret=server_hello(s);
187                         if (ret <= 0) goto end;
188                         s->init_num=0;
189                         if (!s->hit)
190                                 {
191                                 s->state=SSL2_ST_GET_CLIENT_MASTER_KEY_A;
192                                 BREAK;
193                                 }
194                         else
195                                 {
196                                 s->state=SSL2_ST_SERVER_START_ENCRYPTION;
197                                 BREAK;
198                                 }
199                 case SSL2_ST_GET_CLIENT_MASTER_KEY_A:
200                 case SSL2_ST_GET_CLIENT_MASTER_KEY_B:
201                         ret=get_client_master_key(s);
202                         if (ret <= 0) goto end;
203                         s->init_num=0;
204                         s->state=SSL2_ST_SERVER_START_ENCRYPTION;
205                         BREAK;
206
207                 case SSL2_ST_SERVER_START_ENCRYPTION:
208                         /* Ok we how have sent all the stuff needed to
209                          * start encrypting, the next packet back will
210                          * be encrypted. */
211                         if (!ssl2_enc_init(s,0))
212                                 { ret= -1; goto end; }
213                         s->s2->clear_text=0;
214                         s->state=SSL2_ST_SEND_SERVER_VERIFY_A;
215                         BREAK;
216
217                 case SSL2_ST_SEND_SERVER_VERIFY_A:
218                 case SSL2_ST_SEND_SERVER_VERIFY_B:
219                         ret=server_verify(s);
220                         if (ret <= 0) goto end;
221                         s->init_num=0;
222                         if (s->hit)
223                                 {
224                                 /* If we are in here, we have been
225                                  * buffering the output, so we need to
226                                  * flush it and remove buffering from
227                                  * future traffic */
228                                 s->state=SSL2_ST_SEND_SERVER_VERIFY_C;
229                                 BREAK;
230                                 }
231                         else
232                                 {
233                                 s->state=SSL2_ST_GET_CLIENT_FINISHED_A;
234                                 break;
235                                 }
236
237                 case SSL2_ST_SEND_SERVER_VERIFY_C:
238                         /* get the number of bytes to write */
239                         num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
240                         if (num1 != 0)
241                                 {
242                                 s->rwstate=SSL_WRITING;
243                                 num1=BIO_flush(s->wbio);
244                                 if (num1 <= 0) { ret= -1; goto end; }
245                                 s->rwstate=SSL_NOTHING;
246                                 }
247
248                         /* flushed and now remove buffering */
249                         s->wbio=BIO_pop(s->wbio);
250
251                         s->state=SSL2_ST_GET_CLIENT_FINISHED_A;
252                         BREAK;
253
254                 case SSL2_ST_GET_CLIENT_FINISHED_A:
255                 case SSL2_ST_GET_CLIENT_FINISHED_B:
256                         ret=get_client_finished(s);
257                         if (ret <= 0)
258                                 goto end;
259                         s->init_num=0;
260                         s->state=SSL2_ST_SEND_REQUEST_CERTIFICATE_A;
261                         BREAK;
262
263                 case SSL2_ST_SEND_REQUEST_CERTIFICATE_A:
264                 case SSL2_ST_SEND_REQUEST_CERTIFICATE_B:
265                 case SSL2_ST_SEND_REQUEST_CERTIFICATE_C:
266                 case SSL2_ST_SEND_REQUEST_CERTIFICATE_D:
267                         /* don't do a 'request certificate' if we
268                          * don't want to, or we already have one, and
269                          * we only want to do it once. */
270                         if (!(s->verify_mode & SSL_VERIFY_PEER) ||
271                                 ((s->session->peer != NULL) &&
272                                 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)))
273                                 {
274                                 s->state=SSL2_ST_SEND_SERVER_FINISHED_A;
275                                 break;
276                                 }
277                         else
278                                 {
279                                 ret=request_certificate(s);
280                                 if (ret <= 0) goto end;
281                                 s->init_num=0;
282                                 s->state=SSL2_ST_SEND_SERVER_FINISHED_A;
283                                 }
284                         BREAK;
285
286                 case SSL2_ST_SEND_SERVER_FINISHED_A:
287                 case SSL2_ST_SEND_SERVER_FINISHED_B:
288                         ret=server_finish(s);
289                         if (ret <= 0) goto end;
290                         s->init_num=0;
291                         s->state=SSL_ST_OK;
292                         break;
293
294                 case SSL_ST_OK:
295                         BUF_MEM_free(s->init_buf);
296                         s->init_buf=NULL;
297                         s->init_num=0;
298                 /*      ERR_clear_error();*/
299
300                         ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
301
302                         s->ctx->sess_accept_good++;
303                         /* s->server=1; */
304                         ret=1;
305
306                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
307
308                         goto end;
309                         /* BREAK; */
310
311                 default:
312                         SSLerr(SSL_F_SSL2_ACCEPT,SSL_R_UNKNOWN_STATE);
313                         ret= -1;
314                         goto end;
315                         /* BREAK; */
316                         }
317                 
318                 if ((cb != NULL) && (s->state != state))
319                         {
320                         new_state=s->state;
321                         s->state=state;
322                         cb(s,SSL_CB_ACCEPT_LOOP,1);
323                         s->state=new_state;
324                         }
325                 }
326 end:
327         s->in_handshake--;
328         if (cb != NULL)
329                 cb(s,SSL_CB_ACCEPT_EXIT,ret);
330         return(ret);
331         }
332
333 static int get_client_master_key(s)
334 SSL *s;
335         {
336         int export,i,n,keya,ek;
337 #if 0
338         int error=0;
339 #endif
340         unsigned char *p;
341         SSL_CIPHER *cp;
342         EVP_CIPHER *c;
343         EVP_MD *md;
344
345         p=(unsigned char *)s->init_buf->data;
346         if (s->state == SSL2_ST_GET_CLIENT_MASTER_KEY_A)
347                 {
348                 i=ssl2_read(s,(char *)&(p[s->init_num]),10-s->init_num);
349
350                 if (i < (10-s->init_num))
351                         return(ssl2_part_read(s,SSL_F_GET_CLIENT_MASTER_KEY,i));
352                 if (*(p++) != SSL2_MT_CLIENT_MASTER_KEY)
353                         {
354                         if (p[-1] != SSL2_MT_ERROR)
355                                 {
356                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
357                                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_READ_WRONG_PACKET_TYPE);
358                                 }
359                         else
360                                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
361                                         SSL_R_PEER_ERROR);
362                         return(-1);
363                         }
364
365                 cp=ssl2_get_cipher_by_char(p);
366                 if (cp == NULL)
367                         {
368                         ssl2_return_error(s,SSL2_PE_NO_CIPHER);
369                         SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
370                                 SSL_R_NO_CIPHER_MATCH);
371                         return(-1);
372                         }
373                 s->session->cipher= cp;
374
375                 p+=3;
376                 n2s(p,i); s->s2->tmp.clear=i;
377                 n2s(p,i); s->s2->tmp.enc=i;
378                 n2s(p,i); s->session->key_arg_length=i;
379                 s->state=SSL2_ST_GET_CLIENT_MASTER_KEY_B;
380                 s->init_num=0;
381                 }
382
383         /* SSL2_ST_GET_CLIENT_MASTER_KEY_B */
384         p=(unsigned char *)s->init_buf->data;
385         keya=s->session->key_arg_length;
386         n=s->s2->tmp.clear+s->s2->tmp.enc+keya - s->init_num;
387         i=ssl2_read(s,(char *)&(p[s->init_num]),n);
388         if (i != n) return(ssl2_part_read(s,SSL_F_GET_CLIENT_MASTER_KEY,i));
389
390         memcpy(s->session->key_arg,&(p[s->s2->tmp.clear+s->s2->tmp.enc]),
391                 (unsigned int)keya);
392
393         if (s->session->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL)
394                 {
395                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
396                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_NO_PRIVATEKEY);
397                 return(-1);
398                 }
399         i=ssl_rsa_private_decrypt(s->cert,s->s2->tmp.enc,
400                 &(p[s->s2->tmp.clear]),&(p[s->s2->tmp.clear]),
401                 (s->s2->ssl2_rollback)?RSA_SSLV23_PADDING:RSA_PKCS1_PADDING);
402
403         export=(s->session->cipher->algorithms & SSL_EXP)?1:0;
404         
405         if (!ssl_cipher_get_evp(s->session->cipher,&c,&md))
406                 {
407                 ssl2_return_error(s,SSL2_PE_NO_CIPHER);
408                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS);
409                 return(0);
410                 }
411
412         if (s->session->cipher->algorithm2 & SSL2_CF_8_BYTE_ENC)
413                 {
414                 export=1;
415                 ek=8;
416                 }
417         else
418                 ek=5;
419
420         /* bad decrypt */
421 #if 1
422         /* If a bad decrypt, continue with protocol but with a
423          * dud master secret */
424         if ((i < 0) ||
425                 ((!export && (i != EVP_CIPHER_key_length(c)))
426                 || ( export && ((i != ek) || (s->s2->tmp.clear+i !=
427                         EVP_CIPHER_key_length(c))))))
428                 {
429                 if (export)
430                         i=ek;
431                 else
432                         i=EVP_CIPHER_key_length(c);
433                 RAND_bytes(p,i);
434                 }
435 #else
436         if (i < 0)
437                 {
438                 error=1;
439                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_BAD_RSA_DECRYPT);
440                 }
441         /* incorrect number of key bytes for non export cipher */
442         else if ((!export && (i != EVP_CIPHER_key_length(c)))
443                 || ( export && ((i != ek) || (s->s2->tmp.clear+i !=
444                         EVP_CIPHER_key_length(c)))))
445                 {
446                 error=1;
447                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_WRONG_NUMBER_OF_KEY_BITS);
448                 }
449         if (error)
450                 {
451                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
452                 return(-1);
453                 }
454 #endif
455
456         if (export) i+=s->s2->tmp.clear;
457         s->session->master_key_length=i;
458         memcpy(s->session->master_key,p,(unsigned int)i);
459         return(1);
460         }
461
462 static int get_client_hello(s)
463 SSL *s;
464         {
465         int i,n;
466         unsigned char *p;
467         STACK *cs; /* a stack of SSL_CIPHERS */
468         STACK *cl; /* the ones we want to use */
469         int z;
470
471         /* This is a bit of a hack to check for the correct packet
472          * type the first time round. */
473         if (s->state == SSL2_ST_GET_CLIENT_HELLO_A)
474                 {
475                 s->first_packet=1;
476                 s->state=SSL2_ST_GET_CLIENT_HELLO_B;
477                 }
478
479         p=(unsigned char *)s->init_buf->data;
480         if (s->state == SSL2_ST_GET_CLIENT_HELLO_B)
481                 {
482                 i=ssl2_read(s,(char *)&(p[s->init_num]),9-s->init_num);
483                 if (i < (9-s->init_num)) 
484                         return(ssl2_part_read(s,SSL_F_GET_CLIENT_HELLO,i));
485         
486                 if (*(p++) != SSL2_MT_CLIENT_HELLO)
487                         {
488                         if (p[-1] != SSL2_MT_ERROR)
489                                 {
490                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
491                                 SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_READ_WRONG_PACKET_TYPE);
492                                 }
493                         else
494                                 SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_PEER_ERROR);
495                         return(-1);
496                         }
497                 n2s(p,i);
498                 if (i < s->version) s->version=i;
499                 n2s(p,i); s->s2->tmp.cipher_spec_length=i;
500                 n2s(p,i); s->s2->tmp.session_id_length=i;
501                 n2s(p,i); s->s2->challenge_length=i;
502                 if (    (i < SSL2_MIN_CHALLENGE_LENGTH) ||
503                         (i > SSL2_MAX_CHALLENGE_LENGTH))
504                         {
505                         SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_INVALID_CHALLENGE_LENGTH);
506                         return(-1);
507                         }
508                 s->state=SSL2_ST_GET_CLIENT_HELLO_C;
509                 s->init_num=0;
510                 }
511
512         /* SSL2_ST_GET_CLIENT_HELLO_C */
513         p=(unsigned char *)s->init_buf->data;
514         n=s->s2->tmp.cipher_spec_length+s->s2->challenge_length+
515                 s->s2->tmp.session_id_length-s->init_num;
516         i=ssl2_read(s,(char *)&(p[s->init_num]),n);
517         if (i != n) return(ssl2_part_read(s,SSL_F_GET_CLIENT_HELLO,i));
518
519         /* get session-id before cipher stuff so we can get out session
520          * structure if it is cached */
521         /* session-id */
522         if ((s->s2->tmp.session_id_length != 0) && 
523                 (s->s2->tmp.session_id_length != SSL2_SSL_SESSION_ID_LENGTH))
524                 {
525                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
526                 SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_BAD_SSL_SESSION_ID_LENGTH);
527                 return(-1);
528                 }
529
530         if (s->s2->tmp.session_id_length == 0)
531                 {
532                 if (!ssl_get_new_session(s,1))
533                         {
534                         ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
535                         return(-1);
536                         }
537                 }
538         else
539                 {
540                 i=ssl_get_prev_session(s,&(p[s->s2->tmp.cipher_spec_length]),
541                         s->s2->tmp.session_id_length);
542                 if (i == 1)
543                         { /* previous session */
544                         s->hit=1;
545                         }
546                 else if (i == -1)
547                         {
548                         ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
549                         return(-1);
550                         }
551                 else
552                         {
553                         if (s->cert == NULL)
554                                 {
555                                 ssl2_return_error(s,SSL2_PE_NO_CERTIFICATE);
556                                 SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_NO_CERTIFICATE_SET);
557                                 return(-1);
558                                 }
559
560                         if (!ssl_get_new_session(s,1))
561                                 {
562                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
563                                 return(-1);
564                                 }
565                         }
566                 }
567
568         if (!s->hit)
569                 {
570                 cs=ssl_bytes_to_cipher_list(s,p,s->s2->tmp.cipher_spec_length,
571                         &s->session->ciphers);
572                 if (cs == NULL) goto mem_err;
573
574                 cl=ssl_get_ciphers_by_id(s);
575
576                 for (z=0; z<sk_num(cs); z++)
577                         {
578                         if (sk_find(cl,sk_value(cs,z)) < 0)
579                                 {
580                                 sk_delete(cs,z);
581                                 z--;
582                                 }
583                         }
584
585                 /* s->session->ciphers should now have a list of
586                  * ciphers that are on both the client and server.
587                  * This list is ordered by the order the client sent
588                  * the ciphers.
589                  */
590                 }
591         p+=s->s2->tmp.cipher_spec_length;
592         /* done cipher selection */
593
594         /* session id extracted already */
595         p+=s->s2->tmp.session_id_length;
596
597         /* challenge */
598         memcpy(s->s2->challenge,p,(unsigned int)s->s2->challenge_length);
599         return(1);
600 mem_err:
601         SSLerr(SSL_F_GET_CLIENT_HELLO,ERR_R_MALLOC_FAILURE);
602         return(0);
603         }
604
605 static int server_hello(s)
606 SSL *s;
607         {
608         unsigned char *p,*d;
609         int n,hit;
610         STACK *sk;
611
612         p=(unsigned char *)s->init_buf->data;
613         if (s->state == SSL2_ST_SEND_SERVER_HELLO_A)
614                 {
615                 d=p+11;
616                 *(p++)=SSL2_MT_SERVER_HELLO;            /* type */
617                 hit=s->hit;
618                 *(p++)=(unsigned char)hit;
619                 if (!hit)
620                         {                       /* else add cert to session */
621                         CRYPTO_add(&s->cert->references,1,CRYPTO_LOCK_SSL_CERT);
622                         if (s->session->cert != NULL)
623                                 ssl_cert_free(s->session->cert);
624                         s->session->cert=s->cert;               
625                         }
626                 else    /* We have a session id-cache hit, if the
627                          * session-id has no certificate listed against
628                          * the 'cert' structure, grab the 'old' one
629                          * listed against the SSL connection */
630                         {
631                         if (s->session->cert == NULL)
632                                 {
633                                 CRYPTO_add(&s->cert->references,1,
634                                         CRYPTO_LOCK_SSL_CERT);
635                                 s->session->cert=s->cert;
636                                 }
637                         }
638
639                 if (s->session->cert == NULL)
640                         {
641                         ssl2_return_error(s,SSL2_PE_NO_CERTIFICATE);
642                         SSLerr(SSL_F_SERVER_HELLO,SSL_R_NO_CERTIFICATE_SPECIFIED);
643                         return(-1);
644                         }
645
646                 if (hit)
647                         {
648                         *(p++)=0;               /* no certificate type */
649                         s2n(s->version,p);      /* version */
650                         s2n(0,p);               /* cert len */
651                         s2n(0,p);               /* ciphers len */
652                         }
653                 else
654                         {
655                         /* EAY EAY */
656                         /* put certificate type */
657                         *(p++)=SSL2_CT_X509_CERTIFICATE;
658                         s2n(s->version,p);      /* version */
659                         n=i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509,NULL);
660                         s2n(n,p);               /* certificate length */
661                         i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509,&d);
662                         n=0;
663                         
664                         /* lets send out the ciphers we like in the
665                          * prefered order */
666                         sk= s->session->ciphers;
667                         n=ssl_cipher_list_to_bytes(s,s->session->ciphers,d);
668                         d+=n;
669                         s2n(n,p);               /* add cipher length */
670                         }
671
672                 /* make and send conn_id */
673                 s2n(SSL2_CONNECTION_ID_LENGTH,p);       /* add conn_id length */
674                 s->s2->conn_id_length=SSL2_CONNECTION_ID_LENGTH;
675                 RAND_bytes(s->s2->conn_id,(int)s->s2->conn_id_length);
676                 memcpy(d,s->s2->conn_id,SSL2_CONNECTION_ID_LENGTH);
677                 d+=SSL2_CONNECTION_ID_LENGTH;
678
679                 s->state=SSL2_ST_SEND_SERVER_HELLO_B;
680                 s->init_num=d-(unsigned char *)s->init_buf->data;
681                 s->init_off=0;
682                 }
683         /* SSL2_ST_SEND_SERVER_HELLO_B */
684         /* If we are using TCP/IP, the performace is bad if we do 2
685          * writes without a read between them.  This occurs when
686          * Session-id reuse is used, so I will put in a buffering module
687          */
688         if (s->hit)
689                 {
690                 if (!ssl_init_wbio_buffer(s,1)) return(-1);
691                 }
692  
693         return(ssl2_do_write(s));
694         }
695
696 static int get_client_finished(s)
697 SSL *s;
698         {
699         unsigned char *p;
700         int i;
701
702         p=(unsigned char *)s->init_buf->data;
703         if (s->state == SSL2_ST_GET_CLIENT_FINISHED_A)
704                 {
705                 i=ssl2_read(s,(char *)&(p[s->init_num]),1-s->init_num);
706                 if (i < 1-s->init_num)
707                         return(ssl2_part_read(s,SSL_F_GET_CLIENT_FINISHED,i));
708
709                 if (*p != SSL2_MT_CLIENT_FINISHED)
710                         {
711                         if (*p != SSL2_MT_ERROR)
712                                 {
713                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
714                                 SSLerr(SSL_F_GET_CLIENT_FINISHED,SSL_R_READ_WRONG_PACKET_TYPE);
715                                 }
716                         else
717                                 SSLerr(SSL_F_GET_CLIENT_FINISHED,SSL_R_PEER_ERROR);
718                         return(-1);
719                         }
720                 s->init_num=0;
721                 s->state=SSL2_ST_GET_CLIENT_FINISHED_B;
722                 }
723
724         /* SSL2_ST_GET_CLIENT_FINISHED_B */
725         i=ssl2_read(s,(char *)&(p[s->init_num]),s->s2->conn_id_length-s->init_num);
726         if (i < (int)s->s2->conn_id_length-s->init_num)
727                 {
728                 return(ssl2_part_read(s,SSL_F_GET_CLIENT_FINISHED,i));
729                 }
730         if (memcmp(p,s->s2->conn_id,(unsigned int)s->s2->conn_id_length) != 0)
731                 {
732                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
733                 SSLerr(SSL_F_GET_CLIENT_FINISHED,SSL_R_CONNECTION_ID_IS_DIFFERENT);
734                 return(-1);
735                 }
736         return(1);
737         }
738
739 static int server_verify(s)
740 SSL *s;
741         {
742         unsigned char *p;
743
744         if (s->state == SSL2_ST_SEND_SERVER_VERIFY_A)
745                 {
746                 p=(unsigned char *)s->init_buf->data;
747                 *(p++)=SSL2_MT_SERVER_VERIFY;
748                 memcpy(p,s->s2->challenge,(unsigned int)s->s2->challenge_length);
749                 /* p+=s->s2->challenge_length; */
750
751                 s->state=SSL2_ST_SEND_SERVER_VERIFY_B;
752                 s->init_num=s->s2->challenge_length+1;
753                 s->init_off=0;
754                 }
755         return(ssl2_do_write(s));
756         }
757
758 static int server_finish(s)
759 SSL *s;
760         {
761         unsigned char *p;
762
763         if (s->state == SSL2_ST_SEND_SERVER_FINISHED_A)
764                 {
765                 p=(unsigned char *)s->init_buf->data;
766                 *(p++)=SSL2_MT_SERVER_FINISHED;
767
768                 memcpy(p,s->session->session_id,
769                         (unsigned int)s->session->session_id_length);
770                 /* p+=s->session->session_id_length; */
771
772                 s->state=SSL2_ST_SEND_SERVER_FINISHED_B;
773                 s->init_num=s->session->session_id_length+1;
774                 s->init_off=0;
775                 }
776
777         /* SSL2_ST_SEND_SERVER_FINISHED_B */
778         return(ssl2_do_write(s));
779         }
780
781 /* send the request and check the response */
782 static int request_certificate(s)
783 SSL *s;
784         {
785         unsigned char *p,*p2,*buf2;
786         unsigned char *ccd;
787         int i,j,ctype,ret= -1;
788         X509 *x509=NULL;
789         STACK *sk=NULL;
790
791         ccd=s->s2->tmp.ccl;
792         if (s->state == SSL2_ST_SEND_REQUEST_CERTIFICATE_A)
793                 {
794                 p=(unsigned char *)s->init_buf->data;
795                 *(p++)=SSL2_MT_REQUEST_CERTIFICATE;
796                 *(p++)=SSL2_AT_MD5_WITH_RSA_ENCRYPTION;
797                 RAND_bytes(ccd,SSL2_MIN_CERT_CHALLENGE_LENGTH);
798                 memcpy(p,ccd,SSL2_MIN_CERT_CHALLENGE_LENGTH);
799
800                 s->state=SSL2_ST_SEND_REQUEST_CERTIFICATE_B;
801                 s->init_num=SSL2_MIN_CERT_CHALLENGE_LENGTH+2;
802                 s->init_off=0;
803                 }
804
805         if (s->state == SSL2_ST_SEND_REQUEST_CERTIFICATE_B)
806                 {
807                 i=ssl2_do_write(s);
808                 if (i <= 0)
809                         {
810                         ret=i;
811                         goto end;
812                         }
813
814                 s->init_num=0;
815                 s->state=SSL2_ST_SEND_REQUEST_CERTIFICATE_C;
816                 }
817
818         if (s->state == SSL2_ST_SEND_REQUEST_CERTIFICATE_C)
819                 {
820                 p=(unsigned char *)s->init_buf->data;
821                 i=ssl2_read(s,(char *)&(p[s->init_num]),6-s->init_num);
822                 if (i < 3)
823                         {
824                         ret=ssl2_part_read(s,SSL_F_REQUEST_CERTIFICATE,i);
825                         goto end;
826                         }
827
828                 if ((*p == SSL2_MT_ERROR) && (i >= 3))
829                         {
830                         n2s(p,i);
831                         if (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
832                                 {
833                                 ssl2_return_error(s,SSL2_PE_BAD_CERTIFICATE);
834                                 SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
835                                 goto end;
836                                 }
837                         ret=1;
838                         goto end;
839                         }
840                 if ((*(p++) != SSL2_MT_CLIENT_CERTIFICATE) || (i < 6))
841                         {
842                         ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
843                         SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_SHORT_READ);
844                         goto end;
845                         }
846                 /* ok we have a response */
847                 /* certificate type, there is only one right now. */
848                 ctype= *(p++);
849                 if (ctype != SSL2_AT_MD5_WITH_RSA_ENCRYPTION)
850                         {
851                         ssl2_return_error(s,SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE);
852                         SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_BAD_RESPONSE_ARGUMENT);
853                         goto end;
854                         }
855                 n2s(p,i); s->s2->tmp.clen=i;
856                 n2s(p,i); s->s2->tmp.rlen=i;
857                 s->state=SSL2_ST_SEND_REQUEST_CERTIFICATE_D;
858                 s->init_num=0;
859                 }
860
861         /* SSL2_ST_SEND_REQUEST_CERTIFICATE_D */
862         p=(unsigned char *)s->init_buf->data;
863         j=s->s2->tmp.clen+s->s2->tmp.rlen-s->init_num;
864         i=ssl2_read(s,(char *)&(p[s->init_num]),j);
865         if (i < j) 
866                 {
867                 ret=ssl2_part_read(s,SSL_F_REQUEST_CERTIFICATE,i);
868                 goto end;
869                 }
870
871         x509=(X509 *)d2i_X509(NULL,&p,(long)s->s2->tmp.clen);
872         if (x509 == NULL)
873                 {
874                 SSLerr(SSL_F_REQUEST_CERTIFICATE,ERR_R_X509_LIB);
875                 goto msg_end;
876                 }
877
878         if (((sk=sk_new_null()) == NULL) || (!sk_push(sk,(char *)x509)))
879                 {
880                 SSLerr(SSL_F_REQUEST_CERTIFICATE,ERR_R_MALLOC_FAILURE);
881                 goto msg_end;
882                 }
883
884         i=ssl_verify_cert_chain(s,sk);
885
886         if (i)  /* we like the packet, now check the chksum */
887                 {
888                 EVP_MD_CTX ctx;
889                 EVP_PKEY *pkey=NULL;
890
891                 EVP_VerifyInit(&ctx,s->ctx->rsa_md5);
892                 EVP_VerifyUpdate(&ctx,s->s2->key_material,
893                         (unsigned int)s->s2->key_material_length);
894                 EVP_VerifyUpdate(&ctx,ccd,SSL2_MIN_CERT_CHALLENGE_LENGTH);
895
896                 i=i2d_X509(s->session->cert->pkeys[SSL_PKEY_RSA_ENC].x509,NULL);
897                 buf2=(unsigned char *)Malloc((unsigned int)i);
898                 if (buf2 == NULL)
899                         {
900                         SSLerr(SSL_F_REQUEST_CERTIFICATE,ERR_R_MALLOC_FAILURE);
901                         goto msg_end;
902                         }
903                 p2=buf2;
904                 i=i2d_X509(s->session->cert->pkeys[SSL_PKEY_RSA_ENC].x509,&p2);
905                 EVP_VerifyUpdate(&ctx,buf2,(unsigned int)i);
906                 Free(buf2);
907
908                 pkey=X509_get_pubkey(x509);
909                 if (pkey == NULL) goto end;
910                 i=EVP_VerifyFinal(&ctx,p,s->s2->tmp.rlen,pkey);
911                 memset(&ctx,0,sizeof(ctx));
912
913                 if (i) 
914                         {
915                         if (s->session->peer != NULL)
916                                 X509_free(s->session->peer);
917                         s->session->peer=x509;
918                         CRYPTO_add(&x509->references,1,CRYPTO_LOCK_X509);
919                         ret=1;
920                         goto end;
921                         }
922                 else
923                         {
924                         SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_BAD_CHECKSUM);
925                         goto msg_end;
926                         }
927                 }
928         else
929                 {
930 msg_end:
931                 ssl2_return_error(s,SSL2_PE_BAD_CERTIFICATE);
932                 }
933 end:
934         if (sk != NULL) sk_free(sk);
935         if (x509 != NULL) X509_free(x509);
936         return(ret);
937         }
938
939 static int ssl_rsa_private_decrypt(c, len, from, to,padding)
940 CERT *c;
941 int len;
942 unsigned char *from;
943 unsigned char *to;
944 int padding;
945         {
946         RSA *rsa;
947         int i;
948
949         if ((c == NULL) || (c->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL))
950                 {
951                 SSLerr(SSL_F_SSL_RSA_PRIVATE_DECRYPT,SSL_R_NO_PRIVATEKEY);
952                 return(-1);
953                 }
954         if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey->type != EVP_PKEY_RSA)
955                 {
956                 SSLerr(SSL_F_SSL_RSA_PRIVATE_DECRYPT,SSL_R_PUBLIC_KEY_IS_NOT_RSA);
957                 return(-1);
958                 }
959         rsa=c->pkeys[SSL_PKEY_RSA_ENC].privatekey->pkey.rsa;
960
961         /* we have the public key */
962         i=RSA_private_decrypt(len,from,to,rsa,padding);
963         if (i < 0)
964                 SSLerr(SSL_F_SSL_RSA_PRIVATE_DECRYPT,ERR_R_RSA_LIB);
965         return(i);
966         }
967