xref: /freebsd/crypto/openssl/test/ssl_old_test.c (revision a91a2465)
1 /*
2  * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  * Copyright 2005 Nokia. All rights reserved.
5  *
6  * Licensed under the Apache License 2.0 (the "License").  You may not use
7  * this file except in compliance with the License.  You can obtain a copy
8  * in the file LICENSE in the source distribution or at
9  * https://www.openssl.org/source/license.html
10  */
11 
12 #include "e_os.h"
13 
14 /* Or gethostname won't be declared properly on Linux and GNU platforms. */
15 #ifndef _BSD_SOURCE
16 # define _BSD_SOURCE 1
17 #endif
18 #ifndef _DEFAULT_SOURCE
19 # define _DEFAULT_SOURCE 1
20 #endif
21 
22 #include <assert.h>
23 #include <errno.h>
24 #include <limits.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <time.h>
29 
30 #include "internal/nelem.h"
31 
32 #ifdef OPENSSL_SYS_VMS
33 /*
34  * Or isascii won't be declared properly on VMS (at least with DECompHP C).
35  */
36 # define _XOPEN_SOURCE 500
37 #endif
38 
39 #include <ctype.h>
40 
41 #include <openssl/bio.h>
42 #include <openssl/crypto.h>
43 #include <openssl/evp.h>
44 #include <openssl/x509.h>
45 #include <openssl/x509v3.h>
46 #include <openssl/ssl.h>
47 #include <openssl/err.h>
48 #include <openssl/rand.h>
49 #include <openssl/rsa.h>
50 #ifndef OPENSSL_NO_DSA
51 # include <openssl/dsa.h>
52 #endif
53 #include <openssl/bn.h>
54 #ifndef OPENSSL_NO_CT
55 # include <openssl/ct.h>
56 #endif
57 #include <openssl/provider.h>
58 #include "testutil.h"
59 
60 /*
61  * Or gethostname won't be declared properly
62  * on Compaq platforms (at least with DEC C).
63  * Do not try to put it earlier, or IPv6 includes
64  * get screwed...
65  */
66 #define _XOPEN_SOURCE_EXTENDED  1
67 
68 #ifdef OPENSSL_SYS_WINDOWS
69 # include <winsock.h>
70 #else
71 # include <unistd.h>
72 #endif
73 
74 #include "helpers/predefined_dhparams.h"
75 
76 static SSL_CTX *s_ctx = NULL;
77 static SSL_CTX *s_ctx2 = NULL;
78 
79 /*
80  * There is really no standard for this, so let's assign something
81  * only for this test
82  */
83 #define COMP_ZLIB       1
84 
85 static int verify_callback(int ok, X509_STORE_CTX *ctx);
86 static int app_verify_callback(X509_STORE_CTX *ctx, void *arg);
87 #define APP_CALLBACK_STRING "Test Callback Argument"
88 struct app_verify_arg {
89     char *string;
90     int app_verify;
91 };
92 
93 static char *psk_key = NULL;    /* by default PSK is not used */
94 #ifndef OPENSSL_NO_PSK
95 static unsigned int psk_client_callback(SSL *ssl, const char *hint,
96                                         char *identity,
97                                         unsigned int max_identity_len,
98                                         unsigned char *psk,
99                                         unsigned int max_psk_len);
100 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
101                                         unsigned char *psk,
102                                         unsigned int max_psk_len);
103 #endif
104 
105 static BIO *bio_stdout = NULL;
106 
107 #ifndef OPENSSL_NO_NEXTPROTONEG
108 /* Note that this code assumes that this is only a one element list: */
109 static const char NEXT_PROTO_STRING[] = "\x09testproto";
110 static int npn_client = 0;
111 static int npn_server = 0;
112 static int npn_server_reject = 0;
113 
114 static int cb_client_npn(SSL *s, unsigned char **out, unsigned char *outlen,
115                          const unsigned char *in, unsigned int inlen,
116                          void *arg)
117 {
118     /*
119      * This callback only returns the protocol string, rather than a length
120      * prefixed set. We assume that NEXT_PROTO_STRING is a one element list
121      * and remove the first byte to chop off the length prefix.
122      */
123     *out = (unsigned char *)NEXT_PROTO_STRING + 1;
124     *outlen = sizeof(NEXT_PROTO_STRING) - 2;
125     return SSL_TLSEXT_ERR_OK;
126 }
127 
128 static int cb_server_npn(SSL *s, const unsigned char **data,
129                          unsigned int *len, void *arg)
130 {
131     *data = (const unsigned char *)NEXT_PROTO_STRING;
132     *len = sizeof(NEXT_PROTO_STRING) - 1;
133     return SSL_TLSEXT_ERR_OK;
134 }
135 
136 static int cb_server_rejects_npn(SSL *s, const unsigned char **data,
137                                  unsigned int *len, void *arg)
138 {
139     return SSL_TLSEXT_ERR_NOACK;
140 }
141 
142 static int verify_npn(SSL *client, SSL *server)
143 {
144     const unsigned char *client_s;
145     unsigned client_len;
146     const unsigned char *server_s;
147     unsigned server_len;
148 
149     SSL_get0_next_proto_negotiated(client, &client_s, &client_len);
150     SSL_get0_next_proto_negotiated(server, &server_s, &server_len);
151 
152     if (client_len) {
153         BIO_printf(bio_stdout, "Client NPN: ");
154         BIO_write(bio_stdout, client_s, client_len);
155         BIO_printf(bio_stdout, "\n");
156     }
157 
158     if (server_len) {
159         BIO_printf(bio_stdout, "Server NPN: ");
160         BIO_write(bio_stdout, server_s, server_len);
161         BIO_printf(bio_stdout, "\n");
162     }
163 
164     /*
165      * If an NPN string was returned, it must be the protocol that we
166      * expected to negotiate.
167      */
168     if (client_len && (client_len != sizeof(NEXT_PROTO_STRING) - 2 ||
169                        memcmp(client_s, NEXT_PROTO_STRING + 1, client_len)))
170         return -1;
171     if (server_len && (server_len != sizeof(NEXT_PROTO_STRING) - 2 ||
172                        memcmp(server_s, NEXT_PROTO_STRING + 1, server_len)))
173         return -1;
174 
175     if (!npn_client && client_len)
176         return -1;
177     if (!npn_server && server_len)
178         return -1;
179     if (npn_server_reject && server_len)
180         return -1;
181     if (npn_client && npn_server && (!client_len || !server_len))
182         return -1;
183 
184     return 0;
185 }
186 #endif
187 
188 static const char *alpn_client;
189 static char *alpn_server;
190 static char *alpn_server2;
191 static const char *alpn_expected;
192 static unsigned char *alpn_selected;
193 static const char *server_min_proto;
194 static const char *server_max_proto;
195 static const char *client_min_proto;
196 static const char *client_max_proto;
197 static const char *should_negotiate;
198 static const char *sn_client;
199 static const char *sn_server1;
200 static const char *sn_server2;
201 static int sn_expect = 0;
202 static const char *server_sess_out;
203 static const char *server_sess_in;
204 static const char *client_sess_out;
205 static const char *client_sess_in;
206 static SSL_SESSION *server_sess;
207 static SSL_SESSION *client_sess;
208 
209 static int servername_cb(SSL *s, int *ad, void *arg)
210 {
211     const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
212     if (sn_server2 == NULL) {
213         BIO_printf(bio_stdout, "Servername 2 is NULL\n");
214         return SSL_TLSEXT_ERR_NOACK;
215     }
216 
217     if (servername) {
218         if (s_ctx2 != NULL && sn_server2 != NULL &&
219             !OPENSSL_strcasecmp(servername, sn_server2)) {
220             BIO_printf(bio_stdout, "Switching server context.\n");
221             SSL_set_SSL_CTX(s, s_ctx2);
222         }
223     }
224     return SSL_TLSEXT_ERR_OK;
225 }
226 static int verify_servername(SSL *client, SSL *server)
227 {
228     /* just need to see if sn_context is what we expect */
229     SSL_CTX* ctx = SSL_get_SSL_CTX(server);
230     if (sn_expect == 0)
231         return 0;
232     if (sn_expect == 1 && ctx == s_ctx)
233         return 0;
234     if (sn_expect == 2 && ctx == s_ctx2)
235         return 0;
236     BIO_printf(bio_stdout, "Servername: expected context %d\n", sn_expect);
237     if (ctx == s_ctx2)
238         BIO_printf(bio_stdout, "Servername: context is 2\n");
239     else if (ctx == s_ctx)
240         BIO_printf(bio_stdout, "Servername: context is 1\n");
241     else
242         BIO_printf(bio_stdout, "Servername: context is unknown\n");
243     return -1;
244 }
245 
246 
247 /*-
248  * next_protos_parse parses a comma separated list of strings into a string
249  * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
250  *   outlen: (output) set to the length of the resulting buffer on success.
251  *   in: a NUL terminated string like "abc,def,ghi"
252  *
253  *   returns: a malloced buffer or NULL on failure.
254  */
255 static unsigned char *next_protos_parse(size_t *outlen,
256                                         const char *in)
257 {
258     size_t len;
259     unsigned char *out;
260     size_t i, start = 0;
261 
262     len = strlen(in);
263     if (len >= 65535)
264         return NULL;
265 
266     out = OPENSSL_malloc(strlen(in) + 1);
267     if (!out)
268         return NULL;
269 
270     for (i = 0; i <= len; ++i) {
271         if (i == len || in[i] == ',') {
272             if (i - start > 255) {
273                 OPENSSL_free(out);
274                 return NULL;
275             }
276             out[start] = (unsigned char)(i - start);
277             start = i + 1;
278         } else
279             out[i + 1] = in[i];
280     }
281 
282     *outlen = len + 1;
283     return out;
284 }
285 
286 static int cb_server_alpn(SSL *s, const unsigned char **out,
287                           unsigned char *outlen, const unsigned char *in,
288                           unsigned int inlen, void *arg)
289 {
290     unsigned char *protos;
291     size_t protos_len;
292     char* alpn_str = arg;
293 
294     protos = next_protos_parse(&protos_len, alpn_str);
295     if (protos == NULL) {
296         fprintf(stderr, "failed to parser ALPN server protocol string: %s\n",
297                 alpn_str);
298         abort();
299     }
300 
301     if (SSL_select_next_proto
302         ((unsigned char **)out, outlen, protos, protos_len, in,
303          inlen) != OPENSSL_NPN_NEGOTIATED) {
304         OPENSSL_free(protos);
305         return SSL_TLSEXT_ERR_NOACK;
306     }
307 
308     /*
309      * Make a copy of the selected protocol which will be freed in
310      * verify_alpn.
311      */
312     alpn_selected = OPENSSL_malloc(*outlen);
313     if (alpn_selected == NULL) {
314         fprintf(stderr, "failed to allocate memory\n");
315         OPENSSL_free(protos);
316         abort();
317     }
318     memcpy(alpn_selected, *out, *outlen);
319     *out = alpn_selected;
320 
321     OPENSSL_free(protos);
322     return SSL_TLSEXT_ERR_OK;
323 }
324 
325 static int verify_alpn(SSL *client, SSL *server)
326 {
327     const unsigned char *client_proto, *server_proto;
328     unsigned int client_proto_len = 0, server_proto_len = 0;
329     SSL_get0_alpn_selected(client, &client_proto, &client_proto_len);
330     SSL_get0_alpn_selected(server, &server_proto, &server_proto_len);
331 
332     OPENSSL_free(alpn_selected);
333     alpn_selected = NULL;
334 
335     if (client_proto_len != server_proto_len) {
336         BIO_printf(bio_stdout, "ALPN selected protocols differ!\n");
337         goto err;
338     }
339 
340     if (client_proto != NULL &&
341         memcmp(client_proto, server_proto, client_proto_len) != 0) {
342         BIO_printf(bio_stdout, "ALPN selected protocols differ!\n");
343         goto err;
344     }
345 
346     if (client_proto_len > 0 && alpn_expected == NULL) {
347         BIO_printf(bio_stdout, "ALPN unexpectedly negotiated\n");
348         goto err;
349     }
350 
351     if (alpn_expected != NULL &&
352         (client_proto_len != strlen(alpn_expected) ||
353          memcmp(client_proto, alpn_expected, client_proto_len) != 0)) {
354         BIO_printf(bio_stdout,
355                    "ALPN selected protocols not equal to expected protocol: %s\n",
356                    alpn_expected);
357         goto err;
358     }
359 
360     return 0;
361 
362  err:
363     BIO_printf(bio_stdout, "ALPN results: client: '");
364     BIO_write(bio_stdout, client_proto, client_proto_len);
365     BIO_printf(bio_stdout, "', server: '");
366     BIO_write(bio_stdout, server_proto, server_proto_len);
367     BIO_printf(bio_stdout, "'\n");
368     BIO_printf(bio_stdout, "ALPN configured: client: '%s', server: '",
369                    alpn_client);
370     if (SSL_get_SSL_CTX(server) == s_ctx2) {
371         BIO_printf(bio_stdout, "%s'\n",
372                    alpn_server2);
373     } else {
374         BIO_printf(bio_stdout, "%s'\n",
375                    alpn_server);
376     }
377     return -1;
378 }
379 
380 /*
381  * WARNING : below extension types are *NOT* IETF assigned, and could
382  * conflict if these types are reassigned and handled specially by OpenSSL
383  * in the future
384  */
385 #define TACK_EXT_TYPE 62208
386 #define CUSTOM_EXT_TYPE_0 1000
387 #define CUSTOM_EXT_TYPE_1 1001
388 #define CUSTOM_EXT_TYPE_2 1002
389 #define CUSTOM_EXT_TYPE_3 1003
390 
391 static const char custom_ext_cli_string[] = "abc";
392 static const char custom_ext_srv_string[] = "defg";
393 
394 /* These set from cmdline */
395 static char *serverinfo_file = NULL;
396 static int serverinfo_sct = 0;
397 static int serverinfo_tack = 0;
398 
399 /* These set based on extension callbacks */
400 static int serverinfo_sct_seen = 0;
401 static int serverinfo_tack_seen = 0;
402 static int serverinfo_other_seen = 0;
403 
404 /* This set from cmdline */
405 static int custom_ext = 0;
406 
407 /* This set based on extension callbacks */
408 static int custom_ext_error = 0;
409 
410 static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
411                                    const unsigned char *in, size_t inlen,
412                                    int *al, void *arg)
413 {
414     if (ext_type == TLSEXT_TYPE_signed_certificate_timestamp)
415         serverinfo_sct_seen++;
416     else if (ext_type == TACK_EXT_TYPE)
417         serverinfo_tack_seen++;
418     else
419         serverinfo_other_seen++;
420     return 1;
421 }
422 
423 static int verify_serverinfo(void)
424 {
425     if (serverinfo_sct != serverinfo_sct_seen)
426         return -1;
427     if (serverinfo_tack != serverinfo_tack_seen)
428         return -1;
429     if (serverinfo_other_seen)
430         return -1;
431     return 0;
432 }
433 
434 /*-
435  * Four test cases for custom extensions:
436  * 0 - no ClientHello extension or ServerHello response
437  * 1 - ClientHello with "abc", no response
438  * 2 - ClientHello with "abc", empty response
439  * 3 - ClientHello with "abc", "defg" response
440  */
441 
442 static int custom_ext_0_cli_add_cb(SSL *s, unsigned int ext_type,
443                                    const unsigned char **out,
444                                    size_t *outlen, int *al, void *arg)
445 {
446     if (ext_type != CUSTOM_EXT_TYPE_0)
447         custom_ext_error = 1;
448     return 0;                   /* Don't send an extension */
449 }
450 
451 static int custom_ext_0_cli_parse_cb(SSL *s, unsigned int ext_type,
452                                      const unsigned char *in,
453                                      size_t inlen, int *al, void *arg)
454 {
455     return 1;
456 }
457 
458 static int custom_ext_1_cli_add_cb(SSL *s, unsigned int ext_type,
459                                    const unsigned char **out,
460                                    size_t *outlen, int *al, void *arg)
461 {
462     if (ext_type != CUSTOM_EXT_TYPE_1)
463         custom_ext_error = 1;
464     *out = (const unsigned char *)custom_ext_cli_string;
465     *outlen = strlen(custom_ext_cli_string);
466     return 1;                   /* Send "abc" */
467 }
468 
469 static int custom_ext_1_cli_parse_cb(SSL *s, unsigned int ext_type,
470                                      const unsigned char *in,
471                                      size_t inlen, int *al, void *arg)
472 {
473     return 1;
474 }
475 
476 static int custom_ext_2_cli_add_cb(SSL *s, unsigned int ext_type,
477                                    const unsigned char **out,
478                                    size_t *outlen, int *al, void *arg)
479 {
480     if (ext_type != CUSTOM_EXT_TYPE_2)
481         custom_ext_error = 1;
482     *out = (const unsigned char *)custom_ext_cli_string;
483     *outlen = strlen(custom_ext_cli_string);
484     return 1;                   /* Send "abc" */
485 }
486 
487 static int custom_ext_2_cli_parse_cb(SSL *s, unsigned int ext_type,
488                                      const unsigned char *in,
489                                      size_t inlen, int *al, void *arg)
490 {
491     if (ext_type != CUSTOM_EXT_TYPE_2)
492         custom_ext_error = 1;
493     if (inlen != 0)
494         custom_ext_error = 1;   /* Should be empty response */
495     return 1;
496 }
497 
498 static int custom_ext_3_cli_add_cb(SSL *s, unsigned int ext_type,
499                                    const unsigned char **out,
500                                    size_t *outlen, int *al, void *arg)
501 {
502     if (ext_type != CUSTOM_EXT_TYPE_3)
503         custom_ext_error = 1;
504     *out = (const unsigned char *)custom_ext_cli_string;
505     *outlen = strlen(custom_ext_cli_string);
506     return 1;                   /* Send "abc" */
507 }
508 
509 static int custom_ext_3_cli_parse_cb(SSL *s, unsigned int ext_type,
510                                      const unsigned char *in,
511                                      size_t inlen, int *al, void *arg)
512 {
513     if (ext_type != CUSTOM_EXT_TYPE_3)
514         custom_ext_error = 1;
515     if (inlen != strlen(custom_ext_srv_string))
516         custom_ext_error = 1;
517     if (memcmp(custom_ext_srv_string, in, inlen) != 0)
518         custom_ext_error = 1;   /* Check for "defg" */
519     return 1;
520 }
521 
522 /*
523  * custom_ext_0_cli_add_cb returns 0 - the server won't receive a callback
524  * for this extension
525  */
526 static int custom_ext_0_srv_parse_cb(SSL *s, unsigned int ext_type,
527                                      const unsigned char *in,
528                                      size_t inlen, int *al, void *arg)
529 {
530     custom_ext_error = 1;
531     return 1;
532 }
533 
534 /* 'add' callbacks are only called if the 'parse' callback is called */
535 static int custom_ext_0_srv_add_cb(SSL *s, unsigned int ext_type,
536                                    const unsigned char **out,
537                                    size_t *outlen, int *al, void *arg)
538 {
539     /* Error: should not have been called */
540     custom_ext_error = 1;
541     return 0;                   /* Don't send an extension */
542 }
543 
544 static int custom_ext_1_srv_parse_cb(SSL *s, unsigned int ext_type,
545                                      const unsigned char *in,
546                                      size_t inlen, int *al, void *arg)
547 {
548     if (ext_type != CUSTOM_EXT_TYPE_1)
549         custom_ext_error = 1;
550     /* Check for "abc" */
551     if (inlen != strlen(custom_ext_cli_string))
552         custom_ext_error = 1;
553     if (memcmp(in, custom_ext_cli_string, inlen) != 0)
554         custom_ext_error = 1;
555     return 1;
556 }
557 
558 static int custom_ext_1_srv_add_cb(SSL *s, unsigned int ext_type,
559                                    const unsigned char **out,
560                                    size_t *outlen, int *al, void *arg)
561 {
562     return 0;                   /* Don't send an extension */
563 }
564 
565 static int custom_ext_2_srv_parse_cb(SSL *s, unsigned int ext_type,
566                                      const unsigned char *in,
567                                      size_t inlen, int *al, void *arg)
568 {
569     if (ext_type != CUSTOM_EXT_TYPE_2)
570         custom_ext_error = 1;
571     /* Check for "abc" */
572     if (inlen != strlen(custom_ext_cli_string))
573         custom_ext_error = 1;
574     if (memcmp(in, custom_ext_cli_string, inlen) != 0)
575         custom_ext_error = 1;
576     return 1;
577 }
578 
579 static int custom_ext_2_srv_add_cb(SSL *s, unsigned int ext_type,
580                                    const unsigned char **out,
581                                    size_t *outlen, int *al, void *arg)
582 {
583     *out = NULL;
584     *outlen = 0;
585     return 1;                   /* Send empty extension */
586 }
587 
588 static int custom_ext_3_srv_parse_cb(SSL *s, unsigned int ext_type,
589                                      const unsigned char *in,
590                                      size_t inlen, int *al, void *arg)
591 {
592     if (ext_type != CUSTOM_EXT_TYPE_3)
593         custom_ext_error = 1;
594     /* Check for "abc" */
595     if (inlen != strlen(custom_ext_cli_string))
596         custom_ext_error = 1;
597     if (memcmp(in, custom_ext_cli_string, inlen) != 0)
598         custom_ext_error = 1;
599     return 1;
600 }
601 
602 static int custom_ext_3_srv_add_cb(SSL *s, unsigned int ext_type,
603                                    const unsigned char **out,
604                                    size_t *outlen, int *al, void *arg)
605 {
606     *out = (const unsigned char *)custom_ext_srv_string;
607     *outlen = strlen(custom_ext_srv_string);
608     return 1;                   /* Send "defg" */
609 }
610 
611 static char *cipher = NULL;
612 static char *ciphersuites = NULL;
613 static int verbose = 0;
614 static int debug = 0;
615 
616 int doit_localhost(SSL *s_ssl, SSL *c_ssl, int family,
617                    long bytes, clock_t *s_time, clock_t *c_time);
618 int doit_biopair(SSL *s_ssl, SSL *c_ssl, long bytes, clock_t *s_time,
619                  clock_t *c_time);
620 int doit(SSL *s_ssl, SSL *c_ssl, long bytes);
621 
622 static void sv_usage(void)
623 {
624     fprintf(stderr, "usage: ssltest [args ...]\n");
625     fprintf(stderr, "\n");
626     fprintf(stderr, " -server_auth  - check server certificate\n");
627     fprintf(stderr, " -client_auth  - do client authentication\n");
628     fprintf(stderr, " -v            - more output\n");
629     fprintf(stderr, " -d            - debug output\n");
630     fprintf(stderr, " -reuse        - use session-id reuse\n");
631     fprintf(stderr, " -num <val>    - number of connections to perform\n");
632     fprintf(stderr,
633             " -bytes <val>  - number of bytes to swap between client/server\n");
634 #ifndef OPENSSL_NO_DH
635     fprintf(stderr,
636             " -dhe512       - use 512 bit key for DHE (to test failure)\n");
637     fprintf(stderr,
638             " -dhe1024dsa   - use 1024 bit key (with 160-bit subprime) for DHE\n");
639     fprintf(stderr,
640             " -dhe2048      - use 2048 bit key (safe prime) for DHE (default, no-op)\n");
641     fprintf(stderr,
642             " -dhe4096      - use 4096 bit key (safe prime) for DHE\n");
643 #endif
644     fprintf(stderr, " -no_dhe       - disable DHE\n");
645 #ifndef OPENSSL_NO_EC
646     fprintf(stderr, " -no_ecdhe     - disable ECDHE\n");
647 #endif
648 #ifndef OPENSSL_NO_PSK
649     fprintf(stderr, " -psk arg      - PSK in hex (without 0x)\n");
650 #endif
651 #ifndef OPENSSL_NO_SSL3
652     fprintf(stderr, " -ssl3         - use SSLv3\n");
653 #endif
654 #ifndef OPENSSL_NO_TLS1
655     fprintf(stderr, " -tls1         - use TLSv1\n");
656 #endif
657 #ifndef OPENSSL_NO_TLS1_1
658     fprintf(stderr, " -tls1_1       - use TLSv1.1\n");
659 #endif
660 #ifndef OPENSSL_NO_TLS1_2
661     fprintf(stderr, " -tls1_2       - use TLSv1.2\n");
662 #endif
663 #ifndef OPENSSL_NO_DTLS
664     fprintf(stderr, " -dtls         - use DTLS\n");
665 #ifndef OPENSSL_NO_DTLS1
666     fprintf(stderr, " -dtls1        - use DTLSv1\n");
667 #endif
668 #ifndef OPENSSL_NO_DTLS1_2
669     fprintf(stderr, " -dtls12       - use DTLSv1.2\n");
670 #endif
671 #endif
672     fprintf(stderr, " -CApath arg   - PEM format directory of CA's\n");
673     fprintf(stderr, " -CAfile arg   - PEM format file of CA's\n");
674     fprintf(stderr, " -s_cert arg   - Server certificate file\n");
675     fprintf(stderr,
676             " -s_key arg    - Server key file (default: same as -cert)\n");
677     fprintf(stderr, " -c_cert arg   - Client certificate file\n");
678     fprintf(stderr,
679             " -c_key arg    - Client key file (default: same as -c_cert)\n");
680     fprintf(stderr, " -cipher arg   - The TLSv1.2 and below cipher list\n");
681     fprintf(stderr, " -ciphersuites arg   - The TLSv1.3 ciphersuites\n");
682     fprintf(stderr, " -bio_pair     - Use BIO pairs\n");
683     fprintf(stderr, " -ipv4         - Use IPv4 connection on localhost\n");
684     fprintf(stderr, " -ipv6         - Use IPv6 connection on localhost\n");
685     fprintf(stderr, " -f            - Test even cases that can't work\n");
686     fprintf(stderr,
687             " -time         - measure processor time used by client and server\n");
688     fprintf(stderr, " -zlib         - use zlib compression\n");
689 #ifndef OPENSSL_NO_NEXTPROTONEG
690     fprintf(stderr, " -npn_client - have client side offer NPN\n");
691     fprintf(stderr, " -npn_server - have server side offer NPN\n");
692     fprintf(stderr, " -npn_server_reject - have server reject NPN\n");
693 #endif
694     fprintf(stderr, " -serverinfo_file file - have server use this file\n");
695     fprintf(stderr, " -serverinfo_sct  - have client offer and expect SCT\n");
696     fprintf(stderr,
697             " -serverinfo_tack - have client offer and expect TACK\n");
698     fprintf(stderr,
699             " -custom_ext - try various custom extension callbacks\n");
700     fprintf(stderr, " -alpn_client <string> - have client side offer ALPN\n");
701     fprintf(stderr, " -alpn_server <string> - have server side offer ALPN\n");
702     fprintf(stderr, " -alpn_server1 <string> - alias for -alpn_server\n");
703     fprintf(stderr, " -alpn_server2 <string> - have server side context 2 offer ALPN\n");
704     fprintf(stderr,
705             " -alpn_expected <string> - the ALPN protocol that should be negotiated\n");
706     fprintf(stderr, " -server_min_proto <string> - Minimum version the server should support\n");
707     fprintf(stderr, " -server_max_proto <string> - Maximum version the server should support\n");
708     fprintf(stderr, " -client_min_proto <string> - Minimum version the client should support\n");
709     fprintf(stderr, " -client_max_proto <string> - Maximum version the client should support\n");
710     fprintf(stderr, " -should_negotiate <string> - The version that should be negotiated, fail-client or fail-server\n");
711 #ifndef OPENSSL_NO_CT
712     fprintf(stderr, " -noct         - no certificate transparency\n");
713     fprintf(stderr, " -requestct    - request certificate transparency\n");
714     fprintf(stderr, " -requirect    - require certificate transparency\n");
715 #endif
716     fprintf(stderr, " -sn_client <string>  - have client request this servername\n");
717     fprintf(stderr, " -sn_server1 <string> - have server context 1 respond to this servername\n");
718     fprintf(stderr, " -sn_server2 <string> - have server context 2 respond to this servername\n");
719     fprintf(stderr, " -sn_expect1          - expected server 1\n");
720     fprintf(stderr, " -sn_expect2          - expected server 2\n");
721     fprintf(stderr, " -server_sess_out <file>    - Save the server session to a file\n");
722     fprintf(stderr, " -server_sess_in <file>     - Read the server session from a file\n");
723     fprintf(stderr, " -client_sess_out <file>    - Save the client session to a file\n");
724     fprintf(stderr, " -client_sess_in <file>     - Read the client session from a file\n");
725     fprintf(stderr, " -should_reuse <number>     - The expected state of reusing the session\n");
726     fprintf(stderr, " -no_ticket    - do not issue TLS session ticket\n");
727     fprintf(stderr, " -client_ktls  - try to enable client KTLS\n");
728     fprintf(stderr, " -server_ktls  - try to enable server KTLS\n");
729     fprintf(stderr, " -provider <name>    - Load the given provider into the library context\n");
730     fprintf(stderr, " -config <cnf>    - Load the given config file into the library context\n");
731 }
732 
733 static void print_key_details(BIO *out, EVP_PKEY *key)
734 {
735     int keyid = EVP_PKEY_get_id(key);
736 
737 #ifndef OPENSSL_NO_EC
738     if (keyid == EVP_PKEY_EC) {
739         char group[80];
740         size_t size;
741 
742         if (!EVP_PKEY_get_group_name(key, group, sizeof(group), &size))
743             strcpy(group, "unknown group");
744         BIO_printf(out, "%d bits EC (%s)", EVP_PKEY_get_bits(key), group);
745     } else
746 #endif
747     {
748         const char *algname;
749         switch (keyid) {
750         case EVP_PKEY_RSA:
751             algname = "RSA";
752             break;
753         case EVP_PKEY_DSA:
754             algname = "DSA";
755             break;
756         case EVP_PKEY_DH:
757             algname = "DH";
758             break;
759         default:
760             algname = OBJ_nid2sn(keyid);
761             break;
762         }
763         BIO_printf(out, "%d bits %s", EVP_PKEY_get_bits(key), algname);
764     }
765 }
766 
767 static void print_details(SSL *c_ssl, const char *prefix)
768 {
769     const SSL_CIPHER *ciph;
770     int mdnid;
771     X509 *cert;
772     EVP_PKEY *pkey;
773 
774     ciph = SSL_get_current_cipher(c_ssl);
775     BIO_printf(bio_stdout, "%s%s, cipher %s %s",
776                prefix,
777                SSL_get_version(c_ssl),
778                SSL_CIPHER_get_version(ciph), SSL_CIPHER_get_name(ciph));
779     cert = SSL_get0_peer_certificate(c_ssl);
780     if (cert != NULL) {
781         EVP_PKEY* pubkey = X509_get0_pubkey(cert);
782 
783         if (pubkey != NULL) {
784             BIO_puts(bio_stdout, ", ");
785             print_key_details(bio_stdout, pubkey);
786         }
787     }
788     if (SSL_get_peer_tmp_key(c_ssl, &pkey)) {
789         BIO_puts(bio_stdout, ", temp key: ");
790         print_key_details(bio_stdout, pkey);
791         EVP_PKEY_free(pkey);
792     }
793     if (SSL_get_peer_signature_nid(c_ssl, &mdnid))
794         BIO_printf(bio_stdout, ", digest=%s", OBJ_nid2sn(mdnid));
795     BIO_printf(bio_stdout, "\n");
796 }
797 
798 /*
799  * protocol_from_string - converts a protocol version string to a number
800  *
801  * Returns -1 on failure or the version on success
802  */
803 static int protocol_from_string(const char *value)
804 {
805     struct protocol_versions {
806         const char *name;
807         int version;
808     };
809     static const struct protocol_versions versions[] = {
810         {"ssl3", SSL3_VERSION},
811         {"tls1", TLS1_VERSION},
812         {"tls1.1", TLS1_1_VERSION},
813         {"tls1.2", TLS1_2_VERSION},
814         {"tls1.3", TLS1_3_VERSION},
815         {"dtls1", DTLS1_VERSION},
816         {"dtls1.2", DTLS1_2_VERSION}};
817     size_t i;
818     size_t n = OSSL_NELEM(versions);
819 
820     for (i = 0; i < n; i++)
821         if (strcmp(versions[i].name, value) == 0)
822             return versions[i].version;
823     return -1;
824 }
825 
826 static SSL_SESSION *read_session(const char *filename)
827 {
828     SSL_SESSION *sess;
829     BIO *f = BIO_new_file(filename, "r");
830 
831     if (f == NULL) {
832         BIO_printf(bio_err, "Can't open session file %s\n", filename);
833         ERR_print_errors(bio_err);
834         return NULL;
835     }
836     sess = PEM_read_bio_SSL_SESSION(f, NULL, 0, NULL);
837     if (sess == NULL) {
838         BIO_printf(bio_err, "Can't parse session file %s\n", filename);
839         ERR_print_errors(bio_err);
840     }
841     BIO_free(f);
842     return sess;
843 }
844 
845 static int write_session(const char *filename, SSL_SESSION *sess)
846 {
847     BIO *f;
848 
849     if (sess == NULL) {
850         BIO_printf(bio_err, "No session information\n");
851         return 0;
852     }
853 
854     f = BIO_new_file(filename, "w");
855     if (f == NULL) {
856         BIO_printf(bio_err, "Can't open session file %s\n", filename);
857         ERR_print_errors(bio_err);
858         return 0;
859     }
860     PEM_write_bio_SSL_SESSION(f, sess);
861     BIO_free(f);
862     return 1;
863 }
864 
865 /*
866  * set_protocol_version - Sets protocol version minimum or maximum
867  *
868  * Returns 0 on failure and 1 on success
869  */
870 static int set_protocol_version(const char *version, SSL *ssl, int setting)
871 {
872     if (version != NULL) {
873         int ver = protocol_from_string(version);
874         if (ver < 0) {
875             BIO_printf(bio_err, "Error parsing: %s\n", version);
876             return 0;
877         }
878         return SSL_ctrl(ssl, setting, ver, NULL);
879     }
880     return 1;
881 }
882 
883 int main(int argc, char *argv[])
884 {
885     const char *CApath = NULL, *CAfile = NULL;
886     int badop = 0;
887     enum { BIO_MEM, BIO_PAIR, BIO_IPV4, BIO_IPV6 } bio_type = BIO_MEM;
888     int force = 0;
889     int dtls1 = 0, dtls12 = 0, dtls = 0, tls1 = 0, tls1_1 = 0, tls1_2 = 0, ssl3 = 0;
890     int ret = EXIT_FAILURE;
891     int client_auth = 0;
892     int server_auth = 0, i;
893     struct app_verify_arg app_verify_arg =
894         { APP_CALLBACK_STRING, 0 };
895     SSL_CTX *c_ctx = NULL;
896     const SSL_METHOD *meth = NULL;
897     SSL *c_ssl = NULL;
898     SSL *s_ssl = NULL;
899     int number = 1, reuse = 0;
900     int should_reuse = -1;
901     int no_ticket = 0;
902     int client_ktls = 0, server_ktls = 0;
903     long bytes = 256L;
904 #ifndef OPENSSL_NO_DH
905     EVP_PKEY *dhpkey;
906     int dhe512 = 0, dhe1024dsa = 0, dhe4096 = 0;
907     int no_dhe = 0;
908 #endif
909     int no_psk = 0;
910     int print_time = 0;
911     clock_t s_time = 0, c_time = 0;
912 #ifndef OPENSSL_NO_COMP
913     int n, comp = 0;
914     COMP_METHOD *cm = NULL;
915     STACK_OF(SSL_COMP) *ssl_comp_methods = NULL;
916 #endif
917     int no_protocol;
918     int min_version = 0, max_version = 0;
919 #ifndef OPENSSL_NO_CT
920     /*
921      * Disable CT validation by default, because it will interfere with
922      * anything using custom extension handlers to deal with SCT extensions.
923      */
924     int ct_validation = 0;
925 #endif
926     SSL_CONF_CTX *s_cctx = NULL, *c_cctx = NULL, *s_cctx2 = NULL;
927     STACK_OF(OPENSSL_STRING) *conf_args = NULL;
928     char *arg = NULL, *argn = NULL;
929     const char *provider = NULL, *config = NULL;
930     OSSL_PROVIDER *thisprov = NULL, *defctxnull = NULL;
931     OSSL_LIB_CTX *libctx = NULL;
932 
933     verbose = 0;
934     debug = 0;
935 
936     bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
937     bio_stdout = BIO_new_fp(stdout, BIO_NOCLOSE | BIO_FP_TEXT);
938 
939     s_cctx = SSL_CONF_CTX_new();
940     s_cctx2 = SSL_CONF_CTX_new();
941     c_cctx = SSL_CONF_CTX_new();
942 
943     if (!s_cctx || !c_cctx || !s_cctx2) {
944         ERR_print_errors(bio_err);
945         goto end;
946     }
947 
948     SSL_CONF_CTX_set_flags(s_cctx,
949                            SSL_CONF_FLAG_CMDLINE | SSL_CONF_FLAG_SERVER |
950                            SSL_CONF_FLAG_CERTIFICATE |
951                            SSL_CONF_FLAG_REQUIRE_PRIVATE);
952     SSL_CONF_CTX_set_flags(s_cctx2,
953                            SSL_CONF_FLAG_CMDLINE | SSL_CONF_FLAG_SERVER |
954                            SSL_CONF_FLAG_CERTIFICATE |
955                            SSL_CONF_FLAG_REQUIRE_PRIVATE);
956     if (!SSL_CONF_CTX_set1_prefix(s_cctx, "-s_")) {
957         ERR_print_errors(bio_err);
958         goto end;
959     }
960     if (!SSL_CONF_CTX_set1_prefix(s_cctx2, "-s_")) {
961         ERR_print_errors(bio_err);
962         goto end;
963     }
964 
965     SSL_CONF_CTX_set_flags(c_cctx,
966                            SSL_CONF_FLAG_CMDLINE | SSL_CONF_FLAG_CLIENT |
967                            SSL_CONF_FLAG_CERTIFICATE |
968                            SSL_CONF_FLAG_REQUIRE_PRIVATE);
969     if (!SSL_CONF_CTX_set1_prefix(c_cctx, "-c_")) {
970         ERR_print_errors(bio_err);
971         goto end;
972     }
973 
974     argc--;
975     argv++;
976 
977     while (argc >= 1) {
978         if (strcmp(*argv, "-F") == 0) {
979             fprintf(stderr,
980                     "not compiled with FIPS support, so exiting without running.\n");
981             EXIT(0);
982         } else if (strcmp(*argv, "-server_auth") == 0)
983             server_auth = 1;
984         else if (strcmp(*argv, "-client_auth") == 0)
985             client_auth = 1;
986         else if (strcmp(*argv, "-v") == 0)
987             verbose = 1;
988         else if (strcmp(*argv, "-d") == 0)
989             debug = 1;
990         else if (strcmp(*argv, "-reuse") == 0)
991             reuse = 1;
992         else if (strcmp(*argv, "-no_dhe") == 0)
993 #ifdef OPENSSL_NO_DH
994             /* unused in this case */;
995 #else
996             no_dhe = 1;
997         else if (strcmp(*argv, "-dhe512") == 0)
998             dhe512 = 1;
999         else if (strcmp(*argv, "-dhe1024dsa") == 0)
1000             dhe1024dsa = 1;
1001         else if (strcmp(*argv, "-dhe4096") == 0)
1002             dhe4096 = 1;
1003 #endif
1004         else if (strcmp(*argv, "-no_ecdhe") == 0)
1005             /* obsolete */;
1006         else if (strcmp(*argv, "-psk") == 0) {
1007             if (--argc < 1)
1008                 goto bad;
1009             psk_key = *(++argv);
1010 #ifndef OPENSSL_NO_PSK
1011             if (strspn(psk_key, "abcdefABCDEF1234567890") != strlen(psk_key)) {
1012                 BIO_printf(bio_err, "Not a hex number '%s'\n", *argv);
1013                 goto bad;
1014             }
1015 #else
1016             no_psk = 1;
1017 #endif
1018         }
1019         else if (strcmp(*argv, "-tls1_2") == 0) {
1020             tls1_2 = 1;
1021         } else if (strcmp(*argv, "-tls1_1") == 0) {
1022             tls1_1 = 1;
1023         } else if (strcmp(*argv, "-tls1") == 0) {
1024             tls1 = 1;
1025         } else if (strcmp(*argv, "-ssl3") == 0) {
1026             ssl3 = 1;
1027         } else if (strcmp(*argv, "-dtls1") == 0) {
1028             dtls1 = 1;
1029         } else if (strcmp(*argv, "-dtls12") == 0) {
1030             dtls12 = 1;
1031         } else if (strcmp(*argv, "-dtls") == 0) {
1032             dtls = 1;
1033         } else if (strncmp(*argv, "-num", 4) == 0) {
1034             if (--argc < 1)
1035                 goto bad;
1036             number = atoi(*(++argv));
1037             if (number == 0)
1038                 number = 1;
1039         } else if (strcmp(*argv, "-bytes") == 0) {
1040             if (--argc < 1)
1041                 goto bad;
1042             bytes = atol(*(++argv));
1043             if (bytes == 0L)
1044                 bytes = 1L;
1045             i = strlen(argv[0]);
1046             if (argv[0][i - 1] == 'k')
1047                 bytes *= 1024L;
1048             if (argv[0][i - 1] == 'm')
1049                 bytes *= 1024L * 1024L;
1050         } else if (strcmp(*argv, "-cipher") == 0) {
1051             if (--argc < 1)
1052                 goto bad;
1053             cipher = *(++argv);
1054         } else if (strcmp(*argv, "-ciphersuites") == 0) {
1055             if (--argc < 1)
1056                 goto bad;
1057             ciphersuites = *(++argv);
1058         } else if (strcmp(*argv, "-CApath") == 0) {
1059             if (--argc < 1)
1060                 goto bad;
1061             CApath = *(++argv);
1062         } else if (strcmp(*argv, "-CAfile") == 0) {
1063             if (--argc < 1)
1064                 goto bad;
1065             CAfile = *(++argv);
1066         } else if (strcmp(*argv, "-bio_pair") == 0) {
1067             bio_type = BIO_PAIR;
1068         }
1069 #ifndef OPENSSL_NO_SOCK
1070         else if (strcmp(*argv, "-ipv4") == 0) {
1071             bio_type = BIO_IPV4;
1072         } else if (strcmp(*argv, "-ipv6") == 0) {
1073             bio_type = BIO_IPV6;
1074         }
1075 #endif
1076         else if (strcmp(*argv, "-f") == 0) {
1077             force = 1;
1078         } else if (strcmp(*argv, "-time") == 0) {
1079             print_time = 1;
1080         }
1081 #ifndef OPENSSL_NO_CT
1082         else if (strcmp(*argv, "-noct") == 0) {
1083             ct_validation = 0;
1084         }
1085         else if (strcmp(*argv, "-ct") == 0) {
1086             ct_validation = 1;
1087         }
1088 #endif
1089 #ifndef OPENSSL_NO_COMP
1090         else if (strcmp(*argv, "-zlib") == 0) {
1091             comp = COMP_ZLIB;
1092         }
1093 #endif
1094         else if (strcmp(*argv, "-app_verify") == 0) {
1095             app_verify_arg.app_verify = 1;
1096         }
1097 #ifndef OPENSSL_NO_NEXTPROTONEG
1098           else if (strcmp(*argv, "-npn_client") == 0) {
1099             npn_client = 1;
1100         } else if (strcmp(*argv, "-npn_server") == 0) {
1101             npn_server = 1;
1102         } else if (strcmp(*argv, "-npn_server_reject") == 0) {
1103             npn_server_reject = 1;
1104         }
1105 #endif
1106         else if (strcmp(*argv, "-serverinfo_sct") == 0) {
1107             serverinfo_sct = 1;
1108         } else if (strcmp(*argv, "-serverinfo_tack") == 0) {
1109             serverinfo_tack = 1;
1110         } else if (strcmp(*argv, "-serverinfo_file") == 0) {
1111             if (--argc < 1)
1112                 goto bad;
1113             serverinfo_file = *(++argv);
1114         } else if (strcmp(*argv, "-custom_ext") == 0) {
1115             custom_ext = 1;
1116         } else if (strcmp(*argv, "-alpn_client") == 0) {
1117             if (--argc < 1)
1118                 goto bad;
1119             alpn_client = *(++argv);
1120         } else if (strcmp(*argv, "-alpn_server") == 0 ||
1121                    strcmp(*argv, "-alpn_server1") == 0) {
1122             if (--argc < 1)
1123                 goto bad;
1124             alpn_server = *(++argv);
1125         } else if (strcmp(*argv, "-alpn_server2") == 0) {
1126             if (--argc < 1)
1127                 goto bad;
1128             alpn_server2 = *(++argv);
1129         } else if (strcmp(*argv, "-alpn_expected") == 0) {
1130             if (--argc < 1)
1131                 goto bad;
1132             alpn_expected = *(++argv);
1133         } else if (strcmp(*argv, "-server_min_proto") == 0) {
1134             if (--argc < 1)
1135                 goto bad;
1136             server_min_proto = *(++argv);
1137         } else if (strcmp(*argv, "-server_max_proto") == 0) {
1138             if (--argc < 1)
1139                 goto bad;
1140             server_max_proto = *(++argv);
1141         } else if (strcmp(*argv, "-client_min_proto") == 0) {
1142             if (--argc < 1)
1143                 goto bad;
1144             client_min_proto = *(++argv);
1145         } else if (strcmp(*argv, "-client_max_proto") == 0) {
1146             if (--argc < 1)
1147                 goto bad;
1148             client_max_proto = *(++argv);
1149         } else if (strcmp(*argv, "-should_negotiate") == 0) {
1150             if (--argc < 1)
1151                 goto bad;
1152             should_negotiate = *(++argv);
1153         } else if (strcmp(*argv, "-sn_client") == 0) {
1154             if (--argc < 1)
1155                 goto bad;
1156             sn_client = *(++argv);
1157         } else if (strcmp(*argv, "-sn_server1") == 0) {
1158             if (--argc < 1)
1159                 goto bad;
1160             sn_server1 = *(++argv);
1161         } else if (strcmp(*argv, "-sn_server2") == 0) {
1162             if (--argc < 1)
1163                 goto bad;
1164             sn_server2 = *(++argv);
1165         } else if (strcmp(*argv, "-sn_expect1") == 0) {
1166             sn_expect = 1;
1167         } else if (strcmp(*argv, "-sn_expect2") == 0) {
1168             sn_expect = 2;
1169         } else if (strcmp(*argv, "-server_sess_out") == 0) {
1170             if (--argc < 1)
1171                 goto bad;
1172             server_sess_out = *(++argv);
1173         } else if (strcmp(*argv, "-server_sess_in") == 0) {
1174             if (--argc < 1)
1175                 goto bad;
1176             server_sess_in = *(++argv);
1177         } else if (strcmp(*argv, "-client_sess_out") == 0) {
1178             if (--argc < 1)
1179                 goto bad;
1180             client_sess_out = *(++argv);
1181         } else if (strcmp(*argv, "-client_sess_in") == 0) {
1182             if (--argc < 1)
1183                 goto bad;
1184             client_sess_in = *(++argv);
1185         } else if (strcmp(*argv, "-should_reuse") == 0) {
1186             if (--argc < 1)
1187                 goto bad;
1188             should_reuse = !!atoi(*(++argv));
1189         } else if (strcmp(*argv, "-no_ticket") == 0) {
1190             no_ticket = 1;
1191         } else if (strcmp(*argv, "-client_ktls") == 0) {
1192             client_ktls = 1;
1193         } else if (strcmp(*argv, "-server_ktls") == 0) {
1194             server_ktls = 1;
1195         } else if (strcmp(*argv, "-provider") == 0) {
1196             if (--argc < 1)
1197                 goto bad;
1198             provider = *(++argv);
1199         } else if (strcmp(*argv, "-config") == 0) {
1200             if (--argc < 1)
1201                 goto bad;
1202             config = *(++argv);
1203         } else {
1204             int rv;
1205             arg = argv[0];
1206             argn = argv[1];
1207             /* Try to process command using SSL_CONF */
1208             rv = SSL_CONF_cmd_argv(c_cctx, &argc, &argv);
1209             /* If not processed try server */
1210             if (rv == 0)
1211                 rv = SSL_CONF_cmd_argv(s_cctx, &argc, &argv);
1212             /* Recognised: store it for later use */
1213             if (rv > 0) {
1214                 if (rv == 1)
1215                     argn = NULL;
1216                 if (!conf_args) {
1217                     conf_args = sk_OPENSSL_STRING_new_null();
1218                     if (!conf_args)
1219                         goto end;
1220                 }
1221                 if (!sk_OPENSSL_STRING_push(conf_args, arg))
1222                     goto end;
1223                 if (!sk_OPENSSL_STRING_push(conf_args, argn))
1224                     goto end;
1225                 continue;
1226             }
1227             if (rv == -3)
1228                 BIO_printf(bio_err, "Missing argument for %s\n", arg);
1229             else if (rv < 0)
1230                 BIO_printf(bio_err, "Error with command %s\n", arg);
1231             else if (rv == 0)
1232                 BIO_printf(bio_err, "unknown option %s\n", arg);
1233             badop = 1;
1234             break;
1235         }
1236         argc--;
1237         argv++;
1238     }
1239     if (badop) {
1240  bad:
1241         sv_usage();
1242         goto end;
1243     }
1244 
1245     if (ssl3 + tls1 + tls1_1 + tls1_2 + dtls + dtls1 + dtls12 > 1) {
1246         fprintf(stderr, "At most one of -ssl3, -tls1, -tls1_1, -tls1_2, -dtls, -dtls1 or -dtls12 should "
1247                 "be requested.\n");
1248         EXIT(1);
1249     }
1250 
1251 #ifdef OPENSSL_NO_SSL3
1252     if (ssl3)
1253         no_protocol = 1;
1254     else
1255 #endif
1256 #ifdef OPENSSL_NO_TLS1
1257     if (tls1)
1258         no_protocol = 1;
1259     else
1260 #endif
1261 #ifdef OPENSSL_NO_TLS1_1
1262     if (tls1_1)
1263         no_protocol = 1;
1264     else
1265 #endif
1266 #ifdef OPENSSL_NO_TLS1_2
1267     if (tls1_2)
1268         no_protocol = 1;
1269     else
1270 #endif
1271 #if defined(OPENSSL_NO_DTLS) || defined(OPENSSL_NO_DTLS1)
1272     if (dtls1)
1273         no_protocol = 1;
1274     else
1275 #endif
1276 #if defined(OPENSSL_NO_DTLS) || defined(OPENSSL_NO_DTLS1_2)
1277     if (dtls12)
1278         no_protocol = 1;
1279     else
1280 #endif
1281         no_protocol = 0;
1282 
1283     /*
1284      * Testing was requested for a compiled-out protocol (e.g. SSLv3).
1285      * Ideally, we would error out, but the generic test wrapper can't know
1286      * when to expect failure. So we do nothing and return success.
1287      */
1288     if (no_protocol) {
1289         fprintf(stderr, "Testing was requested for a disabled protocol. "
1290                 "Skipping tests.\n");
1291         ret = EXIT_SUCCESS;
1292         goto end;
1293     }
1294 
1295     if (!ssl3 && !tls1 && !tls1_1 && !tls1_2 && !dtls && !dtls1 && !dtls12 && number > 1
1296             && !reuse && !force) {
1297         fprintf(stderr, "This case cannot work.  Use -f to perform "
1298                 "the test anyway (and\n-d to see what happens), "
1299                 "or add one of -ssl3, -tls1, -tls1_1, -tls1_2, -dtls, -dtls1, -dtls12, -reuse\n"
1300                 "to avoid protocol mismatch.\n");
1301         EXIT(1);
1302     }
1303 
1304     if (print_time) {
1305         if (bio_type == BIO_MEM) {
1306             fprintf(stderr, "Using BIO pair (-bio_pair)\n");
1307             bio_type = BIO_PAIR;
1308         }
1309         if (number < 50 && !force)
1310             fprintf(stderr,
1311                     "Warning: For accurate timings, use more connections (e.g. -num 1000)\n");
1312     }
1313 
1314 #ifndef OPENSSL_NO_COMP
1315     if (comp == COMP_ZLIB)
1316         cm = COMP_zlib();
1317     if (cm != NULL) {
1318         if (COMP_get_type(cm) != NID_undef) {
1319             if (SSL_COMP_add_compression_method(comp, cm) != 0) {
1320                 fprintf(stderr, "Failed to add compression method\n");
1321                 ERR_print_errors_fp(stderr);
1322             }
1323         } else {
1324             fprintf(stderr,
1325                     "Warning: %s compression not supported\n",
1326                     comp == COMP_ZLIB ? "zlib" : "unknown");
1327             ERR_print_errors_fp(stderr);
1328         }
1329     }
1330     ssl_comp_methods = SSL_COMP_get_compression_methods();
1331     n = sk_SSL_COMP_num(ssl_comp_methods);
1332     if (n) {
1333         int j;
1334         printf("Available compression methods:");
1335         for (j = 0; j < n; j++) {
1336             SSL_COMP *c = sk_SSL_COMP_value(ssl_comp_methods, j);
1337             printf("  %s:%d", SSL_COMP_get0_name(c), SSL_COMP_get_id(c));
1338         }
1339         printf("\n");
1340     }
1341 #endif
1342 
1343 #ifndef OPENSSL_NO_TLS
1344     meth = TLS_method();
1345     if (ssl3) {
1346         min_version = SSL3_VERSION;
1347         max_version = SSL3_VERSION;
1348     } else if (tls1) {
1349         min_version = TLS1_VERSION;
1350         max_version = TLS1_VERSION;
1351     } else if (tls1_1) {
1352         min_version = TLS1_1_VERSION;
1353         max_version = TLS1_1_VERSION;
1354     } else if (tls1_2) {
1355         min_version = TLS1_2_VERSION;
1356         max_version = TLS1_2_VERSION;
1357     } else {
1358         min_version = 0;
1359 # if defined(OPENSSL_NO_EC) && defined(OPENSSL_NO_DH)
1360         /* We only have ec and dh based built-in groups for TLSv1.3 */
1361         max_version = TLS1_2_VERSION;
1362 # else
1363         max_version = 0;
1364 # endif
1365     }
1366 #endif
1367 #ifndef OPENSSL_NO_DTLS
1368     if (dtls || dtls1 || dtls12) {
1369         meth = DTLS_method();
1370         if (dtls1) {
1371             min_version = DTLS1_VERSION;
1372             max_version = DTLS1_VERSION;
1373         } else if (dtls12) {
1374             min_version = DTLS1_2_VERSION;
1375             max_version = DTLS1_2_VERSION;
1376         } else {
1377             min_version = 0;
1378             max_version = 0;
1379         }
1380     }
1381 #endif
1382 
1383     if (provider != NULL
1384             && !test_get_libctx(&libctx, &defctxnull, config, &thisprov, provider))
1385         goto end;
1386 
1387     c_ctx = SSL_CTX_new_ex(libctx, NULL, meth);
1388     s_ctx = SSL_CTX_new_ex(libctx, NULL, meth);
1389     s_ctx2 = SSL_CTX_new_ex(libctx, NULL, meth); /* no SSL_CTX_dup! */
1390     if ((c_ctx == NULL) || (s_ctx == NULL) || (s_ctx2 == NULL)) {
1391         ERR_print_errors(bio_err);
1392         goto end;
1393     }
1394     /*
1395      * Since we will use low security ciphersuites and keys for testing set
1396      * security level to zero by default. Tests can override this by adding
1397      * "@SECLEVEL=n" to the cipher string.
1398      */
1399     SSL_CTX_set_security_level(c_ctx, 0);
1400     SSL_CTX_set_security_level(s_ctx, 0);
1401     SSL_CTX_set_security_level(s_ctx2, 0);
1402 
1403     if (no_ticket) {
1404         SSL_CTX_set_options(c_ctx, SSL_OP_NO_TICKET);
1405         SSL_CTX_set_options(s_ctx, SSL_OP_NO_TICKET);
1406     }
1407 
1408     if (SSL_CTX_set_min_proto_version(c_ctx, min_version) == 0)
1409         goto end;
1410     if (SSL_CTX_set_max_proto_version(c_ctx, max_version) == 0)
1411         goto end;
1412     if (SSL_CTX_set_min_proto_version(s_ctx, min_version) == 0)
1413         goto end;
1414     if (SSL_CTX_set_max_proto_version(s_ctx, max_version) == 0)
1415         goto end;
1416 
1417     if (cipher != NULL) {
1418         if (strcmp(cipher, "") == 0) {
1419             if (!SSL_CTX_set_cipher_list(c_ctx, cipher)) {
1420                 if (ERR_GET_REASON(ERR_peek_error()) == SSL_R_NO_CIPHER_MATCH) {
1421                     ERR_clear_error();
1422                 } else {
1423                     ERR_print_errors(bio_err);
1424                     goto end;
1425                 }
1426             } else {
1427                 /* Should have failed when clearing all TLSv1.2 ciphers. */
1428                 fprintf(stderr, "CLEARING ALL TLSv1.2 CIPHERS SHOULD FAIL\n");
1429                 goto end;
1430             }
1431 
1432             if (!SSL_CTX_set_cipher_list(s_ctx, cipher)) {
1433                 if (ERR_GET_REASON(ERR_peek_error()) == SSL_R_NO_CIPHER_MATCH) {
1434                     ERR_clear_error();
1435                 } else {
1436                     ERR_print_errors(bio_err);
1437                     goto end;
1438                 }
1439             } else {
1440                 /* Should have failed when clearing all TLSv1.2 ciphers. */
1441                 fprintf(stderr, "CLEARING ALL TLSv1.2 CIPHERS SHOULD FAIL\n");
1442                 goto end;
1443             }
1444 
1445             if (!SSL_CTX_set_cipher_list(s_ctx2, cipher)) {
1446                 if (ERR_GET_REASON(ERR_peek_error()) == SSL_R_NO_CIPHER_MATCH) {
1447                     ERR_clear_error();
1448                 } else {
1449                     ERR_print_errors(bio_err);
1450                     goto end;
1451                 }
1452             } else {
1453                 /* Should have failed when clearing all TLSv1.2 ciphers. */
1454                 fprintf(stderr, "CLEARING ALL TLSv1.2 CIPHERS SHOULD FAIL\n");
1455                 goto end;
1456             }
1457         } else {
1458             if (!SSL_CTX_set_cipher_list(c_ctx, cipher)
1459                     || !SSL_CTX_set_cipher_list(s_ctx, cipher)
1460                     || !SSL_CTX_set_cipher_list(s_ctx2, cipher)) {
1461                 ERR_print_errors(bio_err);
1462                 goto end;
1463             }
1464         }
1465     }
1466     if (ciphersuites != NULL) {
1467         if (!SSL_CTX_set_ciphersuites(c_ctx, ciphersuites)
1468             || !SSL_CTX_set_ciphersuites(s_ctx, ciphersuites)
1469             || !SSL_CTX_set_ciphersuites(s_ctx2, ciphersuites)) {
1470             ERR_print_errors(bio_err);
1471             goto end;
1472         }
1473     }
1474 
1475 #ifndef OPENSSL_NO_CT
1476     if (ct_validation &&
1477         !SSL_CTX_enable_ct(c_ctx, SSL_CT_VALIDATION_STRICT)) {
1478         ERR_print_errors(bio_err);
1479         goto end;
1480     }
1481 #endif
1482 
1483     /* Process SSL_CONF arguments */
1484     SSL_CONF_CTX_set_ssl_ctx(c_cctx, c_ctx);
1485     SSL_CONF_CTX_set_ssl_ctx(s_cctx, s_ctx);
1486     SSL_CONF_CTX_set_ssl_ctx(s_cctx2, s_ctx2);
1487 
1488     for (i = 0; i < sk_OPENSSL_STRING_num(conf_args); i += 2) {
1489         int rv;
1490         arg = sk_OPENSSL_STRING_value(conf_args, i);
1491         argn = sk_OPENSSL_STRING_value(conf_args, i + 1);
1492         rv = SSL_CONF_cmd(c_cctx, arg, argn);
1493         /* If not recognised use server context */
1494         if (rv == -2) {
1495             rv = SSL_CONF_cmd(s_cctx2, arg, argn);
1496             if (rv > 0)
1497                 rv = SSL_CONF_cmd(s_cctx, arg, argn);
1498         }
1499         if (rv <= 0) {
1500             BIO_printf(bio_err, "Error processing %s %s\n",
1501                        arg, argn ? argn : "");
1502             ERR_print_errors(bio_err);
1503             goto end;
1504         }
1505     }
1506 
1507     if (!SSL_CONF_CTX_finish(s_cctx) || !SSL_CONF_CTX_finish(c_cctx) || !SSL_CONF_CTX_finish(s_cctx2)) {
1508         BIO_puts(bio_err, "Error finishing context\n");
1509         ERR_print_errors(bio_err);
1510         goto end;
1511     }
1512 #ifndef OPENSSL_NO_DH
1513     if (!no_dhe) {
1514         if (dhe1024dsa)
1515             dhpkey = get_dh1024dsa(libctx);
1516         else if (dhe512)
1517             dhpkey = get_dh512(libctx);
1518         else if (dhe4096)
1519             dhpkey = get_dh4096(libctx);
1520         else
1521             dhpkey = get_dh2048(libctx);
1522 
1523         if (dhpkey == NULL || !EVP_PKEY_up_ref(dhpkey)) {
1524             EVP_PKEY_free(dhpkey);
1525             BIO_puts(bio_err, "Error getting DH parameters\n");
1526             ERR_print_errors(bio_err);
1527             goto end;
1528         }
1529         if (!SSL_CTX_set0_tmp_dh_pkey(s_ctx, dhpkey))
1530             EVP_PKEY_free(dhpkey);
1531         if (!SSL_CTX_set0_tmp_dh_pkey(s_ctx2, dhpkey))
1532             EVP_PKEY_free(dhpkey);
1533     }
1534 #endif
1535 
1536     if (!(SSL_CTX_load_verify_file(s_ctx, CAfile)
1537           || SSL_CTX_load_verify_dir(s_ctx, CApath))
1538         || !SSL_CTX_set_default_verify_paths(s_ctx)
1539         || !(SSL_CTX_load_verify_file(s_ctx2, CAfile)
1540              || SSL_CTX_load_verify_dir(s_ctx2, CApath))
1541         || !SSL_CTX_set_default_verify_paths(s_ctx2)
1542         || !(SSL_CTX_load_verify_file(c_ctx, CAfile)
1543              || SSL_CTX_load_verify_dir(c_ctx, CApath))
1544         || !SSL_CTX_set_default_verify_paths(c_ctx)) {
1545         ERR_print_errors(bio_err);
1546     }
1547 
1548 #ifndef OPENSSL_NO_CT
1549     if (!SSL_CTX_set_default_ctlog_list_file(s_ctx) ||
1550         !SSL_CTX_set_default_ctlog_list_file(s_ctx2) ||
1551         !SSL_CTX_set_default_ctlog_list_file(c_ctx)) {
1552         ERR_print_errors(bio_err);
1553     }
1554 #endif
1555 
1556     if (client_auth) {
1557         printf("client authentication\n");
1558         SSL_CTX_set_verify(s_ctx,
1559                            SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1560                            verify_callback);
1561         SSL_CTX_set_verify(s_ctx2,
1562                            SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1563                            verify_callback);
1564         SSL_CTX_set_cert_verify_callback(s_ctx, app_verify_callback,
1565                                          &app_verify_arg);
1566         SSL_CTX_set_cert_verify_callback(s_ctx2, app_verify_callback,
1567                                          &app_verify_arg);
1568     }
1569     if (server_auth) {
1570         printf("server authentication\n");
1571         SSL_CTX_set_verify(c_ctx, SSL_VERIFY_PEER, verify_callback);
1572         SSL_CTX_set_cert_verify_callback(c_ctx, app_verify_callback,
1573                                          &app_verify_arg);
1574     }
1575 
1576     {
1577         int session_id_context = 0;
1578         if (!SSL_CTX_set_session_id_context(s_ctx, (void *)&session_id_context,
1579                                             sizeof(session_id_context)) ||
1580             !SSL_CTX_set_session_id_context(s_ctx2, (void *)&session_id_context,
1581                                             sizeof(session_id_context))) {
1582             ERR_print_errors(bio_err);
1583             goto end;
1584         }
1585     }
1586 
1587     /* Use PSK only if PSK key is given */
1588     if (psk_key != NULL) {
1589         /*
1590          * no_psk is used to avoid putting psk command to openssl tool
1591          */
1592         if (no_psk) {
1593             /*
1594              * if PSK is not compiled in and psk key is given, do nothing and
1595              * exit successfully
1596              */
1597             ret = EXIT_SUCCESS;
1598             goto end;
1599         }
1600 #ifndef OPENSSL_NO_PSK
1601         SSL_CTX_set_psk_client_callback(c_ctx, psk_client_callback);
1602         SSL_CTX_set_psk_server_callback(s_ctx, psk_server_callback);
1603         SSL_CTX_set_psk_server_callback(s_ctx2, psk_server_callback);
1604         if (debug)
1605             BIO_printf(bio_err, "setting PSK identity hint to s_ctx\n");
1606         if (!SSL_CTX_use_psk_identity_hint(s_ctx, "ctx server identity_hint") ||
1607             !SSL_CTX_use_psk_identity_hint(s_ctx2, "ctx server identity_hint")) {
1608             BIO_printf(bio_err, "error setting PSK identity hint to s_ctx\n");
1609             ERR_print_errors(bio_err);
1610             goto end;
1611         }
1612 #endif
1613     }
1614 
1615 #ifndef OPENSSL_NO_NEXTPROTONEG
1616     if (npn_client) {
1617         SSL_CTX_set_next_proto_select_cb(c_ctx, cb_client_npn, NULL);
1618     }
1619     if (npn_server) {
1620         if (npn_server_reject) {
1621             BIO_printf(bio_err,
1622                        "Can't have both -npn_server and -npn_server_reject\n");
1623             goto end;
1624         }
1625         SSL_CTX_set_npn_advertised_cb(s_ctx, cb_server_npn, NULL);
1626         SSL_CTX_set_npn_advertised_cb(s_ctx2, cb_server_npn, NULL);
1627     }
1628     if (npn_server_reject) {
1629         SSL_CTX_set_npn_advertised_cb(s_ctx, cb_server_rejects_npn, NULL);
1630         SSL_CTX_set_npn_advertised_cb(s_ctx2, cb_server_rejects_npn, NULL);
1631     }
1632 #endif
1633 
1634     if (serverinfo_sct) {
1635         if (!SSL_CTX_add_client_custom_ext(c_ctx,
1636                 TLSEXT_TYPE_signed_certificate_timestamp,
1637                 NULL, NULL, NULL,
1638                 serverinfo_cli_parse_cb, NULL)) {
1639             BIO_printf(bio_err, "Error adding SCT extension\n");
1640             goto end;
1641         }
1642     }
1643     if (serverinfo_tack) {
1644         if (!SSL_CTX_add_client_custom_ext(c_ctx, TACK_EXT_TYPE,
1645                                       NULL, NULL, NULL,
1646                                       serverinfo_cli_parse_cb, NULL)) {
1647             BIO_printf(bio_err, "Error adding TACK extension\n");
1648             goto end;
1649         }
1650     }
1651     if (serverinfo_file)
1652         if (!SSL_CTX_use_serverinfo_file(s_ctx, serverinfo_file) ||
1653             !SSL_CTX_use_serverinfo_file(s_ctx2, serverinfo_file)) {
1654             BIO_printf(bio_err, "missing serverinfo file\n");
1655             goto end;
1656         }
1657 
1658     if (custom_ext) {
1659         if (!SSL_CTX_add_client_custom_ext(c_ctx, CUSTOM_EXT_TYPE_0,
1660                                       custom_ext_0_cli_add_cb,
1661                                       NULL, NULL,
1662                                       custom_ext_0_cli_parse_cb, NULL)
1663             || !SSL_CTX_add_client_custom_ext(c_ctx, CUSTOM_EXT_TYPE_1,
1664                                       custom_ext_1_cli_add_cb,
1665                                       NULL, NULL,
1666                                       custom_ext_1_cli_parse_cb, NULL)
1667             || !SSL_CTX_add_client_custom_ext(c_ctx, CUSTOM_EXT_TYPE_2,
1668                                       custom_ext_2_cli_add_cb,
1669                                       NULL, NULL,
1670                                       custom_ext_2_cli_parse_cb, NULL)
1671             || !SSL_CTX_add_client_custom_ext(c_ctx, CUSTOM_EXT_TYPE_3,
1672                                       custom_ext_3_cli_add_cb,
1673                                       NULL, NULL,
1674                                       custom_ext_3_cli_parse_cb, NULL)
1675             || !SSL_CTX_add_server_custom_ext(s_ctx, CUSTOM_EXT_TYPE_0,
1676                                       custom_ext_0_srv_add_cb,
1677                                       NULL, NULL,
1678                                       custom_ext_0_srv_parse_cb, NULL)
1679             || !SSL_CTX_add_server_custom_ext(s_ctx2, CUSTOM_EXT_TYPE_0,
1680                                       custom_ext_0_srv_add_cb,
1681                                       NULL, NULL,
1682                                       custom_ext_0_srv_parse_cb, NULL)
1683             || !SSL_CTX_add_server_custom_ext(s_ctx, CUSTOM_EXT_TYPE_1,
1684                                       custom_ext_1_srv_add_cb,
1685                                       NULL, NULL,
1686                                       custom_ext_1_srv_parse_cb, NULL)
1687             || !SSL_CTX_add_server_custom_ext(s_ctx2, CUSTOM_EXT_TYPE_1,
1688                                       custom_ext_1_srv_add_cb,
1689                                       NULL, NULL,
1690                                       custom_ext_1_srv_parse_cb, NULL)
1691             || !SSL_CTX_add_server_custom_ext(s_ctx, CUSTOM_EXT_TYPE_2,
1692                                       custom_ext_2_srv_add_cb,
1693                                       NULL, NULL,
1694                                       custom_ext_2_srv_parse_cb, NULL)
1695             || !SSL_CTX_add_server_custom_ext(s_ctx2, CUSTOM_EXT_TYPE_2,
1696                                       custom_ext_2_srv_add_cb,
1697                                       NULL, NULL,
1698                                       custom_ext_2_srv_parse_cb, NULL)
1699             || !SSL_CTX_add_server_custom_ext(s_ctx, CUSTOM_EXT_TYPE_3,
1700                                       custom_ext_3_srv_add_cb,
1701                                       NULL, NULL,
1702                                       custom_ext_3_srv_parse_cb, NULL)
1703             || !SSL_CTX_add_server_custom_ext(s_ctx2, CUSTOM_EXT_TYPE_3,
1704                                       custom_ext_3_srv_add_cb,
1705                                       NULL, NULL,
1706                                       custom_ext_3_srv_parse_cb, NULL)) {
1707             BIO_printf(bio_err, "Error setting custom extensions\n");
1708             goto end;
1709         }
1710     }
1711 
1712     if (alpn_server)
1713         SSL_CTX_set_alpn_select_cb(s_ctx, cb_server_alpn, alpn_server);
1714     if (alpn_server2)
1715         SSL_CTX_set_alpn_select_cb(s_ctx2, cb_server_alpn, alpn_server2);
1716 
1717     if (alpn_client) {
1718         size_t alpn_len;
1719         unsigned char *alpn = next_protos_parse(&alpn_len, alpn_client);
1720 
1721         if (alpn == NULL) {
1722             BIO_printf(bio_err, "Error parsing -alpn_client argument\n");
1723             goto end;
1724         }
1725         /* Returns 0 on success!! */
1726         if (SSL_CTX_set_alpn_protos(c_ctx, alpn, alpn_len)) {
1727             BIO_printf(bio_err, "Error setting ALPN\n");
1728             OPENSSL_free(alpn);
1729             goto end;
1730         }
1731         OPENSSL_free(alpn);
1732     }
1733 
1734     if (server_sess_in != NULL) {
1735         server_sess = read_session(server_sess_in);
1736         if (server_sess == NULL)
1737             goto end;
1738     }
1739     if (client_sess_in != NULL) {
1740         client_sess = read_session(client_sess_in);
1741         if (client_sess == NULL)
1742             goto end;
1743     }
1744 
1745     if (server_sess_out != NULL || server_sess_in != NULL) {
1746         char *keys;
1747         long size;
1748 
1749         /* Use a fixed key so that we can decrypt the ticket. */
1750         size = SSL_CTX_set_tlsext_ticket_keys(s_ctx, NULL, 0);
1751         keys = OPENSSL_zalloc(size);
1752         if (keys == NULL)
1753             goto end;
1754         SSL_CTX_set_tlsext_ticket_keys(s_ctx, keys, size);
1755         OPENSSL_free(keys);
1756     }
1757 
1758     if (sn_server1 != NULL || sn_server2 != NULL)
1759         SSL_CTX_set_tlsext_servername_callback(s_ctx, servername_cb);
1760 
1761     c_ssl = SSL_new(c_ctx);
1762     s_ssl = SSL_new(s_ctx);
1763     if (c_ssl == NULL || s_ssl == NULL)
1764         goto end;
1765 
1766     if (sn_client)
1767         SSL_set_tlsext_host_name(c_ssl, sn_client);
1768     if (client_ktls)
1769         SSL_set_options(c_ssl, SSL_OP_ENABLE_KTLS);
1770     if (server_ktls)
1771         SSL_set_options(s_ssl, SSL_OP_ENABLE_KTLS);
1772 
1773     if (!set_protocol_version(server_min_proto, s_ssl, SSL_CTRL_SET_MIN_PROTO_VERSION))
1774         goto end;
1775     if (!set_protocol_version(server_max_proto, s_ssl, SSL_CTRL_SET_MAX_PROTO_VERSION))
1776         goto end;
1777     if (!set_protocol_version(client_min_proto, c_ssl, SSL_CTRL_SET_MIN_PROTO_VERSION))
1778         goto end;
1779     if (!set_protocol_version(client_max_proto, c_ssl, SSL_CTRL_SET_MAX_PROTO_VERSION))
1780         goto end;
1781 
1782     if (server_sess) {
1783         if (SSL_CTX_add_session(s_ctx, server_sess) == 0) {
1784             BIO_printf(bio_err, "Can't add server session\n");
1785             ERR_print_errors(bio_err);
1786             goto end;
1787         }
1788     }
1789 
1790     BIO_printf(bio_stdout, "Doing handshakes=%d bytes=%ld\n", number, bytes);
1791     for (i = 0; i < number; i++) {
1792         if (!reuse) {
1793             if (!SSL_set_session(c_ssl, NULL)) {
1794                 BIO_printf(bio_err, "Failed to set session\n");
1795                 goto end;
1796             }
1797         }
1798         if (client_sess_in != NULL) {
1799             if (SSL_set_session(c_ssl, client_sess) == 0) {
1800                 BIO_printf(bio_err, "Can't set client session\n");
1801                 ERR_print_errors(bio_err);
1802                 goto end;
1803             }
1804         }
1805         switch (bio_type) {
1806         case BIO_MEM:
1807             ret = doit(s_ssl, c_ssl, bytes);
1808             break;
1809         case BIO_PAIR:
1810             ret = doit_biopair(s_ssl, c_ssl, bytes, &s_time, &c_time);
1811             break;
1812 #ifndef OPENSSL_NO_SOCK
1813         case BIO_IPV4:
1814             ret = doit_localhost(s_ssl, c_ssl, BIO_FAMILY_IPV4,
1815                                  bytes, &s_time, &c_time);
1816             break;
1817         case BIO_IPV6:
1818             ret = doit_localhost(s_ssl, c_ssl, BIO_FAMILY_IPV6,
1819                                  bytes, &s_time, &c_time);
1820             break;
1821 #else
1822         case BIO_IPV4:
1823         case BIO_IPV6:
1824             ret = EXIT_FAILURE;
1825             goto end;
1826 #endif
1827         }
1828         if (ret != EXIT_SUCCESS)
1829             break;
1830     }
1831 
1832     if (should_negotiate && ret == EXIT_SUCCESS &&
1833         strcmp(should_negotiate, "fail-server") != 0 &&
1834         strcmp(should_negotiate, "fail-client") != 0) {
1835         int version = protocol_from_string(should_negotiate);
1836         if (version < 0) {
1837             BIO_printf(bio_err, "Error parsing: %s\n", should_negotiate);
1838             ret = EXIT_FAILURE;
1839             goto end;
1840         }
1841         if (SSL_version(c_ssl) != version) {
1842             BIO_printf(bio_err, "Unexpected version negotiated. "
1843                 "Expected: %s, got %s\n", should_negotiate, SSL_get_version(c_ssl));
1844             ret = EXIT_FAILURE;
1845             goto end;
1846         }
1847     }
1848 
1849     if (should_reuse != -1) {
1850         if (SSL_session_reused(s_ssl) != should_reuse ||
1851             SSL_session_reused(c_ssl) != should_reuse) {
1852             BIO_printf(bio_err, "Unexpected session reuse state. "
1853                 "Expected: %d, server: %d, client: %d\n", should_reuse,
1854                 SSL_session_reused(s_ssl), SSL_session_reused(c_ssl));
1855             ret = EXIT_FAILURE;
1856             goto end;
1857         }
1858     }
1859 
1860     if (server_sess_out != NULL) {
1861         if (write_session(server_sess_out, SSL_get_session(s_ssl)) == 0) {
1862             ret = EXIT_FAILURE;
1863             goto end;
1864         }
1865     }
1866     if (client_sess_out != NULL) {
1867         if (write_session(client_sess_out, SSL_get_session(c_ssl)) == 0) {
1868             ret = EXIT_FAILURE;
1869             goto end;
1870         }
1871     }
1872 
1873     if (!verbose) {
1874         print_details(c_ssl, "");
1875     }
1876     if (print_time) {
1877 #ifdef CLOCKS_PER_SEC
1878         /*
1879          * "To determine the time in seconds, the value returned by the clock
1880          * function should be divided by the value of the macro
1881          * CLOCKS_PER_SEC." -- ISO/IEC 9899
1882          */
1883         BIO_printf(bio_stdout, "Approximate total server time: %6.2f s\n"
1884                    "Approximate total client time: %6.2f s\n",
1885                    (double)s_time / CLOCKS_PER_SEC,
1886                    (double)c_time / CLOCKS_PER_SEC);
1887 #else
1888         BIO_printf(bio_stdout,
1889                    "Approximate total server time: %6.2f units\n"
1890                    "Approximate total client time: %6.2f units\n",
1891                    (double)s_time, (double)c_time);
1892 #endif
1893     }
1894 
1895  end:
1896     SSL_free(s_ssl);
1897     SSL_free(c_ssl);
1898     SSL_CTX_free(s_ctx);
1899     SSL_CTX_free(s_ctx2);
1900     SSL_CTX_free(c_ctx);
1901     SSL_CONF_CTX_free(s_cctx);
1902     SSL_CONF_CTX_free(s_cctx2);
1903     SSL_CONF_CTX_free(c_cctx);
1904     sk_OPENSSL_STRING_free(conf_args);
1905 
1906     BIO_free(bio_stdout);
1907 
1908     SSL_SESSION_free(server_sess);
1909     SSL_SESSION_free(client_sess);
1910 
1911     OSSL_PROVIDER_unload(defctxnull);
1912     OSSL_PROVIDER_unload(thisprov);
1913     OSSL_LIB_CTX_free(libctx);
1914 
1915     BIO_free(bio_err);
1916     EXIT(ret);
1917 }
1918 
1919 #ifndef OPENSSL_NO_SOCK
1920 int doit_localhost(SSL *s_ssl, SSL *c_ssl, int family, long count,
1921                    clock_t *s_time, clock_t *c_time)
1922 {
1923     long cw_num = count, cr_num = count, sw_num = count, sr_num = count;
1924     BIO *s_ssl_bio = NULL, *c_ssl_bio = NULL;
1925     BIO *acpt = NULL, *server = NULL, *client = NULL;
1926     char addr_str[40];
1927     int ret = EXIT_FAILURE;
1928     int err_in_client = 0;
1929     int err_in_server = 0;
1930 
1931     acpt = BIO_new_accept(family == BIO_FAMILY_IPV4 ? "127.0.0.1:0"
1932                                                     : "[::1]:0");
1933     if (acpt == NULL)
1934         goto err;
1935     BIO_set_accept_ip_family(acpt, family);
1936     BIO_set_bind_mode(acpt, BIO_SOCK_NONBLOCK | BIO_SOCK_REUSEADDR);
1937     if (BIO_do_accept(acpt) <= 0)
1938         goto err;
1939 
1940     BIO_snprintf(addr_str, sizeof(addr_str), ":%s", BIO_get_accept_port(acpt));
1941 
1942     client = BIO_new_connect(addr_str);
1943     if (!client)
1944         goto err;
1945     BIO_set_conn_ip_family(client, family);
1946 
1947     if (BIO_set_nbio(client, 1) <= 0)
1948         goto err;
1949     if (BIO_set_nbio(acpt, 1) <= 0)
1950         goto err;
1951 
1952     {
1953         int st_connect = 0, st_accept = 0;
1954 
1955         while(!st_connect || !st_accept) {
1956             if (!st_connect) {
1957                 if (BIO_do_connect(client) <= 0) {
1958                     if (!BIO_should_retry(client))
1959                         goto err;
1960                 } else {
1961                     st_connect = 1;
1962                 }
1963             }
1964             if (!st_accept) {
1965                 if (BIO_do_accept(acpt) <= 0) {
1966                     if (!BIO_should_retry(acpt))
1967                         goto err;
1968                 } else {
1969                     st_accept = 1;
1970                 }
1971             }
1972         }
1973     }
1974     /* We're not interested in accepting further connects */
1975     server = BIO_pop(acpt);
1976     BIO_free_all(acpt);
1977     acpt = NULL;
1978 
1979     s_ssl_bio = BIO_new(BIO_f_ssl());
1980     if (!s_ssl_bio)
1981         goto err;
1982 
1983     c_ssl_bio = BIO_new(BIO_f_ssl());
1984     if (!c_ssl_bio)
1985         goto err;
1986 
1987     SSL_set_connect_state(c_ssl);
1988     SSL_set_bio(c_ssl, client, client);
1989     (void)BIO_set_ssl(c_ssl_bio, c_ssl, BIO_NOCLOSE);
1990 
1991     SSL_set_accept_state(s_ssl);
1992     SSL_set_bio(s_ssl, server, server);
1993     (void)BIO_set_ssl(s_ssl_bio, s_ssl, BIO_NOCLOSE);
1994 
1995     do {
1996         /*-
1997          * c_ssl_bio:          SSL filter BIO
1998          *
1999          * client:             I/O for SSL library
2000          *
2001          *
2002          * server:             I/O for SSL library
2003          *
2004          * s_ssl_bio:          SSL filter BIO
2005          */
2006 
2007         /*
2008          * We have non-blocking behaviour throughout this test program, but
2009          * can be sure that there is *some* progress in each iteration; so we
2010          * don't have to worry about ..._SHOULD_READ or ..._SHOULD_WRITE --
2011          * we just try everything in each iteration
2012          */
2013 
2014         {
2015             /* CLIENT */
2016 
2017             char cbuf[1024 * 8];
2018             int i, r;
2019             clock_t c_clock = clock();
2020 
2021             memset(cbuf, 0, sizeof(cbuf));
2022 
2023             if (debug)
2024                 if (SSL_in_init(c_ssl))
2025                     printf("client waiting in SSL_connect - %s\n",
2026                            SSL_state_string_long(c_ssl));
2027 
2028             if (cw_num > 0) {
2029                 /* Write to server. */
2030 
2031                 if (cw_num > (long)sizeof(cbuf))
2032                     i = sizeof(cbuf);
2033                 else
2034                     i = (int)cw_num;
2035                 r = BIO_write(c_ssl_bio, cbuf, i);
2036                 if (r < 0) {
2037                     if (!BIO_should_retry(c_ssl_bio)) {
2038                         fprintf(stderr, "ERROR in CLIENT (write)\n");
2039                         err_in_client = 1;
2040                         goto err;
2041                     }
2042                     /*
2043                      * BIO_should_retry(...) can just be ignored here. The
2044                      * library expects us to call BIO_write with the same
2045                      * arguments again, and that's what we will do in the
2046                      * next iteration.
2047                      */
2048                 } else if (r == 0) {
2049                     fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
2050                     goto err;
2051                 } else {
2052                     if (debug)
2053                         printf("client wrote %d\n", r);
2054                     cw_num -= r;
2055                 }
2056             }
2057 
2058             if (cr_num > 0) {
2059                 /* Read from server. */
2060 
2061                 r = BIO_read(c_ssl_bio, cbuf, sizeof(cbuf));
2062                 if (r < 0) {
2063                     if (!BIO_should_retry(c_ssl_bio)) {
2064                         fprintf(stderr, "ERROR in CLIENT (read)\n");
2065                         err_in_client = 1;
2066                         goto err;
2067                     }
2068                     /*
2069                      * Again, "BIO_should_retry" can be ignored.
2070                      */
2071                 } else if (r == 0) {
2072                     fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
2073                     goto err;
2074                 } else {
2075                     if (debug)
2076                         printf("client read %d\n", r);
2077                     cr_num -= r;
2078                 }
2079             }
2080 
2081             /*
2082              * c_time and s_time increments will typically be very small
2083              * (depending on machine speed and clock tick intervals), but
2084              * sampling over a large number of connections should result in
2085              * fairly accurate figures.  We cannot guarantee a lot, however
2086              * -- if each connection lasts for exactly one clock tick, it
2087              * will be counted only for the client or only for the server or
2088              * even not at all.
2089              */
2090             *c_time += (clock() - c_clock);
2091         }
2092 
2093         {
2094             /* SERVER */
2095 
2096             char sbuf[1024 * 8];
2097             int i, r;
2098             clock_t s_clock = clock();
2099 
2100             memset(sbuf, 0, sizeof(sbuf));
2101 
2102             if (debug)
2103                 if (SSL_in_init(s_ssl))
2104                     printf("server waiting in SSL_accept - %s\n",
2105                            SSL_state_string_long(s_ssl));
2106 
2107             if (sw_num > 0) {
2108                 /* Write to client. */
2109 
2110                 if (sw_num > (long)sizeof(sbuf))
2111                     i = sizeof(sbuf);
2112                 else
2113                     i = (int)sw_num;
2114                 r = BIO_write(s_ssl_bio, sbuf, i);
2115                 if (r < 0) {
2116                     if (!BIO_should_retry(s_ssl_bio)) {
2117                         fprintf(stderr, "ERROR in SERVER (write)\n");
2118                         err_in_server = 1;
2119                         goto err;
2120                     }
2121                     /* Ignore "BIO_should_retry". */
2122                 } else if (r == 0) {
2123                     fprintf(stderr, "SSL SERVER STARTUP FAILED\n");
2124                     goto err;
2125                 } else {
2126                     if (debug)
2127                         printf("server wrote %d\n", r);
2128                     sw_num -= r;
2129                 }
2130             }
2131 
2132             if (sr_num > 0) {
2133                 /* Read from client. */
2134 
2135                 r = BIO_read(s_ssl_bio, sbuf, sizeof(sbuf));
2136                 if (r < 0) {
2137                     if (!BIO_should_retry(s_ssl_bio)) {
2138                         fprintf(stderr, "ERROR in SERVER (read)\n");
2139                         err_in_server = 1;
2140                         goto err;
2141                     }
2142                     /* blah, blah */
2143                 } else if (r == 0) {
2144                     fprintf(stderr, "SSL SERVER STARTUP FAILED\n");
2145                     goto err;
2146                 } else {
2147                     if (debug)
2148                         printf("server read %d\n", r);
2149                     sr_num -= r;
2150                 }
2151             }
2152 
2153             *s_time += (clock() - s_clock);
2154         }
2155     }
2156     while (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0);
2157 
2158     if (verbose) {
2159         print_details(c_ssl, "DONE via TCP connect: ");
2160 
2161         if (BIO_get_ktls_send(SSL_get_wbio(s_ssl))
2162                 && BIO_get_ktls_recv(SSL_get_rbio(s_ssl)))
2163             BIO_printf(bio_stdout, "Server using Kernel TLS in both directions\n");
2164         else if (BIO_get_ktls_send(SSL_get_wbio(s_ssl)))
2165             BIO_printf(bio_stdout, "Server using Kernel TLS for sending\n");
2166         else if (BIO_get_ktls_recv(SSL_get_rbio(s_ssl)))
2167             BIO_printf(bio_stdout, "Server using Kernel TLS for receiving\n");
2168 
2169         if (BIO_get_ktls_send(SSL_get_wbio(c_ssl))
2170                 && BIO_get_ktls_recv(SSL_get_rbio(c_ssl)))
2171             BIO_printf(bio_stdout, "Client using Kernel TLS in both directions\n");
2172         else if (BIO_get_ktls_send(SSL_get_wbio(c_ssl)))
2173             BIO_printf(bio_stdout, "Client using Kernel TLS for sending\n");
2174         else if (BIO_get_ktls_recv(SSL_get_rbio(c_ssl)))
2175             BIO_printf(bio_stdout, "Client using Kernel TLS for receiving\n");
2176     }
2177 # ifndef OPENSSL_NO_NEXTPROTONEG
2178     if (verify_npn(c_ssl, s_ssl) < 0)
2179         goto end;
2180 # endif
2181     if (verify_serverinfo() < 0) {
2182         fprintf(stderr, "Server info verify error\n");
2183         goto err;
2184     }
2185     if (verify_alpn(c_ssl, s_ssl) < 0
2186             || verify_servername(c_ssl, s_ssl) < 0)
2187         goto err;
2188 
2189     if (custom_ext_error) {
2190         fprintf(stderr, "Custom extension error\n");
2191         goto err;
2192     }
2193 
2194 # ifndef OPENSSL_NO_NEXTPROTONEG
2195  end:
2196 # endif
2197     ret = EXIT_SUCCESS;
2198 
2199  err:
2200     ERR_print_errors(bio_err);
2201 
2202     BIO_free_all(acpt);
2203     BIO_free(server);
2204     BIO_free(client);
2205     BIO_free(s_ssl_bio);
2206     BIO_free(c_ssl_bio);
2207 
2208     if (should_negotiate != NULL && strcmp(should_negotiate, "fail-client") == 0)
2209         ret = (err_in_client != 0) ? EXIT_SUCCESS : EXIT_FAILURE;
2210     else if (should_negotiate != NULL && strcmp(should_negotiate, "fail-server") == 0)
2211         ret = (err_in_server != 0) ? EXIT_SUCCESS : EXIT_FAILURE;
2212 
2213     return ret;
2214 }
2215 #endif
2216 
2217 int doit_biopair(SSL *s_ssl, SSL *c_ssl, long count,
2218                  clock_t *s_time, clock_t *c_time)
2219 {
2220     long cw_num = count, cr_num = count, sw_num = count, sr_num = count;
2221     BIO *s_ssl_bio = NULL, *c_ssl_bio = NULL;
2222     BIO *server = NULL, *server_io = NULL, *client = NULL, *client_io = NULL;
2223     int ret = EXIT_FAILURE;
2224     int err_in_client = 0;
2225     int err_in_server = 0;
2226 
2227     size_t bufsiz = 256;        /* small buffer for testing */
2228 
2229     if (!BIO_new_bio_pair(&server, bufsiz, &server_io, bufsiz))
2230         goto err;
2231     if (!BIO_new_bio_pair(&client, bufsiz, &client_io, bufsiz))
2232         goto err;
2233 
2234     s_ssl_bio = BIO_new(BIO_f_ssl());
2235     if (!s_ssl_bio)
2236         goto err;
2237 
2238     c_ssl_bio = BIO_new(BIO_f_ssl());
2239     if (!c_ssl_bio)
2240         goto err;
2241 
2242     SSL_set_connect_state(c_ssl);
2243     SSL_set_bio(c_ssl, client, client);
2244     (void)BIO_set_ssl(c_ssl_bio, c_ssl, BIO_NOCLOSE);
2245 
2246     SSL_set_accept_state(s_ssl);
2247     SSL_set_bio(s_ssl, server, server);
2248     (void)BIO_set_ssl(s_ssl_bio, s_ssl, BIO_NOCLOSE);
2249 
2250     do {
2251         /*-
2252          * c_ssl_bio:          SSL filter BIO
2253          *
2254          * client:             pseudo-I/O for SSL library
2255          *
2256          * client_io:          client's SSL communication; usually to be
2257          *                     relayed over some I/O facility, but in this
2258          *                     test program, we're the server, too:
2259          *
2260          * server_io:          server's SSL communication
2261          *
2262          * server:             pseudo-I/O for SSL library
2263          *
2264          * s_ssl_bio:          SSL filter BIO
2265          *
2266          * The client and the server each employ a "BIO pair":
2267          * client + client_io, server + server_io.
2268          * BIO pairs are symmetric.  A BIO pair behaves similar
2269          * to a non-blocking socketpair (but both endpoints must
2270          * be handled by the same thread).
2271          * [Here we could connect client and server to the ends
2272          * of a single BIO pair, but then this code would be less
2273          * suitable as an example for BIO pairs in general.]
2274          *
2275          * Useful functions for querying the state of BIO pair endpoints:
2276          *
2277          * BIO_ctrl_pending(bio)              number of bytes we can read now
2278          * BIO_ctrl_get_read_request(bio)     number of bytes needed to fulfill
2279          *                                      other side's read attempt
2280          * BIO_ctrl_get_write_guarantee(bio)   number of bytes we can write now
2281          *
2282          * ..._read_request is never more than ..._write_guarantee;
2283          * it depends on the application which one you should use.
2284          */
2285 
2286         /*
2287          * We have non-blocking behaviour throughout this test program, but
2288          * can be sure that there is *some* progress in each iteration; so we
2289          * don't have to worry about ..._SHOULD_READ or ..._SHOULD_WRITE --
2290          * we just try everything in each iteration
2291          */
2292 
2293         {
2294             /* CLIENT */
2295 
2296             char cbuf[1024 * 8];
2297             int i, r;
2298             clock_t c_clock = clock();
2299 
2300             memset(cbuf, 0, sizeof(cbuf));
2301 
2302             if (debug)
2303                 if (SSL_in_init(c_ssl))
2304                     printf("client waiting in SSL_connect - %s\n",
2305                            SSL_state_string_long(c_ssl));
2306 
2307             if (cw_num > 0) {
2308                 /* Write to server. */
2309 
2310                 if (cw_num > (long)sizeof(cbuf))
2311                     i = sizeof(cbuf);
2312                 else
2313                     i = (int)cw_num;
2314                 r = BIO_write(c_ssl_bio, cbuf, i);
2315                 if (r < 0) {
2316                     if (!BIO_should_retry(c_ssl_bio)) {
2317                         fprintf(stderr, "ERROR in CLIENT\n");
2318                         err_in_client = 1;
2319                         goto err;
2320                     }
2321                     /*
2322                      * BIO_should_retry(...) can just be ignored here. The
2323                      * library expects us to call BIO_write with the same
2324                      * arguments again, and that's what we will do in the
2325                      * next iteration.
2326                      */
2327                 } else if (r == 0) {
2328                     fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
2329                     goto err;
2330                 } else {
2331                     if (debug)
2332                         printf("client wrote %d\n", r);
2333                     cw_num -= r;
2334                 }
2335             }
2336 
2337             if (cr_num > 0) {
2338                 /* Read from server. */
2339 
2340                 r = BIO_read(c_ssl_bio, cbuf, sizeof(cbuf));
2341                 if (r < 0) {
2342                     if (!BIO_should_retry(c_ssl_bio)) {
2343                         fprintf(stderr, "ERROR in CLIENT\n");
2344                         err_in_client = 1;
2345                         goto err;
2346                     }
2347                     /*
2348                      * Again, "BIO_should_retry" can be ignored.
2349                      */
2350                 } else if (r == 0) {
2351                     fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
2352                     goto err;
2353                 } else {
2354                     if (debug)
2355                         printf("client read %d\n", r);
2356                     cr_num -= r;
2357                 }
2358             }
2359 
2360             /*
2361              * c_time and s_time increments will typically be very small
2362              * (depending on machine speed and clock tick intervals), but
2363              * sampling over a large number of connections should result in
2364              * fairly accurate figures.  We cannot guarantee a lot, however
2365              * -- if each connection lasts for exactly one clock tick, it
2366              * will be counted only for the client or only for the server or
2367              * even not at all.
2368              */
2369             *c_time += (clock() - c_clock);
2370         }
2371 
2372         {
2373             /* SERVER */
2374 
2375             char sbuf[1024 * 8];
2376             int i, r;
2377             clock_t s_clock = clock();
2378 
2379             memset(sbuf, 0, sizeof(sbuf));
2380 
2381             if (debug)
2382                 if (SSL_in_init(s_ssl))
2383                     printf("server waiting in SSL_accept - %s\n",
2384                            SSL_state_string_long(s_ssl));
2385 
2386             if (sw_num > 0) {
2387                 /* Write to client. */
2388 
2389                 if (sw_num > (long)sizeof(sbuf))
2390                     i = sizeof(sbuf);
2391                 else
2392                     i = (int)sw_num;
2393                 r = BIO_write(s_ssl_bio, sbuf, i);
2394                 if (r < 0) {
2395                     if (!BIO_should_retry(s_ssl_bio)) {
2396                         fprintf(stderr, "ERROR in SERVER\n");
2397                         err_in_server = 1;
2398                         goto err;
2399                     }
2400                     /* Ignore "BIO_should_retry". */
2401                 } else if (r == 0) {
2402                     fprintf(stderr, "SSL SERVER STARTUP FAILED\n");
2403                     goto err;
2404                 } else {
2405                     if (debug)
2406                         printf("server wrote %d\n", r);
2407                     sw_num -= r;
2408                 }
2409             }
2410 
2411             if (sr_num > 0) {
2412                 /* Read from client. */
2413 
2414                 r = BIO_read(s_ssl_bio, sbuf, sizeof(sbuf));
2415                 if (r < 0) {
2416                     if (!BIO_should_retry(s_ssl_bio)) {
2417                         fprintf(stderr, "ERROR in SERVER\n");
2418                         err_in_server = 1;
2419                         goto err;
2420                     }
2421                     /* blah, blah */
2422                 } else if (r == 0) {
2423                     fprintf(stderr, "SSL SERVER STARTUP FAILED\n");
2424                     goto err;
2425                 } else {
2426                     if (debug)
2427                         printf("server read %d\n", r);
2428                     sr_num -= r;
2429                 }
2430             }
2431 
2432             *s_time += (clock() - s_clock);
2433         }
2434 
2435         {
2436             /* "I/O" BETWEEN CLIENT AND SERVER. */
2437 
2438             size_t r1, r2;
2439             BIO *io1 = server_io, *io2 = client_io;
2440             /*
2441              * we use the non-copying interface for io1 and the standard
2442              * BIO_write/BIO_read interface for io2
2443              */
2444 
2445             static int prev_progress = 1;
2446             int progress = 0;
2447 
2448             /* io1 to io2 */
2449             do {
2450                 size_t num;
2451                 int r;
2452 
2453                 r1 = BIO_ctrl_pending(io1);
2454                 r2 = BIO_ctrl_get_write_guarantee(io2);
2455 
2456                 num = r1;
2457                 if (r2 < num)
2458                     num = r2;
2459                 if (num) {
2460                     char *dataptr;
2461 
2462                     if (INT_MAX < num) /* yeah, right */
2463                         num = INT_MAX;
2464 
2465                     r = BIO_nread(io1, &dataptr, (int)num);
2466                     assert(r > 0);
2467                     assert(r <= (int)num);
2468                     /*
2469                      * possibly r < num (non-contiguous data)
2470                      */
2471                     num = r;
2472                     r = BIO_write(io2, dataptr, (int)num);
2473                     if (r != (int)num) { /* can't happen */
2474                         fprintf(stderr, "ERROR: BIO_write could not write "
2475                                 "BIO_ctrl_get_write_guarantee() bytes");
2476                         goto err;
2477                     }
2478                     progress = 1;
2479 
2480                     if (debug)
2481                         printf((io1 == client_io) ?
2482                                "C->S relaying: %d bytes\n" :
2483                                "S->C relaying: %d bytes\n", (int)num);
2484                 }
2485             }
2486             while (r1 && r2);
2487 
2488             /* io2 to io1 */
2489             {
2490                 size_t num;
2491                 int r;
2492 
2493                 r1 = BIO_ctrl_pending(io2);
2494                 r2 = BIO_ctrl_get_read_request(io1);
2495                 /*
2496                  * here we could use ..._get_write_guarantee instead of
2497                  * ..._get_read_request, but by using the latter we test
2498                  * restartability of the SSL implementation more thoroughly
2499                  */
2500                 num = r1;
2501                 if (r2 < num)
2502                     num = r2;
2503                 if (num) {
2504                     char *dataptr;
2505 
2506                     if (INT_MAX < num)
2507                         num = INT_MAX;
2508 
2509                     if (num > 1)
2510                         --num;  /* test restartability even more thoroughly */
2511 
2512                     r = BIO_nwrite0(io1, &dataptr);
2513                     assert(r > 0);
2514                     if (r < (int)num)
2515                         num = r;
2516                     r = BIO_read(io2, dataptr, (int)num);
2517                     if (r != (int)num) { /* can't happen */
2518                         fprintf(stderr, "ERROR: BIO_read could not read "
2519                                 "BIO_ctrl_pending() bytes");
2520                         goto err;
2521                     }
2522                     progress = 1;
2523                     r = BIO_nwrite(io1, &dataptr, (int)num);
2524                     if (r != (int)num) { /* can't happen */
2525                         fprintf(stderr, "ERROR: BIO_nwrite() did not accept "
2526                                 "BIO_nwrite0() bytes");
2527                         goto err;
2528                     }
2529 
2530                     if (debug)
2531                         printf((io2 == client_io) ?
2532                                "C->S relaying: %d bytes\n" :
2533                                "S->C relaying: %d bytes\n", (int)num);
2534                 }
2535             }                   /* no loop, BIO_ctrl_get_read_request now
2536                                  * returns 0 anyway */
2537 
2538             if (!progress && !prev_progress)
2539                 if (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0) {
2540                     fprintf(stderr, "ERROR: got stuck\n");
2541                     fprintf(stderr, " ERROR.\n");
2542                     goto err;
2543                 }
2544             prev_progress = progress;
2545         }
2546     }
2547     while (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0);
2548 
2549     if (verbose)
2550         print_details(c_ssl, "DONE via BIO pair: ");
2551 #ifndef OPENSSL_NO_NEXTPROTONEG
2552     if (verify_npn(c_ssl, s_ssl) < 0)
2553         goto end;
2554 #endif
2555     if (verify_serverinfo() < 0) {
2556         fprintf(stderr, "Server info verify error\n");
2557         goto err;
2558     }
2559     if (verify_alpn(c_ssl, s_ssl) < 0
2560             || verify_servername(c_ssl, s_ssl) < 0)
2561         goto err;
2562 
2563     if (custom_ext_error) {
2564         fprintf(stderr, "Custom extension error\n");
2565         goto err;
2566     }
2567 
2568 #ifndef OPENSSL_NO_NEXTPROTONEG
2569  end:
2570 #endif
2571     ret = EXIT_SUCCESS;
2572 
2573  err:
2574     ERR_print_errors(bio_err);
2575 
2576     BIO_free(server);
2577     BIO_free(server_io);
2578     BIO_free(client);
2579     BIO_free(client_io);
2580     BIO_free(s_ssl_bio);
2581     BIO_free(c_ssl_bio);
2582 
2583     if (should_negotiate != NULL && strcmp(should_negotiate, "fail-client") == 0)
2584         ret = (err_in_client != 0) ? EXIT_SUCCESS : EXIT_FAILURE;
2585     else if (should_negotiate != NULL && strcmp(should_negotiate, "fail-server") == 0)
2586         ret = (err_in_server != 0) ? EXIT_SUCCESS : EXIT_FAILURE;
2587 
2588     return ret;
2589 }
2590 
2591 #define W_READ  1
2592 #define W_WRITE 2
2593 #define C_DONE  1
2594 #define S_DONE  2
2595 
2596 int doit(SSL *s_ssl, SSL *c_ssl, long count)
2597 {
2598     char *cbuf = NULL, *sbuf = NULL;
2599     long bufsiz;
2600     long cw_num = count, cr_num = count;
2601     long sw_num = count, sr_num = count;
2602     int ret = EXIT_FAILURE;
2603     BIO *c_to_s = NULL;
2604     BIO *s_to_c = NULL;
2605     BIO *c_bio = NULL;
2606     BIO *s_bio = NULL;
2607     int c_r, c_w, s_r, s_w;
2608     int i, j;
2609     int done = 0;
2610     int c_write, s_write;
2611     int do_server = 0, do_client = 0;
2612     int max_frag = 5 * 1024;
2613     int err_in_client = 0;
2614     int err_in_server = 0;
2615 
2616     bufsiz = count > 40 * 1024 ? 40 * 1024 : count;
2617 
2618     if ((cbuf = OPENSSL_zalloc(bufsiz)) == NULL)
2619         goto err;
2620     if ((sbuf = OPENSSL_zalloc(bufsiz)) == NULL)
2621         goto err;
2622 
2623     c_to_s = BIO_new(BIO_s_mem());
2624     s_to_c = BIO_new(BIO_s_mem());
2625     if ((s_to_c == NULL) || (c_to_s == NULL)) {
2626         ERR_print_errors(bio_err);
2627         goto err;
2628     }
2629 
2630     c_bio = BIO_new(BIO_f_ssl());
2631     s_bio = BIO_new(BIO_f_ssl());
2632     if ((c_bio == NULL) || (s_bio == NULL)) {
2633         ERR_print_errors(bio_err);
2634         goto err;
2635     }
2636 
2637     SSL_set_connect_state(c_ssl);
2638     SSL_set_bio(c_ssl, s_to_c, c_to_s);
2639     SSL_set_max_send_fragment(c_ssl, max_frag);
2640     BIO_set_ssl(c_bio, c_ssl, BIO_NOCLOSE);
2641 
2642     /*
2643      * We've just given our ref to these BIOs to c_ssl. We need another one to
2644      * give to s_ssl
2645      */
2646     if (!BIO_up_ref(c_to_s)) {
2647         /* c_to_s and s_to_c will get freed when we free c_ssl */
2648         c_to_s = NULL;
2649         s_to_c = NULL;
2650         goto err;
2651     }
2652     if (!BIO_up_ref(s_to_c)) {
2653         /* s_to_c will get freed when we free c_ssl */
2654         s_to_c = NULL;
2655         goto err;
2656     }
2657 
2658     SSL_set_accept_state(s_ssl);
2659     SSL_set_bio(s_ssl, c_to_s, s_to_c);
2660 
2661     /* We've used up all our refs to these now */
2662     c_to_s = NULL;
2663     s_to_c = NULL;
2664 
2665     SSL_set_max_send_fragment(s_ssl, max_frag);
2666     BIO_set_ssl(s_bio, s_ssl, BIO_NOCLOSE);
2667 
2668     c_r = 0;
2669     s_r = 1;
2670     c_w = 1;
2671     s_w = 0;
2672     c_write = 1, s_write = 0;
2673 
2674     /* We can always do writes */
2675     for (;;) {
2676         do_server = 0;
2677         do_client = 0;
2678 
2679         i = (int)BIO_pending(s_bio);
2680         if ((i && s_r) || s_w)
2681             do_server = 1;
2682 
2683         i = (int)BIO_pending(c_bio);
2684         if ((i && c_r) || c_w)
2685             do_client = 1;
2686 
2687         if (do_server && debug) {
2688             if (SSL_in_init(s_ssl))
2689                 printf("server waiting in SSL_accept - %s\n",
2690                        SSL_state_string_long(s_ssl));
2691         }
2692 
2693         if (do_client && debug) {
2694             if (SSL_in_init(c_ssl))
2695                 printf("client waiting in SSL_connect - %s\n",
2696                        SSL_state_string_long(c_ssl));
2697         }
2698 
2699         if (!do_client && !do_server) {
2700             fprintf(stdout, "ERROR IN STARTUP\n");
2701             ERR_print_errors(bio_err);
2702             goto err;
2703         }
2704         if (do_client && !(done & C_DONE)) {
2705             if (c_write) {
2706                 j = (cw_num > bufsiz) ? (int)bufsiz : (int)cw_num;
2707                 i = BIO_write(c_bio, cbuf, j);
2708                 if (i < 0) {
2709                     c_r = 0;
2710                     c_w = 0;
2711                     if (BIO_should_retry(c_bio)) {
2712                         if (BIO_should_read(c_bio))
2713                             c_r = 1;
2714                         if (BIO_should_write(c_bio))
2715                             c_w = 1;
2716                     } else {
2717                         fprintf(stderr, "ERROR in CLIENT\n");
2718                         err_in_client = 1;
2719                         ERR_print_errors(bio_err);
2720                         goto err;
2721                     }
2722                 } else if (i == 0) {
2723                     fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
2724                     goto err;
2725                 } else {
2726                     if (debug)
2727                         printf("client wrote %d\n", i);
2728                     /* ok */
2729                     s_r = 1;
2730                     c_write = 0;
2731                     cw_num -= i;
2732                     if (max_frag > 1029)
2733                         SSL_set_max_send_fragment(c_ssl, max_frag -= 5);
2734                 }
2735             } else {
2736                 i = BIO_read(c_bio, cbuf, bufsiz);
2737                 if (i < 0) {
2738                     c_r = 0;
2739                     c_w = 0;
2740                     if (BIO_should_retry(c_bio)) {
2741                         if (BIO_should_read(c_bio))
2742                             c_r = 1;
2743                         if (BIO_should_write(c_bio))
2744                             c_w = 1;
2745                     } else {
2746                         fprintf(stderr, "ERROR in CLIENT\n");
2747                         err_in_client = 1;
2748                         ERR_print_errors(bio_err);
2749                         goto err;
2750                     }
2751                 } else if (i == 0) {
2752                     fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
2753                     goto err;
2754                 } else {
2755                     if (debug)
2756                         printf("client read %d\n", i);
2757                     cr_num -= i;
2758                     if (sw_num > 0) {
2759                         s_write = 1;
2760                         s_w = 1;
2761                     }
2762                     if (cr_num <= 0) {
2763                         s_write = 1;
2764                         s_w = 1;
2765                         done = S_DONE | C_DONE;
2766                     }
2767                 }
2768             }
2769         }
2770 
2771         if (do_server && !(done & S_DONE)) {
2772             if (!s_write) {
2773                 i = BIO_read(s_bio, sbuf, bufsiz);
2774                 if (i < 0) {
2775                     s_r = 0;
2776                     s_w = 0;
2777                     if (BIO_should_retry(s_bio)) {
2778                         if (BIO_should_read(s_bio))
2779                             s_r = 1;
2780                         if (BIO_should_write(s_bio))
2781                             s_w = 1;
2782                     } else {
2783                         fprintf(stderr, "ERROR in SERVER\n");
2784                         err_in_server = 1;
2785                         ERR_print_errors(bio_err);
2786                         goto err;
2787                     }
2788                 } else if (i == 0) {
2789                     ERR_print_errors(bio_err);
2790                     fprintf(stderr,
2791                             "SSL SERVER STARTUP FAILED in SSL_read\n");
2792                     goto err;
2793                 } else {
2794                     if (debug)
2795                         printf("server read %d\n", i);
2796                     sr_num -= i;
2797                     if (cw_num > 0) {
2798                         c_write = 1;
2799                         c_w = 1;
2800                     }
2801                     if (sr_num <= 0) {
2802                         s_write = 1;
2803                         s_w = 1;
2804                         c_write = 0;
2805                     }
2806                 }
2807             } else {
2808                 j = (sw_num > bufsiz) ? (int)bufsiz : (int)sw_num;
2809                 i = BIO_write(s_bio, sbuf, j);
2810                 if (i < 0) {
2811                     s_r = 0;
2812                     s_w = 0;
2813                     if (BIO_should_retry(s_bio)) {
2814                         if (BIO_should_read(s_bio))
2815                             s_r = 1;
2816                         if (BIO_should_write(s_bio))
2817                             s_w = 1;
2818                     } else {
2819                         fprintf(stderr, "ERROR in SERVER\n");
2820                         err_in_server = 1;
2821                         ERR_print_errors(bio_err);
2822                         goto err;
2823                     }
2824                 } else if (i == 0) {
2825                     ERR_print_errors(bio_err);
2826                     fprintf(stderr,
2827                             "SSL SERVER STARTUP FAILED in SSL_write\n");
2828                     goto err;
2829                 } else {
2830                     if (debug)
2831                         printf("server wrote %d\n", i);
2832                     sw_num -= i;
2833                     s_write = 0;
2834                     c_r = 1;
2835                     if (sw_num <= 0)
2836                         done |= S_DONE;
2837                     if (max_frag > 1029)
2838                         SSL_set_max_send_fragment(s_ssl, max_frag -= 5);
2839                 }
2840             }
2841         }
2842 
2843         if ((done & S_DONE) && (done & C_DONE))
2844             break;
2845     }
2846 
2847     if (verbose)
2848         print_details(c_ssl, "DONE: ");
2849 #ifndef OPENSSL_NO_NEXTPROTONEG
2850     if (verify_npn(c_ssl, s_ssl) < 0)
2851         goto err;
2852 #endif
2853     if (verify_serverinfo() < 0) {
2854         fprintf(stderr, "Server info verify error\n");
2855         goto err;
2856     }
2857     if (custom_ext_error) {
2858         fprintf(stderr, "Custom extension error\n");
2859         goto err;
2860     }
2861     ret = EXIT_SUCCESS;
2862  err:
2863     BIO_free(c_to_s);
2864     BIO_free(s_to_c);
2865     BIO_free_all(c_bio);
2866     BIO_free_all(s_bio);
2867     OPENSSL_free(cbuf);
2868     OPENSSL_free(sbuf);
2869 
2870     if (should_negotiate != NULL && strcmp(should_negotiate, "fail-client") == 0)
2871         ret = (err_in_client != 0) ? EXIT_SUCCESS : EXIT_FAILURE;
2872     else if (should_negotiate != NULL && strcmp(should_negotiate, "fail-server") == 0)
2873         ret = (err_in_server != 0) ? EXIT_SUCCESS : EXIT_FAILURE;
2874 
2875     return ret;
2876 }
2877 
2878 static int verify_callback(int ok, X509_STORE_CTX *ctx)
2879 {
2880     char *s, buf[256];
2881 
2882     s = X509_NAME_oneline(X509_get_subject_name(X509_STORE_CTX_get_current_cert(ctx)),
2883                           buf, sizeof(buf));
2884     if (s != NULL) {
2885         if (ok)
2886             printf("depth=%d %s\n", X509_STORE_CTX_get_error_depth(ctx), buf);
2887         else {
2888             fprintf(stderr, "depth=%d error=%d %s\n",
2889                     X509_STORE_CTX_get_error_depth(ctx),
2890                     X509_STORE_CTX_get_error(ctx), buf);
2891         }
2892     }
2893 
2894     if (ok == 0) {
2895         int i = X509_STORE_CTX_get_error(ctx);
2896 
2897         switch (i) {
2898         default:
2899             fprintf(stderr, "Error string: %s\n",
2900                     X509_verify_cert_error_string(i));
2901             break;
2902         case X509_V_ERR_CERT_NOT_YET_VALID:
2903         case X509_V_ERR_CERT_HAS_EXPIRED:
2904         case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
2905             ok = 1;
2906             break;
2907         }
2908     }
2909 
2910     return ok;
2911 }
2912 
2913 static int app_verify_callback(X509_STORE_CTX *ctx, void *arg)
2914 {
2915     int ok = 1;
2916     struct app_verify_arg *cb_arg = arg;
2917 
2918     if (cb_arg->app_verify) {
2919         char *s = NULL, buf[256];
2920         X509 *c = X509_STORE_CTX_get0_cert(ctx);
2921 
2922         printf("In app_verify_callback, allowing cert. ");
2923         printf("Arg is: %s\n", cb_arg->string);
2924         printf("Finished printing do we have a context? 0x%p a cert? 0x%p\n",
2925                 (void *)ctx, (void *)c);
2926         if (c)
2927             s = X509_NAME_oneline(X509_get_subject_name(c), buf, 256);
2928         if (s != NULL) {
2929             printf("cert depth=%d %s\n",
2930                     X509_STORE_CTX_get_error_depth(ctx), buf);
2931         }
2932         return 1;
2933     }
2934 
2935     ok = X509_verify_cert(ctx);
2936 
2937     return ok;
2938 }
2939 
2940 #ifndef OPENSSL_NO_PSK
2941 /* convert the PSK key (psk_key) in ascii to binary (psk) */
2942 static int psk_key2bn(const char *pskkey, unsigned char *psk,
2943                       unsigned int max_psk_len)
2944 {
2945     int ret;
2946     BIGNUM *bn = NULL;
2947 
2948     ret = BN_hex2bn(&bn, pskkey);
2949     if (!ret) {
2950         BIO_printf(bio_err, "Could not convert PSK key '%s' to BIGNUM\n",
2951                    pskkey);
2952         BN_free(bn);
2953         return 0;
2954     }
2955     if (BN_num_bytes(bn) > (int)max_psk_len) {
2956         BIO_printf(bio_err,
2957                    "psk buffer of callback is too small (%d) for key (%d)\n",
2958                    max_psk_len, BN_num_bytes(bn));
2959         BN_free(bn);
2960         return 0;
2961     }
2962     ret = BN_bn2bin(bn, psk);
2963     BN_free(bn);
2964     return ret;
2965 }
2966 
2967 static unsigned int psk_client_callback(SSL *ssl, const char *hint,
2968                                         char *identity,
2969                                         unsigned int max_identity_len,
2970                                         unsigned char *psk,
2971                                         unsigned int max_psk_len)
2972 {
2973     int ret;
2974     unsigned int psk_len = 0;
2975 
2976     ret = BIO_snprintf(identity, max_identity_len, "Client_identity");
2977     if (ret < 0)
2978         goto out_err;
2979     if (debug)
2980         fprintf(stderr, "client: created identity '%s' len=%d\n", identity,
2981                 ret);
2982     ret = psk_key2bn(psk_key, psk, max_psk_len);
2983     if (ret < 0)
2984         goto out_err;
2985     psk_len = ret;
2986  out_err:
2987     return psk_len;
2988 }
2989 
2990 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
2991                                         unsigned char *psk,
2992                                         unsigned int max_psk_len)
2993 {
2994     unsigned int psk_len = 0;
2995 
2996     if (strcmp(identity, "Client_identity") != 0) {
2997         BIO_printf(bio_err, "server: PSK error: client identity not found\n");
2998         return 0;
2999     }
3000     psk_len = psk_key2bn(psk_key, psk, max_psk_len);
3001     return psk_len;
3002 }
3003 #endif
3004