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