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