2 * Copyright 1995-2018 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/pkcs12.h>
33 #include <openssl/ui.h>
34 #include <openssl/safestack.h>
35 #ifndef OPENSSL_NO_ENGINE
36 # include <openssl/engine.h>
38 #ifndef OPENSSL_NO_RSA
39 # include <openssl/rsa.h>
41 #include <openssl/bn.h>
42 #include <openssl/ssl.h>
46 static int WIN32_rename(const char *from, const char *to);
47 # define rename(from,to) WIN32_rename((from),(to))
50 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
54 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32)
58 #define PASS_SOURCE_SIZE_MAX 4
66 static int set_table_opts(unsigned long *flags, const char *arg,
67 const NAME_EX_TBL * in_tbl);
68 static int set_multi_opts(unsigned long *flags, const char *arg,
69 const NAME_EX_TBL * in_tbl);
71 int app_init(long mesgwin);
73 int chopup_args(ARGS *arg, char *buf)
76 char c = '\0', *p = NULL;
81 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
85 /* Skip whitespace. */
86 while (*p && isspace(_UC(*p)))
91 /* The start of something good :-) */
92 if (arg->argc >= arg->size) {
95 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
100 quoted = *p == '\'' || *p == '"';
103 arg->argv[arg->argc++] = p;
105 /* now look for the end of this */
107 while (*p && *p != c)
111 while (*p && !isspace(_UC(*p)))
117 arg->argv[arg->argc] = NULL;
122 int app_init(long mesgwin)
128 int ctx_set_verify_locations(SSL_CTX *ctx,
129 const char *CAfile, int noCAfile,
130 const char *CApath, int noCApath,
131 const char *CAstore, int noCAstore)
133 if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
134 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
136 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
138 if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
144 if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
146 if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
148 if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
153 #ifndef OPENSSL_NO_CT
155 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
158 return SSL_CTX_set_default_ctlog_list_file(ctx);
160 return SSL_CTX_set_ctlog_list_file(ctx, path);
165 static unsigned long nmflag = 0;
166 static char nmflag_set = 0;
168 int set_nameopt(const char *arg)
170 int ret = set_name_ex(&nmflag, arg);
178 unsigned long get_nameopt(void)
180 return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
183 int dump_cert_text(BIO *out, X509 *x)
185 print_name(out, "subject=", X509_get_subject_name(x), get_nameopt());
187 print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
193 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
195 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
199 static char *app_get_pass(const char *arg, int keepbio);
201 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
203 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
206 *pass1 = app_get_pass(arg1, same);
209 } else if (pass1 != NULL) {
213 *pass2 = app_get_pass(arg2, same ? 2 : 0);
216 } else if (pass2 != NULL) {
222 static char *app_get_pass(const char *arg, int keepbio)
224 static BIO *pwdbio = NULL;
225 char *tmp, tpass[APP_PASS_LEN];
228 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
229 if (strncmp(arg, "pass:", 5) == 0)
230 return OPENSSL_strdup(arg + 5);
231 if (strncmp(arg, "env:", 4) == 0) {
232 tmp = getenv(arg + 4);
234 BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
237 return OPENSSL_strdup(tmp);
239 if (!keepbio || pwdbio == NULL) {
240 if (strncmp(arg, "file:", 5) == 0) {
241 pwdbio = BIO_new_file(arg + 5, "r");
242 if (pwdbio == NULL) {
243 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
248 * Under _WIN32, which covers even Win64 and CE, file
249 * descriptors referenced by BIO_s_fd are not inherited
250 * by child process and therefore below is not an option.
251 * It could have been an option if bss_fd.c was operating
252 * on real Windows descriptors, such as those obtained
255 } else if (strncmp(arg, "fd:", 3) == 0) {
259 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
260 if ((i < 0) || !pwdbio) {
261 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
265 * Can't do BIO_gets on an fd BIO so add a buffering BIO
267 btmp = BIO_new(BIO_f_buffer());
268 pwdbio = BIO_push(btmp, pwdbio);
270 } else if (strcmp(arg, "stdin") == 0) {
271 pwdbio = dup_bio_in(FORMAT_TEXT);
272 if (pwdbio == NULL) {
273 BIO_printf(bio_err, "Can't open BIO for stdin\n");
277 /* argument syntax error; do not reveal too much about arg */
278 tmp = strchr(arg, ':');
279 if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
281 "Invalid password argument, missing ':' within the first %d chars\n",
282 PASS_SOURCE_SIZE_MAX + 1);
285 "Invalid password argument, starting with \"%.*s\"\n",
286 (int)(tmp - arg + 1), arg);
290 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
292 BIO_free_all(pwdbio);
296 BIO_printf(bio_err, "Error reading password from BIO\n");
299 tmp = strchr(tpass, '\n');
302 return OPENSSL_strdup(tpass);
305 CONF *app_load_config_bio(BIO *in, const char *filename)
311 conf = NCONF_new(NULL);
312 i = NCONF_load_bio(conf, in, &errorline);
316 if (errorline <= 0) {
317 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
319 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
322 if (filename != NULL)
323 BIO_printf(bio_err, "config file \"%s\"\n", filename);
325 BIO_printf(bio_err, "config input");
331 CONF *app_load_config(const char *filename)
336 in = bio_open_default(filename, 'r', FORMAT_TEXT);
340 conf = app_load_config_bio(in, filename);
345 CONF *app_load_config_quiet(const char *filename)
350 in = bio_open_default_quiet(filename, 'r', FORMAT_TEXT);
354 conf = app_load_config_bio(in, filename);
359 int app_load_modules(const CONF *config)
361 CONF *to_free = NULL;
364 config = to_free = app_load_config_quiet(default_config_file);
368 if (CONF_modules_load(config, NULL, 0) <= 0) {
369 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
370 ERR_print_errors(bio_err);
378 int add_oid_section(CONF *conf)
381 STACK_OF(CONF_VALUE) *sktmp;
385 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
389 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
390 BIO_printf(bio_err, "problem loading oid section %s\n", p);
393 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
394 cnf = sk_CONF_VALUE_value(sktmp, i);
395 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
396 BIO_printf(bio_err, "problem creating object %s=%s\n",
397 cnf->name, cnf->value);
404 static int load_pkcs12(BIO *in, const char *desc,
405 pem_password_cb *pem_cb, PW_CB_DATA *cb_data,
406 EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
409 char tpass[PEM_BUFSIZE];
412 p12 = d2i_PKCS12_bio(in, NULL);
414 BIO_printf(bio_err, "Error loading PKCS12 file for %s\n", desc);
417 /* See if an empty password will do */
418 if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0)) {
422 pem_cb = (pem_password_cb *)password_callback;
423 len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
425 BIO_printf(bio_err, "Passphrase callback error for %s\n", desc);
428 if (len < PEM_BUFSIZE)
430 if (!PKCS12_verify_mac(p12, tpass, len)) {
432 "Mac verify error (wrong password?) in PKCS12 file for %s\n",
438 ret = PKCS12_parse(p12, pass, pkey, cert, ca);
444 X509 *load_cert(const char *file, int format, const char *cert_descrip)
449 if (format == FORMAT_HTTP) {
450 #if !defined(OPENSSL_NO_SOCK)
451 x = X509_load_http(file, NULL, NULL, 0 /* timeout */);
458 cert = dup_bio_in(format);
460 cert = bio_open_default(file, 'r', format);
465 if (format == FORMAT_ASN1) {
466 x = d2i_X509_bio(cert, NULL);
467 } else if (format == FORMAT_PEM) {
468 x = PEM_read_bio_X509_AUX(cert, NULL,
469 (pem_password_cb *)password_callback, NULL);
470 } else if (format == FORMAT_PKCS12) {
471 if (!load_pkcs12(cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
474 BIO_printf(bio_err, "bad input format specified for %s\n", cert_descrip);
479 BIO_printf(bio_err, "unable to load certificate\n");
480 ERR_print_errors(bio_err);
486 X509_CRL *load_crl(const char *infile, int format)
491 if (format == FORMAT_HTTP) {
492 #if !defined(OPENSSL_NO_SOCK)
493 x = X509_CRL_load_http(infile, NULL, NULL, 0 /* timeout */);
498 in = bio_open_default(infile, 'r', format);
501 if (format == FORMAT_ASN1) {
502 x = d2i_X509_CRL_bio(in, NULL);
503 } else if (format == FORMAT_PEM) {
504 x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
506 BIO_printf(bio_err, "bad input format specified for input crl\n");
510 BIO_printf(bio_err, "unable to load CRL\n");
511 ERR_print_errors(bio_err);
520 EVP_PKEY *load_key(const char *file, int format, int maybe_stdin,
521 const char *pass, ENGINE *e, const char *key_descrip)
524 EVP_PKEY *pkey = NULL;
527 cb_data.password = pass;
528 cb_data.prompt_info = file;
530 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
531 BIO_printf(bio_err, "no keyfile specified\n");
534 if (format == FORMAT_ENGINE) {
536 BIO_printf(bio_err, "no engine specified\n");
538 #ifndef OPENSSL_NO_ENGINE
539 if (ENGINE_init(e)) {
540 pkey = ENGINE_load_private_key(e, file,
541 (UI_METHOD *)get_ui_method(),
546 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
547 ERR_print_errors(bio_err);
550 BIO_printf(bio_err, "engines not supported\n");
555 if (file == NULL && maybe_stdin) {
557 key = dup_bio_in(format);
559 key = bio_open_default(file, 'r', format);
563 if (format == FORMAT_ASN1) {
564 pkey = d2i_PrivateKey_bio(key, NULL);
565 } else if (format == FORMAT_PEM) {
566 pkey = PEM_read_bio_PrivateKey(key, NULL, wrap_password_callback, &cb_data);
567 } else if (format == FORMAT_PKCS12) {
568 if (!load_pkcs12(key, key_descrip, wrap_password_callback, &cb_data,
571 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
572 } else if (format == FORMAT_MSBLOB) {
573 pkey = b2i_PrivateKey_bio(key);
574 } else if (format == FORMAT_PVK) {
575 pkey = b2i_PVK_bio(key, wrap_password_callback, &cb_data);
578 BIO_printf(bio_err, "bad input format specified for key file\n");
584 BIO_printf(bio_err, "unable to load %s\n", key_descrip);
585 ERR_print_errors(bio_err);
590 EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin,
591 const char *pass, ENGINE *e, const char *key_descrip)
594 EVP_PKEY *pkey = NULL;
597 cb_data.password = pass;
598 cb_data.prompt_info = file;
600 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
601 BIO_printf(bio_err, "no keyfile specified\n");
604 if (format == FORMAT_ENGINE) {
606 BIO_printf(bio_err, "no engine specified\n");
608 #ifndef OPENSSL_NO_ENGINE
609 pkey = ENGINE_load_public_key(e, file, (UI_METHOD *)get_ui_method(),
612 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
613 ERR_print_errors(bio_err);
616 BIO_printf(bio_err, "engines not supported\n");
621 if (file == NULL && maybe_stdin) {
623 key = dup_bio_in(format);
625 key = bio_open_default(file, 'r', format);
629 if (format == FORMAT_ASN1) {
630 pkey = d2i_PUBKEY_bio(key, NULL);
631 } else if (format == FORMAT_ASN1RSA) {
632 #ifndef OPENSSL_NO_RSA
634 rsa = d2i_RSAPublicKey_bio(key, NULL);
636 pkey = EVP_PKEY_new();
638 EVP_PKEY_set1_RSA(pkey, rsa);
642 BIO_printf(bio_err, "RSA keys not supported\n");
645 } else if (format == FORMAT_PEMRSA) {
646 #ifndef OPENSSL_NO_RSA
648 rsa = PEM_read_bio_RSAPublicKey(key, NULL,
649 (pem_password_cb *)password_callback,
652 pkey = EVP_PKEY_new();
654 EVP_PKEY_set1_RSA(pkey, rsa);
658 BIO_printf(bio_err, "RSA keys not supported\n");
661 } else if (format == FORMAT_PEM) {
662 pkey = PEM_read_bio_PUBKEY(key, NULL,
663 (pem_password_cb *)password_callback,
665 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
666 } else if (format == FORMAT_MSBLOB) {
667 pkey = b2i_PublicKey_bio(key);
673 BIO_printf(bio_err, "unable to load %s\n", key_descrip);
677 static int load_certs_crls(const char *file, int format,
678 const char *pass, const char *desc,
679 STACK_OF(X509) **pcerts,
680 STACK_OF(X509_CRL) **pcrls)
684 STACK_OF(X509_INFO) *xis = NULL;
689 cb_data.password = pass;
690 cb_data.prompt_info = file;
692 if (format != FORMAT_PEM) {
693 BIO_printf(bio_err, "bad input format specified for %s\n", desc);
697 bio = bio_open_default(file, 'r', FORMAT_PEM);
701 xis = PEM_X509_INFO_read_bio(bio, NULL,
702 (pem_password_cb *)password_callback,
707 if (pcerts != NULL && *pcerts == NULL) {
708 *pcerts = sk_X509_new_null();
713 if (pcrls != NULL && *pcrls == NULL) {
714 *pcrls = sk_X509_CRL_new_null();
719 for (i = 0; i < sk_X509_INFO_num(xis); i++) {
720 xi = sk_X509_INFO_value(xis, i);
721 if (xi->x509 != NULL && pcerts != NULL) {
722 if (!sk_X509_push(*pcerts, xi->x509))
726 if (xi->crl != NULL && pcrls != NULL) {
727 if (!sk_X509_CRL_push(*pcrls, xi->crl))
733 if (pcerts != NULL && sk_X509_num(*pcerts) > 0)
736 if (pcrls != NULL && sk_X509_CRL_num(*pcrls) > 0)
741 sk_X509_INFO_pop_free(xis, X509_INFO_free);
744 if (pcerts != NULL) {
745 sk_X509_pop_free(*pcerts, X509_free);
749 sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
752 BIO_printf(bio_err, "unable to load %s\n",
753 pcerts ? "certificates" : "CRLs");
754 ERR_print_errors(bio_err);
759 void* app_malloc(int sz, const char *what)
761 void *vp = OPENSSL_malloc(sz);
764 BIO_printf(bio_err, "%s: Could not allocate %d bytes for %s\n",
765 opt_getprog(), sz, what);
766 ERR_print_errors(bio_err);
773 * Initialize or extend, if *certs != NULL, a certificate stack.
775 int load_certs(const char *file, STACK_OF(X509) **certs, int format,
776 const char *pass, const char *desc)
778 return load_certs_crls(file, format, pass, desc, certs, NULL);
782 * Initialize or extend, if *crls != NULL, a certificate stack.
784 int load_crls(const char *file, STACK_OF(X509_CRL) **crls, int format,
785 const char *pass, const char *desc)
787 return load_certs_crls(file, format, pass, desc, NULL, crls);
790 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
791 /* Return error for unknown extensions */
792 #define X509V3_EXT_DEFAULT 0
793 /* Print error for unknown extensions */
794 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
795 /* ASN1 parse unknown extensions */
796 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
797 /* BIO_dump unknown extensions */
798 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
800 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
801 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
803 int set_cert_ex(unsigned long *flags, const char *arg)
805 static const NAME_EX_TBL cert_tbl[] = {
806 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
807 {"ca_default", X509_FLAG_CA, 0xffffffffl},
808 {"no_header", X509_FLAG_NO_HEADER, 0},
809 {"no_version", X509_FLAG_NO_VERSION, 0},
810 {"no_serial", X509_FLAG_NO_SERIAL, 0},
811 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
812 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
813 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
814 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
815 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
816 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
817 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
818 {"no_aux", X509_FLAG_NO_AUX, 0},
819 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
820 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
821 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
822 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
823 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
826 return set_multi_opts(flags, arg, cert_tbl);
829 int set_name_ex(unsigned long *flags, const char *arg)
831 static const NAME_EX_TBL ex_tbl[] = {
832 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
833 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
834 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
835 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
836 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
837 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
838 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
839 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
840 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
841 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
842 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
843 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
844 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
845 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
846 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
847 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
848 {"dn_rev", XN_FLAG_DN_REV, 0},
849 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
850 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
851 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
852 {"align", XN_FLAG_FN_ALIGN, 0},
853 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
854 {"space_eq", XN_FLAG_SPC_EQ, 0},
855 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
856 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
857 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
858 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
859 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
862 if (set_multi_opts(flags, arg, ex_tbl) == 0)
864 if (*flags != XN_FLAG_COMPAT
865 && (*flags & XN_FLAG_SEP_MASK) == 0)
866 *flags |= XN_FLAG_SEP_CPLUS_SPC;
870 int set_ext_copy(int *copy_type, const char *arg)
872 if (strcasecmp(arg, "none") == 0)
873 *copy_type = EXT_COPY_NONE;
874 else if (strcasecmp(arg, "copy") == 0)
875 *copy_type = EXT_COPY_ADD;
876 else if (strcasecmp(arg, "copyall") == 0)
877 *copy_type = EXT_COPY_ALL;
883 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
885 STACK_OF(X509_EXTENSION) *exts = NULL;
886 X509_EXTENSION *ext, *tmpext;
889 if (!x || !req || (copy_type == EXT_COPY_NONE))
891 exts = X509_REQ_get_extensions(req);
893 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
894 ext = sk_X509_EXTENSION_value(exts, i);
895 obj = X509_EXTENSION_get_object(ext);
896 idx = X509_get_ext_by_OBJ(x, obj, -1);
897 /* Does extension exist? */
899 /* If normal copy don't override existing extension */
900 if (copy_type == EXT_COPY_ADD)
902 /* Delete all extensions of same type */
904 tmpext = X509_get_ext(x, idx);
905 X509_delete_ext(x, idx);
906 X509_EXTENSION_free(tmpext);
907 idx = X509_get_ext_by_OBJ(x, obj, -1);
910 if (!X509_add_ext(x, ext, -1))
918 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
923 static int set_multi_opts(unsigned long *flags, const char *arg,
924 const NAME_EX_TBL * in_tbl)
926 STACK_OF(CONF_VALUE) *vals;
931 vals = X509V3_parse_list(arg);
932 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
933 val = sk_CONF_VALUE_value(vals, i);
934 if (!set_table_opts(flags, val->name, in_tbl))
937 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
941 static int set_table_opts(unsigned long *flags, const char *arg,
942 const NAME_EX_TBL * in_tbl)
945 const NAME_EX_TBL *ptbl;
951 } else if (c == '+') {
958 for (ptbl = in_tbl; ptbl->name; ptbl++) {
959 if (strcasecmp(arg, ptbl->name) == 0) {
960 *flags &= ~ptbl->mask;
962 *flags |= ptbl->flag;
964 *flags &= ~ptbl->flag;
971 void print_name(BIO *out, const char *title, X509_NAME *nm,
972 unsigned long lflags)
979 BIO_puts(out, title);
980 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
984 if (lflags == XN_FLAG_COMPAT) {
985 buf = X509_NAME_oneline(nm, 0, 0);
992 X509_NAME_print_ex(out, nm, indent, lflags);
997 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
998 int len, unsigned char *buffer)
1000 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1001 if (BN_is_zero(in)) {
1002 BIO_printf(out, "\n 0x00");
1006 l = BN_bn2bin(in, buffer);
1007 for (i = 0; i < l; i++) {
1008 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1010 BIO_printf(out, "0x%02X,", buffer[i]);
1012 BIO_printf(out, "0x%02X", buffer[i]);
1015 BIO_printf(out, "\n };\n");
1018 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1022 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1023 for (i = 0; i < len; i++) {
1025 BIO_printf(out, "\n ");
1027 BIO_printf(out, "0x%02X, ", d[i]);
1029 BIO_printf(out, "0x%02X", d[i]);
1031 BIO_printf(out, "\n};\n");
1034 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1035 const char *CApath, int noCApath,
1036 const char *CAstore, int noCAstore)
1038 X509_STORE *store = X509_STORE_new();
1039 X509_LOOKUP *lookup;
1044 if (CAfile != NULL || !noCAfile) {
1045 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1048 if (CAfile != NULL) {
1049 if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1050 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1054 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1058 if (CApath != NULL || !noCApath) {
1059 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1062 if (CApath != NULL) {
1063 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1064 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1068 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1072 if (CAstore != NULL || !noCAstore) {
1073 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1076 if (!X509_LOOKUP_add_store(lookup, CAstore)) {
1077 if (CAstore != NULL)
1078 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1086 X509_STORE_free(store);
1090 #ifndef OPENSSL_NO_ENGINE
1091 /* Try to load an engine in a shareable library */
1092 static ENGINE *try_load_engine(const char *engine)
1094 ENGINE *e = ENGINE_by_id("dynamic");
1096 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1097 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1106 ENGINE *setup_engine(const char *engine, int debug)
1110 #ifndef OPENSSL_NO_ENGINE
1111 if (engine != NULL) {
1112 if (strcmp(engine, "auto") == 0) {
1113 BIO_printf(bio_err, "enabling auto ENGINE support\n");
1114 ENGINE_register_all_complete();
1117 if ((e = ENGINE_by_id(engine)) == NULL
1118 && (e = try_load_engine(engine)) == NULL) {
1119 BIO_printf(bio_err, "invalid engine \"%s\"\n", engine);
1120 ERR_print_errors(bio_err);
1124 ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1126 ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, (void *)get_ui_method(),
1128 if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1129 BIO_printf(bio_err, "can't use that engine\n");
1130 ERR_print_errors(bio_err);
1135 BIO_printf(bio_err, "engine \"%s\" set.\n", ENGINE_get_id(e));
1141 void release_engine(ENGINE *e)
1143 #ifndef OPENSSL_NO_ENGINE
1145 /* Free our "structural" reference. */
1150 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1157 return OPENSSL_LH_strhash(n);
1160 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1161 const OPENSSL_CSTRING *b)
1163 const char *aa, *bb;
1165 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1166 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1167 return strcmp(aa, bb);
1170 static int index_name_qual(char **a)
1172 return (a[0][0] == 'V');
1175 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1177 return OPENSSL_LH_strhash(a[DB_name]);
1180 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1182 return strcmp(a[DB_name], b[DB_name]);
1185 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1186 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1187 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1188 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1191 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1196 ASN1_INTEGER *ai = NULL;
1198 ai = ASN1_INTEGER_new();
1202 in = BIO_new_file(serialfile, "r");
1210 if (ret == NULL || !rand_serial(ret, ai))
1211 BIO_printf(bio_err, "Out of memory\n");
1213 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1214 BIO_printf(bio_err, "unable to load number from %s\n",
1218 ret = ASN1_INTEGER_to_BN(ai, NULL);
1221 "error converting number from bin to BIGNUM\n");
1232 ASN1_INTEGER_free(ai);
1236 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1237 ASN1_INTEGER **retai)
1242 ASN1_INTEGER *ai = NULL;
1246 j = strlen(serialfile);
1248 j = strlen(serialfile) + strlen(suffix) + 1;
1250 BIO_printf(bio_err, "file name too long\n");
1255 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1257 #ifndef OPENSSL_SYS_VMS
1258 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1260 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1263 out = BIO_new_file(buf[0], "w");
1265 ERR_print_errors(bio_err);
1269 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1270 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1273 i2a_ASN1_INTEGER(out, ai);
1274 BIO_puts(out, "\n");
1282 ASN1_INTEGER_free(ai);
1286 int rotate_serial(const char *serialfile, const char *new_suffix,
1287 const char *old_suffix)
1292 i = strlen(serialfile) + strlen(old_suffix);
1293 j = strlen(serialfile) + strlen(new_suffix);
1296 if (j + 1 >= BSIZE) {
1297 BIO_printf(bio_err, "file name too long\n");
1300 #ifndef OPENSSL_SYS_VMS
1301 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1302 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1304 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1305 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1307 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1313 "unable to rename %s to %s\n", serialfile, buf[1]);
1317 if (rename(buf[0], serialfile) < 0) {
1319 "unable to rename %s to %s\n", buf[0], serialfile);
1321 rename(buf[1], serialfile);
1329 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1334 btmp = b == NULL ? BN_new() : b;
1338 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1340 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1353 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1355 CA_DB *retdb = NULL;
1356 TXT_DB *tmpdb = NULL;
1358 CONF *dbattr_conf = NULL;
1360 #ifndef OPENSSL_NO_POSIX_IO
1365 in = BIO_new_file(dbfile, "r");
1367 ERR_print_errors(bio_err);
1371 #ifndef OPENSSL_NO_POSIX_IO
1372 BIO_get_fp(in, &dbfp);
1373 if (fstat(fileno(dbfp), &dbst) == -1) {
1374 ERR_raise_data(ERR_LIB_SYS, errno,
1375 "calling fstat(%s)", dbfile);
1376 ERR_print_errors(bio_err);
1381 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1384 #ifndef OPENSSL_SYS_VMS
1385 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1387 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1389 dbattr_conf = app_load_config_quiet(buf);
1391 retdb = app_malloc(sizeof(*retdb), "new DB");
1395 retdb->attributes = *db_attr;
1397 retdb->attributes.unique_subject = 1;
1401 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1403 retdb->attributes.unique_subject = parse_yesno(p, 1);
1407 retdb->dbfname = OPENSSL_strdup(dbfile);
1408 #ifndef OPENSSL_NO_POSIX_IO
1413 NCONF_free(dbattr_conf);
1420 * Returns > 0 on success, <= 0 on error
1422 int index_index(CA_DB *db)
1424 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1425 LHASH_HASH_FN(index_serial),
1426 LHASH_COMP_FN(index_serial))) {
1428 "error creating serial number index:(%ld,%ld,%ld)\n",
1429 db->db->error, db->db->arg1, db->db->arg2);
1433 if (db->attributes.unique_subject
1434 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1435 LHASH_HASH_FN(index_name),
1436 LHASH_COMP_FN(index_name))) {
1437 BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
1438 db->db->error, db->db->arg1, db->db->arg2);
1444 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1450 j = strlen(dbfile) + strlen(suffix);
1451 if (j + 6 >= BSIZE) {
1452 BIO_printf(bio_err, "file name too long\n");
1455 #ifndef OPENSSL_SYS_VMS
1456 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1457 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1458 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1460 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1461 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1462 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1464 out = BIO_new_file(buf[0], "w");
1467 BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1470 j = TXT_DB_write(out, db->db);
1475 out = BIO_new_file(buf[1], "w");
1478 BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
1481 BIO_printf(out, "unique_subject = %s\n",
1482 db->attributes.unique_subject ? "yes" : "no");
1490 int rotate_index(const char *dbfile, const char *new_suffix,
1491 const char *old_suffix)
1496 i = strlen(dbfile) + strlen(old_suffix);
1497 j = strlen(dbfile) + strlen(new_suffix);
1500 if (j + 6 >= BSIZE) {
1501 BIO_printf(bio_err, "file name too long\n");
1504 #ifndef OPENSSL_SYS_VMS
1505 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1506 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1507 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1508 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1509 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1511 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1512 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1513 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1514 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1515 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1517 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1522 BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
1526 if (rename(buf[0], dbfile) < 0) {
1527 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
1529 rename(buf[1], dbfile);
1532 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1537 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
1539 rename(dbfile, buf[0]);
1540 rename(buf[1], dbfile);
1543 if (rename(buf[2], buf[4]) < 0) {
1544 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
1546 rename(buf[3], buf[4]);
1547 rename(dbfile, buf[0]);
1548 rename(buf[1], dbfile);
1556 void free_index(CA_DB *db)
1559 TXT_DB_free(db->db);
1560 OPENSSL_free(db->dbfname);
1565 int parse_yesno(const char *str, int def)
1569 case 'f': /* false */
1570 case 'F': /* FALSE */
1575 case 't': /* true */
1576 case 'T': /* TRUE */
1587 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1588 * where characters may be escaped by \
1590 X509_NAME *parse_name(const char *cp, long chtype, int canmulti)
1592 int nextismulti = 0;
1598 "name is expected to be in the format "
1599 "/type0=value0/type1=value1/type2=... where characters may "
1600 "be escaped by \\. This name is not in that format: '%s'\n",
1605 n = X509_NAME_new();
1608 work = OPENSSL_strdup(cp);
1610 BIO_printf(bio_err, "%s: Error copying name input\n", opt_getprog());
1617 unsigned char *valstr;
1619 int ismulti = nextismulti;
1622 /* Collect the type */
1623 while (*cp && *cp != '=')
1627 "%s: Hit end of string before finding the '='\n",
1634 /* Collect the value. */
1635 valstr = (unsigned char *)bp;
1636 for (; *cp && *cp != '/'; *bp++ = *cp++) {
1637 if (canmulti && *cp == '+') {
1641 if (*cp == '\\' && *++cp == '\0') {
1643 "%s: escape character at end of string\n",
1650 /* If not at EOS (must be + or /), move forward. */
1655 nid = OBJ_txt2nid(typestr);
1656 if (nid == NID_undef) {
1657 BIO_printf(bio_err, "%s: Skipping unknown attribute \"%s\"\n",
1658 opt_getprog(), typestr);
1661 if (*valstr == '\0') {
1663 "%s: No value provided for Subject Attribute %s, skipped\n",
1664 opt_getprog(), typestr);
1667 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1668 valstr, strlen((char *)valstr),
1669 -1, ismulti ? -1 : 0)) {
1670 BIO_printf(bio_err, "%s: Error adding name attribute \"/%s=%s\"\n",
1671 opt_getprog(), typestr ,valstr);
1686 * Read whole contents of a BIO into an allocated memory buffer and return
1690 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1694 unsigned char tbuf[1024];
1696 mem = BIO_new(BIO_s_mem());
1700 if ((maxlen != -1) && maxlen < 1024)
1704 len = BIO_read(in, tbuf, len);
1711 if (BIO_write(mem, tbuf, len) != len) {
1720 ret = BIO_get_mem_data(mem, (char **)out);
1721 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1726 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1729 char *stmp, *vtmp = NULL;
1730 stmp = OPENSSL_strdup(value);
1733 vtmp = strchr(stmp, ':');
1738 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1743 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1745 X509_POLICY_NODE *node;
1748 BIO_printf(bio_err, "%s Policies:", name);
1750 BIO_puts(bio_err, "\n");
1751 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1752 node = sk_X509_POLICY_NODE_value(nodes, i);
1753 X509_POLICY_NODE_print(bio_err, node, 2);
1756 BIO_puts(bio_err, " <empty>\n");
1760 void policies_print(X509_STORE_CTX *ctx)
1762 X509_POLICY_TREE *tree;
1763 int explicit_policy;
1764 tree = X509_STORE_CTX_get0_policy_tree(ctx);
1765 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1767 BIO_printf(bio_err, "Require explicit Policy: %s\n",
1768 explicit_policy ? "True" : "False");
1770 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1771 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1775 * next_protos_parse parses a comma separated list of strings into a string
1776 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1777 * outlen: (output) set to the length of the resulting buffer on success.
1778 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1779 * in: a NUL terminated string like "abc,def,ghi"
1781 * returns: a malloc'd buffer or NULL on failure.
1783 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1787 size_t i, start = 0;
1791 if (len == 0 || len >= 65535)
1794 out = app_malloc(len + 1, "NPN buffer");
1795 for (i = 0; i <= len; ++i) {
1796 if (i == len || in[i] == ',') {
1798 * Zero-length ALPN elements are invalid on the wire, we could be
1799 * strict and reject the entire string, but just ignoring extra
1800 * commas seems harmless and more friendly.
1802 * Every comma we skip in this way puts the input buffer another
1803 * byte ahead of the output buffer, so all stores into the output
1804 * buffer need to be decremented by the number commas skipped.
1811 if (i - start > 255) {
1815 out[start-skipped] = (unsigned char)(i - start);
1818 out[i + 1 - skipped] = in[i];
1822 if (len <= skipped) {
1827 *outlen = len + 1 - skipped;
1831 void print_cert_checks(BIO *bio, X509 *x,
1832 const char *checkhost,
1833 const char *checkemail, const char *checkip)
1838 BIO_printf(bio, "Hostname %s does%s match certificate\n",
1840 X509_check_host(x, checkhost, 0, 0, NULL) == 1
1845 BIO_printf(bio, "Email %s does%s match certificate\n",
1846 checkemail, X509_check_email(x, checkemail, 0, 0)
1851 BIO_printf(bio, "IP %s does%s match certificate\n",
1852 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1856 /* Get first http URL from a DIST_POINT structure */
1858 static const char *get_dp_url(DIST_POINT *dp)
1860 GENERAL_NAMES *gens;
1864 if (!dp->distpoint || dp->distpoint->type != 0)
1866 gens = dp->distpoint->name.fullname;
1867 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1868 gen = sk_GENERAL_NAME_value(gens, i);
1869 uri = GENERAL_NAME_get0_value(gen, >ype);
1870 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1871 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
1872 if (strncmp(uptr, "http://", 7) == 0)
1880 * Look through a CRLDP structure and attempt to find an http URL to
1881 * downloads a CRL from.
1884 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1887 const char *urlptr = NULL;
1888 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1889 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1890 urlptr = get_dp_url(dp);
1892 return load_crl(urlptr, FORMAT_HTTP);
1898 * Example of downloading CRLs from CRLDP: not usable for real world as it
1899 * always downloads, doesn't support non-blocking I/O and doesn't cache
1903 static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
1906 STACK_OF(X509_CRL) *crls = NULL;
1908 STACK_OF(DIST_POINT) *crldp;
1910 crls = sk_X509_CRL_new_null();
1913 x = X509_STORE_CTX_get_current_cert(ctx);
1914 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
1915 crl = load_crl_crldp(crldp);
1916 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1918 sk_X509_CRL_free(crls);
1921 sk_X509_CRL_push(crls, crl);
1922 /* Try to download delta CRL */
1923 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
1924 crl = load_crl_crldp(crldp);
1925 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1927 sk_X509_CRL_push(crls, crl);
1931 void store_setup_crl_download(X509_STORE *st)
1933 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
1936 #ifndef OPENSSL_NO_SOCK
1937 static const char *tls_error_hint(void)
1939 unsigned long err = ERR_peek_error();
1941 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
1942 err = ERR_peek_last_error();
1943 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
1946 switch (ERR_GET_REASON(err)) {
1947 case SSL_R_WRONG_VERSION_NUMBER:
1948 return "The server does not support (a suitable version of) TLS";
1949 case SSL_R_UNKNOWN_PROTOCOL:
1950 return "The server does not support HTTPS";
1951 case SSL_R_CERTIFICATE_VERIFY_FAILED:
1952 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
1953 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
1954 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
1955 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
1956 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
1957 default: /* no error or no hint available for error */
1962 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
1963 BIO *app_http_tls_cb(BIO *hbio, void *arg, int connect, int detail)
1965 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
1966 SSL_CTX *ssl_ctx = info->ssl_ctx;
1970 if (connect && detail) { /* connecting with TLS */
1971 if ((info->use_proxy
1972 && !OSSL_HTTP_proxy_connect(hbio, info->server, info->port,
1973 NULL, NULL, /* no proxy credentials */
1974 info->timeout, bio_err, opt_getprog()))
1975 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
1978 if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
1983 SSL_set_tlsext_host_name(ssl, info->server);
1985 SSL_set_connect_state(ssl);
1986 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
1988 hbio = BIO_push(sbio, hbio);
1989 } else if (!connect && !detail) { /* disconnecting after error */
1990 const char *hint = tls_error_hint();
1992 ERR_add_error_data(1, hint);
1994 * If we pop sbio and BIO_free() it this may lead to libssl double free.
1995 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2001 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2002 const char *proxy_port, SSL_CTX *ssl_ctx,
2003 const STACK_OF(CONF_VALUE) *headers,
2004 long timeout, const char *expected_content_type,
2005 const ASN1_ITEM *it)
2007 APP_HTTP_TLS_INFO info;
2011 ASN1_VALUE *resp = NULL;
2013 if (url == NULL || it == NULL) {
2014 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2018 if (!OSSL_HTTP_parse_url(url, &server, &port, NULL /* ppath */, &use_ssl))
2020 if (use_ssl && ssl_ctx == NULL) {
2021 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
2022 ERR_add_error_data(1, "missing SSL_CTX");
2026 info.server = server;
2028 info.use_proxy = proxy != NULL;
2029 info.timeout = timeout;
2030 info.ssl_ctx = ssl_ctx;
2031 resp = OSSL_HTTP_get_asn1(url, proxy, proxy_port,
2032 NULL, NULL, app_http_tls_cb, &info,
2033 headers, 0 /* maxline */, 0 /* max_resp_len */,
2034 timeout, expected_content_type, it);
2036 OPENSSL_free(server);
2042 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2043 const char *path, const char *proxy,
2044 const char *proxy_port, SSL_CTX *ssl_ctx,
2045 const STACK_OF(CONF_VALUE) *headers,
2046 const char *content_type,
2047 ASN1_VALUE *req, const ASN1_ITEM *req_it,
2048 long timeout, const ASN1_ITEM *rsp_it)
2050 APP_HTTP_TLS_INFO info;
2054 info.use_proxy = proxy != NULL;
2055 info.timeout = timeout;
2056 info.ssl_ctx = ssl_ctx;
2057 return OSSL_HTTP_post_asn1(host, port, path, ssl_ctx != NULL,
2059 NULL, NULL, app_http_tls_cb, &info,
2060 headers, content_type, req, req_it,
2062 0 /* max_resp_len */, timeout, NULL, rsp_it);
2068 * Platform-specific sections
2073 # define fileno(a) (int)_fileno(a)
2076 # include <windows.h>
2079 static int WIN32_rename(const char *from, const char *to)
2081 TCHAR *tfrom = NULL, *tto;
2085 if (sizeof(TCHAR) == 1) {
2086 tfrom = (TCHAR *)from;
2088 } else { /* UNICODE path */
2090 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2091 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2095 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2096 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2098 for (i = 0; i < flen; i++)
2099 tfrom[i] = (TCHAR)from[i];
2100 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2101 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2103 for (i = 0; i < tlen; i++)
2104 tto[i] = (TCHAR)to[i];
2107 if (MoveFile(tfrom, tto))
2109 err = GetLastError();
2110 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2111 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2113 err = GetLastError();
2115 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2117 else if (err == ERROR_ACCESS_DENIED)
2120 errno = EINVAL; /* we could map more codes... */
2124 if (tfrom != NULL && tfrom != (TCHAR *)from)
2130 /* app_tminterval section */
2132 double app_tminterval(int stop, int usertime)
2136 static ULARGE_INTEGER tmstart;
2137 static int warning = 1;
2138 # ifdef _WIN32_WINNT
2139 static HANDLE proc = NULL;
2143 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2144 GetCurrentProcessId());
2146 proc = (HANDLE) - 1;
2149 if (usertime && proc != (HANDLE) - 1) {
2151 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2157 if (usertime && warning) {
2158 BIO_printf(bio_err, "To get meaningful results, run "
2159 "this program on idle system.\n");
2162 GetSystemTime(&systime);
2163 SystemTimeToFileTime(&systime, &now);
2166 if (stop == TM_START) {
2167 tmstart.u.LowPart = now.dwLowDateTime;
2168 tmstart.u.HighPart = now.dwHighDateTime;
2170 ULARGE_INTEGER tmstop;
2172 tmstop.u.LowPart = now.dwLowDateTime;
2173 tmstop.u.HighPart = now.dwHighDateTime;
2175 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2180 #elif defined(OPENSSL_SYS_VXWORKS)
2183 double app_tminterval(int stop, int usertime)
2186 # ifdef CLOCK_REALTIME
2187 static struct timespec tmstart;
2188 struct timespec now;
2190 static unsigned long tmstart;
2193 static int warning = 1;
2195 if (usertime && warning) {
2196 BIO_printf(bio_err, "To get meaningful results, run "
2197 "this program on idle system.\n");
2200 # ifdef CLOCK_REALTIME
2201 clock_gettime(CLOCK_REALTIME, &now);
2202 if (stop == TM_START)
2205 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2206 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2209 if (stop == TM_START)
2212 ret = (now - tmstart) / (double)sysClkRateGet();
2217 #elif defined(OPENSSL_SYSTEM_VMS)
2221 double app_tminterval(int stop, int usertime)
2223 static clock_t tmstart;
2231 now = rus.tms_utime;
2234 now = clock(); /* sum of user and kernel times */
2237 gettimeofday(&tv, NULL);
2238 now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
2239 (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
2243 if (stop == TM_START)
2246 ret = (now - tmstart) / (double)(CLK_TCK);
2251 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2252 # include <sys/times.h>
2254 double app_tminterval(int stop, int usertime)
2258 clock_t now = times(&rus);
2259 static clock_t tmstart;
2262 now = rus.tms_utime;
2264 if (stop == TM_START) {
2267 long int tck = sysconf(_SC_CLK_TCK);
2268 ret = (now - tmstart) / (double)tck;
2275 # include <sys/time.h>
2276 # include <sys/resource.h>
2278 double app_tminterval(int stop, int usertime)
2283 static struct timeval tmstart;
2286 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2288 gettimeofday(&now, NULL);
2290 if (stop == TM_START)
2293 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2294 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2300 int app_access(const char* name, int flag)
2303 return _access(name, flag);
2305 return access(name, flag);
2309 int app_isdir(const char *name)
2311 return opt_isdir(name);
2314 /* raw_read|write section */
2316 # include "vms_term_sock.h"
2317 static int stdin_sock = -1;
2319 static void close_stdin_sock(void)
2321 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2324 int fileno_stdin(void)
2326 if (stdin_sock == -1) {
2327 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2328 atexit(close_stdin_sock);
2334 int fileno_stdin(void)
2336 return fileno(stdin);
2340 int fileno_stdout(void)
2342 return fileno(stdout);
2345 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2346 int raw_read_stdin(void *buf, int siz)
2349 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2354 #elif defined(__VMS)
2355 # include <sys/socket.h>
2357 int raw_read_stdin(void *buf, int siz)
2359 return recv(fileno_stdin(), buf, siz, 0);
2362 int raw_read_stdin(void *buf, int siz)
2364 return read(fileno_stdin(), buf, siz);
2368 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2369 int raw_write_stdout(const void *buf, int siz)
2372 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2378 int raw_write_stdout(const void *buf, int siz)
2380 return write(fileno_stdout(), buf, siz);
2385 * Centralized handling of input and output files with format specification
2386 * The format is meant to show what the input and output is supposed to be,
2387 * and is therefore a show of intent more than anything else. However, it
2388 * does impact behavior on some platforms, such as differentiating between
2389 * text and binary input/output on non-Unix platforms
2391 BIO *dup_bio_in(int format)
2393 return BIO_new_fp(stdin,
2394 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2397 BIO *dup_bio_out(int format)
2399 BIO *b = BIO_new_fp(stdout,
2400 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2401 void *prefix = NULL;
2403 #ifdef OPENSSL_SYS_VMS
2404 if (FMT_istext(format))
2405 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2408 if (FMT_istext(format)
2409 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2410 b = BIO_push(BIO_new(BIO_f_prefix()), b);
2411 BIO_set_prefix(b, prefix);
2417 BIO *dup_bio_err(int format)
2419 BIO *b = BIO_new_fp(stderr,
2420 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2421 #ifdef OPENSSL_SYS_VMS
2422 if (FMT_istext(format))
2423 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2428 void unbuffer(FILE *fp)
2431 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2432 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2433 * However, we trust that the C RTL will never give us a FILE pointer
2434 * above the first 4 GB of memory, so we simply turn off the warning
2437 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2438 # pragma environment save
2439 # pragma message disable maylosedata2
2442 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2443 # pragma environment restore
2447 static const char *modestr(char mode, int format)
2449 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2453 return FMT_istext(format) ? "a" : "ab";
2455 return FMT_istext(format) ? "r" : "rb";
2457 return FMT_istext(format) ? "w" : "wb";
2459 /* The assert above should make sure we never reach this point */
2463 static const char *modeverb(char mode)
2473 return "(doing something)";
2477 * Open a file for writing, owner-read-only.
2479 BIO *bio_open_owner(const char *filename, int format, int private)
2483 int fd = -1, bflags, mode, textmode;
2485 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2486 return bio_open_default(filename, 'w', format);
2495 textmode = FMT_istext(format);
2499 #elif defined(_O_BINARY)
2504 #ifdef OPENSSL_SYS_VMS
2505 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2506 * it still needs to know that we're going binary, or fdopen()
2507 * will fail with "invalid argument"... so we tell VMS what the
2511 fd = open(filename, mode, 0600, "ctx=bin");
2514 fd = open(filename, mode, 0600);
2517 fp = fdopen(fd, modestr('w', format));
2522 bflags |= BIO_FP_TEXT;
2523 b = BIO_new_fp(fp, bflags);
2528 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2529 opt_getprog(), filename, strerror(errno));
2530 ERR_print_errors(bio_err);
2531 /* If we have fp, then fdopen took over fd, so don't close both. */
2539 static BIO *bio_open_default_(const char *filename, char mode, int format,
2544 if (filename == NULL || strcmp(filename, "-") == 0) {
2545 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2553 "Can't open %s, %s\n",
2554 mode == 'r' ? "stdin" : "stdout", strerror(errno));
2556 ret = BIO_new_file(filename, modestr(mode, format));
2564 "Can't open %s for %s, %s\n",
2565 filename, modeverb(mode), strerror(errno));
2567 ERR_print_errors(bio_err);
2571 BIO *bio_open_default(const char *filename, char mode, int format)
2573 return bio_open_default_(filename, mode, format, 0);
2576 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2578 return bio_open_default_(filename, mode, format, 1);
2581 void wait_for_async(SSL *s)
2583 /* On Windows select only works for sockets, so we simply don't wait */
2584 #ifndef OPENSSL_SYS_WINDOWS
2591 if (!SSL_get_all_async_fds(s, NULL, &numfds))
2595 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2596 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2602 for (i = 0; i < numfds; i++) {
2603 if (width <= (int)fds[i])
2604 width = (int)fds[i] + 1;
2605 openssl_fdset((int)fds[i], &asyncfds);
2607 select(width, (void *)&asyncfds, NULL, NULL, NULL);
2612 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2613 #if defined(OPENSSL_SYS_MSDOS)
2614 int has_stdin_waiting(void)
2616 # if defined(OPENSSL_SYS_WINDOWS)
2617 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2619 INPUT_RECORD inputrec;
2623 if (inhand == INVALID_HANDLE_VALUE) {
2627 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2629 /* Probably redirected input? _kbhit() does not work in this case */
2640 /* Corrupt a signature by modifying final byte */
2641 void corrupt_signature(const ASN1_STRING *signature)
2643 unsigned char *s = signature->data;
2644 s[signature->length - 1] ^= 0x1;
2647 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2650 if (startdate == NULL || strcmp(startdate, "today") == 0) {
2651 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2654 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2657 if (enddate == NULL) {
2658 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2661 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2667 void make_uppercase(char *string)
2671 for (i = 0; string[i] != '\0'; i++)
2672 string[i] = toupper((unsigned char)string[i]);
2675 int opt_printf_stderr(const char *fmt, ...)
2681 ret = BIO_vprintf(bio_err, fmt, ap);
2686 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
2687 const OSSL_PARAM *paramdefs)
2689 OSSL_PARAM *params = NULL;
2690 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
2692 char *opt = "", *stmp, *vtmp = NULL;
2697 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
2701 for (params_n = 0; params_n < sz; params_n++) {
2702 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
2703 if ((stmp = OPENSSL_strdup(opt)) == NULL
2704 || (vtmp = strchr(stmp, ':')) == NULL)
2706 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2708 /* Skip over the separator so that vmtp points to the value */
2710 if (!OSSL_PARAM_allocate_from_text(¶ms[params_n], paramdefs,
2711 stmp, vtmp, strlen(vtmp)))
2715 params[params_n] = OSSL_PARAM_construct_end();
2719 BIO_printf(bio_err, "Parameter error '%s'\n", opt);
2720 ERR_print_errors(bio_err);
2721 app_params_free(params);
2725 void app_params_free(OSSL_PARAM *params)
2729 if (params != NULL) {
2730 for (i = 0; params[i].key != NULL; ++i)
2731 OPENSSL_free(params[i].data);
2732 OPENSSL_free(params);