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