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