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