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