make update
[openssl.git] / ssl / s2_clnt.c
1 /* ssl/s2_clnt.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/rand.h>
116 #include <openssl/buffer.h>
117 #include <openssl/objects.h>
118 #include <openssl/evp.h>
119 #include "cryptlib.h"
120
121 static SSL_METHOD *ssl2_get_client_method(int ver);
122 static int get_server_finished(SSL *s);
123 static int get_server_verify(SSL *s);
124 static int get_server_hello(SSL *s);
125 static int client_hello(SSL *s); 
126 static int client_master_key(SSL *s);
127 static int client_finished(SSL *s);
128 static int client_certificate(SSL *s);
129 static int ssl_rsa_public_encrypt(SESS_CERT *sc, int len, unsigned char *from,
130         unsigned char *to,int padding);
131 #define BREAK   break
132
133 static SSL_METHOD *ssl2_get_client_method(int ver)
134         {
135         if (ver == SSL2_VERSION)
136                 return(SSLv2_client_method());
137         else
138                 return(NULL);
139         }
140
141 SSL_METHOD *SSLv2_client_method(void)
142         {
143         static int init=1;
144         static SSL_METHOD SSLv2_client_data;
145
146         if (init)
147                 {
148                 memcpy((char *)&SSLv2_client_data,(char *)sslv2_base_method(),
149                         sizeof(SSL_METHOD));
150                 SSLv2_client_data.ssl_connect=ssl2_connect;
151                 SSLv2_client_data.get_ssl_method=ssl2_get_client_method;
152                 init=0;
153                 }
154         return(&SSLv2_client_data);
155         }
156
157 int ssl2_connect(SSL *s)
158         {
159         unsigned long l=time(NULL);
160         BUF_MEM *buf=NULL;
161         int ret= -1;
162         void (*cb)(const SSL *ssl,int type,int val)=NULL;
163         int new_state,state;
164
165         RAND_add(&l,sizeof(l),0);
166         ERR_clear_error();
167         clear_sys_error();
168
169         if (s->info_callback != NULL)
170                 cb=s->info_callback;
171         else if (s->ctx->info_callback != NULL)
172                 cb=s->ctx->info_callback;
173
174         /* init things to blank */
175         s->in_handshake++;
176         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
177
178         for (;;)
179                 {
180                 state=s->state;
181
182                 switch (s->state)
183                         {
184                 case SSL_ST_BEFORE:
185                 case SSL_ST_CONNECT:
186                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
187                 case SSL_ST_OK|SSL_ST_CONNECT:
188
189                         s->server=0;
190                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
191
192                         s->version=SSL2_VERSION;
193                         s->type=SSL_ST_CONNECT;
194
195                         buf=s->init_buf;
196                         if ((buf == NULL) && ((buf=BUF_MEM_new()) == NULL))
197                                 {
198                                 ret= -1;
199                                 goto end;
200                                 }
201                         if (!BUF_MEM_grow(buf,
202                                 SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
203                                 {
204                                 ret= -1;
205                                 goto end;
206                                 }
207                         s->init_buf=buf;
208                         s->init_num=0;
209                         s->state=SSL2_ST_SEND_CLIENT_HELLO_A;
210                         s->ctx->stats.sess_connect++;
211                         s->handshake_func=ssl2_connect;
212                         BREAK;
213
214                 case SSL2_ST_SEND_CLIENT_HELLO_A:
215                 case SSL2_ST_SEND_CLIENT_HELLO_B:
216                         s->shutdown=0;
217                         ret=client_hello(s);
218                         if (ret <= 0) goto end;
219                         s->init_num=0;
220                         s->state=SSL2_ST_GET_SERVER_HELLO_A;
221                         BREAK;
222                 
223                 case SSL2_ST_GET_SERVER_HELLO_A:
224                 case SSL2_ST_GET_SERVER_HELLO_B:
225                         ret=get_server_hello(s);
226                         if (ret <= 0) goto end;
227                         s->init_num=0;
228                         if (!s->hit) /* new session */
229                                 {
230                                 s->state=SSL2_ST_SEND_CLIENT_MASTER_KEY_A;
231                                 BREAK; 
232                                 }
233                         else
234                                 {
235                                 s->state=SSL2_ST_CLIENT_START_ENCRYPTION;
236                                 break;
237                                 }
238         
239                 case SSL2_ST_SEND_CLIENT_MASTER_KEY_A:
240                 case SSL2_ST_SEND_CLIENT_MASTER_KEY_B:
241                         ret=client_master_key(s);
242                         if (ret <= 0) goto end;
243                         s->init_num=0;
244                         s->state=SSL2_ST_CLIENT_START_ENCRYPTION;
245                         break;
246
247                 case SSL2_ST_CLIENT_START_ENCRYPTION:
248                         /* Ok, we now have all the stuff needed to
249                          * start encrypting, so lets fire it up :-) */
250                         if (!ssl2_enc_init(s,1))
251                                 {
252                                 ret= -1;
253                                 goto end;
254                                 }
255                         s->s2->clear_text=0;
256                         s->state=SSL2_ST_SEND_CLIENT_FINISHED_A;
257                         break;
258
259                 case SSL2_ST_SEND_CLIENT_FINISHED_A:
260                 case SSL2_ST_SEND_CLIENT_FINISHED_B:
261                         ret=client_finished(s);
262                         if (ret <= 0) goto end;
263                         s->init_num=0;
264                         s->state=SSL2_ST_GET_SERVER_VERIFY_A;
265                         break;
266
267                 case SSL2_ST_GET_SERVER_VERIFY_A:
268                 case SSL2_ST_GET_SERVER_VERIFY_B:
269                         ret=get_server_verify(s);
270                         if (ret <= 0) goto end;
271                         s->init_num=0;
272                         s->state=SSL2_ST_GET_SERVER_FINISHED_A;
273                         break;
274
275                 case SSL2_ST_GET_SERVER_FINISHED_A:
276                 case SSL2_ST_GET_SERVER_FINISHED_B:
277                         ret=get_server_finished(s);
278                         if (ret <= 0) goto end;
279                         break;
280
281                 case SSL2_ST_SEND_CLIENT_CERTIFICATE_A:
282                 case SSL2_ST_SEND_CLIENT_CERTIFICATE_B:
283                 case SSL2_ST_SEND_CLIENT_CERTIFICATE_C:
284                 case SSL2_ST_SEND_CLIENT_CERTIFICATE_D:
285                 case SSL2_ST_X509_GET_CLIENT_CERTIFICATE:
286                         ret=client_certificate(s);
287                         if (ret <= 0) goto end;
288                         s->init_num=0;
289                         s->state=SSL2_ST_GET_SERVER_FINISHED_A;
290                         break;
291
292                 case SSL_ST_OK:
293                         if (s->init_buf != NULL)
294                                 {
295                                 BUF_MEM_free(s->init_buf);
296                                 s->init_buf=NULL;
297                                 }
298                         s->init_num=0;
299                 /*      ERR_clear_error();*/
300
301                         /* If we want to cache session-ids in the client
302                          * and we successfully add the session-id to the
303                          * cache, and there is a callback, then pass it out.
304                          * 26/11/96 - eay - only add if not a re-used session.
305                          */
306
307                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
308                         if (s->hit) s->ctx->stats.sess_hit++;
309
310                         ret=1;
311                         /* s->server=0; */
312                         s->ctx->stats.sess_connect_good++;
313
314                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
315
316                         goto end;
317                         /* break; */
318                 default:
319                         SSLerr(SSL_F_SSL2_CONNECT,SSL_R_UNKNOWN_STATE);
320                         return(-1);
321                         /* break; */
322                         }
323
324                 if ((cb != NULL) && (s->state != state))
325                         {
326                         new_state=s->state;
327                         s->state=state;
328                         cb(s,SSL_CB_CONNECT_LOOP,1);
329                         s->state=new_state;
330                         }
331                 }
332 end:
333         s->in_handshake--;
334         if (cb != NULL) 
335                 cb(s,SSL_CB_CONNECT_EXIT,ret);
336         return(ret);
337         }
338
339 static int get_server_hello(SSL *s)
340         {
341         unsigned char *buf;
342         unsigned char *p;
343         int i,j;
344         unsigned long len;
345         STACK_OF(SSL_CIPHER) *sk=NULL,*cl, *prio, *allow;
346
347         buf=(unsigned char *)s->init_buf->data;
348         p=buf;
349         if (s->state == SSL2_ST_GET_SERVER_HELLO_A)
350                 {
351                 i=ssl2_read(s,(char *)&(buf[s->init_num]),11-s->init_num);
352                 if (i < (11-s->init_num)) 
353                         return(ssl2_part_read(s,SSL_F_GET_SERVER_HELLO,i));
354                 s->init_num = 11;
355
356                 if (*(p++) != SSL2_MT_SERVER_HELLO)
357                         {
358                         if (p[-1] != SSL2_MT_ERROR)
359                                 {
360                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
361                                 SSLerr(SSL_F_GET_SERVER_HELLO,
362                                         SSL_R_READ_WRONG_PACKET_TYPE);
363                                 }
364                         else
365                                 SSLerr(SSL_F_GET_SERVER_HELLO,
366                                         SSL_R_PEER_ERROR);
367                         return(-1);
368                         }
369 #ifdef __APPLE_CC__
370                 /* The Rhapsody 5.5 (a.k.a. MacOS X) compiler bug
371                  * workaround. <appro@fy.chalmers.se> */
372                 s->hit=(i=*(p++))?1:0;
373 #else
374                 s->hit=(*(p++))?1:0;
375 #endif
376                 s->s2->tmp.cert_type= *(p++);
377                 n2s(p,i);
378                 if (i < s->version) s->version=i;
379                 n2s(p,i); s->s2->tmp.cert_length=i;
380                 n2s(p,i); s->s2->tmp.csl=i;
381                 n2s(p,i); s->s2->tmp.conn_id_length=i;
382                 s->state=SSL2_ST_GET_SERVER_HELLO_B;
383                 }
384
385         /* SSL2_ST_GET_SERVER_HELLO_B */
386         len = 11 + (unsigned long)s->s2->tmp.cert_length + (unsigned long)s->s2->tmp.csl + (unsigned long)s->s2->tmp.conn_id_length;
387         if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)
388                 {
389                 SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_MESSAGE_TOO_LONG);
390                 return -1;
391                 }
392         j = (int)len - s->init_num;
393         i = ssl2_read(s,(char *)&(buf[s->init_num]),j);
394         if (i != j) return(ssl2_part_read(s,SSL_F_GET_SERVER_HELLO,i));
395         if (s->msg_callback)
396                 s->msg_callback(0, s->version, 0, buf, (size_t)len, s, s->msg_callback_arg); /* SERVER-HELLO */
397
398         /* things are looking good */
399
400         p = buf + 11;
401         if (s->hit)
402                 {
403                 if (s->s2->tmp.cert_length != 0) 
404                         {
405                         SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_REUSE_CERT_LENGTH_NOT_ZERO);
406                         return(-1);
407                         }
408                 if (s->s2->tmp.cert_type != 0)
409                         {
410                         if (!(s->options &
411                                 SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG))
412                                 {
413                                 SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_REUSE_CERT_TYPE_NOT_ZERO);
414                                 return(-1);
415                                 }
416                         }
417                 if (s->s2->tmp.csl != 0)
418                         {
419                         SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_REUSE_CIPHER_LIST_NOT_ZERO);
420                         return(-1);
421                         }
422                 }
423         else
424                 {
425 #ifdef undef
426                 /* very bad */
427                 memset(s->session->session_id,0,
428                         SSL_MAX_SSL_SESSION_ID_LENGTH_IN_BYTES);
429                 s->session->session_id_length=0;
430                 */
431 #endif
432
433                 /* we need to do this in case we were trying to reuse a 
434                  * client session but others are already reusing it.
435                  * If this was a new 'blank' session ID, the session-id
436                  * length will still be 0 */
437                 if (s->session->session_id_length > 0)
438                         {
439                         if (!ssl_get_new_session(s,0))
440                                 {
441                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
442                                 return(-1);
443                                 }
444                         }
445
446                 if (ssl2_set_certificate(s,s->s2->tmp.cert_type,
447                         s->s2->tmp.cert_length,p) <= 0)
448                         {
449                         ssl2_return_error(s,SSL2_PE_BAD_CERTIFICATE);
450                         return(-1);
451                         }
452                 p+=s->s2->tmp.cert_length;
453
454                 if (s->s2->tmp.csl == 0)
455                         {
456                         ssl2_return_error(s,SSL2_PE_NO_CIPHER);
457                         SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_NO_CIPHER_LIST);
458                         return(-1);
459                         }
460
461                 /* We have just received a list of ciphers back from the
462                  * server.  We need to get the ones that match, then select
463                  * the one we want the most :-). */
464
465                 /* load the ciphers */
466                 sk=ssl_bytes_to_cipher_list(s,p,s->s2->tmp.csl,
467                                             &s->session->ciphers);
468                 p+=s->s2->tmp.csl;
469                 if (sk == NULL)
470                         {
471                         ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
472                         SSLerr(SSL_F_GET_SERVER_HELLO,ERR_R_MALLOC_FAILURE);
473                         return(-1);
474                         }
475
476                 sk_SSL_CIPHER_set_cmp_func(sk,ssl_cipher_ptr_id_cmp);
477
478                 /* get the array of ciphers we will accept */
479                 cl=SSL_get_ciphers(s);
480                 sk_SSL_CIPHER_set_cmp_func(cl,ssl_cipher_ptr_id_cmp);
481
482                 /*
483                  * If server preference flag set, choose the first
484                  * (highest priority) cipher the server sends, otherwise
485                  * client preference has priority.
486                  */
487                 if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE)
488                     {
489                     prio = sk;
490                     allow = cl;
491                     }
492                 else
493                     {
494                     prio = cl;
495                     allow = sk;
496                     }
497                 /* In theory we could have ciphers sent back that we
498                  * don't want to use but that does not matter since we
499                  * will check against the list we originally sent and
500                  * for performance reasons we should not bother to match
501                  * the two lists up just to check. */
502                 for (i=0; i<sk_SSL_CIPHER_num(prio); i++)
503                         {
504                         if (sk_SSL_CIPHER_find(allow,
505                                              sk_SSL_CIPHER_value(prio,i)) >= 0)
506                                 break;
507                         }
508
509                 if (i >= sk_SSL_CIPHER_num(prio))
510                         {
511                         ssl2_return_error(s,SSL2_PE_NO_CIPHER);
512                         SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_NO_CIPHER_MATCH);
513                         return(-1);
514                         }
515                 s->session->cipher=sk_SSL_CIPHER_value(prio,i);
516
517
518                 if (s->session->peer != NULL) /* can't happen*/
519                         {
520                         ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
521                         SSLerr(SSL_F_GET_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
522                         return(-1);
523                         }
524
525                 s->session->peer = s->session->sess_cert->peer_key->x509;
526                 /* peer_key->x509 has been set by ssl2_set_certificate. */
527                 CRYPTO_add(&s->session->peer->references, 1, CRYPTO_LOCK_X509);
528                 }
529
530         if (s->session->peer != s->session->sess_cert->peer_key->x509)
531                 /* can't happen */
532                 {
533                 ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);
534                 SSLerr(SSL_F_GET_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
535                 return(-1);
536                 }
537                 
538         s->s2->conn_id_length=s->s2->tmp.conn_id_length;
539         die(s->s2->conn_id_length <= sizeof s->s2->conn_id);
540         memcpy(s->s2->conn_id,p,s->s2->tmp.conn_id_length);
541         return(1);
542         }
543
544 static int client_hello(SSL *s)
545         {
546         unsigned char *buf;
547         unsigned char *p,*d;
548 /*      CIPHER **cipher;*/
549         int i,n,j;
550
551         buf=(unsigned char *)s->init_buf->data;
552         if (s->state == SSL2_ST_SEND_CLIENT_HELLO_A)
553                 {
554                 if ((s->session == NULL) ||
555                         (s->session->ssl_version != s->version))
556                         {
557                         if (!ssl_get_new_session(s,0))
558                                 {
559                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
560                                 return(-1);
561                                 }
562                         }
563                 /* else use the pre-loaded session */
564
565                 p=buf;                                  /* header */
566                 d=p+9;                                  /* data section */
567                 *(p++)=SSL2_MT_CLIENT_HELLO;            /* type */
568                 s2n(SSL2_VERSION,p);                    /* version */
569                 n=j=0;
570
571                 n=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),d);
572                 d+=n;
573
574                 if (n == 0)
575                         {
576                         SSLerr(SSL_F_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
577                         return(-1);
578                         }
579
580                 s2n(n,p);                       /* cipher spec num bytes */
581
582                 if ((s->session->session_id_length > 0) &&
583                         (s->session->session_id_length <=
584                         SSL2_MAX_SSL_SESSION_ID_LENGTH))
585                         {
586                         i=s->session->session_id_length;
587                         s2n(i,p);               /* session id length */
588                         memcpy(d,s->session->session_id,(unsigned int)i);
589                         d+=i;
590                         }
591                 else
592                         {
593                         s2n(0,p);
594                         }
595
596                 s->s2->challenge_length=SSL2_CHALLENGE_LENGTH;
597                 s2n(SSL2_CHALLENGE_LENGTH,p);           /* challenge length */
598                 /*challenge id data*/
599                 RAND_pseudo_bytes(s->s2->challenge,SSL2_CHALLENGE_LENGTH);
600                 memcpy(d,s->s2->challenge,SSL2_CHALLENGE_LENGTH);
601                 d+=SSL2_CHALLENGE_LENGTH;
602
603                 s->state=SSL2_ST_SEND_CLIENT_HELLO_B;
604                 s->init_num=d-buf;
605                 s->init_off=0;
606                 }
607         /* SSL2_ST_SEND_CLIENT_HELLO_B */
608         return(ssl2_do_write(s));
609         }
610
611 static int client_master_key(SSL *s)
612         {
613         unsigned char *buf;
614         unsigned char *p,*d;
615         int clear,enc,karg,i;
616         SSL_SESSION *sess;
617         const EVP_CIPHER *c;
618         const EVP_MD *md;
619
620         buf=(unsigned char *)s->init_buf->data;
621         if (s->state == SSL2_ST_SEND_CLIENT_MASTER_KEY_A)
622                 {
623
624                 if (!ssl_cipher_get_evp(s->session,&c,&md,NULL))
625                         {
626                         ssl2_return_error(s,SSL2_PE_NO_CIPHER);
627                         SSLerr(SSL_F_CLIENT_MASTER_KEY,SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS);
628                         return(-1);
629                         }
630                 sess=s->session;
631                 p=buf;
632                 d=p+10;
633                 *(p++)=SSL2_MT_CLIENT_MASTER_KEY;/* type */
634
635                 i=ssl_put_cipher_by_char(s,sess->cipher,p);
636                 p+=i;
637
638                 /* make key_arg data */
639                 i=EVP_CIPHER_iv_length(c);
640                 sess->key_arg_length=i;
641                 die(i <= SSL_MAX_KEY_ARG_LENGTH);
642                 if (i > 0) RAND_pseudo_bytes(sess->key_arg,i);
643
644                 /* make a master key */
645                 i=EVP_CIPHER_key_length(c);
646                 sess->master_key_length=i;
647                 if (i > 0)
648                         {
649                         die(i <= sizeof sess->master_key);
650                         if (RAND_bytes(sess->master_key,i) <= 0)
651                                 {
652                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
653                                 return(-1);
654                                 }
655                         }
656
657                 if (sess->cipher->algorithm2 & SSL2_CF_8_BYTE_ENC)
658                         enc=8;
659                 else if (SSL_C_IS_EXPORT(sess->cipher))
660                         enc=5;
661                 else
662                         enc=i;
663
664                 if (i < enc)
665                         {
666                         ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
667                         SSLerr(SSL_F_CLIENT_MASTER_KEY,SSL_R_CIPHER_TABLE_SRC_ERROR);
668                         return(-1);
669                         }
670                 clear=i-enc;
671                 s2n(clear,p);
672                 memcpy(d,sess->master_key,(unsigned int)clear);
673                 d+=clear;
674
675                 enc=ssl_rsa_public_encrypt(sess->sess_cert,enc,
676                         &(sess->master_key[clear]),d,
677                         (s->s2->ssl2_rollback)?RSA_SSLV23_PADDING:RSA_PKCS1_PADDING);
678                 if (enc <= 0)
679                         {
680                         ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
681                         SSLerr(SSL_F_CLIENT_MASTER_KEY,SSL_R_PUBLIC_KEY_ENCRYPT_ERROR);
682                         return(-1);
683                         }
684 #ifdef PKCS1_CHECK
685                 if (s->options & SSL_OP_PKCS1_CHECK_1) d[1]++;
686                 if (s->options & SSL_OP_PKCS1_CHECK_2)
687                         sess->master_key[clear]++;
688 #endif
689                 s2n(enc,p);
690                 d+=enc;
691                 karg=sess->key_arg_length;      
692                 s2n(karg,p); /* key arg size */
693                 die(karg <= sizeof sess->key_arg);
694                 memcpy(d,sess->key_arg,(unsigned int)karg);
695                 d+=karg;
696
697                 s->state=SSL2_ST_SEND_CLIENT_MASTER_KEY_B;
698                 s->init_num=d-buf;
699                 s->init_off=0;
700                 }
701
702         /* SSL2_ST_SEND_CLIENT_MASTER_KEY_B */
703         return(ssl2_do_write(s));
704         }
705
706 static int client_finished(SSL *s)
707         {
708         unsigned char *p;
709
710         if (s->state == SSL2_ST_SEND_CLIENT_FINISHED_A)
711                 {
712                 p=(unsigned char *)s->init_buf->data;
713                 *(p++)=SSL2_MT_CLIENT_FINISHED;
714                 die(s->s2->conn_id_length <= sizeof s->s2->conn_id);
715                 memcpy(p,s->s2->conn_id,(unsigned int)s->s2->conn_id_length);
716
717                 s->state=SSL2_ST_SEND_CLIENT_FINISHED_B;
718                 s->init_num=s->s2->conn_id_length+1;
719                 s->init_off=0;
720                 }
721         return(ssl2_do_write(s));
722         }
723
724 /* read the data and then respond */
725 static int client_certificate(SSL *s)
726         {
727         unsigned char *buf;
728         unsigned char *p,*d;
729         int i;
730         unsigned int n;
731         int cert_ch_len;
732         unsigned char *cert_ch;
733
734         buf=(unsigned char *)s->init_buf->data;
735
736         /* We have a cert associated with the SSL, so attach it to
737          * the session if it does not have one */
738
739         if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_A)
740                 {
741                 i=ssl2_read(s,(char *)&(buf[s->init_num]),
742                         SSL2_MAX_CERT_CHALLENGE_LENGTH+1-s->init_num);
743                 if (i<(SSL2_MIN_CERT_CHALLENGE_LENGTH+1-s->init_num))
744                         return(ssl2_part_read(s,SSL_F_CLIENT_CERTIFICATE,i));
745                 s->init_num += i;
746                 if (s->msg_callback)
747                         s->msg_callback(0, s->version, 0, buf, (size_t)s->init_num, s, s->msg_callback_arg); /* REQUEST-CERTIFICATE */
748
749                 /* type=buf[0]; */
750                 /* type eq x509 */
751                 if (buf[1] != SSL2_AT_MD5_WITH_RSA_ENCRYPTION)
752                         {
753                         ssl2_return_error(s,SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE);
754                         SSLerr(SSL_F_CLIENT_CERTIFICATE,SSL_R_BAD_AUTHENTICATION_TYPE);
755                         return(-1);
756                         }
757
758                 if ((s->cert == NULL) ||
759                         (s->cert->key->x509 == NULL) ||
760                         (s->cert->key->privatekey == NULL))
761                         {
762                         s->state=SSL2_ST_X509_GET_CLIENT_CERTIFICATE;
763                         }
764                 else
765                         s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_C;
766                 }
767
768         cert_ch = buf + 2;
769         cert_ch_len = s->init_num - 2;
770
771         if (s->state == SSL2_ST_X509_GET_CLIENT_CERTIFICATE)
772                 {
773                 X509 *x509=NULL;
774                 EVP_PKEY *pkey=NULL;
775
776                 /* If we get an error we need to
777                  * ssl->rwstate=SSL_X509_LOOKUP;
778                  * return(error);
779                  * We should then be retried when things are ok and we
780                  * can get a cert or not */
781
782                 i=0;
783                 if (s->ctx->client_cert_cb != NULL)
784                         {
785                         i=s->ctx->client_cert_cb(s,&(x509),&(pkey));
786                         }
787
788                 if (i < 0)
789                         {
790                         s->rwstate=SSL_X509_LOOKUP;
791                         return(-1);
792                         }
793                 s->rwstate=SSL_NOTHING;
794
795                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
796                         {
797                         s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_C;
798                         if (    !SSL_use_certificate(s,x509) || 
799                                 !SSL_use_PrivateKey(s,pkey))
800                                 {
801                                 i=0;
802                                 }
803                         X509_free(x509);
804                         EVP_PKEY_free(pkey);
805                         }
806                 else if (i == 1)
807                         {
808                         if (x509 != NULL) X509_free(x509);
809                         if (pkey != NULL) EVP_PKEY_free(pkey);
810                         SSLerr(SSL_F_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
811                         i=0;
812                         }
813
814                 if (i == 0)
815                         {
816                         /* We have no client certificate to respond with
817                          * so send the correct error message back */
818                         s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_B;
819                         p=buf;
820                         *(p++)=SSL2_MT_ERROR;
821                         s2n(SSL2_PE_NO_CERTIFICATE,p);
822                         s->init_off=0;
823                         s->init_num=3;
824                         /* Write is done at the end */
825                         }
826                 }
827
828         if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_B)
829                 {
830                 return(ssl2_do_write(s));
831                 }
832
833         if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_C)
834                 {
835                 EVP_MD_CTX ctx;
836
837                 /* ok, now we calculate the checksum
838                  * do it first so we can reuse buf :-) */
839                 p=buf;
840                 EVP_MD_CTX_init(&ctx);
841                 EVP_SignInit_ex(&ctx,s->ctx->rsa_md5, NULL);
842                 EVP_SignUpdate(&ctx,s->s2->key_material,
843                         (unsigned int)s->s2->key_material_length);
844                 EVP_SignUpdate(&ctx,cert_ch,(unsigned int)cert_ch_len);
845                 n=i2d_X509(s->session->sess_cert->peer_key->x509,&p);
846                 EVP_SignUpdate(&ctx,buf,(unsigned int)n);
847
848                 p=buf;
849                 d=p+6;
850                 *(p++)=SSL2_MT_CLIENT_CERTIFICATE;
851                 *(p++)=SSL2_CT_X509_CERTIFICATE;
852                 n=i2d_X509(s->cert->key->x509,&d);
853                 s2n(n,p);
854
855                 if (!EVP_SignFinal(&ctx,d,&n,s->cert->key->privatekey))
856                         {
857                         /* this is not good.  If things have failed it
858                          * means there so something wrong with the key.
859                          * We will continue with a 0 length signature
860                          */
861                         }
862                 EVP_MD_CTX_cleanup(&ctx);
863                 s2n(n,p);
864                 d+=n;
865
866                 s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_D;
867                 s->init_num=d-buf;
868                 s->init_off=0;
869                 }
870         /* if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_D) */
871         return(ssl2_do_write(s));
872         }
873
874 static int get_server_verify(SSL *s)
875         {
876         unsigned char *p;
877         int i, n, len;
878
879         p=(unsigned char *)s->init_buf->data;
880         if (s->state == SSL2_ST_GET_SERVER_VERIFY_A)
881                 {
882                 i=ssl2_read(s,(char *)&(p[s->init_num]),1-s->init_num);
883                 if (i < (1-s->init_num)) 
884                         return(ssl2_part_read(s,SSL_F_GET_SERVER_VERIFY,i));
885                 s->init_num += i;
886
887                 s->state= SSL2_ST_GET_SERVER_VERIFY_B;
888                 if (*p != SSL2_MT_SERVER_VERIFY)
889                         {
890                         if (p[0] != SSL2_MT_ERROR)
891                                 {
892                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
893                                 SSLerr(SSL_F_GET_SERVER_VERIFY,
894                                         SSL_R_READ_WRONG_PACKET_TYPE);
895                                 }
896                         else
897                                 {
898                                 SSLerr(SSL_F_GET_SERVER_VERIFY,SSL_R_PEER_ERROR);
899                                 /* try to read the error message */
900                                 i=ssl2_read(s,(char *)&(p[s->init_num]),3-s->init_num);
901                                 return ssl2_part_read(s,SSL_F_GET_SERVER_VERIFY,i);
902                                 }
903                         return(-1);
904                         }
905                 }
906         
907         p=(unsigned char *)s->init_buf->data;
908         len = 1 + s->s2->challenge_length;
909         n =  len - s->init_num;
910         i = ssl2_read(s,(char *)&(p[s->init_num]),n);
911         if (i < n)
912                 return(ssl2_part_read(s,SSL_F_GET_SERVER_VERIFY,i));
913         if (s->msg_callback)
914                 s->msg_callback(0, s->version, 0, p, len, s, s->msg_callback_arg); /* SERVER-VERIFY */
915         p += 1;
916
917         if (memcmp(p,s->s2->challenge,(unsigned int)s->s2->challenge_length) != 0)
918                 {
919                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
920                 SSLerr(SSL_F_GET_SERVER_VERIFY,SSL_R_CHALLENGE_IS_DIFFERENT);
921                 return(-1);
922                 }
923         return(1);
924         }
925
926 static int get_server_finished(SSL *s)
927         {
928         unsigned char *buf;
929         unsigned char *p;
930         int i, n, len;
931
932         buf=(unsigned char *)s->init_buf->data;
933         p=buf;
934         if (s->state == SSL2_ST_GET_SERVER_FINISHED_A)
935                 {
936                 i=ssl2_read(s,(char *)&(buf[s->init_num]),1-s->init_num);
937                 if (i < (1-s->init_num))
938                         return(ssl2_part_read(s,SSL_F_GET_SERVER_FINISHED,i));
939                 s->init_num += i;
940
941                 if (*p == SSL2_MT_REQUEST_CERTIFICATE)
942                         {
943                         s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_A;
944                         return(1);
945                         }
946                 else if (*p != SSL2_MT_SERVER_FINISHED)
947                         {
948                         if (p[0] != SSL2_MT_ERROR)
949                                 {
950                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
951                                 SSLerr(SSL_F_GET_SERVER_FINISHED,SSL_R_READ_WRONG_PACKET_TYPE);
952                                 }
953                         else
954                                 {
955                                 SSLerr(SSL_F_GET_SERVER_FINISHED,SSL_R_PEER_ERROR);
956                                 /* try to read the error message */
957                                 i=ssl2_read(s,(char *)&(p[s->init_num]),3-s->init_num);
958                                 return ssl2_part_read(s,SSL_F_GET_SERVER_VERIFY,i);
959                                 }
960                         return(-1);
961                         }
962                 s->state=SSL2_ST_GET_SERVER_FINISHED_B;
963                 }
964
965         len = 1 + SSL2_SSL_SESSION_ID_LENGTH;
966         n = len - s->init_num;
967         i = ssl2_read(s,(char *)&(buf[s->init_num]), n);
968         if (i < n) /* XXX could be shorter than SSL2_SSL_SESSION_ID_LENGTH, that's the maximum */
969                 return(ssl2_part_read(s,SSL_F_GET_SERVER_FINISHED,i));
970         s->init_num += i;
971         if (s->msg_callback)
972                 s->msg_callback(0, s->version, 0, buf, (size_t)s->init_num, s, s->msg_callback_arg); /* SERVER-FINISHED */
973
974         if (!s->hit) /* new session */
975                 {
976                 /* new session-id */
977                 /* Make sure we were not trying to re-use an old SSL_SESSION
978                  * or bad things can happen */
979                 /* ZZZZZZZZZZZZZ */
980                 s->session->session_id_length=SSL2_SSL_SESSION_ID_LENGTH;
981                 memcpy(s->session->session_id,p,SSL2_SSL_SESSION_ID_LENGTH);
982                 }
983         else
984                 {
985                 if (!(s->options & SSL_OP_MICROSOFT_SESS_ID_BUG))
986                         {
987                         die(s->session->session_id_length
988                             <= sizeof s->session->session_id);
989                         if (memcmp(buf,s->session->session_id,
990                                 (unsigned int)s->session->session_id_length) != 0)
991                                 {
992                                 ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR);
993                                 SSLerr(SSL_F_GET_SERVER_FINISHED,SSL_R_SSL_SESSION_ID_IS_DIFFERENT);
994                                 return(-1);
995                                 }
996                         }
997                 }
998         s->state = SSL_ST_OK;
999         return(1);
1000         }
1001
1002 /* loads in the certificate from the server */
1003 int ssl2_set_certificate(SSL *s, int type, int len, unsigned char *data)
1004         {
1005         STACK_OF(X509) *sk=NULL;
1006         EVP_PKEY *pkey=NULL;
1007         SESS_CERT *sc=NULL;
1008         int i;
1009         X509 *x509=NULL;
1010         int ret=0;
1011         
1012         x509=d2i_X509(NULL,&data,(long)len);
1013         if (x509 == NULL)
1014                 {
1015                 SSLerr(SSL_F_SSL2_SET_CERTIFICATE,ERR_R_X509_LIB);
1016                 goto err;
1017                 }
1018
1019         if ((sk=sk_X509_new_null()) == NULL || !sk_X509_push(sk,x509))
1020                 {
1021                 SSLerr(SSL_F_SSL2_SET_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1022                 goto err;
1023                 }
1024
1025         i=ssl_verify_cert_chain(s,sk);
1026                 
1027         if ((s->verify_mode != SSL_VERIFY_NONE) && (!i))
1028                 {
1029                 SSLerr(SSL_F_SSL2_SET_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
1030                 goto err;
1031                 }
1032         ERR_clear_error(); /* but we keep s->verify_result */
1033         s->session->verify_result = s->verify_result;
1034
1035         /* server's cert for this session */
1036         sc=ssl_sess_cert_new();
1037         if (sc == NULL)
1038                 {
1039                 ret= -1;
1040                 goto err;
1041                 }
1042         if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
1043         s->session->sess_cert=sc;
1044
1045         sc->peer_pkeys[SSL_PKEY_RSA_ENC].x509=x509;
1046         sc->peer_key= &(sc->peer_pkeys[SSL_PKEY_RSA_ENC]);
1047
1048         pkey=X509_get_pubkey(x509);
1049         x509=NULL;
1050         if (pkey == NULL)
1051                 {
1052                 SSLerr(SSL_F_SSL2_SET_CERTIFICATE,SSL_R_UNABLE_TO_EXTRACT_PUBLIC_KEY);
1053                 goto err;
1054                 }
1055         if (pkey->type != EVP_PKEY_RSA)
1056                 {
1057                 SSLerr(SSL_F_SSL2_SET_CERTIFICATE,SSL_R_PUBLIC_KEY_NOT_RSA);
1058                 goto err;
1059                 }
1060
1061         if (!ssl_set_peer_cert_type(sc,SSL2_CT_X509_CERTIFICATE))
1062                 goto err;
1063         ret=1;
1064 err:
1065         sk_X509_free(sk);
1066         X509_free(x509);
1067         EVP_PKEY_free(pkey);
1068         return(ret);
1069         }
1070
1071 static int ssl_rsa_public_encrypt(SESS_CERT *sc, int len, unsigned char *from,
1072              unsigned char *to, int padding)
1073         {
1074         EVP_PKEY *pkey=NULL;
1075         int i= -1;
1076
1077         if ((sc == NULL) || (sc->peer_key->x509 == NULL) ||
1078                 ((pkey=X509_get_pubkey(sc->peer_key->x509)) == NULL))
1079                 {
1080                 SSLerr(SSL_F_SSL_RSA_PUBLIC_ENCRYPT,SSL_R_NO_PUBLICKEY);
1081                 return(-1);
1082                 }
1083         if (pkey->type != EVP_PKEY_RSA)
1084                 {
1085                 SSLerr(SSL_F_SSL_RSA_PUBLIC_ENCRYPT,SSL_R_PUBLIC_KEY_IS_NOT_RSA);
1086                 goto end;
1087                 }
1088
1089         /* we have the public key */
1090         i=RSA_public_encrypt(len,from,to,pkey->pkey.rsa,padding);
1091         if (i < 0)
1092                 SSLerr(SSL_F_SSL_RSA_PUBLIC_ENCRYPT,ERR_R_RSA_LIB);
1093 end:
1094         EVP_PKEY_free(pkey);
1095         return(i);
1096         }
1097 #else /* !OPENSSL_NO_SSL2 */
1098
1099 # if PEDANTIC
1100 static void *dummy=&dummy;
1101 # endif
1102
1103 #endif