OpenSSL Security Advisory [30 July 2002]
[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  * Copyright (c) 1998-2001 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include "ssl_locl.h"
113 #ifndef OPENSSL_NO_SSL2
114 #include <stdio.h>
115 #include <openssl/bio.h>
116 #include <openssl/rand.h>
117 #include <openssl/objects.h>
118 #include <openssl/evp.h>
119 #include "cryptlib.h"
120
121 static SSL_METHOD *ssl2_get_server_method(int ver);
122 static int get_client_master_key(SSL *s);
123 static int get_client_hello(SSL *s);
124 static int server_hello(SSL *s); 
125 static int get_client_finished(SSL *s);
126 static int server_verify(SSL *s);
127 static int server_finish(SSL *s);
128 static int request_certificate(SSL *s);
129 static int ssl_rsa_private_decrypt(CERT *c, int len, unsigned char *from,
130         unsigned char *to,int padding);
131 #define BREAK   break
132
133 static SSL_METHOD *ssl2_get_server_method(int ver)
134         {
135         if (ver == SSL2_VERSION)
136                 return(SSLv2_server_method());
137         else
138                 return(NULL);
139         }
140
141 SSL_METHOD *SSLv2_server_method(void)
142         {
143         static int init=1;
144         static SSL_METHOD SSLv2_server_data;
145
146         if (init)
147                 {
148                 memcpy((char *)&SSLv2_server_data,(char *)sslv2_base_method(),
149                         sizeof(SSL_METHOD));
150                 SSLv2_server_data.ssl_accept=ssl2_accept;
151                 SSLv2_server_data.get_ssl_method=ssl2_get_server_method;
152                 init=0;
153                 }
154         return(&SSLv2_server_data);
155         }
156
157 int ssl2_accept(SSL *s)
158         {
159         unsigned long l=time(NULL);
160         BUF_MEM *buf=NULL;
161         int ret= -1;
162         long num1;
163         void (*cb)(const SSL *ssl,int type,int val)=NULL;
164         int new_state,state;
165
166         RAND_add(&l,sizeof(l),0);
167         ERR_clear_error();
168         clear_sys_error();
169
170         if (s->info_callback != NULL)
171                 cb=s->info_callback;
172         else if (s->ctx->info_callback != NULL)
173                 cb=s->ctx->info_callback;
174
175         /* init things to blank */
176         s->in_handshake++;
177         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
178
179         if (s->cert == NULL)
180                 {
181                 SSLerr(SSL_F_SSL2_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
182                 return(-1);
183                 }
184
185         clear_sys_error();
186         for (;;)
187                 {
188                 state=s->state;
189
190                 switch (s->state)
191                         {
192                 case SSL_ST_BEFORE:
193                 case SSL_ST_ACCEPT:
194                 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
195                 case SSL_ST_OK|SSL_ST_ACCEPT:
196
197                         s->server=1;
198                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
199
200                         s->version=SSL2_VERSION;
201                         s->type=SSL_ST_ACCEPT;
202
203                         buf=s->init_buf;
204                         if ((buf == NULL) && ((buf=BUF_MEM_new()) == NULL))
205                                 { ret= -1; goto end; }
206                         if (!BUF_MEM_grow(buf,(int)
207                                 SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
208                                 { ret= -1; goto end; }
209                         s->init_buf=buf;
210                         s->init_num=0;
211                         s->ctx->stats.sess_accept++;
212                         s->handshake_func=ssl2_accept;
213                         s->state=SSL2_ST_GET_CLIENT_HELLO_A;
214                         BREAK;
215
216                 case SSL2_ST_GET_CLIENT_HELLO_A:
217                 case SSL2_ST_GET_CLIENT_HELLO_B:
218                 case SSL2_ST_GET_CLIENT_HELLO_C:
219                         s->shutdown=0;
220                         ret=get_client_hello(s);
221                         if (ret <= 0) goto end;
222                         s->init_num=0;
223                         s->state=SSL2_ST_SEND_SERVER_HELLO_A;
224                         BREAK;
225
226                 case SSL2_ST_SEND_SERVER_HELLO_A:
227                 case SSL2_ST_SEND_SERVER_HELLO_B:
228                         ret=server_hello(s);
229                         if (ret <= 0) goto end;
230                         s->init_num=0;
231                         if (!s->hit)
232                                 {
233                                 s->state=SSL2_ST_GET_CLIENT_MASTER_KEY_A;
234                                 BREAK;
235                                 }
236                         else
237                                 {
238                                 s->state=SSL2_ST_SERVER_START_ENCRYPTION;
239                                 BREAK;
240                                 }
241                 case SSL2_ST_GET_CLIENT_MASTER_KEY_A:
242                 case SSL2_ST_GET_CLIENT_MASTER_KEY_B:
243                         ret=get_client_master_key(s);
244                         if (ret <= 0) goto end;
245                         s->init_num=0;
246                         s->state=SSL2_ST_SERVER_START_ENCRYPTION;
247                         BREAK;
248
249                 case SSL2_ST_SERVER_START_ENCRYPTION:
250                         /* Ok we how have sent all the stuff needed to
251                          * start encrypting, the next packet back will
252                          * be encrypted. */
253                         if (!ssl2_enc_init(s,0))
254                                 { ret= -1; goto end; }
255                         s->s2->clear_text=0;
256                         s->state=SSL2_ST_SEND_SERVER_VERIFY_A;
257                         BREAK;
258
259                 case SSL2_ST_SEND_SERVER_VERIFY_A:
260                 case SSL2_ST_SEND_SERVER_VERIFY_B:
261                         ret=server_verify(s);
262                         if (ret <= 0) goto end;
263                         s->init_num=0;
264                         if (s->hit)
265                                 {
266                                 /* If we are in here, we have been
267                                  * buffering the output, so we need to
268                                  * flush it and remove buffering from
269                                  * future traffic */
270                                 s->state=SSL2_ST_SEND_SERVER_VERIFY_C;
271                                 BREAK;
272                                 }
273                         else
274                                 {
275                                 s->state=SSL2_ST_GET_CLIENT_FINISHED_A;
276                                 break;
277                                 }
278
279                 case SSL2_ST_SEND_SERVER_VERIFY_C:
280                         /* get the number of bytes to write */
281                         num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
282                         if (num1 != 0)
283                                 {
284                                 s->rwstate=SSL_WRITING;
285                                 num1=BIO_flush(s->wbio);
286                                 if (num1 <= 0) { ret= -1; goto end; }
287                                 s->rwstate=SSL_NOTHING;
288                                 }
289
290                         /* flushed and now remove buffering */
291                         s->wbio=BIO_pop(s->wbio);
292
293                         s->state=SSL2_ST_GET_CLIENT_FINISHED_A;
294                         BREAK;
295
296                 case SSL2_ST_GET_CLIENT_FINISHED_A:
297                 case SSL2_ST_GET_CLIENT_FINISHED_B:
298                         ret=get_client_finished(s);
299                         if (ret <= 0)
300                                 goto end;
301                         s->init_num=0;
302                         s->state=SSL2_ST_SEND_REQUEST_CERTIFICATE_A;
303                         BREAK;
304
305                 case SSL2_ST_SEND_REQUEST_CERTIFICATE_A:
306                 case SSL2_ST_SEND_REQUEST_CERTIFICATE_B:
307                 case SSL2_ST_SEND_REQUEST_CERTIFICATE_C:
308                 case SSL2_ST_SEND_REQUEST_CERTIFICATE_D:
309                         /* don't do a 'request certificate' if we
310                          * don't want to, or we already have one, and
311                          * we only want to do it once. */
312                         if (!(s->verify_mode & SSL_VERIFY_PEER) ||
313                                 ((s->session->peer != NULL) &&
314                                 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)))
315                                 {
316                                 s->state=SSL2_ST_SEND_SERVER_FINISHED_A;
317                                 break;
318                                 }
319                         else
320                                 {
321                                 ret=request_certificate(s);
322                                 if (ret <= 0) goto end;
323                                 s->init_num=0;
324                                 s->state=SSL2_ST_SEND_SERVER_FINISHED_A;
325                                 }
326                         BREAK;
327
328                 case SSL2_ST_SEND_SERVER_FINISHED_A:
329                 case SSL2_ST_SEND_SERVER_FINISHED_B:
330                         ret=server_finish(s);
331                         if (ret <= 0) goto end;
332                         s->init_num=0;
333                         s->state=SSL_ST_OK;
334                         break;
335
336                 case SSL_ST_OK:
337                         BUF_MEM_free(s->init_buf);
338                         ssl_free_wbio_buffer(s);
339                         s->init_buf=NULL;
340                         s->init_num=0;
341                 /*      ERR_clear_error();*/
342
343                         ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
344
345                         s->ctx->stats.sess_accept_good++;
346                         /* s->server=1; */
347                         ret=1;
348
349                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
350
351                         goto end;
352                         /* BREAK; */
353
354                 default:
355                         SSLerr(SSL_F_SSL2_ACCEPT,SSL_R_UNKNOWN_STATE);
356                         ret= -1;
357                         goto end;
358                         /* BREAK; */
359                         }
360                 
361                 if ((cb != NULL) && (s->state != state))
362                         {
363                         new_state=s->state;
364                         s->state=state;
365                         cb(s,SSL_CB_ACCEPT_LOOP,1);
366                         s->state=new_state;
367                         }
368                 }
369 end:
370         s->in_handshake--;
371         if (cb != NULL)
372                 cb(s,SSL_CB_ACCEPT_EXIT,ret);
373         return(ret);
374         }
375
376 static int get_client_master_key(SSL *s)
377         {
378         int is_export,i,n,keya,ek;
379         unsigned long len;
380         unsigned char *p;
381         SSL_CIPHER *cp;
382         const EVP_CIPHER *c;
383         const EVP_MD *md;
384
385         p=(unsigned char *)s->init_buf->data;
386         if (s->state == SSL2_ST_GET_CLIENT_MASTER_KEY_A)
387                 {
388                 i=ssl2_read(s,(char *)&(p[s->init_num]),10-s->init_num);
389
390                 if (i < (10-s->init_num))
391                         return(ssl2_part_read(s,SSL_F_GET_CLIENT_MASTER_KEY,i));
392                 s->init_num = 10;
393
394                 if (*(p++) != SSL2_MT_CLIENT_MASTER_KEY)
395                         {
396                         if (p[-1] != SSL2_MT_ERROR)
397                                 {
398                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
399                                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_READ_WRONG_PACKET_TYPE);
400                                 }
401                         else
402                                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
403                                         SSL_R_PEER_ERROR);
404                         return(-1);
405                         }
406
407                 cp=ssl2_get_cipher_by_char(p);
408                 if (cp == NULL)
409                         {
410                         ssl2_return_error(s,SSL2_PE_NO_CIPHER);
411                         SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
412                                 SSL_R_NO_CIPHER_MATCH);
413                         return(-1);
414                         }
415                 s->session->cipher= cp;
416
417                 p+=3;
418                 n2s(p,i); s->s2->tmp.clear=i;
419                 n2s(p,i); s->s2->tmp.enc=i;
420                 n2s(p,i); s->session->key_arg_length=i;
421                 if(s->session->key_arg_length > SSL_MAX_KEY_ARG_LENGTH)
422                         {
423                         SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,
424                                    SSL_R_KEY_ARG_TOO_LONG);
425                         return -1;
426                         }
427                 s->state=SSL2_ST_GET_CLIENT_MASTER_KEY_B;
428                 }
429
430         /* SSL2_ST_GET_CLIENT_MASTER_KEY_B */
431         p=(unsigned char *)s->init_buf->data;
432         die(s->init_buf->length >= SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER);
433         keya=s->session->key_arg_length;
434         len = 10 + (unsigned long)s->s2->tmp.clear + (unsigned long)s->s2->tmp.enc + (unsigned long)keya;
435         if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)
436                 {
437                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_MESSAGE_TOO_LONG);
438                 return -1;
439                 }
440         n = (int)len - s->init_num;
441         i = ssl2_read(s,(char *)&(p[s->init_num]),n);
442         if (i != n) return(ssl2_part_read(s,SSL_F_GET_CLIENT_MASTER_KEY,i));
443         if (s->msg_callback)
444                 s->msg_callback(0, s->version, 0, p, (size_t)len, s, s->msg_callback_arg); /* CLIENT-MASTER-KEY */
445         p += 10;
446
447         memcpy(s->session->key_arg,&(p[s->s2->tmp.clear+s->s2->tmp.enc]),
448                 (unsigned int)keya);
449
450         if (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL)
451                 {
452                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
453                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_NO_PRIVATEKEY);
454                 return(-1);
455                 }
456         i=ssl_rsa_private_decrypt(s->cert,s->s2->tmp.enc,
457                 &(p[s->s2->tmp.clear]),&(p[s->s2->tmp.clear]),
458                 (s->s2->ssl2_rollback)?RSA_SSLV23_PADDING:RSA_PKCS1_PADDING);
459
460         is_export=SSL_C_IS_EXPORT(s->session->cipher);
461         
462         if (!ssl_cipher_get_evp(s->session,&c,&md,NULL))
463                 {
464                 ssl2_return_error(s,SSL2_PE_NO_CIPHER);
465                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS);
466                 return(0);
467                 }
468
469         if (s->session->cipher->algorithm2 & SSL2_CF_8_BYTE_ENC)
470                 {
471                 is_export=1;
472                 ek=8;
473                 }
474         else
475                 ek=5;
476
477         /* bad decrypt */
478 #if 1
479         /* If a bad decrypt, continue with protocol but with a
480          * random master secret (Bleichenbacher attack) */
481         if ((i < 0) ||
482                 ((!is_export && (i != EVP_CIPHER_key_length(c)))
483                 || (is_export && ((i != ek) || (s->s2->tmp.clear+(unsigned int)i !=
484                         (unsigned int)EVP_CIPHER_key_length(c))))))
485                 {
486                 ERR_clear_error();
487                 if (is_export)
488                         i=ek;
489                 else
490                         i=EVP_CIPHER_key_length(c);
491                 RAND_pseudo_bytes(p,i);
492                 }
493 #else
494         if (i < 0)
495                 {
496                 error=1;
497                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_BAD_RSA_DECRYPT);
498                 }
499         /* incorrect number of key bytes for non export cipher */
500         else if ((!is_export && (i != EVP_CIPHER_key_length(c)))
501                 || (is_export && ((i != ek) || (s->s2->tmp.clear+i !=
502                         EVP_CIPHER_key_length(c)))))
503                 {
504                 error=1;
505                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_WRONG_NUMBER_OF_KEY_BITS);
506                 }
507         if (error)
508                 {
509                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
510                 return(-1);
511                 }
512 #endif
513
514         if (is_export) i+=s->s2->tmp.clear;
515         die(i <= SSL_MAX_MASTER_KEY_LENGTH);
516         s->session->master_key_length=i;
517         memcpy(s->session->master_key,p,(unsigned int)i);
518         return(1);
519         }
520
521 static int get_client_hello(SSL *s)
522         {
523         int i,n;
524         unsigned long len;
525         unsigned char *p;
526         STACK_OF(SSL_CIPHER) *cs; /* a stack of SSL_CIPHERS */
527         STACK_OF(SSL_CIPHER) *cl; /* the ones we want to use */
528         STACK_OF(SSL_CIPHER) *prio, *allow;
529         int z;
530
531         /* This is a bit of a hack to check for the correct packet
532          * type the first time round. */
533         if (s->state == SSL2_ST_GET_CLIENT_HELLO_A)
534                 {
535                 s->first_packet=1;
536                 s->state=SSL2_ST_GET_CLIENT_HELLO_B;
537                 }
538
539         p=(unsigned char *)s->init_buf->data;
540         if (s->state == SSL2_ST_GET_CLIENT_HELLO_B)
541                 {
542                 i=ssl2_read(s,(char *)&(p[s->init_num]),9-s->init_num);
543                 if (i < (9-s->init_num)) 
544                         return(ssl2_part_read(s,SSL_F_GET_CLIENT_HELLO,i));
545                 s->init_num = 9;
546         
547                 if (*(p++) != SSL2_MT_CLIENT_HELLO)
548                         {
549                         if (p[-1] != SSL2_MT_ERROR)
550                                 {
551                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
552                                 SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_READ_WRONG_PACKET_TYPE);
553                                 }
554                         else
555                                 SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_PEER_ERROR);
556                         return(-1);
557                         }
558                 n2s(p,i);
559                 if (i < s->version) s->version=i;
560                 n2s(p,i); s->s2->tmp.cipher_spec_length=i;
561                 n2s(p,i); s->s2->tmp.session_id_length=i;
562                 n2s(p,i); s->s2->challenge_length=i;
563                 if (    (i < SSL2_MIN_CHALLENGE_LENGTH) ||
564                         (i > SSL2_MAX_CHALLENGE_LENGTH))
565                         {
566                         SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_INVALID_CHALLENGE_LENGTH);
567                         return(-1);
568                         }
569                 s->state=SSL2_ST_GET_CLIENT_HELLO_C;
570                 }
571
572         /* SSL2_ST_GET_CLIENT_HELLO_C */
573         p=(unsigned char *)s->init_buf->data;
574         len = 9 + (unsigned long)s->s2->tmp.cipher_spec_length + (unsigned long)s->s2->challenge_length + (unsigned long)s->s2->tmp.session_id_length;
575         if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)
576                 {
577                 SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_MESSAGE_TOO_LONG);
578                 return -1;
579                 }
580         n = (int)len - s->init_num;
581         i = ssl2_read(s,(char *)&(p[s->init_num]),n);
582         if (i != n) return(ssl2_part_read(s,SSL_F_GET_CLIENT_HELLO,i));
583         if (s->msg_callback)
584                 s->msg_callback(0, s->version, 0, p, (size_t)len, s, s->msg_callback_arg); /* CLIENT-HELLO */
585         p += 9;
586
587         /* get session-id before cipher stuff so we can get out session
588          * structure if it is cached */
589         /* session-id */
590         if ((s->s2->tmp.session_id_length != 0) && 
591                 (s->s2->tmp.session_id_length != SSL2_SSL_SESSION_ID_LENGTH))
592                 {
593                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
594                 SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_BAD_SSL_SESSION_ID_LENGTH);
595                 return(-1);
596                 }
597
598         if (s->s2->tmp.session_id_length == 0)
599                 {
600                 if (!ssl_get_new_session(s,1))
601                         {
602                         ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
603                         return(-1);
604                         }
605                 }
606         else
607                 {
608                 i=ssl_get_prev_session(s,&(p[s->s2->tmp.cipher_spec_length]),
609                         s->s2->tmp.session_id_length);
610                 if (i == 1)
611                         { /* previous session */
612                         s->hit=1;
613                         }
614                 else if (i == -1)
615                         {
616                         ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
617                         return(-1);
618                         }
619                 else
620                         {
621                         if (s->cert == NULL)
622                                 {
623                                 ssl2_return_error(s,SSL2_PE_NO_CERTIFICATE);
624                                 SSLerr(SSL_F_GET_CLIENT_HELLO,SSL_R_NO_CERTIFICATE_SET);
625                                 return(-1);
626                                 }
627
628                         if (!ssl_get_new_session(s,1))
629                                 {
630                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
631                                 return(-1);
632                                 }
633                         }
634                 }
635
636         if (!s->hit)
637                 {
638                 cs=ssl_bytes_to_cipher_list(s,p,s->s2->tmp.cipher_spec_length,
639                         &s->session->ciphers);
640                 if (cs == NULL) goto mem_err;
641
642                 cl=SSL_get_ciphers(s);
643
644                 if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE)
645                     {
646                     prio=sk_SSL_CIPHER_dup(cl);
647                     if (prio == NULL) goto mem_err;
648                     allow = cs;
649                     }
650                 else
651                     {
652                     prio = cs;
653                     allow = cl;
654                     }
655                 for (z=0; z<sk_SSL_CIPHER_num(prio); z++)
656                         {
657                         if (sk_SSL_CIPHER_find(allow,sk_SSL_CIPHER_value(prio,z)) < 0)
658                                 {
659                                 sk_SSL_CIPHER_delete(prio,z);
660                                 z--;
661                                 }
662                         }
663                 if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE)
664                     {
665                     sk_SSL_CIPHER_free(s->session->ciphers);
666                     s->session->ciphers = prio;
667                     }
668                 /* s->session->ciphers should now have a list of
669                  * ciphers that are on both the client and server.
670                  * This list is ordered by the order the client sent
671                  * the ciphers or in the order of the server's preference
672                  * if SSL_OP_CIPHER_SERVER_PREFERENCE was set.
673                  */
674                 }
675         p+=s->s2->tmp.cipher_spec_length;
676         /* done cipher selection */
677
678         /* session id extracted already */
679         p+=s->s2->tmp.session_id_length;
680
681         /* challenge */
682         die(s->s2->challenge_length <= sizeof s->s2->challenge);
683         memcpy(s->s2->challenge,p,(unsigned int)s->s2->challenge_length);
684         return(1);
685 mem_err:
686         SSLerr(SSL_F_GET_CLIENT_HELLO,ERR_R_MALLOC_FAILURE);
687         return(0);
688         }
689
690 static int server_hello(SSL *s)
691         {
692         unsigned char *p,*d;
693         int n,hit;
694         STACK_OF(SSL_CIPHER) *sk;
695
696         p=(unsigned char *)s->init_buf->data;
697         if (s->state == SSL2_ST_SEND_SERVER_HELLO_A)
698                 {
699                 d=p+11;
700                 *(p++)=SSL2_MT_SERVER_HELLO;            /* type */
701                 hit=s->hit;
702                 *(p++)=(unsigned char)hit;
703 #if 1
704                 if (!hit)
705                         {
706                         if (s->session->sess_cert != NULL)
707                                 /* This can't really happen because get_client_hello
708                                  * has called ssl_get_new_session, which does not set
709                                  * sess_cert. */
710                                 ssl_sess_cert_free(s->session->sess_cert);
711                         s->session->sess_cert = ssl_sess_cert_new();
712                         if (s->session->sess_cert == NULL)
713                                 {
714                                 SSLerr(SSL_F_SERVER_HELLO, ERR_R_MALLOC_FAILURE);
715                                 return(-1);
716                                 }
717                         }
718                 /* If 'hit' is set, then s->sess_cert may be non-NULL or NULL,
719                  * depending on whether it survived in the internal cache
720                  * or was retrieved from an external cache.
721                  * If it is NULL, we cannot put any useful data in it anyway,
722                  * so we don't touch it.
723                  */
724
725 #else /* That's what used to be done when cert_st and sess_cert_st were
726            * the same. */
727                 if (!hit)
728                         {                       /* else add cert to session */
729                         CRYPTO_add(&s->cert->references,1,CRYPTO_LOCK_SSL_CERT);
730                         if (s->session->sess_cert != NULL)
731                                 ssl_cert_free(s->session->sess_cert);
732                         s->session->sess_cert=s->cert;          
733                         }
734                 else    /* We have a session id-cache hit, if the
735                          * session-id has no certificate listed against
736                          * the 'cert' structure, grab the 'old' one
737                          * listed against the SSL connection */
738                         {
739                         if (s->session->sess_cert == NULL)
740                                 {
741                                 CRYPTO_add(&s->cert->references,1,
742                                         CRYPTO_LOCK_SSL_CERT);
743                                 s->session->sess_cert=s->cert;
744                                 }
745                         }
746 #endif
747
748                 if (s->cert == NULL)
749                         {
750                         ssl2_return_error(s,SSL2_PE_NO_CERTIFICATE);
751                         SSLerr(SSL_F_SERVER_HELLO,SSL_R_NO_CERTIFICATE_SPECIFIED);
752                         return(-1);
753                         }
754
755                 if (hit)
756                         {
757                         *(p++)=0;               /* no certificate type */
758                         s2n(s->version,p);      /* version */
759                         s2n(0,p);               /* cert len */
760                         s2n(0,p);               /* ciphers len */
761                         }
762                 else
763                         {
764                         /* EAY EAY */
765                         /* put certificate type */
766                         *(p++)=SSL2_CT_X509_CERTIFICATE;
767                         s2n(s->version,p);      /* version */
768                         n=i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509,NULL);
769                         s2n(n,p);               /* certificate length */
770                         i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509,&d);
771                         n=0;
772                         
773                         /* lets send out the ciphers we like in the
774                          * prefered order */
775                         sk= s->session->ciphers;
776                         n=ssl_cipher_list_to_bytes(s,s->session->ciphers,d);
777                         d+=n;
778                         s2n(n,p);               /* add cipher length */
779                         }
780
781                 /* make and send conn_id */
782                 s2n(SSL2_CONNECTION_ID_LENGTH,p);       /* add conn_id length */
783                 s->s2->conn_id_length=SSL2_CONNECTION_ID_LENGTH;
784                 RAND_pseudo_bytes(s->s2->conn_id,(int)s->s2->conn_id_length);
785                 memcpy(d,s->s2->conn_id,SSL2_CONNECTION_ID_LENGTH);
786                 d+=SSL2_CONNECTION_ID_LENGTH;
787
788                 s->state=SSL2_ST_SEND_SERVER_HELLO_B;
789                 s->init_num=d-(unsigned char *)s->init_buf->data;
790                 s->init_off=0;
791                 }
792         /* SSL2_ST_SEND_SERVER_HELLO_B */
793         /* If we are using TCP/IP, the performance is bad if we do 2
794          * writes without a read between them.  This occurs when
795          * Session-id reuse is used, so I will put in a buffering module
796          */
797         if (s->hit)
798                 {
799                 if (!ssl_init_wbio_buffer(s,1)) return(-1);
800                 }
801  
802         return(ssl2_do_write(s));
803         }
804
805 static int get_client_finished(SSL *s)
806         {
807         unsigned char *p;
808         int i, n;
809         unsigned long len;
810
811         p=(unsigned char *)s->init_buf->data;
812         if (s->state == SSL2_ST_GET_CLIENT_FINISHED_A)
813                 {
814                 i=ssl2_read(s,(char *)&(p[s->init_num]),1-s->init_num);
815                 if (i < 1-s->init_num)
816                         return(ssl2_part_read(s,SSL_F_GET_CLIENT_FINISHED,i));
817                 s->init_num += i;
818
819                 if (*p != SSL2_MT_CLIENT_FINISHED)
820                         {
821                         if (*p != SSL2_MT_ERROR)
822                                 {
823                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
824                                 SSLerr(SSL_F_GET_CLIENT_FINISHED,SSL_R_READ_WRONG_PACKET_TYPE);
825                                 }
826                         else
827                                 {
828                                 SSLerr(SSL_F_GET_CLIENT_FINISHED,SSL_R_PEER_ERROR);
829                                 /* try to read the error message */
830                                 i=ssl2_read(s,(char *)&(p[s->init_num]),3-s->init_num);
831                                 return ssl2_part_read(s,SSL_F_GET_SERVER_VERIFY,i);
832                                 }
833                         return(-1);
834                         }
835                 s->state=SSL2_ST_GET_CLIENT_FINISHED_B;
836                 }
837
838         /* SSL2_ST_GET_CLIENT_FINISHED_B */
839         die(s->s2->conn_id_length <= sizeof s->s2->conn_id);
840         len = 1 + (unsigned long)s->s2->conn_id_length;
841         n = (int)len - s->init_num;
842         i = ssl2_read(s,(char *)&(p[s->init_num]),n);
843         if (i < n)
844                 {
845                 return(ssl2_part_read(s,SSL_F_GET_CLIENT_FINISHED,i));
846                 }
847         if (s->msg_callback)
848                 s->msg_callback(0, s->version, 0, p, len, s, s->msg_callback_arg); /* CLIENT-FINISHED */
849         p += 1;
850         if (memcmp(p,s->s2->conn_id,(unsigned int)s->s2->conn_id_length) != 0)
851                 {
852                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
853                 SSLerr(SSL_F_GET_CLIENT_FINISHED,SSL_R_CONNECTION_ID_IS_DIFFERENT);
854                 return(-1);
855                 }
856         return(1);
857         }
858
859 static int server_verify(SSL *s)
860         {
861         unsigned char *p;
862
863         if (s->state == SSL2_ST_SEND_SERVER_VERIFY_A)
864                 {
865                 p=(unsigned char *)s->init_buf->data;
866                 *(p++)=SSL2_MT_SERVER_VERIFY;
867                 die(s->s2->challenge_length <= sizeof s->s2->challenge);
868                 memcpy(p,s->s2->challenge,(unsigned int)s->s2->challenge_length);
869                 /* p+=s->s2->challenge_length; */
870
871                 s->state=SSL2_ST_SEND_SERVER_VERIFY_B;
872                 s->init_num=s->s2->challenge_length+1;
873                 s->init_off=0;
874                 }
875         return(ssl2_do_write(s));
876         }
877
878 static int server_finish(SSL *s)
879         {
880         unsigned char *p;
881
882         if (s->state == SSL2_ST_SEND_SERVER_FINISHED_A)
883                 {
884                 p=(unsigned char *)s->init_buf->data;
885                 *(p++)=SSL2_MT_SERVER_FINISHED;
886
887                 die(s->session->session_id_length
888                     <= sizeof s->session->session_id);
889                 memcpy(p,s->session->session_id,
890                         (unsigned int)s->session->session_id_length);
891                 /* p+=s->session->session_id_length; */
892
893                 s->state=SSL2_ST_SEND_SERVER_FINISHED_B;
894                 s->init_num=s->session->session_id_length+1;
895                 s->init_off=0;
896                 }
897
898         /* SSL2_ST_SEND_SERVER_FINISHED_B */
899         return(ssl2_do_write(s));
900         }
901
902 /* send the request and check the response */
903 static int request_certificate(SSL *s)
904         {
905         unsigned char *p,*p2,*buf2;
906         unsigned char *ccd;
907         int i,j,ctype,ret= -1;
908         unsigned long len;
909         X509 *x509=NULL;
910         STACK_OF(X509) *sk=NULL;
911
912         ccd=s->s2->tmp.ccl;
913         if (s->state == SSL2_ST_SEND_REQUEST_CERTIFICATE_A)
914                 {
915                 p=(unsigned char *)s->init_buf->data;
916                 *(p++)=SSL2_MT_REQUEST_CERTIFICATE;
917                 *(p++)=SSL2_AT_MD5_WITH_RSA_ENCRYPTION;
918                 RAND_pseudo_bytes(ccd,SSL2_MIN_CERT_CHALLENGE_LENGTH);
919                 memcpy(p,ccd,SSL2_MIN_CERT_CHALLENGE_LENGTH);
920
921                 s->state=SSL2_ST_SEND_REQUEST_CERTIFICATE_B;
922                 s->init_num=SSL2_MIN_CERT_CHALLENGE_LENGTH+2;
923                 s->init_off=0;
924                 }
925
926         if (s->state == SSL2_ST_SEND_REQUEST_CERTIFICATE_B)
927                 {
928                 i=ssl2_do_write(s);
929                 if (i <= 0)
930                         {
931                         ret=i;
932                         goto end;
933                         }
934
935                 s->init_num=0;
936                 s->state=SSL2_ST_SEND_REQUEST_CERTIFICATE_C;
937                 }
938
939         if (s->state == SSL2_ST_SEND_REQUEST_CERTIFICATE_C)
940                 {
941                 p=(unsigned char *)s->init_buf->data;
942                 i=ssl2_read(s,(char *)&(p[s->init_num]),6-s->init_num); /* try to read 6 octets ... */
943                 if (i < 3-s->init_num) /* ... but don't call ssl2_part_read now if we got at least 3
944                                         * (probably NO-CERTIFICATE-ERROR) */
945                         {
946                         ret=ssl2_part_read(s,SSL_F_REQUEST_CERTIFICATE,i);
947                         goto end;
948                         }
949                 s->init_num += i;
950
951                 if ((s->init_num >= 3) && (p[0] == SSL2_MT_ERROR))
952                         {
953                         n2s(p,i);
954                         if (i != SSL2_PE_NO_CERTIFICATE)
955                                 {
956                                 /* not the error message we expected -- let ssl2_part_read handle it */
957                                 s->init_num -= 3;
958                                 ret = ssl2_part_read(s,SSL_F_REQUEST_CERTIFICATE, 3);
959                                 goto end;
960                                 }
961
962                         if (s->msg_callback)
963                                 s->msg_callback(0, s->version, 0, p, 3, s, s->msg_callback_arg); /* ERROR */
964
965                         /* this is the one place where we can recover from an SSL 2.0 error */
966
967                         if (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
968                                 {
969                                 ssl2_return_error(s,SSL2_PE_BAD_CERTIFICATE);
970                                 SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
971                                 goto end;
972                                 }
973                         ret=1;
974                         goto end;
975                         }
976                 if ((*(p++) != SSL2_MT_CLIENT_CERTIFICATE) || (s->init_num < 6))
977                         {
978                         ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
979                         SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_SHORT_READ);
980                         goto end;
981                         }
982                 if (s->init_num != 6)
983                         {
984                         SSLerr(SSL_F_REQUEST_CERTIFICATE, ERR_R_INTERNAL_ERROR);
985                         goto end;
986                         }
987                 
988                 /* ok we have a response */
989                 /* certificate type, there is only one right now. */
990                 ctype= *(p++);
991                 if (ctype != SSL2_AT_MD5_WITH_RSA_ENCRYPTION)
992                         {
993                         ssl2_return_error(s,SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE);
994                         SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_BAD_RESPONSE_ARGUMENT);
995                         goto end;
996                         }
997                 n2s(p,i); s->s2->tmp.clen=i;
998                 n2s(p,i); s->s2->tmp.rlen=i;
999                 s->state=SSL2_ST_SEND_REQUEST_CERTIFICATE_D;
1000                 }
1001
1002         /* SSL2_ST_SEND_REQUEST_CERTIFICATE_D */
1003         p=(unsigned char *)s->init_buf->data;
1004         len = 6 + (unsigned long)s->s2->tmp.clen + (unsigned long)s->s2->tmp.rlen;
1005         if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)
1006                 {
1007                 SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_MESSAGE_TOO_LONG);
1008                 goto end;
1009                 }
1010         j = (int)len - s->init_num;
1011         i = ssl2_read(s,(char *)&(p[s->init_num]),j);
1012         if (i < j) 
1013                 {
1014                 ret=ssl2_part_read(s,SSL_F_REQUEST_CERTIFICATE,i);
1015                 goto end;
1016                 }
1017         if (s->msg_callback)
1018                 s->msg_callback(0, s->version, 0, p, len, s, s->msg_callback_arg); /* CLIENT-CERTIFICATE */
1019         p += 6;
1020
1021         x509=(X509 *)d2i_X509(NULL,&p,(long)s->s2->tmp.clen);
1022         if (x509 == NULL)
1023                 {
1024                 SSLerr(SSL_F_REQUEST_CERTIFICATE,ERR_R_X509_LIB);
1025                 goto msg_end;
1026                 }
1027
1028         if (((sk=sk_X509_new_null()) == NULL) || (!sk_X509_push(sk,x509)))
1029                 {
1030                 SSLerr(SSL_F_REQUEST_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1031                 goto msg_end;
1032                 }
1033
1034         i=ssl_verify_cert_chain(s,sk);
1035
1036         if (i)  /* we like the packet, now check the chksum */
1037                 {
1038                 EVP_MD_CTX ctx;
1039                 EVP_PKEY *pkey=NULL;
1040
1041                 EVP_MD_CTX_init(&ctx);
1042                 EVP_VerifyInit_ex(&ctx,s->ctx->rsa_md5, NULL);
1043                 EVP_VerifyUpdate(&ctx,s->s2->key_material,
1044                         (unsigned int)s->s2->key_material_length);
1045                 EVP_VerifyUpdate(&ctx,ccd,SSL2_MIN_CERT_CHALLENGE_LENGTH);
1046
1047                 i=i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509,NULL);
1048                 buf2=OPENSSL_malloc((unsigned int)i);
1049                 if (buf2 == NULL)
1050                         {
1051                         SSLerr(SSL_F_REQUEST_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1052                         goto msg_end;
1053                         }
1054                 p2=buf2;
1055                 i=i2d_X509(s->cert->pkeys[SSL_PKEY_RSA_ENC].x509,&p2);
1056                 EVP_VerifyUpdate(&ctx,buf2,(unsigned int)i);
1057                 OPENSSL_free(buf2);
1058
1059                 pkey=X509_get_pubkey(x509);
1060                 if (pkey == NULL) goto end;
1061                 i=EVP_VerifyFinal(&ctx,p,s->s2->tmp.rlen,pkey);
1062                 EVP_PKEY_free(pkey);
1063                 EVP_MD_CTX_cleanup(&ctx);
1064
1065                 if (i) 
1066                         {
1067                         if (s->session->peer != NULL)
1068                                 X509_free(s->session->peer);
1069                         s->session->peer=x509;
1070                         CRYPTO_add(&x509->references,1,CRYPTO_LOCK_X509);
1071                         s->session->verify_result = s->verify_result;
1072                         ret=1;
1073                         goto end;
1074                         }
1075                 else
1076                         {
1077                         SSLerr(SSL_F_REQUEST_CERTIFICATE,SSL_R_BAD_CHECKSUM);
1078                         goto msg_end;
1079                         }
1080                 }
1081         else
1082                 {
1083 msg_end:
1084                 ssl2_return_error(s,SSL2_PE_BAD_CERTIFICATE);
1085                 }
1086 end:
1087         sk_X509_free(sk);
1088         X509_free(x509);
1089         return(ret);
1090         }
1091
1092 static int ssl_rsa_private_decrypt(CERT *c, int len, unsigned char *from,
1093              unsigned char *to, int padding)
1094         {
1095         RSA *rsa;
1096         int i;
1097
1098         if ((c == NULL) || (c->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL))
1099                 {
1100                 SSLerr(SSL_F_SSL_RSA_PRIVATE_DECRYPT,SSL_R_NO_PRIVATEKEY);
1101                 return(-1);
1102                 }
1103         if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey->type != EVP_PKEY_RSA)
1104                 {
1105                 SSLerr(SSL_F_SSL_RSA_PRIVATE_DECRYPT,SSL_R_PUBLIC_KEY_IS_NOT_RSA);
1106                 return(-1);
1107                 }
1108         rsa=c->pkeys[SSL_PKEY_RSA_ENC].privatekey->pkey.rsa;
1109
1110         /* we have the public key */
1111         i=RSA_private_decrypt(len,from,to,rsa,padding);
1112         if (i < 0)
1113                 SSLerr(SSL_F_SSL_RSA_PRIVATE_DECRYPT,ERR_R_RSA_LIB);
1114         return(i);
1115         }
1116 #else /* !OPENSSL_NO_SSL2 */
1117
1118 # if PEDANTIC
1119 static void *dummy=&dummy;
1120 # endif
1121
1122 #endif