RAND_seed
[openssl.git] / ssl / ssltest.c
1 /* ssl/ssltest.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 #include <assert.h>
60 #include <errno.h>
61 #include <limits.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65
66 #include "openssl/e_os.h"
67
68 #include <openssl/bio.h>
69 #include <openssl/crypto.h>
70 #include <openssl/x509.h>
71 #include <openssl/ssl.h>
72 #include <openssl/err.h>
73 #include <openssl/rand.h>
74 #ifdef WINDOWS
75 #include "../crypto/bio/bss_file.c"
76 #endif
77
78 #if defined(NO_RSA) && !defined(NO_SSL2)
79 #define NO_SSL2
80 #endif
81
82 #ifdef VMS
83 #  define TEST_SERVER_CERT "SYS$DISK:[-.APPS]SERVER.PEM"
84 #  define TEST_CLIENT_CERT "SYS$DISK:[-.APPS]CLIENT.PEM"
85 #else
86 #  define TEST_SERVER_CERT "../apps/server.pem"
87 #  define TEST_CLIENT_CERT "../apps/client.pem"
88 #endif
89
90 static int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx);
91 #ifndef NO_RSA
92 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export,int keylength);
93 #endif
94 #ifndef NO_DH
95 static DH *get_dh512(void);
96 #endif
97 static BIO *bio_err=NULL;
98 static BIO *bio_stdout=NULL;
99
100 static char *cipher=NULL;
101 static int verbose=0;
102 static int debug=0;
103 #if 0
104 /* Not used yet. */
105 #ifdef FIONBIO
106 static int s_nbio=0;
107 #endif
108 #endif
109
110 static const char rnd_seed[] = "string to make the random number generator think it has entropy";
111
112 int doit_biopair(SSL *s_ssl,SSL *c_ssl,long bytes);
113 int doit(SSL *s_ssl,SSL *c_ssl,long bytes);
114 static void sv_usage(void)
115         {
116         fprintf(stderr,"usage: ssltest [args ...]\n");
117         fprintf(stderr,"\n");
118         fprintf(stderr," -server_auth  - check server certificate\n");
119         fprintf(stderr," -client_auth  - do client authentication\n");
120         fprintf(stderr," -v            - more output\n");
121         fprintf(stderr," -d            - debug output\n");
122         fprintf(stderr," -reuse        - use session-id reuse\n");
123         fprintf(stderr," -num <val>    - number of connections to perform\n");
124         fprintf(stderr," -bytes <val>  - number of bytes to swap between client/server\n");
125 #if !defined NO_DH && !defined NO_DSA
126         fprintf(stderr," -dhe1024      - generate 1024 bit key for DHE\n");
127 #endif
128 #if !defined NO_DH
129         fprintf(stderr," -no_dhe       - disable DHE\n");
130 #endif
131 #ifndef NO_SSL2
132         fprintf(stderr," -ssl2         - use SSLv2\n");
133 #endif
134 #ifndef NO_SSL3
135         fprintf(stderr," -ssl3         - use SSLv3\n");
136 #endif
137 #ifndef NO_TLS1
138         fprintf(stderr," -tls1         - use TLSv1\n");
139 #endif
140         fprintf(stderr," -CApath arg   - PEM format directory of CA's\n");
141         fprintf(stderr," -CAfile arg   - PEM format file of CA's\n");
142         fprintf(stderr," -cert arg     - Certificate file\n");
143         fprintf(stderr," -s_cert arg   - Just the server certificate file\n");
144         fprintf(stderr," -c_cert arg   - Just the client certificate file\n");
145         fprintf(stderr," -cipher arg   - The cipher list\n");
146         fprintf(stderr," -bio_pair     - Use BIO pairs\n");
147         fprintf(stderr," -f            - Test even cases that can't work\n");
148         }
149
150 int main(int argc, char *argv[])
151         {
152         char *CApath=NULL,*CAfile=NULL;
153         int badop=0;
154         int bio_pair=0;
155         int force=0;
156         int tls1=0,ssl2=0,ssl3=0,ret=1;
157         int client_auth=0;
158         int server_auth=0,i;
159         char *server_cert=TEST_SERVER_CERT;
160         char *client_cert=TEST_CLIENT_CERT;
161         SSL_CTX *s_ctx=NULL;
162         SSL_CTX *c_ctx=NULL;
163         SSL_METHOD *meth=NULL;
164         SSL *c_ssl,*s_ssl;
165         int number=1,reuse=0;
166         long bytes=1L;
167         SSL_CIPHER *ciph;
168         int dhe1024 = 0, no_dhe = 0;
169 #ifndef NO_DH
170         DH *dh;
171 #endif
172         verbose = 0;
173         debug = 0;
174         cipher = 0;
175         
176         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
177
178         RAND_seed(rnd_seed, sizeof rnd_seed);
179
180         bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
181         bio_stdout=BIO_new_fp(stdout,BIO_NOCLOSE);
182
183         argc--;
184         argv++;
185
186         while (argc >= 1)
187                 {
188                 if      (strcmp(*argv,"-server_auth") == 0)
189                         server_auth=1;
190                 else if (strcmp(*argv,"-client_auth") == 0)
191                         client_auth=1;
192                 else if (strcmp(*argv,"-v") == 0)
193                         verbose=1;
194                 else if (strcmp(*argv,"-d") == 0)
195                         debug=1;
196                 else if (strcmp(*argv,"-reuse") == 0)
197                         reuse=1;
198                 else if (strcmp(*argv,"-dhe1024") == 0)
199                         dhe1024=1;
200                 else if (strcmp(*argv,"-no_dhe") == 0)
201                         no_dhe=1;
202                 else if (strcmp(*argv,"-ssl2") == 0)
203                         ssl2=1;
204                 else if (strcmp(*argv,"-tls1") == 0)
205                         tls1=1;
206                 else if (strcmp(*argv,"-ssl3") == 0)
207                         ssl3=1;
208                 else if (strncmp(*argv,"-num",4) == 0)
209                         {
210                         if (--argc < 1) goto bad;
211                         number= atoi(*(++argv));
212                         if (number == 0) number=1;
213                         }
214                 else if (strcmp(*argv,"-bytes") == 0)
215                         {
216                         if (--argc < 1) goto bad;
217                         bytes= atol(*(++argv));
218                         if (bytes == 0L) bytes=1L;
219                         i=strlen(argv[0]);
220                         if (argv[0][i-1] == 'k') bytes*=1024L;
221                         if (argv[0][i-1] == 'm') bytes*=1024L*1024L;
222                         }
223                 else if (strcmp(*argv,"-cert") == 0)
224                         {
225                         if (--argc < 1) goto bad;
226                         server_cert= *(++argv);
227                         }
228                 else if (strcmp(*argv,"-s_cert") == 0)
229                         {
230                         if (--argc < 1) goto bad;
231                         server_cert= *(++argv);
232                         }
233                 else if (strcmp(*argv,"-c_cert") == 0)
234                         {
235                         if (--argc < 1) goto bad;
236                         client_cert= *(++argv);
237                         }
238                 else if (strcmp(*argv,"-cipher") == 0)
239                         {
240                         if (--argc < 1) goto bad;
241                         cipher= *(++argv);
242                         }
243                 else if (strcmp(*argv,"-CApath") == 0)
244                         {
245                         if (--argc < 1) goto bad;
246                         CApath= *(++argv);
247                         }
248                 else if (strcmp(*argv,"-CAfile") == 0)
249                         {
250                         if (--argc < 1) goto bad;
251                         CAfile= *(++argv);
252                         }
253                 else if (strcmp(*argv,"-bio_pair") == 0)
254                         {
255                         bio_pair = 1;
256                         }
257                 else if (strcmp(*argv,"-f") == 0)
258                         {
259                         force = 1;
260                         }
261                 else
262                         {
263                         fprintf(stderr,"unknown option %s\n",*argv);
264                         badop=1;
265                         break;
266                         }
267                 argc--;
268                 argv++;
269                 }
270         if (badop)
271                 {
272 bad:
273                 sv_usage();
274                 goto end;
275                 }
276
277         if (!ssl2 && !ssl3 && !tls1 && number > 1 && !reuse && !force)
278                 {
279                 fprintf(stderr, "This case cannot work.  Use -f switch to perform "
280                         "the test anyway\n"
281                         "(and -d to see what happens, "
282                         "and -bio_pair to really make it happen :-)\n"
283                         "or add one of -ssl2, -ssl3, -tls1, -reuse to "
284                         "avoid protocol mismatch.\n");
285                 exit(1);
286                 }
287
288 /*      if (cipher == NULL) cipher=getenv("SSL_CIPHER"); */
289
290         SSL_library_init();
291         SSL_load_error_strings();
292
293 #if !defined(NO_SSL2) && !defined(NO_SSL3)
294         if (ssl2)
295                 meth=SSLv2_method();
296         else 
297         if (tls1)
298                 meth=TLSv1_method();
299         else
300         if (ssl3)
301                 meth=SSLv3_method();
302         else
303                 meth=SSLv23_method();
304 #else
305 #ifdef NO_SSL2
306         meth=SSLv3_method();
307 #else
308         meth=SSLv2_method();
309 #endif
310 #endif
311
312         c_ctx=SSL_CTX_new(meth);
313         s_ctx=SSL_CTX_new(meth);
314         if ((c_ctx == NULL) || (s_ctx == NULL))
315                 {
316                 ERR_print_errors(bio_err);
317                 goto end;
318                 }
319
320         if (cipher != NULL)
321                 {
322                 SSL_CTX_set_cipher_list(c_ctx,cipher);
323                 SSL_CTX_set_cipher_list(s_ctx,cipher);
324                 }
325
326 #ifndef NO_DH
327         if (!no_dhe)
328                 {
329 # ifndef NO_DSA
330                 if (dhe1024) 
331                         {
332                         DSA *dsa;
333                         unsigned char seed[20];
334                         
335                         if (verbose)
336                                 {
337                                 fprintf(stdout, "Creating 1024 bit DHE parameters ...");
338                                 fflush(stdout);
339                                 }
340                         
341                         memcpy(seed, "Random String no. 12", 20);
342                         dsa = DSA_generate_parameters(1024, seed, 20, NULL, NULL, 0, NULL);
343                         dh = DSA_dup_DH(dsa);   
344                         DSA_free(dsa);
345                         /* important: SSL_OP_SINGLE_DH_USE to avoid small subgroup attacks */
346                         SSL_CTX_set_options(s_ctx, SSL_OP_SINGLE_DH_USE);
347                         
348                         if (verbose)
349                                 fprintf(stdout, " done\n");
350                         }
351                 else
352 # endif
353                         dh=get_dh512();
354                 SSL_CTX_set_tmp_dh(s_ctx,dh);
355                 DH_free(dh);
356                 }
357 #endif
358
359 #ifndef NO_RSA
360         SSL_CTX_set_tmp_rsa_callback(s_ctx,tmp_rsa_cb);
361 #endif
362
363         if (!SSL_CTX_use_certificate_file(s_ctx,server_cert,SSL_FILETYPE_PEM))
364                 {
365                 ERR_print_errors(bio_err);
366                 }
367         else if (!SSL_CTX_use_PrivateKey_file(s_ctx,server_cert,
368                 SSL_FILETYPE_PEM))
369                 {
370                 ERR_print_errors(bio_err);
371                 goto end;
372                 }
373
374         if (client_auth)
375                 {
376                 SSL_CTX_use_certificate_file(c_ctx,client_cert,
377                         SSL_FILETYPE_PEM);
378                 SSL_CTX_use_PrivateKey_file(c_ctx,client_cert,
379                         SSL_FILETYPE_PEM);
380                 }
381
382         if (    (!SSL_CTX_load_verify_locations(s_ctx,CAfile,CApath)) ||
383                 (!SSL_CTX_set_default_verify_paths(s_ctx)) ||
384                 (!SSL_CTX_load_verify_locations(c_ctx,CAfile,CApath)) ||
385                 (!SSL_CTX_set_default_verify_paths(c_ctx)))
386                 {
387                 /* fprintf(stderr,"SSL_load_verify_locations\n"); */
388                 ERR_print_errors(bio_err);
389                 /* goto end; */
390                 }
391
392         if (client_auth)
393                 {
394                 fprintf(stderr,"client authentication\n");
395                 SSL_CTX_set_verify(s_ctx,
396                         SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
397                         verify_callback);
398                 }
399         if (server_auth)
400                 {
401                 fprintf(stderr,"server authentication\n");
402                 SSL_CTX_set_verify(c_ctx,SSL_VERIFY_PEER,
403                         verify_callback);
404                 }
405         
406         {
407                 int session_id_context = 0;
408                 SSL_CTX_set_session_id_context(s_ctx, (void *)&session_id_context, sizeof session_id_context);
409         }
410
411         c_ssl=SSL_new(c_ctx);
412         s_ssl=SSL_new(s_ctx);
413
414         for (i=0; i<number; i++)
415                 {
416                 if (!reuse) SSL_set_session(c_ssl,NULL);
417                 if (bio_pair)
418                         ret=doit_biopair(s_ssl,c_ssl,bytes);
419                 else
420                         ret=doit(s_ssl,c_ssl,bytes);
421                 }
422
423         if (!verbose)
424                 {
425                 ciph=SSL_get_current_cipher(c_ssl);
426                 fprintf(stdout,"Protocol %s, cipher %s, %s\n",
427                         SSL_get_version(c_ssl),
428                         SSL_CIPHER_get_version(ciph),
429                         SSL_CIPHER_get_name(ciph));
430                 }
431         if ((number > 1) || (bytes > 1L))
432                 printf("%d handshakes of %ld bytes done\n",number,bytes);
433
434         SSL_free(s_ssl);
435         SSL_free(c_ssl);
436
437 end:
438         if (s_ctx != NULL) SSL_CTX_free(s_ctx);
439         if (c_ctx != NULL) SSL_CTX_free(c_ctx);
440
441         if (bio_stdout != NULL) BIO_free(bio_stdout);
442
443         ERR_free_strings();
444         ERR_remove_state(0);
445         EVP_cleanup();
446         CRYPTO_mem_leaks(bio_err);
447         if (bio_err != NULL) BIO_free(bio_err);
448         EXIT(ret);
449         }
450
451 int doit_biopair(SSL *s_ssl, SSL *c_ssl, long count)
452         {
453         long cw_num = count, cr_num = count, sw_num = count, sr_num = count;
454         BIO *s_ssl_bio = NULL, *c_ssl_bio = NULL;
455         BIO *server = NULL, *server_io = NULL, *client = NULL, *client_io = NULL;
456         SSL_CIPHER *ciph;
457         int ret = 1;
458         
459         size_t bufsiz = 256; /* small buffer for testing */
460
461         if (!BIO_new_bio_pair(&server, bufsiz, &server_io, bufsiz))
462                 goto err;
463         if (!BIO_new_bio_pair(&client, bufsiz, &client_io, bufsiz))
464                 goto err;
465         
466         s_ssl_bio = BIO_new(BIO_f_ssl());
467         if (!s_ssl_bio)
468                 goto err;
469
470         c_ssl_bio = BIO_new(BIO_f_ssl());
471         if (!c_ssl_bio)
472                 goto err;
473
474         SSL_set_connect_state(c_ssl);
475         SSL_set_bio(c_ssl, client, client);
476         (void)BIO_set_ssl(c_ssl_bio, c_ssl, BIO_NOCLOSE);
477
478         SSL_set_accept_state(s_ssl);
479         SSL_set_bio(s_ssl, server, server);
480         (void)BIO_set_ssl(s_ssl_bio, s_ssl, BIO_NOCLOSE);
481
482         do
483                 {
484                 /* c_ssl_bio:          SSL filter BIO
485                  *
486                  * client:             pseudo-I/O for SSL library
487                  *
488                  * client_io:          client's SSL communication; usually to be
489                  *                     relayed over some I/O facility, but in this
490                  *                     test program, we're the server, too:
491                  *
492                  * server_io:          server's SSL communication
493                  *
494                  * server:             pseudo-I/O for SSL library
495                  *
496                  * s_ssl_bio:          SSL filter BIO
497                  *
498                  * The client and the server each employ a "BIO pair":
499                  * client + client_io, server + server_io.
500                  * BIO pairs are symmetric.  A BIO pair behaves similar
501                  * to a non-blocking socketpair (but both endpoints must
502                  * be handled by the same thread).
503                  * [Here we could connect client and server to the ends
504                  * of a single BIO pair, but then this code would be less
505                  * suitable as an example for BIO pairs in general.]
506                  *
507                  * Useful functions for querying the state of BIO pair endpoints:
508                  *
509                  * BIO_ctrl_pending(bio)              number of bytes we can read now
510                  * BIO_ctrl_get_read_request(bio)     number of bytes needed to fulfil
511                  *                                      other side's read attempt
512                  * BIO_ctrl_get_write_gurantee(bio)   number of bytes we can write now
513                  *
514                  * ..._read_request is never more than ..._write_guarantee;
515                  * it depends on the application which one you should use.
516                  */
517
518                 /* We have non-blocking behaviour throughout this test program, but
519                  * can be sure that there is *some* progress in each iteration; so
520                  * we don't have to worry about ..._SHOULD_READ or ..._SHOULD_WRITE
521                  * -- we just try everything in each iteration
522                  */
523
524                         {
525                         /* CLIENT */
526                 
527                         MS_STATIC char cbuf[1024*8];
528                         int i, r;
529
530                         if (debug)
531                                 if (SSL_in_init(c_ssl))
532                                         printf("client waiting in SSL_connect - %s\n",
533                                                 SSL_state_string_long(c_ssl));
534
535                         if (cw_num > 0)
536                                 {
537                                 /* Write to server. */
538                                 
539                                 if (cw_num > (long)sizeof cbuf)
540                                         i = sizeof cbuf;
541                                 else
542                                         i = (int)cw_num;
543                                 r = BIO_write(c_ssl_bio, cbuf, i);
544                                 if (r < 0)
545                                         {
546                                         if (!BIO_should_retry(c_ssl_bio))
547                                                 {
548                                                 fprintf(stderr,"ERROR in CLIENT\n");
549                                                 goto err;
550                                                 }
551                                         /* BIO_should_retry(...) can just be ignored here.
552                                          * The library expects us to call BIO_write with
553                                          * the same arguments again, and that's what we will
554                                          * do in the next iteration. */
555                                         }
556                                 else if (r == 0)
557                                         {
558                                         fprintf(stderr,"SSL CLIENT STARTUP FAILED\n");
559                                         goto err;
560                                         }
561                                 else
562                                         {
563                                         if (debug)
564                                                 printf("client wrote %d\n", r);
565                                         cw_num -= r;                            
566                                         }
567                                 }
568
569                         if (cr_num > 0)
570                                 {
571                                 /* Read from server. */
572
573                                 r = BIO_read(c_ssl_bio, cbuf, sizeof(cbuf));
574                                 if (r < 0)
575                                         {
576                                         if (!BIO_should_retry(c_ssl_bio))
577                                                 {
578                                                 fprintf(stderr,"ERROR in CLIENT\n");
579                                                 goto err;
580                                                 }
581                                         /* Again, "BIO_should_retry" can be ignored. */
582                                         }
583                                 else if (r == 0)
584                                         {
585                                         fprintf(stderr,"SSL CLIENT STARTUP FAILED\n");
586                                         goto err;
587                                         }
588                                 else
589                                         {
590                                         if (debug)
591                                                 printf("client read %d\n", r);
592                                         cr_num -= r;
593                                         }
594                                 }
595                         }
596
597                         {
598                         /* SERVER */
599                 
600                         MS_STATIC char sbuf[1024*8];
601                         int i, r;
602
603                         if (debug)
604                                 if (SSL_in_init(s_ssl))
605                                         printf("server waiting in SSL_accept - %s\n",
606                                                 SSL_state_string_long(s_ssl));
607
608                         if (sw_num > 0)
609                                 {
610                                 /* Write to client. */
611                                 
612                                 if (sw_num > (long)sizeof sbuf)
613                                         i = sizeof sbuf;
614                                 else
615                                         i = (int)sw_num;
616                                 r = BIO_write(s_ssl_bio, sbuf, i);
617                                 if (r < 0)
618                                         {
619                                         if (!BIO_should_retry(s_ssl_bio))
620                                                 {
621                                                 fprintf(stderr,"ERROR in SERVER\n");
622                                                 goto err;
623                                                 }
624                                         /* Ignore "BIO_should_retry". */
625                                         }
626                                 else if (r == 0)
627                                         {
628                                         fprintf(stderr,"SSL SERVER STARTUP FAILED\n");
629                                         goto err;
630                                         }
631                                 else
632                                         {
633                                         if (debug)
634                                                 printf("server wrote %d\n", r);
635                                         sw_num -= r;                            
636                                         }
637                                 }
638
639                         if (sr_num > 0)
640                                 {
641                                 /* Read from client. */
642
643                                 r = BIO_read(s_ssl_bio, sbuf, sizeof(sbuf));
644                                 if (r < 0)
645                                         {
646                                         if (!BIO_should_retry(s_ssl_bio))
647                                                 {
648                                                 fprintf(stderr,"ERROR in SERVER\n");
649                                                 goto err;
650                                                 }
651                                         /* blah, blah */
652                                         }
653                                 else if (r == 0)
654                                         {
655                                         fprintf(stderr,"SSL SERVER STARTUP FAILED\n");
656                                         goto err;
657                                         }
658                                 else
659                                         {
660                                         if (debug)
661                                                 printf("server read %d\n", r);
662                                         sr_num -= r;
663                                         }
664                                 }
665                         }
666                         
667                         {
668                         /* "I/O" BETWEEN CLIENT AND SERVER. */
669
670                         size_t r1, r2;
671                         BIO *io1 = server_io, *io2 = client_io;
672                         /* we use the non-copying interface for io1
673                          * and the standard BIO_write/BIO_read interface for io2
674                          */
675                         
676                         static int prev_progress = 1;
677                         int progress = 0;
678                         
679                         /* io1 to io2 */
680                         do
681                                 {
682                                 size_t num;
683                                 int r;
684
685                                 r1 = BIO_ctrl_pending(io1);
686                                 r2 = BIO_ctrl_get_write_guarantee(io2);
687
688                                 num = r1;
689                                 if (r2 < num)
690                                         num = r2;
691                                 if (num)
692                                         {
693                                         char *dataptr;
694
695                                         if (INT_MAX < num) /* yeah, right */
696                                                 num = INT_MAX;
697                                         
698                                         r = BIO_nread(io1, &dataptr, (int)num);
699                                         assert(r > 0);
700                                         assert(r <= (int)num);
701                                         /* possibly r < num (non-contiguous data) */
702                                         num = r;
703                                         r = BIO_write(io2, dataptr, (int)num);
704                                         if (r != (int)num) /* can't happen */
705                                                 {
706                                                 fprintf(stderr, "ERROR: BIO_write could not write "
707                                                         "BIO_ctrl_get_write_guarantee() bytes");
708                                                 goto err;
709                                                 }
710                                         progress = 1;
711
712                                         if (debug)
713                                                 printf((io1 == client_io) ?
714                                                         "C->S relaying: %d bytes\n" :
715                                                         "S->C relaying: %d bytes\n",
716                                                         (int)num);
717                                         }
718                                 }
719                         while (r1 && r2);
720
721                         /* io2 to io1 */
722                         {
723                                 size_t num;
724                                 int r;
725
726                                 r1 = BIO_ctrl_pending(io2);
727                                 r2 = BIO_ctrl_get_read_request(io1);
728                                 /* here we could use ..._get_write_guarantee instead of
729                                  * ..._get_read_request, but by using the latter
730                                  * we test restartability of the SSL implementation
731                                  * more thoroughly */
732                                 num = r1;
733                                 if (r2 < num)
734                                         num = r2;
735                                 if (num)
736                                         {
737                                         char *dataptr;
738                                         
739                                         if (INT_MAX < num)
740                                                 num = INT_MAX;
741
742                                         if (num > 1)
743                                                 --num; /* test restartability even more thoroughly */
744                                         
745                                         r = BIO_nwrite(io1, &dataptr, (int)num);
746                                         assert(r > 0);
747                                         assert(r <= (int)num);
748                                         num = r;
749                                         r = BIO_read(io2, dataptr, (int)num);
750                                         if (r != (int)num) /* can't happen */
751                                                 {
752                                                 fprintf(stderr, "ERROR: BIO_read could not read "
753                                                         "BIO_ctrl_pending() bytes");
754                                                 goto err;
755                                                 }
756                                         progress = 1;
757                                         
758                                         if (debug)
759                                                 printf((io2 == client_io) ?
760                                                         "C->S relaying: %d bytes\n" :
761                                                         "S->C relaying: %d bytes\n",
762                                                         (int)num);
763                                         }
764                         } /* no loop, BIO_ctrl_get_read_request now returns 0 anyway */
765
766                         if (!progress && !prev_progress)
767                                 if (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0)
768                                         {
769                                         fprintf(stderr, "ERROR: got stuck\n");
770                                         if (strcmp("SSLv2", SSL_get_version(c_ssl)) == 0)
771                                                 {
772                                                 fprintf(stderr, "This can happen for SSL2 because "
773                                                         "CLIENT-FINISHED and SERVER-VERIFY are written \n"
774                                                         "concurrently ...");
775                                                 if (strncmp("2SCF", SSL_state_string(c_ssl), 4) == 0
776                                                         && strncmp("2SSV", SSL_state_string(s_ssl), 4) == 0)
777                                                         {
778                                                         fprintf(stderr, " ok.\n");
779                                                         goto end;
780                                                         }
781                                                 }
782                                         fprintf(stderr, " ERROR.\n");
783                                         goto err;
784                                         }
785                         prev_progress = progress;
786                         }
787                 }
788         while (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0);
789
790         ciph = SSL_get_current_cipher(c_ssl);
791         if (verbose)
792                 fprintf(stdout,"DONE via BIO pair, protocol %s, cipher %s, %s\n",
793                         SSL_get_version(c_ssl),
794                         SSL_CIPHER_get_version(ciph),
795                         SSL_CIPHER_get_name(ciph));
796  end:
797         ret = 0;
798
799  err:
800         ERR_print_errors(bio_err);
801         
802         if (server)
803                 BIO_free(server);
804         if (server_io)
805                 BIO_free(server_io);
806         if (client)
807                 BIO_free(client);
808         if (client_io)
809                 BIO_free(client_io);
810         if (s_ssl_bio)
811                 BIO_free(s_ssl_bio);
812         if (c_ssl_bio)
813                 BIO_free(c_ssl_bio);
814
815         return ret;
816         }
817
818
819 #define W_READ  1
820 #define W_WRITE 2
821 #define C_DONE  1
822 #define S_DONE  2
823
824 int doit(SSL *s_ssl, SSL *c_ssl, long count)
825         {
826         MS_STATIC char cbuf[1024*8],sbuf[1024*8];
827         long cw_num=count,cr_num=count;
828         long sw_num=count,sr_num=count;
829         int ret=1;
830         BIO *c_to_s=NULL;
831         BIO *s_to_c=NULL;
832         BIO *c_bio=NULL;
833         BIO *s_bio=NULL;
834         int c_r,c_w,s_r,s_w;
835         int c_want,s_want;
836         int i,j;
837         int done=0;
838         int c_write,s_write;
839         int do_server=0,do_client=0;
840         SSL_CIPHER *ciph;
841
842         c_to_s=BIO_new(BIO_s_mem());
843         s_to_c=BIO_new(BIO_s_mem());
844         if ((s_to_c == NULL) || (c_to_s == NULL))
845                 {
846                 ERR_print_errors(bio_err);
847                 goto err;
848                 }
849
850         c_bio=BIO_new(BIO_f_ssl());
851         s_bio=BIO_new(BIO_f_ssl());
852         if ((c_bio == NULL) || (s_bio == NULL))
853                 {
854                 ERR_print_errors(bio_err);
855                 goto err;
856                 }
857
858         SSL_set_connect_state(c_ssl);
859         SSL_set_bio(c_ssl,s_to_c,c_to_s);
860         BIO_set_ssl(c_bio,c_ssl,BIO_NOCLOSE);
861
862         SSL_set_accept_state(s_ssl);
863         SSL_set_bio(s_ssl,c_to_s,s_to_c);
864         BIO_set_ssl(s_bio,s_ssl,BIO_NOCLOSE);
865
866         c_r=0; s_r=1;
867         c_w=1; s_w=0;
868         c_want=W_WRITE;
869         s_want=0;
870         c_write=1,s_write=0;
871
872         /* We can always do writes */
873         for (;;)
874                 {
875                 do_server=0;
876                 do_client=0;
877
878                 i=(int)BIO_pending(s_bio);
879                 if ((i && s_r) || s_w) do_server=1;
880
881                 i=(int)BIO_pending(c_bio);
882                 if ((i && c_r) || c_w) do_client=1;
883
884                 if (do_server && debug)
885                         {
886                         if (SSL_in_init(s_ssl))
887                                 printf("server waiting in SSL_accept - %s\n",
888                                         SSL_state_string_long(s_ssl));
889 /*                      else if (s_write)
890                                 printf("server:SSL_write()\n");
891                         else
892                                 printf("server:SSL_read()\n"); */
893                         }
894
895                 if (do_client && debug)
896                         {
897                         if (SSL_in_init(c_ssl))
898                                 printf("client waiting in SSL_connect - %s\n",
899                                         SSL_state_string_long(c_ssl));
900 /*                      else if (c_write)
901                                 printf("client:SSL_write()\n");
902                         else
903                                 printf("client:SSL_read()\n"); */
904                         }
905
906                 if (!do_client && !do_server)
907                         {
908                         fprintf(stdout,"ERROR IN STARTUP\n");
909                         ERR_print_errors(bio_err);
910                         break;
911                         }
912                 if (do_client && !(done & C_DONE))
913                         {
914                         if (c_write)
915                                 {
916                                 j=(cw_num > (long)sizeof(cbuf))
917                                         ?sizeof(cbuf):(int)cw_num;
918                                 i=BIO_write(c_bio,cbuf,j);
919                                 if (i < 0)
920                                         {
921                                         c_r=0;
922                                         c_w=0;
923                                         if (BIO_should_retry(c_bio))
924                                                 {
925                                                 if (BIO_should_read(c_bio))
926                                                         c_r=1;
927                                                 if (BIO_should_write(c_bio))
928                                                         c_w=1;
929                                                 }
930                                         else
931                                                 {
932                                                 fprintf(stderr,"ERROR in CLIENT\n");
933                                                 ERR_print_errors(bio_err);
934                                                 goto err;
935                                                 }
936                                         }
937                                 else if (i == 0)
938                                         {
939                                         fprintf(stderr,"SSL CLIENT STARTUP FAILED\n");
940                                         goto err;
941                                         }
942                                 else
943                                         {
944                                         if (debug)
945                                                 printf("client wrote %d\n",i);
946                                         /* ok */
947                                         s_r=1;
948                                         c_write=0;
949                                         cw_num-=i;
950                                         }
951                                 }
952                         else
953                                 {
954                                 i=BIO_read(c_bio,cbuf,sizeof(cbuf));
955                                 if (i < 0)
956                                         {
957                                         c_r=0;
958                                         c_w=0;
959                                         if (BIO_should_retry(c_bio))
960                                                 {
961                                                 if (BIO_should_read(c_bio))
962                                                         c_r=1;
963                                                 if (BIO_should_write(c_bio))
964                                                         c_w=1;
965                                                 }
966                                         else
967                                                 {
968                                                 fprintf(stderr,"ERROR in CLIENT\n");
969                                                 ERR_print_errors(bio_err);
970                                                 goto err;
971                                                 }
972                                         }
973                                 else if (i == 0)
974                                         {
975                                         fprintf(stderr,"SSL CLIENT STARTUP FAILED\n");
976                                         goto err;
977                                         }
978                                 else
979                                         {
980                                         if (debug)
981                                                 printf("client read %d\n",i);
982                                         cr_num-=i;
983                                         if (sw_num > 0)
984                                                 {
985                                                 s_write=1;
986                                                 s_w=1;
987                                                 }
988                                         if (cr_num <= 0)
989                                                 {
990                                                 s_write=1;
991                                                 s_w=1;
992                                                 done=S_DONE|C_DONE;
993                                                 }
994                                         }
995                                 }
996                         }
997
998                 if (do_server && !(done & S_DONE))
999                         {
1000                         if (!s_write)
1001                                 {
1002                                 i=BIO_read(s_bio,sbuf,sizeof(cbuf));
1003                                 if (i < 0)
1004                                         {
1005                                         s_r=0;
1006                                         s_w=0;
1007                                         if (BIO_should_retry(s_bio))
1008                                                 {
1009                                                 if (BIO_should_read(s_bio))
1010                                                         s_r=1;
1011                                                 if (BIO_should_write(s_bio))
1012                                                         s_w=1;
1013                                                 }
1014                                         else
1015                                                 {
1016                                                 fprintf(stderr,"ERROR in SERVER\n");
1017                                                 ERR_print_errors(bio_err);
1018                                                 goto err;
1019                                                 }
1020                                         }
1021                                 else if (i == 0)
1022                                         {
1023                                         ERR_print_errors(bio_err);
1024                                         fprintf(stderr,"SSL SERVER STARTUP FAILED in SSL_read\n");
1025                                         goto err;
1026                                         }
1027                                 else
1028                                         {
1029                                         if (debug)
1030                                                 printf("server read %d\n",i);
1031                                         sr_num-=i;
1032                                         if (cw_num > 0)
1033                                                 {
1034                                                 c_write=1;
1035                                                 c_w=1;
1036                                                 }
1037                                         if (sr_num <= 0)
1038                                                 {
1039                                                 s_write=1;
1040                                                 s_w=1;
1041                                                 c_write=0;
1042                                                 }
1043                                         }
1044                                 }
1045                         else
1046                                 {
1047                                 j=(sw_num > (long)sizeof(sbuf))?
1048                                         sizeof(sbuf):(int)sw_num;
1049                                 i=BIO_write(s_bio,sbuf,j);
1050                                 if (i < 0)
1051                                         {
1052                                         s_r=0;
1053                                         s_w=0;
1054                                         if (BIO_should_retry(s_bio))
1055                                                 {
1056                                                 if (BIO_should_read(s_bio))
1057                                                         s_r=1;
1058                                                 if (BIO_should_write(s_bio))
1059                                                         s_w=1;
1060                                                 }
1061                                         else
1062                                                 {
1063                                                 fprintf(stderr,"ERROR in SERVER\n");
1064                                                 ERR_print_errors(bio_err);
1065                                                 goto err;
1066                                                 }
1067                                         }
1068                                 else if (i == 0)
1069                                         {
1070                                         ERR_print_errors(bio_err);
1071                                         fprintf(stderr,"SSL SERVER STARTUP FAILED in SSL_write\n");
1072                                         goto err;
1073                                         }
1074                                 else
1075                                         {
1076                                         if (debug)
1077                                                 printf("server wrote %d\n",i);
1078                                         sw_num-=i;
1079                                         s_write=0;
1080                                         c_r=1;
1081                                         if (sw_num <= 0)
1082                                                 done|=S_DONE;
1083                                         }
1084                                 }
1085                         }
1086
1087                 if ((done & S_DONE) && (done & C_DONE)) break;
1088                 }
1089
1090         ciph=SSL_get_current_cipher(c_ssl);
1091         if (verbose)
1092                 fprintf(stdout,"DONE, protocol %s, cipher %s, %s\n",
1093                         SSL_get_version(c_ssl),
1094                         SSL_CIPHER_get_version(ciph),
1095                         SSL_CIPHER_get_name(ciph));
1096         ret=0;
1097 err:
1098         /* We have to set the BIO's to NULL otherwise they will be
1099          * Free()ed twice.  Once when th s_ssl is SSL_free()ed and
1100          * again when c_ssl is SSL_free()ed.
1101          * This is a hack required because s_ssl and c_ssl are sharing the same
1102          * BIO structure and SSL_set_bio() and SSL_free() automatically
1103          * BIO_free non NULL entries.
1104          * You should not normally do this or be required to do this */
1105         if (s_ssl != NULL)
1106                 {
1107                 s_ssl->rbio=NULL;
1108                 s_ssl->wbio=NULL;
1109                 }
1110         if (c_ssl != NULL)
1111                 {
1112                 c_ssl->rbio=NULL;
1113                 c_ssl->wbio=NULL;
1114                 }
1115
1116         if (c_to_s != NULL) BIO_free(c_to_s);
1117         if (s_to_c != NULL) BIO_free(s_to_c);
1118         if (c_bio != NULL) BIO_free_all(c_bio);
1119         if (s_bio != NULL) BIO_free_all(s_bio);
1120         return(ret);
1121         }
1122
1123 static int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx)
1124         {
1125         char *s,buf[256];
1126
1127         s=X509_NAME_oneline(X509_get_subject_name(ctx->current_cert),buf,256);
1128         if (s != NULL)
1129                 {
1130                 if (ok)
1131                         fprintf(stderr,"depth=%d %s\n",ctx->error_depth,buf);
1132                 else
1133                         fprintf(stderr,"depth=%d error=%d %s\n",
1134                                 ctx->error_depth,ctx->error,buf);
1135                 }
1136
1137         if (ok == 0)
1138                 {
1139                 switch (ctx->error)
1140                         {
1141                 case X509_V_ERR_CERT_NOT_YET_VALID:
1142                 case X509_V_ERR_CERT_HAS_EXPIRED:
1143                 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1144                         ok=1;
1145                         }
1146                 }
1147
1148         return(ok);
1149         }
1150
1151 #ifndef NO_DH
1152 static unsigned char dh512_p[]={
1153         0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
1154         0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
1155         0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
1156         0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
1157         0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
1158         0x47,0x74,0xE8,0x33,
1159         };
1160 static unsigned char dh512_g[]={
1161         0x02,
1162         };
1163
1164 static DH *get_dh512(void)
1165         {
1166         DH *dh=NULL;
1167
1168         if ((dh=DH_new()) == NULL) return(NULL);
1169         dh->p=BN_bin2bn(dh512_p,sizeof(dh512_p),NULL);
1170         dh->g=BN_bin2bn(dh512_g,sizeof(dh512_g),NULL);
1171         if ((dh->p == NULL) || (dh->g == NULL))
1172                 return(NULL);
1173         return(dh);
1174         }
1175 #endif
1176
1177 #ifndef NO_RSA
1178 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength)
1179         {
1180         static RSA *rsa_tmp=NULL;
1181
1182         if (rsa_tmp == NULL)
1183                 {
1184                 BIO_printf(bio_err,"Generating temp (%d bit) RSA key...",keylength);
1185                 (void)BIO_flush(bio_err);
1186                 rsa_tmp=RSA_generate_key(keylength,RSA_F4,NULL,NULL);
1187                 BIO_printf(bio_err,"\n");
1188                 (void)BIO_flush(bio_err);
1189                 }
1190         return(rsa_tmp);
1191         }
1192 #endif