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