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