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