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