abcbad4738299f35dc04c0e7cfc3e7de54f7cd34
[openssl.git] / apps / s_cb.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110
111 /* callback functions used by s_client, s_server, and s_time */
112 #include <stdio.h>
113 #include <stdlib.h>
114 #include <string.h> /* for memcpy() and strcmp() */
115 #define USE_SOCKETS
116 #include "apps.h"
117 #undef USE_SOCKETS
118 #include <openssl/err.h>
119 #include <openssl/rand.h>
120 #include <openssl/x509.h>
121 #include <openssl/ssl.h>
122 #include <openssl/bn.h>
123 #ifndef OPENSSL_NO_DH
124 # include <openssl/dh.h>
125 #endif
126 #include "s_apps.h"
127
128 #define COOKIE_SECRET_LENGTH    16
129
130 int verify_depth = 0;
131 int verify_quiet = 0;
132 int verify_error = X509_V_OK;
133 int verify_return_error = 0;
134 #ifndef OPENSSL_NO_SOCK
135 static unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
136 static int cookie_initialized = 0;
137 #endif
138
139 static const char *lookup(int val, const STRINT_PAIR* list, const char* def)
140 {
141     for ( ; list->name; ++list)
142         if (list->retval == val)
143             return list->name;
144     return def;
145 }
146
147 int verify_callback(int ok, X509_STORE_CTX *ctx)
148 {
149     X509 *err_cert;
150     int err, depth;
151
152     err_cert = X509_STORE_CTX_get_current_cert(ctx);
153     err = X509_STORE_CTX_get_error(ctx);
154     depth = X509_STORE_CTX_get_error_depth(ctx);
155
156     if (!verify_quiet || !ok) {
157         BIO_printf(bio_err, "depth=%d ", depth);
158         if (err_cert) {
159             X509_NAME_print_ex(bio_err,
160                                X509_get_subject_name(err_cert),
161                                0, XN_FLAG_ONELINE);
162             BIO_puts(bio_err, "\n");
163         } else
164             BIO_puts(bio_err, "<no cert>\n");
165     }
166     if (!ok) {
167         BIO_printf(bio_err, "verify error:num=%d:%s\n", err,
168                    X509_verify_cert_error_string(err));
169         if (verify_depth >= depth) {
170             if (!verify_return_error)
171                 ok = 1;
172             verify_error = err;
173         } else {
174             ok = 0;
175             verify_error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
176         }
177     }
178     switch (err) {
179     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
180         BIO_puts(bio_err, "issuer= ");
181         X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert),
182                            0, XN_FLAG_ONELINE);
183         BIO_puts(bio_err, "\n");
184         break;
185     case X509_V_ERR_CERT_NOT_YET_VALID:
186     case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
187         BIO_printf(bio_err, "notBefore=");
188         ASN1_TIME_print(bio_err, X509_get_notBefore(err_cert));
189         BIO_printf(bio_err, "\n");
190         break;
191     case X509_V_ERR_CERT_HAS_EXPIRED:
192     case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
193         BIO_printf(bio_err, "notAfter=");
194         ASN1_TIME_print(bio_err, X509_get_notAfter(err_cert));
195         BIO_printf(bio_err, "\n");
196         break;
197     case X509_V_ERR_NO_EXPLICIT_POLICY:
198         if (!verify_quiet)
199             policies_print(ctx);
200         break;
201     }
202     if (err == X509_V_OK && ok == 2 && !verify_quiet)
203         policies_print(ctx);
204     if (ok && !verify_quiet)
205         BIO_printf(bio_err, "verify return:%d\n", ok);
206     return (ok);
207 }
208
209 int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file)
210 {
211     if (cert_file != NULL) {
212         if (SSL_CTX_use_certificate_file(ctx, cert_file,
213                                          SSL_FILETYPE_PEM) <= 0) {
214             BIO_printf(bio_err, "unable to get certificate from '%s'\n",
215                        cert_file);
216             ERR_print_errors(bio_err);
217             return (0);
218         }
219         if (key_file == NULL)
220             key_file = cert_file;
221         if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) {
222             BIO_printf(bio_err, "unable to get private key from '%s'\n",
223                        key_file);
224             ERR_print_errors(bio_err);
225             return (0);
226         }
227
228         /*
229          * If we are using DSA, we can copy the parameters from the private
230          * key
231          */
232
233         /*
234          * Now we know that a key and cert have been set against the SSL
235          * context
236          */
237         if (!SSL_CTX_check_private_key(ctx)) {
238             BIO_printf(bio_err,
239                        "Private key does not match the certificate public key\n");
240             return (0);
241         }
242     }
243     return (1);
244 }
245
246 int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key,
247                        STACK_OF(X509) *chain, int build_chain)
248 {
249     int chflags = chain ? SSL_BUILD_CHAIN_FLAG_CHECK : 0;
250     if (cert == NULL)
251         return 1;
252     if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
253         BIO_printf(bio_err, "error setting certificate\n");
254         ERR_print_errors(bio_err);
255         return 0;
256     }
257
258     if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) {
259         BIO_printf(bio_err, "error setting private key\n");
260         ERR_print_errors(bio_err);
261         return 0;
262     }
263
264     /*
265      * Now we know that a key and cert have been set against the SSL context
266      */
267     if (!SSL_CTX_check_private_key(ctx)) {
268         BIO_printf(bio_err,
269                    "Private key does not match the certificate public key\n");
270         return 0;
271     }
272     if (chain && !SSL_CTX_set1_chain(ctx, chain)) {
273         BIO_printf(bio_err, "error setting certificate chain\n");
274         ERR_print_errors(bio_err);
275         return 0;
276     }
277     if (build_chain && !SSL_CTX_build_cert_chain(ctx, chflags)) {
278         BIO_printf(bio_err, "error building certificate chain\n");
279         ERR_print_errors(bio_err);
280         return 0;
281     }
282     return 1;
283 }
284
285 static STRINT_PAIR cert_type_list[] = {
286     {"RSA sign", TLS_CT_RSA_SIGN},
287     {"DSA sign", TLS_CT_DSS_SIGN},
288     {"RSA fixed DH", TLS_CT_RSA_FIXED_DH},
289     {"DSS fixed DH", TLS_CT_DSS_FIXED_DH},
290     {"ECDSA sign", TLS_CT_ECDSA_SIGN},
291     {"RSA fixed ECDH", TLS_CT_RSA_FIXED_ECDH},
292     {"ECDSA fixed ECDH", TLS_CT_ECDSA_FIXED_ECDH},
293     {"GOST01 Sign", TLS_CT_GOST01_SIGN},
294     {NULL}
295 };
296
297 static void ssl_print_client_cert_types(BIO *bio, SSL *s)
298 {
299     const unsigned char *p;
300     int i;
301     int cert_type_num = SSL_get0_certificate_types(s, &p);
302     if (!cert_type_num)
303         return;
304     BIO_puts(bio, "Client Certificate Types: ");
305     for (i = 0; i < cert_type_num; i++) {
306         unsigned char cert_type = p[i];
307         const char *cname = lookup((int)cert_type, cert_type_list, NULL);
308
309         if (i)
310             BIO_puts(bio, ", ");
311         if (cname)
312             BIO_puts(bio, cname);
313         else
314             BIO_printf(bio, "UNKNOWN (%d),", cert_type);
315     }
316     BIO_puts(bio, "\n");
317 }
318
319 static int do_print_sigalgs(BIO *out, SSL *s, int shared)
320 {
321     int i, nsig, client;
322     client = SSL_is_server(s) ? 0 : 1;
323     if (shared)
324         nsig = SSL_get_shared_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
325     else
326         nsig = SSL_get_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
327     if (nsig == 0)
328         return 1;
329
330     if (shared)
331         BIO_puts(out, "Shared ");
332
333     if (client)
334         BIO_puts(out, "Requested ");
335     BIO_puts(out, "Signature Algorithms: ");
336     for (i = 0; i < nsig; i++) {
337         int hash_nid, sign_nid;
338         unsigned char rhash, rsign;
339         const char *sstr = NULL;
340         if (shared)
341             SSL_get_shared_sigalgs(s, i, &sign_nid, &hash_nid, NULL,
342                                    &rsign, &rhash);
343         else
344             SSL_get_sigalgs(s, i, &sign_nid, &hash_nid, NULL, &rsign, &rhash);
345         if (i)
346             BIO_puts(out, ":");
347         if (sign_nid == EVP_PKEY_RSA)
348             sstr = "RSA";
349         else if (sign_nid == EVP_PKEY_DSA)
350             sstr = "DSA";
351         else if (sign_nid == EVP_PKEY_EC)
352             sstr = "ECDSA";
353         if (sstr)
354             BIO_printf(out, "%s+", sstr);
355         else
356             BIO_printf(out, "0x%02X+", (int)rsign);
357         if (hash_nid != NID_undef)
358             BIO_printf(out, "%s", OBJ_nid2sn(hash_nid));
359         else
360             BIO_printf(out, "0x%02X", (int)rhash);
361     }
362     BIO_puts(out, "\n");
363     return 1;
364 }
365
366 int ssl_print_sigalgs(BIO *out, SSL *s)
367 {
368     int mdnid;
369     if (!SSL_is_server(s))
370         ssl_print_client_cert_types(out, s);
371     do_print_sigalgs(out, s, 0);
372     do_print_sigalgs(out, s, 1);
373     if (SSL_get_peer_signature_nid(s, &mdnid))
374         BIO_printf(out, "Peer signing digest: %s\n", OBJ_nid2sn(mdnid));
375     return 1;
376 }
377
378 #ifndef OPENSSL_NO_EC
379 int ssl_print_point_formats(BIO *out, SSL *s)
380 {
381     int i, nformats;
382     const char *pformats;
383     nformats = SSL_get0_ec_point_formats(s, &pformats);
384     if (nformats <= 0)
385         return 1;
386     BIO_puts(out, "Supported Elliptic Curve Point Formats: ");
387     for (i = 0; i < nformats; i++, pformats++) {
388         if (i)
389             BIO_puts(out, ":");
390         switch (*pformats) {
391         case TLSEXT_ECPOINTFORMAT_uncompressed:
392             BIO_puts(out, "uncompressed");
393             break;
394
395         case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime:
396             BIO_puts(out, "ansiX962_compressed_prime");
397             break;
398
399         case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2:
400             BIO_puts(out, "ansiX962_compressed_char2");
401             break;
402
403         default:
404             BIO_printf(out, "unknown(%d)", (int)*pformats);
405             break;
406
407         }
408     }
409     if (nformats <= 0)
410         BIO_puts(out, "NONE");
411     BIO_puts(out, "\n");
412     return 1;
413 }
414
415 int ssl_print_curves(BIO *out, SSL *s, int noshared)
416 {
417     int i, ncurves, *curves, nid;
418     const char *cname;
419
420     ncurves = SSL_get1_curves(s, NULL);
421     if (ncurves <= 0)
422         return 1;
423     curves = app_malloc(ncurves * sizeof(int), "curves to print");
424     SSL_get1_curves(s, curves);
425
426     BIO_puts(out, "Supported Elliptic Curves: ");
427     for (i = 0; i < ncurves; i++) {
428         if (i)
429             BIO_puts(out, ":");
430         nid = curves[i];
431         /* If unrecognised print out hex version */
432         if (nid & TLSEXT_nid_unknown)
433             BIO_printf(out, "0x%04X", nid & 0xFFFF);
434         else {
435             /* Use NIST name for curve if it exists */
436             cname = EC_curve_nid2nist(nid);
437             if (!cname)
438                 cname = OBJ_nid2sn(nid);
439             BIO_printf(out, "%s", cname);
440         }
441     }
442     if (ncurves == 0)
443         BIO_puts(out, "NONE");
444     OPENSSL_free(curves);
445     if (noshared) {
446         BIO_puts(out, "\n");
447         return 1;
448     }
449     BIO_puts(out, "\nShared Elliptic curves: ");
450     ncurves = SSL_get_shared_curve(s, -1);
451     for (i = 0; i < ncurves; i++) {
452         if (i)
453             BIO_puts(out, ":");
454         nid = SSL_get_shared_curve(s, i);
455         cname = EC_curve_nid2nist(nid);
456         if (!cname)
457             cname = OBJ_nid2sn(nid);
458         BIO_printf(out, "%s", cname);
459     }
460     if (ncurves == 0)
461         BIO_puts(out, "NONE");
462     BIO_puts(out, "\n");
463     return 1;
464 }
465 #endif
466 int ssl_print_tmp_key(BIO *out, SSL *s)
467 {
468     EVP_PKEY *key;
469     if (!SSL_get_server_tmp_key(s, &key))
470         return 1;
471     BIO_puts(out, "Server Temp Key: ");
472     switch (EVP_PKEY_id(key)) {
473     case EVP_PKEY_RSA:
474         BIO_printf(out, "RSA, %d bits\n", EVP_PKEY_bits(key));
475         break;
476
477     case EVP_PKEY_DH:
478         BIO_printf(out, "DH, %d bits\n", EVP_PKEY_bits(key));
479         break;
480 #ifndef OPENSSL_NO_EC
481     case EVP_PKEY_EC:
482         {
483             EC_KEY *ec = EVP_PKEY_get1_EC_KEY(key);
484             int nid;
485             const char *cname;
486             nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
487             EC_KEY_free(ec);
488             cname = EC_curve_nid2nist(nid);
489             if (!cname)
490                 cname = OBJ_nid2sn(nid);
491             BIO_printf(out, "ECDH, %s, %d bits\n", cname, EVP_PKEY_bits(key));
492         }
493 #endif
494     }
495     EVP_PKEY_free(key);
496     return 1;
497 }
498
499 long bio_dump_callback(BIO *bio, int cmd, const char *argp,
500                        int argi, long argl, long ret)
501 {
502     BIO *out;
503
504     out = (BIO *)BIO_get_callback_arg(bio);
505     if (out == NULL)
506         return (ret);
507
508     if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
509         BIO_printf(out, "read from %p [%p] (%lu bytes => %ld (0x%lX))\n",
510                    (void *)bio, (void *)argp, (unsigned long)argi, ret, ret);
511         BIO_dump(out, argp, (int)ret);
512         return (ret);
513     } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
514         BIO_printf(out, "write to %p [%p] (%lu bytes => %ld (0x%lX))\n",
515                    (void *)bio, (void *)argp, (unsigned long)argi, ret, ret);
516         BIO_dump(out, argp, (int)ret);
517     }
518     return (ret);
519 }
520
521 void apps_ssl_info_callback(const SSL *s, int where, int ret)
522 {
523     const char *str;
524     int w;
525
526     w = where & ~SSL_ST_MASK;
527
528     if (w & SSL_ST_CONNECT)
529         str = "SSL_connect";
530     else if (w & SSL_ST_ACCEPT)
531         str = "SSL_accept";
532     else
533         str = "undefined";
534
535     if (where & SSL_CB_LOOP) {
536         BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s));
537     } else if (where & SSL_CB_ALERT) {
538         str = (where & SSL_CB_READ) ? "read" : "write";
539         BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n",
540                    str,
541                    SSL_alert_type_string_long(ret),
542                    SSL_alert_desc_string_long(ret));
543     } else if (where & SSL_CB_EXIT) {
544         if (ret == 0)
545             BIO_printf(bio_err, "%s:failed in %s\n",
546                        str, SSL_state_string_long(s));
547         else if (ret < 0) {
548             BIO_printf(bio_err, "%s:error in %s\n",
549                        str, SSL_state_string_long(s));
550         }
551     }
552 }
553
554 static STRINT_PAIR ssl_versions[] = {
555     {"SSL 3.0", SSL3_VERSION},
556     {"TLS 1.0", TLS1_VERSION},
557     {"TLS 1.1", TLS1_1_VERSION},
558     {"TLS 1.2", TLS1_2_VERSION},
559     {"DTLS 1.0", DTLS1_VERSION},
560     {"DTLS 1.0 (bad)", DTLS1_BAD_VER},
561     {NULL}
562 };
563 static STRINT_PAIR alert_types[] = {
564     {" close_notify", 0},
565     {" unexpected_message", 10},
566     {" bad_record_mac", 20},
567     {" decryption_failed", 21},
568     {" record_overflow", 22},
569     {" decompression_failure", 30},
570     {" handshake_failure", 40},
571     {" bad_certificate", 42},
572     {" unsupported_certificate", 43},
573     {" certificate_revoked", 44},
574     {" certificate_expired", 45},
575     {" certificate_unknown", 46},
576     {" illegal_parameter", 47},
577     {" unknown_ca", 48},
578     {" access_denied", 49},
579     {" decode_error", 50},
580     {" decrypt_error", 51},
581     {" export_restriction", 60},
582     {" protocol_version", 70},
583     {" insufficient_security", 71},
584     {" internal_error", 80},
585     {" user_canceled", 90},
586     {" no_renegotiation", 100},
587     {" unsupported_extension", 110},
588     {" certificate_unobtainable", 111},
589     {" unrecognized_name", 112},
590     {" bad_certificate_status_response", 113},
591     {" bad_certificate_hash_value", 114},
592     {" unknown_psk_identity", 115},
593     {NULL}
594 };
595
596 static STRINT_PAIR handshakes[] = {
597     {", HelloRequest", 0},
598     {", ClientHello", 1},
599     {", ServerHello", 2},
600     {", HelloVerifyRequest", 3},
601     {", NewSessionTicket", 4},
602     {", Certificate", 11},
603     {", ServerKeyExchange", 12},
604     {", CertificateRequest", 13},
605     {", ServerHelloDone", 14},
606     {", CertificateVerify", 15},
607     {", ClientKeyExchange", 16},
608     {", Finished", 20},
609     {", CertificateUrl", 21},
610     {", CertificateStatus", 22},
611     {", SupplementalData", 23},
612     {NULL}
613 };
614
615 void msg_cb(int write_p, int version, int content_type, const void *buf,
616             size_t len, SSL *ssl, void *arg)
617 {
618     BIO *bio = arg;
619     const char *str_write_p = write_p ? ">>>" : "<<<";
620     const char *str_version = lookup(version, ssl_versions, "???");
621     const char *str_content_type = "", *str_details1 = "", *str_details2 = "";
622     const unsigned char* bp = buf;
623
624     if (version == SSL3_VERSION ||
625         version == TLS1_VERSION ||
626         version == TLS1_1_VERSION ||
627         version == TLS1_2_VERSION ||
628         version == DTLS1_VERSION || version == DTLS1_BAD_VER) {
629         switch (content_type) {
630         case 20:
631             str_content_type = "ChangeCipherSpec";
632             break;
633         case 21:
634             str_content_type = "Alert";
635             str_details1 = ", ???";
636             if (len == 2) {
637                 switch (bp[0]) {
638                 case 1:
639                     str_details1 = ", warning";
640                     break;
641                 case 2:
642                     str_details1 = ", fatal";
643                     break;
644                 }
645                 str_details2 = lookup((int)bp[1], alert_types, " ???");
646             }
647             break;
648         case 22:
649             str_content_type = "Handshake";
650             str_details1 = "???";
651             if (len > 0)
652                 str_details1 = lookup((int)bp[0], handshakes, "???");
653             break;
654         case 23:
655             str_content_type = "ApplicationData";
656             break;
657 #ifndef OPENSSL_NO_HEARTBEATS
658         case 24:
659             str_details1 = ", Heartbeat";
660
661             if (len > 0) {
662                 switch (bp[0]) {
663                 case 1:
664                     str_details1 = ", HeartbeatRequest";
665                     break;
666                 case 2:
667                     str_details1 = ", HeartbeatResponse";
668                     break;
669                 }
670             }
671             break;
672 #endif
673         }
674     }
675
676     BIO_printf(bio, "%s %s%s [length %04lx]%s%s\n", str_write_p, str_version,
677                str_content_type, (unsigned long)len, str_details1,
678                str_details2);
679
680     if (len > 0) {
681         size_t num, i;
682
683         BIO_printf(bio, "   ");
684         num = len;
685         for (i = 0; i < num; i++) {
686             if (i % 16 == 0 && i > 0)
687                 BIO_printf(bio, "\n   ");
688             BIO_printf(bio, " %02x", ((const unsigned char *)buf)[i]);
689         }
690         if (i < len)
691             BIO_printf(bio, " ...");
692         BIO_printf(bio, "\n");
693     }
694     (void)BIO_flush(bio);
695 }
696
697 static STRINT_PAIR tlsext_types[] = {
698     {"server name", TLSEXT_TYPE_server_name},
699     {"max fragment length", TLSEXT_TYPE_max_fragment_length},
700     {"client certificate URL", TLSEXT_TYPE_client_certificate_url},
701     {"trusted CA keys", TLSEXT_TYPE_trusted_ca_keys},
702     {"truncated HMAC", TLSEXT_TYPE_truncated_hmac},
703     {"status request", TLSEXT_TYPE_status_request},
704     {"user mapping", TLSEXT_TYPE_user_mapping},
705     {"client authz", TLSEXT_TYPE_client_authz},
706     {"server authz", TLSEXT_TYPE_server_authz},
707     {"cert type", TLSEXT_TYPE_cert_type},
708     {"elliptic curves", TLSEXT_TYPE_elliptic_curves},
709     {"EC point formats", TLSEXT_TYPE_ec_point_formats},
710     {"SRP", TLSEXT_TYPE_srp},
711     {"signature algorithms", TLSEXT_TYPE_signature_algorithms},
712     {"use SRTP", TLSEXT_TYPE_use_srtp},
713     {"heartbeat", TLSEXT_TYPE_heartbeat},
714     {"session ticket", TLSEXT_TYPE_session_ticket},
715     {"renegotiation info", TLSEXT_TYPE_renegotiate},
716     {"signed certificate timestamps", TLSEXT_TYPE_signed_certificate_timestamp},
717     {"TLS padding", TLSEXT_TYPE_padding},
718 #ifdef TLSEXT_TYPE_next_proto_neg
719     {"next protocol", TLSEXT_TYPE_next_proto_neg},
720 #endif
721 #ifdef TLSEXT_TYPE_encrypt_then_mac
722     {"encrypt-then-mac", TLSEXT_TYPE_encrypt_then_mac},
723 #endif
724 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
725     {"application layer protocol negotiation",
726      TLSEXT_TYPE_application_layer_protocol_negotiation},
727 #endif
728 #ifdef TLSEXT_TYPE_extended_master_secret
729     {"extended master secret", TLSEXT_TYPE_extended_master_secret},
730 #endif
731     {NULL}
732 };
733
734 void tlsext_cb(SSL *s, int client_server, int type,
735                const unsigned char *data, int len, void *arg)
736 {
737     BIO *bio = arg;
738     const char *extname = lookup(type, tlsext_types, "unknown");
739
740     BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
741                client_server ? "server" : "client", extname, type, len);
742     BIO_dump(bio, (const char *)data, len);
743     (void)BIO_flush(bio);
744 }
745
746 #ifndef OPENSSL_NO_SOCK
747 int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
748                              unsigned int *cookie_len)
749 {
750     unsigned char *buffer;
751     size_t length;
752     unsigned short port;
753     BIO_ADDR *peer = NULL;
754
755     /* Initialize a random secret */
756     if (!cookie_initialized) {
757         if (RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH) <= 0) {
758             BIO_printf(bio_err, "error setting random cookie secret\n");
759             return 0;
760         }
761         cookie_initialized = 1;
762     }
763
764     peer = BIO_ADDR_new();
765     if (peer == NULL) {
766         BIO_printf(bio_err, "memory full\n");
767         return 0;
768     }
769
770     /* Read peer information */
771     (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), peer);
772
773     /* Create buffer with peer's address and port */
774     BIO_ADDR_rawaddress(peer, NULL, &length);
775     OPENSSL_assert(length != 0);
776     port = BIO_ADDR_rawport(peer);
777     length += sizeof(port);
778     buffer = app_malloc(length, "cookie generate buffer");
779
780     memcpy(buffer, &port, sizeof(port));
781     BIO_ADDR_rawaddress(peer, buffer + sizeof(port), NULL);
782
783     /* Calculate HMAC of buffer using the secret */
784     HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
785          buffer, length, cookie, cookie_len);
786
787     OPENSSL_free(buffer);
788     BIO_ADDR_free(peer);
789
790     return 1;
791 }
792
793 int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
794                            unsigned int cookie_len)
795 {
796     unsigned char result[EVP_MAX_MD_SIZE];
797     unsigned int resultlength;
798
799     /* Note: we check cookie_initialized because if it's not,
800      * it cannot be valid */
801     if (cookie_initialized
802         && generate_cookie_callback(ssl, result, &resultlength)
803         && cookie_len == resultlength
804         && memcmp(result, cookie, resultlength) == 0)
805         return 1;
806
807     return 0;
808 }
809 #endif
810
811 /*
812  * Example of extended certificate handling. Where the standard support of
813  * one certificate per algorithm is not sufficient an application can decide
814  * which certificate(s) to use at runtime based on whatever criteria it deems
815  * appropriate.
816  */
817
818 /* Linked list of certificates, keys and chains */
819 struct ssl_excert_st {
820     int certform;
821     const char *certfile;
822     int keyform;
823     const char *keyfile;
824     const char *chainfile;
825     X509 *cert;
826     EVP_PKEY *key;
827     STACK_OF(X509) *chain;
828     int build_chain;
829     struct ssl_excert_st *next, *prev;
830 };
831
832 static STRINT_PAIR chain_flags[] = {
833     {"Overall Validity", CERT_PKEY_VALID},
834     {"Sign with EE key", CERT_PKEY_SIGN},
835     {"EE signature", CERT_PKEY_EE_SIGNATURE},
836     {"CA signature", CERT_PKEY_CA_SIGNATURE},
837     {"EE key parameters", CERT_PKEY_EE_PARAM},
838     {"CA key parameters", CERT_PKEY_CA_PARAM},
839     {"Explicitly sign with EE key", CERT_PKEY_EXPLICIT_SIGN},
840     {"Issuer Name", CERT_PKEY_ISSUER_NAME},
841     {"Certificate Type", CERT_PKEY_CERT_TYPE},
842     {NULL}
843 };
844
845 static void print_chain_flags(SSL *s, int flags)
846 {
847     STRINT_PAIR *pp;
848
849     for (pp = chain_flags; pp->name; ++pp)
850         BIO_printf(bio_err, "\t%s: %s\n",
851                    pp->name,
852                    (flags & pp->retval) ? "OK" : "NOT OK");
853     BIO_printf(bio_err, "\tSuite B: ");
854     if (SSL_set_cert_flags(s, 0) & SSL_CERT_FLAG_SUITEB_128_LOS)
855         BIO_puts(bio_err, flags & CERT_PKEY_SUITEB ? "OK\n" : "NOT OK\n");
856     else
857         BIO_printf(bio_err, "not tested\n");
858 }
859
860 /*
861  * Very basic selection callback: just use any certificate chain reported as
862  * valid. More sophisticated could prioritise according to local policy.
863  */
864 static int set_cert_cb(SSL *ssl, void *arg)
865 {
866     int i, rv;
867     SSL_EXCERT *exc = arg;
868 #ifdef CERT_CB_TEST_RETRY
869     static int retry_cnt;
870     if (retry_cnt < 5) {
871         retry_cnt++;
872         BIO_printf(bio_err,
873                    "Certificate callback retry test: count %d\n",
874                    retry_cnt);
875         return -1;
876     }
877 #endif
878     SSL_certs_clear(ssl);
879
880     if (!exc)
881         return 1;
882
883     /*
884      * Go to end of list and traverse backwards since we prepend newer
885      * entries this retains the original order.
886      */
887     while (exc->next)
888         exc = exc->next;
889
890     i = 0;
891
892     while (exc) {
893         i++;
894         rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain);
895         BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i);
896         X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0,
897                            XN_FLAG_ONELINE);
898         BIO_puts(bio_err, "\n");
899         print_chain_flags(ssl, rv);
900         if (rv & CERT_PKEY_VALID) {
901             if (!SSL_use_certificate(ssl, exc->cert)
902                     || !SSL_use_PrivateKey(ssl, exc->key)) {
903                 return 0;
904             }
905             /*
906              * NB: we wouldn't normally do this as it is not efficient
907              * building chains on each connection better to cache the chain
908              * in advance.
909              */
910             if (exc->build_chain) {
911                 if (!SSL_build_cert_chain(ssl, 0))
912                     return 0;
913             } else if (exc->chain)
914                 SSL_set1_chain(ssl, exc->chain);
915         }
916         exc = exc->prev;
917     }
918     return 1;
919 }
920
921 void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc)
922 {
923     SSL_CTX_set_cert_cb(ctx, set_cert_cb, exc);
924 }
925
926 static int ssl_excert_prepend(SSL_EXCERT **pexc)
927 {
928     SSL_EXCERT *exc = app_malloc(sizeof(*exc), "prepend cert");
929
930     memset(exc, 0, sizeof(*exc));
931
932     exc->next = *pexc;
933     *pexc = exc;
934
935     if (exc->next) {
936         exc->certform = exc->next->certform;
937         exc->keyform = exc->next->keyform;
938         exc->next->prev = exc;
939     } else {
940         exc->certform = FORMAT_PEM;
941         exc->keyform = FORMAT_PEM;
942     }
943     return 1;
944
945 }
946
947 void ssl_excert_free(SSL_EXCERT *exc)
948 {
949     SSL_EXCERT *curr;
950
951     if (!exc)
952         return;
953     while (exc) {
954         X509_free(exc->cert);
955         EVP_PKEY_free(exc->key);
956         sk_X509_pop_free(exc->chain, X509_free);
957         curr = exc;
958         exc = exc->next;
959         OPENSSL_free(curr);
960     }
961 }
962
963 int load_excert(SSL_EXCERT **pexc)
964 {
965     SSL_EXCERT *exc = *pexc;
966     if (!exc)
967         return 1;
968     /* If nothing in list, free and set to NULL */
969     if (!exc->certfile && !exc->next) {
970         ssl_excert_free(exc);
971         *pexc = NULL;
972         return 1;
973     }
974     for (; exc; exc = exc->next) {
975         if (!exc->certfile) {
976             BIO_printf(bio_err, "Missing filename\n");
977             return 0;
978         }
979         exc->cert = load_cert(exc->certfile, exc->certform,
980                               "Server Certificate");
981         if (!exc->cert)
982             return 0;
983         if (exc->keyfile) {
984             exc->key = load_key(exc->keyfile, exc->keyform,
985                                 0, NULL, NULL, "Server Key");
986         } else {
987             exc->key = load_key(exc->certfile, exc->certform,
988                                 0, NULL, NULL, "Server Key");
989         }
990         if (!exc->key)
991             return 0;
992         if (exc->chainfile) {
993             if (!load_certs(exc->chainfile, &exc->chain, FORMAT_PEM, NULL,
994                             "Server Chain"))
995                 return 0;
996         }
997     }
998     return 1;
999 }
1000
1001 enum range { OPT_X_ENUM };
1002
1003 int args_excert(int opt, SSL_EXCERT **pexc)
1004 {
1005     SSL_EXCERT *exc = *pexc;
1006
1007     assert(opt > OPT_X__FIRST);
1008     assert(opt < OPT_X__LAST);
1009
1010     if (exc == NULL) {
1011         if (!ssl_excert_prepend(&exc)) {
1012             BIO_printf(bio_err, " %s: Error initialising xcert\n",
1013                        opt_getprog());
1014             goto err;
1015         }
1016         *pexc = exc;
1017     }
1018
1019     switch ((enum range)opt) {
1020     case OPT_X__FIRST:
1021     case OPT_X__LAST:
1022         return 0;
1023     case OPT_X_CERT:
1024         if (exc->certfile && !ssl_excert_prepend(&exc)) {
1025             BIO_printf(bio_err, "%s: Error adding xcert\n", opt_getprog());
1026             goto err;
1027         }
1028         exc->certfile = opt_arg();
1029         break;
1030     case OPT_X_KEY:
1031         if (exc->keyfile) {
1032             BIO_printf(bio_err, "%s: Key already specified\n", opt_getprog());
1033             goto err;
1034         }
1035         exc->keyfile = opt_arg();
1036         break;
1037     case OPT_X_CHAIN:
1038         if (exc->chainfile) {
1039             BIO_printf(bio_err, "%s: Chain already specified\n",
1040                        opt_getprog());
1041             goto err;
1042         }
1043         exc->chainfile = opt_arg();
1044         break;
1045     case OPT_X_CHAIN_BUILD:
1046         exc->build_chain = 1;
1047         break;
1048     case OPT_X_CERTFORM:
1049         if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &exc->certform))
1050             return 0;
1051         break;
1052     case OPT_X_KEYFORM:
1053         if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &exc->keyform))
1054             return 0;
1055         break;
1056     }
1057     return 1;
1058
1059  err:
1060     ERR_print_errors(bio_err);
1061     ssl_excert_free(exc);
1062     *pexc = NULL;
1063     return 0;
1064 }
1065
1066 static void print_raw_cipherlist(SSL *s)
1067 {
1068     const unsigned char *rlist;
1069     static const unsigned char scsv_id[] = { 0, 0xFF };
1070     size_t i, rlistlen, num;
1071     if (!SSL_is_server(s))
1072         return;
1073     num = SSL_get0_raw_cipherlist(s, NULL);
1074     OPENSSL_assert(num == 2);
1075     rlistlen = SSL_get0_raw_cipherlist(s, &rlist);
1076     BIO_puts(bio_err, "Client cipher list: ");
1077     for (i = 0; i < rlistlen; i += num, rlist += num) {
1078         const SSL_CIPHER *c = SSL_CIPHER_find(s, rlist);
1079         if (i)
1080             BIO_puts(bio_err, ":");
1081         if (c)
1082             BIO_puts(bio_err, SSL_CIPHER_get_name(c));
1083         else if (!memcmp(rlist, scsv_id, num))
1084             BIO_puts(bio_err, "SCSV");
1085         else {
1086             size_t j;
1087             BIO_puts(bio_err, "0x");
1088             for (j = 0; j < num; j++)
1089                 BIO_printf(bio_err, "%02X", rlist[j]);
1090         }
1091     }
1092     BIO_puts(bio_err, "\n");
1093 }
1094
1095 /*
1096  * Hex encoder for TLSA RRdata, not ':' delimited.
1097  */
1098 static char *hexencode(const unsigned char *data, size_t len)
1099 {
1100     static const char *hex = "0123456789abcdef";
1101     char *out;
1102     char *cp;
1103     size_t outlen = 2 * len + 1;
1104     int ilen = (int) outlen;
1105
1106     if (outlen < len || ilen < 0 || outlen != (size_t)ilen) {
1107         BIO_printf(bio_err, "%s: %" PRIu64 "-byte buffer too large to hexencode\n",
1108                    opt_getprog(), (uint64_t)len);
1109         exit(1);
1110     }
1111     cp = out = app_malloc(ilen, "TLSA hex data buffer");
1112
1113     while (len-- > 0) {
1114         *cp++ = hex[(*data >> 4) & 0x0f];
1115         *cp++ = hex[*data++ & 0x0f];
1116     }
1117     *cp = '\0';
1118     return out;
1119 }
1120
1121 void print_verify_detail(SSL *s, BIO *bio)
1122 {
1123     int mdpth;
1124     EVP_PKEY *mspki;
1125     long verify_err = SSL_get_verify_result(s);
1126
1127     if (verify_err == X509_V_OK) {
1128         const char *peername = SSL_get0_peername(s);
1129
1130         BIO_printf(bio, "Verification: OK\n");
1131         if (peername != NULL)
1132             BIO_printf(bio, "Verified peername: %s\n", peername);
1133     } else {
1134         const char *reason = X509_verify_cert_error_string(verify_err);
1135
1136         BIO_printf(bio, "Verification error: %s\n", reason);
1137     }
1138
1139     if ((mdpth = SSL_get0_dane_authority(s, NULL, &mspki)) >= 0) {
1140         uint8_t usage, selector, mtype;
1141         const unsigned char *data = NULL;
1142         size_t dlen = 0;
1143         char *hexdata;
1144
1145         mdpth = SSL_get0_dane_tlsa(s, &usage, &selector, &mtype, &data, &dlen);
1146
1147         /*
1148          * The TLSA data field can be quite long when it is a certificate,
1149          * public key or even a SHA2-512 digest.  Because the initial octets of
1150          * ASN.1 certificates and public keys contain mostly boilerplate OIDs
1151          * and lengths, we show the last 12 bytes of the data instead, as these
1152          * are more likely to distinguish distinct TLSA records.
1153          */
1154 #define TLSA_TAIL_SIZE 12
1155         if (dlen > TLSA_TAIL_SIZE)
1156             hexdata = hexencode(data + dlen - TLSA_TAIL_SIZE, TLSA_TAIL_SIZE);
1157         else
1158             hexdata = hexencode(data, dlen);
1159         BIO_printf(bio, "DANE TLSA %d %d %d %s%s %s at depth %d\n",
1160                    usage, selector, mtype,
1161                    (dlen > TLSA_TAIL_SIZE) ? "..." : "", hexdata,
1162                    (mspki != NULL) ? "signed the certificate" :
1163                    mdpth ? "matched TA certificate" : "matched EE certificate",
1164                    mdpth);
1165         OPENSSL_free(hexdata);
1166     }
1167 }
1168
1169 void print_ssl_summary(SSL *s)
1170 {
1171     const SSL_CIPHER *c;
1172     X509 *peer;
1173     /* const char *pnam = SSL_is_server(s) ? "client" : "server"; */
1174
1175     BIO_printf(bio_err, "Protocol version: %s\n", SSL_get_version(s));
1176     print_raw_cipherlist(s);
1177     c = SSL_get_current_cipher(s);
1178     BIO_printf(bio_err, "Ciphersuite: %s\n", SSL_CIPHER_get_name(c));
1179     do_print_sigalgs(bio_err, s, 0);
1180     peer = SSL_get_peer_certificate(s);
1181     if (peer) {
1182         int nid;
1183
1184         BIO_puts(bio_err, "Peer certificate: ");
1185         X509_NAME_print_ex(bio_err, X509_get_subject_name(peer),
1186                            0, XN_FLAG_ONELINE);
1187         BIO_puts(bio_err, "\n");
1188         if (SSL_get_peer_signature_nid(s, &nid))
1189             BIO_printf(bio_err, "Hash used: %s\n", OBJ_nid2sn(nid));
1190         print_verify_detail(s, bio_err);
1191     } else
1192         BIO_puts(bio_err, "No peer certificate\n");
1193     X509_free(peer);
1194 #ifndef OPENSSL_NO_EC
1195     ssl_print_point_formats(bio_err, s);
1196     if (SSL_is_server(s))
1197         ssl_print_curves(bio_err, s, 1);
1198     else
1199         ssl_print_tmp_key(bio_err, s);
1200 #else
1201     if (!SSL_is_server(s))
1202         ssl_print_tmp_key(bio_err, s);
1203 #endif
1204 }
1205
1206 int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str,
1207                SSL_CTX *ctx)
1208 {
1209     int i;
1210
1211     SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
1212     for (i = 0; i < sk_OPENSSL_STRING_num(str); i += 2) {
1213         const char *flag = sk_OPENSSL_STRING_value(str, i);
1214         const char *arg = sk_OPENSSL_STRING_value(str, i + 1);
1215         if (SSL_CONF_cmd(cctx, flag, arg) <= 0) {
1216             if (arg)
1217                 BIO_printf(bio_err, "Error with command: \"%s %s\"\n",
1218                            flag, arg);
1219             else
1220                 BIO_printf(bio_err, "Error with command: \"%s\"\n", flag);
1221             ERR_print_errors(bio_err);
1222             return 0;
1223         }
1224     }
1225     if (!SSL_CONF_CTX_finish(cctx)) {
1226         BIO_puts(bio_err, "Error finishing context\n");
1227         ERR_print_errors(bio_err);
1228         return 0;
1229     }
1230     return 1;
1231 }
1232
1233 static int add_crls_store(X509_STORE *st, STACK_OF(X509_CRL) *crls)
1234 {
1235     X509_CRL *crl;
1236     int i;
1237     for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1238         crl = sk_X509_CRL_value(crls, i);
1239         X509_STORE_add_crl(st, crl);
1240     }
1241     return 1;
1242 }
1243
1244 int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls, int crl_download)
1245 {
1246     X509_STORE *st;
1247     st = SSL_CTX_get_cert_store(ctx);
1248     add_crls_store(st, crls);
1249     if (crl_download)
1250         store_setup_crl_download(st);
1251     return 1;
1252 }
1253
1254 int ssl_load_stores(SSL_CTX *ctx,
1255                     const char *vfyCApath, const char *vfyCAfile,
1256                     const char *chCApath, const char *chCAfile,
1257                     STACK_OF(X509_CRL) *crls, int crl_download)
1258 {
1259     X509_STORE *vfy = NULL, *ch = NULL;
1260     int rv = 0;
1261     if (vfyCApath != NULL || vfyCAfile != NULL) {
1262         vfy = X509_STORE_new();
1263         if (vfy == NULL)
1264             goto err;
1265         if (!X509_STORE_load_locations(vfy, vfyCAfile, vfyCApath))
1266             goto err;
1267         add_crls_store(vfy, crls);
1268         SSL_CTX_set1_verify_cert_store(ctx, vfy);
1269         if (crl_download)
1270             store_setup_crl_download(vfy);
1271     }
1272     if (chCApath != NULL || chCAfile != NULL) {
1273         ch = X509_STORE_new();
1274         if (ch == NULL)
1275             goto err;
1276         if (!X509_STORE_load_locations(ch, chCAfile, chCApath))
1277             goto err;
1278         SSL_CTX_set1_chain_cert_store(ctx, ch);
1279     }
1280     rv = 1;
1281  err:
1282     X509_STORE_free(vfy);
1283     X509_STORE_free(ch);
1284     return rv;
1285 }
1286
1287 /* Verbose print out of security callback */
1288
1289 typedef struct {
1290     BIO *out;
1291     int verbose;
1292     int (*old_cb) (const SSL *s, const SSL_CTX *ctx, int op, int bits, int nid,
1293                    void *other, void *ex);
1294 } security_debug_ex;
1295
1296 static STRINT_PAIR callback_types[] = {
1297     {"Supported Ciphersuite", SSL_SECOP_CIPHER_SUPPORTED},
1298     {"Shared Ciphersuite", SSL_SECOP_CIPHER_SHARED},
1299     {"Check Ciphersuite", SSL_SECOP_CIPHER_CHECK},
1300 #ifndef OPENSSL_NO_DH
1301     {"Temp DH key bits", SSL_SECOP_TMP_DH},
1302 #endif
1303     {"Supported Curve", SSL_SECOP_CURVE_SUPPORTED},
1304     {"Shared Curve", SSL_SECOP_CURVE_SHARED},
1305     {"Check Curve", SSL_SECOP_CURVE_CHECK},
1306     {"Supported Signature Algorithm digest", SSL_SECOP_SIGALG_SUPPORTED},
1307     {"Shared Signature Algorithm digest", SSL_SECOP_SIGALG_SHARED},
1308     {"Check Signature Algorithm digest", SSL_SECOP_SIGALG_CHECK},
1309     {"Signature Algorithm mask", SSL_SECOP_SIGALG_MASK},
1310     {"Certificate chain EE key", SSL_SECOP_EE_KEY},
1311     {"Certificate chain CA key", SSL_SECOP_CA_KEY},
1312     {"Peer Chain EE key", SSL_SECOP_PEER_EE_KEY},
1313     {"Peer Chain CA key", SSL_SECOP_PEER_CA_KEY},
1314     {"Certificate chain CA digest", SSL_SECOP_CA_MD},
1315     {"Peer chain CA digest", SSL_SECOP_PEER_CA_MD},
1316     {"SSL compression", SSL_SECOP_COMPRESSION},
1317     {"Session ticket", SSL_SECOP_TICKET},
1318     {NULL}
1319 };
1320
1321 static int security_callback_debug(const SSL *s, const SSL_CTX *ctx,
1322                                    int op, int bits, int nid,
1323                                    void *other, void *ex)
1324 {
1325     security_debug_ex *sdb = ex;
1326     int rv, show_bits = 1, cert_md = 0;
1327     const char *nm;
1328     rv = sdb->old_cb(s, ctx, op, bits, nid, other, ex);
1329     if (rv == 1 && sdb->verbose < 2)
1330         return 1;
1331     BIO_puts(sdb->out, "Security callback: ");
1332
1333     nm = lookup(op, callback_types, NULL);
1334     switch (op) {
1335     case SSL_SECOP_TICKET:
1336     case SSL_SECOP_COMPRESSION:
1337         show_bits = 0;
1338         nm = NULL;
1339         break;
1340     case SSL_SECOP_VERSION:
1341         BIO_printf(sdb->out, "Version=%s", lookup(nid, ssl_versions, "???"));
1342         show_bits = 0;
1343         nm = NULL;
1344         break;
1345     case SSL_SECOP_CA_MD:
1346     case SSL_SECOP_PEER_CA_MD:
1347         cert_md = 1;
1348         break;
1349     }
1350     if (nm)
1351         BIO_printf(sdb->out, "%s=", nm);
1352
1353     switch (op & SSL_SECOP_OTHER_TYPE) {
1354
1355     case SSL_SECOP_OTHER_CIPHER:
1356         BIO_puts(sdb->out, SSL_CIPHER_get_name(other));
1357         break;
1358
1359 #ifndef OPENSSL_NO_EC
1360     case SSL_SECOP_OTHER_CURVE:
1361         {
1362             const char *cname;
1363             cname = EC_curve_nid2nist(nid);
1364             if (cname == NULL)
1365                 cname = OBJ_nid2sn(nid);
1366             BIO_puts(sdb->out, cname);
1367         }
1368         break;
1369 #endif
1370 #ifndef OPENSSL_NO_DH
1371     case SSL_SECOP_OTHER_DH:
1372         {
1373             DH *dh = other;
1374             BIO_printf(sdb->out, "%d", DH_bits(dh));
1375             break;
1376         }
1377 #endif
1378     case SSL_SECOP_OTHER_CERT:
1379         {
1380             if (cert_md) {
1381                 int sig_nid = X509_get_signature_nid(other);
1382                 BIO_puts(sdb->out, OBJ_nid2sn(sig_nid));
1383             } else {
1384                 EVP_PKEY *pkey = X509_get0_pubkey(other);
1385                 const char *algname = "";
1386                 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL,
1387                                         &algname, EVP_PKEY_get0_asn1(pkey));
1388                 BIO_printf(sdb->out, "%s, bits=%d",
1389                            algname, EVP_PKEY_bits(pkey));
1390             }
1391             break;
1392         }
1393     case SSL_SECOP_OTHER_SIGALG:
1394         {
1395             const unsigned char *salg = other;
1396             const char *sname = NULL;
1397             switch (salg[1]) {
1398             case TLSEXT_signature_anonymous:
1399                 sname = "anonymous";
1400                 break;
1401             case TLSEXT_signature_rsa:
1402                 sname = "RSA";
1403                 break;
1404             case TLSEXT_signature_dsa:
1405                 sname = "DSA";
1406                 break;
1407             case TLSEXT_signature_ecdsa:
1408                 sname = "ECDSA";
1409                 break;
1410             }
1411
1412             BIO_puts(sdb->out, OBJ_nid2sn(nid));
1413             if (sname)
1414                 BIO_printf(sdb->out, ", algorithm=%s", sname);
1415             else
1416                 BIO_printf(sdb->out, ", algid=%d", salg[1]);
1417             break;
1418         }
1419
1420     }
1421
1422     if (show_bits)
1423         BIO_printf(sdb->out, ", security bits=%d", bits);
1424     BIO_printf(sdb->out, ": %s\n", rv ? "yes" : "no");
1425     return rv;
1426 }
1427
1428 void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose)
1429 {
1430     static security_debug_ex sdb;
1431
1432     sdb.out = bio_err;
1433     sdb.verbose = verbose;
1434     sdb.old_cb = SSL_CTX_get_security_callback(ctx);
1435     SSL_CTX_set_security_callback(ctx, security_callback_debug);
1436     SSL_CTX_set0_security_ex_data(ctx, &sdb);
1437 }