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
21 #include <sys/types.h>
22 #ifndef OPENSSL_NO_POSIX_IO
23 # include <sys/stat.h>
28 #include <openssl/err.h>
29 #include <openssl/x509.h>
30 #include <openssl/x509v3.h>
31 #include <openssl/http.h>
32 #include <openssl/pem.h>
33 #include <openssl/store.h>
34 #include <openssl/pkcs12.h>
35 #include <openssl/ui.h>
36 #include <openssl/safestack.h>
37 #include <openssl/rsa.h>
38 #include <openssl/bn.h>
39 #include <openssl/ssl.h>
40 #include <openssl/store.h>
41 #include <openssl/core_names.h>
46 static int WIN32_rename(const char *from, const char *to);
47 # define rename(from,to) WIN32_rename((from),(to))
50 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
54 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) || defined(__BORLANDC__)
58 static BIO *bio_open_default_(const char *filename, char mode, int format,
61 #define PASS_SOURCE_SIZE_MAX 4
71 static OSSL_LIB_CTX *app_libctx = NULL;
73 static int set_table_opts(unsigned long *flags, const char *arg,
74 const NAME_EX_TBL * in_tbl);
75 static int set_multi_opts(unsigned long *flags, const char *arg,
76 const NAME_EX_TBL * in_tbl);
78 int app_init(long mesgwin);
80 int chopup_args(ARGS *arg, char *buf)
83 char c = '\0', *p = NULL;
88 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
92 /* Skip whitespace. */
93 while (*p && isspace(_UC(*p)))
98 /* The start of something good :-) */
99 if (arg->argc >= arg->size) {
102 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
107 quoted = *p == '\'' || *p == '"';
110 arg->argv[arg->argc++] = p;
112 /* now look for the end of this */
114 while (*p && *p != c)
118 while (*p && !isspace(_UC(*p)))
124 arg->argv[arg->argc] = NULL;
129 int app_init(long mesgwin)
135 int ctx_set_verify_locations(SSL_CTX *ctx,
136 const char *CAfile, int noCAfile,
137 const char *CApath, int noCApath,
138 const char *CAstore, int noCAstore)
140 if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
141 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
143 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
145 if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
151 if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
153 if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
155 if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
160 #ifndef OPENSSL_NO_CT
162 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
165 return SSL_CTX_set_default_ctlog_list_file(ctx);
167 return SSL_CTX_set_ctlog_list_file(ctx, path);
172 static unsigned long nmflag = 0;
173 static char nmflag_set = 0;
175 int set_nameopt(const char *arg)
177 int ret = set_name_ex(&nmflag, arg);
185 unsigned long get_nameopt(void)
187 return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
190 int dump_cert_text(BIO *out, X509 *x)
192 print_name(out, "subject=", X509_get_subject_name(x));
194 print_name(out, "issuer=", X509_get_issuer_name(x));
200 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
202 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);
221 BIO_printf(bio_err, "Out of memory getting password for %s\n", desc);
226 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
228 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
231 *pass1 = app_get_pass(arg1, same);
234 } else if (pass1 != NULL) {
238 *pass2 = app_get_pass(arg2, same ? 2 : 0);
241 } else if (pass2 != NULL) {
247 static char *app_get_pass(const char *arg, int keepbio)
249 static BIO *pwdbio = NULL;
250 char *tmp, tpass[APP_PASS_LEN];
253 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
254 if (strncmp(arg, "pass:", 5) == 0)
255 return OPENSSL_strdup(arg + 5);
256 if (strncmp(arg, "env:", 4) == 0) {
257 tmp = getenv(arg + 4);
259 BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
262 return OPENSSL_strdup(tmp);
264 if (!keepbio || pwdbio == NULL) {
265 if (strncmp(arg, "file:", 5) == 0) {
266 pwdbio = BIO_new_file(arg + 5, "r");
267 if (pwdbio == NULL) {
268 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
273 * Under _WIN32, which covers even Win64 and CE, file
274 * descriptors referenced by BIO_s_fd are not inherited
275 * by child process and therefore below is not an option.
276 * It could have been an option if bss_fd.c was operating
277 * on real Windows descriptors, such as those obtained
280 } else if (strncmp(arg, "fd:", 3) == 0) {
284 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
285 if ((i < 0) || !pwdbio) {
286 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
290 * Can't do BIO_gets on an fd BIO so add a buffering BIO
292 btmp = BIO_new(BIO_f_buffer());
293 pwdbio = BIO_push(btmp, pwdbio);
295 } else if (strcmp(arg, "stdin") == 0) {
296 pwdbio = dup_bio_in(FORMAT_TEXT);
297 if (pwdbio == NULL) {
298 BIO_printf(bio_err, "Can't open BIO for stdin\n");
302 /* argument syntax error; do not reveal too much about arg */
303 tmp = strchr(arg, ':');
304 if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
306 "Invalid password argument, missing ':' within the first %d chars\n",
307 PASS_SOURCE_SIZE_MAX + 1);
310 "Invalid password argument, starting with \"%.*s\"\n",
311 (int)(tmp - arg + 1), arg);
315 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
317 BIO_free_all(pwdbio);
321 BIO_printf(bio_err, "Error reading password from BIO\n");
324 tmp = strchr(tpass, '\n');
327 return OPENSSL_strdup(tpass);
330 OSSL_LIB_CTX *app_get0_libctx(void)
335 static const char *app_propq = NULL;
337 int app_set_propq(const char *arg)
343 const char *app_get0_propq(void)
348 OSSL_LIB_CTX *app_create_libctx(void)
351 * Load the NULL provider into the default library context and create a
352 * library context which will then be used for any OPT_PROV options.
354 if (app_libctx == NULL) {
356 if (!app_provider_load(NULL, "null")) {
357 BIO_puts(bio_err, "Failed to create null provider\n");
360 app_libctx = OSSL_LIB_CTX_new();
362 if (app_libctx == NULL)
363 BIO_puts(bio_err, "Failed to create library context\n");
367 CONF *app_load_config_bio(BIO *in, const char *filename)
373 conf = NCONF_new_ex(app_libctx, NULL);
374 i = NCONF_load_bio(conf, in, &errorline);
378 if (errorline <= 0) {
379 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
381 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
384 if (filename != NULL)
385 BIO_printf(bio_err, "config file \"%s\"\n", filename);
387 BIO_printf(bio_err, "config input");
393 CONF *app_load_config_verbose(const char *filename, int verbose)
396 if (*filename == '\0')
397 BIO_printf(bio_err, "No configuration used\n");
399 BIO_printf(bio_err, "Using configuration from %s\n", filename);
401 return app_load_config_internal(filename, 0);
404 CONF *app_load_config_internal(const char *filename, int quiet)
406 BIO *in = NULL; /* leads to empty config in case filename == "" */
409 if (*filename != '\0'
410 && (in = bio_open_default_(filename, 'r', FORMAT_TEXT, quiet)) == NULL)
412 conf = app_load_config_bio(in, filename);
417 int app_load_modules(const CONF *config)
419 CONF *to_free = NULL;
422 config = to_free = app_load_config_quiet(default_config_file);
426 if (CONF_modules_load(config, NULL, 0) <= 0) {
427 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
428 ERR_print_errors(bio_err);
436 int add_oid_section(CONF *conf)
439 STACK_OF(CONF_VALUE) *sktmp;
443 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
447 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
448 BIO_printf(bio_err, "problem loading oid section %s\n", p);
451 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
452 cnf = sk_CONF_VALUE_value(sktmp, i);
453 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
454 BIO_printf(bio_err, "problem creating object %s=%s\n",
455 cnf->name, cnf->value);
462 CONF *app_load_config_modules(const char *configfile)
466 if (configfile != NULL) {
467 if ((conf = app_load_config_verbose(configfile, 1)) == NULL)
469 if (configfile != default_config_file && !app_load_modules(conf)) {
477 #define IS_HTTP(uri) ((uri) != NULL \
478 && strncmp(uri, OSSL_HTTP_PREFIX, strlen(OSSL_HTTP_PREFIX)) == 0)
479 #define IS_HTTPS(uri) ((uri) != NULL \
480 && strncmp(uri, OSSL_HTTPS_PREFIX, strlen(OSSL_HTTPS_PREFIX)) == 0)
482 X509 *load_cert_pass(const char *uri, int format, int maybe_stdin,
483 const char *pass, const char *desc)
488 desc = "certificate";
490 BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
491 else if (IS_HTTP(uri))
492 cert = X509_load_http(uri, NULL, NULL, 0 /* timeout */);
494 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc,
495 NULL, NULL, NULL, &cert, NULL, NULL, NULL);
497 BIO_printf(bio_err, "Unable to load %s\n", desc);
498 ERR_print_errors(bio_err);
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 (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc,
516 NULL, NULL, NULL, NULL, NULL, &crl, NULL);
518 BIO_printf(bio_err, "Unable to load %s\n", desc);
519 ERR_print_errors(bio_err);
524 X509_REQ *load_csr(const char *file, int format, const char *desc)
526 X509_REQ *req = NULL;
529 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 BIO_printf(bio_err, "Unable to load %s\n", desc);
547 ERR_print_errors(bio_err);
553 void cleanse(char *str)
556 OPENSSL_cleanse(str, strlen(str));
559 void clear_free(char *str)
562 OPENSSL_clear_free(str, strlen(str));
565 EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
566 const char *pass, ENGINE *e, const char *desc)
568 EVP_PKEY *pkey = NULL;
569 char *allocated_uri = NULL;
572 desc = "private key";
574 if (format == FORMAT_ENGINE) {
575 uri = allocated_uri = make_engine_uri(e, uri, desc);
577 (void)load_key_certs_crls(uri, format, may_stdin, pass, desc,
578 &pkey, NULL, NULL, NULL, NULL, NULL, NULL);
580 OPENSSL_free(allocated_uri);
584 EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
585 const char *pass, ENGINE *e, const char *desc)
587 EVP_PKEY *pkey = NULL;
588 char *allocated_uri = NULL;
593 if (format == FORMAT_ENGINE) {
594 uri = allocated_uri = make_engine_uri(e, uri, desc);
596 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc,
597 NULL, &pkey, NULL, NULL, NULL, NULL, NULL);
599 OPENSSL_free(allocated_uri);
603 EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin,
604 const char *keytype, const char *desc)
606 EVP_PKEY *params = NULL;
609 desc = "key parameters";
611 (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc,
612 NULL, NULL, ¶ms, NULL, NULL, NULL, NULL);
613 if (params != NULL && keytype != NULL && !EVP_PKEY_is_a(params, keytype)) {
615 "Unable to load %s from %s (unexpected parameters type)\n",
617 ERR_print_errors(bio_err);
618 EVP_PKEY_free(params);
624 void app_bail_out(char *fmt, ...)
629 BIO_vprintf(bio_err, fmt, args);
631 ERR_print_errors(bio_err);
635 void *app_malloc(size_t sz, const char *what)
637 void *vp = OPENSSL_malloc(sz);
640 app_bail_out("%s: Could not allocate %zu bytes for %s\n",
641 opt_getprog(), sz, what);
645 char *next_item(char *opt) /* in list separated by comma and/or space */
647 /* advance to separator (comma or whitespace), if any */
648 while (*opt != ',' && !isspace(*opt) && *opt != '\0')
651 /* terminate current item */
653 /* skip over any whitespace after separator */
654 while (isspace(*opt))
657 return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */
660 static void warn_cert_msg(const char *uri, X509 *cert, const char *msg)
662 char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
664 BIO_printf(bio_err, "Warning: certificate from '%s' with subject '%s' %s\n",
669 static void warn_cert(const char *uri, X509 *cert, int warn_EE,
670 X509_VERIFY_PARAM *vpm)
672 uint32_t ex_flags = X509_get_extension_flags(cert);
673 int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
674 X509_get0_notAfter(cert));
677 warn_cert_msg(uri, cert, res > 0 ? "has expired" : "not yet valid");
678 if (warn_EE && (ex_flags & EXFLAG_V1) == 0 && (ex_flags & EXFLAG_CA) == 0)
679 warn_cert_msg(uri, cert, "is not a CA cert");
682 static void warn_certs(const char *uri, STACK_OF(X509) *certs, int warn_EE,
683 X509_VERIFY_PARAM *vpm)
687 for (i = 0; i < sk_X509_num(certs); i++)
688 warn_cert(uri, sk_X509_value(certs, i), warn_EE, vpm);
691 int load_cert_certs(const char *uri,
692 X509 **pcert, STACK_OF(X509) **pcerts,
693 int exclude_http, const char *pass, const char *desc,
694 X509_VERIFY_PARAM *vpm)
699 if (exclude_http && (strncasecmp(uri, "http://", 7) == 0
700 || strncasecmp(uri, "https://", 8) == 0)) {
701 BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc);
704 pass_string = get_passwd(pass, desc);
705 ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass_string, desc,
707 pcert, pcerts, NULL, NULL);
708 clear_free(pass_string);
712 warn_cert(uri, *pcert, 0, vpm);
713 warn_certs(uri, *pcerts, 1, vpm);
715 sk_X509_pop_free(*pcerts, X509_free);
721 STACK_OF(X509) *load_certs_multifile(char *files, const char *pass,
722 const char *desc, X509_VERIFY_PARAM *vpm)
724 STACK_OF(X509) *certs = NULL;
725 STACK_OF(X509) *result = sk_X509_new_null();
732 while (files != NULL) {
733 char *next = next_item(files);
735 if (!load_cert_certs(files, NULL, &certs, 0, pass, desc, vpm))
737 if (!X509_add_certs(result, certs,
738 X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
740 sk_X509_pop_free(certs, X509_free);
747 BIO_printf(bio_err, "out of memory\n");
749 sk_X509_pop_free(certs, X509_free);
750 sk_X509_pop_free(result, X509_free);
754 static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */,
755 const STACK_OF(X509) *certs /* may NULL */)
760 store = X509_STORE_new();
763 for (i = 0; i < sk_X509_num(certs); i++) {
764 if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) {
765 X509_STORE_free(store);
773 * Create cert store structure with certificates read from given file(s).
774 * Returns pointer to created X509_STORE on success, NULL on error.
776 X509_STORE *load_certstore(char *input, const char *pass, const char *desc,
777 X509_VERIFY_PARAM *vpm)
779 X509_STORE *store = NULL;
780 STACK_OF(X509) *certs = NULL;
782 while (input != NULL) {
783 char *next = next_item(input);
786 if (!load_cert_certs(input, NULL, &certs, 1, pass, desc, vpm)) {
787 X509_STORE_free(store);
790 ok = (store = sk_X509_to_store(store, certs)) != NULL;
791 sk_X509_pop_free(certs, X509_free);
801 * Initialize or extend, if *certs != NULL, a certificate stack.
802 * The caller is responsible for freeing *certs if its value is left not NULL.
804 int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs,
805 const char *pass, const char *desc)
807 int was_NULL = *certs == NULL;
808 int ret = load_key_certs_crls(uri, FORMAT_UNDEF, maybe_stdin,
809 pass, desc, NULL, NULL,
810 NULL, NULL, certs, NULL, NULL);
812 if (!ret && was_NULL) {
813 sk_X509_pop_free(*certs, X509_free);
820 * Initialize or extend, if *crls != NULL, a certificate stack.
821 * The caller is responsible for freeing *crls if its value is left not NULL.
823 int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
824 const char *pass, const char *desc)
826 int was_NULL = *crls == NULL;
827 int ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass, desc,
829 NULL, NULL, NULL, crls);
831 if (!ret && was_NULL) {
832 sk_X509_CRL_pop_free(*crls, X509_CRL_free);
838 static const char *format2string(int format)
849 /* Set type expectation, but clear it if objects of different types expected. */
850 #define SET_EXPECT(expect, val) ((expect) = (expect) < 0 ? (val) : ((expect) == (val) ? (val) : 0))
852 * Load those types of credentials for which the result pointer is not NULL.
853 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
854 * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
855 * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
856 * If pcerts is non-NULL then all available certificates are appended to *pcerts
857 * except any certificate assigned to *pcert.
858 * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
859 * If pcrls is non-NULL then all available CRLs are appended to *pcerts
860 * except any CRL assigned to *pcrl.
861 * In any case (also on error) the caller is responsible for freeing all members
862 * of *pcerts and *pcrls (as far as they are not NULL).
864 int load_key_certs_crls(const char *uri, int format, int maybe_stdin,
865 const char *pass, const char *desc,
866 EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
868 X509 **pcert, STACK_OF(X509) **pcerts,
869 X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
872 OSSL_STORE_CTX *ctx = NULL;
873 OSSL_LIB_CTX *libctx = app_get0_libctx();
874 const char *propq = app_get0_propq();
878 ppkey != NULL ? "key" : ppubkey != NULL ? "public key" :
879 pparams != NULL ? "params" : pcert != NULL ? "cert" :
880 pcrl != NULL ? "CRL" : pcerts != NULL ? "certs" :
881 pcrls != NULL ? "CRLs" : NULL;
882 int cnt_expectations = 0;
884 const char *input_type;
886 const OSSL_PARAM *params = NULL;
887 /* TODO make use of the engine reference 'eng' when loading pkeys */
892 SET_EXPECT(expect, OSSL_STORE_INFO_PKEY);
894 if (ppubkey != NULL) {
897 SET_EXPECT(expect, OSSL_STORE_INFO_PUBKEY);
899 if (pparams != NULL) {
902 SET_EXPECT(expect, OSSL_STORE_INFO_PARAMS);
907 SET_EXPECT(expect, OSSL_STORE_INFO_CERT);
909 if (pcerts != NULL) {
910 if (*pcerts == NULL && (*pcerts = sk_X509_new_null()) == NULL) {
911 BIO_printf(bio_err, "Out of memory loading");
915 SET_EXPECT(expect, OSSL_STORE_INFO_CERT);
920 SET_EXPECT(expect, OSSL_STORE_INFO_CRL);
923 if (*pcrls == NULL && (*pcrls = sk_X509_CRL_new_null()) == NULL) {
924 BIO_printf(bio_err, "Out of memory loading");
928 SET_EXPECT(expect, OSSL_STORE_INFO_CRL);
930 if (cnt_expectations == 0) {
931 BIO_printf(bio_err, "Internal error: nothing to load from %s\n",
932 uri != NULL ? uri : "<stdin>");
936 uidata.password = pass;
937 uidata.prompt_info = uri;
939 if ((input_type = format2string(format)) != NULL) {
940 itp[0] = OSSL_PARAM_construct_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE,
941 (char *)input_type, 0);
942 itp[1] = OSSL_PARAM_construct_end();
950 BIO_printf(bio_err, "No filename or uri specified for loading");
955 bio = BIO_new_fp(stdin, 0);
957 ctx = OSSL_STORE_attach(bio, "file", libctx, propq,
958 get_ui_method(), &uidata, params,
963 ctx = OSSL_STORE_open_ex(uri, libctx, propq, get_ui_method(), &uidata,
967 BIO_printf(bio_err, "Could not open file or uri for loading");
970 if (expect > 0 && !OSSL_STORE_expect(ctx, expect))
974 while (cnt_expectations > 0 && !OSSL_STORE_eof(ctx)) {
975 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
979 * This can happen (for example) if we attempt to load a file with
980 * multiple different types of things in it - but the thing we just
981 * tried to load wasn't one of the ones we wanted, e.g. if we're trying
982 * to load a certificate but the file has both the private key and the
983 * certificate in it. We just retry until eof.
986 if (OSSL_STORE_error(ctx)) {
987 ERR_print_errors(bio_err);
993 type = OSSL_STORE_INFO_get_type(info);
995 case OSSL_STORE_INFO_PKEY:
996 if (ppkey != NULL && *ppkey == NULL) {
997 ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL;
998 cnt_expectations -= ok;
1001 * An EVP_PKEY with private parts also holds the public parts,
1002 * so if the caller asked for a public key, and we got a private
1003 * key, we can still pass it back.
1005 if (ok && ppubkey != NULL && *ppubkey == NULL) {
1006 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL);
1007 cnt_expectations -= ok;
1010 case OSSL_STORE_INFO_PUBKEY:
1011 if (ppubkey != NULL && *ppubkey == NULL) {
1012 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL);
1013 cnt_expectations -= ok;
1016 case OSSL_STORE_INFO_PARAMS:
1017 if (pparams != NULL && *pparams == NULL) {
1018 ok = ((*pparams = OSSL_STORE_INFO_get1_PARAMS(info)) != NULL);
1019 cnt_expectations -= ok;
1022 case OSSL_STORE_INFO_CERT:
1023 if (pcert != NULL && *pcert == NULL) {
1024 ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL;
1025 cnt_expectations -= ok;
1027 else if (pcerts != NULL)
1028 ok = X509_add_cert(*pcerts,
1029 OSSL_STORE_INFO_get1_CERT(info),
1030 X509_ADD_FLAG_DEFAULT);
1033 case OSSL_STORE_INFO_CRL:
1034 if (pcrl != NULL && *pcrl == NULL) {
1035 ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL;
1036 cnt_expectations -= ok;
1038 else if (pcrls != NULL)
1039 ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info));
1043 /* skip any other type */
1046 OSSL_STORE_INFO_free(info);
1048 failed = info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
1049 BIO_printf(bio_err, "Error reading");
1055 OSSL_STORE_close(ctx);
1056 if (failed == NULL) {
1059 if ((ppkey != NULL && *ppkey == NULL)
1060 || (ppubkey != NULL && *ppubkey == NULL)) {
1062 } else if (pparams != NULL && *pparams == NULL) {
1064 } else if ((pcert != NULL || pcerts != NULL) && ncerts == 0) {
1068 } else if ((pcrl != NULL || pcrls != NULL) && ncrls == 0) {
1074 BIO_printf(bio_err, "Could not read");
1076 BIO_printf(bio_err, " any");
1078 if (failed != NULL) {
1079 if (desc != NULL && strstr(desc, failed) != NULL) {
1080 BIO_printf(bio_err, " %s", desc);
1082 BIO_printf(bio_err, " %s", failed);
1084 BIO_printf(bio_err, " of %s", desc);
1087 BIO_printf(bio_err, " from %s", uri);
1088 BIO_printf(bio_err, "\n");
1089 ERR_print_errors(bio_err);
1091 return failed == NULL;
1095 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
1096 /* Return error for unknown extensions */
1097 #define X509V3_EXT_DEFAULT 0
1098 /* Print error for unknown extensions */
1099 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
1100 /* ASN1 parse unknown extensions */
1101 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
1102 /* BIO_dump unknown extensions */
1103 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
1105 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1106 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1108 int set_cert_ex(unsigned long *flags, const char *arg)
1110 static const NAME_EX_TBL cert_tbl[] = {
1111 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
1112 {"ca_default", X509_FLAG_CA, 0xffffffffl},
1113 {"no_header", X509_FLAG_NO_HEADER, 0},
1114 {"no_version", X509_FLAG_NO_VERSION, 0},
1115 {"no_serial", X509_FLAG_NO_SERIAL, 0},
1116 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
1117 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
1118 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
1119 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1120 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1121 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1122 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1123 {"no_aux", X509_FLAG_NO_AUX, 0},
1124 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1125 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1126 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1127 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1128 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1131 return set_multi_opts(flags, arg, cert_tbl);
1134 int set_name_ex(unsigned long *flags, const char *arg)
1136 static const NAME_EX_TBL ex_tbl[] = {
1137 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1138 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
1139 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1140 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1141 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1142 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1143 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1144 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1145 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1146 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1147 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1148 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1149 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1150 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1151 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1152 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1153 {"dn_rev", XN_FLAG_DN_REV, 0},
1154 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1155 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1156 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1157 {"align", XN_FLAG_FN_ALIGN, 0},
1158 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1159 {"space_eq", XN_FLAG_SPC_EQ, 0},
1160 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1161 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1162 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1163 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1164 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1167 if (set_multi_opts(flags, arg, ex_tbl) == 0)
1169 if (*flags != XN_FLAG_COMPAT
1170 && (*flags & XN_FLAG_SEP_MASK) == 0)
1171 *flags |= XN_FLAG_SEP_CPLUS_SPC;
1175 int set_ext_copy(int *copy_type, const char *arg)
1177 if (strcasecmp(arg, "none") == 0)
1178 *copy_type = EXT_COPY_NONE;
1179 else if (strcasecmp(arg, "copy") == 0)
1180 *copy_type = EXT_COPY_ADD;
1181 else if (strcasecmp(arg, "copyall") == 0)
1182 *copy_type = EXT_COPY_ALL;
1188 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1190 STACK_OF(X509_EXTENSION) *exts;
1193 if (x == NULL || req == NULL)
1195 if (copy_type == EXT_COPY_NONE)
1197 exts = X509_REQ_get_extensions(req);
1199 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1200 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
1201 ASN1_OBJECT *obj = X509_EXTENSION_get_object(ext);
1202 int idx = X509_get_ext_by_OBJ(x, obj, -1);
1204 /* Does extension exist in target? */
1206 /* If normal copy don't override existing extension */
1207 if (copy_type == EXT_COPY_ADD)
1209 /* Delete all extensions of same type */
1211 X509_EXTENSION_free(X509_delete_ext(x, idx));
1212 idx = X509_get_ext_by_OBJ(x, obj, -1);
1213 } while (idx != -1);
1215 if (!X509_add_ext(x, ext, -1))
1221 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1225 static int set_multi_opts(unsigned long *flags, const char *arg,
1226 const NAME_EX_TBL * in_tbl)
1228 STACK_OF(CONF_VALUE) *vals;
1233 vals = X509V3_parse_list(arg);
1234 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1235 val = sk_CONF_VALUE_value(vals, i);
1236 if (!set_table_opts(flags, val->name, in_tbl))
1239 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1243 static int set_table_opts(unsigned long *flags, const char *arg,
1244 const NAME_EX_TBL * in_tbl)
1247 const NAME_EX_TBL *ptbl;
1253 } else if (c == '+') {
1260 for (ptbl = in_tbl; ptbl->name; ptbl++) {
1261 if (strcasecmp(arg, ptbl->name) == 0) {
1262 *flags &= ~ptbl->mask;
1264 *flags |= ptbl->flag;
1266 *flags &= ~ptbl->flag;
1273 void print_name(BIO *out, const char *title, const X509_NAME *nm)
1278 unsigned long lflags = get_nameopt();
1281 BIO_puts(out, title);
1282 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1286 if (lflags == XN_FLAG_COMPAT) {
1287 buf = X509_NAME_oneline(nm, 0, 0);
1289 BIO_puts(out, "\n");
1293 BIO_puts(out, "\n");
1294 X509_NAME_print_ex(out, nm, indent, lflags);
1295 BIO_puts(out, "\n");
1299 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1300 int len, unsigned char *buffer)
1302 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1303 if (BN_is_zero(in)) {
1304 BIO_printf(out, "\n 0x00");
1308 l = BN_bn2bin(in, buffer);
1309 for (i = 0; i < l; i++) {
1310 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1312 BIO_printf(out, "0x%02X,", buffer[i]);
1314 BIO_printf(out, "0x%02X", buffer[i]);
1317 BIO_printf(out, "\n };\n");
1320 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1324 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1325 for (i = 0; i < len; i++) {
1327 BIO_printf(out, "\n ");
1329 BIO_printf(out, "0x%02X, ", d[i]);
1331 BIO_printf(out, "0x%02X", d[i]);
1333 BIO_printf(out, "\n};\n");
1336 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1337 const char *CApath, int noCApath,
1338 const char *CAstore, int noCAstore)
1340 X509_STORE *store = X509_STORE_new();
1341 X509_LOOKUP *lookup;
1342 OSSL_LIB_CTX *libctx = app_get0_libctx();
1343 const char *propq = app_get0_propq();
1348 if (CAfile != NULL || !noCAfile) {
1349 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1352 if (CAfile != NULL) {
1353 if (!X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM,
1355 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1359 X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT,
1364 if (CApath != NULL || !noCApath) {
1365 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1368 if (CApath != NULL) {
1369 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1370 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1374 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1378 if (CAstore != NULL || !noCAstore) {
1379 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1382 if (!X509_LOOKUP_add_store_ex(lookup, CAstore, libctx, propq)) {
1383 if (CAstore != NULL)
1384 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1392 ERR_print_errors(bio_err);
1393 X509_STORE_free(store);
1397 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1404 return OPENSSL_LH_strhash(n);
1407 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1408 const OPENSSL_CSTRING *b)
1410 const char *aa, *bb;
1412 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1413 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1414 return strcmp(aa, bb);
1417 static int index_name_qual(char **a)
1419 return (a[0][0] == 'V');
1422 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1424 return OPENSSL_LH_strhash(a[DB_name]);
1427 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1429 return strcmp(a[DB_name], b[DB_name]);
1432 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1433 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1434 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1435 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1438 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1443 ASN1_INTEGER *ai = NULL;
1445 ai = ASN1_INTEGER_new();
1449 in = BIO_new_file(serialfile, "r");
1457 if (ret == NULL || !rand_serial(ret, ai))
1458 BIO_printf(bio_err, "Out of memory\n");
1460 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1461 BIO_printf(bio_err, "Unable to load number from %s\n",
1465 ret = ASN1_INTEGER_to_BN(ai, NULL);
1467 BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1477 ERR_print_errors(bio_err);
1479 ASN1_INTEGER_free(ai);
1483 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1484 ASN1_INTEGER **retai)
1489 ASN1_INTEGER *ai = NULL;
1493 j = strlen(serialfile);
1495 j = strlen(serialfile) + strlen(suffix) + 1;
1497 BIO_printf(bio_err, "File name too long\n");
1502 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1504 #ifndef OPENSSL_SYS_VMS
1505 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1507 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1510 out = BIO_new_file(buf[0], "w");
1515 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1516 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1519 i2a_ASN1_INTEGER(out, ai);
1520 BIO_puts(out, "\n");
1528 ERR_print_errors(bio_err);
1530 ASN1_INTEGER_free(ai);
1534 int rotate_serial(const char *serialfile, const char *new_suffix,
1535 const char *old_suffix)
1540 i = strlen(serialfile) + strlen(old_suffix);
1541 j = strlen(serialfile) + strlen(new_suffix);
1544 if (j + 1 >= BSIZE) {
1545 BIO_printf(bio_err, "File name too long\n");
1548 #ifndef OPENSSL_SYS_VMS
1549 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1550 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1552 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1553 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1555 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1561 "Unable to rename %s to %s\n", serialfile, buf[1]);
1565 if (rename(buf[0], serialfile) < 0) {
1567 "Unable to rename %s to %s\n", buf[0], serialfile);
1569 rename(buf[1], serialfile);
1574 ERR_print_errors(bio_err);
1578 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1583 btmp = b == NULL ? BN_new() : b;
1587 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1589 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1602 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1604 CA_DB *retdb = NULL;
1605 TXT_DB *tmpdb = NULL;
1607 CONF *dbattr_conf = NULL;
1609 #ifndef OPENSSL_NO_POSIX_IO
1614 in = BIO_new_file(dbfile, "r");
1618 #ifndef OPENSSL_NO_POSIX_IO
1619 BIO_get_fp(in, &dbfp);
1620 if (fstat(fileno(dbfp), &dbst) == -1) {
1621 ERR_raise_data(ERR_LIB_SYS, errno,
1622 "calling fstat(%s)", dbfile);
1627 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1630 #ifndef OPENSSL_SYS_VMS
1631 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1633 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1635 dbattr_conf = app_load_config_quiet(buf);
1637 retdb = app_malloc(sizeof(*retdb), "new DB");
1641 retdb->attributes = *db_attr;
1643 retdb->attributes.unique_subject = 1;
1647 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1649 retdb->attributes.unique_subject = parse_yesno(p, 1);
1653 retdb->dbfname = OPENSSL_strdup(dbfile);
1654 #ifndef OPENSSL_NO_POSIX_IO
1659 ERR_print_errors(bio_err);
1660 NCONF_free(dbattr_conf);
1667 * Returns > 0 on success, <= 0 on error
1669 int index_index(CA_DB *db)
1671 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1672 LHASH_HASH_FN(index_serial),
1673 LHASH_COMP_FN(index_serial))) {
1675 "Error creating serial number index:(%ld,%ld,%ld)\n",
1676 db->db->error, db->db->arg1, db->db->arg2);
1680 if (db->attributes.unique_subject
1681 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1682 LHASH_HASH_FN(index_name),
1683 LHASH_COMP_FN(index_name))) {
1684 BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1685 db->db->error, db->db->arg1, db->db->arg2);
1690 ERR_print_errors(bio_err);
1694 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1700 j = strlen(dbfile) + strlen(suffix);
1701 if (j + 6 >= BSIZE) {
1702 BIO_printf(bio_err, "File name too long\n");
1705 #ifndef OPENSSL_SYS_VMS
1706 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1707 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1708 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1710 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1711 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1712 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1714 out = BIO_new_file(buf[0], "w");
1717 BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1720 j = TXT_DB_write(out, db->db);
1725 out = BIO_new_file(buf[1], "w");
1728 BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1731 BIO_printf(out, "unique_subject = %s\n",
1732 db->attributes.unique_subject ? "yes" : "no");
1737 ERR_print_errors(bio_err);
1741 int rotate_index(const char *dbfile, const char *new_suffix,
1742 const char *old_suffix)
1747 i = strlen(dbfile) + strlen(old_suffix);
1748 j = strlen(dbfile) + strlen(new_suffix);
1751 if (j + 6 >= BSIZE) {
1752 BIO_printf(bio_err, "File name too long\n");
1755 #ifndef OPENSSL_SYS_VMS
1756 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1757 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1758 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1759 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1760 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1762 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1763 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1764 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1765 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1766 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1768 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1773 BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1777 if (rename(buf[0], dbfile) < 0) {
1778 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1780 rename(buf[1], dbfile);
1783 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1788 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1790 rename(dbfile, buf[0]);
1791 rename(buf[1], dbfile);
1794 if (rename(buf[2], buf[4]) < 0) {
1795 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1797 rename(buf[3], buf[4]);
1798 rename(dbfile, buf[0]);
1799 rename(buf[1], dbfile);
1804 ERR_print_errors(bio_err);
1808 void free_index(CA_DB *db)
1811 TXT_DB_free(db->db);
1812 OPENSSL_free(db->dbfname);
1817 int parse_yesno(const char *str, int def)
1821 case 'f': /* false */
1822 case 'F': /* FALSE */
1827 case 't': /* true */
1828 case 'T': /* TRUE */
1839 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1840 * where + can be used instead of / to form multi-valued RDNs if canmulti
1841 * and characters may be escaped by \
1843 X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
1846 int nextismulti = 0;
1852 "%s: %s name is expected to be in the format "
1853 "/type0=value0/type1=value1/type2=... where characters may "
1854 "be escaped by \\. This name is not in that format: '%s'\n",
1855 opt_getprog(), desc, --cp);
1859 n = X509_NAME_new();
1861 BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
1864 work = OPENSSL_strdup(cp);
1866 BIO_printf(bio_err, "%s: Error copying %s name input\n",
1867 opt_getprog(), desc);
1871 while (*cp != '\0') {
1874 unsigned char *valstr;
1876 int ismulti = nextismulti;
1879 /* Collect the type */
1880 while (*cp != '\0' && *cp != '=')
1885 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1886 opt_getprog(), typestr, desc);
1891 /* Collect the value. */
1892 valstr = (unsigned char *)bp;
1893 for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
1894 /* unescaped '+' symbol string signals further member of multiRDN */
1895 if (canmulti && *cp == '+') {
1899 if (*cp == '\\' && *++cp == '\0') {
1901 "%s: Escape character at end of %s name string\n",
1902 opt_getprog(), desc);
1908 /* If not at EOS (must be + or /), move forward. */
1913 nid = OBJ_txt2nid(typestr);
1914 if (nid == NID_undef) {
1916 "%s: Skipping unknown %s name attribute \"%s\"\n",
1917 opt_getprog(), desc, typestr);
1920 "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
1923 if (*valstr == '\0') {
1925 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1926 opt_getprog(), desc, typestr);
1929 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1930 valstr, strlen((char *)valstr),
1931 -1, ismulti ? -1 : 0)) {
1932 ERR_print_errors(bio_err);
1934 "%s: Error adding %s name attribute \"/%s=%s\"\n",
1935 opt_getprog(), desc, typestr ,valstr);
1950 * Read whole contents of a BIO into an allocated memory buffer and return
1954 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1958 unsigned char tbuf[1024];
1960 mem = BIO_new(BIO_s_mem());
1964 if ((maxlen != -1) && maxlen < 1024)
1968 len = BIO_read(in, tbuf, len);
1975 if (BIO_write(mem, tbuf, len) != len) {
1984 ret = BIO_get_mem_data(mem, (char **)out);
1985 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1990 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1993 char *stmp, *vtmp = NULL;
1995 stmp = OPENSSL_strdup(value);
1998 vtmp = strchr(stmp, ':');
2004 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
2011 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
2013 X509_POLICY_NODE *node;
2016 BIO_printf(bio_err, "%s Policies:", name);
2018 BIO_puts(bio_err, "\n");
2019 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
2020 node = sk_X509_POLICY_NODE_value(nodes, i);
2021 X509_POLICY_NODE_print(bio_err, node, 2);
2024 BIO_puts(bio_err, " <empty>\n");
2028 void policies_print(X509_STORE_CTX *ctx)
2030 X509_POLICY_TREE *tree;
2031 int explicit_policy;
2032 tree = X509_STORE_CTX_get0_policy_tree(ctx);
2033 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2035 BIO_printf(bio_err, "Require explicit Policy: %s\n",
2036 explicit_policy ? "True" : "False");
2038 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
2039 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
2043 * next_protos_parse parses a comma separated list of strings into a string
2044 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
2045 * outlen: (output) set to the length of the resulting buffer on success.
2046 * err: (maybe NULL) on failure, an error message line is written to this BIO.
2047 * in: a NUL terminated string like "abc,def,ghi"
2049 * returns: a malloc'd buffer or NULL on failure.
2051 unsigned char *next_protos_parse(size_t *outlen, const char *in)
2055 size_t i, start = 0;
2059 if (len == 0 || len >= 65535)
2062 out = app_malloc(len + 1, "NPN buffer");
2063 for (i = 0; i <= len; ++i) {
2064 if (i == len || in[i] == ',') {
2066 * Zero-length ALPN elements are invalid on the wire, we could be
2067 * strict and reject the entire string, but just ignoring extra
2068 * commas seems harmless and more friendly.
2070 * Every comma we skip in this way puts the input buffer another
2071 * byte ahead of the output buffer, so all stores into the output
2072 * buffer need to be decremented by the number commas skipped.
2079 if (i - start > 255) {
2083 out[start-skipped] = (unsigned char)(i - start);
2086 out[i + 1 - skipped] = in[i];
2090 if (len <= skipped) {
2095 *outlen = len + 1 - skipped;
2099 void print_cert_checks(BIO *bio, X509 *x,
2100 const char *checkhost,
2101 const char *checkemail, const char *checkip)
2106 BIO_printf(bio, "Hostname %s does%s match certificate\n",
2108 X509_check_host(x, checkhost, 0, 0, NULL) == 1
2113 BIO_printf(bio, "Email %s does%s match certificate\n",
2114 checkemail, X509_check_email(x, checkemail, 0, 0)
2119 BIO_printf(bio, "IP %s does%s match certificate\n",
2120 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
2124 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
2131 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2132 char *opt = sk_OPENSSL_STRING_value(opts, i);
2133 if (pkey_ctrl_string(pkctx, opt) <= 0) {
2134 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2135 ERR_print_errors(bio_err);
2143 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
2150 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2151 char *opt = sk_OPENSSL_STRING_value(opts, i);
2152 if (x509_ctrl_string(x, opt) <= 0) {
2153 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2154 ERR_print_errors(bio_err);
2162 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
2169 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2170 char *opt = sk_OPENSSL_STRING_value(opts, i);
2171 if (x509_req_ctrl_string(x, opt) <= 0) {
2172 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2173 ERR_print_errors(bio_err);
2181 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
2182 const char *md, STACK_OF(OPENSSL_STRING) *sigopts)
2184 EVP_PKEY_CTX *pkctx = NULL;
2190 * EVP_PKEY_get_default_digest_name() returns 2 if the digest is mandatory
2191 * for this algorithm.
2193 if (EVP_PKEY_get_default_digest_name(pkey, def_md, sizeof(def_md)) == 2
2194 && strcmp(def_md, "UNDEF") == 0) {
2195 /* The signing algorithm requires there to be no digest */
2199 return EVP_DigestSignInit_ex(ctx, &pkctx, md, app_get0_libctx(),
2200 app_get0_propq(), pkey, NULL)
2201 && do_pkey_ctx_init(pkctx, sigopts);
2204 static int adapt_keyid_ext(X509 *cert, X509V3_CTX *ext_ctx,
2205 const char *name, const char *value, int add_default)
2207 const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
2208 X509_EXTENSION *new_ext = X509V3_EXT_nconf(NULL, ext_ctx, name, value);
2211 if (new_ext == NULL)
2214 idx = X509v3_get_ext_by_OBJ(exts, X509_EXTENSION_get_object(new_ext), -1);
2216 X509_EXTENSION *found_ext = X509v3_get_ext(exts, idx);
2217 ASN1_OCTET_STRING *data = X509_EXTENSION_get_data(found_ext);
2218 int disabled = ASN1_STRING_length(data) <= 2; /* config said "none" */
2221 X509_delete_ext(cert, idx);
2222 X509_EXTENSION_free(found_ext);
2223 } /* else keep existing key identifier, which might be outdated */
2226 rv = !add_default || X509_add_ext(cert, new_ext, -1);
2228 X509_EXTENSION_free(new_ext);
2232 /* Ensure RFC 5280 compliance, adapt keyIDs as needed, and sign the cert info */
2233 int do_X509_sign(X509 *cert, EVP_PKEY *pkey, const char *md,
2234 STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx)
2236 const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
2237 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2241 if (sk_X509_EXTENSION_num(exts /* may be NULL */) > 0) {
2242 /* Prevent X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 */
2243 if (!X509_set_version(cert, X509_VERSION_3))
2247 * Add default SKID before such that default AKID can make use of it
2248 * in case the certificate is self-signed
2250 /* Prevent X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER */
2251 if (!adapt_keyid_ext(cert, ext_ctx, "subjectKeyIdentifier", "hash", 1))
2253 /* Prevent X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER */
2255 self_sign = X509_check_private_key(cert, pkey);
2257 if (!adapt_keyid_ext(cert, ext_ctx, "authorityKeyIdentifier",
2258 "keyid, issuer", !self_sign))
2261 /* TODO any further measures for ensuring default RFC 5280 compliance */
2264 if (mctx != NULL && do_sign_init(mctx, pkey, md, sigopts) > 0)
2265 rv = (X509_sign_ctx(cert, mctx) > 0);
2267 EVP_MD_CTX_free(mctx);
2271 /* Sign the certificate request info */
2272 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md,
2273 STACK_OF(OPENSSL_STRING) *sigopts)
2276 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2278 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2279 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
2280 EVP_MD_CTX_free(mctx);
2284 /* Sign the CRL info */
2285 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md,
2286 STACK_OF(OPENSSL_STRING) *sigopts)
2289 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2291 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2292 rv = (X509_CRL_sign_ctx(x, mctx) > 0);
2293 EVP_MD_CTX_free(mctx);
2297 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
2301 if (do_x509_init(x, vfyopts) > 0)
2302 rv = (X509_verify(x, pkey) > 0);
2306 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
2307 STACK_OF(OPENSSL_STRING) *vfyopts)
2311 if (do_x509_req_init(x, vfyopts) > 0)
2312 rv = (X509_REQ_verify_ex(x, pkey,
2313 app_get0_libctx(), app_get0_propq()) > 0);
2317 /* Get first http URL from a DIST_POINT structure */
2319 static const char *get_dp_url(DIST_POINT *dp)
2321 GENERAL_NAMES *gens;
2325 if (!dp->distpoint || dp->distpoint->type != 0)
2327 gens = dp->distpoint->name.fullname;
2328 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2329 gen = sk_GENERAL_NAME_value(gens, i);
2330 uri = GENERAL_NAME_get0_value(gen, >ype);
2331 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
2332 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
2334 if (IS_HTTP(uptr)) /* can/should not use HTTPS here */
2342 * Look through a CRLDP structure and attempt to find an http URL to
2343 * downloads a CRL from.
2346 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
2349 const char *urlptr = NULL;
2350 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2351 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
2352 urlptr = get_dp_url(dp);
2354 return load_crl(urlptr, FORMAT_UNDEF, 0, "CRL via CDP");
2360 * Example of downloading CRLs from CRLDP:
2361 * not usable for real world as it always downloads and doesn't cache anything.
2364 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
2365 const X509_NAME *nm)
2368 STACK_OF(X509_CRL) *crls = NULL;
2370 STACK_OF(DIST_POINT) *crldp;
2372 crls = sk_X509_CRL_new_null();
2375 x = X509_STORE_CTX_get_current_cert(ctx);
2376 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2377 crl = load_crl_crldp(crldp);
2378 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2380 sk_X509_CRL_free(crls);
2383 sk_X509_CRL_push(crls, crl);
2384 /* Try to download delta CRL */
2385 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2386 crl = load_crl_crldp(crldp);
2387 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2389 sk_X509_CRL_push(crls, crl);
2393 void store_setup_crl_download(X509_STORE *st)
2395 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2398 #ifndef OPENSSL_NO_SOCK
2399 static const char *tls_error_hint(void)
2401 unsigned long err = ERR_peek_error();
2403 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2404 err = ERR_peek_last_error();
2405 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2408 switch (ERR_GET_REASON(err)) {
2409 case SSL_R_WRONG_VERSION_NUMBER:
2410 return "The server does not support (a suitable version of) TLS";
2411 case SSL_R_UNKNOWN_PROTOCOL:
2412 return "The server does not support HTTPS";
2413 case SSL_R_CERTIFICATE_VERIFY_FAILED:
2414 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2415 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
2416 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2417 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
2418 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2419 default: /* no error or no hint available for error */
2424 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
2425 BIO *app_http_tls_cb(BIO *hbio, void *arg, int connect, int detail)
2427 if (connect && detail) { /* connecting with TLS */
2428 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
2429 SSL_CTX *ssl_ctx = info->ssl_ctx;
2433 if ((info->use_proxy
2434 && !OSSL_HTTP_proxy_connect(hbio, info->server, info->port,
2435 NULL, NULL, /* no proxy credentials */
2436 info->timeout, bio_err, opt_getprog()))
2437 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
2440 if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
2445 SSL_set_tlsext_host_name(ssl, info->server);
2447 SSL_set_connect_state(ssl);
2448 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2450 hbio = BIO_push(sbio, hbio);
2451 } else if (!connect && !detail) { /* disconnecting after error */
2452 const char *hint = tls_error_hint();
2455 ERR_add_error_data(2, " : ", hint);
2457 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2458 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2464 void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info)
2467 SSL_CTX_free(info->ssl_ctx);
2472 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2473 const char *no_proxy, SSL_CTX *ssl_ctx,
2474 const STACK_OF(CONF_VALUE) *headers,
2475 long timeout, const char *expected_content_type,
2476 const ASN1_ITEM *it)
2478 APP_HTTP_TLS_INFO info;
2483 ASN1_VALUE *resp = NULL;
2485 if (url == NULL || it == NULL) {
2486 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
2490 if (!OSSL_HTTP_parse_url(url, &use_ssl, NULL /* userinfo */, &server, &port,
2491 NULL /* port_num, */, NULL, NULL, NULL))
2493 if (use_ssl && ssl_ctx == NULL) {
2494 ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER,
2499 info.server = server;
2501 info.use_proxy = proxy != NULL;
2502 info.timeout = timeout;
2503 info.ssl_ctx = ssl_ctx;
2504 mem = OSSL_HTTP_get(url, proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2505 app_http_tls_cb, &info, 0 /* buf_size */, headers,
2506 expected_content_type, 1 /* expect_asn1 */,
2507 HTTP_DEFAULT_MAX_RESP_LEN, timeout);
2508 resp = ASN1_item_d2i_bio(it, mem, NULL);
2512 OPENSSL_free(server);
2518 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2519 const char *path, const char *proxy,
2520 const char *no_proxy, SSL_CTX *ssl_ctx,
2521 const STACK_OF(CONF_VALUE) *headers,
2522 const char *content_type,
2523 ASN1_VALUE *req, const ASN1_ITEM *req_it,
2524 const char *expected_content_type,
2525 long timeout, const ASN1_ITEM *rsp_it)
2527 APP_HTTP_TLS_INFO info;
2528 BIO *rsp, *req_mem = ASN1_item_i2d_mem_bio(req_it, req);
2531 if (req_mem == NULL)
2535 info.use_proxy = proxy != NULL;
2536 info.timeout = timeout;
2537 info.ssl_ctx = ssl_ctx;
2538 rsp = OSSL_HTTP_transfer(NULL, host, port, path, ssl_ctx != NULL,
2539 proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2540 app_http_tls_cb, &info,
2541 0 /* buf_size */, headers, content_type, req_mem,
2542 expected_content_type, 1 /* expect_asn1 */,
2543 HTTP_DEFAULT_MAX_RESP_LEN, timeout,
2544 0 /* keep_alive */);
2546 res = ASN1_item_d2i_bio(rsp_it, rsp, NULL);
2554 * Platform-specific sections
2559 # define fileno(a) (int)_fileno(a)
2562 # include <windows.h>
2565 static int WIN32_rename(const char *from, const char *to)
2567 TCHAR *tfrom = NULL, *tto;
2571 if (sizeof(TCHAR) == 1) {
2572 tfrom = (TCHAR *)from;
2574 } else { /* UNICODE path */
2576 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2577 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2581 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2582 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2584 for (i = 0; i < flen; i++)
2585 tfrom[i] = (TCHAR)from[i];
2586 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2587 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2589 for (i = 0; i < tlen; i++)
2590 tto[i] = (TCHAR)to[i];
2593 if (MoveFile(tfrom, tto))
2595 err = GetLastError();
2596 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2597 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2599 err = GetLastError();
2601 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2603 else if (err == ERROR_ACCESS_DENIED)
2606 errno = EINVAL; /* we could map more codes... */
2610 if (tfrom != NULL && tfrom != (TCHAR *)from)
2616 /* app_tminterval section */
2618 double app_tminterval(int stop, int usertime)
2622 static ULARGE_INTEGER tmstart;
2623 static int warning = 1;
2624 # ifdef _WIN32_WINNT
2625 static HANDLE proc = NULL;
2629 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2630 GetCurrentProcessId());
2632 proc = (HANDLE) - 1;
2635 if (usertime && proc != (HANDLE) - 1) {
2637 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2643 if (usertime && warning) {
2644 BIO_printf(bio_err, "To get meaningful results, run "
2645 "this program on idle system.\n");
2648 GetSystemTime(&systime);
2649 SystemTimeToFileTime(&systime, &now);
2652 if (stop == TM_START) {
2653 tmstart.u.LowPart = now.dwLowDateTime;
2654 tmstart.u.HighPart = now.dwHighDateTime;
2656 ULARGE_INTEGER tmstop;
2658 tmstop.u.LowPart = now.dwLowDateTime;
2659 tmstop.u.HighPart = now.dwHighDateTime;
2661 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2666 #elif defined(OPENSSL_SYS_VXWORKS)
2669 double app_tminterval(int stop, int usertime)
2672 # ifdef CLOCK_REALTIME
2673 static struct timespec tmstart;
2674 struct timespec now;
2676 static unsigned long tmstart;
2679 static int warning = 1;
2681 if (usertime && warning) {
2682 BIO_printf(bio_err, "To get meaningful results, run "
2683 "this program on idle system.\n");
2686 # ifdef CLOCK_REALTIME
2687 clock_gettime(CLOCK_REALTIME, &now);
2688 if (stop == TM_START)
2691 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2692 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2695 if (stop == TM_START)
2698 ret = (now - tmstart) / (double)sysClkRateGet();
2703 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2704 # include <sys/times.h>
2706 double app_tminterval(int stop, int usertime)
2710 clock_t now = times(&rus);
2711 static clock_t tmstart;
2714 now = rus.tms_utime;
2716 if (stop == TM_START) {
2719 long int tck = sysconf(_SC_CLK_TCK);
2720 ret = (now - tmstart) / (double)tck;
2727 # include <sys/time.h>
2728 # include <sys/resource.h>
2730 double app_tminterval(int stop, int usertime)
2735 static struct timeval tmstart;
2738 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2740 gettimeofday(&now, NULL);
2742 if (stop == TM_START)
2745 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2746 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2752 int app_access(const char* name, int flag)
2755 return _access(name, flag);
2757 return access(name, flag);
2761 int app_isdir(const char *name)
2763 return opt_isdir(name);
2766 /* raw_read|write section */
2768 # include "vms_term_sock.h"
2769 static int stdin_sock = -1;
2771 static void close_stdin_sock(void)
2773 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2776 int fileno_stdin(void)
2778 if (stdin_sock == -1) {
2779 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2780 atexit(close_stdin_sock);
2786 int fileno_stdin(void)
2788 return fileno(stdin);
2792 int fileno_stdout(void)
2794 return fileno(stdout);
2797 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2798 int raw_read_stdin(void *buf, int siz)
2801 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2806 #elif defined(__VMS)
2807 # include <sys/socket.h>
2809 int raw_read_stdin(void *buf, int siz)
2811 return recv(fileno_stdin(), buf, siz, 0);
2814 # if defined(__TANDEM)
2815 # if defined(OPENSSL_TANDEM_FLOSS)
2816 # include <floss.h(floss_read)>
2819 int raw_read_stdin(void *buf, int siz)
2821 return read(fileno_stdin(), buf, siz);
2825 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2826 int raw_write_stdout(const void *buf, int siz)
2829 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2834 #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
2835 # if defined(__TANDEM)
2836 # if defined(OPENSSL_TANDEM_FLOSS)
2837 # include <floss.h(floss_write)>
2840 int raw_write_stdout(const void *buf,int siz)
2842 return write(fileno(stdout),(void*)buf,siz);
2845 # if defined(__TANDEM)
2846 # if defined(OPENSSL_TANDEM_FLOSS)
2847 # include <floss.h(floss_write)>
2850 int raw_write_stdout(const void *buf, int siz)
2852 return write(fileno_stdout(), buf, siz);
2857 * Centralized handling of input and output files with format specification
2858 * The format is meant to show what the input and output is supposed to be,
2859 * and is therefore a show of intent more than anything else. However, it
2860 * does impact behavior on some platforms, such as differentiating between
2861 * text and binary input/output on non-Unix platforms
2863 BIO *dup_bio_in(int format)
2865 return BIO_new_fp(stdin,
2866 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2869 BIO *dup_bio_out(int format)
2871 BIO *b = BIO_new_fp(stdout,
2872 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2873 void *prefix = NULL;
2875 #ifdef OPENSSL_SYS_VMS
2876 if (FMT_istext(format))
2877 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2880 if (FMT_istext(format)
2881 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2882 b = BIO_push(BIO_new(BIO_f_prefix()), b);
2883 BIO_set_prefix(b, prefix);
2889 BIO *dup_bio_err(int format)
2891 BIO *b = BIO_new_fp(stderr,
2892 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2893 #ifdef OPENSSL_SYS_VMS
2894 if (FMT_istext(format))
2895 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2900 void unbuffer(FILE *fp)
2903 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2904 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2905 * However, we trust that the C RTL will never give us a FILE pointer
2906 * above the first 4 GB of memory, so we simply turn off the warning
2909 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2910 # pragma environment save
2911 # pragma message disable maylosedata2
2914 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2915 # pragma environment restore
2919 static const char *modestr(char mode, int format)
2921 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2925 return FMT_istext(format) ? "a" : "ab";
2927 return FMT_istext(format) ? "r" : "rb";
2929 return FMT_istext(format) ? "w" : "wb";
2931 /* The assert above should make sure we never reach this point */
2935 static const char *modeverb(char mode)
2945 return "(doing something)";
2949 * Open a file for writing, owner-read-only.
2951 BIO *bio_open_owner(const char *filename, int format, int private)
2955 int fd = -1, bflags, mode, textmode;
2957 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2958 return bio_open_default(filename, 'w', format);
2967 textmode = FMT_istext(format);
2971 #elif defined(_O_BINARY)
2976 #ifdef OPENSSL_SYS_VMS
2977 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2978 * it still needs to know that we're going binary, or fdopen()
2979 * will fail with "invalid argument"... so we tell VMS what the
2983 fd = open(filename, mode, 0600, "ctx=bin");
2986 fd = open(filename, mode, 0600);
2989 fp = fdopen(fd, modestr('w', format));
2994 bflags |= BIO_FP_TEXT;
2995 b = BIO_new_fp(fp, bflags);
3000 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
3001 opt_getprog(), filename, strerror(errno));
3002 ERR_print_errors(bio_err);
3003 /* If we have fp, then fdopen took over fd, so don't close both. */
3011 static BIO *bio_open_default_(const char *filename, char mode, int format,
3016 if (filename == NULL || strcmp(filename, "-") == 0) {
3017 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
3025 "Can't open %s, %s\n",
3026 mode == 'r' ? "stdin" : "stdout", strerror(errno));
3028 ret = BIO_new_file(filename, modestr(mode, format));
3036 "Can't open \"%s\" for %s, %s\n",
3037 filename, modeverb(mode), strerror(errno));
3039 ERR_print_errors(bio_err);
3043 BIO *bio_open_default(const char *filename, char mode, int format)
3045 return bio_open_default_(filename, mode, format, 0);
3048 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
3050 return bio_open_default_(filename, mode, format, 1);
3053 void wait_for_async(SSL *s)
3055 /* On Windows select only works for sockets, so we simply don't wait */
3056 #ifndef OPENSSL_SYS_WINDOWS
3063 if (!SSL_get_all_async_fds(s, NULL, &numfds))
3067 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
3068 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
3074 for (i = 0; i < numfds; i++) {
3075 if (width <= (int)fds[i])
3076 width = (int)fds[i] + 1;
3077 openssl_fdset((int)fds[i], &asyncfds);
3079 select(width, (void *)&asyncfds, NULL, NULL, NULL);
3084 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
3085 #if defined(OPENSSL_SYS_MSDOS)
3086 int has_stdin_waiting(void)
3088 # if defined(OPENSSL_SYS_WINDOWS)
3089 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
3091 INPUT_RECORD inputrec;
3095 if (inhand == INVALID_HANDLE_VALUE) {
3099 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
3101 /* Probably redirected input? _kbhit() does not work in this case */
3112 /* Corrupt a signature by modifying final byte */
3113 void corrupt_signature(const ASN1_STRING *signature)
3115 unsigned char *s = signature->data;
3116 s[signature->length - 1] ^= 0x1;
3119 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
3122 if (startdate == NULL || strcmp(startdate, "today") == 0) {
3123 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
3126 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
3129 if (enddate == NULL) {
3130 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
3133 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
3139 int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate)
3142 ASN1_TIME *tm = ASN1_TIME_new();
3147 if (lastupdate == NULL) {
3148 if (X509_gmtime_adj(tm, 0) == NULL)
3151 if (!ASN1_TIME_set_string_X509(tm, lastupdate))
3155 if (!X509_CRL_set1_lastUpdate(crl, tm))
3164 int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
3165 long days, long hours, long secs)
3168 ASN1_TIME *tm = ASN1_TIME_new();
3173 if (nextupdate == NULL) {
3174 if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL)
3177 if (!ASN1_TIME_set_string_X509(tm, nextupdate))
3181 if (!X509_CRL_set1_nextUpdate(crl, tm))
3190 void make_uppercase(char *string)
3194 for (i = 0; string[i] != '\0'; i++)
3195 string[i] = toupper((unsigned char)string[i]);
3198 /* This function is defined here due to visibility of bio_err */
3199 int opt_printf_stderr(const char *fmt, ...)
3205 ret = BIO_vprintf(bio_err, fmt, ap);
3210 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
3211 const OSSL_PARAM *paramdefs)
3213 OSSL_PARAM *params = NULL;
3214 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
3216 char *opt = "", *stmp, *vtmp = NULL;
3222 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
3226 for (params_n = 0; params_n < sz; params_n++) {
3227 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
3228 if ((stmp = OPENSSL_strdup(opt)) == NULL
3229 || (vtmp = strchr(stmp, ':')) == NULL)
3231 /* Replace ':' with 0 to terminate the string pointed to by stmp */
3233 /* Skip over the separator so that vmtp points to the value */
3235 if (!OSSL_PARAM_allocate_from_text(¶ms[params_n], paramdefs,
3236 stmp, vtmp, strlen(vtmp), &found))
3240 params[params_n] = OSSL_PARAM_construct_end();
3244 BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
3246 ERR_print_errors(bio_err);
3247 app_params_free(params);
3251 void app_params_free(OSSL_PARAM *params)
3255 if (params != NULL) {
3256 for (i = 0; params[i].key != NULL; ++i)
3257 OPENSSL_free(params[i].data);
3258 OPENSSL_free(params);