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