dsa: deprecate applications that depend on the low level DSA functions.
[openssl.git] / apps / lib / s_cb.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* callback functions used by s_client, s_server, and s_time */
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h> /* for memcpy() and strcmp() */
14 #include "apps.h"
15 #include <openssl/core_names.h>
16 #include <openssl/params.h>
17 #include <openssl/err.h>
18 #include <openssl/rand.h>
19 #include <openssl/x509.h>
20 #include <openssl/ssl.h>
21 #include <openssl/bn.h>
22 #ifndef OPENSSL_NO_DH
23 # include <openssl/dh.h>
24 #endif
25 #include "s_apps.h"
26
27 #define COOKIE_SECRET_LENGTH    16
28
29 VERIFY_CB_ARGS verify_args = { -1, 0, X509_V_OK, 0 };
30
31 #ifndef OPENSSL_NO_SOCK
32 static unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
33 static int cookie_initialized = 0;
34 #endif
35 static BIO *bio_keylog = NULL;
36
37 static const char *lookup(int val, const STRINT_PAIR* list, const char* def)
38 {
39     for ( ; list->name; ++list)
40         if (list->retval == val)
41             return list->name;
42     return def;
43 }
44
45 int verify_callback(int ok, X509_STORE_CTX *ctx)
46 {
47     X509 *err_cert;
48     int err, depth;
49
50     err_cert = X509_STORE_CTX_get_current_cert(ctx);
51     err = X509_STORE_CTX_get_error(ctx);
52     depth = X509_STORE_CTX_get_error_depth(ctx);
53
54     if (!verify_args.quiet || !ok) {
55         BIO_printf(bio_err, "depth=%d ", depth);
56         if (err_cert != NULL) {
57             X509_NAME_print_ex(bio_err,
58                                X509_get_subject_name(err_cert),
59                                0, get_nameopt());
60             BIO_puts(bio_err, "\n");
61         } else {
62             BIO_puts(bio_err, "<no cert>\n");
63         }
64     }
65     if (!ok) {
66         BIO_printf(bio_err, "verify error:num=%d:%s\n", err,
67                    X509_verify_cert_error_string(err));
68         if (verify_args.depth < 0 || verify_args.depth >= depth) {
69             if (!verify_args.return_error)
70                 ok = 1;
71             verify_args.error = err;
72         } else {
73             ok = 0;
74             verify_args.error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
75         }
76     }
77     switch (err) {
78     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
79         BIO_puts(bio_err, "issuer= ");
80         X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert),
81                            0, get_nameopt());
82         BIO_puts(bio_err, "\n");
83         break;
84     case X509_V_ERR_CERT_NOT_YET_VALID:
85     case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
86         BIO_printf(bio_err, "notBefore=");
87         ASN1_TIME_print(bio_err, X509_get0_notBefore(err_cert));
88         BIO_printf(bio_err, "\n");
89         break;
90     case X509_V_ERR_CERT_HAS_EXPIRED:
91     case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
92         BIO_printf(bio_err, "notAfter=");
93         ASN1_TIME_print(bio_err, X509_get0_notAfter(err_cert));
94         BIO_printf(bio_err, "\n");
95         break;
96     case X509_V_ERR_NO_EXPLICIT_POLICY:
97         if (!verify_args.quiet)
98             policies_print(ctx);
99         break;
100     }
101     if (err == X509_V_OK && ok == 2 && !verify_args.quiet)
102         policies_print(ctx);
103     if (ok && !verify_args.quiet)
104         BIO_printf(bio_err, "verify return:%d\n", ok);
105     return ok;
106 }
107
108 int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file)
109 {
110     if (cert_file != NULL) {
111         if (SSL_CTX_use_certificate_file(ctx, cert_file,
112                                          SSL_FILETYPE_PEM) <= 0) {
113             BIO_printf(bio_err, "unable to get certificate from '%s'\n",
114                        cert_file);
115             ERR_print_errors(bio_err);
116             return 0;
117         }
118         if (key_file == NULL)
119             key_file = cert_file;
120         if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) {
121             BIO_printf(bio_err, "unable to get private key from '%s'\n",
122                        key_file);
123             ERR_print_errors(bio_err);
124             return 0;
125         }
126
127         /*
128          * If we are using DSA, we can copy the parameters from the private
129          * key
130          */
131
132         /*
133          * Now we know that a key and cert have been set against the SSL
134          * context
135          */
136         if (!SSL_CTX_check_private_key(ctx)) {
137             BIO_printf(bio_err,
138                        "Private key does not match the certificate public key\n");
139             return 0;
140         }
141     }
142     return 1;
143 }
144
145 int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key,
146                        STACK_OF(X509) *chain, int build_chain)
147 {
148     int chflags = chain ? SSL_BUILD_CHAIN_FLAG_CHECK : 0;
149     if (cert == NULL)
150         return 1;
151     if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
152         BIO_printf(bio_err, "error setting certificate\n");
153         ERR_print_errors(bio_err);
154         return 0;
155     }
156
157     if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) {
158         BIO_printf(bio_err, "error setting private key\n");
159         ERR_print_errors(bio_err);
160         return 0;
161     }
162
163     /*
164      * Now we know that a key and cert have been set against the SSL context
165      */
166     if (!SSL_CTX_check_private_key(ctx)) {
167         BIO_printf(bio_err,
168                    "Private key does not match the certificate public key\n");
169         return 0;
170     }
171     if (chain && !SSL_CTX_set1_chain(ctx, chain)) {
172         BIO_printf(bio_err, "error setting certificate chain\n");
173         ERR_print_errors(bio_err);
174         return 0;
175     }
176     if (build_chain && !SSL_CTX_build_cert_chain(ctx, chflags)) {
177         BIO_printf(bio_err, "error building certificate chain\n");
178         ERR_print_errors(bio_err);
179         return 0;
180     }
181     return 1;
182 }
183
184 static STRINT_PAIR cert_type_list[] = {
185     {"RSA sign", TLS_CT_RSA_SIGN},
186     {"DSA sign", TLS_CT_DSS_SIGN},
187     {"RSA fixed DH", TLS_CT_RSA_FIXED_DH},
188     {"DSS fixed DH", TLS_CT_DSS_FIXED_DH},
189     {"ECDSA sign", TLS_CT_ECDSA_SIGN},
190     {"RSA fixed ECDH", TLS_CT_RSA_FIXED_ECDH},
191     {"ECDSA fixed ECDH", TLS_CT_ECDSA_FIXED_ECDH},
192     {"GOST01 Sign", TLS_CT_GOST01_SIGN},
193     {NULL}
194 };
195
196 static void ssl_print_client_cert_types(BIO *bio, SSL *s)
197 {
198     const unsigned char *p;
199     int i;
200     int cert_type_num = SSL_get0_certificate_types(s, &p);
201     if (!cert_type_num)
202         return;
203     BIO_puts(bio, "Client Certificate Types: ");
204     for (i = 0; i < cert_type_num; i++) {
205         unsigned char cert_type = p[i];
206         const char *cname = lookup((int)cert_type, cert_type_list, NULL);
207
208         if (i)
209             BIO_puts(bio, ", ");
210         if (cname != NULL)
211             BIO_puts(bio, cname);
212         else
213             BIO_printf(bio, "UNKNOWN (%d),", cert_type);
214     }
215     BIO_puts(bio, "\n");
216 }
217
218 static const char *get_sigtype(int nid)
219 {
220     switch (nid) {
221     case EVP_PKEY_RSA:
222         return "RSA";
223
224     case EVP_PKEY_RSA_PSS:
225         return "RSA-PSS";
226
227     case EVP_PKEY_DSA:
228         return "DSA";
229
230      case EVP_PKEY_EC:
231         return "ECDSA";
232
233      case NID_ED25519:
234         return "Ed25519";
235
236      case NID_ED448:
237         return "Ed448";
238
239      case NID_id_GostR3410_2001:
240         return "gost2001";
241
242      case NID_id_GostR3410_2012_256:
243         return "gost2012_256";
244
245      case NID_id_GostR3410_2012_512:
246         return "gost2012_512";
247
248     default:
249         return NULL;
250     }
251 }
252
253 static int do_print_sigalgs(BIO *out, SSL *s, int shared)
254 {
255     int i, nsig, client;
256     client = SSL_is_server(s) ? 0 : 1;
257     if (shared)
258         nsig = SSL_get_shared_sigalgs(s, 0, NULL, NULL, NULL, NULL, NULL);
259     else
260         nsig = SSL_get_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL);
261     if (nsig == 0)
262         return 1;
263
264     if (shared)
265         BIO_puts(out, "Shared ");
266
267     if (client)
268         BIO_puts(out, "Requested ");
269     BIO_puts(out, "Signature Algorithms: ");
270     for (i = 0; i < nsig; i++) {
271         int hash_nid, sign_nid;
272         unsigned char rhash, rsign;
273         const char *sstr = NULL;
274         if (shared)
275             SSL_get_shared_sigalgs(s, i, &sign_nid, &hash_nid, NULL,
276                                    &rsign, &rhash);
277         else
278             SSL_get_sigalgs(s, i, &sign_nid, &hash_nid, NULL, &rsign, &rhash);
279         if (i)
280             BIO_puts(out, ":");
281         sstr = get_sigtype(sign_nid);
282         if (sstr)
283             BIO_printf(out, "%s", sstr);
284         else
285             BIO_printf(out, "0x%02X", (int)rsign);
286         if (hash_nid != NID_undef)
287             BIO_printf(out, "+%s", OBJ_nid2sn(hash_nid));
288         else if (sstr == NULL)
289             BIO_printf(out, "+0x%02X", (int)rhash);
290     }
291     BIO_puts(out, "\n");
292     return 1;
293 }
294
295 int ssl_print_sigalgs(BIO *out, SSL *s)
296 {
297     int nid;
298     if (!SSL_is_server(s))
299         ssl_print_client_cert_types(out, s);
300     do_print_sigalgs(out, s, 0);
301     do_print_sigalgs(out, s, 1);
302     if (SSL_get_peer_signature_nid(s, &nid) && nid != NID_undef)
303         BIO_printf(out, "Peer signing digest: %s\n", OBJ_nid2sn(nid));
304     if (SSL_get_peer_signature_type_nid(s, &nid))
305         BIO_printf(out, "Peer signature type: %s\n", get_sigtype(nid));
306     return 1;
307 }
308
309 #ifndef OPENSSL_NO_EC
310 int ssl_print_point_formats(BIO *out, SSL *s)
311 {
312     int i, nformats;
313     const char *pformats;
314     nformats = SSL_get0_ec_point_formats(s, &pformats);
315     if (nformats <= 0)
316         return 1;
317     BIO_puts(out, "Supported Elliptic Curve Point Formats: ");
318     for (i = 0; i < nformats; i++, pformats++) {
319         if (i)
320             BIO_puts(out, ":");
321         switch (*pformats) {
322         case TLSEXT_ECPOINTFORMAT_uncompressed:
323             BIO_puts(out, "uncompressed");
324             break;
325
326         case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime:
327             BIO_puts(out, "ansiX962_compressed_prime");
328             break;
329
330         case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2:
331             BIO_puts(out, "ansiX962_compressed_char2");
332             break;
333
334         default:
335             BIO_printf(out, "unknown(%d)", (int)*pformats);
336             break;
337
338         }
339     }
340     BIO_puts(out, "\n");
341     return 1;
342 }
343
344 int ssl_print_groups(BIO *out, SSL *s, int noshared)
345 {
346     int i, ngroups, *groups, nid;
347     const char *gname;
348
349     ngroups = SSL_get1_groups(s, NULL);
350     if (ngroups <= 0)
351         return 1;
352     groups = app_malloc(ngroups * sizeof(int), "groups to print");
353     SSL_get1_groups(s, groups);
354
355     BIO_puts(out, "Supported Elliptic Groups: ");
356     for (i = 0; i < ngroups; i++) {
357         if (i)
358             BIO_puts(out, ":");
359         nid = groups[i];
360         /* If unrecognised print out hex version */
361         if (nid & TLSEXT_nid_unknown) {
362             BIO_printf(out, "0x%04X", nid & 0xFFFF);
363         } else {
364             /* TODO(TLS1.3): Get group name here */
365             /* Use NIST name for curve if it exists */
366             gname = EC_curve_nid2nist(nid);
367             if (gname == NULL)
368                 gname = OBJ_nid2sn(nid);
369             BIO_printf(out, "%s", gname);
370         }
371     }
372     OPENSSL_free(groups);
373     if (noshared) {
374         BIO_puts(out, "\n");
375         return 1;
376     }
377     BIO_puts(out, "\nShared Elliptic groups: ");
378     ngroups = SSL_get_shared_group(s, -1);
379     for (i = 0; i < ngroups; i++) {
380         if (i)
381             BIO_puts(out, ":");
382         nid = SSL_get_shared_group(s, i);
383         /* TODO(TLS1.3): Convert for DH groups */
384         gname = EC_curve_nid2nist(nid);
385         if (gname == NULL)
386             gname = OBJ_nid2sn(nid);
387         BIO_printf(out, "%s", gname);
388     }
389     if (ngroups == 0)
390         BIO_puts(out, "NONE");
391     BIO_puts(out, "\n");
392     return 1;
393 }
394 #endif
395
396 int ssl_print_tmp_key(BIO *out, SSL *s)
397 {
398     EVP_PKEY *key;
399
400     if (!SSL_get_peer_tmp_key(s, &key))
401         return 1;
402     BIO_puts(out, "Server Temp Key: ");
403     switch (EVP_PKEY_id(key)) {
404     case EVP_PKEY_RSA:
405         BIO_printf(out, "RSA, %d bits\n", EVP_PKEY_bits(key));
406         break;
407
408     case EVP_PKEY_DH:
409         BIO_printf(out, "DH, %d bits\n", EVP_PKEY_bits(key));
410         break;
411 #ifndef OPENSSL_NO_EC
412     case EVP_PKEY_EC:
413         {
414             EC_KEY *ec = EVP_PKEY_get1_EC_KEY(key);
415             int nid;
416             const char *cname;
417             nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
418             EC_KEY_free(ec);
419             cname = EC_curve_nid2nist(nid);
420             if (cname == NULL)
421                 cname = OBJ_nid2sn(nid);
422             BIO_printf(out, "ECDH, %s, %d bits\n", cname, EVP_PKEY_bits(key));
423         }
424     break;
425 #endif
426     default:
427         BIO_printf(out, "%s, %d bits\n", OBJ_nid2sn(EVP_PKEY_id(key)),
428                    EVP_PKEY_bits(key));
429     }
430     EVP_PKEY_free(key);
431     return 1;
432 }
433
434 long bio_dump_callback(BIO *bio, int cmd, const char *argp,
435                        int argi, long argl, long ret)
436 {
437     BIO *out;
438
439     out = (BIO *)BIO_get_callback_arg(bio);
440     if (out == NULL)
441         return ret;
442
443     if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
444         BIO_printf(out, "read from %p [%p] (%lu bytes => %ld (0x%lX))\n",
445                    (void *)bio, (void *)argp, (unsigned long)argi, ret, ret);
446         BIO_dump(out, argp, (int)ret);
447         return ret;
448     } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
449         BIO_printf(out, "write to %p [%p] (%lu bytes => %ld (0x%lX))\n",
450                    (void *)bio, (void *)argp, (unsigned long)argi, ret, ret);
451         BIO_dump(out, argp, (int)ret);
452     }
453     return ret;
454 }
455
456 void apps_ssl_info_callback(const SSL *s, int where, int ret)
457 {
458     const char *str;
459     int w;
460
461     w = where & ~SSL_ST_MASK;
462
463     if (w & SSL_ST_CONNECT)
464         str = "SSL_connect";
465     else if (w & SSL_ST_ACCEPT)
466         str = "SSL_accept";
467     else
468         str = "undefined";
469
470     if (where & SSL_CB_LOOP) {
471         BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s));
472     } else if (where & SSL_CB_ALERT) {
473         str = (where & SSL_CB_READ) ? "read" : "write";
474         BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n",
475                    str,
476                    SSL_alert_type_string_long(ret),
477                    SSL_alert_desc_string_long(ret));
478     } else if (where & SSL_CB_EXIT) {
479         if (ret == 0)
480             BIO_printf(bio_err, "%s:failed in %s\n",
481                        str, SSL_state_string_long(s));
482         else if (ret < 0)
483             BIO_printf(bio_err, "%s:error in %s\n",
484                        str, SSL_state_string_long(s));
485     }
486 }
487
488 static STRINT_PAIR ssl_versions[] = {
489     {"SSL 3.0", SSL3_VERSION},
490     {"TLS 1.0", TLS1_VERSION},
491     {"TLS 1.1", TLS1_1_VERSION},
492     {"TLS 1.2", TLS1_2_VERSION},
493     {"TLS 1.3", TLS1_3_VERSION},
494     {"DTLS 1.0", DTLS1_VERSION},
495     {"DTLS 1.0 (bad)", DTLS1_BAD_VER},
496     {NULL}
497 };
498
499 static STRINT_PAIR alert_types[] = {
500     {" close_notify", 0},
501     {" end_of_early_data", 1},
502     {" unexpected_message", 10},
503     {" bad_record_mac", 20},
504     {" decryption_failed", 21},
505     {" record_overflow", 22},
506     {" decompression_failure", 30},
507     {" handshake_failure", 40},
508     {" bad_certificate", 42},
509     {" unsupported_certificate", 43},
510     {" certificate_revoked", 44},
511     {" certificate_expired", 45},
512     {" certificate_unknown", 46},
513     {" illegal_parameter", 47},
514     {" unknown_ca", 48},
515     {" access_denied", 49},
516     {" decode_error", 50},
517     {" decrypt_error", 51},
518     {" export_restriction", 60},
519     {" protocol_version", 70},
520     {" insufficient_security", 71},
521     {" internal_error", 80},
522     {" inappropriate_fallback", 86},
523     {" user_canceled", 90},
524     {" no_renegotiation", 100},
525     {" missing_extension", 109},
526     {" unsupported_extension", 110},
527     {" certificate_unobtainable", 111},
528     {" unrecognized_name", 112},
529     {" bad_certificate_status_response", 113},
530     {" bad_certificate_hash_value", 114},
531     {" unknown_psk_identity", 115},
532     {" certificate_required", 116},
533     {NULL}
534 };
535
536 static STRINT_PAIR handshakes[] = {
537     {", HelloRequest", SSL3_MT_HELLO_REQUEST},
538     {", ClientHello", SSL3_MT_CLIENT_HELLO},
539     {", ServerHello", SSL3_MT_SERVER_HELLO},
540     {", HelloVerifyRequest", DTLS1_MT_HELLO_VERIFY_REQUEST},
541     {", NewSessionTicket", SSL3_MT_NEWSESSION_TICKET},
542     {", EndOfEarlyData", SSL3_MT_END_OF_EARLY_DATA},
543     {", EncryptedExtensions", SSL3_MT_ENCRYPTED_EXTENSIONS},
544     {", Certificate", SSL3_MT_CERTIFICATE},
545     {", ServerKeyExchange", SSL3_MT_SERVER_KEY_EXCHANGE},
546     {", CertificateRequest", SSL3_MT_CERTIFICATE_REQUEST},
547     {", ServerHelloDone", SSL3_MT_SERVER_DONE},
548     {", CertificateVerify", SSL3_MT_CERTIFICATE_VERIFY},
549     {", ClientKeyExchange", SSL3_MT_CLIENT_KEY_EXCHANGE},
550     {", Finished", SSL3_MT_FINISHED},
551     {", CertificateUrl", SSL3_MT_CERTIFICATE_URL},
552     {", CertificateStatus", SSL3_MT_CERTIFICATE_STATUS},
553     {", SupplementalData", SSL3_MT_SUPPLEMENTAL_DATA},
554     {", KeyUpdate", SSL3_MT_KEY_UPDATE},
555 #ifndef OPENSSL_NO_NEXTPROTONEG
556     {", NextProto", SSL3_MT_NEXT_PROTO},
557 #endif
558     {", MessageHash", SSL3_MT_MESSAGE_HASH},
559     {NULL}
560 };
561
562 void msg_cb(int write_p, int version, int content_type, const void *buf,
563             size_t len, SSL *ssl, void *arg)
564 {
565     BIO *bio = arg;
566     const char *str_write_p = write_p ? ">>>" : "<<<";
567     const char *str_version = lookup(version, ssl_versions, "???");
568     const char *str_content_type = "", *str_details1 = "", *str_details2 = "";
569     const unsigned char* bp = buf;
570
571     if (version == SSL3_VERSION ||
572         version == TLS1_VERSION ||
573         version == TLS1_1_VERSION ||
574         version == TLS1_2_VERSION ||
575         version == TLS1_3_VERSION ||
576         version == DTLS1_VERSION || version == DTLS1_BAD_VER) {
577         switch (content_type) {
578         case 20:
579             str_content_type = ", ChangeCipherSpec";
580             break;
581         case 21:
582             str_content_type = ", Alert";
583             str_details1 = ", ???";
584             if (len == 2) {
585                 switch (bp[0]) {
586                 case 1:
587                     str_details1 = ", warning";
588                     break;
589                 case 2:
590                     str_details1 = ", fatal";
591                     break;
592                 }
593                 str_details2 = lookup((int)bp[1], alert_types, " ???");
594             }
595             break;
596         case 22:
597             str_content_type = ", Handshake";
598             str_details1 = "???";
599             if (len > 0)
600                 str_details1 = lookup((int)bp[0], handshakes, "???");
601             break;
602         case 23:
603             str_content_type = ", ApplicationData";
604             break;
605         }
606     }
607
608     BIO_printf(bio, "%s %s%s [length %04lx]%s%s\n", str_write_p, str_version,
609                str_content_type, (unsigned long)len, str_details1,
610                str_details2);
611
612     if (len > 0) {
613         size_t num, i;
614
615         BIO_printf(bio, "   ");
616         num = len;
617         for (i = 0; i < num; i++) {
618             if (i % 16 == 0 && i > 0)
619                 BIO_printf(bio, "\n   ");
620             BIO_printf(bio, " %02x", ((const unsigned char *)buf)[i]);
621         }
622         if (i < len)
623             BIO_printf(bio, " ...");
624         BIO_printf(bio, "\n");
625     }
626     (void)BIO_flush(bio);
627 }
628
629 static STRINT_PAIR tlsext_types[] = {
630     {"server name", TLSEXT_TYPE_server_name},
631     {"max fragment length", TLSEXT_TYPE_max_fragment_length},
632     {"client certificate URL", TLSEXT_TYPE_client_certificate_url},
633     {"trusted CA keys", TLSEXT_TYPE_trusted_ca_keys},
634     {"truncated HMAC", TLSEXT_TYPE_truncated_hmac},
635     {"status request", TLSEXT_TYPE_status_request},
636     {"user mapping", TLSEXT_TYPE_user_mapping},
637     {"client authz", TLSEXT_TYPE_client_authz},
638     {"server authz", TLSEXT_TYPE_server_authz},
639     {"cert type", TLSEXT_TYPE_cert_type},
640     {"supported_groups", TLSEXT_TYPE_supported_groups},
641     {"EC point formats", TLSEXT_TYPE_ec_point_formats},
642     {"SRP", TLSEXT_TYPE_srp},
643     {"signature algorithms", TLSEXT_TYPE_signature_algorithms},
644     {"use SRTP", TLSEXT_TYPE_use_srtp},
645     {"session ticket", TLSEXT_TYPE_session_ticket},
646     {"renegotiation info", TLSEXT_TYPE_renegotiate},
647     {"signed certificate timestamps", TLSEXT_TYPE_signed_certificate_timestamp},
648     {"TLS padding", TLSEXT_TYPE_padding},
649 #ifdef TLSEXT_TYPE_next_proto_neg
650     {"next protocol", TLSEXT_TYPE_next_proto_neg},
651 #endif
652 #ifdef TLSEXT_TYPE_encrypt_then_mac
653     {"encrypt-then-mac", TLSEXT_TYPE_encrypt_then_mac},
654 #endif
655 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
656     {"application layer protocol negotiation",
657      TLSEXT_TYPE_application_layer_protocol_negotiation},
658 #endif
659 #ifdef TLSEXT_TYPE_extended_master_secret
660     {"extended master secret", TLSEXT_TYPE_extended_master_secret},
661 #endif
662     {"key share", TLSEXT_TYPE_key_share},
663     {"supported versions", TLSEXT_TYPE_supported_versions},
664     {"psk", TLSEXT_TYPE_psk},
665     {"psk kex modes", TLSEXT_TYPE_psk_kex_modes},
666     {"certificate authorities", TLSEXT_TYPE_certificate_authorities},
667     {"post handshake auth", TLSEXT_TYPE_post_handshake_auth},
668     {NULL}
669 };
670
671 /* from rfc8446 4.2.3. + gost (https://tools.ietf.org/id/draft-smyshlyaev-tls12-gost-suites-04.html) */
672 static STRINT_PAIR signature_tls13_scheme_list[] = {
673     {"rsa_pkcs1_sha1",         0x0201 /* TLSEXT_SIGALG_rsa_pkcs1_sha1 */},
674     {"ecdsa_sha1",             0x0203 /* TLSEXT_SIGALG_ecdsa_sha1 */},
675 /*  {"rsa_pkcs1_sha224",       0x0301    TLSEXT_SIGALG_rsa_pkcs1_sha224}, not in rfc8446 */
676 /*  {"ecdsa_sha224",           0x0303    TLSEXT_SIGALG_ecdsa_sha224}      not in rfc8446 */
677     {"rsa_pkcs1_sha256",       0x0401 /* TLSEXT_SIGALG_rsa_pkcs1_sha256 */},
678     {"ecdsa_secp256r1_sha256", 0x0403 /* TLSEXT_SIGALG_ecdsa_secp256r1_sha256 */},
679     {"rsa_pkcs1_sha384",       0x0501 /* TLSEXT_SIGALG_rsa_pkcs1_sha384 */},
680     {"ecdsa_secp384r1_sha384", 0x0503 /* TLSEXT_SIGALG_ecdsa_secp384r1_sha384 */},
681     {"rsa_pkcs1_sha512",       0x0601 /* TLSEXT_SIGALG_rsa_pkcs1_sha512 */},
682     {"ecdsa_secp521r1_sha512", 0x0603 /* TLSEXT_SIGALG_ecdsa_secp521r1_sha512 */},
683     {"rsa_pss_rsae_sha256",    0x0804 /* TLSEXT_SIGALG_rsa_pss_rsae_sha256 */},
684     {"rsa_pss_rsae_sha384",    0x0805 /* TLSEXT_SIGALG_rsa_pss_rsae_sha384 */},
685     {"rsa_pss_rsae_sha512",    0x0806 /* TLSEXT_SIGALG_rsa_pss_rsae_sha512 */},
686     {"ed25519",                0x0807 /* TLSEXT_SIGALG_ed25519 */},
687     {"ed448",                  0x0808 /* TLSEXT_SIGALG_ed448 */},
688     {"rsa_pss_pss_sha256",     0x0809 /* TLSEXT_SIGALG_rsa_pss_pss_sha256 */},
689     {"rsa_pss_pss_sha384",     0x080a /* TLSEXT_SIGALG_rsa_pss_pss_sha384 */},
690     {"rsa_pss_pss_sha512",     0x080b /* TLSEXT_SIGALG_rsa_pss_pss_sha512 */},
691     {"gostr34102001",          0xeded /* TLSEXT_SIGALG_gostr34102001_gostr3411 */},
692     {"gostr34102012_256",      0xeeee /* TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256 */},
693     {"gostr34102012_512",      0xefef /* TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512 */},
694     {NULL}
695 };
696
697 /* from rfc5246 7.4.1.4.1. */
698 static STRINT_PAIR signature_tls12_alg_list[] = {
699     {"anonymous", TLSEXT_signature_anonymous /* 0 */},
700     {"RSA",       TLSEXT_signature_rsa       /* 1 */},
701     {"DSA",       TLSEXT_signature_dsa       /* 2 */},
702     {"ECDSA",     TLSEXT_signature_ecdsa     /* 3 */},
703     {NULL}
704 };
705
706 /* from rfc5246 7.4.1.4.1. */
707 static STRINT_PAIR signature_tls12_hash_list[] = {
708     {"none",   TLSEXT_hash_none   /* 0 */},
709     {"MD5",    TLSEXT_hash_md5    /* 1 */},
710     {"SHA1",   TLSEXT_hash_sha1   /* 2 */},
711     {"SHA224", TLSEXT_hash_sha224 /* 3 */},
712     {"SHA256", TLSEXT_hash_sha256 /* 4 */},
713     {"SHA384", TLSEXT_hash_sha384 /* 5 */},
714     {"SHA512", TLSEXT_hash_sha512 /* 6 */},
715     {NULL}
716 };
717
718 void tlsext_cb(SSL *s, int client_server, int type,
719                const unsigned char *data, int len, void *arg)
720 {
721     BIO *bio = arg;
722     const char *extname = lookup(type, tlsext_types, "unknown");
723
724     BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
725                client_server ? "server" : "client", extname, type, len);
726     BIO_dump(bio, (const char *)data, len);
727     (void)BIO_flush(bio);
728 }
729
730 #ifndef OPENSSL_NO_SOCK
731 int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
732                              unsigned int *cookie_len)
733 {
734     unsigned char *buffer = NULL;
735     size_t length = 0;
736     unsigned short port;
737     BIO_ADDR *lpeer = NULL, *peer = NULL;
738     int res = 0;
739     EVP_MAC *hmac = NULL;
740     EVP_MAC_CTX *ctx = NULL;
741     OSSL_PARAM params[3], *p = params;
742
743     /* Initialize a random secret */
744     if (!cookie_initialized) {
745         if (RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH) <= 0) {
746             BIO_printf(bio_err, "error setting random cookie secret\n");
747             return 0;
748         }
749         cookie_initialized = 1;
750     }
751
752     if (SSL_is_dtls(ssl)) {
753         lpeer = peer = BIO_ADDR_new();
754         if (peer == NULL) {
755             BIO_printf(bio_err, "memory full\n");
756             return 0;
757         }
758
759         /* Read peer information */
760         (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), peer);
761     } else {
762         peer = ourpeer;
763     }
764
765     /* Create buffer with peer's address and port */
766     if (!BIO_ADDR_rawaddress(peer, NULL, &length)) {
767         BIO_printf(bio_err, "Failed getting peer address\n");
768         return 0;
769     }
770     OPENSSL_assert(length != 0);
771     port = BIO_ADDR_rawport(peer);
772     length += sizeof(port);
773     buffer = app_malloc(length, "cookie generate buffer");
774
775     memcpy(buffer, &port, sizeof(port));
776     BIO_ADDR_rawaddress(peer, buffer + sizeof(port), NULL);
777
778     /* Calculate HMAC of buffer using the secret */
779     hmac = EVP_MAC_fetch(NULL, "HMAC", NULL);
780     if (hmac == NULL) {
781             BIO_printf(bio_err, "HMAC not found\n");
782             goto end;
783     }
784     ctx = EVP_MAC_CTX_new(hmac);
785     if (ctx == NULL) {
786             BIO_printf(bio_err, "HMAC context allocation failed\n");
787             goto end;
788     }
789     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, "SHA1", 0);
790     *p++ = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, cookie_secret,
791                                              COOKIE_SECRET_LENGTH);
792     *p = OSSL_PARAM_construct_end();
793     if (!EVP_MAC_CTX_set_params(ctx, params)) {
794             BIO_printf(bio_err, "HMAC context parameter setting failed\n");
795             goto end;
796     }
797     if (!EVP_MAC_init(ctx)) {
798             BIO_printf(bio_err, "HMAC context initialisation failed\n");
799             goto end;
800     }
801     if (!EVP_MAC_update(ctx, buffer, length)) {
802             BIO_printf(bio_err, "HMAC context update failed\n");
803             goto end;
804     }
805     if (!EVP_MAC_final(ctx, cookie, NULL, (size_t)cookie_len)) {
806             BIO_printf(bio_err, "HMAC context final failed\n");
807             goto end;
808     }
809     res = 1;
810 end:
811     OPENSSL_free(buffer);
812     BIO_ADDR_free(lpeer);
813
814     return res;
815 }
816
817 int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
818                            unsigned int cookie_len)
819 {
820     unsigned char result[EVP_MAX_MD_SIZE];
821     unsigned int resultlength;
822
823     /* Note: we check cookie_initialized because if it's not,
824      * it cannot be valid */
825     if (cookie_initialized
826         && generate_cookie_callback(ssl, result, &resultlength)
827         && cookie_len == resultlength
828         && memcmp(result, cookie, resultlength) == 0)
829         return 1;
830
831     return 0;
832 }
833
834 int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
835                                        size_t *cookie_len)
836 {
837     unsigned int temp;
838     int res = generate_cookie_callback(ssl, cookie, &temp);
839     *cookie_len = temp;
840     return res;
841 }
842
843 int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
844                                      size_t cookie_len)
845 {
846     return verify_cookie_callback(ssl, cookie, cookie_len);
847 }
848
849 #endif
850
851 /*
852  * Example of extended certificate handling. Where the standard support of
853  * one certificate per algorithm is not sufficient an application can decide
854  * which certificate(s) to use at runtime based on whatever criteria it deems
855  * appropriate.
856  */
857
858 /* Linked list of certificates, keys and chains */
859 struct ssl_excert_st {
860     int certform;
861     const char *certfile;
862     int keyform;
863     const char *keyfile;
864     const char *chainfile;
865     X509 *cert;
866     EVP_PKEY *key;
867     STACK_OF(X509) *chain;
868     int build_chain;
869     struct ssl_excert_st *next, *prev;
870 };
871
872 static STRINT_PAIR chain_flags[] = {
873     {"Overall Validity", CERT_PKEY_VALID},
874     {"Sign with EE key", CERT_PKEY_SIGN},
875     {"EE signature", CERT_PKEY_EE_SIGNATURE},
876     {"CA signature", CERT_PKEY_CA_SIGNATURE},
877     {"EE key parameters", CERT_PKEY_EE_PARAM},
878     {"CA key parameters", CERT_PKEY_CA_PARAM},
879     {"Explicitly sign with EE key", CERT_PKEY_EXPLICIT_SIGN},
880     {"Issuer Name", CERT_PKEY_ISSUER_NAME},
881     {"Certificate Type", CERT_PKEY_CERT_TYPE},
882     {NULL}
883 };
884
885 static void print_chain_flags(SSL *s, int flags)
886 {
887     STRINT_PAIR *pp;
888
889     for (pp = chain_flags; pp->name; ++pp)
890         BIO_printf(bio_err, "\t%s: %s\n",
891                    pp->name,
892                    (flags & pp->retval) ? "OK" : "NOT OK");
893     BIO_printf(bio_err, "\tSuite B: ");
894     if (SSL_set_cert_flags(s, 0) & SSL_CERT_FLAG_SUITEB_128_LOS)
895         BIO_puts(bio_err, flags & CERT_PKEY_SUITEB ? "OK\n" : "NOT OK\n");
896     else
897         BIO_printf(bio_err, "not tested\n");
898 }
899
900 /*
901  * Very basic selection callback: just use any certificate chain reported as
902  * valid. More sophisticated could prioritise according to local policy.
903  */
904 static int set_cert_cb(SSL *ssl, void *arg)
905 {
906     int i, rv;
907     SSL_EXCERT *exc = arg;
908 #ifdef CERT_CB_TEST_RETRY
909     static int retry_cnt;
910     if (retry_cnt < 5) {
911         retry_cnt++;
912         BIO_printf(bio_err,
913                    "Certificate callback retry test: count %d\n",
914                    retry_cnt);
915         return -1;
916     }
917 #endif
918     SSL_certs_clear(ssl);
919
920     if (exc == NULL)
921         return 1;
922
923     /*
924      * Go to end of list and traverse backwards since we prepend newer
925      * entries this retains the original order.
926      */
927     while (exc->next != NULL)
928         exc = exc->next;
929
930     i = 0;
931
932     while (exc != NULL) {
933         i++;
934         rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain);
935         BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i);
936         X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0,
937                            get_nameopt());
938         BIO_puts(bio_err, "\n");
939         print_chain_flags(ssl, rv);
940         if (rv & CERT_PKEY_VALID) {
941             if (!SSL_use_certificate(ssl, exc->cert)
942                     || !SSL_use_PrivateKey(ssl, exc->key)) {
943                 return 0;
944             }
945             /*
946              * NB: we wouldn't normally do this as it is not efficient
947              * building chains on each connection better to cache the chain
948              * in advance.
949              */
950             if (exc->build_chain) {
951                 if (!SSL_build_cert_chain(ssl, 0))
952                     return 0;
953             } else if (exc->chain != NULL) {
954                 SSL_set1_chain(ssl, exc->chain);
955             }
956         }
957         exc = exc->prev;
958     }
959     return 1;
960 }
961
962 void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc)
963 {
964     SSL_CTX_set_cert_cb(ctx, set_cert_cb, exc);
965 }
966
967 static int ssl_excert_prepend(SSL_EXCERT **pexc)
968 {
969     SSL_EXCERT *exc = app_malloc(sizeof(*exc), "prepend cert");
970
971     memset(exc, 0, sizeof(*exc));
972
973     exc->next = *pexc;
974     *pexc = exc;
975
976     if (exc->next) {
977         exc->certform = exc->next->certform;
978         exc->keyform = exc->next->keyform;
979         exc->next->prev = exc;
980     } else {
981         exc->certform = FORMAT_PEM;
982         exc->keyform = FORMAT_PEM;
983     }
984     return 1;
985
986 }
987
988 void ssl_excert_free(SSL_EXCERT *exc)
989 {
990     SSL_EXCERT *curr;
991
992     if (exc == NULL)
993         return;
994     while (exc) {
995         X509_free(exc->cert);
996         EVP_PKEY_free(exc->key);
997         sk_X509_pop_free(exc->chain, X509_free);
998         curr = exc;
999         exc = exc->next;
1000         OPENSSL_free(curr);
1001     }
1002 }
1003
1004 int load_excert(SSL_EXCERT **pexc)
1005 {
1006     SSL_EXCERT *exc = *pexc;
1007     if (exc == NULL)
1008         return 1;
1009     /* If nothing in list, free and set to NULL */
1010     if (exc->certfile == NULL && exc->next == NULL) {
1011         ssl_excert_free(exc);
1012         *pexc = NULL;
1013         return 1;
1014     }
1015     for (; exc; exc = exc->next) {
1016         if (exc->certfile == NULL) {
1017             BIO_printf(bio_err, "Missing filename\n");
1018             return 0;
1019         }
1020         exc->cert = load_cert(exc->certfile, exc->certform,
1021                               "Server Certificate");
1022         if (exc->cert == NULL)
1023             return 0;
1024         if (exc->keyfile != NULL) {
1025             exc->key = load_key(exc->keyfile, exc->keyform,
1026                                 0, NULL, NULL, "Server Key");
1027         } else {
1028             exc->key = load_key(exc->certfile, exc->certform,
1029                                 0, NULL, NULL, "Server Key");
1030         }
1031         if (exc->key == NULL)
1032             return 0;
1033         if (exc->chainfile != NULL) {
1034             if (!load_certs(exc->chainfile, &exc->chain, FORMAT_PEM, NULL,
1035                             "Server Chain"))
1036                 return 0;
1037         }
1038     }
1039     return 1;
1040 }
1041
1042 enum range { OPT_X_ENUM };
1043
1044 int args_excert(int opt, SSL_EXCERT **pexc)
1045 {
1046     SSL_EXCERT *exc = *pexc;
1047
1048     assert(opt > OPT_X__FIRST);
1049     assert(opt < OPT_X__LAST);
1050
1051     if (exc == NULL) {
1052         if (!ssl_excert_prepend(&exc)) {
1053             BIO_printf(bio_err, " %s: Error initialising xcert\n",
1054                        opt_getprog());
1055             goto err;
1056         }
1057         *pexc = exc;
1058     }
1059
1060     switch ((enum range)opt) {
1061     case OPT_X__FIRST:
1062     case OPT_X__LAST:
1063         return 0;
1064     case OPT_X_CERT:
1065         if (exc->certfile != NULL && !ssl_excert_prepend(&exc)) {
1066             BIO_printf(bio_err, "%s: Error adding xcert\n", opt_getprog());
1067             goto err;
1068         }
1069         *pexc = exc;
1070         exc->certfile = opt_arg();
1071         break;
1072     case OPT_X_KEY:
1073         if (exc->keyfile != NULL) {
1074             BIO_printf(bio_err, "%s: Key already specified\n", opt_getprog());
1075             goto err;
1076         }
1077         exc->keyfile = opt_arg();
1078         break;
1079     case OPT_X_CHAIN:
1080         if (exc->chainfile != NULL) {
1081             BIO_printf(bio_err, "%s: Chain already specified\n",
1082                        opt_getprog());
1083             goto err;
1084         }
1085         exc->chainfile = opt_arg();
1086         break;
1087     case OPT_X_CHAIN_BUILD:
1088         exc->build_chain = 1;
1089         break;
1090     case OPT_X_CERTFORM:
1091         if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &exc->certform))
1092             return 0;
1093         break;
1094     case OPT_X_KEYFORM:
1095         if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &exc->keyform))
1096             return 0;
1097         break;
1098     }
1099     return 1;
1100
1101  err:
1102     ERR_print_errors(bio_err);
1103     ssl_excert_free(exc);
1104     *pexc = NULL;
1105     return 0;
1106 }
1107
1108 static void print_raw_cipherlist(SSL *s)
1109 {
1110     const unsigned char *rlist;
1111     static const unsigned char scsv_id[] = { 0, 0xFF };
1112     size_t i, rlistlen, num;
1113     if (!SSL_is_server(s))
1114         return;
1115     num = SSL_get0_raw_cipherlist(s, NULL);
1116     OPENSSL_assert(num == 2);
1117     rlistlen = SSL_get0_raw_cipherlist(s, &rlist);
1118     BIO_puts(bio_err, "Client cipher list: ");
1119     for (i = 0; i < rlistlen; i += num, rlist += num) {
1120         const SSL_CIPHER *c = SSL_CIPHER_find(s, rlist);
1121         if (i)
1122             BIO_puts(bio_err, ":");
1123         if (c != NULL) {
1124             BIO_puts(bio_err, SSL_CIPHER_get_name(c));
1125         } else if (memcmp(rlist, scsv_id, num) == 0) {
1126             BIO_puts(bio_err, "SCSV");
1127         } else {
1128             size_t j;
1129             BIO_puts(bio_err, "0x");
1130             for (j = 0; j < num; j++)
1131                 BIO_printf(bio_err, "%02X", rlist[j]);
1132         }
1133     }
1134     BIO_puts(bio_err, "\n");
1135 }
1136
1137 /*
1138  * Hex encoder for TLSA RRdata, not ':' delimited.
1139  */
1140 static char *hexencode(const unsigned char *data, size_t len)
1141 {
1142     static const char *hex = "0123456789abcdef";
1143     char *out;
1144     char *cp;
1145     size_t outlen = 2 * len + 1;
1146     int ilen = (int) outlen;
1147
1148     if (outlen < len || ilen < 0 || outlen != (size_t)ilen) {
1149         BIO_printf(bio_err, "%s: %zu-byte buffer too large to hexencode\n",
1150                    opt_getprog(), len);
1151         exit(1);
1152     }
1153     cp = out = app_malloc(ilen, "TLSA hex data buffer");
1154
1155     while (len-- > 0) {
1156         *cp++ = hex[(*data >> 4) & 0x0f];
1157         *cp++ = hex[*data++ & 0x0f];
1158     }
1159     *cp = '\0';
1160     return out;
1161 }
1162
1163 void print_verify_detail(SSL *s, BIO *bio)
1164 {
1165     int mdpth;
1166     EVP_PKEY *mspki;
1167     long verify_err = SSL_get_verify_result(s);
1168
1169     if (verify_err == X509_V_OK) {
1170         const char *peername = SSL_get0_peername(s);
1171
1172         BIO_printf(bio, "Verification: OK\n");
1173         if (peername != NULL)
1174             BIO_printf(bio, "Verified peername: %s\n", peername);
1175     } else {
1176         const char *reason = X509_verify_cert_error_string(verify_err);
1177
1178         BIO_printf(bio, "Verification error: %s\n", reason);
1179     }
1180
1181     if ((mdpth = SSL_get0_dane_authority(s, NULL, &mspki)) >= 0) {
1182         uint8_t usage, selector, mtype;
1183         const unsigned char *data = NULL;
1184         size_t dlen = 0;
1185         char *hexdata;
1186
1187         mdpth = SSL_get0_dane_tlsa(s, &usage, &selector, &mtype, &data, &dlen);
1188
1189         /*
1190          * The TLSA data field can be quite long when it is a certificate,
1191          * public key or even a SHA2-512 digest.  Because the initial octets of
1192          * ASN.1 certificates and public keys contain mostly boilerplate OIDs
1193          * and lengths, we show the last 12 bytes of the data instead, as these
1194          * are more likely to distinguish distinct TLSA records.
1195          */
1196 #define TLSA_TAIL_SIZE 12
1197         if (dlen > TLSA_TAIL_SIZE)
1198             hexdata = hexencode(data + dlen - TLSA_TAIL_SIZE, TLSA_TAIL_SIZE);
1199         else
1200             hexdata = hexencode(data, dlen);
1201         BIO_printf(bio, "DANE TLSA %d %d %d %s%s %s at depth %d\n",
1202                    usage, selector, mtype,
1203                    (dlen > TLSA_TAIL_SIZE) ? "..." : "", hexdata,
1204                    (mspki != NULL) ? "signed the certificate" :
1205                    mdpth ? "matched TA certificate" : "matched EE certificate",
1206                    mdpth);
1207         OPENSSL_free(hexdata);
1208     }
1209 }
1210
1211 void print_ssl_summary(SSL *s)
1212 {
1213     const SSL_CIPHER *c;
1214     X509 *peer;
1215
1216     BIO_printf(bio_err, "Protocol version: %s\n", SSL_get_version(s));
1217     print_raw_cipherlist(s);
1218     c = SSL_get_current_cipher(s);
1219     BIO_printf(bio_err, "Ciphersuite: %s\n", SSL_CIPHER_get_name(c));
1220     do_print_sigalgs(bio_err, s, 0);
1221     peer = SSL_get_peer_certificate(s);
1222     if (peer != NULL) {
1223         int nid;
1224
1225         BIO_puts(bio_err, "Peer certificate: ");
1226         X509_NAME_print_ex(bio_err, X509_get_subject_name(peer),
1227                            0, get_nameopt());
1228         BIO_puts(bio_err, "\n");
1229         if (SSL_get_peer_signature_nid(s, &nid))
1230             BIO_printf(bio_err, "Hash used: %s\n", OBJ_nid2sn(nid));
1231         if (SSL_get_peer_signature_type_nid(s, &nid))
1232             BIO_printf(bio_err, "Signature type: %s\n", get_sigtype(nid));
1233         print_verify_detail(s, bio_err);
1234     } else {
1235         BIO_puts(bio_err, "No peer certificate\n");
1236     }
1237     X509_free(peer);
1238 #ifndef OPENSSL_NO_EC
1239     ssl_print_point_formats(bio_err, s);
1240     if (SSL_is_server(s))
1241         ssl_print_groups(bio_err, s, 1);
1242     else
1243         ssl_print_tmp_key(bio_err, s);
1244 #else
1245     if (!SSL_is_server(s))
1246         ssl_print_tmp_key(bio_err, s);
1247 #endif
1248 }
1249
1250 int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str,
1251                SSL_CTX *ctx)
1252 {
1253     int i;
1254
1255     SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
1256     for (i = 0; i < sk_OPENSSL_STRING_num(str); i += 2) {
1257         const char *flag = sk_OPENSSL_STRING_value(str, i);
1258         const char *arg = sk_OPENSSL_STRING_value(str, i + 1);
1259         if (SSL_CONF_cmd(cctx, flag, arg) <= 0) {
1260             if (arg != NULL)
1261                 BIO_printf(bio_err, "Error with command: \"%s %s\"\n",
1262                            flag, arg);
1263             else
1264                 BIO_printf(bio_err, "Error with command: \"%s\"\n", flag);
1265             ERR_print_errors(bio_err);
1266             return 0;
1267         }
1268     }
1269     if (!SSL_CONF_CTX_finish(cctx)) {
1270         BIO_puts(bio_err, "Error finishing context\n");
1271         ERR_print_errors(bio_err);
1272         return 0;
1273     }
1274     return 1;
1275 }
1276
1277 static int add_crls_store(X509_STORE *st, STACK_OF(X509_CRL) *crls)
1278 {
1279     X509_CRL *crl;
1280     int i;
1281     for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1282         crl = sk_X509_CRL_value(crls, i);
1283         X509_STORE_add_crl(st, crl);
1284     }
1285     return 1;
1286 }
1287
1288 int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls, int crl_download)
1289 {
1290     X509_STORE *st;
1291     st = SSL_CTX_get_cert_store(ctx);
1292     add_crls_store(st, crls);
1293     if (crl_download)
1294         store_setup_crl_download(st);
1295     return 1;
1296 }
1297
1298 int ssl_load_stores(SSL_CTX *ctx,
1299                     const char *vfyCApath, const char *vfyCAfile,
1300                     const char *vfyCAstore,
1301                     const char *chCApath, const char *chCAfile,
1302                     const char *chCAstore,
1303                     STACK_OF(X509_CRL) *crls, int crl_download)
1304 {
1305     X509_STORE *vfy = NULL, *ch = NULL;
1306     int rv = 0;
1307     if (vfyCApath != NULL || vfyCAfile != NULL || vfyCAstore != NULL) {
1308         vfy = X509_STORE_new();
1309         if (vfy == NULL)
1310             goto err;
1311         if (vfyCAfile != NULL && !X509_STORE_load_file(vfy, vfyCAfile))
1312             goto err;
1313         if (vfyCApath != NULL && !X509_STORE_load_path(vfy, vfyCApath))
1314             goto err;
1315         if (vfyCAstore != NULL && !X509_STORE_load_store(vfy, vfyCAstore))
1316             goto err;
1317         add_crls_store(vfy, crls);
1318         SSL_CTX_set1_verify_cert_store(ctx, vfy);
1319         if (crl_download)
1320             store_setup_crl_download(vfy);
1321     }
1322     if (chCApath != NULL || chCAfile != NULL || chCAstore != NULL) {
1323         ch = X509_STORE_new();
1324         if (ch == NULL)
1325             goto err;
1326         if (chCAfile != NULL && !X509_STORE_load_file(ch, chCAfile))
1327             goto err;
1328         if (chCApath != NULL && !X509_STORE_load_path(ch, chCApath))
1329             goto err;
1330         if (chCAstore != NULL && !X509_STORE_load_store(ch, chCAstore))
1331             goto err;
1332         SSL_CTX_set1_chain_cert_store(ctx, ch);
1333     }
1334     rv = 1;
1335  err:
1336     X509_STORE_free(vfy);
1337     X509_STORE_free(ch);
1338     return rv;
1339 }
1340
1341 /* Verbose print out of security callback */
1342
1343 typedef struct {
1344     BIO *out;
1345     int verbose;
1346     int (*old_cb) (const SSL *s, const SSL_CTX *ctx, int op, int bits, int nid,
1347                    void *other, void *ex);
1348 } security_debug_ex;
1349
1350 static STRINT_PAIR callback_types[] = {
1351     {"Supported Ciphersuite", SSL_SECOP_CIPHER_SUPPORTED},
1352     {"Shared Ciphersuite", SSL_SECOP_CIPHER_SHARED},
1353     {"Check Ciphersuite", SSL_SECOP_CIPHER_CHECK},
1354 #ifndef OPENSSL_NO_DH
1355     {"Temp DH key bits", SSL_SECOP_TMP_DH},
1356 #endif
1357     {"Supported Curve", SSL_SECOP_CURVE_SUPPORTED},
1358     {"Shared Curve", SSL_SECOP_CURVE_SHARED},
1359     {"Check Curve", SSL_SECOP_CURVE_CHECK},
1360     {"Supported Signature Algorithm", SSL_SECOP_SIGALG_SUPPORTED},
1361     {"Shared Signature Algorithm", SSL_SECOP_SIGALG_SHARED},
1362     {"Check Signature Algorithm", SSL_SECOP_SIGALG_CHECK},
1363     {"Signature Algorithm mask", SSL_SECOP_SIGALG_MASK},
1364     {"Certificate chain EE key", SSL_SECOP_EE_KEY},
1365     {"Certificate chain CA key", SSL_SECOP_CA_KEY},
1366     {"Peer Chain EE key", SSL_SECOP_PEER_EE_KEY},
1367     {"Peer Chain CA key", SSL_SECOP_PEER_CA_KEY},
1368     {"Certificate chain CA digest", SSL_SECOP_CA_MD},
1369     {"Peer chain CA digest", SSL_SECOP_PEER_CA_MD},
1370     {"SSL compression", SSL_SECOP_COMPRESSION},
1371     {"Session ticket", SSL_SECOP_TICKET},
1372     {NULL}
1373 };
1374
1375 static int security_callback_debug(const SSL *s, const SSL_CTX *ctx,
1376                                    int op, int bits, int nid,
1377                                    void *other, void *ex)
1378 {
1379     security_debug_ex *sdb = ex;
1380     int rv, show_bits = 1, cert_md = 0;
1381     const char *nm;
1382     int show_nm;
1383     rv = sdb->old_cb(s, ctx, op, bits, nid, other, ex);
1384     if (rv == 1 && sdb->verbose < 2)
1385         return 1;
1386     BIO_puts(sdb->out, "Security callback: ");
1387
1388     nm = lookup(op, callback_types, NULL);
1389     show_nm = nm != NULL;
1390     switch (op) {
1391     case SSL_SECOP_TICKET:
1392     case SSL_SECOP_COMPRESSION:
1393         show_bits = 0;
1394         show_nm = 0;
1395         break;
1396     case SSL_SECOP_VERSION:
1397         BIO_printf(sdb->out, "Version=%s", lookup(nid, ssl_versions, "???"));
1398         show_bits = 0;
1399         show_nm = 0;
1400         break;
1401     case SSL_SECOP_CA_MD:
1402     case SSL_SECOP_PEER_CA_MD:
1403         cert_md = 1;
1404         break;
1405     case SSL_SECOP_SIGALG_SUPPORTED:
1406     case SSL_SECOP_SIGALG_SHARED:
1407     case SSL_SECOP_SIGALG_CHECK:
1408     case SSL_SECOP_SIGALG_MASK:
1409         show_nm = 0;
1410         break;
1411     }
1412     if (show_nm)
1413         BIO_printf(sdb->out, "%s=", nm);
1414
1415     switch (op & SSL_SECOP_OTHER_TYPE) {
1416
1417     case SSL_SECOP_OTHER_CIPHER:
1418         BIO_puts(sdb->out, SSL_CIPHER_get_name(other));
1419         break;
1420
1421 #ifndef OPENSSL_NO_EC
1422     case SSL_SECOP_OTHER_CURVE:
1423         {
1424             const char *cname;
1425             cname = EC_curve_nid2nist(nid);
1426             if (cname == NULL)
1427                 cname = OBJ_nid2sn(nid);
1428             BIO_puts(sdb->out, cname);
1429         }
1430         break;
1431 #endif
1432 #ifndef OPENSSL_NO_DH
1433     case SSL_SECOP_OTHER_DH:
1434         {
1435             DH *dh = other;
1436             BIO_printf(sdb->out, "%d", DH_bits(dh));
1437             break;
1438         }
1439 #endif
1440     case SSL_SECOP_OTHER_CERT:
1441         {
1442             if (cert_md) {
1443                 int sig_nid = X509_get_signature_nid(other);
1444                 BIO_puts(sdb->out, OBJ_nid2sn(sig_nid));
1445             } else {
1446                 EVP_PKEY *pkey = X509_get0_pubkey(other);
1447                 const char *algname = "";
1448                 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL,
1449                                         &algname, EVP_PKEY_get0_asn1(pkey));
1450                 BIO_printf(sdb->out, "%s, bits=%d",
1451                            algname, EVP_PKEY_bits(pkey));
1452             }
1453             break;
1454         }
1455     case SSL_SECOP_OTHER_SIGALG:
1456         {
1457             const unsigned char *salg = other;
1458             const char *sname = NULL;
1459             int raw_sig_code = (salg[0] << 8) + salg[1]; /* always big endian (msb, lsb) */
1460                 /* raw_sig_code: signature_scheme from tls1.3, or signature_and_hash from tls1.2 */
1461
1462             if (nm != NULL)
1463                 BIO_printf(sdb->out, "%s", nm);
1464             else
1465                 BIO_printf(sdb->out, "s_cb.c:security_callback_debug op=0x%x", op);
1466
1467             sname = lookup(raw_sig_code, signature_tls13_scheme_list, NULL);
1468             if (sname != NULL) {
1469                 BIO_printf(sdb->out, " scheme=%s", sname);
1470             } else {
1471                 int alg_code = salg[1];
1472                 int hash_code = salg[0];
1473                 const char *alg_str = lookup(alg_code, signature_tls12_alg_list, NULL);
1474                 const char *hash_str = lookup(hash_code, signature_tls12_hash_list, NULL);
1475
1476                 if (alg_str != NULL && hash_str != NULL)
1477                     BIO_printf(sdb->out, " digest=%s, algorithm=%s", hash_str, alg_str);
1478                 else
1479                     BIO_printf(sdb->out, " scheme=unknown(0x%04x)", raw_sig_code);
1480             }
1481         }
1482
1483     }
1484
1485     if (show_bits)
1486         BIO_printf(sdb->out, ", security bits=%d", bits);
1487     BIO_printf(sdb->out, ": %s\n", rv ? "yes" : "no");
1488     return rv;
1489 }
1490
1491 void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose)
1492 {
1493     static security_debug_ex sdb;
1494
1495     sdb.out = bio_err;
1496     sdb.verbose = verbose;
1497     sdb.old_cb = SSL_CTX_get_security_callback(ctx);
1498     SSL_CTX_set_security_callback(ctx, security_callback_debug);
1499     SSL_CTX_set0_security_ex_data(ctx, &sdb);
1500 }
1501
1502 static void keylog_callback(const SSL *ssl, const char *line)
1503 {
1504     if (bio_keylog == NULL) {
1505         BIO_printf(bio_err, "Keylog callback is invoked without valid file!\n");
1506         return;
1507     }
1508
1509     /*
1510      * There might be concurrent writers to the keylog file, so we must ensure
1511      * that the given line is written at once.
1512      */
1513     BIO_printf(bio_keylog, "%s\n", line);
1514     (void)BIO_flush(bio_keylog);
1515 }
1516
1517 int set_keylog_file(SSL_CTX *ctx, const char *keylog_file)
1518 {
1519     /* Close any open files */
1520     BIO_free_all(bio_keylog);
1521     bio_keylog = NULL;
1522
1523     if (ctx == NULL || keylog_file == NULL) {
1524         /* Keylogging is disabled, OK. */
1525         return 0;
1526     }
1527
1528     /*
1529      * Append rather than write in order to allow concurrent modification.
1530      * Furthermore, this preserves existing keylog files which is useful when
1531      * the tool is run multiple times.
1532      */
1533     bio_keylog = BIO_new_file(keylog_file, "a");
1534     if (bio_keylog == NULL) {
1535         BIO_printf(bio_err, "Error writing keylog file %s\n", keylog_file);
1536         return 1;
1537     }
1538
1539     /* Write a header for seekable, empty files (this excludes pipes). */
1540     if (BIO_tell(bio_keylog) == 0) {
1541         BIO_puts(bio_keylog,
1542                  "# SSL/TLS secrets log file, generated by OpenSSL\n");
1543         (void)BIO_flush(bio_keylog);
1544     }
1545     SSL_CTX_set_keylog_callback(ctx, keylog_callback);
1546     return 0;
1547 }
1548
1549 void print_ca_names(BIO *bio, SSL *s)
1550 {
1551     const char *cs = SSL_is_server(s) ? "server" : "client";
1552     const STACK_OF(X509_NAME) *sk = SSL_get0_peer_CA_list(s);
1553     int i;
1554
1555     if (sk == NULL || sk_X509_NAME_num(sk) == 0) {
1556         if (!SSL_is_server(s))
1557             BIO_printf(bio, "---\nNo %s certificate CA names sent\n", cs);
1558         return;
1559     }
1560
1561     BIO_printf(bio, "---\nAcceptable %s certificate CA names\n",cs);
1562     for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1563         X509_NAME_print_ex(bio, sk_X509_NAME_value(sk, i), 0, get_nameopt());
1564         BIO_write(bio, "\n", 1);
1565     }
1566 }