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
)
73 static OPENSSL_CTX
*app_libctx
= NULL
;
75 static int set_table_opts(unsigned long *flags
, const char *arg
,
76 const NAME_EX_TBL
* in_tbl
);
77 static int set_multi_opts(unsigned long *flags
, const char *arg
,
78 const NAME_EX_TBL
* in_tbl
);
80 int app_init(long mesgwin
);
82 int chopup_args(ARGS
*arg
, char *buf
)
85 char c
= '\0', *p
= NULL
;
90 arg
->argv
= app_malloc(sizeof(*arg
->argv
) * arg
->size
, "argv space");
94 /* Skip whitespace. */
95 while (*p
&& isspace(_UC(*p
)))
100 /* The start of something good :-) */
101 if (arg
->argc
>= arg
->size
) {
104 tmp
= OPENSSL_realloc(arg
->argv
, sizeof(*arg
->argv
) * arg
->size
);
109 quoted
= *p
== '\'' || *p
== '"';
112 arg
->argv
[arg
->argc
++] = p
;
114 /* now look for the end of this */
116 while (*p
&& *p
!= c
)
120 while (*p
&& !isspace(_UC(*p
)))
126 arg
->argv
[arg
->argc
] = NULL
;
131 int app_init(long mesgwin
)
137 int ctx_set_verify_locations(SSL_CTX
*ctx
,
138 const char *CAfile
, int noCAfile
,
139 const char *CApath
, int noCApath
,
140 const char *CAstore
, int noCAstore
)
142 if (CAfile
== NULL
&& CApath
== NULL
&& CAstore
== NULL
) {
143 if (!noCAfile
&& SSL_CTX_set_default_verify_file(ctx
) <= 0)
145 if (!noCApath
&& SSL_CTX_set_default_verify_dir(ctx
) <= 0)
147 if (!noCAstore
&& SSL_CTX_set_default_verify_store(ctx
) <= 0)
153 if (CAfile
!= NULL
&& !SSL_CTX_load_verify_file(ctx
, CAfile
))
155 if (CApath
!= NULL
&& !SSL_CTX_load_verify_dir(ctx
, CApath
))
157 if (CAstore
!= NULL
&& !SSL_CTX_load_verify_store(ctx
, CAstore
))
162 #ifndef OPENSSL_NO_CT
164 int ctx_set_ctlog_list_file(SSL_CTX
*ctx
, const char *path
)
167 return SSL_CTX_set_default_ctlog_list_file(ctx
);
169 return SSL_CTX_set_ctlog_list_file(ctx
, path
);
174 static unsigned long nmflag
= 0;
175 static char nmflag_set
= 0;
177 int set_nameopt(const char *arg
)
179 int ret
= set_name_ex(&nmflag
, arg
);
187 unsigned long get_nameopt(void)
189 return (nmflag_set
) ? nmflag
: XN_FLAG_ONELINE
;
192 int dump_cert_text(BIO
*out
, X509
*x
)
194 print_name(out
, "subject=", X509_get_subject_name(x
), get_nameopt());
196 print_name(out
, "issuer=", X509_get_issuer_name(x
), get_nameopt());
202 int wrap_password_callback(char *buf
, int bufsiz
, int verify
, void *userdata
)
204 return password_callback(buf
, bufsiz
, verify
, (PW_CB_DATA
*)userdata
);
208 static char *app_get_pass(const char *arg
, int keepbio
);
210 char *get_passwd(const char *pass
, const char *desc
)
216 if (!app_passwd(pass
, NULL
, &result
, NULL
))
217 BIO_printf(bio_err
, "Error getting password for %s\n", desc
);
218 if (pass
!= NULL
&& result
== NULL
) {
220 "Trying plain input string (better precede with 'pass:')\n");
221 result
= OPENSSL_strdup(pass
);
223 BIO_printf(bio_err
, "Out of memory getting password for %s\n", desc
);
228 int app_passwd(const char *arg1
, const char *arg2
, char **pass1
, char **pass2
)
230 int same
= arg1
!= NULL
&& arg2
!= NULL
&& strcmp(arg1
, arg2
) == 0;
233 *pass1
= app_get_pass(arg1
, same
);
236 } else if (pass1
!= NULL
) {
240 *pass2
= app_get_pass(arg2
, same
? 2 : 0);
243 } else if (pass2
!= NULL
) {
249 static char *app_get_pass(const char *arg
, int keepbio
)
251 static BIO
*pwdbio
= NULL
;
252 char *tmp
, tpass
[APP_PASS_LEN
];
255 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
256 if (strncmp(arg
, "pass:", 5) == 0)
257 return OPENSSL_strdup(arg
+ 5);
258 if (strncmp(arg
, "env:", 4) == 0) {
259 tmp
= getenv(arg
+ 4);
261 BIO_printf(bio_err
, "No environment variable %s\n", arg
+ 4);
264 return OPENSSL_strdup(tmp
);
266 if (!keepbio
|| pwdbio
== NULL
) {
267 if (strncmp(arg
, "file:", 5) == 0) {
268 pwdbio
= BIO_new_file(arg
+ 5, "r");
269 if (pwdbio
== NULL
) {
270 BIO_printf(bio_err
, "Can't open file %s\n", arg
+ 5);
275 * Under _WIN32, which covers even Win64 and CE, file
276 * descriptors referenced by BIO_s_fd are not inherited
277 * by child process and therefore below is not an option.
278 * It could have been an option if bss_fd.c was operating
279 * on real Windows descriptors, such as those obtained
282 } else if (strncmp(arg
, "fd:", 3) == 0) {
286 pwdbio
= BIO_new_fd(i
, BIO_NOCLOSE
);
287 if ((i
< 0) || !pwdbio
) {
288 BIO_printf(bio_err
, "Can't access file descriptor %s\n", arg
+ 3);
292 * Can't do BIO_gets on an fd BIO so add a buffering BIO
294 btmp
= BIO_new(BIO_f_buffer());
295 pwdbio
= BIO_push(btmp
, pwdbio
);
297 } else if (strcmp(arg
, "stdin") == 0) {
298 pwdbio
= dup_bio_in(FORMAT_TEXT
);
299 if (pwdbio
== NULL
) {
300 BIO_printf(bio_err
, "Can't open BIO for stdin\n");
304 /* argument syntax error; do not reveal too much about arg */
305 tmp
= strchr(arg
, ':');
306 if (tmp
== NULL
|| tmp
- arg
> PASS_SOURCE_SIZE_MAX
)
308 "Invalid password argument, missing ':' within the first %d chars\n",
309 PASS_SOURCE_SIZE_MAX
+ 1);
312 "Invalid password argument, starting with \"%.*s\"\n",
313 (int)(tmp
- arg
+ 1), arg
);
317 i
= BIO_gets(pwdbio
, tpass
, APP_PASS_LEN
);
319 BIO_free_all(pwdbio
);
323 BIO_printf(bio_err
, "Error reading password from BIO\n");
326 tmp
= strchr(tpass
, '\n');
329 return OPENSSL_strdup(tpass
);
332 OPENSSL_CTX
*app_get0_libctx(void)
337 /* TODO(3.0): Make this an environment variable if required */
338 const char *app_get0_propq(void)
343 OPENSSL_CTX
*app_create_libctx(void)
346 * Load the NULL provider into the default library context and create a
347 * library context which will then be used for any OPT_PROV options.
349 if (app_libctx
== NULL
) {
351 if (!app_provider_load(NULL
, "null")) {
352 BIO_puts(bio_err
, "Failed to create null provider\n");
355 app_libctx
= OPENSSL_CTX_new();
357 if (app_libctx
== NULL
)
358 BIO_puts(bio_err
, "Failed to create library context\n");
362 CONF
*app_load_config_bio(BIO
*in
, const char *filename
)
368 conf
= NCONF_new_with_libctx(app_libctx
, NULL
);
369 i
= NCONF_load_bio(conf
, in
, &errorline
);
373 if (errorline
<= 0) {
374 BIO_printf(bio_err
, "%s: Can't load ", opt_getprog());
376 BIO_printf(bio_err
, "%s: Error on line %ld of ", opt_getprog(),
379 if (filename
!= NULL
)
380 BIO_printf(bio_err
, "config file \"%s\"\n", filename
);
382 BIO_printf(bio_err
, "config input");
388 CONF
*app_load_config(const char *filename
)
393 in
= bio_open_default(filename
, 'r', FORMAT_TEXT
);
397 conf
= app_load_config_bio(in
, filename
);
402 CONF
*app_load_config_quiet(const char *filename
)
407 in
= bio_open_default_quiet(filename
, 'r', FORMAT_TEXT
);
411 conf
= app_load_config_bio(in
, filename
);
416 int app_load_modules(const CONF
*config
)
418 CONF
*to_free
= NULL
;
421 config
= to_free
= app_load_config_quiet(default_config_file
);
425 if (CONF_modules_load(config
, NULL
, 0) <= 0) {
426 BIO_printf(bio_err
, "Error configuring OpenSSL modules\n");
427 ERR_print_errors(bio_err
);
435 int add_oid_section(CONF
*conf
)
438 STACK_OF(CONF_VALUE
) *sktmp
;
442 if ((p
= NCONF_get_string(conf
, NULL
, "oid_section")) == NULL
) {
446 if ((sktmp
= NCONF_get_section(conf
, p
)) == NULL
) {
447 BIO_printf(bio_err
, "problem loading oid section %s\n", p
);
450 for (i
= 0; i
< sk_CONF_VALUE_num(sktmp
); i
++) {
451 cnf
= sk_CONF_VALUE_value(sktmp
, i
);
452 if (OBJ_create(cnf
->value
, cnf
->name
, cnf
->name
) == NID_undef
) {
453 BIO_printf(bio_err
, "problem creating object %s=%s\n",
454 cnf
->name
, cnf
->value
);
461 CONF
*app_load_config_modules(const char *configfile
)
465 if (configfile
!= NULL
) {
466 BIO_printf(bio_err
, "Using configuration from %s\n", configfile
);
468 if ((conf
= app_load_config(configfile
)) == NULL
)
470 if (configfile
!= default_config_file
&& !app_load_modules(conf
)) {
478 X509
*load_cert_pass(const char *uri
, int maybe_stdin
,
479 const char *pass
, const char *desc
)
484 desc
= "certificate";
485 (void)load_key_certs_crls(uri
, maybe_stdin
, pass
, desc
,
486 NULL
, NULL
, &cert
, NULL
, NULL
, NULL
);
488 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
489 ERR_print_errors(bio_err
);
494 /* the format parameter is meanwhile not needed anymore and thus ignored */
495 X509_CRL
*load_crl(const char *uri
, int format
, const char *desc
)
497 X509_CRL
*crl
= NULL
;
501 (void)load_key_certs_crls(uri
, 0, NULL
, desc
,
502 NULL
, NULL
, NULL
, NULL
, &crl
, NULL
);
504 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
505 ERR_print_errors(bio_err
);
510 X509_REQ
*load_csr(const char *file
, int format
, const char *desc
)
512 X509_REQ
*req
= NULL
;
517 in
= bio_open_default(file
, 'r', format
);
521 if (format
== FORMAT_ASN1
)
522 req
= d2i_X509_REQ_bio(in
, NULL
);
523 else if (format
== FORMAT_PEM
)
524 req
= PEM_read_bio_X509_REQ(in
, NULL
, NULL
, NULL
);
526 print_format_error(format
, OPT_FMT_PEMDER
);
530 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
531 ERR_print_errors(bio_err
);
537 void cleanse(char *str
)
540 OPENSSL_cleanse(str
, strlen(str
));
543 void clear_free(char *str
)
546 OPENSSL_clear_free(str
, strlen(str
));
549 EVP_PKEY
*load_key(const char *uri
, int format
, int may_stdin
,
550 const char *pass
, ENGINE
*e
, const char *desc
)
552 EVP_PKEY
*pkey
= NULL
;
555 desc
= "private key";
557 if (format
== FORMAT_ENGINE
) {
559 BIO_printf(bio_err
, "No engine specified for loading %s\n", desc
);
561 #ifndef OPENSSL_NO_ENGINE
564 cb_data
.password
= pass
;
565 cb_data
.prompt_info
= uri
;
566 if (ENGINE_init(e
)) {
567 pkey
= ENGINE_load_private_key(e
, uri
,
568 (UI_METHOD
*)get_ui_method(),
573 BIO_printf(bio_err
, "Cannot load %s from engine\n", desc
);
574 ERR_print_errors(bio_err
);
577 BIO_printf(bio_err
, "Engines not supported for loading %s\n", desc
);
581 (void)load_key_certs_crls(uri
, may_stdin
, pass
, desc
,
582 &pkey
, NULL
, NULL
, NULL
, NULL
, NULL
);
586 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
587 ERR_print_errors(bio_err
);
592 EVP_PKEY
*load_pubkey(const char *uri
, int format
, int maybe_stdin
,
593 const char *pass
, ENGINE
*e
, const char *desc
)
595 EVP_PKEY
*pkey
= NULL
;
600 if (format
== FORMAT_ENGINE
) {
602 BIO_printf(bio_err
, "No engine specified for loading %s\n", desc
);
604 #ifndef OPENSSL_NO_ENGINE
607 cb_data
.password
= pass
;
608 cb_data
.prompt_info
= uri
;
609 pkey
= ENGINE_load_public_key(e
, uri
, (UI_METHOD
*)get_ui_method(),
612 BIO_printf(bio_err
, "Cannot load %s from engine\n", desc
);
613 ERR_print_errors(bio_err
);
616 BIO_printf(bio_err
, "Engines not supported for loading %s\n", desc
);
620 (void)load_key_certs_crls(uri
, maybe_stdin
, pass
, desc
,
621 NULL
, &pkey
, NULL
, NULL
, NULL
, NULL
);
624 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
625 ERR_print_errors(bio_err
);
630 void app_bail_out(char *fmt
, ...)
635 BIO_vprintf(bio_err
, fmt
, args
);
637 ERR_print_errors(bio_err
);
641 void* app_malloc(int sz
, const char *what
)
643 void *vp
= OPENSSL_malloc(sz
);
646 app_bail_out("%s: Could not allocate %d bytes for %s\n",
647 opt_getprog(), sz
, what
);
652 * Initialize or extend, if *certs != NULL, a certificate stack.
653 * The caller is responsible for freeing *certs if its value is left not NULL.
655 int load_certs(const char *uri
, STACK_OF(X509
) **certs
,
656 const char *pass
, const char *desc
)
658 int was_NULL
= *certs
== NULL
;
659 int ret
= load_key_certs_crls(uri
, 0, pass
, desc
, NULL
, NULL
,
660 NULL
, certs
, NULL
, NULL
);
662 if (!ret
&& was_NULL
) {
663 sk_X509_pop_free(*certs
, X509_free
);
670 * Initialize or extend, if *crls != NULL, a certificate stack.
671 * The caller is responsible for freeing *crls if its value is left not NULL.
673 int load_crls(const char *uri
, STACK_OF(X509_CRL
) **crls
,
674 const char *pass
, const char *desc
)
676 int was_NULL
= *crls
== NULL
;
677 int ret
= load_key_certs_crls(uri
, 0, pass
, desc
, NULL
, NULL
,
678 NULL
, NULL
, NULL
, crls
);
680 if (!ret
&& was_NULL
) {
681 sk_X509_CRL_pop_free(*crls
, X509_CRL_free
);
688 * Load those types of credentials for which the result pointer is not NULL.
689 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
690 * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
691 * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
692 * If pcerts is non-NULL then all available certificates are appended to *pcerts
693 * except any certificate assigned to *pcert.
694 * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
695 * If pcrls is non-NULL then all available CRLs are appended to *pcerts
696 * except any CRL assigned to *pcrl.
697 * In any case (also on error) the caller is responsible for freeing all members
698 * of *pcerts and *pcrls (as far as they are not NULL).
700 int load_key_certs_crls(const char *uri
, int maybe_stdin
,
701 const char *pass
, const char *desc
,
702 EVP_PKEY
**ppkey
, EVP_PKEY
**ppubkey
,
703 X509
**pcert
, STACK_OF(X509
) **pcerts
,
704 X509_CRL
**pcrl
, STACK_OF(X509_CRL
) **pcrls
)
707 OSSL_STORE_CTX
*ctx
= NULL
;
708 OPENSSL_CTX
*libctx
= app_get0_libctx();
709 const char *propq
= app_get0_propq();
712 const char *failed
= "any";
713 /* TODO make use of the engine reference 'eng' when loading pkeys */
721 if (pcerts
!= NULL
&& *pcerts
== NULL
722 && (*pcerts
= sk_X509_new_null()) == NULL
) {
723 BIO_printf(bio_err
, "Out of memory");
728 if (pcrls
!= NULL
&& *pcrls
== NULL
729 && (*pcrls
= sk_X509_CRL_new_null()) == NULL
) {
730 BIO_printf(bio_err
, "Out of memory");
735 desc
= "key/certificate/CRL";
736 uidata
.password
= pass
;
737 uidata
.prompt_info
= uri
;
744 BIO_printf(bio_err
, "No filename or uri specified for loading %s\n",
749 bio
= BIO_new_fp(stdin
, 0);
751 ctx
= OSSL_STORE_attach(bio
, "file", libctx
, propq
,
752 get_ui_method(), &uidata
, NULL
, NULL
);
754 ctx
= OSSL_STORE_open_with_libctx(uri
, libctx
, propq
, get_ui_method(),
755 &uidata
, NULL
, NULL
);
758 BIO_printf(bio_err
, "Could not open file or uri %s for loading %s\n",
764 while (!OSSL_STORE_eof(ctx
)) {
765 OSSL_STORE_INFO
*info
= OSSL_STORE_load(ctx
);
766 int type
= info
== NULL
? 0 : OSSL_STORE_INFO_get_type(info
);
770 case OSSL_STORE_INFO_PKEY
:
771 if (ppkey
!= NULL
&& *ppkey
== NULL
)
772 ok
= (*ppkey
= OSSL_STORE_INFO_get1_PKEY(info
)) != NULL
;
775 * An EVP_PKEY with private parts also holds the public parts,
776 * so if the caller asked for a public key, and we got a private
777 * key, we can still pass it back.
779 if (ok
&& ppubkey
!= NULL
&& *ppubkey
== NULL
)
780 ok
= ((*ppubkey
= OSSL_STORE_INFO_get1_PKEY(info
)) != NULL
);
782 case OSSL_STORE_INFO_PUBKEY
:
783 if (ppubkey
!= NULL
&& *ppubkey
== NULL
)
784 ok
= ((*ppubkey
= OSSL_STORE_INFO_get1_PUBKEY(info
)) != NULL
);
786 case OSSL_STORE_INFO_CERT
:
787 if (pcert
!= NULL
&& *pcert
== NULL
)
788 ok
= (*pcert
= OSSL_STORE_INFO_get1_CERT(info
)) != NULL
;
789 else if (pcerts
!= NULL
)
790 ok
= X509_add_cert(*pcerts
,
791 OSSL_STORE_INFO_get1_CERT(info
),
792 X509_ADD_FLAG_DEFAULT
);
795 case OSSL_STORE_INFO_CRL
:
796 if (pcrl
!= NULL
&& *pcrl
== NULL
)
797 ok
= (*pcrl
= OSSL_STORE_INFO_get1_CRL(info
)) != NULL
;
798 else if (pcrls
!= NULL
)
799 ok
= sk_X509_CRL_push(*pcrls
, OSSL_STORE_INFO_get1_CRL(info
));
803 /* skip any other type */
806 OSSL_STORE_INFO_free(info
);
808 failed
= info
== NULL
? NULL
: OSSL_STORE_INFO_type_string(type
);
809 BIO_printf(bio_err
, "Error reading %s of %s from %s\n",
816 OSSL_STORE_close(ctx
);
817 if (failed
== NULL
) {
818 if (ppkey
!= NULL
&& *ppkey
== NULL
)
820 else if ((pcert
!= NULL
|| pcerts
!= NULL
) && ncerts
== 0)
822 else if ((pcrl
!= NULL
|| pcrls
!= NULL
) && ncrls
== 0)
825 BIO_printf(bio_err
, "Could not read any %s of %s from %s\n",
829 ERR_print_errors(bio_err
);
830 return failed
== NULL
;
834 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
835 /* Return error for unknown extensions */
836 #define X509V3_EXT_DEFAULT 0
837 /* Print error for unknown extensions */
838 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
839 /* ASN1 parse unknown extensions */
840 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
841 /* BIO_dump unknown extensions */
842 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
844 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
845 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
847 int set_cert_ex(unsigned long *flags
, const char *arg
)
849 static const NAME_EX_TBL cert_tbl
[] = {
850 {"compatible", X509_FLAG_COMPAT
, 0xffffffffl
},
851 {"ca_default", X509_FLAG_CA
, 0xffffffffl
},
852 {"no_header", X509_FLAG_NO_HEADER
, 0},
853 {"no_version", X509_FLAG_NO_VERSION
, 0},
854 {"no_serial", X509_FLAG_NO_SERIAL
, 0},
855 {"no_signame", X509_FLAG_NO_SIGNAME
, 0},
856 {"no_validity", X509_FLAG_NO_VALIDITY
, 0},
857 {"no_subject", X509_FLAG_NO_SUBJECT
, 0},
858 {"no_issuer", X509_FLAG_NO_ISSUER
, 0},
859 {"no_pubkey", X509_FLAG_NO_PUBKEY
, 0},
860 {"no_extensions", X509_FLAG_NO_EXTENSIONS
, 0},
861 {"no_sigdump", X509_FLAG_NO_SIGDUMP
, 0},
862 {"no_aux", X509_FLAG_NO_AUX
, 0},
863 {"no_attributes", X509_FLAG_NO_ATTRIBUTES
, 0},
864 {"ext_default", X509V3_EXT_DEFAULT
, X509V3_EXT_UNKNOWN_MASK
},
865 {"ext_error", X509V3_EXT_ERROR_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
866 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
867 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
870 return set_multi_opts(flags
, arg
, cert_tbl
);
873 int set_name_ex(unsigned long *flags
, const char *arg
)
875 static const NAME_EX_TBL ex_tbl
[] = {
876 {"esc_2253", ASN1_STRFLGS_ESC_2253
, 0},
877 {"esc_2254", ASN1_STRFLGS_ESC_2254
, 0},
878 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL
, 0},
879 {"esc_msb", ASN1_STRFLGS_ESC_MSB
, 0},
880 {"use_quote", ASN1_STRFLGS_ESC_QUOTE
, 0},
881 {"utf8", ASN1_STRFLGS_UTF8_CONVERT
, 0},
882 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE
, 0},
883 {"show_type", ASN1_STRFLGS_SHOW_TYPE
, 0},
884 {"dump_all", ASN1_STRFLGS_DUMP_ALL
, 0},
885 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN
, 0},
886 {"dump_der", ASN1_STRFLGS_DUMP_DER
, 0},
887 {"compat", XN_FLAG_COMPAT
, 0xffffffffL
},
888 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS
, XN_FLAG_SEP_MASK
},
889 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC
, XN_FLAG_SEP_MASK
},
890 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC
, XN_FLAG_SEP_MASK
},
891 {"sep_multiline", XN_FLAG_SEP_MULTILINE
, XN_FLAG_SEP_MASK
},
892 {"dn_rev", XN_FLAG_DN_REV
, 0},
893 {"nofname", XN_FLAG_FN_NONE
, XN_FLAG_FN_MASK
},
894 {"sname", XN_FLAG_FN_SN
, XN_FLAG_FN_MASK
},
895 {"lname", XN_FLAG_FN_LN
, XN_FLAG_FN_MASK
},
896 {"align", XN_FLAG_FN_ALIGN
, 0},
897 {"oid", XN_FLAG_FN_OID
, XN_FLAG_FN_MASK
},
898 {"space_eq", XN_FLAG_SPC_EQ
, 0},
899 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS
, 0},
900 {"RFC2253", XN_FLAG_RFC2253
, 0xffffffffL
},
901 {"oneline", XN_FLAG_ONELINE
, 0xffffffffL
},
902 {"multiline", XN_FLAG_MULTILINE
, 0xffffffffL
},
903 {"ca_default", XN_FLAG_MULTILINE
, 0xffffffffL
},
906 if (set_multi_opts(flags
, arg
, ex_tbl
) == 0)
908 if (*flags
!= XN_FLAG_COMPAT
909 && (*flags
& XN_FLAG_SEP_MASK
) == 0)
910 *flags
|= XN_FLAG_SEP_CPLUS_SPC
;
914 int set_ext_copy(int *copy_type
, const char *arg
)
916 if (strcasecmp(arg
, "none") == 0)
917 *copy_type
= EXT_COPY_NONE
;
918 else if (strcasecmp(arg
, "copy") == 0)
919 *copy_type
= EXT_COPY_ADD
;
920 else if (strcasecmp(arg
, "copyall") == 0)
921 *copy_type
= EXT_COPY_ALL
;
927 int copy_extensions(X509
*x
, X509_REQ
*req
, int copy_type
)
929 STACK_OF(X509_EXTENSION
) *exts
= NULL
;
930 X509_EXTENSION
*ext
, *tmpext
;
933 if (!x
|| !req
|| (copy_type
== EXT_COPY_NONE
))
935 exts
= X509_REQ_get_extensions(req
);
937 for (i
= 0; i
< sk_X509_EXTENSION_num(exts
); i
++) {
938 ext
= sk_X509_EXTENSION_value(exts
, i
);
939 obj
= X509_EXTENSION_get_object(ext
);
940 idx
= X509_get_ext_by_OBJ(x
, obj
, -1);
941 /* Does extension exist? */
943 /* If normal copy don't override existing extension */
944 if (copy_type
== EXT_COPY_ADD
)
946 /* Delete all extensions of same type */
948 tmpext
= X509_get_ext(x
, idx
);
949 X509_delete_ext(x
, idx
);
950 X509_EXTENSION_free(tmpext
);
951 idx
= X509_get_ext_by_OBJ(x
, obj
, -1);
954 if (!X509_add_ext(x
, ext
, -1))
962 sk_X509_EXTENSION_pop_free(exts
, X509_EXTENSION_free
);
967 static int set_multi_opts(unsigned long *flags
, const char *arg
,
968 const NAME_EX_TBL
* in_tbl
)
970 STACK_OF(CONF_VALUE
) *vals
;
975 vals
= X509V3_parse_list(arg
);
976 for (i
= 0; i
< sk_CONF_VALUE_num(vals
); i
++) {
977 val
= sk_CONF_VALUE_value(vals
, i
);
978 if (!set_table_opts(flags
, val
->name
, in_tbl
))
981 sk_CONF_VALUE_pop_free(vals
, X509V3_conf_free
);
985 static int set_table_opts(unsigned long *flags
, const char *arg
,
986 const NAME_EX_TBL
* in_tbl
)
989 const NAME_EX_TBL
*ptbl
;
995 } else if (c
== '+') {
1002 for (ptbl
= in_tbl
; ptbl
->name
; ptbl
++) {
1003 if (strcasecmp(arg
, ptbl
->name
) == 0) {
1004 *flags
&= ~ptbl
->mask
;
1006 *flags
|= ptbl
->flag
;
1008 *flags
&= ~ptbl
->flag
;
1015 void print_name(BIO
*out
, const char *title
, const X509_NAME
*nm
,
1016 unsigned long lflags
)
1023 BIO_puts(out
, title
);
1024 if ((lflags
& XN_FLAG_SEP_MASK
) == XN_FLAG_SEP_MULTILINE
) {
1028 if (lflags
== XN_FLAG_COMPAT
) {
1029 buf
= X509_NAME_oneline(nm
, 0, 0);
1031 BIO_puts(out
, "\n");
1035 BIO_puts(out
, "\n");
1036 X509_NAME_print_ex(out
, nm
, indent
, lflags
);
1037 BIO_puts(out
, "\n");
1041 void print_bignum_var(BIO
*out
, const BIGNUM
*in
, const char *var
,
1042 int len
, unsigned char *buffer
)
1044 BIO_printf(out
, " static unsigned char %s_%d[] = {", var
, len
);
1045 if (BN_is_zero(in
)) {
1046 BIO_printf(out
, "\n 0x00");
1050 l
= BN_bn2bin(in
, buffer
);
1051 for (i
= 0; i
< l
; i
++) {
1052 BIO_printf(out
, (i
% 10) == 0 ? "\n " : " ");
1054 BIO_printf(out
, "0x%02X,", buffer
[i
]);
1056 BIO_printf(out
, "0x%02X", buffer
[i
]);
1059 BIO_printf(out
, "\n };\n");
1062 void print_array(BIO
*out
, const char* title
, int len
, const unsigned char* d
)
1066 BIO_printf(out
, "unsigned char %s[%d] = {", title
, len
);
1067 for (i
= 0; i
< len
; i
++) {
1069 BIO_printf(out
, "\n ");
1071 BIO_printf(out
, "0x%02X, ", d
[i
]);
1073 BIO_printf(out
, "0x%02X", d
[i
]);
1075 BIO_printf(out
, "\n};\n");
1078 X509_STORE
*setup_verify(const char *CAfile
, int noCAfile
,
1079 const char *CApath
, int noCApath
,
1080 const char *CAstore
, int noCAstore
)
1082 X509_STORE
*store
= X509_STORE_new();
1083 X509_LOOKUP
*lookup
;
1084 OPENSSL_CTX
*libctx
= app_get0_libctx();
1085 const char *propq
= app_get0_propq();
1090 if (CAfile
!= NULL
|| !noCAfile
) {
1091 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_file());
1094 if (CAfile
!= NULL
) {
1095 if (!X509_LOOKUP_load_file_with_libctx(lookup
, CAfile
,
1098 BIO_printf(bio_err
, "Error loading file %s\n", CAfile
);
1102 X509_LOOKUP_load_file_with_libctx(lookup
, NULL
,
1103 X509_FILETYPE_DEFAULT
,
1108 if (CApath
!= NULL
|| !noCApath
) {
1109 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_hash_dir());
1112 if (CApath
!= NULL
) {
1113 if (!X509_LOOKUP_add_dir(lookup
, CApath
, X509_FILETYPE_PEM
)) {
1114 BIO_printf(bio_err
, "Error loading directory %s\n", CApath
);
1118 X509_LOOKUP_add_dir(lookup
, NULL
, X509_FILETYPE_DEFAULT
);
1122 if (CAstore
!= NULL
|| !noCAstore
) {
1123 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_store());
1126 if (!X509_LOOKUP_add_store_with_libctx(lookup
, CAstore
, libctx
, propq
)) {
1127 if (CAstore
!= NULL
)
1128 BIO_printf(bio_err
, "Error loading store URI %s\n", CAstore
);
1136 ERR_print_errors(bio_err
);
1137 X509_STORE_free(store
);
1141 #ifndef OPENSSL_NO_ENGINE
1142 /* Try to load an engine in a shareable library */
1143 static ENGINE
*try_load_engine(const char *engine
)
1145 ENGINE
*e
= ENGINE_by_id("dynamic");
1147 if (!ENGINE_ctrl_cmd_string(e
, "SO_PATH", engine
, 0)
1148 || !ENGINE_ctrl_cmd_string(e
, "LOAD", NULL
, 0)) {
1157 ENGINE
*setup_engine_methods(const char *id
, unsigned int methods
, int debug
)
1161 #ifndef OPENSSL_NO_ENGINE
1163 if (strcmp(id
, "auto") == 0) {
1164 BIO_printf(bio_err
, "Enabling auto ENGINE support\n");
1165 ENGINE_register_all_complete();
1168 if ((e
= ENGINE_by_id(id
)) == NULL
1169 && (e
= try_load_engine(id
)) == NULL
) {
1170 BIO_printf(bio_err
, "Invalid engine \"%s\"\n", id
);
1171 ERR_print_errors(bio_err
);
1175 (void)ENGINE_ctrl(e
, ENGINE_CTRL_SET_LOGSTREAM
, 0, bio_err
, 0);
1176 if (!ENGINE_ctrl_cmd(e
, "SET_USER_INTERFACE", 0,
1177 (void *)get_ui_method(), 0, 1)
1178 || !ENGINE_set_default(e
, methods
)) {
1179 BIO_printf(bio_err
, "Cannot use engine \"%s\"\n", ENGINE_get_id(e
));
1180 ERR_print_errors(bio_err
);
1185 BIO_printf(bio_err
, "Engine \"%s\" set.\n", ENGINE_get_id(e
));
1191 void release_engine(ENGINE
*e
)
1193 #ifndef OPENSSL_NO_ENGINE
1194 /* Free our "structural" reference. */
1199 static unsigned long index_serial_hash(const OPENSSL_CSTRING
*a
)
1206 return OPENSSL_LH_strhash(n
);
1209 static int index_serial_cmp(const OPENSSL_CSTRING
*a
,
1210 const OPENSSL_CSTRING
*b
)
1212 const char *aa
, *bb
;
1214 for (aa
= a
[DB_serial
]; *aa
== '0'; aa
++) ;
1215 for (bb
= b
[DB_serial
]; *bb
== '0'; bb
++) ;
1216 return strcmp(aa
, bb
);
1219 static int index_name_qual(char **a
)
1221 return (a
[0][0] == 'V');
1224 static unsigned long index_name_hash(const OPENSSL_CSTRING
*a
)
1226 return OPENSSL_LH_strhash(a
[DB_name
]);
1229 int index_name_cmp(const OPENSSL_CSTRING
*a
, const OPENSSL_CSTRING
*b
)
1231 return strcmp(a
[DB_name
], b
[DB_name
]);
1234 static IMPLEMENT_LHASH_HASH_FN(index_serial
, OPENSSL_CSTRING
)
1235 static IMPLEMENT_LHASH_COMP_FN(index_serial
, OPENSSL_CSTRING
)
1236 static IMPLEMENT_LHASH_HASH_FN(index_name
, OPENSSL_CSTRING
)
1237 static IMPLEMENT_LHASH_COMP_FN(index_name
, OPENSSL_CSTRING
)
1240 BIGNUM
*load_serial(const char *serialfile
, int create
, ASN1_INTEGER
**retai
)
1245 ASN1_INTEGER
*ai
= NULL
;
1247 ai
= ASN1_INTEGER_new();
1251 in
= BIO_new_file(serialfile
, "r");
1259 if (ret
== NULL
|| !rand_serial(ret
, ai
))
1260 BIO_printf(bio_err
, "Out of memory\n");
1262 if (!a2i_ASN1_INTEGER(in
, ai
, buf
, 1024)) {
1263 BIO_printf(bio_err
, "Unable to load number from %s\n",
1267 ret
= ASN1_INTEGER_to_BN(ai
, NULL
);
1269 BIO_printf(bio_err
, "Error converting number from bin to BIGNUM\n");
1279 ERR_print_errors(bio_err
);
1281 ASN1_INTEGER_free(ai
);
1285 int save_serial(const char *serialfile
, const char *suffix
, const BIGNUM
*serial
,
1286 ASN1_INTEGER
**retai
)
1291 ASN1_INTEGER
*ai
= NULL
;
1295 j
= strlen(serialfile
);
1297 j
= strlen(serialfile
) + strlen(suffix
) + 1;
1299 BIO_printf(bio_err
, "File name too long\n");
1304 OPENSSL_strlcpy(buf
[0], serialfile
, BSIZE
);
1306 #ifndef OPENSSL_SYS_VMS
1307 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, suffix
);
1309 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, suffix
);
1312 out
= BIO_new_file(buf
[0], "w");
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 ERR_print_errors(bio_err
);
1332 ASN1_INTEGER_free(ai
);
1336 int rotate_serial(const char *serialfile
, const char *new_suffix
,
1337 const char *old_suffix
)
1342 i
= strlen(serialfile
) + strlen(old_suffix
);
1343 j
= strlen(serialfile
) + strlen(new_suffix
);
1346 if (j
+ 1 >= BSIZE
) {
1347 BIO_printf(bio_err
, "File name too long\n");
1350 #ifndef OPENSSL_SYS_VMS
1351 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, new_suffix
);
1352 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", serialfile
, old_suffix
);
1354 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, new_suffix
);
1355 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", serialfile
, old_suffix
);
1357 if (rename(serialfile
, buf
[1]) < 0 && errno
!= ENOENT
1363 "Unable to rename %s to %s\n", serialfile
, buf
[1]);
1367 if (rename(buf
[0], serialfile
) < 0) {
1369 "Unable to rename %s to %s\n", buf
[0], serialfile
);
1371 rename(buf
[1], serialfile
);
1376 ERR_print_errors(bio_err
);
1380 int rand_serial(BIGNUM
*b
, ASN1_INTEGER
*ai
)
1385 btmp
= b
== NULL
? BN_new() : b
;
1389 if (!BN_rand(btmp
, SERIAL_RAND_BITS
, BN_RAND_TOP_ANY
, BN_RAND_BOTTOM_ANY
))
1391 if (ai
&& !BN_to_ASN1_INTEGER(btmp
, ai
))
1404 CA_DB
*load_index(const char *dbfile
, DB_ATTR
*db_attr
)
1406 CA_DB
*retdb
= NULL
;
1407 TXT_DB
*tmpdb
= NULL
;
1409 CONF
*dbattr_conf
= NULL
;
1411 #ifndef OPENSSL_NO_POSIX_IO
1416 in
= BIO_new_file(dbfile
, "r");
1420 #ifndef OPENSSL_NO_POSIX_IO
1421 BIO_get_fp(in
, &dbfp
);
1422 if (fstat(fileno(dbfp
), &dbst
) == -1) {
1423 ERR_raise_data(ERR_LIB_SYS
, errno
,
1424 "calling fstat(%s)", dbfile
);
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 ERR_print_errors(bio_err
);
1462 NCONF_free(dbattr_conf
);
1469 * Returns > 0 on success, <= 0 on error
1471 int index_index(CA_DB
*db
)
1473 if (!TXT_DB_create_index(db
->db
, DB_serial
, NULL
,
1474 LHASH_HASH_FN(index_serial
),
1475 LHASH_COMP_FN(index_serial
))) {
1477 "Error creating serial number index:(%ld,%ld,%ld)\n",
1478 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1482 if (db
->attributes
.unique_subject
1483 && !TXT_DB_create_index(db
->db
, DB_name
, index_name_qual
,
1484 LHASH_HASH_FN(index_name
),
1485 LHASH_COMP_FN(index_name
))) {
1486 BIO_printf(bio_err
, "Error creating name index:(%ld,%ld,%ld)\n",
1487 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1492 ERR_print_errors(bio_err
);
1496 int save_index(const char *dbfile
, const char *suffix
, CA_DB
*db
)
1502 j
= strlen(dbfile
) + strlen(suffix
);
1503 if (j
+ 6 >= BSIZE
) {
1504 BIO_printf(bio_err
, "File name too long\n");
1507 #ifndef OPENSSL_SYS_VMS
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 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 out
= BIO_new_file(buf
[0], "w");
1519 BIO_printf(bio_err
, "Unable to open '%s'\n", dbfile
);
1522 j
= TXT_DB_write(out
, db
->db
);
1527 out
= BIO_new_file(buf
[1], "w");
1530 BIO_printf(bio_err
, "Unable to open '%s'\n", buf
[2]);
1533 BIO_printf(out
, "unique_subject = %s\n",
1534 db
->attributes
.unique_subject
? "yes" : "no");
1539 ERR_print_errors(bio_err
);
1543 int rotate_index(const char *dbfile
, const char *new_suffix
,
1544 const char *old_suffix
)
1549 i
= strlen(dbfile
) + strlen(old_suffix
);
1550 j
= strlen(dbfile
) + strlen(new_suffix
);
1553 if (j
+ 6 >= BSIZE
) {
1554 BIO_printf(bio_err
, "File name too long\n");
1557 #ifndef OPENSSL_SYS_VMS
1558 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s.attr", dbfile
);
1559 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s.attr.%s", dbfile
, old_suffix
);
1560 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr.%s", dbfile
, new_suffix
);
1561 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", dbfile
, old_suffix
);
1562 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, new_suffix
);
1564 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s-attr", dbfile
);
1565 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s-attr-%s", dbfile
, old_suffix
);
1566 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr-%s", dbfile
, new_suffix
);
1567 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", dbfile
, old_suffix
);
1568 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, new_suffix
);
1570 if (rename(dbfile
, buf
[1]) < 0 && errno
!= ENOENT
1575 BIO_printf(bio_err
, "Unable to rename %s to %s\n", dbfile
, buf
[1]);
1579 if (rename(buf
[0], dbfile
) < 0) {
1580 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[0], dbfile
);
1582 rename(buf
[1], dbfile
);
1585 if (rename(buf
[4], buf
[3]) < 0 && errno
!= ENOENT
1590 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[4], buf
[3]);
1592 rename(dbfile
, buf
[0]);
1593 rename(buf
[1], dbfile
);
1596 if (rename(buf
[2], buf
[4]) < 0) {
1597 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[2], buf
[4]);
1599 rename(buf
[3], buf
[4]);
1600 rename(dbfile
, buf
[0]);
1601 rename(buf
[1], dbfile
);
1606 ERR_print_errors(bio_err
);
1610 void free_index(CA_DB
*db
)
1613 TXT_DB_free(db
->db
);
1614 OPENSSL_free(db
->dbfname
);
1619 int parse_yesno(const char *str
, int def
)
1623 case 'f': /* false */
1624 case 'F': /* FALSE */
1629 case 't': /* true */
1630 case 'T': /* TRUE */
1641 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1642 * where + can be used instead of / to form multi-valued RDNs if canmulti
1643 * and characters may be escaped by \
1645 X509_NAME
*parse_name(const char *cp
, int chtype
, int canmulti
,
1648 int nextismulti
= 0;
1654 "%s: %s name is expected to be in the format "
1655 "/type0=value0/type1=value1/type2=... where characters may "
1656 "be escaped by \\. This name is not in that format: '%s'\n",
1657 opt_getprog(), desc
, --cp
);
1661 n
= X509_NAME_new();
1663 BIO_printf(bio_err
, "%s: Out of memory\n", opt_getprog());
1666 work
= OPENSSL_strdup(cp
);
1668 BIO_printf(bio_err
, "%s: Error copying %s name input\n",
1669 opt_getprog(), desc
);
1673 while (*cp
!= '\0') {
1676 unsigned char *valstr
;
1678 int ismulti
= nextismulti
;
1681 /* Collect the type */
1682 while (*cp
!= '\0' && *cp
!= '=')
1687 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1688 opt_getprog(), typestr
, desc
);
1693 /* Collect the value. */
1694 valstr
= (unsigned char *)bp
;
1695 for (; *cp
!= '\0' && *cp
!= '/'; *bp
++ = *cp
++) {
1696 /* unescaped '+' symbol string signals further member of multiRDN */
1697 if (canmulti
&& *cp
== '+') {
1701 if (*cp
== '\\' && *++cp
== '\0') {
1703 "%s: Escape character at end of %s name string\n",
1704 opt_getprog(), desc
);
1710 /* If not at EOS (must be + or /), move forward. */
1715 nid
= OBJ_txt2nid(typestr
);
1716 if (nid
== NID_undef
) {
1718 "%s: Skipping unknown %s name attribute \"%s\"\n",
1719 opt_getprog(), desc
, typestr
);
1722 "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
1725 if (*valstr
== '\0') {
1727 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1728 opt_getprog(), desc
, typestr
);
1731 if (!X509_NAME_add_entry_by_NID(n
, nid
, chtype
,
1732 valstr
, strlen((char *)valstr
),
1733 -1, ismulti
? -1 : 0)) {
1734 ERR_print_errors(bio_err
);
1736 "%s: Error adding %s name attribute \"/%s=%s\"\n",
1737 opt_getprog(), desc
, typestr
,valstr
);
1752 * Read whole contents of a BIO into an allocated memory buffer and return
1756 int bio_to_mem(unsigned char **out
, int maxlen
, BIO
*in
)
1760 unsigned char tbuf
[1024];
1762 mem
= BIO_new(BIO_s_mem());
1766 if ((maxlen
!= -1) && maxlen
< 1024)
1770 len
= BIO_read(in
, tbuf
, len
);
1777 if (BIO_write(mem
, tbuf
, len
) != len
) {
1786 ret
= BIO_get_mem_data(mem
, (char **)out
);
1787 BIO_set_flags(mem
, BIO_FLAGS_MEM_RDONLY
);
1792 int pkey_ctrl_string(EVP_PKEY_CTX
*ctx
, const char *value
)
1795 char *stmp
, *vtmp
= NULL
;
1796 stmp
= OPENSSL_strdup(value
);
1799 vtmp
= strchr(stmp
, ':');
1804 rv
= EVP_PKEY_CTX_ctrl_str(ctx
, stmp
, vtmp
);
1809 static void nodes_print(const char *name
, STACK_OF(X509_POLICY_NODE
) *nodes
)
1811 X509_POLICY_NODE
*node
;
1814 BIO_printf(bio_err
, "%s Policies:", name
);
1816 BIO_puts(bio_err
, "\n");
1817 for (i
= 0; i
< sk_X509_POLICY_NODE_num(nodes
); i
++) {
1818 node
= sk_X509_POLICY_NODE_value(nodes
, i
);
1819 X509_POLICY_NODE_print(bio_err
, node
, 2);
1822 BIO_puts(bio_err
, " <empty>\n");
1826 void policies_print(X509_STORE_CTX
*ctx
)
1828 X509_POLICY_TREE
*tree
;
1829 int explicit_policy
;
1830 tree
= X509_STORE_CTX_get0_policy_tree(ctx
);
1831 explicit_policy
= X509_STORE_CTX_get_explicit_policy(ctx
);
1833 BIO_printf(bio_err
, "Require explicit Policy: %s\n",
1834 explicit_policy
? "True" : "False");
1836 nodes_print("Authority", X509_policy_tree_get0_policies(tree
));
1837 nodes_print("User", X509_policy_tree_get0_user_policies(tree
));
1841 * next_protos_parse parses a comma separated list of strings into a string
1842 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1843 * outlen: (output) set to the length of the resulting buffer on success.
1844 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1845 * in: a NUL terminated string like "abc,def,ghi"
1847 * returns: a malloc'd buffer or NULL on failure.
1849 unsigned char *next_protos_parse(size_t *outlen
, const char *in
)
1853 size_t i
, start
= 0;
1857 if (len
== 0 || len
>= 65535)
1860 out
= app_malloc(len
+ 1, "NPN buffer");
1861 for (i
= 0; i
<= len
; ++i
) {
1862 if (i
== len
|| in
[i
] == ',') {
1864 * Zero-length ALPN elements are invalid on the wire, we could be
1865 * strict and reject the entire string, but just ignoring extra
1866 * commas seems harmless and more friendly.
1868 * Every comma we skip in this way puts the input buffer another
1869 * byte ahead of the output buffer, so all stores into the output
1870 * buffer need to be decremented by the number commas skipped.
1877 if (i
- start
> 255) {
1881 out
[start
-skipped
] = (unsigned char)(i
- start
);
1884 out
[i
+ 1 - skipped
] = in
[i
];
1888 if (len
<= skipped
) {
1893 *outlen
= len
+ 1 - skipped
;
1897 void print_cert_checks(BIO
*bio
, X509
*x
,
1898 const char *checkhost
,
1899 const char *checkemail
, const char *checkip
)
1904 BIO_printf(bio
, "Hostname %s does%s match certificate\n",
1906 X509_check_host(x
, checkhost
, 0, 0, NULL
) == 1
1911 BIO_printf(bio
, "Email %s does%s match certificate\n",
1912 checkemail
, X509_check_email(x
, checkemail
, 0, 0)
1917 BIO_printf(bio
, "IP %s does%s match certificate\n",
1918 checkip
, X509_check_ip_asc(x
, checkip
, 0) ? "" : " NOT");
1922 /* Get first http URL from a DIST_POINT structure */
1924 static const char *get_dp_url(DIST_POINT
*dp
)
1926 GENERAL_NAMES
*gens
;
1930 if (!dp
->distpoint
|| dp
->distpoint
->type
!= 0)
1932 gens
= dp
->distpoint
->name
.fullname
;
1933 for (i
= 0; i
< sk_GENERAL_NAME_num(gens
); i
++) {
1934 gen
= sk_GENERAL_NAME_value(gens
, i
);
1935 uri
= GENERAL_NAME_get0_value(gen
, >ype
);
1936 if (gtype
== GEN_URI
&& ASN1_STRING_length(uri
) > 6) {
1937 const char *uptr
= (const char *)ASN1_STRING_get0_data(uri
);
1938 if (strncmp(uptr
, "http://", 7) == 0)
1946 * Look through a CRLDP structure and attempt to find an http URL to
1947 * downloads a CRL from.
1950 static X509_CRL
*load_crl_crldp(STACK_OF(DIST_POINT
) *crldp
)
1953 const char *urlptr
= NULL
;
1954 for (i
= 0; i
< sk_DIST_POINT_num(crldp
); i
++) {
1955 DIST_POINT
*dp
= sk_DIST_POINT_value(crldp
, i
);
1956 urlptr
= get_dp_url(dp
);
1958 return load_crl(urlptr
, FORMAT_HTTP
, "CRL via CDP");
1964 * Example of downloading CRLs from CRLDP:
1965 * not usable for real world as it always downloads and doesn't cache anything.
1968 static STACK_OF(X509_CRL
) *crls_http_cb(const X509_STORE_CTX
*ctx
,
1969 const X509_NAME
*nm
)
1972 STACK_OF(X509_CRL
) *crls
= NULL
;
1974 STACK_OF(DIST_POINT
) *crldp
;
1976 crls
= sk_X509_CRL_new_null();
1979 x
= X509_STORE_CTX_get_current_cert(ctx
);
1980 crldp
= X509_get_ext_d2i(x
, NID_crl_distribution_points
, NULL
, NULL
);
1981 crl
= load_crl_crldp(crldp
);
1982 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
1984 sk_X509_CRL_free(crls
);
1987 sk_X509_CRL_push(crls
, crl
);
1988 /* Try to download delta CRL */
1989 crldp
= X509_get_ext_d2i(x
, NID_freshest_crl
, NULL
, NULL
);
1990 crl
= load_crl_crldp(crldp
);
1991 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
1993 sk_X509_CRL_push(crls
, crl
);
1997 void store_setup_crl_download(X509_STORE
*st
)
1999 X509_STORE_set_lookup_crls_cb(st
, crls_http_cb
);
2002 #ifndef OPENSSL_NO_SOCK
2003 static const char *tls_error_hint(void)
2005 unsigned long err
= ERR_peek_error();
2007 if (ERR_GET_LIB(err
) != ERR_LIB_SSL
)
2008 err
= ERR_peek_last_error();
2009 if (ERR_GET_LIB(err
) != ERR_LIB_SSL
)
2012 switch (ERR_GET_REASON(err
)) {
2013 case SSL_R_WRONG_VERSION_NUMBER
:
2014 return "The server does not support (a suitable version of) TLS";
2015 case SSL_R_UNKNOWN_PROTOCOL
:
2016 return "The server does not support HTTPS";
2017 case SSL_R_CERTIFICATE_VERIFY_FAILED
:
2018 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2019 case SSL_AD_REASON_OFFSET
+ TLS1_AD_UNKNOWN_CA
:
2020 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2021 case SSL_AD_REASON_OFFSET
+ SSL3_AD_HANDSHAKE_FAILURE
:
2022 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2023 default: /* no error or no hint available for error */
2028 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
2029 BIO
*app_http_tls_cb(BIO
*hbio
, void *arg
, int connect
, int detail
)
2031 APP_HTTP_TLS_INFO
*info
= (APP_HTTP_TLS_INFO
*)arg
;
2032 SSL_CTX
*ssl_ctx
= info
->ssl_ctx
;
2036 if (connect
&& detail
) { /* connecting with TLS */
2037 if ((info
->use_proxy
2038 && !OSSL_HTTP_proxy_connect(hbio
, info
->server
, info
->port
,
2039 NULL
, NULL
, /* no proxy credentials */
2040 info
->timeout
, bio_err
, opt_getprog()))
2041 || (sbio
= BIO_new(BIO_f_ssl())) == NULL
) {
2044 if (ssl_ctx
== NULL
|| (ssl
= SSL_new(ssl_ctx
)) == NULL
) {
2049 SSL_set_tlsext_host_name(ssl
, info
->server
);
2051 SSL_set_connect_state(ssl
);
2052 BIO_set_ssl(sbio
, ssl
, BIO_CLOSE
);
2054 hbio
= BIO_push(sbio
, hbio
);
2055 } else if (!connect
&& !detail
) { /* disconnecting after error */
2056 const char *hint
= tls_error_hint();
2058 ERR_add_error_data(2, " : ", hint
);
2060 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2061 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2067 ASN1_VALUE
*app_http_get_asn1(const char *url
, const char *proxy
,
2068 const char *no_proxy
, SSL_CTX
*ssl_ctx
,
2069 const STACK_OF(CONF_VALUE
) *headers
,
2070 long timeout
, const char *expected_content_type
,
2071 const ASN1_ITEM
*it
)
2073 APP_HTTP_TLS_INFO info
;
2077 ASN1_VALUE
*resp
= NULL
;
2079 if (url
== NULL
|| it
== NULL
) {
2080 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER
);
2084 if (!OSSL_HTTP_parse_url(url
, &server
, &port
, NULL
, NULL
, &use_ssl
))
2086 if (use_ssl
&& ssl_ctx
== NULL
) {
2087 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER
);
2088 ERR_add_error_data(1, "missing SSL_CTX");
2092 info
.server
= server
;
2094 info
.use_proxy
= proxy
!= NULL
;
2095 info
.timeout
= timeout
;
2096 info
.ssl_ctx
= ssl_ctx
;
2097 resp
= OSSL_HTTP_get_asn1(url
, proxy
, no_proxy
,
2098 NULL
, NULL
, app_http_tls_cb
, &info
,
2099 headers
, 0 /* maxline */, 0 /* max_resp_len */,
2100 timeout
, expected_content_type
, it
);
2102 OPENSSL_free(server
);
2108 ASN1_VALUE
*app_http_post_asn1(const char *host
, const char *port
,
2109 const char *path
, const char *proxy
,
2110 const char *no_proxy
, SSL_CTX
*ssl_ctx
,
2111 const STACK_OF(CONF_VALUE
) *headers
,
2112 const char *content_type
,
2113 ASN1_VALUE
*req
, const ASN1_ITEM
*req_it
,
2114 long timeout
, const ASN1_ITEM
*rsp_it
)
2116 APP_HTTP_TLS_INFO info
;
2120 info
.use_proxy
= proxy
!= NULL
;
2121 info
.timeout
= timeout
;
2122 info
.ssl_ctx
= ssl_ctx
;
2123 return OSSL_HTTP_post_asn1(host
, port
, path
, ssl_ctx
!= NULL
,
2125 NULL
, NULL
, app_http_tls_cb
, &info
,
2126 headers
, content_type
, req
, req_it
,
2128 0 /* max_resp_len */, timeout
, NULL
, rsp_it
);
2134 * Platform-specific sections
2139 # define fileno(a) (int)_fileno(a)
2142 # include <windows.h>
2145 static int WIN32_rename(const char *from
, const char *to
)
2147 TCHAR
*tfrom
= NULL
, *tto
;
2151 if (sizeof(TCHAR
) == 1) {
2152 tfrom
= (TCHAR
*)from
;
2154 } else { /* UNICODE path */
2156 size_t i
, flen
= strlen(from
) + 1, tlen
= strlen(to
) + 1;
2157 tfrom
= malloc(sizeof(*tfrom
) * (flen
+ tlen
));
2161 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2162 if (!MultiByteToWideChar(CP_ACP
, 0, from
, flen
, (WCHAR
*)tfrom
, flen
))
2164 for (i
= 0; i
< flen
; i
++)
2165 tfrom
[i
] = (TCHAR
)from
[i
];
2166 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2167 if (!MultiByteToWideChar(CP_ACP
, 0, to
, tlen
, (WCHAR
*)tto
, tlen
))
2169 for (i
= 0; i
< tlen
; i
++)
2170 tto
[i
] = (TCHAR
)to
[i
];
2173 if (MoveFile(tfrom
, tto
))
2175 err
= GetLastError();
2176 if (err
== ERROR_ALREADY_EXISTS
|| err
== ERROR_FILE_EXISTS
) {
2177 if (DeleteFile(tto
) && MoveFile(tfrom
, tto
))
2179 err
= GetLastError();
2181 if (err
== ERROR_FILE_NOT_FOUND
|| err
== ERROR_PATH_NOT_FOUND
)
2183 else if (err
== ERROR_ACCESS_DENIED
)
2186 errno
= EINVAL
; /* we could map more codes... */
2190 if (tfrom
!= NULL
&& tfrom
!= (TCHAR
*)from
)
2196 /* app_tminterval section */
2198 double app_tminterval(int stop
, int usertime
)
2202 static ULARGE_INTEGER tmstart
;
2203 static int warning
= 1;
2204 # ifdef _WIN32_WINNT
2205 static HANDLE proc
= NULL
;
2209 proc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
,
2210 GetCurrentProcessId());
2212 proc
= (HANDLE
) - 1;
2215 if (usertime
&& proc
!= (HANDLE
) - 1) {
2217 GetProcessTimes(proc
, &junk
, &junk
, &junk
, &now
);
2223 if (usertime
&& warning
) {
2224 BIO_printf(bio_err
, "To get meaningful results, run "
2225 "this program on idle system.\n");
2228 GetSystemTime(&systime
);
2229 SystemTimeToFileTime(&systime
, &now
);
2232 if (stop
== TM_START
) {
2233 tmstart
.u
.LowPart
= now
.dwLowDateTime
;
2234 tmstart
.u
.HighPart
= now
.dwHighDateTime
;
2236 ULARGE_INTEGER tmstop
;
2238 tmstop
.u
.LowPart
= now
.dwLowDateTime
;
2239 tmstop
.u
.HighPart
= now
.dwHighDateTime
;
2241 ret
= (__int64
)(tmstop
.QuadPart
- tmstart
.QuadPart
) * 1e-7;
2246 #elif defined(OPENSSL_SYS_VXWORKS)
2249 double app_tminterval(int stop
, int usertime
)
2252 # ifdef CLOCK_REALTIME
2253 static struct timespec tmstart
;
2254 struct timespec now
;
2256 static unsigned long tmstart
;
2259 static int warning
= 1;
2261 if (usertime
&& warning
) {
2262 BIO_printf(bio_err
, "To get meaningful results, run "
2263 "this program on idle system.\n");
2266 # ifdef CLOCK_REALTIME
2267 clock_gettime(CLOCK_REALTIME
, &now
);
2268 if (stop
== TM_START
)
2271 ret
= ((now
.tv_sec
+ now
.tv_nsec
* 1e-9)
2272 - (tmstart
.tv_sec
+ tmstart
.tv_nsec
* 1e-9));
2275 if (stop
== TM_START
)
2278 ret
= (now
- tmstart
) / (double)sysClkRateGet();
2283 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2284 # include <sys/times.h>
2286 double app_tminterval(int stop
, int usertime
)
2290 clock_t now
= times(&rus
);
2291 static clock_t tmstart
;
2294 now
= rus
.tms_utime
;
2296 if (stop
== TM_START
) {
2299 long int tck
= sysconf(_SC_CLK_TCK
);
2300 ret
= (now
- tmstart
) / (double)tck
;
2307 # include <sys/time.h>
2308 # include <sys/resource.h>
2310 double app_tminterval(int stop
, int usertime
)
2315 static struct timeval tmstart
;
2318 getrusage(RUSAGE_SELF
, &rus
), now
= rus
.ru_utime
;
2320 gettimeofday(&now
, NULL
);
2322 if (stop
== TM_START
)
2325 ret
= ((now
.tv_sec
+ now
.tv_usec
* 1e-6)
2326 - (tmstart
.tv_sec
+ tmstart
.tv_usec
* 1e-6));
2332 int app_access(const char* name
, int flag
)
2335 return _access(name
, flag
);
2337 return access(name
, flag
);
2341 int app_isdir(const char *name
)
2343 return opt_isdir(name
);
2346 /* raw_read|write section */
2348 # include "vms_term_sock.h"
2349 static int stdin_sock
= -1;
2351 static void close_stdin_sock(void)
2353 TerminalSocket (TERM_SOCK_DELETE
, &stdin_sock
);
2356 int fileno_stdin(void)
2358 if (stdin_sock
== -1) {
2359 TerminalSocket(TERM_SOCK_CREATE
, &stdin_sock
);
2360 atexit(close_stdin_sock
);
2366 int fileno_stdin(void)
2368 return fileno(stdin
);
2372 int fileno_stdout(void)
2374 return fileno(stdout
);
2377 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2378 int raw_read_stdin(void *buf
, int siz
)
2381 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2386 #elif defined(__VMS)
2387 # include <sys/socket.h>
2389 int raw_read_stdin(void *buf
, int siz
)
2391 return recv(fileno_stdin(), buf
, siz
, 0);
2394 # if defined(__TANDEM)
2395 # if defined(OPENSSL_TANDEM_FLOSS)
2396 # include <floss.h(floss_read)>
2399 int raw_read_stdin(void *buf
, int siz
)
2401 return read(fileno_stdin(), buf
, siz
);
2405 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2406 int raw_write_stdout(const void *buf
, int siz
)
2409 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2414 #elif defined(OPENSSL_SYSNAME_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
2415 # if defined(__TANDEM)
2416 # if defined(OPENSSL_TANDEM_FLOSS)
2417 # include <floss.h(floss_write)>
2420 int raw_write_stdout(const void *buf
,int siz
)
2422 return write(fileno(stdout
),(void*)buf
,siz
);
2425 # if defined(__TANDEM)
2426 # if defined(OPENSSL_TANDEM_FLOSS)
2427 # include <floss.h(floss_write)>
2430 int raw_write_stdout(const void *buf
, int siz
)
2432 return write(fileno_stdout(), buf
, siz
);
2437 * Centralized handling of input and output files with format specification
2438 * The format is meant to show what the input and output is supposed to be,
2439 * and is therefore a show of intent more than anything else. However, it
2440 * does impact behavior on some platforms, such as differentiating between
2441 * text and binary input/output on non-Unix platforms
2443 BIO
*dup_bio_in(int format
)
2445 return BIO_new_fp(stdin
,
2446 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2449 BIO
*dup_bio_out(int format
)
2451 BIO
*b
= BIO_new_fp(stdout
,
2452 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2453 void *prefix
= NULL
;
2455 #ifdef OPENSSL_SYS_VMS
2456 if (FMT_istext(format
))
2457 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2460 if (FMT_istext(format
)
2461 && (prefix
= getenv("HARNESS_OSSL_PREFIX")) != NULL
) {
2462 b
= BIO_push(BIO_new(BIO_f_prefix()), b
);
2463 BIO_set_prefix(b
, prefix
);
2469 BIO
*dup_bio_err(int format
)
2471 BIO
*b
= BIO_new_fp(stderr
,
2472 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2473 #ifdef OPENSSL_SYS_VMS
2474 if (FMT_istext(format
))
2475 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2480 void unbuffer(FILE *fp
)
2483 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2484 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2485 * However, we trust that the C RTL will never give us a FILE pointer
2486 * above the first 4 GB of memory, so we simply turn off the warning
2489 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2490 # pragma environment save
2491 # pragma message disable maylosedata2
2494 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2495 # pragma environment restore
2499 static const char *modestr(char mode
, int format
)
2501 OPENSSL_assert(mode
== 'a' || mode
== 'r' || mode
== 'w');
2505 return FMT_istext(format
) ? "a" : "ab";
2507 return FMT_istext(format
) ? "r" : "rb";
2509 return FMT_istext(format
) ? "w" : "wb";
2511 /* The assert above should make sure we never reach this point */
2515 static const char *modeverb(char mode
)
2525 return "(doing something)";
2529 * Open a file for writing, owner-read-only.
2531 BIO
*bio_open_owner(const char *filename
, int format
, int private)
2535 int fd
= -1, bflags
, mode
, textmode
;
2537 if (!private || filename
== NULL
|| strcmp(filename
, "-") == 0)
2538 return bio_open_default(filename
, 'w', format
);
2547 textmode
= FMT_istext(format
);
2551 #elif defined(_O_BINARY)
2556 #ifdef OPENSSL_SYS_VMS
2557 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2558 * it still needs to know that we're going binary, or fdopen()
2559 * will fail with "invalid argument"... so we tell VMS what the
2563 fd
= open(filename
, mode
, 0600, "ctx=bin");
2566 fd
= open(filename
, mode
, 0600);
2569 fp
= fdopen(fd
, modestr('w', format
));
2574 bflags
|= BIO_FP_TEXT
;
2575 b
= BIO_new_fp(fp
, bflags
);
2580 BIO_printf(bio_err
, "%s: Can't open \"%s\" for writing, %s\n",
2581 opt_getprog(), filename
, strerror(errno
));
2582 ERR_print_errors(bio_err
);
2583 /* If we have fp, then fdopen took over fd, so don't close both. */
2591 static BIO
*bio_open_default_(const char *filename
, char mode
, int format
,
2596 if (filename
== NULL
|| strcmp(filename
, "-") == 0) {
2597 ret
= mode
== 'r' ? dup_bio_in(format
) : dup_bio_out(format
);
2605 "Can't open %s, %s\n",
2606 mode
== 'r' ? "stdin" : "stdout", strerror(errno
));
2608 ret
= BIO_new_file(filename
, modestr(mode
, format
));
2616 "Can't open %s for %s, %s\n",
2617 filename
, modeverb(mode
), strerror(errno
));
2619 ERR_print_errors(bio_err
);
2623 BIO
*bio_open_default(const char *filename
, char mode
, int format
)
2625 return bio_open_default_(filename
, mode
, format
, 0);
2628 BIO
*bio_open_default_quiet(const char *filename
, char mode
, int format
)
2630 return bio_open_default_(filename
, mode
, format
, 1);
2633 void wait_for_async(SSL
*s
)
2635 /* On Windows select only works for sockets, so we simply don't wait */
2636 #ifndef OPENSSL_SYS_WINDOWS
2643 if (!SSL_get_all_async_fds(s
, NULL
, &numfds
))
2647 fds
= app_malloc(sizeof(OSSL_ASYNC_FD
) * numfds
, "allocate async fds");
2648 if (!SSL_get_all_async_fds(s
, fds
, &numfds
)) {
2654 for (i
= 0; i
< numfds
; i
++) {
2655 if (width
<= (int)fds
[i
])
2656 width
= (int)fds
[i
] + 1;
2657 openssl_fdset((int)fds
[i
], &asyncfds
);
2659 select(width
, (void *)&asyncfds
, NULL
, NULL
, NULL
);
2664 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2665 #if defined(OPENSSL_SYS_MSDOS)
2666 int has_stdin_waiting(void)
2668 # if defined(OPENSSL_SYS_WINDOWS)
2669 HANDLE inhand
= GetStdHandle(STD_INPUT_HANDLE
);
2671 INPUT_RECORD inputrec
;
2675 if (inhand
== INVALID_HANDLE_VALUE
) {
2679 peeked
= PeekConsoleInput(inhand
, &inputrec
, insize
, &events
);
2681 /* Probably redirected input? _kbhit() does not work in this case */
2692 /* Corrupt a signature by modifying final byte */
2693 void corrupt_signature(const ASN1_STRING
*signature
)
2695 unsigned char *s
= signature
->data
;
2696 s
[signature
->length
- 1] ^= 0x1;
2699 int set_cert_times(X509
*x
, const char *startdate
, const char *enddate
,
2702 if (startdate
== NULL
|| strcmp(startdate
, "today") == 0) {
2703 if (X509_gmtime_adj(X509_getm_notBefore(x
), 0) == NULL
)
2706 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x
), startdate
))
2709 if (enddate
== NULL
) {
2710 if (X509_time_adj_ex(X509_getm_notAfter(x
), days
, 0, NULL
)
2713 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x
), enddate
)) {
2719 int set_crl_lastupdate(X509_CRL
*crl
, const char *lastupdate
)
2722 ASN1_TIME
*tm
= ASN1_TIME_new();
2727 if (lastupdate
== NULL
) {
2728 if (X509_gmtime_adj(tm
, 0) == NULL
)
2731 if (!ASN1_TIME_set_string_X509(tm
, lastupdate
))
2735 if (!X509_CRL_set1_lastUpdate(crl
, tm
))
2744 int set_crl_nextupdate(X509_CRL
*crl
, const char *nextupdate
,
2745 long days
, long hours
, long secs
)
2748 ASN1_TIME
*tm
= ASN1_TIME_new();
2753 if (nextupdate
== NULL
) {
2754 if (X509_time_adj_ex(tm
, days
, hours
* 60 * 60 + secs
, NULL
) == NULL
)
2757 if (!ASN1_TIME_set_string_X509(tm
, nextupdate
))
2761 if (!X509_CRL_set1_nextUpdate(crl
, tm
))
2770 void make_uppercase(char *string
)
2774 for (i
= 0; string
[i
] != '\0'; i
++)
2775 string
[i
] = toupper((unsigned char)string
[i
]);
2778 int opt_printf_stderr(const char *fmt
, ...)
2784 ret
= BIO_vprintf(bio_err
, fmt
, ap
);
2789 OSSL_PARAM
*app_params_new_from_opts(STACK_OF(OPENSSL_STRING
) *opts
,
2790 const OSSL_PARAM
*paramdefs
)
2792 OSSL_PARAM
*params
= NULL
;
2793 size_t sz
= (size_t)sk_OPENSSL_STRING_num(opts
);
2795 char *opt
= "", *stmp
, *vtmp
= NULL
;
2801 params
= OPENSSL_zalloc(sizeof(OSSL_PARAM
) * (sz
+ 1));
2805 for (params_n
= 0; params_n
< sz
; params_n
++) {
2806 opt
= sk_OPENSSL_STRING_value(opts
, (int)params_n
);
2807 if ((stmp
= OPENSSL_strdup(opt
)) == NULL
2808 || (vtmp
= strchr(stmp
, ':')) == NULL
)
2810 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2812 /* Skip over the separator so that vmtp points to the value */
2814 if (!OSSL_PARAM_allocate_from_text(¶ms
[params_n
], paramdefs
,
2815 stmp
, vtmp
, strlen(vtmp
), &found
))
2819 params
[params_n
] = OSSL_PARAM_construct_end();
2823 BIO_printf(bio_err
, "Parameter %s '%s'\n", found
? "error" : "unknown",
2825 ERR_print_errors(bio_err
);
2826 app_params_free(params
);
2830 void app_params_free(OSSL_PARAM
*params
)
2834 if (params
!= NULL
) {
2835 for (i
= 0; params
[i
].key
!= NULL
; ++i
)
2836 OPENSSL_free(params
[i
].data
);
2837 OPENSSL_free(params
);