xref: /freebsd/crypto/openssl/apps/lib/apps.c (revision 63f537551380d2dab29fa402ad1269feae17e594)
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\n");
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         goto end;
965     if (expect > 0 && !OSSL_STORE_expect(ctx, expect))
966         goto end;
967 
968     failed = NULL;
969     while (cnt_expectations > 0 && !OSSL_STORE_eof(ctx)) {
970         OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
971         int type, ok = 1;
972 
973         /*
974          * This can happen (for example) if we attempt to load a file with
975          * multiple different types of things in it - but the thing we just
976          * tried to load wasn't one of the ones we wanted, e.g. if we're trying
977          * to load a certificate but the file has both the private key and the
978          * certificate in it. We just retry until eof.
979          */
980         if (info == NULL) {
981             continue;
982         }
983 
984         type = OSSL_STORE_INFO_get_type(info);
985         switch (type) {
986         case OSSL_STORE_INFO_PKEY:
987             if (ppkey != NULL && *ppkey == NULL) {
988                 ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL;
989                 cnt_expectations -= ok;
990             }
991             /*
992              * An EVP_PKEY with private parts also holds the public parts,
993              * so if the caller asked for a public key, and we got a private
994              * key, we can still pass it back.
995              */
996             if (ok && ppubkey != NULL && *ppubkey == NULL) {
997                 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL);
998                 cnt_expectations -= ok;
999             }
1000             break;
1001         case OSSL_STORE_INFO_PUBKEY:
1002             if (ppubkey != NULL && *ppubkey == NULL) {
1003                 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL);
1004                 cnt_expectations -= ok;
1005             }
1006             break;
1007         case OSSL_STORE_INFO_PARAMS:
1008             if (pparams != NULL && *pparams == NULL) {
1009                 ok = ((*pparams = OSSL_STORE_INFO_get1_PARAMS(info)) != NULL);
1010                 cnt_expectations -= ok;
1011             }
1012             break;
1013         case OSSL_STORE_INFO_CERT:
1014             if (pcert != NULL && *pcert == NULL) {
1015                 ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL;
1016                 cnt_expectations -= ok;
1017             }
1018             else if (pcerts != NULL)
1019                 ok = X509_add_cert(*pcerts,
1020                                    OSSL_STORE_INFO_get1_CERT(info),
1021                                    X509_ADD_FLAG_DEFAULT);
1022             ncerts += ok;
1023             break;
1024         case OSSL_STORE_INFO_CRL:
1025             if (pcrl != NULL && *pcrl == NULL) {
1026                 ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL;
1027                 cnt_expectations -= ok;
1028             }
1029             else if (pcrls != NULL)
1030                 ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info));
1031             ncrls += ok;
1032             break;
1033         default:
1034             /* skip any other type */
1035             break;
1036         }
1037         OSSL_STORE_INFO_free(info);
1038         if (!ok) {
1039             failed = info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
1040             BIO_printf(bio_err, "Error reading");
1041             break;
1042         }
1043     }
1044 
1045  end:
1046     OSSL_STORE_close(ctx);
1047     if (failed == NULL) {
1048         int any = 0;
1049 
1050         if ((ppkey != NULL && *ppkey == NULL)
1051             || (ppubkey != NULL && *ppubkey == NULL)) {
1052             failed = "key";
1053         } else if (pparams != NULL && *pparams == NULL) {
1054             failed = "params";
1055         } else if ((pcert != NULL || pcerts != NULL) && ncerts == 0) {
1056             if (pcert == NULL)
1057                 any = 1;
1058             failed = "cert";
1059         } else if ((pcrl != NULL || pcrls != NULL) && ncrls == 0) {
1060             if (pcrl == NULL)
1061                 any = 1;
1062             failed = "CRL";
1063         }
1064         if (!suppress_decode_errors) {
1065             if (failed != NULL)
1066                 BIO_printf(bio_err, "Could not read");
1067             if (any)
1068                 BIO_printf(bio_err, " any");
1069         }
1070     }
1071     if (!suppress_decode_errors && failed != NULL) {
1072         if (desc != NULL && strstr(desc, failed) != NULL) {
1073             BIO_printf(bio_err, " %s", desc);
1074         } else {
1075             BIO_printf(bio_err, " %s", failed);
1076             if (desc != NULL)
1077                 BIO_printf(bio_err, " of %s", desc);
1078         }
1079         if (uri != NULL)
1080             BIO_printf(bio_err, " from %s", uri);
1081         BIO_printf(bio_err, "\n");
1082         ERR_print_errors(bio_err);
1083     }
1084     if (suppress_decode_errors || failed == NULL)
1085         /* clear any spurious errors */
1086         ERR_clear_error();
1087     return failed == NULL;
1088 }
1089 
1090 int load_key_certs_crls(const char *uri, int format, int maybe_stdin,
1091                         const char *pass, const char *desc,
1092                         EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
1093                         EVP_PKEY **pparams,
1094                         X509 **pcert, STACK_OF(X509) **pcerts,
1095                         X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
1096 {
1097     return load_key_certs_crls_suppress(uri, format, maybe_stdin, pass, desc,
1098                                         ppkey, ppubkey, pparams, pcert, pcerts,
1099                                         pcrl, pcrls, 0);
1100 }
1101 
1102 #define X509V3_EXT_UNKNOWN_MASK         (0xfL << 16)
1103 /* Return error for unknown extensions */
1104 #define X509V3_EXT_DEFAULT              0
1105 /* Print error for unknown extensions */
1106 #define X509V3_EXT_ERROR_UNKNOWN        (1L << 16)
1107 /* ASN1 parse unknown extensions */
1108 #define X509V3_EXT_PARSE_UNKNOWN        (2L << 16)
1109 /* BIO_dump unknown extensions */
1110 #define X509V3_EXT_DUMP_UNKNOWN         (3L << 16)
1111 
1112 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1113                          X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1114 
1115 int set_cert_ex(unsigned long *flags, const char *arg)
1116 {
1117     static const NAME_EX_TBL cert_tbl[] = {
1118         {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
1119         {"ca_default", X509_FLAG_CA, 0xffffffffl},
1120         {"no_header", X509_FLAG_NO_HEADER, 0},
1121         {"no_version", X509_FLAG_NO_VERSION, 0},
1122         {"no_serial", X509_FLAG_NO_SERIAL, 0},
1123         {"no_signame", X509_FLAG_NO_SIGNAME, 0},
1124         {"no_validity", X509_FLAG_NO_VALIDITY, 0},
1125         {"no_subject", X509_FLAG_NO_SUBJECT, 0},
1126         {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1127         {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1128         {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1129         {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1130         {"no_aux", X509_FLAG_NO_AUX, 0},
1131         {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1132         {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1133         {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1134         {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1135         {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1136         {NULL, 0, 0}
1137     };
1138     return set_multi_opts(flags, arg, cert_tbl);
1139 }
1140 
1141 int set_name_ex(unsigned long *flags, const char *arg)
1142 {
1143     static const NAME_EX_TBL ex_tbl[] = {
1144         {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1145         {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
1146         {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1147         {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1148         {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1149         {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1150         {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1151         {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1152         {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1153         {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1154         {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1155         {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1156         {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1157         {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1158         {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1159         {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1160         {"dn_rev", XN_FLAG_DN_REV, 0},
1161         {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1162         {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1163         {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1164         {"align", XN_FLAG_FN_ALIGN, 0},
1165         {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1166         {"space_eq", XN_FLAG_SPC_EQ, 0},
1167         {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1168         {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1169         {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1170         {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1171         {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1172         {NULL, 0, 0}
1173     };
1174     if (set_multi_opts(flags, arg, ex_tbl) == 0)
1175         return 0;
1176     if (*flags != XN_FLAG_COMPAT
1177         && (*flags & XN_FLAG_SEP_MASK) == 0)
1178         *flags |= XN_FLAG_SEP_CPLUS_SPC;
1179     return 1;
1180 }
1181 
1182 int set_dateopt(unsigned long *dateopt, const char *arg)
1183 {
1184     if (OPENSSL_strcasecmp(arg, "rfc_822") == 0)
1185         *dateopt = ASN1_DTFLGS_RFC822;
1186     else if (OPENSSL_strcasecmp(arg, "iso_8601") == 0)
1187         *dateopt = ASN1_DTFLGS_ISO8601;
1188     else
1189         return 0;
1190     return 1;
1191 }
1192 
1193 int set_ext_copy(int *copy_type, const char *arg)
1194 {
1195     if (OPENSSL_strcasecmp(arg, "none") == 0)
1196         *copy_type = EXT_COPY_NONE;
1197     else if (OPENSSL_strcasecmp(arg, "copy") == 0)
1198         *copy_type = EXT_COPY_ADD;
1199     else if (OPENSSL_strcasecmp(arg, "copyall") == 0)
1200         *copy_type = EXT_COPY_ALL;
1201     else
1202         return 0;
1203     return 1;
1204 }
1205 
1206 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1207 {
1208     STACK_OF(X509_EXTENSION) *exts;
1209     int i, ret = 0;
1210 
1211     if (x == NULL || req == NULL)
1212         return 0;
1213     if (copy_type == EXT_COPY_NONE)
1214         return 1;
1215     exts = X509_REQ_get_extensions(req);
1216 
1217     for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1218         X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
1219         ASN1_OBJECT *obj = X509_EXTENSION_get_object(ext);
1220         int idx = X509_get_ext_by_OBJ(x, obj, -1);
1221 
1222         /* Does extension exist in target? */
1223         if (idx != -1) {
1224             /* If normal copy don't override existing extension */
1225             if (copy_type == EXT_COPY_ADD)
1226                 continue;
1227             /* Delete all extensions of same type */
1228             do {
1229                 X509_EXTENSION_free(X509_delete_ext(x, idx));
1230                 idx = X509_get_ext_by_OBJ(x, obj, -1);
1231             } while (idx != -1);
1232         }
1233         if (!X509_add_ext(x, ext, -1))
1234             goto end;
1235     }
1236     ret = 1;
1237 
1238  end:
1239     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1240     return ret;
1241 }
1242 
1243 static int set_multi_opts(unsigned long *flags, const char *arg,
1244                           const NAME_EX_TBL * in_tbl)
1245 {
1246     STACK_OF(CONF_VALUE) *vals;
1247     CONF_VALUE *val;
1248     int i, ret = 1;
1249     if (!arg)
1250         return 0;
1251     vals = X509V3_parse_list(arg);
1252     for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1253         val = sk_CONF_VALUE_value(vals, i);
1254         if (!set_table_opts(flags, val->name, in_tbl))
1255             ret = 0;
1256     }
1257     sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1258     return ret;
1259 }
1260 
1261 static int set_table_opts(unsigned long *flags, const char *arg,
1262                           const NAME_EX_TBL * in_tbl)
1263 {
1264     char c;
1265     const NAME_EX_TBL *ptbl;
1266     c = arg[0];
1267 
1268     if (c == '-') {
1269         c = 0;
1270         arg++;
1271     } else if (c == '+') {
1272         c = 1;
1273         arg++;
1274     } else {
1275         c = 1;
1276     }
1277 
1278     for (ptbl = in_tbl; ptbl->name; ptbl++) {
1279         if (OPENSSL_strcasecmp(arg, ptbl->name) == 0) {
1280             *flags &= ~ptbl->mask;
1281             if (c)
1282                 *flags |= ptbl->flag;
1283             else
1284                 *flags &= ~ptbl->flag;
1285             return 1;
1286         }
1287     }
1288     return 0;
1289 }
1290 
1291 void print_name(BIO *out, const char *title, const X509_NAME *nm)
1292 {
1293     char *buf;
1294     char mline = 0;
1295     int indent = 0;
1296     unsigned long lflags = get_nameopt();
1297 
1298     if (out == NULL)
1299         return;
1300     if (title != NULL)
1301         BIO_puts(out, title);
1302     if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1303         mline = 1;
1304         indent = 4;
1305     }
1306     if (lflags == XN_FLAG_COMPAT) {
1307         buf = X509_NAME_oneline(nm, 0, 0);
1308         BIO_puts(out, buf);
1309         BIO_puts(out, "\n");
1310         OPENSSL_free(buf);
1311     } else {
1312         if (mline)
1313             BIO_puts(out, "\n");
1314         X509_NAME_print_ex(out, nm, indent, lflags);
1315         BIO_puts(out, "\n");
1316     }
1317 }
1318 
1319 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1320                       int len, unsigned char *buffer)
1321 {
1322     BIO_printf(out, "    static unsigned char %s_%d[] = {", var, len);
1323     if (BN_is_zero(in)) {
1324         BIO_printf(out, "\n        0x00");
1325     } else {
1326         int i, l;
1327 
1328         l = BN_bn2bin(in, buffer);
1329         for (i = 0; i < l; i++) {
1330             BIO_printf(out, (i % 10) == 0 ? "\n        " : " ");
1331             if (i < l - 1)
1332                 BIO_printf(out, "0x%02X,", buffer[i]);
1333             else
1334                 BIO_printf(out, "0x%02X", buffer[i]);
1335         }
1336     }
1337     BIO_printf(out, "\n    };\n");
1338 }
1339 
1340 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1341 {
1342     int i;
1343 
1344     BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1345     for (i = 0; i < len; i++) {
1346         if ((i % 10) == 0)
1347             BIO_printf(out, "\n    ");
1348         if (i < len - 1)
1349             BIO_printf(out, "0x%02X, ", d[i]);
1350         else
1351             BIO_printf(out, "0x%02X", d[i]);
1352     }
1353     BIO_printf(out, "\n};\n");
1354 }
1355 
1356 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1357                          const char *CApath, int noCApath,
1358                          const char *CAstore, int noCAstore)
1359 {
1360     X509_STORE *store = X509_STORE_new();
1361     X509_LOOKUP *lookup;
1362     OSSL_LIB_CTX *libctx = app_get0_libctx();
1363     const char *propq = app_get0_propq();
1364 
1365     if (store == NULL)
1366         goto end;
1367 
1368     if (CAfile != NULL || !noCAfile) {
1369         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1370         if (lookup == NULL)
1371             goto end;
1372         if (CAfile != NULL) {
1373             if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM,
1374                                           libctx, propq) <= 0) {
1375                 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1376                 goto end;
1377             }
1378         } else {
1379             X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT,
1380                                      libctx, propq);
1381         }
1382     }
1383 
1384     if (CApath != NULL || !noCApath) {
1385         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1386         if (lookup == NULL)
1387             goto end;
1388         if (CApath != NULL) {
1389             if (X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM) <= 0) {
1390                 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1391                 goto end;
1392             }
1393         } else {
1394             X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1395         }
1396     }
1397 
1398     if (CAstore != NULL || !noCAstore) {
1399         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1400         if (lookup == NULL)
1401             goto end;
1402         if (!X509_LOOKUP_add_store_ex(lookup, CAstore, libctx, propq)) {
1403             if (CAstore != NULL)
1404                 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1405             goto end;
1406         }
1407     }
1408 
1409     ERR_clear_error();
1410     return store;
1411  end:
1412     ERR_print_errors(bio_err);
1413     X509_STORE_free(store);
1414     return NULL;
1415 }
1416 
1417 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1418 {
1419     const char *n;
1420 
1421     n = a[DB_serial];
1422     while (*n == '0')
1423         n++;
1424     return OPENSSL_LH_strhash(n);
1425 }
1426 
1427 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1428                             const OPENSSL_CSTRING *b)
1429 {
1430     const char *aa, *bb;
1431 
1432     for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1433     for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1434     return strcmp(aa, bb);
1435 }
1436 
1437 static int index_name_qual(char **a)
1438 {
1439     return (a[0][0] == 'V');
1440 }
1441 
1442 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1443 {
1444     return OPENSSL_LH_strhash(a[DB_name]);
1445 }
1446 
1447 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1448 {
1449     return strcmp(a[DB_name], b[DB_name]);
1450 }
1451 
1452 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1453 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1454 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1455 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1456 #undef BSIZE
1457 #define BSIZE 256
1458 BIGNUM *load_serial(const char *serialfile, int *exists, int create,
1459                     ASN1_INTEGER **retai)
1460 {
1461     BIO *in = NULL;
1462     BIGNUM *ret = NULL;
1463     char buf[1024];
1464     ASN1_INTEGER *ai = NULL;
1465 
1466     ai = ASN1_INTEGER_new();
1467     if (ai == NULL)
1468         goto err;
1469 
1470     in = BIO_new_file(serialfile, "r");
1471     if (exists != NULL)
1472         *exists = in != NULL;
1473     if (in == NULL) {
1474         if (!create) {
1475             perror(serialfile);
1476             goto err;
1477         }
1478         ERR_clear_error();
1479         ret = BN_new();
1480         if (ret == NULL) {
1481             BIO_printf(bio_err, "Out of memory\n");
1482         } else if (!rand_serial(ret, ai)) {
1483             BIO_printf(bio_err, "Error creating random number to store in %s\n",
1484                        serialfile);
1485             BN_free(ret);
1486             ret = NULL;
1487         }
1488     } else {
1489         if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1490             BIO_printf(bio_err, "Unable to load number from %s\n",
1491                        serialfile);
1492             goto err;
1493         }
1494         ret = ASN1_INTEGER_to_BN(ai, NULL);
1495         if (ret == NULL) {
1496             BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1497             goto err;
1498         }
1499     }
1500 
1501     if (ret != NULL && retai != NULL) {
1502         *retai = ai;
1503         ai = NULL;
1504     }
1505  err:
1506     if (ret == NULL)
1507         ERR_print_errors(bio_err);
1508     BIO_free(in);
1509     ASN1_INTEGER_free(ai);
1510     return ret;
1511 }
1512 
1513 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1514                 ASN1_INTEGER **retai)
1515 {
1516     char buf[1][BSIZE];
1517     BIO *out = NULL;
1518     int ret = 0;
1519     ASN1_INTEGER *ai = NULL;
1520     int j;
1521 
1522     if (suffix == NULL)
1523         j = strlen(serialfile);
1524     else
1525         j = strlen(serialfile) + strlen(suffix) + 1;
1526     if (j >= BSIZE) {
1527         BIO_printf(bio_err, "File name too long\n");
1528         goto err;
1529     }
1530 
1531     if (suffix == NULL)
1532         OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1533     else {
1534 #ifndef OPENSSL_SYS_VMS
1535         j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1536 #else
1537         j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1538 #endif
1539     }
1540     out = BIO_new_file(buf[0], "w");
1541     if (out == NULL) {
1542         goto err;
1543     }
1544 
1545     if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1546         BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1547         goto err;
1548     }
1549     i2a_ASN1_INTEGER(out, ai);
1550     BIO_puts(out, "\n");
1551     ret = 1;
1552     if (retai) {
1553         *retai = ai;
1554         ai = NULL;
1555     }
1556  err:
1557     if (!ret)
1558         ERR_print_errors(bio_err);
1559     BIO_free_all(out);
1560     ASN1_INTEGER_free(ai);
1561     return ret;
1562 }
1563 
1564 int rotate_serial(const char *serialfile, const char *new_suffix,
1565                   const char *old_suffix)
1566 {
1567     char buf[2][BSIZE];
1568     int i, j;
1569 
1570     i = strlen(serialfile) + strlen(old_suffix);
1571     j = strlen(serialfile) + strlen(new_suffix);
1572     if (i > j)
1573         j = i;
1574     if (j + 1 >= BSIZE) {
1575         BIO_printf(bio_err, "File name too long\n");
1576         goto err;
1577     }
1578 #ifndef OPENSSL_SYS_VMS
1579     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1580     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1581 #else
1582     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1583     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1584 #endif
1585     if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1586 #ifdef ENOTDIR
1587         && errno != ENOTDIR
1588 #endif
1589         ) {
1590         BIO_printf(bio_err,
1591                    "Unable to rename %s to %s\n", serialfile, buf[1]);
1592         perror("reason");
1593         goto err;
1594     }
1595     if (rename(buf[0], serialfile) < 0) {
1596         BIO_printf(bio_err,
1597                    "Unable to rename %s to %s\n", buf[0], serialfile);
1598         perror("reason");
1599         rename(buf[1], serialfile);
1600         goto err;
1601     }
1602     return 1;
1603  err:
1604     ERR_print_errors(bio_err);
1605     return 0;
1606 }
1607 
1608 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1609 {
1610     BIGNUM *btmp;
1611     int ret = 0;
1612 
1613     btmp = b == NULL ? BN_new() : b;
1614     if (btmp == NULL)
1615         return 0;
1616 
1617     if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1618         goto error;
1619     if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1620         goto error;
1621 
1622     ret = 1;
1623 
1624  error:
1625 
1626     if (btmp != b)
1627         BN_free(btmp);
1628 
1629     return ret;
1630 }
1631 
1632 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1633 {
1634     CA_DB *retdb = NULL;
1635     TXT_DB *tmpdb = NULL;
1636     BIO *in;
1637     CONF *dbattr_conf = NULL;
1638     char buf[BSIZE];
1639 #ifndef OPENSSL_NO_POSIX_IO
1640     FILE *dbfp;
1641     struct stat dbst;
1642 #endif
1643 
1644     in = BIO_new_file(dbfile, "r");
1645     if (in == NULL)
1646         goto err;
1647 
1648 #ifndef OPENSSL_NO_POSIX_IO
1649     BIO_get_fp(in, &dbfp);
1650     if (fstat(fileno(dbfp), &dbst) == -1) {
1651         ERR_raise_data(ERR_LIB_SYS, errno,
1652                        "calling fstat(%s)", dbfile);
1653         goto err;
1654     }
1655 #endif
1656 
1657     if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1658         goto err;
1659 
1660 #ifndef OPENSSL_SYS_VMS
1661     BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1662 #else
1663     BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1664 #endif
1665     dbattr_conf = app_load_config_quiet(buf);
1666 
1667     retdb = app_malloc(sizeof(*retdb), "new DB");
1668     retdb->db = tmpdb;
1669     tmpdb = NULL;
1670     if (db_attr)
1671         retdb->attributes = *db_attr;
1672     else {
1673         retdb->attributes.unique_subject = 1;
1674     }
1675 
1676     if (dbattr_conf) {
1677         char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1678         if (p) {
1679             retdb->attributes.unique_subject = parse_yesno(p, 1);
1680         } else {
1681             ERR_clear_error();
1682         }
1683 
1684     }
1685 
1686     retdb->dbfname = OPENSSL_strdup(dbfile);
1687 #ifndef OPENSSL_NO_POSIX_IO
1688     retdb->dbst = dbst;
1689 #endif
1690 
1691  err:
1692     ERR_print_errors(bio_err);
1693     NCONF_free(dbattr_conf);
1694     TXT_DB_free(tmpdb);
1695     BIO_free_all(in);
1696     return retdb;
1697 }
1698 
1699 /*
1700  * Returns > 0 on success, <= 0 on error
1701  */
1702 int index_index(CA_DB *db)
1703 {
1704     if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1705                              LHASH_HASH_FN(index_serial),
1706                              LHASH_COMP_FN(index_serial))) {
1707         BIO_printf(bio_err,
1708                    "Error creating serial number index:(%ld,%ld,%ld)\n",
1709                    db->db->error, db->db->arg1, db->db->arg2);
1710         goto err;
1711     }
1712 
1713     if (db->attributes.unique_subject
1714         && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1715                                 LHASH_HASH_FN(index_name),
1716                                 LHASH_COMP_FN(index_name))) {
1717         BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1718                    db->db->error, db->db->arg1, db->db->arg2);
1719         goto err;
1720     }
1721     return 1;
1722  err:
1723     ERR_print_errors(bio_err);
1724     return 0;
1725 }
1726 
1727 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1728 {
1729     char buf[3][BSIZE];
1730     BIO *out;
1731     int j;
1732 
1733     j = strlen(dbfile) + strlen(suffix);
1734     if (j + 6 >= BSIZE) {
1735         BIO_printf(bio_err, "File name too long\n");
1736         goto err;
1737     }
1738 #ifndef OPENSSL_SYS_VMS
1739     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1740     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1741     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1742 #else
1743     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1744     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1745     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1746 #endif
1747     out = BIO_new_file(buf[0], "w");
1748     if (out == NULL) {
1749         perror(dbfile);
1750         BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1751         goto err;
1752     }
1753     j = TXT_DB_write(out, db->db);
1754     BIO_free(out);
1755     if (j <= 0)
1756         goto err;
1757 
1758     out = BIO_new_file(buf[1], "w");
1759     if (out == NULL) {
1760         perror(buf[2]);
1761         BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1762         goto err;
1763     }
1764     BIO_printf(out, "unique_subject = %s\n",
1765                db->attributes.unique_subject ? "yes" : "no");
1766     BIO_free(out);
1767 
1768     return 1;
1769  err:
1770     ERR_print_errors(bio_err);
1771     return 0;
1772 }
1773 
1774 int rotate_index(const char *dbfile, const char *new_suffix,
1775                  const char *old_suffix)
1776 {
1777     char buf[5][BSIZE];
1778     int i, j;
1779 
1780     i = strlen(dbfile) + strlen(old_suffix);
1781     j = strlen(dbfile) + strlen(new_suffix);
1782     if (i > j)
1783         j = i;
1784     if (j + 6 >= BSIZE) {
1785         BIO_printf(bio_err, "File name too long\n");
1786         goto err;
1787     }
1788 #ifndef OPENSSL_SYS_VMS
1789     j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1790     j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1791     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1792     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1793     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1794 #else
1795     j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1796     j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1797     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1798     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1799     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1800 #endif
1801     if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1802 #ifdef ENOTDIR
1803         && errno != ENOTDIR
1804 #endif
1805         ) {
1806         BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1807         perror("reason");
1808         goto err;
1809     }
1810     if (rename(buf[0], dbfile) < 0) {
1811         BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1812         perror("reason");
1813         rename(buf[1], dbfile);
1814         goto err;
1815     }
1816     if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1817 #ifdef ENOTDIR
1818         && errno != ENOTDIR
1819 #endif
1820         ) {
1821         BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1822         perror("reason");
1823         rename(dbfile, buf[0]);
1824         rename(buf[1], dbfile);
1825         goto err;
1826     }
1827     if (rename(buf[2], buf[4]) < 0) {
1828         BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1829         perror("reason");
1830         rename(buf[3], buf[4]);
1831         rename(dbfile, buf[0]);
1832         rename(buf[1], dbfile);
1833         goto err;
1834     }
1835     return 1;
1836  err:
1837     ERR_print_errors(bio_err);
1838     return 0;
1839 }
1840 
1841 void free_index(CA_DB *db)
1842 {
1843     if (db) {
1844         TXT_DB_free(db->db);
1845         OPENSSL_free(db->dbfname);
1846         OPENSSL_free(db);
1847     }
1848 }
1849 
1850 int parse_yesno(const char *str, int def)
1851 {
1852     if (str) {
1853         switch (*str) {
1854         case 'f':              /* false */
1855         case 'F':              /* FALSE */
1856         case 'n':              /* no */
1857         case 'N':              /* NO */
1858         case '0':              /* 0 */
1859             return 0;
1860         case 't':              /* true */
1861         case 'T':              /* TRUE */
1862         case 'y':              /* yes */
1863         case 'Y':              /* YES */
1864         case '1':              /* 1 */
1865             return 1;
1866         }
1867     }
1868     return def;
1869 }
1870 
1871 /*
1872  * name is expected to be in the format /type0=value0/type1=value1/type2=...
1873  * where + can be used instead of / to form multi-valued RDNs if canmulti
1874  * and characters may be escaped by \
1875  */
1876 X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
1877                       const char *desc)
1878 {
1879     int nextismulti = 0;
1880     char *work;
1881     X509_NAME *n;
1882 
1883     if (*cp++ != '/') {
1884         BIO_printf(bio_err,
1885                    "%s: %s name is expected to be in the format "
1886                    "/type0=value0/type1=value1/type2=... where characters may "
1887                    "be escaped by \\. This name is not in that format: '%s'\n",
1888                    opt_getprog(), desc, --cp);
1889         return NULL;
1890     }
1891 
1892     n = X509_NAME_new();
1893     if (n == NULL) {
1894         BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
1895         return NULL;
1896     }
1897     work = OPENSSL_strdup(cp);
1898     if (work == NULL) {
1899         BIO_printf(bio_err, "%s: Error copying %s name input\n",
1900                    opt_getprog(), desc);
1901         goto err;
1902     }
1903 
1904     while (*cp != '\0') {
1905         char *bp = work;
1906         char *typestr = bp;
1907         unsigned char *valstr;
1908         int nid;
1909         int ismulti = nextismulti;
1910         nextismulti = 0;
1911 
1912         /* Collect the type */
1913         while (*cp != '\0' && *cp != '=')
1914             *bp++ = *cp++;
1915         *bp++ = '\0';
1916         if (*cp == '\0') {
1917             BIO_printf(bio_err,
1918                        "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1919                        opt_getprog(), typestr, desc);
1920             goto err;
1921         }
1922         ++cp;
1923 
1924         /* Collect the value. */
1925         valstr = (unsigned char *)bp;
1926         for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
1927             /* unescaped '+' symbol string signals further member of multiRDN */
1928             if (canmulti && *cp == '+') {
1929                 nextismulti = 1;
1930                 break;
1931             }
1932             if (*cp == '\\' && *++cp == '\0') {
1933                 BIO_printf(bio_err,
1934                            "%s: Escape character at end of %s name string\n",
1935                            opt_getprog(), desc);
1936                 goto err;
1937             }
1938         }
1939         *bp++ = '\0';
1940 
1941         /* If not at EOS (must be + or /), move forward. */
1942         if (*cp != '\0')
1943             ++cp;
1944 
1945         /* Parse */
1946         nid = OBJ_txt2nid(typestr);
1947         if (nid == NID_undef) {
1948             BIO_printf(bio_err,
1949                        "%s warning: Skipping unknown %s name attribute \"%s\"\n",
1950                        opt_getprog(), desc, typestr);
1951             if (ismulti)
1952                 BIO_printf(bio_err,
1953                            "%s hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n",
1954                            opt_getprog());
1955             continue;
1956         }
1957         if (*valstr == '\0') {
1958             BIO_printf(bio_err,
1959                        "%s warning: No value provided for %s name attribute \"%s\", skipped\n",
1960                        opt_getprog(), desc, typestr);
1961             continue;
1962         }
1963         if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1964                                         valstr, strlen((char *)valstr),
1965                                         -1, ismulti ? -1 : 0)) {
1966             ERR_print_errors(bio_err);
1967             BIO_printf(bio_err,
1968                        "%s: Error adding %s name attribute \"/%s=%s\"\n",
1969                        opt_getprog(), desc, typestr ,valstr);
1970             goto err;
1971         }
1972     }
1973 
1974     OPENSSL_free(work);
1975     return n;
1976 
1977  err:
1978     X509_NAME_free(n);
1979     OPENSSL_free(work);
1980     return NULL;
1981 }
1982 
1983 /*
1984  * Read whole contents of a BIO into an allocated memory buffer and return
1985  * it.
1986  */
1987 
1988 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1989 {
1990     BIO *mem;
1991     int len, ret;
1992     unsigned char tbuf[1024];
1993 
1994     mem = BIO_new(BIO_s_mem());
1995     if (mem == NULL)
1996         return -1;
1997     for (;;) {
1998         if ((maxlen != -1) && maxlen < 1024)
1999             len = maxlen;
2000         else
2001             len = 1024;
2002         len = BIO_read(in, tbuf, len);
2003         if (len < 0) {
2004             BIO_free(mem);
2005             return -1;
2006         }
2007         if (len == 0)
2008             break;
2009         if (BIO_write(mem, tbuf, len) != len) {
2010             BIO_free(mem);
2011             return -1;
2012         }
2013         if (maxlen != -1)
2014             maxlen -= len;
2015 
2016         if (maxlen == 0)
2017             break;
2018     }
2019     ret = BIO_get_mem_data(mem, (char **)out);
2020     BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
2021     BIO_free(mem);
2022     return ret;
2023 }
2024 
2025 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
2026 {
2027     int rv = 0;
2028     char *stmp, *vtmp = NULL;
2029 
2030     stmp = OPENSSL_strdup(value);
2031     if (stmp == NULL)
2032         return -1;
2033     vtmp = strchr(stmp, ':');
2034     if (vtmp == NULL)
2035         goto err;
2036 
2037     *vtmp = 0;
2038     vtmp++;
2039     rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
2040 
2041  err:
2042     OPENSSL_free(stmp);
2043     return rv;
2044 }
2045 
2046 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
2047 {
2048     X509_POLICY_NODE *node;
2049     int i;
2050 
2051     BIO_printf(bio_err, "%s Policies:", name);
2052     if (nodes) {
2053         BIO_puts(bio_err, "\n");
2054         for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
2055             node = sk_X509_POLICY_NODE_value(nodes, i);
2056             X509_POLICY_NODE_print(bio_err, node, 2);
2057         }
2058     } else {
2059         BIO_puts(bio_err, " <empty>\n");
2060     }
2061 }
2062 
2063 void policies_print(X509_STORE_CTX *ctx)
2064 {
2065     X509_POLICY_TREE *tree;
2066     int explicit_policy;
2067     tree = X509_STORE_CTX_get0_policy_tree(ctx);
2068     explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2069 
2070     BIO_printf(bio_err, "Require explicit Policy: %s\n",
2071                explicit_policy ? "True" : "False");
2072 
2073     nodes_print("Authority", X509_policy_tree_get0_policies(tree));
2074     nodes_print("User", X509_policy_tree_get0_user_policies(tree));
2075 }
2076 
2077 /*-
2078  * next_protos_parse parses a comma separated list of strings into a string
2079  * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
2080  *   outlen: (output) set to the length of the resulting buffer on success.
2081  *   err: (maybe NULL) on failure, an error message line is written to this BIO.
2082  *   in: a NUL terminated string like "abc,def,ghi"
2083  *
2084  *   returns: a malloc'd buffer or NULL on failure.
2085  */
2086 unsigned char *next_protos_parse(size_t *outlen, const char *in)
2087 {
2088     size_t len;
2089     unsigned char *out;
2090     size_t i, start = 0;
2091     size_t skipped = 0;
2092 
2093     len = strlen(in);
2094     if (len == 0 || len >= 65535)
2095         return NULL;
2096 
2097     out = app_malloc(len + 1, "NPN buffer");
2098     for (i = 0; i <= len; ++i) {
2099         if (i == len || in[i] == ',') {
2100             /*
2101              * Zero-length ALPN elements are invalid on the wire, we could be
2102              * strict and reject the entire string, but just ignoring extra
2103              * commas seems harmless and more friendly.
2104              *
2105              * Every comma we skip in this way puts the input buffer another
2106              * byte ahead of the output buffer, so all stores into the output
2107              * buffer need to be decremented by the number commas skipped.
2108              */
2109             if (i == start) {
2110                 ++start;
2111                 ++skipped;
2112                 continue;
2113             }
2114             if (i - start > 255) {
2115                 OPENSSL_free(out);
2116                 return NULL;
2117             }
2118             out[start-skipped] = (unsigned char)(i - start);
2119             start = i + 1;
2120         } else {
2121             out[i + 1 - skipped] = in[i];
2122         }
2123     }
2124 
2125     if (len <= skipped) {
2126         OPENSSL_free(out);
2127         return NULL;
2128     }
2129 
2130     *outlen = len + 1 - skipped;
2131     return out;
2132 }
2133 
2134 void print_cert_checks(BIO *bio, X509 *x,
2135                        const char *checkhost,
2136                        const char *checkemail, const char *checkip)
2137 {
2138     if (x == NULL)
2139         return;
2140     if (checkhost) {
2141         BIO_printf(bio, "Hostname %s does%s match certificate\n",
2142                    checkhost,
2143                    X509_check_host(x, checkhost, 0, 0, NULL) == 1
2144                        ? "" : " NOT");
2145     }
2146 
2147     if (checkemail) {
2148         BIO_printf(bio, "Email %s does%s match certificate\n",
2149                    checkemail, X509_check_email(x, checkemail, 0, 0)
2150                    ? "" : " NOT");
2151     }
2152 
2153     if (checkip) {
2154         BIO_printf(bio, "IP %s does%s match certificate\n",
2155                    checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
2156     }
2157 }
2158 
2159 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
2160 {
2161     int i;
2162 
2163     if (opts == NULL)
2164         return 1;
2165 
2166     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2167         char *opt = sk_OPENSSL_STRING_value(opts, i);
2168         if (pkey_ctrl_string(pkctx, opt) <= 0) {
2169             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2170             ERR_print_errors(bio_err);
2171             return 0;
2172         }
2173     }
2174 
2175     return 1;
2176 }
2177 
2178 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
2179 {
2180     int i;
2181 
2182     if (opts == NULL)
2183         return 1;
2184 
2185     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2186         char *opt = sk_OPENSSL_STRING_value(opts, i);
2187         if (x509_ctrl_string(x, opt) <= 0) {
2188             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2189             ERR_print_errors(bio_err);
2190             return 0;
2191         }
2192     }
2193 
2194     return 1;
2195 }
2196 
2197 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
2198 {
2199     int i;
2200 
2201     if (opts == NULL)
2202         return 1;
2203 
2204     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2205         char *opt = sk_OPENSSL_STRING_value(opts, i);
2206         if (x509_req_ctrl_string(x, opt) <= 0) {
2207             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2208             ERR_print_errors(bio_err);
2209             return 0;
2210         }
2211     }
2212 
2213     return 1;
2214 }
2215 
2216 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
2217                         const char *md, STACK_OF(OPENSSL_STRING) *sigopts)
2218 {
2219     EVP_PKEY_CTX *pkctx = NULL;
2220     char def_md[80];
2221 
2222     if (ctx == NULL)
2223         return 0;
2224     /*
2225      * EVP_PKEY_get_default_digest_name() returns 2 if the digest is mandatory
2226      * for this algorithm.
2227      */
2228     if (EVP_PKEY_get_default_digest_name(pkey, def_md, sizeof(def_md)) == 2
2229             && strcmp(def_md, "UNDEF") == 0) {
2230         /* The signing algorithm requires there to be no digest */
2231         md = NULL;
2232     }
2233 
2234     return EVP_DigestSignInit_ex(ctx, &pkctx, md, app_get0_libctx(),
2235                                  app_get0_propq(), pkey, NULL)
2236         && do_pkey_ctx_init(pkctx, sigopts);
2237 }
2238 
2239 static int adapt_keyid_ext(X509 *cert, X509V3_CTX *ext_ctx,
2240                            const char *name, const char *value, int add_default)
2241 {
2242     const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
2243     X509_EXTENSION *new_ext = X509V3_EXT_nconf(NULL, ext_ctx, name, value);
2244     int idx, rv = 0;
2245 
2246     if (new_ext == NULL)
2247         return rv;
2248 
2249     idx = X509v3_get_ext_by_OBJ(exts, X509_EXTENSION_get_object(new_ext), -1);
2250     if (idx >= 0) {
2251         X509_EXTENSION *found_ext = X509v3_get_ext(exts, idx);
2252         ASN1_OCTET_STRING *data = X509_EXTENSION_get_data(found_ext);
2253         int disabled = ASN1_STRING_length(data) <= 2; /* config said "none" */
2254 
2255         if (disabled) {
2256             X509_delete_ext(cert, idx);
2257             X509_EXTENSION_free(found_ext);
2258         } /* else keep existing key identifier, which might be outdated */
2259         rv = 1;
2260     } else  {
2261         rv = !add_default || X509_add_ext(cert, new_ext, -1);
2262     }
2263     X509_EXTENSION_free(new_ext);
2264     return rv;
2265 }
2266 
2267 /* Ensure RFC 5280 compliance, adapt keyIDs as needed, and sign the cert info */
2268 int do_X509_sign(X509 *cert, EVP_PKEY *pkey, const char *md,
2269                  STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx)
2270 {
2271     const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
2272     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2273     int self_sign;
2274     int rv = 0;
2275 
2276     if (sk_X509_EXTENSION_num(exts /* may be NULL */) > 0) {
2277         /* Prevent X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 */
2278         if (!X509_set_version(cert, X509_VERSION_3))
2279             goto end;
2280 
2281         /*
2282          * Add default SKID before such that default AKID can make use of it
2283          * in case the certificate is self-signed
2284          */
2285         /* Prevent X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER */
2286         if (!adapt_keyid_ext(cert, ext_ctx, "subjectKeyIdentifier", "hash", 1))
2287             goto end;
2288         /* Prevent X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER */
2289         ERR_set_mark();
2290         self_sign = X509_check_private_key(cert, pkey);
2291         ERR_pop_to_mark();
2292         if (!adapt_keyid_ext(cert, ext_ctx, "authorityKeyIdentifier",
2293                              "keyid, issuer", !self_sign))
2294             goto end;
2295     }
2296 
2297     if (mctx != NULL && do_sign_init(mctx, pkey, md, sigopts) > 0)
2298         rv = (X509_sign_ctx(cert, mctx) > 0);
2299  end:
2300     EVP_MD_CTX_free(mctx);
2301     return rv;
2302 }
2303 
2304 /* Sign the certificate request info */
2305 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md,
2306                      STACK_OF(OPENSSL_STRING) *sigopts)
2307 {
2308     int rv = 0;
2309     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2310 
2311     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2312         rv = (X509_REQ_sign_ctx(x, mctx) > 0);
2313     EVP_MD_CTX_free(mctx);
2314     return rv;
2315 }
2316 
2317 /* Sign the CRL info */
2318 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md,
2319                      STACK_OF(OPENSSL_STRING) *sigopts)
2320 {
2321     int rv = 0;
2322     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2323 
2324     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2325         rv = (X509_CRL_sign_ctx(x, mctx) > 0);
2326     EVP_MD_CTX_free(mctx);
2327     return rv;
2328 }
2329 
2330 /*
2331  * do_X509_verify returns 1 if the signature is valid,
2332  * 0 if the signature check fails, or -1 if error occurs.
2333  */
2334 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
2335 {
2336     int rv = 0;
2337 
2338     if (do_x509_init(x, vfyopts) > 0)
2339         rv = X509_verify(x, pkey);
2340     else
2341         rv = -1;
2342     return rv;
2343 }
2344 
2345 /*
2346  * do_X509_REQ_verify returns 1 if the signature is valid,
2347  * 0 if the signature check fails, or -1 if error occurs.
2348  */
2349 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
2350                        STACK_OF(OPENSSL_STRING) *vfyopts)
2351 {
2352     int rv = 0;
2353 
2354     if (do_x509_req_init(x, vfyopts) > 0)
2355         rv = X509_REQ_verify_ex(x, pkey,
2356                                  app_get0_libctx(), app_get0_propq());
2357     else
2358         rv = -1;
2359     return rv;
2360 }
2361 
2362 /* Get first http URL from a DIST_POINT structure */
2363 
2364 static const char *get_dp_url(DIST_POINT *dp)
2365 {
2366     GENERAL_NAMES *gens;
2367     GENERAL_NAME *gen;
2368     int i, gtype;
2369     ASN1_STRING *uri;
2370     if (!dp->distpoint || dp->distpoint->type != 0)
2371         return NULL;
2372     gens = dp->distpoint->name.fullname;
2373     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2374         gen = sk_GENERAL_NAME_value(gens, i);
2375         uri = GENERAL_NAME_get0_value(gen, &gtype);
2376         if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
2377             const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
2378 
2379             if (IS_HTTP(uptr)) /* can/should not use HTTPS here */
2380                 return uptr;
2381         }
2382     }
2383     return NULL;
2384 }
2385 
2386 /*
2387  * Look through a CRLDP structure and attempt to find an http URL to
2388  * downloads a CRL from.
2389  */
2390 
2391 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
2392 {
2393     int i;
2394     const char *urlptr = NULL;
2395     for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2396         DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
2397         urlptr = get_dp_url(dp);
2398         if (urlptr != NULL)
2399             return load_crl(urlptr, FORMAT_UNDEF, 0, "CRL via CDP");
2400     }
2401     return NULL;
2402 }
2403 
2404 /*
2405  * Example of downloading CRLs from CRLDP:
2406  * not usable for real world as it always downloads and doesn't cache anything.
2407  */
2408 
2409 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
2410                                         const X509_NAME *nm)
2411 {
2412     X509 *x;
2413     STACK_OF(X509_CRL) *crls = NULL;
2414     X509_CRL *crl;
2415     STACK_OF(DIST_POINT) *crldp;
2416 
2417     crls = sk_X509_CRL_new_null();
2418     if (!crls)
2419         return NULL;
2420     x = X509_STORE_CTX_get_current_cert(ctx);
2421     crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2422     crl = load_crl_crldp(crldp);
2423     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2424     if (!crl) {
2425         sk_X509_CRL_free(crls);
2426         return NULL;
2427     }
2428     sk_X509_CRL_push(crls, crl);
2429     /* Try to download delta CRL */
2430     crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2431     crl = load_crl_crldp(crldp);
2432     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2433     if (crl)
2434         sk_X509_CRL_push(crls, crl);
2435     return crls;
2436 }
2437 
2438 void store_setup_crl_download(X509_STORE *st)
2439 {
2440     X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2441 }
2442 
2443 #ifndef OPENSSL_NO_SOCK
2444 static const char *tls_error_hint(void)
2445 {
2446     unsigned long err = ERR_peek_error();
2447 
2448     if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2449         err = ERR_peek_last_error();
2450     if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2451         return NULL;
2452 
2453     switch (ERR_GET_REASON(err)) {
2454     case SSL_R_WRONG_VERSION_NUMBER:
2455         return "The server does not support (a suitable version of) TLS";
2456     case SSL_R_UNKNOWN_PROTOCOL:
2457         return "The server does not support HTTPS";
2458     case SSL_R_CERTIFICATE_VERIFY_FAILED:
2459         return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2460     case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
2461         return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2462     case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
2463         return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2464     default: /* no error or no hint available for error */
2465         return NULL;
2466     }
2467 }
2468 
2469 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
2470 BIO *app_http_tls_cb(BIO *bio, void *arg, int connect, int detail)
2471 {
2472     APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
2473     SSL_CTX *ssl_ctx = info->ssl_ctx;
2474 
2475     if (ssl_ctx == NULL) /* not using TLS */
2476         return bio;
2477     if (connect) {
2478         SSL *ssl;
2479         BIO *sbio = NULL;
2480         X509_STORE *ts = SSL_CTX_get_cert_store(ssl_ctx);
2481         X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts);
2482         const char *host = vpm == NULL ? NULL :
2483             X509_VERIFY_PARAM_get0_host(vpm, 0 /* first hostname */);
2484 
2485         /* adapt after fixing callback design flaw, see #17088 */
2486         if ((info->use_proxy
2487              && !OSSL_HTTP_proxy_connect(bio, info->server, info->port,
2488                                          NULL, NULL, /* no proxy credentials */
2489                                          info->timeout, bio_err, opt_getprog()))
2490                 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
2491             return NULL;
2492         }
2493         if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
2494             BIO_free(sbio);
2495             return NULL;
2496         }
2497 
2498         if (vpm != NULL)
2499             SSL_set_tlsext_host_name(ssl, host /* may be NULL */);
2500 
2501         SSL_set_connect_state(ssl);
2502         BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2503 
2504         bio = BIO_push(sbio, bio);
2505     }
2506     if (!connect) {
2507         const char *hint;
2508         BIO *cbio;
2509 
2510         if (!detail) { /* disconnecting after error */
2511             hint = tls_error_hint();
2512             if (hint != NULL)
2513                 ERR_add_error_data(2, " : ", hint);
2514         }
2515         if (ssl_ctx != NULL) {
2516             (void)ERR_set_mark();
2517             BIO_ssl_shutdown(bio);
2518             cbio = BIO_pop(bio); /* connect+HTTP BIO */
2519             BIO_free(bio); /* SSL BIO */
2520             (void)ERR_pop_to_mark(); /* hide SSL_R_READ_BIO_NOT_SET etc. */
2521             bio = cbio;
2522         }
2523     }
2524     return bio;
2525 }
2526 
2527 void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info)
2528 {
2529     if (info != NULL) {
2530         SSL_CTX_free(info->ssl_ctx);
2531         OPENSSL_free(info);
2532     }
2533 }
2534 
2535 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2536                               const char *no_proxy, SSL_CTX *ssl_ctx,
2537                               const STACK_OF(CONF_VALUE) *headers,
2538                               long timeout, const char *expected_content_type,
2539                               const ASN1_ITEM *it)
2540 {
2541     APP_HTTP_TLS_INFO info;
2542     char *server;
2543     char *port;
2544     int use_ssl;
2545     BIO *mem;
2546     ASN1_VALUE *resp = NULL;
2547 
2548     if (url == NULL || it == NULL) {
2549         ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
2550         return NULL;
2551     }
2552 
2553     if (!OSSL_HTTP_parse_url(url, &use_ssl, NULL /* userinfo */, &server, &port,
2554                              NULL /* port_num, */, NULL, NULL, NULL))
2555         return NULL;
2556     if (use_ssl && ssl_ctx == NULL) {
2557         ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER,
2558                        "missing SSL_CTX");
2559         goto end;
2560     }
2561     if (!use_ssl && ssl_ctx != NULL) {
2562         ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT,
2563                        "SSL_CTX given but use_ssl == 0");
2564         goto end;
2565     }
2566 
2567     info.server = server;
2568     info.port = port;
2569     info.use_proxy = /* workaround for callback design flaw, see #17088 */
2570         OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl) != NULL;
2571     info.timeout = timeout;
2572     info.ssl_ctx = ssl_ctx;
2573     mem = OSSL_HTTP_get(url, proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2574                         app_http_tls_cb, &info, 0 /* buf_size */, headers,
2575                         expected_content_type, 1 /* expect_asn1 */,
2576                         OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout);
2577     resp = ASN1_item_d2i_bio(it, mem, NULL);
2578     BIO_free(mem);
2579 
2580  end:
2581     OPENSSL_free(server);
2582     OPENSSL_free(port);
2583     return resp;
2584 
2585 }
2586 
2587 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2588                                const char *path, const char *proxy,
2589                                const char *no_proxy, SSL_CTX *ssl_ctx,
2590                                const STACK_OF(CONF_VALUE) *headers,
2591                                const char *content_type,
2592                                ASN1_VALUE *req, const ASN1_ITEM *req_it,
2593                                const char *expected_content_type,
2594                                long timeout, const ASN1_ITEM *rsp_it)
2595 {
2596     int use_ssl = ssl_ctx != NULL;
2597     APP_HTTP_TLS_INFO info;
2598     BIO *rsp, *req_mem = ASN1_item_i2d_mem_bio(req_it, req);
2599     ASN1_VALUE *res;
2600 
2601     if (req_mem == NULL)
2602         return NULL;
2603 
2604     info.server = host;
2605     info.port = port;
2606     info.use_proxy = /* workaround for callback design flaw, see #17088 */
2607         OSSL_HTTP_adapt_proxy(proxy, no_proxy, host, use_ssl) != NULL;
2608     info.timeout = timeout;
2609     info.ssl_ctx = ssl_ctx;
2610     rsp = OSSL_HTTP_transfer(NULL, host, port, path, use_ssl,
2611                              proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2612                              app_http_tls_cb, &info,
2613                              0 /* buf_size */, headers, content_type, req_mem,
2614                              expected_content_type, 1 /* expect_asn1 */,
2615                              OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout,
2616                              0 /* keep_alive */);
2617     BIO_free(req_mem);
2618     res = ASN1_item_d2i_bio(rsp_it, rsp, NULL);
2619     BIO_free(rsp);
2620     return res;
2621 }
2622 
2623 #endif
2624 
2625 /*
2626  * Platform-specific sections
2627  */
2628 #if defined(_WIN32)
2629 # ifdef fileno
2630 #  undef fileno
2631 #  define fileno(a) (int)_fileno(a)
2632 # endif
2633 
2634 # include <windows.h>
2635 # include <tchar.h>
2636 
2637 static int WIN32_rename(const char *from, const char *to)
2638 {
2639     TCHAR *tfrom = NULL, *tto;
2640     DWORD err;
2641     int ret = 0;
2642 
2643     if (sizeof(TCHAR) == 1) {
2644         tfrom = (TCHAR *)from;
2645         tto = (TCHAR *)to;
2646     } else {                    /* UNICODE path */
2647 
2648         size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2649         tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2650         if (tfrom == NULL)
2651             goto err;
2652         tto = tfrom + flen;
2653 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2654         if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2655 # endif
2656             for (i = 0; i < flen; i++)
2657                 tfrom[i] = (TCHAR)from[i];
2658 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2659         if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2660 # endif
2661             for (i = 0; i < tlen; i++)
2662                 tto[i] = (TCHAR)to[i];
2663     }
2664 
2665     if (MoveFile(tfrom, tto))
2666         goto ok;
2667     err = GetLastError();
2668     if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2669         if (DeleteFile(tto) && MoveFile(tfrom, tto))
2670             goto ok;
2671         err = GetLastError();
2672     }
2673     if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2674         errno = ENOENT;
2675     else if (err == ERROR_ACCESS_DENIED)
2676         errno = EACCES;
2677     else
2678         errno = EINVAL;         /* we could map more codes... */
2679  err:
2680     ret = -1;
2681  ok:
2682     if (tfrom != NULL && tfrom != (TCHAR *)from)
2683         free(tfrom);
2684     return ret;
2685 }
2686 #endif
2687 
2688 /* app_tminterval section */
2689 #if defined(_WIN32)
2690 double app_tminterval(int stop, int usertime)
2691 {
2692     FILETIME now;
2693     double ret = 0;
2694     static ULARGE_INTEGER tmstart;
2695     static int warning = 1;
2696 # ifdef _WIN32_WINNT
2697     static HANDLE proc = NULL;
2698 
2699     if (proc == NULL) {
2700         if (check_winnt())
2701             proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2702                                GetCurrentProcessId());
2703         if (proc == NULL)
2704             proc = (HANDLE) - 1;
2705     }
2706 
2707     if (usertime && proc != (HANDLE) - 1) {
2708         FILETIME junk;
2709         GetProcessTimes(proc, &junk, &junk, &junk, &now);
2710     } else
2711 # endif
2712     {
2713         SYSTEMTIME systime;
2714 
2715         if (usertime && warning) {
2716             BIO_printf(bio_err, "To get meaningful results, run "
2717                        "this program on idle system.\n");
2718             warning = 0;
2719         }
2720         GetSystemTime(&systime);
2721         SystemTimeToFileTime(&systime, &now);
2722     }
2723 
2724     if (stop == TM_START) {
2725         tmstart.u.LowPart = now.dwLowDateTime;
2726         tmstart.u.HighPart = now.dwHighDateTime;
2727     } else {
2728         ULARGE_INTEGER tmstop;
2729 
2730         tmstop.u.LowPart = now.dwLowDateTime;
2731         tmstop.u.HighPart = now.dwHighDateTime;
2732 
2733         ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2734     }
2735 
2736     return ret;
2737 }
2738 #elif defined(OPENSSL_SYS_VXWORKS)
2739 # include <time.h>
2740 
2741 double app_tminterval(int stop, int usertime)
2742 {
2743     double ret = 0;
2744 # ifdef CLOCK_REALTIME
2745     static struct timespec tmstart;
2746     struct timespec now;
2747 # else
2748     static unsigned long tmstart;
2749     unsigned long now;
2750 # endif
2751     static int warning = 1;
2752 
2753     if (usertime && warning) {
2754         BIO_printf(bio_err, "To get meaningful results, run "
2755                    "this program on idle system.\n");
2756         warning = 0;
2757     }
2758 # ifdef CLOCK_REALTIME
2759     clock_gettime(CLOCK_REALTIME, &now);
2760     if (stop == TM_START)
2761         tmstart = now;
2762     else
2763         ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2764                - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2765 # else
2766     now = tickGet();
2767     if (stop == TM_START)
2768         tmstart = now;
2769     else
2770         ret = (now - tmstart) / (double)sysClkRateGet();
2771 # endif
2772     return ret;
2773 }
2774 
2775 #elif defined(_SC_CLK_TCK)      /* by means of unistd.h */
2776 # include <sys/times.h>
2777 
2778 double app_tminterval(int stop, int usertime)
2779 {
2780     double ret = 0;
2781     struct tms rus;
2782     clock_t now = times(&rus);
2783     static clock_t tmstart;
2784 
2785     if (usertime)
2786         now = rus.tms_utime;
2787 
2788     if (stop == TM_START) {
2789         tmstart = now;
2790     } else {
2791         long int tck = sysconf(_SC_CLK_TCK);
2792         ret = (now - tmstart) / (double)tck;
2793     }
2794 
2795     return ret;
2796 }
2797 
2798 #else
2799 # include <sys/time.h>
2800 # include <sys/resource.h>
2801 
2802 double app_tminterval(int stop, int usertime)
2803 {
2804     double ret = 0;
2805     struct rusage rus;
2806     struct timeval now;
2807     static struct timeval tmstart;
2808 
2809     if (usertime)
2810         getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2811     else
2812         gettimeofday(&now, NULL);
2813 
2814     if (stop == TM_START)
2815         tmstart = now;
2816     else
2817         ret = ((now.tv_sec + now.tv_usec * 1e-6)
2818                - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2819 
2820     return ret;
2821 }
2822 #endif
2823 
2824 int app_access(const char* name, int flag)
2825 {
2826 #ifdef _WIN32
2827     return _access(name, flag);
2828 #else
2829     return access(name, flag);
2830 #endif
2831 }
2832 
2833 int app_isdir(const char *name)
2834 {
2835     return opt_isdir(name);
2836 }
2837 
2838 /* raw_read|write section */
2839 #if defined(__VMS)
2840 # include "vms_term_sock.h"
2841 static int stdin_sock = -1;
2842 
2843 static void close_stdin_sock(void)
2844 {
2845     TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2846 }
2847 
2848 int fileno_stdin(void)
2849 {
2850     if (stdin_sock == -1) {
2851         TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2852         atexit(close_stdin_sock);
2853     }
2854 
2855     return stdin_sock;
2856 }
2857 #else
2858 int fileno_stdin(void)
2859 {
2860     return fileno(stdin);
2861 }
2862 #endif
2863 
2864 int fileno_stdout(void)
2865 {
2866     return fileno(stdout);
2867 }
2868 
2869 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2870 int raw_read_stdin(void *buf, int siz)
2871 {
2872     DWORD n;
2873     if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2874         return n;
2875     else
2876         return -1;
2877 }
2878 #elif defined(__VMS)
2879 # include <sys/socket.h>
2880 
2881 int raw_read_stdin(void *buf, int siz)
2882 {
2883     return recv(fileno_stdin(), buf, siz, 0);
2884 }
2885 #else
2886 # if defined(__TANDEM)
2887 #  if defined(OPENSSL_TANDEM_FLOSS)
2888 #   include <floss.h(floss_read)>
2889 #  endif
2890 # endif
2891 int raw_read_stdin(void *buf, int siz)
2892 {
2893     return read(fileno_stdin(), buf, siz);
2894 }
2895 #endif
2896 
2897 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2898 int raw_write_stdout(const void *buf, int siz)
2899 {
2900     DWORD n;
2901     if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2902         return n;
2903     else
2904         return -1;
2905 }
2906 #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
2907 # if defined(__TANDEM)
2908 #  if defined(OPENSSL_TANDEM_FLOSS)
2909 #   include <floss.h(floss_write)>
2910 #  endif
2911 # endif
2912 int raw_write_stdout(const void *buf,int siz)
2913 {
2914 	return write(fileno(stdout),(void*)buf,siz);
2915 }
2916 #else
2917 # if defined(__TANDEM)
2918 #  if defined(OPENSSL_TANDEM_FLOSS)
2919 #   include <floss.h(floss_write)>
2920 #  endif
2921 # endif
2922 int raw_write_stdout(const void *buf, int siz)
2923 {
2924     return write(fileno_stdout(), buf, siz);
2925 }
2926 #endif
2927 
2928 /*
2929  * Centralized handling of input and output files with format specification
2930  * The format is meant to show what the input and output is supposed to be,
2931  * and is therefore a show of intent more than anything else.  However, it
2932  * does impact behavior on some platforms, such as differentiating between
2933  * text and binary input/output on non-Unix platforms
2934  */
2935 BIO *dup_bio_in(int format)
2936 {
2937     return BIO_new_fp(stdin,
2938                       BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2939 }
2940 
2941 BIO *dup_bio_out(int format)
2942 {
2943     BIO *b = BIO_new_fp(stdout,
2944                         BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2945     void *prefix = NULL;
2946 
2947     if (b == NULL)
2948         return NULL;
2949 
2950 #ifdef OPENSSL_SYS_VMS
2951     if (FMT_istext(format))
2952         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2953 #endif
2954 
2955     if (FMT_istext(format)
2956         && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2957         b = BIO_push(BIO_new(BIO_f_prefix()), b);
2958         BIO_set_prefix(b, prefix);
2959     }
2960 
2961     return b;
2962 }
2963 
2964 BIO *dup_bio_err(int format)
2965 {
2966     BIO *b = BIO_new_fp(stderr,
2967                         BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2968 #ifdef OPENSSL_SYS_VMS
2969     if (b != NULL && FMT_istext(format))
2970         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2971 #endif
2972     return b;
2973 }
2974 
2975 void unbuffer(FILE *fp)
2976 {
2977 /*
2978  * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2979  * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2980  * However, we trust that the C RTL will never give us a FILE pointer
2981  * above the first 4 GB of memory, so we simply turn off the warning
2982  * temporarily.
2983  */
2984 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2985 # pragma environment save
2986 # pragma message disable maylosedata2
2987 #endif
2988     setbuf(fp, NULL);
2989 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2990 # pragma environment restore
2991 #endif
2992 }
2993 
2994 static const char *modestr(char mode, int format)
2995 {
2996     OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2997 
2998     switch (mode) {
2999     case 'a':
3000         return FMT_istext(format) ? "a" : "ab";
3001     case 'r':
3002         return FMT_istext(format) ? "r" : "rb";
3003     case 'w':
3004         return FMT_istext(format) ? "w" : "wb";
3005     }
3006     /* The assert above should make sure we never reach this point */
3007     return NULL;
3008 }
3009 
3010 static const char *modeverb(char mode)
3011 {
3012     switch (mode) {
3013     case 'a':
3014         return "appending";
3015     case 'r':
3016         return "reading";
3017     case 'w':
3018         return "writing";
3019     }
3020     return "(doing something)";
3021 }
3022 
3023 /*
3024  * Open a file for writing, owner-read-only.
3025  */
3026 BIO *bio_open_owner(const char *filename, int format, int private)
3027 {
3028     FILE *fp = NULL;
3029     BIO *b = NULL;
3030     int textmode, bflags;
3031 #ifndef OPENSSL_NO_POSIX_IO
3032     int fd = -1, mode;
3033 #endif
3034 
3035     if (!private || filename == NULL || strcmp(filename, "-") == 0)
3036         return bio_open_default(filename, 'w', format);
3037 
3038     textmode = FMT_istext(format);
3039 #ifndef OPENSSL_NO_POSIX_IO
3040     mode = O_WRONLY;
3041 # ifdef O_CREAT
3042     mode |= O_CREAT;
3043 # endif
3044 # ifdef O_TRUNC
3045     mode |= O_TRUNC;
3046 # endif
3047     if (!textmode) {
3048 # ifdef O_BINARY
3049         mode |= O_BINARY;
3050 # elif defined(_O_BINARY)
3051         mode |= _O_BINARY;
3052 # endif
3053     }
3054 
3055 # ifdef OPENSSL_SYS_VMS
3056     /* VMS doesn't have O_BINARY, it just doesn't make sense.  But,
3057      * it still needs to know that we're going binary, or fdopen()
3058      * will fail with "invalid argument"...  so we tell VMS what the
3059      * context is.
3060      */
3061     if (!textmode)
3062         fd = open(filename, mode, 0600, "ctx=bin");
3063     else
3064 # endif
3065         fd = open(filename, mode, 0600);
3066     if (fd < 0)
3067         goto err;
3068     fp = fdopen(fd, modestr('w', format));
3069 #else   /* OPENSSL_NO_POSIX_IO */
3070     /* Have stdio but not Posix IO, do the best we can */
3071     fp = fopen(filename, modestr('w', format));
3072 #endif  /* OPENSSL_NO_POSIX_IO */
3073     if (fp == NULL)
3074         goto err;
3075     bflags = BIO_CLOSE;
3076     if (textmode)
3077         bflags |= BIO_FP_TEXT;
3078     b = BIO_new_fp(fp, bflags);
3079     if (b != NULL)
3080         return b;
3081 
3082  err:
3083     BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
3084                opt_getprog(), filename, strerror(errno));
3085     ERR_print_errors(bio_err);
3086     /* If we have fp, then fdopen took over fd, so don't close both. */
3087     if (fp != NULL)
3088         fclose(fp);
3089 #ifndef OPENSSL_NO_POSIX_IO
3090     else if (fd >= 0)
3091         close(fd);
3092 #endif
3093     return NULL;
3094 }
3095 
3096 static BIO *bio_open_default_(const char *filename, char mode, int format,
3097                               int quiet)
3098 {
3099     BIO *ret;
3100 
3101     if (filename == NULL || strcmp(filename, "-") == 0) {
3102         ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
3103         if (quiet) {
3104             ERR_clear_error();
3105             return ret;
3106         }
3107         if (ret != NULL)
3108             return ret;
3109         BIO_printf(bio_err,
3110                    "Can't open %s, %s\n",
3111                    mode == 'r' ? "stdin" : "stdout", strerror(errno));
3112     } else {
3113         ret = BIO_new_file(filename, modestr(mode, format));
3114         if (quiet) {
3115             ERR_clear_error();
3116             return ret;
3117         }
3118         if (ret != NULL)
3119             return ret;
3120         BIO_printf(bio_err,
3121                    "Can't open \"%s\" for %s, %s\n",
3122                    filename, modeverb(mode), strerror(errno));
3123     }
3124     ERR_print_errors(bio_err);
3125     return NULL;
3126 }
3127 
3128 BIO *bio_open_default(const char *filename, char mode, int format)
3129 {
3130     return bio_open_default_(filename, mode, format, 0);
3131 }
3132 
3133 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
3134 {
3135     return bio_open_default_(filename, mode, format, 1);
3136 }
3137 
3138 void wait_for_async(SSL *s)
3139 {
3140     /* On Windows select only works for sockets, so we simply don't wait  */
3141 #ifndef OPENSSL_SYS_WINDOWS
3142     int width = 0;
3143     fd_set asyncfds;
3144     OSSL_ASYNC_FD *fds;
3145     size_t numfds;
3146     size_t i;
3147 
3148     if (!SSL_get_all_async_fds(s, NULL, &numfds))
3149         return;
3150     if (numfds == 0)
3151         return;
3152     fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
3153     if (!SSL_get_all_async_fds(s, fds, &numfds)) {
3154         OPENSSL_free(fds);
3155         return;
3156     }
3157 
3158     FD_ZERO(&asyncfds);
3159     for (i = 0; i < numfds; i++) {
3160         if (width <= (int)fds[i])
3161             width = (int)fds[i] + 1;
3162         openssl_fdset((int)fds[i], &asyncfds);
3163     }
3164     select(width, (void *)&asyncfds, NULL, NULL, NULL);
3165     OPENSSL_free(fds);
3166 #endif
3167 }
3168 
3169 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
3170 #if defined(OPENSSL_SYS_MSDOS)
3171 int has_stdin_waiting(void)
3172 {
3173 # if defined(OPENSSL_SYS_WINDOWS)
3174     HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
3175     DWORD events = 0;
3176     INPUT_RECORD inputrec;
3177     DWORD insize = 1;
3178     BOOL peeked;
3179 
3180     if (inhand == INVALID_HANDLE_VALUE) {
3181         return 0;
3182     }
3183 
3184     peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
3185     if (!peeked) {
3186         /* Probably redirected input? _kbhit() does not work in this case */
3187         if (!feof(stdin)) {
3188             return 1;
3189         }
3190         return 0;
3191     }
3192 # endif
3193     return _kbhit();
3194 }
3195 #endif
3196 
3197 /* Corrupt a signature by modifying final byte */
3198 void corrupt_signature(const ASN1_STRING *signature)
3199 {
3200         unsigned char *s = signature->data;
3201         s[signature->length - 1] ^= 0x1;
3202 }
3203 
3204 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
3205                    int days)
3206 {
3207     if (startdate == NULL || strcmp(startdate, "today") == 0) {
3208         if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
3209             return 0;
3210     } else {
3211         if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
3212             return 0;
3213     }
3214     if (enddate == NULL) {
3215         if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
3216             == NULL)
3217             return 0;
3218     } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
3219         return 0;
3220     }
3221     return 1;
3222 }
3223 
3224 int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate)
3225 {
3226     int ret = 0;
3227     ASN1_TIME *tm = ASN1_TIME_new();
3228 
3229     if (tm == NULL)
3230         goto end;
3231 
3232     if (lastupdate == NULL) {
3233         if (X509_gmtime_adj(tm, 0) == NULL)
3234             goto end;
3235     } else {
3236         if (!ASN1_TIME_set_string_X509(tm, lastupdate))
3237             goto end;
3238     }
3239 
3240     if (!X509_CRL_set1_lastUpdate(crl, tm))
3241         goto end;
3242 
3243     ret = 1;
3244 end:
3245     ASN1_TIME_free(tm);
3246     return ret;
3247 }
3248 
3249 int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
3250                        long days, long hours, long secs)
3251 {
3252     int ret = 0;
3253     ASN1_TIME *tm = ASN1_TIME_new();
3254 
3255     if (tm == NULL)
3256         goto end;
3257 
3258     if (nextupdate == NULL) {
3259         if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL)
3260             goto end;
3261     } else {
3262         if (!ASN1_TIME_set_string_X509(tm, nextupdate))
3263             goto end;
3264     }
3265 
3266     if (!X509_CRL_set1_nextUpdate(crl, tm))
3267         goto end;
3268 
3269     ret = 1;
3270 end:
3271     ASN1_TIME_free(tm);
3272     return ret;
3273 }
3274 
3275 void make_uppercase(char *string)
3276 {
3277     int i;
3278 
3279     for (i = 0; string[i] != '\0'; i++)
3280         string[i] = toupper((unsigned char)string[i]);
3281 }
3282 
3283 /* This function is defined here due to visibility of bio_err */
3284 int opt_printf_stderr(const char *fmt, ...)
3285 {
3286     va_list ap;
3287     int ret;
3288 
3289     va_start(ap, fmt);
3290     ret = BIO_vprintf(bio_err, fmt, ap);
3291     va_end(ap);
3292     return ret;
3293 }
3294 
3295 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
3296                                      const OSSL_PARAM *paramdefs)
3297 {
3298     OSSL_PARAM *params = NULL;
3299     size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
3300     size_t params_n;
3301     char *opt = "", *stmp, *vtmp = NULL;
3302     int found = 1;
3303 
3304     if (opts == NULL)
3305         return NULL;
3306 
3307     params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
3308     if (params == NULL)
3309         return NULL;
3310 
3311     for (params_n = 0; params_n < sz; params_n++) {
3312         opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
3313         if ((stmp = OPENSSL_strdup(opt)) == NULL
3314             || (vtmp = strchr(stmp, ':')) == NULL)
3315             goto err;
3316         /* Replace ':' with 0 to terminate the string pointed to by stmp */
3317         *vtmp = 0;
3318         /* Skip over the separator so that vmtp points to the value */
3319         vtmp++;
3320         if (!OSSL_PARAM_allocate_from_text(&params[params_n], paramdefs,
3321                                            stmp, vtmp, strlen(vtmp), &found))
3322             goto err;
3323         OPENSSL_free(stmp);
3324     }
3325     params[params_n] = OSSL_PARAM_construct_end();
3326     return params;
3327 err:
3328     OPENSSL_free(stmp);
3329     BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
3330                opt);
3331     ERR_print_errors(bio_err);
3332     app_params_free(params);
3333     return NULL;
3334 }
3335 
3336 void app_params_free(OSSL_PARAM *params)
3337 {
3338     int i;
3339 
3340     if (params != NULL) {
3341         for (i = 0; params[i].key != NULL; ++i)
3342             OPENSSL_free(params[i].data);
3343         OPENSSL_free(params);
3344     }
3345 }
3346 
3347 EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose)
3348 {
3349     EVP_PKEY *res = NULL;
3350 
3351     if (verbose && alg != NULL) {
3352         BIO_printf(bio_err, "Generating %s key", alg);
3353         if (bits > 0)
3354             BIO_printf(bio_err, " with %d bits\n", bits);
3355         else
3356             BIO_printf(bio_err, "\n");
3357     }
3358     if (!RAND_status())
3359         BIO_printf(bio_err, "Warning: generating random key material may take a long time\n"
3360                    "if the system has a poor entropy source\n");
3361     if (EVP_PKEY_keygen(ctx, &res) <= 0)
3362         app_bail_out("%s: Error generating %s key\n", opt_getprog(),
3363                      alg != NULL ? alg : "asymmetric");
3364     return res;
3365 }
3366 
3367 EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg)
3368 {
3369     EVP_PKEY *res = NULL;
3370 
3371     if (!RAND_status())
3372         BIO_printf(bio_err, "Warning: generating random key parameters may take a long time\n"
3373                    "if the system has a poor entropy source\n");
3374     if (EVP_PKEY_paramgen(ctx, &res) <= 0)
3375         app_bail_out("%s: Generating %s key parameters failed\n",
3376                      opt_getprog(), alg != NULL ? alg : "asymmetric");
3377     return res;
3378 }
3379 
3380 /*
3381  * Return non-zero if the legacy path is still an option.
3382  * This decision is based on the global command line operations and the
3383  * behaviour thus far.
3384  */
3385 int opt_legacy_okay(void)
3386 {
3387     int provider_options = opt_provider_option_given();
3388     int libctx = app_get0_libctx() != NULL || app_get0_propq() != NULL;
3389     /*
3390      * Having a provider option specified or a custom library context or
3391      * property query, is a sure sign we're not using legacy.
3392      */
3393     if (provider_options || libctx)
3394         return 0;
3395     return 1;
3396 }
3397