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