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 /* We need to use some engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
13 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
15 * On VMS, you need to define this to get the declaration of fileno(). The
16 * value 2 is to make sure no function defined in POSIX-2 is left undefined.
18 # define _POSIX_C_SOURCE 2
24 #include <sys/types.h>
25 #ifndef OPENSSL_NO_POSIX_IO
26 # include <sys/stat.h>
31 #include <openssl/err.h>
32 #include <openssl/x509.h>
33 #include <openssl/x509v3.h>
34 #include <openssl/pem.h>
35 #include <openssl/store.h>
36 #include <openssl/pkcs12.h>
37 #include <openssl/ui.h>
38 #include <openssl/safestack.h>
39 #ifndef OPENSSL_NO_ENGINE
40 # include <openssl/engine.h>
42 #ifndef OPENSSL_NO_RSA
43 # include <openssl/rsa.h>
45 #include <openssl/bn.h>
46 #include <openssl/ssl.h>
50 static int WIN32_rename(const char *from, const char *to);
51 # define rename(from,to) WIN32_rename((from),(to))
54 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
58 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32)
62 #define PASS_SOURCE_SIZE_MAX 4
65 DEFINE_STACK_OF(CONF_VALUE)
67 DEFINE_STACK_OF(X509_CRL)
68 DEFINE_STACK_OF(X509_INFO)
69 DEFINE_STACK_OF(X509_EXTENSION)
70 DEFINE_STACK_OF(X509_POLICY_NODE)
71 DEFINE_STACK_OF(GENERAL_NAME)
72 DEFINE_STACK_OF(DIST_POINT)
73 DEFINE_STACK_OF_STRING()
81 static OPENSSL_CTX *app_libctx = NULL;
83 static int set_table_opts(unsigned long *flags, const char *arg,
84 const NAME_EX_TBL * in_tbl);
85 static int set_multi_opts(unsigned long *flags, const char *arg,
86 const NAME_EX_TBL * in_tbl);
88 int app_init(long mesgwin);
90 int chopup_args(ARGS *arg, char *buf)
93 char c = '\0', *p = NULL;
98 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
102 /* Skip whitespace. */
103 while (*p && isspace(_UC(*p)))
108 /* The start of something good :-) */
109 if (arg->argc >= arg->size) {
112 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
117 quoted = *p == '\'' || *p == '"';
120 arg->argv[arg->argc++] = p;
122 /* now look for the end of this */
124 while (*p && *p != c)
128 while (*p && !isspace(_UC(*p)))
134 arg->argv[arg->argc] = NULL;
139 int app_init(long mesgwin)
145 int ctx_set_verify_locations(SSL_CTX *ctx,
146 const char *CAfile, int noCAfile,
147 const char *CApath, int noCApath,
148 const char *CAstore, int noCAstore)
150 if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
151 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
153 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
155 if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
161 if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
163 if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
165 if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
170 #ifndef OPENSSL_NO_CT
172 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
175 return SSL_CTX_set_default_ctlog_list_file(ctx);
177 return SSL_CTX_set_ctlog_list_file(ctx, path);
182 static unsigned long nmflag = 0;
183 static char nmflag_set = 0;
185 int set_nameopt(const char *arg)
187 int ret = set_name_ex(&nmflag, arg);
195 unsigned long get_nameopt(void)
197 return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
200 int dump_cert_text(BIO *out, X509 *x)
202 print_name(out, "subject=", X509_get_subject_name(x), get_nameopt());
204 print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
210 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
212 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
216 static char *app_get_pass(const char *arg, int keepbio);
218 char *get_passwd(const char *pass, const char *desc)
224 if (!app_passwd(pass, NULL, &result, NULL))
225 BIO_printf(bio_err, "Error getting password for %s\n", desc);
226 if (pass != NULL && result == NULL) {
228 "Trying plain input string (better precede with 'pass:')\n");
229 result = OPENSSL_strdup(pass);
231 BIO_printf(bio_err, "Out of memory getting password for %s\n", desc);
236 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
238 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
241 *pass1 = app_get_pass(arg1, same);
244 } else if (pass1 != NULL) {
248 *pass2 = app_get_pass(arg2, same ? 2 : 0);
251 } else if (pass2 != NULL) {
257 static char *app_get_pass(const char *arg, int keepbio)
259 static BIO *pwdbio = NULL;
260 char *tmp, tpass[APP_PASS_LEN];
263 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
264 if (strncmp(arg, "pass:", 5) == 0)
265 return OPENSSL_strdup(arg + 5);
266 if (strncmp(arg, "env:", 4) == 0) {
267 tmp = getenv(arg + 4);
269 BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
272 return OPENSSL_strdup(tmp);
274 if (!keepbio || pwdbio == NULL) {
275 if (strncmp(arg, "file:", 5) == 0) {
276 pwdbio = BIO_new_file(arg + 5, "r");
277 if (pwdbio == NULL) {
278 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
283 * Under _WIN32, which covers even Win64 and CE, file
284 * descriptors referenced by BIO_s_fd are not inherited
285 * by child process and therefore below is not an option.
286 * It could have been an option if bss_fd.c was operating
287 * on real Windows descriptors, such as those obtained
290 } else if (strncmp(arg, "fd:", 3) == 0) {
294 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
295 if ((i < 0) || !pwdbio) {
296 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
300 * Can't do BIO_gets on an fd BIO so add a buffering BIO
302 btmp = BIO_new(BIO_f_buffer());
303 pwdbio = BIO_push(btmp, pwdbio);
305 } else if (strcmp(arg, "stdin") == 0) {
306 pwdbio = dup_bio_in(FORMAT_TEXT);
307 if (pwdbio == NULL) {
308 BIO_printf(bio_err, "Can't open BIO for stdin\n");
312 /* argument syntax error; do not reveal too much about arg */
313 tmp = strchr(arg, ':');
314 if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
316 "Invalid password argument, missing ':' within the first %d chars\n",
317 PASS_SOURCE_SIZE_MAX + 1);
320 "Invalid password argument, starting with \"%.*s\"\n",
321 (int)(tmp - arg + 1), arg);
325 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
327 BIO_free_all(pwdbio);
331 BIO_printf(bio_err, "Error reading password from BIO\n");
334 tmp = strchr(tpass, '\n');
337 return OPENSSL_strdup(tpass);
340 OPENSSL_CTX *app_get0_libctx(void)
345 /* TODO(3.0): Make this an environment variable if required */
346 const char *app_get0_propq(void)
351 OPENSSL_CTX *app_create_libctx(void)
354 * Load the NULL provider into the default library context and create a
355 * library context which will then be used for any OPT_PROV options.
357 if (app_libctx == NULL) {
359 if (!app_provider_load(NULL, "null")) {
360 BIO_puts(bio_err, "Failed to create null provider\n");
363 app_libctx = OPENSSL_CTX_new();
365 if (app_libctx == NULL)
366 BIO_puts(bio_err, "Failed to create library context\n");
370 CONF *app_load_config_bio(BIO *in, const char *filename)
376 conf = NCONF_new_with_libctx(app_libctx, NULL);
377 i = NCONF_load_bio(conf, in, &errorline);
381 if (errorline <= 0) {
382 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
384 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
387 if (filename != NULL)
388 BIO_printf(bio_err, "config file \"%s\"\n", filename);
390 BIO_printf(bio_err, "config input");
392 CONF_modules_load(conf, NULL, 0);
397 CONF *app_load_config(const char *filename)
402 in = bio_open_default(filename, 'r', FORMAT_TEXT);
406 conf = app_load_config_bio(in, filename);
411 CONF *app_load_config_quiet(const char *filename)
416 in = bio_open_default_quiet(filename, 'r', FORMAT_TEXT);
420 conf = app_load_config_bio(in, filename);
425 int app_load_modules(const CONF *config)
427 CONF *to_free = NULL;
430 config = to_free = app_load_config_quiet(default_config_file);
434 if (CONF_modules_load(config, NULL, 0) <= 0) {
435 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
436 ERR_print_errors(bio_err);
444 int add_oid_section(CONF *conf)
447 STACK_OF(CONF_VALUE) *sktmp;
451 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
455 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
456 BIO_printf(bio_err, "problem loading oid section %s\n", p);
459 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
460 cnf = sk_CONF_VALUE_value(sktmp, i);
461 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
462 BIO_printf(bio_err, "problem creating object %s=%s\n",
463 cnf->name, cnf->value);
470 CONF *app_load_config_modules(const char *configfile)
474 if (configfile != NULL) {
475 BIO_printf(bio_err, "Using configuration from %s\n", configfile);
477 if ((conf = app_load_config(configfile)) == NULL)
479 if (configfile != default_config_file && !app_load_modules(conf)) {
487 X509 *load_cert_pass(const char *uri, int maybe_stdin,
488 const char *pass, const char *desc)
493 desc = "certificate";
494 (void)load_key_cert_crl(uri, maybe_stdin, pass, desc, NULL, &cert, NULL);
496 BIO_printf(bio_err, "Unable to load %s\n", desc);
497 ERR_print_errors(bio_err);
502 /* the format parameter is meanwhile not needed anymore and thus ignored */
503 X509 *load_cert(const char *uri, int format, const char *desc)
505 return load_cert_pass(uri, 1, NULL, desc);
508 /* the format parameter is meanwhile not needed anymore and thus ignored */
509 X509_CRL *load_crl(const char *uri, int format, const char *desc)
511 X509_CRL *crl = NULL;
515 (void)load_key_cert_crl(uri, 0, NULL, desc, NULL, NULL, &crl);
517 BIO_printf(bio_err, "Unable to load %s\n", desc);
518 ERR_print_errors(bio_err);
523 X509_REQ *load_csr(const char *file, int format, const char *desc)
525 X509_REQ *req = NULL;
530 in = bio_open_default(file, 'r', format);
534 if (format == FORMAT_ASN1)
535 req = d2i_X509_REQ_bio(in, NULL);
536 else if (format == FORMAT_PEM)
537 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
539 print_format_error(format, OPT_FMT_PEMDER);
543 BIO_printf(bio_err, "Unable to load %s\n", desc);
544 ERR_print_errors(bio_err);
550 void cleanse(char *str)
553 OPENSSL_cleanse(str, strlen(str));
556 void clear_free(char *str)
559 OPENSSL_clear_free(str, strlen(str));
562 EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
563 const char *pass, ENGINE *e, const char *desc)
565 EVP_PKEY *pkey = NULL;
568 desc = "private key";
570 if (format == FORMAT_ENGINE) {
572 BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
574 #ifndef OPENSSL_NO_ENGINE
577 cb_data.password = pass;
578 cb_data.prompt_info = uri;
579 if (ENGINE_init(e)) {
580 pkey = ENGINE_load_private_key(e, uri,
581 (UI_METHOD *)get_ui_method(),
586 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
587 ERR_print_errors(bio_err);
590 BIO_printf(bio_err, "Engines not supported for loading %s\n", desc);
594 (void)load_key_cert_crl(uri, may_stdin, pass, desc, &pkey, NULL, NULL);
598 BIO_printf(bio_err, "Unable to load %s\n", desc);
599 ERR_print_errors(bio_err);
604 EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
605 const char *pass, ENGINE *e, const char *desc)
607 EVP_PKEY *pkey = NULL;
612 if (format == FORMAT_ENGINE) {
614 BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
616 #ifndef OPENSSL_NO_ENGINE
619 cb_data.password = pass;
620 cb_data.prompt_info = uri;
621 pkey = ENGINE_load_public_key(e, uri, (UI_METHOD *)get_ui_method(),
624 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
625 ERR_print_errors(bio_err);
628 BIO_printf(bio_err, "Engines not supported for loading %s\n", desc);
632 (void)load_key_cert_crl(uri, maybe_stdin, pass, desc, &pkey,
636 BIO_printf(bio_err, "Unable to load %s\n", desc);
637 ERR_print_errors(bio_err);
642 static int load_certs_crls(const char *file, int format,
643 const char *pass, const char *desc,
644 STACK_OF(X509) **pcerts,
645 STACK_OF(X509_CRL) **pcrls)
649 STACK_OF(X509_INFO) *xis = NULL;
654 cb_data.password = pass;
655 cb_data.prompt_info = file;
657 if (format != FORMAT_PEM) {
658 BIO_printf(bio_err, "Bad input format specified for %s\n", desc);
662 bio = bio_open_default(file, 'r', FORMAT_PEM);
666 xis = PEM_X509_INFO_read_bio_with_libctx(bio, NULL,
667 (pem_password_cb *)password_callback,
674 if (pcerts != NULL && *pcerts == NULL) {
675 *pcerts = sk_X509_new_null();
680 if (pcrls != NULL && *pcrls == NULL) {
681 *pcrls = sk_X509_CRL_new_null();
686 for (i = 0; i < sk_X509_INFO_num(xis); i++) {
687 xi = sk_X509_INFO_value(xis, i);
688 if (xi->x509 != NULL && pcerts != NULL) {
689 if (!sk_X509_push(*pcerts, xi->x509))
693 if (xi->crl != NULL && pcrls != NULL) {
694 if (!sk_X509_CRL_push(*pcrls, xi->crl))
700 if (pcerts != NULL && sk_X509_num(*pcerts) > 0)
703 if (pcrls != NULL && sk_X509_CRL_num(*pcrls) > 0)
708 sk_X509_INFO_pop_free(xis, X509_INFO_free);
711 if (pcerts != NULL) {
712 sk_X509_pop_free(*pcerts, X509_free);
716 sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
719 BIO_printf(bio_err, "Unable to load %s\n", desc != NULL ? desc :
720 pcerts != NULL ? "certificates" : "CRLs");
725 void app_bail_out(char *fmt, ...)
730 BIO_vprintf(bio_err, fmt, args);
732 ERR_print_errors(bio_err);
736 void* app_malloc(int sz, const char *what)
738 void *vp = OPENSSL_malloc(sz);
741 app_bail_out("%s: Could not allocate %d bytes for %s\n",
742 opt_getprog(), sz, what);
747 * Initialize or extend, if *certs != NULL, a certificate stack.
749 int load_certs(const char *file, STACK_OF(X509) **certs, int format,
750 const char *pass, const char *desc)
752 return load_certs_crls(file, format, pass, desc, certs, NULL);
756 * Initialize or extend, if *crls != NULL, a certificate stack.
758 int load_crls(const char *file, STACK_OF(X509_CRL) **crls, int format,
759 const char *pass, const char *desc)
761 return load_certs_crls(file, format, pass, desc, NULL, crls);
765 * Load those types of credentials for which the result pointer is not NULL.
766 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
767 * For each type the first credential found in the store is loaded.
768 * May yield partial result even if rv == 0.
770 int load_key_cert_crl(const char *uri, int maybe_stdin,
771 const char *pass, const char *desc,
772 EVP_PKEY **ppkey, X509 **pcert, X509_CRL **pcrl)
775 OSSL_STORE_CTX *ctx = NULL;
776 OPENSSL_CTX *libctx = app_get0_libctx();
777 const char *propq = app_get0_propq();
779 /* TODO make use of the engine reference 'eng' when loading pkeys */
789 desc = "key/certificate/CRL";
790 uidata.password = pass;
791 uidata.prompt_info = uri;
797 BIO_printf(bio_err, "No filename or uri specified for loading %s\n",
802 bio = BIO_new_fp(stdin, 0);
804 ctx = OSSL_STORE_attach(bio, "file", libctx, propq,
805 get_ui_method(), &uidata, NULL, NULL);
808 ctx = OSSL_STORE_open_with_libctx(uri, libctx, propq, get_ui_method(),
809 &uidata, NULL, NULL);
812 BIO_printf(bio_err, "Could not open file or uri %s for loading %s\n",
818 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
819 int type = info == NULL ? 0 : OSSL_STORE_INFO_get_type(info);
820 const char *infostr =
821 info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
825 if (OSSL_STORE_eof(ctx))
831 case OSSL_STORE_INFO_PKEY:
832 if (ppkey != NULL && *ppkey == NULL)
833 err = ((*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) == NULL);
835 case OSSL_STORE_INFO_CERT:
836 if (pcert != NULL && *pcert == NULL)
837 err = ((*pcert = OSSL_STORE_INFO_get1_CERT(info)) == NULL);
839 case OSSL_STORE_INFO_CRL:
840 if (pcrl != NULL && *pcrl == NULL)
841 err = ((*pcrl = OSSL_STORE_INFO_get1_CRL(info)) == NULL);
844 /* skip any other type */
847 OSSL_STORE_INFO_free(info);
849 BIO_printf(bio_err, "Could not read %s of %s from %s\n",
856 OSSL_STORE_close(ctx);
858 ERR_print_errors(bio_err);
863 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
864 /* Return error for unknown extensions */
865 #define X509V3_EXT_DEFAULT 0
866 /* Print error for unknown extensions */
867 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
868 /* ASN1 parse unknown extensions */
869 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
870 /* BIO_dump unknown extensions */
871 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
873 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
874 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
876 int set_cert_ex(unsigned long *flags, const char *arg)
878 static const NAME_EX_TBL cert_tbl[] = {
879 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
880 {"ca_default", X509_FLAG_CA, 0xffffffffl},
881 {"no_header", X509_FLAG_NO_HEADER, 0},
882 {"no_version", X509_FLAG_NO_VERSION, 0},
883 {"no_serial", X509_FLAG_NO_SERIAL, 0},
884 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
885 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
886 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
887 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
888 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
889 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
890 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
891 {"no_aux", X509_FLAG_NO_AUX, 0},
892 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
893 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
894 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
895 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
896 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
899 return set_multi_opts(flags, arg, cert_tbl);
902 int set_name_ex(unsigned long *flags, const char *arg)
904 static const NAME_EX_TBL ex_tbl[] = {
905 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
906 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
907 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
908 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
909 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
910 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
911 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
912 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
913 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
914 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
915 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
916 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
917 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
918 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
919 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
920 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
921 {"dn_rev", XN_FLAG_DN_REV, 0},
922 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
923 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
924 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
925 {"align", XN_FLAG_FN_ALIGN, 0},
926 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
927 {"space_eq", XN_FLAG_SPC_EQ, 0},
928 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
929 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
930 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
931 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
932 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
935 if (set_multi_opts(flags, arg, ex_tbl) == 0)
937 if (*flags != XN_FLAG_COMPAT
938 && (*flags & XN_FLAG_SEP_MASK) == 0)
939 *flags |= XN_FLAG_SEP_CPLUS_SPC;
943 int set_ext_copy(int *copy_type, const char *arg)
945 if (strcasecmp(arg, "none") == 0)
946 *copy_type = EXT_COPY_NONE;
947 else if (strcasecmp(arg, "copy") == 0)
948 *copy_type = EXT_COPY_ADD;
949 else if (strcasecmp(arg, "copyall") == 0)
950 *copy_type = EXT_COPY_ALL;
956 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
958 STACK_OF(X509_EXTENSION) *exts = NULL;
959 X509_EXTENSION *ext, *tmpext;
962 if (!x || !req || (copy_type == EXT_COPY_NONE))
964 exts = X509_REQ_get_extensions(req);
966 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
967 ext = sk_X509_EXTENSION_value(exts, i);
968 obj = X509_EXTENSION_get_object(ext);
969 idx = X509_get_ext_by_OBJ(x, obj, -1);
970 /* Does extension exist? */
972 /* If normal copy don't override existing extension */
973 if (copy_type == EXT_COPY_ADD)
975 /* Delete all extensions of same type */
977 tmpext = X509_get_ext(x, idx);
978 X509_delete_ext(x, idx);
979 X509_EXTENSION_free(tmpext);
980 idx = X509_get_ext_by_OBJ(x, obj, -1);
983 if (!X509_add_ext(x, ext, -1))
991 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
996 static int set_multi_opts(unsigned long *flags, const char *arg,
997 const NAME_EX_TBL * in_tbl)
999 STACK_OF(CONF_VALUE) *vals;
1004 vals = X509V3_parse_list(arg);
1005 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1006 val = sk_CONF_VALUE_value(vals, i);
1007 if (!set_table_opts(flags, val->name, in_tbl))
1010 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1014 static int set_table_opts(unsigned long *flags, const char *arg,
1015 const NAME_EX_TBL * in_tbl)
1018 const NAME_EX_TBL *ptbl;
1024 } else if (c == '+') {
1031 for (ptbl = in_tbl; ptbl->name; ptbl++) {
1032 if (strcasecmp(arg, ptbl->name) == 0) {
1033 *flags &= ~ptbl->mask;
1035 *flags |= ptbl->flag;
1037 *flags &= ~ptbl->flag;
1044 void print_name(BIO *out, const char *title, const X509_NAME *nm,
1045 unsigned long lflags)
1052 BIO_puts(out, title);
1053 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1057 if (lflags == XN_FLAG_COMPAT) {
1058 buf = X509_NAME_oneline(nm, 0, 0);
1060 BIO_puts(out, "\n");
1064 BIO_puts(out, "\n");
1065 X509_NAME_print_ex(out, nm, indent, lflags);
1066 BIO_puts(out, "\n");
1070 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1071 int len, unsigned char *buffer)
1073 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1074 if (BN_is_zero(in)) {
1075 BIO_printf(out, "\n 0x00");
1079 l = BN_bn2bin(in, buffer);
1080 for (i = 0; i < l; i++) {
1081 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1083 BIO_printf(out, "0x%02X,", buffer[i]);
1085 BIO_printf(out, "0x%02X", buffer[i]);
1088 BIO_printf(out, "\n };\n");
1091 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1095 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1096 for (i = 0; i < len; i++) {
1098 BIO_printf(out, "\n ");
1100 BIO_printf(out, "0x%02X, ", d[i]);
1102 BIO_printf(out, "0x%02X", d[i]);
1104 BIO_printf(out, "\n};\n");
1107 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1108 const char *CApath, int noCApath,
1109 const char *CAstore, int noCAstore)
1111 X509_STORE *store = X509_STORE_new();
1112 X509_LOOKUP *lookup;
1113 OPENSSL_CTX *libctx = app_get0_libctx();
1114 const char *propq = app_get0_propq();
1119 if (CAfile != NULL || !noCAfile) {
1120 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1123 if (CAfile != NULL) {
1124 if (!X509_LOOKUP_load_file_with_libctx(lookup, CAfile,
1127 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1131 X509_LOOKUP_load_file_with_libctx(lookup, NULL,
1132 X509_FILETYPE_DEFAULT,
1137 if (CApath != NULL || !noCApath) {
1138 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1141 if (CApath != NULL) {
1142 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1143 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1147 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1151 if (CAstore != NULL || !noCAstore) {
1152 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1155 if (!X509_LOOKUP_add_store_with_libctx(lookup, CAstore, libctx, propq)) {
1156 if (CAstore != NULL)
1157 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1165 ERR_print_errors(bio_err);
1166 X509_STORE_free(store);
1170 #ifndef OPENSSL_NO_ENGINE
1171 /* Try to load an engine in a shareable library */
1172 static ENGINE *try_load_engine(const char *engine)
1174 ENGINE *e = ENGINE_by_id("dynamic");
1176 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1177 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1186 ENGINE *setup_engine_methods(const char *id, unsigned int methods, int debug)
1190 #ifndef OPENSSL_NO_ENGINE
1192 if (strcmp(id, "auto") == 0) {
1193 BIO_printf(bio_err, "Enabling auto ENGINE support\n");
1194 ENGINE_register_all_complete();
1197 if ((e = ENGINE_by_id(id)) == NULL
1198 && (e = try_load_engine(id)) == NULL) {
1199 BIO_printf(bio_err, "Invalid engine \"%s\"\n", id);
1200 ERR_print_errors(bio_err);
1204 (void)ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1205 if (!ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0,
1206 (void *)get_ui_method(), 0, 1)
1207 || !ENGINE_set_default(e, methods)) {
1208 BIO_printf(bio_err, "Cannot use engine \"%s\"\n", ENGINE_get_id(e));
1209 ERR_print_errors(bio_err);
1214 BIO_printf(bio_err, "Engine \"%s\" set.\n", ENGINE_get_id(e));
1220 void release_engine(ENGINE *e)
1222 #ifndef OPENSSL_NO_ENGINE
1223 /* Free our "structural" reference. */
1228 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1235 return OPENSSL_LH_strhash(n);
1238 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1239 const OPENSSL_CSTRING *b)
1241 const char *aa, *bb;
1243 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1244 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1245 return strcmp(aa, bb);
1248 static int index_name_qual(char **a)
1250 return (a[0][0] == 'V');
1253 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1255 return OPENSSL_LH_strhash(a[DB_name]);
1258 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1260 return strcmp(a[DB_name], b[DB_name]);
1263 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1264 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1265 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1266 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1269 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1274 ASN1_INTEGER *ai = NULL;
1276 ai = ASN1_INTEGER_new();
1280 in = BIO_new_file(serialfile, "r");
1288 if (ret == NULL || !rand_serial(ret, ai))
1289 BIO_printf(bio_err, "Out of memory\n");
1291 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1292 BIO_printf(bio_err, "Unable to load number from %s\n",
1296 ret = ASN1_INTEGER_to_BN(ai, NULL);
1298 BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1308 ERR_print_errors(bio_err);
1310 ASN1_INTEGER_free(ai);
1314 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1315 ASN1_INTEGER **retai)
1320 ASN1_INTEGER *ai = NULL;
1324 j = strlen(serialfile);
1326 j = strlen(serialfile) + strlen(suffix) + 1;
1328 BIO_printf(bio_err, "File name too long\n");
1333 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1335 #ifndef OPENSSL_SYS_VMS
1336 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1338 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1341 out = BIO_new_file(buf[0], "w");
1346 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1347 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1350 i2a_ASN1_INTEGER(out, ai);
1351 BIO_puts(out, "\n");
1359 ERR_print_errors(bio_err);
1361 ASN1_INTEGER_free(ai);
1365 int rotate_serial(const char *serialfile, const char *new_suffix,
1366 const char *old_suffix)
1371 i = strlen(serialfile) + strlen(old_suffix);
1372 j = strlen(serialfile) + strlen(new_suffix);
1375 if (j + 1 >= BSIZE) {
1376 BIO_printf(bio_err, "File name too long\n");
1379 #ifndef OPENSSL_SYS_VMS
1380 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1381 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1383 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1384 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1386 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1392 "Unable to rename %s to %s\n", serialfile, buf[1]);
1396 if (rename(buf[0], serialfile) < 0) {
1398 "Unable to rename %s to %s\n", buf[0], serialfile);
1400 rename(buf[1], serialfile);
1405 ERR_print_errors(bio_err);
1409 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1414 btmp = b == NULL ? BN_new() : b;
1418 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1420 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1433 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1435 CA_DB *retdb = NULL;
1436 TXT_DB *tmpdb = NULL;
1438 CONF *dbattr_conf = NULL;
1440 #ifndef OPENSSL_NO_POSIX_IO
1445 in = BIO_new_file(dbfile, "r");
1449 #ifndef OPENSSL_NO_POSIX_IO
1450 BIO_get_fp(in, &dbfp);
1451 if (fstat(fileno(dbfp), &dbst) == -1) {
1452 ERR_raise_data(ERR_LIB_SYS, errno,
1453 "calling fstat(%s)", dbfile);
1458 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1461 #ifndef OPENSSL_SYS_VMS
1462 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1464 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1466 dbattr_conf = app_load_config_quiet(buf);
1468 retdb = app_malloc(sizeof(*retdb), "new DB");
1472 retdb->attributes = *db_attr;
1474 retdb->attributes.unique_subject = 1;
1478 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1480 retdb->attributes.unique_subject = parse_yesno(p, 1);
1484 retdb->dbfname = OPENSSL_strdup(dbfile);
1485 #ifndef OPENSSL_NO_POSIX_IO
1490 ERR_print_errors(bio_err);
1491 NCONF_free(dbattr_conf);
1498 * Returns > 0 on success, <= 0 on error
1500 int index_index(CA_DB *db)
1502 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1503 LHASH_HASH_FN(index_serial),
1504 LHASH_COMP_FN(index_serial))) {
1506 "Error creating serial number index:(%ld,%ld,%ld)\n",
1507 db->db->error, db->db->arg1, db->db->arg2);
1511 if (db->attributes.unique_subject
1512 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1513 LHASH_HASH_FN(index_name),
1514 LHASH_COMP_FN(index_name))) {
1515 BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1516 db->db->error, db->db->arg1, db->db->arg2);
1521 ERR_print_errors(bio_err);
1525 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1531 j = strlen(dbfile) + strlen(suffix);
1532 if (j + 6 >= BSIZE) {
1533 BIO_printf(bio_err, "File name too long\n");
1536 #ifndef OPENSSL_SYS_VMS
1537 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1538 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1539 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1541 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1542 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1543 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1545 out = BIO_new_file(buf[0], "w");
1548 BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1551 j = TXT_DB_write(out, db->db);
1556 out = BIO_new_file(buf[1], "w");
1559 BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1562 BIO_printf(out, "unique_subject = %s\n",
1563 db->attributes.unique_subject ? "yes" : "no");
1568 ERR_print_errors(bio_err);
1572 int rotate_index(const char *dbfile, const char *new_suffix,
1573 const char *old_suffix)
1578 i = strlen(dbfile) + strlen(old_suffix);
1579 j = strlen(dbfile) + strlen(new_suffix);
1582 if (j + 6 >= BSIZE) {
1583 BIO_printf(bio_err, "File name too long\n");
1586 #ifndef OPENSSL_SYS_VMS
1587 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1588 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1589 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1590 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1591 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1593 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1594 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1595 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1596 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1597 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1599 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1604 BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1608 if (rename(buf[0], dbfile) < 0) {
1609 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1611 rename(buf[1], dbfile);
1614 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1619 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1621 rename(dbfile, buf[0]);
1622 rename(buf[1], dbfile);
1625 if (rename(buf[2], buf[4]) < 0) {
1626 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1628 rename(buf[3], buf[4]);
1629 rename(dbfile, buf[0]);
1630 rename(buf[1], dbfile);
1635 ERR_print_errors(bio_err);
1639 void free_index(CA_DB *db)
1642 TXT_DB_free(db->db);
1643 OPENSSL_free(db->dbfname);
1648 int parse_yesno(const char *str, int def)
1652 case 'f': /* false */
1653 case 'F': /* FALSE */
1658 case 't': /* true */
1659 case 'T': /* TRUE */
1670 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1671 * where characters may be escaped by \
1673 X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
1676 int nextismulti = 0;
1682 "%s: %s name is expected to be in the format "
1683 "/type0=value0/type1=value1/type2=... where characters may "
1684 "be escaped by \\. This name is not in that format: '%s'\n",
1685 opt_getprog(), desc, --cp);
1689 n = X509_NAME_new();
1691 BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
1694 work = OPENSSL_strdup(cp);
1696 BIO_printf(bio_err, "%s: Error copying %s name input\n",
1697 opt_getprog(), desc);
1701 while (*cp != '\0') {
1704 unsigned char *valstr;
1706 int ismulti = nextismulti;
1709 /* Collect the type */
1710 while (*cp != '\0' && *cp != '=')
1715 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1716 opt_getprog(), typestr, desc);
1721 /* Collect the value. */
1722 valstr = (unsigned char *)bp;
1723 for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
1724 if (canmulti && *cp == '+') {
1728 if (*cp == '\\' && *++cp == '\0') {
1730 "%s: Escape character at end of %s name string\n",
1731 opt_getprog(), desc);
1737 /* If not at EOS (must be + or /), move forward. */
1742 nid = OBJ_txt2nid(typestr);
1743 if (nid == NID_undef) {
1745 "%s: Skipping unknown %s name attribute \"%s\"\n",
1746 opt_getprog(), desc, typestr);
1749 if (*valstr == '\0') {
1751 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1752 opt_getprog(), desc, typestr);
1755 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1756 valstr, strlen((char *)valstr),
1757 -1, ismulti ? -1 : 0)) {
1758 ERR_print_errors(bio_err);
1760 "%s: Error adding %s name attribute \"/%s=%s\"\n",
1761 opt_getprog(), desc, typestr ,valstr);
1776 * Read whole contents of a BIO into an allocated memory buffer and return
1780 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1784 unsigned char tbuf[1024];
1786 mem = BIO_new(BIO_s_mem());
1790 if ((maxlen != -1) && maxlen < 1024)
1794 len = BIO_read(in, tbuf, len);
1801 if (BIO_write(mem, tbuf, len) != len) {
1810 ret = BIO_get_mem_data(mem, (char **)out);
1811 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1816 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1819 char *stmp, *vtmp = NULL;
1820 stmp = OPENSSL_strdup(value);
1823 vtmp = strchr(stmp, ':');
1828 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1833 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1835 X509_POLICY_NODE *node;
1838 BIO_printf(bio_err, "%s Policies:", name);
1840 BIO_puts(bio_err, "\n");
1841 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1842 node = sk_X509_POLICY_NODE_value(nodes, i);
1843 X509_POLICY_NODE_print(bio_err, node, 2);
1846 BIO_puts(bio_err, " <empty>\n");
1850 void policies_print(X509_STORE_CTX *ctx)
1852 X509_POLICY_TREE *tree;
1853 int explicit_policy;
1854 tree = X509_STORE_CTX_get0_policy_tree(ctx);
1855 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1857 BIO_printf(bio_err, "Require explicit Policy: %s\n",
1858 explicit_policy ? "True" : "False");
1860 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1861 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1865 * next_protos_parse parses a comma separated list of strings into a string
1866 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1867 * outlen: (output) set to the length of the resulting buffer on success.
1868 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1869 * in: a NUL terminated string like "abc,def,ghi"
1871 * returns: a malloc'd buffer or NULL on failure.
1873 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1877 size_t i, start = 0;
1881 if (len == 0 || len >= 65535)
1884 out = app_malloc(len + 1, "NPN buffer");
1885 for (i = 0; i <= len; ++i) {
1886 if (i == len || in[i] == ',') {
1888 * Zero-length ALPN elements are invalid on the wire, we could be
1889 * strict and reject the entire string, but just ignoring extra
1890 * commas seems harmless and more friendly.
1892 * Every comma we skip in this way puts the input buffer another
1893 * byte ahead of the output buffer, so all stores into the output
1894 * buffer need to be decremented by the number commas skipped.
1901 if (i - start > 255) {
1905 out[start-skipped] = (unsigned char)(i - start);
1908 out[i + 1 - skipped] = in[i];
1912 if (len <= skipped) {
1917 *outlen = len + 1 - skipped;
1921 void print_cert_checks(BIO *bio, X509 *x,
1922 const char *checkhost,
1923 const char *checkemail, const char *checkip)
1928 BIO_printf(bio, "Hostname %s does%s match certificate\n",
1930 X509_check_host(x, checkhost, 0, 0, NULL) == 1
1935 BIO_printf(bio, "Email %s does%s match certificate\n",
1936 checkemail, X509_check_email(x, checkemail, 0, 0)
1941 BIO_printf(bio, "IP %s does%s match certificate\n",
1942 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1946 /* Get first http URL from a DIST_POINT structure */
1948 static const char *get_dp_url(DIST_POINT *dp)
1950 GENERAL_NAMES *gens;
1954 if (!dp->distpoint || dp->distpoint->type != 0)
1956 gens = dp->distpoint->name.fullname;
1957 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1958 gen = sk_GENERAL_NAME_value(gens, i);
1959 uri = GENERAL_NAME_get0_value(gen, >ype);
1960 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1961 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
1962 if (strncmp(uptr, "http://", 7) == 0)
1970 * Look through a CRLDP structure and attempt to find an http URL to
1971 * downloads a CRL from.
1974 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1977 const char *urlptr = NULL;
1978 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1979 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1980 urlptr = get_dp_url(dp);
1982 return load_crl(urlptr, FORMAT_HTTP, "CRL via CDP");
1988 * Example of downloading CRLs from CRLDP:
1989 * not usable for real world as it always downloads and doesn't cache anything.
1992 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
1993 const X509_NAME *nm)
1996 STACK_OF(X509_CRL) *crls = NULL;
1998 STACK_OF(DIST_POINT) *crldp;
2000 crls = sk_X509_CRL_new_null();
2003 x = X509_STORE_CTX_get_current_cert(ctx);
2004 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2005 crl = load_crl_crldp(crldp);
2006 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2008 sk_X509_CRL_free(crls);
2011 sk_X509_CRL_push(crls, crl);
2012 /* Try to download delta CRL */
2013 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2014 crl = load_crl_crldp(crldp);
2015 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2017 sk_X509_CRL_push(crls, crl);
2021 void store_setup_crl_download(X509_STORE *st)
2023 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2026 #ifndef OPENSSL_NO_SOCK
2027 static const char *tls_error_hint(void)
2029 unsigned long err = ERR_peek_error();
2031 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2032 err = ERR_peek_last_error();
2033 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2036 switch (ERR_GET_REASON(err)) {
2037 case SSL_R_WRONG_VERSION_NUMBER:
2038 return "The server does not support (a suitable version of) TLS";
2039 case SSL_R_UNKNOWN_PROTOCOL:
2040 return "The server does not support HTTPS";
2041 case SSL_R_CERTIFICATE_VERIFY_FAILED:
2042 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2043 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
2044 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2045 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
2046 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2047 default: /* no error or no hint available for error */
2052 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
2053 BIO *app_http_tls_cb(BIO *hbio, void *arg, int connect, int detail)
2055 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
2056 SSL_CTX *ssl_ctx = info->ssl_ctx;
2060 if (connect && detail) { /* connecting with TLS */
2061 if ((info->use_proxy
2062 && !OSSL_HTTP_proxy_connect(hbio, info->server, info->port,
2063 NULL, NULL, /* no proxy credentials */
2064 info->timeout, bio_err, opt_getprog()))
2065 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
2068 if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
2073 SSL_set_tlsext_host_name(ssl, info->server);
2075 SSL_set_connect_state(ssl);
2076 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2078 hbio = BIO_push(sbio, hbio);
2079 } else if (!connect && !detail) { /* disconnecting after error */
2080 const char *hint = tls_error_hint();
2082 ERR_add_error_data(2, " : ", hint);
2084 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2085 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2091 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2092 const char *no_proxy, SSL_CTX *ssl_ctx,
2093 const STACK_OF(CONF_VALUE) *headers,
2094 long timeout, const char *expected_content_type,
2095 const ASN1_ITEM *it)
2097 APP_HTTP_TLS_INFO info;
2101 ASN1_VALUE *resp = NULL;
2103 if (url == NULL || it == NULL) {
2104 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2108 if (!OSSL_HTTP_parse_url(url, &server, &port, NULL /* ppath */, &use_ssl))
2110 if (use_ssl && ssl_ctx == NULL) {
2111 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2112 ERR_add_error_data(1, "missing SSL_CTX");
2116 info.server = server;
2118 info.use_proxy = proxy != NULL;
2119 info.timeout = timeout;
2120 info.ssl_ctx = ssl_ctx;
2121 resp = OSSL_HTTP_get_asn1(url, proxy, no_proxy,
2122 NULL, NULL, app_http_tls_cb, &info,
2123 headers, 0 /* maxline */, 0 /* max_resp_len */,
2124 timeout, expected_content_type, it);
2126 OPENSSL_free(server);
2132 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2133 const char *path, const char *proxy,
2134 const char *no_proxy, SSL_CTX *ssl_ctx,
2135 const STACK_OF(CONF_VALUE) *headers,
2136 const char *content_type,
2137 ASN1_VALUE *req, const ASN1_ITEM *req_it,
2138 long timeout, const ASN1_ITEM *rsp_it)
2140 APP_HTTP_TLS_INFO info;
2144 info.use_proxy = proxy != NULL;
2145 info.timeout = timeout;
2146 info.ssl_ctx = ssl_ctx;
2147 return OSSL_HTTP_post_asn1(host, port, path, ssl_ctx != NULL,
2149 NULL, NULL, app_http_tls_cb, &info,
2150 headers, content_type, req, req_it,
2152 0 /* max_resp_len */, timeout, NULL, rsp_it);
2158 * Platform-specific sections
2163 # define fileno(a) (int)_fileno(a)
2166 # include <windows.h>
2169 static int WIN32_rename(const char *from, const char *to)
2171 TCHAR *tfrom = NULL, *tto;
2175 if (sizeof(TCHAR) == 1) {
2176 tfrom = (TCHAR *)from;
2178 } else { /* UNICODE path */
2180 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2181 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2185 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2186 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2188 for (i = 0; i < flen; i++)
2189 tfrom[i] = (TCHAR)from[i];
2190 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2191 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2193 for (i = 0; i < tlen; i++)
2194 tto[i] = (TCHAR)to[i];
2197 if (MoveFile(tfrom, tto))
2199 err = GetLastError();
2200 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2201 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2203 err = GetLastError();
2205 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2207 else if (err == ERROR_ACCESS_DENIED)
2210 errno = EINVAL; /* we could map more codes... */
2214 if (tfrom != NULL && tfrom != (TCHAR *)from)
2220 /* app_tminterval section */
2222 double app_tminterval(int stop, int usertime)
2226 static ULARGE_INTEGER tmstart;
2227 static int warning = 1;
2228 # ifdef _WIN32_WINNT
2229 static HANDLE proc = NULL;
2233 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2234 GetCurrentProcessId());
2236 proc = (HANDLE) - 1;
2239 if (usertime && proc != (HANDLE) - 1) {
2241 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2247 if (usertime && warning) {
2248 BIO_printf(bio_err, "To get meaningful results, run "
2249 "this program on idle system.\n");
2252 GetSystemTime(&systime);
2253 SystemTimeToFileTime(&systime, &now);
2256 if (stop == TM_START) {
2257 tmstart.u.LowPart = now.dwLowDateTime;
2258 tmstart.u.HighPart = now.dwHighDateTime;
2260 ULARGE_INTEGER tmstop;
2262 tmstop.u.LowPart = now.dwLowDateTime;
2263 tmstop.u.HighPart = now.dwHighDateTime;
2265 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2270 #elif defined(OPENSSL_SYS_VXWORKS)
2273 double app_tminterval(int stop, int usertime)
2276 # ifdef CLOCK_REALTIME
2277 static struct timespec tmstart;
2278 struct timespec now;
2280 static unsigned long tmstart;
2283 static int warning = 1;
2285 if (usertime && warning) {
2286 BIO_printf(bio_err, "To get meaningful results, run "
2287 "this program on idle system.\n");
2290 # ifdef CLOCK_REALTIME
2291 clock_gettime(CLOCK_REALTIME, &now);
2292 if (stop == TM_START)
2295 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2296 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2299 if (stop == TM_START)
2302 ret = (now - tmstart) / (double)sysClkRateGet();
2307 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2308 # include <sys/times.h>
2310 double app_tminterval(int stop, int usertime)
2314 clock_t now = times(&rus);
2315 static clock_t tmstart;
2318 now = rus.tms_utime;
2320 if (stop == TM_START) {
2323 long int tck = sysconf(_SC_CLK_TCK);
2324 ret = (now - tmstart) / (double)tck;
2331 # include <sys/time.h>
2332 # include <sys/resource.h>
2334 double app_tminterval(int stop, int usertime)
2339 static struct timeval tmstart;
2342 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2344 gettimeofday(&now, NULL);
2346 if (stop == TM_START)
2349 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2350 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2356 int app_access(const char* name, int flag)
2359 return _access(name, flag);
2361 return access(name, flag);
2365 int app_isdir(const char *name)
2367 return opt_isdir(name);
2370 /* raw_read|write section */
2372 # include "vms_term_sock.h"
2373 static int stdin_sock = -1;
2375 static void close_stdin_sock(void)
2377 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2380 int fileno_stdin(void)
2382 if (stdin_sock == -1) {
2383 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2384 atexit(close_stdin_sock);
2390 int fileno_stdin(void)
2392 return fileno(stdin);
2396 int fileno_stdout(void)
2398 return fileno(stdout);
2401 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2402 int raw_read_stdin(void *buf, int siz)
2405 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2410 #elif defined(__VMS)
2411 # include <sys/socket.h>
2413 int raw_read_stdin(void *buf, int siz)
2415 return recv(fileno_stdin(), buf, siz, 0);
2418 int raw_read_stdin(void *buf, int siz)
2420 return read(fileno_stdin(), buf, siz);
2424 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2425 int raw_write_stdout(const void *buf, int siz)
2428 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2434 int raw_write_stdout(const void *buf, int siz)
2436 return write(fileno_stdout(), buf, siz);
2441 * Centralized handling of input and output files with format specification
2442 * The format is meant to show what the input and output is supposed to be,
2443 * and is therefore a show of intent more than anything else. However, it
2444 * does impact behavior on some platforms, such as differentiating between
2445 * text and binary input/output on non-Unix platforms
2447 BIO *dup_bio_in(int format)
2449 return BIO_new_fp(stdin,
2450 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2453 BIO *dup_bio_out(int format)
2455 BIO *b = BIO_new_fp(stdout,
2456 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2457 void *prefix = NULL;
2459 #ifdef OPENSSL_SYS_VMS
2460 if (FMT_istext(format))
2461 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2464 if (FMT_istext(format)
2465 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2466 b = BIO_push(BIO_new(BIO_f_prefix()), b);
2467 BIO_set_prefix(b, prefix);
2473 BIO *dup_bio_err(int format)
2475 BIO *b = BIO_new_fp(stderr,
2476 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2477 #ifdef OPENSSL_SYS_VMS
2478 if (FMT_istext(format))
2479 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2484 void unbuffer(FILE *fp)
2487 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2488 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2489 * However, we trust that the C RTL will never give us a FILE pointer
2490 * above the first 4 GB of memory, so we simply turn off the warning
2493 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2494 # pragma environment save
2495 # pragma message disable maylosedata2
2498 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2499 # pragma environment restore
2503 static const char *modestr(char mode, int format)
2505 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2509 return FMT_istext(format) ? "a" : "ab";
2511 return FMT_istext(format) ? "r" : "rb";
2513 return FMT_istext(format) ? "w" : "wb";
2515 /* The assert above should make sure we never reach this point */
2519 static const char *modeverb(char mode)
2529 return "(doing something)";
2533 * Open a file for writing, owner-read-only.
2535 BIO *bio_open_owner(const char *filename, int format, int private)
2539 int fd = -1, bflags, mode, textmode;
2541 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2542 return bio_open_default(filename, 'w', format);
2551 textmode = FMT_istext(format);
2555 #elif defined(_O_BINARY)
2560 #ifdef OPENSSL_SYS_VMS
2561 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2562 * it still needs to know that we're going binary, or fdopen()
2563 * will fail with "invalid argument"... so we tell VMS what the
2567 fd = open(filename, mode, 0600, "ctx=bin");
2570 fd = open(filename, mode, 0600);
2573 fp = fdopen(fd, modestr('w', format));
2578 bflags |= BIO_FP_TEXT;
2579 b = BIO_new_fp(fp, bflags);
2584 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2585 opt_getprog(), filename, strerror(errno));
2586 ERR_print_errors(bio_err);
2587 /* If we have fp, then fdopen took over fd, so don't close both. */
2595 static BIO *bio_open_default_(const char *filename, char mode, int format,
2600 if (filename == NULL || strcmp(filename, "-") == 0) {
2601 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2609 "Can't open %s, %s\n",
2610 mode == 'r' ? "stdin" : "stdout", strerror(errno));
2612 ret = BIO_new_file(filename, modestr(mode, format));
2620 "Can't open %s for %s, %s\n",
2621 filename, modeverb(mode), strerror(errno));
2623 ERR_print_errors(bio_err);
2627 BIO *bio_open_default(const char *filename, char mode, int format)
2629 return bio_open_default_(filename, mode, format, 0);
2632 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2634 return bio_open_default_(filename, mode, format, 1);
2637 void wait_for_async(SSL *s)
2639 /* On Windows select only works for sockets, so we simply don't wait */
2640 #ifndef OPENSSL_SYS_WINDOWS
2647 if (!SSL_get_all_async_fds(s, NULL, &numfds))
2651 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2652 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2658 for (i = 0; i < numfds; i++) {
2659 if (width <= (int)fds[i])
2660 width = (int)fds[i] + 1;
2661 openssl_fdset((int)fds[i], &asyncfds);
2663 select(width, (void *)&asyncfds, NULL, NULL, NULL);
2668 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2669 #if defined(OPENSSL_SYS_MSDOS)
2670 int has_stdin_waiting(void)
2672 # if defined(OPENSSL_SYS_WINDOWS)
2673 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2675 INPUT_RECORD inputrec;
2679 if (inhand == INVALID_HANDLE_VALUE) {
2683 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2685 /* Probably redirected input? _kbhit() does not work in this case */
2696 /* Corrupt a signature by modifying final byte */
2697 void corrupt_signature(const ASN1_STRING *signature)
2699 unsigned char *s = signature->data;
2700 s[signature->length - 1] ^= 0x1;
2703 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2706 if (startdate == NULL || strcmp(startdate, "today") == 0) {
2707 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2710 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2713 if (enddate == NULL) {
2714 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2717 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2723 void make_uppercase(char *string)
2727 for (i = 0; string[i] != '\0'; i++)
2728 string[i] = toupper((unsigned char)string[i]);
2731 int opt_printf_stderr(const char *fmt, ...)
2737 ret = BIO_vprintf(bio_err, fmt, ap);
2742 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
2743 const OSSL_PARAM *paramdefs)
2745 OSSL_PARAM *params = NULL;
2746 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
2748 char *opt = "", *stmp, *vtmp = NULL;
2754 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
2758 for (params_n = 0; params_n < sz; params_n++) {
2759 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
2760 if ((stmp = OPENSSL_strdup(opt)) == NULL
2761 || (vtmp = strchr(stmp, ':')) == NULL)
2763 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2765 /* Skip over the separator so that vmtp points to the value */
2767 if (!OSSL_PARAM_allocate_from_text(¶ms[params_n], paramdefs,
2768 stmp, vtmp, strlen(vtmp), &found))
2772 params[params_n] = OSSL_PARAM_construct_end();
2776 BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
2778 ERR_print_errors(bio_err);
2779 app_params_free(params);
2783 void app_params_free(OSSL_PARAM *params)
2787 if (params != NULL) {
2788 for (i = 0; params[i].key != NULL; ++i)
2789 OPENSSL_free(params[i].data);
2790 OPENSSL_free(params);