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