xref: /freebsd/crypto/openssl/apps/lib/s_cb.c (revision 9b04aee86ccd58a6f3c936e0cd95bb9305a69848)
1 /*
2  * Copyright 1995-2024 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 const 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     {"early_data", TLSEXT_TYPE_early_data},
692     {NULL}
693 };
694 
695 /* from rfc8446 4.2.3. + gost (https://tools.ietf.org/id/draft-smyshlyaev-tls12-gost-suites-04.html) */
696 static STRINT_PAIR signature_tls13_scheme_list[] = {
697     {"rsa_pkcs1_sha1",         0x0201 /* TLSEXT_SIGALG_rsa_pkcs1_sha1 */},
698     {"ecdsa_sha1",             0x0203 /* TLSEXT_SIGALG_ecdsa_sha1 */},
699 /*  {"rsa_pkcs1_sha224",       0x0301    TLSEXT_SIGALG_rsa_pkcs1_sha224}, not in rfc8446 */
700 /*  {"ecdsa_sha224",           0x0303    TLSEXT_SIGALG_ecdsa_sha224}      not in rfc8446 */
701     {"rsa_pkcs1_sha256",       0x0401 /* TLSEXT_SIGALG_rsa_pkcs1_sha256 */},
702     {"ecdsa_secp256r1_sha256", 0x0403 /* TLSEXT_SIGALG_ecdsa_secp256r1_sha256 */},
703     {"rsa_pkcs1_sha384",       0x0501 /* TLSEXT_SIGALG_rsa_pkcs1_sha384 */},
704     {"ecdsa_secp384r1_sha384", 0x0503 /* TLSEXT_SIGALG_ecdsa_secp384r1_sha384 */},
705     {"rsa_pkcs1_sha512",       0x0601 /* TLSEXT_SIGALG_rsa_pkcs1_sha512 */},
706     {"ecdsa_secp521r1_sha512", 0x0603 /* TLSEXT_SIGALG_ecdsa_secp521r1_sha512 */},
707     {"rsa_pss_rsae_sha256",    0x0804 /* TLSEXT_SIGALG_rsa_pss_rsae_sha256 */},
708     {"rsa_pss_rsae_sha384",    0x0805 /* TLSEXT_SIGALG_rsa_pss_rsae_sha384 */},
709     {"rsa_pss_rsae_sha512",    0x0806 /* TLSEXT_SIGALG_rsa_pss_rsae_sha512 */},
710     {"ed25519",                0x0807 /* TLSEXT_SIGALG_ed25519 */},
711     {"ed448",                  0x0808 /* TLSEXT_SIGALG_ed448 */},
712     {"rsa_pss_pss_sha256",     0x0809 /* TLSEXT_SIGALG_rsa_pss_pss_sha256 */},
713     {"rsa_pss_pss_sha384",     0x080a /* TLSEXT_SIGALG_rsa_pss_pss_sha384 */},
714     {"rsa_pss_pss_sha512",     0x080b /* TLSEXT_SIGALG_rsa_pss_pss_sha512 */},
715     {"gostr34102001",          0xeded /* TLSEXT_SIGALG_gostr34102001_gostr3411 */},
716     {"gostr34102012_256",      0xeeee /* TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256 */},
717     {"gostr34102012_512",      0xefef /* TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512 */},
718     {NULL}
719 };
720 
721 /* from rfc5246 7.4.1.4.1. */
722 static STRINT_PAIR signature_tls12_alg_list[] = {
723     {"anonymous", TLSEXT_signature_anonymous /* 0 */},
724     {"RSA",       TLSEXT_signature_rsa       /* 1 */},
725     {"DSA",       TLSEXT_signature_dsa       /* 2 */},
726     {"ECDSA",     TLSEXT_signature_ecdsa     /* 3 */},
727     {NULL}
728 };
729 
730 /* from rfc5246 7.4.1.4.1. */
731 static STRINT_PAIR signature_tls12_hash_list[] = {
732     {"none",   TLSEXT_hash_none   /* 0 */},
733     {"MD5",    TLSEXT_hash_md5    /* 1 */},
734     {"SHA1",   TLSEXT_hash_sha1   /* 2 */},
735     {"SHA224", TLSEXT_hash_sha224 /* 3 */},
736     {"SHA256", TLSEXT_hash_sha256 /* 4 */},
737     {"SHA384", TLSEXT_hash_sha384 /* 5 */},
738     {"SHA512", TLSEXT_hash_sha512 /* 6 */},
739     {NULL}
740 };
741 
742 void tlsext_cb(SSL *s, int client_server, int type,
743                const unsigned char *data, int len, void *arg)
744 {
745     BIO *bio = arg;
746     const char *extname = lookup(type, tlsext_types, "unknown");
747 
748     BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
749                client_server ? "server" : "client", extname, type, len);
750     BIO_dump(bio, (const char *)data, len);
751     (void)BIO_flush(bio);
752 }
753 
754 #ifndef OPENSSL_NO_SOCK
755 int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
756                                        size_t *cookie_len)
757 {
758     unsigned char *buffer = NULL;
759     size_t length = 0;
760     unsigned short port;
761     BIO_ADDR *lpeer = NULL, *peer = NULL;
762     int res = 0;
763 
764     /* Initialize a random secret */
765     if (!cookie_initialized) {
766         if (RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH) <= 0) {
767             BIO_printf(bio_err, "error setting random cookie secret\n");
768             return 0;
769         }
770         cookie_initialized = 1;
771     }
772 
773     if (SSL_is_dtls(ssl)) {
774         lpeer = peer = BIO_ADDR_new();
775         if (peer == NULL) {
776             BIO_printf(bio_err, "memory full\n");
777             return 0;
778         }
779 
780         /* Read peer information */
781         (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), peer);
782     } else {
783         peer = ourpeer;
784     }
785 
786     /* Create buffer with peer's address and port */
787     if (!BIO_ADDR_rawaddress(peer, NULL, &length)) {
788         BIO_printf(bio_err, "Failed getting peer address\n");
789         BIO_ADDR_free(lpeer);
790         return 0;
791     }
792     OPENSSL_assert(length != 0);
793     port = BIO_ADDR_rawport(peer);
794     length += sizeof(port);
795     buffer = app_malloc(length, "cookie generate buffer");
796 
797     memcpy(buffer, &port, sizeof(port));
798     BIO_ADDR_rawaddress(peer, buffer + sizeof(port), NULL);
799 
800     if (EVP_Q_mac(NULL, "HMAC", NULL, "SHA1", NULL,
801                   cookie_secret, COOKIE_SECRET_LENGTH, buffer, length,
802                   cookie, DTLS1_COOKIE_LENGTH, cookie_len) == NULL) {
803         BIO_printf(bio_err,
804                    "Error calculating HMAC-SHA1 of buffer with secret\n");
805         goto end;
806     }
807     res = 1;
808 end:
809     OPENSSL_free(buffer);
810     BIO_ADDR_free(lpeer);
811 
812     return res;
813 }
814 
815 int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
816                                      size_t cookie_len)
817 {
818     unsigned char result[EVP_MAX_MD_SIZE];
819     size_t resultlength;
820 
821     /* Note: we check cookie_initialized because if it's not,
822      * it cannot be valid */
823     if (cookie_initialized
824         && generate_stateless_cookie_callback(ssl, result, &resultlength)
825         && cookie_len == resultlength
826         && memcmp(result, cookie, resultlength) == 0)
827         return 1;
828 
829     return 0;
830 }
831 
832 int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
833                              unsigned int *cookie_len)
834 {
835     size_t temp = 0;
836     int res = generate_stateless_cookie_callback(ssl, cookie, &temp);
837 
838     if (res != 0)
839         *cookie_len = (unsigned int)temp;
840     return res;
841 }
842 
843 int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
844                            unsigned int cookie_len)
845 {
846     return verify_stateless_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 
911     if (retry_cnt < 5) {
912         retry_cnt++;
913         BIO_printf(bio_err,
914                    "Certificate callback retry test: count %d\n",
915                    retry_cnt);
916         return -1;
917     }
918 #endif
919     SSL_certs_clear(ssl);
920 
921     if (exc == NULL)
922         return 1;
923 
924     /*
925      * Go to end of list and traverse backwards since we prepend newer
926      * entries this retains the original order.
927      */
928     while (exc->next != NULL)
929         exc = exc->next;
930 
931     i = 0;
932 
933     while (exc != NULL) {
934         i++;
935         rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain);
936         BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i);
937         X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0,
938                            get_nameopt());
939         BIO_puts(bio_err, "\n");
940         print_chain_flags(ssl, rv);
941         if (rv & CERT_PKEY_VALID) {
942             if (!SSL_use_certificate(ssl, exc->cert)
943                     || !SSL_use_PrivateKey(ssl, exc->key)) {
944                 return 0;
945             }
946             /*
947              * NB: we wouldn't normally do this as it is not efficient
948              * building chains on each connection better to cache the chain
949              * in advance.
950              */
951             if (exc->build_chain) {
952                 if (!SSL_build_cert_chain(ssl, 0))
953                     return 0;
954             } else if (exc->chain != NULL) {
955                 if (!SSL_set1_chain(ssl, exc->chain))
956                     return 0;
957             }
958         }
959         exc = exc->prev;
960     }
961     return 1;
962 }
963 
964 void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc)
965 {
966     SSL_CTX_set_cert_cb(ctx, set_cert_cb, exc);
967 }
968 
969 static int ssl_excert_prepend(SSL_EXCERT **pexc)
970 {
971     SSL_EXCERT *exc = app_malloc(sizeof(*exc), "prepend cert");
972 
973     memset(exc, 0, sizeof(*exc));
974 
975     exc->next = *pexc;
976     *pexc = exc;
977 
978     if (exc->next) {
979         exc->certform = exc->next->certform;
980         exc->keyform = exc->next->keyform;
981         exc->next->prev = exc;
982     } else {
983         exc->certform = FORMAT_PEM;
984         exc->keyform = FORMAT_PEM;
985     }
986     return 1;
987 
988 }
989 
990 void ssl_excert_free(SSL_EXCERT *exc)
991 {
992     SSL_EXCERT *curr;
993 
994     if (exc == NULL)
995         return;
996     while (exc) {
997         X509_free(exc->cert);
998         EVP_PKEY_free(exc->key);
999         sk_X509_pop_free(exc->chain, X509_free);
1000         curr = exc;
1001         exc = exc->next;
1002         OPENSSL_free(curr);
1003     }
1004 }
1005 
1006 int load_excert(SSL_EXCERT **pexc)
1007 {
1008     SSL_EXCERT *exc = *pexc;
1009 
1010     if (exc == NULL)
1011         return 1;
1012     /* If nothing in list, free and set to NULL */
1013     if (exc->certfile == NULL && exc->next == NULL) {
1014         ssl_excert_free(exc);
1015         *pexc = NULL;
1016         return 1;
1017     }
1018     for (; exc; exc = exc->next) {
1019         if (exc->certfile == NULL) {
1020             BIO_printf(bio_err, "Missing filename\n");
1021             return 0;
1022         }
1023         exc->cert = load_cert(exc->certfile, exc->certform,
1024                               "Server Certificate");
1025         if (exc->cert == NULL)
1026             return 0;
1027         if (exc->keyfile != NULL) {
1028             exc->key = load_key(exc->keyfile, exc->keyform,
1029                                 0, NULL, NULL, "server key");
1030         } else {
1031             exc->key = load_key(exc->certfile, exc->certform,
1032                                 0, NULL, NULL, "server key");
1033         }
1034         if (exc->key == NULL)
1035             return 0;
1036         if (exc->chainfile != NULL) {
1037             if (!load_certs(exc->chainfile, 0, &exc->chain, NULL, "server chain"))
1038                 return 0;
1039         }
1040     }
1041     return 1;
1042 }
1043 
1044 enum range { OPT_X_ENUM };
1045 
1046 int args_excert(int opt, SSL_EXCERT **pexc)
1047 {
1048     SSL_EXCERT *exc = *pexc;
1049 
1050     assert(opt > OPT_X__FIRST);
1051     assert(opt < OPT_X__LAST);
1052 
1053     if (exc == NULL) {
1054         if (!ssl_excert_prepend(&exc)) {
1055             BIO_printf(bio_err, " %s: Error initialising xcert\n",
1056                        opt_getprog());
1057             goto err;
1058         }
1059         *pexc = exc;
1060     }
1061 
1062     switch ((enum range)opt) {
1063     case OPT_X__FIRST:
1064     case OPT_X__LAST:
1065         return 0;
1066     case OPT_X_CERT:
1067         if (exc->certfile != NULL && !ssl_excert_prepend(&exc)) {
1068             BIO_printf(bio_err, "%s: Error adding xcert\n", opt_getprog());
1069             goto err;
1070         }
1071         *pexc = exc;
1072         exc->certfile = opt_arg();
1073         break;
1074     case OPT_X_KEY:
1075         if (exc->keyfile != NULL) {
1076             BIO_printf(bio_err, "%s: Key already specified\n", opt_getprog());
1077             goto err;
1078         }
1079         exc->keyfile = opt_arg();
1080         break;
1081     case OPT_X_CHAIN:
1082         if (exc->chainfile != NULL) {
1083             BIO_printf(bio_err, "%s: Chain already specified\n",
1084                        opt_getprog());
1085             goto err;
1086         }
1087         exc->chainfile = opt_arg();
1088         break;
1089     case OPT_X_CHAIN_BUILD:
1090         exc->build_chain = 1;
1091         break;
1092     case OPT_X_CERTFORM:
1093         if (!opt_format(opt_arg(), OPT_FMT_ANY, &exc->certform))
1094             return 0;
1095         break;
1096     case OPT_X_KEYFORM:
1097         if (!opt_format(opt_arg(), OPT_FMT_ANY, &exc->keyform))
1098             return 0;
1099         break;
1100     }
1101     return 1;
1102 
1103  err:
1104     ERR_print_errors(bio_err);
1105     ssl_excert_free(exc);
1106     *pexc = NULL;
1107     return 0;
1108 }
1109 
1110 static void print_raw_cipherlist(SSL *s)
1111 {
1112     const unsigned char *rlist;
1113     static const unsigned char scsv_id[] = { 0, 0xFF };
1114     size_t i, rlistlen, num;
1115 
1116     if (!SSL_is_server(s))
1117         return;
1118     num = SSL_get0_raw_cipherlist(s, NULL);
1119     OPENSSL_assert(num == 2);
1120     rlistlen = SSL_get0_raw_cipherlist(s, &rlist);
1121     BIO_puts(bio_err, "Client cipher list: ");
1122     for (i = 0; i < rlistlen; i += num, rlist += num) {
1123         const SSL_CIPHER *c = SSL_CIPHER_find(s, rlist);
1124         if (i)
1125             BIO_puts(bio_err, ":");
1126         if (c != NULL) {
1127             BIO_puts(bio_err, SSL_CIPHER_get_name(c));
1128         } else if (memcmp(rlist, scsv_id, num) == 0) {
1129             BIO_puts(bio_err, "SCSV");
1130         } else {
1131             size_t j;
1132             BIO_puts(bio_err, "0x");
1133             for (j = 0; j < num; j++)
1134                 BIO_printf(bio_err, "%02X", rlist[j]);
1135         }
1136     }
1137     BIO_puts(bio_err, "\n");
1138 }
1139 
1140 /*
1141  * Hex encoder for TLSA RRdata, not ':' delimited.
1142  */
1143 static char *hexencode(const unsigned char *data, size_t len)
1144 {
1145     static const char *hex = "0123456789abcdef";
1146     char *out;
1147     char *cp;
1148     size_t outlen = 2 * len + 1;
1149     int ilen = (int) outlen;
1150 
1151     if (outlen < len || ilen < 0 || outlen != (size_t)ilen) {
1152         BIO_printf(bio_err, "%s: %zu-byte buffer too large to hexencode\n",
1153                    opt_getprog(), len);
1154         exit(1);
1155     }
1156     cp = out = app_malloc(ilen, "TLSA hex data buffer");
1157 
1158     while (len-- > 0) {
1159         *cp++ = hex[(*data >> 4) & 0x0f];
1160         *cp++ = hex[*data++ & 0x0f];
1161     }
1162     *cp = '\0';
1163     return out;
1164 }
1165 
1166 void print_verify_detail(SSL *s, BIO *bio)
1167 {
1168     int mdpth;
1169     EVP_PKEY *mspki;
1170     long verify_err = SSL_get_verify_result(s);
1171 
1172     if (verify_err == X509_V_OK) {
1173         const char *peername = SSL_get0_peername(s);
1174 
1175         BIO_printf(bio, "Verification: OK\n");
1176         if (peername != NULL)
1177             BIO_printf(bio, "Verified peername: %s\n", peername);
1178     } else {
1179         const char *reason = X509_verify_cert_error_string(verify_err);
1180 
1181         BIO_printf(bio, "Verification error: %s\n", reason);
1182     }
1183 
1184     if ((mdpth = SSL_get0_dane_authority(s, NULL, &mspki)) >= 0) {
1185         uint8_t usage, selector, mtype;
1186         const unsigned char *data = NULL;
1187         size_t dlen = 0;
1188         char *hexdata;
1189 
1190         mdpth = SSL_get0_dane_tlsa(s, &usage, &selector, &mtype, &data, &dlen);
1191 
1192         /*
1193          * The TLSA data field can be quite long when it is a certificate,
1194          * public key or even a SHA2-512 digest.  Because the initial octets of
1195          * ASN.1 certificates and public keys contain mostly boilerplate OIDs
1196          * and lengths, we show the last 12 bytes of the data instead, as these
1197          * are more likely to distinguish distinct TLSA records.
1198          */
1199 #define TLSA_TAIL_SIZE 12
1200         if (dlen > TLSA_TAIL_SIZE)
1201             hexdata = hexencode(data + dlen - TLSA_TAIL_SIZE, TLSA_TAIL_SIZE);
1202         else
1203             hexdata = hexencode(data, dlen);
1204         BIO_printf(bio, "DANE TLSA %d %d %d %s%s %s at depth %d\n",
1205                    usage, selector, mtype,
1206                    (dlen > TLSA_TAIL_SIZE) ? "..." : "", hexdata,
1207                    (mspki != NULL) ? "signed the certificate" :
1208                    mdpth ? "matched TA certificate" : "matched EE certificate",
1209                    mdpth);
1210         OPENSSL_free(hexdata);
1211     }
1212 }
1213 
1214 void print_ssl_summary(SSL *s)
1215 {
1216     const SSL_CIPHER *c;
1217     X509 *peer;
1218 
1219     BIO_printf(bio_err, "Protocol version: %s\n", SSL_get_version(s));
1220     print_raw_cipherlist(s);
1221     c = SSL_get_current_cipher(s);
1222     BIO_printf(bio_err, "Ciphersuite: %s\n", SSL_CIPHER_get_name(c));
1223     do_print_sigalgs(bio_err, s, 0);
1224     peer = SSL_get0_peer_certificate(s);
1225     if (peer != NULL) {
1226         int nid;
1227 
1228         BIO_puts(bio_err, "Peer certificate: ");
1229         X509_NAME_print_ex(bio_err, X509_get_subject_name(peer),
1230                            0, get_nameopt());
1231         BIO_puts(bio_err, "\n");
1232         if (SSL_get_peer_signature_nid(s, &nid))
1233             BIO_printf(bio_err, "Hash used: %s\n", OBJ_nid2sn(nid));
1234         if (SSL_get_peer_signature_type_nid(s, &nid))
1235             BIO_printf(bio_err, "Signature type: %s\n", get_sigtype(nid));
1236         print_verify_detail(s, bio_err);
1237     } else {
1238         BIO_puts(bio_err, "No peer certificate\n");
1239     }
1240 #ifndef OPENSSL_NO_EC
1241     ssl_print_point_formats(bio_err, s);
1242     if (SSL_is_server(s))
1243         ssl_print_groups(bio_err, s, 1);
1244     else
1245         ssl_print_tmp_key(bio_err, s);
1246 #else
1247     if (!SSL_is_server(s))
1248         ssl_print_tmp_key(bio_err, s);
1249 #endif
1250 }
1251 
1252 int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str,
1253                SSL_CTX *ctx)
1254 {
1255     int i;
1256 
1257     SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
1258     for (i = 0; i < sk_OPENSSL_STRING_num(str); i += 2) {
1259         const char *flag = sk_OPENSSL_STRING_value(str, i);
1260         const char *arg = sk_OPENSSL_STRING_value(str, i + 1);
1261 
1262         if (SSL_CONF_cmd(cctx, flag, arg) <= 0) {
1263             BIO_printf(bio_err, "Call to SSL_CONF_cmd(%s, %s) failed\n",
1264                        flag, arg == NULL ? "<NULL>" : arg);
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, ret = 1;
1281 
1282     for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1283         crl = sk_X509_CRL_value(crls, i);
1284         if (!X509_STORE_add_crl(st, crl))
1285             ret = 0;
1286     }
1287     return ret;
1288 }
1289 
1290 int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls, int crl_download)
1291 {
1292     X509_STORE *st;
1293 
1294     st = SSL_CTX_get_cert_store(ctx);
1295     add_crls_store(st, crls);
1296     if (crl_download)
1297         store_setup_crl_download(st);
1298     return 1;
1299 }
1300 
1301 int ssl_load_stores(SSL_CTX *ctx,
1302                     const char *vfyCApath, const char *vfyCAfile,
1303                     const char *vfyCAstore,
1304                     const char *chCApath, const char *chCAfile,
1305                     const char *chCAstore,
1306                     STACK_OF(X509_CRL) *crls, int crl_download)
1307 {
1308     X509_STORE *vfy = NULL, *ch = NULL;
1309     int rv = 0;
1310 
1311     if (vfyCApath != NULL || vfyCAfile != NULL || vfyCAstore != NULL) {
1312         vfy = X509_STORE_new();
1313         if (vfy == NULL)
1314             goto err;
1315         if (vfyCAfile != NULL && !X509_STORE_load_file(vfy, vfyCAfile))
1316             goto err;
1317         if (vfyCApath != NULL && !X509_STORE_load_path(vfy, vfyCApath))
1318             goto err;
1319         if (vfyCAstore != NULL && !X509_STORE_load_store(vfy, vfyCAstore))
1320             goto err;
1321         add_crls_store(vfy, crls);
1322         if (SSL_CTX_set1_verify_cert_store(ctx, vfy) == 0)
1323             goto err;
1324         if (crl_download)
1325             store_setup_crl_download(vfy);
1326     }
1327     if (chCApath != NULL || chCAfile != NULL || chCAstore != NULL) {
1328         ch = X509_STORE_new();
1329         if (ch == NULL)
1330             goto err;
1331         if (chCAfile != NULL && !X509_STORE_load_file(ch, chCAfile))
1332             goto err;
1333         if (chCApath != NULL && !X509_STORE_load_path(ch, chCApath))
1334             goto err;
1335         if (chCAstore != NULL && !X509_STORE_load_store(ch, chCAstore))
1336             goto err;
1337         if (SSL_CTX_set1_chain_cert_store(ctx, ch) == 0)
1338             goto err;
1339     }
1340     rv = 1;
1341  err:
1342     X509_STORE_free(vfy);
1343     X509_STORE_free(ch);
1344     return rv;
1345 }
1346 
1347 /* Verbose print out of security callback */
1348 
1349 typedef struct {
1350     BIO *out;
1351     int verbose;
1352     int (*old_cb) (const SSL *s, const SSL_CTX *ctx, int op, int bits, int nid,
1353                    void *other, void *ex);
1354 } security_debug_ex;
1355 
1356 static STRINT_PAIR callback_types[] = {
1357     {"Supported Ciphersuite", SSL_SECOP_CIPHER_SUPPORTED},
1358     {"Shared Ciphersuite", SSL_SECOP_CIPHER_SHARED},
1359     {"Check Ciphersuite", SSL_SECOP_CIPHER_CHECK},
1360 #ifndef OPENSSL_NO_DH
1361     {"Temp DH key bits", SSL_SECOP_TMP_DH},
1362 #endif
1363     {"Supported Curve", SSL_SECOP_CURVE_SUPPORTED},
1364     {"Shared Curve", SSL_SECOP_CURVE_SHARED},
1365     {"Check Curve", SSL_SECOP_CURVE_CHECK},
1366     {"Supported Signature Algorithm", SSL_SECOP_SIGALG_SUPPORTED},
1367     {"Shared Signature Algorithm", SSL_SECOP_SIGALG_SHARED},
1368     {"Check Signature Algorithm", SSL_SECOP_SIGALG_CHECK},
1369     {"Signature Algorithm mask", SSL_SECOP_SIGALG_MASK},
1370     {"Certificate chain EE key", SSL_SECOP_EE_KEY},
1371     {"Certificate chain CA key", SSL_SECOP_CA_KEY},
1372     {"Peer Chain EE key", SSL_SECOP_PEER_EE_KEY},
1373     {"Peer Chain CA key", SSL_SECOP_PEER_CA_KEY},
1374     {"Certificate chain CA digest", SSL_SECOP_CA_MD},
1375     {"Peer chain CA digest", SSL_SECOP_PEER_CA_MD},
1376     {"SSL compression", SSL_SECOP_COMPRESSION},
1377     {"Session ticket", SSL_SECOP_TICKET},
1378     {NULL}
1379 };
1380 
1381 static int security_callback_debug(const SSL *s, const SSL_CTX *ctx,
1382                                    int op, int bits, int nid,
1383                                    void *other, void *ex)
1384 {
1385     security_debug_ex *sdb = ex;
1386     int rv, show_bits = 1, cert_md = 0;
1387     const char *nm;
1388     int show_nm;
1389 
1390     rv = sdb->old_cb(s, ctx, op, bits, nid, other, ex);
1391     if (rv == 1 && sdb->verbose < 2)
1392         return 1;
1393     BIO_puts(sdb->out, "Security callback: ");
1394 
1395     nm = lookup(op, callback_types, NULL);
1396     show_nm = nm != NULL;
1397     switch (op) {
1398     case SSL_SECOP_TICKET:
1399     case SSL_SECOP_COMPRESSION:
1400         show_bits = 0;
1401         show_nm = 0;
1402         break;
1403     case SSL_SECOP_VERSION:
1404         BIO_printf(sdb->out, "Version=%s", lookup(nid, ssl_versions, "???"));
1405         show_bits = 0;
1406         show_nm = 0;
1407         break;
1408     case SSL_SECOP_CA_MD:
1409     case SSL_SECOP_PEER_CA_MD:
1410         cert_md = 1;
1411         break;
1412     case SSL_SECOP_SIGALG_SUPPORTED:
1413     case SSL_SECOP_SIGALG_SHARED:
1414     case SSL_SECOP_SIGALG_CHECK:
1415     case SSL_SECOP_SIGALG_MASK:
1416         show_nm = 0;
1417         break;
1418     }
1419     if (show_nm)
1420         BIO_printf(sdb->out, "%s=", nm);
1421 
1422     switch (op & SSL_SECOP_OTHER_TYPE) {
1423 
1424     case SSL_SECOP_OTHER_CIPHER:
1425         BIO_puts(sdb->out, SSL_CIPHER_get_name(other));
1426         break;
1427 
1428 #ifndef OPENSSL_NO_EC
1429     case SSL_SECOP_OTHER_CURVE:
1430         {
1431             const char *cname;
1432             cname = EC_curve_nid2nist(nid);
1433             if (cname == NULL)
1434                 cname = OBJ_nid2sn(nid);
1435             BIO_puts(sdb->out, cname);
1436         }
1437         break;
1438 #endif
1439     case SSL_SECOP_OTHER_CERT:
1440         {
1441             if (cert_md) {
1442                 int sig_nid = X509_get_signature_nid(other);
1443 
1444                 BIO_puts(sdb->out, OBJ_nid2sn(sig_nid));
1445             } else {
1446                 EVP_PKEY *pkey = X509_get0_pubkey(other);
1447 
1448                 if (pkey == NULL) {
1449                     BIO_printf(sdb->out, "Public key missing");
1450                 } else {
1451                     const char *algname = "";
1452 
1453                     EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL,
1454                                             &algname, EVP_PKEY_get0_asn1(pkey));
1455                     BIO_printf(sdb->out, "%s, bits=%d",
1456                             algname, EVP_PKEY_get_bits(pkey));
1457                 }
1458             }
1459             break;
1460         }
1461     case SSL_SECOP_OTHER_SIGALG:
1462         {
1463             const unsigned char *salg = other;
1464             const char *sname = NULL;
1465             int raw_sig_code = (salg[0] << 8) + salg[1]; /* always big endian (msb, lsb) */
1466                 /* raw_sig_code: signature_scheme from tls1.3, or signature_and_hash from tls1.2 */
1467 
1468             if (nm != NULL)
1469                 BIO_printf(sdb->out, "%s", nm);
1470             else
1471                 BIO_printf(sdb->out, "s_cb.c:security_callback_debug op=0x%x", op);
1472 
1473             sname = lookup(raw_sig_code, signature_tls13_scheme_list, NULL);
1474             if (sname != NULL) {
1475                 BIO_printf(sdb->out, " scheme=%s", sname);
1476             } else {
1477                 int alg_code = salg[1];
1478                 int hash_code = salg[0];
1479                 const char *alg_str = lookup(alg_code, signature_tls12_alg_list, NULL);
1480                 const char *hash_str = lookup(hash_code, signature_tls12_hash_list, NULL);
1481 
1482                 if (alg_str != NULL && hash_str != NULL)
1483                     BIO_printf(sdb->out, " digest=%s, algorithm=%s", hash_str, alg_str);
1484                 else
1485                     BIO_printf(sdb->out, " scheme=unknown(0x%04x)", raw_sig_code);
1486             }
1487         }
1488 
1489     }
1490 
1491     if (show_bits)
1492         BIO_printf(sdb->out, ", security bits=%d", bits);
1493     BIO_printf(sdb->out, ": %s\n", rv ? "yes" : "no");
1494     return rv;
1495 }
1496 
1497 void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose)
1498 {
1499     static security_debug_ex sdb;
1500 
1501     sdb.out = bio_err;
1502     sdb.verbose = verbose;
1503     sdb.old_cb = SSL_CTX_get_security_callback(ctx);
1504     SSL_CTX_set_security_callback(ctx, security_callback_debug);
1505     SSL_CTX_set0_security_ex_data(ctx, &sdb);
1506 }
1507 
1508 static void keylog_callback(const SSL *ssl, const char *line)
1509 {
1510     if (bio_keylog == NULL) {
1511         BIO_printf(bio_err, "Keylog callback is invoked without valid file!\n");
1512         return;
1513     }
1514 
1515     /*
1516      * There might be concurrent writers to the keylog file, so we must ensure
1517      * that the given line is written at once.
1518      */
1519     BIO_printf(bio_keylog, "%s\n", line);
1520     (void)BIO_flush(bio_keylog);
1521 }
1522 
1523 int set_keylog_file(SSL_CTX *ctx, const char *keylog_file)
1524 {
1525     /* Close any open files */
1526     BIO_free_all(bio_keylog);
1527     bio_keylog = NULL;
1528 
1529     if (ctx == NULL || keylog_file == NULL) {
1530         /* Keylogging is disabled, OK. */
1531         return 0;
1532     }
1533 
1534     /*
1535      * Append rather than write in order to allow concurrent modification.
1536      * Furthermore, this preserves existing keylog files which is useful when
1537      * the tool is run multiple times.
1538      */
1539     bio_keylog = BIO_new_file(keylog_file, "a");
1540     if (bio_keylog == NULL) {
1541         BIO_printf(bio_err, "Error writing keylog file %s\n", keylog_file);
1542         return 1;
1543     }
1544 
1545     /* Write a header for seekable, empty files (this excludes pipes). */
1546     if (BIO_tell(bio_keylog) == 0) {
1547         BIO_puts(bio_keylog,
1548                  "# SSL/TLS secrets log file, generated by OpenSSL\n");
1549         (void)BIO_flush(bio_keylog);
1550     }
1551     SSL_CTX_set_keylog_callback(ctx, keylog_callback);
1552     return 0;
1553 }
1554 
1555 void print_ca_names(BIO *bio, SSL *s)
1556 {
1557     const char *cs = SSL_is_server(s) ? "server" : "client";
1558     const STACK_OF(X509_NAME) *sk = SSL_get0_peer_CA_list(s);
1559     int i;
1560 
1561     if (sk == NULL || sk_X509_NAME_num(sk) == 0) {
1562         if (!SSL_is_server(s))
1563             BIO_printf(bio, "---\nNo %s certificate CA names sent\n", cs);
1564         return;
1565     }
1566 
1567     BIO_printf(bio, "---\nAcceptable %s certificate CA names\n",cs);
1568     for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1569         X509_NAME_print_ex(bio, sk_X509_NAME_value(sk, i), 0, get_nameopt());
1570         BIO_write(bio, "\n", 1);
1571     }
1572 }
1573