Fix error handling in ssltest
[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  * Copyright (c) 1998-2000 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  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  * ECC cipher suite support in OpenSSL originally developed by
114  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
115  */
116
117 /* Or gethostname won't be declared properly on Linux and GNU platforms. */
118 #define _BSD_SOURCE 1
119
120 #include <assert.h>
121 #include <errno.h>
122 #include <limits.h>
123 #include <stdio.h>
124 #include <stdlib.h>
125 #include <string.h>
126 #include <time.h>
127
128 #define USE_SOCKETS
129 #include "e_os.h"
130
131 /*
132  * Or isascii won't be declared properly on VMS (at least with DECompHP C).
133  */
134 #define _XOPEN_SOURCE 500
135 #include <ctype.h>
136
137 #include <openssl/bio.h>
138 #include <openssl/crypto.h>
139 #include <openssl/evp.h>
140 #include <openssl/x509.h>
141 #include <openssl/x509v3.h>
142 #include <openssl/ssl.h>
143 #ifndef OPENSSL_NO_ENGINE
144 # include <openssl/engine.h>
145 #endif
146 #include <openssl/err.h>
147 #include <openssl/rand.h>
148 #ifndef OPENSSL_NO_RSA
149 # include <openssl/rsa.h>
150 #endif
151 #ifndef OPENSSL_NO_DSA
152 # include <openssl/dsa.h>
153 #endif
154 #ifndef OPENSSL_NO_DH
155 # include <openssl/dh.h>
156 #endif
157 #include <openssl/bn.h>
158
159 /*
160  * Or gethostname won't be declared properly
161  * on Compaq platforms (at least with DEC C).
162  * Do not try to put it earlier, or IPv6 includes
163  * get screwed...
164  */
165 #define _XOPEN_SOURCE_EXTENDED  1
166
167 #ifdef OPENSSL_SYS_WINDOWS
168 # include <winsock.h>
169 #else
170 # include OPENSSL_UNISTD
171 #endif
172
173 #ifdef OPENSSL_SYS_VMS
174 # define TEST_SERVER_CERT "SYS$DISK:[-.APPS]SERVER.PEM"
175 # define TEST_CLIENT_CERT "SYS$DISK:[-.APPS]CLIENT.PEM"
176 #elif defined(OPENSSL_SYS_WINCE)
177 # define TEST_SERVER_CERT "\\OpenSSL\\server.pem"
178 # define TEST_CLIENT_CERT "\\OpenSSL\\client.pem"
179 #elif defined(OPENSSL_SYS_NETWARE)
180 # define TEST_SERVER_CERT "\\openssl\\apps\\server.pem"
181 # define TEST_CLIENT_CERT "\\openssl\\apps\\client.pem"
182 #else
183 # define TEST_SERVER_CERT "../apps/server.pem"
184 # define TEST_CLIENT_CERT "../apps/client.pem"
185 #endif
186
187 /*
188  * There is really no standard for this, so let's assign some tentative
189  * numbers.  In any case, these numbers are only for this test
190  */
191 #define COMP_RLE        255
192 #define COMP_ZLIB       1
193
194 static int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx);
195 #ifndef OPENSSL_NO_RSA
196 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength);
197 static void free_tmp_rsa(void);
198 #endif
199 static int MS_CALLBACK app_verify_callback(X509_STORE_CTX *ctx, void *arg);
200 #define APP_CALLBACK_STRING "Test Callback Argument"
201 struct app_verify_arg {
202     char *string;
203     int app_verify;
204     int allow_proxy_certs;
205     char *proxy_auth;
206     char *proxy_cond;
207 };
208
209 #ifndef OPENSSL_NO_DH
210 static DH *get_dh512(void);
211 static DH *get_dh1024(void);
212 static DH *get_dh1024dsa(void);
213 #endif
214
215 static BIO *bio_err = NULL;
216 static BIO *bio_stdout = NULL;
217
218 static char *cipher = NULL;
219 static int verbose = 0;
220 static int debug = 0;
221 #if 0
222 /* Not used yet. */
223 # ifdef FIONBIO
224 static int s_nbio = 0;
225 # endif
226 #endif
227
228 static const char rnd_seed[] =
229     "string to make the random number generator think it has entropy";
230
231 int doit_biopair(SSL *s_ssl, SSL *c_ssl, long bytes, clock_t *s_time,
232                  clock_t *c_time);
233 int doit(SSL *s_ssl, SSL *c_ssl, long bytes);
234 static int do_test_cipherlist(void);
235 static void sv_usage(void)
236 {
237     fprintf(stderr, "usage: ssltest [args ...]\n");
238     fprintf(stderr, "\n");
239 #ifdef OPENSSL_FIPS
240     fprintf(stderr, "-F             - run test in FIPS mode\n");
241 #endif
242     fprintf(stderr, " -server_auth  - check server certificate\n");
243     fprintf(stderr, " -client_auth  - do client authentication\n");
244     fprintf(stderr, " -proxy        - allow proxy certificates\n");
245     fprintf(stderr, " -proxy_auth <val> - set proxy policy rights\n");
246     fprintf(stderr,
247             " -proxy_cond <val> - experssion to test proxy policy rights\n");
248     fprintf(stderr, " -v            - more output\n");
249     fprintf(stderr, " -d            - debug output\n");
250     fprintf(stderr, " -reuse        - use session-id reuse\n");
251     fprintf(stderr, " -num <val>    - number of connections to perform\n");
252     fprintf(stderr,
253             " -bytes <val>  - number of bytes to swap between client/server\n");
254 #ifndef OPENSSL_NO_DH
255     fprintf(stderr,
256             " -dhe1024      - use 1024 bit key (safe prime) for DHE\n");
257     fprintf(stderr,
258             " -dhe1024dsa   - use 1024 bit key (with 160-bit subprime) for DHE\n");
259     fprintf(stderr, " -no_dhe       - disable DHE\n");
260 #endif
261 #ifndef OPENSSL_NO_ECDH
262     fprintf(stderr, " -no_ecdhe     - disable ECDHE\n");
263 #endif
264 #ifndef OPENSSL_NO_SSL2
265     fprintf(stderr, " -ssl2         - use SSLv2\n");
266 #endif
267 #ifndef OPENSSL_NO_SSL3
268     fprintf(stderr, " -ssl3         - use SSLv3\n");
269 #endif
270 #ifndef OPENSSL_NO_TLS1
271     fprintf(stderr, " -tls1         - use TLSv1\n");
272 #endif
273     fprintf(stderr, " -CApath arg   - PEM format directory of CA's\n");
274     fprintf(stderr, " -CAfile arg   - PEM format file of CA's\n");
275     fprintf(stderr, " -cert arg     - Server certificate file\n");
276     fprintf(stderr,
277             " -key arg      - Server key file (default: same as -cert)\n");
278     fprintf(stderr, " -c_cert arg   - Client certificate file\n");
279     fprintf(stderr,
280             " -c_key arg    - Client key file (default: same as -c_cert)\n");
281     fprintf(stderr, " -cipher arg   - The cipher list\n");
282     fprintf(stderr, " -bio_pair     - Use BIO pairs\n");
283     fprintf(stderr, " -f            - Test even cases that can't work\n");
284     fprintf(stderr,
285             " -time         - measure processor time used by client and server\n");
286     fprintf(stderr, " -zlib         - use zlib compression\n");
287     fprintf(stderr, " -rle          - use rle compression\n");
288 #ifndef OPENSSL_NO_ECDH
289     fprintf(stderr,
290             " -named_curve arg  - Elliptic curve name to use for ephemeral ECDH keys.\n"
291             "                 Use \"openssl ecparam -list_curves\" for all names\n"
292             "                 (default is sect163r2).\n");
293 #endif
294     fprintf(stderr,
295             " -test_cipherlist - verifies the order of the ssl cipher lists\n");
296 }
297
298 static void print_details(SSL *c_ssl, const char *prefix)
299 {
300     SSL_CIPHER *ciph;
301     X509 *cert;
302
303     ciph = SSL_get_current_cipher(c_ssl);
304     BIO_printf(bio_stdout, "%s%s, cipher %s %s",
305                prefix,
306                SSL_get_version(c_ssl),
307                SSL_CIPHER_get_version(ciph), SSL_CIPHER_get_name(ciph));
308     cert = SSL_get_peer_certificate(c_ssl);
309     if (cert != NULL) {
310         EVP_PKEY *pkey = X509_get_pubkey(cert);
311         if (pkey != NULL) {
312             if (0) ;
313 #ifndef OPENSSL_NO_RSA
314             else if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != NULL
315                      && pkey->pkey.rsa->n != NULL) {
316                 BIO_printf(bio_stdout, ", %d bit RSA",
317                            BN_num_bits(pkey->pkey.rsa->n));
318             }
319 #endif
320 #ifndef OPENSSL_NO_DSA
321             else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != NULL
322                      && pkey->pkey.dsa->p != NULL) {
323                 BIO_printf(bio_stdout, ", %d bit DSA",
324                            BN_num_bits(pkey->pkey.dsa->p));
325             }
326 #endif
327             EVP_PKEY_free(pkey);
328         }
329         X509_free(cert);
330     }
331     /*
332      * The SSL API does not allow us to look at temporary RSA/DH keys,
333      * otherwise we should print their lengths too
334      */
335     BIO_printf(bio_stdout, "\n");
336 }
337
338 static void lock_dbg_cb(int mode, int type, const char *file, int line)
339 {
340     static int modes[CRYPTO_NUM_LOCKS]; /* = {0, 0, ... } */
341     const char *errstr = NULL;
342     int rw;
343
344     rw = mode & (CRYPTO_READ | CRYPTO_WRITE);
345     if (!((rw == CRYPTO_READ) || (rw == CRYPTO_WRITE))) {
346         errstr = "invalid mode";
347         goto err;
348     }
349
350     if (type < 0 || type >= CRYPTO_NUM_LOCKS) {
351         errstr = "type out of bounds";
352         goto err;
353     }
354
355     if (mode & CRYPTO_LOCK) {
356         if (modes[type]) {
357             errstr = "already locked";
358             /*
359              * must not happen in a single-threaded program (would deadlock)
360              */
361             goto err;
362         }
363
364         modes[type] = rw;
365     } else if (mode & CRYPTO_UNLOCK) {
366         if (!modes[type]) {
367             errstr = "not locked";
368             goto err;
369         }
370
371         if (modes[type] != rw) {
372             errstr = (rw == CRYPTO_READ) ?
373                 "CRYPTO_r_unlock on write lock" :
374                 "CRYPTO_w_unlock on read lock";
375         }
376
377         modes[type] = 0;
378     } else {
379         errstr = "invalid mode";
380         goto err;
381     }
382
383  err:
384     if (errstr) {
385         /* we cannot use bio_err here */
386         fprintf(stderr,
387                 "openssl (lock_dbg_cb): %s (mode=%d, type=%d) at %s:%d\n",
388                 errstr, mode, type, file, line);
389     }
390 }
391
392 int main(int argc, char *argv[])
393 {
394     char *CApath = NULL, *CAfile = NULL;
395     int badop = 0;
396     int bio_pair = 0;
397     int force = 0;
398     int tls1 = 0, ssl2 = 0, ssl3 = 0, ret = 1;
399     int client_auth = 0;
400     int server_auth = 0, i;
401     struct app_verify_arg app_verify_arg =
402         { APP_CALLBACK_STRING, 0, 0, NULL, NULL };
403     char *server_cert = TEST_SERVER_CERT;
404     char *server_key = NULL;
405     char *client_cert = TEST_CLIENT_CERT;
406     char *client_key = NULL;
407 #ifndef OPENSSL_NO_ECDH
408     char *named_curve = NULL;
409 #endif
410     SSL_CTX *s_ctx = NULL;
411     SSL_CTX *c_ctx = NULL;
412     SSL_METHOD *meth = NULL;
413     SSL *c_ssl, *s_ssl;
414     int number = 1, reuse = 0;
415     long bytes = 256L;
416 #ifndef OPENSSL_NO_DH
417     DH *dh;
418     int dhe1024 = 1, dhe1024dsa = 0;
419 #endif
420 #ifndef OPENSSL_NO_ECDH
421     EC_KEY *ecdh = NULL;
422 #endif
423     int no_dhe = 0;
424     int no_ecdhe = 0;
425     int print_time = 0;
426     clock_t s_time = 0, c_time = 0;
427     int comp = 0;
428 #ifndef OPENSSL_NO_COMP
429     COMP_METHOD *cm = NULL;
430 #endif
431     STACK_OF(SSL_COMP) *ssl_comp_methods = NULL;
432     int test_cipherlist = 0;
433 #ifdef OPENSSL_FIPS
434     int fips_mode = 0;
435 #endif
436
437     verbose = 0;
438     debug = 0;
439     cipher = 0;
440
441     bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
442
443     CRYPTO_set_locking_callback(lock_dbg_cb);
444
445     /* enable memory leak checking unless explicitly disabled */
446     if (!((getenv("OPENSSL_DEBUG_MEMORY") != NULL)
447           && (0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off")))) {
448         CRYPTO_malloc_debug_init();
449         CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
450     } else {
451         /* OPENSSL_DEBUG_MEMORY=off */
452         CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
453     }
454     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
455
456     RAND_seed(rnd_seed, sizeof rnd_seed);
457
458     bio_stdout = BIO_new_fp(stdout, BIO_NOCLOSE);
459
460     argc--;
461     argv++;
462
463     while (argc >= 1) {
464         if (!strcmp(*argv, "-F")) {
465 #ifdef OPENSSL_FIPS
466             fips_mode = 1;
467 #else
468             fprintf(stderr,
469                     "not compiled with FIPS support, so exitting without running.\n");
470             EXIT(0);
471 #endif
472         } else if (strcmp(*argv, "-server_auth") == 0)
473             server_auth = 1;
474         else if (strcmp(*argv, "-client_auth") == 0)
475             client_auth = 1;
476         else if (strcmp(*argv, "-proxy_auth") == 0) {
477             if (--argc < 1)
478                 goto bad;
479             app_verify_arg.proxy_auth = *(++argv);
480         } else if (strcmp(*argv, "-proxy_cond") == 0) {
481             if (--argc < 1)
482                 goto bad;
483             app_verify_arg.proxy_cond = *(++argv);
484         } else if (strcmp(*argv, "-v") == 0)
485             verbose = 1;
486         else if (strcmp(*argv, "-d") == 0)
487             debug = 1;
488         else if (strcmp(*argv, "-reuse") == 0)
489             reuse = 1;
490         else if (strcmp(*argv, "-dhe1024") == 0) {
491 #ifndef OPENSSL_NO_DH
492             dhe1024 = 1;
493 #else
494             fprintf(stderr,
495                     "ignoring -dhe1024, since I'm compiled without DH\n");
496 #endif
497         } else if (strcmp(*argv, "-dhe1024dsa") == 0) {
498 #ifndef OPENSSL_NO_DH
499             dhe1024dsa = 1;
500 #else
501             fprintf(stderr,
502                     "ignoring -dhe1024, since I'm compiled without DH\n");
503 #endif
504         } else if (strcmp(*argv, "-no_dhe") == 0)
505             no_dhe = 1;
506         else if (strcmp(*argv, "-no_ecdhe") == 0)
507             no_ecdhe = 1;
508         else if (strcmp(*argv, "-ssl2") == 0)
509             ssl2 = 1;
510         else if (strcmp(*argv, "-tls1") == 0)
511             tls1 = 1;
512         else if (strcmp(*argv, "-ssl3") == 0)
513             ssl3 = 1;
514         else if (strncmp(*argv, "-num", 4) == 0) {
515             if (--argc < 1)
516                 goto bad;
517             number = atoi(*(++argv));
518             if (number == 0)
519                 number = 1;
520         } else if (strcmp(*argv, "-bytes") == 0) {
521             if (--argc < 1)
522                 goto bad;
523             bytes = atol(*(++argv));
524             if (bytes == 0L)
525                 bytes = 1L;
526             i = strlen(argv[0]);
527             if (argv[0][i - 1] == 'k')
528                 bytes *= 1024L;
529             if (argv[0][i - 1] == 'm')
530                 bytes *= 1024L * 1024L;
531         } else if (strcmp(*argv, "-cert") == 0) {
532             if (--argc < 1)
533                 goto bad;
534             server_cert = *(++argv);
535         } else if (strcmp(*argv, "-s_cert") == 0) {
536             if (--argc < 1)
537                 goto bad;
538             server_cert = *(++argv);
539         } else if (strcmp(*argv, "-key") == 0) {
540             if (--argc < 1)
541                 goto bad;
542             server_key = *(++argv);
543         } else if (strcmp(*argv, "-s_key") == 0) {
544             if (--argc < 1)
545                 goto bad;
546             server_key = *(++argv);
547         } else if (strcmp(*argv, "-c_cert") == 0) {
548             if (--argc < 1)
549                 goto bad;
550             client_cert = *(++argv);
551         } else if (strcmp(*argv, "-c_key") == 0) {
552             if (--argc < 1)
553                 goto bad;
554             client_key = *(++argv);
555         } else if (strcmp(*argv, "-cipher") == 0) {
556             if (--argc < 1)
557                 goto bad;
558             cipher = *(++argv);
559         } else if (strcmp(*argv, "-CApath") == 0) {
560             if (--argc < 1)
561                 goto bad;
562             CApath = *(++argv);
563         } else if (strcmp(*argv, "-CAfile") == 0) {
564             if (--argc < 1)
565                 goto bad;
566             CAfile = *(++argv);
567         } else if (strcmp(*argv, "-bio_pair") == 0) {
568             bio_pair = 1;
569         } else if (strcmp(*argv, "-f") == 0) {
570             force = 1;
571         } else if (strcmp(*argv, "-time") == 0) {
572             print_time = 1;
573         } else if (strcmp(*argv, "-zlib") == 0) {
574             comp = COMP_ZLIB;
575         } else if (strcmp(*argv, "-rle") == 0) {
576             comp = COMP_RLE;
577         } else if (strcmp(*argv, "-named_curve") == 0) {
578             if (--argc < 1)
579                 goto bad;
580 #ifndef OPENSSL_NO_ECDH
581             named_curve = *(++argv);
582 #else
583             fprintf(stderr,
584                     "ignoring -named_curve, since I'm compiled without ECDH\n");
585             ++argv;
586 #endif
587         } else if (strcmp(*argv, "-app_verify") == 0) {
588             app_verify_arg.app_verify = 1;
589         } else if (strcmp(*argv, "-proxy") == 0) {
590             app_verify_arg.allow_proxy_certs = 1;
591         } else if (strcmp(*argv, "-test_cipherlist") == 0) {
592             test_cipherlist = 1;
593         } else {
594             fprintf(stderr, "unknown option %s\n", *argv);
595             badop = 1;
596             break;
597         }
598         argc--;
599         argv++;
600     }
601     if (badop) {
602  bad:
603         sv_usage();
604         goto end;
605     }
606
607     if (test_cipherlist == 1) {
608         /*
609          * ensure that the cipher list are correctly sorted and exit
610          */
611         if (do_test_cipherlist() == 0)
612             EXIT(1);
613         ret = 0;
614         goto end;
615     }
616
617     if (!ssl2 && !ssl3 && !tls1 && number > 1 && !reuse && !force) {
618         fprintf(stderr, "This case cannot work.  Use -f to perform "
619                 "the test anyway (and\n-d to see what happens), "
620                 "or add one of -ssl2, -ssl3, -tls1, -reuse\n"
621                 "to avoid protocol mismatch.\n");
622         EXIT(1);
623     }
624 #ifdef OPENSSL_FIPS
625     if (fips_mode) {
626         if (!FIPS_mode_set(1)) {
627             ERR_load_crypto_strings();
628             ERR_print_errors(BIO_new_fp(stderr, BIO_NOCLOSE));
629             EXIT(1);
630         } else
631             fprintf(stderr, "*** IN FIPS MODE ***\n");
632     }
633 #endif
634
635     if (print_time) {
636         if (!bio_pair) {
637             fprintf(stderr, "Using BIO pair (-bio_pair)\n");
638             bio_pair = 1;
639         }
640         if (number < 50 && !force)
641             fprintf(stderr,
642                     "Warning: For accurate timings, use more connections (e.g. -num 1000)\n");
643     }
644
645 /*      if (cipher == NULL) cipher=getenv("SSL_CIPHER"); */
646
647     SSL_library_init();
648     SSL_load_error_strings();
649
650 #ifndef OPENSSL_NO_COMP
651     if (comp == COMP_ZLIB)
652         cm = COMP_zlib();
653     if (comp == COMP_RLE)
654         cm = COMP_rle();
655     if (cm != NULL) {
656         if (cm->type != NID_undef) {
657             if (SSL_COMP_add_compression_method(comp, cm) != 0) {
658                 fprintf(stderr, "Failed to add compression method\n");
659                 ERR_print_errors_fp(stderr);
660             }
661         } else {
662             fprintf(stderr,
663                     "Warning: %s compression not supported\n",
664                     (comp == COMP_RLE ? "rle" :
665                      (comp == COMP_ZLIB ? "zlib" : "unknown")));
666             ERR_print_errors_fp(stderr);
667         }
668     }
669     ssl_comp_methods = SSL_COMP_get_compression_methods();
670     fprintf(stderr, "Available compression methods:\n");
671     {
672         int j, n = sk_SSL_COMP_num(ssl_comp_methods);
673         if (n == 0)
674             fprintf(stderr, "  NONE\n");
675         else
676             for (j = 0; j < n; j++) {
677                 SSL_COMP *c = sk_SSL_COMP_value(ssl_comp_methods, j);
678                 fprintf(stderr, "  %d: %s\n", c->id, c->name);
679             }
680     }
681 #endif
682
683 #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
684     if (ssl2)
685         meth = SSLv2_method();
686     else if (tls1)
687         meth = TLSv1_method();
688     else if (ssl3)
689         meth = SSLv3_method();
690     else
691         meth = SSLv23_method();
692 #else
693 # ifdef OPENSSL_NO_SSL2
694     if (tls1)
695         meth = TLSv1_method();
696     else if (ssl3)
697         meth = SSLv3_method();
698     else
699         meth = SSLv23_method();
700 # else
701     meth = SSLv2_method();
702 # endif
703 #endif
704
705     c_ctx = SSL_CTX_new(meth);
706     s_ctx = SSL_CTX_new(meth);
707     if ((c_ctx == NULL) || (s_ctx == NULL)) {
708         ERR_print_errors(bio_err);
709         goto end;
710     }
711
712     if (cipher != NULL) {
713         SSL_CTX_set_cipher_list(c_ctx, cipher);
714         SSL_CTX_set_cipher_list(s_ctx, cipher);
715     }
716 #ifndef OPENSSL_NO_DH
717     if (!no_dhe) {
718         if (dhe1024dsa) {
719             /*
720              * use SSL_OP_SINGLE_DH_USE to avoid small subgroup attacks
721              */
722             SSL_CTX_set_options(s_ctx, SSL_OP_SINGLE_DH_USE);
723             dh = get_dh1024dsa();
724         } else if (dhe1024)
725             dh = get_dh1024();
726         else
727             dh = get_dh512();
728         SSL_CTX_set_tmp_dh(s_ctx, dh);
729         DH_free(dh);
730     }
731 #else
732     (void)no_dhe;
733 #endif
734
735 #ifndef OPENSSL_NO_ECDH
736     if (!no_ecdhe) {
737         int nid;
738
739         if (named_curve != NULL) {
740             nid = OBJ_sn2nid(named_curve);
741             if (nid == 0) {
742                 BIO_printf(bio_err, "unknown curve name (%s)\n", named_curve);
743                 goto end;
744             }
745         } else
746             nid = NID_sect163r2;
747
748         ecdh = EC_KEY_new_by_curve_name(nid);
749         if (ecdh == NULL) {
750             BIO_printf(bio_err, "unable to create curve\n");
751             goto end;
752         }
753
754         SSL_CTX_set_tmp_ecdh(s_ctx, ecdh);
755         SSL_CTX_set_options(s_ctx, SSL_OP_SINGLE_ECDH_USE);
756         EC_KEY_free(ecdh);
757     }
758 #else
759     (void)no_ecdhe;
760 #endif
761
762 #ifndef OPENSSL_NO_RSA
763     SSL_CTX_set_tmp_rsa_callback(s_ctx, tmp_rsa_cb);
764 #endif
765
766     if (!SSL_CTX_use_certificate_file(s_ctx, server_cert, SSL_FILETYPE_PEM)) {
767         ERR_print_errors(bio_err);
768     } else if (!SSL_CTX_use_PrivateKey_file(s_ctx,
769                                             (server_key ? server_key :
770                                              server_cert),
771                                             SSL_FILETYPE_PEM)) {
772         ERR_print_errors(bio_err);
773         goto end;
774     }
775
776     if (client_auth) {
777         SSL_CTX_use_certificate_file(c_ctx, client_cert, SSL_FILETYPE_PEM);
778         SSL_CTX_use_PrivateKey_file(c_ctx,
779                                     (client_key ? client_key : client_cert),
780                                     SSL_FILETYPE_PEM);
781     }
782
783     if ((!SSL_CTX_load_verify_locations(s_ctx, CAfile, CApath)) ||
784         (!SSL_CTX_set_default_verify_paths(s_ctx)) ||
785         (!SSL_CTX_load_verify_locations(c_ctx, CAfile, CApath)) ||
786         (!SSL_CTX_set_default_verify_paths(c_ctx))) {
787         /* fprintf(stderr,"SSL_load_verify_locations\n"); */
788         ERR_print_errors(bio_err);
789         /* goto end; */
790     }
791
792     if (client_auth) {
793         BIO_printf(bio_err, "client authentication\n");
794         SSL_CTX_set_verify(s_ctx,
795                            SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
796                            verify_callback);
797         SSL_CTX_set_cert_verify_callback(s_ctx, app_verify_callback,
798                                          &app_verify_arg);
799     }
800     if (server_auth) {
801         BIO_printf(bio_err, "server authentication\n");
802         SSL_CTX_set_verify(c_ctx, SSL_VERIFY_PEER, verify_callback);
803         SSL_CTX_set_cert_verify_callback(c_ctx, app_verify_callback,
804                                          &app_verify_arg);
805     }
806
807     {
808         int session_id_context = 0;
809         SSL_CTX_set_session_id_context(s_ctx, (void *)&session_id_context,
810                                        sizeof session_id_context);
811     }
812
813     c_ssl = SSL_new(c_ctx);
814     s_ssl = SSL_new(s_ctx);
815
816 #ifndef OPENSSL_NO_KRB5
817     if (c_ssl && c_ssl->kssl_ctx) {
818         char localhost[MAXHOSTNAMELEN + 2];
819
820         if (gethostname(localhost, sizeof localhost - 1) == 0) {
821             localhost[sizeof localhost - 1] = '\0';
822             if (strlen(localhost) == sizeof localhost - 1) {
823                 BIO_printf(bio_err, "localhost name too long\n");
824                 goto end;
825             }
826             kssl_ctx_setstring(c_ssl->kssl_ctx, KSSL_SERVER, localhost);
827         }
828     }
829 #endif                          /* OPENSSL_NO_KRB5 */
830
831     for (i = 0; i < number; i++) {
832         if (!reuse)
833             SSL_set_session(c_ssl, NULL);
834         if (bio_pair)
835             ret = doit_biopair(s_ssl, c_ssl, bytes, &s_time, &c_time);
836         else
837             ret = doit(s_ssl, c_ssl, bytes);
838     }
839
840     if (!verbose) {
841         print_details(c_ssl, "");
842     }
843     if ((number > 1) || (bytes > 1L))
844         BIO_printf(bio_stdout, "%d handshakes of %ld bytes done\n", number,
845                    bytes);
846     if (print_time) {
847 #ifdef CLOCKS_PER_SEC
848         /*
849          * "To determine the time in seconds, the value returned by the clock
850          * function should be divided by the value of the macro
851          * CLOCKS_PER_SEC." -- ISO/IEC 9899
852          */
853         BIO_printf(bio_stdout, "Approximate total server time: %6.2f s\n"
854                    "Approximate total client time: %6.2f s\n",
855                    (double)s_time / CLOCKS_PER_SEC,
856                    (double)c_time / CLOCKS_PER_SEC);
857 #else
858         /*
859          * "`CLOCKS_PER_SEC' undeclared (first use this function)" -- cc on
860          * NeXTstep/OpenStep
861          */
862         BIO_printf(bio_stdout,
863                    "Approximate total server time: %6.2f units\n"
864                    "Approximate total client time: %6.2f units\n",
865                    (double)s_time, (double)c_time);
866 #endif
867     }
868
869     SSL_free(s_ssl);
870     SSL_free(c_ssl);
871
872  end:
873     if (s_ctx != NULL)
874         SSL_CTX_free(s_ctx);
875     if (c_ctx != NULL)
876         SSL_CTX_free(c_ctx);
877
878     if (bio_stdout != NULL)
879         BIO_free(bio_stdout);
880
881 #ifndef OPENSSL_NO_RSA
882     free_tmp_rsa();
883 #endif
884 #ifndef OPENSSL_NO_ENGINE
885     ENGINE_cleanup();
886 #endif
887     CRYPTO_cleanup_all_ex_data();
888     ERR_free_strings();
889     ERR_remove_state(0);
890     EVP_cleanup();
891     CRYPTO_mem_leaks(bio_err);
892     if (bio_err != NULL)
893         BIO_free(bio_err);
894     EXIT(ret);
895     return ret;
896 }
897
898 int doit_biopair(SSL *s_ssl, SSL *c_ssl, long count,
899                  clock_t *s_time, clock_t *c_time)
900 {
901     long cw_num = count, cr_num = count, sw_num = count, sr_num = count;
902     BIO *s_ssl_bio = NULL, *c_ssl_bio = NULL;
903     BIO *server = NULL, *server_io = NULL, *client = NULL, *client_io = NULL;
904     int ret = 1;
905
906     size_t bufsiz = 256;        /* small buffer for testing */
907
908     if (!BIO_new_bio_pair(&server, bufsiz, &server_io, bufsiz))
909         goto err;
910     if (!BIO_new_bio_pair(&client, bufsiz, &client_io, bufsiz))
911         goto err;
912
913     s_ssl_bio = BIO_new(BIO_f_ssl());
914     if (!s_ssl_bio)
915         goto err;
916
917     c_ssl_bio = BIO_new(BIO_f_ssl());
918     if (!c_ssl_bio)
919         goto err;
920
921     SSL_set_connect_state(c_ssl);
922     SSL_set_bio(c_ssl, client, client);
923     (void)BIO_set_ssl(c_ssl_bio, c_ssl, BIO_NOCLOSE);
924
925     SSL_set_accept_state(s_ssl);
926     SSL_set_bio(s_ssl, server, server);
927     (void)BIO_set_ssl(s_ssl_bio, s_ssl, BIO_NOCLOSE);
928
929     do {
930         /*-
931          * c_ssl_bio:          SSL filter BIO
932          *
933          * client:             pseudo-I/O for SSL library
934          *
935          * client_io:          client's SSL communication; usually to be
936          *                     relayed over some I/O facility, but in this
937          *                     test program, we're the server, too:
938          *
939          * server_io:          server's SSL communication
940          *
941          * server:             pseudo-I/O for SSL library
942          *
943          * s_ssl_bio:          SSL filter BIO
944          *
945          * The client and the server each employ a "BIO pair":
946          * client + client_io, server + server_io.
947          * BIO pairs are symmetric.  A BIO pair behaves similar
948          * to a non-blocking socketpair (but both endpoints must
949          * be handled by the same thread).
950          * [Here we could connect client and server to the ends
951          * of a single BIO pair, but then this code would be less
952          * suitable as an example for BIO pairs in general.]
953          *
954          * Useful functions for querying the state of BIO pair endpoints:
955          *
956          * BIO_ctrl_pending(bio)              number of bytes we can read now
957          * BIO_ctrl_get_read_request(bio)     number of bytes needed to fulfil
958          *                                      other side's read attempt
959          * BIO_ctrl_get_write_guarantee(bio)   number of bytes we can write now
960          *
961          * ..._read_request is never more than ..._write_guarantee;
962          * it depends on the application which one you should use.
963          */
964
965         /*
966          * We have non-blocking behaviour throughout this test program, but
967          * can be sure that there is *some* progress in each iteration; so we
968          * don't have to worry about ..._SHOULD_READ or ..._SHOULD_WRITE --
969          * we just try everything in each iteration
970          */
971
972         {
973             /* CLIENT */
974
975             MS_STATIC char cbuf[1024 * 8];
976             int i, r;
977             clock_t c_clock = clock();
978
979             memset(cbuf, 0, sizeof(cbuf));
980
981             if (debug)
982                 if (SSL_in_init(c_ssl))
983                     printf("client waiting in SSL_connect - %s\n",
984                            SSL_state_string_long(c_ssl));
985
986             if (cw_num > 0) {
987                 /* Write to server. */
988
989                 if (cw_num > (long)sizeof cbuf)
990                     i = sizeof cbuf;
991                 else
992                     i = (int)cw_num;
993                 r = BIO_write(c_ssl_bio, cbuf, i);
994                 if (r < 0) {
995                     if (!BIO_should_retry(c_ssl_bio)) {
996                         fprintf(stderr, "ERROR in CLIENT\n");
997                         goto err;
998                     }
999                     /*
1000                      * BIO_should_retry(...) can just be ignored here. The
1001                      * library expects us to call BIO_write with the same
1002                      * arguments again, and that's what we will do in the
1003                      * next iteration.
1004                      */
1005                 } else if (r == 0) {
1006                     fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
1007                     goto err;
1008                 } else {
1009                     if (debug)
1010                         printf("client wrote %d\n", r);
1011                     cw_num -= r;
1012                 }
1013             }
1014
1015             if (cr_num > 0) {
1016                 /* Read from server. */
1017
1018                 r = BIO_read(c_ssl_bio, cbuf, sizeof(cbuf));
1019                 if (r < 0) {
1020                     if (!BIO_should_retry(c_ssl_bio)) {
1021                         fprintf(stderr, "ERROR in CLIENT\n");
1022                         goto err;
1023                     }
1024                     /*
1025                      * Again, "BIO_should_retry" can be ignored.
1026                      */
1027                 } else if (r == 0) {
1028                     fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
1029                     goto err;
1030                 } else {
1031                     if (debug)
1032                         printf("client read %d\n", r);
1033                     cr_num -= r;
1034                 }
1035             }
1036
1037             /*
1038              * c_time and s_time increments will typically be very small
1039              * (depending on machine speed and clock tick intervals), but
1040              * sampling over a large number of connections should result in
1041              * fairly accurate figures.  We cannot guarantee a lot, however
1042              * -- if each connection lasts for exactly one clock tick, it
1043              * will be counted only for the client or only for the server or
1044              * even not at all.
1045              */
1046             *c_time += (clock() - c_clock);
1047         }
1048
1049         {
1050             /* SERVER */
1051
1052             MS_STATIC char sbuf[1024 * 8];
1053             int i, r;
1054             clock_t s_clock = clock();
1055
1056             memset(sbuf, 0, sizeof(sbuf));
1057
1058             if (debug)
1059                 if (SSL_in_init(s_ssl))
1060                     printf("server waiting in SSL_accept - %s\n",
1061                            SSL_state_string_long(s_ssl));
1062
1063             if (sw_num > 0) {
1064                 /* Write to client. */
1065
1066                 if (sw_num > (long)sizeof sbuf)
1067                     i = sizeof sbuf;
1068                 else
1069                     i = (int)sw_num;
1070                 r = BIO_write(s_ssl_bio, sbuf, i);
1071                 if (r < 0) {
1072                     if (!BIO_should_retry(s_ssl_bio)) {
1073                         fprintf(stderr, "ERROR in SERVER\n");
1074                         goto err;
1075                     }
1076                     /* Ignore "BIO_should_retry". */
1077                 } else if (r == 0) {
1078                     fprintf(stderr, "SSL SERVER STARTUP FAILED\n");
1079                     goto err;
1080                 } else {
1081                     if (debug)
1082                         printf("server wrote %d\n", r);
1083                     sw_num -= r;
1084                 }
1085             }
1086
1087             if (sr_num > 0) {
1088                 /* Read from client. */
1089
1090                 r = BIO_read(s_ssl_bio, sbuf, sizeof(sbuf));
1091                 if (r < 0) {
1092                     if (!BIO_should_retry(s_ssl_bio)) {
1093                         fprintf(stderr, "ERROR in SERVER\n");
1094                         goto err;
1095                     }
1096                     /* blah, blah */
1097                 } else if (r == 0) {
1098                     fprintf(stderr, "SSL SERVER STARTUP FAILED\n");
1099                     goto err;
1100                 } else {
1101                     if (debug)
1102                         printf("server read %d\n", r);
1103                     sr_num -= r;
1104                 }
1105             }
1106
1107             *s_time += (clock() - s_clock);
1108         }
1109
1110         {
1111             /* "I/O" BETWEEN CLIENT AND SERVER. */
1112
1113             size_t r1, r2;
1114             BIO *io1 = server_io, *io2 = client_io;
1115             /*
1116              * we use the non-copying interface for io1 and the standard
1117              * BIO_write/BIO_read interface for io2
1118              */
1119
1120             static int prev_progress = 1;
1121             int progress = 0;
1122
1123             /* io1 to io2 */
1124             do {
1125                 size_t num;
1126                 int r;
1127
1128                 r1 = BIO_ctrl_pending(io1);
1129                 r2 = BIO_ctrl_get_write_guarantee(io2);
1130
1131                 num = r1;
1132                 if (r2 < num)
1133                     num = r2;
1134                 if (num) {
1135                     char *dataptr;
1136
1137                     if (INT_MAX < num) /* yeah, right */
1138                         num = INT_MAX;
1139
1140                     r = BIO_nread(io1, &dataptr, (int)num);
1141                     assert(r > 0);
1142                     assert(r <= (int)num);
1143                     /*
1144                      * possibly r < num (non-contiguous data)
1145                      */
1146                     num = r;
1147                     r = BIO_write(io2, dataptr, (int)num);
1148                     if (r != (int)num) { /* can't happen */
1149                         fprintf(stderr, "ERROR: BIO_write could not write "
1150                                 "BIO_ctrl_get_write_guarantee() bytes");
1151                         goto err;
1152                     }
1153                     progress = 1;
1154
1155                     if (debug)
1156                         printf((io1 == client_io) ?
1157                                "C->S relaying: %d bytes\n" :
1158                                "S->C relaying: %d bytes\n", (int)num);
1159                 }
1160             }
1161             while (r1 && r2);
1162
1163             /* io2 to io1 */
1164             {
1165                 size_t num;
1166                 int r;
1167
1168                 r1 = BIO_ctrl_pending(io2);
1169                 r2 = BIO_ctrl_get_read_request(io1);
1170                 /*
1171                  * here we could use ..._get_write_guarantee instead of
1172                  * ..._get_read_request, but by using the latter we test
1173                  * restartability of the SSL implementation more thoroughly
1174                  */
1175                 num = r1;
1176                 if (r2 < num)
1177                     num = r2;
1178                 if (num) {
1179                     char *dataptr;
1180
1181                     if (INT_MAX < num)
1182                         num = INT_MAX;
1183
1184                     if (num > 1)
1185                         --num;  /* test restartability even more thoroughly */
1186
1187                     r = BIO_nwrite0(io1, &dataptr);
1188                     assert(r > 0);
1189                     if (r < (int)num)
1190                         num = r;
1191                     r = BIO_read(io2, dataptr, (int)num);
1192                     if (r != (int)num) { /* can't happen */
1193                         fprintf(stderr, "ERROR: BIO_read could not read "
1194                                 "BIO_ctrl_pending() bytes");
1195                         goto err;
1196                     }
1197                     progress = 1;
1198                     r = BIO_nwrite(io1, &dataptr, (int)num);
1199                     if (r != (int)num) { /* can't happen */
1200                         fprintf(stderr, "ERROR: BIO_nwrite() did not accept "
1201                                 "BIO_nwrite0() bytes");
1202                         goto err;
1203                     }
1204
1205                     if (debug)
1206                         printf((io2 == client_io) ?
1207                                "C->S relaying: %d bytes\n" :
1208                                "S->C relaying: %d bytes\n", (int)num);
1209                 }
1210             }                   /* no loop, BIO_ctrl_get_read_request now
1211                                  * returns 0 anyway */
1212
1213             if (!progress && !prev_progress)
1214                 if (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0) {
1215                     fprintf(stderr, "ERROR: got stuck\n");
1216                     if (strcmp("SSLv2", SSL_get_version(c_ssl)) == 0) {
1217                         fprintf(stderr, "This can happen for SSL2 because "
1218                                 "CLIENT-FINISHED and SERVER-VERIFY are written \n"
1219                                 "concurrently ...");
1220                         if (strncmp("2SCF", SSL_state_string(c_ssl), 4) == 0
1221                             && strncmp("2SSV", SSL_state_string(s_ssl),
1222                                        4) == 0) {
1223                             fprintf(stderr, " ok.\n");
1224                             goto end;
1225                         }
1226                     }
1227                     fprintf(stderr, " ERROR.\n");
1228                     goto err;
1229                 }
1230             prev_progress = progress;
1231         }
1232     }
1233     while (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0);
1234
1235     if (verbose)
1236         print_details(c_ssl, "DONE via BIO pair: ");
1237  end:
1238     ret = 0;
1239
1240  err:
1241     ERR_print_errors(bio_err);
1242
1243     if (server)
1244         BIO_free(server);
1245     if (server_io)
1246         BIO_free(server_io);
1247     if (client)
1248         BIO_free(client);
1249     if (client_io)
1250         BIO_free(client_io);
1251     if (s_ssl_bio)
1252         BIO_free(s_ssl_bio);
1253     if (c_ssl_bio)
1254         BIO_free(c_ssl_bio);
1255
1256     return ret;
1257 }
1258
1259 #define W_READ  1
1260 #define W_WRITE 2
1261 #define C_DONE  1
1262 #define S_DONE  2
1263
1264 int doit(SSL *s_ssl, SSL *c_ssl, long count)
1265 {
1266     MS_STATIC char cbuf[1024 * 8], sbuf[1024 * 8];
1267     long cw_num = count, cr_num = count;
1268     long sw_num = count, sr_num = count;
1269     int ret = 1;
1270     BIO *c_to_s = NULL;
1271     BIO *s_to_c = NULL;
1272     BIO *c_bio = NULL;
1273     BIO *s_bio = NULL;
1274     int c_r, c_w, s_r, s_w;
1275     int i, j;
1276     int done = 0;
1277     int c_write, s_write;
1278     int do_server = 0, do_client = 0;
1279
1280     memset(cbuf, 0, sizeof(cbuf));
1281     memset(sbuf, 0, sizeof(sbuf));
1282
1283     c_to_s = BIO_new(BIO_s_mem());
1284     s_to_c = BIO_new(BIO_s_mem());
1285     if ((s_to_c == NULL) || (c_to_s == NULL)) {
1286         ERR_print_errors(bio_err);
1287         goto err;
1288     }
1289
1290     c_bio = BIO_new(BIO_f_ssl());
1291     s_bio = BIO_new(BIO_f_ssl());
1292     if ((c_bio == NULL) || (s_bio == NULL)) {
1293         ERR_print_errors(bio_err);
1294         goto err;
1295     }
1296
1297     SSL_set_connect_state(c_ssl);
1298     SSL_set_bio(c_ssl, s_to_c, c_to_s);
1299     BIO_set_ssl(c_bio, c_ssl, BIO_NOCLOSE);
1300
1301     SSL_set_accept_state(s_ssl);
1302     SSL_set_bio(s_ssl, c_to_s, s_to_c);
1303     BIO_set_ssl(s_bio, s_ssl, BIO_NOCLOSE);
1304
1305     c_r = 0;
1306     s_r = 1;
1307     c_w = 1;
1308     s_w = 0;
1309     c_write = 1, s_write = 0;
1310
1311     /* We can always do writes */
1312     for (;;) {
1313         do_server = 0;
1314         do_client = 0;
1315
1316         i = (int)BIO_pending(s_bio);
1317         if ((i && s_r) || s_w)
1318             do_server = 1;
1319
1320         i = (int)BIO_pending(c_bio);
1321         if ((i && c_r) || c_w)
1322             do_client = 1;
1323
1324         if (do_server && debug) {
1325             if (SSL_in_init(s_ssl))
1326                 printf("server waiting in SSL_accept - %s\n",
1327                        SSL_state_string_long(s_ssl));
1328 /*-
1329             else if (s_write)
1330                 printf("server:SSL_write()\n");
1331             else
1332                 printf("server:SSL_read()\n"); */
1333         }
1334
1335         if (do_client && debug) {
1336             if (SSL_in_init(c_ssl))
1337                 printf("client waiting in SSL_connect - %s\n",
1338                        SSL_state_string_long(c_ssl));
1339 /*-
1340             else if (c_write)
1341                 printf("client:SSL_write()\n");
1342             else
1343                 printf("client:SSL_read()\n"); */
1344         }
1345
1346         if (!do_client && !do_server) {
1347             fprintf(stdout, "ERROR IN STARTUP\n");
1348             ERR_print_errors(bio_err);
1349             goto err;
1350         }
1351         if (do_client && !(done & C_DONE)) {
1352             if (c_write) {
1353                 j = (cw_num > (long)sizeof(cbuf)) ?
1354                     (int)sizeof(cbuf) : (int)cw_num;
1355                 i = BIO_write(c_bio, cbuf, j);
1356                 if (i < 0) {
1357                     c_r = 0;
1358                     c_w = 0;
1359                     if (BIO_should_retry(c_bio)) {
1360                         if (BIO_should_read(c_bio))
1361                             c_r = 1;
1362                         if (BIO_should_write(c_bio))
1363                             c_w = 1;
1364                     } else {
1365                         fprintf(stderr, "ERROR in CLIENT\n");
1366                         ERR_print_errors(bio_err);
1367                         goto err;
1368                     }
1369                 } else if (i == 0) {
1370                     fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
1371                     goto err;
1372                 } else {
1373                     if (debug)
1374                         printf("client wrote %d\n", i);
1375                     /* ok */
1376                     s_r = 1;
1377                     c_write = 0;
1378                     cw_num -= i;
1379                 }
1380             } else {
1381                 i = BIO_read(c_bio, cbuf, sizeof(cbuf));
1382                 if (i < 0) {
1383                     c_r = 0;
1384                     c_w = 0;
1385                     if (BIO_should_retry(c_bio)) {
1386                         if (BIO_should_read(c_bio))
1387                             c_r = 1;
1388                         if (BIO_should_write(c_bio))
1389                             c_w = 1;
1390                     } else {
1391                         fprintf(stderr, "ERROR in CLIENT\n");
1392                         ERR_print_errors(bio_err);
1393                         goto err;
1394                     }
1395                 } else if (i == 0) {
1396                     fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
1397                     goto err;
1398                 } else {
1399                     if (debug)
1400                         printf("client read %d\n", i);
1401                     cr_num -= i;
1402                     if (sw_num > 0) {
1403                         s_write = 1;
1404                         s_w = 1;
1405                     }
1406                     if (cr_num <= 0) {
1407                         s_write = 1;
1408                         s_w = 1;
1409                         done = S_DONE | C_DONE;
1410                     }
1411                 }
1412             }
1413         }
1414
1415         if (do_server && !(done & S_DONE)) {
1416             if (!s_write) {
1417                 i = BIO_read(s_bio, sbuf, sizeof(cbuf));
1418                 if (i < 0) {
1419                     s_r = 0;
1420                     s_w = 0;
1421                     if (BIO_should_retry(s_bio)) {
1422                         if (BIO_should_read(s_bio))
1423                             s_r = 1;
1424                         if (BIO_should_write(s_bio))
1425                             s_w = 1;
1426                     } else {
1427                         fprintf(stderr, "ERROR in SERVER\n");
1428                         ERR_print_errors(bio_err);
1429                         goto err;
1430                     }
1431                 } else if (i == 0) {
1432                     ERR_print_errors(bio_err);
1433                     fprintf(stderr,
1434                             "SSL SERVER STARTUP FAILED in SSL_read\n");
1435                     goto err;
1436                 } else {
1437                     if (debug)
1438                         printf("server read %d\n", i);
1439                     sr_num -= i;
1440                     if (cw_num > 0) {
1441                         c_write = 1;
1442                         c_w = 1;
1443                     }
1444                     if (sr_num <= 0) {
1445                         s_write = 1;
1446                         s_w = 1;
1447                         c_write = 0;
1448                     }
1449                 }
1450             } else {
1451                 j = (sw_num > (long)sizeof(sbuf)) ?
1452                     (int)sizeof(sbuf) : (int)sw_num;
1453                 i = BIO_write(s_bio, sbuf, j);
1454                 if (i < 0) {
1455                     s_r = 0;
1456                     s_w = 0;
1457                     if (BIO_should_retry(s_bio)) {
1458                         if (BIO_should_read(s_bio))
1459                             s_r = 1;
1460                         if (BIO_should_write(s_bio))
1461                             s_w = 1;
1462                     } else {
1463                         fprintf(stderr, "ERROR in SERVER\n");
1464                         ERR_print_errors(bio_err);
1465                         goto err;
1466                     }
1467                 } else if (i == 0) {
1468                     ERR_print_errors(bio_err);
1469                     fprintf(stderr,
1470                             "SSL SERVER STARTUP FAILED in SSL_write\n");
1471                     goto err;
1472                 } else {
1473                     if (debug)
1474                         printf("server wrote %d\n", i);
1475                     sw_num -= i;
1476                     s_write = 0;
1477                     c_r = 1;
1478                     if (sw_num <= 0)
1479                         done |= S_DONE;
1480                 }
1481             }
1482         }
1483
1484         if ((done & S_DONE) && (done & C_DONE))
1485             break;
1486     }
1487
1488     if (verbose)
1489         print_details(c_ssl, "DONE: ");
1490     ret = 0;
1491  err:
1492     /*
1493      * We have to set the BIO's to NULL otherwise they will be
1494      * OPENSSL_free()ed twice.  Once when th s_ssl is SSL_free()ed and again
1495      * when c_ssl is SSL_free()ed. This is a hack required because s_ssl and
1496      * c_ssl are sharing the same BIO structure and SSL_set_bio() and
1497      * SSL_free() automatically BIO_free non NULL entries. You should not
1498      * normally do this or be required to do this
1499      */
1500     if (s_ssl != NULL) {
1501         s_ssl->rbio = NULL;
1502         s_ssl->wbio = NULL;
1503     }
1504     if (c_ssl != NULL) {
1505         c_ssl->rbio = NULL;
1506         c_ssl->wbio = NULL;
1507     }
1508
1509     if (c_to_s != NULL)
1510         BIO_free(c_to_s);
1511     if (s_to_c != NULL)
1512         BIO_free(s_to_c);
1513     if (c_bio != NULL)
1514         BIO_free_all(c_bio);
1515     if (s_bio != NULL)
1516         BIO_free_all(s_bio);
1517     return (ret);
1518 }
1519
1520 static int get_proxy_auth_ex_data_idx(void)
1521 {
1522     static volatile int idx = -1;
1523     if (idx < 0) {
1524         CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
1525         if (idx < 0) {
1526             idx = X509_STORE_CTX_get_ex_new_index(0,
1527                                                   "SSLtest for verify callback",
1528                                                   NULL, NULL, NULL);
1529         }
1530         CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
1531     }
1532     return idx;
1533 }
1534
1535 static int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx)
1536 {
1537     char *s, buf[256];
1538
1539     s = X509_NAME_oneline(X509_get_subject_name(ctx->current_cert), buf,
1540                           sizeof buf);
1541     if (s != NULL) {
1542         if (ok)
1543             fprintf(stderr, "depth=%d %s\n", ctx->error_depth, buf);
1544         else {
1545             fprintf(stderr, "depth=%d error=%d %s\n",
1546                     ctx->error_depth, ctx->error, buf);
1547         }
1548     }
1549
1550     if (ok == 0) {
1551         fprintf(stderr, "Error string: %s\n",
1552                 X509_verify_cert_error_string(ctx->error));
1553         switch (ctx->error) {
1554         case X509_V_ERR_CERT_NOT_YET_VALID:
1555         case X509_V_ERR_CERT_HAS_EXPIRED:
1556         case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1557             fprintf(stderr, "  ... ignored.\n");
1558             ok = 1;
1559         }
1560     }
1561
1562     if (ok == 1) {
1563         X509 *xs = ctx->current_cert;
1564 #if 0
1565         X509 *xi = ctx->current_issuer;
1566 #endif
1567
1568         if (xs->ex_flags & EXFLAG_PROXY) {
1569             unsigned int *letters = X509_STORE_CTX_get_ex_data(ctx,
1570                                                                get_proxy_auth_ex_data_idx
1571                                                                ());
1572
1573             if (letters) {
1574                 int found_any = 0;
1575                 int i;
1576                 PROXY_CERT_INFO_EXTENSION *pci =
1577                     X509_get_ext_d2i(xs, NID_proxyCertInfo,
1578                                      NULL, NULL);
1579
1580                 switch (OBJ_obj2nid(pci->proxyPolicy->policyLanguage)) {
1581                 case NID_Independent:
1582                     /*
1583                      * Completely meaningless in this program, as there's no
1584                      * way to grant explicit rights to a specific PrC.
1585                      * Basically, using id-ppl-Independent is the perfect way
1586                      * to grant no rights at all.
1587                      */
1588                     fprintf(stderr, "  Independent proxy certificate");
1589                     for (i = 0; i < 26; i++)
1590                         letters[i] = 0;
1591                     break;
1592                 case NID_id_ppl_inheritAll:
1593                     /*
1594                      * This is basically a NOP, we simply let the current
1595                      * rights stand as they are.
1596                      */
1597                     fprintf(stderr, "  Proxy certificate inherits all");
1598                     break;
1599                 default:
1600                     s = (char *)
1601                         pci->proxyPolicy->policy->data;
1602                     i = pci->proxyPolicy->policy->length;
1603
1604                     /*
1605                      * The algorithm works as follows: it is assumed that
1606                      * previous iterations or the initial granted rights has
1607                      * already set some elements of `letters'.  What we need
1608                      * to do is to clear those that weren't granted by the
1609                      * current PrC as well.  The easiest way to do this is to
1610                      * add 1 to all the elements whose letters are given with
1611                      * the current policy. That way, all elements that are
1612                      * set by the current policy and were already set by
1613                      * earlier policies and through the original grant of
1614                      * rights will get the value 2 or higher. The last thing
1615                      * to do is to sweep through `letters' and keep the
1616                      * elements having the value 2 as set, and clear all the
1617                      * others.
1618                      */
1619
1620                     fprintf(stderr, "  Certificate proxy rights = %*.*s", i,
1621                             i, s);
1622                     while (i-- > 0) {
1623                         int c = *s++;
1624                         if (isascii(c) && isalpha(c)) {
1625                             if (islower(c))
1626                                 c = toupper(c);
1627                             letters[c - 'A']++;
1628                         }
1629                     }
1630                     for (i = 0; i < 26; i++)
1631                         if (letters[i] < 2)
1632                             letters[i] = 0;
1633                         else
1634                             letters[i] = 1;
1635                 }
1636
1637                 found_any = 0;
1638                 fprintf(stderr, ", resulting proxy rights = ");
1639                 for (i = 0; i < 26; i++)
1640                     if (letters[i]) {
1641                         fprintf(stderr, "%c", i + 'A');
1642                         found_any = 1;
1643                     }
1644                 if (!found_any)
1645                     fprintf(stderr, "none");
1646                 fprintf(stderr, "\n");
1647
1648                 PROXY_CERT_INFO_EXTENSION_free(pci);
1649             }
1650         }
1651     }
1652
1653     return (ok);
1654 }
1655
1656 static void process_proxy_debug(int indent, const char *format, ...)
1657 {
1658     /* That's 80 > */
1659     static const char indentation[] =
1660         ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
1661         ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>";
1662     char my_format[256];
1663     va_list args;
1664
1665     BIO_snprintf(my_format, sizeof(my_format), "%*.*s %s",
1666                  indent, indent, indentation, format);
1667
1668     va_start(args, format);
1669     vfprintf(stderr, my_format, args);
1670     va_end(args);
1671 }
1672
1673 /*-
1674  * Priority levels:
1675  *  0   [!]var, ()
1676  *  1   & ^
1677  *  2   |
1678  */
1679 static int process_proxy_cond_adders(unsigned int letters[26],
1680                                      const char *cond, const char **cond_end,
1681                                      int *pos, int indent);
1682 static int process_proxy_cond_val(unsigned int letters[26], const char *cond,
1683                                   const char **cond_end, int *pos, int indent)
1684 {
1685     int c;
1686     int ok = 1;
1687     int negate = 0;
1688
1689     while (isspace((int)*cond)) {
1690         cond++;
1691         (*pos)++;
1692     }
1693     c = *cond;
1694
1695     if (debug)
1696         process_proxy_debug(indent,
1697                             "Start process_proxy_cond_val at position %d: %s\n",
1698                             *pos, cond);
1699
1700     while (c == '!') {
1701         negate = !negate;
1702         cond++;
1703         (*pos)++;
1704         while (isspace((int)*cond)) {
1705             cond++;
1706             (*pos)++;
1707         }
1708         c = *cond;
1709     }
1710
1711     if (c == '(') {
1712         cond++;
1713         (*pos)++;
1714         ok = process_proxy_cond_adders(letters, cond, cond_end, pos,
1715                                        indent + 1);
1716         cond = *cond_end;
1717         if (ok < 0)
1718             goto end;
1719         while (isspace((int)*cond)) {
1720             cond++;
1721             (*pos)++;
1722         }
1723         c = *cond;
1724         if (c != ')') {
1725             fprintf(stderr,
1726                     "Weird condition character in position %d: "
1727                     "%c\n", *pos, c);
1728             ok = -1;
1729             goto end;
1730         }
1731         cond++;
1732         (*pos)++;
1733     } else if (isascii(c) && isalpha(c)) {
1734         if (islower(c))
1735             c = toupper(c);
1736         ok = letters[c - 'A'];
1737         cond++;
1738         (*pos)++;
1739     } else {
1740         fprintf(stderr,
1741                 "Weird condition character in position %d: " "%c\n", *pos, c);
1742         ok = -1;
1743         goto end;
1744     }
1745  end:
1746     *cond_end = cond;
1747     if (ok >= 0 && negate)
1748         ok = !ok;
1749
1750     if (debug)
1751         process_proxy_debug(indent,
1752                             "End process_proxy_cond_val at position %d: %s, returning %d\n",
1753                             *pos, cond, ok);
1754
1755     return ok;
1756 }
1757
1758 static int process_proxy_cond_multipliers(unsigned int letters[26],
1759                                           const char *cond,
1760                                           const char **cond_end, int *pos,
1761                                           int indent)
1762 {
1763     int ok;
1764     char c;
1765
1766     if (debug)
1767         process_proxy_debug(indent,
1768                             "Start process_proxy_cond_multipliers at position %d: %s\n",
1769                             *pos, cond);
1770
1771     ok = process_proxy_cond_val(letters, cond, cond_end, pos, indent + 1);
1772     cond = *cond_end;
1773     if (ok < 0)
1774         goto end;
1775
1776     while (ok >= 0) {
1777         while (isspace((int)*cond)) {
1778             cond++;
1779             (*pos)++;
1780         }
1781         c = *cond;
1782
1783         switch (c) {
1784         case '&':
1785         case '^':
1786             {
1787                 int save_ok = ok;
1788
1789                 cond++;
1790                 (*pos)++;
1791                 ok = process_proxy_cond_val(letters,
1792                                             cond, cond_end, pos, indent + 1);
1793                 cond = *cond_end;
1794                 if (ok < 0)
1795                     break;
1796
1797                 switch (c) {
1798                 case '&':
1799                     ok &= save_ok;
1800                     break;
1801                 case '^':
1802                     ok ^= save_ok;
1803                     break;
1804                 default:
1805                     fprintf(stderr, "SOMETHING IS SERIOUSLY WRONG!"
1806                             " STOPPING\n");
1807                     EXIT(1);
1808                 }
1809             }
1810             break;
1811         default:
1812             goto end;
1813         }
1814     }
1815  end:
1816     if (debug)
1817         process_proxy_debug(indent,
1818                             "End process_proxy_cond_multipliers at position %d: %s, returning %d\n",
1819                             *pos, cond, ok);
1820
1821     *cond_end = cond;
1822     return ok;
1823 }
1824
1825 static int process_proxy_cond_adders(unsigned int letters[26],
1826                                      const char *cond, const char **cond_end,
1827                                      int *pos, int indent)
1828 {
1829     int ok;
1830     char c;
1831
1832     if (debug)
1833         process_proxy_debug(indent,
1834                             "Start process_proxy_cond_adders at position %d: %s\n",
1835                             *pos, cond);
1836
1837     ok = process_proxy_cond_multipliers(letters, cond, cond_end, pos,
1838                                         indent + 1);
1839     cond = *cond_end;
1840     if (ok < 0)
1841         goto end;
1842
1843     while (ok >= 0) {
1844         while (isspace((int)*cond)) {
1845             cond++;
1846             (*pos)++;
1847         }
1848         c = *cond;
1849
1850         switch (c) {
1851         case '|':
1852             {
1853                 int save_ok = ok;
1854
1855                 cond++;
1856                 (*pos)++;
1857                 ok = process_proxy_cond_multipliers(letters,
1858                                                     cond, cond_end, pos,
1859                                                     indent + 1);
1860                 cond = *cond_end;
1861                 if (ok < 0)
1862                     break;
1863
1864                 switch (c) {
1865                 case '|':
1866                     ok |= save_ok;
1867                     break;
1868                 default:
1869                     fprintf(stderr, "SOMETHING IS SERIOUSLY WRONG!"
1870                             " STOPPING\n");
1871                     EXIT(1);
1872                 }
1873             }
1874             break;
1875         default:
1876             goto end;
1877         }
1878     }
1879  end:
1880     if (debug)
1881         process_proxy_debug(indent,
1882                             "End process_proxy_cond_adders at position %d: %s, returning %d\n",
1883                             *pos, cond, ok);
1884
1885     *cond_end = cond;
1886     return ok;
1887 }
1888
1889 static int process_proxy_cond(unsigned int letters[26],
1890                               const char *cond, const char **cond_end)
1891 {
1892     int pos = 1;
1893     return process_proxy_cond_adders(letters, cond, cond_end, &pos, 1);
1894 }
1895
1896 static int MS_CALLBACK app_verify_callback(X509_STORE_CTX *ctx, void *arg)
1897 {
1898     int ok = 1;
1899     struct app_verify_arg *cb_arg = arg;
1900     unsigned int letters[26];   /* only used with proxy_auth */
1901
1902     if (cb_arg->app_verify) {
1903         char *s = NULL, buf[256];
1904
1905         fprintf(stderr, "In app_verify_callback, allowing cert. ");
1906         fprintf(stderr, "Arg is: %s\n", cb_arg->string);
1907         fprintf(stderr,
1908                 "Finished printing do we have a context? 0x%p a cert? 0x%p\n",
1909                 (void *)ctx, (void *)ctx->cert);
1910         if (ctx->cert)
1911             s = X509_NAME_oneline(X509_get_subject_name(ctx->cert), buf, 256);
1912         if (s != NULL) {
1913             fprintf(stderr, "cert depth=%d %s\n", ctx->error_depth, buf);
1914         }
1915         return (1);
1916     }
1917     if (cb_arg->proxy_auth) {
1918         int found_any = 0, i;
1919         char *sp;
1920
1921         for (i = 0; i < 26; i++)
1922             letters[i] = 0;
1923         for (sp = cb_arg->proxy_auth; *sp; sp++) {
1924             int c = *sp;
1925             if (isascii(c) && isalpha(c)) {
1926                 if (islower(c))
1927                     c = toupper(c);
1928                 letters[c - 'A'] = 1;
1929             }
1930         }
1931
1932         fprintf(stderr, "  Initial proxy rights = ");
1933         for (i = 0; i < 26; i++)
1934             if (letters[i]) {
1935                 fprintf(stderr, "%c", i + 'A');
1936                 found_any = 1;
1937             }
1938         if (!found_any)
1939             fprintf(stderr, "none");
1940         fprintf(stderr, "\n");
1941
1942         X509_STORE_CTX_set_ex_data(ctx,
1943                                    get_proxy_auth_ex_data_idx(), letters);
1944     }
1945     if (cb_arg->allow_proxy_certs) {
1946         X509_STORE_CTX_set_flags(ctx, X509_V_FLAG_ALLOW_PROXY_CERTS);
1947     }
1948 #ifndef OPENSSL_NO_X509_VERIFY
1949     ok = X509_verify_cert(ctx);
1950 #endif
1951
1952     if (cb_arg->proxy_auth) {
1953         if (ok > 0) {
1954             const char *cond_end = NULL;
1955
1956             ok = process_proxy_cond(letters, cb_arg->proxy_cond, &cond_end);
1957
1958             if (ok < 0)
1959                 EXIT(3);
1960             if (*cond_end) {
1961                 fprintf(stderr,
1962                         "Stopped processing condition before it's end.\n");
1963                 ok = 0;
1964             }
1965             if (!ok)
1966                 fprintf(stderr,
1967                         "Proxy rights check with condition '%s' proved invalid\n",
1968                         cb_arg->proxy_cond);
1969             else
1970                 fprintf(stderr,
1971                         "Proxy rights check with condition '%s' proved valid\n",
1972                         cb_arg->proxy_cond);
1973         }
1974     }
1975     return (ok);
1976 }
1977
1978 #ifndef OPENSSL_NO_RSA
1979 static RSA *rsa_tmp = NULL;
1980
1981 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength)
1982 {
1983     BIGNUM *bn = NULL;
1984     if (rsa_tmp == NULL) {
1985         bn = BN_new();
1986         rsa_tmp = RSA_new();
1987         if (!bn || !rsa_tmp || !BN_set_word(bn, RSA_F4)) {
1988             BIO_printf(bio_err, "Memory error...");
1989             goto end;
1990         }
1991         BIO_printf(bio_err, "Generating temp (%d bit) RSA key...", keylength);
1992         (void)BIO_flush(bio_err);
1993         if (!RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL)) {
1994             BIO_printf(bio_err, "Error generating key.");
1995             RSA_free(rsa_tmp);
1996             rsa_tmp = NULL;
1997         }
1998  end:
1999         BIO_printf(bio_err, "\n");
2000         (void)BIO_flush(bio_err);
2001     }
2002     if (bn)
2003         BN_free(bn);
2004     return (rsa_tmp);
2005 }
2006
2007 static void free_tmp_rsa(void)
2008 {
2009     if (rsa_tmp != NULL) {
2010         RSA_free(rsa_tmp);
2011         rsa_tmp = NULL;
2012     }
2013 }
2014 #endif
2015
2016 #ifndef OPENSSL_NO_DH
2017 /*-
2018  * These DH parameters have been generated as follows:
2019  *    $ openssl dhparam -C -noout 512
2020  *    $ openssl dhparam -C -noout 1024
2021  *    $ openssl dhparam -C -noout -dsaparam 1024
2022  * (The third function has been renamed to avoid name conflicts.)
2023  */
2024 static DH *get_dh512()
2025 {
2026     static unsigned char dh512_p[] = {
2027         0xCB, 0xC8, 0xE1, 0x86, 0xD0, 0x1F, 0x94, 0x17, 0xA6, 0x99, 0xF0,
2028         0xC6,
2029         0x1F, 0x0D, 0xAC, 0xB6, 0x25, 0x3E, 0x06, 0x39, 0xCA, 0x72, 0x04,
2030         0xB0,
2031         0x6E, 0xDA, 0xC0, 0x61, 0xE6, 0x7A, 0x77, 0x25, 0xE8, 0x3B, 0xB9,
2032         0x5F,
2033         0x9A, 0xB6, 0xB5, 0xFE, 0x99, 0x0B, 0xA1, 0x93, 0x4E, 0x35, 0x33,
2034         0xB8,
2035         0xE1, 0xF1, 0x13, 0x4F, 0x59, 0x1A, 0xD2, 0x57, 0xC0, 0x26, 0x21,
2036         0x33,
2037         0x02, 0xC5, 0xAE, 0x23,
2038     };
2039     static unsigned char dh512_g[] = {
2040         0x02,
2041     };
2042     DH *dh;
2043
2044     if ((dh = DH_new()) == NULL)
2045         return (NULL);
2046     dh->p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
2047     dh->g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
2048     if ((dh->p == NULL) || (dh->g == NULL)) {
2049         DH_free(dh);
2050         return (NULL);
2051     }
2052     return (dh);
2053 }
2054
2055 static DH *get_dh1024()
2056 {
2057     static unsigned char dh1024_p[] = {
2058         0xF8, 0x81, 0x89, 0x7D, 0x14, 0x24, 0xC5, 0xD1, 0xE6, 0xF7, 0xBF,
2059         0x3A,
2060         0xE4, 0x90, 0xF4, 0xFC, 0x73, 0xFB, 0x34, 0xB5, 0xFA, 0x4C, 0x56,
2061         0xA2,
2062         0xEA, 0xA7, 0xE9, 0xC0, 0xC0, 0xCE, 0x89, 0xE1, 0xFA, 0x63, 0x3F,
2063         0xB0,
2064         0x6B, 0x32, 0x66, 0xF1, 0xD1, 0x7B, 0xB0, 0x00, 0x8F, 0xCA, 0x87,
2065         0xC2,
2066         0xAE, 0x98, 0x89, 0x26, 0x17, 0xC2, 0x05, 0xD2, 0xEC, 0x08, 0xD0,
2067         0x8C,
2068         0xFF, 0x17, 0x52, 0x8C, 0xC5, 0x07, 0x93, 0x03, 0xB1, 0xF6, 0x2F,
2069         0xB8,
2070         0x1C, 0x52, 0x47, 0x27, 0x1B, 0xDB, 0xD1, 0x8D, 0x9D, 0x69, 0x1D,
2071         0x52,
2072         0x4B, 0x32, 0x81, 0xAA, 0x7F, 0x00, 0xC8, 0xDC, 0xE6, 0xD9, 0xCC,
2073         0xC1,
2074         0x11, 0x2D, 0x37, 0x34, 0x6C, 0xEA, 0x02, 0x97, 0x4B, 0x0E, 0xBB,
2075         0xB1,
2076         0x71, 0x33, 0x09, 0x15, 0xFD, 0xDD, 0x23, 0x87, 0x07, 0x5E, 0x89,
2077         0xAB,
2078         0x6B, 0x7C, 0x5F, 0xEC, 0xA6, 0x24, 0xDC, 0x53,
2079     };
2080     static unsigned char dh1024_g[] = {
2081         0x02,
2082     };
2083     DH *dh;
2084
2085     if ((dh = DH_new()) == NULL)
2086         return (NULL);
2087     dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
2088     dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
2089     if ((dh->p == NULL) || (dh->g == NULL)) {
2090         DH_free(dh);
2091         return (NULL);
2092     }
2093     return (dh);
2094 }
2095
2096 static DH *get_dh1024dsa()
2097 {
2098     static unsigned char dh1024_p[] = {
2099         0xC8, 0x00, 0xF7, 0x08, 0x07, 0x89, 0x4D, 0x90, 0x53, 0xF3, 0xD5,
2100         0x00,
2101         0x21, 0x1B, 0xF7, 0x31, 0xA6, 0xA2, 0xDA, 0x23, 0x9A, 0xC7, 0x87,
2102         0x19,
2103         0x3B, 0x47, 0xB6, 0x8C, 0x04, 0x6F, 0xFF, 0xC6, 0x9B, 0xB8, 0x65,
2104         0xD2,
2105         0xC2, 0x5F, 0x31, 0x83, 0x4A, 0xA7, 0x5F, 0x2F, 0x88, 0x38, 0xB6,
2106         0x55,
2107         0xCF, 0xD9, 0x87, 0x6D, 0x6F, 0x9F, 0xDA, 0xAC, 0xA6, 0x48, 0xAF,
2108         0xFC,
2109         0x33, 0x84, 0x37, 0x5B, 0x82, 0x4A, 0x31, 0x5D, 0xE7, 0xBD, 0x52,
2110         0x97,
2111         0xA1, 0x77, 0xBF, 0x10, 0x9E, 0x37, 0xEA, 0x64, 0xFA, 0xCA, 0x28,
2112         0x8D,
2113         0x9D, 0x3B, 0xD2, 0x6E, 0x09, 0x5C, 0x68, 0xC7, 0x45, 0x90, 0xFD,
2114         0xBB,
2115         0x70, 0xC9, 0x3A, 0xBB, 0xDF, 0xD4, 0x21, 0x0F, 0xC4, 0x6A, 0x3C,
2116         0xF6,
2117         0x61, 0xCF, 0x3F, 0xD6, 0x13, 0xF1, 0x5F, 0xBC, 0xCF, 0xBC, 0x26,
2118         0x9E,
2119         0xBC, 0x0B, 0xBD, 0xAB, 0x5D, 0xC9, 0x54, 0x39,
2120     };
2121     static unsigned char dh1024_g[] = {
2122         0x3B, 0x40, 0x86, 0xE7, 0xF3, 0x6C, 0xDE, 0x67, 0x1C, 0xCC, 0x80,
2123         0x05,
2124         0x5A, 0xDF, 0xFE, 0xBD, 0x20, 0x27, 0x74, 0x6C, 0x24, 0xC9, 0x03,
2125         0xF3,
2126         0xE1, 0x8D, 0xC3, 0x7D, 0x98, 0x27, 0x40, 0x08, 0xB8, 0x8C, 0x6A,
2127         0xE9,
2128         0xBB, 0x1A, 0x3A, 0xD6, 0x86, 0x83, 0x5E, 0x72, 0x41, 0xCE, 0x85,
2129         0x3C,
2130         0xD2, 0xB3, 0xFC, 0x13, 0xCE, 0x37, 0x81, 0x9E, 0x4C, 0x1C, 0x7B,
2131         0x65,
2132         0xD3, 0xE6, 0xA6, 0x00, 0xF5, 0x5A, 0x95, 0x43, 0x5E, 0x81, 0xCF,
2133         0x60,
2134         0xA2, 0x23, 0xFC, 0x36, 0xA7, 0x5D, 0x7A, 0x4C, 0x06, 0x91, 0x6E,
2135         0xF6,
2136         0x57, 0xEE, 0x36, 0xCB, 0x06, 0xEA, 0xF5, 0x3D, 0x95, 0x49, 0xCB,
2137         0xA7,
2138         0xDD, 0x81, 0xDF, 0x80, 0x09, 0x4A, 0x97, 0x4D, 0xA8, 0x22, 0x72,
2139         0xA1,
2140         0x7F, 0xC4, 0x70, 0x56, 0x70, 0xE8, 0x20, 0x10, 0x18, 0x8F, 0x2E,
2141         0x60,
2142         0x07, 0xE7, 0x68, 0x1A, 0x82, 0x5D, 0x32, 0xA2,
2143     };
2144     DH *dh;
2145
2146     if ((dh = DH_new()) == NULL)
2147         return (NULL);
2148     dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
2149     dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
2150     if ((dh->p == NULL) || (dh->g == NULL)) {
2151         DH_free(dh);
2152         return (NULL);
2153     }
2154     dh->length = 160;
2155     return (dh);
2156 }
2157 #endif
2158
2159 static int do_test_cipherlist(void)
2160 {
2161     int i = 0;
2162     const SSL_METHOD *meth;
2163     SSL_CIPHER *ci, *tci = NULL;
2164
2165 #ifndef OPENSSL_NO_SSL2
2166     fprintf(stderr, "testing SSLv2 cipher list order: ");
2167     meth = SSLv2_method();
2168     while ((ci = meth->get_cipher(i++)) != NULL) {
2169         if (tci != NULL)
2170             if (ci->id >= tci->id) {
2171                 fprintf(stderr, "failed %lx vs. %lx\n", ci->id, tci->id);
2172                 return 0;
2173             }
2174         tci = ci;
2175     }
2176     fprintf(stderr, "ok\n");
2177 #endif
2178 #ifndef OPENSSL_NO_SSL3
2179     fprintf(stderr, "testing SSLv3 cipher list order: ");
2180     meth = SSLv3_method();
2181     tci = NULL;
2182     while ((ci = meth->get_cipher(i++)) != NULL) {
2183         if (tci != NULL)
2184             if (ci->id >= tci->id) {
2185                 fprintf(stderr, "failed %lx vs. %lx\n", ci->id, tci->id);
2186                 return 0;
2187             }
2188         tci = ci;
2189     }
2190     fprintf(stderr, "ok\n");
2191 #endif
2192 #ifndef OPENSSL_NO_TLS1
2193     fprintf(stderr, "testing TLSv1 cipher list order: ");
2194     meth = TLSv1_method();
2195     tci = NULL;
2196     while ((ci = meth->get_cipher(i++)) != NULL) {
2197         if (tci != NULL)
2198             if (ci->id >= tci->id) {
2199                 fprintf(stderr, "failed %lx vs. %lx\n", ci->id, tci->id);
2200                 return 0;
2201             }
2202         tci = ci;
2203     }
2204     fprintf(stderr, "ok\n");
2205 #endif
2206
2207     return 1;
2208 }