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, const char *CAfile,
129 const char *CApath, int noCAfile, int noCApath)
131 if (CAfile == NULL && CApath == NULL) {
132 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
134 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
139 return SSL_CTX_load_verify_locations(ctx, CAfile, CApath);
142 #ifndef OPENSSL_NO_CT
144 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
147 return SSL_CTX_set_default_ctlog_list_file(ctx);
149 return SSL_CTX_set_ctlog_list_file(ctx, path);
154 static unsigned long nmflag = 0;
155 static char nmflag_set = 0;
157 int set_nameopt(const char *arg)
159 int ret = set_name_ex(&nmflag, arg);
167 unsigned long get_nameopt(void)
169 return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
172 int dump_cert_text(BIO *out, X509 *x)
174 print_name(out, "subject=", X509_get_subject_name(x), get_nameopt());
176 print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
182 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
184 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
188 static char *app_get_pass(const char *arg, int keepbio);
190 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
192 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
195 *pass1 = app_get_pass(arg1, same);
198 } else if (pass1 != NULL) {
202 *pass2 = app_get_pass(arg2, same ? 2 : 0);
205 } else if (pass2 != NULL) {
211 static char *app_get_pass(const char *arg, int keepbio)
213 static BIO *pwdbio = NULL;
214 char *tmp, tpass[APP_PASS_LEN];
217 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
218 if (strncmp(arg, "pass:", 5) == 0)
219 return OPENSSL_strdup(arg + 5);
220 if (strncmp(arg, "env:", 4) == 0) {
221 tmp = getenv(arg + 4);
223 BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
226 return OPENSSL_strdup(tmp);
228 if (!keepbio || pwdbio == NULL) {
229 if (strncmp(arg, "file:", 5) == 0) {
230 pwdbio = BIO_new_file(arg + 5, "r");
231 if (pwdbio == NULL) {
232 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
237 * Under _WIN32, which covers even Win64 and CE, file
238 * descriptors referenced by BIO_s_fd are not inherited
239 * by child process and therefore below is not an option.
240 * It could have been an option if bss_fd.c was operating
241 * on real Windows descriptors, such as those obtained
244 } else if (strncmp(arg, "fd:", 3) == 0) {
248 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
249 if ((i < 0) || !pwdbio) {
250 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
254 * Can't do BIO_gets on an fd BIO so add a buffering BIO
256 btmp = BIO_new(BIO_f_buffer());
257 pwdbio = BIO_push(btmp, pwdbio);
259 } else if (strcmp(arg, "stdin") == 0) {
260 pwdbio = dup_bio_in(FORMAT_TEXT);
262 BIO_printf(bio_err, "Can't open BIO for stdin\n");
266 /* argument syntax error; do not reveal too much about arg */
267 tmp = strchr(arg, ':');
268 if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
270 "Invalid password argument, missing ':' within the first %d chars\n",
271 PASS_SOURCE_SIZE_MAX + 1);
274 "Invalid password argument, starting with \"%.*s\"\n",
275 (int)(tmp - arg + 1), arg);
279 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
281 BIO_free_all(pwdbio);
285 BIO_printf(bio_err, "Error reading password from BIO\n");
288 tmp = strchr(tpass, '\n');
291 return OPENSSL_strdup(tpass);
294 CONF *app_load_config_bio(BIO *in, const char *filename)
300 conf = NCONF_new(NULL);
301 i = NCONF_load_bio(conf, in, &errorline);
305 if (errorline <= 0) {
306 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
308 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
311 if (filename != NULL)
312 BIO_printf(bio_err, "config file \"%s\"\n", filename);
314 BIO_printf(bio_err, "config input");
320 CONF *app_load_config(const char *filename)
325 in = bio_open_default(filename, 'r', FORMAT_TEXT);
329 conf = app_load_config_bio(in, filename);
334 CONF *app_load_config_quiet(const char *filename)
339 in = bio_open_default_quiet(filename, 'r', FORMAT_TEXT);
343 conf = app_load_config_bio(in, filename);
348 int app_load_modules(const CONF *config)
350 CONF *to_free = NULL;
353 config = to_free = app_load_config_quiet(default_config_file);
357 if (CONF_modules_load(config, NULL, 0) <= 0) {
358 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
359 ERR_print_errors(bio_err);
367 int add_oid_section(CONF *conf)
370 STACK_OF(CONF_VALUE) *sktmp;
374 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
378 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
379 BIO_printf(bio_err, "problem loading oid section %s\n", p);
382 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
383 cnf = sk_CONF_VALUE_value(sktmp, i);
384 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
385 BIO_printf(bio_err, "problem creating object %s=%s\n",
386 cnf->name, cnf->value);
393 static int load_pkcs12(BIO *in, const char *desc,
394 pem_password_cb *pem_cb, PW_CB_DATA *cb_data,
395 EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
398 char tpass[PEM_BUFSIZE];
401 p12 = d2i_PKCS12_bio(in, NULL);
403 BIO_printf(bio_err, "Error loading PKCS12 file for %s\n", desc);
406 /* See if an empty password will do */
407 if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0)) {
411 pem_cb = (pem_password_cb *)password_callback;
412 len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
414 BIO_printf(bio_err, "Passphrase callback error for %s\n", desc);
417 if (len < PEM_BUFSIZE)
419 if (!PKCS12_verify_mac(p12, tpass, len)) {
421 "Mac verify error (wrong password?) in PKCS12 file for %s\n",
427 ret = PKCS12_parse(p12, pass, pkey, cert, ca);
433 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
434 static int load_cert_crl_http(const char *url, X509 **pcert, X509_CRL **pcrl)
436 char *host = NULL, *port = NULL, *path = NULL;
438 OCSP_REQ_CTX *rctx = NULL;
440 if (!OCSP_parse_url(url, &host, &port, &path, &use_ssl))
443 BIO_puts(bio_err, "https not supported\n");
446 bio = BIO_new_connect(host);
447 if (!bio || !BIO_set_conn_port(bio, port))
449 rctx = OCSP_REQ_CTX_new(bio, 1024);
452 if (!OCSP_REQ_CTX_http(rctx, "GET", path))
454 if (!OCSP_REQ_CTX_add1_header(rctx, "Host", host))
458 rv = X509_http_nbio(rctx, pcert);
462 rv = X509_CRL_http_nbio(rctx, pcrl);
471 OCSP_REQ_CTX_free(rctx);
473 BIO_printf(bio_err, "Error loading %s from %s\n",
474 pcert ? "certificate" : "CRL", url);
475 ERR_print_errors(bio_err);
481 X509 *load_cert(const char *file, int format, const char *cert_descrip)
486 if (format == FORMAT_HTTP) {
487 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
488 load_cert_crl_http(file, &x, NULL);
495 cert = dup_bio_in(format);
497 cert = bio_open_default(file, 'r', format);
502 if (format == FORMAT_ASN1) {
503 x = d2i_X509_bio(cert, NULL);
504 } else if (format == FORMAT_PEM) {
505 x = PEM_read_bio_X509_AUX(cert, NULL,
506 (pem_password_cb *)password_callback, NULL);
507 } else if (format == FORMAT_PKCS12) {
508 if (!load_pkcs12(cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
511 BIO_printf(bio_err, "bad input format specified for %s\n", cert_descrip);
516 BIO_printf(bio_err, "unable to load certificate\n");
517 ERR_print_errors(bio_err);
523 X509_CRL *load_crl(const char *infile, int format)
528 if (format == FORMAT_HTTP) {
529 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
530 load_cert_crl_http(infile, NULL, &x);
535 in = bio_open_default(infile, 'r', format);
538 if (format == FORMAT_ASN1) {
539 x = d2i_X509_CRL_bio(in, NULL);
540 } else if (format == FORMAT_PEM) {
541 x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
543 BIO_printf(bio_err, "bad input format specified for input crl\n");
547 BIO_printf(bio_err, "unable to load CRL\n");
548 ERR_print_errors(bio_err);
557 EVP_PKEY *load_key(const char *file, int format, int maybe_stdin,
558 const char *pass, ENGINE *e, const char *key_descrip)
561 EVP_PKEY *pkey = NULL;
564 cb_data.password = pass;
565 cb_data.prompt_info = file;
567 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
568 BIO_printf(bio_err, "no keyfile specified\n");
571 if (format == FORMAT_ENGINE) {
573 BIO_printf(bio_err, "no engine specified\n");
575 #ifndef OPENSSL_NO_ENGINE
576 if (ENGINE_init(e)) {
577 pkey = ENGINE_load_private_key(e, file,
578 (UI_METHOD *)get_ui_method(),
583 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
584 ERR_print_errors(bio_err);
587 BIO_printf(bio_err, "engines not supported\n");
592 if (file == NULL && maybe_stdin) {
594 key = dup_bio_in(format);
596 key = bio_open_default(file, 'r', format);
600 if (format == FORMAT_ASN1) {
601 pkey = d2i_PrivateKey_bio(key, NULL);
602 } else if (format == FORMAT_PEM) {
603 pkey = PEM_read_bio_PrivateKey(key, NULL, wrap_password_callback, &cb_data);
604 } else if (format == FORMAT_PKCS12) {
605 if (!load_pkcs12(key, key_descrip, wrap_password_callback, &cb_data,
608 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
609 } else if (format == FORMAT_MSBLOB) {
610 pkey = b2i_PrivateKey_bio(key);
611 } else if (format == FORMAT_PVK) {
612 pkey = b2i_PVK_bio(key, wrap_password_callback, &cb_data);
615 BIO_printf(bio_err, "bad input format specified for key file\n");
621 BIO_printf(bio_err, "unable to load %s\n", key_descrip);
622 ERR_print_errors(bio_err);
627 EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin,
628 const char *pass, ENGINE *e, const char *key_descrip)
631 EVP_PKEY *pkey = NULL;
634 cb_data.password = pass;
635 cb_data.prompt_info = file;
637 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
638 BIO_printf(bio_err, "no keyfile specified\n");
641 if (format == FORMAT_ENGINE) {
643 BIO_printf(bio_err, "no engine specified\n");
645 #ifndef OPENSSL_NO_ENGINE
646 pkey = ENGINE_load_public_key(e, file, (UI_METHOD *)get_ui_method(),
649 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
650 ERR_print_errors(bio_err);
653 BIO_printf(bio_err, "engines not supported\n");
658 if (file == NULL && maybe_stdin) {
660 key = dup_bio_in(format);
662 key = bio_open_default(file, 'r', format);
666 if (format == FORMAT_ASN1) {
667 pkey = d2i_PUBKEY_bio(key, NULL);
668 } else if (format == FORMAT_ASN1RSA) {
669 #ifndef OPENSSL_NO_RSA
671 rsa = d2i_RSAPublicKey_bio(key, NULL);
673 pkey = EVP_PKEY_new();
675 EVP_PKEY_set1_RSA(pkey, rsa);
679 BIO_printf(bio_err, "RSA keys not supported\n");
682 } else if (format == FORMAT_PEMRSA) {
683 #ifndef OPENSSL_NO_RSA
685 rsa = PEM_read_bio_RSAPublicKey(key, NULL,
686 (pem_password_cb *)password_callback,
689 pkey = EVP_PKEY_new();
691 EVP_PKEY_set1_RSA(pkey, rsa);
695 BIO_printf(bio_err, "RSA keys not supported\n");
698 } else if (format == FORMAT_PEM) {
699 pkey = PEM_read_bio_PUBKEY(key, NULL,
700 (pem_password_cb *)password_callback,
702 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
703 } else if (format == FORMAT_MSBLOB) {
704 pkey = b2i_PublicKey_bio(key);
710 BIO_printf(bio_err, "unable to load %s\n", key_descrip);
714 static int load_certs_crls(const char *file, int format,
715 const char *pass, const char *desc,
716 STACK_OF(X509) **pcerts,
717 STACK_OF(X509_CRL) **pcrls)
721 STACK_OF(X509_INFO) *xis = NULL;
726 cb_data.password = pass;
727 cb_data.prompt_info = file;
729 if (format != FORMAT_PEM) {
730 BIO_printf(bio_err, "bad input format specified for %s\n", desc);
734 bio = bio_open_default(file, 'r', FORMAT_PEM);
738 xis = PEM_X509_INFO_read_bio(bio, NULL,
739 (pem_password_cb *)password_callback,
744 if (pcerts != NULL && *pcerts == NULL) {
745 *pcerts = sk_X509_new_null();
750 if (pcrls != NULL && *pcrls == NULL) {
751 *pcrls = sk_X509_CRL_new_null();
756 for (i = 0; i < sk_X509_INFO_num(xis); i++) {
757 xi = sk_X509_INFO_value(xis, i);
758 if (xi->x509 != NULL && pcerts != NULL) {
759 if (!sk_X509_push(*pcerts, xi->x509))
763 if (xi->crl != NULL && pcrls != NULL) {
764 if (!sk_X509_CRL_push(*pcrls, xi->crl))
770 if (pcerts != NULL && sk_X509_num(*pcerts) > 0)
773 if (pcrls != NULL && sk_X509_CRL_num(*pcrls) > 0)
778 sk_X509_INFO_pop_free(xis, X509_INFO_free);
781 if (pcerts != NULL) {
782 sk_X509_pop_free(*pcerts, X509_free);
786 sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
789 BIO_printf(bio_err, "unable to load %s\n",
790 pcerts ? "certificates" : "CRLs");
791 ERR_print_errors(bio_err);
796 void* app_malloc(int sz, const char *what)
798 void *vp = OPENSSL_malloc(sz);
801 BIO_printf(bio_err, "%s: Could not allocate %d bytes for %s\n",
802 opt_getprog(), sz, what);
803 ERR_print_errors(bio_err);
810 * Initialize or extend, if *certs != NULL, a certificate stack.
812 int load_certs(const char *file, STACK_OF(X509) **certs, int format,
813 const char *pass, const char *desc)
815 return load_certs_crls(file, format, pass, desc, certs, NULL);
819 * Initialize or extend, if *crls != NULL, a certificate stack.
821 int load_crls(const char *file, STACK_OF(X509_CRL) **crls, int format,
822 const char *pass, const char *desc)
824 return load_certs_crls(file, format, pass, desc, NULL, crls);
827 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
828 /* Return error for unknown extensions */
829 #define X509V3_EXT_DEFAULT 0
830 /* Print error for unknown extensions */
831 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
832 /* ASN1 parse unknown extensions */
833 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
834 /* BIO_dump unknown extensions */
835 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
837 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
838 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
840 int set_cert_ex(unsigned long *flags, const char *arg)
842 static const NAME_EX_TBL cert_tbl[] = {
843 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
844 {"ca_default", X509_FLAG_CA, 0xffffffffl},
845 {"no_header", X509_FLAG_NO_HEADER, 0},
846 {"no_version", X509_FLAG_NO_VERSION, 0},
847 {"no_serial", X509_FLAG_NO_SERIAL, 0},
848 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
849 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
850 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
851 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
852 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
853 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
854 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
855 {"no_aux", X509_FLAG_NO_AUX, 0},
856 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
857 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
858 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
859 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
860 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
863 return set_multi_opts(flags, arg, cert_tbl);
866 int set_name_ex(unsigned long *flags, const char *arg)
868 static const NAME_EX_TBL ex_tbl[] = {
869 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
870 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
871 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
872 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
873 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
874 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
875 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
876 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
877 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
878 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
879 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
880 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
881 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
882 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
883 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
884 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
885 {"dn_rev", XN_FLAG_DN_REV, 0},
886 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
887 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
888 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
889 {"align", XN_FLAG_FN_ALIGN, 0},
890 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
891 {"space_eq", XN_FLAG_SPC_EQ, 0},
892 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
893 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
894 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
895 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
896 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
899 if (set_multi_opts(flags, arg, ex_tbl) == 0)
901 if (*flags != XN_FLAG_COMPAT
902 && (*flags & XN_FLAG_SEP_MASK) == 0)
903 *flags |= XN_FLAG_SEP_CPLUS_SPC;
907 int set_ext_copy(int *copy_type, const char *arg)
909 if (strcasecmp(arg, "none") == 0)
910 *copy_type = EXT_COPY_NONE;
911 else if (strcasecmp(arg, "copy") == 0)
912 *copy_type = EXT_COPY_ADD;
913 else if (strcasecmp(arg, "copyall") == 0)
914 *copy_type = EXT_COPY_ALL;
920 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
922 STACK_OF(X509_EXTENSION) *exts = NULL;
923 X509_EXTENSION *ext, *tmpext;
926 if (!x || !req || (copy_type == EXT_COPY_NONE))
928 exts = X509_REQ_get_extensions(req);
930 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
931 ext = sk_X509_EXTENSION_value(exts, i);
932 obj = X509_EXTENSION_get_object(ext);
933 idx = X509_get_ext_by_OBJ(x, obj, -1);
934 /* Does extension exist? */
936 /* If normal copy don't override existing extension */
937 if (copy_type == EXT_COPY_ADD)
939 /* Delete all extensions of same type */
941 tmpext = X509_get_ext(x, idx);
942 X509_delete_ext(x, idx);
943 X509_EXTENSION_free(tmpext);
944 idx = X509_get_ext_by_OBJ(x, obj, -1);
947 if (!X509_add_ext(x, ext, -1))
955 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
960 static int set_multi_opts(unsigned long *flags, const char *arg,
961 const NAME_EX_TBL * in_tbl)
963 STACK_OF(CONF_VALUE) *vals;
968 vals = X509V3_parse_list(arg);
969 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
970 val = sk_CONF_VALUE_value(vals, i);
971 if (!set_table_opts(flags, val->name, in_tbl))
974 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
978 static int set_table_opts(unsigned long *flags, const char *arg,
979 const NAME_EX_TBL * in_tbl)
982 const NAME_EX_TBL *ptbl;
988 } else if (c == '+') {
995 for (ptbl = in_tbl; ptbl->name; ptbl++) {
996 if (strcasecmp(arg, ptbl->name) == 0) {
997 *flags &= ~ptbl->mask;
999 *flags |= ptbl->flag;
1001 *flags &= ~ptbl->flag;
1008 void print_name(BIO *out, const char *title, X509_NAME *nm,
1009 unsigned long lflags)
1016 BIO_puts(out, title);
1017 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1021 if (lflags == XN_FLAG_COMPAT) {
1022 buf = X509_NAME_oneline(nm, 0, 0);
1024 BIO_puts(out, "\n");
1028 BIO_puts(out, "\n");
1029 X509_NAME_print_ex(out, nm, indent, lflags);
1030 BIO_puts(out, "\n");
1034 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1035 int len, unsigned char *buffer)
1037 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1038 if (BN_is_zero(in)) {
1039 BIO_printf(out, "\n 0x00");
1043 l = BN_bn2bin(in, buffer);
1044 for (i = 0; i < l; i++) {
1045 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1047 BIO_printf(out, "0x%02X,", buffer[i]);
1049 BIO_printf(out, "0x%02X", buffer[i]);
1052 BIO_printf(out, "\n };\n");
1055 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1059 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1060 for (i = 0; i < len; i++) {
1062 BIO_printf(out, "\n ");
1064 BIO_printf(out, "0x%02X, ", d[i]);
1066 BIO_printf(out, "0x%02X", d[i]);
1068 BIO_printf(out, "\n};\n");
1071 X509_STORE *setup_verify(const char *CAfile, const char *CApath, int noCAfile, int noCApath)
1073 X509_STORE *store = X509_STORE_new();
1074 X509_LOOKUP *lookup;
1079 if (CAfile != NULL || !noCAfile) {
1080 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1084 if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1085 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1089 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1093 if (CApath != NULL || !noCApath) {
1094 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1098 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1099 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1103 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1110 X509_STORE_free(store);
1114 #ifndef OPENSSL_NO_ENGINE
1115 /* Try to load an engine in a shareable library */
1116 static ENGINE *try_load_engine(const char *engine)
1118 ENGINE *e = ENGINE_by_id("dynamic");
1120 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1121 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1130 ENGINE *setup_engine(const char *engine, int debug)
1134 #ifndef OPENSSL_NO_ENGINE
1135 if (engine != NULL) {
1136 if (strcmp(engine, "auto") == 0) {
1137 BIO_printf(bio_err, "enabling auto ENGINE support\n");
1138 ENGINE_register_all_complete();
1141 if ((e = ENGINE_by_id(engine)) == NULL
1142 && (e = try_load_engine(engine)) == NULL) {
1143 BIO_printf(bio_err, "invalid engine \"%s\"\n", engine);
1144 ERR_print_errors(bio_err);
1148 ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1150 ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, (void *)get_ui_method(),
1152 if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1153 BIO_printf(bio_err, "can't use that engine\n");
1154 ERR_print_errors(bio_err);
1159 BIO_printf(bio_err, "engine \"%s\" set.\n", ENGINE_get_id(e));
1165 void release_engine(ENGINE *e)
1167 #ifndef OPENSSL_NO_ENGINE
1169 /* Free our "structural" reference. */
1174 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1181 return OPENSSL_LH_strhash(n);
1184 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1185 const OPENSSL_CSTRING *b)
1187 const char *aa, *bb;
1189 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1190 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1191 return strcmp(aa, bb);
1194 static int index_name_qual(char **a)
1196 return (a[0][0] == 'V');
1199 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1201 return OPENSSL_LH_strhash(a[DB_name]);
1204 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1206 return strcmp(a[DB_name], b[DB_name]);
1209 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1210 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1211 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1212 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1215 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1220 ASN1_INTEGER *ai = NULL;
1222 ai = ASN1_INTEGER_new();
1226 in = BIO_new_file(serialfile, "r");
1234 if (ret == NULL || !rand_serial(ret, ai))
1235 BIO_printf(bio_err, "Out of memory\n");
1237 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1238 BIO_printf(bio_err, "unable to load number from %s\n",
1242 ret = ASN1_INTEGER_to_BN(ai, NULL);
1245 "error converting number from bin to BIGNUM\n");
1256 ASN1_INTEGER_free(ai);
1260 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1261 ASN1_INTEGER **retai)
1266 ASN1_INTEGER *ai = NULL;
1270 j = strlen(serialfile);
1272 j = strlen(serialfile) + strlen(suffix) + 1;
1274 BIO_printf(bio_err, "file name too long\n");
1279 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1281 #ifndef OPENSSL_SYS_VMS
1282 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1284 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1287 out = BIO_new_file(buf[0], "w");
1289 ERR_print_errors(bio_err);
1293 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1294 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1297 i2a_ASN1_INTEGER(out, ai);
1298 BIO_puts(out, "\n");
1306 ASN1_INTEGER_free(ai);
1310 int rotate_serial(const char *serialfile, const char *new_suffix,
1311 const char *old_suffix)
1316 i = strlen(serialfile) + strlen(old_suffix);
1317 j = strlen(serialfile) + strlen(new_suffix);
1320 if (j + 1 >= BSIZE) {
1321 BIO_printf(bio_err, "file name too long\n");
1324 #ifndef OPENSSL_SYS_VMS
1325 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1326 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1328 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1329 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1331 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1337 "unable to rename %s to %s\n", serialfile, buf[1]);
1341 if (rename(buf[0], serialfile) < 0) {
1343 "unable to rename %s to %s\n", buf[0], serialfile);
1345 rename(buf[1], serialfile);
1353 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1358 btmp = b == NULL ? BN_new() : b;
1362 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1364 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1377 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1379 CA_DB *retdb = NULL;
1380 TXT_DB *tmpdb = NULL;
1382 CONF *dbattr_conf = NULL;
1384 #ifndef OPENSSL_NO_POSIX_IO
1389 in = BIO_new_file(dbfile, "r");
1391 ERR_print_errors(bio_err);
1395 #ifndef OPENSSL_NO_POSIX_IO
1396 BIO_get_fp(in, &dbfp);
1397 if (fstat(fileno(dbfp), &dbst) == -1) {
1398 ERR_raise_data(ERR_LIB_SYS, errno,
1399 "calling fstat(%s)", dbfile);
1400 ERR_print_errors(bio_err);
1405 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1408 #ifndef OPENSSL_SYS_VMS
1409 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1411 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1413 dbattr_conf = app_load_config_quiet(buf);
1415 retdb = app_malloc(sizeof(*retdb), "new DB");
1419 retdb->attributes = *db_attr;
1421 retdb->attributes.unique_subject = 1;
1425 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1427 retdb->attributes.unique_subject = parse_yesno(p, 1);
1431 retdb->dbfname = OPENSSL_strdup(dbfile);
1432 #ifndef OPENSSL_NO_POSIX_IO
1437 NCONF_free(dbattr_conf);
1444 * Returns > 0 on success, <= 0 on error
1446 int index_index(CA_DB *db)
1448 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1449 LHASH_HASH_FN(index_serial),
1450 LHASH_COMP_FN(index_serial))) {
1452 "error creating serial number index:(%ld,%ld,%ld)\n",
1453 db->db->error, db->db->arg1, db->db->arg2);
1457 if (db->attributes.unique_subject
1458 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1459 LHASH_HASH_FN(index_name),
1460 LHASH_COMP_FN(index_name))) {
1461 BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
1462 db->db->error, db->db->arg1, db->db->arg2);
1468 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1474 j = strlen(dbfile) + strlen(suffix);
1475 if (j + 6 >= BSIZE) {
1476 BIO_printf(bio_err, "file name too long\n");
1479 #ifndef OPENSSL_SYS_VMS
1480 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1481 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1482 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1484 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1485 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1486 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1488 out = BIO_new_file(buf[0], "w");
1491 BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1494 j = TXT_DB_write(out, db->db);
1499 out = BIO_new_file(buf[1], "w");
1502 BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
1505 BIO_printf(out, "unique_subject = %s\n",
1506 db->attributes.unique_subject ? "yes" : "no");
1514 int rotate_index(const char *dbfile, const char *new_suffix,
1515 const char *old_suffix)
1520 i = strlen(dbfile) + strlen(old_suffix);
1521 j = strlen(dbfile) + strlen(new_suffix);
1524 if (j + 6 >= BSIZE) {
1525 BIO_printf(bio_err, "file name too long\n");
1528 #ifndef OPENSSL_SYS_VMS
1529 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1530 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1531 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1532 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1533 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1535 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1536 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1537 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1538 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1539 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1541 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1546 BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
1550 if (rename(buf[0], dbfile) < 0) {
1551 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
1553 rename(buf[1], dbfile);
1556 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1561 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
1563 rename(dbfile, buf[0]);
1564 rename(buf[1], dbfile);
1567 if (rename(buf[2], buf[4]) < 0) {
1568 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
1570 rename(buf[3], buf[4]);
1571 rename(dbfile, buf[0]);
1572 rename(buf[1], dbfile);
1580 void free_index(CA_DB *db)
1583 TXT_DB_free(db->db);
1584 OPENSSL_free(db->dbfname);
1589 int parse_yesno(const char *str, int def)
1593 case 'f': /* false */
1594 case 'F': /* FALSE */
1599 case 't': /* true */
1600 case 'T': /* TRUE */
1611 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1612 * where characters may be escaped by \
1614 X509_NAME *parse_name(const char *cp, long chtype, int canmulti)
1616 int nextismulti = 0;
1622 "name is expected to be in the format "
1623 "/type0=value0/type1=value1/type2=... where characters may "
1624 "be escaped by \\. This name is not in that format: '%s'\n",
1629 n = X509_NAME_new();
1632 work = OPENSSL_strdup(cp);
1634 BIO_printf(bio_err, "%s: Error copying name input\n", opt_getprog());
1641 unsigned char *valstr;
1643 int ismulti = nextismulti;
1646 /* Collect the type */
1647 while (*cp && *cp != '=')
1651 "%s: Hit end of string before finding the '='\n",
1658 /* Collect the value. */
1659 valstr = (unsigned char *)bp;
1660 for (; *cp && *cp != '/'; *bp++ = *cp++) {
1661 if (canmulti && *cp == '+') {
1665 if (*cp == '\\' && *++cp == '\0') {
1667 "%s: escape character at end of string\n",
1674 /* If not at EOS (must be + or /), move forward. */
1679 nid = OBJ_txt2nid(typestr);
1680 if (nid == NID_undef) {
1681 BIO_printf(bio_err, "%s: Skipping unknown attribute \"%s\"\n",
1682 opt_getprog(), typestr);
1685 if (*valstr == '\0') {
1687 "%s: No value provided for Subject Attribute %s, skipped\n",
1688 opt_getprog(), typestr);
1691 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1692 valstr, strlen((char *)valstr),
1693 -1, ismulti ? -1 : 0)) {
1694 BIO_printf(bio_err, "%s: Error adding name attribute \"/%s=%s\"\n",
1695 opt_getprog(), typestr ,valstr);
1710 * Read whole contents of a BIO into an allocated memory buffer and return
1714 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1718 unsigned char tbuf[1024];
1720 mem = BIO_new(BIO_s_mem());
1724 if ((maxlen != -1) && maxlen < 1024)
1728 len = BIO_read(in, tbuf, len);
1735 if (BIO_write(mem, tbuf, len) != len) {
1744 ret = BIO_get_mem_data(mem, (char **)out);
1745 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1750 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1753 char *stmp, *vtmp = NULL;
1754 stmp = OPENSSL_strdup(value);
1757 vtmp = strchr(stmp, ':');
1762 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1767 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1769 X509_POLICY_NODE *node;
1772 BIO_printf(bio_err, "%s Policies:", name);
1774 BIO_puts(bio_err, "\n");
1775 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1776 node = sk_X509_POLICY_NODE_value(nodes, i);
1777 X509_POLICY_NODE_print(bio_err, node, 2);
1780 BIO_puts(bio_err, " <empty>\n");
1784 void policies_print(X509_STORE_CTX *ctx)
1786 X509_POLICY_TREE *tree;
1787 int explicit_policy;
1788 tree = X509_STORE_CTX_get0_policy_tree(ctx);
1789 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1791 BIO_printf(bio_err, "Require explicit Policy: %s\n",
1792 explicit_policy ? "True" : "False");
1794 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1795 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1799 * next_protos_parse parses a comma separated list of strings into a string
1800 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1801 * outlen: (output) set to the length of the resulting buffer on success.
1802 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1803 * in: a NUL terminated string like "abc,def,ghi"
1805 * returns: a malloc'd buffer or NULL on failure.
1807 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1811 size_t i, start = 0;
1817 out = app_malloc(strlen(in) + 1, "NPN buffer");
1818 for (i = 0; i <= len; ++i) {
1819 if (i == len || in[i] == ',') {
1820 if (i - start > 255) {
1824 out[start] = (unsigned char)(i - start);
1835 void print_cert_checks(BIO *bio, X509 *x,
1836 const char *checkhost,
1837 const char *checkemail, const char *checkip)
1842 BIO_printf(bio, "Hostname %s does%s match certificate\n",
1844 X509_check_host(x, checkhost, 0, 0, NULL) == 1
1849 BIO_printf(bio, "Email %s does%s match certificate\n",
1850 checkemail, X509_check_email(x, checkemail, 0, 0)
1855 BIO_printf(bio, "IP %s does%s match certificate\n",
1856 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1860 /* Get first http URL from a DIST_POINT structure */
1862 static const char *get_dp_url(DIST_POINT *dp)
1864 GENERAL_NAMES *gens;
1868 if (!dp->distpoint || dp->distpoint->type != 0)
1870 gens = dp->distpoint->name.fullname;
1871 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1872 gen = sk_GENERAL_NAME_value(gens, i);
1873 uri = GENERAL_NAME_get0_value(gen, >ype);
1874 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
1875 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
1876 if (strncmp(uptr, "http://", 7) == 0)
1884 * Look through a CRLDP structure and attempt to find an http URL to
1885 * downloads a CRL from.
1888 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
1891 const char *urlptr = NULL;
1892 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
1893 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
1894 urlptr = get_dp_url(dp);
1896 return load_crl(urlptr, FORMAT_HTTP);
1902 * Example of downloading CRLs from CRLDP: not usable for real world as it
1903 * always downloads, doesn't support non-blocking I/O and doesn't cache
1907 static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
1910 STACK_OF(X509_CRL) *crls = NULL;
1912 STACK_OF(DIST_POINT) *crldp;
1914 crls = sk_X509_CRL_new_null();
1917 x = X509_STORE_CTX_get_current_cert(ctx);
1918 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
1919 crl = load_crl_crldp(crldp);
1920 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1922 sk_X509_CRL_free(crls);
1925 sk_X509_CRL_push(crls, crl);
1926 /* Try to download delta CRL */
1927 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
1928 crl = load_crl_crldp(crldp);
1929 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1931 sk_X509_CRL_push(crls, crl);
1935 void store_setup_crl_download(X509_STORE *st)
1937 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
1941 * Platform-specific sections
1946 # define fileno(a) (int)_fileno(a)
1949 # include <windows.h>
1952 static int WIN32_rename(const char *from, const char *to)
1954 TCHAR *tfrom = NULL, *tto;
1958 if (sizeof(TCHAR) == 1) {
1959 tfrom = (TCHAR *)from;
1961 } else { /* UNICODE path */
1963 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
1964 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
1968 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
1969 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
1971 for (i = 0; i < flen; i++)
1972 tfrom[i] = (TCHAR)from[i];
1973 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
1974 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
1976 for (i = 0; i < tlen; i++)
1977 tto[i] = (TCHAR)to[i];
1980 if (MoveFile(tfrom, tto))
1982 err = GetLastError();
1983 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
1984 if (DeleteFile(tto) && MoveFile(tfrom, tto))
1986 err = GetLastError();
1988 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
1990 else if (err == ERROR_ACCESS_DENIED)
1993 errno = EINVAL; /* we could map more codes... */
1997 if (tfrom != NULL && tfrom != (TCHAR *)from)
2003 /* app_tminterval section */
2005 double app_tminterval(int stop, int usertime)
2009 static ULARGE_INTEGER tmstart;
2010 static int warning = 1;
2011 # ifdef _WIN32_WINNT
2012 static HANDLE proc = NULL;
2016 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2017 GetCurrentProcessId());
2019 proc = (HANDLE) - 1;
2022 if (usertime && proc != (HANDLE) - 1) {
2024 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2030 if (usertime && warning) {
2031 BIO_printf(bio_err, "To get meaningful results, run "
2032 "this program on idle system.\n");
2035 GetSystemTime(&systime);
2036 SystemTimeToFileTime(&systime, &now);
2039 if (stop == TM_START) {
2040 tmstart.u.LowPart = now.dwLowDateTime;
2041 tmstart.u.HighPart = now.dwHighDateTime;
2043 ULARGE_INTEGER tmstop;
2045 tmstop.u.LowPart = now.dwLowDateTime;
2046 tmstop.u.HighPart = now.dwHighDateTime;
2048 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2053 #elif defined(OPENSSL_SYS_VXWORKS)
2056 double app_tminterval(int stop, int usertime)
2059 # ifdef CLOCK_REALTIME
2060 static struct timespec tmstart;
2061 struct timespec now;
2063 static unsigned long tmstart;
2066 static int warning = 1;
2068 if (usertime && warning) {
2069 BIO_printf(bio_err, "To get meaningful results, run "
2070 "this program on idle system.\n");
2073 # ifdef CLOCK_REALTIME
2074 clock_gettime(CLOCK_REALTIME, &now);
2075 if (stop == TM_START)
2078 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2079 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2082 if (stop == TM_START)
2085 ret = (now - tmstart) / (double)sysClkRateGet();
2090 #elif defined(OPENSSL_SYSTEM_VMS)
2094 double app_tminterval(int stop, int usertime)
2096 static clock_t tmstart;
2104 now = rus.tms_utime;
2107 now = clock(); /* sum of user and kernel times */
2110 gettimeofday(&tv, NULL);
2111 now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
2112 (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
2116 if (stop == TM_START)
2119 ret = (now - tmstart) / (double)(CLK_TCK);
2124 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2125 # include <sys/times.h>
2127 double app_tminterval(int stop, int usertime)
2131 clock_t now = times(&rus);
2132 static clock_t tmstart;
2135 now = rus.tms_utime;
2137 if (stop == TM_START) {
2140 long int tck = sysconf(_SC_CLK_TCK);
2141 ret = (now - tmstart) / (double)tck;
2148 # include <sys/time.h>
2149 # include <sys/resource.h>
2151 double app_tminterval(int stop, int usertime)
2156 static struct timeval tmstart;
2159 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2161 gettimeofday(&now, NULL);
2163 if (stop == TM_START)
2166 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2167 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2173 int app_access(const char* name, int flag)
2176 return _access(name, flag);
2178 return access(name, flag);
2182 int app_isdir(const char *name)
2184 return opt_isdir(name);
2187 /* raw_read|write section */
2189 # include "vms_term_sock.h"
2190 static int stdin_sock = -1;
2192 static void close_stdin_sock(void)
2194 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2197 int fileno_stdin(void)
2199 if (stdin_sock == -1) {
2200 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2201 atexit(close_stdin_sock);
2207 int fileno_stdin(void)
2209 return fileno(stdin);
2213 int fileno_stdout(void)
2215 return fileno(stdout);
2218 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2219 int raw_read_stdin(void *buf, int siz)
2222 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2227 #elif defined(__VMS)
2228 # include <sys/socket.h>
2230 int raw_read_stdin(void *buf, int siz)
2232 return recv(fileno_stdin(), buf, siz, 0);
2235 int raw_read_stdin(void *buf, int siz)
2237 return read(fileno_stdin(), buf, siz);
2241 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2242 int raw_write_stdout(const void *buf, int siz)
2245 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2251 int raw_write_stdout(const void *buf, int siz)
2253 return write(fileno_stdout(), buf, siz);
2258 * Centralized handling of input and output files with format specification
2259 * The format is meant to show what the input and output is supposed to be,
2260 * and is therefore a show of intent more than anything else. However, it
2261 * does impact behavior on some platforms, such as differentiating between
2262 * text and binary input/output on non-Unix platforms
2264 BIO *dup_bio_in(int format)
2266 return BIO_new_fp(stdin,
2267 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2270 BIO *dup_bio_out(int format)
2272 BIO *b = BIO_new_fp(stdout,
2273 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2274 void *prefix = NULL;
2276 #ifdef OPENSSL_SYS_VMS
2277 if (FMT_istext(format))
2278 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2281 if (FMT_istext(format)
2282 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2283 b = BIO_push(BIO_new(apps_bf_prefix()), b);
2284 BIO_ctrl(b, PREFIX_CTRL_SET_PREFIX, 0, prefix);
2290 BIO *dup_bio_err(int format)
2292 BIO *b = BIO_new_fp(stderr,
2293 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2294 #ifdef OPENSSL_SYS_VMS
2295 if (FMT_istext(format))
2296 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2302 * Because the prefix method is created dynamically, we must also be able
2305 void destroy_prefix_method(void)
2307 BIO_METHOD *prefix_method = apps_bf_prefix();
2308 BIO_meth_free(prefix_method);
2309 prefix_method = NULL;
2312 void unbuffer(FILE *fp)
2315 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2316 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2317 * However, we trust that the C RTL will never give us a FILE pointer
2318 * above the first 4 GB of memory, so we simply turn off the warning
2321 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2322 # pragma environment save
2323 # pragma message disable maylosedata2
2326 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2327 # pragma environment restore
2331 static const char *modestr(char mode, int format)
2333 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2337 return FMT_istext(format) ? "a" : "ab";
2339 return FMT_istext(format) ? "r" : "rb";
2341 return FMT_istext(format) ? "w" : "wb";
2343 /* The assert above should make sure we never reach this point */
2347 static const char *modeverb(char mode)
2357 return "(doing something)";
2361 * Open a file for writing, owner-read-only.
2363 BIO *bio_open_owner(const char *filename, int format, int private)
2367 int fd = -1, bflags, mode, textmode;
2369 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2370 return bio_open_default(filename, 'w', format);
2379 textmode = FMT_istext(format);
2383 #elif defined(_O_BINARY)
2388 #ifdef OPENSSL_SYS_VMS
2389 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2390 * it still needs to know that we're going binary, or fdopen()
2391 * will fail with "invalid argument"... so we tell VMS what the
2395 fd = open(filename, mode, 0600, "ctx=bin");
2398 fd = open(filename, mode, 0600);
2401 fp = fdopen(fd, modestr('w', format));
2406 bflags |= BIO_FP_TEXT;
2407 b = BIO_new_fp(fp, bflags);
2412 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2413 opt_getprog(), filename, strerror(errno));
2414 ERR_print_errors(bio_err);
2415 /* If we have fp, then fdopen took over fd, so don't close both. */
2423 static BIO *bio_open_default_(const char *filename, char mode, int format,
2428 if (filename == NULL || strcmp(filename, "-") == 0) {
2429 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2437 "Can't open %s, %s\n",
2438 mode == 'r' ? "stdin" : "stdout", strerror(errno));
2440 ret = BIO_new_file(filename, modestr(mode, format));
2448 "Can't open %s for %s, %s\n",
2449 filename, modeverb(mode), strerror(errno));
2451 ERR_print_errors(bio_err);
2455 BIO *bio_open_default(const char *filename, char mode, int format)
2457 return bio_open_default_(filename, mode, format, 0);
2460 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2462 return bio_open_default_(filename, mode, format, 1);
2465 void wait_for_async(SSL *s)
2467 /* On Windows select only works for sockets, so we simply don't wait */
2468 #ifndef OPENSSL_SYS_WINDOWS
2475 if (!SSL_get_all_async_fds(s, NULL, &numfds))
2479 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2480 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2486 for (i = 0; i < numfds; i++) {
2487 if (width <= (int)fds[i])
2488 width = (int)fds[i] + 1;
2489 openssl_fdset((int)fds[i], &asyncfds);
2491 select(width, (void *)&asyncfds, NULL, NULL, NULL);
2496 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2497 #if defined(OPENSSL_SYS_MSDOS)
2498 int has_stdin_waiting(void)
2500 # if defined(OPENSSL_SYS_WINDOWS)
2501 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2503 INPUT_RECORD inputrec;
2507 if (inhand == INVALID_HANDLE_VALUE) {
2511 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2513 /* Probably redirected input? _kbhit() does not work in this case */
2524 /* Corrupt a signature by modifying final byte */
2525 void corrupt_signature(const ASN1_STRING *signature)
2527 unsigned char *s = signature->data;
2528 s[signature->length - 1] ^= 0x1;
2531 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2534 if (startdate == NULL || strcmp(startdate, "today") == 0) {
2535 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2538 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2541 if (enddate == NULL) {
2542 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2545 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2551 void make_uppercase(char *string)
2555 for (i = 0; string[i] != '\0'; i++)
2556 string[i] = toupper((unsigned char)string[i]);
2559 int opt_printf_stderr(const char *fmt, ...)
2565 ret = BIO_vprintf(bio_err, fmt, ap);
2570 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
2571 const OSSL_PARAM *paramdefs)
2573 OSSL_PARAM *params = NULL;
2574 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
2576 char *opt = "", *stmp, *vtmp = NULL;
2581 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
2585 for (params_n = 0; params_n < sz; params_n++) {
2586 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
2587 if ((stmp = OPENSSL_strdup(opt)) == NULL
2588 || (vtmp = strchr(stmp, ':')) == NULL)
2590 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2592 /* Skip over the separator so that vmtp points to the value */
2594 if (!OSSL_PARAM_allocate_from_text(¶ms[params_n], paramdefs,
2595 stmp, vtmp, strlen(vtmp)))
2599 params[params_n] = OSSL_PARAM_construct_end();
2603 BIO_printf(bio_err, "Parameter error '%s'\n", opt);
2604 ERR_print_errors(bio_err);
2605 app_params_free(params);
2609 void app_params_free(OSSL_PARAM *params)
2613 if (params != NULL) {
2614 for (i = 0; params[i].key != NULL; ++i)
2615 OPENSSL_free(params[i].data);
2616 OPENSSL_free(params);