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>
47 static int WIN32_rename(const char *from, const char *to);
48 # define rename(from,to) WIN32_rename((from),(to))
57 static int set_table_opts(unsigned long *flags, const char *arg,
58 const NAME_EX_TBL * in_tbl);
59 static int set_multi_opts(unsigned long *flags, const char *arg,
60 const NAME_EX_TBL * in_tbl);
62 int app_init(long mesgwin);
64 int chopup_args(ARGS *arg, char *buf)
67 char c = '\0', *p = NULL;
72 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
76 /* Skip whitespace. */
77 while (*p && isspace(_UC(*p)))
82 /* The start of something good :-) */
83 if (arg->argc >= arg->size) {
86 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
91 quoted = *p == '\'' || *p == '"';
94 arg->argv[arg->argc++] = p;
96 /* now look for the end of this */
102 while (*p && !isspace(_UC(*p)))
108 arg->argv[arg->argc] = NULL;
113 int app_init(long mesgwin)
119 int ctx_set_verify_locations(SSL_CTX *ctx, const char *CAfile,
120 const char *CApath, int noCAfile, int noCApath)
122 if (CAfile == NULL && CApath == NULL) {
123 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
125 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
130 return SSL_CTX_load_verify_locations(ctx, CAfile, CApath);
133 #ifndef OPENSSL_NO_CT
135 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
138 return SSL_CTX_set_default_ctlog_list_file(ctx);
140 return SSL_CTX_set_ctlog_list_file(ctx, path);
145 static unsigned long nmflag = 0;
146 static char nmflag_set = 0;
148 int set_nameopt(const char *arg)
150 int ret = set_name_ex(&nmflag, arg);
158 unsigned long get_nameopt(void)
160 return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
163 int dump_cert_text(BIO *out, X509 *x)
165 print_name(out, "subject=", X509_get_subject_name(x), get_nameopt());
167 print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
173 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
175 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
179 static char *app_get_pass(const char *arg, int keepbio);
181 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
183 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
186 *pass1 = app_get_pass(arg1, same);
189 } else if (pass1 != NULL) {
193 *pass2 = app_get_pass(arg2, same ? 2 : 0);
196 } else if (pass2 != NULL) {
202 static char *app_get_pass(const char *arg, int keepbio)
204 static BIO *pwdbio = NULL;
205 char *tmp, tpass[APP_PASS_LEN];
208 if (strncmp(arg, "pass:", 5) == 0)
209 return OPENSSL_strdup(arg + 5);
210 if (strncmp(arg, "env:", 4) == 0) {
211 tmp = getenv(arg + 4);
213 BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
216 return OPENSSL_strdup(tmp);
218 if (!keepbio || pwdbio == NULL) {
219 if (strncmp(arg, "file:", 5) == 0) {
220 pwdbio = BIO_new_file(arg + 5, "r");
221 if (pwdbio == NULL) {
222 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
227 * Under _WIN32, which covers even Win64 and CE, file
228 * descriptors referenced by BIO_s_fd are not inherited
229 * by child process and therefore below is not an option.
230 * It could have been an option if bss_fd.c was operating
231 * on real Windows descriptors, such as those obtained
234 } else if (strncmp(arg, "fd:", 3) == 0) {
238 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
239 if ((i < 0) || !pwdbio) {
240 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
244 * Can't do BIO_gets on an fd BIO so add a buffering BIO
246 btmp = BIO_new(BIO_f_buffer());
247 pwdbio = BIO_push(btmp, pwdbio);
249 } else if (strcmp(arg, "stdin") == 0) {
250 pwdbio = dup_bio_in(FORMAT_TEXT);
252 BIO_printf(bio_err, "Can't open BIO for stdin\n");
256 BIO_printf(bio_err, "Invalid password argument \"%s\"\n", arg);
260 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
262 BIO_free_all(pwdbio);
266 BIO_printf(bio_err, "Error reading password from BIO\n");
269 tmp = strchr(tpass, '\n');
272 return OPENSSL_strdup(tpass);
275 CONF *app_load_config_bio(BIO *in, const char *filename)
281 conf = NCONF_new(NULL);
282 i = NCONF_load_bio(conf, in, &errorline);
286 if (errorline <= 0) {
287 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
289 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
292 if (filename != NULL)
293 BIO_printf(bio_err, "config file \"%s\"\n", filename);
295 BIO_printf(bio_err, "config input");
301 CONF *app_load_config(const char *filename)
306 in = bio_open_default(filename, 'r', FORMAT_TEXT);
310 conf = app_load_config_bio(in, filename);
315 CONF *app_load_config_quiet(const char *filename)
320 in = bio_open_default_quiet(filename, 'r', FORMAT_TEXT);
324 conf = app_load_config_bio(in, filename);
329 int app_load_modules(const CONF *config)
331 CONF *to_free = NULL;
334 config = to_free = app_load_config_quiet(default_config_file);
338 if (CONF_modules_load(config, NULL, 0) <= 0) {
339 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
340 ERR_print_errors(bio_err);
348 int add_oid_section(CONF *conf)
351 STACK_OF(CONF_VALUE) *sktmp;
355 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
359 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
360 BIO_printf(bio_err, "problem loading oid section %s\n", p);
363 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
364 cnf = sk_CONF_VALUE_value(sktmp, i);
365 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
366 BIO_printf(bio_err, "problem creating object %s=%s\n",
367 cnf->name, cnf->value);
374 static int load_pkcs12(BIO *in, const char *desc,
375 pem_password_cb *pem_cb, PW_CB_DATA *cb_data,
376 EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
379 char tpass[PEM_BUFSIZE];
382 p12 = d2i_PKCS12_bio(in, NULL);
384 BIO_printf(bio_err, "Error loading PKCS12 file for %s\n", desc);
387 /* See if an empty password will do */
388 if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0)) {
392 pem_cb = (pem_password_cb *)password_callback;
393 len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
395 BIO_printf(bio_err, "Passphrase callback error for %s\n", desc);
398 if (len < PEM_BUFSIZE)
400 if (!PKCS12_verify_mac(p12, tpass, len)) {
402 "Mac verify error (wrong password?) in PKCS12 file for %s\n",
408 ret = PKCS12_parse(p12, pass, pkey, cert, ca);
414 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
415 static int load_cert_crl_http(const char *url, X509 **pcert, X509_CRL **pcrl)
417 char *host = NULL, *port = NULL, *path = NULL;
419 OCSP_REQ_CTX *rctx = NULL;
421 if (!OCSP_parse_url(url, &host, &port, &path, &use_ssl))
424 BIO_puts(bio_err, "https not supported\n");
427 bio = BIO_new_connect(host);
428 if (!bio || !BIO_set_conn_port(bio, port))
430 rctx = OCSP_REQ_CTX_new(bio, 1024);
433 if (!OCSP_REQ_CTX_http(rctx, "GET", path))
435 if (!OCSP_REQ_CTX_add1_header(rctx, "Host", host))
439 rv = X509_http_nbio(rctx, pcert);
443 rv = X509_CRL_http_nbio(rctx, pcrl);
452 OCSP_REQ_CTX_free(rctx);
454 BIO_printf(bio_err, "Error loading %s from %s\n",
455 pcert ? "certificate" : "CRL", url);
456 ERR_print_errors(bio_err);
462 X509 *load_cert(const char *file, int format, const char *cert_descrip)
467 if (format == FORMAT_HTTP) {
468 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
469 load_cert_crl_http(file, &x, NULL);
476 cert = dup_bio_in(format);
478 cert = bio_open_default(file, 'r', format);
483 if (format == FORMAT_ASN1) {
484 x = d2i_X509_bio(cert, NULL);
485 } else if (format == FORMAT_PEM) {
486 x = PEM_read_bio_X509_AUX(cert, NULL,
487 (pem_password_cb *)password_callback, NULL);
488 } else if (format == FORMAT_PKCS12) {
489 if (!load_pkcs12(cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
492 BIO_printf(bio_err, "bad input format specified for %s\n", cert_descrip);
497 BIO_printf(bio_err, "unable to load certificate\n");
498 ERR_print_errors(bio_err);
504 X509_CRL *load_crl(const char *infile, int format)
509 if (format == FORMAT_HTTP) {
510 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
511 load_cert_crl_http(infile, NULL, &x);
516 in = bio_open_default(infile, 'r', format);
519 if (format == FORMAT_ASN1) {
520 x = d2i_X509_CRL_bio(in, NULL);
521 } else if (format == FORMAT_PEM) {
522 x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
524 BIO_printf(bio_err, "bad input format specified for input crl\n");
528 BIO_printf(bio_err, "unable to load CRL\n");
529 ERR_print_errors(bio_err);
538 EVP_PKEY *load_key(const char *file, int format, int maybe_stdin,
539 const char *pass, ENGINE *e, const char *key_descrip)
542 EVP_PKEY *pkey = NULL;
545 cb_data.password = pass;
546 cb_data.prompt_info = file;
548 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
549 BIO_printf(bio_err, "no keyfile specified\n");
552 if (format == FORMAT_ENGINE) {
554 BIO_printf(bio_err, "no engine specified\n");
556 #ifndef OPENSSL_NO_ENGINE
557 if (ENGINE_init(e)) {
558 pkey = ENGINE_load_private_key(e, file,
559 (UI_METHOD *)get_ui_method(),
564 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
565 ERR_print_errors(bio_err);
568 BIO_printf(bio_err, "engines not supported\n");
573 if (file == NULL && maybe_stdin) {
575 key = dup_bio_in(format);
577 key = bio_open_default(file, 'r', format);
581 if (format == FORMAT_ASN1) {
582 pkey = d2i_PrivateKey_bio(key, NULL);
583 } else if (format == FORMAT_PEM) {
584 pkey = PEM_read_bio_PrivateKey(key, NULL, wrap_password_callback, &cb_data);
585 } else if (format == FORMAT_PKCS12) {
586 if (!load_pkcs12(key, key_descrip, wrap_password_callback, &cb_data,
589 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
590 } else if (format == FORMAT_MSBLOB) {
591 pkey = b2i_PrivateKey_bio(key);
592 } else if (format == FORMAT_PVK) {
593 pkey = b2i_PVK_bio(key, wrap_password_callback, &cb_data);
596 BIO_printf(bio_err, "bad input format specified for key file\n");
602 BIO_printf(bio_err, "unable to load %s\n", key_descrip);
603 ERR_print_errors(bio_err);
608 EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin,
609 const char *pass, ENGINE *e, const char *key_descrip)
612 EVP_PKEY *pkey = NULL;
615 cb_data.password = pass;
616 cb_data.prompt_info = file;
618 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
619 BIO_printf(bio_err, "no keyfile specified\n");
622 if (format == FORMAT_ENGINE) {
624 BIO_printf(bio_err, "no engine specified\n");
626 #ifndef OPENSSL_NO_ENGINE
627 pkey = ENGINE_load_public_key(e, file, (UI_METHOD *)get_ui_method(),
630 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
631 ERR_print_errors(bio_err);
634 BIO_printf(bio_err, "engines not supported\n");
639 if (file == NULL && maybe_stdin) {
641 key = dup_bio_in(format);
643 key = bio_open_default(file, 'r', format);
647 if (format == FORMAT_ASN1) {
648 pkey = d2i_PUBKEY_bio(key, NULL);
649 } else if (format == FORMAT_ASN1RSA) {
650 #ifndef OPENSSL_NO_RSA
652 rsa = d2i_RSAPublicKey_bio(key, NULL);
654 pkey = EVP_PKEY_new();
656 EVP_PKEY_set1_RSA(pkey, rsa);
660 BIO_printf(bio_err, "RSA keys not supported\n");
663 } else if (format == FORMAT_PEMRSA) {
664 #ifndef OPENSSL_NO_RSA
666 rsa = PEM_read_bio_RSAPublicKey(key, NULL,
667 (pem_password_cb *)password_callback,
670 pkey = EVP_PKEY_new();
672 EVP_PKEY_set1_RSA(pkey, rsa);
676 BIO_printf(bio_err, "RSA keys not supported\n");
679 } else if (format == FORMAT_PEM) {
680 pkey = PEM_read_bio_PUBKEY(key, NULL,
681 (pem_password_cb *)password_callback,
683 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
684 } else if (format == FORMAT_MSBLOB) {
685 pkey = b2i_PublicKey_bio(key);
691 BIO_printf(bio_err, "unable to load %s\n", key_descrip);
695 static int load_certs_crls(const char *file, int format,
696 const char *pass, const char *desc,
697 STACK_OF(X509) **pcerts,
698 STACK_OF(X509_CRL) **pcrls)
702 STACK_OF(X509_INFO) *xis = NULL;
707 cb_data.password = pass;
708 cb_data.prompt_info = file;
710 if (format != FORMAT_PEM) {
711 BIO_printf(bio_err, "bad input format specified for %s\n", desc);
715 bio = bio_open_default(file, 'r', FORMAT_PEM);
719 xis = PEM_X509_INFO_read_bio(bio, NULL,
720 (pem_password_cb *)password_callback,
725 if (pcerts != NULL && *pcerts == NULL) {
726 *pcerts = sk_X509_new_null();
731 if (pcrls != NULL && *pcrls == NULL) {
732 *pcrls = sk_X509_CRL_new_null();
737 for (i = 0; i < sk_X509_INFO_num(xis); i++) {
738 xi = sk_X509_INFO_value(xis, i);
739 if (xi->x509 != NULL && pcerts != NULL) {
740 if (!sk_X509_push(*pcerts, xi->x509))
744 if (xi->crl != NULL && pcrls != NULL) {
745 if (!sk_X509_CRL_push(*pcrls, xi->crl))
751 if (pcerts != NULL && sk_X509_num(*pcerts) > 0)
754 if (pcrls != NULL && sk_X509_CRL_num(*pcrls) > 0)
759 sk_X509_INFO_pop_free(xis, X509_INFO_free);
762 if (pcerts != NULL) {
763 sk_X509_pop_free(*pcerts, X509_free);
767 sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
770 BIO_printf(bio_err, "unable to load %s\n",
771 pcerts ? "certificates" : "CRLs");
772 ERR_print_errors(bio_err);
777 void* app_malloc(int sz, const char *what)
779 void *vp = OPENSSL_malloc(sz);
782 BIO_printf(bio_err, "%s: Could not allocate %d bytes for %s\n",
783 opt_getprog(), sz, what);
784 ERR_print_errors(bio_err);
791 * Initialize or extend, if *certs != NULL, a certificate stack.
793 int load_certs(const char *file, STACK_OF(X509) **certs, int format,
794 const char *pass, const char *desc)
796 return load_certs_crls(file, format, pass, desc, certs, NULL);
800 * Initialize or extend, if *crls != NULL, a certificate stack.
802 int load_crls(const char *file, STACK_OF(X509_CRL) **crls, int format,
803 const char *pass, const char *desc)
805 return load_certs_crls(file, format, pass, desc, NULL, crls);
808 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
809 /* Return error for unknown extensions */
810 #define X509V3_EXT_DEFAULT 0
811 /* Print error for unknown extensions */
812 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
813 /* ASN1 parse unknown extensions */
814 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
815 /* BIO_dump unknown extensions */
816 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
818 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
819 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
821 int set_cert_ex(unsigned long *flags, const char *arg)
823 static const NAME_EX_TBL cert_tbl[] = {
824 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
825 {"ca_default", X509_FLAG_CA, 0xffffffffl},
826 {"no_header", X509_FLAG_NO_HEADER, 0},
827 {"no_version", X509_FLAG_NO_VERSION, 0},
828 {"no_serial", X509_FLAG_NO_SERIAL, 0},
829 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
830 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
831 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
832 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
833 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
834 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
835 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
836 {"no_aux", X509_FLAG_NO_AUX, 0},
837 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
838 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
839 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
840 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
841 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
844 return set_multi_opts(flags, arg, cert_tbl);
847 int set_name_ex(unsigned long *flags, const char *arg)
849 static const NAME_EX_TBL ex_tbl[] = {
850 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
851 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
852 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
853 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
854 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
855 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
856 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
857 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
858 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
859 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
860 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
861 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
862 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
863 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
864 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
865 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
866 {"dn_rev", XN_FLAG_DN_REV, 0},
867 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
868 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
869 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
870 {"align", XN_FLAG_FN_ALIGN, 0},
871 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
872 {"space_eq", XN_FLAG_SPC_EQ, 0},
873 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
874 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
875 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
876 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
877 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
880 if (set_multi_opts(flags, arg, ex_tbl) == 0)
882 if (*flags != XN_FLAG_COMPAT
883 && (*flags & XN_FLAG_SEP_MASK) == 0)
884 *flags |= XN_FLAG_SEP_CPLUS_SPC;
888 int set_ext_copy(int *copy_type, const char *arg)
890 if (strcasecmp(arg, "none") == 0)
891 *copy_type = EXT_COPY_NONE;
892 else if (strcasecmp(arg, "copy") == 0)
893 *copy_type = EXT_COPY_ADD;
894 else if (strcasecmp(arg, "copyall") == 0)
895 *copy_type = EXT_COPY_ALL;
901 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
903 STACK_OF(X509_EXTENSION) *exts = NULL;
904 X509_EXTENSION *ext, *tmpext;
907 if (!x || !req || (copy_type == EXT_COPY_NONE))
909 exts = X509_REQ_get_extensions(req);
911 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
912 ext = sk_X509_EXTENSION_value(exts, i);
913 obj = X509_EXTENSION_get_object(ext);
914 idx = X509_get_ext_by_OBJ(x, obj, -1);
915 /* Does extension exist? */
917 /* If normal copy don't override existing extension */
918 if (copy_type == EXT_COPY_ADD)
920 /* Delete all extensions of same type */
922 tmpext = X509_get_ext(x, idx);
923 X509_delete_ext(x, idx);
924 X509_EXTENSION_free(tmpext);
925 idx = X509_get_ext_by_OBJ(x, obj, -1);
928 if (!X509_add_ext(x, ext, -1))
936 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
941 static int set_multi_opts(unsigned long *flags, const char *arg,
942 const NAME_EX_TBL * in_tbl)
944 STACK_OF(CONF_VALUE) *vals;
949 vals = X509V3_parse_list(arg);
950 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
951 val = sk_CONF_VALUE_value(vals, i);
952 if (!set_table_opts(flags, val->name, in_tbl))
955 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
959 static int set_table_opts(unsigned long *flags, const char *arg,
960 const NAME_EX_TBL * in_tbl)
963 const NAME_EX_TBL *ptbl;
969 } else if (c == '+') {
976 for (ptbl = in_tbl; ptbl->name; ptbl++) {
977 if (strcasecmp(arg, ptbl->name) == 0) {
978 *flags &= ~ptbl->mask;
980 *flags |= ptbl->flag;
982 *flags &= ~ptbl->flag;
989 void print_name(BIO *out, const char *title, X509_NAME *nm,
990 unsigned long lflags)
997 BIO_puts(out, title);
998 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1002 if (lflags == XN_FLAG_COMPAT) {
1003 buf = X509_NAME_oneline(nm, 0, 0);
1005 BIO_puts(out, "\n");
1009 BIO_puts(out, "\n");
1010 X509_NAME_print_ex(out, nm, indent, lflags);
1011 BIO_puts(out, "\n");
1015 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1016 int len, unsigned char *buffer)
1018 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1019 if (BN_is_zero(in)) {
1020 BIO_printf(out, "\n 0x00");
1024 l = BN_bn2bin(in, buffer);
1025 for (i = 0; i < l; i++) {
1026 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1028 BIO_printf(out, "0x%02X,", buffer[i]);
1030 BIO_printf(out, "0x%02X", buffer[i]);
1033 BIO_printf(out, "\n };\n");
1036 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1040 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1041 for (i = 0; i < len; i++) {
1043 BIO_printf(out, "\n ");
1045 BIO_printf(out, "0x%02X, ", d[i]);
1047 BIO_printf(out, "0x%02X", d[i]);
1049 BIO_printf(out, "\n};\n");
1052 X509_STORE *setup_verify(const char *CAfile, const char *CApath, int noCAfile, int noCApath)
1054 X509_STORE *store = X509_STORE_new();
1055 X509_LOOKUP *lookup;
1060 if (CAfile != NULL || !noCAfile) {
1061 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1065 if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1066 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1070 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1074 if (CApath != NULL || !noCApath) {
1075 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1079 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1080 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1084 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1091 X509_STORE_free(store);
1095 #ifndef OPENSSL_NO_ENGINE
1096 /* Try to load an engine in a shareable library */
1097 static ENGINE *try_load_engine(const char *engine)
1099 ENGINE *e = ENGINE_by_id("dynamic");
1101 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1102 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1111 ENGINE *setup_engine(const char *engine, int debug)
1115 #ifndef OPENSSL_NO_ENGINE
1116 if (engine != NULL) {
1117 if (strcmp(engine, "auto") == 0) {
1118 BIO_printf(bio_err, "enabling auto ENGINE support\n");
1119 ENGINE_register_all_complete();
1122 if ((e = ENGINE_by_id(engine)) == NULL
1123 && (e = try_load_engine(engine)) == NULL) {
1124 BIO_printf(bio_err, "invalid engine \"%s\"\n", engine);
1125 ERR_print_errors(bio_err);
1129 ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1131 ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, (void *)get_ui_method(),
1133 if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1134 BIO_printf(bio_err, "can't use that engine\n");
1135 ERR_print_errors(bio_err);
1140 BIO_printf(bio_err, "engine \"%s\" set.\n", ENGINE_get_id(e));
1146 void release_engine(ENGINE *e)
1148 #ifndef OPENSSL_NO_ENGINE
1150 /* Free our "structural" reference. */
1155 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1162 return OPENSSL_LH_strhash(n);
1165 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1166 const OPENSSL_CSTRING *b)
1168 const char *aa, *bb;
1170 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1171 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1172 return strcmp(aa, bb);
1175 static int index_name_qual(char **a)
1177 return (a[0][0] == 'V');
1180 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1182 return OPENSSL_LH_strhash(a[DB_name]);
1185 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1187 return strcmp(a[DB_name], b[DB_name]);
1190 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1191 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1192 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1193 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1196 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1201 ASN1_INTEGER *ai = NULL;
1203 ai = ASN1_INTEGER_new();
1207 in = BIO_new_file(serialfile, "r");
1215 if (ret == NULL || !rand_serial(ret, ai))
1216 BIO_printf(bio_err, "Out of memory\n");
1218 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1219 BIO_printf(bio_err, "unable to load number from %s\n",
1223 ret = ASN1_INTEGER_to_BN(ai, NULL);
1226 "error converting number from bin to BIGNUM\n");
1237 ASN1_INTEGER_free(ai);
1241 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1242 ASN1_INTEGER **retai)
1247 ASN1_INTEGER *ai = NULL;
1251 j = strlen(serialfile);
1253 j = strlen(serialfile) + strlen(suffix) + 1;
1255 BIO_printf(bio_err, "file name too long\n");
1260 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1262 #ifndef OPENSSL_SYS_VMS
1263 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1265 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1268 out = BIO_new_file(buf[0], "w");
1270 ERR_print_errors(bio_err);
1274 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1275 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1278 i2a_ASN1_INTEGER(out, ai);
1279 BIO_puts(out, "\n");
1287 ASN1_INTEGER_free(ai);
1291 int rotate_serial(const char *serialfile, const char *new_suffix,
1292 const char *old_suffix)
1297 i = strlen(serialfile) + strlen(old_suffix);
1298 j = strlen(serialfile) + strlen(new_suffix);
1301 if (j + 1 >= BSIZE) {
1302 BIO_printf(bio_err, "file name too long\n");
1305 #ifndef OPENSSL_SYS_VMS
1306 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1307 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1309 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1310 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1312 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1318 "unable to rename %s to %s\n", serialfile, buf[1]);
1322 if (rename(buf[0], serialfile) < 0) {
1324 "unable to rename %s to %s\n", buf[0], serialfile);
1326 rename(buf[1], serialfile);
1334 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1339 btmp = b == NULL ? BN_new() : b;
1343 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1345 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1358 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1360 CA_DB *retdb = NULL;
1361 TXT_DB *tmpdb = NULL;
1363 CONF *dbattr_conf = NULL;
1365 #ifndef OPENSSL_NO_POSIX_IO
1370 in = BIO_new_file(dbfile, "r");
1372 ERR_print_errors(bio_err);
1376 #ifndef OPENSSL_NO_POSIX_IO
1377 BIO_get_fp(in, &dbfp);
1378 if (fstat(fileno(dbfp), &dbst) == -1) {
1379 SYSerr(SYS_F_FSTAT, errno);
1380 ERR_add_error_data(3, "fstat('", dbfile, "')");
1381 ERR_print_errors(bio_err);
1386 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1389 #ifndef OPENSSL_SYS_VMS
1390 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1392 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1394 dbattr_conf = app_load_config_quiet(buf);
1396 retdb = app_malloc(sizeof(*retdb), "new DB");
1400 retdb->attributes = *db_attr;
1402 retdb->attributes.unique_subject = 1;
1406 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1408 retdb->attributes.unique_subject = parse_yesno(p, 1);
1412 retdb->dbfname = OPENSSL_strdup(dbfile);
1413 #ifndef OPENSSL_NO_POSIX_IO
1418 NCONF_free(dbattr_conf);
1425 * Returns > 0 on success, <= 0 on error
1427 int index_index(CA_DB *db)
1429 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1430 LHASH_HASH_FN(index_serial),
1431 LHASH_COMP_FN(index_serial))) {
1433 "error creating serial number index:(%ld,%ld,%ld)\n",
1434 db->db->error, db->db->arg1, db->db->arg2);
1438 if (db->attributes.unique_subject
1439 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1440 LHASH_HASH_FN(index_name),
1441 LHASH_COMP_FN(index_name))) {
1442 BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
1443 db->db->error, db->db->arg1, db->db->arg2);
1449 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1455 j = strlen(dbfile) + strlen(suffix);
1456 if (j + 6 >= BSIZE) {
1457 BIO_printf(bio_err, "file name too long\n");
1460 #ifndef OPENSSL_SYS_VMS
1461 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1462 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1463 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1465 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1466 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1467 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1469 out = BIO_new_file(buf[0], "w");
1472 BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1475 j = TXT_DB_write(out, db->db);
1480 out = BIO_new_file(buf[1], "w");
1483 BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
1486 BIO_printf(out, "unique_subject = %s\n",
1487 db->attributes.unique_subject ? "yes" : "no");
1495 int rotate_index(const char *dbfile, const char *new_suffix,
1496 const char *old_suffix)
1501 i = strlen(dbfile) + strlen(old_suffix);
1502 j = strlen(dbfile) + strlen(new_suffix);
1505 if (j + 6 >= BSIZE) {
1506 BIO_printf(bio_err, "file name too long\n");
1509 #ifndef OPENSSL_SYS_VMS
1510 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1511 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1512 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1513 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1514 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1516 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1517 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1518 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1519 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1520 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1522 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1527 BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
1531 if (rename(buf[0], dbfile) < 0) {
1532 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
1534 rename(buf[1], dbfile);
1537 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1542 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
1544 rename(dbfile, buf[0]);
1545 rename(buf[1], dbfile);
1548 if (rename(buf[2], buf[4]) < 0) {
1549 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
1551 rename(buf[3], buf[4]);
1552 rename(dbfile, buf[0]);
1553 rename(buf[1], dbfile);
1561 void free_index(CA_DB *db)
1564 TXT_DB_free(db->db);
1565 OPENSSL_free(db->dbfname);
1570 int parse_yesno(const char *str, int def)
1574 case 'f': /* false */
1575 case 'F': /* FALSE */
1580 case 't': /* true */
1581 case 'T': /* TRUE */
1592 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1593 * where characters may be escaped by \
1595 X509_NAME *parse_name(const char *cp, long chtype, int canmulti)
1597 int nextismulti = 0;
1603 "name is expected to be in the format "
1604 "/type0=value0/type1=value1/type2=... where characters may "
1605 "be escaped by \\. This name is not in that format: '%s'\n",
1610 n = X509_NAME_new();
1613 work = OPENSSL_strdup(cp);
1620 unsigned char *valstr;
1622 int ismulti = nextismulti;
1625 /* Collect the type */
1626 while (*cp && *cp != '=')
1630 "%s: Hit end of string before finding the equals.\n",
1637 /* Collect the value. */
1638 valstr = (unsigned char *)bp;
1639 for (; *cp && *cp != '/'; *bp++ = *cp++) {
1640 if (canmulti && *cp == '+') {
1644 if (*cp == '\\' && *++cp == '\0') {
1646 "%s: escape character at end of string\n",
1653 /* If not at EOS (must be + or /), move forward. */
1658 nid = OBJ_txt2nid(typestr);
1659 if (nid == NID_undef) {
1660 BIO_printf(bio_err, "%s: Skipping unknown attribute \"%s\"\n",
1661 opt_getprog(), typestr);
1664 if (*valstr == '\0') {
1666 "%s: No value provided for Subject Attribute %s, skipped\n",
1667 opt_getprog(), typestr);
1670 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1671 valstr, strlen((char *)valstr),
1672 -1, ismulti ? -1 : 0))
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;
1793 out = app_malloc(strlen(in) + 1, "NPN buffer");
1794 for (i = 0; i <= len; ++i) {
1795 if (i == len || in[i] == ',') {
1796 if (i - start > 255) {
1800 out[start] = (unsigned char)(i - start);
1811 void print_cert_checks(BIO *bio, X509 *x,
1812 const char *checkhost,
1813 const char *checkemail, const char *checkip)
1818 BIO_printf(bio, "Hostname %s does%s match certificate\n",
1820 X509_check_host(x, checkhost, 0, 0, NULL) == 1
1825 BIO_printf(bio, "Email %s does%s match certificate\n",
1826 checkemail, X509_check_email(x, checkemail, 0, 0)
1831 BIO_printf(bio, "IP %s does%s match certificate\n",
1832 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1836 /* Get first http URL from a DIST_POINT structure */
1838 static const char *get_dp_url(DIST_POINT *dp)
1840 GENERAL_NAMES *gens;
1844 if (!dp->distpoint || dp->distpoint->type != 0)
1846 gens = dp->distpoint->name.fullname;
1847 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1848 gen = sk_GENERAL_NAME_value(gens, i);
1849 uri = GENERAL_NAME_get0_value(gen, >ype);
1850 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1851 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
1852 if (strncmp(uptr, "http://", 7) == 0)
1860 * Look through a CRLDP structure and attempt to find an http URL to
1861 * downloads a CRL from.
1864 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1867 const char *urlptr = NULL;
1868 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1869 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1870 urlptr = get_dp_url(dp);
1872 return load_crl(urlptr, FORMAT_HTTP);
1878 * Example of downloading CRLs from CRLDP: not usable for real world as it
1879 * always downloads, doesn't support non-blocking I/O and doesn't cache
1883 static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
1886 STACK_OF(X509_CRL) *crls = NULL;
1888 STACK_OF(DIST_POINT) *crldp;
1890 crls = sk_X509_CRL_new_null();
1893 x = X509_STORE_CTX_get_current_cert(ctx);
1894 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
1895 crl = load_crl_crldp(crldp);
1896 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1898 sk_X509_CRL_free(crls);
1901 sk_X509_CRL_push(crls, crl);
1902 /* Try to download delta CRL */
1903 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
1904 crl = load_crl_crldp(crldp);
1905 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1907 sk_X509_CRL_push(crls, crl);
1911 void store_setup_crl_download(X509_STORE *st)
1913 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
1917 * Platform-specific sections
1922 # define fileno(a) (int)_fileno(a)
1925 # include <windows.h>
1928 static int WIN32_rename(const char *from, const char *to)
1930 TCHAR *tfrom = NULL, *tto;
1934 if (sizeof(TCHAR) == 1) {
1935 tfrom = (TCHAR *)from;
1937 } else { /* UNICODE path */
1939 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
1940 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
1944 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
1945 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
1947 for (i = 0; i < flen; i++)
1948 tfrom[i] = (TCHAR)from[i];
1949 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
1950 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
1952 for (i = 0; i < tlen; i++)
1953 tto[i] = (TCHAR)to[i];
1956 if (MoveFile(tfrom, tto))
1958 err = GetLastError();
1959 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
1960 if (DeleteFile(tto) && MoveFile(tfrom, tto))
1962 err = GetLastError();
1964 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
1966 else if (err == ERROR_ACCESS_DENIED)
1969 errno = EINVAL; /* we could map more codes... */
1973 if (tfrom != NULL && tfrom != (TCHAR *)from)
1979 /* app_tminterval section */
1981 double app_tminterval(int stop, int usertime)
1985 static ULARGE_INTEGER tmstart;
1986 static int warning = 1;
1987 # ifdef _WIN32_WINNT
1988 static HANDLE proc = NULL;
1992 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
1993 GetCurrentProcessId());
1995 proc = (HANDLE) - 1;
1998 if (usertime && proc != (HANDLE) - 1) {
2000 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2006 if (usertime && warning) {
2007 BIO_printf(bio_err, "To get meaningful results, run "
2008 "this program on idle system.\n");
2011 GetSystemTime(&systime);
2012 SystemTimeToFileTime(&systime, &now);
2015 if (stop == TM_START) {
2016 tmstart.u.LowPart = now.dwLowDateTime;
2017 tmstart.u.HighPart = now.dwHighDateTime;
2019 ULARGE_INTEGER tmstop;
2021 tmstop.u.LowPart = now.dwLowDateTime;
2022 tmstop.u.HighPart = now.dwHighDateTime;
2024 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2029 #elif defined(OPENSSL_SYS_VXWORKS)
2032 double app_tminterval(int stop, int usertime)
2035 # ifdef CLOCK_REALTIME
2036 static struct timespec tmstart;
2037 struct timespec now;
2039 static unsigned long tmstart;
2042 static int warning = 1;
2044 if (usertime && warning) {
2045 BIO_printf(bio_err, "To get meaningful results, run "
2046 "this program on idle system.\n");
2049 # ifdef CLOCK_REALTIME
2050 clock_gettime(CLOCK_REALTIME, &now);
2051 if (stop == TM_START)
2054 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2055 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2058 if (stop == TM_START)
2061 ret = (now - tmstart) / (double)sysClkRateGet();
2066 #elif defined(OPENSSL_SYSTEM_VMS)
2070 double app_tminterval(int stop, int usertime)
2072 static clock_t tmstart;
2080 now = rus.tms_utime;
2083 now = clock(); /* sum of user and kernel times */
2086 gettimeofday(&tv, NULL);
2087 now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
2088 (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
2092 if (stop == TM_START)
2095 ret = (now - tmstart) / (double)(CLK_TCK);
2100 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2101 # include <sys/times.h>
2103 double app_tminterval(int stop, int usertime)
2107 clock_t now = times(&rus);
2108 static clock_t tmstart;
2111 now = rus.tms_utime;
2113 if (stop == TM_START) {
2116 long int tck = sysconf(_SC_CLK_TCK);
2117 ret = (now - tmstart) / (double)tck;
2124 # include <sys/time.h>
2125 # include <sys/resource.h>
2127 double app_tminterval(int stop, int usertime)
2132 static struct timeval tmstart;
2135 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2137 gettimeofday(&now, NULL);
2139 if (stop == TM_START)
2142 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2143 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2149 int app_access(const char* name, int flag)
2152 return _access(name, flag);
2154 return access(name, flag);
2158 int app_isdir(const char *name)
2160 return opt_isdir(name);
2163 /* raw_read|write section */
2165 # include "vms_term_sock.h"
2166 static int stdin_sock = -1;
2168 static void close_stdin_sock(void)
2170 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2173 int fileno_stdin(void)
2175 if (stdin_sock == -1) {
2176 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2177 atexit(close_stdin_sock);
2183 int fileno_stdin(void)
2185 return fileno(stdin);
2189 int fileno_stdout(void)
2191 return fileno(stdout);
2194 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2195 int raw_read_stdin(void *buf, int siz)
2198 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2203 #elif defined(__VMS)
2204 # include <sys/socket.h>
2206 int raw_read_stdin(void *buf, int siz)
2208 return recv(fileno_stdin(), buf, siz, 0);
2211 int raw_read_stdin(void *buf, int siz)
2213 return read(fileno_stdin(), buf, siz);
2217 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2218 int raw_write_stdout(const void *buf, int siz)
2221 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2227 int raw_write_stdout(const void *buf, int siz)
2229 return write(fileno_stdout(), buf, siz);
2234 * Centralized handling of input and output files with format specification
2235 * The format is meant to show what the input and output is supposed to be,
2236 * and is therefore a show of intent more than anything else. However, it
2237 * does impact behavior on some platforms, such as differentiating between
2238 * text and binary input/output on non-Unix platforms
2240 BIO *dup_bio_in(int format)
2242 return BIO_new_fp(stdin,
2243 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2246 static BIO_METHOD *prefix_method = NULL;
2248 BIO *dup_bio_out(int format)
2250 BIO *b = BIO_new_fp(stdout,
2251 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2252 void *prefix = NULL;
2254 #ifdef OPENSSL_SYS_VMS
2255 if (FMT_istext(format))
2256 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2259 if (FMT_istext(format) && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2260 if (prefix_method == NULL)
2261 prefix_method = apps_bf_prefix();
2262 b = BIO_push(BIO_new(prefix_method), b);
2263 BIO_ctrl(b, PREFIX_CTRL_SET_PREFIX, 0, prefix);
2269 BIO *dup_bio_err(int format)
2271 BIO *b = BIO_new_fp(stderr,
2272 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2273 #ifdef OPENSSL_SYS_VMS
2274 if (FMT_istext(format))
2275 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2280 void destroy_prefix_method(void)
2282 BIO_meth_free(prefix_method);
2283 prefix_method = NULL;
2286 void unbuffer(FILE *fp)
2289 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2290 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2291 * However, we trust that the C RTL will never give us a FILE pointer
2292 * above the first 4 GB of memory, so we simply turn off the warning
2295 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2296 # pragma environment save
2297 # pragma message disable maylosedata2
2300 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2301 # pragma environment restore
2305 static const char *modestr(char mode, int format)
2307 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2311 return FMT_istext(format) ? "a" : "ab";
2313 return FMT_istext(format) ? "r" : "rb";
2315 return FMT_istext(format) ? "w" : "wb";
2317 /* The assert above should make sure we never reach this point */
2321 static const char *modeverb(char mode)
2331 return "(doing something)";
2335 * Open a file for writing, owner-read-only.
2337 BIO *bio_open_owner(const char *filename, int format, int private)
2341 int fd = -1, bflags, mode, textmode;
2343 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2344 return bio_open_default(filename, 'w', format);
2353 textmode = FMT_istext(format);
2357 #elif defined(_O_BINARY)
2362 #ifdef OPENSSL_SYS_VMS
2363 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2364 * it still needs to know that we're going binary, or fdopen()
2365 * will fail with "invalid argument"... so we tell VMS what the
2369 fd = open(filename, mode, 0600, "ctx=bin");
2372 fd = open(filename, mode, 0600);
2375 fp = fdopen(fd, modestr('w', format));
2380 bflags |= BIO_FP_TEXT;
2381 b = BIO_new_fp(fp, bflags);
2386 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2387 opt_getprog(), filename, strerror(errno));
2388 ERR_print_errors(bio_err);
2389 /* If we have fp, then fdopen took over fd, so don't close both. */
2397 static BIO *bio_open_default_(const char *filename, char mode, int format,
2402 if (filename == NULL || strcmp(filename, "-") == 0) {
2403 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2411 "Can't open %s, %s\n",
2412 mode == 'r' ? "stdin" : "stdout", strerror(errno));
2414 ret = BIO_new_file(filename, modestr(mode, format));
2422 "Can't open %s for %s, %s\n",
2423 filename, modeverb(mode), strerror(errno));
2425 ERR_print_errors(bio_err);
2429 BIO *bio_open_default(const char *filename, char mode, int format)
2431 return bio_open_default_(filename, mode, format, 0);
2434 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2436 return bio_open_default_(filename, mode, format, 1);
2439 void wait_for_async(SSL *s)
2441 /* On Windows select only works for sockets, so we simply don't wait */
2442 #ifndef OPENSSL_SYS_WINDOWS
2449 if (!SSL_get_all_async_fds(s, NULL, &numfds))
2453 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2454 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2460 for (i = 0; i < numfds; i++) {
2461 if (width <= (int)fds[i])
2462 width = (int)fds[i] + 1;
2463 openssl_fdset((int)fds[i], &asyncfds);
2465 select(width, (void *)&asyncfds, NULL, NULL, NULL);
2470 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2471 #if defined(OPENSSL_SYS_MSDOS)
2472 int has_stdin_waiting(void)
2474 # if defined(OPENSSL_SYS_WINDOWS)
2475 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2477 INPUT_RECORD inputrec;
2481 if (inhand == INVALID_HANDLE_VALUE) {
2485 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2487 /* Probably redirected input? _kbhit() does not work in this case */
2498 /* Corrupt a signature by modifying final byte */
2499 void corrupt_signature(const ASN1_STRING *signature)
2501 unsigned char *s = signature->data;
2502 s[signature->length - 1] ^= 0x1;
2505 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2508 if (startdate == NULL || strcmp(startdate, "today") == 0) {
2509 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2512 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2515 if (enddate == NULL) {
2516 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2519 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2525 void make_uppercase(char *string)
2529 for (i = 0; string[i] != '\0'; i++)
2530 string[i] = toupper((unsigned char)string[i]);
2533 int opt_printf_stderr(const char *fmt, ...)
2539 ret = BIO_vprintf(bio_err, fmt, ap);