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