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