2 * Copyright 1995-2021 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/store.h>
48 #include <openssl/core_names.h>
53 static int WIN32_rename(const char *from, const char *to);
54 # define rename(from,to) WIN32_rename((from),(to))
57 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
61 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) || defined(__BORLANDC__)
65 static BIO *bio_open_default_(const char *filename, char mode, int format,
68 #define PASS_SOURCE_SIZE_MAX 4
78 static int set_table_opts(unsigned long *flags, const char *arg,
79 const NAME_EX_TBL * in_tbl);
80 static int set_multi_opts(unsigned long *flags, const char *arg,
81 const NAME_EX_TBL * in_tbl);
83 int load_key_certs_crls_suppress(const char *uri, int format, int maybe_stdin,
84 const char *pass, const char *desc,
85 EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
87 X509 **pcert, STACK_OF(X509) **pcerts,
88 X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls,
89 int suppress_decode_errors);
91 int app_init(long mesgwin);
93 int chopup_args(ARGS *arg, char *buf)
96 char c = '\0', *p = NULL;
101 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
105 /* Skip whitespace. */
106 while (*p && isspace(_UC(*p)))
111 /* The start of something good :-) */
112 if (arg->argc >= arg->size) {
115 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
120 quoted = *p == '\'' || *p == '"';
123 arg->argv[arg->argc++] = p;
125 /* now look for the end of this */
127 while (*p && *p != c)
131 while (*p && !isspace(_UC(*p)))
137 arg->argv[arg->argc] = NULL;
142 int app_init(long mesgwin)
148 int ctx_set_verify_locations(SSL_CTX *ctx,
149 const char *CAfile, int noCAfile,
150 const char *CApath, int noCApath,
151 const char *CAstore, int noCAstore)
153 if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
154 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
156 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
158 if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
164 if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
166 if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
168 if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
173 #ifndef OPENSSL_NO_CT
175 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
178 return SSL_CTX_set_default_ctlog_list_file(ctx);
180 return SSL_CTX_set_ctlog_list_file(ctx, path);
185 static unsigned long nmflag = 0;
186 static char nmflag_set = 0;
188 int set_nameopt(const char *arg)
190 int ret = set_name_ex(&nmflag, arg);
198 unsigned long get_nameopt(void)
200 return (nmflag_set) ? nmflag : XN_FLAG_SEP_CPLUS_SPC | ASN1_STRFLGS_UTF8_CONVERT;
203 void dump_cert_text(BIO *out, X509 *x)
205 print_name(out, "subject=", X509_get_subject_name(x));
206 print_name(out, "issuer=", X509_get_issuer_name(x));
209 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
211 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
215 static char *app_get_pass(const char *arg, int keepbio);
217 char *get_passwd(const char *pass, const char *desc)
223 if (!app_passwd(pass, NULL, &result, NULL))
224 BIO_printf(bio_err, "Error getting password for %s\n", desc);
225 if (pass != NULL && result == NULL) {
227 "Trying plain input string (better precede with 'pass:')\n");
228 result = OPENSSL_strdup(pass);
230 BIO_printf(bio_err, "Out of memory getting password for %s\n", desc);
235 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
237 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
240 *pass1 = app_get_pass(arg1, same);
243 } else if (pass1 != NULL) {
247 *pass2 = app_get_pass(arg2, same ? 2 : 0);
250 } else if (pass2 != NULL) {
256 static char *app_get_pass(const char *arg, int keepbio)
258 static BIO *pwdbio = NULL;
259 char *tmp, tpass[APP_PASS_LEN];
262 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
263 if (CHECK_AND_SKIP_PREFIX(arg, "pass:"))
264 return OPENSSL_strdup(arg);
265 if (CHECK_AND_SKIP_PREFIX(arg, "env:")) {
268 BIO_printf(bio_err, "No environment variable %s\n", arg);
271 return OPENSSL_strdup(tmp);
273 if (!keepbio || pwdbio == NULL) {
274 if (CHECK_AND_SKIP_PREFIX(arg, "file:")) {
275 pwdbio = BIO_new_file(arg, "r");
276 if (pwdbio == NULL) {
277 BIO_printf(bio_err, "Can't open file %s\n", arg);
282 * Under _WIN32, which covers even Win64 and CE, file
283 * descriptors referenced by BIO_s_fd are not inherited
284 * by child process and therefore below is not an option.
285 * It could have been an option if bss_fd.c was operating
286 * on real Windows descriptors, such as those obtained
289 } else if (CHECK_AND_SKIP_PREFIX(arg, "fd:")) {
293 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
294 if ((i < 0) || !pwdbio) {
295 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg);
299 * Can't do BIO_gets on an fd BIO so add a buffering BIO
301 btmp = BIO_new(BIO_f_buffer());
302 pwdbio = BIO_push(btmp, pwdbio);
304 } 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 CONF *app_load_config_bio(BIO *in, const char *filename)
345 conf = NCONF_new_ex(app_get0_libctx(), NULL);
346 i = NCONF_load_bio(conf, in, &errorline);
350 if (errorline <= 0) {
351 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
353 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
356 if (filename != NULL)
357 BIO_printf(bio_err, "config file \"%s\"\n", filename);
359 BIO_printf(bio_err, "config input");
365 CONF *app_load_config_verbose(const char *filename, int verbose)
368 if (*filename == '\0')
369 BIO_printf(bio_err, "No configuration used\n");
371 BIO_printf(bio_err, "Using configuration from %s\n", filename);
373 return app_load_config_internal(filename, 0);
376 CONF *app_load_config_internal(const char *filename, int quiet)
381 if (filename == NULL || *filename != '\0') {
382 if ((in = bio_open_default_(filename, 'r', FORMAT_TEXT, quiet)) == NULL)
384 conf = app_load_config_bio(in, filename);
387 /* Return empty config if filename is empty string. */
388 conf = NCONF_new_ex(app_get0_libctx(), NULL);
393 int app_load_modules(const CONF *config)
395 CONF *to_free = NULL;
398 config = to_free = app_load_config_quiet(default_config_file);
402 if (CONF_modules_load(config, NULL, 0) <= 0) {
403 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
404 ERR_print_errors(bio_err);
412 int add_oid_section(CONF *conf)
415 STACK_OF(CONF_VALUE) *sktmp;
419 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
423 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
424 BIO_printf(bio_err, "problem loading oid section %s\n", p);
427 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
428 cnf = sk_CONF_VALUE_value(sktmp, i);
429 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
430 BIO_printf(bio_err, "problem creating object %s=%s\n",
431 cnf->name, cnf->value);
438 CONF *app_load_config_modules(const char *configfile)
442 if (configfile != NULL) {
443 if ((conf = app_load_config_verbose(configfile, 1)) == NULL)
445 if (configfile != default_config_file && !app_load_modules(conf)) {
453 #define IS_HTTP(uri) ((uri) != NULL && HAS_PREFIX(uri, OSSL_HTTP_PREFIX))
454 #define IS_HTTPS(uri) ((uri) != NULL && HAS_PREFIX(uri, OSSL_HTTPS_PREFIX))
456 X509 *load_cert_pass(const char *uri, int format, int maybe_stdin,
457 const char *pass, const char *desc)
462 desc = "certificate";
464 BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
465 else if (IS_HTTP(uri))
466 cert = X509_load_http(uri, NULL, NULL, 0 /* timeout */);
468 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc,
469 NULL, NULL, NULL, &cert, NULL, NULL, NULL);
471 BIO_printf(bio_err, "Unable to load %s\n", desc);
472 ERR_print_errors(bio_err);
477 X509_CRL *load_crl(const char *uri, int format, int maybe_stdin,
480 X509_CRL *crl = NULL;
485 BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
486 else if (IS_HTTP(uri))
487 crl = X509_CRL_load_http(uri, NULL, NULL, 0 /* timeout */);
489 (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc,
490 NULL, NULL, NULL, NULL, NULL, &crl, NULL);
492 BIO_printf(bio_err, "Unable to load %s\n", desc);
493 ERR_print_errors(bio_err);
498 X509_REQ *load_csr(const char *file, int format, const char *desc)
500 X509_REQ *req = NULL;
503 if (format == FORMAT_UNDEF)
507 in = bio_open_default(file, 'r', format);
511 if (format == FORMAT_ASN1)
512 req = d2i_X509_REQ_bio(in, NULL);
513 else if (format == FORMAT_PEM)
514 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
516 print_format_error(format, OPT_FMT_PEMDER);
520 BIO_printf(bio_err, "Unable to load %s\n", desc);
521 ERR_print_errors(bio_err);
527 void cleanse(char *str)
530 OPENSSL_cleanse(str, strlen(str));
533 void clear_free(char *str)
536 OPENSSL_clear_free(str, strlen(str));
539 EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
540 const char *pass, ENGINE *e, const char *desc)
542 EVP_PKEY *pkey = NULL;
543 char *allocated_uri = NULL;
546 desc = "private key";
548 if (format == FORMAT_ENGINE) {
549 uri = allocated_uri = make_engine_uri(e, uri, desc);
551 (void)load_key_certs_crls(uri, format, may_stdin, pass, desc,
552 &pkey, NULL, NULL, NULL, NULL, NULL, NULL);
554 OPENSSL_free(allocated_uri);
558 EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
559 const char *pass, ENGINE *e, const char *desc)
561 EVP_PKEY *pkey = NULL;
562 char *allocated_uri = NULL;
567 if (format == FORMAT_ENGINE) {
568 uri = allocated_uri = make_engine_uri(e, uri, desc);
570 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc,
571 NULL, &pkey, NULL, NULL, NULL, NULL, NULL);
573 OPENSSL_free(allocated_uri);
577 EVP_PKEY *load_keyparams_suppress(const char *uri, int format, int maybe_stdin,
578 const char *keytype, const char *desc,
579 int suppress_decode_errors)
581 EVP_PKEY *params = NULL;
584 desc = "key parameters";
586 (void)load_key_certs_crls_suppress(uri, format, maybe_stdin, NULL, desc,
587 NULL, NULL, ¶ms, NULL, NULL, NULL,
588 NULL, suppress_decode_errors);
589 if (params != NULL && keytype != NULL && !EVP_PKEY_is_a(params, keytype)) {
590 if (!suppress_decode_errors) {
592 "Unable to load %s from %s (unexpected parameters type)\n",
594 ERR_print_errors(bio_err);
596 EVP_PKEY_free(params);
602 EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin,
603 const char *keytype, const char *desc)
605 return load_keyparams_suppress(uri, format, maybe_stdin, keytype, desc, 0);
608 void app_bail_out(char *fmt, ...)
613 BIO_vprintf(bio_err, fmt, args);
615 ERR_print_errors(bio_err);
619 void *app_malloc(size_t sz, const char *what)
621 void *vp = OPENSSL_malloc(sz);
624 app_bail_out("%s: Could not allocate %zu bytes for %s\n",
625 opt_getprog(), sz, what);
629 char *next_item(char *opt) /* in list separated by comma and/or space */
631 /* advance to separator (comma or whitespace), if any */
632 while (*opt != ',' && !isspace(*opt) && *opt != '\0')
635 /* terminate current item */
637 /* skip over any whitespace after separator */
638 while (isspace(*opt))
641 return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */
644 static void warn_cert_msg(const char *uri, X509 *cert, const char *msg)
646 char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
648 BIO_printf(bio_err, "Warning: certificate from '%s' with subject '%s' %s\n",
653 static void warn_cert(const char *uri, X509 *cert, int warn_EE,
654 X509_VERIFY_PARAM *vpm)
656 uint32_t ex_flags = X509_get_extension_flags(cert);
657 int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
658 X509_get0_notAfter(cert));
661 warn_cert_msg(uri, cert, res > 0 ? "has expired" : "not yet valid");
662 if (warn_EE && (ex_flags & EXFLAG_V1) == 0 && (ex_flags & EXFLAG_CA) == 0)
663 warn_cert_msg(uri, cert, "is not a CA cert");
666 static void warn_certs(const char *uri, STACK_OF(X509) *certs, int warn_EE,
667 X509_VERIFY_PARAM *vpm)
671 for (i = 0; i < sk_X509_num(certs); i++)
672 warn_cert(uri, sk_X509_value(certs, i), warn_EE, vpm);
675 int load_cert_certs(const char *uri,
676 X509 **pcert, STACK_OF(X509) **pcerts,
677 int exclude_http, const char *pass, const char *desc,
678 X509_VERIFY_PARAM *vpm)
683 if (exclude_http && (HAS_CASE_PREFIX(uri, "http://")
684 || HAS_CASE_PREFIX(uri, "https://"))) {
685 BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc);
688 pass_string = get_passwd(pass, desc);
689 ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass_string, desc,
691 pcert, pcerts, NULL, NULL);
692 clear_free(pass_string);
696 warn_cert(uri, *pcert, 0, vpm);
697 warn_certs(uri, *pcerts, 1, vpm);
699 OSSL_STACK_OF_X509_free(*pcerts);
705 STACK_OF(X509) *load_certs_multifile(char *files, const char *pass,
706 const char *desc, X509_VERIFY_PARAM *vpm)
708 STACK_OF(X509) *certs = NULL;
709 STACK_OF(X509) *result = sk_X509_new_null();
716 while (files != NULL) {
717 char *next = next_item(files);
719 if (!load_cert_certs(files, NULL, &certs, 0, pass, desc, vpm))
721 if (!X509_add_certs(result, certs,
722 X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
724 OSSL_STACK_OF_X509_free(certs);
731 BIO_printf(bio_err, "out of memory\n");
733 OSSL_STACK_OF_X509_free(certs);
734 OSSL_STACK_OF_X509_free(result);
738 static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */,
739 const STACK_OF(X509) *certs /* may NULL */)
744 store = X509_STORE_new();
747 for (i = 0; i < sk_X509_num(certs); i++) {
748 if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) {
749 X509_STORE_free(store);
757 * Create cert store structure with certificates read from given file(s).
758 * Returns pointer to created X509_STORE on success, NULL on error.
760 X509_STORE *load_certstore(char *input, const char *pass, const char *desc,
761 X509_VERIFY_PARAM *vpm)
763 X509_STORE *store = NULL;
764 STACK_OF(X509) *certs = NULL;
766 while (input != NULL) {
767 char *next = next_item(input);
770 if (!load_cert_certs(input, NULL, &certs, 1, pass, desc, vpm)) {
771 X509_STORE_free(store);
774 ok = (store = sk_X509_to_store(store, certs)) != NULL;
775 OSSL_STACK_OF_X509_free(certs);
785 * Initialize or extend, if *certs != NULL, a certificate stack.
786 * The caller is responsible for freeing *certs if its value is left not NULL.
788 int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs,
789 const char *pass, const char *desc)
791 int was_NULL = *certs == NULL;
792 int ret = load_key_certs_crls(uri, FORMAT_UNDEF, maybe_stdin,
793 pass, desc, NULL, NULL,
794 NULL, NULL, certs, NULL, NULL);
796 if (!ret && was_NULL) {
797 OSSL_STACK_OF_X509_free(*certs);
804 * Initialize or extend, if *crls != NULL, a certificate stack.
805 * The caller is responsible for freeing *crls if its value is left not NULL.
807 int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
808 const char *pass, const char *desc)
810 int was_NULL = *crls == NULL;
811 int ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass, desc,
813 NULL, NULL, NULL, crls);
815 if (!ret && was_NULL) {
816 sk_X509_CRL_pop_free(*crls, X509_CRL_free);
822 static const char *format2string(int format)
833 /* Set type expectation, but clear it if objects of different types expected. */
834 #define SET_EXPECT(expect, val) ((expect) = (expect) < 0 ? (val) : ((expect) == (val) ? (val) : 0))
836 * Load those types of credentials for which the result pointer is not NULL.
837 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
838 * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
839 * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
840 * If pcerts is non-NULL then all available certificates are appended to *pcerts
841 * except any certificate assigned to *pcert.
842 * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
843 * If pcrls is non-NULL then all available CRLs are appended to *pcerts
844 * except any CRL assigned to *pcrl.
845 * In any case (also on error) the caller is responsible for freeing all members
846 * of *pcerts and *pcrls (as far as they are not NULL).
849 int load_key_certs_crls_suppress(const char *uri, int format, int maybe_stdin,
850 const char *pass, const char *desc,
851 EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
853 X509 **pcert, STACK_OF(X509) **pcerts,
854 X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls,
855 int suppress_decode_errors)
858 OSSL_STORE_CTX *ctx = NULL;
859 OSSL_LIB_CTX *libctx = app_get0_libctx();
860 const char *propq = app_get0_propq();
864 ppkey != NULL ? "key" : ppubkey != NULL ? "public key" :
865 pparams != NULL ? "params" : pcert != NULL ? "cert" :
866 pcrl != NULL ? "CRL" : pcerts != NULL ? "certs" :
867 pcrls != NULL ? "CRLs" : NULL;
868 int cnt_expectations = 0;
870 const char *input_type;
872 const OSSL_PARAM *params = NULL;
877 SET_EXPECT(expect, OSSL_STORE_INFO_PKEY);
879 if (ppubkey != NULL) {
882 SET_EXPECT(expect, OSSL_STORE_INFO_PUBKEY);
884 if (pparams != NULL) {
887 SET_EXPECT(expect, OSSL_STORE_INFO_PARAMS);
892 SET_EXPECT(expect, OSSL_STORE_INFO_CERT);
894 if (pcerts != NULL) {
895 if (*pcerts == NULL && (*pcerts = sk_X509_new_null()) == NULL) {
896 BIO_printf(bio_err, "Out of memory loading");
900 SET_EXPECT(expect, OSSL_STORE_INFO_CERT);
905 SET_EXPECT(expect, OSSL_STORE_INFO_CRL);
908 if (*pcrls == NULL && (*pcrls = sk_X509_CRL_new_null()) == NULL) {
909 BIO_printf(bio_err, "Out of memory loading");
913 SET_EXPECT(expect, OSSL_STORE_INFO_CRL);
915 if (cnt_expectations == 0) {
916 BIO_printf(bio_err, "Internal error: nothing to load from %s\n",
917 uri != NULL ? uri : "<stdin>");
921 uidata.password = pass;
922 uidata.prompt_info = uri;
924 if ((input_type = format2string(format)) != NULL) {
925 itp[0] = OSSL_PARAM_construct_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE,
926 (char *)input_type, 0);
927 itp[1] = OSSL_PARAM_construct_end();
935 BIO_printf(bio_err, "No filename or uri specified for loading");
940 bio = BIO_new_fp(stdin, 0);
942 ctx = OSSL_STORE_attach(bio, "file", libctx, propq,
943 get_ui_method(), &uidata, params,
948 ctx = OSSL_STORE_open_ex(uri, libctx, propq, get_ui_method(), &uidata,
952 BIO_printf(bio_err, "Could not open file or uri for loading");
955 if (expect > 0 && !OSSL_STORE_expect(ctx, expect))
959 while (cnt_expectations > 0 && !OSSL_STORE_eof(ctx)) {
960 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
964 * This can happen (for example) if we attempt to load a file with
965 * multiple different types of things in it - but the thing we just
966 * tried to load wasn't one of the ones we wanted, e.g. if we're trying
967 * to load a certificate but the file has both the private key and the
968 * certificate in it. We just retry until eof.
974 type = OSSL_STORE_INFO_get_type(info);
976 case OSSL_STORE_INFO_PKEY:
977 if (ppkey != NULL && *ppkey == NULL) {
978 ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL;
979 cnt_expectations -= ok;
982 * An EVP_PKEY with private parts also holds the public parts,
983 * so if the caller asked for a public key, and we got a private
984 * key, we can still pass it back.
986 if (ok && ppubkey != NULL && *ppubkey == NULL) {
987 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL);
988 cnt_expectations -= ok;
991 case OSSL_STORE_INFO_PUBKEY:
992 if (ppubkey != NULL && *ppubkey == NULL) {
993 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL);
994 cnt_expectations -= ok;
997 case OSSL_STORE_INFO_PARAMS:
998 if (pparams != NULL && *pparams == NULL) {
999 ok = ((*pparams = OSSL_STORE_INFO_get1_PARAMS(info)) != NULL);
1000 cnt_expectations -= ok;
1003 case OSSL_STORE_INFO_CERT:
1004 if (pcert != NULL && *pcert == NULL) {
1005 ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL;
1006 cnt_expectations -= ok;
1008 else if (pcerts != NULL)
1009 ok = X509_add_cert(*pcerts,
1010 OSSL_STORE_INFO_get1_CERT(info),
1011 X509_ADD_FLAG_DEFAULT);
1014 case OSSL_STORE_INFO_CRL:
1015 if (pcrl != NULL && *pcrl == NULL) {
1016 ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL;
1017 cnt_expectations -= ok;
1019 else if (pcrls != NULL)
1020 ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info));
1024 /* skip any other type */
1027 OSSL_STORE_INFO_free(info);
1029 failed = info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
1030 BIO_printf(bio_err, "Error reading");
1036 OSSL_STORE_close(ctx);
1037 if (failed == NULL) {
1040 if ((ppkey != NULL && *ppkey == NULL)
1041 || (ppubkey != NULL && *ppubkey == NULL)) {
1043 } else if (pparams != NULL && *pparams == NULL) {
1045 } else if ((pcert != NULL || pcerts != NULL) && ncerts == 0) {
1049 } else if ((pcrl != NULL || pcrls != NULL) && ncrls == 0) {
1054 if (!suppress_decode_errors) {
1056 BIO_printf(bio_err, "Could not read");
1058 BIO_printf(bio_err, " any");
1061 if (!suppress_decode_errors && failed != NULL) {
1062 if (desc != NULL && strstr(desc, failed) != NULL) {
1063 BIO_printf(bio_err, " %s", desc);
1065 BIO_printf(bio_err, " %s", failed);
1067 BIO_printf(bio_err, " of %s", desc);
1070 BIO_printf(bio_err, " from %s", uri);
1071 BIO_printf(bio_err, "\n");
1072 ERR_print_errors(bio_err);
1074 if (suppress_decode_errors || failed == NULL)
1075 /* clear any spurious errors */
1077 return failed == NULL;
1080 int load_key_certs_crls(const char *uri, int format, int maybe_stdin,
1081 const char *pass, const char *desc,
1082 EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
1084 X509 **pcert, STACK_OF(X509) **pcerts,
1085 X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
1087 return load_key_certs_crls_suppress(uri, format, maybe_stdin, pass, desc,
1088 ppkey, ppubkey, pparams, pcert, pcerts,
1092 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
1093 /* Return error for unknown extensions */
1094 #define X509V3_EXT_DEFAULT 0
1095 /* Print error for unknown extensions */
1096 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
1097 /* ASN1 parse unknown extensions */
1098 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
1099 /* BIO_dump unknown extensions */
1100 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
1102 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1103 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1105 int set_cert_ex(unsigned long *flags, const char *arg)
1107 static const NAME_EX_TBL cert_tbl[] = {
1108 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
1109 {"ca_default", X509_FLAG_CA, 0xffffffffl},
1110 {"no_header", X509_FLAG_NO_HEADER, 0},
1111 {"no_version", X509_FLAG_NO_VERSION, 0},
1112 {"no_serial", X509_FLAG_NO_SERIAL, 0},
1113 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
1114 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
1115 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
1116 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1117 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1118 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1119 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1120 {"no_aux", X509_FLAG_NO_AUX, 0},
1121 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1122 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1123 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1124 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1125 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1128 return set_multi_opts(flags, arg, cert_tbl);
1131 int set_name_ex(unsigned long *flags, const char *arg)
1133 static const NAME_EX_TBL ex_tbl[] = {
1134 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1135 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
1136 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1137 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1138 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1139 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1140 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1141 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1142 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1143 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1144 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1145 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1146 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1147 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1148 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1149 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1150 {"dn_rev", XN_FLAG_DN_REV, 0},
1151 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1152 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1153 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1154 {"align", XN_FLAG_FN_ALIGN, 0},
1155 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1156 {"space_eq", XN_FLAG_SPC_EQ, 0},
1157 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1158 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1159 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1160 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1161 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1164 if (set_multi_opts(flags, arg, ex_tbl) == 0)
1166 if (*flags != XN_FLAG_COMPAT
1167 && (*flags & XN_FLAG_SEP_MASK) == 0)
1168 *flags |= XN_FLAG_SEP_CPLUS_SPC;
1172 int set_dateopt(unsigned long *dateopt, const char *arg)
1174 if (strcasecmp(arg, "rfc_822") == 0)
1175 *dateopt = ASN1_DTFLGS_RFC822;
1176 else if (strcasecmp(arg, "iso_8601") == 0)
1177 *dateopt = ASN1_DTFLGS_ISO8601;
1181 int set_ext_copy(int *copy_type, const char *arg)
1183 if (strcasecmp(arg, "none") == 0)
1184 *copy_type = EXT_COPY_NONE;
1185 else if (strcasecmp(arg, "copy") == 0)
1186 *copy_type = EXT_COPY_ADD;
1187 else if (strcasecmp(arg, "copyall") == 0)
1188 *copy_type = EXT_COPY_ALL;
1194 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1196 STACK_OF(X509_EXTENSION) *exts;
1199 if (x == NULL || req == NULL)
1201 if (copy_type == EXT_COPY_NONE)
1203 exts = X509_REQ_get_extensions(req);
1205 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1206 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
1207 ASN1_OBJECT *obj = X509_EXTENSION_get_object(ext);
1208 int idx = X509_get_ext_by_OBJ(x, obj, -1);
1210 /* Does extension exist in target? */
1212 /* If normal copy don't override existing extension */
1213 if (copy_type == EXT_COPY_ADD)
1215 /* Delete all extensions of same type */
1217 X509_EXTENSION_free(X509_delete_ext(x, idx));
1218 idx = X509_get_ext_by_OBJ(x, obj, -1);
1219 } while (idx != -1);
1221 if (!X509_add_ext(x, ext, -1))
1227 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1231 static int set_multi_opts(unsigned long *flags, const char *arg,
1232 const NAME_EX_TBL * in_tbl)
1234 STACK_OF(CONF_VALUE) *vals;
1239 vals = X509V3_parse_list(arg);
1240 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1241 val = sk_CONF_VALUE_value(vals, i);
1242 if (!set_table_opts(flags, val->name, in_tbl))
1245 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1249 static int set_table_opts(unsigned long *flags, const char *arg,
1250 const NAME_EX_TBL * in_tbl)
1253 const NAME_EX_TBL *ptbl;
1259 } else if (c == '+') {
1266 for (ptbl = in_tbl; ptbl->name; ptbl++) {
1267 if (strcasecmp(arg, ptbl->name) == 0) {
1268 *flags &= ~ptbl->mask;
1270 *flags |= ptbl->flag;
1272 *flags &= ~ptbl->flag;
1279 void print_name(BIO *out, const char *title, const X509_NAME *nm)
1284 unsigned long lflags = get_nameopt();
1289 BIO_puts(out, title);
1290 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1294 if (lflags == XN_FLAG_COMPAT) {
1295 buf = X509_NAME_oneline(nm, 0, 0);
1297 BIO_puts(out, "\n");
1301 BIO_puts(out, "\n");
1302 X509_NAME_print_ex(out, nm, indent, lflags);
1303 BIO_puts(out, "\n");
1307 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1308 int len, unsigned char *buffer)
1310 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1311 if (BN_is_zero(in)) {
1312 BIO_printf(out, "\n 0x00");
1316 l = BN_bn2bin(in, buffer);
1317 for (i = 0; i < l; i++) {
1318 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1320 BIO_printf(out, "0x%02X,", buffer[i]);
1322 BIO_printf(out, "0x%02X", buffer[i]);
1325 BIO_printf(out, "\n };\n");
1328 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1332 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1333 for (i = 0; i < len; i++) {
1335 BIO_printf(out, "\n ");
1337 BIO_printf(out, "0x%02X, ", d[i]);
1339 BIO_printf(out, "0x%02X", d[i]);
1341 BIO_printf(out, "\n};\n");
1344 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1345 const char *CApath, int noCApath,
1346 const char *CAstore, int noCAstore)
1348 X509_STORE *store = X509_STORE_new();
1349 X509_LOOKUP *lookup;
1350 OSSL_LIB_CTX *libctx = app_get0_libctx();
1351 const char *propq = app_get0_propq();
1356 if (CAfile != NULL || !noCAfile) {
1357 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1360 if (CAfile != NULL) {
1361 if (!X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM,
1363 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1367 X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT,
1372 if (CApath != NULL || !noCApath) {
1373 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1376 if (CApath != NULL) {
1377 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1378 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1382 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1386 if (CAstore != NULL || !noCAstore) {
1387 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1390 if (!X509_LOOKUP_add_store_ex(lookup, CAstore, libctx, propq)) {
1391 if (CAstore != NULL)
1392 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1400 ERR_print_errors(bio_err);
1401 X509_STORE_free(store);
1405 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1412 return OPENSSL_LH_strhash(n);
1415 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1416 const OPENSSL_CSTRING *b)
1418 const char *aa, *bb;
1420 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1421 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1422 return strcmp(aa, bb);
1425 static int index_name_qual(char **a)
1427 return (a[0][0] == 'V');
1430 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1432 return OPENSSL_LH_strhash(a[DB_name]);
1435 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1437 return strcmp(a[DB_name], b[DB_name]);
1440 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1441 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1442 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1443 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1446 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1451 ASN1_INTEGER *ai = NULL;
1453 ai = ASN1_INTEGER_new();
1457 in = BIO_new_file(serialfile, "r");
1465 if (ret == NULL || !rand_serial(ret, ai))
1466 BIO_printf(bio_err, "Out of memory\n");
1468 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1469 BIO_printf(bio_err, "Unable to load number from %s\n",
1473 ret = ASN1_INTEGER_to_BN(ai, NULL);
1475 BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1485 ERR_print_errors(bio_err);
1487 ASN1_INTEGER_free(ai);
1491 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1492 ASN1_INTEGER **retai)
1497 ASN1_INTEGER *ai = NULL;
1501 j = strlen(serialfile);
1503 j = strlen(serialfile) + strlen(suffix) + 1;
1505 BIO_printf(bio_err, "File name too long\n");
1510 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1512 #ifndef OPENSSL_SYS_VMS
1513 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1515 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1518 out = BIO_new_file(buf[0], "w");
1523 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1524 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1527 i2a_ASN1_INTEGER(out, ai);
1528 BIO_puts(out, "\n");
1536 ERR_print_errors(bio_err);
1538 ASN1_INTEGER_free(ai);
1542 int rotate_serial(const char *serialfile, const char *new_suffix,
1543 const char *old_suffix)
1548 i = strlen(serialfile) + strlen(old_suffix);
1549 j = strlen(serialfile) + strlen(new_suffix);
1552 if (j + 1 >= BSIZE) {
1553 BIO_printf(bio_err, "File name too long\n");
1556 #ifndef OPENSSL_SYS_VMS
1557 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1558 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1560 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1561 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1563 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1569 "Unable to rename %s to %s\n", serialfile, buf[1]);
1573 if (rename(buf[0], serialfile) < 0) {
1575 "Unable to rename %s to %s\n", buf[0], serialfile);
1577 rename(buf[1], serialfile);
1582 ERR_print_errors(bio_err);
1586 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1591 btmp = b == NULL ? BN_new() : b;
1595 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1597 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1610 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1612 CA_DB *retdb = NULL;
1613 TXT_DB *tmpdb = NULL;
1615 CONF *dbattr_conf = NULL;
1617 #ifndef OPENSSL_NO_POSIX_IO
1622 in = BIO_new_file(dbfile, "r");
1626 #ifndef OPENSSL_NO_POSIX_IO
1627 BIO_get_fp(in, &dbfp);
1628 if (fstat(fileno(dbfp), &dbst) == -1) {
1629 ERR_raise_data(ERR_LIB_SYS, errno,
1630 "calling fstat(%s)", dbfile);
1635 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1638 #ifndef OPENSSL_SYS_VMS
1639 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1641 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1643 dbattr_conf = app_load_config_quiet(buf);
1645 retdb = app_malloc(sizeof(*retdb), "new DB");
1649 retdb->attributes = *db_attr;
1651 retdb->attributes.unique_subject = 1;
1655 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1657 retdb->attributes.unique_subject = parse_yesno(p, 1);
1661 retdb->dbfname = OPENSSL_strdup(dbfile);
1662 #ifndef OPENSSL_NO_POSIX_IO
1667 ERR_print_errors(bio_err);
1668 NCONF_free(dbattr_conf);
1675 * Returns > 0 on success, <= 0 on error
1677 int index_index(CA_DB *db)
1679 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1680 LHASH_HASH_FN(index_serial),
1681 LHASH_COMP_FN(index_serial))) {
1683 "Error creating serial number index:(%ld,%ld,%ld)\n",
1684 db->db->error, db->db->arg1, db->db->arg2);
1688 if (db->attributes.unique_subject
1689 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1690 LHASH_HASH_FN(index_name),
1691 LHASH_COMP_FN(index_name))) {
1692 BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1693 db->db->error, db->db->arg1, db->db->arg2);
1698 ERR_print_errors(bio_err);
1702 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1708 j = strlen(dbfile) + strlen(suffix);
1709 if (j + 6 >= BSIZE) {
1710 BIO_printf(bio_err, "File name too long\n");
1713 #ifndef OPENSSL_SYS_VMS
1714 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1715 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1716 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1718 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1719 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1720 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1722 out = BIO_new_file(buf[0], "w");
1725 BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1728 j = TXT_DB_write(out, db->db);
1733 out = BIO_new_file(buf[1], "w");
1736 BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1739 BIO_printf(out, "unique_subject = %s\n",
1740 db->attributes.unique_subject ? "yes" : "no");
1745 ERR_print_errors(bio_err);
1749 int rotate_index(const char *dbfile, const char *new_suffix,
1750 const char *old_suffix)
1755 i = strlen(dbfile) + strlen(old_suffix);
1756 j = strlen(dbfile) + strlen(new_suffix);
1759 if (j + 6 >= BSIZE) {
1760 BIO_printf(bio_err, "File name too long\n");
1763 #ifndef OPENSSL_SYS_VMS
1764 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1765 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1766 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1767 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1768 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1770 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1771 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1772 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1773 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1774 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1776 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1781 BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1785 if (rename(buf[0], dbfile) < 0) {
1786 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1788 rename(buf[1], dbfile);
1791 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1796 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1798 rename(dbfile, buf[0]);
1799 rename(buf[1], dbfile);
1802 if (rename(buf[2], buf[4]) < 0) {
1803 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1805 rename(buf[3], buf[4]);
1806 rename(dbfile, buf[0]);
1807 rename(buf[1], dbfile);
1812 ERR_print_errors(bio_err);
1816 void free_index(CA_DB *db)
1819 TXT_DB_free(db->db);
1820 OPENSSL_free(db->dbfname);
1825 int parse_yesno(const char *str, int def)
1829 case 'f': /* false */
1830 case 'F': /* FALSE */
1835 case 't': /* true */
1836 case 'T': /* TRUE */
1847 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1848 * where + can be used instead of / to form multi-valued RDNs if canmulti
1849 * and characters may be escaped by \
1851 X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
1854 int nextismulti = 0;
1860 "%s: %s name is expected to be in the format "
1861 "/type0=value0/type1=value1/type2=... where characters may "
1862 "be escaped by \\. This name is not in that format: '%s'\n",
1863 opt_getprog(), desc, --cp);
1867 n = X509_NAME_new();
1869 BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
1872 work = OPENSSL_strdup(cp);
1874 BIO_printf(bio_err, "%s: Error copying %s name input\n",
1875 opt_getprog(), desc);
1879 while (*cp != '\0') {
1882 unsigned char *valstr;
1884 int ismulti = nextismulti;
1887 /* Collect the type */
1888 while (*cp != '\0' && *cp != '=')
1893 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1894 opt_getprog(), typestr, desc);
1899 /* Collect the value. */
1900 valstr = (unsigned char *)bp;
1901 for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
1902 /* unescaped '+' symbol string signals further member of multiRDN */
1903 if (canmulti && *cp == '+') {
1907 if (*cp == '\\' && *++cp == '\0') {
1909 "%s: Escape character at end of %s name string\n",
1910 opt_getprog(), desc);
1916 /* If not at EOS (must be + or /), move forward. */
1921 nid = OBJ_txt2nid(typestr);
1922 if (nid == NID_undef) {
1924 "%s: Skipping unknown %s name attribute \"%s\"\n",
1925 opt_getprog(), desc, typestr);
1928 "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
1931 if (*valstr == '\0') {
1933 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1934 opt_getprog(), desc, typestr);
1937 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1938 valstr, strlen((char *)valstr),
1939 -1, ismulti ? -1 : 0)) {
1940 ERR_print_errors(bio_err);
1942 "%s: Error adding %s name attribute \"/%s=%s\"\n",
1943 opt_getprog(), desc, typestr, valstr);
1958 * Read whole contents of a BIO into an allocated memory buffer and return
1962 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1966 unsigned char tbuf[1024];
1968 mem = BIO_new(BIO_s_mem());
1972 if ((maxlen != -1) && maxlen < 1024)
1976 len = BIO_read(in, tbuf, len);
1983 if (BIO_write(mem, tbuf, len) != len) {
1992 ret = BIO_get_mem_data(mem, (char **)out);
1993 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1998 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
2001 char *stmp, *vtmp = NULL;
2003 stmp = OPENSSL_strdup(value);
2006 vtmp = strchr(stmp, ':');
2012 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
2019 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
2021 X509_POLICY_NODE *node;
2024 BIO_printf(bio_err, "%s Policies:", name);
2026 BIO_puts(bio_err, "\n");
2027 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
2028 node = sk_X509_POLICY_NODE_value(nodes, i);
2029 X509_POLICY_NODE_print(bio_err, node, 2);
2032 BIO_puts(bio_err, " <empty>\n");
2036 void policies_print(X509_STORE_CTX *ctx)
2038 X509_POLICY_TREE *tree;
2039 int explicit_policy;
2040 tree = X509_STORE_CTX_get0_policy_tree(ctx);
2041 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2043 BIO_printf(bio_err, "Require explicit Policy: %s\n",
2044 explicit_policy ? "True" : "False");
2046 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
2047 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
2051 * next_protos_parse parses a comma separated list of strings into a string
2052 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
2053 * outlen: (output) set to the length of the resulting buffer on success.
2054 * err: (maybe NULL) on failure, an error message line is written to this BIO.
2055 * in: a NUL terminated string like "abc,def,ghi"
2057 * returns: a malloc'd buffer or NULL on failure.
2059 unsigned char *next_protos_parse(size_t *outlen, const char *in)
2063 size_t i, start = 0;
2067 if (len == 0 || len >= 65535)
2070 out = app_malloc(len + 1, "NPN buffer");
2071 for (i = 0; i <= len; ++i) {
2072 if (i == len || in[i] == ',') {
2074 * Zero-length ALPN elements are invalid on the wire, we could be
2075 * strict and reject the entire string, but just ignoring extra
2076 * commas seems harmless and more friendly.
2078 * Every comma we skip in this way puts the input buffer another
2079 * byte ahead of the output buffer, so all stores into the output
2080 * buffer need to be decremented by the number commas skipped.
2087 if (i - start > 255) {
2091 out[start-skipped] = (unsigned char)(i - start);
2094 out[i + 1 - skipped] = in[i];
2098 if (len <= skipped) {
2103 *outlen = len + 1 - skipped;
2107 int check_cert_attributes(BIO *bio, X509 *x,
2108 const char *checkhost,
2109 const char *checkemail, const char *checkip, int print)
2119 if (checkhost != NULL) {
2120 valid_host = X509_check_host(x, checkhost, 0, 0, NULL);
2122 BIO_printf(bio, "Hostname %s does%s match certificate\n",
2123 checkhost, valid_host == 1 ? "" : " NOT");
2124 ret = ret && valid_host;
2127 if (checkemail != NULL) {
2128 valid_mail = X509_check_email(x, checkemail, 0, 0);
2130 BIO_printf(bio, "Email %s does%s match certificate\n",
2131 checkemail, valid_mail ? "" : " NOT");
2132 ret = ret && valid_mail;
2135 if (checkip != NULL) {
2136 valid_ip = X509_check_ip_asc(x, checkip, 0);
2138 BIO_printf(bio, "IP %s does%s match certificate\n",
2139 checkip, valid_ip ? "" : " NOT");
2140 ret = ret && valid_ip;
2146 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
2153 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2154 char *opt = sk_OPENSSL_STRING_value(opts, i);
2155 if (pkey_ctrl_string(pkctx, opt) <= 0) {
2156 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2157 ERR_print_errors(bio_err);
2165 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
2172 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2173 char *opt = sk_OPENSSL_STRING_value(opts, i);
2174 if (x509_ctrl_string(x, opt) <= 0) {
2175 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2176 ERR_print_errors(bio_err);
2184 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
2191 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2192 char *opt = sk_OPENSSL_STRING_value(opts, i);
2193 if (x509_req_ctrl_string(x, opt) <= 0) {
2194 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2195 ERR_print_errors(bio_err);
2203 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
2204 const char *md, STACK_OF(OPENSSL_STRING) *sigopts)
2206 EVP_PKEY_CTX *pkctx = NULL;
2212 * EVP_PKEY_get_default_digest_name() returns 2 if the digest is mandatory
2213 * for this algorithm.
2215 if (EVP_PKEY_get_default_digest_name(pkey, def_md, sizeof(def_md)) == 2
2216 && strcmp(def_md, "UNDEF") == 0) {
2217 /* The signing algorithm requires there to be no digest */
2221 return EVP_DigestSignInit_ex(ctx, &pkctx, md, app_get0_libctx(),
2222 app_get0_propq(), pkey, NULL)
2223 && do_pkey_ctx_init(pkctx, sigopts);
2226 static int adapt_keyid_ext(X509 *cert, X509V3_CTX *ext_ctx,
2227 const char *name, const char *value, int add_default)
2229 const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
2230 X509_EXTENSION *new_ext = X509V3_EXT_nconf(NULL, ext_ctx, name, value);
2233 if (new_ext == NULL)
2236 idx = X509v3_get_ext_by_OBJ(exts, X509_EXTENSION_get_object(new_ext), -1);
2238 X509_EXTENSION *found_ext = X509v3_get_ext(exts, idx);
2239 ASN1_OCTET_STRING *encoded = X509_EXTENSION_get_data(found_ext);
2240 int disabled = ASN1_STRING_length(encoded) <= 2; /* indicating "none" */
2243 X509_delete_ext(cert, idx);
2244 X509_EXTENSION_free(found_ext);
2245 } /* else keep existing key identifier, which might be outdated */
2248 rv = !add_default || X509_add_ext(cert, new_ext, -1);
2250 X509_EXTENSION_free(new_ext);
2254 int cert_matches_key(const X509 *cert, const EVP_PKEY *pkey)
2259 match = X509_check_private_key(cert, pkey);
2264 /* Ensure RFC 5280 compliance, adapt keyIDs as needed, and sign the cert info */
2265 int do_X509_sign(X509 *cert, EVP_PKEY *pkey, const char *md,
2266 STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx)
2268 const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
2269 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2273 if (sk_X509_EXTENSION_num(exts /* may be NULL */) > 0) {
2274 /* Prevent X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 */
2275 if (!X509_set_version(cert, X509_VERSION_3))
2279 * Add default SKID before AKID such that AKID can make use of it
2280 * in case the certificate is self-signed
2282 /* Prevent X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER */
2283 if (!adapt_keyid_ext(cert, ext_ctx, "subjectKeyIdentifier", "hash", 1))
2285 /* Prevent X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER */
2286 self_sign = cert_matches_key(cert, pkey);
2287 if (!adapt_keyid_ext(cert, ext_ctx, "authorityKeyIdentifier",
2288 "keyid, issuer", !self_sign))
2292 if (mctx != NULL && do_sign_init(mctx, pkey, md, sigopts) > 0)
2293 rv = (X509_sign_ctx(cert, mctx) > 0);
2295 EVP_MD_CTX_free(mctx);
2299 /* Sign the certificate request info */
2300 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md,
2301 STACK_OF(OPENSSL_STRING) *sigopts)
2304 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2306 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2307 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
2308 EVP_MD_CTX_free(mctx);
2312 /* Sign the CRL info */
2313 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md,
2314 STACK_OF(OPENSSL_STRING) *sigopts)
2317 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2319 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2320 rv = (X509_CRL_sign_ctx(x, mctx) > 0);
2321 EVP_MD_CTX_free(mctx);
2326 * do_X509_verify returns 1 if the signature is valid,
2327 * 0 if the signature check fails, or -1 if error occurs.
2329 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
2333 if (do_x509_init(x, vfyopts) > 0)
2334 rv = X509_verify(x, pkey);
2341 * do_X509_REQ_verify returns 1 if the signature is valid,
2342 * 0 if the signature check fails, or -1 if error occurs.
2344 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
2345 STACK_OF(OPENSSL_STRING) *vfyopts)
2349 if (do_x509_req_init(x, vfyopts) > 0)
2350 rv = X509_REQ_verify_ex(x, pkey,
2351 app_get0_libctx(), app_get0_propq());
2357 /* Get first http URL from a DIST_POINT structure */
2359 static const char *get_dp_url(DIST_POINT *dp)
2361 GENERAL_NAMES *gens;
2365 if (!dp->distpoint || dp->distpoint->type != 0)
2367 gens = dp->distpoint->name.fullname;
2368 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2369 gen = sk_GENERAL_NAME_value(gens, i);
2370 uri = GENERAL_NAME_get0_value(gen, >ype);
2371 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
2372 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
2374 if (IS_HTTP(uptr)) /* can/should not use HTTPS here */
2382 * Look through a CRLDP structure and attempt to find an http URL to
2383 * downloads a CRL from.
2386 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
2389 const char *urlptr = NULL;
2390 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2391 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
2392 urlptr = get_dp_url(dp);
2394 return load_crl(urlptr, FORMAT_UNDEF, 0, "CRL via CDP");
2400 * Example of downloading CRLs from CRLDP:
2401 * not usable for real world as it always downloads and doesn't cache anything.
2404 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
2405 const X509_NAME *nm)
2408 STACK_OF(X509_CRL) *crls = NULL;
2410 STACK_OF(DIST_POINT) *crldp;
2412 crls = sk_X509_CRL_new_null();
2415 x = X509_STORE_CTX_get_current_cert(ctx);
2416 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2417 crl = load_crl_crldp(crldp);
2418 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2420 sk_X509_CRL_free(crls);
2423 sk_X509_CRL_push(crls, crl);
2424 /* Try to download delta CRL */
2425 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2426 crl = load_crl_crldp(crldp);
2427 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2429 sk_X509_CRL_push(crls, crl);
2433 void store_setup_crl_download(X509_STORE *st)
2435 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2438 #ifndef OPENSSL_NO_SOCK
2439 static const char *tls_error_hint(void)
2441 unsigned long err = ERR_peek_error();
2443 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2444 err = ERR_peek_last_error();
2445 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2448 switch (ERR_GET_REASON(err)) {
2449 case SSL_R_WRONG_VERSION_NUMBER:
2450 return "The server does not support (a suitable version of) TLS";
2451 case SSL_R_UNKNOWN_PROTOCOL:
2452 return "The server does not support HTTPS";
2453 case SSL_R_CERTIFICATE_VERIFY_FAILED:
2454 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2455 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
2456 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2457 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
2458 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2459 default: /* no error or no hint available for error */
2464 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
2465 BIO *app_http_tls_cb(BIO *hbio, void *arg, int connect, int detail)
2467 if (connect && detail) { /* connecting with TLS */
2468 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
2469 SSL_CTX *ssl_ctx = info->ssl_ctx;
2473 if ((info->use_proxy
2474 && !OSSL_HTTP_proxy_connect(hbio, info->server, info->port,
2475 NULL, NULL, /* no proxy credentials */
2476 info->timeout, bio_err, opt_getprog()))
2477 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
2480 if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
2485 SSL_set_tlsext_host_name(ssl, info->server);
2487 SSL_set_connect_state(ssl);
2488 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2490 hbio = BIO_push(sbio, hbio);
2491 } else if (!connect && !detail) { /* disconnecting after error */
2492 const char *hint = tls_error_hint();
2495 ERR_add_error_data(2, " : ", hint);
2497 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2498 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2504 void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info)
2507 SSL_CTX_free(info->ssl_ctx);
2512 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2513 const char *no_proxy, SSL_CTX *ssl_ctx,
2514 const STACK_OF(CONF_VALUE) *headers,
2515 long timeout, const char *expected_content_type,
2516 const ASN1_ITEM *it)
2518 APP_HTTP_TLS_INFO info;
2523 ASN1_VALUE *resp = NULL;
2525 if (url == NULL || it == NULL) {
2526 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
2530 if (!OSSL_HTTP_parse_url(url, &use_ssl, NULL /* userinfo */, &server, &port,
2531 NULL /* port_num, */, NULL, NULL, NULL))
2533 if (use_ssl && ssl_ctx == NULL) {
2534 ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER,
2539 info.server = server;
2541 info.use_proxy = proxy != NULL;
2542 info.timeout = timeout;
2543 info.ssl_ctx = ssl_ctx;
2544 mem = OSSL_HTTP_get(url, proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2545 app_http_tls_cb, &info, 0 /* buf_size */, headers,
2546 expected_content_type, 1 /* expect_asn1 */,
2547 OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout);
2548 resp = ASN1_item_d2i_bio(it, mem, NULL);
2552 OPENSSL_free(server);
2558 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2559 const char *path, const char *proxy,
2560 const char *no_proxy, SSL_CTX *ssl_ctx,
2561 const STACK_OF(CONF_VALUE) *headers,
2562 const char *content_type,
2563 ASN1_VALUE *req, const ASN1_ITEM *req_it,
2564 const char *expected_content_type,
2565 long timeout, const ASN1_ITEM *rsp_it)
2567 APP_HTTP_TLS_INFO info;
2568 BIO *rsp, *req_mem = ASN1_item_i2d_mem_bio(req_it, req);
2571 if (req_mem == NULL)
2575 info.use_proxy = proxy != NULL;
2576 info.timeout = timeout;
2577 info.ssl_ctx = ssl_ctx;
2578 rsp = OSSL_HTTP_transfer(NULL, host, port, path, ssl_ctx != NULL,
2579 proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2580 app_http_tls_cb, &info,
2581 0 /* buf_size */, headers, content_type, req_mem,
2582 expected_content_type, 1 /* expect_asn1 */,
2583 OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout,
2584 0 /* keep_alive */);
2586 res = ASN1_item_d2i_bio(rsp_it, rsp, NULL);
2594 * Platform-specific sections
2599 # define fileno(a) (int)_fileno(a)
2602 # include <windows.h>
2605 static int WIN32_rename(const char *from, const char *to)
2607 TCHAR *tfrom = NULL, *tto;
2611 if (sizeof(TCHAR) == 1) {
2612 tfrom = (TCHAR *)from;
2614 } else { /* UNICODE path */
2616 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2617 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2621 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2622 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2624 for (i = 0; i < flen; i++)
2625 tfrom[i] = (TCHAR)from[i];
2626 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2627 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2629 for (i = 0; i < tlen; i++)
2630 tto[i] = (TCHAR)to[i];
2633 if (MoveFile(tfrom, tto))
2635 err = GetLastError();
2636 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2637 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2639 err = GetLastError();
2641 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2643 else if (err == ERROR_ACCESS_DENIED)
2646 errno = EINVAL; /* we could map more codes... */
2650 if (tfrom != NULL && tfrom != (TCHAR *)from)
2656 /* app_tminterval section */
2658 double app_tminterval(int stop, int usertime)
2662 static ULARGE_INTEGER tmstart;
2663 static int warning = 1;
2664 # ifdef _WIN32_WINNT
2665 static HANDLE proc = NULL;
2669 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2670 GetCurrentProcessId());
2672 proc = (HANDLE) - 1;
2675 if (usertime && proc != (HANDLE) - 1) {
2677 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2683 if (usertime && warning) {
2684 BIO_printf(bio_err, "To get meaningful results, run "
2685 "this program on idle system.\n");
2688 GetSystemTime(&systime);
2689 SystemTimeToFileTime(&systime, &now);
2692 if (stop == TM_START) {
2693 tmstart.u.LowPart = now.dwLowDateTime;
2694 tmstart.u.HighPart = now.dwHighDateTime;
2696 ULARGE_INTEGER tmstop;
2698 tmstop.u.LowPart = now.dwLowDateTime;
2699 tmstop.u.HighPart = now.dwHighDateTime;
2701 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2706 #elif defined(OPENSSL_SYS_VXWORKS)
2709 double app_tminterval(int stop, int usertime)
2712 # ifdef CLOCK_REALTIME
2713 static struct timespec tmstart;
2714 struct timespec now;
2716 static unsigned long tmstart;
2719 static int warning = 1;
2721 if (usertime && warning) {
2722 BIO_printf(bio_err, "To get meaningful results, run "
2723 "this program on idle system.\n");
2726 # ifdef CLOCK_REALTIME
2727 clock_gettime(CLOCK_REALTIME, &now);
2728 if (stop == TM_START)
2731 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2732 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2735 if (stop == TM_START)
2738 ret = (now - tmstart) / (double)sysClkRateGet();
2743 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2744 # include <sys/times.h>
2746 double app_tminterval(int stop, int usertime)
2750 clock_t now = times(&rus);
2751 static clock_t tmstart;
2754 now = rus.tms_utime;
2756 if (stop == TM_START) {
2759 long int tck = sysconf(_SC_CLK_TCK);
2760 ret = (now - tmstart) / (double)tck;
2767 # include <sys/time.h>
2768 # include <sys/resource.h>
2770 double app_tminterval(int stop, int usertime)
2775 static struct timeval tmstart;
2778 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2780 gettimeofday(&now, NULL);
2782 if (stop == TM_START)
2785 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2786 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2792 int app_access(const char* name, int flag)
2795 return _access(name, flag);
2797 return access(name, flag);
2801 int app_isdir(const char *name)
2803 return opt_isdir(name);
2806 /* raw_read|write section */
2808 # include "vms_term_sock.h"
2809 static int stdin_sock = -1;
2811 static void close_stdin_sock(void)
2813 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2816 int fileno_stdin(void)
2818 if (stdin_sock == -1) {
2819 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2820 atexit(close_stdin_sock);
2826 int fileno_stdin(void)
2828 return fileno(stdin);
2832 int fileno_stdout(void)
2834 return fileno(stdout);
2837 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2838 int raw_read_stdin(void *buf, int siz)
2841 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2846 #elif defined(__VMS)
2847 # include <sys/socket.h>
2849 int raw_read_stdin(void *buf, int siz)
2851 return recv(fileno_stdin(), buf, siz, 0);
2854 # if defined(__TANDEM)
2855 # if defined(OPENSSL_TANDEM_FLOSS)
2856 # include <floss.h(floss_read)>
2859 int raw_read_stdin(void *buf, int siz)
2861 return read(fileno_stdin(), buf, siz);
2865 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2866 int raw_write_stdout(const void *buf, int siz)
2869 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2874 #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
2875 # if defined(__TANDEM)
2876 # if defined(OPENSSL_TANDEM_FLOSS)
2877 # include <floss.h(floss_write)>
2880 int raw_write_stdout(const void *buf, int siz)
2882 return write(fileno(stdout), (void*)buf, siz);
2885 # if defined(__TANDEM)
2886 # if defined(OPENSSL_TANDEM_FLOSS)
2887 # include <floss.h(floss_write)>
2890 int raw_write_stdout(const void *buf, int siz)
2892 return write(fileno_stdout(), buf, siz);
2897 * Centralized handling of input and output files with format specification
2898 * The format is meant to show what the input and output is supposed to be,
2899 * and is therefore a show of intent more than anything else. However, it
2900 * does impact behavior on some platforms, such as differentiating between
2901 * text and binary input/output on non-Unix platforms
2903 BIO *dup_bio_in(int format)
2905 return BIO_new_fp(stdin,
2906 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2909 BIO *dup_bio_out(int format)
2911 BIO *b = BIO_new_fp(stdout,
2912 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2913 void *prefix = NULL;
2915 #ifdef OPENSSL_SYS_VMS
2916 if (FMT_istext(format))
2917 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2920 if (FMT_istext(format)
2921 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2922 b = BIO_push(BIO_new(BIO_f_prefix()), b);
2923 BIO_set_prefix(b, prefix);
2929 BIO *dup_bio_err(int format)
2931 BIO *b = BIO_new_fp(stderr,
2932 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2933 #ifdef OPENSSL_SYS_VMS
2934 if (FMT_istext(format))
2935 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2940 void unbuffer(FILE *fp)
2943 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2944 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2945 * However, we trust that the C RTL will never give us a FILE pointer
2946 * above the first 4 GB of memory, so we simply turn off the warning
2949 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2950 # pragma environment save
2951 # pragma message disable maylosedata2
2954 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2955 # pragma environment restore
2959 static const char *modestr(char mode, int format)
2961 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2965 return FMT_istext(format) ? "a" : "ab";
2967 return FMT_istext(format) ? "r" : "rb";
2969 return FMT_istext(format) ? "w" : "wb";
2971 /* The assert above should make sure we never reach this point */
2975 static const char *modeverb(char mode)
2985 return "(doing something)";
2989 * Open a file for writing, owner-read-only.
2991 BIO *bio_open_owner(const char *filename, int format, int private)
2995 int textmode, bflags;
2996 #ifndef OPENSSL_NO_POSIX_IO
3000 if (!private || filename == NULL || strcmp(filename, "-") == 0)
3001 return bio_open_default(filename, 'w', format);
3003 textmode = FMT_istext(format);
3004 #ifndef OPENSSL_NO_POSIX_IO
3015 # elif defined(_O_BINARY)
3020 # ifdef OPENSSL_SYS_VMS
3021 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
3022 * it still needs to know that we're going binary, or fdopen()
3023 * will fail with "invalid argument"... so we tell VMS what the
3027 fd = open(filename, mode, 0600, "ctx=bin");
3030 fd = open(filename, mode, 0600);
3033 fp = fdopen(fd, modestr('w', format));
3034 #else /* OPENSSL_NO_POSIX_IO */
3035 /* Have stdio but not Posix IO, do the best we can */
3036 fp = fopen(filename, modestr('w', format));
3037 #endif /* OPENSSL_NO_POSIX_IO */
3042 bflags |= BIO_FP_TEXT;
3043 b = BIO_new_fp(fp, bflags);
3048 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
3049 opt_getprog(), filename, strerror(errno));
3050 ERR_print_errors(bio_err);
3051 /* If we have fp, then fdopen took over fd, so don't close both. */
3054 #ifndef OPENSSL_NO_POSIX_IO
3061 static BIO *bio_open_default_(const char *filename, char mode, int format,
3066 if (filename == NULL || strcmp(filename, "-") == 0) {
3067 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
3075 "Can't open %s, %s\n",
3076 mode == 'r' ? "stdin" : "stdout", strerror(errno));
3078 ret = BIO_new_file(filename, modestr(mode, format));
3086 "Can't open \"%s\" for %s, %s\n",
3087 filename, modeverb(mode), strerror(errno));
3089 ERR_print_errors(bio_err);
3093 BIO *bio_open_default(const char *filename, char mode, int format)
3095 return bio_open_default_(filename, mode, format, 0);
3098 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
3100 return bio_open_default_(filename, mode, format, 1);
3103 void wait_for_async(SSL *s)
3105 /* On Windows select only works for sockets, so we simply don't wait */
3106 #ifndef OPENSSL_SYS_WINDOWS
3113 if (!SSL_get_all_async_fds(s, NULL, &numfds))
3117 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
3118 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
3124 for (i = 0; i < numfds; i++) {
3125 if (width <= (int)fds[i])
3126 width = (int)fds[i] + 1;
3127 openssl_fdset((int)fds[i], &asyncfds);
3129 select(width, (void *)&asyncfds, NULL, NULL, NULL);
3134 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
3135 #if defined(OPENSSL_SYS_MSDOS)
3136 int has_stdin_waiting(void)
3138 # if defined(OPENSSL_SYS_WINDOWS)
3139 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
3141 INPUT_RECORD inputrec;
3145 if (inhand == INVALID_HANDLE_VALUE) {
3149 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
3151 /* Probably redirected input? _kbhit() does not work in this case */
3162 /* Corrupt a signature by modifying final byte */
3163 void corrupt_signature(const ASN1_STRING *signature)
3165 unsigned char *s = signature->data;
3166 s[signature->length - 1] ^= 0x1;
3169 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
3172 if (startdate == NULL || strcmp(startdate, "today") == 0) {
3173 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
3176 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
3179 if (enddate == NULL) {
3180 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
3183 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
3189 int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate)
3192 ASN1_TIME *tm = ASN1_TIME_new();
3197 if (lastupdate == NULL) {
3198 if (X509_gmtime_adj(tm, 0) == NULL)
3201 if (!ASN1_TIME_set_string_X509(tm, lastupdate))
3205 if (!X509_CRL_set1_lastUpdate(crl, tm))
3214 int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
3215 long days, long hours, long secs)
3218 ASN1_TIME *tm = ASN1_TIME_new();
3223 if (nextupdate == NULL) {
3224 if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL)
3227 if (!ASN1_TIME_set_string_X509(tm, nextupdate))
3231 if (!X509_CRL_set1_nextUpdate(crl, tm))
3240 void make_uppercase(char *string)
3244 for (i = 0; string[i] != '\0'; i++)
3245 string[i] = toupper((unsigned char)string[i]);
3248 /* This function is defined here due to visibility of bio_err */
3249 int opt_printf_stderr(const char *fmt, ...)
3255 ret = BIO_vprintf(bio_err, fmt, ap);
3260 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
3261 const OSSL_PARAM *paramdefs)
3263 OSSL_PARAM *params = NULL;
3264 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
3266 char *opt = "", *stmp, *vtmp = NULL;
3272 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
3276 for (params_n = 0; params_n < sz; params_n++) {
3277 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
3278 if ((stmp = OPENSSL_strdup(opt)) == NULL
3279 || (vtmp = strchr(stmp, ':')) == NULL)
3281 /* Replace ':' with 0 to terminate the string pointed to by stmp */
3283 /* Skip over the separator so that vmtp points to the value */
3285 if (!OSSL_PARAM_allocate_from_text(¶ms[params_n], paramdefs,
3286 stmp, vtmp, strlen(vtmp), &found))
3290 params[params_n] = OSSL_PARAM_construct_end();
3294 BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
3296 ERR_print_errors(bio_err);
3297 app_params_free(params);
3301 void app_params_free(OSSL_PARAM *params)
3305 if (params != NULL) {
3306 for (i = 0; params[i].key != NULL; ++i)
3307 OPENSSL_free(params[i].data);
3308 OPENSSL_free(params);
3312 EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose)
3314 EVP_PKEY *res = NULL;
3316 if (verbose && alg != NULL) {
3317 BIO_printf(bio_err, "Generating %s key", alg);
3319 BIO_printf(bio_err, " with %d bits\n", bits);
3321 BIO_printf(bio_err, "\n");
3324 BIO_printf(bio_err, "Warning: generating random key material may take a long time\n"
3325 "if the system has a poor entropy source\n");
3326 if (EVP_PKEY_keygen(ctx, &res) <= 0)
3327 app_bail_out("%s: Error generating %s key\n", opt_getprog(),
3328 alg != NULL ? alg : "asymmetric");
3332 EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg)
3334 EVP_PKEY *res = NULL;
3337 BIO_printf(bio_err, "Warning: generating random key parameters may take a long time\n"
3338 "if the system has a poor entropy source\n");
3339 if (EVP_PKEY_paramgen(ctx, &res) <= 0)
3340 app_bail_out("%s: Generating %s key parameters failed\n",
3341 opt_getprog(), alg != NULL ? alg : "asymmetric");
3346 * Return non-zero if the legacy path is still an option.
3347 * This decision is based on the global command line operations and the
3348 * behaviour thus far.
3350 int opt_legacy_okay(void)
3352 int provider_options = opt_provider_option_given();
3353 int libctx = app_get0_libctx() != NULL || app_get0_propq() != NULL;
3354 #ifndef OPENSSL_NO_ENGINE
3355 ENGINE *e = ENGINE_get_first();
3363 * Having a provider option specified or a custom library context or
3364 * property query, is a sure sign we're not using legacy.
3366 if (provider_options || libctx)