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