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