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