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