2 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
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
10 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
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.
15 # define _POSIX_C_SOURCE 2
18 #ifndef OPENSSL_NO_ENGINE
19 /* We need to use some deprecated APIs */
20 # define OPENSSL_SUPPRESS_DEPRECATED
21 # include <openssl/engine.h>
27 #include <sys/types.h>
28 #ifndef OPENSSL_NO_POSIX_IO
29 # include <sys/stat.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>
52 static int WIN32_rename(const char *from, const char *to);
53 # define rename(from, to) WIN32_rename((from), (to))
56 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
60 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) || defined(__BORLANDC__)
64 static BIO *bio_open_default_(const char *filename, char mode, int format,
67 #define PASS_SOURCE_SIZE_MAX 4
77 static int set_table_opts(unsigned long *flags, const char *arg,
78 const NAME_EX_TBL * in_tbl);
79 static int set_multi_opts(unsigned long *flags, const char *arg,
80 const NAME_EX_TBL * in_tbl);
81 int app_init(long mesgwin);
83 int chopup_args(ARGS *arg, char *buf)
86 char c = '\0', *p = NULL;
91 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
95 /* Skip whitespace. */
96 while (*p && isspace(_UC(*p)))
101 /* The start of something good :-) */
102 if (arg->argc >= arg->size) {
106 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
111 quoted = *p == '\'' || *p == '"';
114 arg->argv[arg->argc++] = p;
116 /* now look for the end of this */
118 while (*p && *p != c)
122 while (*p && !isspace(_UC(*p)))
128 arg->argv[arg->argc] = NULL;
133 int app_init(long mesgwin)
139 int ctx_set_verify_locations(SSL_CTX *ctx,
140 const char *CAfile, int noCAfile,
141 const char *CApath, int noCApath,
142 const char *CAstore, int noCAstore)
144 if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
145 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
147 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
149 if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
155 if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
157 if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
159 if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
164 #ifndef OPENSSL_NO_CT
166 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
169 return SSL_CTX_set_default_ctlog_list_file(ctx);
171 return SSL_CTX_set_ctlog_list_file(ctx, path);
176 static unsigned long nmflag = 0;
177 static char nmflag_set = 0;
179 int set_nameopt(const char *arg)
181 int ret = set_name_ex(&nmflag, arg);
189 unsigned long get_nameopt(void)
192 nmflag_set ? nmflag : XN_FLAG_SEP_CPLUS_SPC | ASN1_STRFLGS_UTF8_CONVERT;
195 void dump_cert_text(BIO *out, X509 *x)
197 print_name(out, "subject=", X509_get_subject_name(x));
198 print_name(out, "issuer=", X509_get_issuer_name(x));
201 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
203 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
206 static char *app_get_pass(const char *arg, int keepbio);
208 char *get_passwd(const char *pass, const char *desc)
214 if (!app_passwd(pass, NULL, &result, NULL))
215 BIO_printf(bio_err, "Error getting password for %s\n", desc);
216 if (pass != NULL && result == NULL) {
218 "Trying plain input string (better precede with 'pass:')\n");
219 result = OPENSSL_strdup(pass);
222 "Out of memory getting password for %s\n", desc);
227 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
229 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
232 *pass1 = app_get_pass(arg1, same);
235 } else if (pass1 != NULL) {
239 *pass2 = app_get_pass(arg2, same ? 2 : 0);
242 } else if (pass2 != NULL) {
248 static char *app_get_pass(const char *arg, int keepbio)
250 static BIO *pwdbio = NULL;
251 char *tmp, tpass[APP_PASS_LEN];
254 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
255 if (CHECK_AND_SKIP_PREFIX(arg, "pass:"))
256 return OPENSSL_strdup(arg);
257 if (CHECK_AND_SKIP_PREFIX(arg, "env:")) {
260 BIO_printf(bio_err, "No environment variable %s\n", arg);
263 return OPENSSL_strdup(tmp);
265 if (!keepbio || pwdbio == NULL) {
266 if (CHECK_AND_SKIP_PREFIX(arg, "file:")) {
267 pwdbio = BIO_new_file(arg, "r");
268 if (pwdbio == NULL) {
269 BIO_printf(bio_err, "Can't open file %s\n", arg);
274 * Under _WIN32, which covers even Win64 and CE, file
275 * descriptors referenced by BIO_s_fd are not inherited
276 * by child process and therefore below is not an option.
277 * It could have been an option if bss_fd.c was operating
278 * on real Windows descriptors, such as those obtained
281 } else if (CHECK_AND_SKIP_PREFIX(arg, "fd:")) {
286 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
287 if ((i < 0) || pwdbio == NULL) {
288 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg);
292 * Can't do BIO_gets on an fd BIO so add a buffering BIO
294 btmp = BIO_new(BIO_f_buffer());
296 BIO_free_all(pwdbio);
298 BIO_printf(bio_err, "Out of memory\n");
301 pwdbio = BIO_push(btmp, pwdbio);
303 } else if (strcmp(arg, "stdin") == 0) {
305 pwdbio = dup_bio_in(FORMAT_TEXT);
306 if (pwdbio == NULL) {
307 BIO_printf(bio_err, "Can't open BIO for stdin\n");
311 /* argument syntax error; do not reveal too much about arg */
312 tmp = strchr(arg, ':');
313 if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
315 "Invalid password argument, missing ':' within the first %d chars\n",
316 PASS_SOURCE_SIZE_MAX + 1);
319 "Invalid password argument, starting with \"%.*s\"\n",
320 (int)(tmp - arg + 1), arg);
324 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
326 BIO_free_all(pwdbio);
330 BIO_printf(bio_err, "Error reading password from BIO\n");
333 tmp = strchr(tpass, '\n');
336 return OPENSSL_strdup(tpass);
339 char *app_conf_try_string(const CONF *conf, const char *group, const char *name)
344 res = NCONF_get_string(conf, group, name);
348 ERR_clear_last_mark();
352 int app_conf_try_number(const CONF *conf, const char *group, const char *name,
358 ok = NCONF_get_number(conf, group, name, result);
362 ERR_clear_last_mark();
366 CONF *app_load_config_bio(BIO *in, const char *filename)
372 conf = NCONF_new_ex(app_get0_libctx(), NULL);
373 i = NCONF_load_bio(conf, in, &errorline);
377 if (errorline <= 0) {
378 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
380 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
383 if (filename != NULL)
384 BIO_printf(bio_err, "config file \"%s\"\n", filename);
386 BIO_printf(bio_err, "config input");
392 CONF *app_load_config_verbose(const char *filename, int verbose)
395 if (*filename == '\0')
396 BIO_printf(bio_err, "No configuration used\n");
398 BIO_printf(bio_err, "Using configuration from %s\n", filename);
400 return app_load_config_internal(filename, 0);
403 CONF *app_load_config_internal(const char *filename, int quiet)
408 if (filename == NULL || *filename != '\0') {
409 if ((in = bio_open_default_(filename, 'r', FORMAT_TEXT, quiet)) == NULL)
411 conf = app_load_config_bio(in, filename);
414 /* Return empty config if filename is empty string. */
415 conf = NCONF_new_ex(app_get0_libctx(), NULL);
420 int app_load_modules(const CONF *config)
422 CONF *to_free = NULL;
425 config = to_free = app_load_config_quiet(default_config_file);
429 if (CONF_modules_load(config, NULL, 0) <= 0) {
430 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
431 ERR_print_errors(bio_err);
439 int add_oid_section(CONF *conf)
442 STACK_OF(CONF_VALUE) *sktmp;
446 if ((p = app_conf_try_string(conf, NULL, "oid_section")) == NULL)
448 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
449 BIO_printf(bio_err, "problem loading oid section %s\n", p);
452 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
453 cnf = sk_CONF_VALUE_value(sktmp, i);
454 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
455 BIO_printf(bio_err, "problem creating object %s=%s\n",
456 cnf->name, cnf->value);
463 CONF *app_load_config_modules(const char *configfile)
467 if (configfile != NULL) {
468 if ((conf = app_load_config_verbose(configfile, 1)) == NULL)
470 if (configfile != default_config_file && !app_load_modules(conf)) {
478 #define IS_HTTP(uri) ((uri) != NULL && HAS_PREFIX(uri, OSSL_HTTP_PREFIX))
479 #define IS_HTTPS(uri) ((uri) != NULL && HAS_PREFIX(uri, OSSL_HTTPS_PREFIX))
481 X509 *load_cert_pass(const char *uri, int format, int maybe_stdin,
482 const char *pass, const char *desc)
487 desc = "certificate";
489 BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
490 } else if (IS_HTTP(uri)) {
491 cert = X509_load_http(uri, NULL, NULL, 0 /* timeout */);
493 ERR_print_errors(bio_err);
494 BIO_printf(bio_err, "Unable to load %s from %s\n", desc, uri);
497 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, 0,
498 NULL, NULL, NULL, &cert, NULL, NULL, NULL);
503 X509_CRL *load_crl(const char *uri, int format, int maybe_stdin,
506 X509_CRL *crl = NULL;
511 BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
512 } else if (IS_HTTP(uri)) {
513 crl = X509_CRL_load_http(uri, NULL, NULL, 0 /* timeout */);
515 ERR_print_errors(bio_err);
516 BIO_printf(bio_err, "Unable to load %s from %s\n", desc, uri);
519 (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc, 0,
520 NULL, NULL, NULL, NULL, NULL, &crl, NULL);
525 /* Could be simplified if OSSL_STORE supported CSRs, see FR #15725 */
526 X509_REQ *load_csr(const char *file, int format, const char *desc)
528 X509_REQ *req = NULL;
531 if (format == FORMAT_UNDEF)
533 in = bio_open_default(file, 'r', format);
537 if (format == FORMAT_ASN1)
538 req = d2i_X509_REQ_bio(in, NULL);
539 else if (format == FORMAT_PEM)
540 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
542 print_format_error(format, OPT_FMT_PEMDER);
546 ERR_print_errors(bio_err);
548 BIO_printf(bio_err, "Unable to load %s\n", desc);
554 /* Better extend OSSL_STORE to support CSRs, see FR #15725 */
555 X509_REQ *load_csr_autofmt(const char *infile, int format,
556 STACK_OF(OPENSSL_STRING) *vfyopts, const char *desc)
560 if (format != FORMAT_UNDEF) {
561 csr = load_csr(infile, format, desc);
562 } else { /* try PEM, then DER */
563 BIO *bio_bak = bio_err;
565 bio_err = NULL; /* do not show errors on more than one try */
566 csr = load_csr(infile, FORMAT_PEM, NULL /* desc */);
570 csr = load_csr(infile, FORMAT_ASN1, NULL /* desc */);
573 BIO_printf(bio_err, "error: unable to load %s from file '%s'\n",
578 EVP_PKEY *pkey = X509_REQ_get0_pubkey(csr);
579 int ret = do_X509_REQ_verify(csr, pkey, vfyopts);
581 if (pkey == NULL || ret < 0)
582 BIO_puts(bio_err, "Warning: error while verifying CSR self-signature\n");
584 BIO_puts(bio_err, "Warning: CSR self-signature does not match the contents\n");
590 void cleanse(char *str)
593 OPENSSL_cleanse(str, strlen(str));
596 void clear_free(char *str)
599 OPENSSL_clear_free(str, strlen(str));
602 EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
603 const char *pass, ENGINE *e, const char *desc)
605 EVP_PKEY *pkey = NULL;
606 char *allocated_uri = NULL;
609 desc = "private key";
611 if (format == FORMAT_ENGINE)
612 uri = allocated_uri = make_engine_uri(e, uri, desc);
613 (void)load_key_certs_crls(uri, format, may_stdin, pass, desc, 0,
614 &pkey, NULL, NULL, NULL, NULL, NULL, NULL);
616 OPENSSL_free(allocated_uri);
620 /* first try reading public key, on failure resort to loading private key */
621 EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
622 const char *pass, ENGINE *e, const char *desc)
624 EVP_PKEY *pkey = NULL;
625 char *allocated_uri = NULL;
630 if (format == FORMAT_ENGINE)
631 uri = allocated_uri = make_engine_uri(e, uri, desc);
632 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, 1,
633 NULL, &pkey, NULL, NULL, NULL, NULL, NULL);
635 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, 0,
636 &pkey, NULL, NULL, NULL, NULL, NULL, NULL);
637 OPENSSL_free(allocated_uri);
641 EVP_PKEY *load_keyparams_suppress(const char *uri, int format, int maybe_stdin,
642 const char *keytype, const char *desc,
643 int suppress_decode_errors)
645 EVP_PKEY *params = NULL;
648 desc = "key parameters";
649 (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc,
650 suppress_decode_errors,
651 NULL, NULL, ¶ms, NULL, NULL, NULL, NULL);
652 if (params != NULL && keytype != NULL && !EVP_PKEY_is_a(params, keytype)) {
653 ERR_print_errors(bio_err);
655 "Unable to load %s from %s (unexpected parameters type)\n",
657 EVP_PKEY_free(params);
663 EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin,
664 const char *keytype, const char *desc)
666 return load_keyparams_suppress(uri, format, maybe_stdin, keytype, desc, 0);
669 void app_bail_out(char *fmt, ...)
674 BIO_vprintf(bio_err, fmt, args);
676 ERR_print_errors(bio_err);
680 void *app_malloc(size_t sz, const char *what)
682 void *vp = OPENSSL_malloc(sz);
685 app_bail_out("%s: Could not allocate %zu bytes for %s\n",
686 opt_getprog(), sz, what);
690 char *next_item(char *opt) /* in list separated by comma and/or space */
692 /* advance to separator (comma or whitespace), if any */
693 while (*opt != ',' && !isspace(_UC(*opt)) && *opt != '\0')
696 /* terminate current item */
698 /* skip over any whitespace after separator */
699 while (isspace(_UC(*opt)))
702 return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */
705 static void warn_cert_msg(const char *uri, X509 *cert, const char *msg)
707 char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
709 BIO_printf(bio_err, "Warning: certificate from '%s' with subject '%s' %s\n",
714 static void warn_cert(const char *uri, X509 *cert, int warn_EE,
715 X509_VERIFY_PARAM *vpm)
717 uint32_t ex_flags = X509_get_extension_flags(cert);
718 int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
719 X509_get0_notAfter(cert));
722 warn_cert_msg(uri, cert, res > 0 ? "has expired" : "not yet valid");
723 if (warn_EE && (ex_flags & EXFLAG_V1) == 0 && (ex_flags & EXFLAG_CA) == 0)
724 warn_cert_msg(uri, cert, "is not a CA cert");
727 static void warn_certs(const char *uri, STACK_OF(X509) *certs, int warn_EE,
728 X509_VERIFY_PARAM *vpm)
732 for (i = 0; i < sk_X509_num(certs); i++)
733 warn_cert(uri, sk_X509_value(certs, i), warn_EE, vpm);
736 int load_cert_certs(const char *uri,
737 X509 **pcert, STACK_OF(X509) **pcerts,
738 int exclude_http, const char *pass, const char *desc,
739 X509_VERIFY_PARAM *vpm)
745 desc = pcerts == NULL ? "certificate" : "certificates";
746 if (exclude_http && (HAS_CASE_PREFIX(uri, "http://")
747 || HAS_CASE_PREFIX(uri, "https://"))) {
748 BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc);
751 pass_string = get_passwd(pass, desc);
752 ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass_string, desc, 0,
753 NULL, NULL, NULL, pcert, pcerts, NULL, NULL);
754 clear_free(pass_string);
758 warn_cert(uri, *pcert, 0, vpm);
760 warn_certs(uri, *pcerts, 1, vpm);
762 if (pcerts != NULL) {
763 OSSL_STACK_OF_X509_free(*pcerts);
770 STACK_OF(X509) *load_certs_multifile(char *files, const char *pass,
771 const char *desc, X509_VERIFY_PARAM *vpm)
773 STACK_OF(X509) *certs = NULL;
774 STACK_OF(X509) *result = sk_X509_new_null();
781 while (files != NULL) {
782 char *next = next_item(files);
784 if (!load_cert_certs(files, NULL, &certs, 0, pass, desc, vpm))
786 if (!X509_add_certs(result, certs,
787 X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
789 OSSL_STACK_OF_X509_free(certs);
796 BIO_printf(bio_err, "out of memory\n");
798 OSSL_STACK_OF_X509_free(certs);
799 OSSL_STACK_OF_X509_free(result);
803 static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */,
804 const STACK_OF(X509) *certs /* may NULL */)
809 store = X509_STORE_new();
812 for (i = 0; i < sk_X509_num(certs); i++) {
813 if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) {
814 X509_STORE_free(store);
822 * Create cert store structure with certificates read from given file(s).
823 * Returns pointer to created X509_STORE on success, NULL on error.
825 X509_STORE *load_certstore(char *input, const char *pass, const char *desc,
826 X509_VERIFY_PARAM *vpm)
828 X509_STORE *store = NULL;
829 STACK_OF(X509) *certs = NULL;
831 while (input != NULL) {
832 char *next = next_item(input);
835 if (!load_cert_certs(input, NULL, &certs, 1, pass, desc, vpm)) {
836 X509_STORE_free(store);
839 ok = (store = sk_X509_to_store(store, certs)) != NULL;
840 OSSL_STACK_OF_X509_free(certs);
850 * Initialize or extend, if *certs != NULL, a certificate stack.
851 * The caller is responsible for freeing *certs if its value is left not NULL.
853 int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs,
854 const char *pass, const char *desc)
856 int ret, was_NULL = *certs == NULL;
859 desc = "certificates";
860 ret = load_key_certs_crls(uri, FORMAT_UNDEF, maybe_stdin, pass, desc, 0,
861 NULL, NULL, NULL, NULL, certs, NULL, NULL);
863 if (!ret && was_NULL) {
864 OSSL_STACK_OF_X509_free(*certs);
871 * Initialize or extend, if *crls != NULL, a certificate stack.
872 * The caller is responsible for freeing *crls if its value is left not NULL.
874 int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
875 const char *pass, const char *desc)
877 int ret, was_NULL = *crls == NULL;
881 ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass, desc, 0,
882 NULL, NULL, NULL, NULL, NULL, NULL, crls);
884 if (!ret && was_NULL) {
885 sk_X509_CRL_pop_free(*crls, X509_CRL_free);
891 static const char *format2string(int format)
902 /* Set type expectation, but clear it if objects of different types expected. */
903 #define SET_EXPECT(val) \
904 (expect = expect < 0 ? (val) : (expect == (val) ? (val) : 0))
905 #define SET_EXPECT1(pvar, val) \
906 if ((pvar) != NULL) { \
911 (ppkey != NULL ? "key etc." : ppubkey != NULL ? "public key etc." : \
912 pparams != NULL ? "params etc." : \
913 pcert != NULL ? "cert etc." : pcerts != NULL ? "certs etc." : \
914 pcrl != NULL ? "CRL etc." : pcrls != NULL ? "CRLs etc." : NULL)
916 * Load those types of credentials for which the result pointer is not NULL.
917 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
918 * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
919 * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
920 * If pcerts is non-NULL then all available certificates are appended to *pcerts
921 * except any certificate assigned to *pcert.
922 * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
923 * If pcrls is non-NULL then all available CRLs are appended to *pcerts
924 * except any CRL assigned to *pcrl.
925 * In any case (also on error) the caller is responsible for freeing all members
926 * of *pcerts and *pcrls (as far as they are not NULL).
928 int load_key_certs_crls(const char *uri, int format, int maybe_stdin,
929 const char *pass, const char *desc, int quiet,
930 EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
932 X509 **pcert, STACK_OF(X509) **pcerts,
933 X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
936 OSSL_STORE_CTX *ctx = NULL;
937 OSSL_LIB_CTX *libctx = app_get0_libctx();
938 const char *propq = app_get0_propq();
939 int ncerts = 0, ncrls = 0, expect = -1;
940 const char *failed = FAIL_NAME;
941 const char *input_type;
943 const OSSL_PARAM *params = NULL;
945 if (failed == NULL) {
947 BIO_printf(bio_err, "Internal error: nothing to load from %s\n",
948 uri != NULL ? uri : "<stdin>");
953 SET_EXPECT1(ppkey, OSSL_STORE_INFO_PKEY);
954 SET_EXPECT1(ppubkey, OSSL_STORE_INFO_PUBKEY);
955 SET_EXPECT1(pparams, OSSL_STORE_INFO_PARAMS);
956 SET_EXPECT1(pcert, OSSL_STORE_INFO_CERT);
957 if (pcerts != NULL) {
958 if (*pcerts == NULL && (*pcerts = sk_X509_new_null()) == NULL) {
960 BIO_printf(bio_err, "Out of memory loading");
963 SET_EXPECT(OSSL_STORE_INFO_CERT);
965 SET_EXPECT1(pcrl, OSSL_STORE_INFO_CRL);
967 if (*pcrls == NULL && (*pcrls = sk_X509_CRL_new_null()) == NULL) {
969 BIO_printf(bio_err, "Out of memory loading");
972 SET_EXPECT(OSSL_STORE_INFO_CRL);
975 uidata.password = pass;
976 uidata.prompt_info = uri;
978 if ((input_type = format2string(format)) != NULL) {
979 itp[0] = OSSL_PARAM_construct_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE,
980 (char *)input_type, 0);
981 itp[1] = OSSL_PARAM_construct_end();
990 BIO_printf(bio_err, "No filename or uri specified for loading");
995 bio = BIO_new_fp(stdin, 0);
997 ctx = OSSL_STORE_attach(bio, "file", libctx, propq,
998 get_ui_method(), &uidata, params,
1003 ctx = OSSL_STORE_open_ex(uri, libctx, propq, get_ui_method(), &uidata,
1004 params, NULL, NULL);
1008 BIO_printf(bio_err, "Could not open file or uri for loading");
1011 if (expect > 0 && !OSSL_STORE_expect(ctx, expect))
1015 while ((ppkey != NULL || ppubkey != NULL || pparams != NULL
1016 || pcert != NULL || pcerts != NULL || pcrl != NULL || pcrls != NULL)
1017 && !OSSL_STORE_eof(ctx)) {
1018 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
1022 * This can happen (for example) if we attempt to load a file with
1023 * multiple different types of things in it - but the thing we just
1024 * tried to load wasn't one of the ones we wanted, e.g. if we're trying
1025 * to load a certificate but the file has both the private key and the
1026 * certificate in it. We just retry until eof.
1032 type = OSSL_STORE_INFO_get_type(info);
1034 case OSSL_STORE_INFO_PKEY:
1035 if (ppkey != NULL) {
1036 ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL;
1042 * An EVP_PKEY with private parts also holds the public parts,
1043 * so if the caller asked for a public key, and we got a private
1044 * key, we can still pass it back.
1047 case OSSL_STORE_INFO_PUBKEY:
1048 if (ppubkey != NULL) {
1049 ok = (*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL;
1054 case OSSL_STORE_INFO_PARAMS:
1055 if (pparams != NULL) {
1056 ok = (*pparams = OSSL_STORE_INFO_get1_PARAMS(info)) != NULL;
1061 case OSSL_STORE_INFO_CERT:
1062 if (pcert != NULL) {
1063 ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL;
1066 } else if (pcerts != NULL) {
1067 ok = X509_add_cert(*pcerts,
1068 OSSL_STORE_INFO_get1_CERT(info),
1069 X509_ADD_FLAG_DEFAULT);
1073 case OSSL_STORE_INFO_CRL:
1075 ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL;
1078 } else if (pcrls != NULL) {
1079 ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info));
1084 /* skip any other type */
1087 OSSL_STORE_INFO_free(info);
1089 failed = OSSL_STORE_INFO_type_string(type);
1091 BIO_printf(bio_err, "Error reading");
1097 OSSL_STORE_close(ctx);
1102 if (failed == NULL) {
1104 if (failed != NULL && !quiet)
1105 BIO_printf(bio_err, "Could not find");
1106 } else if (!quiet) {
1107 BIO_printf(bio_err, "Could not read");
1109 if (failed != NULL && !quiet) {
1110 unsigned long err = ERR_peek_last_error();
1112 if (desc != NULL && strstr(desc, failed) != NULL) {
1113 BIO_printf(bio_err, " %s", desc);
1115 BIO_printf(bio_err, " %s", failed);
1117 BIO_printf(bio_err, " of %s", desc);
1120 BIO_printf(bio_err, " from %s", uri);
1121 if (ERR_SYSTEM_ERROR(err)) {
1122 /* provide more readable diagnostic output */
1123 BIO_printf(bio_err, ": %s", strerror(ERR_GET_REASON(err)));
1127 BIO_printf(bio_err, "\n");
1128 ERR_print_errors(bio_err);
1130 if (quiet || failed == NULL)
1131 /* clear any suppressed or spurious errors */
1134 ERR_clear_last_mark();
1135 return failed == NULL;
1138 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
1139 #define X509V3_EXT_DEFAULT 0 /* Return error for unknown exts */
1140 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16) /* Print error for unknown exts */
1141 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16) /* ASN1 parse unknown extensions */
1142 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16) /* BIO_dump unknown extensions */
1144 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1145 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1147 int set_cert_ex(unsigned long *flags, const char *arg)
1149 static const NAME_EX_TBL cert_tbl[] = {
1150 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
1151 {"ca_default", X509_FLAG_CA, 0xffffffffl},
1152 {"no_header", X509_FLAG_NO_HEADER, 0},
1153 {"no_version", X509_FLAG_NO_VERSION, 0},
1154 {"no_serial", X509_FLAG_NO_SERIAL, 0},
1155 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
1156 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
1157 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
1158 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1159 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1160 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1161 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1162 {"no_aux", X509_FLAG_NO_AUX, 0},
1163 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1164 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1165 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1166 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1167 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1170 return set_multi_opts(flags, arg, cert_tbl);
1173 int set_name_ex(unsigned long *flags, const char *arg)
1175 static const NAME_EX_TBL ex_tbl[] = {
1176 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1177 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
1178 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1179 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1180 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1181 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1182 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1183 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1184 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1185 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1186 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1187 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1188 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1189 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1190 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1191 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1192 {"dn_rev", XN_FLAG_DN_REV, 0},
1193 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1194 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1195 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1196 {"align", XN_FLAG_FN_ALIGN, 0},
1197 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1198 {"space_eq", XN_FLAG_SPC_EQ, 0},
1199 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1200 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1201 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1202 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1203 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1206 if (set_multi_opts(flags, arg, ex_tbl) == 0)
1208 if (*flags != XN_FLAG_COMPAT
1209 && (*flags & XN_FLAG_SEP_MASK) == 0)
1210 *flags |= XN_FLAG_SEP_CPLUS_SPC;
1214 int set_dateopt(unsigned long *dateopt, const char *arg)
1216 if (OPENSSL_strcasecmp(arg, "rfc_822") == 0)
1217 *dateopt = ASN1_DTFLGS_RFC822;
1218 else if (OPENSSL_strcasecmp(arg, "iso_8601") == 0)
1219 *dateopt = ASN1_DTFLGS_ISO8601;
1225 int set_ext_copy(int *copy_type, const char *arg)
1227 if (OPENSSL_strcasecmp(arg, "none") == 0)
1228 *copy_type = EXT_COPY_NONE;
1229 else if (OPENSSL_strcasecmp(arg, "copy") == 0)
1230 *copy_type = EXT_COPY_ADD;
1231 else if (OPENSSL_strcasecmp(arg, "copyall") == 0)
1232 *copy_type = EXT_COPY_ALL;
1238 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1240 STACK_OF(X509_EXTENSION) *exts;
1243 if (x == NULL || req == NULL)
1245 if (copy_type == EXT_COPY_NONE)
1247 exts = X509_REQ_get_extensions(req);
1249 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1250 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
1251 ASN1_OBJECT *obj = X509_EXTENSION_get_object(ext);
1252 int idx = X509_get_ext_by_OBJ(x, obj, -1);
1254 /* Does extension exist in target? */
1256 /* If normal copy don't override existing extension */
1257 if (copy_type == EXT_COPY_ADD)
1259 /* Delete all extensions of same type */
1261 X509_EXTENSION_free(X509_delete_ext(x, idx));
1262 idx = X509_get_ext_by_OBJ(x, obj, -1);
1263 } while (idx != -1);
1265 if (!X509_add_ext(x, ext, -1))
1271 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1275 static int set_multi_opts(unsigned long *flags, const char *arg,
1276 const NAME_EX_TBL * in_tbl)
1278 STACK_OF(CONF_VALUE) *vals;
1284 vals = X509V3_parse_list(arg);
1285 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1286 val = sk_CONF_VALUE_value(vals, i);
1287 if (!set_table_opts(flags, val->name, in_tbl))
1290 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1294 static int set_table_opts(unsigned long *flags, const char *arg,
1295 const NAME_EX_TBL * in_tbl)
1298 const NAME_EX_TBL *ptbl;
1304 } else if (c == '+') {
1311 for (ptbl = in_tbl; ptbl->name; ptbl++) {
1312 if (OPENSSL_strcasecmp(arg, ptbl->name) == 0) {
1313 *flags &= ~ptbl->mask;
1315 *flags |= ptbl->flag;
1317 *flags &= ~ptbl->flag;
1324 void print_name(BIO *out, const char *title, const X509_NAME *nm)
1329 unsigned long lflags = get_nameopt();
1334 BIO_puts(out, title);
1335 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1339 if (lflags == XN_FLAG_COMPAT) {
1340 buf = X509_NAME_oneline(nm, 0, 0);
1342 BIO_puts(out, "\n");
1346 BIO_puts(out, "\n");
1347 X509_NAME_print_ex(out, nm, indent, lflags);
1348 BIO_puts(out, "\n");
1352 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1353 int len, unsigned char *buffer)
1355 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1356 if (BN_is_zero(in)) {
1357 BIO_printf(out, "\n 0x00");
1361 l = BN_bn2bin(in, buffer);
1362 for (i = 0; i < l; i++) {
1363 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1365 BIO_printf(out, "0x%02X,", buffer[i]);
1367 BIO_printf(out, "0x%02X", buffer[i]);
1370 BIO_printf(out, "\n };\n");
1373 void print_array(BIO *out, const char *title, int len, const unsigned char *d)
1377 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1378 for (i = 0; i < len; i++) {
1380 BIO_printf(out, "\n ");
1382 BIO_printf(out, "0x%02X, ", d[i]);
1384 BIO_printf(out, "0x%02X", d[i]);
1386 BIO_printf(out, "\n};\n");
1389 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1390 const char *CApath, int noCApath,
1391 const char *CAstore, int noCAstore)
1393 X509_STORE *store = X509_STORE_new();
1394 X509_LOOKUP *lookup;
1395 OSSL_LIB_CTX *libctx = app_get0_libctx();
1396 const char *propq = app_get0_propq();
1401 if (CAfile != NULL || !noCAfile) {
1402 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1405 if (CAfile != NULL) {
1406 if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM,
1407 libctx, propq) <= 0) {
1409 if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_ASN1,
1410 libctx, propq) <= 0) {
1411 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1416 X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT,
1421 if (CApath != NULL || !noCApath) {
1422 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1425 if (CApath != NULL) {
1426 if (X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM) <= 0) {
1427 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1431 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1435 if (CAstore != NULL || !noCAstore) {
1436 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1439 if (!X509_LOOKUP_add_store_ex(lookup, CAstore, libctx, propq)) {
1440 if (CAstore != NULL)
1441 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1449 ERR_print_errors(bio_err);
1450 X509_STORE_free(store);
1454 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1461 return OPENSSL_LH_strhash(n);
1464 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1465 const OPENSSL_CSTRING *b)
1467 const char *aa, *bb;
1469 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1470 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1471 return strcmp(aa, bb);
1474 static int index_name_qual(char **a)
1476 return (a[0][0] == 'V');
1479 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1481 return OPENSSL_LH_strhash(a[DB_name]);
1484 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1486 return strcmp(a[DB_name], b[DB_name]);
1489 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1490 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1491 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1492 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1495 BIGNUM *load_serial(const char *serialfile, int *exists, int create,
1496 ASN1_INTEGER **retai)
1501 ASN1_INTEGER *ai = NULL;
1503 ai = ASN1_INTEGER_new();
1507 in = BIO_new_file(serialfile, "r");
1509 *exists = in != NULL;
1518 BIO_printf(bio_err, "Out of memory\n");
1519 } else if (!rand_serial(ret, ai)) {
1520 BIO_printf(bio_err, "Error creating random number to store in %s\n",
1526 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1527 BIO_printf(bio_err, "Unable to load number from %s\n",
1531 ret = ASN1_INTEGER_to_BN(ai, NULL);
1533 BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1538 if (ret != NULL && retai != NULL) {
1544 ERR_print_errors(bio_err);
1546 ASN1_INTEGER_free(ai);
1550 int save_serial(const char *serialfile, const char *suffix,
1551 const BIGNUM *serial, ASN1_INTEGER **retai)
1556 ASN1_INTEGER *ai = NULL;
1560 j = strlen(serialfile);
1562 j = strlen(serialfile) + strlen(suffix) + 1;
1564 BIO_printf(bio_err, "File name too long\n");
1568 if (suffix == NULL) {
1569 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1571 #ifndef OPENSSL_SYS_VMS
1572 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1574 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1577 out = BIO_new_file(buf[0], "w");
1582 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1583 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1586 i2a_ASN1_INTEGER(out, ai);
1587 BIO_puts(out, "\n");
1595 ERR_print_errors(bio_err);
1597 ASN1_INTEGER_free(ai);
1601 int rotate_serial(const char *serialfile, const char *new_suffix,
1602 const char *old_suffix)
1607 i = strlen(serialfile) + strlen(old_suffix);
1608 j = strlen(serialfile) + strlen(new_suffix);
1611 if (j + 1 >= BSIZE) {
1612 BIO_printf(bio_err, "File name too long\n");
1615 #ifndef OPENSSL_SYS_VMS
1616 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1617 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1619 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1620 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1622 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1628 "Unable to rename %s to %s\n", serialfile, buf[1]);
1632 if (rename(buf[0], serialfile) < 0) {
1634 "Unable to rename %s to %s\n", buf[0], serialfile);
1636 rename(buf[1], serialfile);
1641 ERR_print_errors(bio_err);
1645 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1650 btmp = b == NULL ? BN_new() : b;
1654 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1656 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1669 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1671 CA_DB *retdb = NULL;
1672 TXT_DB *tmpdb = NULL;
1674 CONF *dbattr_conf = NULL;
1676 #ifndef OPENSSL_NO_POSIX_IO
1681 in = BIO_new_file(dbfile, "r");
1685 #ifndef OPENSSL_NO_POSIX_IO
1686 BIO_get_fp(in, &dbfp);
1687 if (fstat(fileno(dbfp), &dbst) == -1) {
1688 ERR_raise_data(ERR_LIB_SYS, errno,
1689 "calling fstat(%s)", dbfile);
1694 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1697 #ifndef OPENSSL_SYS_VMS
1698 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1700 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1702 dbattr_conf = app_load_config_quiet(buf);
1704 retdb = app_malloc(sizeof(*retdb), "new DB");
1708 retdb->attributes = *db_attr;
1710 retdb->attributes.unique_subject = 1;
1712 if (dbattr_conf != NULL) {
1713 char *p = app_conf_try_string(dbattr_conf, NULL, "unique_subject");
1716 retdb->attributes.unique_subject = parse_yesno(p, 1);
1719 retdb->dbfname = OPENSSL_strdup(dbfile);
1720 #ifndef OPENSSL_NO_POSIX_IO
1725 ERR_print_errors(bio_err);
1726 NCONF_free(dbattr_conf);
1733 * Returns > 0 on success, <= 0 on error
1735 int index_index(CA_DB *db)
1737 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1738 LHASH_HASH_FN(index_serial),
1739 LHASH_COMP_FN(index_serial))) {
1741 "Error creating serial number index:(%ld,%ld,%ld)\n",
1742 db->db->error, db->db->arg1, db->db->arg2);
1746 if (db->attributes.unique_subject
1747 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1748 LHASH_HASH_FN(index_name),
1749 LHASH_COMP_FN(index_name))) {
1750 BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1751 db->db->error, db->db->arg1, db->db->arg2);
1756 ERR_print_errors(bio_err);
1760 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1766 j = strlen(dbfile) + strlen(suffix);
1767 if (j + 6 >= BSIZE) {
1768 BIO_printf(bio_err, "File name too long\n");
1771 #ifndef OPENSSL_SYS_VMS
1772 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1773 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1774 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1776 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1777 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1778 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1780 out = BIO_new_file(buf[0], "w");
1783 BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1786 j = TXT_DB_write(out, db->db);
1791 out = BIO_new_file(buf[1], "w");
1794 BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1797 BIO_printf(out, "unique_subject = %s\n",
1798 db->attributes.unique_subject ? "yes" : "no");
1803 ERR_print_errors(bio_err);
1807 int rotate_index(const char *dbfile, const char *new_suffix,
1808 const char *old_suffix)
1813 i = strlen(dbfile) + strlen(old_suffix);
1814 j = strlen(dbfile) + strlen(new_suffix);
1817 if (j + 6 >= BSIZE) {
1818 BIO_printf(bio_err, "File name too long\n");
1821 #ifndef OPENSSL_SYS_VMS
1822 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1823 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1824 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1825 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1826 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1828 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1829 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1830 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1831 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1832 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1834 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1839 BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1843 if (rename(buf[0], dbfile) < 0) {
1844 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1846 rename(buf[1], dbfile);
1849 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1854 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1856 rename(dbfile, buf[0]);
1857 rename(buf[1], dbfile);
1860 if (rename(buf[2], buf[4]) < 0) {
1861 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1863 rename(buf[3], buf[4]);
1864 rename(dbfile, buf[0]);
1865 rename(buf[1], dbfile);
1870 ERR_print_errors(bio_err);
1874 void free_index(CA_DB *db)
1877 TXT_DB_free(db->db);
1878 OPENSSL_free(db->dbfname);
1883 int parse_yesno(const char *str, int def)
1887 case 'f': /* false */
1888 case 'F': /* FALSE */
1893 case 't': /* true */
1894 case 'T': /* TRUE */
1905 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1906 * where + can be used instead of / to form multi-valued RDNs if canmulti
1907 * and characters may be escaped by \
1909 X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
1912 int nextismulti = 0;
1918 "%s: %s name is expected to be in the format "
1919 "/type0=value0/type1=value1/type2=... where characters may "
1920 "be escaped by \\. This name is not in that format: '%s'\n",
1921 opt_getprog(), desc, --cp);
1925 n = X509_NAME_new();
1927 BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
1930 work = OPENSSL_strdup(cp);
1932 BIO_printf(bio_err, "%s: Error copying %s name input\n",
1933 opt_getprog(), desc);
1937 while (*cp != '\0') {
1940 unsigned char *valstr;
1942 int ismulti = nextismulti;
1946 /* Collect the type */
1947 while (*cp != '\0' && *cp != '=')
1952 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1953 opt_getprog(), typestr, desc);
1958 /* Collect the value. */
1959 valstr = (unsigned char *)bp;
1960 for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
1961 /* unescaped '+' symbol string signals further member of multiRDN */
1962 if (canmulti && *cp == '+') {
1966 if (*cp == '\\' && *++cp == '\0') {
1968 "%s: Escape character at end of %s name string\n",
1969 opt_getprog(), desc);
1975 /* If not at EOS (must be + or /), move forward. */
1980 nid = OBJ_txt2nid(typestr);
1981 if (nid == NID_undef) {
1983 "%s: Skipping unknown %s name attribute \"%s\"\n",
1984 opt_getprog(), desc, typestr);
1987 "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
1990 if (*valstr == '\0') {
1992 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1993 opt_getprog(), desc, typestr);
1996 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1997 valstr, strlen((char *)valstr),
1998 -1, ismulti ? -1 : 0)) {
1999 ERR_print_errors(bio_err);
2001 "%s: Error adding %s name attribute \"/%s=%s\"\n",
2002 opt_getprog(), desc, typestr, valstr);
2017 * Read whole contents of a BIO into an allocated memory buffer and return
2021 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
2025 unsigned char tbuf[1024];
2027 mem = BIO_new(BIO_s_mem());
2031 if ((maxlen != -1) && maxlen < 1024)
2035 len = BIO_read(in, tbuf, len);
2042 if (BIO_write(mem, tbuf, len) != len) {
2052 ret = BIO_get_mem_data(mem, (char **)out);
2053 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
2058 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
2061 char *stmp, *vtmp = NULL;
2063 stmp = OPENSSL_strdup(value);
2066 vtmp = strchr(stmp, ':');
2072 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
2079 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
2081 X509_POLICY_NODE *node;
2084 BIO_printf(bio_err, "%s Policies:", name);
2086 BIO_puts(bio_err, "\n");
2087 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
2088 node = sk_X509_POLICY_NODE_value(nodes, i);
2089 X509_POLICY_NODE_print(bio_err, node, 2);
2092 BIO_puts(bio_err, " <empty>\n");
2096 void policies_print(X509_STORE_CTX *ctx)
2098 X509_POLICY_TREE *tree;
2099 int explicit_policy;
2101 tree = X509_STORE_CTX_get0_policy_tree(ctx);
2102 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2104 BIO_printf(bio_err, "Require explicit Policy: %s\n",
2105 explicit_policy ? "True" : "False");
2107 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
2108 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
2112 * next_protos_parse parses a comma separated list of strings into a string
2113 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
2114 * outlen: (output) set to the length of the resulting buffer on success.
2115 * err: (maybe NULL) on failure, an error message line is written to this BIO.
2116 * in: a NUL terminated string like "abc,def,ghi"
2118 * returns: a malloc'd buffer or NULL on failure.
2120 unsigned char *next_protos_parse(size_t *outlen, const char *in)
2124 size_t i, start = 0;
2128 if (len == 0 || len >= 65535)
2131 out = app_malloc(len + 1, "NPN buffer");
2132 for (i = 0; i <= len; ++i) {
2133 if (i == len || in[i] == ',') {
2135 * Zero-length ALPN elements are invalid on the wire, we could be
2136 * strict and reject the entire string, but just ignoring extra
2137 * commas seems harmless and more friendly.
2139 * Every comma we skip in this way puts the input buffer another
2140 * byte ahead of the output buffer, so all stores into the output
2141 * buffer need to be decremented by the number commas skipped.
2148 if (i - start > 255) {
2152 out[start - skipped] = (unsigned char)(i - start);
2155 out[i + 1 - skipped] = in[i];
2159 if (len <= skipped) {
2164 *outlen = len + 1 - skipped;
2168 int check_cert_attributes(BIO *bio, X509 *x, const char *checkhost,
2169 const char *checkemail, const char *checkip,
2180 if (checkhost != NULL) {
2181 valid_host = X509_check_host(x, checkhost, 0, 0, NULL);
2183 BIO_printf(bio, "Hostname %s does%s match certificate\n",
2184 checkhost, valid_host == 1 ? "" : " NOT");
2185 ret = ret && valid_host;
2188 if (checkemail != NULL) {
2189 valid_mail = X509_check_email(x, checkemail, 0, 0);
2191 BIO_printf(bio, "Email %s does%s match certificate\n",
2192 checkemail, valid_mail ? "" : " NOT");
2193 ret = ret && valid_mail;
2196 if (checkip != NULL) {
2197 valid_ip = X509_check_ip_asc(x, checkip, 0);
2199 BIO_printf(bio, "IP %s does%s match certificate\n",
2200 checkip, valid_ip ? "" : " NOT");
2201 ret = ret && valid_ip;
2207 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
2214 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2215 char *opt = sk_OPENSSL_STRING_value(opts, i);
2217 if (pkey_ctrl_string(pkctx, opt) <= 0) {
2218 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2219 ERR_print_errors(bio_err);
2227 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
2234 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2235 char *opt = sk_OPENSSL_STRING_value(opts, i);
2237 if (x509_ctrl_string(x, opt) <= 0) {
2238 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2239 ERR_print_errors(bio_err);
2247 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
2254 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2255 char *opt = sk_OPENSSL_STRING_value(opts, i);
2257 if (x509_req_ctrl_string(x, opt) <= 0) {
2258 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2259 ERR_print_errors(bio_err);
2267 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
2268 const char *md, STACK_OF(OPENSSL_STRING) *sigopts)
2270 EVP_PKEY_CTX *pkctx = NULL;
2276 * EVP_PKEY_get_default_digest_name() returns 2 if the digest is mandatory
2277 * for this algorithm.
2279 if (EVP_PKEY_get_default_digest_name(pkey, def_md, sizeof(def_md)) == 2
2280 && strcmp(def_md, "UNDEF") == 0) {
2281 /* The signing algorithm requires there to be no digest */
2285 return EVP_DigestSignInit_ex(ctx, &pkctx, md, app_get0_libctx(),
2286 app_get0_propq(), pkey, NULL)
2287 && do_pkey_ctx_init(pkctx, sigopts);
2290 static int adapt_keyid_ext(X509 *cert, X509V3_CTX *ext_ctx,
2291 const char *name, const char *value, int add_default)
2293 const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
2294 X509_EXTENSION *new_ext = X509V3_EXT_nconf(NULL, ext_ctx, name, value);
2297 if (new_ext == NULL)
2300 idx = X509v3_get_ext_by_OBJ(exts, X509_EXTENSION_get_object(new_ext), -1);
2302 X509_EXTENSION *found_ext = X509v3_get_ext(exts, idx);
2303 ASN1_OCTET_STRING *encoded = X509_EXTENSION_get_data(found_ext);
2304 int disabled = ASN1_STRING_length(encoded) <= 2; /* indicating "none" */
2307 X509_delete_ext(cert, idx);
2308 X509_EXTENSION_free(found_ext);
2309 } /* else keep existing key identifier, which might be outdated */
2312 rv = !add_default || X509_add_ext(cert, new_ext, -1);
2314 X509_EXTENSION_free(new_ext);
2318 int cert_matches_key(const X509 *cert, const EVP_PKEY *pkey)
2323 match = X509_check_private_key(cert, pkey);
2328 /* Ensure RFC 5280 compliance, adapt keyIDs as needed, and sign the cert info */
2329 int do_X509_sign(X509 *cert, int force_v1, EVP_PKEY *pkey, const char *md,
2330 STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx)
2332 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2337 if (!X509_set_version(cert, X509_VERSION_3))
2341 * Add default SKID before AKID such that AKID can make use of it
2342 * in case the certificate is self-signed
2344 /* Prevent X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER */
2345 if (!adapt_keyid_ext(cert, ext_ctx, "subjectKeyIdentifier", "hash", 1))
2347 /* Prevent X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER */
2348 self_sign = cert_matches_key(cert, pkey);
2349 if (!adapt_keyid_ext(cert, ext_ctx, "authorityKeyIdentifier",
2350 "keyid, issuer", !self_sign))
2353 /* May add further measures for ensuring RFC 5280 compliance, see #19805 */
2355 if (mctx != NULL && do_sign_init(mctx, pkey, md, sigopts) > 0)
2356 rv = (X509_sign_ctx(cert, mctx) > 0);
2358 EVP_MD_CTX_free(mctx);
2362 /* Sign the certificate request info */
2363 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md,
2364 STACK_OF(OPENSSL_STRING) *sigopts)
2367 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2369 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2370 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
2371 EVP_MD_CTX_free(mctx);
2375 /* Sign the CRL info */
2376 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md,
2377 STACK_OF(OPENSSL_STRING) *sigopts)
2380 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2382 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2383 rv = (X509_CRL_sign_ctx(x, mctx) > 0);
2384 EVP_MD_CTX_free(mctx);
2389 * do_X509_verify returns 1 if the signature is valid,
2390 * 0 if the signature check fails, or -1 if error occurs.
2392 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
2396 if (do_x509_init(x, vfyopts) > 0)
2397 rv = X509_verify(x, pkey);
2404 * do_X509_REQ_verify returns 1 if the signature is valid,
2405 * 0 if the signature check fails, or -1 if error occurs.
2407 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
2408 STACK_OF(OPENSSL_STRING) *vfyopts)
2412 if (do_x509_req_init(x, vfyopts) > 0)
2413 rv = X509_REQ_verify_ex(x, pkey, app_get0_libctx(), app_get0_propq());
2419 /* Get first http URL from a DIST_POINT structure */
2421 static const char *get_dp_url(DIST_POINT *dp)
2423 GENERAL_NAMES *gens;
2428 if (!dp->distpoint || dp->distpoint->type != 0)
2430 gens = dp->distpoint->name.fullname;
2431 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2432 gen = sk_GENERAL_NAME_value(gens, i);
2433 uri = GENERAL_NAME_get0_value(gen, >ype);
2434 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
2435 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
2437 if (IS_HTTP(uptr)) /* can/should not use HTTPS here */
2445 * Look through a CRLDP structure and attempt to find an http URL to
2446 * downloads a CRL from.
2449 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
2452 const char *urlptr = NULL;
2454 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2455 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
2457 urlptr = get_dp_url(dp);
2459 return load_crl(urlptr, FORMAT_UNDEF, 0, "CRL via CDP");
2465 * Example of downloading CRLs from CRLDP:
2466 * not usable for real world as it always downloads and doesn't cache anything.
2469 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
2470 const X509_NAME *nm)
2473 STACK_OF(X509_CRL) *crls = NULL;
2475 STACK_OF(DIST_POINT) *crldp;
2477 crls = sk_X509_CRL_new_null();
2480 x = X509_STORE_CTX_get_current_cert(ctx);
2481 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2482 crl = load_crl_crldp(crldp);
2483 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2485 sk_X509_CRL_free(crls);
2488 sk_X509_CRL_push(crls, crl);
2489 /* Try to download delta CRL */
2490 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2491 crl = load_crl_crldp(crldp);
2492 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2494 sk_X509_CRL_push(crls, crl);
2498 void store_setup_crl_download(X509_STORE *st)
2500 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2503 #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP)
2504 static const char *tls_error_hint(void)
2506 unsigned long err = ERR_peek_error();
2508 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2509 err = ERR_peek_last_error();
2510 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2511 return NULL; /* likely no TLS error */
2513 switch (ERR_GET_REASON(err)) {
2514 case SSL_R_WRONG_VERSION_NUMBER:
2515 return "The server does not support (a suitable version of) TLS";
2516 case SSL_R_UNKNOWN_PROTOCOL:
2517 return "The server does not support HTTPS";
2518 case SSL_R_CERTIFICATE_VERIFY_FAILED:
2519 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2520 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
2521 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2522 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
2523 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2525 return NULL; /* no hint available for TLS error */
2529 static BIO *http_tls_shutdown(BIO *bio)
2533 const char *hint = tls_error_hint();
2536 BIO_printf(bio_err, "%s\n", hint);
2537 (void)ERR_set_mark();
2538 BIO_ssl_shutdown(bio);
2539 cbio = BIO_pop(bio); /* connect+HTTP BIO */
2540 BIO_free(bio); /* SSL BIO */
2541 (void)ERR_pop_to_mark(); /* hide SSL_R_READ_BIO_NOT_SET etc. */
2547 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
2548 BIO *app_http_tls_cb(BIO *bio, void *arg, int connect, int detail)
2550 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
2551 SSL_CTX *ssl_ctx = info->ssl_ctx;
2553 if (ssl_ctx == NULL) /* not using TLS */
2558 X509_STORE *ts = SSL_CTX_get_cert_store(ssl_ctx);
2559 X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts);
2560 const char *host = vpm == NULL ? NULL :
2561 X509_VERIFY_PARAM_get0_host(vpm, 0 /* first hostname */);
2563 /* adapt after fixing callback design flaw, see #17088 */
2564 if ((info->use_proxy
2565 && !OSSL_HTTP_proxy_connect(bio, info->server, info->port,
2566 NULL, NULL, /* no proxy credentials */
2567 info->timeout, bio_err, opt_getprog()))
2568 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
2571 if ((ssl = SSL_new(ssl_ctx)) == NULL) {
2577 SSL_set_tlsext_host_name(ssl, host /* may be NULL */);
2579 SSL_set_connect_state(ssl);
2580 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2582 bio = BIO_push(sbio, bio);
2583 } else { /* disconnect from TLS */
2584 bio = http_tls_shutdown(bio);
2589 void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info)
2592 SSL_CTX_free(info->ssl_ctx);
2597 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2598 const char *no_proxy, SSL_CTX *ssl_ctx,
2599 const STACK_OF(CONF_VALUE) *headers,
2600 long timeout, const char *expected_content_type,
2601 const ASN1_ITEM *it)
2603 APP_HTTP_TLS_INFO info;
2608 ASN1_VALUE *resp = NULL;
2610 if (url == NULL || it == NULL) {
2611 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
2615 if (!OSSL_HTTP_parse_url(url, &use_ssl, NULL /* userinfo */, &server, &port,
2616 NULL /* port_num, */, NULL, NULL, NULL))
2618 if (use_ssl && ssl_ctx == NULL) {
2619 ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER,
2623 if (!use_ssl && ssl_ctx != NULL) {
2624 ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT,
2625 "SSL_CTX given but use_ssl == 0");
2629 info.server = server;
2631 info.use_proxy = /* workaround for callback design flaw, see #17088 */
2632 OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl) != NULL;
2633 info.timeout = timeout;
2634 info.ssl_ctx = ssl_ctx;
2635 mem = OSSL_HTTP_get(url, proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2636 app_http_tls_cb, &info, 0 /* buf_size */, headers,
2637 expected_content_type, 1 /* expect_asn1 */,
2638 OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout);
2639 resp = ASN1_item_d2i_bio(it, mem, NULL);
2643 OPENSSL_free(server);
2649 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2650 const char *path, const char *proxy,
2651 const char *no_proxy, SSL_CTX *ssl_ctx,
2652 const STACK_OF(CONF_VALUE) *headers,
2653 const char *content_type,
2654 ASN1_VALUE *req, const ASN1_ITEM *req_it,
2655 const char *expected_content_type,
2656 long timeout, const ASN1_ITEM *rsp_it)
2658 int use_ssl = ssl_ctx != NULL;
2659 APP_HTTP_TLS_INFO info;
2660 BIO *rsp, *req_mem = ASN1_item_i2d_mem_bio(req_it, req);
2663 if (req_mem == NULL)
2668 info.use_proxy = /* workaround for callback design flaw, see #17088 */
2669 OSSL_HTTP_adapt_proxy(proxy, no_proxy, host, use_ssl) != NULL;
2670 info.timeout = timeout;
2671 info.ssl_ctx = ssl_ctx;
2672 rsp = OSSL_HTTP_transfer(NULL, host, port, path, use_ssl,
2673 proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2674 app_http_tls_cb, &info,
2675 0 /* buf_size */, headers, content_type, req_mem,
2676 expected_content_type, 1 /* expect_asn1 */,
2677 OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout,
2678 0 /* keep_alive */);
2680 res = ASN1_item_d2i_bio(rsp_it, rsp, NULL);
2688 * Platform-specific sections
2693 # define fileno(a) (int)_fileno(a)
2696 # include <windows.h>
2699 static int WIN32_rename(const char *from, const char *to)
2701 TCHAR *tfrom = NULL, *tto;
2705 if (sizeof(TCHAR) == 1) {
2706 tfrom = (TCHAR *)from;
2708 } else { /* UNICODE path */
2709 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2711 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2715 # if !defined(_WIN32_WCE) || _WIN32_WCE >= 101
2716 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2718 for (i = 0; i < flen; i++)
2719 tfrom[i] = (TCHAR)from[i];
2720 # if !defined(_WIN32_WCE) || _WIN32_WCE >= 101
2721 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2723 for (i = 0; i < tlen; i++)
2724 tto[i] = (TCHAR)to[i];
2727 if (MoveFile(tfrom, tto))
2729 err = GetLastError();
2730 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2731 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2733 err = GetLastError();
2735 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2737 else if (err == ERROR_ACCESS_DENIED)
2740 errno = EINVAL; /* we could map more codes... */
2744 if (tfrom != NULL && tfrom != (TCHAR *)from)
2750 /* app_tminterval section */
2752 double app_tminterval(int stop, int usertime)
2756 static ULARGE_INTEGER tmstart;
2757 static int warning = 1;
2758 int use_GetSystemTime = 1;
2759 # ifdef _WIN32_WINNT
2760 static HANDLE proc = NULL;
2764 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2765 GetCurrentProcessId());
2767 proc = (HANDLE) - 1;
2770 if (usertime && proc != (HANDLE) - 1) {
2773 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2774 use_GetSystemTime = 0;
2777 if (use_GetSystemTime) {
2780 if (usertime && warning) {
2781 BIO_printf(bio_err, "To get meaningful results, run "
2782 "this program on idle system.\n");
2785 GetSystemTime(&systime);
2786 SystemTimeToFileTime(&systime, &now);
2789 if (stop == TM_START) {
2790 tmstart.u.LowPart = now.dwLowDateTime;
2791 tmstart.u.HighPart = now.dwHighDateTime;
2793 ULARGE_INTEGER tmstop;
2795 tmstop.u.LowPart = now.dwLowDateTime;
2796 tmstop.u.HighPart = now.dwHighDateTime;
2798 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2803 #elif defined(OPENSSL_SYS_VXWORKS)
2806 double app_tminterval(int stop, int usertime)
2809 # ifdef CLOCK_REALTIME
2810 static struct timespec tmstart;
2811 struct timespec now;
2813 static unsigned long tmstart;
2816 static int warning = 1;
2818 if (usertime && warning) {
2819 BIO_printf(bio_err, "To get meaningful results, run "
2820 "this program on idle system.\n");
2823 # ifdef CLOCK_REALTIME
2824 clock_gettime(CLOCK_REALTIME, &now);
2825 if (stop == TM_START)
2828 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2829 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2832 if (stop == TM_START)
2835 ret = (now - tmstart) / (double)sysClkRateGet();
2840 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2841 # include <sys/times.h>
2843 double app_tminterval(int stop, int usertime)
2847 clock_t now = times(&rus);
2848 static clock_t tmstart;
2851 now = rus.tms_utime;
2853 if (stop == TM_START) {
2856 long int tck = sysconf(_SC_CLK_TCK);
2858 ret = (now - tmstart) / (double)tck;
2865 # include <sys/time.h>
2866 # include <sys/resource.h>
2868 double app_tminterval(int stop, int usertime)
2873 static struct timeval tmstart;
2876 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2878 gettimeofday(&now, NULL);
2880 if (stop == TM_START)
2883 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2884 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2890 int app_access(const char *name, int flag)
2893 return _access(name, flag);
2895 return access(name, flag);
2899 int app_isdir(const char *name)
2901 return opt_isdir(name);
2904 /* raw_read|write section */
2906 # include "vms_term_sock.h"
2907 static int stdin_sock = -1;
2909 static void close_stdin_sock(void)
2911 TerminalSocket(TERM_SOCK_DELETE, &stdin_sock);
2914 int fileno_stdin(void)
2916 if (stdin_sock == -1) {
2917 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2918 atexit(close_stdin_sock);
2924 int fileno_stdin(void)
2926 return fileno(stdin);
2930 int fileno_stdout(void)
2932 return fileno(stdout);
2935 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2936 int raw_read_stdin(void *buf, int siz)
2940 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2945 #elif defined(__VMS)
2946 # include <sys/socket.h>
2948 int raw_read_stdin(void *buf, int siz)
2950 return recv(fileno_stdin(), buf, siz, 0);
2953 # if defined(__TANDEM)
2954 # if defined(OPENSSL_TANDEM_FLOSS)
2955 # include <floss.h(floss_read)>
2958 int raw_read_stdin(void *buf, int siz)
2960 return read(fileno_stdin(), buf, siz);
2964 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2965 int raw_write_stdout(const void *buf, int siz)
2969 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2974 #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) \
2975 && defined(_SPT_MODEL_)
2976 # if defined(__TANDEM)
2977 # if defined(OPENSSL_TANDEM_FLOSS)
2978 # include <floss.h(floss_write)>
2981 int raw_write_stdout(const void *buf, int siz)
2983 return write(fileno(stdout), (void *)buf, siz);
2986 # if defined(__TANDEM)
2987 # if defined(OPENSSL_TANDEM_FLOSS)
2988 # include <floss.h(floss_write)>
2991 int raw_write_stdout(const void *buf, int siz)
2993 return write(fileno_stdout(), buf, siz);
2998 * Centralized handling of input and output files with format specification
2999 * The format is meant to show what the input and output is supposed to be,
3000 * and is therefore a show of intent more than anything else. However, it
3001 * does impact behavior on some platforms, such as differentiating between
3002 * text and binary input/output on non-Unix platforms
3004 BIO *dup_bio_in(int format)
3006 return BIO_new_fp(stdin,
3007 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
3010 BIO *dup_bio_out(int format)
3012 BIO *b = BIO_new_fp(stdout,
3013 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
3014 void *prefix = NULL;
3019 #ifdef OPENSSL_SYS_VMS
3020 if (FMT_istext(format))
3021 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
3024 if (FMT_istext(format)
3025 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
3026 b = BIO_push(BIO_new(BIO_f_prefix()), b);
3027 BIO_set_prefix(b, prefix);
3033 BIO *dup_bio_err(int format)
3035 BIO *b = BIO_new_fp(stderr,
3036 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
3038 #ifdef OPENSSL_SYS_VMS
3039 if (b != NULL && FMT_istext(format))
3040 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
3045 void unbuffer(FILE *fp)
3048 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
3049 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
3050 * However, we trust that the C RTL will never give us a FILE pointer
3051 * above the first 4 GB of memory, so we simply turn off the warning
3054 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
3055 # pragma environment save
3056 # pragma message disable maylosedata2
3059 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
3060 # pragma environment restore
3064 static const char *modestr(char mode, int format)
3066 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
3070 return FMT_istext(format) ? "a" : "ab";
3072 return FMT_istext(format) ? "r" : "rb";
3074 return FMT_istext(format) ? "w" : "wb";
3076 /* The assert above should make sure we never reach this point */
3080 static const char *modeverb(char mode)
3090 return "(doing something)";
3094 * Open a file for writing, owner-read-only.
3096 BIO *bio_open_owner(const char *filename, int format, int private)
3100 int textmode, bflags;
3101 #ifndef OPENSSL_NO_POSIX_IO
3105 if (!private || filename == NULL || strcmp(filename, "-") == 0)
3106 return bio_open_default(filename, 'w', format);
3108 textmode = FMT_istext(format);
3109 #ifndef OPENSSL_NO_POSIX_IO
3120 # elif defined(_O_BINARY)
3125 # ifdef OPENSSL_SYS_VMS
3127 * VMS doesn't have O_BINARY, it just doesn't make sense. But,
3128 * it still needs to know that we're going binary, or fdopen()
3129 * will fail with "invalid argument"... so we tell VMS what the
3133 fd = open(filename, mode, 0600, "ctx=bin");
3136 fd = open(filename, mode, 0600);
3139 fp = fdopen(fd, modestr('w', format));
3140 #else /* OPENSSL_NO_POSIX_IO */
3141 /* Have stdio but not Posix IO, do the best we can */
3142 fp = fopen(filename, modestr('w', format));
3143 #endif /* OPENSSL_NO_POSIX_IO */
3148 bflags |= BIO_FP_TEXT;
3149 b = BIO_new_fp(fp, bflags);
3154 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
3155 opt_getprog(), filename, strerror(errno));
3156 ERR_print_errors(bio_err);
3157 /* If we have fp, then fdopen took over fd, so don't close both. */
3160 #ifndef OPENSSL_NO_POSIX_IO
3167 static BIO *bio_open_default_(const char *filename, char mode, int format,
3172 if (filename == NULL || strcmp(filename, "-") == 0) {
3173 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
3181 "Can't open %s, %s\n",
3182 mode == 'r' ? "stdin" : "stdout", strerror(errno));
3184 ret = BIO_new_file(filename, modestr(mode, format));
3192 "Can't open \"%s\" for %s, %s\n",
3193 filename, modeverb(mode), strerror(errno));
3195 ERR_print_errors(bio_err);
3199 BIO *bio_open_default(const char *filename, char mode, int format)
3201 return bio_open_default_(filename, mode, format, 0);
3204 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
3206 return bio_open_default_(filename, mode, format, 1);
3209 void wait_for_async(SSL *s)
3211 /* On Windows select only works for sockets, so we simply don't wait */
3212 #ifndef OPENSSL_SYS_WINDOWS
3219 if (!SSL_get_all_async_fds(s, NULL, &numfds))
3223 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
3224 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
3230 for (i = 0; i < numfds; i++) {
3231 if (width <= (int)fds[i])
3232 width = (int)fds[i] + 1;
3233 openssl_fdset((int)fds[i], &asyncfds);
3235 select(width, (void *)&asyncfds, NULL, NULL, NULL);
3240 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
3241 #if defined(OPENSSL_SYS_MSDOS)
3242 int has_stdin_waiting(void)
3244 # if defined(OPENSSL_SYS_WINDOWS)
3245 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
3247 INPUT_RECORD inputrec;
3251 if (inhand == INVALID_HANDLE_VALUE) {
3255 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
3257 /* Probably redirected input? _kbhit() does not work in this case */
3268 /* Corrupt a signature by modifying final byte */
3269 void corrupt_signature(const ASN1_STRING *signature)
3271 unsigned char *s = signature->data;
3273 s[signature->length - 1] ^= 0x1;
3276 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
3279 if (startdate == NULL || strcmp(startdate, "today") == 0) {
3280 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
3283 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
3286 if (enddate == NULL) {
3287 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
3290 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
3296 int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate)
3299 ASN1_TIME *tm = ASN1_TIME_new();
3304 if (lastupdate == NULL) {
3305 if (X509_gmtime_adj(tm, 0) == NULL)
3308 if (!ASN1_TIME_set_string_X509(tm, lastupdate))
3312 if (!X509_CRL_set1_lastUpdate(crl, tm))
3321 int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
3322 long days, long hours, long secs)
3325 ASN1_TIME *tm = ASN1_TIME_new();
3330 if (nextupdate == NULL) {
3331 if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL)
3334 if (!ASN1_TIME_set_string_X509(tm, nextupdate))
3338 if (!X509_CRL_set1_nextUpdate(crl, tm))
3347 void make_uppercase(char *string)
3351 for (i = 0; string[i] != '\0'; i++)
3352 string[i] = toupper((unsigned char)string[i]);
3355 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
3356 const OSSL_PARAM *paramdefs)
3358 OSSL_PARAM *params = NULL;
3359 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
3361 char *opt = "", *stmp, *vtmp = NULL;
3367 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
3371 for (params_n = 0; params_n < sz; params_n++) {
3372 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
3373 if ((stmp = OPENSSL_strdup(opt)) == NULL
3374 || (vtmp = strchr(stmp, ':')) == NULL)
3376 /* Replace ':' with 0 to terminate the string pointed to by stmp */
3378 /* Skip over the separator so that vmtp points to the value */
3380 if (!OSSL_PARAM_allocate_from_text(¶ms[params_n], paramdefs,
3381 stmp, vtmp, strlen(vtmp), &found))
3385 params[params_n] = OSSL_PARAM_construct_end();
3389 BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
3391 ERR_print_errors(bio_err);
3392 app_params_free(params);
3396 void app_params_free(OSSL_PARAM *params)
3400 if (params != NULL) {
3401 for (i = 0; params[i].key != NULL; ++i)
3402 OPENSSL_free(params[i].data);
3403 OPENSSL_free(params);
3407 EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose)
3409 EVP_PKEY *res = NULL;
3411 if (verbose && alg != NULL) {
3412 BIO_printf(bio_err, "Generating %s key", alg);
3414 BIO_printf(bio_err, " with %d bits\n", bits);
3416 BIO_printf(bio_err, "\n");
3419 BIO_printf(bio_err, "Warning: generating random key material may take a long time\n"
3420 "if the system has a poor entropy source\n");
3421 if (EVP_PKEY_keygen(ctx, &res) <= 0)
3422 app_bail_out("%s: Error generating %s key\n", opt_getprog(),
3423 alg != NULL ? alg : "asymmetric");
3427 EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg)
3429 EVP_PKEY *res = NULL;
3432 BIO_printf(bio_err, "Warning: generating random key parameters may take a long time\n"
3433 "if the system has a poor entropy source\n");
3434 if (EVP_PKEY_paramgen(ctx, &res) <= 0)
3435 app_bail_out("%s: Generating %s key parameters failed\n",
3436 opt_getprog(), alg != NULL ? alg : "asymmetric");
3441 * Return non-zero if the legacy path is still an option.
3442 * This decision is based on the global command line operations and the
3443 * behaviour thus far.
3445 int opt_legacy_okay(void)
3447 int provider_options = opt_provider_option_given();
3448 int libctx = app_get0_libctx() != NULL || app_get0_propq() != NULL;
3450 * Having a provider option specified or a custom library context or
3451 * property query, is a sure sign we're not using legacy.
3453 if (provider_options || libctx)