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