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