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_malloc(int sz, const char *what)
676 void *vp = OPENSSL_malloc(sz);
679 BIO_printf(bio_err, "%s: Could not allocate %d bytes for %s\n",
680 opt_getprog(), sz, what);
681 ERR_print_errors(bio_err);
688 * Initialize or extend, if *certs != NULL, a certificate stack.
690 int load_certs(const char *file, STACK_OF(X509) **certs, int format,
691 const char *pass, const char *desc)
693 return load_certs_crls(file, format, pass, desc, certs, NULL);
697 * Initialize or extend, if *crls != NULL, a certificate stack.
699 int load_crls(const char *file, STACK_OF(X509_CRL) **crls, int format,
700 const char *pass, const char *desc)
702 return load_certs_crls(file, format, pass, desc, NULL, crls);
706 * Load those types of credentials for which the result pointer is not NULL.
707 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
708 * For each type the first credential found in the store is loaded.
709 * May yield partial result even if rv == 0.
711 int load_key_cert_crl(const char *uri, int maybe_stdin,
712 const char *pass, const char *desc,
713 EVP_PKEY **ppkey, X509 **pcert, X509_CRL **pcrl)
716 OSSL_STORE_CTX *ctx = NULL;
718 /* TODO make use of the engine reference 'eng' when loading pkeys */
728 desc = "key/certificate/CRL";
729 uidata.password = pass;
730 uidata.prompt_info = uri;
736 BIO_printf(bio_err, "No filename or uri specified for loading %s\n",
741 bio = BIO_new_fp(stdin, 0);
743 ctx = OSSL_STORE_attach(bio, NULL, "file", NULL,
744 get_ui_method(), &uidata, NULL, NULL);
747 ctx = OSSL_STORE_open(uri, get_ui_method(), &uidata, NULL, NULL);
750 BIO_printf(bio_err, "Could not open file or uri %s for loading %s\n",
756 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
757 int type = info == NULL ? 0 : OSSL_STORE_INFO_get_type(info);
758 const char *infostr =
759 info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
763 if (OSSL_STORE_eof(ctx))
769 case OSSL_STORE_INFO_PKEY:
770 if (ppkey != NULL && *ppkey == NULL)
771 err = ((*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) == NULL);
773 case OSSL_STORE_INFO_CERT:
774 if (pcert != NULL && *pcert == NULL)
775 err = ((*pcert = OSSL_STORE_INFO_get1_CERT(info)) == NULL);
777 case OSSL_STORE_INFO_CRL:
778 if (pcrl != NULL && *pcrl == NULL)
779 err = ((*pcrl = OSSL_STORE_INFO_get1_CRL(info)) == NULL);
782 /* skip any other type */
785 OSSL_STORE_INFO_free(info);
787 BIO_printf(bio_err, "Could not read %s of %s from %s\n",
794 OSSL_STORE_close(ctx);
796 ERR_print_errors(bio_err);
801 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
802 /* Return error for unknown extensions */
803 #define X509V3_EXT_DEFAULT 0
804 /* Print error for unknown extensions */
805 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
806 /* ASN1 parse unknown extensions */
807 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
808 /* BIO_dump unknown extensions */
809 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
811 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
812 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
814 int set_cert_ex(unsigned long *flags, const char *arg)
816 static const NAME_EX_TBL cert_tbl[] = {
817 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
818 {"ca_default", X509_FLAG_CA, 0xffffffffl},
819 {"no_header", X509_FLAG_NO_HEADER, 0},
820 {"no_version", X509_FLAG_NO_VERSION, 0},
821 {"no_serial", X509_FLAG_NO_SERIAL, 0},
822 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
823 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
824 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
825 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
826 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
827 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
828 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
829 {"no_aux", X509_FLAG_NO_AUX, 0},
830 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
831 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
832 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
833 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
834 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
837 return set_multi_opts(flags, arg, cert_tbl);
840 int set_name_ex(unsigned long *flags, const char *arg)
842 static const NAME_EX_TBL ex_tbl[] = {
843 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
844 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
845 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
846 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
847 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
848 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
849 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
850 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
851 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
852 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
853 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
854 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
855 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
856 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
857 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
858 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
859 {"dn_rev", XN_FLAG_DN_REV, 0},
860 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
861 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
862 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
863 {"align", XN_FLAG_FN_ALIGN, 0},
864 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
865 {"space_eq", XN_FLAG_SPC_EQ, 0},
866 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
867 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
868 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
869 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
870 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
873 if (set_multi_opts(flags, arg, ex_tbl) == 0)
875 if (*flags != XN_FLAG_COMPAT
876 && (*flags & XN_FLAG_SEP_MASK) == 0)
877 *flags |= XN_FLAG_SEP_CPLUS_SPC;
881 int set_ext_copy(int *copy_type, const char *arg)
883 if (strcasecmp(arg, "none") == 0)
884 *copy_type = EXT_COPY_NONE;
885 else if (strcasecmp(arg, "copy") == 0)
886 *copy_type = EXT_COPY_ADD;
887 else if (strcasecmp(arg, "copyall") == 0)
888 *copy_type = EXT_COPY_ALL;
894 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
896 STACK_OF(X509_EXTENSION) *exts = NULL;
897 X509_EXTENSION *ext, *tmpext;
900 if (!x || !req || (copy_type == EXT_COPY_NONE))
902 exts = X509_REQ_get_extensions(req);
904 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
905 ext = sk_X509_EXTENSION_value(exts, i);
906 obj = X509_EXTENSION_get_object(ext);
907 idx = X509_get_ext_by_OBJ(x, obj, -1);
908 /* Does extension exist? */
910 /* If normal copy don't override existing extension */
911 if (copy_type == EXT_COPY_ADD)
913 /* Delete all extensions of same type */
915 tmpext = X509_get_ext(x, idx);
916 X509_delete_ext(x, idx);
917 X509_EXTENSION_free(tmpext);
918 idx = X509_get_ext_by_OBJ(x, obj, -1);
921 if (!X509_add_ext(x, ext, -1))
929 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
934 static int set_multi_opts(unsigned long *flags, const char *arg,
935 const NAME_EX_TBL * in_tbl)
937 STACK_OF(CONF_VALUE) *vals;
942 vals = X509V3_parse_list(arg);
943 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
944 val = sk_CONF_VALUE_value(vals, i);
945 if (!set_table_opts(flags, val->name, in_tbl))
948 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
952 static int set_table_opts(unsigned long *flags, const char *arg,
953 const NAME_EX_TBL * in_tbl)
956 const NAME_EX_TBL *ptbl;
962 } else if (c == '+') {
969 for (ptbl = in_tbl; ptbl->name; ptbl++) {
970 if (strcasecmp(arg, ptbl->name) == 0) {
971 *flags &= ~ptbl->mask;
973 *flags |= ptbl->flag;
975 *flags &= ~ptbl->flag;
982 void print_name(BIO *out, const char *title, const X509_NAME *nm,
983 unsigned long lflags)
990 BIO_puts(out, title);
991 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
995 if (lflags == XN_FLAG_COMPAT) {
996 buf = X509_NAME_oneline(nm, 0, 0);
1002 BIO_puts(out, "\n");
1003 X509_NAME_print_ex(out, nm, indent, lflags);
1004 BIO_puts(out, "\n");
1008 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1009 int len, unsigned char *buffer)
1011 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1012 if (BN_is_zero(in)) {
1013 BIO_printf(out, "\n 0x00");
1017 l = BN_bn2bin(in, buffer);
1018 for (i = 0; i < l; i++) {
1019 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1021 BIO_printf(out, "0x%02X,", buffer[i]);
1023 BIO_printf(out, "0x%02X", buffer[i]);
1026 BIO_printf(out, "\n };\n");
1029 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1033 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1034 for (i = 0; i < len; i++) {
1036 BIO_printf(out, "\n ");
1038 BIO_printf(out, "0x%02X, ", d[i]);
1040 BIO_printf(out, "0x%02X", d[i]);
1042 BIO_printf(out, "\n};\n");
1045 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1046 const char *CApath, int noCApath,
1047 const char *CAstore, int noCAstore)
1049 X509_STORE *store = X509_STORE_new();
1050 X509_LOOKUP *lookup;
1055 if (CAfile != NULL || !noCAfile) {
1056 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1059 if (CAfile != NULL) {
1060 if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1061 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1065 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1069 if (CApath != NULL || !noCApath) {
1070 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1073 if (CApath != NULL) {
1074 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1075 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1079 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1083 if (CAstore != NULL || !noCAstore) {
1084 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1087 if (!X509_LOOKUP_add_store(lookup, CAstore)) {
1088 if (CAstore != NULL)
1089 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1097 ERR_print_errors(bio_err);
1098 X509_STORE_free(store);
1102 #ifndef OPENSSL_NO_ENGINE
1103 /* Try to load an engine in a shareable library */
1104 static ENGINE *try_load_engine(const char *engine)
1106 ENGINE *e = ENGINE_by_id("dynamic");
1108 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1109 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1118 ENGINE *setup_engine_methods(const char *id, unsigned int methods, int debug)
1122 #ifndef OPENSSL_NO_ENGINE
1124 if (strcmp(id, "auto") == 0) {
1125 BIO_printf(bio_err, "Enabling auto ENGINE support\n");
1126 ENGINE_register_all_complete();
1129 if ((e = ENGINE_by_id(id)) == NULL
1130 && (e = try_load_engine(id)) == NULL) {
1131 BIO_printf(bio_err, "Invalid engine \"%s\"\n", id);
1132 ERR_print_errors(bio_err);
1136 (void)ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1137 if (!ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0,
1138 (void *)get_ui_method(), 0, 1)
1139 || !ENGINE_set_default(e, methods)) {
1140 BIO_printf(bio_err, "Cannot use engine \"%s\"\n", ENGINE_get_id(e));
1141 ERR_print_errors(bio_err);
1146 BIO_printf(bio_err, "Engine \"%s\" set.\n", ENGINE_get_id(e));
1152 void release_engine(ENGINE *e)
1154 #ifndef OPENSSL_NO_ENGINE
1156 /* Free our "structural" reference. */
1161 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1168 return OPENSSL_LH_strhash(n);
1171 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1172 const OPENSSL_CSTRING *b)
1174 const char *aa, *bb;
1176 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1177 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1178 return strcmp(aa, bb);
1181 static int index_name_qual(char **a)
1183 return (a[0][0] == 'V');
1186 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1188 return OPENSSL_LH_strhash(a[DB_name]);
1191 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1193 return strcmp(a[DB_name], b[DB_name]);
1196 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1197 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1198 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1199 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1202 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1207 ASN1_INTEGER *ai = NULL;
1209 ai = ASN1_INTEGER_new();
1213 in = BIO_new_file(serialfile, "r");
1221 if (ret == NULL || !rand_serial(ret, ai))
1222 BIO_printf(bio_err, "Out of memory\n");
1224 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1225 BIO_printf(bio_err, "Unable to load number from %s\n",
1229 ret = ASN1_INTEGER_to_BN(ai, NULL);
1231 BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1241 ERR_print_errors(bio_err);
1243 ASN1_INTEGER_free(ai);
1247 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1248 ASN1_INTEGER **retai)
1253 ASN1_INTEGER *ai = NULL;
1257 j = strlen(serialfile);
1259 j = strlen(serialfile) + strlen(suffix) + 1;
1261 BIO_printf(bio_err, "File name too long\n");
1266 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1268 #ifndef OPENSSL_SYS_VMS
1269 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1271 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1274 out = BIO_new_file(buf[0], "w");
1279 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1280 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1283 i2a_ASN1_INTEGER(out, ai);
1284 BIO_puts(out, "\n");
1292 ERR_print_errors(bio_err);
1294 ASN1_INTEGER_free(ai);
1298 int rotate_serial(const char *serialfile, const char *new_suffix,
1299 const char *old_suffix)
1304 i = strlen(serialfile) + strlen(old_suffix);
1305 j = strlen(serialfile) + strlen(new_suffix);
1308 if (j + 1 >= BSIZE) {
1309 BIO_printf(bio_err, "File name too long\n");
1312 #ifndef OPENSSL_SYS_VMS
1313 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1314 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
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 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1325 "Unable to rename %s to %s\n", serialfile, buf[1]);
1329 if (rename(buf[0], serialfile) < 0) {
1331 "Unable to rename %s to %s\n", buf[0], serialfile);
1333 rename(buf[1], serialfile);
1338 ERR_print_errors(bio_err);
1342 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1347 btmp = b == NULL ? BN_new() : b;
1351 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1353 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1366 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1368 CA_DB *retdb = NULL;
1369 TXT_DB *tmpdb = NULL;
1371 CONF *dbattr_conf = NULL;
1373 #ifndef OPENSSL_NO_POSIX_IO
1378 in = BIO_new_file(dbfile, "r");
1382 #ifndef OPENSSL_NO_POSIX_IO
1383 BIO_get_fp(in, &dbfp);
1384 if (fstat(fileno(dbfp), &dbst) == -1) {
1385 ERR_raise_data(ERR_LIB_SYS, errno,
1386 "calling fstat(%s)", dbfile);
1391 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1394 #ifndef OPENSSL_SYS_VMS
1395 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1397 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1399 dbattr_conf = app_load_config_quiet(buf);
1401 retdb = app_malloc(sizeof(*retdb), "new DB");
1405 retdb->attributes = *db_attr;
1407 retdb->attributes.unique_subject = 1;
1411 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1413 retdb->attributes.unique_subject = parse_yesno(p, 1);
1417 retdb->dbfname = OPENSSL_strdup(dbfile);
1418 #ifndef OPENSSL_NO_POSIX_IO
1423 ERR_print_errors(bio_err);
1424 NCONF_free(dbattr_conf);
1431 * Returns > 0 on success, <= 0 on error
1433 int index_index(CA_DB *db)
1435 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1436 LHASH_HASH_FN(index_serial),
1437 LHASH_COMP_FN(index_serial))) {
1439 "Error creating serial number index:(%ld,%ld,%ld)\n",
1440 db->db->error, db->db->arg1, db->db->arg2);
1444 if (db->attributes.unique_subject
1445 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1446 LHASH_HASH_FN(index_name),
1447 LHASH_COMP_FN(index_name))) {
1448 BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1449 db->db->error, db->db->arg1, db->db->arg2);
1454 ERR_print_errors(bio_err);
1458 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1464 j = strlen(dbfile) + strlen(suffix);
1465 if (j + 6 >= BSIZE) {
1466 BIO_printf(bio_err, "File name too long\n");
1469 #ifndef OPENSSL_SYS_VMS
1470 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1471 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1472 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1474 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1475 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1476 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1478 out = BIO_new_file(buf[0], "w");
1481 BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1484 j = TXT_DB_write(out, db->db);
1489 out = BIO_new_file(buf[1], "w");
1492 BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1495 BIO_printf(out, "unique_subject = %s\n",
1496 db->attributes.unique_subject ? "yes" : "no");
1501 ERR_print_errors(bio_err);
1505 int rotate_index(const char *dbfile, const char *new_suffix,
1506 const char *old_suffix)
1511 i = strlen(dbfile) + strlen(old_suffix);
1512 j = strlen(dbfile) + strlen(new_suffix);
1515 if (j + 6 >= BSIZE) {
1516 BIO_printf(bio_err, "File name too long\n");
1519 #ifndef OPENSSL_SYS_VMS
1520 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1521 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1522 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1523 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1524 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1526 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1527 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1528 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1529 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1530 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1532 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1537 BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1541 if (rename(buf[0], dbfile) < 0) {
1542 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1544 rename(buf[1], dbfile);
1547 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1552 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1554 rename(dbfile, buf[0]);
1555 rename(buf[1], dbfile);
1558 if (rename(buf[2], buf[4]) < 0) {
1559 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1561 rename(buf[3], buf[4]);
1562 rename(dbfile, buf[0]);
1563 rename(buf[1], dbfile);
1568 ERR_print_errors(bio_err);
1572 void free_index(CA_DB *db)
1575 TXT_DB_free(db->db);
1576 OPENSSL_free(db->dbfname);
1581 int parse_yesno(const char *str, int def)
1585 case 'f': /* false */
1586 case 'F': /* FALSE */
1591 case 't': /* true */
1592 case 'T': /* TRUE */
1603 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1604 * where characters may be escaped by \
1606 X509_NAME *parse_name(const char *cp, long chtype, int canmulti)
1608 int nextismulti = 0;
1614 "name is expected to be in the format "
1615 "/type0=value0/type1=value1/type2=... where characters may "
1616 "be escaped by \\. This name is not in that format: '%s'\n",
1621 n = X509_NAME_new();
1624 work = OPENSSL_strdup(cp);
1626 BIO_printf(bio_err, "%s: Error copying name input\n", opt_getprog());
1633 unsigned char *valstr;
1635 int ismulti = nextismulti;
1638 /* Collect the type */
1639 while (*cp && *cp != '=')
1643 "%s: Hit end of string before finding the '='\n",
1650 /* Collect the value. */
1651 valstr = (unsigned char *)bp;
1652 for (; *cp && *cp != '/'; *bp++ = *cp++) {
1653 if (canmulti && *cp == '+') {
1657 if (*cp == '\\' && *++cp == '\0') {
1659 "%s: Escape character at end of string\n",
1666 /* If not at EOS (must be + or /), move forward. */
1671 nid = OBJ_txt2nid(typestr);
1672 if (nid == NID_undef) {
1673 BIO_printf(bio_err, "%s: Skipping unknown attribute \"%s\"\n",
1674 opt_getprog(), typestr);
1677 if (*valstr == '\0') {
1679 "%s: No value provided for Subject Attribute %s, skipped\n",
1680 opt_getprog(), typestr);
1683 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1684 valstr, strlen((char *)valstr),
1685 -1, ismulti ? -1 : 0)) {
1686 BIO_printf(bio_err, "%s: Error adding name attribute \"/%s=%s\"\n",
1687 opt_getprog(), typestr ,valstr);
1702 * Read whole contents of a BIO into an allocated memory buffer and return
1706 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1710 unsigned char tbuf[1024];
1712 mem = BIO_new(BIO_s_mem());
1716 if ((maxlen != -1) && maxlen < 1024)
1720 len = BIO_read(in, tbuf, len);
1727 if (BIO_write(mem, tbuf, len) != len) {
1736 ret = BIO_get_mem_data(mem, (char **)out);
1737 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1742 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1745 char *stmp, *vtmp = NULL;
1746 stmp = OPENSSL_strdup(value);
1749 vtmp = strchr(stmp, ':');
1754 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1759 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1761 X509_POLICY_NODE *node;
1764 BIO_printf(bio_err, "%s Policies:", name);
1766 BIO_puts(bio_err, "\n");
1767 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1768 node = sk_X509_POLICY_NODE_value(nodes, i);
1769 X509_POLICY_NODE_print(bio_err, node, 2);
1772 BIO_puts(bio_err, " <empty>\n");
1776 void policies_print(X509_STORE_CTX *ctx)
1778 X509_POLICY_TREE *tree;
1779 int explicit_policy;
1780 tree = X509_STORE_CTX_get0_policy_tree(ctx);
1781 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1783 BIO_printf(bio_err, "Require explicit Policy: %s\n",
1784 explicit_policy ? "True" : "False");
1786 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1787 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1791 * next_protos_parse parses a comma separated list of strings into a string
1792 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1793 * outlen: (output) set to the length of the resulting buffer on success.
1794 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1795 * in: a NUL terminated string like "abc,def,ghi"
1797 * returns: a malloc'd buffer or NULL on failure.
1799 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1803 size_t i, start = 0;
1807 if (len == 0 || len >= 65535)
1810 out = app_malloc(len + 1, "NPN buffer");
1811 for (i = 0; i <= len; ++i) {
1812 if (i == len || in[i] == ',') {
1814 * Zero-length ALPN elements are invalid on the wire, we could be
1815 * strict and reject the entire string, but just ignoring extra
1816 * commas seems harmless and more friendly.
1818 * Every comma we skip in this way puts the input buffer another
1819 * byte ahead of the output buffer, so all stores into the output
1820 * buffer need to be decremented by the number commas skipped.
1827 if (i - start > 255) {
1831 out[start-skipped] = (unsigned char)(i - start);
1834 out[i + 1 - skipped] = in[i];
1838 if (len <= skipped) {
1843 *outlen = len + 1 - skipped;
1847 void print_cert_checks(BIO *bio, X509 *x,
1848 const char *checkhost,
1849 const char *checkemail, const char *checkip)
1854 BIO_printf(bio, "Hostname %s does%s match certificate\n",
1856 X509_check_host(x, checkhost, 0, 0, NULL) == 1
1861 BIO_printf(bio, "Email %s does%s match certificate\n",
1862 checkemail, X509_check_email(x, checkemail, 0, 0)
1867 BIO_printf(bio, "IP %s does%s match certificate\n",
1868 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1872 /* Get first http URL from a DIST_POINT structure */
1874 static const char *get_dp_url(DIST_POINT *dp)
1876 GENERAL_NAMES *gens;
1880 if (!dp->distpoint || dp->distpoint->type != 0)
1882 gens = dp->distpoint->name.fullname;
1883 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1884 gen = sk_GENERAL_NAME_value(gens, i);
1885 uri = GENERAL_NAME_get0_value(gen, >ype);
1886 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1887 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
1888 if (strncmp(uptr, "http://", 7) == 0)
1896 * Look through a CRLDP structure and attempt to find an http URL to
1897 * downloads a CRL from.
1900 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1903 const char *urlptr = NULL;
1904 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1905 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1906 urlptr = get_dp_url(dp);
1908 return load_crl(urlptr, FORMAT_HTTP, "CRL via CDP");
1914 * Example of downloading CRLs from CRLDP:
1915 * not usable for real world as it always downloads and doesn't cache anything.
1918 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
1919 const X509_NAME *nm)
1922 STACK_OF(X509_CRL) *crls = NULL;
1924 STACK_OF(DIST_POINT) *crldp;
1926 crls = sk_X509_CRL_new_null();
1929 x = X509_STORE_CTX_get_current_cert(ctx);
1930 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
1931 crl = load_crl_crldp(crldp);
1932 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1934 sk_X509_CRL_free(crls);
1937 sk_X509_CRL_push(crls, crl);
1938 /* Try to download delta CRL */
1939 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
1940 crl = load_crl_crldp(crldp);
1941 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1943 sk_X509_CRL_push(crls, crl);
1947 void store_setup_crl_download(X509_STORE *st)
1949 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
1952 #ifndef OPENSSL_NO_SOCK
1953 static const char *tls_error_hint(void)
1955 unsigned long err = ERR_peek_error();
1957 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
1958 err = ERR_peek_last_error();
1959 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
1962 switch (ERR_GET_REASON(err)) {
1963 case SSL_R_WRONG_VERSION_NUMBER:
1964 return "The server does not support (a suitable version of) TLS";
1965 case SSL_R_UNKNOWN_PROTOCOL:
1966 return "The server does not support HTTPS";
1967 case SSL_R_CERTIFICATE_VERIFY_FAILED:
1968 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
1969 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
1970 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
1971 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
1972 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
1973 default: /* no error or no hint available for error */
1978 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
1979 BIO *app_http_tls_cb(BIO *hbio, void *arg, int connect, int detail)
1981 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
1982 SSL_CTX *ssl_ctx = info->ssl_ctx;
1986 if (connect && detail) { /* connecting with TLS */
1987 if ((info->use_proxy
1988 && !OSSL_HTTP_proxy_connect(hbio, info->server, info->port,
1989 NULL, NULL, /* no proxy credentials */
1990 info->timeout, bio_err, opt_getprog()))
1991 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
1994 if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
1999 SSL_set_tlsext_host_name(ssl, info->server);
2001 SSL_set_connect_state(ssl);
2002 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2004 hbio = BIO_push(sbio, hbio);
2005 } else if (!connect && !detail) { /* disconnecting after error */
2006 const char *hint = tls_error_hint();
2008 ERR_add_error_data(2, " : ", hint);
2010 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2011 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2017 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2018 const char *no_proxy, SSL_CTX *ssl_ctx,
2019 const STACK_OF(CONF_VALUE) *headers,
2020 long timeout, const char *expected_content_type,
2021 const ASN1_ITEM *it)
2023 APP_HTTP_TLS_INFO info;
2027 ASN1_VALUE *resp = NULL;
2029 if (url == NULL || it == NULL) {
2030 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2034 if (!OSSL_HTTP_parse_url(url, &server, &port, NULL /* ppath */, &use_ssl))
2036 if (use_ssl && ssl_ctx == NULL) {
2037 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2038 ERR_add_error_data(1, "missing SSL_CTX");
2042 info.server = server;
2044 info.use_proxy = proxy != NULL;
2045 info.timeout = timeout;
2046 info.ssl_ctx = ssl_ctx;
2047 resp = OSSL_HTTP_get_asn1(url, proxy, no_proxy,
2048 NULL, NULL, app_http_tls_cb, &info,
2049 headers, 0 /* maxline */, 0 /* max_resp_len */,
2050 timeout, expected_content_type, it);
2052 OPENSSL_free(server);
2058 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2059 const char *path, const char *proxy,
2060 const char *no_proxy, SSL_CTX *ssl_ctx,
2061 const STACK_OF(CONF_VALUE) *headers,
2062 const char *content_type,
2063 ASN1_VALUE *req, const ASN1_ITEM *req_it,
2064 long timeout, const ASN1_ITEM *rsp_it)
2066 APP_HTTP_TLS_INFO info;
2070 info.use_proxy = proxy != NULL;
2071 info.timeout = timeout;
2072 info.ssl_ctx = ssl_ctx;
2073 return OSSL_HTTP_post_asn1(host, port, path, ssl_ctx != NULL,
2075 NULL, NULL, app_http_tls_cb, &info,
2076 headers, content_type, req, req_it,
2078 0 /* max_resp_len */, timeout, NULL, rsp_it);
2084 * Platform-specific sections
2089 # define fileno(a) (int)_fileno(a)
2092 # include <windows.h>
2095 static int WIN32_rename(const char *from, const char *to)
2097 TCHAR *tfrom = NULL, *tto;
2101 if (sizeof(TCHAR) == 1) {
2102 tfrom = (TCHAR *)from;
2104 } else { /* UNICODE path */
2106 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2107 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2111 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2112 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2114 for (i = 0; i < flen; i++)
2115 tfrom[i] = (TCHAR)from[i];
2116 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2117 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2119 for (i = 0; i < tlen; i++)
2120 tto[i] = (TCHAR)to[i];
2123 if (MoveFile(tfrom, tto))
2125 err = GetLastError();
2126 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2127 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2129 err = GetLastError();
2131 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2133 else if (err == ERROR_ACCESS_DENIED)
2136 errno = EINVAL; /* we could map more codes... */
2140 if (tfrom != NULL && tfrom != (TCHAR *)from)
2146 /* app_tminterval section */
2148 double app_tminterval(int stop, int usertime)
2152 static ULARGE_INTEGER tmstart;
2153 static int warning = 1;
2154 # ifdef _WIN32_WINNT
2155 static HANDLE proc = NULL;
2159 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2160 GetCurrentProcessId());
2162 proc = (HANDLE) - 1;
2165 if (usertime && proc != (HANDLE) - 1) {
2167 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2173 if (usertime && warning) {
2174 BIO_printf(bio_err, "To get meaningful results, run "
2175 "this program on idle system.\n");
2178 GetSystemTime(&systime);
2179 SystemTimeToFileTime(&systime, &now);
2182 if (stop == TM_START) {
2183 tmstart.u.LowPart = now.dwLowDateTime;
2184 tmstart.u.HighPart = now.dwHighDateTime;
2186 ULARGE_INTEGER tmstop;
2188 tmstop.u.LowPart = now.dwLowDateTime;
2189 tmstop.u.HighPart = now.dwHighDateTime;
2191 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2196 #elif defined(OPENSSL_SYS_VXWORKS)
2199 double app_tminterval(int stop, int usertime)
2202 # ifdef CLOCK_REALTIME
2203 static struct timespec tmstart;
2204 struct timespec now;
2206 static unsigned long tmstart;
2209 static int warning = 1;
2211 if (usertime && warning) {
2212 BIO_printf(bio_err, "To get meaningful results, run "
2213 "this program on idle system.\n");
2216 # ifdef CLOCK_REALTIME
2217 clock_gettime(CLOCK_REALTIME, &now);
2218 if (stop == TM_START)
2221 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2222 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2225 if (stop == TM_START)
2228 ret = (now - tmstart) / (double)sysClkRateGet();
2233 #elif defined(OPENSSL_SYSTEM_VMS)
2237 double app_tminterval(int stop, int usertime)
2239 static clock_t tmstart;
2247 now = rus.tms_utime;
2250 now = clock(); /* sum of user and kernel times */
2253 gettimeofday(&tv, NULL);
2254 now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
2255 (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
2259 if (stop == TM_START)
2262 ret = (now - tmstart) / (double)(CLK_TCK);
2267 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2268 # include <sys/times.h>
2270 double app_tminterval(int stop, int usertime)
2274 clock_t now = times(&rus);
2275 static clock_t tmstart;
2278 now = rus.tms_utime;
2280 if (stop == TM_START) {
2283 long int tck = sysconf(_SC_CLK_TCK);
2284 ret = (now - tmstart) / (double)tck;
2291 # include <sys/time.h>
2292 # include <sys/resource.h>
2294 double app_tminterval(int stop, int usertime)
2299 static struct timeval tmstart;
2302 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2304 gettimeofday(&now, NULL);
2306 if (stop == TM_START)
2309 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2310 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2316 int app_access(const char* name, int flag)
2319 return _access(name, flag);
2321 return access(name, flag);
2325 int app_isdir(const char *name)
2327 return opt_isdir(name);
2330 /* raw_read|write section */
2332 # include "vms_term_sock.h"
2333 static int stdin_sock = -1;
2335 static void close_stdin_sock(void)
2337 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2340 int fileno_stdin(void)
2342 if (stdin_sock == -1) {
2343 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2344 atexit(close_stdin_sock);
2350 int fileno_stdin(void)
2352 return fileno(stdin);
2356 int fileno_stdout(void)
2358 return fileno(stdout);
2361 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2362 int raw_read_stdin(void *buf, int siz)
2365 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2370 #elif defined(__VMS)
2371 # include <sys/socket.h>
2373 int raw_read_stdin(void *buf, int siz)
2375 return recv(fileno_stdin(), buf, siz, 0);
2378 int raw_read_stdin(void *buf, int siz)
2380 return read(fileno_stdin(), buf, siz);
2384 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2385 int raw_write_stdout(const void *buf, int siz)
2388 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2394 int raw_write_stdout(const void *buf, int siz)
2396 return write(fileno_stdout(), buf, siz);
2401 * Centralized handling of input and output files with format specification
2402 * The format is meant to show what the input and output is supposed to be,
2403 * and is therefore a show of intent more than anything else. However, it
2404 * does impact behavior on some platforms, such as differentiating between
2405 * text and binary input/output on non-Unix platforms
2407 BIO *dup_bio_in(int format)
2409 return BIO_new_fp(stdin,
2410 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2413 BIO *dup_bio_out(int format)
2415 BIO *b = BIO_new_fp(stdout,
2416 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2417 void *prefix = NULL;
2419 #ifdef OPENSSL_SYS_VMS
2420 if (FMT_istext(format))
2421 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2424 if (FMT_istext(format)
2425 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2426 b = BIO_push(BIO_new(BIO_f_prefix()), b);
2427 BIO_set_prefix(b, prefix);
2433 BIO *dup_bio_err(int format)
2435 BIO *b = BIO_new_fp(stderr,
2436 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2437 #ifdef OPENSSL_SYS_VMS
2438 if (FMT_istext(format))
2439 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2444 void unbuffer(FILE *fp)
2447 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2448 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2449 * However, we trust that the C RTL will never give us a FILE pointer
2450 * above the first 4 GB of memory, so we simply turn off the warning
2453 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2454 # pragma environment save
2455 # pragma message disable maylosedata2
2458 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2459 # pragma environment restore
2463 static const char *modestr(char mode, int format)
2465 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2469 return FMT_istext(format) ? "a" : "ab";
2471 return FMT_istext(format) ? "r" : "rb";
2473 return FMT_istext(format) ? "w" : "wb";
2475 /* The assert above should make sure we never reach this point */
2479 static const char *modeverb(char mode)
2489 return "(doing something)";
2493 * Open a file for writing, owner-read-only.
2495 BIO *bio_open_owner(const char *filename, int format, int private)
2499 int fd = -1, bflags, mode, textmode;
2501 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2502 return bio_open_default(filename, 'w', format);
2511 textmode = FMT_istext(format);
2515 #elif defined(_O_BINARY)
2520 #ifdef OPENSSL_SYS_VMS
2521 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2522 * it still needs to know that we're going binary, or fdopen()
2523 * will fail with "invalid argument"... so we tell VMS what the
2527 fd = open(filename, mode, 0600, "ctx=bin");
2530 fd = open(filename, mode, 0600);
2533 fp = fdopen(fd, modestr('w', format));
2538 bflags |= BIO_FP_TEXT;
2539 b = BIO_new_fp(fp, bflags);
2544 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2545 opt_getprog(), filename, strerror(errno));
2546 ERR_print_errors(bio_err);
2547 /* If we have fp, then fdopen took over fd, so don't close both. */
2555 static BIO *bio_open_default_(const char *filename, char mode, int format,
2560 if (filename == NULL || strcmp(filename, "-") == 0) {
2561 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2569 "Can't open %s, %s\n",
2570 mode == 'r' ? "stdin" : "stdout", strerror(errno));
2572 ret = BIO_new_file(filename, modestr(mode, format));
2580 "Can't open %s for %s, %s\n",
2581 filename, modeverb(mode), strerror(errno));
2583 ERR_print_errors(bio_err);
2587 BIO *bio_open_default(const char *filename, char mode, int format)
2589 return bio_open_default_(filename, mode, format, 0);
2592 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2594 return bio_open_default_(filename, mode, format, 1);
2597 void wait_for_async(SSL *s)
2599 /* On Windows select only works for sockets, so we simply don't wait */
2600 #ifndef OPENSSL_SYS_WINDOWS
2607 if (!SSL_get_all_async_fds(s, NULL, &numfds))
2611 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2612 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2618 for (i = 0; i < numfds; i++) {
2619 if (width <= (int)fds[i])
2620 width = (int)fds[i] + 1;
2621 openssl_fdset((int)fds[i], &asyncfds);
2623 select(width, (void *)&asyncfds, NULL, NULL, NULL);
2628 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2629 #if defined(OPENSSL_SYS_MSDOS)
2630 int has_stdin_waiting(void)
2632 # if defined(OPENSSL_SYS_WINDOWS)
2633 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2635 INPUT_RECORD inputrec;
2639 if (inhand == INVALID_HANDLE_VALUE) {
2643 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2645 /* Probably redirected input? _kbhit() does not work in this case */
2656 /* Corrupt a signature by modifying final byte */
2657 void corrupt_signature(const ASN1_STRING *signature)
2659 unsigned char *s = signature->data;
2660 s[signature->length - 1] ^= 0x1;
2663 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2666 if (startdate == NULL || strcmp(startdate, "today") == 0) {
2667 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2670 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2673 if (enddate == NULL) {
2674 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2677 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2683 void make_uppercase(char *string)
2687 for (i = 0; string[i] != '\0'; i++)
2688 string[i] = toupper((unsigned char)string[i]);
2691 int opt_printf_stderr(const char *fmt, ...)
2697 ret = BIO_vprintf(bio_err, fmt, ap);
2702 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
2703 const OSSL_PARAM *paramdefs)
2705 OSSL_PARAM *params = NULL;
2706 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
2708 char *opt = "", *stmp, *vtmp = NULL;
2714 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
2718 for (params_n = 0; params_n < sz; params_n++) {
2719 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
2720 if ((stmp = OPENSSL_strdup(opt)) == NULL
2721 || (vtmp = strchr(stmp, ':')) == NULL)
2723 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2725 /* Skip over the separator so that vmtp points to the value */
2727 if (!OSSL_PARAM_allocate_from_text(¶ms[params_n], paramdefs,
2728 stmp, vtmp, strlen(vtmp), &found))
2732 params[params_n] = OSSL_PARAM_construct_end();
2736 BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
2738 ERR_print_errors(bio_err);
2739 app_params_free(params);
2743 void app_params_free(OSSL_PARAM *params)
2747 if (params != NULL) {
2748 for (i = 0; params[i].key != NULL; ++i)
2749 OPENSSL_free(params[i].data);
2750 OPENSSL_free(params);