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