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