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