xref: /freebsd/crypto/openssl/apps/lib/apps.c (revision 1523ccfd9c8c254f7928143d31c305384b05fd11)
1 /*
2  * Copyright 1995-2026 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 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
11 /*
12  * On VMS, you need to define this to get the declaration of fileno().  The
13  * value 2 is to make sure no function defined in POSIX-2 is left undefined.
14  */
15 #define _POSIX_C_SOURCE 2
16 #endif
17 
18 #ifndef OPENSSL_NO_ENGINE
19 /* We need to use some deprecated APIs */
20 #define OPENSSL_SUPPRESS_DEPRECATED
21 #include <openssl/engine.h>
22 #endif
23 
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/types.h>
28 #ifndef OPENSSL_NO_POSIX_IO
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #endif
32 #include <ctype.h>
33 #include <errno.h>
34 #include <openssl/err.h>
35 #include <openssl/x509.h>
36 #include <openssl/x509v3.h>
37 #include <openssl/http.h>
38 #include <openssl/pem.h>
39 #include <openssl/store.h>
40 #include <openssl/pkcs12.h>
41 #include <openssl/ui.h>
42 #include <openssl/safestack.h>
43 #include <openssl/rsa.h>
44 #include <openssl/rand.h>
45 #include <openssl/bn.h>
46 #include <openssl/ssl.h>
47 #include <openssl/core_names.h>
48 #include "s_apps.h"
49 #include "apps.h"
50 
51 #include "internal/sockets.h" /* for openssl_fdset() */
52 #include "internal/numbers.h" /* for LONG_MAX */
53 #include "internal/e_os.h"
54 
55 #ifdef _WIN32
56 static int WIN32_rename(const char *from, const char *to);
57 #define rename(from, to) WIN32_rename((from), (to))
58 #endif
59 
60 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
61 #include <conio.h>
62 #endif
63 
64 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) || defined(__BORLANDC__)
65 #define _kbhit kbhit
66 #endif
67 
68 static BIO *bio_open_default_(const char *filename, char mode, int format,
69     int quiet);
70 
71 #define PASS_SOURCE_SIZE_MAX 4
72 
73 DEFINE_STACK_OF(CONF)
74 
75 typedef struct {
76     const char *name;
77     unsigned long flag;
78     unsigned long mask;
79 } NAME_EX_TBL;
80 
81 static int set_table_opts(unsigned long *flags, const char *arg,
82     const NAME_EX_TBL *in_tbl);
83 static int set_multi_opts(unsigned long *flags, const char *arg,
84     const NAME_EX_TBL *in_tbl);
85 int app_init(long mesgwin);
86 
87 #ifndef APP_INIT
88 int app_init(long mesgwin)
89 {
90     return 1;
91 }
92 #endif
93 
94 int ctx_set_verify_locations(SSL_CTX *ctx,
95     const char *CAfile, int noCAfile,
96     const char *CApath, int noCApath,
97     const char *CAstore, int noCAstore)
98 {
99     if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
100         if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
101             return 0;
102         if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
103             return 0;
104         if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
105             return 0;
106 
107         return 1;
108     }
109 
110     if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
111         return 0;
112     if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
113         return 0;
114     if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
115         return 0;
116     return 1;
117 }
118 
119 #ifndef OPENSSL_NO_CT
120 
121 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
122 {
123     if (path == NULL)
124         return SSL_CTX_set_default_ctlog_list_file(ctx);
125 
126     return SSL_CTX_set_ctlog_list_file(ctx, path);
127 }
128 
129 #endif
130 
131 static unsigned long nmflag = 0;
132 static char nmflag_set = 0;
133 
134 int set_nameopt(const char *arg)
135 {
136     int ret = set_name_ex(&nmflag, arg);
137 
138     if (ret)
139         nmflag_set = 1;
140 
141     return ret;
142 }
143 
144 unsigned long get_nameopt(void)
145 {
146     return nmflag_set ? nmflag : XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_FN_SN | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_UTF8_CONVERT | ASN1_STRFLGS_DUMP_UNKNOWN | ASN1_STRFLGS_DUMP_DER;
147 }
148 
149 void dump_cert_text(BIO *out, X509 *x)
150 {
151     print_name(out, "subject=", X509_get_subject_name(x));
152     print_name(out, "issuer=", X509_get_issuer_name(x));
153 }
154 
155 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
156 {
157     return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
158 }
159 
160 static char *app_get_pass(const char *arg, int keepbio);
161 
162 char *get_passwd(const char *pass, const char *desc)
163 {
164     char *result = NULL;
165 
166     if (desc == NULL)
167         desc = "<unknown>";
168     if (!app_passwd(pass, NULL, &result, NULL))
169         BIO_printf(bio_err, "Error getting password for %s\n", desc);
170     if (pass != NULL && result == NULL) {
171         BIO_printf(bio_err,
172             "Trying plain input string (better precede with 'pass:')\n");
173         result = OPENSSL_strdup(pass);
174         if (result == NULL)
175             BIO_printf(bio_err,
176                 "Out of memory getting password for %s\n", desc);
177     }
178     return result;
179 }
180 
181 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
182 {
183     int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
184 
185     if (arg1 != NULL) {
186         *pass1 = app_get_pass(arg1, same);
187         if (*pass1 == NULL)
188             return 0;
189     } else if (pass1 != NULL) {
190         *pass1 = NULL;
191     }
192     if (arg2 != NULL) {
193         *pass2 = app_get_pass(arg2, same ? 2 : 0);
194         if (*pass2 == NULL) {
195             if (pass1 != NULL) {
196                 clear_free(*pass1);
197                 *pass1 = NULL;
198             }
199             return 0;
200         }
201     } else if (pass2 != NULL) {
202         *pass2 = NULL;
203     }
204     return 1;
205 }
206 
207 static char *app_get_pass(const char *arg, int keepbio)
208 {
209     static BIO *pwdbio = NULL;
210     char *tmp, tpass[APP_PASS_LEN];
211     int i;
212 
213     /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
214     if (CHECK_AND_SKIP_PREFIX(arg, "pass:"))
215         return OPENSSL_strdup(arg);
216     if (CHECK_AND_SKIP_PREFIX(arg, "env:")) {
217         tmp = getenv(arg);
218         if (tmp == NULL) {
219             BIO_printf(bio_err, "No environment variable %s\n", arg);
220             return NULL;
221         }
222         return OPENSSL_strdup(tmp);
223     }
224     if (!keepbio || pwdbio == NULL) {
225         if (CHECK_AND_SKIP_PREFIX(arg, "file:")) {
226             pwdbio = BIO_new_file(arg, "r");
227             if (pwdbio == NULL) {
228                 BIO_printf(bio_err, "Can't open file %s\n", arg);
229                 return NULL;
230             }
231 #if !defined(_WIN32)
232             /*
233              * Under _WIN32, which covers even Win64 and CE, file
234              * descriptors referenced by BIO_s_fd are not inherited
235              * by child process and therefore below is not an option.
236              * It could have been an option if bss_fd.c was operating
237              * on real Windows descriptors, such as those obtained
238              * with CreateFile.
239              */
240         } else if (CHECK_AND_SKIP_PREFIX(arg, "fd:")) {
241             BIO *btmp;
242 
243             i = atoi(arg);
244             if (i >= 0)
245                 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
246             if ((i < 0) || pwdbio == NULL) {
247                 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg);
248                 return NULL;
249             }
250             /*
251              * Can't do BIO_gets on an fd BIO so add a buffering BIO
252              */
253             btmp = BIO_new(BIO_f_buffer());
254             if (btmp == NULL) {
255                 BIO_free_all(pwdbio);
256                 pwdbio = NULL;
257                 BIO_printf(bio_err, "Out of memory\n");
258                 return NULL;
259             }
260             pwdbio = BIO_push(btmp, pwdbio);
261 #endif
262         } else if (strcmp(arg, "stdin") == 0) {
263             unbuffer(stdin);
264             pwdbio = dup_bio_in(FORMAT_TEXT);
265             if (pwdbio == NULL) {
266                 BIO_printf(bio_err, "Can't open BIO for stdin\n");
267                 return NULL;
268             }
269         } else {
270             /* argument syntax error; do not reveal too much about arg */
271             const char *arg_ptr = strchr(arg, ':');
272             if (arg_ptr == NULL || arg_ptr - arg > PASS_SOURCE_SIZE_MAX)
273                 BIO_printf(bio_err,
274                     "Invalid password argument, missing ':' within the first %d chars\n",
275                     PASS_SOURCE_SIZE_MAX + 1);
276             else
277                 BIO_printf(bio_err,
278                     "Invalid password argument, starting with \"%.*s\"\n",
279                     (int)(arg_ptr - arg + 1), arg);
280             return NULL;
281         }
282     }
283     i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
284     if (keepbio != 1) {
285         BIO_free_all(pwdbio);
286         pwdbio = NULL;
287     }
288     if (i <= 0) {
289         BIO_printf(bio_err, "Error reading password from BIO\n");
290         return NULL;
291     }
292     tmp = strchr(tpass, '\n');
293     if (tmp != NULL)
294         *tmp = 0;
295     return OPENSSL_strdup(tpass);
296 }
297 
298 char *app_conf_try_string(const CONF *conf, const char *group, const char *name)
299 {
300     char *res;
301 
302     ERR_set_mark();
303     res = NCONF_get_string(conf, group, name);
304     if (res == NULL)
305         ERR_pop_to_mark();
306     else
307         ERR_clear_last_mark();
308     return res;
309 }
310 
311 int app_conf_try_number(const CONF *conf, const char *group, const char *name,
312     long *result)
313 {
314     int ok;
315 
316     ERR_set_mark();
317     ok = NCONF_get_number(conf, group, name, result);
318     if (!ok)
319         ERR_pop_to_mark();
320     else
321         ERR_clear_last_mark();
322     return ok;
323 }
324 
325 CONF *app_load_config_bio(BIO *in, const char *filename)
326 {
327     long errorline = -1;
328     CONF *conf;
329     int i;
330 
331     conf = NCONF_new_ex(app_get0_libctx(), NULL);
332     i = NCONF_load_bio(conf, in, &errorline);
333     if (i > 0)
334         return conf;
335 
336     if (errorline <= 0) {
337         BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
338     } else {
339         BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
340             errorline);
341     }
342     if (filename != NULL)
343         BIO_printf(bio_err, "config file \"%s\"\n", filename);
344     else
345         BIO_printf(bio_err, "config input");
346 
347     NCONF_free(conf);
348     return NULL;
349 }
350 
351 CONF *app_load_config_verbose(const char *filename, int verbose)
352 {
353     if (verbose) {
354         if (*filename == '\0')
355             BIO_printf(bio_err, "No configuration used\n");
356         else
357             BIO_printf(bio_err, "Using configuration from %s\n", filename);
358     }
359     return app_load_config_internal(filename, 0);
360 }
361 
362 CONF *app_load_config_internal(const char *filename, int quiet)
363 {
364     BIO *in;
365     CONF *conf;
366 
367     if (filename == NULL || *filename != '\0') {
368         if ((in = bio_open_default_(filename, 'r', FORMAT_TEXT, quiet)) == NULL)
369             return NULL;
370         conf = app_load_config_bio(in, filename);
371         BIO_free(in);
372     } else {
373         /* Return empty config if filename is empty string. */
374         conf = NCONF_new_ex(app_get0_libctx(), NULL);
375     }
376     return conf;
377 }
378 
379 int app_load_modules(const CONF *config)
380 {
381     CONF *to_free = NULL;
382 
383     if (config == NULL)
384         config = to_free = app_load_config_quiet(default_config_file);
385     if (config == NULL)
386         return 1;
387 
388     if (CONF_modules_load(config, NULL, 0) <= 0) {
389         BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
390         ERR_print_errors(bio_err);
391         NCONF_free(to_free);
392         return 0;
393     }
394     NCONF_free(to_free);
395     return 1;
396 }
397 
398 int add_oid_section(CONF *conf)
399 {
400     char *p;
401     STACK_OF(CONF_VALUE) *sktmp;
402     CONF_VALUE *cnf;
403     int i;
404 
405     if ((p = app_conf_try_string(conf, NULL, "oid_section")) == NULL)
406         return 1;
407     if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
408         BIO_printf(bio_err, "problem loading oid section %s\n", p);
409         return 0;
410     }
411     for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
412         cnf = sk_CONF_VALUE_value(sktmp, i);
413         if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
414             BIO_printf(bio_err, "problem creating object %s=%s\n",
415                 cnf->name, cnf->value);
416             return 0;
417         }
418     }
419     return 1;
420 }
421 
422 CONF *app_load_config_modules(const char *configfile)
423 {
424     CONF *conf = NULL;
425 
426     if (configfile != NULL) {
427         if ((conf = app_load_config_verbose(configfile, 1)) == NULL)
428             return NULL;
429         if (configfile != default_config_file && !app_load_modules(conf)) {
430             NCONF_free(conf);
431             conf = NULL;
432         }
433     }
434     return conf;
435 }
436 
437 #define IS_HTTP(uri) ((uri) != NULL && HAS_PREFIX(uri, OSSL_HTTP_PREFIX))
438 #define IS_HTTPS(uri) ((uri) != NULL && HAS_PREFIX(uri, OSSL_HTTPS_PREFIX))
439 
440 X509 *load_cert_pass(const char *uri, int format, int maybe_stdin,
441     const char *pass, const char *desc)
442 {
443     X509 *cert = NULL;
444 
445     if (desc == NULL)
446         desc = "certificate";
447     if (IS_HTTPS(uri)) {
448         BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
449     } else if (IS_HTTP(uri)) {
450         cert = X509_load_http(uri, NULL, NULL, 0 /* timeout */);
451         if (cert == NULL) {
452             ERR_print_errors(bio_err);
453             BIO_printf(bio_err, "Unable to load %s from %s\n", desc, uri);
454         }
455     } else {
456         (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, 0,
457             NULL, NULL, NULL, &cert, NULL, NULL, NULL);
458     }
459     return cert;
460 }
461 
462 X509_CRL *load_crl(const char *uri, int format, int maybe_stdin,
463     const char *desc)
464 {
465     X509_CRL *crl = NULL;
466 
467     if (desc == NULL)
468         desc = "CRL";
469     if (IS_HTTPS(uri)) {
470         BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
471     } else if (IS_HTTP(uri)) {
472         crl = X509_CRL_load_http(uri, NULL, NULL, 0 /* timeout */);
473         if (crl == NULL) {
474             ERR_print_errors(bio_err);
475             BIO_printf(bio_err, "Unable to load %s from %s\n", desc, uri);
476         }
477     } else {
478         (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc, 0,
479             NULL, NULL, NULL, NULL, NULL, &crl, NULL);
480     }
481     return crl;
482 }
483 
484 /* Could be simplified if OSSL_STORE supported CSRs, see FR #15725 */
485 X509_REQ *load_csr(const char *file, int format, const char *desc)
486 {
487     X509_REQ *req = NULL;
488     BIO *in;
489 
490     if (format == FORMAT_UNDEF)
491         format = FORMAT_PEM;
492     in = bio_open_default(file, 'r', format);
493     if (in == NULL)
494         goto end;
495 
496     if (format == FORMAT_ASN1)
497         req = d2i_X509_REQ_bio(in, NULL);
498     else if (format == FORMAT_PEM)
499         req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
500     else
501         print_format_error(format, OPT_FMT_PEMDER);
502 
503 end:
504     if (req == NULL) {
505         ERR_print_errors(bio_err);
506         if (desc != NULL)
507             BIO_printf(bio_err, "Unable to load %s\n", desc);
508     }
509     BIO_free(in);
510     return req;
511 }
512 
513 /* Better extend OSSL_STORE to support CSRs, see FR #15725 */
514 X509_REQ *load_csr_autofmt(const char *infile, int format,
515     STACK_OF(OPENSSL_STRING) *vfyopts, const char *desc)
516 {
517     X509_REQ *csr;
518 
519     if (format != FORMAT_UNDEF) {
520         csr = load_csr(infile, format, desc);
521     } else { /* try PEM, then DER */
522         BIO *bio_bak = bio_err;
523 
524         bio_err = NULL; /* do not show errors on more than one try */
525         csr = load_csr(infile, FORMAT_PEM, NULL /* desc */);
526         bio_err = bio_bak;
527         if (csr == NULL) {
528             ERR_clear_error();
529             csr = load_csr(infile, FORMAT_ASN1, NULL /* desc */);
530         }
531         if (csr == NULL) {
532             BIO_printf(bio_err, "error: unable to load %s from file '%s'\n",
533                 desc, infile);
534         }
535     }
536     if (csr != NULL) {
537         EVP_PKEY *pkey = X509_REQ_get0_pubkey(csr);
538         int ret = do_X509_REQ_verify(csr, pkey, vfyopts);
539 
540         if (pkey == NULL || ret < 0)
541             BIO_puts(bio_err, "Warning: error while verifying CSR self-signature\n");
542         else if (ret == 0)
543             BIO_puts(bio_err, "Warning: CSR self-signature does not match the contents\n");
544         return csr;
545     }
546     return csr;
547 }
548 
549 void cleanse(char *str)
550 {
551     if (str != NULL)
552         OPENSSL_cleanse(str, strlen(str));
553 }
554 
555 void clear_free(char *str)
556 {
557     if (str != NULL)
558         OPENSSL_clear_free(str, strlen(str));
559 }
560 
561 EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
562     const char *pass, ENGINE *e, const char *desc)
563 {
564     EVP_PKEY *pkey = NULL;
565     char *allocated_uri = NULL;
566 
567     if (desc == NULL)
568         desc = "private key";
569 
570     if (format == FORMAT_ENGINE)
571         uri = allocated_uri = make_engine_uri(e, uri, desc);
572     (void)load_key_certs_crls(uri, format, may_stdin, pass, desc, 0,
573         &pkey, NULL, NULL, NULL, NULL, NULL, NULL);
574 
575     OPENSSL_free(allocated_uri);
576     return pkey;
577 }
578 
579 /* first try reading public key, on failure resort to loading private key */
580 EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
581     const char *pass, ENGINE *e, const char *desc)
582 {
583     EVP_PKEY *pkey = NULL;
584     char *allocated_uri = NULL;
585 
586     if (desc == NULL)
587         desc = "public key";
588 
589     if (format == FORMAT_ENGINE)
590         uri = allocated_uri = make_engine_uri(e, uri, desc);
591     (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, 1,
592         NULL, &pkey, NULL, NULL, NULL, NULL, NULL);
593     if (pkey == NULL)
594         (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, 0,
595             &pkey, NULL, NULL, NULL, NULL, NULL, NULL);
596     OPENSSL_free(allocated_uri);
597     return pkey;
598 }
599 
600 EVP_PKEY *load_keyparams_suppress(const char *uri, int format, int maybe_stdin,
601     const char *keytype, const char *desc,
602     int suppress_decode_errors)
603 {
604     EVP_PKEY *params = NULL;
605 
606     if (desc == NULL)
607         desc = "key parameters";
608     (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc,
609         suppress_decode_errors,
610         NULL, NULL, &params, NULL, NULL, NULL, NULL);
611     if (params != NULL && keytype != NULL && !EVP_PKEY_is_a(params, keytype)) {
612         ERR_print_errors(bio_err);
613         BIO_printf(bio_err,
614             "Unable to load %s from %s (unexpected parameters type)\n",
615             desc, uri);
616         EVP_PKEY_free(params);
617         params = NULL;
618     }
619     return params;
620 }
621 
622 EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin,
623     const char *keytype, const char *desc)
624 {
625     return load_keyparams_suppress(uri, format, maybe_stdin, keytype, desc, 0);
626 }
627 
628 void app_bail_out(char *fmt, ...)
629 {
630     va_list args;
631 
632     va_start(args, fmt);
633     BIO_vprintf(bio_err, fmt, args);
634     va_end(args);
635     ERR_print_errors(bio_err);
636     exit(EXIT_FAILURE);
637 }
638 
639 void *app_malloc(size_t sz, const char *what)
640 {
641     void *vp = OPENSSL_malloc(sz);
642 
643     if (vp == NULL)
644         app_bail_out("%s: Could not allocate %zu bytes for %s\n",
645             opt_getprog(), sz, what);
646     return vp;
647 }
648 
649 char *next_item(char *opt) /* in list separated by comma and/or space */
650 {
651     /* advance to separator (comma or whitespace), if any */
652     while (*opt != ',' && !isspace(_UC(*opt)) && *opt != '\0')
653         opt++;
654     if (*opt != '\0') {
655         /* terminate current item */
656         *opt++ = '\0';
657         /* skip over any whitespace after separator */
658         while (isspace(_UC(*opt)))
659             opt++;
660     }
661     return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */
662 }
663 
664 static void warn_cert_msg(const char *uri, X509 *cert, const char *msg)
665 {
666     char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
667 
668     BIO_printf(bio_err, "Warning: certificate from '%s' with subject '%s' %s\n",
669         uri, subj, msg);
670     OPENSSL_free(subj);
671 }
672 
673 static void warn_cert(const char *uri, X509 *cert, int warn_EE,
674     X509_VERIFY_PARAM *vpm)
675 {
676     uint32_t ex_flags = X509_get_extension_flags(cert);
677     int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
678         X509_get0_notAfter(cert));
679 
680     if (res != 0)
681         warn_cert_msg(uri, cert, res > 0 ? "has expired" : "not yet valid");
682     if (warn_EE && (ex_flags & EXFLAG_V1) == 0 && (ex_flags & EXFLAG_CA) == 0)
683         warn_cert_msg(uri, cert, "is not a CA cert");
684 }
685 
686 static void warn_certs(const char *uri, STACK_OF(X509) *certs, int warn_EE,
687     X509_VERIFY_PARAM *vpm)
688 {
689     int i;
690 
691     for (i = 0; i < sk_X509_num(certs); i++)
692         warn_cert(uri, sk_X509_value(certs, i), warn_EE, vpm);
693 }
694 
695 int load_cert_certs(const char *uri,
696     X509 **pcert, STACK_OF(X509) **pcerts,
697     int exclude_http, const char *pass, const char *desc,
698     X509_VERIFY_PARAM *vpm)
699 {
700     int ret = 0;
701     char *pass_string;
702 
703     if (desc == NULL)
704         desc = pcerts == NULL ? "certificate" : "certificates";
705     if (exclude_http && (HAS_CASE_PREFIX(uri, "http://") || HAS_CASE_PREFIX(uri, "https://"))) {
706         BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc);
707         return ret;
708     }
709     pass_string = get_passwd(pass, desc);
710     ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass_string, desc, 0,
711         NULL, NULL, NULL, pcert, pcerts, NULL, NULL);
712     clear_free(pass_string);
713 
714     if (ret) {
715         if (pcert != NULL)
716             warn_cert(uri, *pcert, 0, vpm);
717         if (pcerts != NULL)
718             warn_certs(uri, *pcerts, 1, vpm);
719     } else {
720         if (pcerts != NULL) {
721             OSSL_STACK_OF_X509_free(*pcerts);
722             *pcerts = NULL;
723         }
724     }
725     return ret;
726 }
727 
728 STACK_OF(X509) *load_certs_multifile(char *files, const char *pass,
729     const char *desc, X509_VERIFY_PARAM *vpm)
730 {
731     STACK_OF(X509) *certs = NULL;
732     STACK_OF(X509) *result = sk_X509_new_null();
733 
734     if (files == NULL)
735         goto err;
736     if (result == NULL)
737         goto oom;
738 
739     while (files != NULL) {
740         char *next = next_item(files);
741 
742         if (!load_cert_certs(files, NULL, &certs, 0, pass, desc, vpm))
743             goto err;
744         if (!X509_add_certs(result, certs,
745                 X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
746             goto oom;
747         OSSL_STACK_OF_X509_free(certs);
748         certs = NULL;
749         files = next;
750     }
751     return result;
752 
753 oom:
754     BIO_printf(bio_err, "out of memory\n");
755 err:
756     OSSL_STACK_OF_X509_free(certs);
757     OSSL_STACK_OF_X509_free(result);
758     return NULL;
759 }
760 
761 static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */,
762     const STACK_OF(X509) *certs /* may NULL */)
763 {
764     int i;
765 
766     if (store == NULL)
767         store = X509_STORE_new();
768     if (store == NULL)
769         return NULL;
770     for (i = 0; i < sk_X509_num(certs); i++) {
771         if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) {
772             X509_STORE_free(store);
773             return NULL;
774         }
775     }
776     return store;
777 }
778 
779 /*
780  * Create cert store structure with certificates read from given file(s).
781  * Returns pointer to created X509_STORE on success, NULL on error.
782  */
783 X509_STORE *load_certstore(char *input, const char *pass, const char *desc,
784     X509_VERIFY_PARAM *vpm)
785 {
786     X509_STORE *store = NULL;
787     STACK_OF(X509) *certs = NULL;
788 
789     while (input != NULL) {
790         char *next = next_item(input);
791         int ok;
792 
793         if (!load_cert_certs(input, NULL, &certs, 1, pass, desc, vpm)) {
794             X509_STORE_free(store);
795             return NULL;
796         }
797         ok = (store = sk_X509_to_store(store, certs)) != NULL;
798         OSSL_STACK_OF_X509_free(certs);
799         certs = NULL;
800         if (!ok)
801             return NULL;
802         input = next;
803     }
804     return store;
805 }
806 
807 /*
808  * Initialize or extend, if *certs != NULL, a certificate stack.
809  * The caller is responsible for freeing *certs if its value is left not NULL.
810  */
811 int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs,
812     const char *pass, const char *desc)
813 {
814     int ret, was_NULL = *certs == NULL;
815 
816     if (desc == NULL)
817         desc = "certificates";
818     ret = load_key_certs_crls(uri, FORMAT_UNDEF, maybe_stdin, pass, desc, 0,
819         NULL, NULL, NULL, NULL, certs, NULL, NULL);
820 
821     if (!ret && was_NULL) {
822         OSSL_STACK_OF_X509_free(*certs);
823         *certs = NULL;
824     }
825     return ret;
826 }
827 
828 /*
829  * Initialize or extend, if *crls != NULL, a certificate stack.
830  * The caller is responsible for freeing *crls if its value is left not NULL.
831  */
832 int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
833     const char *pass, const char *desc)
834 {
835     int ret, was_NULL = *crls == NULL;
836 
837     if (desc == NULL)
838         desc = "CRLs";
839     ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass, desc, 0,
840         NULL, NULL, NULL, NULL, NULL, NULL, crls);
841 
842     if (!ret && was_NULL) {
843         sk_X509_CRL_pop_free(*crls, X509_CRL_free);
844         *crls = NULL;
845     }
846     return ret;
847 }
848 
849 static const char *format2string(int format)
850 {
851     switch (format) {
852     case FORMAT_PEM:
853         return "PEM";
854     case FORMAT_ASN1:
855         return "DER";
856     case FORMAT_PVK:
857         return "PVK";
858     case FORMAT_MSBLOB:
859         return "MSBLOB";
860     }
861     return NULL;
862 }
863 
864 /* Set type expectation, but set to 0 if objects of multiple types expected. */
865 #define SET_EXPECT(val) \
866     (expect = expect < 0 ? (val) : (expect == (val) ? (val) : 0))
867 #define SET_EXPECT1(pvar, val) \
868     if ((pvar) != NULL) {      \
869         *(pvar) = NULL;        \
870         SET_EXPECT(val);       \
871     }
872 /* Provide (error msg) text for some of the credential types to be loaded. */
873 #define FAIL_NAME                                                       \
874     (ppkey != NULL ? "private key" : ppubkey != NULL ? "public key"     \
875             : pparams != NULL                        ? "key parameters" \
876             : pcert != NULL                          ? "certificate"    \
877             : pcerts != NULL                         ? "certificates"   \
878             : pcrl != NULL                           ? "CRL"            \
879             : pcrls != NULL                          ? "CRLs"           \
880                                                      : NULL)
881 /*
882  * Load those types of credentials for which the result pointer is not NULL.
883  * Reads from stdin if 'uri' is NULL and 'maybe_stdin' is nonzero.
884  * 'format' parameter may be FORMAT_PEM, FORMAT_ASN1, or 0 for no hint.
885  * desc may contain more detail on the credential(s) to be loaded for error msg
886  * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
887  * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
888  * If pcerts is non-NULL then all available certificates are appended to *pcerts
889  * except any certificate assigned to *pcert.
890  * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
891  * If pcrls is non-NULL then all available CRLs are appended to *pcerts
892  * except any CRL assigned to *pcrl.
893  * In any case (also on error) the caller is responsible for freeing all members
894  * of *pcerts and *pcrls (as far as they are not NULL).
895  */
896 int load_key_certs_crls(const char *uri, int format, int maybe_stdin,
897     const char *pass, const char *desc, int quiet,
898     EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
899     EVP_PKEY **pparams,
900     X509 **pcert, STACK_OF(X509) **pcerts,
901     X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
902 {
903     PW_CB_DATA uidata;
904     OSSL_STORE_CTX *ctx = NULL;
905     OSSL_LIB_CTX *libctx = app_get0_libctx();
906     const char *propq = app_get0_propq();
907     int ncerts = 0, ncrls = 0, expect = -1;
908     const char *failed = FAIL_NAME;
909     const char *input_type;
910     OSSL_PARAM itp[2];
911     const OSSL_PARAM *params = NULL;
912 
913     /* 'failed' describes type of credential to load for potential error msg */
914     if (failed == NULL) {
915         if (!quiet)
916             BIO_printf(bio_err, "Internal error: nothing was requested to load from %s\n",
917                 uri != NULL ? uri : "<stdin>");
918         return 0;
919     }
920     /* suppress any extraneous errors left over from failed parse attempts */
921     ERR_set_mark();
922 
923     SET_EXPECT1(ppkey, OSSL_STORE_INFO_PKEY);
924     SET_EXPECT1(ppubkey, OSSL_STORE_INFO_PUBKEY);
925     SET_EXPECT1(pparams, OSSL_STORE_INFO_PARAMS);
926     SET_EXPECT1(pcert, OSSL_STORE_INFO_CERT);
927     /*
928      * Up to here, the following holds.
929      * If just one of the ppkey, ppubkey, pparams, and pcert function parameters
930      * is nonzero, expect > 0 indicates which type of credential is expected.
931      * If expect == 0, more than one of them is nonzero (multiple types expected).
932      */
933 
934     if (pcerts != NULL) {
935         if (*pcerts == NULL && (*pcerts = sk_X509_new_null()) == NULL) {
936             if (!quiet)
937                 BIO_printf(bio_err, "Out of memory loading");
938             goto end;
939         }
940         /*
941          * Adapt the 'expect' variable:
942          * set to OSSL_STORE_INFO_CERT if no other type is expected so far,
943          * otherwise set to 0 (indicating that multiple types are expected).
944          */
945         SET_EXPECT(OSSL_STORE_INFO_CERT);
946     }
947     SET_EXPECT1(pcrl, OSSL_STORE_INFO_CRL);
948     if (pcrls != NULL) {
949         if (*pcrls == NULL && (*pcrls = sk_X509_CRL_new_null()) == NULL) {
950             if (!quiet)
951                 BIO_printf(bio_err, "Out of memory loading");
952             goto end;
953         }
954         /*
955          * Adapt the 'expect' variable:
956          * set to OSSL_STORE_INFO_CRL if no other type is expected so far,
957          * otherwise set to 0 (indicating that multiple types are expected).
958          */
959         SET_EXPECT(OSSL_STORE_INFO_CRL);
960     }
961 
962     uidata.password = pass;
963     uidata.prompt_info = uri;
964 
965     if ((input_type = format2string(format)) != NULL) {
966         itp[0] = OSSL_PARAM_construct_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE,
967             (char *)input_type, 0);
968         itp[1] = OSSL_PARAM_construct_end();
969         params = itp;
970     }
971 
972     if (uri == NULL) {
973         BIO *bio;
974 
975         if (!maybe_stdin) {
976             if (!quiet)
977                 BIO_printf(bio_err, "No filename or uri specified for loading\n");
978             goto end;
979         }
980         uri = "<stdin>";
981         unbuffer(stdin);
982         bio = BIO_new_fp(stdin, 0);
983         if (bio != NULL) {
984             ctx = OSSL_STORE_attach(bio, "file", libctx, propq,
985                 get_ui_method(), &uidata, params,
986                 NULL, NULL);
987             BIO_free(bio);
988         }
989     } else {
990         ctx = OSSL_STORE_open_ex(uri, libctx, propq, get_ui_method(), &uidata,
991             params, NULL, NULL);
992     }
993     if (ctx == NULL) {
994         if (!quiet)
995             BIO_printf(bio_err, "Could not open file or uri for loading");
996         goto end;
997     }
998     /* expect == 0 means here multiple types of credentials are to be loaded */
999     if (expect > 0 && !OSSL_STORE_expect(ctx, expect)) {
1000         if (!quiet)
1001             BIO_printf(bio_err, "Internal error trying to load");
1002         goto end;
1003     }
1004 
1005     failed = NULL;
1006     /* from here, failed != NULL only if actually an error has been detected */
1007 
1008     while ((ppkey != NULL || ppubkey != NULL || pparams != NULL
1009                || pcert != NULL || pcerts != NULL || pcrl != NULL || pcrls != NULL)
1010         && !OSSL_STORE_eof(ctx)) {
1011         OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
1012         int type, ok = 1;
1013 
1014         /*
1015          * This can happen (for example) if we attempt to load a file with
1016          * multiple different types of things in it - but the thing we just
1017          * tried to load wasn't one of the ones we wanted, e.g. if we're trying
1018          * to load a certificate but the file has both the private key and the
1019          * certificate in it. We just retry until eof.
1020          */
1021         if (info == NULL) {
1022             continue;
1023         }
1024 
1025         type = OSSL_STORE_INFO_get_type(info);
1026         switch (type) {
1027         case OSSL_STORE_INFO_PKEY:
1028             if (ppkey != NULL) {
1029                 ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL;
1030                 if (ok)
1031                     ppkey = NULL;
1032                 break;
1033             }
1034             /*
1035              * An EVP_PKEY with private parts also holds the public parts,
1036              * so if the caller asked for a public key, and we got a private
1037              * key, we can still pass it back.
1038              */
1039             /* fall through */
1040         case OSSL_STORE_INFO_PUBKEY:
1041             if (ppubkey != NULL) {
1042                 ok = (*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL;
1043                 if (ok)
1044                     ppubkey = NULL;
1045             }
1046             break;
1047         case OSSL_STORE_INFO_PARAMS:
1048             if (pparams != NULL) {
1049                 ok = (*pparams = OSSL_STORE_INFO_get1_PARAMS(info)) != NULL;
1050                 if (ok)
1051                     pparams = NULL;
1052             }
1053             break;
1054         case OSSL_STORE_INFO_CERT:
1055             if (pcert != NULL) {
1056                 ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL;
1057                 if (ok)
1058                     pcert = NULL;
1059             } else if (pcerts != NULL) {
1060                 X509 *cert = OSSL_STORE_INFO_get1_CERT(info);
1061 
1062                 ok = cert != NULL
1063                     && X509_add_cert(*pcerts, cert, X509_ADD_FLAG_DEFAULT);
1064                 if (!ok)
1065                     X509_free(cert);
1066             }
1067             ncerts += ok;
1068             break;
1069         case OSSL_STORE_INFO_CRL:
1070             if (pcrl != NULL) {
1071                 ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL;
1072                 if (ok)
1073                     pcrl = NULL;
1074             } else if (pcrls != NULL) {
1075                 X509_CRL *crl = OSSL_STORE_INFO_get1_CRL(info);
1076 
1077                 ok = crl != NULL && sk_X509_CRL_push(*pcrls, crl);
1078                 if (!ok)
1079                     X509_CRL_free(crl);
1080             }
1081             ncrls += ok;
1082             break;
1083         default:
1084             /* skip any other type; ok stays == 1 */
1085             break;
1086         }
1087         OSSL_STORE_INFO_free(info);
1088         if (!ok) {
1089             failed = OSSL_STORE_INFO_type_string(type);
1090             if (!quiet)
1091                 BIO_printf(bio_err, "Error reading");
1092             break;
1093         }
1094     }
1095 
1096 end:
1097     OSSL_STORE_close(ctx);
1098 
1099     /* see if any of the requested types of credentials was not found */
1100     if (failed == NULL) {
1101         if (ncerts > 0)
1102             pcerts = NULL;
1103         if (ncrls > 0)
1104             pcrls = NULL;
1105         failed = FAIL_NAME;
1106         if (failed != NULL && !quiet)
1107             BIO_printf(bio_err, "Could not find");
1108     }
1109 
1110     if (failed != NULL && !quiet) {
1111         unsigned long err = ERR_peek_last_error();
1112 
1113         /* continue the error message with the type of credential affected */
1114         if (desc != NULL && strstr(desc, failed) != NULL) {
1115             BIO_printf(bio_err, " %s", desc);
1116         } else {
1117             BIO_printf(bio_err, " %s", failed);
1118             if (desc != NULL)
1119                 BIO_printf(bio_err, " of %s", desc);
1120         }
1121         if (uri != NULL)
1122             BIO_printf(bio_err, " from %s", uri);
1123         if (ERR_SYSTEM_ERROR(err)) {
1124             /* provide more readable diagnostic output */
1125             BIO_printf(bio_err, ": %s", strerror(ERR_GET_REASON(err)));
1126             ERR_pop_to_mark();
1127             ERR_set_mark();
1128         }
1129         BIO_printf(bio_err, "\n");
1130         ERR_print_errors(bio_err);
1131     }
1132     if (quiet || failed == NULL)
1133         /* clear any suppressed or spurious errors */
1134         ERR_pop_to_mark();
1135     else
1136         ERR_clear_last_mark();
1137     return failed == NULL;
1138 }
1139 
1140 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
1141 #define X509V3_EXT_DEFAULT 0 /* Return error for unknown exts */
1142 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16) /* Print error for unknown exts */
1143 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16) /* ASN1 parse unknown extensions */
1144 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16) /* BIO_dump unknown extensions */
1145 
1146 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1147 
1148 int set_cert_ex(unsigned long *flags, const char *arg)
1149 {
1150     static const NAME_EX_TBL cert_tbl[] = {
1151         { "compatible", X509_FLAG_COMPAT, 0xffffffffl },
1152         { "ca_default", X509_FLAG_CA, 0xffffffffl },
1153         { "no_header", X509_FLAG_NO_HEADER, 0 },
1154         { "no_version", X509_FLAG_NO_VERSION, 0 },
1155         { "no_serial", X509_FLAG_NO_SERIAL, 0 },
1156         { "no_signame", X509_FLAG_NO_SIGNAME, 0 },
1157         { "no_validity", X509_FLAG_NO_VALIDITY, 0 },
1158         { "no_subject", X509_FLAG_NO_SUBJECT, 0 },
1159         { "no_issuer", X509_FLAG_NO_ISSUER, 0 },
1160         { "no_pubkey", X509_FLAG_NO_PUBKEY, 0 },
1161         { "no_extensions", X509_FLAG_NO_EXTENSIONS, 0 },
1162         { "no_sigdump", X509_FLAG_NO_SIGDUMP, 0 },
1163         { "no_aux", X509_FLAG_NO_AUX, 0 },
1164         { "no_attributes", X509_FLAG_NO_ATTRIBUTES, 0 },
1165         { "ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK },
1166         { "ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK },
1167         { "ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK },
1168         { "ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK },
1169         { NULL, 0, 0 }
1170     };
1171     return set_multi_opts(flags, arg, cert_tbl);
1172 }
1173 
1174 int set_name_ex(unsigned long *flags, const char *arg)
1175 {
1176     static const NAME_EX_TBL ex_tbl[] = {
1177         { "esc_2253", ASN1_STRFLGS_ESC_2253, 0 },
1178         { "esc_2254", ASN1_STRFLGS_ESC_2254, 0 },
1179         { "esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0 },
1180         { "esc_msb", ASN1_STRFLGS_ESC_MSB, 0 },
1181         { "use_quote", ASN1_STRFLGS_ESC_QUOTE, 0 },
1182         { "utf8", ASN1_STRFLGS_UTF8_CONVERT, 0 },
1183         { "ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0 },
1184         { "show_type", ASN1_STRFLGS_SHOW_TYPE, 0 },
1185         { "dump_all", ASN1_STRFLGS_DUMP_ALL, 0 },
1186         { "dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0 },
1187         { "dump_der", ASN1_STRFLGS_DUMP_DER, 0 },
1188         { "compat", XN_FLAG_COMPAT, 0xffffffffL },
1189         { "sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK },
1190         { "sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK },
1191         { "sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK },
1192         { "sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK },
1193         { "dn_rev", XN_FLAG_DN_REV, 0 },
1194         { "nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK },
1195         { "sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK },
1196         { "lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK },
1197         { "align", XN_FLAG_FN_ALIGN, 0 },
1198         { "oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK },
1199         { "space_eq", XN_FLAG_SPC_EQ, 0 },
1200         { "dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0 },
1201         { "RFC2253", XN_FLAG_RFC2253, 0xffffffffL },
1202         { "oneline", XN_FLAG_ONELINE, 0xffffffffL },
1203         { "multiline", XN_FLAG_MULTILINE, 0xffffffffL },
1204         { "ca_default", XN_FLAG_MULTILINE, 0xffffffffL },
1205         { NULL, 0, 0 }
1206     };
1207     if (set_multi_opts(flags, arg, ex_tbl) == 0)
1208         return 0;
1209     if (*flags != XN_FLAG_COMPAT
1210         && (*flags & XN_FLAG_SEP_MASK) == 0)
1211         *flags |= XN_FLAG_SEP_CPLUS_SPC;
1212     return 1;
1213 }
1214 
1215 int set_dateopt(unsigned long *dateopt, const char *arg)
1216 {
1217     if (OPENSSL_strcasecmp(arg, "rfc_822") == 0)
1218         *dateopt = ASN1_DTFLGS_RFC822;
1219     else if (OPENSSL_strcasecmp(arg, "iso_8601") == 0)
1220         *dateopt = ASN1_DTFLGS_ISO8601;
1221     else
1222         return 0;
1223     return 1;
1224 }
1225 
1226 int set_ext_copy(int *copy_type, const char *arg)
1227 {
1228     if (OPENSSL_strcasecmp(arg, "none") == 0)
1229         *copy_type = EXT_COPY_NONE;
1230     else if (OPENSSL_strcasecmp(arg, "copy") == 0)
1231         *copy_type = EXT_COPY_ADD;
1232     else if (OPENSSL_strcasecmp(arg, "copyall") == 0)
1233         *copy_type = EXT_COPY_ALL;
1234     else
1235         return 0;
1236     return 1;
1237 }
1238 
1239 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1240 {
1241     STACK_OF(X509_EXTENSION) *exts;
1242     int i, ret = 0;
1243 
1244     if (x == NULL || req == NULL)
1245         return 0;
1246     if (copy_type == EXT_COPY_NONE)
1247         return 1;
1248     exts = X509_REQ_get_extensions(req);
1249 
1250     for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1251         X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
1252         ASN1_OBJECT *obj = X509_EXTENSION_get_object(ext);
1253         int idx = X509_get_ext_by_OBJ(x, obj, -1);
1254 
1255         /* Does extension exist in target? */
1256         if (idx != -1) {
1257             /* If normal copy don't override existing extension */
1258             if (copy_type == EXT_COPY_ADD)
1259                 continue;
1260             /* Delete all extensions of same type */
1261             do {
1262                 X509_EXTENSION_free(X509_delete_ext(x, idx));
1263                 idx = X509_get_ext_by_OBJ(x, obj, -1);
1264             } while (idx != -1);
1265         }
1266         if (!X509_add_ext(x, ext, -1))
1267             goto end;
1268     }
1269     ret = 1;
1270 
1271 end:
1272     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1273     return ret;
1274 }
1275 
1276 static int set_multi_opts(unsigned long *flags, const char *arg,
1277     const NAME_EX_TBL *in_tbl)
1278 {
1279     STACK_OF(CONF_VALUE) *vals;
1280     CONF_VALUE *val;
1281     int i, ret = 1;
1282 
1283     if (!arg)
1284         return 0;
1285     vals = X509V3_parse_list(arg);
1286     for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1287         val = sk_CONF_VALUE_value(vals, i);
1288         if (!set_table_opts(flags, val->name, in_tbl))
1289             ret = 0;
1290     }
1291     sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1292     return ret;
1293 }
1294 
1295 static int set_table_opts(unsigned long *flags, const char *arg,
1296     const NAME_EX_TBL *in_tbl)
1297 {
1298     char c;
1299     const NAME_EX_TBL *ptbl;
1300 
1301     c = arg[0];
1302     if (c == '-') {
1303         c = 0;
1304         arg++;
1305     } else if (c == '+') {
1306         c = 1;
1307         arg++;
1308     } else {
1309         c = 1;
1310     }
1311 
1312     for (ptbl = in_tbl; ptbl->name; ptbl++) {
1313         if (OPENSSL_strcasecmp(arg, ptbl->name) == 0) {
1314             *flags &= ~ptbl->mask;
1315             if (c)
1316                 *flags |= ptbl->flag;
1317             else
1318                 *flags &= ~ptbl->flag;
1319             return 1;
1320         }
1321     }
1322     return 0;
1323 }
1324 
1325 void print_name(BIO *out, const char *title, const X509_NAME *nm)
1326 {
1327     char *buf;
1328     char mline = 0;
1329     int indent = 0;
1330     unsigned long lflags = get_nameopt();
1331 
1332     if (out == NULL)
1333         return;
1334     if (title != NULL)
1335         BIO_puts(out, title);
1336     if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1337         mline = 1;
1338         indent = 4;
1339     }
1340     if (lflags == XN_FLAG_COMPAT) {
1341         buf = X509_NAME_oneline(nm, 0, 0);
1342         BIO_puts(out, buf);
1343         BIO_puts(out, "\n");
1344         OPENSSL_free(buf);
1345     } else {
1346         if (mline)
1347             BIO_puts(out, "\n");
1348         X509_NAME_print_ex(out, nm, indent, lflags);
1349         BIO_puts(out, "\n");
1350     }
1351 }
1352 
1353 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1354     int len, unsigned char *buffer)
1355 {
1356     BIO_printf(out, "    static unsigned char %s_%d[] = {", var, len);
1357     if (BN_is_zero(in)) {
1358         BIO_printf(out, "\n        0x00");
1359     } else {
1360         int i, l;
1361 
1362         l = BN_bn2bin(in, buffer);
1363         for (i = 0; i < l; i++) {
1364             BIO_printf(out, (i % 10) == 0 ? "\n        " : " ");
1365             if (i < l - 1)
1366                 BIO_printf(out, "0x%02X,", buffer[i]);
1367             else
1368                 BIO_printf(out, "0x%02X", buffer[i]);
1369         }
1370     }
1371     BIO_printf(out, "\n    };\n");
1372 }
1373 
1374 void print_array(BIO *out, const char *title, int len, const unsigned char *d)
1375 {
1376     int i;
1377 
1378     BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1379     for (i = 0; i < len; i++) {
1380         if ((i % 10) == 0)
1381             BIO_printf(out, "\n    ");
1382         if (i < len - 1)
1383             BIO_printf(out, "0x%02X, ", d[i]);
1384         else
1385             BIO_printf(out, "0x%02X", d[i]);
1386     }
1387     BIO_printf(out, "\n};\n");
1388 }
1389 
1390 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1391     const char *CApath, int noCApath,
1392     const char *CAstore, int noCAstore)
1393 {
1394     X509_STORE *store = X509_STORE_new();
1395     X509_LOOKUP *lookup;
1396     OSSL_LIB_CTX *libctx = app_get0_libctx();
1397     const char *propq = app_get0_propq();
1398 
1399     if (store == NULL)
1400         goto end;
1401 
1402     if (CAfile != NULL || !noCAfile) {
1403         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1404         if (lookup == NULL)
1405             goto end;
1406         if (CAfile != NULL) {
1407             if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM,
1408                     libctx, propq)
1409                 <= 0) {
1410                 ERR_clear_error();
1411                 if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_ASN1,
1412                         libctx, propq)
1413                     <= 0) {
1414                     BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1415                     goto end;
1416                 }
1417             }
1418         } else {
1419             X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT,
1420                 libctx, propq);
1421         }
1422     }
1423 
1424     if (CApath != NULL || !noCApath) {
1425         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1426         if (lookup == NULL)
1427             goto end;
1428         if (CApath != NULL) {
1429             if (X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM) <= 0) {
1430                 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1431                 goto end;
1432             }
1433         } else {
1434             X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1435         }
1436     }
1437 
1438     if (CAstore != NULL || !noCAstore) {
1439         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1440         if (lookup == NULL)
1441             goto end;
1442         if (!X509_LOOKUP_add_store_ex(lookup, CAstore, libctx, propq)) {
1443             if (CAstore != NULL)
1444                 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1445             goto end;
1446         }
1447     }
1448 
1449     ERR_clear_error();
1450     return store;
1451 end:
1452     ERR_print_errors(bio_err);
1453     X509_STORE_free(store);
1454     return NULL;
1455 }
1456 
1457 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1458 {
1459     const char *n;
1460 
1461     n = a[DB_serial];
1462     while (*n == '0')
1463         n++;
1464     return OPENSSL_LH_strhash(n);
1465 }
1466 
1467 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1468     const OPENSSL_CSTRING *b)
1469 {
1470     const char *aa, *bb;
1471 
1472     for (aa = a[DB_serial]; *aa == '0'; aa++)
1473         ;
1474     for (bb = b[DB_serial]; *bb == '0'; bb++)
1475         ;
1476     return strcmp(aa, bb);
1477 }
1478 
1479 static int index_name_qual(char **a)
1480 {
1481     return (a[0][0] == 'V');
1482 }
1483 
1484 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1485 {
1486     return OPENSSL_LH_strhash(a[DB_name]);
1487 }
1488 
1489 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1490 {
1491     return strcmp(a[DB_name], b[DB_name]);
1492 }
1493 
1494 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1495 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1496 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1497 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1498 #undef BSIZE
1499 #define BSIZE 256
1500 BIGNUM *load_serial(const char *serialfile, int *exists, int create,
1501     ASN1_INTEGER **retai)
1502 {
1503     BIO *in = NULL;
1504     BIGNUM *ret = NULL;
1505     char buf[1024];
1506     ASN1_INTEGER *ai = NULL;
1507 
1508     ai = ASN1_INTEGER_new();
1509     if (ai == NULL)
1510         goto err;
1511 
1512     in = BIO_new_file(serialfile, "r");
1513     if (exists != NULL)
1514         *exists = in != NULL;
1515     if (in == NULL) {
1516         if (!create) {
1517             perror(serialfile);
1518             goto err;
1519         }
1520         ERR_clear_error();
1521         ret = BN_new();
1522         if (ret == NULL) {
1523             BIO_printf(bio_err, "Out of memory\n");
1524         } else if (!rand_serial(ret, ai)) {
1525             BIO_printf(bio_err, "Error creating random number to store in %s\n",
1526                 serialfile);
1527             BN_free(ret);
1528             ret = NULL;
1529         }
1530     } else {
1531         if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1532             BIO_printf(bio_err, "Unable to load number from %s\n",
1533                 serialfile);
1534             goto err;
1535         }
1536         ret = ASN1_INTEGER_to_BN(ai, NULL);
1537         if (ret == NULL) {
1538             BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1539             goto err;
1540         }
1541     }
1542 
1543     if (ret != NULL && retai != NULL) {
1544         *retai = ai;
1545         ai = NULL;
1546     }
1547 err:
1548     if (ret == NULL)
1549         ERR_print_errors(bio_err);
1550     BIO_free(in);
1551     ASN1_INTEGER_free(ai);
1552     return ret;
1553 }
1554 
1555 int save_serial(const char *serialfile, const char *suffix,
1556     const BIGNUM *serial, ASN1_INTEGER **retai)
1557 {
1558     char buf[1][BSIZE];
1559     BIO *out = NULL;
1560     int ret = 0;
1561     ASN1_INTEGER *ai = NULL;
1562     int j;
1563 
1564     if (suffix == NULL)
1565         j = strlen(serialfile);
1566     else
1567         j = strlen(serialfile) + strlen(suffix) + 1;
1568     if (j >= BSIZE) {
1569         BIO_printf(bio_err, "File name too long\n");
1570         goto err;
1571     }
1572 
1573     if (suffix == NULL) {
1574         OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1575     } else {
1576 #ifndef OPENSSL_SYS_VMS
1577         BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1578 #else
1579         BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1580 #endif
1581     }
1582     out = BIO_new_file(buf[0], "w");
1583     if (out == NULL) {
1584         goto err;
1585     }
1586 
1587     if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1588         BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1589         goto err;
1590     }
1591     i2a_ASN1_INTEGER(out, ai);
1592     BIO_puts(out, "\n");
1593     ret = 1;
1594     if (retai) {
1595         *retai = ai;
1596         ai = NULL;
1597     }
1598 err:
1599     if (!ret)
1600         ERR_print_errors(bio_err);
1601     BIO_free_all(out);
1602     ASN1_INTEGER_free(ai);
1603     return ret;
1604 }
1605 
1606 int rotate_serial(const char *serialfile, const char *new_suffix,
1607     const char *old_suffix)
1608 {
1609     char buf[2][BSIZE];
1610     int i, j;
1611 
1612     i = strlen(serialfile) + strlen(old_suffix);
1613     j = strlen(serialfile) + strlen(new_suffix);
1614     if (i > j)
1615         j = i;
1616     if (j + 1 >= BSIZE) {
1617         BIO_printf(bio_err, "File name too long\n");
1618         goto err;
1619     }
1620 #ifndef OPENSSL_SYS_VMS
1621     BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1622     BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1623 #else
1624     BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1625     BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1626 #endif
1627     if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1628 #ifdef ENOTDIR
1629         && errno != ENOTDIR
1630 #endif
1631     ) {
1632         BIO_printf(bio_err,
1633             "Unable to rename %s to %s\n", serialfile, buf[1]);
1634         perror("reason");
1635         goto err;
1636     }
1637     if (rename(buf[0], serialfile) < 0) {
1638         BIO_printf(bio_err,
1639             "Unable to rename %s to %s\n", buf[0], serialfile);
1640         perror("reason");
1641         rename(buf[1], serialfile);
1642         goto err;
1643     }
1644     return 1;
1645 err:
1646     ERR_print_errors(bio_err);
1647     return 0;
1648 }
1649 
1650 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1651 {
1652     BIGNUM *btmp;
1653     int ret = 0;
1654 
1655     btmp = b == NULL ? BN_new() : b;
1656     if (btmp == NULL)
1657         return 0;
1658 
1659     if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1660         goto error;
1661     if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1662         goto error;
1663 
1664     ret = 1;
1665 
1666 error:
1667 
1668     if (btmp != b)
1669         BN_free(btmp);
1670 
1671     return ret;
1672 }
1673 
1674 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1675 {
1676     CA_DB *retdb = NULL;
1677     TXT_DB *tmpdb = NULL;
1678     BIO *in;
1679     CONF *dbattr_conf = NULL;
1680     char buf[BSIZE];
1681 #ifndef OPENSSL_NO_POSIX_IO
1682     FILE *dbfp;
1683     struct stat dbst;
1684 #endif
1685 
1686     in = BIO_new_file(dbfile, "r");
1687     if (in == NULL)
1688         goto err;
1689 
1690 #ifndef OPENSSL_NO_POSIX_IO
1691     BIO_get_fp(in, &dbfp);
1692     if (fstat(fileno(dbfp), &dbst) == -1) {
1693         ERR_raise_data(ERR_LIB_SYS, errno,
1694             "calling fstat(%s)", dbfile);
1695         goto err;
1696     }
1697 #endif
1698 
1699     if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1700         goto err;
1701 
1702 #ifndef OPENSSL_SYS_VMS
1703     BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1704 #else
1705     BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1706 #endif
1707     dbattr_conf = app_load_config_quiet(buf);
1708 
1709     retdb = app_malloc(sizeof(*retdb), "new DB");
1710     retdb->db = tmpdb;
1711     tmpdb = NULL;
1712     if (db_attr)
1713         retdb->attributes = *db_attr;
1714     else
1715         retdb->attributes.unique_subject = 1;
1716 
1717     if (dbattr_conf != NULL) {
1718         char *p = app_conf_try_string(dbattr_conf, NULL, "unique_subject");
1719 
1720         if (p != NULL)
1721             retdb->attributes.unique_subject = parse_yesno(p, 1);
1722     }
1723 
1724     retdb->dbfname = OPENSSL_strdup(dbfile);
1725     if (retdb->dbfname == NULL)
1726         goto err;
1727 
1728 #ifndef OPENSSL_NO_POSIX_IO
1729     retdb->dbst = dbst;
1730 #endif
1731 
1732 err:
1733     ERR_print_errors(bio_err);
1734     NCONF_free(dbattr_conf);
1735     TXT_DB_free(tmpdb);
1736     BIO_free_all(in);
1737     return retdb;
1738 }
1739 
1740 /*
1741  * Returns > 0 on success, <= 0 on error
1742  */
1743 int index_index(CA_DB *db)
1744 {
1745     if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1746             LHASH_HASH_FN(index_serial),
1747             LHASH_COMP_FN(index_serial))) {
1748         BIO_printf(bio_err,
1749             "Error creating serial number index:(%ld,%ld,%ld)\n",
1750             db->db->error, db->db->arg1, db->db->arg2);
1751         goto err;
1752     }
1753 
1754     if (db->attributes.unique_subject
1755         && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1756             LHASH_HASH_FN(index_name),
1757             LHASH_COMP_FN(index_name))) {
1758         BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1759             db->db->error, db->db->arg1, db->db->arg2);
1760         goto err;
1761     }
1762     return 1;
1763 err:
1764     ERR_print_errors(bio_err);
1765     return 0;
1766 }
1767 
1768 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1769 {
1770     char buf[3][BSIZE];
1771     BIO *out;
1772     int j;
1773 
1774     j = strlen(dbfile) + strlen(suffix);
1775     if (j + 6 >= BSIZE) {
1776         BIO_printf(bio_err, "File name too long\n");
1777         goto err;
1778     }
1779 #ifndef OPENSSL_SYS_VMS
1780     BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1781     BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1782     BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1783 #else
1784     BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1785     BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1786     BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1787 #endif
1788     out = BIO_new_file(buf[0], "w");
1789     if (out == NULL) {
1790         perror(dbfile);
1791         BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1792         goto err;
1793     }
1794     j = TXT_DB_write(out, db->db);
1795     BIO_free(out);
1796     if (j <= 0)
1797         goto err;
1798 
1799     out = BIO_new_file(buf[1], "w");
1800     if (out == NULL) {
1801         perror(buf[2]);
1802         BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1803         goto err;
1804     }
1805     BIO_printf(out, "unique_subject = %s\n",
1806         db->attributes.unique_subject ? "yes" : "no");
1807     BIO_free(out);
1808 
1809     return 1;
1810 err:
1811     ERR_print_errors(bio_err);
1812     return 0;
1813 }
1814 
1815 int rotate_index(const char *dbfile, const char *new_suffix,
1816     const char *old_suffix)
1817 {
1818     char buf[5][BSIZE];
1819     int i, j;
1820 
1821     i = strlen(dbfile) + strlen(old_suffix);
1822     j = strlen(dbfile) + strlen(new_suffix);
1823     if (i > j)
1824         j = i;
1825     if (j + 6 >= BSIZE) {
1826         BIO_printf(bio_err, "File name too long\n");
1827         goto err;
1828     }
1829 #ifndef OPENSSL_SYS_VMS
1830     BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1831     BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1832     BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1833     BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1834     BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1835 #else
1836     BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1837     BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1838     BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1839     BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1840     BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1841 #endif
1842     if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1843 #ifdef ENOTDIR
1844         && errno != ENOTDIR
1845 #endif
1846     ) {
1847         BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1848         perror("reason");
1849         goto err;
1850     }
1851     if (rename(buf[0], dbfile) < 0) {
1852         BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1853         perror("reason");
1854         rename(buf[1], dbfile);
1855         goto err;
1856     }
1857     if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1858 #ifdef ENOTDIR
1859         && errno != ENOTDIR
1860 #endif
1861     ) {
1862         BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1863         perror("reason");
1864         rename(dbfile, buf[0]);
1865         rename(buf[1], dbfile);
1866         goto err;
1867     }
1868     if (rename(buf[2], buf[4]) < 0) {
1869         BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1870         perror("reason");
1871         rename(buf[3], buf[4]);
1872         rename(dbfile, buf[0]);
1873         rename(buf[1], dbfile);
1874         goto err;
1875     }
1876     return 1;
1877 err:
1878     ERR_print_errors(bio_err);
1879     return 0;
1880 }
1881 
1882 void free_index(CA_DB *db)
1883 {
1884     if (db) {
1885         TXT_DB_free(db->db);
1886         OPENSSL_free(db->dbfname);
1887         OPENSSL_free(db);
1888     }
1889 }
1890 
1891 int parse_yesno(const char *str, int def)
1892 {
1893     if (str) {
1894         switch (*str) {
1895         case 'f': /* false */
1896         case 'F': /* FALSE */
1897         case 'n': /* no */
1898         case 'N': /* NO */
1899         case '0': /* 0 */
1900             return 0;
1901         case 't': /* true */
1902         case 'T': /* TRUE */
1903         case 'y': /* yes */
1904         case 'Y': /* YES */
1905         case '1': /* 1 */
1906             return 1;
1907         }
1908     }
1909     return def;
1910 }
1911 
1912 /*
1913  * name is expected to be in the format /type0=value0/type1=value1/type2=...
1914  * where + can be used instead of / to form multi-valued RDNs if canmulti
1915  * and characters may be escaped by \
1916  */
1917 X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
1918     const char *desc)
1919 {
1920     int nextismulti = 0;
1921     char *work;
1922     X509_NAME *n;
1923 
1924     if (*cp++ != '/') {
1925         BIO_printf(bio_err,
1926             "%s: %s name is expected to be in the format "
1927             "/type0=value0/type1=value1/type2=... where characters may "
1928             "be escaped by \\. This name is not in that format: '%s'\n",
1929             opt_getprog(), desc, --cp);
1930         return NULL;
1931     }
1932 
1933     n = X509_NAME_new();
1934     if (n == NULL) {
1935         BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
1936         return NULL;
1937     }
1938     work = OPENSSL_strdup(cp);
1939     if (work == NULL) {
1940         BIO_printf(bio_err, "%s: Error copying %s name input\n",
1941             opt_getprog(), desc);
1942         goto err;
1943     }
1944 
1945     while (*cp != '\0') {
1946         char *bp = work;
1947         char *typestr = bp;
1948         unsigned char *valstr;
1949         int nid;
1950         int ismulti = nextismulti;
1951 
1952         nextismulti = 0;
1953 
1954         /* Collect the type */
1955         while (*cp != '\0' && *cp != '=')
1956             *bp++ = *cp++;
1957         *bp++ = '\0';
1958         if (*cp == '\0') {
1959             BIO_printf(bio_err,
1960                 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1961                 opt_getprog(), typestr, desc);
1962             goto err;
1963         }
1964         ++cp;
1965 
1966         /* Collect the value. */
1967         valstr = (unsigned char *)bp;
1968         for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
1969             /* unescaped '+' symbol string signals further member of multiRDN */
1970             if (canmulti && *cp == '+') {
1971                 nextismulti = 1;
1972                 break;
1973             }
1974             if (*cp == '\\' && *++cp == '\0') {
1975                 BIO_printf(bio_err,
1976                     "%s: Escape character at end of %s name string\n",
1977                     opt_getprog(), desc);
1978                 goto err;
1979             }
1980         }
1981         *bp++ = '\0';
1982 
1983         /* If not at EOS (must be + or /), move forward. */
1984         if (*cp != '\0')
1985             ++cp;
1986 
1987         /* Parse */
1988         nid = OBJ_txt2nid(typestr);
1989         if (nid == NID_undef) {
1990             BIO_printf(bio_err,
1991                 "%s warning: Skipping unknown %s name attribute \"%s\"\n",
1992                 opt_getprog(), desc, typestr);
1993             if (ismulti)
1994                 BIO_printf(bio_err,
1995                     "%s hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n",
1996                     opt_getprog());
1997             continue;
1998         }
1999         if (*valstr == '\0') {
2000             BIO_printf(bio_err,
2001                 "%s warning: No value provided for %s name attribute \"%s\", skipped\n",
2002                 opt_getprog(), desc, typestr);
2003             continue;
2004         }
2005         if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
2006                 valstr, strlen((char *)valstr),
2007                 -1, ismulti ? -1 : 0)) {
2008             ERR_print_errors(bio_err);
2009             BIO_printf(bio_err,
2010                 "%s: Error adding %s name attribute \"/%s=%s\"\n",
2011                 opt_getprog(), desc, typestr, valstr);
2012             goto err;
2013         }
2014     }
2015 
2016     OPENSSL_free(work);
2017     return n;
2018 
2019 err:
2020     X509_NAME_free(n);
2021     OPENSSL_free(work);
2022     return NULL;
2023 }
2024 
2025 /*
2026  * Read whole contents of a BIO into an allocated memory buffer.
2027  * The return value is one on success, zero on error.
2028  * If `maxlen` is non-zero, at most `maxlen` bytes are returned, or else, if
2029  * the input is longer than `maxlen`, an error is returned.
2030  * If `maxlen` is zero, the limit is effectively `SIZE_MAX`.
2031  */
2032 int bio_to_mem(unsigned char **out, size_t *outlen, size_t maxlen, BIO *in)
2033 {
2034     unsigned char tbuf[4096];
2035     BIO *mem;
2036     BUF_MEM *bufm;
2037     size_t sz = 0;
2038     int len;
2039 
2040     mem = BIO_new(BIO_s_mem());
2041     if (mem == NULL)
2042         return 0;
2043     for (;;) {
2044         if ((len = BIO_read(in, tbuf, 4096)) == 0)
2045             break;
2046         if (len < 0
2047             || BIO_write(mem, tbuf, len) != len
2048             || sz > SIZE_MAX - len
2049             || ((sz += len) > maxlen && maxlen != 0)) {
2050             BIO_free(mem);
2051             return 0;
2052         }
2053     }
2054 
2055     /* So BIO_free orphans BUF_MEM */
2056     (void)BIO_set_close(mem, BIO_NOCLOSE);
2057     BIO_get_mem_ptr(mem, &bufm);
2058     BIO_free(mem);
2059     *out = (unsigned char *)bufm->data;
2060     *outlen = bufm->length;
2061     /* Tell BUF_MEM to orphan data */
2062     bufm->data = NULL;
2063     BUF_MEM_free(bufm);
2064     return 1;
2065 }
2066 
2067 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
2068 {
2069     int rv = 0;
2070     char *stmp, *vtmp = NULL;
2071 
2072     stmp = OPENSSL_strdup(value);
2073     if (stmp == NULL)
2074         return -1;
2075     vtmp = strchr(stmp, ':');
2076     if (vtmp == NULL)
2077         goto err;
2078 
2079     *vtmp = 0;
2080     vtmp++;
2081     rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
2082 
2083 err:
2084     OPENSSL_free(stmp);
2085     return rv;
2086 }
2087 
2088 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
2089 {
2090     X509_POLICY_NODE *node;
2091     int i;
2092 
2093     BIO_printf(bio_err, "%s Policies:", name);
2094     if (nodes) {
2095         BIO_puts(bio_err, "\n");
2096         for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
2097             node = sk_X509_POLICY_NODE_value(nodes, i);
2098             X509_POLICY_NODE_print(bio_err, node, 2);
2099         }
2100     } else {
2101         BIO_puts(bio_err, " <empty>\n");
2102     }
2103 }
2104 
2105 void policies_print(X509_STORE_CTX *ctx)
2106 {
2107     X509_POLICY_TREE *tree;
2108     int explicit_policy;
2109 
2110     tree = X509_STORE_CTX_get0_policy_tree(ctx);
2111     explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2112 
2113     BIO_printf(bio_err, "Require explicit Policy: %s\n",
2114         explicit_policy ? "True" : "False");
2115 
2116     nodes_print("Authority", X509_policy_tree_get0_policies(tree));
2117     nodes_print("User", X509_policy_tree_get0_user_policies(tree));
2118 }
2119 
2120 /*-
2121  * next_protos_parse parses a comma separated list of strings into a string
2122  * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
2123  *   outlen: (output) set to the length of the resulting buffer on success.
2124  *   err: (maybe NULL) on failure, an error message line is written to this BIO.
2125  *   in: a NUL terminated string like "abc,def,ghi"
2126  *
2127  *   returns: a malloc'd buffer or NULL on failure.
2128  */
2129 unsigned char *next_protos_parse(size_t *outlen, const char *in)
2130 {
2131     size_t len;
2132     unsigned char *out;
2133     size_t i, start = 0;
2134     size_t skipped = 0;
2135 
2136     len = strlen(in);
2137     if (len == 0 || len >= 65535)
2138         return NULL;
2139 
2140     out = app_malloc(len + 1, "NPN buffer");
2141     for (i = 0; i <= len; ++i) {
2142         if (i == len || in[i] == ',') {
2143             /*
2144              * Zero-length ALPN elements are invalid on the wire, we could be
2145              * strict and reject the entire string, but just ignoring extra
2146              * commas seems harmless and more friendly.
2147              *
2148              * Every comma we skip in this way puts the input buffer another
2149              * byte ahead of the output buffer, so all stores into the output
2150              * buffer need to be decremented by the number commas skipped.
2151              */
2152             if (i == start) {
2153                 ++start;
2154                 ++skipped;
2155                 continue;
2156             }
2157             if (i - start > 255) {
2158                 OPENSSL_free(out);
2159                 return NULL;
2160             }
2161             out[start - skipped] = (unsigned char)(i - start);
2162             start = i + 1;
2163         } else {
2164             out[i + 1 - skipped] = in[i];
2165         }
2166     }
2167 
2168     if (len <= skipped) {
2169         OPENSSL_free(out);
2170         return NULL;
2171     }
2172 
2173     *outlen = len + 1 - skipped;
2174     return out;
2175 }
2176 
2177 int check_cert_attributes(BIO *bio, X509 *x, const char *checkhost,
2178     const char *checkemail, const char *checkip,
2179     int print)
2180 {
2181     int valid_host = 0;
2182     int valid_mail = 0;
2183     int valid_ip = 0;
2184     int ret = 1;
2185 
2186     if (x == NULL)
2187         return 0;
2188 
2189     if (checkhost != NULL) {
2190         valid_host = X509_check_host(x, checkhost, 0, 0, NULL);
2191         if (print)
2192             BIO_printf(bio, "Hostname %s does%s match certificate\n",
2193                 checkhost, valid_host == 1 ? "" : " NOT");
2194         ret = ret && valid_host > 0;
2195     }
2196 
2197     if (checkemail != NULL) {
2198         valid_mail = X509_check_email(x, checkemail, 0, 0);
2199         if (print)
2200             BIO_printf(bio, "Email %s does%s match certificate\n",
2201                 checkemail, valid_mail ? "" : " NOT");
2202         ret = ret && valid_mail > 0;
2203     }
2204 
2205     if (checkip != NULL) {
2206         valid_ip = X509_check_ip_asc(x, checkip, 0);
2207         if (print)
2208             BIO_printf(bio, "IP %s does%s match certificate\n",
2209                 checkip, valid_ip ? "" : " NOT");
2210         ret = ret && valid_ip > 0;
2211     }
2212 
2213     return ret;
2214 }
2215 
2216 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
2217 {
2218     int i;
2219 
2220     if (opts == NULL)
2221         return 1;
2222 
2223     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2224         char *opt = sk_OPENSSL_STRING_value(opts, i);
2225 
2226         if (pkey_ctrl_string(pkctx, opt) <= 0) {
2227             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2228             ERR_print_errors(bio_err);
2229             return 0;
2230         }
2231     }
2232 
2233     return 1;
2234 }
2235 
2236 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
2237 {
2238     int i;
2239 
2240     if (opts == NULL)
2241         return 1;
2242 
2243     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2244         char *opt = sk_OPENSSL_STRING_value(opts, i);
2245 
2246         if (x509_ctrl_string(x, opt) <= 0) {
2247             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2248             ERR_print_errors(bio_err);
2249             return 0;
2250         }
2251     }
2252 
2253     return 1;
2254 }
2255 
2256 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
2257 {
2258     int i;
2259 
2260     if (opts == NULL)
2261         return 1;
2262 
2263     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2264         char *opt = sk_OPENSSL_STRING_value(opts, i);
2265 
2266         if (x509_req_ctrl_string(x, opt) <= 0) {
2267             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2268             ERR_print_errors(bio_err);
2269             return 0;
2270         }
2271     }
2272 
2273     return 1;
2274 }
2275 
2276 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
2277     const char *md, STACK_OF(OPENSSL_STRING) *sigopts)
2278 {
2279     EVP_PKEY_CTX *pkctx = NULL;
2280     char def_md[80];
2281 
2282     if (ctx == NULL)
2283         return 0;
2284     /*
2285      * EVP_PKEY_get_default_digest_name() returns 2 if the digest is mandatory
2286      * for this algorithm.
2287      */
2288     if (EVP_PKEY_get_default_digest_name(pkey, def_md, sizeof(def_md)) == 2
2289         && strcmp(def_md, "UNDEF") == 0) {
2290         /* The signing algorithm requires there to be no digest */
2291         md = NULL;
2292     }
2293 
2294     return EVP_DigestSignInit_ex(ctx, &pkctx, md, app_get0_libctx(),
2295                app_get0_propq(), pkey, NULL)
2296         && do_pkey_ctx_init(pkctx, sigopts);
2297 }
2298 
2299 static int adapt_keyid_ext(X509 *cert, X509V3_CTX *ext_ctx,
2300     const char *name, const char *value, int add_default)
2301 {
2302     const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
2303     X509_EXTENSION *new_ext = X509V3_EXT_nconf(NULL, ext_ctx, name, value);
2304     int idx, rv = 0;
2305 
2306     if (new_ext == NULL)
2307         return rv;
2308 
2309     idx = X509v3_get_ext_by_OBJ(exts, X509_EXTENSION_get_object(new_ext), -1);
2310     if (idx >= 0) {
2311         X509_EXTENSION *found_ext = X509v3_get_ext(exts, idx);
2312         ASN1_OCTET_STRING *encoded = X509_EXTENSION_get_data(found_ext);
2313         int disabled = ASN1_STRING_length(encoded) <= 2; /* indicating "none" */
2314 
2315         if (disabled) {
2316             X509_delete_ext(cert, idx);
2317             X509_EXTENSION_free(found_ext);
2318         } /* else keep existing key identifier, which might be outdated */
2319         rv = 1;
2320     } else {
2321         rv = !add_default || X509_add_ext(cert, new_ext, -1);
2322     }
2323     X509_EXTENSION_free(new_ext);
2324     return rv;
2325 }
2326 
2327 int cert_matches_key(const X509 *cert, const EVP_PKEY *pkey)
2328 {
2329     int match;
2330 
2331     ERR_set_mark();
2332     match = X509_check_private_key(cert, pkey);
2333     ERR_pop_to_mark();
2334     return match;
2335 }
2336 
2337 /* Ensure RFC 5280 compliance, adapt keyIDs as needed, and sign the cert info */
2338 int do_X509_sign(X509 *cert, int force_v1, EVP_PKEY *pkey, const char *md,
2339     STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx)
2340 {
2341     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2342     int self_sign;
2343     int rv = 0;
2344 
2345     if (!force_v1) {
2346         if (!X509_set_version(cert, X509_VERSION_3))
2347             goto end;
2348 
2349         /*
2350          * Add default SKID before AKID such that AKID can make use of it
2351          * in case the certificate is self-signed
2352          */
2353         /* Prevent X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER */
2354         if (!adapt_keyid_ext(cert, ext_ctx, "subjectKeyIdentifier", "hash", 1))
2355             goto end;
2356         /* Prevent X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER */
2357         self_sign = cert_matches_key(cert, pkey);
2358         if (!adapt_keyid_ext(cert, ext_ctx, "authorityKeyIdentifier",
2359                 "keyid, issuer", !self_sign))
2360             goto end;
2361     }
2362     /* May add further measures for ensuring RFC 5280 compliance, see #19805 */
2363 
2364     if (mctx != NULL && do_sign_init(mctx, pkey, md, sigopts) > 0)
2365         rv = (X509_sign_ctx(cert, mctx) > 0);
2366 end:
2367     EVP_MD_CTX_free(mctx);
2368     return rv;
2369 }
2370 
2371 /* Sign the certificate request info */
2372 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md,
2373     STACK_OF(OPENSSL_STRING) *sigopts)
2374 {
2375     int rv = 0;
2376     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2377 
2378     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2379         rv = (X509_REQ_sign_ctx(x, mctx) > 0);
2380     EVP_MD_CTX_free(mctx);
2381     return rv;
2382 }
2383 
2384 /* Sign the CRL info */
2385 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md,
2386     STACK_OF(OPENSSL_STRING) *sigopts)
2387 {
2388     int rv = 0;
2389     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2390 
2391     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2392         rv = (X509_CRL_sign_ctx(x, mctx) > 0);
2393     EVP_MD_CTX_free(mctx);
2394     return rv;
2395 }
2396 
2397 /*
2398  * do_X509_verify returns 1 if the signature is valid,
2399  * 0 if the signature check fails, or -1 if error occurs.
2400  */
2401 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
2402 {
2403     int rv = 0;
2404 
2405     if (do_x509_init(x, vfyopts) > 0)
2406         rv = X509_verify(x, pkey);
2407     else
2408         rv = -1;
2409     return rv;
2410 }
2411 
2412 /*
2413  * do_X509_REQ_verify returns 1 if the signature is valid,
2414  * 0 if the signature check fails, or -1 if error occurs.
2415  */
2416 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
2417     STACK_OF(OPENSSL_STRING) *vfyopts)
2418 {
2419     int rv = 0;
2420 
2421     if (do_x509_req_init(x, vfyopts) > 0)
2422         rv = X509_REQ_verify_ex(x, pkey, app_get0_libctx(), app_get0_propq());
2423     else
2424         rv = -1;
2425     return rv;
2426 }
2427 
2428 /* Get first http URL from a DIST_POINT structure */
2429 
2430 static const char *get_dp_url(DIST_POINT *dp)
2431 {
2432     GENERAL_NAMES *gens;
2433     GENERAL_NAME *gen;
2434     int i, gtype;
2435     ASN1_STRING *uri;
2436 
2437     if (!dp->distpoint || dp->distpoint->type != 0)
2438         return NULL;
2439     gens = dp->distpoint->name.fullname;
2440     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2441         gen = sk_GENERAL_NAME_value(gens, i);
2442         uri = GENERAL_NAME_get0_value(gen, &gtype);
2443         if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
2444             const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
2445 
2446             if (IS_HTTP(uptr)) /* can/should not use HTTPS here */
2447                 return uptr;
2448         }
2449     }
2450     return NULL;
2451 }
2452 
2453 /*
2454  * Look through a CRLDP structure and attempt to find an http URL to
2455  * downloads a CRL from.
2456  */
2457 
2458 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
2459 {
2460     int i;
2461     const char *urlptr = NULL;
2462 
2463     for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2464         DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
2465 
2466         urlptr = get_dp_url(dp);
2467         if (urlptr != NULL)
2468             return load_crl(urlptr, FORMAT_UNDEF, 0, "CRL via CDP");
2469     }
2470     return NULL;
2471 }
2472 
2473 /*
2474  * Example of downloading CRLs from CRLDP:
2475  * not usable for real world as it always downloads and doesn't cache anything.
2476  */
2477 
2478 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
2479     const X509_NAME *nm)
2480 {
2481     X509 *x;
2482     STACK_OF(X509_CRL) *crls = NULL;
2483     X509_CRL *crl;
2484     STACK_OF(DIST_POINT) *crldp;
2485 
2486     crls = sk_X509_CRL_new_null();
2487     if (!crls)
2488         return NULL;
2489     x = X509_STORE_CTX_get_current_cert(ctx);
2490     crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2491     crl = load_crl_crldp(crldp);
2492     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2493 
2494     if (crl == NULL || !sk_X509_CRL_push(crls, crl))
2495         goto error;
2496 
2497     /* Try to download delta CRL */
2498     crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2499     crl = load_crl_crldp(crldp);
2500     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2501 
2502     if (crl != NULL && !sk_X509_CRL_push(crls, crl))
2503         goto error;
2504 
2505     return crls;
2506 
2507 error:
2508     X509_CRL_free(crl);
2509     sk_X509_CRL_pop_free(crls, X509_CRL_free);
2510     return NULL;
2511 }
2512 
2513 void store_setup_crl_download(X509_STORE *st)
2514 {
2515     X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2516 }
2517 
2518 #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP)
2519 static const char *tls_error_hint(void)
2520 {
2521     unsigned long err = ERR_peek_error();
2522 
2523     if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2524         err = ERR_peek_last_error();
2525     if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2526         return NULL; /* likely no TLS error */
2527 
2528     switch (ERR_GET_REASON(err)) {
2529     case SSL_R_WRONG_VERSION_NUMBER:
2530         return "The server does not support (a suitable version of) TLS";
2531     case SSL_R_UNKNOWN_PROTOCOL:
2532         return "The server does not support HTTPS";
2533     case SSL_R_CERTIFICATE_VERIFY_FAILED:
2534         return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2535     case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
2536         return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2537     case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
2538         return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2539     default:
2540         return NULL; /* no hint available for TLS error */
2541     }
2542 }
2543 
2544 static BIO *http_tls_shutdown(BIO *bio)
2545 {
2546     if (bio != NULL) {
2547         BIO *cbio;
2548         const char *hint = tls_error_hint();
2549 
2550         if (hint != NULL)
2551             BIO_printf(bio_err, "%s\n", hint);
2552         (void)ERR_set_mark();
2553         BIO_ssl_shutdown(bio);
2554         cbio = BIO_pop(bio); /* connect+HTTP BIO */
2555         BIO_free(bio); /* SSL BIO */
2556         (void)ERR_pop_to_mark(); /* hide SSL_R_READ_BIO_NOT_SET etc. */
2557         bio = cbio;
2558     }
2559     return bio;
2560 }
2561 
2562 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
2563 BIO *app_http_tls_cb(BIO *bio, void *arg, int connect, int detail)
2564 {
2565     APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
2566     SSL_CTX *ssl_ctx = info->ssl_ctx;
2567 
2568     if (ssl_ctx == NULL) /* not using TLS */
2569         return bio;
2570     if (connect) {
2571         SSL *ssl;
2572         BIO *sbio = NULL;
2573         X509_STORE *ts = SSL_CTX_get_cert_store(ssl_ctx);
2574         X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts);
2575         const char *host = vpm == NULL ? NULL : X509_VERIFY_PARAM_get0_host(vpm, 0 /* first hostname */);
2576 
2577         /* adapt after fixing callback design flaw, see #17088 */
2578         if ((info->use_proxy
2579                 && !OSSL_HTTP_proxy_connect(bio, info->server, info->port,
2580                     NULL, NULL, /* no proxy credentials */
2581                     info->timeout, bio_err, opt_getprog()))
2582             || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
2583             return NULL;
2584         }
2585         if ((ssl = SSL_new(ssl_ctx)) == NULL) {
2586             BIO_free(sbio);
2587             return NULL;
2588         }
2589 
2590         if (vpm != NULL)
2591             SSL_set_tlsext_host_name(ssl, host /* may be NULL */);
2592 
2593         SSL_set_connect_state(ssl);
2594         BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2595 
2596         bio = BIO_push(sbio, bio);
2597     } else { /* disconnect from TLS */
2598         bio = http_tls_shutdown(bio);
2599     }
2600     return bio;
2601 }
2602 
2603 void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info)
2604 {
2605     if (info != NULL) {
2606         SSL_CTX_free(info->ssl_ctx);
2607         OPENSSL_free(info);
2608     }
2609 }
2610 
2611 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2612     const char *no_proxy, SSL_CTX *ssl_ctx,
2613     const STACK_OF(CONF_VALUE) *headers,
2614     long timeout, const char *expected_content_type,
2615     const ASN1_ITEM *it)
2616 {
2617     APP_HTTP_TLS_INFO info;
2618     char *server;
2619     char *port;
2620     int use_ssl;
2621     BIO *mem;
2622     ASN1_VALUE *resp = NULL;
2623 
2624     if (url == NULL || it == NULL) {
2625         ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
2626         return NULL;
2627     }
2628 
2629     if (!OSSL_HTTP_parse_url(url, &use_ssl, NULL /* userinfo */, &server, &port,
2630             NULL /* port_num, */, NULL, NULL, NULL))
2631         return NULL;
2632     if (use_ssl && ssl_ctx == NULL) {
2633         ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER,
2634             "missing SSL_CTX");
2635         goto end;
2636     }
2637     if (!use_ssl && ssl_ctx != NULL) {
2638         ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT,
2639             "SSL_CTX given but use_ssl == 0");
2640         goto end;
2641     }
2642 
2643     info.server = server;
2644     info.port = port;
2645     info.use_proxy = /* workaround for callback design flaw, see #17088 */
2646         OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl) != NULL;
2647     info.timeout = timeout;
2648     info.ssl_ctx = ssl_ctx;
2649     mem = OSSL_HTTP_get(url, proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2650         app_http_tls_cb, &info, 0 /* buf_size */, headers,
2651         expected_content_type, 1 /* expect_asn1 */,
2652         OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout);
2653     resp = ASN1_item_d2i_bio(it, mem, NULL);
2654     BIO_free(mem);
2655 
2656 end:
2657     OPENSSL_free(server);
2658     OPENSSL_free(port);
2659     return resp;
2660 }
2661 
2662 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2663     const char *path, const char *proxy,
2664     const char *no_proxy, SSL_CTX *ssl_ctx,
2665     const STACK_OF(CONF_VALUE) *headers,
2666     const char *content_type,
2667     ASN1_VALUE *req, const ASN1_ITEM *req_it,
2668     const char *expected_content_type,
2669     long timeout, const ASN1_ITEM *rsp_it)
2670 {
2671     int use_ssl = ssl_ctx != NULL;
2672     APP_HTTP_TLS_INFO info;
2673     BIO *rsp, *req_mem = ASN1_item_i2d_mem_bio(req_it, req);
2674     ASN1_VALUE *res;
2675 
2676     if (req_mem == NULL)
2677         return NULL;
2678 
2679     info.server = host;
2680     info.port = port;
2681     info.use_proxy = /* workaround for callback design flaw, see #17088 */
2682         OSSL_HTTP_adapt_proxy(proxy, no_proxy, host, use_ssl) != NULL;
2683     info.timeout = timeout;
2684     info.ssl_ctx = ssl_ctx;
2685     rsp = OSSL_HTTP_transfer(NULL, host, port, path, use_ssl,
2686         proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2687         app_http_tls_cb, &info,
2688         0 /* buf_size */, headers, content_type, req_mem,
2689         expected_content_type, 1 /* expect_asn1 */,
2690         OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout,
2691         0 /* keep_alive */);
2692     BIO_free(req_mem);
2693     res = ASN1_item_d2i_bio(rsp_it, rsp, NULL);
2694     BIO_free(rsp);
2695     return res;
2696 }
2697 
2698 #endif
2699 
2700 /*
2701  * Platform-specific sections
2702  */
2703 #if defined(_WIN32)
2704 #ifdef fileno
2705 #undef fileno
2706 #define fileno(a) (int)_fileno(a)
2707 #endif
2708 
2709 #include <windows.h>
2710 #include <tchar.h>
2711 
2712 static int WIN32_rename(const char *from, const char *to)
2713 {
2714     TCHAR *tfrom = NULL, *tto;
2715     DWORD err;
2716     int ret = 0;
2717 
2718     if (sizeof(TCHAR) == 1) {
2719         tfrom = (TCHAR *)from;
2720         tto = (TCHAR *)to;
2721     } else { /* UNICODE path */
2722         size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2723 
2724         tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2725         if (tfrom == NULL)
2726             goto err;
2727         tto = tfrom + flen;
2728 #if !defined(_WIN32_WCE) || _WIN32_WCE >= 101
2729         if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2730 #endif
2731             for (i = 0; i < flen; i++)
2732                 tfrom[i] = (TCHAR)from[i];
2733 #if !defined(_WIN32_WCE) || _WIN32_WCE >= 101
2734         if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2735 #endif
2736             for (i = 0; i < tlen; i++)
2737                 tto[i] = (TCHAR)to[i];
2738     }
2739 
2740     if (MoveFile(tfrom, tto))
2741         goto ok;
2742     err = GetLastError();
2743     if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2744         if (DeleteFile(tto) && MoveFile(tfrom, tto))
2745             goto ok;
2746         err = GetLastError();
2747     }
2748     if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2749         errno = ENOENT;
2750     else if (err == ERROR_ACCESS_DENIED)
2751         errno = EACCES;
2752     else
2753         errno = EINVAL; /* we could map more codes... */
2754 err:
2755     ret = -1;
2756 ok:
2757     if (tfrom != NULL && tfrom != (TCHAR *)from)
2758         free(tfrom);
2759     return ret;
2760 }
2761 #endif
2762 
2763 /* app_tminterval section */
2764 #if defined(_WIN32)
2765 double app_tminterval(int stop, int usertime)
2766 {
2767     FILETIME now;
2768     double ret = 0;
2769     static ULARGE_INTEGER tmstart;
2770     static int warning = 1;
2771     int use_GetSystemTime = 1;
2772 #ifdef _WIN32_WINNT
2773     static HANDLE proc = NULL;
2774 
2775     if (proc == NULL) {
2776         if (check_winnt())
2777             proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2778                 GetCurrentProcessId());
2779         if (proc == NULL)
2780             proc = (HANDLE)-1;
2781     }
2782 
2783     if (usertime && proc != (HANDLE)-1) {
2784         FILETIME junk;
2785 
2786         GetProcessTimes(proc, &junk, &junk, &junk, &now);
2787         use_GetSystemTime = 0;
2788     }
2789 #endif
2790     if (use_GetSystemTime) {
2791         SYSTEMTIME systime;
2792 
2793         if (usertime && warning) {
2794             BIO_printf(bio_err, "To get meaningful results, run "
2795                                 "this program on idle system.\n");
2796             warning = 0;
2797         }
2798         GetSystemTime(&systime);
2799         SystemTimeToFileTime(&systime, &now);
2800     }
2801 
2802     if (stop == TM_START) {
2803         tmstart.u.LowPart = now.dwLowDateTime;
2804         tmstart.u.HighPart = now.dwHighDateTime;
2805     } else {
2806         ULARGE_INTEGER tmstop;
2807 
2808         tmstop.u.LowPart = now.dwLowDateTime;
2809         tmstop.u.HighPart = now.dwHighDateTime;
2810 
2811         ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2812     }
2813 
2814     return ret;
2815 }
2816 #elif defined(OPENSSL_SYS_VXWORKS)
2817 #include <time.h>
2818 
2819 double app_tminterval(int stop, int usertime)
2820 {
2821     double ret = 0;
2822 #ifdef CLOCK_REALTIME
2823     static struct timespec tmstart;
2824     struct timespec now;
2825 #else
2826     static unsigned long tmstart;
2827     unsigned long now;
2828 #endif
2829     static int warning = 1;
2830 
2831     if (usertime && warning) {
2832         BIO_printf(bio_err, "To get meaningful results, run "
2833                             "this program on idle system.\n");
2834         warning = 0;
2835     }
2836 #ifdef CLOCK_REALTIME
2837     clock_gettime(CLOCK_REALTIME, &now);
2838     if (stop == TM_START)
2839         tmstart = now;
2840     else
2841         ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2842             - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2843 #else
2844     now = tickGet();
2845     if (stop == TM_START)
2846         tmstart = now;
2847     else
2848         ret = (now - tmstart) / (double)sysClkRateGet();
2849 #endif
2850     return ret;
2851 }
2852 
2853 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2854 #include <sys/times.h>
2855 
2856 double app_tminterval(int stop, int usertime)
2857 {
2858     double ret = 0;
2859     struct tms rus;
2860     clock_t now = times(&rus);
2861     static clock_t tmstart;
2862 
2863     if (usertime)
2864         now = rus.tms_utime;
2865 
2866     if (stop == TM_START) {
2867         tmstart = now;
2868     } else {
2869         long int tck = sysconf(_SC_CLK_TCK);
2870 
2871         ret = (now - tmstart) / (double)tck;
2872     }
2873 
2874     return ret;
2875 }
2876 
2877 #else
2878 #include <sys/time.h>
2879 #include <sys/resource.h>
2880 
2881 double app_tminterval(int stop, int usertime)
2882 {
2883     double ret = 0;
2884     struct rusage rus;
2885     struct timeval now;
2886     static struct timeval tmstart;
2887 
2888     if (usertime)
2889         getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2890     else
2891         gettimeofday(&now, NULL);
2892 
2893     if (stop == TM_START)
2894         tmstart = now;
2895     else
2896         ret = ((now.tv_sec + now.tv_usec * 1e-6)
2897             - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2898 
2899     return ret;
2900 }
2901 #endif
2902 
2903 int app_access(const char *name, int flag)
2904 {
2905 #ifdef _WIN32
2906     return _access(name, flag);
2907 #else
2908     return access(name, flag);
2909 #endif
2910 }
2911 
2912 int app_isdir(const char *name)
2913 {
2914     return opt_isdir(name);
2915 }
2916 
2917 /* raw_read|write section */
2918 #if defined(__VMS)
2919 #include "vms_term_sock.h"
2920 static int stdin_sock = -1;
2921 
2922 static void close_stdin_sock(void)
2923 {
2924     TerminalSocket(TERM_SOCK_DELETE, &stdin_sock);
2925 }
2926 
2927 int fileno_stdin(void)
2928 {
2929     if (stdin_sock == -1) {
2930         TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2931         atexit(close_stdin_sock);
2932     }
2933 
2934     return stdin_sock;
2935 }
2936 #else
2937 int fileno_stdin(void)
2938 {
2939     return fileno(stdin);
2940 }
2941 #endif
2942 
2943 int fileno_stdout(void)
2944 {
2945     return fileno(stdout);
2946 }
2947 
2948 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2949 int raw_read_stdin(void *buf, int siz)
2950 {
2951     DWORD n;
2952 
2953     if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2954         return n;
2955     else
2956         return -1;
2957 }
2958 #elif defined(__VMS)
2959 #include <sys/socket.h>
2960 
2961 int raw_read_stdin(void *buf, int siz)
2962 {
2963     return recv(fileno_stdin(), buf, siz, 0);
2964 }
2965 #else
2966 int raw_read_stdin(void *buf, int siz)
2967 {
2968     return read(fileno_stdin(), buf, siz);
2969 }
2970 #endif
2971 
2972 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2973 int raw_write_stdout(const void *buf, int siz)
2974 {
2975     DWORD n;
2976 
2977     if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2978         return n;
2979     else
2980         return -1;
2981 }
2982 #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) \
2983     && defined(_SPT_MODEL_)
2984 int raw_write_stdout(const void *buf, int siz)
2985 {
2986     return write(fileno(stdout), (void *)buf, siz);
2987 }
2988 #else
2989 int raw_write_stdout(const void *buf, int siz)
2990 {
2991     return write(fileno_stdout(), buf, siz);
2992 }
2993 #endif
2994 
2995 /*
2996  * Centralized handling of input and output files with format specification
2997  * The format is meant to show what the input and output is supposed to be,
2998  * and is therefore a show of intent more than anything else.  However, it
2999  * does impact behavior on some platforms, such as differentiating between
3000  * text and binary input/output on non-Unix platforms
3001  */
3002 BIO *dup_bio_in(int format)
3003 {
3004     return BIO_new_fp(stdin,
3005         BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
3006 }
3007 
3008 BIO *dup_bio_out(int format)
3009 {
3010     BIO *b = BIO_new_fp(stdout,
3011         BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
3012     void *prefix = NULL;
3013 
3014     if (b == NULL)
3015         return NULL;
3016 
3017 #ifdef OPENSSL_SYS_VMS
3018     if (FMT_istext(format))
3019         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
3020 #endif
3021 
3022     if (FMT_istext(format)
3023         && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
3024         b = BIO_push(BIO_new(BIO_f_prefix()), b);
3025         BIO_set_prefix(b, prefix);
3026     }
3027 
3028     return b;
3029 }
3030 
3031 BIO *dup_bio_err(int format)
3032 {
3033     BIO *b = BIO_new_fp(stderr,
3034         BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
3035 
3036 #ifdef OPENSSL_SYS_VMS
3037     if (b != NULL && FMT_istext(format))
3038         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
3039 #endif
3040     return b;
3041 }
3042 
3043 void unbuffer(FILE *fp)
3044 {
3045 /*
3046  * On VMS, setbuf() will only take 32-bit pointers, and a compilation
3047  * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
3048  * However, we trust that the C RTL will never give us a FILE pointer
3049  * above the first 4 GB of memory, so we simply turn off the warning
3050  * temporarily.
3051  */
3052 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
3053 #pragma environment save
3054 #pragma message disable maylosedata2
3055 #endif
3056     setbuf(fp, NULL);
3057 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
3058 #pragma environment restore
3059 #endif
3060 }
3061 
3062 static const char *modestr(char mode, int format)
3063 {
3064     OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
3065 
3066     switch (mode) {
3067     case 'a':
3068         return FMT_istext(format) ? "a" : "ab";
3069     case 'r':
3070         return FMT_istext(format) ? "r" : "rb";
3071     case 'w':
3072         return FMT_istext(format) ? "w" : "wb";
3073     }
3074     /* The assert above should make sure we never reach this point */
3075     return NULL;
3076 }
3077 
3078 static const char *modeverb(char mode)
3079 {
3080     switch (mode) {
3081     case 'a':
3082         return "appending";
3083     case 'r':
3084         return "reading";
3085     case 'w':
3086         return "writing";
3087     }
3088     return "(doing something)";
3089 }
3090 
3091 /*
3092  * Open a file for writing, owner-read-only.
3093  */
3094 BIO *bio_open_owner(const char *filename, int format, int private)
3095 {
3096     FILE *fp = NULL;
3097     BIO *b = NULL;
3098     int textmode, bflags;
3099 #ifndef OPENSSL_NO_POSIX_IO
3100     int fd = -1, mode;
3101 #endif
3102 
3103     if (!private || filename == NULL || strcmp(filename, "-") == 0)
3104         return bio_open_default(filename, 'w', format);
3105 
3106     textmode = FMT_istext(format);
3107 #ifndef OPENSSL_NO_POSIX_IO
3108     mode = O_WRONLY;
3109 #ifdef O_CREAT
3110     mode |= O_CREAT;
3111 #endif
3112 #ifdef O_TRUNC
3113     mode |= O_TRUNC;
3114 #endif
3115     if (!textmode) {
3116 #ifdef O_BINARY
3117         mode |= O_BINARY;
3118 #elif defined(_O_BINARY)
3119         mode |= _O_BINARY;
3120 #endif
3121     }
3122 
3123 #ifdef OPENSSL_SYS_VMS
3124     /*
3125      * VMS doesn't have O_BINARY, it just doesn't make sense.  But,
3126      * it still needs to know that we're going binary, or fdopen()
3127      * will fail with "invalid argument"...  so we tell VMS what the
3128      * context is.
3129      */
3130     if (!textmode)
3131         fd = open(filename, mode, 0600, "ctx=bin");
3132     else
3133 #endif
3134         fd = open(filename, mode, 0600);
3135     if (fd < 0)
3136         goto err;
3137     fp = fdopen(fd, modestr('w', format));
3138 #else /* OPENSSL_NO_POSIX_IO */
3139     /* Have stdio but not Posix IO, do the best we can */
3140     fp = fopen(filename, modestr('w', format));
3141 #endif /* OPENSSL_NO_POSIX_IO */
3142     if (fp == NULL)
3143         goto err;
3144     bflags = BIO_CLOSE;
3145     if (textmode)
3146         bflags |= BIO_FP_TEXT;
3147     b = BIO_new_fp(fp, bflags);
3148     if (b != NULL)
3149         return b;
3150 
3151 err:
3152     BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
3153         opt_getprog(), filename, strerror(errno));
3154     ERR_print_errors(bio_err);
3155     /* If we have fp, then fdopen took over fd, so don't close both. */
3156     if (fp != NULL)
3157         fclose(fp);
3158 #ifndef OPENSSL_NO_POSIX_IO
3159     else if (fd >= 0)
3160         close(fd);
3161 #endif
3162     return NULL;
3163 }
3164 
3165 static BIO *bio_open_default_(const char *filename, char mode, int format,
3166     int quiet)
3167 {
3168     BIO *ret;
3169 
3170     if (filename == NULL || strcmp(filename, "-") == 0) {
3171         ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
3172         if (quiet) {
3173             ERR_clear_error();
3174             return ret;
3175         }
3176         if (ret != NULL)
3177             return ret;
3178         BIO_printf(bio_err,
3179             "Can't open %s, %s\n",
3180             mode == 'r' ? "stdin" : "stdout", strerror(errno));
3181     } else {
3182         ret = BIO_new_file(filename, modestr(mode, format));
3183         if (quiet) {
3184             ERR_clear_error();
3185             return ret;
3186         }
3187         if (ret != NULL)
3188             return ret;
3189         BIO_printf(bio_err,
3190             "Can't open \"%s\" for %s, %s\n",
3191             filename, modeverb(mode), strerror(errno));
3192     }
3193     ERR_print_errors(bio_err);
3194     return NULL;
3195 }
3196 
3197 BIO *bio_open_default(const char *filename, char mode, int format)
3198 {
3199     return bio_open_default_(filename, mode, format, 0);
3200 }
3201 
3202 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
3203 {
3204     return bio_open_default_(filename, mode, format, 1);
3205 }
3206 
3207 int mem_bio_to_file(BIO *in, const char *filename, int format, int private)
3208 {
3209     int rv = 0, ret = 0;
3210     BIO *out = NULL;
3211     BUF_MEM *mem_buffer = NULL;
3212 
3213     rv = BIO_get_mem_ptr(in, &mem_buffer);
3214     if (rv <= 0) {
3215         BIO_puts(bio_err, "Error reading mem buffer\n");
3216         goto end;
3217     }
3218     out = bio_open_owner(filename, format, private);
3219     if (out == NULL)
3220         goto end;
3221     rv = BIO_write(out, mem_buffer->data, mem_buffer->length);
3222     if (rv < 0 || (size_t)rv != mem_buffer->length)
3223         BIO_printf(bio_err, "Error writing to output file: '%s'\n", filename);
3224     else
3225         ret = 1;
3226 end:
3227     if (!ret)
3228         ERR_print_errors(bio_err);
3229     BIO_free_all(out);
3230     return ret;
3231 }
3232 
3233 void wait_for_async(SSL *s)
3234 {
3235     /* On Windows select only works for sockets, so we simply don't wait  */
3236 #ifndef OPENSSL_SYS_WINDOWS
3237     int width = 0;
3238     fd_set asyncfds;
3239     OSSL_ASYNC_FD *fds;
3240     size_t numfds;
3241     size_t i;
3242 
3243     if (!SSL_get_all_async_fds(s, NULL, &numfds))
3244         return;
3245     if (numfds == 0)
3246         return;
3247     fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
3248     if (!SSL_get_all_async_fds(s, fds, &numfds)) {
3249         OPENSSL_free(fds);
3250         return;
3251     }
3252 
3253     FD_ZERO(&asyncfds);
3254     for (i = 0; i < numfds; i++) {
3255         if (width <= (int)fds[i])
3256             width = (int)fds[i] + 1;
3257         openssl_fdset((int)fds[i], &asyncfds);
3258     }
3259     select(width, (void *)&asyncfds, NULL, NULL, NULL);
3260     OPENSSL_free(fds);
3261 #endif
3262 }
3263 
3264 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
3265 #if defined(OPENSSL_SYS_MSDOS)
3266 int has_stdin_waiting(void)
3267 {
3268 #if defined(OPENSSL_SYS_WINDOWS)
3269     HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
3270     DWORD events = 0;
3271     INPUT_RECORD inputrec;
3272     DWORD insize = 1;
3273     BOOL peeked;
3274 
3275     if (inhand == INVALID_HANDLE_VALUE) {
3276         return 0;
3277     }
3278 
3279     peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
3280     if (!peeked) {
3281         /* Probably redirected input? _kbhit() does not work in this case */
3282         if (!feof(stdin)) {
3283             return 1;
3284         }
3285         return 0;
3286     }
3287 #endif
3288     return _kbhit();
3289 }
3290 #endif
3291 
3292 /* Corrupt a signature by modifying final byte */
3293 void corrupt_signature(const ASN1_STRING *signature)
3294 {
3295     unsigned char *s = signature->data;
3296 
3297     s[signature->length - 1] ^= 0x1;
3298 }
3299 
3300 int check_cert_time_string(const char *time, const char *desc)
3301 {
3302     if (time == NULL || strcmp(time, "today") == 0
3303         || ASN1_TIME_set_string_X509(NULL, time))
3304         return 1;
3305     BIO_printf(bio_err,
3306         "%s is invalid, it should be \"today\" or have format [CC]YYMMDDHHMMSSZ\n",
3307         desc);
3308     return 0;
3309 }
3310 
3311 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
3312     int days, int strict_compare_times)
3313 {
3314     if (!check_cert_time_string(startdate, "start date"))
3315         return 0;
3316     if (!check_cert_time_string(enddate, "end date"))
3317         return 0;
3318     if (startdate == NULL || strcmp(startdate, "today") == 0) {
3319         if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL) {
3320             BIO_printf(bio_err, "Error setting notBefore certificate field\n");
3321             return 0;
3322         }
3323     } else {
3324         if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate)) {
3325             BIO_printf(bio_err, "Error setting notBefore certificate field\n");
3326             return 0;
3327         }
3328     }
3329     if (enddate != NULL && strcmp(enddate, "today") == 0) {
3330         enddate = NULL;
3331         days = 0;
3332     }
3333     if (enddate == NULL) {
3334         if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL) == NULL) {
3335             BIO_printf(bio_err, "Error setting notAfter certificate field\n");
3336             return 0;
3337         }
3338     } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
3339         BIO_printf(bio_err, "Error setting notAfter certificate field\n");
3340         return 0;
3341     }
3342     if (ASN1_TIME_compare(X509_get0_notAfter(x), X509_get0_notBefore(x)) < 0) {
3343         BIO_printf(bio_err, "%s: end date before start date\n",
3344             strict_compare_times ? "Error" : "Warning");
3345         if (strict_compare_times)
3346             return 0;
3347     }
3348     return 1;
3349 }
3350 
3351 int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate)
3352 {
3353     int ret = 0;
3354     ASN1_TIME *tm = ASN1_TIME_new();
3355 
3356     if (tm == NULL)
3357         goto end;
3358 
3359     if (lastupdate == NULL) {
3360         if (X509_gmtime_adj(tm, 0) == NULL)
3361             goto end;
3362     } else {
3363         if (!ASN1_TIME_set_string_X509(tm, lastupdate))
3364             goto end;
3365     }
3366 
3367     if (!X509_CRL_set1_lastUpdate(crl, tm))
3368         goto end;
3369 
3370     ret = 1;
3371 end:
3372     ASN1_TIME_free(tm);
3373     return ret;
3374 }
3375 
3376 int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
3377     long days, long hours, long secs)
3378 {
3379     int ret = 0;
3380     ASN1_TIME *tm = ASN1_TIME_new();
3381 
3382     if (tm == NULL)
3383         goto end;
3384 
3385     if (nextupdate == NULL) {
3386         if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL)
3387             goto end;
3388     } else {
3389         if (!ASN1_TIME_set_string_X509(tm, nextupdate))
3390             goto end;
3391     }
3392 
3393     if (!X509_CRL_set1_nextUpdate(crl, tm))
3394         goto end;
3395 
3396     ret = 1;
3397 end:
3398     ASN1_TIME_free(tm);
3399     return ret;
3400 }
3401 
3402 void make_uppercase(char *string)
3403 {
3404     int i;
3405 
3406     for (i = 0; string[i] != '\0'; i++)
3407         string[i] = toupper((unsigned char)string[i]);
3408 }
3409 
3410 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
3411     const OSSL_PARAM *paramdefs)
3412 {
3413     OSSL_PARAM *params = NULL;
3414     size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
3415     size_t params_n;
3416     char *opt = "", *stmp, *vtmp = NULL;
3417     int found = 1;
3418 
3419     if (opts == NULL)
3420         return NULL;
3421 
3422     params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
3423     if (params == NULL)
3424         return NULL;
3425 
3426     for (params_n = 0; params_n < sz; params_n++) {
3427         opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
3428         if ((stmp = OPENSSL_strdup(opt)) == NULL
3429             || (vtmp = strchr(stmp, ':')) == NULL)
3430             goto err;
3431         /* Replace ':' with 0 to terminate the string pointed to by stmp */
3432         *vtmp = 0;
3433         /* Skip over the separator so that vmtp points to the value */
3434         vtmp++;
3435         if (!OSSL_PARAM_allocate_from_text(&params[params_n], paramdefs,
3436                 stmp, vtmp, strlen(vtmp), &found))
3437             goto err;
3438         OPENSSL_free(stmp);
3439     }
3440     params[params_n] = OSSL_PARAM_construct_end();
3441     return params;
3442 err:
3443     OPENSSL_free(stmp);
3444     BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
3445         opt);
3446     ERR_print_errors(bio_err);
3447     app_params_free(params);
3448     return NULL;
3449 }
3450 
3451 void app_params_free(OSSL_PARAM *params)
3452 {
3453     int i;
3454 
3455     if (params != NULL) {
3456         for (i = 0; params[i].key != NULL; ++i)
3457             OPENSSL_free(params[i].data);
3458         OPENSSL_free(params);
3459     }
3460 }
3461 
3462 EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose)
3463 {
3464     EVP_PKEY *res = NULL;
3465 
3466     if (verbose && alg != NULL) {
3467         BIO_printf(bio_err, "Generating %s key", alg);
3468         if (bits > 0)
3469             BIO_printf(bio_err, " with %d bits\n", bits);
3470         else
3471             BIO_printf(bio_err, "\n");
3472     }
3473     if (!RAND_status())
3474         BIO_printf(bio_err, "Warning: generating random key material may take a long time\n"
3475                             "if the system has a poor entropy source\n");
3476     if (EVP_PKEY_keygen(ctx, &res) <= 0)
3477         BIO_printf(bio_err, "%s: Error generating %s key\n", opt_getprog(),
3478             alg != NULL ? alg : "asymmetric");
3479     return res;
3480 }
3481 
3482 EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg)
3483 {
3484     EVP_PKEY *res = NULL;
3485 
3486     if (!RAND_status())
3487         BIO_printf(bio_err, "Warning: generating random key parameters may take a long time\n"
3488                             "if the system has a poor entropy source\n");
3489     if (EVP_PKEY_paramgen(ctx, &res) <= 0)
3490         BIO_printf(bio_err, "%s: Generating %s key parameters failed\n",
3491             opt_getprog(), alg != NULL ? alg : "asymmetric");
3492     return res;
3493 }
3494 
3495 /*
3496  * Return non-zero if the legacy path is still an option.
3497  * This decision is based on the global command line operations and the
3498  * behaviour thus far.
3499  */
3500 int opt_legacy_okay(void)
3501 {
3502     int provider_options = opt_provider_option_given();
3503     int libctx = app_get0_libctx() != NULL || app_get0_propq() != NULL;
3504 
3505     /*
3506      * Having a provider option specified or a custom library context or
3507      * property query, is a sure sign we're not using legacy.
3508      */
3509     if (provider_options || libctx)
3510         return 0;
3511     return 1;
3512 }
3513