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