Fix safestack issues in x509.h
[openssl.git] / apps / lib / apps.c
1 /*
2  * Copyright 1995-2020 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 /* We need to use some engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
12
13 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
14 /*
15  * On VMS, you need to define this to get the declaration of fileno().  The
16  * value 2 is to make sure no function defined in POSIX-2 is left undefined.
17  */
18 # define _POSIX_C_SOURCE 2
19 #endif
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/types.h>
25 #ifndef OPENSSL_NO_POSIX_IO
26 # include <sys/stat.h>
27 # include <fcntl.h>
28 #endif
29 #include <ctype.h>
30 #include <errno.h>
31 #include <openssl/err.h>
32 #include <openssl/x509.h>
33 #include <openssl/x509v3.h>
34 #include <openssl/pem.h>
35 #include <openssl/store.h>
36 #include <openssl/pkcs12.h>
37 #include <openssl/ui.h>
38 #include <openssl/safestack.h>
39 #ifndef OPENSSL_NO_ENGINE
40 # include <openssl/engine.h>
41 #endif
42 #ifndef OPENSSL_NO_RSA
43 # include <openssl/rsa.h>
44 #endif
45 #include <openssl/bn.h>
46 #include <openssl/ssl.h>
47 #include "apps.h"
48
49 #ifdef _WIN32
50 static int WIN32_rename(const char *from, const char *to);
51 # define rename(from,to) WIN32_rename((from),(to))
52 #endif
53
54 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
55 # include <conio.h>
56 #endif
57
58 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32)
59 # define _kbhit kbhit
60 #endif
61
62 #define PASS_SOURCE_SIZE_MAX 4
63
64 DEFINE_STACK_OF(CONF)
65 DEFINE_STACK_OF(CONF_VALUE)
66 DEFINE_STACK_OF(X509_POLICY_NODE)
67 DEFINE_STACK_OF(GENERAL_NAME)
68 DEFINE_STACK_OF(DIST_POINT)
69 DEFINE_STACK_OF_STRING()
70
71 typedef struct {
72     const char *name;
73     unsigned long flag;
74     unsigned long mask;
75 } NAME_EX_TBL;
76
77 static OPENSSL_CTX *app_libctx = NULL;
78
79 static int set_table_opts(unsigned long *flags, const char *arg,
80                           const NAME_EX_TBL * in_tbl);
81 static int set_multi_opts(unsigned long *flags, const char *arg,
82                           const NAME_EX_TBL * in_tbl);
83
84 int app_init(long mesgwin);
85
86 int chopup_args(ARGS *arg, char *buf)
87 {
88     int quoted;
89     char c = '\0', *p = NULL;
90
91     arg->argc = 0;
92     if (arg->size == 0) {
93         arg->size = 20;
94         arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
95     }
96
97     for (p = buf;;) {
98         /* Skip whitespace. */
99         while (*p && isspace(_UC(*p)))
100             p++;
101         if (*p == '\0')
102             break;
103
104         /* The start of something good :-) */
105         if (arg->argc >= arg->size) {
106             char **tmp;
107             arg->size += 20;
108             tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
109             if (tmp == NULL)
110                 return 0;
111             arg->argv = tmp;
112         }
113         quoted = *p == '\'' || *p == '"';
114         if (quoted)
115             c = *p++;
116         arg->argv[arg->argc++] = p;
117
118         /* now look for the end of this */
119         if (quoted) {
120             while (*p && *p != c)
121                 p++;
122             *p++ = '\0';
123         } else {
124             while (*p && !isspace(_UC(*p)))
125                 p++;
126             if (*p)
127                 *p++ = '\0';
128         }
129     }
130     arg->argv[arg->argc] = NULL;
131     return 1;
132 }
133
134 #ifndef APP_INIT
135 int app_init(long mesgwin)
136 {
137     return 1;
138 }
139 #endif
140
141 int ctx_set_verify_locations(SSL_CTX *ctx,
142                              const char *CAfile, int noCAfile,
143                              const char *CApath, int noCApath,
144                              const char *CAstore, int noCAstore)
145 {
146     if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
147         if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
148             return 0;
149         if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
150             return 0;
151         if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
152             return 0;
153
154         return 1;
155     }
156
157     if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
158         return 0;
159     if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
160         return 0;
161     if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
162         return 0;
163     return 1;
164 }
165
166 #ifndef OPENSSL_NO_CT
167
168 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
169 {
170     if (path == NULL)
171         return SSL_CTX_set_default_ctlog_list_file(ctx);
172
173     return SSL_CTX_set_ctlog_list_file(ctx, path);
174 }
175
176 #endif
177
178 static unsigned long nmflag = 0;
179 static char nmflag_set = 0;
180
181 int set_nameopt(const char *arg)
182 {
183     int ret = set_name_ex(&nmflag, arg);
184
185     if (ret)
186         nmflag_set = 1;
187
188     return ret;
189 }
190
191 unsigned long get_nameopt(void)
192 {
193     return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
194 }
195
196 int dump_cert_text(BIO *out, X509 *x)
197 {
198     print_name(out, "subject=", X509_get_subject_name(x), get_nameopt());
199     BIO_puts(out, "\n");
200     print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
201     BIO_puts(out, "\n");
202
203     return 0;
204 }
205
206 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
207 {
208     return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
209 }
210
211
212 static char *app_get_pass(const char *arg, int keepbio);
213
214 char *get_passwd(const char *pass, const char *desc)
215 {
216     char *result = NULL;
217
218     if (desc == NULL)
219         desc = "<unknown>";
220     if (!app_passwd(pass, NULL, &result, NULL))
221         BIO_printf(bio_err, "Error getting password for %s\n", desc);
222     if (pass != NULL && result == NULL) {
223         BIO_printf(bio_err,
224                    "Trying plain input string (better precede with 'pass:')\n");
225         result = OPENSSL_strdup(pass);
226         if (result == NULL)
227             BIO_printf(bio_err, "Out of memory getting password for %s\n", desc);
228     }
229     return result;
230 }
231
232 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
233 {
234     int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
235
236     if (arg1 != NULL) {
237         *pass1 = app_get_pass(arg1, same);
238         if (*pass1 == NULL)
239             return 0;
240     } else if (pass1 != NULL) {
241         *pass1 = NULL;
242     }
243     if (arg2 != NULL) {
244         *pass2 = app_get_pass(arg2, same ? 2 : 0);
245         if (*pass2 == NULL)
246             return 0;
247     } else if (pass2 != NULL) {
248         *pass2 = NULL;
249     }
250     return 1;
251 }
252
253 static char *app_get_pass(const char *arg, int keepbio)
254 {
255     static BIO *pwdbio = NULL;
256     char *tmp, tpass[APP_PASS_LEN];
257     int i;
258
259     /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
260     if (strncmp(arg, "pass:", 5) == 0)
261         return OPENSSL_strdup(arg + 5);
262     if (strncmp(arg, "env:", 4) == 0) {
263         tmp = getenv(arg + 4);
264         if (tmp == NULL) {
265             BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
266             return NULL;
267         }
268         return OPENSSL_strdup(tmp);
269     }
270     if (!keepbio || pwdbio == NULL) {
271         if (strncmp(arg, "file:", 5) == 0) {
272             pwdbio = BIO_new_file(arg + 5, "r");
273             if (pwdbio == NULL) {
274                 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
275                 return NULL;
276             }
277 #if !defined(_WIN32)
278             /*
279              * Under _WIN32, which covers even Win64 and CE, file
280              * descriptors referenced by BIO_s_fd are not inherited
281              * by child process and therefore below is not an option.
282              * It could have been an option if bss_fd.c was operating
283              * on real Windows descriptors, such as those obtained
284              * with CreateFile.
285              */
286         } else if (strncmp(arg, "fd:", 3) == 0) {
287             BIO *btmp;
288             i = atoi(arg + 3);
289             if (i >= 0)
290                 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
291             if ((i < 0) || !pwdbio) {
292                 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
293                 return NULL;
294             }
295             /*
296              * Can't do BIO_gets on an fd BIO so add a buffering BIO
297              */
298             btmp = BIO_new(BIO_f_buffer());
299             pwdbio = BIO_push(btmp, pwdbio);
300 #endif
301         } else if (strcmp(arg, "stdin") == 0) {
302             pwdbio = dup_bio_in(FORMAT_TEXT);
303             if (pwdbio == NULL) {
304                 BIO_printf(bio_err, "Can't open BIO for stdin\n");
305                 return NULL;
306             }
307         } else {
308             /* argument syntax error; do not reveal too much about arg */
309             tmp = strchr(arg, ':');
310             if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
311                 BIO_printf(bio_err,
312                            "Invalid password argument, missing ':' within the first %d chars\n",
313                            PASS_SOURCE_SIZE_MAX + 1);
314             else
315                 BIO_printf(bio_err,
316                            "Invalid password argument, starting with \"%.*s\"\n",
317                            (int)(tmp - arg + 1), arg);
318             return NULL;
319         }
320     }
321     i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
322     if (keepbio != 1) {
323         BIO_free_all(pwdbio);
324         pwdbio = NULL;
325     }
326     if (i <= 0) {
327         BIO_printf(bio_err, "Error reading password from BIO\n");
328         return NULL;
329     }
330     tmp = strchr(tpass, '\n');
331     if (tmp != NULL)
332         *tmp = 0;
333     return OPENSSL_strdup(tpass);
334 }
335
336 OPENSSL_CTX *app_get0_libctx(void)
337 {
338     return app_libctx;
339 }
340
341 /* TODO(3.0): Make this an environment variable if required */
342 const char *app_get0_propq(void)
343 {
344     return NULL;
345 }
346
347 OPENSSL_CTX *app_create_libctx(void)
348 {
349     /*
350      * Load the NULL provider into the default library context and create a
351      * library context which will then be used for any OPT_PROV options.
352      */
353     if (app_libctx == NULL) {
354
355         if (!app_provider_load(NULL, "null")) {
356             BIO_puts(bio_err, "Failed to create null provider\n");
357             return NULL;
358         }
359         app_libctx = OPENSSL_CTX_new();
360     }
361     if (app_libctx == NULL)
362         BIO_puts(bio_err, "Failed to create library context\n");
363     return app_libctx;
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_with_libctx(app_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(const char *filename)
393 {
394     BIO *in;
395     CONF *conf;
396
397     in = bio_open_default(filename, 'r', FORMAT_TEXT);
398     if (in == NULL)
399         return NULL;
400
401     conf = app_load_config_bio(in, filename);
402     BIO_free(in);
403     return conf;
404 }
405
406 CONF *app_load_config_quiet(const char *filename)
407 {
408     BIO *in;
409     CONF *conf;
410
411     in = bio_open_default_quiet(filename, 'r', FORMAT_TEXT);
412     if (in == NULL)
413         return NULL;
414
415     conf = app_load_config_bio(in, filename);
416     BIO_free(in);
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 = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
447         ERR_clear_error();
448         return 1;
449     }
450     if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
451         BIO_printf(bio_err, "problem loading oid section %s\n", p);
452         return 0;
453     }
454     for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
455         cnf = sk_CONF_VALUE_value(sktmp, i);
456         if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
457             BIO_printf(bio_err, "problem creating object %s=%s\n",
458                        cnf->name, cnf->value);
459             return 0;
460         }
461     }
462     return 1;
463 }
464
465 CONF *app_load_config_modules(const char *configfile)
466 {
467     CONF *conf = NULL;
468
469     if (configfile != NULL) {
470         BIO_printf(bio_err, "Using configuration from %s\n", configfile);
471
472         if ((conf = app_load_config(configfile)) == NULL)
473             return NULL;
474         if (configfile != default_config_file && !app_load_modules(conf)) {
475             NCONF_free(conf);
476             conf = NULL;
477         }
478     }
479     return conf;
480 }
481
482 X509 *load_cert_pass(const char *uri, int maybe_stdin,
483                      const char *pass, const char *desc)
484 {
485     X509 *cert = NULL;
486
487     if (desc == NULL)
488         desc = "certificate";
489     (void)load_key_certs_crls(uri, maybe_stdin, pass, desc,
490                               NULL, NULL, &cert, NULL, NULL, NULL);
491     if (cert == NULL) {
492         BIO_printf(bio_err, "Unable to load %s\n", desc);
493         ERR_print_errors(bio_err);
494     }
495     return cert;
496 }
497
498 /* the format parameter is meanwhile not needed anymore and thus ignored */
499 X509_CRL *load_crl(const char *uri, int format, const char *desc)
500 {
501     X509_CRL *crl = NULL;
502
503     if (desc == NULL)
504         desc = "CRL";
505     (void)load_key_certs_crls(uri, 0, NULL, desc,
506                               NULL,  NULL, NULL, NULL, &crl, NULL);
507     if (crl == NULL) {
508         BIO_printf(bio_err, "Unable to load %s\n", desc);
509         ERR_print_errors(bio_err);
510     }
511     return crl;
512 }
513
514 X509_REQ *load_csr(const char *file, int format, const char *desc)
515 {
516     X509_REQ *req = NULL;
517     BIO *in;
518
519     if (desc == NULL)
520         desc = "CSR";
521     in = bio_open_default(file, 'r', format);
522     if (in == NULL)
523         goto end;
524
525     if (format == FORMAT_ASN1)
526         req = d2i_X509_REQ_bio(in, NULL);
527     else if (format == FORMAT_PEM)
528         req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
529     else
530         print_format_error(format, OPT_FMT_PEMDER);
531
532  end:
533     if (req == NULL) {
534         BIO_printf(bio_err, "Unable to load %s\n", desc);
535         ERR_print_errors(bio_err);
536     }
537     BIO_free(in);
538     return req;
539 }
540
541 void cleanse(char *str)
542 {
543     if (str != NULL)
544         OPENSSL_cleanse(str, strlen(str));
545 }
546
547 void clear_free(char *str)
548 {
549     if (str != NULL)
550         OPENSSL_clear_free(str, strlen(str));
551 }
552
553 EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
554                    const char *pass, ENGINE *e, const char *desc)
555 {
556     EVP_PKEY *pkey = NULL;
557
558     if (desc == NULL)
559         desc = "private key";
560
561     if (format == FORMAT_ENGINE) {
562         if (e == NULL) {
563             BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
564         } else {
565 #ifndef OPENSSL_NO_ENGINE
566             PW_CB_DATA cb_data;
567
568             cb_data.password = pass;
569             cb_data.prompt_info = uri;
570             if (ENGINE_init(e)) {
571                 pkey = ENGINE_load_private_key(e, uri,
572                                                (UI_METHOD *)get_ui_method(),
573                                                &cb_data);
574                 ENGINE_finish(e);
575             }
576             if (pkey == NULL) {
577                 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
578                 ERR_print_errors(bio_err);
579             }
580 #else
581             BIO_printf(bio_err, "Engines not supported for loading %s\n", desc);
582 #endif
583         }
584     } else {
585         (void)load_key_certs_crls(uri, may_stdin, pass, desc,
586                                   &pkey, NULL, NULL, NULL, NULL, NULL);
587     }
588
589     if (pkey == NULL) {
590         BIO_printf(bio_err, "Unable to load %s\n", desc);
591         ERR_print_errors(bio_err);
592     }
593     return pkey;
594 }
595
596 EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
597                       const char *pass, ENGINE *e, const char *desc)
598 {
599     EVP_PKEY *pkey = NULL;
600
601     if (desc == NULL)
602         desc = "public key";
603
604     if (format == FORMAT_ENGINE) {
605         if (e == NULL) {
606             BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
607         } else {
608 #ifndef OPENSSL_NO_ENGINE
609             PW_CB_DATA cb_data;
610
611             cb_data.password = pass;
612             cb_data.prompt_info = uri;
613             pkey = ENGINE_load_public_key(e, uri, (UI_METHOD *)get_ui_method(),
614                                           &cb_data);
615             if (pkey == NULL) {
616                 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
617                 ERR_print_errors(bio_err);
618             }
619 #else
620             BIO_printf(bio_err, "Engines not supported for loading %s\n", desc);
621 #endif
622         }
623     } else {
624         (void)load_key_certs_crls(uri, maybe_stdin, pass, desc,
625                                   NULL, &pkey, NULL, NULL, NULL, NULL);
626     }
627     if (pkey == NULL) {
628         BIO_printf(bio_err, "Unable to load %s\n", desc);
629         ERR_print_errors(bio_err);
630     }
631     return pkey;
632 }
633
634 void app_bail_out(char *fmt, ...)
635 {
636     va_list args;
637
638     va_start(args, fmt);
639     BIO_vprintf(bio_err, fmt, args);
640     va_end(args);
641     ERR_print_errors(bio_err);
642     exit(1);
643 }
644
645 void* app_malloc(int sz, const char *what)
646 {
647     void *vp = OPENSSL_malloc(sz);
648
649     if (vp == NULL)
650         app_bail_out("%s: Could not allocate %d bytes for %s\n",
651                      opt_getprog(), sz, what);
652     return vp;
653 }
654
655 /*
656  * Initialize or extend, if *certs != NULL, a certificate stack.
657  * The caller is responsible for freeing *certs if its value is left not NULL.
658  */
659 int load_certs(const char *uri, STACK_OF(X509) **certs,
660                const char *pass, const char *desc)
661 {
662     int was_NULL = *certs == NULL;
663     int ret = load_key_certs_crls(uri, 0, pass, desc, NULL, NULL,
664                                   NULL, certs, NULL, NULL);
665
666     if (!ret && was_NULL) {
667         sk_X509_pop_free(*certs, X509_free);
668         *certs = NULL;
669     }
670     return ret;
671 }
672
673 /*
674  * Initialize or extend, if *crls != NULL, a certificate stack.
675  * The caller is responsible for freeing *crls if its value is left not NULL.
676  */
677 int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
678               const char *pass, const char *desc)
679 {
680     int was_NULL = *crls == NULL;
681     int ret = load_key_certs_crls(uri, 0, pass, desc, NULL, NULL,
682                                   NULL, NULL, NULL, crls);
683
684     if (!ret && was_NULL) {
685         sk_X509_CRL_pop_free(*crls, X509_CRL_free);
686         *crls = NULL;
687     }
688     return ret;
689 }
690
691 /*
692  * Load those types of credentials for which the result pointer is not NULL.
693  * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
694  * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
695  * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
696  * If pcerts is non-NULL then all available certificates are appended to *pcerts
697  * except any certificate assigned to *pcert.
698  * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
699  * If pcrls is non-NULL then all available CRLs are appended to *pcerts
700  * except any CRL assigned to *pcrl.
701  * In any case (also on error) the caller is responsible for freeing all members
702  * of *pcerts and *pcrls (as far as they are not NULL).
703  */
704 int load_key_certs_crls(const char *uri, int maybe_stdin,
705                         const char *pass, const char *desc,
706                         EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
707                         X509 **pcert, STACK_OF(X509) **pcerts,
708                         X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
709 {
710     PW_CB_DATA uidata;
711     OSSL_STORE_CTX *ctx = NULL;
712     OPENSSL_CTX *libctx = app_get0_libctx();
713     const char *propq = app_get0_propq();
714     int ncerts = 0;
715     int ncrls = 0;
716     const char *failed = "any";
717     /* TODO make use of the engine reference 'eng' when loading pkeys */
718
719     if (ppkey != NULL)
720         *ppkey = NULL;
721     if (ppubkey != NULL)
722         *ppubkey = NULL;
723     if (pcert != NULL)
724         *pcert = NULL;
725     if (pcerts != NULL && *pcerts == NULL
726             && (*pcerts = sk_X509_new_null()) == NULL) {
727         BIO_printf(bio_err, "Out of memory");
728         goto end;
729     }
730     if (pcrl != NULL)
731         *pcrl = NULL;
732     if (pcrls != NULL && *pcrls == NULL
733             && (*pcrls = sk_X509_CRL_new_null()) == NULL) {
734         BIO_printf(bio_err, "Out of memory");
735         goto end;
736     }
737
738     if (desc == NULL)
739         desc = "key/certificate/CRL";
740     uidata.password = pass;
741     uidata.prompt_info = uri;
742
743     if (uri == NULL) {
744         BIO *bio;
745
746         uri = "<stdin>";
747         if (!maybe_stdin) {
748             BIO_printf(bio_err, "No filename or uri specified for loading %s\n",
749                        desc);
750             goto end;
751         }
752         unbuffer(stdin);
753         bio = BIO_new_fp(stdin, 0);
754         if (bio != NULL)
755             ctx = OSSL_STORE_attach(bio, "file", libctx, propq,
756                                     get_ui_method(), &uidata, NULL, NULL);
757     } else {
758         ctx = OSSL_STORE_open_with_libctx(uri, libctx, propq, get_ui_method(),
759                                           &uidata, NULL, NULL);
760     }
761     if (ctx == NULL) {
762         BIO_printf(bio_err, "Could not open file or uri %s for loading %s\n",
763                    uri, desc);
764         goto end;
765     }
766
767     failed = NULL;
768     while (!OSSL_STORE_eof(ctx)) {
769         OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
770         int type = info == NULL ? 0 : OSSL_STORE_INFO_get_type(info);
771         int ok = 1;
772
773         switch (type) {
774         case OSSL_STORE_INFO_PKEY:
775             if (ppkey != NULL && *ppkey == NULL)
776                 ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL;
777
778             /*
779              * An EVP_PKEY with private parts also holds the public parts,
780              * so if the caller asked for a public key, and we got a private
781              * key, we can still pass it back.
782              */
783             if (ok && ppubkey != NULL && *ppubkey == NULL)
784                 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL);
785             break;
786         case OSSL_STORE_INFO_PUBKEY:
787             if (ppubkey != NULL && *ppubkey == NULL)
788                 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL);
789             break;
790         case OSSL_STORE_INFO_CERT:
791             if (pcert != NULL && *pcert == NULL)
792                 ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL;
793             else if (pcerts != NULL)
794                 ok = X509_add_cert(*pcerts,
795                                    OSSL_STORE_INFO_get1_CERT(info),
796                                    X509_ADD_FLAG_DEFAULT);
797             ncerts += ok;
798             break;
799         case OSSL_STORE_INFO_CRL:
800             if (pcrl != NULL && *pcrl == NULL)
801                 ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL;
802             else if (pcrls != NULL)
803                 ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info));
804             ncrls += ok;
805             break;
806         default:
807             /* skip any other type */
808             break;
809         }
810         OSSL_STORE_INFO_free(info);
811         if (!ok) {
812             failed = info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
813             BIO_printf(bio_err, "Error reading %s of %s from %s\n",
814                        failed, desc, uri);
815             break;
816         }
817     }
818
819  end:
820     OSSL_STORE_close(ctx);
821     if (failed == NULL) {
822         if (ppkey != NULL && *ppkey == NULL)
823             failed = "key";
824         else if ((pcert != NULL || pcerts != NULL) && ncerts == 0)
825             failed = "cert";
826         else if ((pcrl != NULL || pcrls != NULL) && ncrls == 0)
827             failed = "CRL";
828         if (failed != NULL)
829             BIO_printf(bio_err, "Could not read any %s of %s from %s\n",
830                        failed, desc, uri);
831     }
832     if (failed != NULL)
833         ERR_print_errors(bio_err);
834     return failed == NULL;
835 }
836
837
838 #define X509V3_EXT_UNKNOWN_MASK         (0xfL << 16)
839 /* Return error for unknown extensions */
840 #define X509V3_EXT_DEFAULT              0
841 /* Print error for unknown extensions */
842 #define X509V3_EXT_ERROR_UNKNOWN        (1L << 16)
843 /* ASN1 parse unknown extensions */
844 #define X509V3_EXT_PARSE_UNKNOWN        (2L << 16)
845 /* BIO_dump unknown extensions */
846 #define X509V3_EXT_DUMP_UNKNOWN         (3L << 16)
847
848 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
849                          X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
850
851 int set_cert_ex(unsigned long *flags, const char *arg)
852 {
853     static const NAME_EX_TBL cert_tbl[] = {
854         {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
855         {"ca_default", X509_FLAG_CA, 0xffffffffl},
856         {"no_header", X509_FLAG_NO_HEADER, 0},
857         {"no_version", X509_FLAG_NO_VERSION, 0},
858         {"no_serial", X509_FLAG_NO_SERIAL, 0},
859         {"no_signame", X509_FLAG_NO_SIGNAME, 0},
860         {"no_validity", X509_FLAG_NO_VALIDITY, 0},
861         {"no_subject", X509_FLAG_NO_SUBJECT, 0},
862         {"no_issuer", X509_FLAG_NO_ISSUER, 0},
863         {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
864         {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
865         {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
866         {"no_aux", X509_FLAG_NO_AUX, 0},
867         {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
868         {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
869         {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
870         {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
871         {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
872         {NULL, 0, 0}
873     };
874     return set_multi_opts(flags, arg, cert_tbl);
875 }
876
877 int set_name_ex(unsigned long *flags, const char *arg)
878 {
879     static const NAME_EX_TBL ex_tbl[] = {
880         {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
881         {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
882         {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
883         {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
884         {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
885         {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
886         {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
887         {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
888         {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
889         {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
890         {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
891         {"compat", XN_FLAG_COMPAT, 0xffffffffL},
892         {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
893         {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
894         {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
895         {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
896         {"dn_rev", XN_FLAG_DN_REV, 0},
897         {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
898         {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
899         {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
900         {"align", XN_FLAG_FN_ALIGN, 0},
901         {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
902         {"space_eq", XN_FLAG_SPC_EQ, 0},
903         {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
904         {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
905         {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
906         {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
907         {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
908         {NULL, 0, 0}
909     };
910     if (set_multi_opts(flags, arg, ex_tbl) == 0)
911         return 0;
912     if (*flags != XN_FLAG_COMPAT
913         && (*flags & XN_FLAG_SEP_MASK) == 0)
914         *flags |= XN_FLAG_SEP_CPLUS_SPC;
915     return 1;
916 }
917
918 int set_ext_copy(int *copy_type, const char *arg)
919 {
920     if (strcasecmp(arg, "none") == 0)
921         *copy_type = EXT_COPY_NONE;
922     else if (strcasecmp(arg, "copy") == 0)
923         *copy_type = EXT_COPY_ADD;
924     else if (strcasecmp(arg, "copyall") == 0)
925         *copy_type = EXT_COPY_ALL;
926     else
927         return 0;
928     return 1;
929 }
930
931 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
932 {
933     STACK_OF(X509_EXTENSION) *exts = NULL;
934     X509_EXTENSION *ext, *tmpext;
935     ASN1_OBJECT *obj;
936     int i, idx, ret = 0;
937     if (!x || !req || (copy_type == EXT_COPY_NONE))
938         return 1;
939     exts = X509_REQ_get_extensions(req);
940
941     for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
942         ext = sk_X509_EXTENSION_value(exts, i);
943         obj = X509_EXTENSION_get_object(ext);
944         idx = X509_get_ext_by_OBJ(x, obj, -1);
945         /* Does extension exist? */
946         if (idx != -1) {
947             /* If normal copy don't override existing extension */
948             if (copy_type == EXT_COPY_ADD)
949                 continue;
950             /* Delete all extensions of same type */
951             do {
952                 tmpext = X509_get_ext(x, idx);
953                 X509_delete_ext(x, idx);
954                 X509_EXTENSION_free(tmpext);
955                 idx = X509_get_ext_by_OBJ(x, obj, -1);
956             } while (idx != -1);
957         }
958         if (!X509_add_ext(x, ext, -1))
959             goto end;
960     }
961
962     ret = 1;
963
964  end:
965
966     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
967
968     return ret;
969 }
970
971 static int set_multi_opts(unsigned long *flags, const char *arg,
972                           const NAME_EX_TBL * in_tbl)
973 {
974     STACK_OF(CONF_VALUE) *vals;
975     CONF_VALUE *val;
976     int i, ret = 1;
977     if (!arg)
978         return 0;
979     vals = X509V3_parse_list(arg);
980     for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
981         val = sk_CONF_VALUE_value(vals, i);
982         if (!set_table_opts(flags, val->name, in_tbl))
983             ret = 0;
984     }
985     sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
986     return ret;
987 }
988
989 static int set_table_opts(unsigned long *flags, const char *arg,
990                           const NAME_EX_TBL * in_tbl)
991 {
992     char c;
993     const NAME_EX_TBL *ptbl;
994     c = arg[0];
995
996     if (c == '-') {
997         c = 0;
998         arg++;
999     } else if (c == '+') {
1000         c = 1;
1001         arg++;
1002     } else {
1003         c = 1;
1004     }
1005
1006     for (ptbl = in_tbl; ptbl->name; ptbl++) {
1007         if (strcasecmp(arg, ptbl->name) == 0) {
1008             *flags &= ~ptbl->mask;
1009             if (c)
1010                 *flags |= ptbl->flag;
1011             else
1012                 *flags &= ~ptbl->flag;
1013             return 1;
1014         }
1015     }
1016     return 0;
1017 }
1018
1019 void print_name(BIO *out, const char *title, const X509_NAME *nm,
1020                 unsigned long lflags)
1021 {
1022     char *buf;
1023     char mline = 0;
1024     int indent = 0;
1025
1026     if (title)
1027         BIO_puts(out, title);
1028     if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1029         mline = 1;
1030         indent = 4;
1031     }
1032     if (lflags == XN_FLAG_COMPAT) {
1033         buf = X509_NAME_oneline(nm, 0, 0);
1034         BIO_puts(out, buf);
1035         BIO_puts(out, "\n");
1036         OPENSSL_free(buf);
1037     } else {
1038         if (mline)
1039             BIO_puts(out, "\n");
1040         X509_NAME_print_ex(out, nm, indent, lflags);
1041         BIO_puts(out, "\n");
1042     }
1043 }
1044
1045 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1046                       int len, unsigned char *buffer)
1047 {
1048     BIO_printf(out, "    static unsigned char %s_%d[] = {", var, len);
1049     if (BN_is_zero(in)) {
1050         BIO_printf(out, "\n        0x00");
1051     } else {
1052         int i, l;
1053
1054         l = BN_bn2bin(in, buffer);
1055         for (i = 0; i < l; i++) {
1056             BIO_printf(out, (i % 10) == 0 ? "\n        " : " ");
1057             if (i < l - 1)
1058                 BIO_printf(out, "0x%02X,", buffer[i]);
1059             else
1060                 BIO_printf(out, "0x%02X", buffer[i]);
1061         }
1062     }
1063     BIO_printf(out, "\n    };\n");
1064 }
1065
1066 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1067 {
1068     int i;
1069
1070     BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1071     for (i = 0; i < len; i++) {
1072         if ((i % 10) == 0)
1073             BIO_printf(out, "\n    ");
1074         if (i < len - 1)
1075             BIO_printf(out, "0x%02X, ", d[i]);
1076         else
1077             BIO_printf(out, "0x%02X", d[i]);
1078     }
1079     BIO_printf(out, "\n};\n");
1080 }
1081
1082 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1083                          const char *CApath, int noCApath,
1084                          const char *CAstore, int noCAstore)
1085 {
1086     X509_STORE *store = X509_STORE_new();
1087     X509_LOOKUP *lookup;
1088     OPENSSL_CTX *libctx = app_get0_libctx();
1089     const char *propq = app_get0_propq();
1090
1091     if (store == NULL)
1092         goto end;
1093
1094     if (CAfile != NULL || !noCAfile) {
1095         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1096         if (lookup == NULL)
1097             goto end;
1098         if (CAfile != NULL) {
1099             if (!X509_LOOKUP_load_file_with_libctx(lookup, CAfile,
1100                                                    X509_FILETYPE_PEM,
1101                                                    libctx, propq)) {
1102                 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1103                 goto end;
1104             }
1105         } else {
1106             X509_LOOKUP_load_file_with_libctx(lookup, NULL,
1107                                               X509_FILETYPE_DEFAULT,
1108                                               libctx, propq);
1109         }
1110     }
1111
1112     if (CApath != NULL || !noCApath) {
1113         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1114         if (lookup == NULL)
1115             goto end;
1116         if (CApath != NULL) {
1117             if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1118                 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1119                 goto end;
1120             }
1121         } else {
1122             X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1123         }
1124     }
1125
1126     if (CAstore != NULL || !noCAstore) {
1127         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1128         if (lookup == NULL)
1129             goto end;
1130         if (!X509_LOOKUP_add_store_with_libctx(lookup, CAstore, libctx, propq)) {
1131             if (CAstore != NULL)
1132                 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1133             goto end;
1134         }
1135     }
1136
1137     ERR_clear_error();
1138     return store;
1139  end:
1140     ERR_print_errors(bio_err);
1141     X509_STORE_free(store);
1142     return NULL;
1143 }
1144
1145 #ifndef OPENSSL_NO_ENGINE
1146 /* Try to load an engine in a shareable library */
1147 static ENGINE *try_load_engine(const char *engine)
1148 {
1149     ENGINE *e = ENGINE_by_id("dynamic");
1150     if (e) {
1151         if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1152             || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1153             ENGINE_free(e);
1154             e = NULL;
1155         }
1156     }
1157     return e;
1158 }
1159 #endif
1160
1161 ENGINE *setup_engine_methods(const char *id, unsigned int methods, int debug)
1162 {
1163     ENGINE *e = NULL;
1164
1165 #ifndef OPENSSL_NO_ENGINE
1166     if (id != NULL) {
1167         if (strcmp(id, "auto") == 0) {
1168             BIO_printf(bio_err, "Enabling auto ENGINE support\n");
1169             ENGINE_register_all_complete();
1170             return NULL;
1171         }
1172         if ((e = ENGINE_by_id(id)) == NULL
1173             && (e = try_load_engine(id)) == NULL) {
1174             BIO_printf(bio_err, "Invalid engine \"%s\"\n", id);
1175             ERR_print_errors(bio_err);
1176             return NULL;
1177         }
1178         if (debug)
1179             (void)ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1180         if (!ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0,
1181                              (void *)get_ui_method(), 0, 1)
1182                 || !ENGINE_set_default(e, methods)) {
1183             BIO_printf(bio_err, "Cannot use engine \"%s\"\n", ENGINE_get_id(e));
1184             ERR_print_errors(bio_err);
1185             ENGINE_free(e);
1186             return NULL;
1187         }
1188
1189         BIO_printf(bio_err, "Engine \"%s\" set.\n", ENGINE_get_id(e));
1190     }
1191 #endif
1192     return e;
1193 }
1194
1195 void release_engine(ENGINE *e)
1196 {
1197 #ifndef OPENSSL_NO_ENGINE
1198     /* Free our "structural" reference. */
1199     ENGINE_free(e);
1200 #endif
1201 }
1202
1203 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1204 {
1205     const char *n;
1206
1207     n = a[DB_serial];
1208     while (*n == '0')
1209         n++;
1210     return OPENSSL_LH_strhash(n);
1211 }
1212
1213 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1214                             const OPENSSL_CSTRING *b)
1215 {
1216     const char *aa, *bb;
1217
1218     for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1219     for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1220     return strcmp(aa, bb);
1221 }
1222
1223 static int index_name_qual(char **a)
1224 {
1225     return (a[0][0] == 'V');
1226 }
1227
1228 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1229 {
1230     return OPENSSL_LH_strhash(a[DB_name]);
1231 }
1232
1233 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1234 {
1235     return strcmp(a[DB_name], b[DB_name]);
1236 }
1237
1238 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1239 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1240 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1241 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1242 #undef BSIZE
1243 #define BSIZE 256
1244 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1245 {
1246     BIO *in = NULL;
1247     BIGNUM *ret = NULL;
1248     char buf[1024];
1249     ASN1_INTEGER *ai = NULL;
1250
1251     ai = ASN1_INTEGER_new();
1252     if (ai == NULL)
1253         goto err;
1254
1255     in = BIO_new_file(serialfile, "r");
1256     if (in == NULL) {
1257         if (!create) {
1258             perror(serialfile);
1259             goto err;
1260         }
1261         ERR_clear_error();
1262         ret = BN_new();
1263         if (ret == NULL || !rand_serial(ret, ai))
1264             BIO_printf(bio_err, "Out of memory\n");
1265     } else {
1266         if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1267             BIO_printf(bio_err, "Unable to load number from %s\n",
1268                        serialfile);
1269             goto err;
1270         }
1271         ret = ASN1_INTEGER_to_BN(ai, NULL);
1272         if (ret == NULL) {
1273             BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1274             goto err;
1275         }
1276     }
1277
1278     if (ret && retai) {
1279         *retai = ai;
1280         ai = NULL;
1281     }
1282  err:
1283     ERR_print_errors(bio_err);
1284     BIO_free(in);
1285     ASN1_INTEGER_free(ai);
1286     return ret;
1287 }
1288
1289 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1290                 ASN1_INTEGER **retai)
1291 {
1292     char buf[1][BSIZE];
1293     BIO *out = NULL;
1294     int ret = 0;
1295     ASN1_INTEGER *ai = NULL;
1296     int j;
1297
1298     if (suffix == NULL)
1299         j = strlen(serialfile);
1300     else
1301         j = strlen(serialfile) + strlen(suffix) + 1;
1302     if (j >= BSIZE) {
1303         BIO_printf(bio_err, "File name too long\n");
1304         goto err;
1305     }
1306
1307     if (suffix == NULL)
1308         OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1309     else {
1310 #ifndef OPENSSL_SYS_VMS
1311         j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1312 #else
1313         j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1314 #endif
1315     }
1316     out = BIO_new_file(buf[0], "w");
1317     if (out == NULL) {
1318         goto err;
1319     }
1320
1321     if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1322         BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1323         goto err;
1324     }
1325     i2a_ASN1_INTEGER(out, ai);
1326     BIO_puts(out, "\n");
1327     ret = 1;
1328     if (retai) {
1329         *retai = ai;
1330         ai = NULL;
1331     }
1332  err:
1333     if (!ret)
1334         ERR_print_errors(bio_err);
1335     BIO_free_all(out);
1336     ASN1_INTEGER_free(ai);
1337     return ret;
1338 }
1339
1340 int rotate_serial(const char *serialfile, const char *new_suffix,
1341                   const char *old_suffix)
1342 {
1343     char buf[2][BSIZE];
1344     int i, j;
1345
1346     i = strlen(serialfile) + strlen(old_suffix);
1347     j = strlen(serialfile) + strlen(new_suffix);
1348     if (i > j)
1349         j = i;
1350     if (j + 1 >= BSIZE) {
1351         BIO_printf(bio_err, "File name too long\n");
1352         goto err;
1353     }
1354 #ifndef OPENSSL_SYS_VMS
1355     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1356     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1357 #else
1358     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1359     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1360 #endif
1361     if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1362 #ifdef ENOTDIR
1363         && errno != ENOTDIR
1364 #endif
1365         ) {
1366         BIO_printf(bio_err,
1367                    "Unable to rename %s to %s\n", serialfile, buf[1]);
1368         perror("reason");
1369         goto err;
1370     }
1371     if (rename(buf[0], serialfile) < 0) {
1372         BIO_printf(bio_err,
1373                    "Unable to rename %s to %s\n", buf[0], serialfile);
1374         perror("reason");
1375         rename(buf[1], serialfile);
1376         goto err;
1377     }
1378     return 1;
1379  err:
1380     ERR_print_errors(bio_err);
1381     return 0;
1382 }
1383
1384 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1385 {
1386     BIGNUM *btmp;
1387     int ret = 0;
1388
1389     btmp = b == NULL ? BN_new() : b;
1390     if (btmp == NULL)
1391         return 0;
1392
1393     if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1394         goto error;
1395     if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1396         goto error;
1397
1398     ret = 1;
1399
1400  error:
1401
1402     if (btmp != b)
1403         BN_free(btmp);
1404
1405     return ret;
1406 }
1407
1408 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1409 {
1410     CA_DB *retdb = NULL;
1411     TXT_DB *tmpdb = NULL;
1412     BIO *in;
1413     CONF *dbattr_conf = NULL;
1414     char buf[BSIZE];
1415 #ifndef OPENSSL_NO_POSIX_IO
1416     FILE *dbfp;
1417     struct stat dbst;
1418 #endif
1419
1420     in = BIO_new_file(dbfile, "r");
1421     if (in == NULL)
1422         goto err;
1423
1424 #ifndef OPENSSL_NO_POSIX_IO
1425     BIO_get_fp(in, &dbfp);
1426     if (fstat(fileno(dbfp), &dbst) == -1) {
1427         ERR_raise_data(ERR_LIB_SYS, errno,
1428                        "calling fstat(%s)", dbfile);
1429         goto err;
1430     }
1431 #endif
1432
1433     if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1434         goto err;
1435
1436 #ifndef OPENSSL_SYS_VMS
1437     BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1438 #else
1439     BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1440 #endif
1441     dbattr_conf = app_load_config_quiet(buf);
1442
1443     retdb = app_malloc(sizeof(*retdb), "new DB");
1444     retdb->db = tmpdb;
1445     tmpdb = NULL;
1446     if (db_attr)
1447         retdb->attributes = *db_attr;
1448     else {
1449         retdb->attributes.unique_subject = 1;
1450     }
1451
1452     if (dbattr_conf) {
1453         char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1454         if (p) {
1455             retdb->attributes.unique_subject = parse_yesno(p, 1);
1456         }
1457     }
1458
1459     retdb->dbfname = OPENSSL_strdup(dbfile);
1460 #ifndef OPENSSL_NO_POSIX_IO
1461     retdb->dbst = dbst;
1462 #endif
1463
1464  err:
1465     ERR_print_errors(bio_err);
1466     NCONF_free(dbattr_conf);
1467     TXT_DB_free(tmpdb);
1468     BIO_free_all(in);
1469     return retdb;
1470 }
1471
1472 /*
1473  * Returns > 0 on success, <= 0 on error
1474  */
1475 int index_index(CA_DB *db)
1476 {
1477     if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1478                              LHASH_HASH_FN(index_serial),
1479                              LHASH_COMP_FN(index_serial))) {
1480         BIO_printf(bio_err,
1481                    "Error creating serial number index:(%ld,%ld,%ld)\n",
1482                    db->db->error, db->db->arg1, db->db->arg2);
1483         goto err;
1484     }
1485
1486     if (db->attributes.unique_subject
1487         && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1488                                 LHASH_HASH_FN(index_name),
1489                                 LHASH_COMP_FN(index_name))) {
1490         BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1491                    db->db->error, db->db->arg1, db->db->arg2);
1492         goto err;
1493     }
1494     return 1;
1495  err:
1496     ERR_print_errors(bio_err);
1497     return 0;
1498 }
1499
1500 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1501 {
1502     char buf[3][BSIZE];
1503     BIO *out;
1504     int j;
1505
1506     j = strlen(dbfile) + strlen(suffix);
1507     if (j + 6 >= BSIZE) {
1508         BIO_printf(bio_err, "File name too long\n");
1509         goto err;
1510     }
1511 #ifndef OPENSSL_SYS_VMS
1512     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1513     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1514     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1515 #else
1516     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1517     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1518     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1519 #endif
1520     out = BIO_new_file(buf[0], "w");
1521     if (out == NULL) {
1522         perror(dbfile);
1523         BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1524         goto err;
1525     }
1526     j = TXT_DB_write(out, db->db);
1527     BIO_free(out);
1528     if (j <= 0)
1529         goto err;
1530
1531     out = BIO_new_file(buf[1], "w");
1532     if (out == NULL) {
1533         perror(buf[2]);
1534         BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1535         goto err;
1536     }
1537     BIO_printf(out, "unique_subject = %s\n",
1538                db->attributes.unique_subject ? "yes" : "no");
1539     BIO_free(out);
1540
1541     return 1;
1542  err:
1543     ERR_print_errors(bio_err);
1544     return 0;
1545 }
1546
1547 int rotate_index(const char *dbfile, const char *new_suffix,
1548                  const char *old_suffix)
1549 {
1550     char buf[5][BSIZE];
1551     int i, j;
1552
1553     i = strlen(dbfile) + strlen(old_suffix);
1554     j = strlen(dbfile) + strlen(new_suffix);
1555     if (i > j)
1556         j = i;
1557     if (j + 6 >= BSIZE) {
1558         BIO_printf(bio_err, "File name too long\n");
1559         goto err;
1560     }
1561 #ifndef OPENSSL_SYS_VMS
1562     j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1563     j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1564     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1565     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1566     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1567 #else
1568     j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1569     j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1570     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1571     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1572     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1573 #endif
1574     if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1575 #ifdef ENOTDIR
1576         && errno != ENOTDIR
1577 #endif
1578         ) {
1579         BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1580         perror("reason");
1581         goto err;
1582     }
1583     if (rename(buf[0], dbfile) < 0) {
1584         BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1585         perror("reason");
1586         rename(buf[1], dbfile);
1587         goto err;
1588     }
1589     if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1590 #ifdef ENOTDIR
1591         && errno != ENOTDIR
1592 #endif
1593         ) {
1594         BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1595         perror("reason");
1596         rename(dbfile, buf[0]);
1597         rename(buf[1], dbfile);
1598         goto err;
1599     }
1600     if (rename(buf[2], buf[4]) < 0) {
1601         BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1602         perror("reason");
1603         rename(buf[3], buf[4]);
1604         rename(dbfile, buf[0]);
1605         rename(buf[1], dbfile);
1606         goto err;
1607     }
1608     return 1;
1609  err:
1610     ERR_print_errors(bio_err);
1611     return 0;
1612 }
1613
1614 void free_index(CA_DB *db)
1615 {
1616     if (db) {
1617         TXT_DB_free(db->db);
1618         OPENSSL_free(db->dbfname);
1619         OPENSSL_free(db);
1620     }
1621 }
1622
1623 int parse_yesno(const char *str, int def)
1624 {
1625     if (str) {
1626         switch (*str) {
1627         case 'f':              /* false */
1628         case 'F':              /* FALSE */
1629         case 'n':              /* no */
1630         case 'N':              /* NO */
1631         case '0':              /* 0 */
1632             return 0;
1633         case 't':              /* true */
1634         case 'T':              /* TRUE */
1635         case 'y':              /* yes */
1636         case 'Y':              /* YES */
1637         case '1':              /* 1 */
1638             return 1;
1639         }
1640     }
1641     return def;
1642 }
1643
1644 /*
1645  * name is expected to be in the format /type0=value0/type1=value1/type2=...
1646  * where + can be used instead of / to form multi-valued RDNs if canmulti
1647  * and characters may be escaped by \
1648  */
1649 X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
1650                       const char *desc)
1651 {
1652     int nextismulti = 0;
1653     char *work;
1654     X509_NAME *n;
1655
1656     if (*cp++ != '/') {
1657         BIO_printf(bio_err,
1658                    "%s: %s name is expected to be in the format "
1659                    "/type0=value0/type1=value1/type2=... where characters may "
1660                    "be escaped by \\. This name is not in that format: '%s'\n",
1661                    opt_getprog(), desc, --cp);
1662         return NULL;
1663     }
1664
1665     n = X509_NAME_new();
1666     if (n == NULL) {
1667         BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
1668         return NULL;
1669     }
1670     work = OPENSSL_strdup(cp);
1671     if (work == NULL) {
1672         BIO_printf(bio_err, "%s: Error copying %s name input\n",
1673                    opt_getprog(), desc);
1674         goto err;
1675     }
1676
1677     while (*cp != '\0') {
1678         char *bp = work;
1679         char *typestr = bp;
1680         unsigned char *valstr;
1681         int nid;
1682         int ismulti = nextismulti;
1683         nextismulti = 0;
1684
1685         /* Collect the type */
1686         while (*cp != '\0' && *cp != '=')
1687             *bp++ = *cp++;
1688         *bp++ = '\0';
1689         if (*cp == '\0') {
1690             BIO_printf(bio_err,
1691                        "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1692                        opt_getprog(), typestr, desc);
1693             goto err;
1694         }
1695         ++cp;
1696
1697         /* Collect the value. */
1698         valstr = (unsigned char *)bp;
1699         for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
1700             /* unescaped '+' symbol string signals further member of multiRDN */
1701             if (canmulti && *cp == '+') {
1702                 nextismulti = 1;
1703                 break;
1704             }
1705             if (*cp == '\\' && *++cp == '\0') {
1706                 BIO_printf(bio_err,
1707                            "%s: Escape character at end of %s name string\n",
1708                            opt_getprog(), desc);
1709                 goto err;
1710             }
1711         }
1712         *bp++ = '\0';
1713
1714         /* If not at EOS (must be + or /), move forward. */
1715         if (*cp != '\0')
1716             ++cp;
1717
1718         /* Parse */
1719         nid = OBJ_txt2nid(typestr);
1720         if (nid == NID_undef) {
1721             BIO_printf(bio_err,
1722                        "%s: Skipping unknown %s name attribute \"%s\"\n",
1723                        opt_getprog(), desc, typestr);
1724             if (ismulti)
1725                 BIO_printf(bio_err,
1726                            "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
1727             continue;
1728         }
1729         if (*valstr == '\0') {
1730             BIO_printf(bio_err,
1731                        "%s: No value provided for %s name attribute \"%s\", skipped\n",
1732                        opt_getprog(), desc, typestr);
1733             continue;
1734         }
1735         if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1736                                         valstr, strlen((char *)valstr),
1737                                         -1, ismulti ? -1 : 0)) {
1738             ERR_print_errors(bio_err);
1739             BIO_printf(bio_err,
1740                        "%s: Error adding %s name attribute \"/%s=%s\"\n",
1741                        opt_getprog(), desc, typestr ,valstr);
1742             goto err;
1743         }
1744     }
1745
1746     OPENSSL_free(work);
1747     return n;
1748
1749  err:
1750     X509_NAME_free(n);
1751     OPENSSL_free(work);
1752     return NULL;
1753 }
1754
1755 /*
1756  * Read whole contents of a BIO into an allocated memory buffer and return
1757  * it.
1758  */
1759
1760 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1761 {
1762     BIO *mem;
1763     int len, ret;
1764     unsigned char tbuf[1024];
1765
1766     mem = BIO_new(BIO_s_mem());
1767     if (mem == NULL)
1768         return -1;
1769     for (;;) {
1770         if ((maxlen != -1) && maxlen < 1024)
1771             len = maxlen;
1772         else
1773             len = 1024;
1774         len = BIO_read(in, tbuf, len);
1775         if (len < 0) {
1776             BIO_free(mem);
1777             return -1;
1778         }
1779         if (len == 0)
1780             break;
1781         if (BIO_write(mem, tbuf, len) != len) {
1782             BIO_free(mem);
1783             return -1;
1784         }
1785         maxlen -= len;
1786
1787         if (maxlen == 0)
1788             break;
1789     }
1790     ret = BIO_get_mem_data(mem, (char **)out);
1791     BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1792     BIO_free(mem);
1793     return ret;
1794 }
1795
1796 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1797 {
1798     int rv;
1799     char *stmp, *vtmp = NULL;
1800     stmp = OPENSSL_strdup(value);
1801     if (!stmp)
1802         return -1;
1803     vtmp = strchr(stmp, ':');
1804     if (vtmp) {
1805         *vtmp = 0;
1806         vtmp++;
1807     }
1808     rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1809     OPENSSL_free(stmp);
1810     return rv;
1811 }
1812
1813 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1814 {
1815     X509_POLICY_NODE *node;
1816     int i;
1817
1818     BIO_printf(bio_err, "%s Policies:", name);
1819     if (nodes) {
1820         BIO_puts(bio_err, "\n");
1821         for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1822             node = sk_X509_POLICY_NODE_value(nodes, i);
1823             X509_POLICY_NODE_print(bio_err, node, 2);
1824         }
1825     } else {
1826         BIO_puts(bio_err, " <empty>\n");
1827     }
1828 }
1829
1830 void policies_print(X509_STORE_CTX *ctx)
1831 {
1832     X509_POLICY_TREE *tree;
1833     int explicit_policy;
1834     tree = X509_STORE_CTX_get0_policy_tree(ctx);
1835     explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1836
1837     BIO_printf(bio_err, "Require explicit Policy: %s\n",
1838                explicit_policy ? "True" : "False");
1839
1840     nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1841     nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1842 }
1843
1844 /*-
1845  * next_protos_parse parses a comma separated list of strings into a string
1846  * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1847  *   outlen: (output) set to the length of the resulting buffer on success.
1848  *   err: (maybe NULL) on failure, an error message line is written to this BIO.
1849  *   in: a NUL terminated string like "abc,def,ghi"
1850  *
1851  *   returns: a malloc'd buffer or NULL on failure.
1852  */
1853 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1854 {
1855     size_t len;
1856     unsigned char *out;
1857     size_t i, start = 0;
1858     size_t skipped = 0;
1859
1860     len = strlen(in);
1861     if (len == 0 || len >= 65535)
1862         return NULL;
1863
1864     out = app_malloc(len + 1, "NPN buffer");
1865     for (i = 0; i <= len; ++i) {
1866         if (i == len || in[i] == ',') {
1867             /*
1868              * Zero-length ALPN elements are invalid on the wire, we could be
1869              * strict and reject the entire string, but just ignoring extra
1870              * commas seems harmless and more friendly.
1871              *
1872              * Every comma we skip in this way puts the input buffer another
1873              * byte ahead of the output buffer, so all stores into the output
1874              * buffer need to be decremented by the number commas skipped.
1875              */
1876             if (i == start) {
1877                 ++start;
1878                 ++skipped;
1879                 continue;
1880             }
1881             if (i - start > 255) {
1882                 OPENSSL_free(out);
1883                 return NULL;
1884             }
1885             out[start-skipped] = (unsigned char)(i - start);
1886             start = i + 1;
1887         } else {
1888             out[i + 1 - skipped] = in[i];
1889         }
1890     }
1891
1892     if (len <= skipped) {
1893         OPENSSL_free(out);
1894         return NULL;
1895     }
1896
1897     *outlen = len + 1 - skipped;
1898     return out;
1899 }
1900
1901 void print_cert_checks(BIO *bio, X509 *x,
1902                        const char *checkhost,
1903                        const char *checkemail, const char *checkip)
1904 {
1905     if (x == NULL)
1906         return;
1907     if (checkhost) {
1908         BIO_printf(bio, "Hostname %s does%s match certificate\n",
1909                    checkhost,
1910                    X509_check_host(x, checkhost, 0, 0, NULL) == 1
1911                        ? "" : " NOT");
1912     }
1913
1914     if (checkemail) {
1915         BIO_printf(bio, "Email %s does%s match certificate\n",
1916                    checkemail, X509_check_email(x, checkemail, 0, 0)
1917                    ? "" : " NOT");
1918     }
1919
1920     if (checkip) {
1921         BIO_printf(bio, "IP %s does%s match certificate\n",
1922                    checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1923     }
1924 }
1925
1926 /* Get first http URL from a DIST_POINT structure */
1927
1928 static const char *get_dp_url(DIST_POINT *dp)
1929 {
1930     GENERAL_NAMES *gens;
1931     GENERAL_NAME *gen;
1932     int i, gtype;
1933     ASN1_STRING *uri;
1934     if (!dp->distpoint || dp->distpoint->type != 0)
1935         return NULL;
1936     gens = dp->distpoint->name.fullname;
1937     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1938         gen = sk_GENERAL_NAME_value(gens, i);
1939         uri = GENERAL_NAME_get0_value(gen, &gtype);
1940         if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1941             const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
1942             if (strncmp(uptr, "http://", 7) == 0)
1943                 return uptr;
1944         }
1945     }
1946     return NULL;
1947 }
1948
1949 /*
1950  * Look through a CRLDP structure and attempt to find an http URL to
1951  * downloads a CRL from.
1952  */
1953
1954 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1955 {
1956     int i;
1957     const char *urlptr = NULL;
1958     for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1959         DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1960         urlptr = get_dp_url(dp);
1961         if (urlptr)
1962             return load_crl(urlptr, FORMAT_HTTP, "CRL via CDP");
1963     }
1964     return NULL;
1965 }
1966
1967 /*
1968  * Example of downloading CRLs from CRLDP:
1969  * not usable for real world as it always downloads and doesn't cache anything.
1970  */
1971
1972 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
1973                                         const X509_NAME *nm)
1974 {
1975     X509 *x;
1976     STACK_OF(X509_CRL) *crls = NULL;
1977     X509_CRL *crl;
1978     STACK_OF(DIST_POINT) *crldp;
1979
1980     crls = sk_X509_CRL_new_null();
1981     if (!crls)
1982         return NULL;
1983     x = X509_STORE_CTX_get_current_cert(ctx);
1984     crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
1985     crl = load_crl_crldp(crldp);
1986     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1987     if (!crl) {
1988         sk_X509_CRL_free(crls);
1989         return NULL;
1990     }
1991     sk_X509_CRL_push(crls, crl);
1992     /* Try to download delta CRL */
1993     crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
1994     crl = load_crl_crldp(crldp);
1995     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1996     if (crl)
1997         sk_X509_CRL_push(crls, crl);
1998     return crls;
1999 }
2000
2001 void store_setup_crl_download(X509_STORE *st)
2002 {
2003     X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2004 }
2005
2006 #ifndef OPENSSL_NO_SOCK
2007 static const char *tls_error_hint(void)
2008 {
2009     unsigned long err = ERR_peek_error();
2010
2011     if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2012         err = ERR_peek_last_error();
2013     if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2014         return NULL;
2015
2016     switch (ERR_GET_REASON(err)) {
2017     case SSL_R_WRONG_VERSION_NUMBER:
2018         return "The server does not support (a suitable version of) TLS";
2019     case SSL_R_UNKNOWN_PROTOCOL:
2020         return "The server does not support HTTPS";
2021     case SSL_R_CERTIFICATE_VERIFY_FAILED:
2022         return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2023     case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
2024         return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2025     case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
2026         return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2027     default: /* no error or no hint available for error */
2028         return NULL;
2029     }
2030 }
2031
2032 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
2033 BIO *app_http_tls_cb(BIO *hbio, void *arg, int connect, int detail)
2034 {
2035     APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
2036     SSL_CTX *ssl_ctx = info->ssl_ctx;
2037     SSL *ssl;
2038     BIO *sbio = NULL;
2039
2040     if (connect && detail) { /* connecting with TLS */
2041         if ((info->use_proxy
2042              && !OSSL_HTTP_proxy_connect(hbio, info->server, info->port,
2043                                          NULL, NULL, /* no proxy credentials */
2044                                          info->timeout, bio_err, opt_getprog()))
2045                 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
2046             return NULL;
2047         }
2048         if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
2049             BIO_free(sbio);
2050             return NULL;
2051         }
2052
2053         SSL_set_tlsext_host_name(ssl, info->server);
2054
2055         SSL_set_connect_state(ssl);
2056         BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2057
2058         hbio = BIO_push(sbio, hbio);
2059     } else if (!connect && !detail) { /* disconnecting after error */
2060         const char *hint = tls_error_hint();
2061         if (hint != NULL)
2062             ERR_add_error_data(2, " : ", hint);
2063         /*
2064          * If we pop sbio and BIO_free() it this may lead to libssl double free.
2065          * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2066          */
2067     }
2068     return hbio;
2069 }
2070
2071 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2072                               const char *no_proxy, SSL_CTX *ssl_ctx,
2073                               const STACK_OF(CONF_VALUE) *headers,
2074                               long timeout, const char *expected_content_type,
2075                               const ASN1_ITEM *it)
2076 {
2077     APP_HTTP_TLS_INFO info;
2078     char *server;
2079     char *port;
2080     int use_ssl;
2081     ASN1_VALUE *resp = NULL;
2082
2083     if (url == NULL || it == NULL) {
2084         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2085         return NULL;
2086     }
2087
2088     if (!OSSL_HTTP_parse_url(url, &server, &port, NULL, NULL, &use_ssl))
2089         return NULL;
2090     if (use_ssl && ssl_ctx == NULL) {
2091         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2092         ERR_add_error_data(1, "missing SSL_CTX");
2093         goto end;
2094     }
2095
2096     info.server = server;
2097     info.port = port;
2098     info.use_proxy = proxy != NULL;
2099     info.timeout = timeout;
2100     info.ssl_ctx = ssl_ctx;
2101     resp = OSSL_HTTP_get_asn1(url, proxy, no_proxy,
2102                               NULL, NULL, app_http_tls_cb, &info,
2103                               headers, 0 /* maxline */, 0 /* max_resp_len */,
2104                               timeout, expected_content_type, it);
2105  end:
2106     OPENSSL_free(server);
2107     OPENSSL_free(port);
2108     return resp;
2109
2110 }
2111
2112 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2113                                const char *path, const char *proxy,
2114                                const char *no_proxy, SSL_CTX *ssl_ctx,
2115                                const STACK_OF(CONF_VALUE) *headers,
2116                                const char *content_type,
2117                                ASN1_VALUE *req, const ASN1_ITEM *req_it,
2118                                long timeout, const ASN1_ITEM *rsp_it)
2119 {
2120     APP_HTTP_TLS_INFO info;
2121
2122     info.server = host;
2123     info.port = port;
2124     info.use_proxy = proxy != NULL;
2125     info.timeout = timeout;
2126     info.ssl_ctx = ssl_ctx;
2127     return OSSL_HTTP_post_asn1(host, port, path, ssl_ctx != NULL,
2128                                proxy, no_proxy,
2129                                NULL, NULL, app_http_tls_cb, &info,
2130                                headers, content_type, req, req_it,
2131                                0 /* maxline */,
2132                                0 /* max_resp_len */, timeout, NULL, rsp_it);
2133 }
2134
2135 #endif
2136
2137 /*
2138  * Platform-specific sections
2139  */
2140 #if defined(_WIN32)
2141 # ifdef fileno
2142 #  undef fileno
2143 #  define fileno(a) (int)_fileno(a)
2144 # endif
2145
2146 # include <windows.h>
2147 # include <tchar.h>
2148
2149 static int WIN32_rename(const char *from, const char *to)
2150 {
2151     TCHAR *tfrom = NULL, *tto;
2152     DWORD err;
2153     int ret = 0;
2154
2155     if (sizeof(TCHAR) == 1) {
2156         tfrom = (TCHAR *)from;
2157         tto = (TCHAR *)to;
2158     } else {                    /* UNICODE path */
2159
2160         size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2161         tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2162         if (tfrom == NULL)
2163             goto err;
2164         tto = tfrom + flen;
2165 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2166         if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2167 # endif
2168             for (i = 0; i < flen; i++)
2169                 tfrom[i] = (TCHAR)from[i];
2170 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2171         if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2172 # endif
2173             for (i = 0; i < tlen; i++)
2174                 tto[i] = (TCHAR)to[i];
2175     }
2176
2177     if (MoveFile(tfrom, tto))
2178         goto ok;
2179     err = GetLastError();
2180     if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2181         if (DeleteFile(tto) && MoveFile(tfrom, tto))
2182             goto ok;
2183         err = GetLastError();
2184     }
2185     if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2186         errno = ENOENT;
2187     else if (err == ERROR_ACCESS_DENIED)
2188         errno = EACCES;
2189     else
2190         errno = EINVAL;         /* we could map more codes... */
2191  err:
2192     ret = -1;
2193  ok:
2194     if (tfrom != NULL && tfrom != (TCHAR *)from)
2195         free(tfrom);
2196     return ret;
2197 }
2198 #endif
2199
2200 /* app_tminterval section */
2201 #if defined(_WIN32)
2202 double app_tminterval(int stop, int usertime)
2203 {
2204     FILETIME now;
2205     double ret = 0;
2206     static ULARGE_INTEGER tmstart;
2207     static int warning = 1;
2208 # ifdef _WIN32_WINNT
2209     static HANDLE proc = NULL;
2210
2211     if (proc == NULL) {
2212         if (check_winnt())
2213             proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2214                                GetCurrentProcessId());
2215         if (proc == NULL)
2216             proc = (HANDLE) - 1;
2217     }
2218
2219     if (usertime && proc != (HANDLE) - 1) {
2220         FILETIME junk;
2221         GetProcessTimes(proc, &junk, &junk, &junk, &now);
2222     } else
2223 # endif
2224     {
2225         SYSTEMTIME systime;
2226
2227         if (usertime && warning) {
2228             BIO_printf(bio_err, "To get meaningful results, run "
2229                        "this program on idle system.\n");
2230             warning = 0;
2231         }
2232         GetSystemTime(&systime);
2233         SystemTimeToFileTime(&systime, &now);
2234     }
2235
2236     if (stop == TM_START) {
2237         tmstart.u.LowPart = now.dwLowDateTime;
2238         tmstart.u.HighPart = now.dwHighDateTime;
2239     } else {
2240         ULARGE_INTEGER tmstop;
2241
2242         tmstop.u.LowPart = now.dwLowDateTime;
2243         tmstop.u.HighPart = now.dwHighDateTime;
2244
2245         ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2246     }
2247
2248     return ret;
2249 }
2250 #elif defined(OPENSSL_SYS_VXWORKS)
2251 # include <time.h>
2252
2253 double app_tminterval(int stop, int usertime)
2254 {
2255     double ret = 0;
2256 # ifdef CLOCK_REALTIME
2257     static struct timespec tmstart;
2258     struct timespec now;
2259 # else
2260     static unsigned long tmstart;
2261     unsigned long now;
2262 # endif
2263     static int warning = 1;
2264
2265     if (usertime && warning) {
2266         BIO_printf(bio_err, "To get meaningful results, run "
2267                    "this program on idle system.\n");
2268         warning = 0;
2269     }
2270 # ifdef CLOCK_REALTIME
2271     clock_gettime(CLOCK_REALTIME, &now);
2272     if (stop == TM_START)
2273         tmstart = now;
2274     else
2275         ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2276                - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2277 # else
2278     now = tickGet();
2279     if (stop == TM_START)
2280         tmstart = now;
2281     else
2282         ret = (now - tmstart) / (double)sysClkRateGet();
2283 # endif
2284     return ret;
2285 }
2286
2287 #elif defined(_SC_CLK_TCK)      /* by means of unistd.h */
2288 # include <sys/times.h>
2289
2290 double app_tminterval(int stop, int usertime)
2291 {
2292     double ret = 0;
2293     struct tms rus;
2294     clock_t now = times(&rus);
2295     static clock_t tmstart;
2296
2297     if (usertime)
2298         now = rus.tms_utime;
2299
2300     if (stop == TM_START) {
2301         tmstart = now;
2302     } else {
2303         long int tck = sysconf(_SC_CLK_TCK);
2304         ret = (now - tmstart) / (double)tck;
2305     }
2306
2307     return ret;
2308 }
2309
2310 #else
2311 # include <sys/time.h>
2312 # include <sys/resource.h>
2313
2314 double app_tminterval(int stop, int usertime)
2315 {
2316     double ret = 0;
2317     struct rusage rus;
2318     struct timeval now;
2319     static struct timeval tmstart;
2320
2321     if (usertime)
2322         getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2323     else
2324         gettimeofday(&now, NULL);
2325
2326     if (stop == TM_START)
2327         tmstart = now;
2328     else
2329         ret = ((now.tv_sec + now.tv_usec * 1e-6)
2330                - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2331
2332     return ret;
2333 }
2334 #endif
2335
2336 int app_access(const char* name, int flag)
2337 {
2338 #ifdef _WIN32
2339     return _access(name, flag);
2340 #else
2341     return access(name, flag);
2342 #endif
2343 }
2344
2345 int app_isdir(const char *name)
2346 {
2347     return opt_isdir(name);
2348 }
2349
2350 /* raw_read|write section */
2351 #if defined(__VMS)
2352 # include "vms_term_sock.h"
2353 static int stdin_sock = -1;
2354
2355 static void close_stdin_sock(void)
2356 {
2357     TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2358 }
2359
2360 int fileno_stdin(void)
2361 {
2362     if (stdin_sock == -1) {
2363         TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2364         atexit(close_stdin_sock);
2365     }
2366
2367     return stdin_sock;
2368 }
2369 #else
2370 int fileno_stdin(void)
2371 {
2372     return fileno(stdin);
2373 }
2374 #endif
2375
2376 int fileno_stdout(void)
2377 {
2378     return fileno(stdout);
2379 }
2380
2381 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2382 int raw_read_stdin(void *buf, int siz)
2383 {
2384     DWORD n;
2385     if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2386         return n;
2387     else
2388         return -1;
2389 }
2390 #elif defined(__VMS)
2391 # include <sys/socket.h>
2392
2393 int raw_read_stdin(void *buf, int siz)
2394 {
2395     return recv(fileno_stdin(), buf, siz, 0);
2396 }
2397 #else
2398 # if defined(__TANDEM)
2399 #  if defined(OPENSSL_TANDEM_FLOSS)
2400 #   include <floss.h(floss_read)>
2401 #  endif
2402 # endif
2403 int raw_read_stdin(void *buf, int siz)
2404 {
2405     return read(fileno_stdin(), buf, siz);
2406 }
2407 #endif
2408
2409 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2410 int raw_write_stdout(const void *buf, int siz)
2411 {
2412     DWORD n;
2413     if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2414         return n;
2415     else
2416         return -1;
2417 }
2418 #elif defined(OPENSSL_SYSNAME_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
2419 # if defined(__TANDEM)
2420 #  if defined(OPENSSL_TANDEM_FLOSS)
2421 #   include <floss.h(floss_write)>
2422 #  endif
2423 # endif
2424 int raw_write_stdout(const void *buf,int siz)
2425 {
2426         return write(fileno(stdout),(void*)buf,siz);
2427 }
2428 #else
2429 # if defined(__TANDEM)
2430 #  if defined(OPENSSL_TANDEM_FLOSS)
2431 #   include <floss.h(floss_write)>
2432 #  endif
2433 # endif
2434 int raw_write_stdout(const void *buf, int siz)
2435 {
2436     return write(fileno_stdout(), buf, siz);
2437 }
2438 #endif
2439
2440 /*
2441  * Centralized handling of input and output files with format specification
2442  * The format is meant to show what the input and output is supposed to be,
2443  * and is therefore a show of intent more than anything else.  However, it
2444  * does impact behavior on some platforms, such as differentiating between
2445  * text and binary input/output on non-Unix platforms
2446  */
2447 BIO *dup_bio_in(int format)
2448 {
2449     return BIO_new_fp(stdin,
2450                       BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2451 }
2452
2453 BIO *dup_bio_out(int format)
2454 {
2455     BIO *b = BIO_new_fp(stdout,
2456                         BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2457     void *prefix = NULL;
2458
2459 #ifdef OPENSSL_SYS_VMS
2460     if (FMT_istext(format))
2461         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2462 #endif
2463
2464     if (FMT_istext(format)
2465         && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2466         b = BIO_push(BIO_new(BIO_f_prefix()), b);
2467         BIO_set_prefix(b, prefix);
2468     }
2469
2470     return b;
2471 }
2472
2473 BIO *dup_bio_err(int format)
2474 {
2475     BIO *b = BIO_new_fp(stderr,
2476                         BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2477 #ifdef OPENSSL_SYS_VMS
2478     if (FMT_istext(format))
2479         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2480 #endif
2481     return b;
2482 }
2483
2484 void unbuffer(FILE *fp)
2485 {
2486 /*
2487  * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2488  * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2489  * However, we trust that the C RTL will never give us a FILE pointer
2490  * above the first 4 GB of memory, so we simply turn off the warning
2491  * temporarily.
2492  */
2493 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2494 # pragma environment save
2495 # pragma message disable maylosedata2
2496 #endif
2497     setbuf(fp, NULL);
2498 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2499 # pragma environment restore
2500 #endif
2501 }
2502
2503 static const char *modestr(char mode, int format)
2504 {
2505     OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2506
2507     switch (mode) {
2508     case 'a':
2509         return FMT_istext(format) ? "a" : "ab";
2510     case 'r':
2511         return FMT_istext(format) ? "r" : "rb";
2512     case 'w':
2513         return FMT_istext(format) ? "w" : "wb";
2514     }
2515     /* The assert above should make sure we never reach this point */
2516     return NULL;
2517 }
2518
2519 static const char *modeverb(char mode)
2520 {
2521     switch (mode) {
2522     case 'a':
2523         return "appending";
2524     case 'r':
2525         return "reading";
2526     case 'w':
2527         return "writing";
2528     }
2529     return "(doing something)";
2530 }
2531
2532 /*
2533  * Open a file for writing, owner-read-only.
2534  */
2535 BIO *bio_open_owner(const char *filename, int format, int private)
2536 {
2537     FILE *fp = NULL;
2538     BIO *b = NULL;
2539     int fd = -1, bflags, mode, textmode;
2540
2541     if (!private || filename == NULL || strcmp(filename, "-") == 0)
2542         return bio_open_default(filename, 'w', format);
2543
2544     mode = O_WRONLY;
2545 #ifdef O_CREAT
2546     mode |= O_CREAT;
2547 #endif
2548 #ifdef O_TRUNC
2549     mode |= O_TRUNC;
2550 #endif
2551     textmode = FMT_istext(format);
2552     if (!textmode) {
2553 #ifdef O_BINARY
2554         mode |= O_BINARY;
2555 #elif defined(_O_BINARY)
2556         mode |= _O_BINARY;
2557 #endif
2558     }
2559
2560 #ifdef OPENSSL_SYS_VMS
2561     /* VMS doesn't have O_BINARY, it just doesn't make sense.  But,
2562      * it still needs to know that we're going binary, or fdopen()
2563      * will fail with "invalid argument"...  so we tell VMS what the
2564      * context is.
2565      */
2566     if (!textmode)
2567         fd = open(filename, mode, 0600, "ctx=bin");
2568     else
2569 #endif
2570         fd = open(filename, mode, 0600);
2571     if (fd < 0)
2572         goto err;
2573     fp = fdopen(fd, modestr('w', format));
2574     if (fp == NULL)
2575         goto err;
2576     bflags = BIO_CLOSE;
2577     if (textmode)
2578         bflags |= BIO_FP_TEXT;
2579     b = BIO_new_fp(fp, bflags);
2580     if (b)
2581         return b;
2582
2583  err:
2584     BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2585                opt_getprog(), filename, strerror(errno));
2586     ERR_print_errors(bio_err);
2587     /* If we have fp, then fdopen took over fd, so don't close both. */
2588     if (fp)
2589         fclose(fp);
2590     else if (fd >= 0)
2591         close(fd);
2592     return NULL;
2593 }
2594
2595 static BIO *bio_open_default_(const char *filename, char mode, int format,
2596                               int quiet)
2597 {
2598     BIO *ret;
2599
2600     if (filename == NULL || strcmp(filename, "-") == 0) {
2601         ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2602         if (quiet) {
2603             ERR_clear_error();
2604             return ret;
2605         }
2606         if (ret != NULL)
2607             return ret;
2608         BIO_printf(bio_err,
2609                    "Can't open %s, %s\n",
2610                    mode == 'r' ? "stdin" : "stdout", strerror(errno));
2611     } else {
2612         ret = BIO_new_file(filename, modestr(mode, format));
2613         if (quiet) {
2614             ERR_clear_error();
2615             return ret;
2616         }
2617         if (ret != NULL)
2618             return ret;
2619         BIO_printf(bio_err,
2620                    "Can't open %s for %s, %s\n",
2621                    filename, modeverb(mode), strerror(errno));
2622     }
2623     ERR_print_errors(bio_err);
2624     return NULL;
2625 }
2626
2627 BIO *bio_open_default(const char *filename, char mode, int format)
2628 {
2629     return bio_open_default_(filename, mode, format, 0);
2630 }
2631
2632 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2633 {
2634     return bio_open_default_(filename, mode, format, 1);
2635 }
2636
2637 void wait_for_async(SSL *s)
2638 {
2639     /* On Windows select only works for sockets, so we simply don't wait  */
2640 #ifndef OPENSSL_SYS_WINDOWS
2641     int width = 0;
2642     fd_set asyncfds;
2643     OSSL_ASYNC_FD *fds;
2644     size_t numfds;
2645     size_t i;
2646
2647     if (!SSL_get_all_async_fds(s, NULL, &numfds))
2648         return;
2649     if (numfds == 0)
2650         return;
2651     fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2652     if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2653         OPENSSL_free(fds);
2654         return;
2655     }
2656
2657     FD_ZERO(&asyncfds);
2658     for (i = 0; i < numfds; i++) {
2659         if (width <= (int)fds[i])
2660             width = (int)fds[i] + 1;
2661         openssl_fdset((int)fds[i], &asyncfds);
2662     }
2663     select(width, (void *)&asyncfds, NULL, NULL, NULL);
2664     OPENSSL_free(fds);
2665 #endif
2666 }
2667
2668 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2669 #if defined(OPENSSL_SYS_MSDOS)
2670 int has_stdin_waiting(void)
2671 {
2672 # if defined(OPENSSL_SYS_WINDOWS)
2673     HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2674     DWORD events = 0;
2675     INPUT_RECORD inputrec;
2676     DWORD insize = 1;
2677     BOOL peeked;
2678
2679     if (inhand == INVALID_HANDLE_VALUE) {
2680         return 0;
2681     }
2682
2683     peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2684     if (!peeked) {
2685         /* Probably redirected input? _kbhit() does not work in this case */
2686         if (!feof(stdin)) {
2687             return 1;
2688         }
2689         return 0;
2690     }
2691 # endif
2692     return _kbhit();
2693 }
2694 #endif
2695
2696 /* Corrupt a signature by modifying final byte */
2697 void corrupt_signature(const ASN1_STRING *signature)
2698 {
2699         unsigned char *s = signature->data;
2700         s[signature->length - 1] ^= 0x1;
2701 }
2702
2703 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2704                    int days)
2705 {
2706     if (startdate == NULL || strcmp(startdate, "today") == 0) {
2707         if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2708             return 0;
2709     } else {
2710         if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2711             return 0;
2712     }
2713     if (enddate == NULL) {
2714         if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2715             == NULL)
2716             return 0;
2717     } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2718         return 0;
2719     }
2720     return 1;
2721 }
2722
2723 int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate)
2724 {
2725     int ret = 0;
2726     ASN1_TIME *tm = ASN1_TIME_new();
2727
2728     if (tm == NULL)
2729         goto end;
2730
2731     if (lastupdate == NULL) {
2732         if (X509_gmtime_adj(tm, 0) == NULL)
2733             goto end;
2734     } else {
2735         if (!ASN1_TIME_set_string_X509(tm, lastupdate))
2736             goto end;
2737     }
2738
2739     if (!X509_CRL_set1_lastUpdate(crl, tm))
2740         goto end;
2741
2742     ret = 1;
2743 end:
2744     ASN1_TIME_free(tm);
2745     return ret;
2746 }
2747
2748 int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
2749                        long days, long hours, long secs)
2750 {
2751     int ret = 0;
2752     ASN1_TIME *tm = ASN1_TIME_new();
2753
2754     if (tm == NULL)
2755         goto end;
2756
2757     if (nextupdate == NULL) {
2758         if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL)
2759             goto end;
2760     } else {
2761         if (!ASN1_TIME_set_string_X509(tm, nextupdate))
2762             goto end;
2763     }
2764
2765     if (!X509_CRL_set1_nextUpdate(crl, tm))
2766         goto end;
2767
2768     ret = 1;
2769 end:
2770     ASN1_TIME_free(tm);
2771     return ret;
2772 }
2773
2774 void make_uppercase(char *string)
2775 {
2776     int i;
2777
2778     for (i = 0; string[i] != '\0'; i++)
2779         string[i] = toupper((unsigned char)string[i]);
2780 }
2781
2782 int opt_printf_stderr(const char *fmt, ...)
2783 {
2784     va_list ap;
2785     int ret;
2786
2787     va_start(ap, fmt);
2788     ret = BIO_vprintf(bio_err, fmt, ap);
2789     va_end(ap);
2790     return ret;
2791 }
2792
2793 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
2794                                      const OSSL_PARAM *paramdefs)
2795 {
2796     OSSL_PARAM *params = NULL;
2797     size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
2798     size_t params_n;
2799     char *opt = "", *stmp, *vtmp = NULL;
2800     int found = 1;
2801
2802     if (opts == NULL)
2803         return NULL;
2804
2805     params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
2806     if (params == NULL)
2807         return NULL;
2808
2809     for (params_n = 0; params_n < sz; params_n++) {
2810         opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
2811         if ((stmp = OPENSSL_strdup(opt)) == NULL
2812             || (vtmp = strchr(stmp, ':')) == NULL)
2813             goto err;
2814         /* Replace ':' with 0 to terminate the string pointed to by stmp */
2815         *vtmp = 0;
2816         /* Skip over the separator so that vmtp points to the value */
2817         vtmp++;
2818         if (!OSSL_PARAM_allocate_from_text(&params[params_n], paramdefs,
2819                                            stmp, vtmp, strlen(vtmp), &found))
2820             goto err;
2821         OPENSSL_free(stmp);
2822     }
2823     params[params_n] = OSSL_PARAM_construct_end();
2824     return params;
2825 err:
2826     OPENSSL_free(stmp);
2827     BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
2828                opt);
2829     ERR_print_errors(bio_err);
2830     app_params_free(params);
2831     return NULL;
2832 }
2833
2834 void app_params_free(OSSL_PARAM *params)
2835 {
2836     int i;
2837
2838     if (params != NULL) {
2839         for (i = 0; params[i].key != NULL; ++i)
2840             OPENSSL_free(params[i].data);
2841         OPENSSL_free(params);
2842     }
2843 }