ssltest.c revision 1.42
1/*	$OpenBSD: ssltest.c,v 1.42 2023/07/27 07:08:09 tb Exp $ */
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/* XXX - USE_BIOPAIR code needs updating for BIO_n{read,write}{,0} removal. */
144/* #define USE_BIOPAIR */
145
146#define _BSD_SOURCE 1		/* Or gethostname won't be declared properly
147				   on Linux and GNU platforms. */
148#include <sys/types.h>
149#include <sys/socket.h>
150
151#include <netinet/in.h>
152
153#include <assert.h>
154#include <errno.h>
155#include <limits.h>
156#include <netdb.h>
157#include <stdio.h>
158#include <stdlib.h>
159#include <string.h>
160#include <time.h>
161#include <unistd.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#include "ssl_local.h"
181
182#define TEST_SERVER_CERT "../apps/server.pem"
183#define TEST_CLIENT_CERT "../apps/client.pem"
184
185static int verify_callback(int ok, X509_STORE_CTX *ctx);
186static int app_verify_callback(X509_STORE_CTX *ctx, void *arg);
187
188static DH *get_dh1024(void);
189static DH *get_dh1024dsa(void);
190
191static BIO *bio_err = NULL;
192static BIO *bio_stdout = NULL;
193
194static const char *alpn_client;
195static const char *alpn_server;
196static const char *alpn_expected;
197static unsigned char *alpn_selected;
198
199/*
200 * next_protos_parse parses a comma separated list of strings into a string
201 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
202 *   outlen: (output) set to the length of the resulting buffer on success.
203 *   err: (maybe NULL) on failure, an error message line is written to this BIO.
204 *   in: a NUL terminated string like "abc,def,ghi"
205 *
206 *   returns: a malloced buffer or NULL on failure.
207 */
208static unsigned char *
209next_protos_parse(unsigned short *outlen, const char *in)
210{
211	size_t i, len, start = 0;
212	unsigned char *out;
213
214	len = strlen(in);
215	if (len >= 65535)
216		return (NULL);
217
218	if ((out = malloc(strlen(in) + 1)) == NULL)
219		return (NULL);
220
221	for (i = 0; i <= len; ++i) {
222		if (i == len || in[i] == ',') {
223			if (i - start > 255) {
224				free(out);
225				return (NULL);
226			}
227			out[start] = i - start;
228			start = i + 1;
229		} else
230			out[i+1] = in[i];
231	}
232	*outlen = len + 1;
233	return (out);
234}
235
236static int
237cb_server_alpn(SSL *s, const unsigned char **out, unsigned char *outlen,
238    const unsigned char *in, unsigned int inlen, void *arg)
239{
240	unsigned char *protos;
241	unsigned short protos_len;
242
243	if ((protos = next_protos_parse(&protos_len, alpn_server)) == NULL) {
244		fprintf(stderr,
245		    "failed to parser ALPN server protocol string: %s\n",
246		    alpn_server);
247		abort();
248	}
249
250	if (SSL_select_next_proto((unsigned char **)out, outlen, protos,
251	    protos_len, in, inlen) != OPENSSL_NPN_NEGOTIATED) {
252		free(protos);
253		return (SSL_TLSEXT_ERR_NOACK);
254	}
255
256	/*
257	 * Make a copy of the selected protocol which will be freed in
258	 * verify_alpn.
259	 */
260	free(alpn_selected);
261	if ((alpn_selected = malloc(*outlen)) == NULL) {
262		fprintf(stderr, "malloc failed\n");
263		abort();
264	}
265	memcpy(alpn_selected, *out, *outlen);
266	*out = alpn_selected;
267	free(protos);
268
269	return (SSL_TLSEXT_ERR_OK);
270}
271
272static int
273verify_alpn(SSL *client, SSL *server)
274{
275	const unsigned char *client_proto, *server_proto;
276	unsigned int client_proto_len = 0, server_proto_len = 0;
277
278	SSL_get0_alpn_selected(client, &client_proto, &client_proto_len);
279	SSL_get0_alpn_selected(server, &server_proto, &server_proto_len);
280
281	free(alpn_selected);
282	alpn_selected = NULL;
283
284	if (client_proto_len != server_proto_len ||
285	    memcmp(client_proto, server_proto, client_proto_len) != 0) {
286		BIO_printf(bio_stdout, "ALPN selected protocols differ!\n");
287		goto err;
288	}
289
290	if (client_proto_len > 0 && alpn_expected == NULL) {
291		BIO_printf(bio_stdout, "ALPN unexpectedly negotiated\n");
292		goto err;
293	}
294
295	if (alpn_expected != NULL &&
296	    (client_proto_len != strlen(alpn_expected) ||
297	     memcmp(client_proto, alpn_expected, client_proto_len) != 0)) {
298		BIO_printf(bio_stdout, "ALPN selected protocols not equal to "
299		    "expected protocol: %s\n", alpn_expected);
300		goto err;
301	}
302
303	return (0);
304
305err:
306	BIO_printf(bio_stdout, "ALPN results: client: '");
307	BIO_write(bio_stdout, client_proto, client_proto_len);
308	BIO_printf(bio_stdout, "', server: '");
309	BIO_write(bio_stdout, server_proto, server_proto_len);
310	BIO_printf(bio_stdout, "'\n");
311	BIO_printf(bio_stdout, "ALPN configured: client: '%s', server: '%s'\n",
312	    alpn_client, alpn_server);
313
314	return (-1);
315}
316
317static char *cipher = NULL;
318static int verbose = 0;
319static int debug = 0;
320
321int doit_biopair(SSL *s_ssl, SSL *c_ssl, long bytes, clock_t *s_time,
322    clock_t *c_time);
323int doit(SSL *s_ssl, SSL *c_ssl, long bytes);
324
325static void
326sv_usage(void)
327{
328	fprintf(stderr, "usage: ssltest [args ...]\n");
329	fprintf(stderr, "\n");
330	fprintf(stderr, " -server_auth  - check server certificate\n");
331	fprintf(stderr, " -client_auth  - do client authentication\n");
332	fprintf(stderr, " -proxy        - allow proxy certificates\n");
333	fprintf(stderr, " -proxy_auth <val> - set proxy policy rights\n");
334	fprintf(stderr, " -proxy_cond <val> - experssion to test proxy policy rights\n");
335	fprintf(stderr, " -v            - more output\n");
336	fprintf(stderr, " -d            - debug output\n");
337	fprintf(stderr, " -reuse        - use session-id reuse\n");
338	fprintf(stderr, " -num <val>    - number of connections to perform\n");
339	fprintf(stderr, " -bytes <val>  - number of bytes to swap between client/server\n");
340	fprintf(stderr, " -dhe1024dsa   - use 1024 bit key (with 160-bit subprime) for DHE\n");
341	fprintf(stderr, " -no_dhe       - disable DHE\n");
342	fprintf(stderr, " -no_ecdhe     - disable ECDHE\n");
343	fprintf(stderr, " -dtls1_2      - use DTLSv1.2\n");
344	fprintf(stderr, " -tls1         - use TLSv1\n");
345	fprintf(stderr, " -tls1_2       - use TLSv1.2\n");
346	fprintf(stderr, " -CApath arg   - PEM format directory of CA's\n");
347	fprintf(stderr, " -CAfile arg   - PEM format file of CA's\n");
348	fprintf(stderr, " -cert arg     - Server certificate file\n");
349	fprintf(stderr, " -key arg      - Server key file (default: same as -cert)\n");
350	fprintf(stderr, " -c_cert arg   - Client certificate file\n");
351	fprintf(stderr, " -c_key arg    - Client key file (default: same as -c_cert)\n");
352	fprintf(stderr, " -cipher arg   - The cipher list\n");
353	fprintf(stderr, " -bio_pair     - Use BIO pairs\n");
354	fprintf(stderr, " -f            - Test even cases that can't work\n");
355	fprintf(stderr, " -time         - measure processor time used by client and server\n");
356	fprintf(stderr, " -named_curve arg  - Elliptic curve name to use for ephemeral ECDH keys.\n" \
357	               "                 Use \"openssl ecparam -list_curves\" for all names\n"  \
358	               "                 (default is sect163r2).\n");
359	fprintf(stderr, " -alpn_client <string> - have client side offer ALPN\n");
360	fprintf(stderr, " -alpn_server <string> - have server side offer ALPN\n");
361	fprintf(stderr, " -alpn_expected <string> - the ALPN protocol that should be negotiated\n");
362}
363
364static void
365print_details(SSL *c_ssl, const char *prefix)
366{
367	const SSL_CIPHER *ciph;
368	X509 *cert = NULL;
369	EVP_PKEY *pkey;
370
371	ciph = SSL_get_current_cipher(c_ssl);
372	BIO_printf(bio_stdout, "%s%s, cipher %s %s",
373	    prefix, SSL_get_version(c_ssl), SSL_CIPHER_get_version(ciph),
374	    SSL_CIPHER_get_name(ciph));
375
376	if ((cert = SSL_get_peer_certificate(c_ssl)) == NULL)
377		goto out;
378	if ((pkey = X509_get0_pubkey(cert)) == NULL)
379		goto out;
380	if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) {
381		RSA *rsa;
382
383		if ((rsa = EVP_PKEY_get0_RSA(pkey)) == NULL)
384			goto out;
385
386		BIO_printf(bio_stdout, ", %d bit RSA", RSA_bits(rsa));
387	} else if (EVP_PKEY_id(pkey) == EVP_PKEY_DSA) {
388		DSA *dsa;
389		const BIGNUM *p;
390
391		if ((dsa = EVP_PKEY_get0_DSA(pkey)) == NULL)
392			goto out;
393
394		DSA_get0_pqg(dsa, &p, NULL, NULL);
395
396		BIO_printf(bio_stdout, ", %d bit DSA", BN_num_bits(p));
397	}
398
399 out:
400	/*
401	 * The SSL API does not allow us to look at temporary RSA/DH keys,
402	 * otherwise we should print their lengths too
403	 */
404	BIO_printf(bio_stdout, "\n");
405
406	X509_free(cert);
407}
408
409int
410main(int argc, char *argv[])
411{
412	char *CApath = NULL, *CAfile = NULL;
413	int badop = 0;
414	int bio_pair = 0;
415	int force = 0;
416	int tls1 = 0, tls1_2 = 0, dtls1_2 = 0, ret = 1;
417	int client_auth = 0;
418	int server_auth = 0, i;
419	char *app_verify_arg = "Test Callback Argument";
420	char *server_cert = TEST_SERVER_CERT;
421	char *server_key = NULL;
422	char *client_cert = TEST_CLIENT_CERT;
423	char *client_key = NULL;
424	char *named_curve = NULL;
425	SSL_CTX *s_ctx = NULL;
426	SSL_CTX *c_ctx = NULL;
427	const SSL_METHOD *meth = NULL;
428	SSL *c_ssl, *s_ssl;
429	int number = 1, reuse = 0;
430	int seclevel = 0;
431	long bytes = 256L;
432	DH *dh;
433	int dhe1024dsa = 0;
434	EC_KEY *ecdh = NULL;
435	int no_dhe = 0;
436	int no_ecdhe = 0;
437	int print_time = 0;
438	clock_t s_time = 0, c_time = 0;
439
440	verbose = 0;
441	debug = 0;
442	cipher = 0;
443
444	bio_err = BIO_new_fp(stderr, BIO_NOCLOSE|BIO_FP_TEXT);
445
446	bio_stdout = BIO_new_fp(stdout, BIO_NOCLOSE|BIO_FP_TEXT);
447
448	argc--;
449	argv++;
450
451	while (argc >= 1) {
452		if (!strcmp(*argv, "-F")) {
453			fprintf(stderr, "not compiled with FIPS support, so exiting without running.\n");
454			exit(0);
455		} else if (strcmp(*argv, "-server_auth") == 0)
456			server_auth = 1;
457		else if (strcmp(*argv, "-client_auth") == 0)
458			client_auth = 1;
459		else if (strcmp(*argv, "-v") == 0)
460			verbose = 1;
461		else if (strcmp(*argv, "-d") == 0)
462			debug = 1;
463		else if (strcmp(*argv, "-reuse") == 0)
464			reuse = 1;
465		else if (strcmp(*argv, "-dhe1024dsa") == 0) {
466			dhe1024dsa = 1;
467		} else if (strcmp(*argv, "-no_dhe") == 0)
468			no_dhe = 1;
469		else if (strcmp(*argv, "-no_ecdhe") == 0)
470			no_ecdhe = 1;
471		else if (strcmp(*argv, "-dtls1_2") == 0)
472			dtls1_2 = 1;
473		else if (strcmp(*argv, "-tls1") == 0)
474			tls1 = 1;
475		else if (strcmp(*argv, "-tls1_2") == 0)
476			tls1_2 = 1;
477		else if (strncmp(*argv, "-num", 4) == 0) {
478			if (--argc < 1)
479				goto bad;
480			number = atoi(*(++argv));
481			if (number == 0)
482				number = 1;
483		} else if (strncmp(*argv, "-seclevel", 9) == 0) {
484			if (--argc < 1)
485				goto bad;
486			seclevel = atoi(*(++argv));
487		} else if (strcmp(*argv, "-bytes") == 0) {
488			if (--argc < 1)
489				goto bad;
490			bytes = atol(*(++argv));
491			if (bytes == 0L)
492				bytes = 1L;
493			i = strlen(argv[0]);
494			if (argv[0][i - 1] == 'k')
495				bytes*=1024L;
496			if (argv[0][i - 1] == 'm')
497				bytes*=1024L*1024L;
498		} else if (strcmp(*argv, "-cert") == 0) {
499			if (--argc < 1)
500				goto bad;
501			server_cert= *(++argv);
502		} else if (strcmp(*argv, "-s_cert") == 0) {
503			if (--argc < 1)
504				goto bad;
505			server_cert= *(++argv);
506		} else if (strcmp(*argv, "-key") == 0) {
507			if (--argc < 1)
508				goto bad;
509			server_key= *(++argv);
510		} else if (strcmp(*argv, "-s_key") == 0) {
511			if (--argc < 1)
512				goto bad;
513			server_key= *(++argv);
514		} else if (strcmp(*argv, "-c_cert") == 0) {
515			if (--argc < 1)
516				goto bad;
517			client_cert= *(++argv);
518		} else if (strcmp(*argv, "-c_key") == 0) {
519			if (--argc < 1)
520				goto bad;
521			client_key= *(++argv);
522		} else if (strcmp(*argv, "-cipher") == 0) {
523			if (--argc < 1)
524				goto bad;
525			cipher= *(++argv);
526		} else if (strcmp(*argv, "-CApath") == 0) {
527			if (--argc < 1)
528				goto bad;
529			CApath= *(++argv);
530		} else if (strcmp(*argv, "-CAfile") == 0) {
531			if (--argc < 1)
532				goto bad;
533			CAfile= *(++argv);
534		} else if (strcmp(*argv, "-bio_pair") == 0) {
535			bio_pair = 1;
536		} else if (strcmp(*argv, "-f") == 0) {
537			force = 1;
538		} else if (strcmp(*argv, "-time") == 0) {
539			print_time = 1;
540		} else if (strcmp(*argv, "-named_curve") == 0) {
541			if (--argc < 1)
542				goto bad;
543			named_curve = *(++argv);
544		} else if (strcmp(*argv, "-app_verify") == 0) {
545			;
546		} else if (strcmp(*argv, "-alpn_client") == 0) {
547			if (--argc < 1)
548				goto bad;
549			alpn_client = *(++argv);
550		} else if (strcmp(*argv, "-alpn_server") == 0) {
551			if (--argc < 1)
552				goto bad;
553			alpn_server = *(++argv);
554		} else if (strcmp(*argv, "-alpn_expected") == 0) {
555			if (--argc < 1)
556				goto bad;
557			alpn_expected = *(++argv);
558		} else {
559			fprintf(stderr, "unknown option %s\n", *argv);
560			badop = 1;
561			break;
562		}
563		argc--;
564		argv++;
565	}
566	if (badop) {
567bad:
568		sv_usage();
569		goto end;
570	}
571
572	if (!dtls1_2 && !tls1 && !tls1_2 && number > 1 && !reuse && !force) {
573		fprintf(stderr,
574		    "This case cannot work.  Use -f to perform "
575		    "the test anyway (and\n-d to see what happens), "
576		    "or add one of -dtls1, -tls1, -tls1_2, -reuse\n"
577		    "to avoid protocol mismatch.\n");
578		exit(1);
579	}
580
581	if (print_time) {
582		if (!bio_pair) {
583			fprintf(stderr, "Using BIO pair (-bio_pair)\n");
584			bio_pair = 1;
585		}
586		if (number < 50 && !force)
587			fprintf(stderr, "Warning: For accurate timings, use more connections (e.g. -num 1000)\n");
588	}
589
590/*	if (cipher == NULL) cipher=getenv("SSL_CIPHER"); */
591
592	SSL_library_init();
593	SSL_load_error_strings();
594
595	if (dtls1_2)
596		meth = DTLSv1_2_method();
597	else if (tls1)
598		meth = TLSv1_method();
599	else if (tls1_2)
600		meth = TLSv1_2_method();
601	else
602		meth = TLS_method();
603
604	c_ctx = SSL_CTX_new(meth);
605	s_ctx = SSL_CTX_new(meth);
606	if ((c_ctx == NULL) || (s_ctx == NULL)) {
607		ERR_print_errors(bio_err);
608		goto end;
609	}
610
611	SSL_CTX_set_security_level(c_ctx, seclevel);
612	SSL_CTX_set_security_level(s_ctx, seclevel);
613
614	if (cipher != NULL) {
615		SSL_CTX_set_cipher_list(c_ctx, cipher);
616		SSL_CTX_set_cipher_list(s_ctx, cipher);
617	}
618
619	if (!no_dhe) {
620		if (dhe1024dsa) {
621			/* use SSL_OP_SINGLE_DH_USE to avoid small subgroup attacks */
622			SSL_CTX_set_options(s_ctx, SSL_OP_SINGLE_DH_USE);
623			dh = get_dh1024dsa();
624		} else
625			dh = get_dh1024();
626		SSL_CTX_set_tmp_dh(s_ctx, dh);
627		DH_free(dh);
628	}
629
630	if (!no_ecdhe) {
631		int nid;
632
633		if (named_curve != NULL) {
634			nid = OBJ_sn2nid(named_curve);
635			if (nid == 0) {
636				BIO_printf(bio_err, "unknown curve name (%s)\n", named_curve);
637				goto end;
638			}
639		} else
640			nid = NID_X9_62_prime256v1;
641
642		ecdh = EC_KEY_new_by_curve_name(nid);
643		if (ecdh == NULL) {
644			BIO_printf(bio_err, "unable to create curve\n");
645			goto end;
646		}
647
648		SSL_CTX_set_tmp_ecdh(s_ctx, ecdh);
649		SSL_CTX_set_options(s_ctx, SSL_OP_SINGLE_ECDH_USE);
650		EC_KEY_free(ecdh);
651	}
652
653	if (!SSL_CTX_use_certificate_chain_file(s_ctx, server_cert)) {
654		ERR_print_errors(bio_err);
655	} else if (!SSL_CTX_use_PrivateKey_file(s_ctx,
656	    (server_key ? server_key : server_cert), SSL_FILETYPE_PEM)) {
657		ERR_print_errors(bio_err);
658		goto end;
659	}
660
661	if (client_auth) {
662		SSL_CTX_use_certificate_chain_file(c_ctx, client_cert);
663		SSL_CTX_use_PrivateKey_file(c_ctx,
664		    (client_key ? client_key : client_cert),
665		    SSL_FILETYPE_PEM);
666	}
667
668	if ((!SSL_CTX_load_verify_locations(s_ctx, CAfile, CApath)) ||
669	    (!SSL_CTX_set_default_verify_paths(s_ctx)) ||
670	    (!SSL_CTX_load_verify_locations(c_ctx, CAfile, CApath)) ||
671	    (!SSL_CTX_set_default_verify_paths(c_ctx))) {
672		/* fprintf(stderr,"SSL_load_verify_locations\n"); */
673		ERR_print_errors(bio_err);
674		/* goto end; */
675	}
676
677	if (client_auth) {
678		BIO_printf(bio_err, "client authentication\n");
679		SSL_CTX_set_verify(s_ctx,
680		    SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
681		    verify_callback);
682		SSL_CTX_set_cert_verify_callback(s_ctx, app_verify_callback,
683		    app_verify_arg);
684	}
685	if (server_auth) {
686		BIO_printf(bio_err, "server authentication\n");
687		SSL_CTX_set_verify(c_ctx, SSL_VERIFY_PEER,
688		    verify_callback);
689		SSL_CTX_set_cert_verify_callback(c_ctx, app_verify_callback,
690		    app_verify_arg);
691	}
692
693	{
694		int session_id_context = 0;
695		SSL_CTX_set_session_id_context(s_ctx,
696		    (void *)&session_id_context, sizeof(session_id_context));
697	}
698
699	if (alpn_server != NULL)
700		SSL_CTX_set_alpn_select_cb(s_ctx, cb_server_alpn, NULL);
701
702	if (alpn_client != NULL) {
703		unsigned short alpn_len;
704		unsigned char *alpn = next_protos_parse(&alpn_len, alpn_client);
705
706		if (alpn == NULL) {
707			BIO_printf(bio_err, "Error parsing -alpn_client argument\n");
708			goto end;
709		}
710		SSL_CTX_set_alpn_protos(c_ctx, alpn, alpn_len);
711		free(alpn);
712	}
713
714	c_ssl = SSL_new(c_ctx);
715	s_ssl = SSL_new(s_ctx);
716
717	for (i = 0; i < number; i++) {
718		if (!reuse)
719			SSL_set_session(c_ssl, NULL);
720#ifdef USE_BIOPAIR
721		if (bio_pair)
722			ret = doit_biopair(s_ssl, c_ssl, bytes, &s_time,
723			    &c_time);
724		else
725#endif
726			ret = doit(s_ssl, c_ssl, bytes);
727	}
728
729	if (!verbose) {
730		print_details(c_ssl, "");
731	}
732	if ((number > 1) || (bytes > 1L))
733		BIO_printf(bio_stdout, "%d handshakes of %ld bytes done\n",
734		    number, bytes);
735	if (print_time) {
736#ifdef CLOCKS_PER_SEC
737		/* "To determine the time in seconds, the value returned
738		 * by the clock function should be divided by the value
739		 * of the macro CLOCKS_PER_SEC."
740		 *                                       -- ISO/IEC 9899 */
741		BIO_printf(bio_stdout,
742		    "Approximate total server time: %6.2f s\n"
743		    "Approximate total client time: %6.2f s\n",
744		    (double)s_time/CLOCKS_PER_SEC,
745		    (double)c_time/CLOCKS_PER_SEC);
746#else
747		/* "`CLOCKS_PER_SEC' undeclared (first use this function)"
748		 *                            -- cc on NeXTstep/OpenStep */
749		BIO_printf(bio_stdout,
750		    "Approximate total server time: %6.2f units\n"
751		    "Approximate total client time: %6.2f units\n",
752		    (double)s_time,
753		    (double)c_time);
754#endif
755	}
756
757	SSL_free(s_ssl);
758	SSL_free(c_ssl);
759
760end:
761	SSL_CTX_free(s_ctx);
762	SSL_CTX_free(c_ctx);
763	BIO_free(bio_stdout);
764
765#ifndef OPENSSL_NO_ENGINE
766	ENGINE_cleanup();
767#endif
768	CRYPTO_cleanup_all_ex_data();
769	ERR_free_strings();
770	ERR_remove_thread_state(NULL);
771	EVP_cleanup();
772	CRYPTO_mem_leaks(bio_err);
773	BIO_free(bio_err);
774
775	exit(ret);
776	return ret;
777}
778
779#if USE_BIOPAIR
780int
781doit_biopair(SSL *s_ssl, SSL *c_ssl, long count, clock_t *s_time,
782    clock_t *c_time)
783{
784	long cw_num = count, cr_num = count, sw_num = count, sr_num = count;
785	BIO *s_ssl_bio = NULL, *c_ssl_bio = NULL;
786	BIO *server = NULL, *server_io = NULL;
787	BIO *client = NULL, *client_io = NULL;
788	int ret = 1;
789
790	size_t bufsiz = 256; /* small buffer for testing */
791
792	if (!BIO_new_bio_pair(&server, bufsiz, &server_io, bufsiz))
793		goto err;
794	if (!BIO_new_bio_pair(&client, bufsiz, &client_io, bufsiz))
795		goto err;
796
797	s_ssl_bio = BIO_new(BIO_f_ssl());
798	if (!s_ssl_bio)
799		goto err;
800
801	c_ssl_bio = BIO_new(BIO_f_ssl());
802	if (!c_ssl_bio)
803		goto err;
804
805	SSL_set_connect_state(c_ssl);
806	SSL_set_bio(c_ssl, client, client);
807	(void)BIO_set_ssl(c_ssl_bio, c_ssl, BIO_NOCLOSE);
808
809	SSL_set_accept_state(s_ssl);
810	SSL_set_bio(s_ssl, server, server);
811	(void)BIO_set_ssl(s_ssl_bio, s_ssl, BIO_NOCLOSE);
812
813	do {
814		/* c_ssl_bio:          SSL filter BIO
815		 *
816		 * client:             pseudo-I/O for SSL library
817		 *
818		 * client_io:          client's SSL communication; usually to be
819		 *                     relayed over some I/O facility, but in this
820		 *                     test program, we're the server, too:
821		 *
822		 * server_io:          server's SSL communication
823		 *
824		 * server:             pseudo-I/O for SSL library
825		 *
826		 * s_ssl_bio:          SSL filter BIO
827		 *
828		 * The client and the server each employ a "BIO pair":
829		 * client + client_io, server + server_io.
830		 * BIO pairs are symmetric.  A BIO pair behaves similar
831		 * to a non-blocking socketpair (but both endpoints must
832		 * be handled by the same thread).
833		 * [Here we could connect client and server to the ends
834		 * of a single BIO pair, but then this code would be less
835		 * suitable as an example for BIO pairs in general.]
836		 *
837		 * Useful functions for querying the state of BIO pair endpoints:
838		 *
839		 * BIO_ctrl_pending(bio)              number of bytes we can read now
840		 * BIO_ctrl_get_read_request(bio)     number of bytes needed to fulfil
841		 *                                      other side's read attempt
842		 * BIO_ctrl_get_write_guarantee(bio)   number of bytes we can write now
843		 *
844		 * ..._read_request is never more than ..._write_guarantee;
845		 * it depends on the application which one you should use.
846		 */
847
848		/* We have non-blocking behaviour throughout this test program, but
849		 * can be sure that there is *some* progress in each iteration; so
850		 * we don't have to worry about ..._SHOULD_READ or ..._SHOULD_WRITE
851		 * -- we just try everything in each iteration
852		 */
853
854		{
855			/* CLIENT */
856
857			char cbuf[1024*8];
858			int i, r;
859			clock_t c_clock = clock();
860
861			memset(cbuf, 0, sizeof(cbuf));
862
863			if (debug)
864				if (SSL_in_init(c_ssl))
865					printf("client waiting in SSL_connect - %s\n",
866					    SSL_state_string_long(c_ssl));
867
868			if (cw_num > 0) {
869				/* Write to server. */
870
871				if (cw_num > (long)sizeof cbuf)
872					i = sizeof cbuf;
873				else
874					i = (int)cw_num;
875				r = BIO_write(c_ssl_bio, cbuf, i);
876				if (r < 0) {
877					if (!BIO_should_retry(c_ssl_bio)) {
878						fprintf(stderr, "ERROR in CLIENT\n");
879						goto err;
880					}
881					/* BIO_should_retry(...) can just be ignored here.
882					 * The library expects us to call BIO_write with
883					 * the same arguments again, and that's what we will
884					 * do in the next iteration. */
885				} else if (r == 0) {
886					fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
887					goto err;
888				} else {
889					if (debug)
890						printf("client wrote %d\n", r);
891					cw_num -= r;
892
893				}
894			}
895
896			if (cr_num > 0) {
897				/* Read from server. */
898
899				r = BIO_read(c_ssl_bio, cbuf, sizeof(cbuf));
900				if (r < 0) {
901					if (!BIO_should_retry(c_ssl_bio)) {
902						fprintf(stderr, "ERROR in CLIENT\n");
903						goto err;
904					}
905					/* Again, "BIO_should_retry" can be ignored. */
906				} else if (r == 0) {
907					fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
908					goto err;
909				} else {
910					if (debug)
911						printf("client read %d\n", r);
912					cr_num -= r;
913				}
914			}
915
916			/* c_time and s_time increments will typically be very small
917			 * (depending on machine speed and clock tick intervals),
918			 * but sampling over a large number of connections should
919			 * result in fairly accurate figures.  We cannot guarantee
920			 * a lot, however -- if each connection lasts for exactly
921			 * one clock tick, it will be counted only for the client
922			 * or only for the server or even not at all.
923			 */
924			*c_time += (clock() - c_clock);
925		}
926
927		{
928			/* SERVER */
929
930			char sbuf[1024*8];
931			int i, r;
932			clock_t s_clock = clock();
933
934			memset(sbuf, 0, sizeof(sbuf));
935
936			if (debug)
937				if (SSL_in_init(s_ssl))
938					printf("server waiting in SSL_accept - %s\n",
939					    SSL_state_string_long(s_ssl));
940
941			if (sw_num > 0) {
942				/* Write to client. */
943
944				if (sw_num > (long)sizeof sbuf)
945					i = sizeof sbuf;
946				else
947					i = (int)sw_num;
948				r = BIO_write(s_ssl_bio, sbuf, i);
949				if (r < 0) {
950					if (!BIO_should_retry(s_ssl_bio)) {
951						fprintf(stderr, "ERROR in SERVER\n");
952						goto err;
953					}
954					/* Ignore "BIO_should_retry". */
955				} else if (r == 0) {
956					fprintf(stderr, "SSL SERVER STARTUP FAILED\n");
957					goto err;
958				} else {
959					if (debug)
960						printf("server wrote %d\n", r);
961					sw_num -= r;
962
963				}
964			}
965
966			if (sr_num > 0) {
967				/* Read from client. */
968
969				r = BIO_read(s_ssl_bio, sbuf, sizeof(sbuf));
970				if (r < 0) {
971					if (!BIO_should_retry(s_ssl_bio)) {
972						fprintf(stderr, "ERROR in SERVER\n");
973						goto err;
974					}
975					/* blah, blah */
976				} else if (r == 0) {
977					fprintf(stderr, "SSL SERVER STARTUP FAILED\n");
978					goto err;
979				} else {
980					if (debug)
981						printf("server read %d\n", r);
982					sr_num -= r;
983				}
984			}
985
986			*s_time += (clock() - s_clock);
987		}
988
989		{
990			/* "I/O" BETWEEN CLIENT AND SERVER. */
991
992			size_t r1, r2;
993			BIO *io1 = server_io, *io2 = client_io;
994			/* we use the non-copying interface for io1
995			 * and the standard BIO_write/BIO_read interface for io2
996			 */
997
998			static int prev_progress = 1;
999			int progress = 0;
1000
1001			/* io1 to io2 */
1002			do {
1003				size_t num;
1004				int r;
1005
1006				r1 = BIO_ctrl_pending(io1);
1007				r2 = BIO_ctrl_get_write_guarantee(io2);
1008
1009				num = r1;
1010				if (r2 < num)
1011					num = r2;
1012				if (num) {
1013					char *dataptr;
1014
1015					if (INT_MAX < num) /* yeah, right */
1016						num = INT_MAX;
1017
1018					r = BIO_nread(io1, &dataptr, (int)num);
1019					assert(r > 0);
1020					assert(r <= (int)num);
1021					/* possibly r < num (non-contiguous data) */
1022					num = r;
1023					r = BIO_write(io2, dataptr, (int)num);
1024					if (r != (int)num) /* can't happen */
1025					{
1026						fprintf(stderr, "ERROR: BIO_write could not write "
1027						    "BIO_ctrl_get_write_guarantee() bytes");
1028						goto err;
1029					}
1030					progress = 1;
1031
1032					if (debug)
1033						printf((io1 == client_io) ?
1034						    "C->S relaying: %d bytes\n" :
1035						    "S->C relaying: %d bytes\n",
1036						    (int)num);
1037				}
1038			} while (r1 && r2);
1039
1040			/* io2 to io1 */
1041			{
1042				size_t num;
1043				int r;
1044
1045				r1 = BIO_ctrl_pending(io2);
1046				r2 = BIO_ctrl_get_read_request(io1);
1047				/* here we could use ..._get_write_guarantee instead of
1048				 * ..._get_read_request, but by using the latter
1049				 * we test restartability of the SSL implementation
1050				 * more thoroughly */
1051				num = r1;
1052				if (r2 < num)
1053					num = r2;
1054				if (num) {
1055					char *dataptr;
1056
1057					if (INT_MAX < num)
1058						num = INT_MAX;
1059
1060					if (num > 1)
1061						--num; /* test restartability even more thoroughly */
1062
1063					r = BIO_nwrite0(io1, &dataptr);
1064					assert(r > 0);
1065					if (r < (int)num)
1066						num = r;
1067					r = BIO_read(io2, dataptr, (int)num);
1068					if (r != (int)num) /* can't happen */
1069					{
1070						fprintf(stderr, "ERROR: BIO_read could not read "
1071						    "BIO_ctrl_pending() bytes");
1072						goto err;
1073					}
1074					progress = 1;
1075					r = BIO_nwrite(io1, &dataptr, (int)num);
1076					if (r != (int)num) /* can't happen */
1077					{
1078						fprintf(stderr, "ERROR: BIO_nwrite() did not accept "
1079						    "BIO_nwrite0() bytes");
1080						goto err;
1081					}
1082
1083					if (debug)
1084						printf((io2 == client_io) ?
1085						    "C->S relaying: %d bytes\n" :
1086						    "S->C relaying: %d bytes\n",
1087						    (int)num);
1088				}
1089			} /* no loop, BIO_ctrl_get_read_request now returns 0 anyway */
1090
1091			if (!progress && !prev_progress) {
1092				if (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0) {
1093					fprintf(stderr, "ERROR: got stuck\n");
1094					goto err;
1095				}
1096			}
1097			prev_progress = progress;
1098		}
1099	} while (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0);
1100
1101	if (verbose)
1102		print_details(c_ssl, "DONE via BIO pair: ");
1103
1104	if (verify_alpn(c_ssl, s_ssl) < 0) {
1105		ret = 1;
1106		goto err;
1107	}
1108
1109	ret = 0;
1110
1111err:
1112	ERR_print_errors(bio_err);
1113
1114	BIO_free(server);
1115	BIO_free(server_io);
1116	BIO_free(client);
1117	BIO_free(client_io);
1118	BIO_free(s_ssl_bio);
1119	BIO_free(c_ssl_bio);
1120
1121	return ret;
1122}
1123#endif
1124
1125
1126#define W_READ	1
1127#define W_WRITE	2
1128#define C_DONE	1
1129#define S_DONE	2
1130
1131int
1132doit(SSL *s_ssl, SSL *c_ssl, long count)
1133{
1134	char cbuf[1024*8], sbuf[1024*8];
1135	long cw_num = count, cr_num = count;
1136	long sw_num = count, sr_num = count;
1137	int ret = 1;
1138	BIO *c_to_s = NULL;
1139	BIO *s_to_c = NULL;
1140	BIO *c_bio = NULL;
1141	BIO *s_bio = NULL;
1142	int c_r, c_w, s_r, s_w;
1143	int i, j;
1144	int done = 0;
1145	int c_write, s_write;
1146	int do_server = 0, do_client = 0;
1147
1148	memset(cbuf, 0, sizeof(cbuf));
1149	memset(sbuf, 0, sizeof(sbuf));
1150
1151	c_to_s = BIO_new(BIO_s_mem());
1152	s_to_c = BIO_new(BIO_s_mem());
1153	if ((s_to_c == NULL) || (c_to_s == NULL)) {
1154		ERR_print_errors(bio_err);
1155		goto err;
1156	}
1157
1158	c_bio = BIO_new(BIO_f_ssl());
1159	s_bio = BIO_new(BIO_f_ssl());
1160	if ((c_bio == NULL) || (s_bio == NULL)) {
1161		ERR_print_errors(bio_err);
1162		goto err;
1163	}
1164
1165	SSL_set_connect_state(c_ssl);
1166	SSL_set_bio(c_ssl, s_to_c, c_to_s);
1167	BIO_set_ssl(c_bio, c_ssl, BIO_NOCLOSE);
1168
1169	SSL_set_accept_state(s_ssl);
1170	SSL_set_bio(s_ssl, c_to_s, s_to_c);
1171	BIO_set_ssl(s_bio, s_ssl, BIO_NOCLOSE);
1172
1173	c_r = 0;
1174	s_r = 1;
1175	c_w = 1;
1176	s_w = 0;
1177	c_write = 1, s_write = 0;
1178
1179	/* We can always do writes */
1180	for (;;) {
1181		do_server = 0;
1182		do_client = 0;
1183
1184		i = (int)BIO_pending(s_bio);
1185		if ((i && s_r) || s_w)
1186			do_server = 1;
1187
1188		i = (int)BIO_pending(c_bio);
1189		if ((i && c_r) || c_w)
1190			do_client = 1;
1191
1192		if (do_server && debug) {
1193			if (SSL_in_init(s_ssl))
1194				printf("server waiting in SSL_accept - %s\n",
1195				    SSL_state_string_long(s_ssl));
1196		}
1197
1198		if (do_client && debug) {
1199			if (SSL_in_init(c_ssl))
1200				printf("client waiting in SSL_connect - %s\n",
1201				    SSL_state_string_long(c_ssl));
1202		}
1203
1204		if (!do_client && !do_server) {
1205			fprintf(stdout, "ERROR in STARTUP\n");
1206			ERR_print_errors(bio_err);
1207			goto err;
1208		}
1209
1210		if (do_client && !(done & C_DONE)) {
1211			if (c_write) {
1212				j = (cw_num > (long)sizeof(cbuf)) ?
1213				    (int)sizeof(cbuf) : (int)cw_num;
1214				i = BIO_write(c_bio, cbuf, j);
1215				if (i < 0) {
1216					c_r = 0;
1217					c_w = 0;
1218					if (BIO_should_retry(c_bio)) {
1219						if (BIO_should_read(c_bio))
1220							c_r = 1;
1221						if (BIO_should_write(c_bio))
1222							c_w = 1;
1223					} else {
1224						fprintf(stderr, "ERROR in CLIENT\n");
1225						ERR_print_errors(bio_err);
1226						goto err;
1227					}
1228				} else if (i == 0) {
1229					fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
1230					goto err;
1231				} else {
1232					if (debug)
1233						printf("client wrote %d\n", i);
1234					/* ok */
1235					s_r = 1;
1236					c_write = 0;
1237					cw_num -= i;
1238				}
1239			} else {
1240				i = BIO_read(c_bio, cbuf, sizeof(cbuf));
1241				if (i < 0) {
1242					c_r = 0;
1243					c_w = 0;
1244					if (BIO_should_retry(c_bio)) {
1245						if (BIO_should_read(c_bio))
1246							c_r = 1;
1247						if (BIO_should_write(c_bio))
1248							c_w = 1;
1249					} else {
1250						fprintf(stderr, "ERROR in CLIENT\n");
1251						ERR_print_errors(bio_err);
1252						goto err;
1253					}
1254				} else if (i == 0) {
1255					fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
1256					goto err;
1257				} else {
1258					if (debug)
1259						printf("client read %d\n", i);
1260					cr_num -= i;
1261					if (sw_num > 0) {
1262						s_write = 1;
1263						s_w = 1;
1264					}
1265					if (cr_num <= 0) {
1266						s_write = 1;
1267						s_w = 1;
1268						done = S_DONE|C_DONE;
1269					}
1270				}
1271			}
1272		}
1273
1274		if (do_server && !(done & S_DONE)) {
1275			if (!s_write) {
1276				i = BIO_read(s_bio, sbuf, sizeof(cbuf));
1277				if (i < 0) {
1278					s_r = 0;
1279					s_w = 0;
1280					if (BIO_should_retry(s_bio)) {
1281						if (BIO_should_read(s_bio))
1282							s_r = 1;
1283						if (BIO_should_write(s_bio))
1284							s_w = 1;
1285					} else {
1286						fprintf(stderr, "ERROR in SERVER\n");
1287						ERR_print_errors(bio_err);
1288						goto err;
1289					}
1290				} else if (i == 0) {
1291					ERR_print_errors(bio_err);
1292					fprintf(stderr, "SSL SERVER STARTUP FAILED in SSL_read\n");
1293					goto err;
1294				} else {
1295					if (debug)
1296						printf("server read %d\n", i);
1297					sr_num -= i;
1298					if (cw_num > 0) {
1299						c_write = 1;
1300						c_w = 1;
1301					}
1302					if (sr_num <= 0) {
1303						s_write = 1;
1304						s_w = 1;
1305						c_write = 0;
1306					}
1307				}
1308			} else {
1309				j = (sw_num > (long)sizeof(sbuf)) ?
1310				    (int)sizeof(sbuf) : (int)sw_num;
1311				i = BIO_write(s_bio, sbuf, j);
1312				if (i < 0) {
1313					s_r = 0;
1314					s_w = 0;
1315					if (BIO_should_retry(s_bio)) {
1316						if (BIO_should_read(s_bio))
1317							s_r = 1;
1318						if (BIO_should_write(s_bio))
1319							s_w = 1;
1320					} else {
1321						fprintf(stderr, "ERROR in SERVER\n");
1322						ERR_print_errors(bio_err);
1323						goto err;
1324					}
1325				} else if (i == 0) {
1326					ERR_print_errors(bio_err);
1327					fprintf(stderr, "SSL SERVER STARTUP FAILED in SSL_write\n");
1328					goto err;
1329				} else {
1330					if (debug)
1331						printf("server wrote %d\n", i);
1332					sw_num -= i;
1333					s_write = 0;
1334					c_r = 1;
1335					if (sw_num <= 0)
1336						done |= S_DONE;
1337				}
1338			}
1339		}
1340
1341		if ((done & S_DONE) && (done & C_DONE))
1342			break;
1343	}
1344
1345	if (verbose)
1346		print_details(c_ssl, "DONE: ");
1347
1348	if (verify_alpn(c_ssl, s_ssl) < 0) {
1349		ret = 1;
1350		goto err;
1351	}
1352
1353	ret = 0;
1354err:
1355	/* We have to set the BIO's to NULL otherwise they will be
1356	 * free()ed twice.  Once when th s_ssl is SSL_free()ed and
1357	 * again when c_ssl is SSL_free()ed.
1358	 * This is a hack required because s_ssl and c_ssl are sharing the same
1359	 * BIO structure and SSL_set_bio() and SSL_free() automatically
1360	 * BIO_free non NULL entries.
1361	 * You should not normally do this or be required to do this */
1362	if (s_ssl != NULL) {
1363		s_ssl->rbio = NULL;
1364		s_ssl->wbio = NULL;
1365	}
1366	if (c_ssl != NULL) {
1367		c_ssl->rbio = NULL;
1368		c_ssl->wbio = NULL;
1369	}
1370
1371	BIO_free(c_to_s);
1372	BIO_free(s_to_c);
1373	BIO_free_all(c_bio);
1374	BIO_free_all(s_bio);
1375
1376	return (ret);
1377}
1378
1379static int
1380verify_callback(int ok, X509_STORE_CTX *ctx)
1381{
1382	X509 *xs;
1383	char *s, buf[256];
1384	int error, error_depth;
1385
1386	xs = X509_STORE_CTX_get_current_cert(ctx);
1387	s = X509_NAME_oneline(X509_get_subject_name(xs), buf, sizeof buf);
1388	error = X509_STORE_CTX_get_error(ctx);
1389	error_depth = X509_STORE_CTX_get_error_depth(ctx);
1390	if (s != NULL) {
1391		if (ok)
1392			fprintf(stderr, "depth=%d %s\n", error_depth, buf);
1393		else {
1394			fprintf(stderr, "depth=%d error=%d %s\n", error_depth,
1395			    error, buf);
1396		}
1397	}
1398
1399	if (ok == 0) {
1400		fprintf(stderr, "Error string: %s\n",
1401		    X509_verify_cert_error_string(error));
1402		switch (error) {
1403		case X509_V_ERR_CERT_NOT_YET_VALID:
1404		case X509_V_ERR_CERT_HAS_EXPIRED:
1405		case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1406			fprintf(stderr, "  ... ignored.\n");
1407			ok = 1;
1408		}
1409	}
1410
1411	return (ok);
1412}
1413
1414static int
1415app_verify_callback(X509_STORE_CTX *ctx, void *arg)
1416{
1417	X509 *xs;
1418	char *s = NULL, buf[256];
1419	const char *cb_arg = arg;
1420
1421	xs = X509_STORE_CTX_get0_cert(ctx);
1422	fprintf(stderr, "In app_verify_callback, allowing cert. ");
1423	fprintf(stderr, "Arg is: %s\n", cb_arg);
1424	fprintf(stderr, "Finished printing do we have a context? 0x%p a cert? 0x%p\n",
1425	    (void *)ctx, (void *)xs);
1426	if (xs)
1427		s = X509_NAME_oneline(X509_get_subject_name(xs), buf, 256);
1428	if (s != NULL) {
1429		fprintf(stderr, "cert depth=%d %s\n",
1430		    X509_STORE_CTX_get_error_depth(ctx), buf);
1431	}
1432
1433	return 1;
1434}
1435
1436/* These DH parameters have been generated as follows:
1437 *    $ openssl dhparam -C -noout 1024
1438 *    $ openssl dhparam -C -noout -dsaparam 1024
1439 * (The second function has been renamed to avoid name conflicts.)
1440 */
1441static DH *
1442get_dh1024(void)
1443{
1444	static unsigned char dh1024_p[] = {
1445		0xF8, 0x81, 0x89, 0x7D, 0x14, 0x24, 0xC5, 0xD1, 0xE6, 0xF7, 0xBF, 0x3A,
1446		0xE4, 0x90, 0xF4, 0xFC, 0x73, 0xFB, 0x34, 0xB5, 0xFA, 0x4C, 0x56, 0xA2,
1447		0xEA, 0xA7, 0xE9, 0xC0, 0xC0, 0xCE, 0x89, 0xE1, 0xFA, 0x63, 0x3F, 0xB0,
1448		0x6B, 0x32, 0x66, 0xF1, 0xD1, 0x7B, 0xB0, 0x00, 0x8F, 0xCA, 0x87, 0xC2,
1449		0xAE, 0x98, 0x89, 0x26, 0x17, 0xC2, 0x05, 0xD2, 0xEC, 0x08, 0xD0, 0x8C,
1450		0xFF, 0x17, 0x52, 0x8C, 0xC5, 0x07, 0x93, 0x03, 0xB1, 0xF6, 0x2F, 0xB8,
1451		0x1C, 0x52, 0x47, 0x27, 0x1B, 0xDB, 0xD1, 0x8D, 0x9D, 0x69, 0x1D, 0x52,
1452		0x4B, 0x32, 0x81, 0xAA, 0x7F, 0x00, 0xC8, 0xDC, 0xE6, 0xD9, 0xCC, 0xC1,
1453		0x11, 0x2D, 0x37, 0x34, 0x6C, 0xEA, 0x02, 0x97, 0x4B, 0x0E, 0xBB, 0xB1,
1454		0x71, 0x33, 0x09, 0x15, 0xFD, 0xDD, 0x23, 0x87, 0x07, 0x5E, 0x89, 0xAB,
1455		0x6B, 0x7C, 0x5F, 0xEC, 0xA6, 0x24, 0xDC, 0x53,
1456	};
1457	static unsigned char dh1024_g[] = {
1458		0x02,
1459	};
1460	DH *dh;
1461	BIGNUM *dh_p = NULL, *dh_g = NULL;
1462
1463	if ((dh = DH_new()) == NULL)
1464		return NULL;
1465
1466	dh_p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
1467	dh_g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
1468	if (dh_p == NULL || dh_g == NULL)
1469		goto err;
1470
1471	if (!DH_set0_pqg(dh, dh_p, NULL, dh_g))
1472		goto err;
1473
1474	return dh;
1475
1476 err:
1477	BN_free(dh_p);
1478	BN_free(dh_g);
1479	DH_free(dh);
1480	return NULL;
1481}
1482
1483static DH *
1484get_dh1024dsa(void)
1485{
1486	static unsigned char dh1024_p[] = {
1487		0xC8, 0x00, 0xF7, 0x08, 0x07, 0x89, 0x4D, 0x90, 0x53, 0xF3, 0xD5, 0x00,
1488		0x21, 0x1B, 0xF7, 0x31, 0xA6, 0xA2, 0xDA, 0x23, 0x9A, 0xC7, 0x87, 0x19,
1489		0x3B, 0x47, 0xB6, 0x8C, 0x04, 0x6F, 0xFF, 0xC6, 0x9B, 0xB8, 0x65, 0xD2,
1490		0xC2, 0x5F, 0x31, 0x83, 0x4A, 0xA7, 0x5F, 0x2F, 0x88, 0x38, 0xB6, 0x55,
1491		0xCF, 0xD9, 0x87, 0x6D, 0x6F, 0x9F, 0xDA, 0xAC, 0xA6, 0x48, 0xAF, 0xFC,
1492		0x33, 0x84, 0x37, 0x5B, 0x82, 0x4A, 0x31, 0x5D, 0xE7, 0xBD, 0x52, 0x97,
1493		0xA1, 0x77, 0xBF, 0x10, 0x9E, 0x37, 0xEA, 0x64, 0xFA, 0xCA, 0x28, 0x8D,
1494		0x9D, 0x3B, 0xD2, 0x6E, 0x09, 0x5C, 0x68, 0xC7, 0x45, 0x90, 0xFD, 0xBB,
1495		0x70, 0xC9, 0x3A, 0xBB, 0xDF, 0xD4, 0x21, 0x0F, 0xC4, 0x6A, 0x3C, 0xF6,
1496		0x61, 0xCF, 0x3F, 0xD6, 0x13, 0xF1, 0x5F, 0xBC, 0xCF, 0xBC, 0x26, 0x9E,
1497		0xBC, 0x0B, 0xBD, 0xAB, 0x5D, 0xC9, 0x54, 0x39,
1498	};
1499	static unsigned char dh1024_g[] = {
1500		0x3B, 0x40, 0x86, 0xE7, 0xF3, 0x6C, 0xDE, 0x67, 0x1C, 0xCC, 0x80, 0x05,
1501		0x5A, 0xDF, 0xFE, 0xBD, 0x20, 0x27, 0x74, 0x6C, 0x24, 0xC9, 0x03, 0xF3,
1502		0xE1, 0x8D, 0xC3, 0x7D, 0x98, 0x27, 0x40, 0x08, 0xB8, 0x8C, 0x6A, 0xE9,
1503		0xBB, 0x1A, 0x3A, 0xD6, 0x86, 0x83, 0x5E, 0x72, 0x41, 0xCE, 0x85, 0x3C,
1504		0xD2, 0xB3, 0xFC, 0x13, 0xCE, 0x37, 0x81, 0x9E, 0x4C, 0x1C, 0x7B, 0x65,
1505		0xD3, 0xE6, 0xA6, 0x00, 0xF5, 0x5A, 0x95, 0x43, 0x5E, 0x81, 0xCF, 0x60,
1506		0xA2, 0x23, 0xFC, 0x36, 0xA7, 0x5D, 0x7A, 0x4C, 0x06, 0x91, 0x6E, 0xF6,
1507		0x57, 0xEE, 0x36, 0xCB, 0x06, 0xEA, 0xF5, 0x3D, 0x95, 0x49, 0xCB, 0xA7,
1508		0xDD, 0x81, 0xDF, 0x80, 0x09, 0x4A, 0x97, 0x4D, 0xA8, 0x22, 0x72, 0xA1,
1509		0x7F, 0xC4, 0x70, 0x56, 0x70, 0xE8, 0x20, 0x10, 0x18, 0x8F, 0x2E, 0x60,
1510		0x07, 0xE7, 0x68, 0x1A, 0x82, 0x5D, 0x32, 0xA2,
1511	};
1512	DH *dh;
1513	BIGNUM *dh_p = NULL, *dh_g = NULL;
1514
1515	if ((dh = DH_new()) == NULL)
1516		return NULL;
1517
1518	dh_p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
1519	dh_g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
1520	if (dh_p == NULL || dh_g == NULL)
1521		goto err;
1522
1523	if (!DH_set0_pqg(dh, dh_p, NULL, dh_g))
1524		goto err;
1525
1526	DH_set_length(dh, 160);
1527
1528	return dh;
1529
1530 err:
1531	BN_free(dh_p);
1532	BN_free(dh_g);
1533	DH_free(dh);
1534	return NULL;
1535}
1536