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";
441 (void)load_key_cert_crl(uri, maybe_stdin, pass, desc, NULL, &cert, NULL);
443 BIO_printf(bio_err, "Unable to load %s\n", desc);
444 ERR_print_errors(bio_err);
449 /* the format parameter is meanwhile not needed anymore and thus ignored */
450 X509 *load_cert(const char *uri, int format, const char *desc)
452 return load_cert_pass(uri, 1, NULL, desc);
455 /* the format parameter is meanwhile not needed anymore and thus ignored */
456 X509_CRL *load_crl(const char *uri, int format, const char *desc)
458 X509_CRL *crl = NULL;
462 (void)load_key_cert_crl(uri, 0, NULL, desc, NULL, NULL, &crl);
464 BIO_printf(bio_err, "Unable to load %s\n", desc);
465 ERR_print_errors(bio_err);
470 X509_REQ *load_csr(const char *file, int format, const char *desc)
472 X509_REQ *req = NULL;
477 in = bio_open_default(file, 'r', format);
481 if (format == FORMAT_ASN1)
482 req = d2i_X509_REQ_bio(in, NULL);
483 else if (format == FORMAT_PEM)
484 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
486 print_format_error(format, OPT_FMT_PEMDER);
490 BIO_printf(bio_err, "Unable to load %s\n", desc);
491 ERR_print_errors(bio_err);
497 void cleanse(char *str)
500 OPENSSL_cleanse(str, strlen(str));
503 void clear_free(char *str)
506 OPENSSL_clear_free(str, strlen(str));
509 EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
510 const char *pass, ENGINE *e, const char *desc)
512 EVP_PKEY *pkey = NULL;
515 desc = "private key";
517 if (format == FORMAT_ENGINE) {
519 BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
521 #ifndef OPENSSL_NO_ENGINE
524 cb_data.password = pass;
525 cb_data.prompt_info = uri;
526 if (ENGINE_init(e)) {
527 pkey = ENGINE_load_private_key(e, uri,
528 (UI_METHOD *)get_ui_method(),
533 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
534 ERR_print_errors(bio_err);
537 BIO_printf(bio_err, "Engines not supported for loading %s\n", desc);
541 (void)load_key_cert_crl(uri, may_stdin, pass, desc, &pkey, NULL, NULL);
545 BIO_printf(bio_err, "Unable to load %s\n", desc);
546 ERR_print_errors(bio_err);
551 EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
552 const char *pass, ENGINE *e, const char *desc)
554 EVP_PKEY *pkey = NULL;
559 if (format == FORMAT_ENGINE) {
561 BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
563 #ifndef OPENSSL_NO_ENGINE
566 cb_data.password = pass;
567 cb_data.prompt_info = uri;
568 pkey = ENGINE_load_public_key(e, uri, (UI_METHOD *)get_ui_method(),
571 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
572 ERR_print_errors(bio_err);
575 BIO_printf(bio_err, "Engines not supported for loading %s\n", desc);
579 (void)load_key_cert_crl(uri, maybe_stdin, pass, desc, &pkey,
583 BIO_printf(bio_err, "Unable to load %s\n", desc);
584 ERR_print_errors(bio_err);
589 static int load_certs_crls(const char *file, int format,
590 const char *pass, const char *desc,
591 STACK_OF(X509) **pcerts,
592 STACK_OF(X509_CRL) **pcrls)
596 STACK_OF(X509_INFO) *xis = NULL;
601 cb_data.password = pass;
602 cb_data.prompt_info = file;
604 if (format != FORMAT_PEM) {
605 BIO_printf(bio_err, "Bad input format specified for %s\n", desc);
609 bio = bio_open_default(file, 'r', FORMAT_PEM);
613 xis = PEM_X509_INFO_read_bio(bio, NULL,
614 (pem_password_cb *)password_callback,
619 if (pcerts != NULL && *pcerts == NULL) {
620 *pcerts = sk_X509_new_null();
625 if (pcrls != NULL && *pcrls == NULL) {
626 *pcrls = sk_X509_CRL_new_null();
631 for (i = 0; i < sk_X509_INFO_num(xis); i++) {
632 xi = sk_X509_INFO_value(xis, i);
633 if (xi->x509 != NULL && pcerts != NULL) {
634 if (!sk_X509_push(*pcerts, xi->x509))
638 if (xi->crl != NULL && pcrls != NULL) {
639 if (!sk_X509_CRL_push(*pcrls, xi->crl))
645 if (pcerts != NULL && sk_X509_num(*pcerts) > 0)
648 if (pcrls != NULL && sk_X509_CRL_num(*pcrls) > 0)
653 sk_X509_INFO_pop_free(xis, X509_INFO_free);
656 if (pcerts != NULL) {
657 sk_X509_pop_free(*pcerts, X509_free);
661 sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
664 BIO_printf(bio_err, "Unable to load %s\n", desc != NULL ? desc :
665 pcerts != NULL ? "certificates" : "CRLs");
670 void app_bail_out(char *fmt, ...)
675 BIO_vprintf(bio_err, fmt, args);
677 ERR_print_errors(bio_err);
681 void* app_malloc(int sz, const char *what)
683 void *vp = OPENSSL_malloc(sz);
686 app_bail_out("%s: Could not allocate %d bytes for %s\n",
687 opt_getprog(), sz, what);
692 * Initialize or extend, if *certs != NULL, a certificate stack.
694 int load_certs(const char *file, STACK_OF(X509) **certs, int format,
695 const char *pass, const char *desc)
697 return load_certs_crls(file, format, pass, desc, certs, NULL);
701 * Initialize or extend, if *crls != NULL, a certificate stack.
703 int load_crls(const char *file, STACK_OF(X509_CRL) **crls, int format,
704 const char *pass, const char *desc)
706 return load_certs_crls(file, format, pass, desc, NULL, crls);
710 * Load those types of credentials for which the result pointer is not NULL.
711 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
712 * For each type the first credential found in the store is loaded.
713 * May yield partial result even if rv == 0.
715 int load_key_cert_crl(const char *uri, int maybe_stdin,
716 const char *pass, const char *desc,
717 EVP_PKEY **ppkey, X509 **pcert, X509_CRL **pcrl)
720 OSSL_STORE_CTX *ctx = NULL;
722 /* TODO make use of the engine reference 'eng' when loading pkeys */
732 desc = "key/certificate/CRL";
733 uidata.password = pass;
734 uidata.prompt_info = uri;
740 BIO_printf(bio_err, "No filename or uri specified for loading %s\n",
745 bio = BIO_new_fp(stdin, 0);
747 ctx = OSSL_STORE_attach(bio, NULL, "file", NULL,
748 get_ui_method(), &uidata, NULL, NULL);
751 ctx = OSSL_STORE_open(uri, get_ui_method(), &uidata, NULL, NULL);
754 BIO_printf(bio_err, "Could not open file or uri %s for loading %s\n",
760 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
761 int type = info == NULL ? 0 : OSSL_STORE_INFO_get_type(info);
762 const char *infostr =
763 info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
767 if (OSSL_STORE_eof(ctx))
773 case OSSL_STORE_INFO_PKEY:
774 if (ppkey != NULL && *ppkey == NULL)
775 err = ((*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) == NULL);
777 case OSSL_STORE_INFO_CERT:
778 if (pcert != NULL && *pcert == NULL)
779 err = ((*pcert = OSSL_STORE_INFO_get1_CERT(info)) == NULL);
781 case OSSL_STORE_INFO_CRL:
782 if (pcrl != NULL && *pcrl == NULL)
783 err = ((*pcrl = OSSL_STORE_INFO_get1_CRL(info)) == NULL);
786 /* skip any other type */
789 OSSL_STORE_INFO_free(info);
791 BIO_printf(bio_err, "Could not read %s of %s from %s\n",
798 OSSL_STORE_close(ctx);
800 ERR_print_errors(bio_err);
805 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
806 /* Return error for unknown extensions */
807 #define X509V3_EXT_DEFAULT 0
808 /* Print error for unknown extensions */
809 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
810 /* ASN1 parse unknown extensions */
811 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
812 /* BIO_dump unknown extensions */
813 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
815 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
816 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
818 int set_cert_ex(unsigned long *flags, const char *arg)
820 static const NAME_EX_TBL cert_tbl[] = {
821 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
822 {"ca_default", X509_FLAG_CA, 0xffffffffl},
823 {"no_header", X509_FLAG_NO_HEADER, 0},
824 {"no_version", X509_FLAG_NO_VERSION, 0},
825 {"no_serial", X509_FLAG_NO_SERIAL, 0},
826 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
827 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
828 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
829 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
830 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
831 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
832 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
833 {"no_aux", X509_FLAG_NO_AUX, 0},
834 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
835 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
836 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
837 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
838 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
841 return set_multi_opts(flags, arg, cert_tbl);
844 int set_name_ex(unsigned long *flags, const char *arg)
846 static const NAME_EX_TBL ex_tbl[] = {
847 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
848 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
849 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
850 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
851 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
852 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
853 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
854 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
855 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
856 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
857 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
858 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
859 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
860 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
861 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
862 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
863 {"dn_rev", XN_FLAG_DN_REV, 0},
864 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
865 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
866 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
867 {"align", XN_FLAG_FN_ALIGN, 0},
868 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
869 {"space_eq", XN_FLAG_SPC_EQ, 0},
870 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
871 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
872 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
873 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
874 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
877 if (set_multi_opts(flags, arg, ex_tbl) == 0)
879 if (*flags != XN_FLAG_COMPAT
880 && (*flags & XN_FLAG_SEP_MASK) == 0)
881 *flags |= XN_FLAG_SEP_CPLUS_SPC;
885 int set_ext_copy(int *copy_type, const char *arg)
887 if (strcasecmp(arg, "none") == 0)
888 *copy_type = EXT_COPY_NONE;
889 else if (strcasecmp(arg, "copy") == 0)
890 *copy_type = EXT_COPY_ADD;
891 else if (strcasecmp(arg, "copyall") == 0)
892 *copy_type = EXT_COPY_ALL;
898 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
900 STACK_OF(X509_EXTENSION) *exts = NULL;
901 X509_EXTENSION *ext, *tmpext;
904 if (!x || !req || (copy_type == EXT_COPY_NONE))
906 exts = X509_REQ_get_extensions(req);
908 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
909 ext = sk_X509_EXTENSION_value(exts, i);
910 obj = X509_EXTENSION_get_object(ext);
911 idx = X509_get_ext_by_OBJ(x, obj, -1);
912 /* Does extension exist? */
914 /* If normal copy don't override existing extension */
915 if (copy_type == EXT_COPY_ADD)
917 /* Delete all extensions of same type */
919 tmpext = X509_get_ext(x, idx);
920 X509_delete_ext(x, idx);
921 X509_EXTENSION_free(tmpext);
922 idx = X509_get_ext_by_OBJ(x, obj, -1);
925 if (!X509_add_ext(x, ext, -1))
933 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
938 static int set_multi_opts(unsigned long *flags, const char *arg,
939 const NAME_EX_TBL * in_tbl)
941 STACK_OF(CONF_VALUE) *vals;
946 vals = X509V3_parse_list(arg);
947 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
948 val = sk_CONF_VALUE_value(vals, i);
949 if (!set_table_opts(flags, val->name, in_tbl))
952 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
956 static int set_table_opts(unsigned long *flags, const char *arg,
957 const NAME_EX_TBL * in_tbl)
960 const NAME_EX_TBL *ptbl;
966 } else if (c == '+') {
973 for (ptbl = in_tbl; ptbl->name; ptbl++) {
974 if (strcasecmp(arg, ptbl->name) == 0) {
975 *flags &= ~ptbl->mask;
977 *flags |= ptbl->flag;
979 *flags &= ~ptbl->flag;
986 void print_name(BIO *out, const char *title, const X509_NAME *nm,
987 unsigned long lflags)
994 BIO_puts(out, title);
995 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
999 if (lflags == XN_FLAG_COMPAT) {
1000 buf = X509_NAME_oneline(nm, 0, 0);
1002 BIO_puts(out, "\n");
1006 BIO_puts(out, "\n");
1007 X509_NAME_print_ex(out, nm, indent, lflags);
1008 BIO_puts(out, "\n");
1012 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1013 int len, unsigned char *buffer)
1015 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1016 if (BN_is_zero(in)) {
1017 BIO_printf(out, "\n 0x00");
1021 l = BN_bn2bin(in, buffer);
1022 for (i = 0; i < l; i++) {
1023 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1025 BIO_printf(out, "0x%02X,", buffer[i]);
1027 BIO_printf(out, "0x%02X", buffer[i]);
1030 BIO_printf(out, "\n };\n");
1033 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1037 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1038 for (i = 0; i < len; i++) {
1040 BIO_printf(out, "\n ");
1042 BIO_printf(out, "0x%02X, ", d[i]);
1044 BIO_printf(out, "0x%02X", d[i]);
1046 BIO_printf(out, "\n};\n");
1049 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1050 const char *CApath, int noCApath,
1051 const char *CAstore, int noCAstore)
1053 X509_STORE *store = X509_STORE_new();
1054 X509_LOOKUP *lookup;
1059 if (CAfile != NULL || !noCAfile) {
1060 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1063 if (CAfile != NULL) {
1064 if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1065 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1069 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1073 if (CApath != NULL || !noCApath) {
1074 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1077 if (CApath != NULL) {
1078 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1079 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1083 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1087 if (CAstore != NULL || !noCAstore) {
1088 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1091 if (!X509_LOOKUP_add_store(lookup, CAstore)) {
1092 if (CAstore != NULL)
1093 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1101 ERR_print_errors(bio_err);
1102 X509_STORE_free(store);
1106 #ifndef OPENSSL_NO_ENGINE
1107 /* Try to load an engine in a shareable library */
1108 static ENGINE *try_load_engine(const char *engine)
1110 ENGINE *e = ENGINE_by_id("dynamic");
1112 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1113 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1122 ENGINE *setup_engine_methods(const char *id, unsigned int methods, int debug)
1126 #ifndef OPENSSL_NO_ENGINE
1128 if (strcmp(id, "auto") == 0) {
1129 BIO_printf(bio_err, "Enabling auto ENGINE support\n");
1130 ENGINE_register_all_complete();
1133 if ((e = ENGINE_by_id(id)) == NULL
1134 && (e = try_load_engine(id)) == NULL) {
1135 BIO_printf(bio_err, "Invalid engine \"%s\"\n", id);
1136 ERR_print_errors(bio_err);
1140 (void)ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1141 if (!ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0,
1142 (void *)get_ui_method(), 0, 1)
1143 || !ENGINE_set_default(e, methods)) {
1144 BIO_printf(bio_err, "Cannot use engine \"%s\"\n", ENGINE_get_id(e));
1145 ERR_print_errors(bio_err);
1150 BIO_printf(bio_err, "Engine \"%s\" set.\n", ENGINE_get_id(e));
1156 void release_engine(ENGINE *e)
1158 #ifndef OPENSSL_NO_ENGINE
1159 /* Free our "structural" reference. */
1164 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1171 return OPENSSL_LH_strhash(n);
1174 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1175 const OPENSSL_CSTRING *b)
1177 const char *aa, *bb;
1179 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1180 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1181 return strcmp(aa, bb);
1184 static int index_name_qual(char **a)
1186 return (a[0][0] == 'V');
1189 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1191 return OPENSSL_LH_strhash(a[DB_name]);
1194 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1196 return strcmp(a[DB_name], b[DB_name]);
1199 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1200 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1201 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1202 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1205 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1210 ASN1_INTEGER *ai = NULL;
1212 ai = ASN1_INTEGER_new();
1216 in = BIO_new_file(serialfile, "r");
1224 if (ret == NULL || !rand_serial(ret, ai))
1225 BIO_printf(bio_err, "Out of memory\n");
1227 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1228 BIO_printf(bio_err, "Unable to load number from %s\n",
1232 ret = ASN1_INTEGER_to_BN(ai, NULL);
1234 BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1244 ERR_print_errors(bio_err);
1246 ASN1_INTEGER_free(ai);
1250 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1251 ASN1_INTEGER **retai)
1256 ASN1_INTEGER *ai = NULL;
1260 j = strlen(serialfile);
1262 j = strlen(serialfile) + strlen(suffix) + 1;
1264 BIO_printf(bio_err, "File name too long\n");
1269 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1271 #ifndef OPENSSL_SYS_VMS
1272 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1274 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1277 out = BIO_new_file(buf[0], "w");
1282 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1283 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1286 i2a_ASN1_INTEGER(out, ai);
1287 BIO_puts(out, "\n");
1295 ERR_print_errors(bio_err);
1297 ASN1_INTEGER_free(ai);
1301 int rotate_serial(const char *serialfile, const char *new_suffix,
1302 const char *old_suffix)
1307 i = strlen(serialfile) + strlen(old_suffix);
1308 j = strlen(serialfile) + strlen(new_suffix);
1311 if (j + 1 >= BSIZE) {
1312 BIO_printf(bio_err, "File name too long\n");
1315 #ifndef OPENSSL_SYS_VMS
1316 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1317 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1319 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1320 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1322 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1328 "Unable to rename %s to %s\n", serialfile, buf[1]);
1332 if (rename(buf[0], serialfile) < 0) {
1334 "Unable to rename %s to %s\n", buf[0], serialfile);
1336 rename(buf[1], serialfile);
1341 ERR_print_errors(bio_err);
1345 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1350 btmp = b == NULL ? BN_new() : b;
1354 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1356 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1369 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1371 CA_DB *retdb = NULL;
1372 TXT_DB *tmpdb = NULL;
1374 CONF *dbattr_conf = NULL;
1376 #ifndef OPENSSL_NO_POSIX_IO
1381 in = BIO_new_file(dbfile, "r");
1385 #ifndef OPENSSL_NO_POSIX_IO
1386 BIO_get_fp(in, &dbfp);
1387 if (fstat(fileno(dbfp), &dbst) == -1) {
1388 ERR_raise_data(ERR_LIB_SYS, errno,
1389 "calling fstat(%s)", dbfile);
1394 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1397 #ifndef OPENSSL_SYS_VMS
1398 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1400 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1402 dbattr_conf = app_load_config_quiet(buf);
1404 retdb = app_malloc(sizeof(*retdb), "new DB");
1408 retdb->attributes = *db_attr;
1410 retdb->attributes.unique_subject = 1;
1414 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1416 retdb->attributes.unique_subject = parse_yesno(p, 1);
1420 retdb->dbfname = OPENSSL_strdup(dbfile);
1421 #ifndef OPENSSL_NO_POSIX_IO
1426 ERR_print_errors(bio_err);
1427 NCONF_free(dbattr_conf);
1434 * Returns > 0 on success, <= 0 on error
1436 int index_index(CA_DB *db)
1438 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1439 LHASH_HASH_FN(index_serial),
1440 LHASH_COMP_FN(index_serial))) {
1442 "Error creating serial number index:(%ld,%ld,%ld)\n",
1443 db->db->error, db->db->arg1, db->db->arg2);
1447 if (db->attributes.unique_subject
1448 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1449 LHASH_HASH_FN(index_name),
1450 LHASH_COMP_FN(index_name))) {
1451 BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1452 db->db->error, db->db->arg1, db->db->arg2);
1457 ERR_print_errors(bio_err);
1461 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1467 j = strlen(dbfile) + strlen(suffix);
1468 if (j + 6 >= BSIZE) {
1469 BIO_printf(bio_err, "File name too long\n");
1472 #ifndef OPENSSL_SYS_VMS
1473 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1474 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1475 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1477 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1478 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1479 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1481 out = BIO_new_file(buf[0], "w");
1484 BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1487 j = TXT_DB_write(out, db->db);
1492 out = BIO_new_file(buf[1], "w");
1495 BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1498 BIO_printf(out, "unique_subject = %s\n",
1499 db->attributes.unique_subject ? "yes" : "no");
1504 ERR_print_errors(bio_err);
1508 int rotate_index(const char *dbfile, const char *new_suffix,
1509 const char *old_suffix)
1514 i = strlen(dbfile) + strlen(old_suffix);
1515 j = strlen(dbfile) + strlen(new_suffix);
1518 if (j + 6 >= BSIZE) {
1519 BIO_printf(bio_err, "File name too long\n");
1522 #ifndef OPENSSL_SYS_VMS
1523 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1524 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1525 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1526 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1527 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1529 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1530 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1531 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1532 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1533 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1535 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1540 BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1544 if (rename(buf[0], dbfile) < 0) {
1545 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1547 rename(buf[1], dbfile);
1550 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1555 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1557 rename(dbfile, buf[0]);
1558 rename(buf[1], dbfile);
1561 if (rename(buf[2], buf[4]) < 0) {
1562 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1564 rename(buf[3], buf[4]);
1565 rename(dbfile, buf[0]);
1566 rename(buf[1], dbfile);
1571 ERR_print_errors(bio_err);
1575 void free_index(CA_DB *db)
1578 TXT_DB_free(db->db);
1579 OPENSSL_free(db->dbfname);
1584 int parse_yesno(const char *str, int def)
1588 case 'f': /* false */
1589 case 'F': /* FALSE */
1594 case 't': /* true */
1595 case 'T': /* TRUE */
1606 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1607 * where characters may be escaped by \
1609 X509_NAME *parse_name(const char *cp, long chtype, int canmulti)
1611 int nextismulti = 0;
1617 "name is expected to be in the format "
1618 "/type0=value0/type1=value1/type2=... where characters may "
1619 "be escaped by \\. This name is not in that format: '%s'\n",
1624 n = X509_NAME_new();
1627 work = OPENSSL_strdup(cp);
1629 BIO_printf(bio_err, "%s: Error copying name input\n", opt_getprog());
1633 while (*cp != '\0') {
1636 unsigned char *valstr;
1638 int ismulti = nextismulti;
1641 /* Collect the type */
1642 while (*cp != '\0' && *cp != '=')
1646 "%s: Hit end of string before finding the '='\n",
1653 /* Collect the value. */
1654 valstr = (unsigned char *)bp;
1655 for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
1656 if (canmulti && *cp == '+') {
1660 if (*cp == '\\' && *++cp == '\0') {
1662 "%s: Escape character at end of string\n",
1669 /* If not at EOS (must be + or /), move forward. */
1674 nid = OBJ_txt2nid(typestr);
1675 if (nid == NID_undef) {
1676 BIO_printf(bio_err, "%s: Skipping unknown attribute \"%s\"\n",
1677 opt_getprog(), typestr);
1680 if (*valstr == '\0') {
1682 "%s: No value provided for Subject Attribute %s, skipped\n",
1683 opt_getprog(), typestr);
1686 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1687 valstr, strlen((char *)valstr),
1688 -1, ismulti ? -1 : 0)) {
1689 ERR_print_errors(bio_err);
1690 BIO_printf(bio_err, "%s: Error adding name attribute \"/%s=%s\"\n",
1691 opt_getprog(), typestr ,valstr);
1706 * Read whole contents of a BIO into an allocated memory buffer and return
1710 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1714 unsigned char tbuf[1024];
1716 mem = BIO_new(BIO_s_mem());
1720 if ((maxlen != -1) && maxlen < 1024)
1724 len = BIO_read(in, tbuf, len);
1731 if (BIO_write(mem, tbuf, len) != len) {
1740 ret = BIO_get_mem_data(mem, (char **)out);
1741 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1746 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1749 char *stmp, *vtmp = NULL;
1750 stmp = OPENSSL_strdup(value);
1753 vtmp = strchr(stmp, ':');
1758 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1763 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1765 X509_POLICY_NODE *node;
1768 BIO_printf(bio_err, "%s Policies:", name);
1770 BIO_puts(bio_err, "\n");
1771 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1772 node = sk_X509_POLICY_NODE_value(nodes, i);
1773 X509_POLICY_NODE_print(bio_err, node, 2);
1776 BIO_puts(bio_err, " <empty>\n");
1780 void policies_print(X509_STORE_CTX *ctx)
1782 X509_POLICY_TREE *tree;
1783 int explicit_policy;
1784 tree = X509_STORE_CTX_get0_policy_tree(ctx);
1785 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1787 BIO_printf(bio_err, "Require explicit Policy: %s\n",
1788 explicit_policy ? "True" : "False");
1790 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1791 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1795 * next_protos_parse parses a comma separated list of strings into a string
1796 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1797 * outlen: (output) set to the length of the resulting buffer on success.
1798 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1799 * in: a NUL terminated string like "abc,def,ghi"
1801 * returns: a malloc'd buffer or NULL on failure.
1803 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1807 size_t i, start = 0;
1811 if (len == 0 || len >= 65535)
1814 out = app_malloc(len + 1, "NPN buffer");
1815 for (i = 0; i <= len; ++i) {
1816 if (i == len || in[i] == ',') {
1818 * Zero-length ALPN elements are invalid on the wire, we could be
1819 * strict and reject the entire string, but just ignoring extra
1820 * commas seems harmless and more friendly.
1822 * Every comma we skip in this way puts the input buffer another
1823 * byte ahead of the output buffer, so all stores into the output
1824 * buffer need to be decremented by the number commas skipped.
1831 if (i - start > 255) {
1835 out[start-skipped] = (unsigned char)(i - start);
1838 out[i + 1 - skipped] = in[i];
1842 if (len <= skipped) {
1847 *outlen = len + 1 - skipped;
1851 void print_cert_checks(BIO *bio, X509 *x,
1852 const char *checkhost,
1853 const char *checkemail, const char *checkip)
1858 BIO_printf(bio, "Hostname %s does%s match certificate\n",
1860 X509_check_host(x, checkhost, 0, 0, NULL) == 1
1865 BIO_printf(bio, "Email %s does%s match certificate\n",
1866 checkemail, X509_check_email(x, checkemail, 0, 0)
1871 BIO_printf(bio, "IP %s does%s match certificate\n",
1872 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1876 /* Get first http URL from a DIST_POINT structure */
1878 static const char *get_dp_url(DIST_POINT *dp)
1880 GENERAL_NAMES *gens;
1884 if (!dp->distpoint || dp->distpoint->type != 0)
1886 gens = dp->distpoint->name.fullname;
1887 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1888 gen = sk_GENERAL_NAME_value(gens, i);
1889 uri = GENERAL_NAME_get0_value(gen, >ype);
1890 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1891 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
1892 if (strncmp(uptr, "http://", 7) == 0)
1900 * Look through a CRLDP structure and attempt to find an http URL to
1901 * downloads a CRL from.
1904 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1907 const char *urlptr = NULL;
1908 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1909 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1910 urlptr = get_dp_url(dp);
1912 return load_crl(urlptr, FORMAT_HTTP, "CRL via CDP");
1918 * Example of downloading CRLs from CRLDP:
1919 * not usable for real world as it always downloads and doesn't cache anything.
1922 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
1923 const X509_NAME *nm)
1926 STACK_OF(X509_CRL) *crls = NULL;
1928 STACK_OF(DIST_POINT) *crldp;
1930 crls = sk_X509_CRL_new_null();
1933 x = X509_STORE_CTX_get_current_cert(ctx);
1934 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
1935 crl = load_crl_crldp(crldp);
1936 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1938 sk_X509_CRL_free(crls);
1941 sk_X509_CRL_push(crls, crl);
1942 /* Try to download delta CRL */
1943 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
1944 crl = load_crl_crldp(crldp);
1945 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1947 sk_X509_CRL_push(crls, crl);
1951 void store_setup_crl_download(X509_STORE *st)
1953 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
1956 #ifndef OPENSSL_NO_SOCK
1957 static const char *tls_error_hint(void)
1959 unsigned long err = ERR_peek_error();
1961 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
1962 err = ERR_peek_last_error();
1963 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
1966 switch (ERR_GET_REASON(err)) {
1967 case SSL_R_WRONG_VERSION_NUMBER:
1968 return "The server does not support (a suitable version of) TLS";
1969 case SSL_R_UNKNOWN_PROTOCOL:
1970 return "The server does not support HTTPS";
1971 case SSL_R_CERTIFICATE_VERIFY_FAILED:
1972 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
1973 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
1974 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
1975 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
1976 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
1977 default: /* no error or no hint available for error */
1982 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
1983 BIO *app_http_tls_cb(BIO *hbio, void *arg, int connect, int detail)
1985 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
1986 SSL_CTX *ssl_ctx = info->ssl_ctx;
1990 if (connect && detail) { /* connecting with TLS */
1991 if ((info->use_proxy
1992 && !OSSL_HTTP_proxy_connect(hbio, info->server, info->port,
1993 NULL, NULL, /* no proxy credentials */
1994 info->timeout, bio_err, opt_getprog()))
1995 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
1998 if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
2003 SSL_set_tlsext_host_name(ssl, info->server);
2005 SSL_set_connect_state(ssl);
2006 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2008 hbio = BIO_push(sbio, hbio);
2009 } else if (!connect && !detail) { /* disconnecting after error */
2010 const char *hint = tls_error_hint();
2012 ERR_add_error_data(2, " : ", hint);
2014 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2015 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2021 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2022 const char *no_proxy, SSL_CTX *ssl_ctx,
2023 const STACK_OF(CONF_VALUE) *headers,
2024 long timeout, const char *expected_content_type,
2025 const ASN1_ITEM *it)
2027 APP_HTTP_TLS_INFO info;
2031 ASN1_VALUE *resp = NULL;
2033 if (url == NULL || it == NULL) {
2034 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2038 if (!OSSL_HTTP_parse_url(url, &server, &port, NULL /* ppath */, &use_ssl))
2040 if (use_ssl && ssl_ctx == NULL) {
2041 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2042 ERR_add_error_data(1, "missing SSL_CTX");
2046 info.server = server;
2048 info.use_proxy = proxy != NULL;
2049 info.timeout = timeout;
2050 info.ssl_ctx = ssl_ctx;
2051 resp = OSSL_HTTP_get_asn1(url, proxy, no_proxy,
2052 NULL, NULL, app_http_tls_cb, &info,
2053 headers, 0 /* maxline */, 0 /* max_resp_len */,
2054 timeout, expected_content_type, it);
2056 OPENSSL_free(server);
2062 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2063 const char *path, const char *proxy,
2064 const char *no_proxy, SSL_CTX *ssl_ctx,
2065 const STACK_OF(CONF_VALUE) *headers,
2066 const char *content_type,
2067 ASN1_VALUE *req, const ASN1_ITEM *req_it,
2068 long timeout, const ASN1_ITEM *rsp_it)
2070 APP_HTTP_TLS_INFO info;
2074 info.use_proxy = proxy != NULL;
2075 info.timeout = timeout;
2076 info.ssl_ctx = ssl_ctx;
2077 return OSSL_HTTP_post_asn1(host, port, path, ssl_ctx != NULL,
2079 NULL, NULL, app_http_tls_cb, &info,
2080 headers, content_type, req, req_it,
2082 0 /* max_resp_len */, timeout, NULL, rsp_it);
2088 * Platform-specific sections
2093 # define fileno(a) (int)_fileno(a)
2096 # include <windows.h>
2099 static int WIN32_rename(const char *from, const char *to)
2101 TCHAR *tfrom = NULL, *tto;
2105 if (sizeof(TCHAR) == 1) {
2106 tfrom = (TCHAR *)from;
2108 } else { /* UNICODE path */
2110 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2111 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2115 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2116 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2118 for (i = 0; i < flen; i++)
2119 tfrom[i] = (TCHAR)from[i];
2120 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2121 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2123 for (i = 0; i < tlen; i++)
2124 tto[i] = (TCHAR)to[i];
2127 if (MoveFile(tfrom, tto))
2129 err = GetLastError();
2130 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2131 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2133 err = GetLastError();
2135 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2137 else if (err == ERROR_ACCESS_DENIED)
2140 errno = EINVAL; /* we could map more codes... */
2144 if (tfrom != NULL && tfrom != (TCHAR *)from)
2150 /* app_tminterval section */
2152 double app_tminterval(int stop, int usertime)
2156 static ULARGE_INTEGER tmstart;
2157 static int warning = 1;
2158 # ifdef _WIN32_WINNT
2159 static HANDLE proc = NULL;
2163 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2164 GetCurrentProcessId());
2166 proc = (HANDLE) - 1;
2169 if (usertime && proc != (HANDLE) - 1) {
2171 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2177 if (usertime && warning) {
2178 BIO_printf(bio_err, "To get meaningful results, run "
2179 "this program on idle system.\n");
2182 GetSystemTime(&systime);
2183 SystemTimeToFileTime(&systime, &now);
2186 if (stop == TM_START) {
2187 tmstart.u.LowPart = now.dwLowDateTime;
2188 tmstart.u.HighPart = now.dwHighDateTime;
2190 ULARGE_INTEGER tmstop;
2192 tmstop.u.LowPart = now.dwLowDateTime;
2193 tmstop.u.HighPart = now.dwHighDateTime;
2195 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2200 #elif defined(OPENSSL_SYS_VXWORKS)
2203 double app_tminterval(int stop, int usertime)
2206 # ifdef CLOCK_REALTIME
2207 static struct timespec tmstart;
2208 struct timespec now;
2210 static unsigned long tmstart;
2213 static int warning = 1;
2215 if (usertime && warning) {
2216 BIO_printf(bio_err, "To get meaningful results, run "
2217 "this program on idle system.\n");
2220 # ifdef CLOCK_REALTIME
2221 clock_gettime(CLOCK_REALTIME, &now);
2222 if (stop == TM_START)
2225 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2226 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2229 if (stop == TM_START)
2232 ret = (now - tmstart) / (double)sysClkRateGet();
2237 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2238 # include <sys/times.h>
2240 double app_tminterval(int stop, int usertime)
2244 clock_t now = times(&rus);
2245 static clock_t tmstart;
2248 now = rus.tms_utime;
2250 if (stop == TM_START) {
2253 long int tck = sysconf(_SC_CLK_TCK);
2254 ret = (now - tmstart) / (double)tck;
2261 # include <sys/time.h>
2262 # include <sys/resource.h>
2264 double app_tminterval(int stop, int usertime)
2269 static struct timeval tmstart;
2272 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2274 gettimeofday(&now, NULL);
2276 if (stop == TM_START)
2279 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2280 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2286 int app_access(const char* name, int flag)
2289 return _access(name, flag);
2291 return access(name, flag);
2295 int app_isdir(const char *name)
2297 return opt_isdir(name);
2300 /* raw_read|write section */
2302 # include "vms_term_sock.h"
2303 static int stdin_sock = -1;
2305 static void close_stdin_sock(void)
2307 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2310 int fileno_stdin(void)
2312 if (stdin_sock == -1) {
2313 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2314 atexit(close_stdin_sock);
2320 int fileno_stdin(void)
2322 return fileno(stdin);
2326 int fileno_stdout(void)
2328 return fileno(stdout);
2331 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2332 int raw_read_stdin(void *buf, int siz)
2335 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2340 #elif defined(__VMS)
2341 # include <sys/socket.h>
2343 int raw_read_stdin(void *buf, int siz)
2345 return recv(fileno_stdin(), buf, siz, 0);
2348 int raw_read_stdin(void *buf, int siz)
2350 return read(fileno_stdin(), buf, siz);
2354 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2355 int raw_write_stdout(const void *buf, int siz)
2358 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2364 int raw_write_stdout(const void *buf, int siz)
2366 return write(fileno_stdout(), buf, siz);
2371 * Centralized handling of input and output files with format specification
2372 * The format is meant to show what the input and output is supposed to be,
2373 * and is therefore a show of intent more than anything else. However, it
2374 * does impact behavior on some platforms, such as differentiating between
2375 * text and binary input/output on non-Unix platforms
2377 BIO *dup_bio_in(int format)
2379 return BIO_new_fp(stdin,
2380 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2383 BIO *dup_bio_out(int format)
2385 BIO *b = BIO_new_fp(stdout,
2386 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2387 void *prefix = NULL;
2389 #ifdef OPENSSL_SYS_VMS
2390 if (FMT_istext(format))
2391 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2394 if (FMT_istext(format)
2395 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2396 b = BIO_push(BIO_new(BIO_f_prefix()), b);
2397 BIO_set_prefix(b, prefix);
2403 BIO *dup_bio_err(int format)
2405 BIO *b = BIO_new_fp(stderr,
2406 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2407 #ifdef OPENSSL_SYS_VMS
2408 if (FMT_istext(format))
2409 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2414 void unbuffer(FILE *fp)
2417 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2418 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2419 * However, we trust that the C RTL will never give us a FILE pointer
2420 * above the first 4 GB of memory, so we simply turn off the warning
2423 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2424 # pragma environment save
2425 # pragma message disable maylosedata2
2428 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2429 # pragma environment restore
2433 static const char *modestr(char mode, int format)
2435 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2439 return FMT_istext(format) ? "a" : "ab";
2441 return FMT_istext(format) ? "r" : "rb";
2443 return FMT_istext(format) ? "w" : "wb";
2445 /* The assert above should make sure we never reach this point */
2449 static const char *modeverb(char mode)
2459 return "(doing something)";
2463 * Open a file for writing, owner-read-only.
2465 BIO *bio_open_owner(const char *filename, int format, int private)
2469 int fd = -1, bflags, mode, textmode;
2471 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2472 return bio_open_default(filename, 'w', format);
2481 textmode = FMT_istext(format);
2485 #elif defined(_O_BINARY)
2490 #ifdef OPENSSL_SYS_VMS
2491 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2492 * it still needs to know that we're going binary, or fdopen()
2493 * will fail with "invalid argument"... so we tell VMS what the
2497 fd = open(filename, mode, 0600, "ctx=bin");
2500 fd = open(filename, mode, 0600);
2503 fp = fdopen(fd, modestr('w', format));
2508 bflags |= BIO_FP_TEXT;
2509 b = BIO_new_fp(fp, bflags);
2514 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2515 opt_getprog(), filename, strerror(errno));
2516 ERR_print_errors(bio_err);
2517 /* If we have fp, then fdopen took over fd, so don't close both. */
2525 static BIO *bio_open_default_(const char *filename, char mode, int format,
2530 if (filename == NULL || strcmp(filename, "-") == 0) {
2531 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2539 "Can't open %s, %s\n",
2540 mode == 'r' ? "stdin" : "stdout", strerror(errno));
2542 ret = BIO_new_file(filename, modestr(mode, format));
2550 "Can't open %s for %s, %s\n",
2551 filename, modeverb(mode), strerror(errno));
2553 ERR_print_errors(bio_err);
2557 BIO *bio_open_default(const char *filename, char mode, int format)
2559 return bio_open_default_(filename, mode, format, 0);
2562 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2564 return bio_open_default_(filename, mode, format, 1);
2567 void wait_for_async(SSL *s)
2569 /* On Windows select only works for sockets, so we simply don't wait */
2570 #ifndef OPENSSL_SYS_WINDOWS
2577 if (!SSL_get_all_async_fds(s, NULL, &numfds))
2581 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2582 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2588 for (i = 0; i < numfds; i++) {
2589 if (width <= (int)fds[i])
2590 width = (int)fds[i] + 1;
2591 openssl_fdset((int)fds[i], &asyncfds);
2593 select(width, (void *)&asyncfds, NULL, NULL, NULL);
2598 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2599 #if defined(OPENSSL_SYS_MSDOS)
2600 int has_stdin_waiting(void)
2602 # if defined(OPENSSL_SYS_WINDOWS)
2603 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2605 INPUT_RECORD inputrec;
2609 if (inhand == INVALID_HANDLE_VALUE) {
2613 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2615 /* Probably redirected input? _kbhit() does not work in this case */
2626 /* Corrupt a signature by modifying final byte */
2627 void corrupt_signature(const ASN1_STRING *signature)
2629 unsigned char *s = signature->data;
2630 s[signature->length - 1] ^= 0x1;
2633 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2636 if (startdate == NULL || strcmp(startdate, "today") == 0) {
2637 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2640 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2643 if (enddate == NULL) {
2644 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2647 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2653 void make_uppercase(char *string)
2657 for (i = 0; string[i] != '\0'; i++)
2658 string[i] = toupper((unsigned char)string[i]);
2661 int opt_printf_stderr(const char *fmt, ...)
2667 ret = BIO_vprintf(bio_err, fmt, ap);
2672 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
2673 const OSSL_PARAM *paramdefs)
2675 OSSL_PARAM *params = NULL;
2676 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
2678 char *opt = "", *stmp, *vtmp = NULL;
2684 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
2688 for (params_n = 0; params_n < sz; params_n++) {
2689 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
2690 if ((stmp = OPENSSL_strdup(opt)) == NULL
2691 || (vtmp = strchr(stmp, ':')) == NULL)
2693 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2695 /* Skip over the separator so that vmtp points to the value */
2697 if (!OSSL_PARAM_allocate_from_text(¶ms[params_n], paramdefs,
2698 stmp, vtmp, strlen(vtmp), &found))
2702 params[params_n] = OSSL_PARAM_construct_end();
2706 BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
2708 ERR_print_errors(bio_err);
2709 app_params_free(params);
2713 void app_params_free(OSSL_PARAM *params)
2717 if (params != NULL) {
2718 for (i = 0; params[i].key != NULL; ++i)
2719 OPENSSL_free(params[i].data);
2720 OPENSSL_free(params);