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