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_ENGINE
37 # include <openssl/engine.h>
39 #ifndef OPENSSL_NO_RSA
40 # include <openssl/rsa.h>
42 #include <openssl/bn.h>
43 #include <openssl/ssl.h>
47 static int WIN32_rename(const char *from, const char *to);
48 # define rename(from,to) WIN32_rename((from),(to))
51 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
55 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32)
59 #define PASS_SOURCE_SIZE_MAX 4
62 DEFINE_STACK_OF(CONF_VALUE)
64 DEFINE_STACK_OF(X509_CRL)
65 DEFINE_STACK_OF(X509_INFO)
66 DEFINE_STACK_OF(X509_EXTENSION)
67 DEFINE_STACK_OF(X509_POLICY_NODE)
68 DEFINE_STACK_OF(GENERAL_NAME)
69 DEFINE_STACK_OF(DIST_POINT)
70 DEFINE_STACK_OF_STRING()
78 static int set_table_opts(unsigned long *flags, const char *arg,
79 const NAME_EX_TBL * in_tbl);
80 static int set_multi_opts(unsigned long *flags, const char *arg,
81 const NAME_EX_TBL * in_tbl);
83 int app_init(long mesgwin);
85 int chopup_args(ARGS *arg, char *buf)
88 char c = '\0', *p = NULL;
93 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
97 /* Skip whitespace. */
98 while (*p && isspace(_UC(*p)))
103 /* The start of something good :-) */
104 if (arg->argc >= arg->size) {
107 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
112 quoted = *p == '\'' || *p == '"';
115 arg->argv[arg->argc++] = p;
117 /* now look for the end of this */
119 while (*p && *p != c)
123 while (*p && !isspace(_UC(*p)))
129 arg->argv[arg->argc] = NULL;
134 int app_init(long mesgwin)
140 int ctx_set_verify_locations(SSL_CTX *ctx,
141 const char *CAfile, int noCAfile,
142 const char *CApath, int noCApath,
143 const char *CAstore, int noCAstore)
145 if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
146 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
148 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
150 if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
156 if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
158 if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
160 if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
165 #ifndef OPENSSL_NO_CT
167 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
170 return SSL_CTX_set_default_ctlog_list_file(ctx);
172 return SSL_CTX_set_ctlog_list_file(ctx, path);
177 static unsigned long nmflag = 0;
178 static char nmflag_set = 0;
180 int set_nameopt(const char *arg)
182 int ret = set_name_ex(&nmflag, arg);
190 unsigned long get_nameopt(void)
192 return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
195 int dump_cert_text(BIO *out, X509 *x)
197 print_name(out, "subject=", X509_get_subject_name(x), get_nameopt());
199 print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
205 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
207 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
211 static char *app_get_pass(const char *arg, int keepbio);
213 char *get_passwd(const char *pass, const char *desc)
219 if (!app_passwd(pass, NULL, &result, NULL))
220 BIO_printf(bio_err, "Error getting password for %s\n", desc);
221 if (pass != NULL && result == NULL) {
223 "Trying plain input string (better precede with 'pass:')\n");
224 result = OPENSSL_strdup(pass);
226 BIO_printf(bio_err, "Out of memory getting password for %s\n", desc);
231 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
233 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
236 *pass1 = app_get_pass(arg1, same);
239 } else if (pass1 != NULL) {
243 *pass2 = app_get_pass(arg2, same ? 2 : 0);
246 } else if (pass2 != NULL) {
252 static char *app_get_pass(const char *arg, int keepbio)
254 static BIO *pwdbio = NULL;
255 char *tmp, tpass[APP_PASS_LEN];
258 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
259 if (strncmp(arg, "pass:", 5) == 0)
260 return OPENSSL_strdup(arg + 5);
261 if (strncmp(arg, "env:", 4) == 0) {
262 tmp = getenv(arg + 4);
264 BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
267 return OPENSSL_strdup(tmp);
269 if (!keepbio || pwdbio == NULL) {
270 if (strncmp(arg, "file:", 5) == 0) {
271 pwdbio = BIO_new_file(arg + 5, "r");
272 if (pwdbio == NULL) {
273 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
278 * Under _WIN32, which covers even Win64 and CE, file
279 * descriptors referenced by BIO_s_fd are not inherited
280 * by child process and therefore below is not an option.
281 * It could have been an option if bss_fd.c was operating
282 * on real Windows descriptors, such as those obtained
285 } else if (strncmp(arg, "fd:", 3) == 0) {
289 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
290 if ((i < 0) || !pwdbio) {
291 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
295 * Can't do BIO_gets on an fd BIO so add a buffering BIO
297 btmp = BIO_new(BIO_f_buffer());
298 pwdbio = BIO_push(btmp, pwdbio);
300 } else if (strcmp(arg, "stdin") == 0) {
301 pwdbio = dup_bio_in(FORMAT_TEXT);
302 if (pwdbio == NULL) {
303 BIO_printf(bio_err, "Can't open BIO for stdin\n");
307 /* argument syntax error; do not reveal too much about arg */
308 tmp = strchr(arg, ':');
309 if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
311 "Invalid password argument, missing ':' within the first %d chars\n",
312 PASS_SOURCE_SIZE_MAX + 1);
315 "Invalid password argument, starting with \"%.*s\"\n",
316 (int)(tmp - arg + 1), arg);
320 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
322 BIO_free_all(pwdbio);
326 BIO_printf(bio_err, "Error reading password from BIO\n");
329 tmp = strchr(tpass, '\n');
332 return OPENSSL_strdup(tpass);
335 CONF *app_load_config_bio(BIO *in, const char *filename)
341 conf = NCONF_new(NULL);
342 i = NCONF_load_bio(conf, in, &errorline);
346 if (errorline <= 0) {
347 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
349 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
352 if (filename != NULL)
353 BIO_printf(bio_err, "config file \"%s\"\n", filename);
355 BIO_printf(bio_err, "config input");
361 CONF *app_load_config(const char *filename)
366 in = bio_open_default(filename, 'r', FORMAT_TEXT);
370 conf = app_load_config_bio(in, filename);
375 CONF *app_load_config_quiet(const char *filename)
380 in = bio_open_default_quiet(filename, 'r', FORMAT_TEXT);
384 conf = app_load_config_bio(in, filename);
389 int app_load_modules(const CONF *config)
391 CONF *to_free = NULL;
394 config = to_free = app_load_config_quiet(default_config_file);
398 if (CONF_modules_load(config, NULL, 0) <= 0) {
399 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
400 ERR_print_errors(bio_err);
408 int add_oid_section(CONF *conf)
411 STACK_OF(CONF_VALUE) *sktmp;
415 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
419 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
420 BIO_printf(bio_err, "problem loading oid section %s\n", p);
423 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
424 cnf = sk_CONF_VALUE_value(sktmp, i);
425 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
426 BIO_printf(bio_err, "problem creating object %s=%s\n",
427 cnf->name, cnf->value);
434 X509 *load_cert_pass(const char *uri, int maybe_stdin,
435 const char *pass, const char *desc)
440 desc = "certificate";
445 (void)load_key_cert_crl(uri, maybe_stdin, pass, desc, NULL, &cert, NULL);
447 BIO_printf(bio_err, "Unable to load %s\n", desc);
448 ERR_print_errors(bio_err);
453 /* the format parameter is meanwhile not needed anymore and thus ignored */
454 X509 *load_cert(const char *uri, int format, const char *desc)
456 return load_cert_pass(uri, 0, NULL, desc);
459 /* the format parameter is meanwhile not needed anymore and thus ignored */
460 X509_CRL *load_crl(const char *uri, int format, const char *desc)
462 X509_CRL *crl = NULL;
466 (void)load_key_cert_crl(uri, 0, NULL, desc, NULL, NULL, &crl);
468 BIO_printf(bio_err, "Unable to load %s\n", desc);
469 ERR_print_errors(bio_err);
474 X509_REQ *load_csr(const char *file, int format, const char *desc)
476 X509_REQ *req = NULL;
481 in = bio_open_default(file, 'r', format);
485 if (format == FORMAT_ASN1)
486 req = d2i_X509_REQ_bio(in, NULL);
487 else if (format == FORMAT_PEM)
488 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
490 print_format_error(format, OPT_FMT_PEMDER);
494 BIO_printf(bio_err, "Unable to load %s\n", desc);
495 ERR_print_errors(bio_err);
501 void cleanse(char *str)
504 OPENSSL_cleanse(str, strlen(str));
507 void clear_free(char *str)
510 OPENSSL_clear_free(str, strlen(str));
513 EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
514 const char *pass, ENGINE *e, const char *desc)
516 EVP_PKEY *pkey = NULL;
519 desc = "private key";
521 if (format == FORMAT_ENGINE) {
523 BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
525 #ifndef OPENSSL_NO_ENGINE
528 cb_data.password = pass;
529 cb_data.prompt_info = uri;
530 if (ENGINE_init(e)) {
531 pkey = ENGINE_load_private_key(e, uri,
532 (UI_METHOD *)get_ui_method(),
537 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
538 ERR_print_errors(bio_err);
541 BIO_printf(bio_err, "Engines not supported for loading %s\n", desc);
545 (void)load_key_cert_crl(uri, may_stdin, pass, desc, &pkey, NULL, NULL);
549 BIO_printf(bio_err, "Unable to load %s\n", desc);
550 ERR_print_errors(bio_err);
555 EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
556 const char *pass, ENGINE *e, const char *desc)
558 EVP_PKEY *pkey = NULL;
563 if (format == FORMAT_ENGINE) {
565 BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
567 #ifndef OPENSSL_NO_ENGINE
570 cb_data.password = pass;
571 cb_data.prompt_info = uri;
572 pkey = ENGINE_load_public_key(e, uri, (UI_METHOD *)get_ui_method(),
575 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
576 ERR_print_errors(bio_err);
579 BIO_printf(bio_err, "Engines not supported for loading %s\n", desc);
583 (void)load_key_cert_crl(uri, maybe_stdin, pass, desc, &pkey,
587 BIO_printf(bio_err, "Unable to load %s\n", desc);
588 ERR_print_errors(bio_err);
593 static int load_certs_crls(const char *file, int format,
594 const char *pass, const char *desc,
595 STACK_OF(X509) **pcerts,
596 STACK_OF(X509_CRL) **pcrls)
600 STACK_OF(X509_INFO) *xis = NULL;
605 cb_data.password = pass;
606 cb_data.prompt_info = file;
608 if (format != FORMAT_PEM) {
609 BIO_printf(bio_err, "Bad input format specified for %s\n", desc);
613 bio = bio_open_default(file, 'r', FORMAT_PEM);
617 xis = PEM_X509_INFO_read_bio(bio, NULL,
618 (pem_password_cb *)password_callback,
623 if (pcerts != NULL && *pcerts == NULL) {
624 *pcerts = sk_X509_new_null();
629 if (pcrls != NULL && *pcrls == NULL) {
630 *pcrls = sk_X509_CRL_new_null();
635 for (i = 0; i < sk_X509_INFO_num(xis); i++) {
636 xi = sk_X509_INFO_value(xis, i);
637 if (xi->x509 != NULL && pcerts != NULL) {
638 if (!sk_X509_push(*pcerts, xi->x509))
642 if (xi->crl != NULL && pcrls != NULL) {
643 if (!sk_X509_CRL_push(*pcrls, xi->crl))
649 if (pcerts != NULL && sk_X509_num(*pcerts) > 0)
652 if (pcrls != NULL && sk_X509_CRL_num(*pcrls) > 0)
657 sk_X509_INFO_pop_free(xis, X509_INFO_free);
660 if (pcerts != NULL) {
661 sk_X509_pop_free(*pcerts, X509_free);
665 sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
668 BIO_printf(bio_err, "Unable to load %s\n", desc != NULL ? desc :
669 pcerts != NULL ? "certificates" : "CRLs");
674 void app_bail_out(char *fmt, ...)
679 BIO_vprintf(bio_err, fmt, args);
681 ERR_print_errors(bio_err);
685 void* app_malloc(int sz, const char *what)
687 void *vp = OPENSSL_malloc(sz);
690 app_bail_out("%s: Could not allocate %d bytes for %s\n",
691 opt_getprog(), sz, what);
696 * Initialize or extend, if *certs != NULL, a certificate stack.
698 int load_certs(const char *file, STACK_OF(X509) **certs, int format,
699 const char *pass, const char *desc)
701 return load_certs_crls(file, format, pass, desc, certs, NULL);
705 * Initialize or extend, if *crls != NULL, a certificate stack.
707 int load_crls(const char *file, STACK_OF(X509_CRL) **crls, int format,
708 const char *pass, const char *desc)
710 return load_certs_crls(file, format, pass, desc, NULL, crls);
714 * Load those types of credentials for which the result pointer is not NULL.
715 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
716 * For each type the first credential found in the store is loaded.
717 * May yield partial result even if rv == 0.
719 int load_key_cert_crl(const char *uri, int maybe_stdin,
720 const char *pass, const char *desc,
721 EVP_PKEY **ppkey, X509 **pcert, X509_CRL **pcrl)
724 OSSL_STORE_CTX *ctx = NULL;
726 /* TODO make use of the engine reference 'eng' when loading pkeys */
736 desc = "key/certificate/CRL";
737 uidata.password = pass;
738 uidata.prompt_info = uri;
744 BIO_printf(bio_err, "No filename or uri specified for loading %s\n",
749 bio = BIO_new_fp(stdin, 0);
751 ctx = OSSL_STORE_attach(bio, NULL, "file", NULL,
752 get_ui_method(), &uidata, NULL, NULL);
755 ctx = OSSL_STORE_open(uri, get_ui_method(), &uidata, NULL, NULL);
758 BIO_printf(bio_err, "Could not open file or uri %s for loading %s\n",
764 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
765 int type = info == NULL ? 0 : OSSL_STORE_INFO_get_type(info);
766 const char *infostr =
767 info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
771 if (OSSL_STORE_eof(ctx))
777 case OSSL_STORE_INFO_PKEY:
778 if (ppkey != NULL && *ppkey == NULL)
779 err = ((*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) == NULL);
781 case OSSL_STORE_INFO_CERT:
782 if (pcert != NULL && *pcert == NULL)
783 err = ((*pcert = OSSL_STORE_INFO_get1_CERT(info)) == NULL);
785 case OSSL_STORE_INFO_CRL:
786 if (pcrl != NULL && *pcrl == NULL)
787 err = ((*pcrl = OSSL_STORE_INFO_get1_CRL(info)) == NULL);
790 /* skip any other type */
793 OSSL_STORE_INFO_free(info);
795 BIO_printf(bio_err, "Could not read %s of %s from %s\n",
802 OSSL_STORE_close(ctx);
804 ERR_print_errors(bio_err);
809 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
810 /* Return error for unknown extensions */
811 #define X509V3_EXT_DEFAULT 0
812 /* Print error for unknown extensions */
813 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
814 /* ASN1 parse unknown extensions */
815 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
816 /* BIO_dump unknown extensions */
817 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
819 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
820 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
822 int set_cert_ex(unsigned long *flags, const char *arg)
824 static const NAME_EX_TBL cert_tbl[] = {
825 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
826 {"ca_default", X509_FLAG_CA, 0xffffffffl},
827 {"no_header", X509_FLAG_NO_HEADER, 0},
828 {"no_version", X509_FLAG_NO_VERSION, 0},
829 {"no_serial", X509_FLAG_NO_SERIAL, 0},
830 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
831 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
832 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
833 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
834 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
835 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
836 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
837 {"no_aux", X509_FLAG_NO_AUX, 0},
838 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
839 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
840 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
841 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
842 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
845 return set_multi_opts(flags, arg, cert_tbl);
848 int set_name_ex(unsigned long *flags, const char *arg)
850 static const NAME_EX_TBL ex_tbl[] = {
851 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
852 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
853 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
854 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
855 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
856 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
857 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
858 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
859 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
860 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
861 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
862 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
863 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
864 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
865 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
866 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
867 {"dn_rev", XN_FLAG_DN_REV, 0},
868 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
869 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
870 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
871 {"align", XN_FLAG_FN_ALIGN, 0},
872 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
873 {"space_eq", XN_FLAG_SPC_EQ, 0},
874 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
875 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
876 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
877 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
878 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
881 if (set_multi_opts(flags, arg, ex_tbl) == 0)
883 if (*flags != XN_FLAG_COMPAT
884 && (*flags & XN_FLAG_SEP_MASK) == 0)
885 *flags |= XN_FLAG_SEP_CPLUS_SPC;
889 int set_ext_copy(int *copy_type, const char *arg)
891 if (strcasecmp(arg, "none") == 0)
892 *copy_type = EXT_COPY_NONE;
893 else if (strcasecmp(arg, "copy") == 0)
894 *copy_type = EXT_COPY_ADD;
895 else if (strcasecmp(arg, "copyall") == 0)
896 *copy_type = EXT_COPY_ALL;
902 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
904 STACK_OF(X509_EXTENSION) *exts = NULL;
905 X509_EXTENSION *ext, *tmpext;
908 if (!x || !req || (copy_type == EXT_COPY_NONE))
910 exts = X509_REQ_get_extensions(req);
912 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
913 ext = sk_X509_EXTENSION_value(exts, i);
914 obj = X509_EXTENSION_get_object(ext);
915 idx = X509_get_ext_by_OBJ(x, obj, -1);
916 /* Does extension exist? */
918 /* If normal copy don't override existing extension */
919 if (copy_type == EXT_COPY_ADD)
921 /* Delete all extensions of same type */
923 tmpext = X509_get_ext(x, idx);
924 X509_delete_ext(x, idx);
925 X509_EXTENSION_free(tmpext);
926 idx = X509_get_ext_by_OBJ(x, obj, -1);
929 if (!X509_add_ext(x, ext, -1))
937 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
942 static int set_multi_opts(unsigned long *flags, const char *arg,
943 const NAME_EX_TBL * in_tbl)
945 STACK_OF(CONF_VALUE) *vals;
950 vals = X509V3_parse_list(arg);
951 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
952 val = sk_CONF_VALUE_value(vals, i);
953 if (!set_table_opts(flags, val->name, in_tbl))
956 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
960 static int set_table_opts(unsigned long *flags, const char *arg,
961 const NAME_EX_TBL * in_tbl)
964 const NAME_EX_TBL *ptbl;
970 } else if (c == '+') {
977 for (ptbl = in_tbl; ptbl->name; ptbl++) {
978 if (strcasecmp(arg, ptbl->name) == 0) {
979 *flags &= ~ptbl->mask;
981 *flags |= ptbl->flag;
983 *flags &= ~ptbl->flag;
990 void print_name(BIO *out, const char *title, const X509_NAME *nm,
991 unsigned long lflags)
998 BIO_puts(out, title);
999 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1003 if (lflags == XN_FLAG_COMPAT) {
1004 buf = X509_NAME_oneline(nm, 0, 0);
1006 BIO_puts(out, "\n");
1010 BIO_puts(out, "\n");
1011 X509_NAME_print_ex(out, nm, indent, lflags);
1012 BIO_puts(out, "\n");
1016 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1017 int len, unsigned char *buffer)
1019 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1020 if (BN_is_zero(in)) {
1021 BIO_printf(out, "\n 0x00");
1025 l = BN_bn2bin(in, buffer);
1026 for (i = 0; i < l; i++) {
1027 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1029 BIO_printf(out, "0x%02X,", buffer[i]);
1031 BIO_printf(out, "0x%02X", buffer[i]);
1034 BIO_printf(out, "\n };\n");
1037 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1041 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1042 for (i = 0; i < len; i++) {
1044 BIO_printf(out, "\n ");
1046 BIO_printf(out, "0x%02X, ", d[i]);
1048 BIO_printf(out, "0x%02X", d[i]);
1050 BIO_printf(out, "\n};\n");
1053 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1054 const char *CApath, int noCApath,
1055 const char *CAstore, int noCAstore)
1057 X509_STORE *store = X509_STORE_new();
1058 X509_LOOKUP *lookup;
1063 if (CAfile != NULL || !noCAfile) {
1064 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1067 if (CAfile != NULL) {
1068 if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1069 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1073 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1077 if (CApath != NULL || !noCApath) {
1078 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1081 if (CApath != NULL) {
1082 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1083 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1087 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1091 if (CAstore != NULL || !noCAstore) {
1092 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1095 if (!X509_LOOKUP_add_store(lookup, CAstore)) {
1096 if (CAstore != NULL)
1097 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1105 ERR_print_errors(bio_err);
1106 X509_STORE_free(store);
1110 #ifndef OPENSSL_NO_ENGINE
1111 /* Try to load an engine in a shareable library */
1112 static ENGINE *try_load_engine(const char *engine)
1114 ENGINE *e = ENGINE_by_id("dynamic");
1116 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1117 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1126 ENGINE *setup_engine_methods(const char *id, unsigned int methods, int debug)
1130 #ifndef OPENSSL_NO_ENGINE
1132 if (strcmp(id, "auto") == 0) {
1133 BIO_printf(bio_err, "Enabling auto ENGINE support\n");
1134 ENGINE_register_all_complete();
1137 if ((e = ENGINE_by_id(id)) == NULL
1138 && (e = try_load_engine(id)) == NULL) {
1139 BIO_printf(bio_err, "Invalid engine \"%s\"\n", id);
1140 ERR_print_errors(bio_err);
1144 (void)ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1145 if (!ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0,
1146 (void *)get_ui_method(), 0, 1)
1147 || !ENGINE_set_default(e, methods)) {
1148 BIO_printf(bio_err, "Cannot use engine \"%s\"\n", ENGINE_get_id(e));
1149 ERR_print_errors(bio_err);
1154 BIO_printf(bio_err, "Engine \"%s\" set.\n", ENGINE_get_id(e));
1160 void release_engine(ENGINE *e)
1162 #ifndef OPENSSL_NO_ENGINE
1164 /* Free our "structural" reference. */
1169 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1176 return OPENSSL_LH_strhash(n);
1179 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1180 const OPENSSL_CSTRING *b)
1182 const char *aa, *bb;
1184 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1185 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1186 return strcmp(aa, bb);
1189 static int index_name_qual(char **a)
1191 return (a[0][0] == 'V');
1194 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1196 return OPENSSL_LH_strhash(a[DB_name]);
1199 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1201 return strcmp(a[DB_name], b[DB_name]);
1204 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1205 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1206 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1207 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1210 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1215 ASN1_INTEGER *ai = NULL;
1217 ai = ASN1_INTEGER_new();
1221 in = BIO_new_file(serialfile, "r");
1229 if (ret == NULL || !rand_serial(ret, ai))
1230 BIO_printf(bio_err, "Out of memory\n");
1232 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1233 BIO_printf(bio_err, "Unable to load number from %s\n",
1237 ret = ASN1_INTEGER_to_BN(ai, NULL);
1239 BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1249 ERR_print_errors(bio_err);
1251 ASN1_INTEGER_free(ai);
1255 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1256 ASN1_INTEGER **retai)
1261 ASN1_INTEGER *ai = NULL;
1265 j = strlen(serialfile);
1267 j = strlen(serialfile) + strlen(suffix) + 1;
1269 BIO_printf(bio_err, "File name too long\n");
1274 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1276 #ifndef OPENSSL_SYS_VMS
1277 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1279 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1282 out = BIO_new_file(buf[0], "w");
1287 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1288 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1291 i2a_ASN1_INTEGER(out, ai);
1292 BIO_puts(out, "\n");
1300 ERR_print_errors(bio_err);
1302 ASN1_INTEGER_free(ai);
1306 int rotate_serial(const char *serialfile, const char *new_suffix,
1307 const char *old_suffix)
1312 i = strlen(serialfile) + strlen(old_suffix);
1313 j = strlen(serialfile) + strlen(new_suffix);
1316 if (j + 1 >= BSIZE) {
1317 BIO_printf(bio_err, "File name too long\n");
1320 #ifndef OPENSSL_SYS_VMS
1321 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1322 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1324 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1325 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1327 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1333 "Unable to rename %s to %s\n", serialfile, buf[1]);
1337 if (rename(buf[0], serialfile) < 0) {
1339 "Unable to rename %s to %s\n", buf[0], serialfile);
1341 rename(buf[1], serialfile);
1346 ERR_print_errors(bio_err);
1350 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1355 btmp = b == NULL ? BN_new() : b;
1359 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1361 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1374 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1376 CA_DB *retdb = NULL;
1377 TXT_DB *tmpdb = NULL;
1379 CONF *dbattr_conf = NULL;
1381 #ifndef OPENSSL_NO_POSIX_IO
1386 in = BIO_new_file(dbfile, "r");
1390 #ifndef OPENSSL_NO_POSIX_IO
1391 BIO_get_fp(in, &dbfp);
1392 if (fstat(fileno(dbfp), &dbst) == -1) {
1393 ERR_raise_data(ERR_LIB_SYS, errno,
1394 "calling fstat(%s)", dbfile);
1399 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1402 #ifndef OPENSSL_SYS_VMS
1403 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1405 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1407 dbattr_conf = app_load_config_quiet(buf);
1409 retdb = app_malloc(sizeof(*retdb), "new DB");
1413 retdb->attributes = *db_attr;
1415 retdb->attributes.unique_subject = 1;
1419 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1421 retdb->attributes.unique_subject = parse_yesno(p, 1);
1425 retdb->dbfname = OPENSSL_strdup(dbfile);
1426 #ifndef OPENSSL_NO_POSIX_IO
1431 ERR_print_errors(bio_err);
1432 NCONF_free(dbattr_conf);
1439 * Returns > 0 on success, <= 0 on error
1441 int index_index(CA_DB *db)
1443 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1444 LHASH_HASH_FN(index_serial),
1445 LHASH_COMP_FN(index_serial))) {
1447 "Error creating serial number index:(%ld,%ld,%ld)\n",
1448 db->db->error, db->db->arg1, db->db->arg2);
1452 if (db->attributes.unique_subject
1453 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1454 LHASH_HASH_FN(index_name),
1455 LHASH_COMP_FN(index_name))) {
1456 BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1457 db->db->error, db->db->arg1, db->db->arg2);
1462 ERR_print_errors(bio_err);
1466 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1472 j = strlen(dbfile) + strlen(suffix);
1473 if (j + 6 >= BSIZE) {
1474 BIO_printf(bio_err, "File name too long\n");
1477 #ifndef OPENSSL_SYS_VMS
1478 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1479 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1480 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1482 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1483 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1484 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1486 out = BIO_new_file(buf[0], "w");
1489 BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1492 j = TXT_DB_write(out, db->db);
1497 out = BIO_new_file(buf[1], "w");
1500 BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1503 BIO_printf(out, "unique_subject = %s\n",
1504 db->attributes.unique_subject ? "yes" : "no");
1509 ERR_print_errors(bio_err);
1513 int rotate_index(const char *dbfile, const char *new_suffix,
1514 const char *old_suffix)
1519 i = strlen(dbfile) + strlen(old_suffix);
1520 j = strlen(dbfile) + strlen(new_suffix);
1523 if (j + 6 >= BSIZE) {
1524 BIO_printf(bio_err, "File name too long\n");
1527 #ifndef OPENSSL_SYS_VMS
1528 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1529 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1530 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1531 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1532 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1534 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1535 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1536 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1537 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1538 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1540 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1545 BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1549 if (rename(buf[0], dbfile) < 0) {
1550 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1552 rename(buf[1], dbfile);
1555 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1560 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1562 rename(dbfile, buf[0]);
1563 rename(buf[1], dbfile);
1566 if (rename(buf[2], buf[4]) < 0) {
1567 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1569 rename(buf[3], buf[4]);
1570 rename(dbfile, buf[0]);
1571 rename(buf[1], dbfile);
1576 ERR_print_errors(bio_err);
1580 void free_index(CA_DB *db)
1583 TXT_DB_free(db->db);
1584 OPENSSL_free(db->dbfname);
1589 int parse_yesno(const char *str, int def)
1593 case 'f': /* false */
1594 case 'F': /* FALSE */
1599 case 't': /* true */
1600 case 'T': /* TRUE */
1611 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1612 * where characters may be escaped by \
1614 X509_NAME *parse_name(const char *cp, long chtype, int canmulti)
1616 int nextismulti = 0;
1622 "name is expected to be in the format "
1623 "/type0=value0/type1=value1/type2=... where characters may "
1624 "be escaped by \\. This name is not in that format: '%s'\n",
1629 n = X509_NAME_new();
1632 work = OPENSSL_strdup(cp);
1634 BIO_printf(bio_err, "%s: Error copying name input\n", opt_getprog());
1641 unsigned char *valstr;
1643 int ismulti = nextismulti;
1646 /* Collect the type */
1647 while (*cp && *cp != '=')
1651 "%s: Hit end of string before finding the '='\n",
1658 /* Collect the value. */
1659 valstr = (unsigned char *)bp;
1660 for (; *cp && *cp != '/'; *bp++ = *cp++) {
1661 if (canmulti && *cp == '+') {
1665 if (*cp == '\\' && *++cp == '\0') {
1667 "%s: Escape character at end of string\n",
1674 /* If not at EOS (must be + or /), move forward. */
1679 nid = OBJ_txt2nid(typestr);
1680 if (nid == NID_undef) {
1681 BIO_printf(bio_err, "%s: Skipping unknown attribute \"%s\"\n",
1682 opt_getprog(), typestr);
1685 if (*valstr == '\0') {
1687 "%s: No value provided for Subject Attribute %s, skipped\n",
1688 opt_getprog(), typestr);
1691 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1692 valstr, strlen((char *)valstr),
1693 -1, ismulti ? -1 : 0)) {
1694 BIO_printf(bio_err, "%s: Error adding name attribute \"/%s=%s\"\n",
1695 opt_getprog(), typestr ,valstr);
1710 * Read whole contents of a BIO into an allocated memory buffer and return
1714 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1718 unsigned char tbuf[1024];
1720 mem = BIO_new(BIO_s_mem());
1724 if ((maxlen != -1) && maxlen < 1024)
1728 len = BIO_read(in, tbuf, len);
1735 if (BIO_write(mem, tbuf, len) != len) {
1744 ret = BIO_get_mem_data(mem, (char **)out);
1745 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1750 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1753 char *stmp, *vtmp = NULL;
1754 stmp = OPENSSL_strdup(value);
1757 vtmp = strchr(stmp, ':');
1762 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1767 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1769 X509_POLICY_NODE *node;
1772 BIO_printf(bio_err, "%s Policies:", name);
1774 BIO_puts(bio_err, "\n");
1775 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1776 node = sk_X509_POLICY_NODE_value(nodes, i);
1777 X509_POLICY_NODE_print(bio_err, node, 2);
1780 BIO_puts(bio_err, " <empty>\n");
1784 void policies_print(X509_STORE_CTX *ctx)
1786 X509_POLICY_TREE *tree;
1787 int explicit_policy;
1788 tree = X509_STORE_CTX_get0_policy_tree(ctx);
1789 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1791 BIO_printf(bio_err, "Require explicit Policy: %s\n",
1792 explicit_policy ? "True" : "False");
1794 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1795 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1799 * next_protos_parse parses a comma separated list of strings into a string
1800 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1801 * outlen: (output) set to the length of the resulting buffer on success.
1802 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1803 * in: a NUL terminated string like "abc,def,ghi"
1805 * returns: a malloc'd buffer or NULL on failure.
1807 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1811 size_t i, start = 0;
1815 if (len == 0 || len >= 65535)
1818 out = app_malloc(len + 1, "NPN buffer");
1819 for (i = 0; i <= len; ++i) {
1820 if (i == len || in[i] == ',') {
1822 * Zero-length ALPN elements are invalid on the wire, we could be
1823 * strict and reject the entire string, but just ignoring extra
1824 * commas seems harmless and more friendly.
1826 * Every comma we skip in this way puts the input buffer another
1827 * byte ahead of the output buffer, so all stores into the output
1828 * buffer need to be decremented by the number commas skipped.
1835 if (i - start > 255) {
1839 out[start-skipped] = (unsigned char)(i - start);
1842 out[i + 1 - skipped] = in[i];
1846 if (len <= skipped) {
1851 *outlen = len + 1 - skipped;
1855 void print_cert_checks(BIO *bio, X509 *x,
1856 const char *checkhost,
1857 const char *checkemail, const char *checkip)
1862 BIO_printf(bio, "Hostname %s does%s match certificate\n",
1864 X509_check_host(x, checkhost, 0, 0, NULL) == 1
1869 BIO_printf(bio, "Email %s does%s match certificate\n",
1870 checkemail, X509_check_email(x, checkemail, 0, 0)
1875 BIO_printf(bio, "IP %s does%s match certificate\n",
1876 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1880 /* Get first http URL from a DIST_POINT structure */
1882 static const char *get_dp_url(DIST_POINT *dp)
1884 GENERAL_NAMES *gens;
1888 if (!dp->distpoint || dp->distpoint->type != 0)
1890 gens = dp->distpoint->name.fullname;
1891 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1892 gen = sk_GENERAL_NAME_value(gens, i);
1893 uri = GENERAL_NAME_get0_value(gen, >ype);
1894 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1895 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
1896 if (strncmp(uptr, "http://", 7) == 0)
1904 * Look through a CRLDP structure and attempt to find an http URL to
1905 * downloads a CRL from.
1908 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1911 const char *urlptr = NULL;
1912 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1913 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1914 urlptr = get_dp_url(dp);
1916 return load_crl(urlptr, FORMAT_HTTP, "CRL via CDP");
1922 * Example of downloading CRLs from CRLDP:
1923 * not usable for real world as it always downloads and doesn't cache anything.
1926 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
1927 const X509_NAME *nm)
1930 STACK_OF(X509_CRL) *crls = NULL;
1932 STACK_OF(DIST_POINT) *crldp;
1934 crls = sk_X509_CRL_new_null();
1937 x = X509_STORE_CTX_get_current_cert(ctx);
1938 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
1939 crl = load_crl_crldp(crldp);
1940 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1942 sk_X509_CRL_free(crls);
1945 sk_X509_CRL_push(crls, crl);
1946 /* Try to download delta CRL */
1947 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
1948 crl = load_crl_crldp(crldp);
1949 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1951 sk_X509_CRL_push(crls, crl);
1955 void store_setup_crl_download(X509_STORE *st)
1957 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
1960 #ifndef OPENSSL_NO_SOCK
1961 static const char *tls_error_hint(void)
1963 unsigned long err = ERR_peek_error();
1965 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
1966 err = ERR_peek_last_error();
1967 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
1970 switch (ERR_GET_REASON(err)) {
1971 case SSL_R_WRONG_VERSION_NUMBER:
1972 return "The server does not support (a suitable version of) TLS";
1973 case SSL_R_UNKNOWN_PROTOCOL:
1974 return "The server does not support HTTPS";
1975 case SSL_R_CERTIFICATE_VERIFY_FAILED:
1976 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
1977 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
1978 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
1979 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
1980 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
1981 default: /* no error or no hint available for error */
1986 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
1987 BIO *app_http_tls_cb(BIO *hbio, void *arg, int connect, int detail)
1989 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
1990 SSL_CTX *ssl_ctx = info->ssl_ctx;
1994 if (connect && detail) { /* connecting with TLS */
1995 if ((info->use_proxy
1996 && !OSSL_HTTP_proxy_connect(hbio, info->server, info->port,
1997 NULL, NULL, /* no proxy credentials */
1998 info->timeout, bio_err, opt_getprog()))
1999 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
2002 if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
2007 SSL_set_tlsext_host_name(ssl, info->server);
2009 SSL_set_connect_state(ssl);
2010 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2012 hbio = BIO_push(sbio, hbio);
2013 } else if (!connect && !detail) { /* disconnecting after error */
2014 const char *hint = tls_error_hint();
2016 ERR_add_error_data(2, " : ", hint);
2018 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2019 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2025 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2026 const char *no_proxy, SSL_CTX *ssl_ctx,
2027 const STACK_OF(CONF_VALUE) *headers,
2028 long timeout, const char *expected_content_type,
2029 const ASN1_ITEM *it)
2031 APP_HTTP_TLS_INFO info;
2035 ASN1_VALUE *resp = NULL;
2037 if (url == NULL || it == NULL) {
2038 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2042 if (!OSSL_HTTP_parse_url(url, &server, &port, NULL /* ppath */, &use_ssl))
2044 if (use_ssl && ssl_ctx == NULL) {
2045 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2046 ERR_add_error_data(1, "missing SSL_CTX");
2050 info.server = server;
2052 info.use_proxy = proxy != NULL;
2053 info.timeout = timeout;
2054 info.ssl_ctx = ssl_ctx;
2055 resp = OSSL_HTTP_get_asn1(url, proxy, no_proxy,
2056 NULL, NULL, app_http_tls_cb, &info,
2057 headers, 0 /* maxline */, 0 /* max_resp_len */,
2058 timeout, expected_content_type, it);
2060 OPENSSL_free(server);
2066 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2067 const char *path, const char *proxy,
2068 const char *no_proxy, SSL_CTX *ssl_ctx,
2069 const STACK_OF(CONF_VALUE) *headers,
2070 const char *content_type,
2071 ASN1_VALUE *req, const ASN1_ITEM *req_it,
2072 long timeout, const ASN1_ITEM *rsp_it)
2074 APP_HTTP_TLS_INFO info;
2078 info.use_proxy = proxy != NULL;
2079 info.timeout = timeout;
2080 info.ssl_ctx = ssl_ctx;
2081 return OSSL_HTTP_post_asn1(host, port, path, ssl_ctx != NULL,
2083 NULL, NULL, app_http_tls_cb, &info,
2084 headers, content_type, req, req_it,
2086 0 /* max_resp_len */, timeout, NULL, rsp_it);
2092 * Platform-specific sections
2097 # define fileno(a) (int)_fileno(a)
2100 # include <windows.h>
2103 static int WIN32_rename(const char *from, const char *to)
2105 TCHAR *tfrom = NULL, *tto;
2109 if (sizeof(TCHAR) == 1) {
2110 tfrom = (TCHAR *)from;
2112 } else { /* UNICODE path */
2114 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2115 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2119 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2120 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2122 for (i = 0; i < flen; i++)
2123 tfrom[i] = (TCHAR)from[i];
2124 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2125 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2127 for (i = 0; i < tlen; i++)
2128 tto[i] = (TCHAR)to[i];
2131 if (MoveFile(tfrom, tto))
2133 err = GetLastError();
2134 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2135 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2137 err = GetLastError();
2139 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2141 else if (err == ERROR_ACCESS_DENIED)
2144 errno = EINVAL; /* we could map more codes... */
2148 if (tfrom != NULL && tfrom != (TCHAR *)from)
2154 /* app_tminterval section */
2156 double app_tminterval(int stop, int usertime)
2160 static ULARGE_INTEGER tmstart;
2161 static int warning = 1;
2162 # ifdef _WIN32_WINNT
2163 static HANDLE proc = NULL;
2167 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2168 GetCurrentProcessId());
2170 proc = (HANDLE) - 1;
2173 if (usertime && proc != (HANDLE) - 1) {
2175 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2181 if (usertime && warning) {
2182 BIO_printf(bio_err, "To get meaningful results, run "
2183 "this program on idle system.\n");
2186 GetSystemTime(&systime);
2187 SystemTimeToFileTime(&systime, &now);
2190 if (stop == TM_START) {
2191 tmstart.u.LowPart = now.dwLowDateTime;
2192 tmstart.u.HighPart = now.dwHighDateTime;
2194 ULARGE_INTEGER tmstop;
2196 tmstop.u.LowPart = now.dwLowDateTime;
2197 tmstop.u.HighPart = now.dwHighDateTime;
2199 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2204 #elif defined(OPENSSL_SYS_VXWORKS)
2207 double app_tminterval(int stop, int usertime)
2210 # ifdef CLOCK_REALTIME
2211 static struct timespec tmstart;
2212 struct timespec now;
2214 static unsigned long tmstart;
2217 static int warning = 1;
2219 if (usertime && warning) {
2220 BIO_printf(bio_err, "To get meaningful results, run "
2221 "this program on idle system.\n");
2224 # ifdef CLOCK_REALTIME
2225 clock_gettime(CLOCK_REALTIME, &now);
2226 if (stop == TM_START)
2229 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2230 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2233 if (stop == TM_START)
2236 ret = (now - tmstart) / (double)sysClkRateGet();
2241 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2242 # include <sys/times.h>
2244 double app_tminterval(int stop, int usertime)
2248 clock_t now = times(&rus);
2249 static clock_t tmstart;
2252 now = rus.tms_utime;
2254 if (stop == TM_START) {
2257 long int tck = sysconf(_SC_CLK_TCK);
2258 ret = (now - tmstart) / (double)tck;
2265 # include <sys/time.h>
2266 # include <sys/resource.h>
2268 double app_tminterval(int stop, int usertime)
2273 static struct timeval tmstart;
2276 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2278 gettimeofday(&now, NULL);
2280 if (stop == TM_START)
2283 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2284 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2290 int app_access(const char* name, int flag)
2293 return _access(name, flag);
2295 return access(name, flag);
2299 int app_isdir(const char *name)
2301 return opt_isdir(name);
2304 /* raw_read|write section */
2306 # include "vms_term_sock.h"
2307 static int stdin_sock = -1;
2309 static void close_stdin_sock(void)
2311 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2314 int fileno_stdin(void)
2316 if (stdin_sock == -1) {
2317 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2318 atexit(close_stdin_sock);
2324 int fileno_stdin(void)
2326 return fileno(stdin);
2330 int fileno_stdout(void)
2332 return fileno(stdout);
2335 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2336 int raw_read_stdin(void *buf, int siz)
2339 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2344 #elif defined(__VMS)
2345 # include <sys/socket.h>
2347 int raw_read_stdin(void *buf, int siz)
2349 return recv(fileno_stdin(), buf, siz, 0);
2352 int raw_read_stdin(void *buf, int siz)
2354 return read(fileno_stdin(), buf, siz);
2358 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2359 int raw_write_stdout(const void *buf, int siz)
2362 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2368 int raw_write_stdout(const void *buf, int siz)
2370 return write(fileno_stdout(), buf, siz);
2375 * Centralized handling of input and output files with format specification
2376 * The format is meant to show what the input and output is supposed to be,
2377 * and is therefore a show of intent more than anything else. However, it
2378 * does impact behavior on some platforms, such as differentiating between
2379 * text and binary input/output on non-Unix platforms
2381 BIO *dup_bio_in(int format)
2383 return BIO_new_fp(stdin,
2384 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2387 BIO *dup_bio_out(int format)
2389 BIO *b = BIO_new_fp(stdout,
2390 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2391 void *prefix = NULL;
2393 #ifdef OPENSSL_SYS_VMS
2394 if (FMT_istext(format))
2395 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2398 if (FMT_istext(format)
2399 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2400 b = BIO_push(BIO_new(BIO_f_prefix()), b);
2401 BIO_set_prefix(b, prefix);
2407 BIO *dup_bio_err(int format)
2409 BIO *b = BIO_new_fp(stderr,
2410 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2411 #ifdef OPENSSL_SYS_VMS
2412 if (FMT_istext(format))
2413 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2418 void unbuffer(FILE *fp)
2421 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2422 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2423 * However, we trust that the C RTL will never give us a FILE pointer
2424 * above the first 4 GB of memory, so we simply turn off the warning
2427 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2428 # pragma environment save
2429 # pragma message disable maylosedata2
2432 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2433 # pragma environment restore
2437 static const char *modestr(char mode, int format)
2439 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2443 return FMT_istext(format) ? "a" : "ab";
2445 return FMT_istext(format) ? "r" : "rb";
2447 return FMT_istext(format) ? "w" : "wb";
2449 /* The assert above should make sure we never reach this point */
2453 static const char *modeverb(char mode)
2463 return "(doing something)";
2467 * Open a file for writing, owner-read-only.
2469 BIO *bio_open_owner(const char *filename, int format, int private)
2473 int fd = -1, bflags, mode, textmode;
2475 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2476 return bio_open_default(filename, 'w', format);
2485 textmode = FMT_istext(format);
2489 #elif defined(_O_BINARY)
2494 #ifdef OPENSSL_SYS_VMS
2495 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2496 * it still needs to know that we're going binary, or fdopen()
2497 * will fail with "invalid argument"... so we tell VMS what the
2501 fd = open(filename, mode, 0600, "ctx=bin");
2504 fd = open(filename, mode, 0600);
2507 fp = fdopen(fd, modestr('w', format));
2512 bflags |= BIO_FP_TEXT;
2513 b = BIO_new_fp(fp, bflags);
2518 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2519 opt_getprog(), filename, strerror(errno));
2520 ERR_print_errors(bio_err);
2521 /* If we have fp, then fdopen took over fd, so don't close both. */
2529 static BIO *bio_open_default_(const char *filename, char mode, int format,
2534 if (filename == NULL || strcmp(filename, "-") == 0) {
2535 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2543 "Can't open %s, %s\n",
2544 mode == 'r' ? "stdin" : "stdout", strerror(errno));
2546 ret = BIO_new_file(filename, modestr(mode, format));
2554 "Can't open %s for %s, %s\n",
2555 filename, modeverb(mode), strerror(errno));
2557 ERR_print_errors(bio_err);
2561 BIO *bio_open_default(const char *filename, char mode, int format)
2563 return bio_open_default_(filename, mode, format, 0);
2566 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2568 return bio_open_default_(filename, mode, format, 1);
2571 void wait_for_async(SSL *s)
2573 /* On Windows select only works for sockets, so we simply don't wait */
2574 #ifndef OPENSSL_SYS_WINDOWS
2581 if (!SSL_get_all_async_fds(s, NULL, &numfds))
2585 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2586 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2592 for (i = 0; i < numfds; i++) {
2593 if (width <= (int)fds[i])
2594 width = (int)fds[i] + 1;
2595 openssl_fdset((int)fds[i], &asyncfds);
2597 select(width, (void *)&asyncfds, NULL, NULL, NULL);
2602 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2603 #if defined(OPENSSL_SYS_MSDOS)
2604 int has_stdin_waiting(void)
2606 # if defined(OPENSSL_SYS_WINDOWS)
2607 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2609 INPUT_RECORD inputrec;
2613 if (inhand == INVALID_HANDLE_VALUE) {
2617 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2619 /* Probably redirected input? _kbhit() does not work in this case */
2630 /* Corrupt a signature by modifying final byte */
2631 void corrupt_signature(const ASN1_STRING *signature)
2633 unsigned char *s = signature->data;
2634 s[signature->length - 1] ^= 0x1;
2637 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2640 if (startdate == NULL || strcmp(startdate, "today") == 0) {
2641 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2644 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2647 if (enddate == NULL) {
2648 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2651 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2657 void make_uppercase(char *string)
2661 for (i = 0; string[i] != '\0'; i++)
2662 string[i] = toupper((unsigned char)string[i]);
2665 int opt_printf_stderr(const char *fmt, ...)
2671 ret = BIO_vprintf(bio_err, fmt, ap);
2676 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
2677 const OSSL_PARAM *paramdefs)
2679 OSSL_PARAM *params = NULL;
2680 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
2682 char *opt = "", *stmp, *vtmp = NULL;
2688 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
2692 for (params_n = 0; params_n < sz; params_n++) {
2693 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
2694 if ((stmp = OPENSSL_strdup(opt)) == NULL
2695 || (vtmp = strchr(stmp, ':')) == NULL)
2697 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2699 /* Skip over the separator so that vmtp points to the value */
2701 if (!OSSL_PARAM_allocate_from_text(¶ms[params_n], paramdefs,
2702 stmp, vtmp, strlen(vtmp), &found))
2706 params[params_n] = OSSL_PARAM_construct_end();
2710 BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
2712 ERR_print_errors(bio_err);
2713 app_params_free(params);
2717 void app_params_free(OSSL_PARAM *params)
2721 if (params != NULL) {
2722 for (i = 0; params[i].key != NULL; ++i)
2723 OPENSSL_free(params[i].data);
2724 OPENSSL_free(params);