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