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