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