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