2 * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
12 * On VMS, you need to define this to get the declaration of fileno(). The
13 * value 2 is to make sure no function defined in POSIX-2 is left undefined.
15 # define _POSIX_C_SOURCE 2
21 #include <sys/types.h>
22 #ifndef OPENSSL_NO_POSIX_IO
23 # include <sys/stat.h>
28 #include <openssl/err.h>
29 #include <openssl/x509.h>
30 #include <openssl/x509v3.h>
31 #include <openssl/pem.h>
32 #include <openssl/pkcs12.h>
33 #include <openssl/ui.h>
34 #include <openssl/safestack.h>
35 #ifndef OPENSSL_NO_ENGINE
36 # include <openssl/engine.h>
38 #ifndef OPENSSL_NO_RSA
39 # include <openssl/rsa.h>
41 #include <openssl/bn.h>
42 #include <openssl/ssl.h>
46 static int WIN32_rename(const char *from
, const char *to
);
47 # define rename(from,to) WIN32_rename((from),(to))
50 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
54 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32)
58 #define PASS_SOURCE_SIZE_MAX 4
66 static int set_table_opts(unsigned long *flags
, const char *arg
,
67 const NAME_EX_TBL
* in_tbl
);
68 static int set_multi_opts(unsigned long *flags
, const char *arg
,
69 const NAME_EX_TBL
* in_tbl
);
71 int app_init(long mesgwin
);
73 int chopup_args(ARGS
*arg
, char *buf
)
76 char c
= '\0', *p
= NULL
;
81 arg
->argv
= app_malloc(sizeof(*arg
->argv
) * arg
->size
, "argv space");
85 /* Skip whitespace. */
86 while (*p
&& isspace(_UC(*p
)))
91 /* The start of something good :-) */
92 if (arg
->argc
>= arg
->size
) {
95 tmp
= OPENSSL_realloc(arg
->argv
, sizeof(*arg
->argv
) * arg
->size
);
100 quoted
= *p
== '\'' || *p
== '"';
103 arg
->argv
[arg
->argc
++] = p
;
105 /* now look for the end of this */
107 while (*p
&& *p
!= c
)
111 while (*p
&& !isspace(_UC(*p
)))
117 arg
->argv
[arg
->argc
] = NULL
;
122 int app_init(long mesgwin
)
128 int ctx_set_verify_locations(SSL_CTX
*ctx
,
129 const char *CAfile
, int noCAfile
,
130 const char *CApath
, int noCApath
,
131 const char *CAstore
, int noCAstore
)
133 if (CAfile
== NULL
&& CApath
== NULL
&& CAstore
== NULL
) {
134 if (!noCAfile
&& SSL_CTX_set_default_verify_file(ctx
) <= 0)
136 if (!noCApath
&& SSL_CTX_set_default_verify_dir(ctx
) <= 0)
138 if (!noCAstore
&& SSL_CTX_set_default_verify_store(ctx
) <= 0)
144 if (CAfile
!= NULL
&& !SSL_CTX_load_verify_file(ctx
, CAfile
))
146 if (CApath
!= NULL
&& !SSL_CTX_load_verify_dir(ctx
, CApath
))
148 if (CAstore
!= NULL
&& !SSL_CTX_load_verify_store(ctx
, CAstore
))
153 #ifndef OPENSSL_NO_CT
155 int ctx_set_ctlog_list_file(SSL_CTX
*ctx
, const char *path
)
158 return SSL_CTX_set_default_ctlog_list_file(ctx
);
160 return SSL_CTX_set_ctlog_list_file(ctx
, path
);
165 static unsigned long nmflag
= 0;
166 static char nmflag_set
= 0;
168 int set_nameopt(const char *arg
)
170 int ret
= set_name_ex(&nmflag
, arg
);
178 unsigned long get_nameopt(void)
180 return (nmflag_set
) ? nmflag
: XN_FLAG_ONELINE
;
183 int dump_cert_text(BIO
*out
, X509
*x
)
185 print_name(out
, "subject=", X509_get_subject_name(x
), get_nameopt());
187 print_name(out
, "issuer=", X509_get_issuer_name(x
), get_nameopt());
193 int wrap_password_callback(char *buf
, int bufsiz
, int verify
, void *userdata
)
195 return password_callback(buf
, bufsiz
, verify
, (PW_CB_DATA
*)userdata
);
199 static char *app_get_pass(const char *arg
, int keepbio
);
201 int app_passwd(const char *arg1
, const char *arg2
, char **pass1
, char **pass2
)
203 int same
= arg1
!= NULL
&& arg2
!= NULL
&& strcmp(arg1
, arg2
) == 0;
206 *pass1
= app_get_pass(arg1
, same
);
209 } else if (pass1
!= NULL
) {
213 *pass2
= app_get_pass(arg2
, same
? 2 : 0);
216 } else if (pass2
!= NULL
) {
222 static char *app_get_pass(const char *arg
, int keepbio
)
224 static BIO
*pwdbio
= NULL
;
225 char *tmp
, tpass
[APP_PASS_LEN
];
228 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
229 if (strncmp(arg
, "pass:", 5) == 0)
230 return OPENSSL_strdup(arg
+ 5);
231 if (strncmp(arg
, "env:", 4) == 0) {
232 tmp
= getenv(arg
+ 4);
234 BIO_printf(bio_err
, "No environment variable %s\n", arg
+ 4);
237 return OPENSSL_strdup(tmp
);
239 if (!keepbio
|| pwdbio
== NULL
) {
240 if (strncmp(arg
, "file:", 5) == 0) {
241 pwdbio
= BIO_new_file(arg
+ 5, "r");
242 if (pwdbio
== NULL
) {
243 BIO_printf(bio_err
, "Can't open file %s\n", arg
+ 5);
248 * Under _WIN32, which covers even Win64 and CE, file
249 * descriptors referenced by BIO_s_fd are not inherited
250 * by child process and therefore below is not an option.
251 * It could have been an option if bss_fd.c was operating
252 * on real Windows descriptors, such as those obtained
255 } else if (strncmp(arg
, "fd:", 3) == 0) {
259 pwdbio
= BIO_new_fd(i
, BIO_NOCLOSE
);
260 if ((i
< 0) || !pwdbio
) {
261 BIO_printf(bio_err
, "Can't access file descriptor %s\n", arg
+ 3);
265 * Can't do BIO_gets on an fd BIO so add a buffering BIO
267 btmp
= BIO_new(BIO_f_buffer());
268 pwdbio
= BIO_push(btmp
, pwdbio
);
270 } else if (strcmp(arg
, "stdin") == 0) {
271 pwdbio
= dup_bio_in(FORMAT_TEXT
);
272 if (pwdbio
== NULL
) {
273 BIO_printf(bio_err
, "Can't open BIO for stdin\n");
277 /* argument syntax error; do not reveal too much about arg */
278 tmp
= strchr(arg
, ':');
279 if (tmp
== NULL
|| tmp
- arg
> PASS_SOURCE_SIZE_MAX
)
281 "Invalid password argument, missing ':' within the first %d chars\n",
282 PASS_SOURCE_SIZE_MAX
+ 1);
285 "Invalid password argument, starting with \"%.*s\"\n",
286 (int)(tmp
- arg
+ 1), arg
);
290 i
= BIO_gets(pwdbio
, tpass
, APP_PASS_LEN
);
292 BIO_free_all(pwdbio
);
296 BIO_printf(bio_err
, "Error reading password from BIO\n");
299 tmp
= strchr(tpass
, '\n');
302 return OPENSSL_strdup(tpass
);
305 CONF
*app_load_config_bio(BIO
*in
, const char *filename
)
311 conf
= NCONF_new(NULL
);
312 i
= NCONF_load_bio(conf
, in
, &errorline
);
316 if (errorline
<= 0) {
317 BIO_printf(bio_err
, "%s: Can't load ", opt_getprog());
319 BIO_printf(bio_err
, "%s: Error on line %ld of ", opt_getprog(),
322 if (filename
!= NULL
)
323 BIO_printf(bio_err
, "config file \"%s\"\n", filename
);
325 BIO_printf(bio_err
, "config input");
331 CONF
*app_load_config(const char *filename
)
336 in
= bio_open_default(filename
, 'r', FORMAT_TEXT
);
340 conf
= app_load_config_bio(in
, filename
);
345 CONF
*app_load_config_quiet(const char *filename
)
350 in
= bio_open_default_quiet(filename
, 'r', FORMAT_TEXT
);
354 conf
= app_load_config_bio(in
, filename
);
359 int app_load_modules(const CONF
*config
)
361 CONF
*to_free
= NULL
;
364 config
= to_free
= app_load_config_quiet(default_config_file
);
368 if (CONF_modules_load(config
, NULL
, 0) <= 0) {
369 BIO_printf(bio_err
, "Error configuring OpenSSL modules\n");
370 ERR_print_errors(bio_err
);
378 int add_oid_section(CONF
*conf
)
381 STACK_OF(CONF_VALUE
) *sktmp
;
385 if ((p
= NCONF_get_string(conf
, NULL
, "oid_section")) == NULL
) {
389 if ((sktmp
= NCONF_get_section(conf
, p
)) == NULL
) {
390 BIO_printf(bio_err
, "problem loading oid section %s\n", p
);
393 for (i
= 0; i
< sk_CONF_VALUE_num(sktmp
); i
++) {
394 cnf
= sk_CONF_VALUE_value(sktmp
, i
);
395 if (OBJ_create(cnf
->value
, cnf
->name
, cnf
->name
) == NID_undef
) {
396 BIO_printf(bio_err
, "problem creating object %s=%s\n",
397 cnf
->name
, cnf
->value
);
404 static int load_pkcs12(BIO
*in
, const char *desc
,
405 pem_password_cb
*pem_cb
, PW_CB_DATA
*cb_data
,
406 EVP_PKEY
**pkey
, X509
**cert
, STACK_OF(X509
) **ca
)
409 char tpass
[PEM_BUFSIZE
];
412 p12
= d2i_PKCS12_bio(in
, NULL
);
414 BIO_printf(bio_err
, "Error loading PKCS12 file for %s\n", desc
);
417 /* See if an empty password will do */
418 if (PKCS12_verify_mac(p12
, "", 0) || PKCS12_verify_mac(p12
, NULL
, 0)) {
422 pem_cb
= (pem_password_cb
*)password_callback
;
423 len
= pem_cb(tpass
, PEM_BUFSIZE
, 0, cb_data
);
425 BIO_printf(bio_err
, "Passphrase callback error for %s\n", desc
);
428 if (len
< PEM_BUFSIZE
)
430 if (!PKCS12_verify_mac(p12
, tpass
, len
)) {
432 "Mac verify error (wrong password?) in PKCS12 file for %s\n",
438 ret
= PKCS12_parse(p12
, pass
, pkey
, cert
, ca
);
444 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
445 static int load_cert_crl_http(const char *url
, X509
**pcert
, X509_CRL
**pcrl
)
447 char *host
= NULL
, *port
= NULL
, *path
= NULL
;
449 OCSP_REQ_CTX
*rctx
= NULL
;
451 if (!OCSP_parse_url(url
, &host
, &port
, &path
, &use_ssl
))
454 BIO_puts(bio_err
, "https not supported\n");
457 bio
= BIO_new_connect(host
);
458 if (!bio
|| !BIO_set_conn_port(bio
, port
))
460 rctx
= OCSP_REQ_CTX_new(bio
, 1024);
463 if (!OCSP_REQ_CTX_http(rctx
, "GET", path
))
465 if (!OCSP_REQ_CTX_add1_header(rctx
, "Host", host
))
469 rv
= X509_http_nbio(rctx
, pcert
);
473 rv
= X509_CRL_http_nbio(rctx
, pcrl
);
482 OCSP_REQ_CTX_free(rctx
);
484 BIO_printf(bio_err
, "Error loading %s from %s\n",
485 pcert
? "certificate" : "CRL", url
);
486 ERR_print_errors(bio_err
);
492 X509
*load_cert(const char *file
, int format
, const char *cert_descrip
)
497 if (format
== FORMAT_HTTP
) {
498 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
499 load_cert_crl_http(file
, &x
, NULL
);
506 cert
= dup_bio_in(format
);
508 cert
= bio_open_default(file
, 'r', format
);
513 if (format
== FORMAT_ASN1
) {
514 x
= d2i_X509_bio(cert
, NULL
);
515 } else if (format
== FORMAT_PEM
) {
516 x
= PEM_read_bio_X509_AUX(cert
, NULL
,
517 (pem_password_cb
*)password_callback
, NULL
);
518 } else if (format
== FORMAT_PKCS12
) {
519 if (!load_pkcs12(cert
, cert_descrip
, NULL
, NULL
, NULL
, &x
, NULL
))
522 BIO_printf(bio_err
, "bad input format specified for %s\n", cert_descrip
);
527 BIO_printf(bio_err
, "unable to load certificate\n");
528 ERR_print_errors(bio_err
);
534 X509_CRL
*load_crl(const char *infile
, int format
)
539 if (format
== FORMAT_HTTP
) {
540 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
541 load_cert_crl_http(infile
, NULL
, &x
);
546 in
= bio_open_default(infile
, 'r', format
);
549 if (format
== FORMAT_ASN1
) {
550 x
= d2i_X509_CRL_bio(in
, NULL
);
551 } else if (format
== FORMAT_PEM
) {
552 x
= PEM_read_bio_X509_CRL(in
, NULL
, NULL
, NULL
);
554 BIO_printf(bio_err
, "bad input format specified for input crl\n");
558 BIO_printf(bio_err
, "unable to load CRL\n");
559 ERR_print_errors(bio_err
);
568 EVP_PKEY
*load_key(const char *file
, int format
, int maybe_stdin
,
569 const char *pass
, ENGINE
*e
, const char *key_descrip
)
572 EVP_PKEY
*pkey
= NULL
;
575 cb_data
.password
= pass
;
576 cb_data
.prompt_info
= file
;
578 if (file
== NULL
&& (!maybe_stdin
|| format
== FORMAT_ENGINE
)) {
579 BIO_printf(bio_err
, "no keyfile specified\n");
582 if (format
== FORMAT_ENGINE
) {
584 BIO_printf(bio_err
, "no engine specified\n");
586 #ifndef OPENSSL_NO_ENGINE
587 if (ENGINE_init(e
)) {
588 pkey
= ENGINE_load_private_key(e
, file
,
589 (UI_METHOD
*)get_ui_method(),
594 BIO_printf(bio_err
, "cannot load %s from engine\n", key_descrip
);
595 ERR_print_errors(bio_err
);
598 BIO_printf(bio_err
, "engines not supported\n");
603 if (file
== NULL
&& maybe_stdin
) {
605 key
= dup_bio_in(format
);
607 key
= bio_open_default(file
, 'r', format
);
611 if (format
== FORMAT_ASN1
) {
612 pkey
= d2i_PrivateKey_bio(key
, NULL
);
613 } else if (format
== FORMAT_PEM
) {
614 pkey
= PEM_read_bio_PrivateKey(key
, NULL
, wrap_password_callback
, &cb_data
);
615 } else if (format
== FORMAT_PKCS12
) {
616 if (!load_pkcs12(key
, key_descrip
, wrap_password_callback
, &cb_data
,
619 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
620 } else if (format
== FORMAT_MSBLOB
) {
621 pkey
= b2i_PrivateKey_bio(key
);
622 } else if (format
== FORMAT_PVK
) {
623 pkey
= b2i_PVK_bio(key
, wrap_password_callback
, &cb_data
);
626 BIO_printf(bio_err
, "bad input format specified for key file\n");
632 BIO_printf(bio_err
, "unable to load %s\n", key_descrip
);
633 ERR_print_errors(bio_err
);
638 EVP_PKEY
*load_pubkey(const char *file
, int format
, int maybe_stdin
,
639 const char *pass
, ENGINE
*e
, const char *key_descrip
)
642 EVP_PKEY
*pkey
= NULL
;
645 cb_data
.password
= pass
;
646 cb_data
.prompt_info
= file
;
648 if (file
== NULL
&& (!maybe_stdin
|| format
== FORMAT_ENGINE
)) {
649 BIO_printf(bio_err
, "no keyfile specified\n");
652 if (format
== FORMAT_ENGINE
) {
654 BIO_printf(bio_err
, "no engine specified\n");
656 #ifndef OPENSSL_NO_ENGINE
657 pkey
= ENGINE_load_public_key(e
, file
, (UI_METHOD
*)get_ui_method(),
660 BIO_printf(bio_err
, "cannot load %s from engine\n", key_descrip
);
661 ERR_print_errors(bio_err
);
664 BIO_printf(bio_err
, "engines not supported\n");
669 if (file
== NULL
&& maybe_stdin
) {
671 key
= dup_bio_in(format
);
673 key
= bio_open_default(file
, 'r', format
);
677 if (format
== FORMAT_ASN1
) {
678 pkey
= d2i_PUBKEY_bio(key
, NULL
);
679 } else if (format
== FORMAT_ASN1RSA
) {
680 #ifndef OPENSSL_NO_RSA
682 rsa
= d2i_RSAPublicKey_bio(key
, NULL
);
684 pkey
= EVP_PKEY_new();
686 EVP_PKEY_set1_RSA(pkey
, rsa
);
690 BIO_printf(bio_err
, "RSA keys not supported\n");
693 } else if (format
== FORMAT_PEMRSA
) {
694 #ifndef OPENSSL_NO_RSA
696 rsa
= PEM_read_bio_RSAPublicKey(key
, NULL
,
697 (pem_password_cb
*)password_callback
,
700 pkey
= EVP_PKEY_new();
702 EVP_PKEY_set1_RSA(pkey
, rsa
);
706 BIO_printf(bio_err
, "RSA keys not supported\n");
709 } else if (format
== FORMAT_PEM
) {
710 pkey
= PEM_read_bio_PUBKEY(key
, NULL
,
711 (pem_password_cb
*)password_callback
,
713 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
714 } else if (format
== FORMAT_MSBLOB
) {
715 pkey
= b2i_PublicKey_bio(key
);
721 BIO_printf(bio_err
, "unable to load %s\n", key_descrip
);
725 static int load_certs_crls(const char *file
, int format
,
726 const char *pass
, const char *desc
,
727 STACK_OF(X509
) **pcerts
,
728 STACK_OF(X509_CRL
) **pcrls
)
732 STACK_OF(X509_INFO
) *xis
= NULL
;
737 cb_data
.password
= pass
;
738 cb_data
.prompt_info
= file
;
740 if (format
!= FORMAT_PEM
) {
741 BIO_printf(bio_err
, "bad input format specified for %s\n", desc
);
745 bio
= bio_open_default(file
, 'r', FORMAT_PEM
);
749 xis
= PEM_X509_INFO_read_bio(bio
, NULL
,
750 (pem_password_cb
*)password_callback
,
755 if (pcerts
!= NULL
&& *pcerts
== NULL
) {
756 *pcerts
= sk_X509_new_null();
761 if (pcrls
!= NULL
&& *pcrls
== NULL
) {
762 *pcrls
= sk_X509_CRL_new_null();
767 for (i
= 0; i
< sk_X509_INFO_num(xis
); i
++) {
768 xi
= sk_X509_INFO_value(xis
, i
);
769 if (xi
->x509
!= NULL
&& pcerts
!= NULL
) {
770 if (!sk_X509_push(*pcerts
, xi
->x509
))
774 if (xi
->crl
!= NULL
&& pcrls
!= NULL
) {
775 if (!sk_X509_CRL_push(*pcrls
, xi
->crl
))
781 if (pcerts
!= NULL
&& sk_X509_num(*pcerts
) > 0)
784 if (pcrls
!= NULL
&& sk_X509_CRL_num(*pcrls
) > 0)
789 sk_X509_INFO_pop_free(xis
, X509_INFO_free
);
792 if (pcerts
!= NULL
) {
793 sk_X509_pop_free(*pcerts
, X509_free
);
797 sk_X509_CRL_pop_free(*pcrls
, X509_CRL_free
);
800 BIO_printf(bio_err
, "unable to load %s\n",
801 pcerts
? "certificates" : "CRLs");
802 ERR_print_errors(bio_err
);
807 void* app_malloc(int sz
, const char *what
)
809 void *vp
= OPENSSL_malloc(sz
);
812 BIO_printf(bio_err
, "%s: Could not allocate %d bytes for %s\n",
813 opt_getprog(), sz
, what
);
814 ERR_print_errors(bio_err
);
821 * Initialize or extend, if *certs != NULL, a certificate stack.
823 int load_certs(const char *file
, STACK_OF(X509
) **certs
, int format
,
824 const char *pass
, const char *desc
)
826 return load_certs_crls(file
, format
, pass
, desc
, certs
, NULL
);
830 * Initialize or extend, if *crls != NULL, a certificate stack.
832 int load_crls(const char *file
, STACK_OF(X509_CRL
) **crls
, int format
,
833 const char *pass
, const char *desc
)
835 return load_certs_crls(file
, format
, pass
, desc
, NULL
, crls
);
838 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
839 /* Return error for unknown extensions */
840 #define X509V3_EXT_DEFAULT 0
841 /* Print error for unknown extensions */
842 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
843 /* ASN1 parse unknown extensions */
844 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
845 /* BIO_dump unknown extensions */
846 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
848 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
849 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
851 int set_cert_ex(unsigned long *flags
, const char *arg
)
853 static const NAME_EX_TBL cert_tbl
[] = {
854 {"compatible", X509_FLAG_COMPAT
, 0xffffffffl
},
855 {"ca_default", X509_FLAG_CA
, 0xffffffffl
},
856 {"no_header", X509_FLAG_NO_HEADER
, 0},
857 {"no_version", X509_FLAG_NO_VERSION
, 0},
858 {"no_serial", X509_FLAG_NO_SERIAL
, 0},
859 {"no_signame", X509_FLAG_NO_SIGNAME
, 0},
860 {"no_validity", X509_FLAG_NO_VALIDITY
, 0},
861 {"no_subject", X509_FLAG_NO_SUBJECT
, 0},
862 {"no_issuer", X509_FLAG_NO_ISSUER
, 0},
863 {"no_pubkey", X509_FLAG_NO_PUBKEY
, 0},
864 {"no_extensions", X509_FLAG_NO_EXTENSIONS
, 0},
865 {"no_sigdump", X509_FLAG_NO_SIGDUMP
, 0},
866 {"no_aux", X509_FLAG_NO_AUX
, 0},
867 {"no_attributes", X509_FLAG_NO_ATTRIBUTES
, 0},
868 {"ext_default", X509V3_EXT_DEFAULT
, X509V3_EXT_UNKNOWN_MASK
},
869 {"ext_error", X509V3_EXT_ERROR_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
870 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
871 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
874 return set_multi_opts(flags
, arg
, cert_tbl
);
877 int set_name_ex(unsigned long *flags
, const char *arg
)
879 static const NAME_EX_TBL ex_tbl
[] = {
880 {"esc_2253", ASN1_STRFLGS_ESC_2253
, 0},
881 {"esc_2254", ASN1_STRFLGS_ESC_2254
, 0},
882 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL
, 0},
883 {"esc_msb", ASN1_STRFLGS_ESC_MSB
, 0},
884 {"use_quote", ASN1_STRFLGS_ESC_QUOTE
, 0},
885 {"utf8", ASN1_STRFLGS_UTF8_CONVERT
, 0},
886 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE
, 0},
887 {"show_type", ASN1_STRFLGS_SHOW_TYPE
, 0},
888 {"dump_all", ASN1_STRFLGS_DUMP_ALL
, 0},
889 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN
, 0},
890 {"dump_der", ASN1_STRFLGS_DUMP_DER
, 0},
891 {"compat", XN_FLAG_COMPAT
, 0xffffffffL
},
892 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS
, XN_FLAG_SEP_MASK
},
893 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC
, XN_FLAG_SEP_MASK
},
894 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC
, XN_FLAG_SEP_MASK
},
895 {"sep_multiline", XN_FLAG_SEP_MULTILINE
, XN_FLAG_SEP_MASK
},
896 {"dn_rev", XN_FLAG_DN_REV
, 0},
897 {"nofname", XN_FLAG_FN_NONE
, XN_FLAG_FN_MASK
},
898 {"sname", XN_FLAG_FN_SN
, XN_FLAG_FN_MASK
},
899 {"lname", XN_FLAG_FN_LN
, XN_FLAG_FN_MASK
},
900 {"align", XN_FLAG_FN_ALIGN
, 0},
901 {"oid", XN_FLAG_FN_OID
, XN_FLAG_FN_MASK
},
902 {"space_eq", XN_FLAG_SPC_EQ
, 0},
903 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS
, 0},
904 {"RFC2253", XN_FLAG_RFC2253
, 0xffffffffL
},
905 {"oneline", XN_FLAG_ONELINE
, 0xffffffffL
},
906 {"multiline", XN_FLAG_MULTILINE
, 0xffffffffL
},
907 {"ca_default", XN_FLAG_MULTILINE
, 0xffffffffL
},
910 if (set_multi_opts(flags
, arg
, ex_tbl
) == 0)
912 if (*flags
!= XN_FLAG_COMPAT
913 && (*flags
& XN_FLAG_SEP_MASK
) == 0)
914 *flags
|= XN_FLAG_SEP_CPLUS_SPC
;
918 int set_ext_copy(int *copy_type
, const char *arg
)
920 if (strcasecmp(arg
, "none") == 0)
921 *copy_type
= EXT_COPY_NONE
;
922 else if (strcasecmp(arg
, "copy") == 0)
923 *copy_type
= EXT_COPY_ADD
;
924 else if (strcasecmp(arg
, "copyall") == 0)
925 *copy_type
= EXT_COPY_ALL
;
931 int copy_extensions(X509
*x
, X509_REQ
*req
, int copy_type
)
933 STACK_OF(X509_EXTENSION
) *exts
= NULL
;
934 X509_EXTENSION
*ext
, *tmpext
;
937 if (!x
|| !req
|| (copy_type
== EXT_COPY_NONE
))
939 exts
= X509_REQ_get_extensions(req
);
941 for (i
= 0; i
< sk_X509_EXTENSION_num(exts
); i
++) {
942 ext
= sk_X509_EXTENSION_value(exts
, i
);
943 obj
= X509_EXTENSION_get_object(ext
);
944 idx
= X509_get_ext_by_OBJ(x
, obj
, -1);
945 /* Does extension exist? */
947 /* If normal copy don't override existing extension */
948 if (copy_type
== EXT_COPY_ADD
)
950 /* Delete all extensions of same type */
952 tmpext
= X509_get_ext(x
, idx
);
953 X509_delete_ext(x
, idx
);
954 X509_EXTENSION_free(tmpext
);
955 idx
= X509_get_ext_by_OBJ(x
, obj
, -1);
958 if (!X509_add_ext(x
, ext
, -1))
966 sk_X509_EXTENSION_pop_free(exts
, X509_EXTENSION_free
);
971 static int set_multi_opts(unsigned long *flags
, const char *arg
,
972 const NAME_EX_TBL
* in_tbl
)
974 STACK_OF(CONF_VALUE
) *vals
;
979 vals
= X509V3_parse_list(arg
);
980 for (i
= 0; i
< sk_CONF_VALUE_num(vals
); i
++) {
981 val
= sk_CONF_VALUE_value(vals
, i
);
982 if (!set_table_opts(flags
, val
->name
, in_tbl
))
985 sk_CONF_VALUE_pop_free(vals
, X509V3_conf_free
);
989 static int set_table_opts(unsigned long *flags
, const char *arg
,
990 const NAME_EX_TBL
* in_tbl
)
993 const NAME_EX_TBL
*ptbl
;
999 } else if (c
== '+') {
1006 for (ptbl
= in_tbl
; ptbl
->name
; ptbl
++) {
1007 if (strcasecmp(arg
, ptbl
->name
) == 0) {
1008 *flags
&= ~ptbl
->mask
;
1010 *flags
|= ptbl
->flag
;
1012 *flags
&= ~ptbl
->flag
;
1019 void print_name(BIO
*out
, const char *title
, X509_NAME
*nm
,
1020 unsigned long lflags
)
1027 BIO_puts(out
, title
);
1028 if ((lflags
& XN_FLAG_SEP_MASK
) == XN_FLAG_SEP_MULTILINE
) {
1032 if (lflags
== XN_FLAG_COMPAT
) {
1033 buf
= X509_NAME_oneline(nm
, 0, 0);
1035 BIO_puts(out
, "\n");
1039 BIO_puts(out
, "\n");
1040 X509_NAME_print_ex(out
, nm
, indent
, lflags
);
1041 BIO_puts(out
, "\n");
1045 void print_bignum_var(BIO
*out
, const BIGNUM
*in
, const char *var
,
1046 int len
, unsigned char *buffer
)
1048 BIO_printf(out
, " static unsigned char %s_%d[] = {", var
, len
);
1049 if (BN_is_zero(in
)) {
1050 BIO_printf(out
, "\n 0x00");
1054 l
= BN_bn2bin(in
, buffer
);
1055 for (i
= 0; i
< l
; i
++) {
1056 BIO_printf(out
, (i
% 10) == 0 ? "\n " : " ");
1058 BIO_printf(out
, "0x%02X,", buffer
[i
]);
1060 BIO_printf(out
, "0x%02X", buffer
[i
]);
1063 BIO_printf(out
, "\n };\n");
1066 void print_array(BIO
*out
, const char* title
, int len
, const unsigned char* d
)
1070 BIO_printf(out
, "unsigned char %s[%d] = {", title
, len
);
1071 for (i
= 0; i
< len
; i
++) {
1073 BIO_printf(out
, "\n ");
1075 BIO_printf(out
, "0x%02X, ", d
[i
]);
1077 BIO_printf(out
, "0x%02X", d
[i
]);
1079 BIO_printf(out
, "\n};\n");
1082 X509_STORE
*setup_verify(const char *CAfile
, int noCAfile
,
1083 const char *CApath
, int noCApath
,
1084 const char *CAstore
, int noCAstore
)
1086 X509_STORE
*store
= X509_STORE_new();
1087 X509_LOOKUP
*lookup
;
1092 if (CAfile
!= NULL
|| !noCAfile
) {
1093 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_file());
1096 if (CAfile
!= NULL
) {
1097 if (!X509_LOOKUP_load_file(lookup
, CAfile
, X509_FILETYPE_PEM
)) {
1098 BIO_printf(bio_err
, "Error loading file %s\n", CAfile
);
1102 X509_LOOKUP_load_file(lookup
, NULL
, X509_FILETYPE_DEFAULT
);
1106 if (CApath
!= NULL
|| !noCApath
) {
1107 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_hash_dir());
1110 if (CApath
!= NULL
) {
1111 if (!X509_LOOKUP_add_dir(lookup
, CApath
, X509_FILETYPE_PEM
)) {
1112 BIO_printf(bio_err
, "Error loading directory %s\n", CApath
);
1116 X509_LOOKUP_add_dir(lookup
, NULL
, X509_FILETYPE_DEFAULT
);
1120 if (CAstore
!= NULL
|| !noCAstore
) {
1121 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_store());
1124 if (!X509_LOOKUP_add_store(lookup
, CAstore
)) {
1125 if (CAstore
!= NULL
)
1126 BIO_printf(bio_err
, "Error loading store URI %s\n", CAstore
);
1134 X509_STORE_free(store
);
1138 #ifndef OPENSSL_NO_ENGINE
1139 /* Try to load an engine in a shareable library */
1140 static ENGINE
*try_load_engine(const char *engine
)
1142 ENGINE
*e
= ENGINE_by_id("dynamic");
1144 if (!ENGINE_ctrl_cmd_string(e
, "SO_PATH", engine
, 0)
1145 || !ENGINE_ctrl_cmd_string(e
, "LOAD", NULL
, 0)) {
1154 ENGINE
*setup_engine(const char *engine
, int debug
)
1158 #ifndef OPENSSL_NO_ENGINE
1159 if (engine
!= NULL
) {
1160 if (strcmp(engine
, "auto") == 0) {
1161 BIO_printf(bio_err
, "enabling auto ENGINE support\n");
1162 ENGINE_register_all_complete();
1165 if ((e
= ENGINE_by_id(engine
)) == NULL
1166 && (e
= try_load_engine(engine
)) == NULL
) {
1167 BIO_printf(bio_err
, "invalid engine \"%s\"\n", engine
);
1168 ERR_print_errors(bio_err
);
1172 ENGINE_ctrl(e
, ENGINE_CTRL_SET_LOGSTREAM
, 0, bio_err
, 0);
1174 ENGINE_ctrl_cmd(e
, "SET_USER_INTERFACE", 0, (void *)get_ui_method(),
1176 if (!ENGINE_set_default(e
, ENGINE_METHOD_ALL
)) {
1177 BIO_printf(bio_err
, "can't use that engine\n");
1178 ERR_print_errors(bio_err
);
1183 BIO_printf(bio_err
, "engine \"%s\" set.\n", ENGINE_get_id(e
));
1189 void release_engine(ENGINE
*e
)
1191 #ifndef OPENSSL_NO_ENGINE
1193 /* Free our "structural" reference. */
1198 static unsigned long index_serial_hash(const OPENSSL_CSTRING
*a
)
1205 return OPENSSL_LH_strhash(n
);
1208 static int index_serial_cmp(const OPENSSL_CSTRING
*a
,
1209 const OPENSSL_CSTRING
*b
)
1211 const char *aa
, *bb
;
1213 for (aa
= a
[DB_serial
]; *aa
== '0'; aa
++) ;
1214 for (bb
= b
[DB_serial
]; *bb
== '0'; bb
++) ;
1215 return strcmp(aa
, bb
);
1218 static int index_name_qual(char **a
)
1220 return (a
[0][0] == 'V');
1223 static unsigned long index_name_hash(const OPENSSL_CSTRING
*a
)
1225 return OPENSSL_LH_strhash(a
[DB_name
]);
1228 int index_name_cmp(const OPENSSL_CSTRING
*a
, const OPENSSL_CSTRING
*b
)
1230 return strcmp(a
[DB_name
], b
[DB_name
]);
1233 static IMPLEMENT_LHASH_HASH_FN(index_serial
, OPENSSL_CSTRING
)
1234 static IMPLEMENT_LHASH_COMP_FN(index_serial
, OPENSSL_CSTRING
)
1235 static IMPLEMENT_LHASH_HASH_FN(index_name
, OPENSSL_CSTRING
)
1236 static IMPLEMENT_LHASH_COMP_FN(index_name
, OPENSSL_CSTRING
)
1239 BIGNUM
*load_serial(const char *serialfile
, int create
, ASN1_INTEGER
**retai
)
1244 ASN1_INTEGER
*ai
= NULL
;
1246 ai
= ASN1_INTEGER_new();
1250 in
= BIO_new_file(serialfile
, "r");
1258 if (ret
== NULL
|| !rand_serial(ret
, ai
))
1259 BIO_printf(bio_err
, "Out of memory\n");
1261 if (!a2i_ASN1_INTEGER(in
, ai
, buf
, 1024)) {
1262 BIO_printf(bio_err
, "unable to load number from %s\n",
1266 ret
= ASN1_INTEGER_to_BN(ai
, NULL
);
1269 "error converting number from bin to BIGNUM\n");
1280 ASN1_INTEGER_free(ai
);
1284 int save_serial(const char *serialfile
, const char *suffix
, const BIGNUM
*serial
,
1285 ASN1_INTEGER
**retai
)
1290 ASN1_INTEGER
*ai
= NULL
;
1294 j
= strlen(serialfile
);
1296 j
= strlen(serialfile
) + strlen(suffix
) + 1;
1298 BIO_printf(bio_err
, "file name too long\n");
1303 OPENSSL_strlcpy(buf
[0], serialfile
, BSIZE
);
1305 #ifndef OPENSSL_SYS_VMS
1306 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, suffix
);
1308 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, suffix
);
1311 out
= BIO_new_file(buf
[0], "w");
1313 ERR_print_errors(bio_err
);
1317 if ((ai
= BN_to_ASN1_INTEGER(serial
, NULL
)) == NULL
) {
1318 BIO_printf(bio_err
, "error converting serial to ASN.1 format\n");
1321 i2a_ASN1_INTEGER(out
, ai
);
1322 BIO_puts(out
, "\n");
1330 ASN1_INTEGER_free(ai
);
1334 int rotate_serial(const char *serialfile
, const char *new_suffix
,
1335 const char *old_suffix
)
1340 i
= strlen(serialfile
) + strlen(old_suffix
);
1341 j
= strlen(serialfile
) + strlen(new_suffix
);
1344 if (j
+ 1 >= BSIZE
) {
1345 BIO_printf(bio_err
, "file name too long\n");
1348 #ifndef OPENSSL_SYS_VMS
1349 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, new_suffix
);
1350 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", serialfile
, old_suffix
);
1352 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, new_suffix
);
1353 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", serialfile
, old_suffix
);
1355 if (rename(serialfile
, buf
[1]) < 0 && errno
!= ENOENT
1361 "unable to rename %s to %s\n", serialfile
, buf
[1]);
1365 if (rename(buf
[0], serialfile
) < 0) {
1367 "unable to rename %s to %s\n", buf
[0], serialfile
);
1369 rename(buf
[1], serialfile
);
1377 int rand_serial(BIGNUM
*b
, ASN1_INTEGER
*ai
)
1382 btmp
= b
== NULL
? BN_new() : b
;
1386 if (!BN_rand(btmp
, SERIAL_RAND_BITS
, BN_RAND_TOP_ANY
, BN_RAND_BOTTOM_ANY
))
1388 if (ai
&& !BN_to_ASN1_INTEGER(btmp
, ai
))
1401 CA_DB
*load_index(const char *dbfile
, DB_ATTR
*db_attr
)
1403 CA_DB
*retdb
= NULL
;
1404 TXT_DB
*tmpdb
= NULL
;
1406 CONF
*dbattr_conf
= NULL
;
1408 #ifndef OPENSSL_NO_POSIX_IO
1413 in
= BIO_new_file(dbfile
, "r");
1415 ERR_print_errors(bio_err
);
1419 #ifndef OPENSSL_NO_POSIX_IO
1420 BIO_get_fp(in
, &dbfp
);
1421 if (fstat(fileno(dbfp
), &dbst
) == -1) {
1422 ERR_raise_data(ERR_LIB_SYS
, errno
,
1423 "calling fstat(%s)", dbfile
);
1424 ERR_print_errors(bio_err
);
1429 if ((tmpdb
= TXT_DB_read(in
, DB_NUMBER
)) == NULL
)
1432 #ifndef OPENSSL_SYS_VMS
1433 BIO_snprintf(buf
, sizeof(buf
), "%s.attr", dbfile
);
1435 BIO_snprintf(buf
, sizeof(buf
), "%s-attr", dbfile
);
1437 dbattr_conf
= app_load_config_quiet(buf
);
1439 retdb
= app_malloc(sizeof(*retdb
), "new DB");
1443 retdb
->attributes
= *db_attr
;
1445 retdb
->attributes
.unique_subject
= 1;
1449 char *p
= NCONF_get_string(dbattr_conf
, NULL
, "unique_subject");
1451 retdb
->attributes
.unique_subject
= parse_yesno(p
, 1);
1455 retdb
->dbfname
= OPENSSL_strdup(dbfile
);
1456 #ifndef OPENSSL_NO_POSIX_IO
1461 NCONF_free(dbattr_conf
);
1468 * Returns > 0 on success, <= 0 on error
1470 int index_index(CA_DB
*db
)
1472 if (!TXT_DB_create_index(db
->db
, DB_serial
, NULL
,
1473 LHASH_HASH_FN(index_serial
),
1474 LHASH_COMP_FN(index_serial
))) {
1476 "error creating serial number index:(%ld,%ld,%ld)\n",
1477 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1481 if (db
->attributes
.unique_subject
1482 && !TXT_DB_create_index(db
->db
, DB_name
, index_name_qual
,
1483 LHASH_HASH_FN(index_name
),
1484 LHASH_COMP_FN(index_name
))) {
1485 BIO_printf(bio_err
, "error creating name index:(%ld,%ld,%ld)\n",
1486 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1492 int save_index(const char *dbfile
, const char *suffix
, CA_DB
*db
)
1498 j
= strlen(dbfile
) + strlen(suffix
);
1499 if (j
+ 6 >= BSIZE
) {
1500 BIO_printf(bio_err
, "file name too long\n");
1503 #ifndef OPENSSL_SYS_VMS
1504 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr", dbfile
);
1505 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.attr.%s", dbfile
, suffix
);
1506 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, suffix
);
1508 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr", dbfile
);
1509 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-attr-%s", dbfile
, suffix
);
1510 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, suffix
);
1512 out
= BIO_new_file(buf
[0], "w");
1515 BIO_printf(bio_err
, "unable to open '%s'\n", dbfile
);
1518 j
= TXT_DB_write(out
, db
->db
);
1523 out
= BIO_new_file(buf
[1], "w");
1526 BIO_printf(bio_err
, "unable to open '%s'\n", buf
[2]);
1529 BIO_printf(out
, "unique_subject = %s\n",
1530 db
->attributes
.unique_subject
? "yes" : "no");
1538 int rotate_index(const char *dbfile
, const char *new_suffix
,
1539 const char *old_suffix
)
1544 i
= strlen(dbfile
) + strlen(old_suffix
);
1545 j
= strlen(dbfile
) + strlen(new_suffix
);
1548 if (j
+ 6 >= BSIZE
) {
1549 BIO_printf(bio_err
, "file name too long\n");
1552 #ifndef OPENSSL_SYS_VMS
1553 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s.attr", dbfile
);
1554 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s.attr.%s", dbfile
, old_suffix
);
1555 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr.%s", dbfile
, new_suffix
);
1556 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", dbfile
, old_suffix
);
1557 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, new_suffix
);
1559 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s-attr", dbfile
);
1560 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s-attr-%s", dbfile
, old_suffix
);
1561 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr-%s", dbfile
, new_suffix
);
1562 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", dbfile
, old_suffix
);
1563 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, new_suffix
);
1565 if (rename(dbfile
, buf
[1]) < 0 && errno
!= ENOENT
1570 BIO_printf(bio_err
, "unable to rename %s to %s\n", dbfile
, buf
[1]);
1574 if (rename(buf
[0], dbfile
) < 0) {
1575 BIO_printf(bio_err
, "unable to rename %s to %s\n", buf
[0], dbfile
);
1577 rename(buf
[1], dbfile
);
1580 if (rename(buf
[4], buf
[3]) < 0 && errno
!= ENOENT
1585 BIO_printf(bio_err
, "unable to rename %s to %s\n", buf
[4], buf
[3]);
1587 rename(dbfile
, buf
[0]);
1588 rename(buf
[1], dbfile
);
1591 if (rename(buf
[2], buf
[4]) < 0) {
1592 BIO_printf(bio_err
, "unable to rename %s to %s\n", buf
[2], buf
[4]);
1594 rename(buf
[3], buf
[4]);
1595 rename(dbfile
, buf
[0]);
1596 rename(buf
[1], dbfile
);
1604 void free_index(CA_DB
*db
)
1607 TXT_DB_free(db
->db
);
1608 OPENSSL_free(db
->dbfname
);
1613 int parse_yesno(const char *str
, int def
)
1617 case 'f': /* false */
1618 case 'F': /* FALSE */
1623 case 't': /* true */
1624 case 'T': /* TRUE */
1635 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1636 * where characters may be escaped by \
1638 X509_NAME
*parse_name(const char *cp
, long chtype
, int canmulti
)
1640 int nextismulti
= 0;
1646 "name is expected to be in the format "
1647 "/type0=value0/type1=value1/type2=... where characters may "
1648 "be escaped by \\. This name is not in that format: '%s'\n",
1653 n
= X509_NAME_new();
1656 work
= OPENSSL_strdup(cp
);
1658 BIO_printf(bio_err
, "%s: Error copying name input\n", opt_getprog());
1665 unsigned char *valstr
;
1667 int ismulti
= nextismulti
;
1670 /* Collect the type */
1671 while (*cp
&& *cp
!= '=')
1675 "%s: Hit end of string before finding the '='\n",
1682 /* Collect the value. */
1683 valstr
= (unsigned char *)bp
;
1684 for (; *cp
&& *cp
!= '/'; *bp
++ = *cp
++) {
1685 if (canmulti
&& *cp
== '+') {
1689 if (*cp
== '\\' && *++cp
== '\0') {
1691 "%s: escape character at end of string\n",
1698 /* If not at EOS (must be + or /), move forward. */
1703 nid
= OBJ_txt2nid(typestr
);
1704 if (nid
== NID_undef
) {
1705 BIO_printf(bio_err
, "%s: Skipping unknown attribute \"%s\"\n",
1706 opt_getprog(), typestr
);
1709 if (*valstr
== '\0') {
1711 "%s: No value provided for Subject Attribute %s, skipped\n",
1712 opt_getprog(), typestr
);
1715 if (!X509_NAME_add_entry_by_NID(n
, nid
, chtype
,
1716 valstr
, strlen((char *)valstr
),
1717 -1, ismulti
? -1 : 0)) {
1718 BIO_printf(bio_err
, "%s: Error adding name attribute \"/%s=%s\"\n",
1719 opt_getprog(), typestr
,valstr
);
1734 * Read whole contents of a BIO into an allocated memory buffer and return
1738 int bio_to_mem(unsigned char **out
, int maxlen
, BIO
*in
)
1742 unsigned char tbuf
[1024];
1744 mem
= BIO_new(BIO_s_mem());
1748 if ((maxlen
!= -1) && maxlen
< 1024)
1752 len
= BIO_read(in
, tbuf
, len
);
1759 if (BIO_write(mem
, tbuf
, len
) != len
) {
1768 ret
= BIO_get_mem_data(mem
, (char **)out
);
1769 BIO_set_flags(mem
, BIO_FLAGS_MEM_RDONLY
);
1774 int pkey_ctrl_string(EVP_PKEY_CTX
*ctx
, const char *value
)
1777 char *stmp
, *vtmp
= NULL
;
1778 stmp
= OPENSSL_strdup(value
);
1781 vtmp
= strchr(stmp
, ':');
1786 rv
= EVP_PKEY_CTX_ctrl_str(ctx
, stmp
, vtmp
);
1791 static void nodes_print(const char *name
, STACK_OF(X509_POLICY_NODE
) *nodes
)
1793 X509_POLICY_NODE
*node
;
1796 BIO_printf(bio_err
, "%s Policies:", name
);
1798 BIO_puts(bio_err
, "\n");
1799 for (i
= 0; i
< sk_X509_POLICY_NODE_num(nodes
); i
++) {
1800 node
= sk_X509_POLICY_NODE_value(nodes
, i
);
1801 X509_POLICY_NODE_print(bio_err
, node
, 2);
1804 BIO_puts(bio_err
, " <empty>\n");
1808 void policies_print(X509_STORE_CTX
*ctx
)
1810 X509_POLICY_TREE
*tree
;
1811 int explicit_policy
;
1812 tree
= X509_STORE_CTX_get0_policy_tree(ctx
);
1813 explicit_policy
= X509_STORE_CTX_get_explicit_policy(ctx
);
1815 BIO_printf(bio_err
, "Require explicit Policy: %s\n",
1816 explicit_policy
? "True" : "False");
1818 nodes_print("Authority", X509_policy_tree_get0_policies(tree
));
1819 nodes_print("User", X509_policy_tree_get0_user_policies(tree
));
1823 * next_protos_parse parses a comma separated list of strings into a string
1824 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1825 * outlen: (output) set to the length of the resulting buffer on success.
1826 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1827 * in: a NUL terminated string like "abc,def,ghi"
1829 * returns: a malloc'd buffer or NULL on failure.
1831 unsigned char *next_protos_parse(size_t *outlen
, const char *in
)
1835 size_t i
, start
= 0;
1839 if (len
== 0 || len
>= 65535)
1842 out
= app_malloc(len
+ 1, "NPN buffer");
1843 for (i
= 0; i
<= len
; ++i
) {
1844 if (i
== len
|| in
[i
] == ',') {
1846 * Zero-length ALPN elements are invalid on the wire, we could be
1847 * strict and reject the entire string, but just ignoring extra
1848 * commas seems harmless and more friendly.
1850 * Every comma we skip in this way puts the input buffer another
1851 * byte ahead of the output buffer, so all stores into the output
1852 * buffer need to be decremented by the number commas skipped.
1859 if (i
- start
> 255) {
1863 out
[start
-skipped
] = (unsigned char)(i
- start
);
1866 out
[i
+ 1 - skipped
] = in
[i
];
1870 if (len
<= skipped
) {
1875 *outlen
= len
+ 1 - skipped
;
1879 void print_cert_checks(BIO
*bio
, X509
*x
,
1880 const char *checkhost
,
1881 const char *checkemail
, const char *checkip
)
1886 BIO_printf(bio
, "Hostname %s does%s match certificate\n",
1888 X509_check_host(x
, checkhost
, 0, 0, NULL
) == 1
1893 BIO_printf(bio
, "Email %s does%s match certificate\n",
1894 checkemail
, X509_check_email(x
, checkemail
, 0, 0)
1899 BIO_printf(bio
, "IP %s does%s match certificate\n",
1900 checkip
, X509_check_ip_asc(x
, checkip
, 0) ? "" : " NOT");
1904 /* Get first http URL from a DIST_POINT structure */
1906 static const char *get_dp_url(DIST_POINT
*dp
)
1908 GENERAL_NAMES
*gens
;
1912 if (!dp
->distpoint
|| dp
->distpoint
->type
!= 0)
1914 gens
= dp
->distpoint
->name
.fullname
;
1915 for (i
= 0; i
< sk_GENERAL_NAME_num(gens
); i
++) {
1916 gen
= sk_GENERAL_NAME_value(gens
, i
);
1917 uri
= GENERAL_NAME_get0_value(gen
, >ype
);
1918 if (gtype
== GEN_URI
&& ASN1_STRING_length(uri
) > 6) {
1919 const char *uptr
= (const char *)ASN1_STRING_get0_data(uri
);
1920 if (strncmp(uptr
, "http://", 7) == 0)
1928 * Look through a CRLDP structure and attempt to find an http URL to
1929 * downloads a CRL from.
1932 static X509_CRL
*load_crl_crldp(STACK_OF(DIST_POINT
) *crldp
)
1935 const char *urlptr
= NULL
;
1936 for (i
= 0; i
< sk_DIST_POINT_num(crldp
); i
++) {
1937 DIST_POINT
*dp
= sk_DIST_POINT_value(crldp
, i
);
1938 urlptr
= get_dp_url(dp
);
1940 return load_crl(urlptr
, FORMAT_HTTP
);
1946 * Example of downloading CRLs from CRLDP: not usable for real world as it
1947 * always downloads, doesn't support non-blocking I/O and doesn't cache
1951 static STACK_OF(X509_CRL
) *crls_http_cb(X509_STORE_CTX
*ctx
, X509_NAME
*nm
)
1954 STACK_OF(X509_CRL
) *crls
= NULL
;
1956 STACK_OF(DIST_POINT
) *crldp
;
1958 crls
= sk_X509_CRL_new_null();
1961 x
= X509_STORE_CTX_get_current_cert(ctx
);
1962 crldp
= X509_get_ext_d2i(x
, NID_crl_distribution_points
, NULL
, NULL
);
1963 crl
= load_crl_crldp(crldp
);
1964 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
1966 sk_X509_CRL_free(crls
);
1969 sk_X509_CRL_push(crls
, crl
);
1970 /* Try to download delta CRL */
1971 crldp
= X509_get_ext_d2i(x
, NID_freshest_crl
, NULL
, NULL
);
1972 crl
= load_crl_crldp(crldp
);
1973 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
1975 sk_X509_CRL_push(crls
, crl
);
1979 void store_setup_crl_download(X509_STORE
*st
)
1981 X509_STORE_set_lookup_crls_cb(st
, crls_http_cb
);
1985 * Platform-specific sections
1990 # define fileno(a) (int)_fileno(a)
1993 # include <windows.h>
1996 static int WIN32_rename(const char *from
, const char *to
)
1998 TCHAR
*tfrom
= NULL
, *tto
;
2002 if (sizeof(TCHAR
) == 1) {
2003 tfrom
= (TCHAR
*)from
;
2005 } else { /* UNICODE path */
2007 size_t i
, flen
= strlen(from
) + 1, tlen
= strlen(to
) + 1;
2008 tfrom
= malloc(sizeof(*tfrom
) * (flen
+ tlen
));
2012 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2013 if (!MultiByteToWideChar(CP_ACP
, 0, from
, flen
, (WCHAR
*)tfrom
, flen
))
2015 for (i
= 0; i
< flen
; i
++)
2016 tfrom
[i
] = (TCHAR
)from
[i
];
2017 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2018 if (!MultiByteToWideChar(CP_ACP
, 0, to
, tlen
, (WCHAR
*)tto
, tlen
))
2020 for (i
= 0; i
< tlen
; i
++)
2021 tto
[i
] = (TCHAR
)to
[i
];
2024 if (MoveFile(tfrom
, tto
))
2026 err
= GetLastError();
2027 if (err
== ERROR_ALREADY_EXISTS
|| err
== ERROR_FILE_EXISTS
) {
2028 if (DeleteFile(tto
) && MoveFile(tfrom
, tto
))
2030 err
= GetLastError();
2032 if (err
== ERROR_FILE_NOT_FOUND
|| err
== ERROR_PATH_NOT_FOUND
)
2034 else if (err
== ERROR_ACCESS_DENIED
)
2037 errno
= EINVAL
; /* we could map more codes... */
2041 if (tfrom
!= NULL
&& tfrom
!= (TCHAR
*)from
)
2047 /* app_tminterval section */
2049 double app_tminterval(int stop
, int usertime
)
2053 static ULARGE_INTEGER tmstart
;
2054 static int warning
= 1;
2055 # ifdef _WIN32_WINNT
2056 static HANDLE proc
= NULL
;
2060 proc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
,
2061 GetCurrentProcessId());
2063 proc
= (HANDLE
) - 1;
2066 if (usertime
&& proc
!= (HANDLE
) - 1) {
2068 GetProcessTimes(proc
, &junk
, &junk
, &junk
, &now
);
2074 if (usertime
&& warning
) {
2075 BIO_printf(bio_err
, "To get meaningful results, run "
2076 "this program on idle system.\n");
2079 GetSystemTime(&systime
);
2080 SystemTimeToFileTime(&systime
, &now
);
2083 if (stop
== TM_START
) {
2084 tmstart
.u
.LowPart
= now
.dwLowDateTime
;
2085 tmstart
.u
.HighPart
= now
.dwHighDateTime
;
2087 ULARGE_INTEGER tmstop
;
2089 tmstop
.u
.LowPart
= now
.dwLowDateTime
;
2090 tmstop
.u
.HighPart
= now
.dwHighDateTime
;
2092 ret
= (__int64
)(tmstop
.QuadPart
- tmstart
.QuadPart
) * 1e-7;
2097 #elif defined(OPENSSL_SYS_VXWORKS)
2100 double app_tminterval(int stop
, int usertime
)
2103 # ifdef CLOCK_REALTIME
2104 static struct timespec tmstart
;
2105 struct timespec now
;
2107 static unsigned long tmstart
;
2110 static int warning
= 1;
2112 if (usertime
&& warning
) {
2113 BIO_printf(bio_err
, "To get meaningful results, run "
2114 "this program on idle system.\n");
2117 # ifdef CLOCK_REALTIME
2118 clock_gettime(CLOCK_REALTIME
, &now
);
2119 if (stop
== TM_START
)
2122 ret
= ((now
.tv_sec
+ now
.tv_nsec
* 1e-9)
2123 - (tmstart
.tv_sec
+ tmstart
.tv_nsec
* 1e-9));
2126 if (stop
== TM_START
)
2129 ret
= (now
- tmstart
) / (double)sysClkRateGet();
2134 #elif defined(OPENSSL_SYSTEM_VMS)
2138 double app_tminterval(int stop
, int usertime
)
2140 static clock_t tmstart
;
2148 now
= rus
.tms_utime
;
2151 now
= clock(); /* sum of user and kernel times */
2154 gettimeofday(&tv
, NULL
);
2155 now
= (clock_t)((unsigned long long)tv
.tv_sec
* CLK_TCK
+
2156 (unsigned long long)tv
.tv_usec
* (1000000 / CLK_TCK
)
2160 if (stop
== TM_START
)
2163 ret
= (now
- tmstart
) / (double)(CLK_TCK
);
2168 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2169 # include <sys/times.h>
2171 double app_tminterval(int stop
, int usertime
)
2175 clock_t now
= times(&rus
);
2176 static clock_t tmstart
;
2179 now
= rus
.tms_utime
;
2181 if (stop
== TM_START
) {
2184 long int tck
= sysconf(_SC_CLK_TCK
);
2185 ret
= (now
- tmstart
) / (double)tck
;
2192 # include <sys/time.h>
2193 # include <sys/resource.h>
2195 double app_tminterval(int stop
, int usertime
)
2200 static struct timeval tmstart
;
2203 getrusage(RUSAGE_SELF
, &rus
), now
= rus
.ru_utime
;
2205 gettimeofday(&now
, NULL
);
2207 if (stop
== TM_START
)
2210 ret
= ((now
.tv_sec
+ now
.tv_usec
* 1e-6)
2211 - (tmstart
.tv_sec
+ tmstart
.tv_usec
* 1e-6));
2217 int app_access(const char* name
, int flag
)
2220 return _access(name
, flag
);
2222 return access(name
, flag
);
2226 int app_isdir(const char *name
)
2228 return opt_isdir(name
);
2231 /* raw_read|write section */
2233 # include "vms_term_sock.h"
2234 static int stdin_sock
= -1;
2236 static void close_stdin_sock(void)
2238 TerminalSocket (TERM_SOCK_DELETE
, &stdin_sock
);
2241 int fileno_stdin(void)
2243 if (stdin_sock
== -1) {
2244 TerminalSocket(TERM_SOCK_CREATE
, &stdin_sock
);
2245 atexit(close_stdin_sock
);
2251 int fileno_stdin(void)
2253 return fileno(stdin
);
2257 int fileno_stdout(void)
2259 return fileno(stdout
);
2262 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2263 int raw_read_stdin(void *buf
, int siz
)
2266 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2271 #elif defined(__VMS)
2272 # include <sys/socket.h>
2274 int raw_read_stdin(void *buf
, int siz
)
2276 return recv(fileno_stdin(), buf
, siz
, 0);
2279 int raw_read_stdin(void *buf
, int siz
)
2281 return read(fileno_stdin(), buf
, siz
);
2285 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2286 int raw_write_stdout(const void *buf
, int siz
)
2289 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2295 int raw_write_stdout(const void *buf
, int siz
)
2297 return write(fileno_stdout(), buf
, siz
);
2302 * Centralized handling of input and output files with format specification
2303 * The format is meant to show what the input and output is supposed to be,
2304 * and is therefore a show of intent more than anything else. However, it
2305 * does impact behavior on some platforms, such as differentiating between
2306 * text and binary input/output on non-Unix platforms
2308 BIO
*dup_bio_in(int format
)
2310 return BIO_new_fp(stdin
,
2311 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2314 BIO
*dup_bio_out(int format
)
2316 BIO
*b
= BIO_new_fp(stdout
,
2317 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2318 void *prefix
= NULL
;
2320 #ifdef OPENSSL_SYS_VMS
2321 if (FMT_istext(format
))
2322 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2325 if (FMT_istext(format
)
2326 && (prefix
= getenv("HARNESS_OSSL_PREFIX")) != NULL
) {
2327 b
= BIO_push(BIO_new(apps_bf_prefix()), b
);
2328 BIO_ctrl(b
, PREFIX_CTRL_SET_PREFIX
, 0, prefix
);
2334 BIO
*dup_bio_err(int format
)
2336 BIO
*b
= BIO_new_fp(stderr
,
2337 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2338 #ifdef OPENSSL_SYS_VMS
2339 if (FMT_istext(format
))
2340 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2346 * Because the prefix method is created dynamically, we must also be able
2349 void destroy_prefix_method(void)
2351 BIO_METHOD
*prefix_method
= apps_bf_prefix();
2352 BIO_meth_free(prefix_method
);
2353 prefix_method
= NULL
;
2356 void unbuffer(FILE *fp
)
2359 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2360 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2361 * However, we trust that the C RTL will never give us a FILE pointer
2362 * above the first 4 GB of memory, so we simply turn off the warning
2365 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2366 # pragma environment save
2367 # pragma message disable maylosedata2
2370 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2371 # pragma environment restore
2375 static const char *modestr(char mode
, int format
)
2377 OPENSSL_assert(mode
== 'a' || mode
== 'r' || mode
== 'w');
2381 return FMT_istext(format
) ? "a" : "ab";
2383 return FMT_istext(format
) ? "r" : "rb";
2385 return FMT_istext(format
) ? "w" : "wb";
2387 /* The assert above should make sure we never reach this point */
2391 static const char *modeverb(char mode
)
2401 return "(doing something)";
2405 * Open a file for writing, owner-read-only.
2407 BIO
*bio_open_owner(const char *filename
, int format
, int private)
2411 int fd
= -1, bflags
, mode
, textmode
;
2413 if (!private || filename
== NULL
|| strcmp(filename
, "-") == 0)
2414 return bio_open_default(filename
, 'w', format
);
2423 textmode
= FMT_istext(format
);
2427 #elif defined(_O_BINARY)
2432 #ifdef OPENSSL_SYS_VMS
2433 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2434 * it still needs to know that we're going binary, or fdopen()
2435 * will fail with "invalid argument"... so we tell VMS what the
2439 fd
= open(filename
, mode
, 0600, "ctx=bin");
2442 fd
= open(filename
, mode
, 0600);
2445 fp
= fdopen(fd
, modestr('w', format
));
2450 bflags
|= BIO_FP_TEXT
;
2451 b
= BIO_new_fp(fp
, bflags
);
2456 BIO_printf(bio_err
, "%s: Can't open \"%s\" for writing, %s\n",
2457 opt_getprog(), filename
, strerror(errno
));
2458 ERR_print_errors(bio_err
);
2459 /* If we have fp, then fdopen took over fd, so don't close both. */
2467 static BIO
*bio_open_default_(const char *filename
, char mode
, int format
,
2472 if (filename
== NULL
|| strcmp(filename
, "-") == 0) {
2473 ret
= mode
== 'r' ? dup_bio_in(format
) : dup_bio_out(format
);
2481 "Can't open %s, %s\n",
2482 mode
== 'r' ? "stdin" : "stdout", strerror(errno
));
2484 ret
= BIO_new_file(filename
, modestr(mode
, format
));
2492 "Can't open %s for %s, %s\n",
2493 filename
, modeverb(mode
), strerror(errno
));
2495 ERR_print_errors(bio_err
);
2499 BIO
*bio_open_default(const char *filename
, char mode
, int format
)
2501 return bio_open_default_(filename
, mode
, format
, 0);
2504 BIO
*bio_open_default_quiet(const char *filename
, char mode
, int format
)
2506 return bio_open_default_(filename
, mode
, format
, 1);
2509 void wait_for_async(SSL
*s
)
2511 /* On Windows select only works for sockets, so we simply don't wait */
2512 #ifndef OPENSSL_SYS_WINDOWS
2519 if (!SSL_get_all_async_fds(s
, NULL
, &numfds
))
2523 fds
= app_malloc(sizeof(OSSL_ASYNC_FD
) * numfds
, "allocate async fds");
2524 if (!SSL_get_all_async_fds(s
, fds
, &numfds
)) {
2530 for (i
= 0; i
< numfds
; i
++) {
2531 if (width
<= (int)fds
[i
])
2532 width
= (int)fds
[i
] + 1;
2533 openssl_fdset((int)fds
[i
], &asyncfds
);
2535 select(width
, (void *)&asyncfds
, NULL
, NULL
, NULL
);
2540 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2541 #if defined(OPENSSL_SYS_MSDOS)
2542 int has_stdin_waiting(void)
2544 # if defined(OPENSSL_SYS_WINDOWS)
2545 HANDLE inhand
= GetStdHandle(STD_INPUT_HANDLE
);
2547 INPUT_RECORD inputrec
;
2551 if (inhand
== INVALID_HANDLE_VALUE
) {
2555 peeked
= PeekConsoleInput(inhand
, &inputrec
, insize
, &events
);
2557 /* Probably redirected input? _kbhit() does not work in this case */
2568 /* Corrupt a signature by modifying final byte */
2569 void corrupt_signature(const ASN1_STRING
*signature
)
2571 unsigned char *s
= signature
->data
;
2572 s
[signature
->length
- 1] ^= 0x1;
2575 int set_cert_times(X509
*x
, const char *startdate
, const char *enddate
,
2578 if (startdate
== NULL
|| strcmp(startdate
, "today") == 0) {
2579 if (X509_gmtime_adj(X509_getm_notBefore(x
), 0) == NULL
)
2582 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x
), startdate
))
2585 if (enddate
== NULL
) {
2586 if (X509_time_adj_ex(X509_getm_notAfter(x
), days
, 0, NULL
)
2589 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x
), enddate
)) {
2595 void make_uppercase(char *string
)
2599 for (i
= 0; string
[i
] != '\0'; i
++)
2600 string
[i
] = toupper((unsigned char)string
[i
]);
2603 int opt_printf_stderr(const char *fmt
, ...)
2609 ret
= BIO_vprintf(bio_err
, fmt
, ap
);
2614 OSSL_PARAM
*app_params_new_from_opts(STACK_OF(OPENSSL_STRING
) *opts
,
2615 const OSSL_PARAM
*paramdefs
)
2617 OSSL_PARAM
*params
= NULL
;
2618 size_t sz
= (size_t)sk_OPENSSL_STRING_num(opts
);
2620 char *opt
= "", *stmp
, *vtmp
= NULL
;
2625 params
= OPENSSL_zalloc(sizeof(OSSL_PARAM
) * (sz
+ 1));
2629 for (params_n
= 0; params_n
< sz
; params_n
++) {
2630 opt
= sk_OPENSSL_STRING_value(opts
, (int)params_n
);
2631 if ((stmp
= OPENSSL_strdup(opt
)) == NULL
2632 || (vtmp
= strchr(stmp
, ':')) == NULL
)
2634 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2636 /* Skip over the separator so that vmtp points to the value */
2638 if (!OSSL_PARAM_allocate_from_text(¶ms
[params_n
], paramdefs
,
2639 stmp
, vtmp
, strlen(vtmp
)))
2643 params
[params_n
] = OSSL_PARAM_construct_end();
2647 BIO_printf(bio_err
, "Parameter error '%s'\n", opt
);
2648 ERR_print_errors(bio_err
);
2649 app_params_free(params
);
2653 void app_params_free(OSSL_PARAM
*params
)
2657 if (params
!= NULL
) {
2658 for (i
= 0; params
[i
].key
!= NULL
; ++i
)
2659 OPENSSL_free(params
[i
].data
);
2660 OPENSSL_free(params
);