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