2 * Copyright 1995-2020 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 /* We need to use some engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
13 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
15 * On VMS, you need to define this to get the declaration of fileno(). The
16 * value 2 is to make sure no function defined in POSIX-2 is left undefined.
18 # define _POSIX_C_SOURCE 2
24 #include <sys/types.h>
25 #ifndef OPENSSL_NO_POSIX_IO
26 # include <sys/stat.h>
31 #include <openssl/err.h>
32 #include <openssl/x509.h>
33 #include <openssl/x509v3.h>
34 #include <openssl/pem.h>
35 #include <openssl/store.h>
36 #include <openssl/pkcs12.h>
37 #include <openssl/ui.h>
38 #include <openssl/safestack.h>
39 #ifndef OPENSSL_NO_ENGINE
40 # include <openssl/engine.h>
42 #ifndef OPENSSL_NO_RSA
43 # include <openssl/rsa.h>
45 #include <openssl/bn.h>
46 #include <openssl/ssl.h>
50 static int WIN32_rename(const char *from
, const char *to
);
51 # define rename(from,to) WIN32_rename((from),(to))
54 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
58 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32)
62 #define PASS_SOURCE_SIZE_MAX 4
65 DEFINE_STACK_OF(CONF_VALUE
)
66 DEFINE_STACK_OF(X509_POLICY_NODE
)
67 DEFINE_STACK_OF(GENERAL_NAME
)
68 DEFINE_STACK_OF(DIST_POINT
)
69 DEFINE_STACK_OF_STRING()
77 static OPENSSL_CTX
*app_libctx
= NULL
;
79 static int set_table_opts(unsigned long *flags
, const char *arg
,
80 const NAME_EX_TBL
* in_tbl
);
81 static int set_multi_opts(unsigned long *flags
, const char *arg
,
82 const NAME_EX_TBL
* in_tbl
);
84 int app_init(long mesgwin
);
86 int chopup_args(ARGS
*arg
, char *buf
)
89 char c
= '\0', *p
= NULL
;
94 arg
->argv
= app_malloc(sizeof(*arg
->argv
) * arg
->size
, "argv space");
98 /* Skip whitespace. */
99 while (*p
&& isspace(_UC(*p
)))
104 /* The start of something good :-) */
105 if (arg
->argc
>= arg
->size
) {
108 tmp
= OPENSSL_realloc(arg
->argv
, sizeof(*arg
->argv
) * arg
->size
);
113 quoted
= *p
== '\'' || *p
== '"';
116 arg
->argv
[arg
->argc
++] = p
;
118 /* now look for the end of this */
120 while (*p
&& *p
!= c
)
124 while (*p
&& !isspace(_UC(*p
)))
130 arg
->argv
[arg
->argc
] = NULL
;
135 int app_init(long mesgwin
)
141 int ctx_set_verify_locations(SSL_CTX
*ctx
,
142 const char *CAfile
, int noCAfile
,
143 const char *CApath
, int noCApath
,
144 const char *CAstore
, int noCAstore
)
146 if (CAfile
== NULL
&& CApath
== NULL
&& CAstore
== NULL
) {
147 if (!noCAfile
&& SSL_CTX_set_default_verify_file(ctx
) <= 0)
149 if (!noCApath
&& SSL_CTX_set_default_verify_dir(ctx
) <= 0)
151 if (!noCAstore
&& SSL_CTX_set_default_verify_store(ctx
) <= 0)
157 if (CAfile
!= NULL
&& !SSL_CTX_load_verify_file(ctx
, CAfile
))
159 if (CApath
!= NULL
&& !SSL_CTX_load_verify_dir(ctx
, CApath
))
161 if (CAstore
!= NULL
&& !SSL_CTX_load_verify_store(ctx
, CAstore
))
166 #ifndef OPENSSL_NO_CT
168 int ctx_set_ctlog_list_file(SSL_CTX
*ctx
, const char *path
)
171 return SSL_CTX_set_default_ctlog_list_file(ctx
);
173 return SSL_CTX_set_ctlog_list_file(ctx
, path
);
178 static unsigned long nmflag
= 0;
179 static char nmflag_set
= 0;
181 int set_nameopt(const char *arg
)
183 int ret
= set_name_ex(&nmflag
, arg
);
191 unsigned long get_nameopt(void)
193 return (nmflag_set
) ? nmflag
: XN_FLAG_ONELINE
;
196 int dump_cert_text(BIO
*out
, X509
*x
)
198 print_name(out
, "subject=", X509_get_subject_name(x
), get_nameopt());
200 print_name(out
, "issuer=", X509_get_issuer_name(x
), get_nameopt());
206 int wrap_password_callback(char *buf
, int bufsiz
, int verify
, void *userdata
)
208 return password_callback(buf
, bufsiz
, verify
, (PW_CB_DATA
*)userdata
);
212 static char *app_get_pass(const char *arg
, int keepbio
);
214 char *get_passwd(const char *pass
, const char *desc
)
220 if (!app_passwd(pass
, NULL
, &result
, NULL
))
221 BIO_printf(bio_err
, "Error getting password for %s\n", desc
);
222 if (pass
!= NULL
&& result
== NULL
) {
224 "Trying plain input string (better precede with 'pass:')\n");
225 result
= OPENSSL_strdup(pass
);
227 BIO_printf(bio_err
, "Out of memory getting password for %s\n", desc
);
232 int app_passwd(const char *arg1
, const char *arg2
, char **pass1
, char **pass2
)
234 int same
= arg1
!= NULL
&& arg2
!= NULL
&& strcmp(arg1
, arg2
) == 0;
237 *pass1
= app_get_pass(arg1
, same
);
240 } else if (pass1
!= NULL
) {
244 *pass2
= app_get_pass(arg2
, same
? 2 : 0);
247 } else if (pass2
!= NULL
) {
253 static char *app_get_pass(const char *arg
, int keepbio
)
255 static BIO
*pwdbio
= NULL
;
256 char *tmp
, tpass
[APP_PASS_LEN
];
259 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
260 if (strncmp(arg
, "pass:", 5) == 0)
261 return OPENSSL_strdup(arg
+ 5);
262 if (strncmp(arg
, "env:", 4) == 0) {
263 tmp
= getenv(arg
+ 4);
265 BIO_printf(bio_err
, "No environment variable %s\n", arg
+ 4);
268 return OPENSSL_strdup(tmp
);
270 if (!keepbio
|| pwdbio
== NULL
) {
271 if (strncmp(arg
, "file:", 5) == 0) {
272 pwdbio
= BIO_new_file(arg
+ 5, "r");
273 if (pwdbio
== NULL
) {
274 BIO_printf(bio_err
, "Can't open file %s\n", arg
+ 5);
279 * Under _WIN32, which covers even Win64 and CE, file
280 * descriptors referenced by BIO_s_fd are not inherited
281 * by child process and therefore below is not an option.
282 * It could have been an option if bss_fd.c was operating
283 * on real Windows descriptors, such as those obtained
286 } else if (strncmp(arg
, "fd:", 3) == 0) {
290 pwdbio
= BIO_new_fd(i
, BIO_NOCLOSE
);
291 if ((i
< 0) || !pwdbio
) {
292 BIO_printf(bio_err
, "Can't access file descriptor %s\n", arg
+ 3);
296 * Can't do BIO_gets on an fd BIO so add a buffering BIO
298 btmp
= BIO_new(BIO_f_buffer());
299 pwdbio
= BIO_push(btmp
, pwdbio
);
301 } else if (strcmp(arg
, "stdin") == 0) {
302 pwdbio
= dup_bio_in(FORMAT_TEXT
);
303 if (pwdbio
== NULL
) {
304 BIO_printf(bio_err
, "Can't open BIO for stdin\n");
308 /* argument syntax error; do not reveal too much about arg */
309 tmp
= strchr(arg
, ':');
310 if (tmp
== NULL
|| tmp
- arg
> PASS_SOURCE_SIZE_MAX
)
312 "Invalid password argument, missing ':' within the first %d chars\n",
313 PASS_SOURCE_SIZE_MAX
+ 1);
316 "Invalid password argument, starting with \"%.*s\"\n",
317 (int)(tmp
- arg
+ 1), arg
);
321 i
= BIO_gets(pwdbio
, tpass
, APP_PASS_LEN
);
323 BIO_free_all(pwdbio
);
327 BIO_printf(bio_err
, "Error reading password from BIO\n");
330 tmp
= strchr(tpass
, '\n');
333 return OPENSSL_strdup(tpass
);
336 OPENSSL_CTX
*app_get0_libctx(void)
341 /* TODO(3.0): Make this an environment variable if required */
342 const char *app_get0_propq(void)
347 OPENSSL_CTX
*app_create_libctx(void)
350 * Load the NULL provider into the default library context and create a
351 * library context which will then be used for any OPT_PROV options.
353 if (app_libctx
== NULL
) {
355 if (!app_provider_load(NULL
, "null")) {
356 BIO_puts(bio_err
, "Failed to create null provider\n");
359 app_libctx
= OPENSSL_CTX_new();
361 if (app_libctx
== NULL
)
362 BIO_puts(bio_err
, "Failed to create library context\n");
366 CONF
*app_load_config_bio(BIO
*in
, const char *filename
)
372 conf
= NCONF_new_with_libctx(app_libctx
, NULL
);
373 i
= NCONF_load_bio(conf
, in
, &errorline
);
377 if (errorline
<= 0) {
378 BIO_printf(bio_err
, "%s: Can't load ", opt_getprog());
380 BIO_printf(bio_err
, "%s: Error on line %ld of ", opt_getprog(),
383 if (filename
!= NULL
)
384 BIO_printf(bio_err
, "config file \"%s\"\n", filename
);
386 BIO_printf(bio_err
, "config input");
392 CONF
*app_load_config(const char *filename
)
397 in
= bio_open_default(filename
, 'r', FORMAT_TEXT
);
401 conf
= app_load_config_bio(in
, filename
);
406 CONF
*app_load_config_quiet(const char *filename
)
411 in
= bio_open_default_quiet(filename
, 'r', FORMAT_TEXT
);
415 conf
= app_load_config_bio(in
, filename
);
420 int app_load_modules(const CONF
*config
)
422 CONF
*to_free
= NULL
;
425 config
= to_free
= app_load_config_quiet(default_config_file
);
429 if (CONF_modules_load(config
, NULL
, 0) <= 0) {
430 BIO_printf(bio_err
, "Error configuring OpenSSL modules\n");
431 ERR_print_errors(bio_err
);
439 int add_oid_section(CONF
*conf
)
442 STACK_OF(CONF_VALUE
) *sktmp
;
446 if ((p
= NCONF_get_string(conf
, NULL
, "oid_section")) == NULL
) {
450 if ((sktmp
= NCONF_get_section(conf
, p
)) == NULL
) {
451 BIO_printf(bio_err
, "problem loading oid section %s\n", p
);
454 for (i
= 0; i
< sk_CONF_VALUE_num(sktmp
); i
++) {
455 cnf
= sk_CONF_VALUE_value(sktmp
, i
);
456 if (OBJ_create(cnf
->value
, cnf
->name
, cnf
->name
) == NID_undef
) {
457 BIO_printf(bio_err
, "problem creating object %s=%s\n",
458 cnf
->name
, cnf
->value
);
465 CONF
*app_load_config_modules(const char *configfile
)
469 if (configfile
!= NULL
) {
470 BIO_printf(bio_err
, "Using configuration from %s\n", configfile
);
472 if ((conf
= app_load_config(configfile
)) == NULL
)
474 if (configfile
!= default_config_file
&& !app_load_modules(conf
)) {
482 X509
*load_cert_pass(const char *uri
, int maybe_stdin
,
483 const char *pass
, const char *desc
)
488 desc
= "certificate";
489 (void)load_key_certs_crls(uri
, maybe_stdin
, pass
, desc
,
490 NULL
, NULL
, &cert
, NULL
, NULL
, NULL
);
492 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
493 ERR_print_errors(bio_err
);
498 /* the format parameter is meanwhile not needed anymore and thus ignored */
499 X509_CRL
*load_crl(const char *uri
, int format
, const char *desc
)
501 X509_CRL
*crl
= NULL
;
505 (void)load_key_certs_crls(uri
, 0, NULL
, desc
,
506 NULL
, NULL
, NULL
, NULL
, &crl
, NULL
);
508 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
509 ERR_print_errors(bio_err
);
514 X509_REQ
*load_csr(const char *file
, int format
, const char *desc
)
516 X509_REQ
*req
= NULL
;
521 in
= bio_open_default(file
, 'r', format
);
525 if (format
== FORMAT_ASN1
)
526 req
= d2i_X509_REQ_bio(in
, NULL
);
527 else if (format
== FORMAT_PEM
)
528 req
= PEM_read_bio_X509_REQ(in
, NULL
, NULL
, NULL
);
530 print_format_error(format
, OPT_FMT_PEMDER
);
534 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
535 ERR_print_errors(bio_err
);
541 void cleanse(char *str
)
544 OPENSSL_cleanse(str
, strlen(str
));
547 void clear_free(char *str
)
550 OPENSSL_clear_free(str
, strlen(str
));
553 EVP_PKEY
*load_key(const char *uri
, int format
, int may_stdin
,
554 const char *pass
, ENGINE
*e
, const char *desc
)
556 EVP_PKEY
*pkey
= NULL
;
559 desc
= "private key";
561 if (format
== FORMAT_ENGINE
) {
563 BIO_printf(bio_err
, "No engine specified for loading %s\n", desc
);
565 #ifndef OPENSSL_NO_ENGINE
568 cb_data
.password
= pass
;
569 cb_data
.prompt_info
= uri
;
570 if (ENGINE_init(e
)) {
571 pkey
= ENGINE_load_private_key(e
, uri
,
572 (UI_METHOD
*)get_ui_method(),
577 BIO_printf(bio_err
, "Cannot load %s from engine\n", desc
);
578 ERR_print_errors(bio_err
);
581 BIO_printf(bio_err
, "Engines not supported for loading %s\n", desc
);
585 (void)load_key_certs_crls(uri
, may_stdin
, pass
, desc
,
586 &pkey
, NULL
, NULL
, NULL
, NULL
, NULL
);
590 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
591 ERR_print_errors(bio_err
);
596 EVP_PKEY
*load_pubkey(const char *uri
, int format
, int maybe_stdin
,
597 const char *pass
, ENGINE
*e
, const char *desc
)
599 EVP_PKEY
*pkey
= NULL
;
604 if (format
== FORMAT_ENGINE
) {
606 BIO_printf(bio_err
, "No engine specified for loading %s\n", desc
);
608 #ifndef OPENSSL_NO_ENGINE
611 cb_data
.password
= pass
;
612 cb_data
.prompt_info
= uri
;
613 pkey
= ENGINE_load_public_key(e
, uri
, (UI_METHOD
*)get_ui_method(),
616 BIO_printf(bio_err
, "Cannot load %s from engine\n", desc
);
617 ERR_print_errors(bio_err
);
620 BIO_printf(bio_err
, "Engines not supported for loading %s\n", desc
);
624 (void)load_key_certs_crls(uri
, maybe_stdin
, pass
, desc
,
625 NULL
, &pkey
, NULL
, NULL
, NULL
, NULL
);
628 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
629 ERR_print_errors(bio_err
);
634 void app_bail_out(char *fmt
, ...)
639 BIO_vprintf(bio_err
, fmt
, args
);
641 ERR_print_errors(bio_err
);
645 void* app_malloc(int sz
, const char *what
)
647 void *vp
= OPENSSL_malloc(sz
);
650 app_bail_out("%s: Could not allocate %d bytes for %s\n",
651 opt_getprog(), sz
, what
);
656 * Initialize or extend, if *certs != NULL, a certificate stack.
657 * The caller is responsible for freeing *certs if its value is left not NULL.
659 int load_certs(const char *uri
, STACK_OF(X509
) **certs
,
660 const char *pass
, const char *desc
)
662 int was_NULL
= *certs
== NULL
;
663 int ret
= load_key_certs_crls(uri
, 0, pass
, desc
, NULL
, NULL
,
664 NULL
, certs
, NULL
, NULL
);
666 if (!ret
&& was_NULL
) {
667 sk_X509_pop_free(*certs
, X509_free
);
674 * Initialize or extend, if *crls != NULL, a certificate stack.
675 * The caller is responsible for freeing *crls if its value is left not NULL.
677 int load_crls(const char *uri
, STACK_OF(X509_CRL
) **crls
,
678 const char *pass
, const char *desc
)
680 int was_NULL
= *crls
== NULL
;
681 int ret
= load_key_certs_crls(uri
, 0, pass
, desc
, NULL
, NULL
,
682 NULL
, NULL
, NULL
, crls
);
684 if (!ret
&& was_NULL
) {
685 sk_X509_CRL_pop_free(*crls
, X509_CRL_free
);
692 * Load those types of credentials for which the result pointer is not NULL.
693 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
694 * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
695 * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
696 * If pcerts is non-NULL then all available certificates are appended to *pcerts
697 * except any certificate assigned to *pcert.
698 * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
699 * If pcrls is non-NULL then all available CRLs are appended to *pcerts
700 * except any CRL assigned to *pcrl.
701 * In any case (also on error) the caller is responsible for freeing all members
702 * of *pcerts and *pcrls (as far as they are not NULL).
704 int load_key_certs_crls(const char *uri
, int maybe_stdin
,
705 const char *pass
, const char *desc
,
706 EVP_PKEY
**ppkey
, EVP_PKEY
**ppubkey
,
707 X509
**pcert
, STACK_OF(X509
) **pcerts
,
708 X509_CRL
**pcrl
, STACK_OF(X509_CRL
) **pcrls
)
711 OSSL_STORE_CTX
*ctx
= NULL
;
712 OPENSSL_CTX
*libctx
= app_get0_libctx();
713 const char *propq
= app_get0_propq();
716 const char *failed
= "any";
717 /* TODO make use of the engine reference 'eng' when loading pkeys */
725 if (pcerts
!= NULL
&& *pcerts
== NULL
726 && (*pcerts
= sk_X509_new_null()) == NULL
) {
727 BIO_printf(bio_err
, "Out of memory");
732 if (pcrls
!= NULL
&& *pcrls
== NULL
733 && (*pcrls
= sk_X509_CRL_new_null()) == NULL
) {
734 BIO_printf(bio_err
, "Out of memory");
739 desc
= "key/certificate/CRL";
740 uidata
.password
= pass
;
741 uidata
.prompt_info
= uri
;
748 BIO_printf(bio_err
, "No filename or uri specified for loading %s\n",
753 bio
= BIO_new_fp(stdin
, 0);
755 ctx
= OSSL_STORE_attach(bio
, "file", libctx
, propq
,
756 get_ui_method(), &uidata
, NULL
, NULL
);
758 ctx
= OSSL_STORE_open_with_libctx(uri
, libctx
, propq
, get_ui_method(),
759 &uidata
, NULL
, NULL
);
762 BIO_printf(bio_err
, "Could not open file or uri %s for loading %s\n",
768 while (!OSSL_STORE_eof(ctx
)) {
769 OSSL_STORE_INFO
*info
= OSSL_STORE_load(ctx
);
770 int type
= info
== NULL
? 0 : OSSL_STORE_INFO_get_type(info
);
774 case OSSL_STORE_INFO_PKEY
:
775 if (ppkey
!= NULL
&& *ppkey
== NULL
)
776 ok
= (*ppkey
= OSSL_STORE_INFO_get1_PKEY(info
)) != NULL
;
779 * An EVP_PKEY with private parts also holds the public parts,
780 * so if the caller asked for a public key, and we got a private
781 * key, we can still pass it back.
783 if (ok
&& ppubkey
!= NULL
&& *ppubkey
== NULL
)
784 ok
= ((*ppubkey
= OSSL_STORE_INFO_get1_PKEY(info
)) != NULL
);
786 case OSSL_STORE_INFO_PUBKEY
:
787 if (ppubkey
!= NULL
&& *ppubkey
== NULL
)
788 ok
= ((*ppubkey
= OSSL_STORE_INFO_get1_PUBKEY(info
)) != NULL
);
790 case OSSL_STORE_INFO_CERT
:
791 if (pcert
!= NULL
&& *pcert
== NULL
)
792 ok
= (*pcert
= OSSL_STORE_INFO_get1_CERT(info
)) != NULL
;
793 else if (pcerts
!= NULL
)
794 ok
= X509_add_cert(*pcerts
,
795 OSSL_STORE_INFO_get1_CERT(info
),
796 X509_ADD_FLAG_DEFAULT
);
799 case OSSL_STORE_INFO_CRL
:
800 if (pcrl
!= NULL
&& *pcrl
== NULL
)
801 ok
= (*pcrl
= OSSL_STORE_INFO_get1_CRL(info
)) != NULL
;
802 else if (pcrls
!= NULL
)
803 ok
= sk_X509_CRL_push(*pcrls
, OSSL_STORE_INFO_get1_CRL(info
));
807 /* skip any other type */
810 OSSL_STORE_INFO_free(info
);
812 failed
= info
== NULL
? NULL
: OSSL_STORE_INFO_type_string(type
);
813 BIO_printf(bio_err
, "Error reading %s of %s from %s\n",
820 OSSL_STORE_close(ctx
);
821 if (failed
== NULL
) {
822 if (ppkey
!= NULL
&& *ppkey
== NULL
)
824 else if ((pcert
!= NULL
|| pcerts
!= NULL
) && ncerts
== 0)
826 else if ((pcrl
!= NULL
|| pcrls
!= NULL
) && ncrls
== 0)
829 BIO_printf(bio_err
, "Could not read any %s of %s from %s\n",
833 ERR_print_errors(bio_err
);
834 return failed
== NULL
;
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
, const 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
;
1088 OPENSSL_CTX
*libctx
= app_get0_libctx();
1089 const char *propq
= app_get0_propq();
1094 if (CAfile
!= NULL
|| !noCAfile
) {
1095 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_file());
1098 if (CAfile
!= NULL
) {
1099 if (!X509_LOOKUP_load_file_with_libctx(lookup
, CAfile
,
1102 BIO_printf(bio_err
, "Error loading file %s\n", CAfile
);
1106 X509_LOOKUP_load_file_with_libctx(lookup
, NULL
,
1107 X509_FILETYPE_DEFAULT
,
1112 if (CApath
!= NULL
|| !noCApath
) {
1113 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_hash_dir());
1116 if (CApath
!= NULL
) {
1117 if (!X509_LOOKUP_add_dir(lookup
, CApath
, X509_FILETYPE_PEM
)) {
1118 BIO_printf(bio_err
, "Error loading directory %s\n", CApath
);
1122 X509_LOOKUP_add_dir(lookup
, NULL
, X509_FILETYPE_DEFAULT
);
1126 if (CAstore
!= NULL
|| !noCAstore
) {
1127 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_store());
1130 if (!X509_LOOKUP_add_store_with_libctx(lookup
, CAstore
, libctx
, propq
)) {
1131 if (CAstore
!= NULL
)
1132 BIO_printf(bio_err
, "Error loading store URI %s\n", CAstore
);
1140 ERR_print_errors(bio_err
);
1141 X509_STORE_free(store
);
1145 #ifndef OPENSSL_NO_ENGINE
1146 /* Try to load an engine in a shareable library */
1147 static ENGINE
*try_load_engine(const char *engine
)
1149 ENGINE
*e
= ENGINE_by_id("dynamic");
1151 if (!ENGINE_ctrl_cmd_string(e
, "SO_PATH", engine
, 0)
1152 || !ENGINE_ctrl_cmd_string(e
, "LOAD", NULL
, 0)) {
1161 ENGINE
*setup_engine_methods(const char *id
, unsigned int methods
, int debug
)
1165 #ifndef OPENSSL_NO_ENGINE
1167 if (strcmp(id
, "auto") == 0) {
1168 BIO_printf(bio_err
, "Enabling auto ENGINE support\n");
1169 ENGINE_register_all_complete();
1172 if ((e
= ENGINE_by_id(id
)) == NULL
1173 && (e
= try_load_engine(id
)) == NULL
) {
1174 BIO_printf(bio_err
, "Invalid engine \"%s\"\n", id
);
1175 ERR_print_errors(bio_err
);
1179 (void)ENGINE_ctrl(e
, ENGINE_CTRL_SET_LOGSTREAM
, 0, bio_err
, 0);
1180 if (!ENGINE_ctrl_cmd(e
, "SET_USER_INTERFACE", 0,
1181 (void *)get_ui_method(), 0, 1)
1182 || !ENGINE_set_default(e
, methods
)) {
1183 BIO_printf(bio_err
, "Cannot use engine \"%s\"\n", ENGINE_get_id(e
));
1184 ERR_print_errors(bio_err
);
1189 BIO_printf(bio_err
, "Engine \"%s\" set.\n", ENGINE_get_id(e
));
1195 void release_engine(ENGINE
*e
)
1197 #ifndef OPENSSL_NO_ENGINE
1198 /* Free our "structural" reference. */
1203 static unsigned long index_serial_hash(const OPENSSL_CSTRING
*a
)
1210 return OPENSSL_LH_strhash(n
);
1213 static int index_serial_cmp(const OPENSSL_CSTRING
*a
,
1214 const OPENSSL_CSTRING
*b
)
1216 const char *aa
, *bb
;
1218 for (aa
= a
[DB_serial
]; *aa
== '0'; aa
++) ;
1219 for (bb
= b
[DB_serial
]; *bb
== '0'; bb
++) ;
1220 return strcmp(aa
, bb
);
1223 static int index_name_qual(char **a
)
1225 return (a
[0][0] == 'V');
1228 static unsigned long index_name_hash(const OPENSSL_CSTRING
*a
)
1230 return OPENSSL_LH_strhash(a
[DB_name
]);
1233 int index_name_cmp(const OPENSSL_CSTRING
*a
, const OPENSSL_CSTRING
*b
)
1235 return strcmp(a
[DB_name
], b
[DB_name
]);
1238 static IMPLEMENT_LHASH_HASH_FN(index_serial
, OPENSSL_CSTRING
)
1239 static IMPLEMENT_LHASH_COMP_FN(index_serial
, OPENSSL_CSTRING
)
1240 static IMPLEMENT_LHASH_HASH_FN(index_name
, OPENSSL_CSTRING
)
1241 static IMPLEMENT_LHASH_COMP_FN(index_name
, OPENSSL_CSTRING
)
1244 BIGNUM
*load_serial(const char *serialfile
, int create
, ASN1_INTEGER
**retai
)
1249 ASN1_INTEGER
*ai
= NULL
;
1251 ai
= ASN1_INTEGER_new();
1255 in
= BIO_new_file(serialfile
, "r");
1263 if (ret
== NULL
|| !rand_serial(ret
, ai
))
1264 BIO_printf(bio_err
, "Out of memory\n");
1266 if (!a2i_ASN1_INTEGER(in
, ai
, buf
, 1024)) {
1267 BIO_printf(bio_err
, "Unable to load number from %s\n",
1271 ret
= ASN1_INTEGER_to_BN(ai
, NULL
);
1273 BIO_printf(bio_err
, "Error converting number from bin to BIGNUM\n");
1283 ERR_print_errors(bio_err
);
1285 ASN1_INTEGER_free(ai
);
1289 int save_serial(const char *serialfile
, const char *suffix
, const BIGNUM
*serial
,
1290 ASN1_INTEGER
**retai
)
1295 ASN1_INTEGER
*ai
= NULL
;
1299 j
= strlen(serialfile
);
1301 j
= strlen(serialfile
) + strlen(suffix
) + 1;
1303 BIO_printf(bio_err
, "File name too long\n");
1308 OPENSSL_strlcpy(buf
[0], serialfile
, BSIZE
);
1310 #ifndef OPENSSL_SYS_VMS
1311 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, suffix
);
1313 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, suffix
);
1316 out
= BIO_new_file(buf
[0], "w");
1321 if ((ai
= BN_to_ASN1_INTEGER(serial
, NULL
)) == NULL
) {
1322 BIO_printf(bio_err
, "error converting serial to ASN.1 format\n");
1325 i2a_ASN1_INTEGER(out
, ai
);
1326 BIO_puts(out
, "\n");
1334 ERR_print_errors(bio_err
);
1336 ASN1_INTEGER_free(ai
);
1340 int rotate_serial(const char *serialfile
, const char *new_suffix
,
1341 const char *old_suffix
)
1346 i
= strlen(serialfile
) + strlen(old_suffix
);
1347 j
= strlen(serialfile
) + strlen(new_suffix
);
1350 if (j
+ 1 >= BSIZE
) {
1351 BIO_printf(bio_err
, "File name too long\n");
1354 #ifndef OPENSSL_SYS_VMS
1355 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, new_suffix
);
1356 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", serialfile
, old_suffix
);
1358 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, new_suffix
);
1359 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", serialfile
, old_suffix
);
1361 if (rename(serialfile
, buf
[1]) < 0 && errno
!= ENOENT
1367 "Unable to rename %s to %s\n", serialfile
, buf
[1]);
1371 if (rename(buf
[0], serialfile
) < 0) {
1373 "Unable to rename %s to %s\n", buf
[0], serialfile
);
1375 rename(buf
[1], serialfile
);
1380 ERR_print_errors(bio_err
);
1384 int rand_serial(BIGNUM
*b
, ASN1_INTEGER
*ai
)
1389 btmp
= b
== NULL
? BN_new() : b
;
1393 if (!BN_rand(btmp
, SERIAL_RAND_BITS
, BN_RAND_TOP_ANY
, BN_RAND_BOTTOM_ANY
))
1395 if (ai
&& !BN_to_ASN1_INTEGER(btmp
, ai
))
1408 CA_DB
*load_index(const char *dbfile
, DB_ATTR
*db_attr
)
1410 CA_DB
*retdb
= NULL
;
1411 TXT_DB
*tmpdb
= NULL
;
1413 CONF
*dbattr_conf
= NULL
;
1415 #ifndef OPENSSL_NO_POSIX_IO
1420 in
= BIO_new_file(dbfile
, "r");
1424 #ifndef OPENSSL_NO_POSIX_IO
1425 BIO_get_fp(in
, &dbfp
);
1426 if (fstat(fileno(dbfp
), &dbst
) == -1) {
1427 ERR_raise_data(ERR_LIB_SYS
, errno
,
1428 "calling fstat(%s)", dbfile
);
1433 if ((tmpdb
= TXT_DB_read(in
, DB_NUMBER
)) == NULL
)
1436 #ifndef OPENSSL_SYS_VMS
1437 BIO_snprintf(buf
, sizeof(buf
), "%s.attr", dbfile
);
1439 BIO_snprintf(buf
, sizeof(buf
), "%s-attr", dbfile
);
1441 dbattr_conf
= app_load_config_quiet(buf
);
1443 retdb
= app_malloc(sizeof(*retdb
), "new DB");
1447 retdb
->attributes
= *db_attr
;
1449 retdb
->attributes
.unique_subject
= 1;
1453 char *p
= NCONF_get_string(dbattr_conf
, NULL
, "unique_subject");
1455 retdb
->attributes
.unique_subject
= parse_yesno(p
, 1);
1459 retdb
->dbfname
= OPENSSL_strdup(dbfile
);
1460 #ifndef OPENSSL_NO_POSIX_IO
1465 ERR_print_errors(bio_err
);
1466 NCONF_free(dbattr_conf
);
1473 * Returns > 0 on success, <= 0 on error
1475 int index_index(CA_DB
*db
)
1477 if (!TXT_DB_create_index(db
->db
, DB_serial
, NULL
,
1478 LHASH_HASH_FN(index_serial
),
1479 LHASH_COMP_FN(index_serial
))) {
1481 "Error creating serial number index:(%ld,%ld,%ld)\n",
1482 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1486 if (db
->attributes
.unique_subject
1487 && !TXT_DB_create_index(db
->db
, DB_name
, index_name_qual
,
1488 LHASH_HASH_FN(index_name
),
1489 LHASH_COMP_FN(index_name
))) {
1490 BIO_printf(bio_err
, "Error creating name index:(%ld,%ld,%ld)\n",
1491 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1496 ERR_print_errors(bio_err
);
1500 int save_index(const char *dbfile
, const char *suffix
, CA_DB
*db
)
1506 j
= strlen(dbfile
) + strlen(suffix
);
1507 if (j
+ 6 >= BSIZE
) {
1508 BIO_printf(bio_err
, "File name too long\n");
1511 #ifndef OPENSSL_SYS_VMS
1512 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr", dbfile
);
1513 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.attr.%s", dbfile
, suffix
);
1514 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, suffix
);
1516 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr", dbfile
);
1517 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-attr-%s", dbfile
, suffix
);
1518 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, suffix
);
1520 out
= BIO_new_file(buf
[0], "w");
1523 BIO_printf(bio_err
, "Unable to open '%s'\n", dbfile
);
1526 j
= TXT_DB_write(out
, db
->db
);
1531 out
= BIO_new_file(buf
[1], "w");
1534 BIO_printf(bio_err
, "Unable to open '%s'\n", buf
[2]);
1537 BIO_printf(out
, "unique_subject = %s\n",
1538 db
->attributes
.unique_subject
? "yes" : "no");
1543 ERR_print_errors(bio_err
);
1547 int rotate_index(const char *dbfile
, const char *new_suffix
,
1548 const char *old_suffix
)
1553 i
= strlen(dbfile
) + strlen(old_suffix
);
1554 j
= strlen(dbfile
) + strlen(new_suffix
);
1557 if (j
+ 6 >= BSIZE
) {
1558 BIO_printf(bio_err
, "File name too long\n");
1561 #ifndef OPENSSL_SYS_VMS
1562 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s.attr", dbfile
);
1563 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s.attr.%s", dbfile
, old_suffix
);
1564 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr.%s", dbfile
, new_suffix
);
1565 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", dbfile
, old_suffix
);
1566 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, new_suffix
);
1568 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s-attr", dbfile
);
1569 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s-attr-%s", dbfile
, old_suffix
);
1570 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr-%s", dbfile
, new_suffix
);
1571 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", dbfile
, old_suffix
);
1572 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, new_suffix
);
1574 if (rename(dbfile
, buf
[1]) < 0 && errno
!= ENOENT
1579 BIO_printf(bio_err
, "Unable to rename %s to %s\n", dbfile
, buf
[1]);
1583 if (rename(buf
[0], dbfile
) < 0) {
1584 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[0], dbfile
);
1586 rename(buf
[1], dbfile
);
1589 if (rename(buf
[4], buf
[3]) < 0 && errno
!= ENOENT
1594 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[4], buf
[3]);
1596 rename(dbfile
, buf
[0]);
1597 rename(buf
[1], dbfile
);
1600 if (rename(buf
[2], buf
[4]) < 0) {
1601 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[2], buf
[4]);
1603 rename(buf
[3], buf
[4]);
1604 rename(dbfile
, buf
[0]);
1605 rename(buf
[1], dbfile
);
1610 ERR_print_errors(bio_err
);
1614 void free_index(CA_DB
*db
)
1617 TXT_DB_free(db
->db
);
1618 OPENSSL_free(db
->dbfname
);
1623 int parse_yesno(const char *str
, int def
)
1627 case 'f': /* false */
1628 case 'F': /* FALSE */
1633 case 't': /* true */
1634 case 'T': /* TRUE */
1645 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1646 * where + can be used instead of / to form multi-valued RDNs if canmulti
1647 * and characters may be escaped by \
1649 X509_NAME
*parse_name(const char *cp
, int chtype
, int canmulti
,
1652 int nextismulti
= 0;
1658 "%s: %s name is expected to be in the format "
1659 "/type0=value0/type1=value1/type2=... where characters may "
1660 "be escaped by \\. This name is not in that format: '%s'\n",
1661 opt_getprog(), desc
, --cp
);
1665 n
= X509_NAME_new();
1667 BIO_printf(bio_err
, "%s: Out of memory\n", opt_getprog());
1670 work
= OPENSSL_strdup(cp
);
1672 BIO_printf(bio_err
, "%s: Error copying %s name input\n",
1673 opt_getprog(), desc
);
1677 while (*cp
!= '\0') {
1680 unsigned char *valstr
;
1682 int ismulti
= nextismulti
;
1685 /* Collect the type */
1686 while (*cp
!= '\0' && *cp
!= '=')
1691 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1692 opt_getprog(), typestr
, desc
);
1697 /* Collect the value. */
1698 valstr
= (unsigned char *)bp
;
1699 for (; *cp
!= '\0' && *cp
!= '/'; *bp
++ = *cp
++) {
1700 /* unescaped '+' symbol string signals further member of multiRDN */
1701 if (canmulti
&& *cp
== '+') {
1705 if (*cp
== '\\' && *++cp
== '\0') {
1707 "%s: Escape character at end of %s name string\n",
1708 opt_getprog(), desc
);
1714 /* If not at EOS (must be + or /), move forward. */
1719 nid
= OBJ_txt2nid(typestr
);
1720 if (nid
== NID_undef
) {
1722 "%s: Skipping unknown %s name attribute \"%s\"\n",
1723 opt_getprog(), desc
, typestr
);
1726 "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
1729 if (*valstr
== '\0') {
1731 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1732 opt_getprog(), desc
, typestr
);
1735 if (!X509_NAME_add_entry_by_NID(n
, nid
, chtype
,
1736 valstr
, strlen((char *)valstr
),
1737 -1, ismulti
? -1 : 0)) {
1738 ERR_print_errors(bio_err
);
1740 "%s: Error adding %s name attribute \"/%s=%s\"\n",
1741 opt_getprog(), desc
, typestr
,valstr
);
1756 * Read whole contents of a BIO into an allocated memory buffer and return
1760 int bio_to_mem(unsigned char **out
, int maxlen
, BIO
*in
)
1764 unsigned char tbuf
[1024];
1766 mem
= BIO_new(BIO_s_mem());
1770 if ((maxlen
!= -1) && maxlen
< 1024)
1774 len
= BIO_read(in
, tbuf
, len
);
1781 if (BIO_write(mem
, tbuf
, len
) != len
) {
1790 ret
= BIO_get_mem_data(mem
, (char **)out
);
1791 BIO_set_flags(mem
, BIO_FLAGS_MEM_RDONLY
);
1796 int pkey_ctrl_string(EVP_PKEY_CTX
*ctx
, const char *value
)
1799 char *stmp
, *vtmp
= NULL
;
1800 stmp
= OPENSSL_strdup(value
);
1803 vtmp
= strchr(stmp
, ':');
1808 rv
= EVP_PKEY_CTX_ctrl_str(ctx
, stmp
, vtmp
);
1813 static void nodes_print(const char *name
, STACK_OF(X509_POLICY_NODE
) *nodes
)
1815 X509_POLICY_NODE
*node
;
1818 BIO_printf(bio_err
, "%s Policies:", name
);
1820 BIO_puts(bio_err
, "\n");
1821 for (i
= 0; i
< sk_X509_POLICY_NODE_num(nodes
); i
++) {
1822 node
= sk_X509_POLICY_NODE_value(nodes
, i
);
1823 X509_POLICY_NODE_print(bio_err
, node
, 2);
1826 BIO_puts(bio_err
, " <empty>\n");
1830 void policies_print(X509_STORE_CTX
*ctx
)
1832 X509_POLICY_TREE
*tree
;
1833 int explicit_policy
;
1834 tree
= X509_STORE_CTX_get0_policy_tree(ctx
);
1835 explicit_policy
= X509_STORE_CTX_get_explicit_policy(ctx
);
1837 BIO_printf(bio_err
, "Require explicit Policy: %s\n",
1838 explicit_policy
? "True" : "False");
1840 nodes_print("Authority", X509_policy_tree_get0_policies(tree
));
1841 nodes_print("User", X509_policy_tree_get0_user_policies(tree
));
1845 * next_protos_parse parses a comma separated list of strings into a string
1846 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1847 * outlen: (output) set to the length of the resulting buffer on success.
1848 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1849 * in: a NUL terminated string like "abc,def,ghi"
1851 * returns: a malloc'd buffer or NULL on failure.
1853 unsigned char *next_protos_parse(size_t *outlen
, const char *in
)
1857 size_t i
, start
= 0;
1861 if (len
== 0 || len
>= 65535)
1864 out
= app_malloc(len
+ 1, "NPN buffer");
1865 for (i
= 0; i
<= len
; ++i
) {
1866 if (i
== len
|| in
[i
] == ',') {
1868 * Zero-length ALPN elements are invalid on the wire, we could be
1869 * strict and reject the entire string, but just ignoring extra
1870 * commas seems harmless and more friendly.
1872 * Every comma we skip in this way puts the input buffer another
1873 * byte ahead of the output buffer, so all stores into the output
1874 * buffer need to be decremented by the number commas skipped.
1881 if (i
- start
> 255) {
1885 out
[start
-skipped
] = (unsigned char)(i
- start
);
1888 out
[i
+ 1 - skipped
] = in
[i
];
1892 if (len
<= skipped
) {
1897 *outlen
= len
+ 1 - skipped
;
1901 void print_cert_checks(BIO
*bio
, X509
*x
,
1902 const char *checkhost
,
1903 const char *checkemail
, const char *checkip
)
1908 BIO_printf(bio
, "Hostname %s does%s match certificate\n",
1910 X509_check_host(x
, checkhost
, 0, 0, NULL
) == 1
1915 BIO_printf(bio
, "Email %s does%s match certificate\n",
1916 checkemail
, X509_check_email(x
, checkemail
, 0, 0)
1921 BIO_printf(bio
, "IP %s does%s match certificate\n",
1922 checkip
, X509_check_ip_asc(x
, checkip
, 0) ? "" : " NOT");
1926 /* Get first http URL from a DIST_POINT structure */
1928 static const char *get_dp_url(DIST_POINT
*dp
)
1930 GENERAL_NAMES
*gens
;
1934 if (!dp
->distpoint
|| dp
->distpoint
->type
!= 0)
1936 gens
= dp
->distpoint
->name
.fullname
;
1937 for (i
= 0; i
< sk_GENERAL_NAME_num(gens
); i
++) {
1938 gen
= sk_GENERAL_NAME_value(gens
, i
);
1939 uri
= GENERAL_NAME_get0_value(gen
, >ype
);
1940 if (gtype
== GEN_URI
&& ASN1_STRING_length(uri
) > 6) {
1941 const char *uptr
= (const char *)ASN1_STRING_get0_data(uri
);
1942 if (strncmp(uptr
, "http://", 7) == 0)
1950 * Look through a CRLDP structure and attempt to find an http URL to
1951 * downloads a CRL from.
1954 static X509_CRL
*load_crl_crldp(STACK_OF(DIST_POINT
) *crldp
)
1957 const char *urlptr
= NULL
;
1958 for (i
= 0; i
< sk_DIST_POINT_num(crldp
); i
++) {
1959 DIST_POINT
*dp
= sk_DIST_POINT_value(crldp
, i
);
1960 urlptr
= get_dp_url(dp
);
1962 return load_crl(urlptr
, FORMAT_HTTP
, "CRL via CDP");
1968 * Example of downloading CRLs from CRLDP:
1969 * not usable for real world as it always downloads and doesn't cache anything.
1972 static STACK_OF(X509_CRL
) *crls_http_cb(const X509_STORE_CTX
*ctx
,
1973 const X509_NAME
*nm
)
1976 STACK_OF(X509_CRL
) *crls
= NULL
;
1978 STACK_OF(DIST_POINT
) *crldp
;
1980 crls
= sk_X509_CRL_new_null();
1983 x
= X509_STORE_CTX_get_current_cert(ctx
);
1984 crldp
= X509_get_ext_d2i(x
, NID_crl_distribution_points
, NULL
, NULL
);
1985 crl
= load_crl_crldp(crldp
);
1986 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
1988 sk_X509_CRL_free(crls
);
1991 sk_X509_CRL_push(crls
, crl
);
1992 /* Try to download delta CRL */
1993 crldp
= X509_get_ext_d2i(x
, NID_freshest_crl
, NULL
, NULL
);
1994 crl
= load_crl_crldp(crldp
);
1995 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
1997 sk_X509_CRL_push(crls
, crl
);
2001 void store_setup_crl_download(X509_STORE
*st
)
2003 X509_STORE_set_lookup_crls_cb(st
, crls_http_cb
);
2006 #ifndef OPENSSL_NO_SOCK
2007 static const char *tls_error_hint(void)
2009 unsigned long err
= ERR_peek_error();
2011 if (ERR_GET_LIB(err
) != ERR_LIB_SSL
)
2012 err
= ERR_peek_last_error();
2013 if (ERR_GET_LIB(err
) != ERR_LIB_SSL
)
2016 switch (ERR_GET_REASON(err
)) {
2017 case SSL_R_WRONG_VERSION_NUMBER
:
2018 return "The server does not support (a suitable version of) TLS";
2019 case SSL_R_UNKNOWN_PROTOCOL
:
2020 return "The server does not support HTTPS";
2021 case SSL_R_CERTIFICATE_VERIFY_FAILED
:
2022 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2023 case SSL_AD_REASON_OFFSET
+ TLS1_AD_UNKNOWN_CA
:
2024 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2025 case SSL_AD_REASON_OFFSET
+ SSL3_AD_HANDSHAKE_FAILURE
:
2026 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2027 default: /* no error or no hint available for error */
2032 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
2033 BIO
*app_http_tls_cb(BIO
*hbio
, void *arg
, int connect
, int detail
)
2035 APP_HTTP_TLS_INFO
*info
= (APP_HTTP_TLS_INFO
*)arg
;
2036 SSL_CTX
*ssl_ctx
= info
->ssl_ctx
;
2040 if (connect
&& detail
) { /* connecting with TLS */
2041 if ((info
->use_proxy
2042 && !OSSL_HTTP_proxy_connect(hbio
, info
->server
, info
->port
,
2043 NULL
, NULL
, /* no proxy credentials */
2044 info
->timeout
, bio_err
, opt_getprog()))
2045 || (sbio
= BIO_new(BIO_f_ssl())) == NULL
) {
2048 if (ssl_ctx
== NULL
|| (ssl
= SSL_new(ssl_ctx
)) == NULL
) {
2053 SSL_set_tlsext_host_name(ssl
, info
->server
);
2055 SSL_set_connect_state(ssl
);
2056 BIO_set_ssl(sbio
, ssl
, BIO_CLOSE
);
2058 hbio
= BIO_push(sbio
, hbio
);
2059 } else if (!connect
&& !detail
) { /* disconnecting after error */
2060 const char *hint
= tls_error_hint();
2062 ERR_add_error_data(2, " : ", hint
);
2064 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2065 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2071 ASN1_VALUE
*app_http_get_asn1(const char *url
, const char *proxy
,
2072 const char *no_proxy
, SSL_CTX
*ssl_ctx
,
2073 const STACK_OF(CONF_VALUE
) *headers
,
2074 long timeout
, const char *expected_content_type
,
2075 const ASN1_ITEM
*it
)
2077 APP_HTTP_TLS_INFO info
;
2081 ASN1_VALUE
*resp
= NULL
;
2083 if (url
== NULL
|| it
== NULL
) {
2084 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER
);
2088 if (!OSSL_HTTP_parse_url(url
, &server
, &port
, NULL
, NULL
, &use_ssl
))
2090 if (use_ssl
&& ssl_ctx
== NULL
) {
2091 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER
);
2092 ERR_add_error_data(1, "missing SSL_CTX");
2096 info
.server
= server
;
2098 info
.use_proxy
= proxy
!= NULL
;
2099 info
.timeout
= timeout
;
2100 info
.ssl_ctx
= ssl_ctx
;
2101 resp
= OSSL_HTTP_get_asn1(url
, proxy
, no_proxy
,
2102 NULL
, NULL
, app_http_tls_cb
, &info
,
2103 headers
, 0 /* maxline */, 0 /* max_resp_len */,
2104 timeout
, expected_content_type
, it
);
2106 OPENSSL_free(server
);
2112 ASN1_VALUE
*app_http_post_asn1(const char *host
, const char *port
,
2113 const char *path
, const char *proxy
,
2114 const char *no_proxy
, SSL_CTX
*ssl_ctx
,
2115 const STACK_OF(CONF_VALUE
) *headers
,
2116 const char *content_type
,
2117 ASN1_VALUE
*req
, const ASN1_ITEM
*req_it
,
2118 long timeout
, const ASN1_ITEM
*rsp_it
)
2120 APP_HTTP_TLS_INFO info
;
2124 info
.use_proxy
= proxy
!= NULL
;
2125 info
.timeout
= timeout
;
2126 info
.ssl_ctx
= ssl_ctx
;
2127 return OSSL_HTTP_post_asn1(host
, port
, path
, ssl_ctx
!= NULL
,
2129 NULL
, NULL
, app_http_tls_cb
, &info
,
2130 headers
, content_type
, req
, req_it
,
2132 0 /* max_resp_len */, timeout
, NULL
, rsp_it
);
2138 * Platform-specific sections
2143 # define fileno(a) (int)_fileno(a)
2146 # include <windows.h>
2149 static int WIN32_rename(const char *from
, const char *to
)
2151 TCHAR
*tfrom
= NULL
, *tto
;
2155 if (sizeof(TCHAR
) == 1) {
2156 tfrom
= (TCHAR
*)from
;
2158 } else { /* UNICODE path */
2160 size_t i
, flen
= strlen(from
) + 1, tlen
= strlen(to
) + 1;
2161 tfrom
= malloc(sizeof(*tfrom
) * (flen
+ tlen
));
2165 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2166 if (!MultiByteToWideChar(CP_ACP
, 0, from
, flen
, (WCHAR
*)tfrom
, flen
))
2168 for (i
= 0; i
< flen
; i
++)
2169 tfrom
[i
] = (TCHAR
)from
[i
];
2170 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2171 if (!MultiByteToWideChar(CP_ACP
, 0, to
, tlen
, (WCHAR
*)tto
, tlen
))
2173 for (i
= 0; i
< tlen
; i
++)
2174 tto
[i
] = (TCHAR
)to
[i
];
2177 if (MoveFile(tfrom
, tto
))
2179 err
= GetLastError();
2180 if (err
== ERROR_ALREADY_EXISTS
|| err
== ERROR_FILE_EXISTS
) {
2181 if (DeleteFile(tto
) && MoveFile(tfrom
, tto
))
2183 err
= GetLastError();
2185 if (err
== ERROR_FILE_NOT_FOUND
|| err
== ERROR_PATH_NOT_FOUND
)
2187 else if (err
== ERROR_ACCESS_DENIED
)
2190 errno
= EINVAL
; /* we could map more codes... */
2194 if (tfrom
!= NULL
&& tfrom
!= (TCHAR
*)from
)
2200 /* app_tminterval section */
2202 double app_tminterval(int stop
, int usertime
)
2206 static ULARGE_INTEGER tmstart
;
2207 static int warning
= 1;
2208 # ifdef _WIN32_WINNT
2209 static HANDLE proc
= NULL
;
2213 proc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
,
2214 GetCurrentProcessId());
2216 proc
= (HANDLE
) - 1;
2219 if (usertime
&& proc
!= (HANDLE
) - 1) {
2221 GetProcessTimes(proc
, &junk
, &junk
, &junk
, &now
);
2227 if (usertime
&& warning
) {
2228 BIO_printf(bio_err
, "To get meaningful results, run "
2229 "this program on idle system.\n");
2232 GetSystemTime(&systime
);
2233 SystemTimeToFileTime(&systime
, &now
);
2236 if (stop
== TM_START
) {
2237 tmstart
.u
.LowPart
= now
.dwLowDateTime
;
2238 tmstart
.u
.HighPart
= now
.dwHighDateTime
;
2240 ULARGE_INTEGER tmstop
;
2242 tmstop
.u
.LowPart
= now
.dwLowDateTime
;
2243 tmstop
.u
.HighPart
= now
.dwHighDateTime
;
2245 ret
= (__int64
)(tmstop
.QuadPart
- tmstart
.QuadPart
) * 1e-7;
2250 #elif defined(OPENSSL_SYS_VXWORKS)
2253 double app_tminterval(int stop
, int usertime
)
2256 # ifdef CLOCK_REALTIME
2257 static struct timespec tmstart
;
2258 struct timespec now
;
2260 static unsigned long tmstart
;
2263 static int warning
= 1;
2265 if (usertime
&& warning
) {
2266 BIO_printf(bio_err
, "To get meaningful results, run "
2267 "this program on idle system.\n");
2270 # ifdef CLOCK_REALTIME
2271 clock_gettime(CLOCK_REALTIME
, &now
);
2272 if (stop
== TM_START
)
2275 ret
= ((now
.tv_sec
+ now
.tv_nsec
* 1e-9)
2276 - (tmstart
.tv_sec
+ tmstart
.tv_nsec
* 1e-9));
2279 if (stop
== TM_START
)
2282 ret
= (now
- tmstart
) / (double)sysClkRateGet();
2287 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2288 # include <sys/times.h>
2290 double app_tminterval(int stop
, int usertime
)
2294 clock_t now
= times(&rus
);
2295 static clock_t tmstart
;
2298 now
= rus
.tms_utime
;
2300 if (stop
== TM_START
) {
2303 long int tck
= sysconf(_SC_CLK_TCK
);
2304 ret
= (now
- tmstart
) / (double)tck
;
2311 # include <sys/time.h>
2312 # include <sys/resource.h>
2314 double app_tminterval(int stop
, int usertime
)
2319 static struct timeval tmstart
;
2322 getrusage(RUSAGE_SELF
, &rus
), now
= rus
.ru_utime
;
2324 gettimeofday(&now
, NULL
);
2326 if (stop
== TM_START
)
2329 ret
= ((now
.tv_sec
+ now
.tv_usec
* 1e-6)
2330 - (tmstart
.tv_sec
+ tmstart
.tv_usec
* 1e-6));
2336 int app_access(const char* name
, int flag
)
2339 return _access(name
, flag
);
2341 return access(name
, flag
);
2345 int app_isdir(const char *name
)
2347 return opt_isdir(name
);
2350 /* raw_read|write section */
2352 # include "vms_term_sock.h"
2353 static int stdin_sock
= -1;
2355 static void close_stdin_sock(void)
2357 TerminalSocket (TERM_SOCK_DELETE
, &stdin_sock
);
2360 int fileno_stdin(void)
2362 if (stdin_sock
== -1) {
2363 TerminalSocket(TERM_SOCK_CREATE
, &stdin_sock
);
2364 atexit(close_stdin_sock
);
2370 int fileno_stdin(void)
2372 return fileno(stdin
);
2376 int fileno_stdout(void)
2378 return fileno(stdout
);
2381 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2382 int raw_read_stdin(void *buf
, int siz
)
2385 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2390 #elif defined(__VMS)
2391 # include <sys/socket.h>
2393 int raw_read_stdin(void *buf
, int siz
)
2395 return recv(fileno_stdin(), buf
, siz
, 0);
2398 # if defined(__TANDEM)
2399 # if defined(OPENSSL_TANDEM_FLOSS)
2400 # include <floss.h(floss_read)>
2403 int raw_read_stdin(void *buf
, int siz
)
2405 return read(fileno_stdin(), buf
, siz
);
2409 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2410 int raw_write_stdout(const void *buf
, int siz
)
2413 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2418 #elif defined(OPENSSL_SYSNAME_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
2419 # if defined(__TANDEM)
2420 # if defined(OPENSSL_TANDEM_FLOSS)
2421 # include <floss.h(floss_write)>
2424 int raw_write_stdout(const void *buf
,int siz
)
2426 return write(fileno(stdout
),(void*)buf
,siz
);
2429 # if defined(__TANDEM)
2430 # if defined(OPENSSL_TANDEM_FLOSS)
2431 # include <floss.h(floss_write)>
2434 int raw_write_stdout(const void *buf
, int siz
)
2436 return write(fileno_stdout(), buf
, siz
);
2441 * Centralized handling of input and output files with format specification
2442 * The format is meant to show what the input and output is supposed to be,
2443 * and is therefore a show of intent more than anything else. However, it
2444 * does impact behavior on some platforms, such as differentiating between
2445 * text and binary input/output on non-Unix platforms
2447 BIO
*dup_bio_in(int format
)
2449 return BIO_new_fp(stdin
,
2450 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2453 BIO
*dup_bio_out(int format
)
2455 BIO
*b
= BIO_new_fp(stdout
,
2456 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2457 void *prefix
= NULL
;
2459 #ifdef OPENSSL_SYS_VMS
2460 if (FMT_istext(format
))
2461 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2464 if (FMT_istext(format
)
2465 && (prefix
= getenv("HARNESS_OSSL_PREFIX")) != NULL
) {
2466 b
= BIO_push(BIO_new(BIO_f_prefix()), b
);
2467 BIO_set_prefix(b
, prefix
);
2473 BIO
*dup_bio_err(int format
)
2475 BIO
*b
= BIO_new_fp(stderr
,
2476 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2477 #ifdef OPENSSL_SYS_VMS
2478 if (FMT_istext(format
))
2479 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2484 void unbuffer(FILE *fp
)
2487 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2488 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2489 * However, we trust that the C RTL will never give us a FILE pointer
2490 * above the first 4 GB of memory, so we simply turn off the warning
2493 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2494 # pragma environment save
2495 # pragma message disable maylosedata2
2498 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2499 # pragma environment restore
2503 static const char *modestr(char mode
, int format
)
2505 OPENSSL_assert(mode
== 'a' || mode
== 'r' || mode
== 'w');
2509 return FMT_istext(format
) ? "a" : "ab";
2511 return FMT_istext(format
) ? "r" : "rb";
2513 return FMT_istext(format
) ? "w" : "wb";
2515 /* The assert above should make sure we never reach this point */
2519 static const char *modeverb(char mode
)
2529 return "(doing something)";
2533 * Open a file for writing, owner-read-only.
2535 BIO
*bio_open_owner(const char *filename
, int format
, int private)
2539 int fd
= -1, bflags
, mode
, textmode
;
2541 if (!private || filename
== NULL
|| strcmp(filename
, "-") == 0)
2542 return bio_open_default(filename
, 'w', format
);
2551 textmode
= FMT_istext(format
);
2555 #elif defined(_O_BINARY)
2560 #ifdef OPENSSL_SYS_VMS
2561 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2562 * it still needs to know that we're going binary, or fdopen()
2563 * will fail with "invalid argument"... so we tell VMS what the
2567 fd
= open(filename
, mode
, 0600, "ctx=bin");
2570 fd
= open(filename
, mode
, 0600);
2573 fp
= fdopen(fd
, modestr('w', format
));
2578 bflags
|= BIO_FP_TEXT
;
2579 b
= BIO_new_fp(fp
, bflags
);
2584 BIO_printf(bio_err
, "%s: Can't open \"%s\" for writing, %s\n",
2585 opt_getprog(), filename
, strerror(errno
));
2586 ERR_print_errors(bio_err
);
2587 /* If we have fp, then fdopen took over fd, so don't close both. */
2595 static BIO
*bio_open_default_(const char *filename
, char mode
, int format
,
2600 if (filename
== NULL
|| strcmp(filename
, "-") == 0) {
2601 ret
= mode
== 'r' ? dup_bio_in(format
) : dup_bio_out(format
);
2609 "Can't open %s, %s\n",
2610 mode
== 'r' ? "stdin" : "stdout", strerror(errno
));
2612 ret
= BIO_new_file(filename
, modestr(mode
, format
));
2620 "Can't open %s for %s, %s\n",
2621 filename
, modeverb(mode
), strerror(errno
));
2623 ERR_print_errors(bio_err
);
2627 BIO
*bio_open_default(const char *filename
, char mode
, int format
)
2629 return bio_open_default_(filename
, mode
, format
, 0);
2632 BIO
*bio_open_default_quiet(const char *filename
, char mode
, int format
)
2634 return bio_open_default_(filename
, mode
, format
, 1);
2637 void wait_for_async(SSL
*s
)
2639 /* On Windows select only works for sockets, so we simply don't wait */
2640 #ifndef OPENSSL_SYS_WINDOWS
2647 if (!SSL_get_all_async_fds(s
, NULL
, &numfds
))
2651 fds
= app_malloc(sizeof(OSSL_ASYNC_FD
) * numfds
, "allocate async fds");
2652 if (!SSL_get_all_async_fds(s
, fds
, &numfds
)) {
2658 for (i
= 0; i
< numfds
; i
++) {
2659 if (width
<= (int)fds
[i
])
2660 width
= (int)fds
[i
] + 1;
2661 openssl_fdset((int)fds
[i
], &asyncfds
);
2663 select(width
, (void *)&asyncfds
, NULL
, NULL
, NULL
);
2668 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2669 #if defined(OPENSSL_SYS_MSDOS)
2670 int has_stdin_waiting(void)
2672 # if defined(OPENSSL_SYS_WINDOWS)
2673 HANDLE inhand
= GetStdHandle(STD_INPUT_HANDLE
);
2675 INPUT_RECORD inputrec
;
2679 if (inhand
== INVALID_HANDLE_VALUE
) {
2683 peeked
= PeekConsoleInput(inhand
, &inputrec
, insize
, &events
);
2685 /* Probably redirected input? _kbhit() does not work in this case */
2696 /* Corrupt a signature by modifying final byte */
2697 void corrupt_signature(const ASN1_STRING
*signature
)
2699 unsigned char *s
= signature
->data
;
2700 s
[signature
->length
- 1] ^= 0x1;
2703 int set_cert_times(X509
*x
, const char *startdate
, const char *enddate
,
2706 if (startdate
== NULL
|| strcmp(startdate
, "today") == 0) {
2707 if (X509_gmtime_adj(X509_getm_notBefore(x
), 0) == NULL
)
2710 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x
), startdate
))
2713 if (enddate
== NULL
) {
2714 if (X509_time_adj_ex(X509_getm_notAfter(x
), days
, 0, NULL
)
2717 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x
), enddate
)) {
2723 int set_crl_lastupdate(X509_CRL
*crl
, const char *lastupdate
)
2726 ASN1_TIME
*tm
= ASN1_TIME_new();
2731 if (lastupdate
== NULL
) {
2732 if (X509_gmtime_adj(tm
, 0) == NULL
)
2735 if (!ASN1_TIME_set_string_X509(tm
, lastupdate
))
2739 if (!X509_CRL_set1_lastUpdate(crl
, tm
))
2748 int set_crl_nextupdate(X509_CRL
*crl
, const char *nextupdate
,
2749 long days
, long hours
, long secs
)
2752 ASN1_TIME
*tm
= ASN1_TIME_new();
2757 if (nextupdate
== NULL
) {
2758 if (X509_time_adj_ex(tm
, days
, hours
* 60 * 60 + secs
, NULL
) == NULL
)
2761 if (!ASN1_TIME_set_string_X509(tm
, nextupdate
))
2765 if (!X509_CRL_set1_nextUpdate(crl
, tm
))
2774 void make_uppercase(char *string
)
2778 for (i
= 0; string
[i
] != '\0'; i
++)
2779 string
[i
] = toupper((unsigned char)string
[i
]);
2782 int opt_printf_stderr(const char *fmt
, ...)
2788 ret
= BIO_vprintf(bio_err
, fmt
, ap
);
2793 OSSL_PARAM
*app_params_new_from_opts(STACK_OF(OPENSSL_STRING
) *opts
,
2794 const OSSL_PARAM
*paramdefs
)
2796 OSSL_PARAM
*params
= NULL
;
2797 size_t sz
= (size_t)sk_OPENSSL_STRING_num(opts
);
2799 char *opt
= "", *stmp
, *vtmp
= NULL
;
2805 params
= OPENSSL_zalloc(sizeof(OSSL_PARAM
) * (sz
+ 1));
2809 for (params_n
= 0; params_n
< sz
; params_n
++) {
2810 opt
= sk_OPENSSL_STRING_value(opts
, (int)params_n
);
2811 if ((stmp
= OPENSSL_strdup(opt
)) == NULL
2812 || (vtmp
= strchr(stmp
, ':')) == NULL
)
2814 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2816 /* Skip over the separator so that vmtp points to the value */
2818 if (!OSSL_PARAM_allocate_from_text(¶ms
[params_n
], paramdefs
,
2819 stmp
, vtmp
, strlen(vtmp
), &found
))
2823 params
[params_n
] = OSSL_PARAM_construct_end();
2827 BIO_printf(bio_err
, "Parameter %s '%s'\n", found
? "error" : "unknown",
2829 ERR_print_errors(bio_err
);
2830 app_params_free(params
);
2834 void app_params_free(OSSL_PARAM
*params
)
2838 if (params
!= NULL
) {
2839 for (i
= 0; params
[i
].key
!= NULL
; ++i
)
2840 OPENSSL_free(params
[i
].data
);
2841 OPENSSL_free(params
);