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