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