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