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))
51 #define PASS_SOURCE_SIZE_MAX 4
59 static int set_table_opts(unsigned long *flags
, const char *arg
,
60 const NAME_EX_TBL
* in_tbl
);
61 static int set_multi_opts(unsigned long *flags
, const char *arg
,
62 const NAME_EX_TBL
* in_tbl
);
64 int app_init(long mesgwin
);
66 int chopup_args(ARGS
*arg
, char *buf
)
69 char c
= '\0', *p
= NULL
;
74 arg
->argv
= app_malloc(sizeof(*arg
->argv
) * arg
->size
, "argv space");
78 /* Skip whitespace. */
79 while (*p
&& isspace(_UC(*p
)))
84 /* The start of something good :-) */
85 if (arg
->argc
>= arg
->size
) {
88 tmp
= OPENSSL_realloc(arg
->argv
, sizeof(*arg
->argv
) * arg
->size
);
93 quoted
= *p
== '\'' || *p
== '"';
96 arg
->argv
[arg
->argc
++] = p
;
98 /* now look for the end of this */
100 while (*p
&& *p
!= c
)
104 while (*p
&& !isspace(_UC(*p
)))
110 arg
->argv
[arg
->argc
] = NULL
;
115 int app_init(long mesgwin
)
121 int ctx_set_verify_locations(SSL_CTX
*ctx
, const char *CAfile
,
122 const char *CApath
, int noCAfile
, int noCApath
)
124 if (CAfile
== NULL
&& CApath
== NULL
) {
125 if (!noCAfile
&& SSL_CTX_set_default_verify_file(ctx
) <= 0)
127 if (!noCApath
&& SSL_CTX_set_default_verify_dir(ctx
) <= 0)
132 return SSL_CTX_load_verify_locations(ctx
, CAfile
, CApath
);
135 #ifndef OPENSSL_NO_CT
137 int ctx_set_ctlog_list_file(SSL_CTX
*ctx
, const char *path
)
140 return SSL_CTX_set_default_ctlog_list_file(ctx
);
142 return SSL_CTX_set_ctlog_list_file(ctx
, path
);
147 static unsigned long nmflag
= 0;
148 static char nmflag_set
= 0;
150 int set_nameopt(const char *arg
)
152 int ret
= set_name_ex(&nmflag
, arg
);
160 unsigned long get_nameopt(void)
162 return (nmflag_set
) ? nmflag
: XN_FLAG_ONELINE
;
165 int dump_cert_text(BIO
*out
, X509
*x
)
167 print_name(out
, "subject=", X509_get_subject_name(x
), get_nameopt());
169 print_name(out
, "issuer=", X509_get_issuer_name(x
), get_nameopt());
175 int wrap_password_callback(char *buf
, int bufsiz
, int verify
, void *userdata
)
177 return password_callback(buf
, bufsiz
, verify
, (PW_CB_DATA
*)userdata
);
181 static char *app_get_pass(const char *arg
, int keepbio
);
183 int app_passwd(const char *arg1
, const char *arg2
, char **pass1
, char **pass2
)
185 int same
= arg1
!= NULL
&& arg2
!= NULL
&& strcmp(arg1
, arg2
) == 0;
188 *pass1
= app_get_pass(arg1
, same
);
191 } else if (pass1
!= NULL
) {
195 *pass2
= app_get_pass(arg2
, same
? 2 : 0);
198 } else if (pass2
!= NULL
) {
204 static char *app_get_pass(const char *arg
, int keepbio
)
206 static BIO
*pwdbio
= NULL
;
207 char *tmp
, tpass
[APP_PASS_LEN
];
210 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
211 if (strncmp(arg
, "pass:", 5) == 0)
212 return OPENSSL_strdup(arg
+ 5);
213 if (strncmp(arg
, "env:", 4) == 0) {
214 tmp
= getenv(arg
+ 4);
216 BIO_printf(bio_err
, "No environment variable %s\n", arg
+ 4);
219 return OPENSSL_strdup(tmp
);
221 if (!keepbio
|| pwdbio
== NULL
) {
222 if (strncmp(arg
, "file:", 5) == 0) {
223 pwdbio
= BIO_new_file(arg
+ 5, "r");
224 if (pwdbio
== NULL
) {
225 BIO_printf(bio_err
, "Can't open file %s\n", arg
+ 5);
230 * Under _WIN32, which covers even Win64 and CE, file
231 * descriptors referenced by BIO_s_fd are not inherited
232 * by child process and therefore below is not an option.
233 * It could have been an option if bss_fd.c was operating
234 * on real Windows descriptors, such as those obtained
237 } else if (strncmp(arg
, "fd:", 3) == 0) {
241 pwdbio
= BIO_new_fd(i
, BIO_NOCLOSE
);
242 if ((i
< 0) || !pwdbio
) {
243 BIO_printf(bio_err
, "Can't access file descriptor %s\n", arg
+ 3);
247 * Can't do BIO_gets on an fd BIO so add a buffering BIO
249 btmp
= BIO_new(BIO_f_buffer());
250 pwdbio
= BIO_push(btmp
, pwdbio
);
252 } else if (strcmp(arg
, "stdin") == 0) {
253 pwdbio
= dup_bio_in(FORMAT_TEXT
);
255 BIO_printf(bio_err
, "Can't open BIO for stdin\n");
259 /* argument syntax error; do not reveal too much about arg */
260 tmp
= strchr(arg
, ':');
261 if (tmp
== NULL
|| tmp
- arg
> PASS_SOURCE_SIZE_MAX
)
263 "Invalid password argument, missing ':' within the first %d chars\n",
264 PASS_SOURCE_SIZE_MAX
+ 1);
267 "Invalid password argument, starting with \"%.*s\"\n",
268 (int)(tmp
- arg
+ 1), arg
);
272 i
= BIO_gets(pwdbio
, tpass
, APP_PASS_LEN
);
274 BIO_free_all(pwdbio
);
278 BIO_printf(bio_err
, "Error reading password from BIO\n");
281 tmp
= strchr(tpass
, '\n');
284 return OPENSSL_strdup(tpass
);
287 CONF
*app_load_config_bio(BIO
*in
, const char *filename
)
293 conf
= NCONF_new(NULL
);
294 i
= NCONF_load_bio(conf
, in
, &errorline
);
298 if (errorline
<= 0) {
299 BIO_printf(bio_err
, "%s: Can't load ", opt_getprog());
301 BIO_printf(bio_err
, "%s: Error on line %ld of ", opt_getprog(),
304 if (filename
!= NULL
)
305 BIO_printf(bio_err
, "config file \"%s\"\n", filename
);
307 BIO_printf(bio_err
, "config input");
313 CONF
*app_load_config(const char *filename
)
318 in
= bio_open_default(filename
, 'r', FORMAT_TEXT
);
322 conf
= app_load_config_bio(in
, filename
);
327 CONF
*app_load_config_quiet(const char *filename
)
332 in
= bio_open_default_quiet(filename
, 'r', FORMAT_TEXT
);
336 conf
= app_load_config_bio(in
, filename
);
341 int app_load_modules(const CONF
*config
)
343 CONF
*to_free
= NULL
;
346 config
= to_free
= app_load_config_quiet(default_config_file
);
350 if (CONF_modules_load(config
, NULL
, 0) <= 0) {
351 BIO_printf(bio_err
, "Error configuring OpenSSL modules\n");
352 ERR_print_errors(bio_err
);
360 int add_oid_section(CONF
*conf
)
363 STACK_OF(CONF_VALUE
) *sktmp
;
367 if ((p
= NCONF_get_string(conf
, NULL
, "oid_section")) == NULL
) {
371 if ((sktmp
= NCONF_get_section(conf
, p
)) == NULL
) {
372 BIO_printf(bio_err
, "problem loading oid section %s\n", p
);
375 for (i
= 0; i
< sk_CONF_VALUE_num(sktmp
); i
++) {
376 cnf
= sk_CONF_VALUE_value(sktmp
, i
);
377 if (OBJ_create(cnf
->value
, cnf
->name
, cnf
->name
) == NID_undef
) {
378 BIO_printf(bio_err
, "problem creating object %s=%s\n",
379 cnf
->name
, cnf
->value
);
386 static int load_pkcs12(BIO
*in
, const char *desc
,
387 pem_password_cb
*pem_cb
, PW_CB_DATA
*cb_data
,
388 EVP_PKEY
**pkey
, X509
**cert
, STACK_OF(X509
) **ca
)
391 char tpass
[PEM_BUFSIZE
];
394 p12
= d2i_PKCS12_bio(in
, NULL
);
396 BIO_printf(bio_err
, "Error loading PKCS12 file for %s\n", desc
);
399 /* See if an empty password will do */
400 if (PKCS12_verify_mac(p12
, "", 0) || PKCS12_verify_mac(p12
, NULL
, 0)) {
404 pem_cb
= (pem_password_cb
*)password_callback
;
405 len
= pem_cb(tpass
, PEM_BUFSIZE
, 0, cb_data
);
407 BIO_printf(bio_err
, "Passphrase callback error for %s\n", desc
);
410 if (len
< PEM_BUFSIZE
)
412 if (!PKCS12_verify_mac(p12
, tpass
, len
)) {
414 "Mac verify error (wrong password?) in PKCS12 file for %s\n",
420 ret
= PKCS12_parse(p12
, pass
, pkey
, cert
, ca
);
426 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
427 static int load_cert_crl_http(const char *url
, X509
**pcert
, X509_CRL
**pcrl
)
429 char *host
= NULL
, *port
= NULL
, *path
= NULL
;
431 OCSP_REQ_CTX
*rctx
= NULL
;
433 if (!OCSP_parse_url(url
, &host
, &port
, &path
, &use_ssl
))
436 BIO_puts(bio_err
, "https not supported\n");
439 bio
= BIO_new_connect(host
);
440 if (!bio
|| !BIO_set_conn_port(bio
, port
))
442 rctx
= OCSP_REQ_CTX_new(bio
, 1024);
445 if (!OCSP_REQ_CTX_http(rctx
, "GET", path
))
447 if (!OCSP_REQ_CTX_add1_header(rctx
, "Host", host
))
451 rv
= X509_http_nbio(rctx
, pcert
);
455 rv
= X509_CRL_http_nbio(rctx
, pcrl
);
464 OCSP_REQ_CTX_free(rctx
);
466 BIO_printf(bio_err
, "Error loading %s from %s\n",
467 pcert
? "certificate" : "CRL", url
);
468 ERR_print_errors(bio_err
);
474 X509
*load_cert(const char *file
, int format
, const char *cert_descrip
)
479 if (format
== FORMAT_HTTP
) {
480 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
481 load_cert_crl_http(file
, &x
, NULL
);
488 cert
= dup_bio_in(format
);
490 cert
= bio_open_default(file
, 'r', format
);
495 if (format
== FORMAT_ASN1
) {
496 x
= d2i_X509_bio(cert
, NULL
);
497 } else if (format
== FORMAT_PEM
) {
498 x
= PEM_read_bio_X509_AUX(cert
, NULL
,
499 (pem_password_cb
*)password_callback
, NULL
);
500 } else if (format
== FORMAT_PKCS12
) {
501 if (!load_pkcs12(cert
, cert_descrip
, NULL
, NULL
, NULL
, &x
, NULL
))
504 BIO_printf(bio_err
, "bad input format specified for %s\n", cert_descrip
);
509 BIO_printf(bio_err
, "unable to load certificate\n");
510 ERR_print_errors(bio_err
);
516 X509_CRL
*load_crl(const char *infile
, int format
)
521 if (format
== FORMAT_HTTP
) {
522 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
523 load_cert_crl_http(infile
, NULL
, &x
);
528 in
= bio_open_default(infile
, 'r', format
);
531 if (format
== FORMAT_ASN1
) {
532 x
= d2i_X509_CRL_bio(in
, NULL
);
533 } else if (format
== FORMAT_PEM
) {
534 x
= PEM_read_bio_X509_CRL(in
, NULL
, NULL
, NULL
);
536 BIO_printf(bio_err
, "bad input format specified for input crl\n");
540 BIO_printf(bio_err
, "unable to load CRL\n");
541 ERR_print_errors(bio_err
);
550 EVP_PKEY
*load_key(const char *file
, int format
, int maybe_stdin
,
551 const char *pass
, ENGINE
*e
, const char *key_descrip
)
554 EVP_PKEY
*pkey
= NULL
;
557 cb_data
.password
= pass
;
558 cb_data
.prompt_info
= file
;
560 if (file
== NULL
&& (!maybe_stdin
|| format
== FORMAT_ENGINE
)) {
561 BIO_printf(bio_err
, "no keyfile specified\n");
564 if (format
== FORMAT_ENGINE
) {
566 BIO_printf(bio_err
, "no engine specified\n");
568 #ifndef OPENSSL_NO_ENGINE
569 if (ENGINE_init(e
)) {
570 pkey
= ENGINE_load_private_key(e
, file
,
571 (UI_METHOD
*)get_ui_method(),
576 BIO_printf(bio_err
, "cannot load %s from engine\n", key_descrip
);
577 ERR_print_errors(bio_err
);
580 BIO_printf(bio_err
, "engines not supported\n");
585 if (file
== NULL
&& maybe_stdin
) {
587 key
= dup_bio_in(format
);
589 key
= bio_open_default(file
, 'r', format
);
593 if (format
== FORMAT_ASN1
) {
594 pkey
= d2i_PrivateKey_bio(key
, NULL
);
595 } else if (format
== FORMAT_PEM
) {
596 pkey
= PEM_read_bio_PrivateKey(key
, NULL
, wrap_password_callback
, &cb_data
);
597 } else if (format
== FORMAT_PKCS12
) {
598 if (!load_pkcs12(key
, key_descrip
, wrap_password_callback
, &cb_data
,
601 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
602 } else if (format
== FORMAT_MSBLOB
) {
603 pkey
= b2i_PrivateKey_bio(key
);
604 } else if (format
== FORMAT_PVK
) {
605 pkey
= b2i_PVK_bio(key
, wrap_password_callback
, &cb_data
);
608 BIO_printf(bio_err
, "bad input format specified for key file\n");
614 BIO_printf(bio_err
, "unable to load %s\n", key_descrip
);
615 ERR_print_errors(bio_err
);
620 EVP_PKEY
*load_pubkey(const char *file
, int format
, int maybe_stdin
,
621 const char *pass
, ENGINE
*e
, const char *key_descrip
)
624 EVP_PKEY
*pkey
= NULL
;
627 cb_data
.password
= pass
;
628 cb_data
.prompt_info
= file
;
630 if (file
== NULL
&& (!maybe_stdin
|| format
== FORMAT_ENGINE
)) {
631 BIO_printf(bio_err
, "no keyfile specified\n");
634 if (format
== FORMAT_ENGINE
) {
636 BIO_printf(bio_err
, "no engine specified\n");
638 #ifndef OPENSSL_NO_ENGINE
639 pkey
= ENGINE_load_public_key(e
, file
, (UI_METHOD
*)get_ui_method(),
642 BIO_printf(bio_err
, "cannot load %s from engine\n", key_descrip
);
643 ERR_print_errors(bio_err
);
646 BIO_printf(bio_err
, "engines not supported\n");
651 if (file
== NULL
&& maybe_stdin
) {
653 key
= dup_bio_in(format
);
655 key
= bio_open_default(file
, 'r', format
);
659 if (format
== FORMAT_ASN1
) {
660 pkey
= d2i_PUBKEY_bio(key
, NULL
);
661 } else if (format
== FORMAT_ASN1RSA
) {
662 #ifndef OPENSSL_NO_RSA
664 rsa
= d2i_RSAPublicKey_bio(key
, NULL
);
666 pkey
= EVP_PKEY_new();
668 EVP_PKEY_set1_RSA(pkey
, rsa
);
672 BIO_printf(bio_err
, "RSA keys not supported\n");
675 } else if (format
== FORMAT_PEMRSA
) {
676 #ifndef OPENSSL_NO_RSA
678 rsa
= PEM_read_bio_RSAPublicKey(key
, NULL
,
679 (pem_password_cb
*)password_callback
,
682 pkey
= EVP_PKEY_new();
684 EVP_PKEY_set1_RSA(pkey
, rsa
);
688 BIO_printf(bio_err
, "RSA keys not supported\n");
691 } else if (format
== FORMAT_PEM
) {
692 pkey
= PEM_read_bio_PUBKEY(key
, NULL
,
693 (pem_password_cb
*)password_callback
,
695 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
696 } else if (format
== FORMAT_MSBLOB
) {
697 pkey
= b2i_PublicKey_bio(key
);
703 BIO_printf(bio_err
, "unable to load %s\n", key_descrip
);
707 static int load_certs_crls(const char *file
, int format
,
708 const char *pass
, const char *desc
,
709 STACK_OF(X509
) **pcerts
,
710 STACK_OF(X509_CRL
) **pcrls
)
714 STACK_OF(X509_INFO
) *xis
= NULL
;
719 cb_data
.password
= pass
;
720 cb_data
.prompt_info
= file
;
722 if (format
!= FORMAT_PEM
) {
723 BIO_printf(bio_err
, "bad input format specified for %s\n", desc
);
727 bio
= bio_open_default(file
, 'r', FORMAT_PEM
);
731 xis
= PEM_X509_INFO_read_bio(bio
, NULL
,
732 (pem_password_cb
*)password_callback
,
737 if (pcerts
!= NULL
&& *pcerts
== NULL
) {
738 *pcerts
= sk_X509_new_null();
743 if (pcrls
!= NULL
&& *pcrls
== NULL
) {
744 *pcrls
= sk_X509_CRL_new_null();
749 for (i
= 0; i
< sk_X509_INFO_num(xis
); i
++) {
750 xi
= sk_X509_INFO_value(xis
, i
);
751 if (xi
->x509
!= NULL
&& pcerts
!= NULL
) {
752 if (!sk_X509_push(*pcerts
, xi
->x509
))
756 if (xi
->crl
!= NULL
&& pcrls
!= NULL
) {
757 if (!sk_X509_CRL_push(*pcrls
, xi
->crl
))
763 if (pcerts
!= NULL
&& sk_X509_num(*pcerts
) > 0)
766 if (pcrls
!= NULL
&& sk_X509_CRL_num(*pcrls
) > 0)
771 sk_X509_INFO_pop_free(xis
, X509_INFO_free
);
774 if (pcerts
!= NULL
) {
775 sk_X509_pop_free(*pcerts
, X509_free
);
779 sk_X509_CRL_pop_free(*pcrls
, X509_CRL_free
);
782 BIO_printf(bio_err
, "unable to load %s\n",
783 pcerts
? "certificates" : "CRLs");
784 ERR_print_errors(bio_err
);
789 void* app_malloc(int sz
, const char *what
)
791 void *vp
= OPENSSL_malloc(sz
);
794 BIO_printf(bio_err
, "%s: Could not allocate %d bytes for %s\n",
795 opt_getprog(), sz
, what
);
796 ERR_print_errors(bio_err
);
803 * Initialize or extend, if *certs != NULL, a certificate stack.
805 int load_certs(const char *file
, STACK_OF(X509
) **certs
, int format
,
806 const char *pass
, const char *desc
)
808 return load_certs_crls(file
, format
, pass
, desc
, certs
, NULL
);
812 * Initialize or extend, if *crls != NULL, a certificate stack.
814 int load_crls(const char *file
, STACK_OF(X509_CRL
) **crls
, int format
,
815 const char *pass
, const char *desc
)
817 return load_certs_crls(file
, format
, pass
, desc
, NULL
, crls
);
820 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
821 /* Return error for unknown extensions */
822 #define X509V3_EXT_DEFAULT 0
823 /* Print error for unknown extensions */
824 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
825 /* ASN1 parse unknown extensions */
826 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
827 /* BIO_dump unknown extensions */
828 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
830 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
831 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
833 int set_cert_ex(unsigned long *flags
, const char *arg
)
835 static const NAME_EX_TBL cert_tbl
[] = {
836 {"compatible", X509_FLAG_COMPAT
, 0xffffffffl
},
837 {"ca_default", X509_FLAG_CA
, 0xffffffffl
},
838 {"no_header", X509_FLAG_NO_HEADER
, 0},
839 {"no_version", X509_FLAG_NO_VERSION
, 0},
840 {"no_serial", X509_FLAG_NO_SERIAL
, 0},
841 {"no_signame", X509_FLAG_NO_SIGNAME
, 0},
842 {"no_validity", X509_FLAG_NO_VALIDITY
, 0},
843 {"no_subject", X509_FLAG_NO_SUBJECT
, 0},
844 {"no_issuer", X509_FLAG_NO_ISSUER
, 0},
845 {"no_pubkey", X509_FLAG_NO_PUBKEY
, 0},
846 {"no_extensions", X509_FLAG_NO_EXTENSIONS
, 0},
847 {"no_sigdump", X509_FLAG_NO_SIGDUMP
, 0},
848 {"no_aux", X509_FLAG_NO_AUX
, 0},
849 {"no_attributes", X509_FLAG_NO_ATTRIBUTES
, 0},
850 {"ext_default", X509V3_EXT_DEFAULT
, X509V3_EXT_UNKNOWN_MASK
},
851 {"ext_error", X509V3_EXT_ERROR_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
852 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
853 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
856 return set_multi_opts(flags
, arg
, cert_tbl
);
859 int set_name_ex(unsigned long *flags
, const char *arg
)
861 static const NAME_EX_TBL ex_tbl
[] = {
862 {"esc_2253", ASN1_STRFLGS_ESC_2253
, 0},
863 {"esc_2254", ASN1_STRFLGS_ESC_2254
, 0},
864 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL
, 0},
865 {"esc_msb", ASN1_STRFLGS_ESC_MSB
, 0},
866 {"use_quote", ASN1_STRFLGS_ESC_QUOTE
, 0},
867 {"utf8", ASN1_STRFLGS_UTF8_CONVERT
, 0},
868 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE
, 0},
869 {"show_type", ASN1_STRFLGS_SHOW_TYPE
, 0},
870 {"dump_all", ASN1_STRFLGS_DUMP_ALL
, 0},
871 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN
, 0},
872 {"dump_der", ASN1_STRFLGS_DUMP_DER
, 0},
873 {"compat", XN_FLAG_COMPAT
, 0xffffffffL
},
874 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS
, XN_FLAG_SEP_MASK
},
875 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC
, XN_FLAG_SEP_MASK
},
876 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC
, XN_FLAG_SEP_MASK
},
877 {"sep_multiline", XN_FLAG_SEP_MULTILINE
, XN_FLAG_SEP_MASK
},
878 {"dn_rev", XN_FLAG_DN_REV
, 0},
879 {"nofname", XN_FLAG_FN_NONE
, XN_FLAG_FN_MASK
},
880 {"sname", XN_FLAG_FN_SN
, XN_FLAG_FN_MASK
},
881 {"lname", XN_FLAG_FN_LN
, XN_FLAG_FN_MASK
},
882 {"align", XN_FLAG_FN_ALIGN
, 0},
883 {"oid", XN_FLAG_FN_OID
, XN_FLAG_FN_MASK
},
884 {"space_eq", XN_FLAG_SPC_EQ
, 0},
885 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS
, 0},
886 {"RFC2253", XN_FLAG_RFC2253
, 0xffffffffL
},
887 {"oneline", XN_FLAG_ONELINE
, 0xffffffffL
},
888 {"multiline", XN_FLAG_MULTILINE
, 0xffffffffL
},
889 {"ca_default", XN_FLAG_MULTILINE
, 0xffffffffL
},
892 if (set_multi_opts(flags
, arg
, ex_tbl
) == 0)
894 if (*flags
!= XN_FLAG_COMPAT
895 && (*flags
& XN_FLAG_SEP_MASK
) == 0)
896 *flags
|= XN_FLAG_SEP_CPLUS_SPC
;
900 int set_ext_copy(int *copy_type
, const char *arg
)
902 if (strcasecmp(arg
, "none") == 0)
903 *copy_type
= EXT_COPY_NONE
;
904 else if (strcasecmp(arg
, "copy") == 0)
905 *copy_type
= EXT_COPY_ADD
;
906 else if (strcasecmp(arg
, "copyall") == 0)
907 *copy_type
= EXT_COPY_ALL
;
913 int copy_extensions(X509
*x
, X509_REQ
*req
, int copy_type
)
915 STACK_OF(X509_EXTENSION
) *exts
= NULL
;
916 X509_EXTENSION
*ext
, *tmpext
;
919 if (!x
|| !req
|| (copy_type
== EXT_COPY_NONE
))
921 exts
= X509_REQ_get_extensions(req
);
923 for (i
= 0; i
< sk_X509_EXTENSION_num(exts
); i
++) {
924 ext
= sk_X509_EXTENSION_value(exts
, i
);
925 obj
= X509_EXTENSION_get_object(ext
);
926 idx
= X509_get_ext_by_OBJ(x
, obj
, -1);
927 /* Does extension exist? */
929 /* If normal copy don't override existing extension */
930 if (copy_type
== EXT_COPY_ADD
)
932 /* Delete all extensions of same type */
934 tmpext
= X509_get_ext(x
, idx
);
935 X509_delete_ext(x
, idx
);
936 X509_EXTENSION_free(tmpext
);
937 idx
= X509_get_ext_by_OBJ(x
, obj
, -1);
940 if (!X509_add_ext(x
, ext
, -1))
948 sk_X509_EXTENSION_pop_free(exts
, X509_EXTENSION_free
);
953 static int set_multi_opts(unsigned long *flags
, const char *arg
,
954 const NAME_EX_TBL
* in_tbl
)
956 STACK_OF(CONF_VALUE
) *vals
;
961 vals
= X509V3_parse_list(arg
);
962 for (i
= 0; i
< sk_CONF_VALUE_num(vals
); i
++) {
963 val
= sk_CONF_VALUE_value(vals
, i
);
964 if (!set_table_opts(flags
, val
->name
, in_tbl
))
967 sk_CONF_VALUE_pop_free(vals
, X509V3_conf_free
);
971 static int set_table_opts(unsigned long *flags
, const char *arg
,
972 const NAME_EX_TBL
* in_tbl
)
975 const NAME_EX_TBL
*ptbl
;
981 } else if (c
== '+') {
988 for (ptbl
= in_tbl
; ptbl
->name
; ptbl
++) {
989 if (strcasecmp(arg
, ptbl
->name
) == 0) {
990 *flags
&= ~ptbl
->mask
;
992 *flags
|= ptbl
->flag
;
994 *flags
&= ~ptbl
->flag
;
1001 void print_name(BIO
*out
, const char *title
, X509_NAME
*nm
,
1002 unsigned long lflags
)
1009 BIO_puts(out
, title
);
1010 if ((lflags
& XN_FLAG_SEP_MASK
) == XN_FLAG_SEP_MULTILINE
) {
1014 if (lflags
== XN_FLAG_COMPAT
) {
1015 buf
= X509_NAME_oneline(nm
, 0, 0);
1017 BIO_puts(out
, "\n");
1021 BIO_puts(out
, "\n");
1022 X509_NAME_print_ex(out
, nm
, indent
, lflags
);
1023 BIO_puts(out
, "\n");
1027 void print_bignum_var(BIO
*out
, const BIGNUM
*in
, const char *var
,
1028 int len
, unsigned char *buffer
)
1030 BIO_printf(out
, " static unsigned char %s_%d[] = {", var
, len
);
1031 if (BN_is_zero(in
)) {
1032 BIO_printf(out
, "\n 0x00");
1036 l
= BN_bn2bin(in
, buffer
);
1037 for (i
= 0; i
< l
; i
++) {
1038 BIO_printf(out
, (i
% 10) == 0 ? "\n " : " ");
1040 BIO_printf(out
, "0x%02X,", buffer
[i
]);
1042 BIO_printf(out
, "0x%02X", buffer
[i
]);
1045 BIO_printf(out
, "\n };\n");
1048 void print_array(BIO
*out
, const char* title
, int len
, const unsigned char* d
)
1052 BIO_printf(out
, "unsigned char %s[%d] = {", title
, len
);
1053 for (i
= 0; i
< len
; i
++) {
1055 BIO_printf(out
, "\n ");
1057 BIO_printf(out
, "0x%02X, ", d
[i
]);
1059 BIO_printf(out
, "0x%02X", d
[i
]);
1061 BIO_printf(out
, "\n};\n");
1064 X509_STORE
*setup_verify(const char *CAfile
, const char *CApath
, int noCAfile
, int noCApath
)
1066 X509_STORE
*store
= X509_STORE_new();
1067 X509_LOOKUP
*lookup
;
1072 if (CAfile
!= NULL
|| !noCAfile
) {
1073 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_file());
1077 if (!X509_LOOKUP_load_file(lookup
, CAfile
, X509_FILETYPE_PEM
)) {
1078 BIO_printf(bio_err
, "Error loading file %s\n", CAfile
);
1082 X509_LOOKUP_load_file(lookup
, NULL
, X509_FILETYPE_DEFAULT
);
1086 if (CApath
!= NULL
|| !noCApath
) {
1087 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_hash_dir());
1091 if (!X509_LOOKUP_add_dir(lookup
, CApath
, X509_FILETYPE_PEM
)) {
1092 BIO_printf(bio_err
, "Error loading directory %s\n", CApath
);
1096 X509_LOOKUP_add_dir(lookup
, NULL
, X509_FILETYPE_DEFAULT
);
1103 X509_STORE_free(store
);
1107 #ifndef OPENSSL_NO_ENGINE
1108 /* Try to load an engine in a shareable library */
1109 static ENGINE
*try_load_engine(const char *engine
)
1111 ENGINE
*e
= ENGINE_by_id("dynamic");
1113 if (!ENGINE_ctrl_cmd_string(e
, "SO_PATH", engine
, 0)
1114 || !ENGINE_ctrl_cmd_string(e
, "LOAD", NULL
, 0)) {
1123 ENGINE
*setup_engine(const char *engine
, int debug
)
1127 #ifndef OPENSSL_NO_ENGINE
1128 if (engine
!= NULL
) {
1129 if (strcmp(engine
, "auto") == 0) {
1130 BIO_printf(bio_err
, "enabling auto ENGINE support\n");
1131 ENGINE_register_all_complete();
1134 if ((e
= ENGINE_by_id(engine
)) == NULL
1135 && (e
= try_load_engine(engine
)) == NULL
) {
1136 BIO_printf(bio_err
, "invalid engine \"%s\"\n", engine
);
1137 ERR_print_errors(bio_err
);
1141 ENGINE_ctrl(e
, ENGINE_CTRL_SET_LOGSTREAM
, 0, bio_err
, 0);
1143 ENGINE_ctrl_cmd(e
, "SET_USER_INTERFACE", 0, (void *)get_ui_method(),
1145 if (!ENGINE_set_default(e
, ENGINE_METHOD_ALL
)) {
1146 BIO_printf(bio_err
, "can't use that engine\n");
1147 ERR_print_errors(bio_err
);
1152 BIO_printf(bio_err
, "engine \"%s\" set.\n", ENGINE_get_id(e
));
1158 void release_engine(ENGINE
*e
)
1160 #ifndef OPENSSL_NO_ENGINE
1162 /* Free our "structural" reference. */
1167 static unsigned long index_serial_hash(const OPENSSL_CSTRING
*a
)
1174 return OPENSSL_LH_strhash(n
);
1177 static int index_serial_cmp(const OPENSSL_CSTRING
*a
,
1178 const OPENSSL_CSTRING
*b
)
1180 const char *aa
, *bb
;
1182 for (aa
= a
[DB_serial
]; *aa
== '0'; aa
++) ;
1183 for (bb
= b
[DB_serial
]; *bb
== '0'; bb
++) ;
1184 return strcmp(aa
, bb
);
1187 static int index_name_qual(char **a
)
1189 return (a
[0][0] == 'V');
1192 static unsigned long index_name_hash(const OPENSSL_CSTRING
*a
)
1194 return OPENSSL_LH_strhash(a
[DB_name
]);
1197 int index_name_cmp(const OPENSSL_CSTRING
*a
, const OPENSSL_CSTRING
*b
)
1199 return strcmp(a
[DB_name
], b
[DB_name
]);
1202 static IMPLEMENT_LHASH_HASH_FN(index_serial
, OPENSSL_CSTRING
)
1203 static IMPLEMENT_LHASH_COMP_FN(index_serial
, OPENSSL_CSTRING
)
1204 static IMPLEMENT_LHASH_HASH_FN(index_name
, OPENSSL_CSTRING
)
1205 static IMPLEMENT_LHASH_COMP_FN(index_name
, OPENSSL_CSTRING
)
1208 BIGNUM
*load_serial(const char *serialfile
, int create
, ASN1_INTEGER
**retai
)
1213 ASN1_INTEGER
*ai
= NULL
;
1215 ai
= ASN1_INTEGER_new();
1219 in
= BIO_new_file(serialfile
, "r");
1227 if (ret
== NULL
|| !rand_serial(ret
, ai
))
1228 BIO_printf(bio_err
, "Out of memory\n");
1230 if (!a2i_ASN1_INTEGER(in
, ai
, buf
, 1024)) {
1231 BIO_printf(bio_err
, "unable to load number from %s\n",
1235 ret
= ASN1_INTEGER_to_BN(ai
, NULL
);
1238 "error converting number from bin to BIGNUM\n");
1249 ASN1_INTEGER_free(ai
);
1253 int save_serial(const char *serialfile
, const char *suffix
, const BIGNUM
*serial
,
1254 ASN1_INTEGER
**retai
)
1259 ASN1_INTEGER
*ai
= NULL
;
1263 j
= strlen(serialfile
);
1265 j
= strlen(serialfile
) + strlen(suffix
) + 1;
1267 BIO_printf(bio_err
, "file name too long\n");
1272 OPENSSL_strlcpy(buf
[0], serialfile
, BSIZE
);
1274 #ifndef OPENSSL_SYS_VMS
1275 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, suffix
);
1277 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, suffix
);
1280 out
= BIO_new_file(buf
[0], "w");
1282 ERR_print_errors(bio_err
);
1286 if ((ai
= BN_to_ASN1_INTEGER(serial
, NULL
)) == NULL
) {
1287 BIO_printf(bio_err
, "error converting serial to ASN.1 format\n");
1290 i2a_ASN1_INTEGER(out
, ai
);
1291 BIO_puts(out
, "\n");
1299 ASN1_INTEGER_free(ai
);
1303 int rotate_serial(const char *serialfile
, const char *new_suffix
,
1304 const char *old_suffix
)
1309 i
= strlen(serialfile
) + strlen(old_suffix
);
1310 j
= strlen(serialfile
) + strlen(new_suffix
);
1313 if (j
+ 1 >= BSIZE
) {
1314 BIO_printf(bio_err
, "file name too long\n");
1317 #ifndef OPENSSL_SYS_VMS
1318 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, new_suffix
);
1319 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", serialfile
, old_suffix
);
1321 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, new_suffix
);
1322 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", serialfile
, old_suffix
);
1324 if (rename(serialfile
, buf
[1]) < 0 && errno
!= ENOENT
1330 "unable to rename %s to %s\n", serialfile
, buf
[1]);
1334 if (rename(buf
[0], serialfile
) < 0) {
1336 "unable to rename %s to %s\n", buf
[0], serialfile
);
1338 rename(buf
[1], serialfile
);
1346 int rand_serial(BIGNUM
*b
, ASN1_INTEGER
*ai
)
1351 btmp
= b
== NULL
? BN_new() : b
;
1355 if (!BN_rand(btmp
, SERIAL_RAND_BITS
, BN_RAND_TOP_ANY
, BN_RAND_BOTTOM_ANY
))
1357 if (ai
&& !BN_to_ASN1_INTEGER(btmp
, ai
))
1370 CA_DB
*load_index(const char *dbfile
, DB_ATTR
*db_attr
)
1372 CA_DB
*retdb
= NULL
;
1373 TXT_DB
*tmpdb
= NULL
;
1375 CONF
*dbattr_conf
= NULL
;
1377 #ifndef OPENSSL_NO_POSIX_IO
1382 in
= BIO_new_file(dbfile
, "r");
1384 ERR_print_errors(bio_err
);
1388 #ifndef OPENSSL_NO_POSIX_IO
1389 BIO_get_fp(in
, &dbfp
);
1390 if (fstat(fileno(dbfp
), &dbst
) == -1) {
1391 SYSerr(SYS_F_FSTAT
, errno
);
1392 ERR_add_error_data(3, "fstat('", dbfile
, "')");
1393 ERR_print_errors(bio_err
);
1398 if ((tmpdb
= TXT_DB_read(in
, DB_NUMBER
)) == NULL
)
1401 #ifndef OPENSSL_SYS_VMS
1402 BIO_snprintf(buf
, sizeof(buf
), "%s.attr", dbfile
);
1404 BIO_snprintf(buf
, sizeof(buf
), "%s-attr", dbfile
);
1406 dbattr_conf
= app_load_config_quiet(buf
);
1408 retdb
= app_malloc(sizeof(*retdb
), "new DB");
1412 retdb
->attributes
= *db_attr
;
1414 retdb
->attributes
.unique_subject
= 1;
1418 char *p
= NCONF_get_string(dbattr_conf
, NULL
, "unique_subject");
1420 retdb
->attributes
.unique_subject
= parse_yesno(p
, 1);
1424 retdb
->dbfname
= OPENSSL_strdup(dbfile
);
1425 #ifndef OPENSSL_NO_POSIX_IO
1430 NCONF_free(dbattr_conf
);
1437 * Returns > 0 on success, <= 0 on error
1439 int index_index(CA_DB
*db
)
1441 if (!TXT_DB_create_index(db
->db
, DB_serial
, NULL
,
1442 LHASH_HASH_FN(index_serial
),
1443 LHASH_COMP_FN(index_serial
))) {
1445 "error creating serial number index:(%ld,%ld,%ld)\n",
1446 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1450 if (db
->attributes
.unique_subject
1451 && !TXT_DB_create_index(db
->db
, DB_name
, index_name_qual
,
1452 LHASH_HASH_FN(index_name
),
1453 LHASH_COMP_FN(index_name
))) {
1454 BIO_printf(bio_err
, "error creating name index:(%ld,%ld,%ld)\n",
1455 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1461 int save_index(const char *dbfile
, const char *suffix
, CA_DB
*db
)
1467 j
= strlen(dbfile
) + strlen(suffix
);
1468 if (j
+ 6 >= BSIZE
) {
1469 BIO_printf(bio_err
, "file name too long\n");
1472 #ifndef OPENSSL_SYS_VMS
1473 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr", dbfile
);
1474 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.attr.%s", dbfile
, suffix
);
1475 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, suffix
);
1477 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr", dbfile
);
1478 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-attr-%s", dbfile
, suffix
);
1479 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, suffix
);
1481 out
= BIO_new_file(buf
[0], "w");
1484 BIO_printf(bio_err
, "unable to open '%s'\n", dbfile
);
1487 j
= TXT_DB_write(out
, db
->db
);
1492 out
= BIO_new_file(buf
[1], "w");
1495 BIO_printf(bio_err
, "unable to open '%s'\n", buf
[2]);
1498 BIO_printf(out
, "unique_subject = %s\n",
1499 db
->attributes
.unique_subject
? "yes" : "no");
1507 int rotate_index(const char *dbfile
, const char *new_suffix
,
1508 const char *old_suffix
)
1513 i
= strlen(dbfile
) + strlen(old_suffix
);
1514 j
= strlen(dbfile
) + strlen(new_suffix
);
1517 if (j
+ 6 >= BSIZE
) {
1518 BIO_printf(bio_err
, "file name too long\n");
1521 #ifndef OPENSSL_SYS_VMS
1522 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s.attr", dbfile
);
1523 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s.attr.%s", dbfile
, old_suffix
);
1524 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr.%s", dbfile
, new_suffix
);
1525 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", dbfile
, old_suffix
);
1526 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, new_suffix
);
1528 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s-attr", dbfile
);
1529 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s-attr-%s", dbfile
, old_suffix
);
1530 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr-%s", dbfile
, new_suffix
);
1531 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", dbfile
, old_suffix
);
1532 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, new_suffix
);
1534 if (rename(dbfile
, buf
[1]) < 0 && errno
!= ENOENT
1539 BIO_printf(bio_err
, "unable to rename %s to %s\n", dbfile
, buf
[1]);
1543 if (rename(buf
[0], dbfile
) < 0) {
1544 BIO_printf(bio_err
, "unable to rename %s to %s\n", buf
[0], dbfile
);
1546 rename(buf
[1], dbfile
);
1549 if (rename(buf
[4], buf
[3]) < 0 && errno
!= ENOENT
1554 BIO_printf(bio_err
, "unable to rename %s to %s\n", buf
[4], buf
[3]);
1556 rename(dbfile
, buf
[0]);
1557 rename(buf
[1], dbfile
);
1560 if (rename(buf
[2], buf
[4]) < 0) {
1561 BIO_printf(bio_err
, "unable to rename %s to %s\n", buf
[2], buf
[4]);
1563 rename(buf
[3], buf
[4]);
1564 rename(dbfile
, buf
[0]);
1565 rename(buf
[1], dbfile
);
1573 void free_index(CA_DB
*db
)
1576 TXT_DB_free(db
->db
);
1577 OPENSSL_free(db
->dbfname
);
1582 int parse_yesno(const char *str
, int def
)
1586 case 'f': /* false */
1587 case 'F': /* FALSE */
1592 case 't': /* true */
1593 case 'T': /* TRUE */
1604 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1605 * where characters may be escaped by \
1607 X509_NAME
*parse_name(const char *cp
, long chtype
, int canmulti
)
1609 int nextismulti
= 0;
1615 "name is expected to be in the format "
1616 "/type0=value0/type1=value1/type2=... where characters may "
1617 "be escaped by \\. This name is not in that format: '%s'\n",
1622 n
= X509_NAME_new();
1625 work
= OPENSSL_strdup(cp
);
1627 BIO_printf(bio_err
, "%s: Error copying name input\n", opt_getprog());
1634 unsigned char *valstr
;
1636 int ismulti
= nextismulti
;
1639 /* Collect the type */
1640 while (*cp
&& *cp
!= '=')
1644 "%s: Hit end of string before finding the '='\n",
1651 /* Collect the value. */
1652 valstr
= (unsigned char *)bp
;
1653 for (; *cp
&& *cp
!= '/'; *bp
++ = *cp
++) {
1654 if (canmulti
&& *cp
== '+') {
1658 if (*cp
== '\\' && *++cp
== '\0') {
1660 "%s: escape character at end of string\n",
1667 /* If not at EOS (must be + or /), move forward. */
1672 nid
= OBJ_txt2nid(typestr
);
1673 if (nid
== NID_undef
) {
1674 BIO_printf(bio_err
, "%s: Skipping unknown attribute \"%s\"\n",
1675 opt_getprog(), typestr
);
1678 if (*valstr
== '\0') {
1680 "%s: No value provided for Subject Attribute %s, skipped\n",
1681 opt_getprog(), typestr
);
1684 if (!X509_NAME_add_entry_by_NID(n
, nid
, chtype
,
1685 valstr
, strlen((char *)valstr
),
1686 -1, ismulti
? -1 : 0)) {
1687 BIO_printf(bio_err
, "%s: Error adding name attribute \"/%s=%s\"\n",
1688 opt_getprog(), typestr
,valstr
);
1703 * Read whole contents of a BIO into an allocated memory buffer and return
1707 int bio_to_mem(unsigned char **out
, int maxlen
, BIO
*in
)
1711 unsigned char tbuf
[1024];
1713 mem
= BIO_new(BIO_s_mem());
1717 if ((maxlen
!= -1) && maxlen
< 1024)
1721 len
= BIO_read(in
, tbuf
, len
);
1728 if (BIO_write(mem
, tbuf
, len
) != len
) {
1737 ret
= BIO_get_mem_data(mem
, (char **)out
);
1738 BIO_set_flags(mem
, BIO_FLAGS_MEM_RDONLY
);
1743 int pkey_ctrl_string(EVP_PKEY_CTX
*ctx
, const char *value
)
1746 char *stmp
, *vtmp
= NULL
;
1747 stmp
= OPENSSL_strdup(value
);
1750 vtmp
= strchr(stmp
, ':');
1755 rv
= EVP_PKEY_CTX_ctrl_str(ctx
, stmp
, vtmp
);
1760 static void nodes_print(const char *name
, STACK_OF(X509_POLICY_NODE
) *nodes
)
1762 X509_POLICY_NODE
*node
;
1765 BIO_printf(bio_err
, "%s Policies:", name
);
1767 BIO_puts(bio_err
, "\n");
1768 for (i
= 0; i
< sk_X509_POLICY_NODE_num(nodes
); i
++) {
1769 node
= sk_X509_POLICY_NODE_value(nodes
, i
);
1770 X509_POLICY_NODE_print(bio_err
, node
, 2);
1773 BIO_puts(bio_err
, " <empty>\n");
1777 void policies_print(X509_STORE_CTX
*ctx
)
1779 X509_POLICY_TREE
*tree
;
1780 int explicit_policy
;
1781 tree
= X509_STORE_CTX_get0_policy_tree(ctx
);
1782 explicit_policy
= X509_STORE_CTX_get_explicit_policy(ctx
);
1784 BIO_printf(bio_err
, "Require explicit Policy: %s\n",
1785 explicit_policy
? "True" : "False");
1787 nodes_print("Authority", X509_policy_tree_get0_policies(tree
));
1788 nodes_print("User", X509_policy_tree_get0_user_policies(tree
));
1792 * next_protos_parse parses a comma separated list of strings into a string
1793 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1794 * outlen: (output) set to the length of the resulting buffer on success.
1795 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1796 * in: a NUL terminated string like "abc,def,ghi"
1798 * returns: a malloc'd buffer or NULL on failure.
1800 unsigned char *next_protos_parse(size_t *outlen
, const char *in
)
1804 size_t i
, start
= 0;
1810 out
= app_malloc(strlen(in
) + 1, "NPN buffer");
1811 for (i
= 0; i
<= len
; ++i
) {
1812 if (i
== len
|| in
[i
] == ',') {
1813 if (i
- start
> 255) {
1817 out
[start
] = (unsigned char)(i
- start
);
1828 void print_cert_checks(BIO
*bio
, X509
*x
,
1829 const char *checkhost
,
1830 const char *checkemail
, const char *checkip
)
1835 BIO_printf(bio
, "Hostname %s does%s match certificate\n",
1837 X509_check_host(x
, checkhost
, 0, 0, NULL
) == 1
1842 BIO_printf(bio
, "Email %s does%s match certificate\n",
1843 checkemail
, X509_check_email(x
, checkemail
, 0, 0)
1848 BIO_printf(bio
, "IP %s does%s match certificate\n",
1849 checkip
, X509_check_ip_asc(x
, checkip
, 0) ? "" : " NOT");
1853 /* Get first http URL from a DIST_POINT structure */
1855 static const char *get_dp_url(DIST_POINT
*dp
)
1857 GENERAL_NAMES
*gens
;
1861 if (!dp
->distpoint
|| dp
->distpoint
->type
!= 0)
1863 gens
= dp
->distpoint
->name
.fullname
;
1864 for (i
= 0; i
< sk_GENERAL_NAME_num(gens
); i
++) {
1865 gen
= sk_GENERAL_NAME_value(gens
, i
);
1866 uri
= GENERAL_NAME_get0_value(gen
, >ype
);
1867 if (gtype
== GEN_URI
&& ASN1_STRING_length(uri
) > 6) {
1868 const char *uptr
= (const char *)ASN1_STRING_get0_data(uri
);
1869 if (strncmp(uptr
, "http://", 7) == 0)
1877 * Look through a CRLDP structure and attempt to find an http URL to
1878 * downloads a CRL from.
1881 static X509_CRL
*load_crl_crldp(STACK_OF(DIST_POINT
) *crldp
)
1884 const char *urlptr
= NULL
;
1885 for (i
= 0; i
< sk_DIST_POINT_num(crldp
); i
++) {
1886 DIST_POINT
*dp
= sk_DIST_POINT_value(crldp
, i
);
1887 urlptr
= get_dp_url(dp
);
1889 return load_crl(urlptr
, FORMAT_HTTP
);
1895 * Example of downloading CRLs from CRLDP: not usable for real world as it
1896 * always downloads, doesn't support non-blocking I/O and doesn't cache
1900 static STACK_OF(X509_CRL
) *crls_http_cb(X509_STORE_CTX
*ctx
, X509_NAME
*nm
)
1903 STACK_OF(X509_CRL
) *crls
= NULL
;
1905 STACK_OF(DIST_POINT
) *crldp
;
1907 crls
= sk_X509_CRL_new_null();
1910 x
= X509_STORE_CTX_get_current_cert(ctx
);
1911 crldp
= X509_get_ext_d2i(x
, NID_crl_distribution_points
, NULL
, NULL
);
1912 crl
= load_crl_crldp(crldp
);
1913 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
1915 sk_X509_CRL_free(crls
);
1918 sk_X509_CRL_push(crls
, crl
);
1919 /* Try to download delta CRL */
1920 crldp
= X509_get_ext_d2i(x
, NID_freshest_crl
, NULL
, NULL
);
1921 crl
= load_crl_crldp(crldp
);
1922 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
1924 sk_X509_CRL_push(crls
, crl
);
1928 void store_setup_crl_download(X509_STORE
*st
)
1930 X509_STORE_set_lookup_crls_cb(st
, crls_http_cb
);
1934 * Platform-specific sections
1939 # define fileno(a) (int)_fileno(a)
1942 # include <windows.h>
1945 static int WIN32_rename(const char *from
, const char *to
)
1947 TCHAR
*tfrom
= NULL
, *tto
;
1951 if (sizeof(TCHAR
) == 1) {
1952 tfrom
= (TCHAR
*)from
;
1954 } else { /* UNICODE path */
1956 size_t i
, flen
= strlen(from
) + 1, tlen
= strlen(to
) + 1;
1957 tfrom
= malloc(sizeof(*tfrom
) * (flen
+ tlen
));
1961 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
1962 if (!MultiByteToWideChar(CP_ACP
, 0, from
, flen
, (WCHAR
*)tfrom
, flen
))
1964 for (i
= 0; i
< flen
; i
++)
1965 tfrom
[i
] = (TCHAR
)from
[i
];
1966 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
1967 if (!MultiByteToWideChar(CP_ACP
, 0, to
, tlen
, (WCHAR
*)tto
, tlen
))
1969 for (i
= 0; i
< tlen
; i
++)
1970 tto
[i
] = (TCHAR
)to
[i
];
1973 if (MoveFile(tfrom
, tto
))
1975 err
= GetLastError();
1976 if (err
== ERROR_ALREADY_EXISTS
|| err
== ERROR_FILE_EXISTS
) {
1977 if (DeleteFile(tto
) && MoveFile(tfrom
, tto
))
1979 err
= GetLastError();
1981 if (err
== ERROR_FILE_NOT_FOUND
|| err
== ERROR_PATH_NOT_FOUND
)
1983 else if (err
== ERROR_ACCESS_DENIED
)
1986 errno
= EINVAL
; /* we could map more codes... */
1990 if (tfrom
!= NULL
&& tfrom
!= (TCHAR
*)from
)
1996 /* app_tminterval section */
1998 double app_tminterval(int stop
, int usertime
)
2002 static ULARGE_INTEGER tmstart
;
2003 static int warning
= 1;
2004 # ifdef _WIN32_WINNT
2005 static HANDLE proc
= NULL
;
2009 proc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
,
2010 GetCurrentProcessId());
2012 proc
= (HANDLE
) - 1;
2015 if (usertime
&& proc
!= (HANDLE
) - 1) {
2017 GetProcessTimes(proc
, &junk
, &junk
, &junk
, &now
);
2023 if (usertime
&& warning
) {
2024 BIO_printf(bio_err
, "To get meaningful results, run "
2025 "this program on idle system.\n");
2028 GetSystemTime(&systime
);
2029 SystemTimeToFileTime(&systime
, &now
);
2032 if (stop
== TM_START
) {
2033 tmstart
.u
.LowPart
= now
.dwLowDateTime
;
2034 tmstart
.u
.HighPart
= now
.dwHighDateTime
;
2036 ULARGE_INTEGER tmstop
;
2038 tmstop
.u
.LowPart
= now
.dwLowDateTime
;
2039 tmstop
.u
.HighPart
= now
.dwHighDateTime
;
2041 ret
= (__int64
)(tmstop
.QuadPart
- tmstart
.QuadPart
) * 1e-7;
2046 #elif defined(OPENSSL_SYS_VXWORKS)
2049 double app_tminterval(int stop
, int usertime
)
2052 # ifdef CLOCK_REALTIME
2053 static struct timespec tmstart
;
2054 struct timespec now
;
2056 static unsigned long tmstart
;
2059 static int warning
= 1;
2061 if (usertime
&& warning
) {
2062 BIO_printf(bio_err
, "To get meaningful results, run "
2063 "this program on idle system.\n");
2066 # ifdef CLOCK_REALTIME
2067 clock_gettime(CLOCK_REALTIME
, &now
);
2068 if (stop
== TM_START
)
2071 ret
= ((now
.tv_sec
+ now
.tv_nsec
* 1e-9)
2072 - (tmstart
.tv_sec
+ tmstart
.tv_nsec
* 1e-9));
2075 if (stop
== TM_START
)
2078 ret
= (now
- tmstart
) / (double)sysClkRateGet();
2083 #elif defined(OPENSSL_SYSTEM_VMS)
2087 double app_tminterval(int stop
, int usertime
)
2089 static clock_t tmstart
;
2097 now
= rus
.tms_utime
;
2100 now
= clock(); /* sum of user and kernel times */
2103 gettimeofday(&tv
, NULL
);
2104 now
= (clock_t)((unsigned long long)tv
.tv_sec
* CLK_TCK
+
2105 (unsigned long long)tv
.tv_usec
* (1000000 / CLK_TCK
)
2109 if (stop
== TM_START
)
2112 ret
= (now
- tmstart
) / (double)(CLK_TCK
);
2117 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2118 # include <sys/times.h>
2120 double app_tminterval(int stop
, int usertime
)
2124 clock_t now
= times(&rus
);
2125 static clock_t tmstart
;
2128 now
= rus
.tms_utime
;
2130 if (stop
== TM_START
) {
2133 long int tck
= sysconf(_SC_CLK_TCK
);
2134 ret
= (now
- tmstart
) / (double)tck
;
2141 # include <sys/time.h>
2142 # include <sys/resource.h>
2144 double app_tminterval(int stop
, int usertime
)
2149 static struct timeval tmstart
;
2152 getrusage(RUSAGE_SELF
, &rus
), now
= rus
.ru_utime
;
2154 gettimeofday(&now
, NULL
);
2156 if (stop
== TM_START
)
2159 ret
= ((now
.tv_sec
+ now
.tv_usec
* 1e-6)
2160 - (tmstart
.tv_sec
+ tmstart
.tv_usec
* 1e-6));
2166 int app_access(const char* name
, int flag
)
2169 return _access(name
, flag
);
2171 return access(name
, flag
);
2175 int app_isdir(const char *name
)
2177 return opt_isdir(name
);
2180 /* raw_read|write section */
2182 # include "vms_term_sock.h"
2183 static int stdin_sock
= -1;
2185 static void close_stdin_sock(void)
2187 TerminalSocket (TERM_SOCK_DELETE
, &stdin_sock
);
2190 int fileno_stdin(void)
2192 if (stdin_sock
== -1) {
2193 TerminalSocket(TERM_SOCK_CREATE
, &stdin_sock
);
2194 atexit(close_stdin_sock
);
2200 int fileno_stdin(void)
2202 return fileno(stdin
);
2206 int fileno_stdout(void)
2208 return fileno(stdout
);
2211 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2212 int raw_read_stdin(void *buf
, int siz
)
2215 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2220 #elif defined(__VMS)
2221 # include <sys/socket.h>
2223 int raw_read_stdin(void *buf
, int siz
)
2225 return recv(fileno_stdin(), buf
, siz
, 0);
2228 int raw_read_stdin(void *buf
, int siz
)
2230 return read(fileno_stdin(), buf
, siz
);
2234 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2235 int raw_write_stdout(const void *buf
, int siz
)
2238 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2244 int raw_write_stdout(const void *buf
, int siz
)
2246 return write(fileno_stdout(), buf
, siz
);
2251 * Centralized handling of input and output files with format specification
2252 * The format is meant to show what the input and output is supposed to be,
2253 * and is therefore a show of intent more than anything else. However, it
2254 * does impact behavior on some platforms, such as differentiating between
2255 * text and binary input/output on non-Unix platforms
2257 BIO
*dup_bio_in(int format
)
2259 return BIO_new_fp(stdin
,
2260 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2263 BIO
*dup_bio_out(int format
)
2265 BIO
*b
= BIO_new_fp(stdout
,
2266 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2267 void *prefix
= NULL
;
2269 #ifdef OPENSSL_SYS_VMS
2270 if (FMT_istext(format
))
2271 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2274 if (FMT_istext(format
)
2275 && (prefix
= getenv("HARNESS_OSSL_PREFIX")) != NULL
) {
2276 b
= BIO_push(BIO_new(apps_bf_prefix()), b
);
2277 BIO_ctrl(b
, PREFIX_CTRL_SET_PREFIX
, 0, prefix
);
2283 BIO
*dup_bio_err(int format
)
2285 BIO
*b
= BIO_new_fp(stderr
,
2286 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2287 #ifdef OPENSSL_SYS_VMS
2288 if (FMT_istext(format
))
2289 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2295 * Because the prefix method is created dynamically, we must also be able
2298 void destroy_prefix_method(void)
2300 BIO_METHOD
*prefix_method
= apps_bf_prefix();
2301 BIO_meth_free(prefix_method
);
2302 prefix_method
= NULL
;
2305 void unbuffer(FILE *fp
)
2308 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2309 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2310 * However, we trust that the C RTL will never give us a FILE pointer
2311 * above the first 4 GB of memory, so we simply turn off the warning
2314 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2315 # pragma environment save
2316 # pragma message disable maylosedata2
2319 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2320 # pragma environment restore
2324 static const char *modestr(char mode
, int format
)
2326 OPENSSL_assert(mode
== 'a' || mode
== 'r' || mode
== 'w');
2330 return FMT_istext(format
) ? "a" : "ab";
2332 return FMT_istext(format
) ? "r" : "rb";
2334 return FMT_istext(format
) ? "w" : "wb";
2336 /* The assert above should make sure we never reach this point */
2340 static const char *modeverb(char mode
)
2350 return "(doing something)";
2354 * Open a file for writing, owner-read-only.
2356 BIO
*bio_open_owner(const char *filename
, int format
, int private)
2360 int fd
= -1, bflags
, mode
, textmode
;
2362 if (!private || filename
== NULL
|| strcmp(filename
, "-") == 0)
2363 return bio_open_default(filename
, 'w', format
);
2372 textmode
= FMT_istext(format
);
2376 #elif defined(_O_BINARY)
2381 #ifdef OPENSSL_SYS_VMS
2382 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2383 * it still needs to know that we're going binary, or fdopen()
2384 * will fail with "invalid argument"... so we tell VMS what the
2388 fd
= open(filename
, mode
, 0600, "ctx=bin");
2391 fd
= open(filename
, mode
, 0600);
2394 fp
= fdopen(fd
, modestr('w', format
));
2399 bflags
|= BIO_FP_TEXT
;
2400 b
= BIO_new_fp(fp
, bflags
);
2405 BIO_printf(bio_err
, "%s: Can't open \"%s\" for writing, %s\n",
2406 opt_getprog(), filename
, strerror(errno
));
2407 ERR_print_errors(bio_err
);
2408 /* If we have fp, then fdopen took over fd, so don't close both. */
2416 static BIO
*bio_open_default_(const char *filename
, char mode
, int format
,
2421 if (filename
== NULL
|| strcmp(filename
, "-") == 0) {
2422 ret
= mode
== 'r' ? dup_bio_in(format
) : dup_bio_out(format
);
2430 "Can't open %s, %s\n",
2431 mode
== 'r' ? "stdin" : "stdout", strerror(errno
));
2433 ret
= BIO_new_file(filename
, modestr(mode
, format
));
2441 "Can't open %s for %s, %s\n",
2442 filename
, modeverb(mode
), strerror(errno
));
2444 ERR_print_errors(bio_err
);
2448 BIO
*bio_open_default(const char *filename
, char mode
, int format
)
2450 return bio_open_default_(filename
, mode
, format
, 0);
2453 BIO
*bio_open_default_quiet(const char *filename
, char mode
, int format
)
2455 return bio_open_default_(filename
, mode
, format
, 1);
2458 void wait_for_async(SSL
*s
)
2460 /* On Windows select only works for sockets, so we simply don't wait */
2461 #ifndef OPENSSL_SYS_WINDOWS
2468 if (!SSL_get_all_async_fds(s
, NULL
, &numfds
))
2472 fds
= app_malloc(sizeof(OSSL_ASYNC_FD
) * numfds
, "allocate async fds");
2473 if (!SSL_get_all_async_fds(s
, fds
, &numfds
)) {
2479 for (i
= 0; i
< numfds
; i
++) {
2480 if (width
<= (int)fds
[i
])
2481 width
= (int)fds
[i
] + 1;
2482 openssl_fdset((int)fds
[i
], &asyncfds
);
2484 select(width
, (void *)&asyncfds
, NULL
, NULL
, NULL
);
2489 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2490 #if defined(OPENSSL_SYS_MSDOS)
2491 int has_stdin_waiting(void)
2493 # if defined(OPENSSL_SYS_WINDOWS)
2494 HANDLE inhand
= GetStdHandle(STD_INPUT_HANDLE
);
2496 INPUT_RECORD inputrec
;
2500 if (inhand
== INVALID_HANDLE_VALUE
) {
2504 peeked
= PeekConsoleInput(inhand
, &inputrec
, insize
, &events
);
2506 /* Probably redirected input? _kbhit() does not work in this case */
2517 /* Corrupt a signature by modifying final byte */
2518 void corrupt_signature(const ASN1_STRING
*signature
)
2520 unsigned char *s
= signature
->data
;
2521 s
[signature
->length
- 1] ^= 0x1;
2524 int set_cert_times(X509
*x
, const char *startdate
, const char *enddate
,
2527 if (startdate
== NULL
|| strcmp(startdate
, "today") == 0) {
2528 if (X509_gmtime_adj(X509_getm_notBefore(x
), 0) == NULL
)
2531 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x
), startdate
))
2534 if (enddate
== NULL
) {
2535 if (X509_time_adj_ex(X509_getm_notAfter(x
), days
, 0, NULL
)
2538 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x
), enddate
)) {
2544 void make_uppercase(char *string
)
2548 for (i
= 0; string
[i
] != '\0'; i
++)
2549 string
[i
] = toupper((unsigned char)string
[i
]);
2552 int opt_printf_stderr(const char *fmt
, ...)
2558 ret
= BIO_vprintf(bio_err
, fmt
, ap
);