2 * Copyright 1995-2020 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/pem.h>
32 #include <openssl/store.h>
33 #include <openssl/pkcs12.h>
34 #include <openssl/ui.h>
35 #include <openssl/safestack.h>
36 #ifndef OPENSSL_NO_RSA
37 # include <openssl/rsa.h>
39 #include <openssl/bn.h>
40 #include <openssl/ssl.h>
44 static int WIN32_rename(const char *from, const char *to);
45 # define rename(from,to) WIN32_rename((from),(to))
48 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
52 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32)
56 #define PASS_SOURCE_SIZE_MAX 4
66 static OSSL_LIB_CTX *app_libctx = NULL;
68 static int set_table_opts(unsigned long *flags, const char *arg,
69 const NAME_EX_TBL * in_tbl);
70 static int set_multi_opts(unsigned long *flags, const char *arg,
71 const NAME_EX_TBL * in_tbl);
73 int app_init(long mesgwin);
75 int chopup_args(ARGS *arg, char *buf)
78 char c = '\0', *p = NULL;
83 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
87 /* Skip whitespace. */
88 while (*p && isspace(_UC(*p)))
93 /* The start of something good :-) */
94 if (arg->argc >= arg->size) {
97 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
102 quoted = *p == '\'' || *p == '"';
105 arg->argv[arg->argc++] = p;
107 /* now look for the end of this */
109 while (*p && *p != c)
113 while (*p && !isspace(_UC(*p)))
119 arg->argv[arg->argc] = NULL;
124 int app_init(long mesgwin)
130 int ctx_set_verify_locations(SSL_CTX *ctx,
131 const char *CAfile, int noCAfile,
132 const char *CApath, int noCApath,
133 const char *CAstore, int noCAstore)
135 if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
136 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
138 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
140 if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
146 if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
148 if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
150 if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
155 #ifndef OPENSSL_NO_CT
157 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
160 return SSL_CTX_set_default_ctlog_list_file(ctx);
162 return SSL_CTX_set_ctlog_list_file(ctx, path);
167 static unsigned long nmflag = 0;
168 static char nmflag_set = 0;
170 int set_nameopt(const char *arg)
172 int ret = set_name_ex(&nmflag, arg);
180 unsigned long get_nameopt(void)
182 return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
185 int dump_cert_text(BIO *out, X509 *x)
187 print_name(out, "subject=", X509_get_subject_name(x), get_nameopt());
189 print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
195 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
197 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
201 static char *app_get_pass(const char *arg, int keepbio);
203 char *get_passwd(const char *pass, const char *desc)
209 if (!app_passwd(pass, NULL, &result, NULL))
210 BIO_printf(bio_err, "Error getting password for %s\n", desc);
211 if (pass != NULL && result == NULL) {
213 "Trying plain input string (better precede with 'pass:')\n");
214 result = OPENSSL_strdup(pass);
216 BIO_printf(bio_err, "Out of memory getting password for %s\n", desc);
221 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
223 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
226 *pass1 = app_get_pass(arg1, same);
229 } else if (pass1 != NULL) {
233 *pass2 = app_get_pass(arg2, same ? 2 : 0);
236 } else if (pass2 != NULL) {
242 static char *app_get_pass(const char *arg, int keepbio)
244 static BIO *pwdbio = NULL;
245 char *tmp, tpass[APP_PASS_LEN];
248 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
249 if (strncmp(arg, "pass:", 5) == 0)
250 return OPENSSL_strdup(arg + 5);
251 if (strncmp(arg, "env:", 4) == 0) {
252 tmp = getenv(arg + 4);
254 BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
257 return OPENSSL_strdup(tmp);
259 if (!keepbio || pwdbio == NULL) {
260 if (strncmp(arg, "file:", 5) == 0) {
261 pwdbio = BIO_new_file(arg + 5, "r");
262 if (pwdbio == NULL) {
263 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
268 * Under _WIN32, which covers even Win64 and CE, file
269 * descriptors referenced by BIO_s_fd are not inherited
270 * by child process and therefore below is not an option.
271 * It could have been an option if bss_fd.c was operating
272 * on real Windows descriptors, such as those obtained
275 } else if (strncmp(arg, "fd:", 3) == 0) {
279 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
280 if ((i < 0) || !pwdbio) {
281 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
285 * Can't do BIO_gets on an fd BIO so add a buffering BIO
287 btmp = BIO_new(BIO_f_buffer());
288 pwdbio = BIO_push(btmp, pwdbio);
290 } else if (strcmp(arg, "stdin") == 0) {
291 pwdbio = dup_bio_in(FORMAT_TEXT);
292 if (pwdbio == NULL) {
293 BIO_printf(bio_err, "Can't open BIO for stdin\n");
297 /* argument syntax error; do not reveal too much about arg */
298 tmp = strchr(arg, ':');
299 if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
301 "Invalid password argument, missing ':' within the first %d chars\n",
302 PASS_SOURCE_SIZE_MAX + 1);
305 "Invalid password argument, starting with \"%.*s\"\n",
306 (int)(tmp - arg + 1), arg);
310 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
312 BIO_free_all(pwdbio);
316 BIO_printf(bio_err, "Error reading password from BIO\n");
319 tmp = strchr(tpass, '\n');
322 return OPENSSL_strdup(tpass);
325 OSSL_LIB_CTX *app_get0_libctx(void)
330 /* TODO(3.0): Make this an environment variable if required */
331 const char *app_get0_propq(void)
336 OSSL_LIB_CTX *app_create_libctx(void)
339 * Load the NULL provider into the default library context and create a
340 * library context which will then be used for any OPT_PROV options.
342 if (app_libctx == NULL) {
344 if (!app_provider_load(NULL, "null")) {
345 BIO_puts(bio_err, "Failed to create null provider\n");
348 app_libctx = OSSL_LIB_CTX_new();
350 if (app_libctx == NULL)
351 BIO_puts(bio_err, "Failed to create library context\n");
355 CONF *app_load_config_bio(BIO *in, const char *filename)
361 conf = NCONF_new_ex(app_libctx, NULL);
362 i = NCONF_load_bio(conf, in, &errorline);
366 if (errorline <= 0) {
367 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
369 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
372 if (filename != NULL)
373 BIO_printf(bio_err, "config file \"%s\"\n", filename);
375 BIO_printf(bio_err, "config input");
381 CONF *app_load_config(const char *filename)
386 in = bio_open_default(filename, 'r', FORMAT_TEXT);
390 conf = app_load_config_bio(in, filename);
395 CONF *app_load_config_quiet(const char *filename)
400 in = bio_open_default_quiet(filename, 'r', FORMAT_TEXT);
404 conf = app_load_config_bio(in, filename);
409 int app_load_modules(const CONF *config)
411 CONF *to_free = NULL;
414 config = to_free = app_load_config_quiet(default_config_file);
418 if (CONF_modules_load(config, NULL, 0) <= 0) {
419 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
420 ERR_print_errors(bio_err);
428 int add_oid_section(CONF *conf)
431 STACK_OF(CONF_VALUE) *sktmp;
435 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
439 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
440 BIO_printf(bio_err, "problem loading oid section %s\n", p);
443 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
444 cnf = sk_CONF_VALUE_value(sktmp, i);
445 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
446 BIO_printf(bio_err, "problem creating object %s=%s\n",
447 cnf->name, cnf->value);
454 CONF *app_load_config_modules(const char *configfile)
458 if (configfile != NULL) {
459 BIO_printf(bio_err, "Using configuration from %s\n", configfile);
461 if ((conf = app_load_config(configfile)) == NULL)
463 if (configfile != default_config_file && !app_load_modules(conf)) {
471 X509 *load_cert_pass(const char *uri, int maybe_stdin,
472 const char *pass, const char *desc)
477 desc = "certificate";
478 (void)load_key_certs_crls(uri, maybe_stdin, pass, desc,
479 NULL, NULL, &cert, NULL, NULL, NULL);
481 BIO_printf(bio_err, "Unable to load %s\n", desc);
482 ERR_print_errors(bio_err);
487 /* the format parameter is meanwhile not needed anymore and thus ignored */
488 X509_CRL *load_crl(const char *uri, int format, const char *desc)
490 X509_CRL *crl = NULL;
494 (void)load_key_certs_crls(uri, 0, NULL, desc,
495 NULL, NULL, NULL, NULL, &crl, NULL);
497 BIO_printf(bio_err, "Unable to load %s\n", desc);
498 ERR_print_errors(bio_err);
503 X509_REQ *load_csr(const char *file, int format, const char *desc)
505 X509_REQ *req = NULL;
510 in = bio_open_default(file, 'r', format);
514 if (format == FORMAT_ASN1)
515 req = d2i_X509_REQ_bio(in, NULL);
516 else if (format == FORMAT_PEM)
517 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
519 print_format_error(format, OPT_FMT_PEMDER);
523 BIO_printf(bio_err, "Unable to load %s\n", desc);
524 ERR_print_errors(bio_err);
530 void cleanse(char *str)
533 OPENSSL_cleanse(str, strlen(str));
536 void clear_free(char *str)
539 OPENSSL_clear_free(str, strlen(str));
542 EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
543 const char *pass, ENGINE *e, const char *desc)
545 EVP_PKEY *pkey = NULL;
548 desc = "private key";
550 if (format == FORMAT_ENGINE) {
552 BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
554 pkey = load_engine_private_key(e, uri, pass, desc);
556 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
557 ERR_print_errors(bio_err);
561 (void)load_key_certs_crls(uri, may_stdin, pass, desc,
562 &pkey, NULL, NULL, NULL, NULL, NULL);
566 BIO_printf(bio_err, "Unable to load %s\n", desc);
567 ERR_print_errors(bio_err);
572 EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
573 const char *pass, ENGINE *e, const char *desc)
575 EVP_PKEY *pkey = NULL;
580 if (format == FORMAT_ENGINE) {
582 BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
584 pkey = load_engine_public_key(e, uri, pass, desc);
586 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
587 ERR_print_errors(bio_err);
591 (void)load_key_certs_crls(uri, maybe_stdin, pass, desc,
592 NULL, &pkey, NULL, NULL, NULL, NULL);
595 BIO_printf(bio_err, "Unable to load %s\n", desc);
596 ERR_print_errors(bio_err);
601 void app_bail_out(char *fmt, ...)
606 BIO_vprintf(bio_err, fmt, args);
608 ERR_print_errors(bio_err);
612 void* app_malloc(int sz, const char *what)
614 void *vp = OPENSSL_malloc(sz);
617 app_bail_out("%s: Could not allocate %d bytes for %s\n",
618 opt_getprog(), sz, what);
623 * Initialize or extend, if *certs != NULL, a certificate stack.
624 * The caller is responsible for freeing *certs if its value is left not NULL.
626 int load_certs(const char *uri, STACK_OF(X509) **certs,
627 const char *pass, const char *desc)
629 int was_NULL = *certs == NULL;
630 int ret = load_key_certs_crls(uri, 0, pass, desc, NULL, NULL,
631 NULL, certs, NULL, NULL);
633 if (!ret && was_NULL) {
634 sk_X509_pop_free(*certs, X509_free);
641 * Initialize or extend, if *crls != NULL, a certificate stack.
642 * The caller is responsible for freeing *crls if its value is left not NULL.
644 int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
645 const char *pass, const char *desc)
647 int was_NULL = *crls == NULL;
648 int ret = load_key_certs_crls(uri, 0, pass, desc, NULL, NULL,
649 NULL, NULL, NULL, crls);
651 if (!ret && was_NULL) {
652 sk_X509_CRL_pop_free(*crls, X509_CRL_free);
659 * Load those types of credentials for which the result pointer is not NULL.
660 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
661 * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
662 * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
663 * If pcerts is non-NULL then all available certificates are appended to *pcerts
664 * except any certificate assigned to *pcert.
665 * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
666 * If pcrls is non-NULL then all available CRLs are appended to *pcerts
667 * except any CRL assigned to *pcrl.
668 * In any case (also on error) the caller is responsible for freeing all members
669 * of *pcerts and *pcrls (as far as they are not NULL).
671 int load_key_certs_crls(const char *uri, int maybe_stdin,
672 const char *pass, const char *desc,
673 EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
674 X509 **pcert, STACK_OF(X509) **pcerts,
675 X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
678 OSSL_STORE_CTX *ctx = NULL;
679 OSSL_LIB_CTX *libctx = app_get0_libctx();
680 const char *propq = app_get0_propq();
684 ppkey != NULL ? "key" : ppubkey != NULL ? "public key" :
685 pcert != NULL ? "cert" : pcrl != NULL ? "CRL" :
686 pcerts != NULL ? "certs" : pcrls != NULL ? "CRLs" : NULL;
687 /* TODO make use of the engine reference 'eng' when loading pkeys */
695 if (failed == NULL) {
696 BIO_printf(bio_err, "Internal error: nothing to load into from %s\n",
697 uri != NULL ? uri : "<stdin>");
701 if (pcerts != NULL && *pcerts == NULL
702 && (*pcerts = sk_X509_new_null()) == NULL) {
703 BIO_printf(bio_err, "Out of memory loading");
708 if (pcrls != NULL && *pcrls == NULL
709 && (*pcrls = sk_X509_CRL_new_null()) == NULL) {
710 BIO_printf(bio_err, "Out of memory loading");
714 uidata.password = pass;
715 uidata.prompt_info = uri;
721 BIO_printf(bio_err, "No filename or uri specified for loading");
726 bio = BIO_new_fp(stdin, 0);
728 ctx = OSSL_STORE_attach(bio, "file", libctx, propq,
729 get_ui_method(), &uidata, NULL, NULL);
731 ctx = OSSL_STORE_open_ex(uri, libctx, propq, get_ui_method(), &uidata,
735 BIO_printf(bio_err, "Could not open file or uri for loading");
740 while (!OSSL_STORE_eof(ctx)) {
741 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
746 type = OSSL_STORE_INFO_get_type(info);
748 case OSSL_STORE_INFO_PKEY:
749 if (ppkey != NULL && *ppkey == NULL)
750 ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL;
753 * An EVP_PKEY with private parts also holds the public parts,
754 * so if the caller asked for a public key, and we got a private
755 * key, we can still pass it back.
757 if (ok && ppubkey != NULL && *ppubkey == NULL)
758 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL);
760 case OSSL_STORE_INFO_PUBKEY:
761 if (ppubkey != NULL && *ppubkey == NULL)
762 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL);
764 case OSSL_STORE_INFO_CERT:
765 if (pcert != NULL && *pcert == NULL)
766 ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL;
767 else if (pcerts != NULL)
768 ok = X509_add_cert(*pcerts,
769 OSSL_STORE_INFO_get1_CERT(info),
770 X509_ADD_FLAG_DEFAULT);
773 case OSSL_STORE_INFO_CRL:
774 if (pcrl != NULL && *pcrl == NULL)
775 ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL;
776 else if (pcrls != NULL)
777 ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info));
781 /* skip any other type */
784 OSSL_STORE_INFO_free(info);
786 failed = info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
787 BIO_printf(bio_err, "Error reading");
793 OSSL_STORE_close(ctx);
794 if (failed == NULL) {
797 if (ppkey != NULL && *ppkey == NULL) {
799 } else if ((pcert != NULL || pcerts != NULL) && ncerts == 0) {
803 } else if ((pcrl != NULL || pcrls != NULL) && ncrls == 0) {
809 BIO_printf(bio_err, "Could not read");
811 BIO_printf(bio_err, " any");
813 if (failed != NULL) {
814 if (desc != NULL && strstr(desc, failed) != NULL) {
815 BIO_printf(bio_err, " %s", desc);
817 BIO_printf(bio_err, " %s", failed);
819 BIO_printf(bio_err, " of %s", desc);
822 BIO_printf(bio_err, " from %s", uri);
823 BIO_printf(bio_err, "\n");
824 ERR_print_errors(bio_err);
826 return failed == NULL;
830 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
831 /* Return error for unknown extensions */
832 #define X509V3_EXT_DEFAULT 0
833 /* Print error for unknown extensions */
834 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
835 /* ASN1 parse unknown extensions */
836 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
837 /* BIO_dump unknown extensions */
838 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
840 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
841 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
843 int set_cert_ex(unsigned long *flags, const char *arg)
845 static const NAME_EX_TBL cert_tbl[] = {
846 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
847 {"ca_default", X509_FLAG_CA, 0xffffffffl},
848 {"no_header", X509_FLAG_NO_HEADER, 0},
849 {"no_version", X509_FLAG_NO_VERSION, 0},
850 {"no_serial", X509_FLAG_NO_SERIAL, 0},
851 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
852 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
853 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
854 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
855 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
856 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
857 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
858 {"no_aux", X509_FLAG_NO_AUX, 0},
859 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
860 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
861 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
862 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
863 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
866 return set_multi_opts(flags, arg, cert_tbl);
869 int set_name_ex(unsigned long *flags, const char *arg)
871 static const NAME_EX_TBL ex_tbl[] = {
872 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
873 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
874 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
875 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
876 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
877 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
878 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
879 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
880 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
881 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
882 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
883 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
884 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
885 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
886 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
887 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
888 {"dn_rev", XN_FLAG_DN_REV, 0},
889 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
890 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
891 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
892 {"align", XN_FLAG_FN_ALIGN, 0},
893 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
894 {"space_eq", XN_FLAG_SPC_EQ, 0},
895 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
896 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
897 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
898 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
899 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
902 if (set_multi_opts(flags, arg, ex_tbl) == 0)
904 if (*flags != XN_FLAG_COMPAT
905 && (*flags & XN_FLAG_SEP_MASK) == 0)
906 *flags |= XN_FLAG_SEP_CPLUS_SPC;
910 int set_ext_copy(int *copy_type, const char *arg)
912 if (strcasecmp(arg, "none") == 0)
913 *copy_type = EXT_COPY_NONE;
914 else if (strcasecmp(arg, "copy") == 0)
915 *copy_type = EXT_COPY_ADD;
916 else if (strcasecmp(arg, "copyall") == 0)
917 *copy_type = EXT_COPY_ALL;
923 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
925 STACK_OF(X509_EXTENSION) *exts = NULL;
926 X509_EXTENSION *ext, *tmpext;
929 if (!x || !req || (copy_type == EXT_COPY_NONE))
931 exts = X509_REQ_get_extensions(req);
933 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
934 ext = sk_X509_EXTENSION_value(exts, i);
935 obj = X509_EXTENSION_get_object(ext);
936 idx = X509_get_ext_by_OBJ(x, obj, -1);
937 /* Does extension exist? */
939 /* If normal copy don't override existing extension */
940 if (copy_type == EXT_COPY_ADD)
942 /* Delete all extensions of same type */
944 tmpext = X509_get_ext(x, idx);
945 X509_delete_ext(x, idx);
946 X509_EXTENSION_free(tmpext);
947 idx = X509_get_ext_by_OBJ(x, obj, -1);
950 if (!X509_add_ext(x, ext, -1))
958 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
963 static int set_multi_opts(unsigned long *flags, const char *arg,
964 const NAME_EX_TBL * in_tbl)
966 STACK_OF(CONF_VALUE) *vals;
971 vals = X509V3_parse_list(arg);
972 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
973 val = sk_CONF_VALUE_value(vals, i);
974 if (!set_table_opts(flags, val->name, in_tbl))
977 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
981 static int set_table_opts(unsigned long *flags, const char *arg,
982 const NAME_EX_TBL * in_tbl)
985 const NAME_EX_TBL *ptbl;
991 } else if (c == '+') {
998 for (ptbl = in_tbl; ptbl->name; ptbl++) {
999 if (strcasecmp(arg, ptbl->name) == 0) {
1000 *flags &= ~ptbl->mask;
1002 *flags |= ptbl->flag;
1004 *flags &= ~ptbl->flag;
1011 void print_name(BIO *out, const char *title, const X509_NAME *nm,
1012 unsigned long lflags)
1019 BIO_puts(out, title);
1020 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1024 if (lflags == XN_FLAG_COMPAT) {
1025 buf = X509_NAME_oneline(nm, 0, 0);
1027 BIO_puts(out, "\n");
1031 BIO_puts(out, "\n");
1032 X509_NAME_print_ex(out, nm, indent, lflags);
1033 BIO_puts(out, "\n");
1037 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1038 int len, unsigned char *buffer)
1040 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1041 if (BN_is_zero(in)) {
1042 BIO_printf(out, "\n 0x00");
1046 l = BN_bn2bin(in, buffer);
1047 for (i = 0; i < l; i++) {
1048 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1050 BIO_printf(out, "0x%02X,", buffer[i]);
1052 BIO_printf(out, "0x%02X", buffer[i]);
1055 BIO_printf(out, "\n };\n");
1058 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1062 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1063 for (i = 0; i < len; i++) {
1065 BIO_printf(out, "\n ");
1067 BIO_printf(out, "0x%02X, ", d[i]);
1069 BIO_printf(out, "0x%02X", d[i]);
1071 BIO_printf(out, "\n};\n");
1074 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1075 const char *CApath, int noCApath,
1076 const char *CAstore, int noCAstore)
1078 X509_STORE *store = X509_STORE_new();
1079 X509_LOOKUP *lookup;
1080 OSSL_LIB_CTX *libctx = app_get0_libctx();
1081 const char *propq = app_get0_propq();
1086 if (CAfile != NULL || !noCAfile) {
1087 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1090 if (CAfile != NULL) {
1091 if (!X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM,
1093 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1097 X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT,
1102 if (CApath != NULL || !noCApath) {
1103 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1106 if (CApath != NULL) {
1107 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1108 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1112 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1116 if (CAstore != NULL || !noCAstore) {
1117 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1120 if (!X509_LOOKUP_add_store_ex(lookup, CAstore, libctx, propq)) {
1121 if (CAstore != NULL)
1122 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1130 ERR_print_errors(bio_err);
1131 X509_STORE_free(store);
1135 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1142 return OPENSSL_LH_strhash(n);
1145 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1146 const OPENSSL_CSTRING *b)
1148 const char *aa, *bb;
1150 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1151 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1152 return strcmp(aa, bb);
1155 static int index_name_qual(char **a)
1157 return (a[0][0] == 'V');
1160 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1162 return OPENSSL_LH_strhash(a[DB_name]);
1165 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1167 return strcmp(a[DB_name], b[DB_name]);
1170 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1171 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1172 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1173 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1176 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1181 ASN1_INTEGER *ai = NULL;
1183 ai = ASN1_INTEGER_new();
1187 in = BIO_new_file(serialfile, "r");
1195 if (ret == NULL || !rand_serial(ret, ai))
1196 BIO_printf(bio_err, "Out of memory\n");
1198 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1199 BIO_printf(bio_err, "Unable to load number from %s\n",
1203 ret = ASN1_INTEGER_to_BN(ai, NULL);
1205 BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1215 ERR_print_errors(bio_err);
1217 ASN1_INTEGER_free(ai);
1221 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1222 ASN1_INTEGER **retai)
1227 ASN1_INTEGER *ai = NULL;
1231 j = strlen(serialfile);
1233 j = strlen(serialfile) + strlen(suffix) + 1;
1235 BIO_printf(bio_err, "File name too long\n");
1240 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1242 #ifndef OPENSSL_SYS_VMS
1243 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1245 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1248 out = BIO_new_file(buf[0], "w");
1253 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1254 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1257 i2a_ASN1_INTEGER(out, ai);
1258 BIO_puts(out, "\n");
1266 ERR_print_errors(bio_err);
1268 ASN1_INTEGER_free(ai);
1272 int rotate_serial(const char *serialfile, const char *new_suffix,
1273 const char *old_suffix)
1278 i = strlen(serialfile) + strlen(old_suffix);
1279 j = strlen(serialfile) + strlen(new_suffix);
1282 if (j + 1 >= BSIZE) {
1283 BIO_printf(bio_err, "File name too long\n");
1286 #ifndef OPENSSL_SYS_VMS
1287 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1288 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1290 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1291 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1293 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1299 "Unable to rename %s to %s\n", serialfile, buf[1]);
1303 if (rename(buf[0], serialfile) < 0) {
1305 "Unable to rename %s to %s\n", buf[0], serialfile);
1307 rename(buf[1], serialfile);
1312 ERR_print_errors(bio_err);
1316 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1321 btmp = b == NULL ? BN_new() : b;
1325 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1327 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1340 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1342 CA_DB *retdb = NULL;
1343 TXT_DB *tmpdb = NULL;
1345 CONF *dbattr_conf = NULL;
1347 #ifndef OPENSSL_NO_POSIX_IO
1352 in = BIO_new_file(dbfile, "r");
1356 #ifndef OPENSSL_NO_POSIX_IO
1357 BIO_get_fp(in, &dbfp);
1358 if (fstat(fileno(dbfp), &dbst) == -1) {
1359 ERR_raise_data(ERR_LIB_SYS, errno,
1360 "calling fstat(%s)", dbfile);
1365 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1368 #ifndef OPENSSL_SYS_VMS
1369 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1371 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1373 dbattr_conf = app_load_config_quiet(buf);
1375 retdb = app_malloc(sizeof(*retdb), "new DB");
1379 retdb->attributes = *db_attr;
1381 retdb->attributes.unique_subject = 1;
1385 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1387 retdb->attributes.unique_subject = parse_yesno(p, 1);
1391 retdb->dbfname = OPENSSL_strdup(dbfile);
1392 #ifndef OPENSSL_NO_POSIX_IO
1397 ERR_print_errors(bio_err);
1398 NCONF_free(dbattr_conf);
1405 * Returns > 0 on success, <= 0 on error
1407 int index_index(CA_DB *db)
1409 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1410 LHASH_HASH_FN(index_serial),
1411 LHASH_COMP_FN(index_serial))) {
1413 "Error creating serial number index:(%ld,%ld,%ld)\n",
1414 db->db->error, db->db->arg1, db->db->arg2);
1418 if (db->attributes.unique_subject
1419 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1420 LHASH_HASH_FN(index_name),
1421 LHASH_COMP_FN(index_name))) {
1422 BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1423 db->db->error, db->db->arg1, db->db->arg2);
1428 ERR_print_errors(bio_err);
1432 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1438 j = strlen(dbfile) + strlen(suffix);
1439 if (j + 6 >= BSIZE) {
1440 BIO_printf(bio_err, "File name too long\n");
1443 #ifndef OPENSSL_SYS_VMS
1444 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1445 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1446 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1448 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1449 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1450 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1452 out = BIO_new_file(buf[0], "w");
1455 BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1458 j = TXT_DB_write(out, db->db);
1463 out = BIO_new_file(buf[1], "w");
1466 BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1469 BIO_printf(out, "unique_subject = %s\n",
1470 db->attributes.unique_subject ? "yes" : "no");
1475 ERR_print_errors(bio_err);
1479 int rotate_index(const char *dbfile, const char *new_suffix,
1480 const char *old_suffix)
1485 i = strlen(dbfile) + strlen(old_suffix);
1486 j = strlen(dbfile) + strlen(new_suffix);
1489 if (j + 6 >= BSIZE) {
1490 BIO_printf(bio_err, "File name too long\n");
1493 #ifndef OPENSSL_SYS_VMS
1494 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1495 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1496 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1497 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1498 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1500 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1501 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1502 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1503 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1504 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1506 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1511 BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1515 if (rename(buf[0], dbfile) < 0) {
1516 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1518 rename(buf[1], dbfile);
1521 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1526 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1528 rename(dbfile, buf[0]);
1529 rename(buf[1], dbfile);
1532 if (rename(buf[2], buf[4]) < 0) {
1533 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1535 rename(buf[3], buf[4]);
1536 rename(dbfile, buf[0]);
1537 rename(buf[1], dbfile);
1542 ERR_print_errors(bio_err);
1546 void free_index(CA_DB *db)
1549 TXT_DB_free(db->db);
1550 OPENSSL_free(db->dbfname);
1555 int parse_yesno(const char *str, int def)
1559 case 'f': /* false */
1560 case 'F': /* FALSE */
1565 case 't': /* true */
1566 case 'T': /* TRUE */
1577 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1578 * where + can be used instead of / to form multi-valued RDNs if canmulti
1579 * and characters may be escaped by \
1581 X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
1584 int nextismulti = 0;
1590 "%s: %s name is expected to be in the format "
1591 "/type0=value0/type1=value1/type2=... where characters may "
1592 "be escaped by \\. This name is not in that format: '%s'\n",
1593 opt_getprog(), desc, --cp);
1597 n = X509_NAME_new();
1599 BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
1602 work = OPENSSL_strdup(cp);
1604 BIO_printf(bio_err, "%s: Error copying %s name input\n",
1605 opt_getprog(), desc);
1609 while (*cp != '\0') {
1612 unsigned char *valstr;
1614 int ismulti = nextismulti;
1617 /* Collect the type */
1618 while (*cp != '\0' && *cp != '=')
1623 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1624 opt_getprog(), typestr, desc);
1629 /* Collect the value. */
1630 valstr = (unsigned char *)bp;
1631 for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
1632 /* unescaped '+' symbol string signals further member of multiRDN */
1633 if (canmulti && *cp == '+') {
1637 if (*cp == '\\' && *++cp == '\0') {
1639 "%s: Escape character at end of %s name string\n",
1640 opt_getprog(), desc);
1646 /* If not at EOS (must be + or /), move forward. */
1651 nid = OBJ_txt2nid(typestr);
1652 if (nid == NID_undef) {
1654 "%s: Skipping unknown %s name attribute \"%s\"\n",
1655 opt_getprog(), desc, typestr);
1658 "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
1661 if (*valstr == '\0') {
1663 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1664 opt_getprog(), desc, typestr);
1667 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1668 valstr, strlen((char *)valstr),
1669 -1, ismulti ? -1 : 0)) {
1670 ERR_print_errors(bio_err);
1672 "%s: Error adding %s name attribute \"/%s=%s\"\n",
1673 opt_getprog(), desc, typestr ,valstr);
1688 * Read whole contents of a BIO into an allocated memory buffer and return
1692 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1696 unsigned char tbuf[1024];
1698 mem = BIO_new(BIO_s_mem());
1702 if ((maxlen != -1) && maxlen < 1024)
1706 len = BIO_read(in, tbuf, len);
1713 if (BIO_write(mem, tbuf, len) != len) {
1722 ret = BIO_get_mem_data(mem, (char **)out);
1723 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1728 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1731 char *stmp, *vtmp = NULL;
1732 stmp = OPENSSL_strdup(value);
1735 vtmp = strchr(stmp, ':');
1740 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1745 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1747 X509_POLICY_NODE *node;
1750 BIO_printf(bio_err, "%s Policies:", name);
1752 BIO_puts(bio_err, "\n");
1753 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1754 node = sk_X509_POLICY_NODE_value(nodes, i);
1755 X509_POLICY_NODE_print(bio_err, node, 2);
1758 BIO_puts(bio_err, " <empty>\n");
1762 void policies_print(X509_STORE_CTX *ctx)
1764 X509_POLICY_TREE *tree;
1765 int explicit_policy;
1766 tree = X509_STORE_CTX_get0_policy_tree(ctx);
1767 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1769 BIO_printf(bio_err, "Require explicit Policy: %s\n",
1770 explicit_policy ? "True" : "False");
1772 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1773 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1777 * next_protos_parse parses a comma separated list of strings into a string
1778 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1779 * outlen: (output) set to the length of the resulting buffer on success.
1780 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1781 * in: a NUL terminated string like "abc,def,ghi"
1783 * returns: a malloc'd buffer or NULL on failure.
1785 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1789 size_t i, start = 0;
1793 if (len == 0 || len >= 65535)
1796 out = app_malloc(len + 1, "NPN buffer");
1797 for (i = 0; i <= len; ++i) {
1798 if (i == len || in[i] == ',') {
1800 * Zero-length ALPN elements are invalid on the wire, we could be
1801 * strict and reject the entire string, but just ignoring extra
1802 * commas seems harmless and more friendly.
1804 * Every comma we skip in this way puts the input buffer another
1805 * byte ahead of the output buffer, so all stores into the output
1806 * buffer need to be decremented by the number commas skipped.
1813 if (i - start > 255) {
1817 out[start-skipped] = (unsigned char)(i - start);
1820 out[i + 1 - skipped] = in[i];
1824 if (len <= skipped) {
1829 *outlen = len + 1 - skipped;
1833 void print_cert_checks(BIO *bio, X509 *x,
1834 const char *checkhost,
1835 const char *checkemail, const char *checkip)
1840 BIO_printf(bio, "Hostname %s does%s match certificate\n",
1842 X509_check_host(x, checkhost, 0, 0, NULL) == 1
1847 BIO_printf(bio, "Email %s does%s match certificate\n",
1848 checkemail, X509_check_email(x, checkemail, 0, 0)
1853 BIO_printf(bio, "IP %s does%s match certificate\n",
1854 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1858 /* Get first http URL from a DIST_POINT structure */
1860 static const char *get_dp_url(DIST_POINT *dp)
1862 GENERAL_NAMES *gens;
1866 if (!dp->distpoint || dp->distpoint->type != 0)
1868 gens = dp->distpoint->name.fullname;
1869 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1870 gen = sk_GENERAL_NAME_value(gens, i);
1871 uri = GENERAL_NAME_get0_value(gen, >ype);
1872 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1873 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
1874 if (strncmp(uptr, "http://", 7) == 0)
1882 * Look through a CRLDP structure and attempt to find an http URL to
1883 * downloads a CRL from.
1886 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1889 const char *urlptr = NULL;
1890 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1891 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1892 urlptr = get_dp_url(dp);
1894 return load_crl(urlptr, FORMAT_HTTP, "CRL via CDP");
1900 * Example of downloading CRLs from CRLDP:
1901 * not usable for real world as it always downloads and doesn't cache anything.
1904 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
1905 const X509_NAME *nm)
1908 STACK_OF(X509_CRL) *crls = NULL;
1910 STACK_OF(DIST_POINT) *crldp;
1912 crls = sk_X509_CRL_new_null();
1915 x = X509_STORE_CTX_get_current_cert(ctx);
1916 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
1917 crl = load_crl_crldp(crldp);
1918 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1920 sk_X509_CRL_free(crls);
1923 sk_X509_CRL_push(crls, crl);
1924 /* Try to download delta CRL */
1925 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
1926 crl = load_crl_crldp(crldp);
1927 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1929 sk_X509_CRL_push(crls, crl);
1933 void store_setup_crl_download(X509_STORE *st)
1935 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
1938 #ifndef OPENSSL_NO_SOCK
1939 static const char *tls_error_hint(void)
1941 unsigned long err = ERR_peek_error();
1943 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
1944 err = ERR_peek_last_error();
1945 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
1948 switch (ERR_GET_REASON(err)) {
1949 case SSL_R_WRONG_VERSION_NUMBER:
1950 return "The server does not support (a suitable version of) TLS";
1951 case SSL_R_UNKNOWN_PROTOCOL:
1952 return "The server does not support HTTPS";
1953 case SSL_R_CERTIFICATE_VERIFY_FAILED:
1954 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
1955 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
1956 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
1957 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
1958 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
1959 default: /* no error or no hint available for error */
1964 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
1965 BIO *app_http_tls_cb(BIO *hbio, void *arg, int connect, int detail)
1967 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
1968 SSL_CTX *ssl_ctx = info->ssl_ctx;
1972 if (connect && detail) { /* connecting with TLS */
1973 if ((info->use_proxy
1974 && !OSSL_HTTP_proxy_connect(hbio, info->server, info->port,
1975 NULL, NULL, /* no proxy credentials */
1976 info->timeout, bio_err, opt_getprog()))
1977 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
1980 if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
1985 SSL_set_tlsext_host_name(ssl, info->server);
1987 SSL_set_connect_state(ssl);
1988 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
1990 hbio = BIO_push(sbio, hbio);
1991 } else if (!connect && !detail) { /* disconnecting after error */
1992 const char *hint = tls_error_hint();
1994 ERR_add_error_data(2, " : ", hint);
1996 * If we pop sbio and BIO_free() it this may lead to libssl double free.
1997 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2003 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2004 const char *no_proxy, SSL_CTX *ssl_ctx,
2005 const STACK_OF(CONF_VALUE) *headers,
2006 long timeout, const char *expected_content_type,
2007 const ASN1_ITEM *it)
2009 APP_HTTP_TLS_INFO info;
2013 ASN1_VALUE *resp = NULL;
2015 if (url == NULL || it == NULL) {
2016 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2020 if (!OSSL_HTTP_parse_url(url, &server, &port, NULL, NULL, &use_ssl))
2022 if (use_ssl && ssl_ctx == NULL) {
2023 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2024 ERR_add_error_data(1, "missing SSL_CTX");
2028 info.server = server;
2030 info.use_proxy = proxy != NULL;
2031 info.timeout = timeout;
2032 info.ssl_ctx = ssl_ctx;
2033 resp = OSSL_HTTP_get_asn1(url, proxy, no_proxy,
2034 NULL, NULL, app_http_tls_cb, &info,
2035 headers, 0 /* maxline */, 0 /* max_resp_len */,
2036 timeout, expected_content_type, it);
2038 OPENSSL_free(server);
2044 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2045 const char *path, const char *proxy,
2046 const char *no_proxy, SSL_CTX *ssl_ctx,
2047 const STACK_OF(CONF_VALUE) *headers,
2048 const char *content_type,
2049 ASN1_VALUE *req, const ASN1_ITEM *req_it,
2050 long timeout, const ASN1_ITEM *rsp_it)
2052 APP_HTTP_TLS_INFO info;
2056 info.use_proxy = proxy != NULL;
2057 info.timeout = timeout;
2058 info.ssl_ctx = ssl_ctx;
2059 return OSSL_HTTP_post_asn1(host, port, path, ssl_ctx != NULL,
2061 NULL, NULL, app_http_tls_cb, &info,
2062 headers, content_type, req, req_it,
2064 0 /* max_resp_len */, timeout, NULL, rsp_it);
2070 * Platform-specific sections
2075 # define fileno(a) (int)_fileno(a)
2078 # include <windows.h>
2081 static int WIN32_rename(const char *from, const char *to)
2083 TCHAR *tfrom = NULL, *tto;
2087 if (sizeof(TCHAR) == 1) {
2088 tfrom = (TCHAR *)from;
2090 } else { /* UNICODE path */
2092 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2093 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2097 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2098 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2100 for (i = 0; i < flen; i++)
2101 tfrom[i] = (TCHAR)from[i];
2102 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2103 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2105 for (i = 0; i < tlen; i++)
2106 tto[i] = (TCHAR)to[i];
2109 if (MoveFile(tfrom, tto))
2111 err = GetLastError();
2112 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2113 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2115 err = GetLastError();
2117 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2119 else if (err == ERROR_ACCESS_DENIED)
2122 errno = EINVAL; /* we could map more codes... */
2126 if (tfrom != NULL && tfrom != (TCHAR *)from)
2132 /* app_tminterval section */
2134 double app_tminterval(int stop, int usertime)
2138 static ULARGE_INTEGER tmstart;
2139 static int warning = 1;
2140 # ifdef _WIN32_WINNT
2141 static HANDLE proc = NULL;
2145 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2146 GetCurrentProcessId());
2148 proc = (HANDLE) - 1;
2151 if (usertime && proc != (HANDLE) - 1) {
2153 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2159 if (usertime && warning) {
2160 BIO_printf(bio_err, "To get meaningful results, run "
2161 "this program on idle system.\n");
2164 GetSystemTime(&systime);
2165 SystemTimeToFileTime(&systime, &now);
2168 if (stop == TM_START) {
2169 tmstart.u.LowPart = now.dwLowDateTime;
2170 tmstart.u.HighPart = now.dwHighDateTime;
2172 ULARGE_INTEGER tmstop;
2174 tmstop.u.LowPart = now.dwLowDateTime;
2175 tmstop.u.HighPart = now.dwHighDateTime;
2177 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2182 #elif defined(OPENSSL_SYS_VXWORKS)
2185 double app_tminterval(int stop, int usertime)
2188 # ifdef CLOCK_REALTIME
2189 static struct timespec tmstart;
2190 struct timespec now;
2192 static unsigned long tmstart;
2195 static int warning = 1;
2197 if (usertime && warning) {
2198 BIO_printf(bio_err, "To get meaningful results, run "
2199 "this program on idle system.\n");
2202 # ifdef CLOCK_REALTIME
2203 clock_gettime(CLOCK_REALTIME, &now);
2204 if (stop == TM_START)
2207 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2208 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2211 if (stop == TM_START)
2214 ret = (now - tmstart) / (double)sysClkRateGet();
2219 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2220 # include <sys/times.h>
2222 double app_tminterval(int stop, int usertime)
2226 clock_t now = times(&rus);
2227 static clock_t tmstart;
2230 now = rus.tms_utime;
2232 if (stop == TM_START) {
2235 long int tck = sysconf(_SC_CLK_TCK);
2236 ret = (now - tmstart) / (double)tck;
2243 # include <sys/time.h>
2244 # include <sys/resource.h>
2246 double app_tminterval(int stop, int usertime)
2251 static struct timeval tmstart;
2254 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2256 gettimeofday(&now, NULL);
2258 if (stop == TM_START)
2261 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2262 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2268 int app_access(const char* name, int flag)
2271 return _access(name, flag);
2273 return access(name, flag);
2277 int app_isdir(const char *name)
2279 return opt_isdir(name);
2282 /* raw_read|write section */
2284 # include "vms_term_sock.h"
2285 static int stdin_sock = -1;
2287 static void close_stdin_sock(void)
2289 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2292 int fileno_stdin(void)
2294 if (stdin_sock == -1) {
2295 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2296 atexit(close_stdin_sock);
2302 int fileno_stdin(void)
2304 return fileno(stdin);
2308 int fileno_stdout(void)
2310 return fileno(stdout);
2313 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2314 int raw_read_stdin(void *buf, int siz)
2317 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2322 #elif defined(__VMS)
2323 # include <sys/socket.h>
2325 int raw_read_stdin(void *buf, int siz)
2327 return recv(fileno_stdin(), buf, siz, 0);
2330 # if defined(__TANDEM)
2331 # if defined(OPENSSL_TANDEM_FLOSS)
2332 # include <floss.h(floss_read)>
2335 int raw_read_stdin(void *buf, int siz)
2337 return read(fileno_stdin(), buf, siz);
2341 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2342 int raw_write_stdout(const void *buf, int siz)
2345 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2350 #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
2351 # if defined(__TANDEM)
2352 # if defined(OPENSSL_TANDEM_FLOSS)
2353 # include <floss.h(floss_write)>
2356 int raw_write_stdout(const void *buf,int siz)
2358 return write(fileno(stdout),(void*)buf,siz);
2361 # if defined(__TANDEM)
2362 # if defined(OPENSSL_TANDEM_FLOSS)
2363 # include <floss.h(floss_write)>
2366 int raw_write_stdout(const void *buf, int siz)
2368 return write(fileno_stdout(), buf, siz);
2373 * Centralized handling of input and output files with format specification
2374 * The format is meant to show what the input and output is supposed to be,
2375 * and is therefore a show of intent more than anything else. However, it
2376 * does impact behavior on some platforms, such as differentiating between
2377 * text and binary input/output on non-Unix platforms
2379 BIO *dup_bio_in(int format)
2381 return BIO_new_fp(stdin,
2382 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2385 BIO *dup_bio_out(int format)
2387 BIO *b = BIO_new_fp(stdout,
2388 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2389 void *prefix = NULL;
2391 #ifdef OPENSSL_SYS_VMS
2392 if (FMT_istext(format))
2393 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2396 if (FMT_istext(format)
2397 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2398 b = BIO_push(BIO_new(BIO_f_prefix()), b);
2399 BIO_set_prefix(b, prefix);
2405 BIO *dup_bio_err(int format)
2407 BIO *b = BIO_new_fp(stderr,
2408 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2409 #ifdef OPENSSL_SYS_VMS
2410 if (FMT_istext(format))
2411 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2416 void unbuffer(FILE *fp)
2419 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2420 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2421 * However, we trust that the C RTL will never give us a FILE pointer
2422 * above the first 4 GB of memory, so we simply turn off the warning
2425 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2426 # pragma environment save
2427 # pragma message disable maylosedata2
2430 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2431 # pragma environment restore
2435 static const char *modestr(char mode, int format)
2437 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2441 return FMT_istext(format) ? "a" : "ab";
2443 return FMT_istext(format) ? "r" : "rb";
2445 return FMT_istext(format) ? "w" : "wb";
2447 /* The assert above should make sure we never reach this point */
2451 static const char *modeverb(char mode)
2461 return "(doing something)";
2465 * Open a file for writing, owner-read-only.
2467 BIO *bio_open_owner(const char *filename, int format, int private)
2471 int fd = -1, bflags, mode, textmode;
2473 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2474 return bio_open_default(filename, 'w', format);
2483 textmode = FMT_istext(format);
2487 #elif defined(_O_BINARY)
2492 #ifdef OPENSSL_SYS_VMS
2493 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2494 * it still needs to know that we're going binary, or fdopen()
2495 * will fail with "invalid argument"... so we tell VMS what the
2499 fd = open(filename, mode, 0600, "ctx=bin");
2502 fd = open(filename, mode, 0600);
2505 fp = fdopen(fd, modestr('w', format));
2510 bflags |= BIO_FP_TEXT;
2511 b = BIO_new_fp(fp, bflags);
2516 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2517 opt_getprog(), filename, strerror(errno));
2518 ERR_print_errors(bio_err);
2519 /* If we have fp, then fdopen took over fd, so don't close both. */
2527 static BIO *bio_open_default_(const char *filename, char mode, int format,
2532 if (filename == NULL || strcmp(filename, "-") == 0) {
2533 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2541 "Can't open %s, %s\n",
2542 mode == 'r' ? "stdin" : "stdout", strerror(errno));
2544 ret = BIO_new_file(filename, modestr(mode, format));
2552 "Can't open %s for %s, %s\n",
2553 filename, modeverb(mode), strerror(errno));
2555 ERR_print_errors(bio_err);
2559 BIO *bio_open_default(const char *filename, char mode, int format)
2561 return bio_open_default_(filename, mode, format, 0);
2564 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2566 return bio_open_default_(filename, mode, format, 1);
2569 void wait_for_async(SSL *s)
2571 /* On Windows select only works for sockets, so we simply don't wait */
2572 #ifndef OPENSSL_SYS_WINDOWS
2579 if (!SSL_get_all_async_fds(s, NULL, &numfds))
2583 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2584 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2590 for (i = 0; i < numfds; i++) {
2591 if (width <= (int)fds[i])
2592 width = (int)fds[i] + 1;
2593 openssl_fdset((int)fds[i], &asyncfds);
2595 select(width, (void *)&asyncfds, NULL, NULL, NULL);
2600 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2601 #if defined(OPENSSL_SYS_MSDOS)
2602 int has_stdin_waiting(void)
2604 # if defined(OPENSSL_SYS_WINDOWS)
2605 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2607 INPUT_RECORD inputrec;
2611 if (inhand == INVALID_HANDLE_VALUE) {
2615 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2617 /* Probably redirected input? _kbhit() does not work in this case */
2628 /* Corrupt a signature by modifying final byte */
2629 void corrupt_signature(const ASN1_STRING *signature)
2631 unsigned char *s = signature->data;
2632 s[signature->length - 1] ^= 0x1;
2635 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2638 if (startdate == NULL || strcmp(startdate, "today") == 0) {
2639 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2642 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2645 if (enddate == NULL) {
2646 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2649 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2655 int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate)
2658 ASN1_TIME *tm = ASN1_TIME_new();
2663 if (lastupdate == NULL) {
2664 if (X509_gmtime_adj(tm, 0) == NULL)
2667 if (!ASN1_TIME_set_string_X509(tm, lastupdate))
2671 if (!X509_CRL_set1_lastUpdate(crl, tm))
2680 int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
2681 long days, long hours, long secs)
2684 ASN1_TIME *tm = ASN1_TIME_new();
2689 if (nextupdate == NULL) {
2690 if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL)
2693 if (!ASN1_TIME_set_string_X509(tm, nextupdate))
2697 if (!X509_CRL_set1_nextUpdate(crl, tm))
2706 void make_uppercase(char *string)
2710 for (i = 0; string[i] != '\0'; i++)
2711 string[i] = toupper((unsigned char)string[i]);
2714 int opt_printf_stderr(const char *fmt, ...)
2720 ret = BIO_vprintf(bio_err, fmt, ap);
2725 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
2726 const OSSL_PARAM *paramdefs)
2728 OSSL_PARAM *params = NULL;
2729 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
2731 char *opt = "", *stmp, *vtmp = NULL;
2737 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
2741 for (params_n = 0; params_n < sz; params_n++) {
2742 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
2743 if ((stmp = OPENSSL_strdup(opt)) == NULL
2744 || (vtmp = strchr(stmp, ':')) == NULL)
2746 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2748 /* Skip over the separator so that vmtp points to the value */
2750 if (!OSSL_PARAM_allocate_from_text(¶ms[params_n], paramdefs,
2751 stmp, vtmp, strlen(vtmp), &found))
2755 params[params_n] = OSSL_PARAM_construct_end();
2759 BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
2761 ERR_print_errors(bio_err);
2762 app_params_free(params);
2766 void app_params_free(OSSL_PARAM *params)
2770 if (params != NULL) {
2771 for (i = 0; params[i].key != NULL; ++i)
2772 OPENSSL_free(params[i].data);
2773 OPENSSL_free(params);