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