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