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