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 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
12 * On VMS, you need to define this to get the declaration of fileno(). The
13 * value 2 is to make sure no function defined in POSIX-2 is left undefined.
15 # define _POSIX_C_SOURCE 2
21 #include <sys/types.h>
22 #ifndef OPENSSL_NO_POSIX_IO
23 # include <sys/stat.h>
28 #include <openssl/err.h>
29 #include <openssl/x509.h>
30 #include <openssl/x509v3.h>
31 #include <openssl/pem.h>
32 #include <openssl/store.h>
33 #include <openssl/pkcs12.h>
34 #include <openssl/ui.h>
35 #include <openssl/safestack.h>
36 #ifndef OPENSSL_NO_RSA
37 # include <openssl/rsa.h>
39 #include <openssl/bn.h>
40 #include <openssl/ssl.h>
44 static int WIN32_rename(const char *from
, const char *to
);
45 # define rename(from,to) WIN32_rename((from),(to))
48 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
52 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32)
56 #define PASS_SOURCE_SIZE_MAX 4
66 static OSSL_LIB_CTX
*app_libctx
= NULL
;
68 static int set_table_opts(unsigned long *flags
, const char *arg
,
69 const NAME_EX_TBL
* in_tbl
);
70 static int set_multi_opts(unsigned long *flags
, const char *arg
,
71 const NAME_EX_TBL
* in_tbl
);
73 int app_init(long mesgwin
);
75 int chopup_args(ARGS
*arg
, char *buf
)
78 char c
= '\0', *p
= NULL
;
83 arg
->argv
= app_malloc(sizeof(*arg
->argv
) * arg
->size
, "argv space");
87 /* Skip whitespace. */
88 while (*p
&& isspace(_UC(*p
)))
93 /* The start of something good :-) */
94 if (arg
->argc
>= arg
->size
) {
97 tmp
= OPENSSL_realloc(arg
->argv
, sizeof(*arg
->argv
) * arg
->size
);
102 quoted
= *p
== '\'' || *p
== '"';
105 arg
->argv
[arg
->argc
++] = p
;
107 /* now look for the end of this */
109 while (*p
&& *p
!= c
)
113 while (*p
&& !isspace(_UC(*p
)))
119 arg
->argv
[arg
->argc
] = NULL
;
124 int app_init(long mesgwin
)
130 int ctx_set_verify_locations(SSL_CTX
*ctx
,
131 const char *CAfile
, int noCAfile
,
132 const char *CApath
, int noCApath
,
133 const char *CAstore
, int noCAstore
)
135 if (CAfile
== NULL
&& CApath
== NULL
&& CAstore
== NULL
) {
136 if (!noCAfile
&& SSL_CTX_set_default_verify_file(ctx
) <= 0)
138 if (!noCApath
&& SSL_CTX_set_default_verify_dir(ctx
) <= 0)
140 if (!noCAstore
&& SSL_CTX_set_default_verify_store(ctx
) <= 0)
146 if (CAfile
!= NULL
&& !SSL_CTX_load_verify_file(ctx
, CAfile
))
148 if (CApath
!= NULL
&& !SSL_CTX_load_verify_dir(ctx
, CApath
))
150 if (CAstore
!= NULL
&& !SSL_CTX_load_verify_store(ctx
, CAstore
))
155 #ifndef OPENSSL_NO_CT
157 int ctx_set_ctlog_list_file(SSL_CTX
*ctx
, const char *path
)
160 return SSL_CTX_set_default_ctlog_list_file(ctx
);
162 return SSL_CTX_set_ctlog_list_file(ctx
, path
);
167 static unsigned long nmflag
= 0;
168 static char nmflag_set
= 0;
170 int set_nameopt(const char *arg
)
172 int ret
= set_name_ex(&nmflag
, arg
);
180 unsigned long get_nameopt(void)
182 return (nmflag_set
) ? nmflag
: XN_FLAG_ONELINE
;
185 int dump_cert_text(BIO
*out
, X509
*x
)
187 print_name(out
, "subject=", X509_get_subject_name(x
), get_nameopt());
189 print_name(out
, "issuer=", X509_get_issuer_name(x
), get_nameopt());
195 int wrap_password_callback(char *buf
, int bufsiz
, int verify
, void *userdata
)
197 return password_callback(buf
, bufsiz
, verify
, (PW_CB_DATA
*)userdata
);
201 static char *app_get_pass(const char *arg
, int keepbio
);
203 char *get_passwd(const char *pass
, const char *desc
)
209 if (!app_passwd(pass
, NULL
, &result
, NULL
))
210 BIO_printf(bio_err
, "Error getting password for %s\n", desc
);
211 if (pass
!= NULL
&& result
== NULL
) {
213 "Trying plain input string (better precede with 'pass:')\n");
214 result
= OPENSSL_strdup(pass
);
216 BIO_printf(bio_err
, "Out of memory getting password for %s\n", desc
);
221 int app_passwd(const char *arg1
, const char *arg2
, char **pass1
, char **pass2
)
223 int same
= arg1
!= NULL
&& arg2
!= NULL
&& strcmp(arg1
, arg2
) == 0;
226 *pass1
= app_get_pass(arg1
, same
);
229 } else if (pass1
!= NULL
) {
233 *pass2
= app_get_pass(arg2
, same
? 2 : 0);
236 } else if (pass2
!= NULL
) {
242 static char *app_get_pass(const char *arg
, int keepbio
)
244 static BIO
*pwdbio
= NULL
;
245 char *tmp
, tpass
[APP_PASS_LEN
];
248 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
249 if (strncmp(arg
, "pass:", 5) == 0)
250 return OPENSSL_strdup(arg
+ 5);
251 if (strncmp(arg
, "env:", 4) == 0) {
252 tmp
= getenv(arg
+ 4);
254 BIO_printf(bio_err
, "No environment variable %s\n", arg
+ 4);
257 return OPENSSL_strdup(tmp
);
259 if (!keepbio
|| pwdbio
== NULL
) {
260 if (strncmp(arg
, "file:", 5) == 0) {
261 pwdbio
= BIO_new_file(arg
+ 5, "r");
262 if (pwdbio
== NULL
) {
263 BIO_printf(bio_err
, "Can't open file %s\n", arg
+ 5);
268 * Under _WIN32, which covers even Win64 and CE, file
269 * descriptors referenced by BIO_s_fd are not inherited
270 * by child process and therefore below is not an option.
271 * It could have been an option if bss_fd.c was operating
272 * on real Windows descriptors, such as those obtained
275 } else if (strncmp(arg
, "fd:", 3) == 0) {
279 pwdbio
= BIO_new_fd(i
, BIO_NOCLOSE
);
280 if ((i
< 0) || !pwdbio
) {
281 BIO_printf(bio_err
, "Can't access file descriptor %s\n", arg
+ 3);
285 * Can't do BIO_gets on an fd BIO so add a buffering BIO
287 btmp
= BIO_new(BIO_f_buffer());
288 pwdbio
= BIO_push(btmp
, pwdbio
);
290 } else if (strcmp(arg
, "stdin") == 0) {
291 pwdbio
= dup_bio_in(FORMAT_TEXT
);
292 if (pwdbio
== NULL
) {
293 BIO_printf(bio_err
, "Can't open BIO for stdin\n");
297 /* argument syntax error; do not reveal too much about arg */
298 tmp
= strchr(arg
, ':');
299 if (tmp
== NULL
|| tmp
- arg
> PASS_SOURCE_SIZE_MAX
)
301 "Invalid password argument, missing ':' within the first %d chars\n",
302 PASS_SOURCE_SIZE_MAX
+ 1);
305 "Invalid password argument, starting with \"%.*s\"\n",
306 (int)(tmp
- arg
+ 1), arg
);
310 i
= BIO_gets(pwdbio
, tpass
, APP_PASS_LEN
);
312 BIO_free_all(pwdbio
);
316 BIO_printf(bio_err
, "Error reading password from BIO\n");
319 tmp
= strchr(tpass
, '\n');
322 return OPENSSL_strdup(tpass
);
325 OSSL_LIB_CTX
*app_get0_libctx(void)
330 /* TODO(3.0): Make this an environment variable if required */
331 const char *app_get0_propq(void)
336 OSSL_LIB_CTX
*app_create_libctx(void)
339 * Load the NULL provider into the default library context and create a
340 * library context which will then be used for any OPT_PROV options.
342 if (app_libctx
== NULL
) {
344 if (!app_provider_load(NULL
, "null")) {
345 BIO_puts(bio_err
, "Failed to create null provider\n");
348 app_libctx
= OSSL_LIB_CTX_new();
350 if (app_libctx
== NULL
)
351 BIO_puts(bio_err
, "Failed to create library context\n");
355 CONF
*app_load_config_bio(BIO
*in
, const char *filename
)
361 conf
= NCONF_new_ex(app_libctx
, NULL
);
362 i
= NCONF_load_bio(conf
, in
, &errorline
);
366 if (errorline
<= 0) {
367 BIO_printf(bio_err
, "%s: Can't load ", opt_getprog());
369 BIO_printf(bio_err
, "%s: Error on line %ld of ", opt_getprog(),
372 if (filename
!= NULL
)
373 BIO_printf(bio_err
, "config file \"%s\"\n", filename
);
375 BIO_printf(bio_err
, "config input");
381 CONF
*app_load_config(const char *filename
)
386 in
= bio_open_default(filename
, 'r', FORMAT_TEXT
);
390 conf
= app_load_config_bio(in
, filename
);
395 CONF
*app_load_config_quiet(const char *filename
)
400 in
= bio_open_default_quiet(filename
, 'r', FORMAT_TEXT
);
404 conf
= app_load_config_bio(in
, filename
);
409 int app_load_modules(const CONF
*config
)
411 CONF
*to_free
= NULL
;
414 config
= to_free
= app_load_config_quiet(default_config_file
);
418 if (CONF_modules_load(config
, NULL
, 0) <= 0) {
419 BIO_printf(bio_err
, "Error configuring OpenSSL modules\n");
420 ERR_print_errors(bio_err
);
428 int add_oid_section(CONF
*conf
)
431 STACK_OF(CONF_VALUE
) *sktmp
;
435 if ((p
= NCONF_get_string(conf
, NULL
, "oid_section")) == NULL
) {
439 if ((sktmp
= NCONF_get_section(conf
, p
)) == NULL
) {
440 BIO_printf(bio_err
, "problem loading oid section %s\n", p
);
443 for (i
= 0; i
< sk_CONF_VALUE_num(sktmp
); i
++) {
444 cnf
= sk_CONF_VALUE_value(sktmp
, i
);
445 if (OBJ_create(cnf
->value
, cnf
->name
, cnf
->name
) == NID_undef
) {
446 BIO_printf(bio_err
, "problem creating object %s=%s\n",
447 cnf
->name
, cnf
->value
);
454 CONF
*app_load_config_modules(const char *configfile
)
458 if (configfile
!= NULL
) {
459 BIO_printf(bio_err
, "Using configuration from %s\n", configfile
);
461 if ((conf
= app_load_config(configfile
)) == NULL
)
463 if (configfile
!= default_config_file
&& !app_load_modules(conf
)) {
471 X509
*load_cert_pass(const char *uri
, int maybe_stdin
,
472 const char *pass
, const char *desc
)
477 desc
= "certificate";
478 (void)load_key_certs_crls(uri
, maybe_stdin
, pass
, desc
,
479 NULL
, NULL
, NULL
, &cert
, NULL
, NULL
, NULL
);
481 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
482 ERR_print_errors(bio_err
);
487 /* the format parameter is meanwhile not needed anymore and thus ignored */
488 X509_CRL
*load_crl(const char *uri
, const char *desc
)
490 X509_CRL
*crl
= NULL
;
494 (void)load_key_certs_crls(uri
, 0, NULL
, desc
,
495 NULL
, NULL
, NULL
, NULL
, NULL
, &crl
, NULL
);
497 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
498 ERR_print_errors(bio_err
);
503 X509_REQ
*load_csr(const char *file
, int format
, const char *desc
)
505 X509_REQ
*req
= NULL
;
510 in
= bio_open_default(file
, 'r', format
);
514 if (format
== FORMAT_ASN1
)
515 req
= d2i_X509_REQ_bio(in
, NULL
);
516 else if (format
== FORMAT_PEM
)
517 req
= PEM_read_bio_X509_REQ(in
, NULL
, NULL
, NULL
);
519 print_format_error(format
, OPT_FMT_PEMDER
);
523 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
524 ERR_print_errors(bio_err
);
530 void cleanse(char *str
)
533 OPENSSL_cleanse(str
, strlen(str
));
536 void clear_free(char *str
)
539 OPENSSL_clear_free(str
, strlen(str
));
542 EVP_PKEY
*load_key(const char *uri
, int format
, int may_stdin
,
543 const char *pass
, ENGINE
*e
, const char *desc
)
545 EVP_PKEY
*pkey
= NULL
;
548 desc
= "private key";
550 if (format
== FORMAT_ENGINE
) {
552 BIO_printf(bio_err
, "No engine specified for loading %s\n", desc
);
554 pkey
= load_engine_private_key(e
, uri
, pass
, desc
);
556 BIO_printf(bio_err
, "Cannot load %s from engine\n", desc
);
557 ERR_print_errors(bio_err
);
561 (void)load_key_certs_crls(uri
, may_stdin
, pass
, desc
,
562 &pkey
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
);
568 EVP_PKEY
*load_pubkey(const char *uri
, int format
, int maybe_stdin
,
569 const char *pass
, ENGINE
*e
, const char *desc
)
571 EVP_PKEY
*pkey
= NULL
;
576 if (format
== FORMAT_ENGINE
) {
578 BIO_printf(bio_err
, "No engine specified for loading %s\n", desc
);
580 pkey
= load_engine_public_key(e
, uri
, pass
, desc
);
582 BIO_printf(bio_err
, "Cannot load %s from engine\n", desc
);
583 ERR_print_errors(bio_err
);
587 (void)load_key_certs_crls(uri
, maybe_stdin
, pass
, desc
,
588 NULL
, &pkey
, NULL
, NULL
, NULL
, NULL
, NULL
);
594 EVP_PKEY
*load_keyparams(const char *uri
, int maybe_stdin
, const char *keytype
,
597 EVP_PKEY
*params
= NULL
;
600 desc
= "key parameters";
602 (void)load_key_certs_crls(uri
, maybe_stdin
, NULL
, desc
,
603 NULL
, NULL
, ¶ms
, NULL
, NULL
, NULL
, NULL
);
604 if (params
!= NULL
&& keytype
!= NULL
&& !EVP_PKEY_is_a(params
, keytype
)) {
606 "Unable to load %s from %s (unexpected parameters type)\n",
608 ERR_print_errors(bio_err
);
609 EVP_PKEY_free(params
);
615 void app_bail_out(char *fmt
, ...)
620 BIO_vprintf(bio_err
, fmt
, args
);
622 ERR_print_errors(bio_err
);
626 void* app_malloc(int sz
, const char *what
)
628 void *vp
= OPENSSL_malloc(sz
);
631 app_bail_out("%s: Could not allocate %d bytes for %s\n",
632 opt_getprog(), sz
, what
);
637 * Initialize or extend, if *certs != NULL, a certificate stack.
638 * The caller is responsible for freeing *certs if its value is left not NULL.
640 int load_certs(const char *uri
, STACK_OF(X509
) **certs
,
641 const char *pass
, const char *desc
)
643 int was_NULL
= *certs
== NULL
;
644 int ret
= load_key_certs_crls(uri
, 0, pass
, desc
, NULL
, NULL
, NULL
,
645 NULL
, certs
, NULL
, NULL
);
647 if (!ret
&& was_NULL
) {
648 sk_X509_pop_free(*certs
, X509_free
);
655 * Initialize or extend, if *crls != NULL, a certificate stack.
656 * The caller is responsible for freeing *crls if its value is left not NULL.
658 int load_crls(const char *uri
, STACK_OF(X509_CRL
) **crls
,
659 const char *pass
, const char *desc
)
661 int was_NULL
= *crls
== NULL
;
662 int ret
= load_key_certs_crls(uri
, 0, pass
, desc
, NULL
, NULL
, NULL
,
663 NULL
, NULL
, NULL
, crls
);
665 if (!ret
&& was_NULL
) {
666 sk_X509_CRL_pop_free(*crls
, X509_CRL_free
);
673 * Load those types of credentials for which the result pointer is not NULL.
674 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
675 * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
676 * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
677 * If pcerts is non-NULL then all available certificates are appended to *pcerts
678 * except any certificate assigned to *pcert.
679 * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
680 * If pcrls is non-NULL then all available CRLs are appended to *pcerts
681 * except any CRL assigned to *pcrl.
682 * In any case (also on error) the caller is responsible for freeing all members
683 * of *pcerts and *pcrls (as far as they are not NULL).
685 int load_key_certs_crls(const char *uri
, int maybe_stdin
,
686 const char *pass
, const char *desc
,
687 EVP_PKEY
**ppkey
, EVP_PKEY
**ppubkey
,
689 X509
**pcert
, STACK_OF(X509
) **pcerts
,
690 X509_CRL
**pcrl
, STACK_OF(X509_CRL
) **pcrls
)
693 OSSL_STORE_CTX
*ctx
= NULL
;
694 OSSL_LIB_CTX
*libctx
= app_get0_libctx();
695 const char *propq
= app_get0_propq();
699 ppkey
!= NULL
? "key" : ppubkey
!= NULL
? "public key" :
700 pparams
!= NULL
? "params" : pcert
!= NULL
? "cert" :
701 pcrl
!= NULL
? "CRL" : pcerts
!= NULL
? "certs" :
702 pcrls
!= NULL
? "CRLs" : NULL
;
703 /* TODO make use of the engine reference 'eng' when loading pkeys */
711 if (failed
== NULL
) {
712 BIO_printf(bio_err
, "Internal error: nothing to load into from %s\n",
713 uri
!= NULL
? uri
: "<stdin>");
717 if (pcerts
!= NULL
&& *pcerts
== NULL
718 && (*pcerts
= sk_X509_new_null()) == NULL
) {
719 BIO_printf(bio_err
, "Out of memory loading");
724 if (pcrls
!= NULL
&& *pcrls
== NULL
725 && (*pcrls
= sk_X509_CRL_new_null()) == NULL
) {
726 BIO_printf(bio_err
, "Out of memory loading");
730 uidata
.password
= pass
;
731 uidata
.prompt_info
= uri
;
737 BIO_printf(bio_err
, "No filename or uri specified for loading");
742 bio
= BIO_new_fp(stdin
, 0);
744 ctx
= OSSL_STORE_attach(bio
, "file", libctx
, propq
,
745 get_ui_method(), &uidata
, NULL
, NULL
);
747 ctx
= OSSL_STORE_open_ex(uri
, libctx
, propq
, get_ui_method(), &uidata
,
751 BIO_printf(bio_err
, "Could not open file or uri for loading");
756 while (!OSSL_STORE_eof(ctx
)) {
757 OSSL_STORE_INFO
*info
= OSSL_STORE_load(ctx
);
762 type
= OSSL_STORE_INFO_get_type(info
);
764 case OSSL_STORE_INFO_PKEY
:
765 if (ppkey
!= NULL
&& *ppkey
== NULL
)
766 ok
= (*ppkey
= OSSL_STORE_INFO_get1_PKEY(info
)) != NULL
;
769 * An EVP_PKEY with private parts also holds the public parts,
770 * so if the caller asked for a public key, and we got a private
771 * key, we can still pass it back.
773 if (ok
&& ppubkey
!= NULL
&& *ppubkey
== NULL
)
774 ok
= ((*ppubkey
= OSSL_STORE_INFO_get1_PKEY(info
)) != NULL
);
776 case OSSL_STORE_INFO_PUBKEY
:
777 if (ppubkey
!= NULL
&& *ppubkey
== NULL
)
778 ok
= ((*ppubkey
= OSSL_STORE_INFO_get1_PUBKEY(info
)) != NULL
);
780 case OSSL_STORE_INFO_PARAMS
:
781 if (pparams
!= NULL
&& *pparams
== NULL
)
782 ok
= ((*pparams
= OSSL_STORE_INFO_get1_PARAMS(info
)) != NULL
);
784 case OSSL_STORE_INFO_CERT
:
785 if (pcert
!= NULL
&& *pcert
== NULL
)
786 ok
= (*pcert
= OSSL_STORE_INFO_get1_CERT(info
)) != NULL
;
787 else if (pcerts
!= NULL
)
788 ok
= X509_add_cert(*pcerts
,
789 OSSL_STORE_INFO_get1_CERT(info
),
790 X509_ADD_FLAG_DEFAULT
);
793 case OSSL_STORE_INFO_CRL
:
794 if (pcrl
!= NULL
&& *pcrl
== NULL
)
795 ok
= (*pcrl
= OSSL_STORE_INFO_get1_CRL(info
)) != NULL
;
796 else if (pcrls
!= NULL
)
797 ok
= sk_X509_CRL_push(*pcrls
, OSSL_STORE_INFO_get1_CRL(info
));
801 /* skip any other type */
804 OSSL_STORE_INFO_free(info
);
806 failed
= info
== NULL
? NULL
: OSSL_STORE_INFO_type_string(type
);
807 BIO_printf(bio_err
, "Error reading");
813 OSSL_STORE_close(ctx
);
814 if (failed
== NULL
) {
817 if ((ppkey
!= NULL
&& *ppkey
== NULL
)
818 || (ppubkey
!= NULL
&& *ppubkey
== NULL
)) {
820 } else if (pparams
!= NULL
&& *pparams
== NULL
) {
822 } else if ((pcert
!= NULL
|| pcerts
!= NULL
) && ncerts
== 0) {
826 } else if ((pcrl
!= NULL
|| pcrls
!= NULL
) && ncrls
== 0) {
832 BIO_printf(bio_err
, "Could not read");
834 BIO_printf(bio_err
, " any");
836 if (failed
!= NULL
) {
837 if (desc
!= NULL
&& strstr(desc
, failed
) != NULL
) {
838 BIO_printf(bio_err
, " %s", desc
);
840 BIO_printf(bio_err
, " %s", failed
);
842 BIO_printf(bio_err
, " of %s", desc
);
845 BIO_printf(bio_err
, " from %s", uri
);
846 BIO_printf(bio_err
, "\n");
847 ERR_print_errors(bio_err
);
849 return failed
== NULL
;
853 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
854 /* Return error for unknown extensions */
855 #define X509V3_EXT_DEFAULT 0
856 /* Print error for unknown extensions */
857 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
858 /* ASN1 parse unknown extensions */
859 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
860 /* BIO_dump unknown extensions */
861 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
863 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
864 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
866 int set_cert_ex(unsigned long *flags
, const char *arg
)
868 static const NAME_EX_TBL cert_tbl
[] = {
869 {"compatible", X509_FLAG_COMPAT
, 0xffffffffl
},
870 {"ca_default", X509_FLAG_CA
, 0xffffffffl
},
871 {"no_header", X509_FLAG_NO_HEADER
, 0},
872 {"no_version", X509_FLAG_NO_VERSION
, 0},
873 {"no_serial", X509_FLAG_NO_SERIAL
, 0},
874 {"no_signame", X509_FLAG_NO_SIGNAME
, 0},
875 {"no_validity", X509_FLAG_NO_VALIDITY
, 0},
876 {"no_subject", X509_FLAG_NO_SUBJECT
, 0},
877 {"no_issuer", X509_FLAG_NO_ISSUER
, 0},
878 {"no_pubkey", X509_FLAG_NO_PUBKEY
, 0},
879 {"no_extensions", X509_FLAG_NO_EXTENSIONS
, 0},
880 {"no_sigdump", X509_FLAG_NO_SIGDUMP
, 0},
881 {"no_aux", X509_FLAG_NO_AUX
, 0},
882 {"no_attributes", X509_FLAG_NO_ATTRIBUTES
, 0},
883 {"ext_default", X509V3_EXT_DEFAULT
, X509V3_EXT_UNKNOWN_MASK
},
884 {"ext_error", X509V3_EXT_ERROR_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
885 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
886 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
889 return set_multi_opts(flags
, arg
, cert_tbl
);
892 int set_name_ex(unsigned long *flags
, const char *arg
)
894 static const NAME_EX_TBL ex_tbl
[] = {
895 {"esc_2253", ASN1_STRFLGS_ESC_2253
, 0},
896 {"esc_2254", ASN1_STRFLGS_ESC_2254
, 0},
897 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL
, 0},
898 {"esc_msb", ASN1_STRFLGS_ESC_MSB
, 0},
899 {"use_quote", ASN1_STRFLGS_ESC_QUOTE
, 0},
900 {"utf8", ASN1_STRFLGS_UTF8_CONVERT
, 0},
901 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE
, 0},
902 {"show_type", ASN1_STRFLGS_SHOW_TYPE
, 0},
903 {"dump_all", ASN1_STRFLGS_DUMP_ALL
, 0},
904 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN
, 0},
905 {"dump_der", ASN1_STRFLGS_DUMP_DER
, 0},
906 {"compat", XN_FLAG_COMPAT
, 0xffffffffL
},
907 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS
, XN_FLAG_SEP_MASK
},
908 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC
, XN_FLAG_SEP_MASK
},
909 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC
, XN_FLAG_SEP_MASK
},
910 {"sep_multiline", XN_FLAG_SEP_MULTILINE
, XN_FLAG_SEP_MASK
},
911 {"dn_rev", XN_FLAG_DN_REV
, 0},
912 {"nofname", XN_FLAG_FN_NONE
, XN_FLAG_FN_MASK
},
913 {"sname", XN_FLAG_FN_SN
, XN_FLAG_FN_MASK
},
914 {"lname", XN_FLAG_FN_LN
, XN_FLAG_FN_MASK
},
915 {"align", XN_FLAG_FN_ALIGN
, 0},
916 {"oid", XN_FLAG_FN_OID
, XN_FLAG_FN_MASK
},
917 {"space_eq", XN_FLAG_SPC_EQ
, 0},
918 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS
, 0},
919 {"RFC2253", XN_FLAG_RFC2253
, 0xffffffffL
},
920 {"oneline", XN_FLAG_ONELINE
, 0xffffffffL
},
921 {"multiline", XN_FLAG_MULTILINE
, 0xffffffffL
},
922 {"ca_default", XN_FLAG_MULTILINE
, 0xffffffffL
},
925 if (set_multi_opts(flags
, arg
, ex_tbl
) == 0)
927 if (*flags
!= XN_FLAG_COMPAT
928 && (*flags
& XN_FLAG_SEP_MASK
) == 0)
929 *flags
|= XN_FLAG_SEP_CPLUS_SPC
;
933 int set_ext_copy(int *copy_type
, const char *arg
)
935 if (strcasecmp(arg
, "none") == 0)
936 *copy_type
= EXT_COPY_NONE
;
937 else if (strcasecmp(arg
, "copy") == 0)
938 *copy_type
= EXT_COPY_ADD
;
939 else if (strcasecmp(arg
, "copyall") == 0)
940 *copy_type
= EXT_COPY_ALL
;
946 int copy_extensions(X509
*x
, X509_REQ
*req
, int copy_type
)
948 STACK_OF(X509_EXTENSION
) *exts
= NULL
;
949 X509_EXTENSION
*ext
, *tmpext
;
952 if (!x
|| !req
|| (copy_type
== EXT_COPY_NONE
))
954 exts
= X509_REQ_get_extensions(req
);
956 for (i
= 0; i
< sk_X509_EXTENSION_num(exts
); i
++) {
957 ext
= sk_X509_EXTENSION_value(exts
, i
);
958 obj
= X509_EXTENSION_get_object(ext
);
959 idx
= X509_get_ext_by_OBJ(x
, obj
, -1);
960 /* Does extension exist? */
962 /* If normal copy don't override existing extension */
963 if (copy_type
== EXT_COPY_ADD
)
965 /* Delete all extensions of same type */
967 tmpext
= X509_get_ext(x
, idx
);
968 X509_delete_ext(x
, idx
);
969 X509_EXTENSION_free(tmpext
);
970 idx
= X509_get_ext_by_OBJ(x
, obj
, -1);
973 if (!X509_add_ext(x
, ext
, -1))
981 sk_X509_EXTENSION_pop_free(exts
, X509_EXTENSION_free
);
986 static int set_multi_opts(unsigned long *flags
, const char *arg
,
987 const NAME_EX_TBL
* in_tbl
)
989 STACK_OF(CONF_VALUE
) *vals
;
994 vals
= X509V3_parse_list(arg
);
995 for (i
= 0; i
< sk_CONF_VALUE_num(vals
); i
++) {
996 val
= sk_CONF_VALUE_value(vals
, i
);
997 if (!set_table_opts(flags
, val
->name
, in_tbl
))
1000 sk_CONF_VALUE_pop_free(vals
, X509V3_conf_free
);
1004 static int set_table_opts(unsigned long *flags
, const char *arg
,
1005 const NAME_EX_TBL
* in_tbl
)
1008 const NAME_EX_TBL
*ptbl
;
1014 } else if (c
== '+') {
1021 for (ptbl
= in_tbl
; ptbl
->name
; ptbl
++) {
1022 if (strcasecmp(arg
, ptbl
->name
) == 0) {
1023 *flags
&= ~ptbl
->mask
;
1025 *flags
|= ptbl
->flag
;
1027 *flags
&= ~ptbl
->flag
;
1034 void print_name(BIO
*out
, const char *title
, const X509_NAME
*nm
,
1035 unsigned long lflags
)
1042 BIO_puts(out
, title
);
1043 if ((lflags
& XN_FLAG_SEP_MASK
) == XN_FLAG_SEP_MULTILINE
) {
1047 if (lflags
== XN_FLAG_COMPAT
) {
1048 buf
= X509_NAME_oneline(nm
, 0, 0);
1050 BIO_puts(out
, "\n");
1054 BIO_puts(out
, "\n");
1055 X509_NAME_print_ex(out
, nm
, indent
, lflags
);
1056 BIO_puts(out
, "\n");
1060 void print_bignum_var(BIO
*out
, const BIGNUM
*in
, const char *var
,
1061 int len
, unsigned char *buffer
)
1063 BIO_printf(out
, " static unsigned char %s_%d[] = {", var
, len
);
1064 if (BN_is_zero(in
)) {
1065 BIO_printf(out
, "\n 0x00");
1069 l
= BN_bn2bin(in
, buffer
);
1070 for (i
= 0; i
< l
; i
++) {
1071 BIO_printf(out
, (i
% 10) == 0 ? "\n " : " ");
1073 BIO_printf(out
, "0x%02X,", buffer
[i
]);
1075 BIO_printf(out
, "0x%02X", buffer
[i
]);
1078 BIO_printf(out
, "\n };\n");
1081 void print_array(BIO
*out
, const char* title
, int len
, const unsigned char* d
)
1085 BIO_printf(out
, "unsigned char %s[%d] = {", title
, len
);
1086 for (i
= 0; i
< len
; i
++) {
1088 BIO_printf(out
, "\n ");
1090 BIO_printf(out
, "0x%02X, ", d
[i
]);
1092 BIO_printf(out
, "0x%02X", d
[i
]);
1094 BIO_printf(out
, "\n};\n");
1097 X509_STORE
*setup_verify(const char *CAfile
, int noCAfile
,
1098 const char *CApath
, int noCApath
,
1099 const char *CAstore
, int noCAstore
)
1101 X509_STORE
*store
= X509_STORE_new();
1102 X509_LOOKUP
*lookup
;
1103 OSSL_LIB_CTX
*libctx
= app_get0_libctx();
1104 const char *propq
= app_get0_propq();
1109 if (CAfile
!= NULL
|| !noCAfile
) {
1110 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_file());
1113 if (CAfile
!= NULL
) {
1114 if (!X509_LOOKUP_load_file_ex(lookup
, CAfile
, X509_FILETYPE_PEM
,
1116 BIO_printf(bio_err
, "Error loading file %s\n", CAfile
);
1120 X509_LOOKUP_load_file_ex(lookup
, NULL
, X509_FILETYPE_DEFAULT
,
1125 if (CApath
!= NULL
|| !noCApath
) {
1126 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_hash_dir());
1129 if (CApath
!= NULL
) {
1130 if (!X509_LOOKUP_add_dir(lookup
, CApath
, X509_FILETYPE_PEM
)) {
1131 BIO_printf(bio_err
, "Error loading directory %s\n", CApath
);
1135 X509_LOOKUP_add_dir(lookup
, NULL
, X509_FILETYPE_DEFAULT
);
1139 if (CAstore
!= NULL
|| !noCAstore
) {
1140 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_store());
1143 if (!X509_LOOKUP_add_store_ex(lookup
, CAstore
, libctx
, propq
)) {
1144 if (CAstore
!= NULL
)
1145 BIO_printf(bio_err
, "Error loading store URI %s\n", CAstore
);
1153 ERR_print_errors(bio_err
);
1154 X509_STORE_free(store
);
1158 static unsigned long index_serial_hash(const OPENSSL_CSTRING
*a
)
1165 return OPENSSL_LH_strhash(n
);
1168 static int index_serial_cmp(const OPENSSL_CSTRING
*a
,
1169 const OPENSSL_CSTRING
*b
)
1171 const char *aa
, *bb
;
1173 for (aa
= a
[DB_serial
]; *aa
== '0'; aa
++) ;
1174 for (bb
= b
[DB_serial
]; *bb
== '0'; bb
++) ;
1175 return strcmp(aa
, bb
);
1178 static int index_name_qual(char **a
)
1180 return (a
[0][0] == 'V');
1183 static unsigned long index_name_hash(const OPENSSL_CSTRING
*a
)
1185 return OPENSSL_LH_strhash(a
[DB_name
]);
1188 int index_name_cmp(const OPENSSL_CSTRING
*a
, const OPENSSL_CSTRING
*b
)
1190 return strcmp(a
[DB_name
], b
[DB_name
]);
1193 static IMPLEMENT_LHASH_HASH_FN(index_serial
, OPENSSL_CSTRING
)
1194 static IMPLEMENT_LHASH_COMP_FN(index_serial
, OPENSSL_CSTRING
)
1195 static IMPLEMENT_LHASH_HASH_FN(index_name
, OPENSSL_CSTRING
)
1196 static IMPLEMENT_LHASH_COMP_FN(index_name
, OPENSSL_CSTRING
)
1199 BIGNUM
*load_serial(const char *serialfile
, int create
, ASN1_INTEGER
**retai
)
1204 ASN1_INTEGER
*ai
= NULL
;
1206 ai
= ASN1_INTEGER_new();
1210 in
= BIO_new_file(serialfile
, "r");
1218 if (ret
== NULL
|| !rand_serial(ret
, ai
))
1219 BIO_printf(bio_err
, "Out of memory\n");
1221 if (!a2i_ASN1_INTEGER(in
, ai
, buf
, 1024)) {
1222 BIO_printf(bio_err
, "Unable to load number from %s\n",
1226 ret
= ASN1_INTEGER_to_BN(ai
, NULL
);
1228 BIO_printf(bio_err
, "Error converting number from bin to BIGNUM\n");
1238 ERR_print_errors(bio_err
);
1240 ASN1_INTEGER_free(ai
);
1244 int save_serial(const char *serialfile
, const char *suffix
, const BIGNUM
*serial
,
1245 ASN1_INTEGER
**retai
)
1250 ASN1_INTEGER
*ai
= NULL
;
1254 j
= strlen(serialfile
);
1256 j
= strlen(serialfile
) + strlen(suffix
) + 1;
1258 BIO_printf(bio_err
, "File name too long\n");
1263 OPENSSL_strlcpy(buf
[0], serialfile
, BSIZE
);
1265 #ifndef OPENSSL_SYS_VMS
1266 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, suffix
);
1268 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, suffix
);
1271 out
= BIO_new_file(buf
[0], "w");
1276 if ((ai
= BN_to_ASN1_INTEGER(serial
, NULL
)) == NULL
) {
1277 BIO_printf(bio_err
, "error converting serial to ASN.1 format\n");
1280 i2a_ASN1_INTEGER(out
, ai
);
1281 BIO_puts(out
, "\n");
1289 ERR_print_errors(bio_err
);
1291 ASN1_INTEGER_free(ai
);
1295 int rotate_serial(const char *serialfile
, const char *new_suffix
,
1296 const char *old_suffix
)
1301 i
= strlen(serialfile
) + strlen(old_suffix
);
1302 j
= strlen(serialfile
) + strlen(new_suffix
);
1305 if (j
+ 1 >= BSIZE
) {
1306 BIO_printf(bio_err
, "File name too long\n");
1309 #ifndef OPENSSL_SYS_VMS
1310 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, new_suffix
);
1311 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", serialfile
, old_suffix
);
1313 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, new_suffix
);
1314 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", serialfile
, old_suffix
);
1316 if (rename(serialfile
, buf
[1]) < 0 && errno
!= ENOENT
1322 "Unable to rename %s to %s\n", serialfile
, buf
[1]);
1326 if (rename(buf
[0], serialfile
) < 0) {
1328 "Unable to rename %s to %s\n", buf
[0], serialfile
);
1330 rename(buf
[1], serialfile
);
1335 ERR_print_errors(bio_err
);
1339 int rand_serial(BIGNUM
*b
, ASN1_INTEGER
*ai
)
1344 btmp
= b
== NULL
? BN_new() : b
;
1348 if (!BN_rand(btmp
, SERIAL_RAND_BITS
, BN_RAND_TOP_ANY
, BN_RAND_BOTTOM_ANY
))
1350 if (ai
&& !BN_to_ASN1_INTEGER(btmp
, ai
))
1363 CA_DB
*load_index(const char *dbfile
, DB_ATTR
*db_attr
)
1365 CA_DB
*retdb
= NULL
;
1366 TXT_DB
*tmpdb
= NULL
;
1368 CONF
*dbattr_conf
= NULL
;
1370 #ifndef OPENSSL_NO_POSIX_IO
1375 in
= BIO_new_file(dbfile
, "r");
1379 #ifndef OPENSSL_NO_POSIX_IO
1380 BIO_get_fp(in
, &dbfp
);
1381 if (fstat(fileno(dbfp
), &dbst
) == -1) {
1382 ERR_raise_data(ERR_LIB_SYS
, errno
,
1383 "calling fstat(%s)", dbfile
);
1388 if ((tmpdb
= TXT_DB_read(in
, DB_NUMBER
)) == NULL
)
1391 #ifndef OPENSSL_SYS_VMS
1392 BIO_snprintf(buf
, sizeof(buf
), "%s.attr", dbfile
);
1394 BIO_snprintf(buf
, sizeof(buf
), "%s-attr", dbfile
);
1396 dbattr_conf
= app_load_config_quiet(buf
);
1398 retdb
= app_malloc(sizeof(*retdb
), "new DB");
1402 retdb
->attributes
= *db_attr
;
1404 retdb
->attributes
.unique_subject
= 1;
1408 char *p
= NCONF_get_string(dbattr_conf
, NULL
, "unique_subject");
1410 retdb
->attributes
.unique_subject
= parse_yesno(p
, 1);
1414 retdb
->dbfname
= OPENSSL_strdup(dbfile
);
1415 #ifndef OPENSSL_NO_POSIX_IO
1420 ERR_print_errors(bio_err
);
1421 NCONF_free(dbattr_conf
);
1428 * Returns > 0 on success, <= 0 on error
1430 int index_index(CA_DB
*db
)
1432 if (!TXT_DB_create_index(db
->db
, DB_serial
, NULL
,
1433 LHASH_HASH_FN(index_serial
),
1434 LHASH_COMP_FN(index_serial
))) {
1436 "Error creating serial number index:(%ld,%ld,%ld)\n",
1437 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1441 if (db
->attributes
.unique_subject
1442 && !TXT_DB_create_index(db
->db
, DB_name
, index_name_qual
,
1443 LHASH_HASH_FN(index_name
),
1444 LHASH_COMP_FN(index_name
))) {
1445 BIO_printf(bio_err
, "Error creating name index:(%ld,%ld,%ld)\n",
1446 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1451 ERR_print_errors(bio_err
);
1455 int save_index(const char *dbfile
, const char *suffix
, CA_DB
*db
)
1461 j
= strlen(dbfile
) + strlen(suffix
);
1462 if (j
+ 6 >= BSIZE
) {
1463 BIO_printf(bio_err
, "File name too long\n");
1466 #ifndef OPENSSL_SYS_VMS
1467 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr", dbfile
);
1468 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.attr.%s", dbfile
, suffix
);
1469 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, suffix
);
1471 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr", dbfile
);
1472 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-attr-%s", dbfile
, suffix
);
1473 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, suffix
);
1475 out
= BIO_new_file(buf
[0], "w");
1478 BIO_printf(bio_err
, "Unable to open '%s'\n", dbfile
);
1481 j
= TXT_DB_write(out
, db
->db
);
1486 out
= BIO_new_file(buf
[1], "w");
1489 BIO_printf(bio_err
, "Unable to open '%s'\n", buf
[2]);
1492 BIO_printf(out
, "unique_subject = %s\n",
1493 db
->attributes
.unique_subject
? "yes" : "no");
1498 ERR_print_errors(bio_err
);
1502 int rotate_index(const char *dbfile
, const char *new_suffix
,
1503 const char *old_suffix
)
1508 i
= strlen(dbfile
) + strlen(old_suffix
);
1509 j
= strlen(dbfile
) + strlen(new_suffix
);
1512 if (j
+ 6 >= BSIZE
) {
1513 BIO_printf(bio_err
, "File name too long\n");
1516 #ifndef OPENSSL_SYS_VMS
1517 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s.attr", dbfile
);
1518 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s.attr.%s", dbfile
, old_suffix
);
1519 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr.%s", dbfile
, new_suffix
);
1520 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", dbfile
, old_suffix
);
1521 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, new_suffix
);
1523 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s-attr", dbfile
);
1524 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s-attr-%s", dbfile
, old_suffix
);
1525 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr-%s", dbfile
, new_suffix
);
1526 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", dbfile
, old_suffix
);
1527 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, new_suffix
);
1529 if (rename(dbfile
, buf
[1]) < 0 && errno
!= ENOENT
1534 BIO_printf(bio_err
, "Unable to rename %s to %s\n", dbfile
, buf
[1]);
1538 if (rename(buf
[0], dbfile
) < 0) {
1539 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[0], dbfile
);
1541 rename(buf
[1], dbfile
);
1544 if (rename(buf
[4], buf
[3]) < 0 && errno
!= ENOENT
1549 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[4], buf
[3]);
1551 rename(dbfile
, buf
[0]);
1552 rename(buf
[1], dbfile
);
1555 if (rename(buf
[2], buf
[4]) < 0) {
1556 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[2], buf
[4]);
1558 rename(buf
[3], buf
[4]);
1559 rename(dbfile
, buf
[0]);
1560 rename(buf
[1], dbfile
);
1565 ERR_print_errors(bio_err
);
1569 void free_index(CA_DB
*db
)
1572 TXT_DB_free(db
->db
);
1573 OPENSSL_free(db
->dbfname
);
1578 int parse_yesno(const char *str
, int def
)
1582 case 'f': /* false */
1583 case 'F': /* FALSE */
1588 case 't': /* true */
1589 case 'T': /* TRUE */
1600 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1601 * where + can be used instead of / to form multi-valued RDNs if canmulti
1602 * and characters may be escaped by \
1604 X509_NAME
*parse_name(const char *cp
, int chtype
, int canmulti
,
1607 int nextismulti
= 0;
1613 "%s: %s name is expected to be in the format "
1614 "/type0=value0/type1=value1/type2=... where characters may "
1615 "be escaped by \\. This name is not in that format: '%s'\n",
1616 opt_getprog(), desc
, --cp
);
1620 n
= X509_NAME_new();
1622 BIO_printf(bio_err
, "%s: Out of memory\n", opt_getprog());
1625 work
= OPENSSL_strdup(cp
);
1627 BIO_printf(bio_err
, "%s: Error copying %s name input\n",
1628 opt_getprog(), desc
);
1632 while (*cp
!= '\0') {
1635 unsigned char *valstr
;
1637 int ismulti
= nextismulti
;
1640 /* Collect the type */
1641 while (*cp
!= '\0' && *cp
!= '=')
1646 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1647 opt_getprog(), typestr
, desc
);
1652 /* Collect the value. */
1653 valstr
= (unsigned char *)bp
;
1654 for (; *cp
!= '\0' && *cp
!= '/'; *bp
++ = *cp
++) {
1655 /* unescaped '+' symbol string signals further member of multiRDN */
1656 if (canmulti
&& *cp
== '+') {
1660 if (*cp
== '\\' && *++cp
== '\0') {
1662 "%s: Escape character at end of %s name string\n",
1663 opt_getprog(), desc
);
1669 /* If not at EOS (must be + or /), move forward. */
1674 nid
= OBJ_txt2nid(typestr
);
1675 if (nid
== NID_undef
) {
1677 "%s: Skipping unknown %s name attribute \"%s\"\n",
1678 opt_getprog(), desc
, typestr
);
1681 "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
1684 if (*valstr
== '\0') {
1686 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1687 opt_getprog(), desc
, typestr
);
1690 if (!X509_NAME_add_entry_by_NID(n
, nid
, chtype
,
1691 valstr
, strlen((char *)valstr
),
1692 -1, ismulti
? -1 : 0)) {
1693 ERR_print_errors(bio_err
);
1695 "%s: Error adding %s name attribute \"/%s=%s\"\n",
1696 opt_getprog(), desc
, typestr
,valstr
);
1711 * Read whole contents of a BIO into an allocated memory buffer and return
1715 int bio_to_mem(unsigned char **out
, int maxlen
, BIO
*in
)
1719 unsigned char tbuf
[1024];
1721 mem
= BIO_new(BIO_s_mem());
1725 if ((maxlen
!= -1) && maxlen
< 1024)
1729 len
= BIO_read(in
, tbuf
, len
);
1736 if (BIO_write(mem
, tbuf
, len
) != len
) {
1745 ret
= BIO_get_mem_data(mem
, (char **)out
);
1746 BIO_set_flags(mem
, BIO_FLAGS_MEM_RDONLY
);
1751 int pkey_ctrl_string(EVP_PKEY_CTX
*ctx
, const char *value
)
1754 char *stmp
, *vtmp
= NULL
;
1755 stmp
= OPENSSL_strdup(value
);
1758 vtmp
= strchr(stmp
, ':');
1763 rv
= EVP_PKEY_CTX_ctrl_str(ctx
, stmp
, vtmp
);
1768 static void nodes_print(const char *name
, STACK_OF(X509_POLICY_NODE
) *nodes
)
1770 X509_POLICY_NODE
*node
;
1773 BIO_printf(bio_err
, "%s Policies:", name
);
1775 BIO_puts(bio_err
, "\n");
1776 for (i
= 0; i
< sk_X509_POLICY_NODE_num(nodes
); i
++) {
1777 node
= sk_X509_POLICY_NODE_value(nodes
, i
);
1778 X509_POLICY_NODE_print(bio_err
, node
, 2);
1781 BIO_puts(bio_err
, " <empty>\n");
1785 void policies_print(X509_STORE_CTX
*ctx
)
1787 X509_POLICY_TREE
*tree
;
1788 int explicit_policy
;
1789 tree
= X509_STORE_CTX_get0_policy_tree(ctx
);
1790 explicit_policy
= X509_STORE_CTX_get_explicit_policy(ctx
);
1792 BIO_printf(bio_err
, "Require explicit Policy: %s\n",
1793 explicit_policy
? "True" : "False");
1795 nodes_print("Authority", X509_policy_tree_get0_policies(tree
));
1796 nodes_print("User", X509_policy_tree_get0_user_policies(tree
));
1800 * next_protos_parse parses a comma separated list of strings into a string
1801 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1802 * outlen: (output) set to the length of the resulting buffer on success.
1803 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1804 * in: a NUL terminated string like "abc,def,ghi"
1806 * returns: a malloc'd buffer or NULL on failure.
1808 unsigned char *next_protos_parse(size_t *outlen
, const char *in
)
1812 size_t i
, start
= 0;
1816 if (len
== 0 || len
>= 65535)
1819 out
= app_malloc(len
+ 1, "NPN buffer");
1820 for (i
= 0; i
<= len
; ++i
) {
1821 if (i
== len
|| in
[i
] == ',') {
1823 * Zero-length ALPN elements are invalid on the wire, we could be
1824 * strict and reject the entire string, but just ignoring extra
1825 * commas seems harmless and more friendly.
1827 * Every comma we skip in this way puts the input buffer another
1828 * byte ahead of the output buffer, so all stores into the output
1829 * buffer need to be decremented by the number commas skipped.
1836 if (i
- start
> 255) {
1840 out
[start
-skipped
] = (unsigned char)(i
- start
);
1843 out
[i
+ 1 - skipped
] = in
[i
];
1847 if (len
<= skipped
) {
1852 *outlen
= len
+ 1 - skipped
;
1856 void print_cert_checks(BIO
*bio
, X509
*x
,
1857 const char *checkhost
,
1858 const char *checkemail
, const char *checkip
)
1863 BIO_printf(bio
, "Hostname %s does%s match certificate\n",
1865 X509_check_host(x
, checkhost
, 0, 0, NULL
) == 1
1870 BIO_printf(bio
, "Email %s does%s match certificate\n",
1871 checkemail
, X509_check_email(x
, checkemail
, 0, 0)
1876 BIO_printf(bio
, "IP %s does%s match certificate\n",
1877 checkip
, X509_check_ip_asc(x
, checkip
, 0) ? "" : " NOT");
1881 /* Get first http URL from a DIST_POINT structure */
1883 static const char *get_dp_url(DIST_POINT
*dp
)
1885 GENERAL_NAMES
*gens
;
1889 if (!dp
->distpoint
|| dp
->distpoint
->type
!= 0)
1891 gens
= dp
->distpoint
->name
.fullname
;
1892 for (i
= 0; i
< sk_GENERAL_NAME_num(gens
); i
++) {
1893 gen
= sk_GENERAL_NAME_value(gens
, i
);
1894 uri
= GENERAL_NAME_get0_value(gen
, >ype
);
1895 if (gtype
== GEN_URI
&& ASN1_STRING_length(uri
) > 6) {
1896 const char *uptr
= (const char *)ASN1_STRING_get0_data(uri
);
1897 if (strncmp(uptr
, "http://", 7) == 0)
1905 * Look through a CRLDP structure and attempt to find an http URL to
1906 * downloads a CRL from.
1909 static X509_CRL
*load_crl_crldp(STACK_OF(DIST_POINT
) *crldp
)
1912 const char *urlptr
= NULL
;
1913 for (i
= 0; i
< sk_DIST_POINT_num(crldp
); i
++) {
1914 DIST_POINT
*dp
= sk_DIST_POINT_value(crldp
, i
);
1915 urlptr
= get_dp_url(dp
);
1917 return load_crl(urlptr
, "CRL via CDP");
1923 * Example of downloading CRLs from CRLDP:
1924 * not usable for real world as it always downloads and doesn't cache anything.
1927 static STACK_OF(X509_CRL
) *crls_http_cb(const X509_STORE_CTX
*ctx
,
1928 const X509_NAME
*nm
)
1931 STACK_OF(X509_CRL
) *crls
= NULL
;
1933 STACK_OF(DIST_POINT
) *crldp
;
1935 crls
= sk_X509_CRL_new_null();
1938 x
= X509_STORE_CTX_get_current_cert(ctx
);
1939 crldp
= X509_get_ext_d2i(x
, NID_crl_distribution_points
, NULL
, NULL
);
1940 crl
= load_crl_crldp(crldp
);
1941 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
1943 sk_X509_CRL_free(crls
);
1946 sk_X509_CRL_push(crls
, crl
);
1947 /* Try to download delta CRL */
1948 crldp
= X509_get_ext_d2i(x
, NID_freshest_crl
, NULL
, NULL
);
1949 crl
= load_crl_crldp(crldp
);
1950 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
1952 sk_X509_CRL_push(crls
, crl
);
1956 void store_setup_crl_download(X509_STORE
*st
)
1958 X509_STORE_set_lookup_crls_cb(st
, crls_http_cb
);
1961 #ifndef OPENSSL_NO_SOCK
1962 static const char *tls_error_hint(void)
1964 unsigned long err
= ERR_peek_error();
1966 if (ERR_GET_LIB(err
) != ERR_LIB_SSL
)
1967 err
= ERR_peek_last_error();
1968 if (ERR_GET_LIB(err
) != ERR_LIB_SSL
)
1971 switch (ERR_GET_REASON(err
)) {
1972 case SSL_R_WRONG_VERSION_NUMBER
:
1973 return "The server does not support (a suitable version of) TLS";
1974 case SSL_R_UNKNOWN_PROTOCOL
:
1975 return "The server does not support HTTPS";
1976 case SSL_R_CERTIFICATE_VERIFY_FAILED
:
1977 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
1978 case SSL_AD_REASON_OFFSET
+ TLS1_AD_UNKNOWN_CA
:
1979 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
1980 case SSL_AD_REASON_OFFSET
+ SSL3_AD_HANDSHAKE_FAILURE
:
1981 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
1982 default: /* no error or no hint available for error */
1987 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
1988 BIO
*app_http_tls_cb(BIO
*hbio
, void *arg
, int connect
, int detail
)
1990 APP_HTTP_TLS_INFO
*info
= (APP_HTTP_TLS_INFO
*)arg
;
1991 SSL_CTX
*ssl_ctx
= info
->ssl_ctx
;
1995 if (connect
&& detail
) { /* connecting with TLS */
1996 if ((info
->use_proxy
1997 && !OSSL_HTTP_proxy_connect(hbio
, info
->server
, info
->port
,
1998 NULL
, NULL
, /* no proxy credentials */
1999 info
->timeout
, bio_err
, opt_getprog()))
2000 || (sbio
= BIO_new(BIO_f_ssl())) == NULL
) {
2003 if (ssl_ctx
== NULL
|| (ssl
= SSL_new(ssl_ctx
)) == NULL
) {
2008 SSL_set_tlsext_host_name(ssl
, info
->server
);
2010 SSL_set_connect_state(ssl
);
2011 BIO_set_ssl(sbio
, ssl
, BIO_CLOSE
);
2013 hbio
= BIO_push(sbio
, hbio
);
2014 } else if (!connect
&& !detail
) { /* disconnecting after error */
2015 const char *hint
= tls_error_hint();
2017 ERR_add_error_data(2, " : ", hint
);
2019 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2020 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2026 ASN1_VALUE
*app_http_get_asn1(const char *url
, const char *proxy
,
2027 const char *no_proxy
, SSL_CTX
*ssl_ctx
,
2028 const STACK_OF(CONF_VALUE
) *headers
,
2029 long timeout
, const char *expected_content_type
,
2030 const ASN1_ITEM
*it
)
2032 APP_HTTP_TLS_INFO info
;
2036 ASN1_VALUE
*resp
= NULL
;
2038 if (url
== NULL
|| it
== NULL
) {
2039 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER
);
2043 if (!OSSL_HTTP_parse_url(url
, &server
, &port
, NULL
, NULL
, &use_ssl
))
2045 if (use_ssl
&& ssl_ctx
== NULL
) {
2046 HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER
);
2047 ERR_add_error_data(1, "missing SSL_CTX");
2051 info
.server
= server
;
2053 info
.use_proxy
= proxy
!= NULL
;
2054 info
.timeout
= timeout
;
2055 info
.ssl_ctx
= ssl_ctx
;
2056 resp
= OSSL_HTTP_get_asn1(url
, proxy
, no_proxy
,
2057 NULL
, NULL
, app_http_tls_cb
, &info
,
2058 headers
, 0 /* maxline */, 0 /* max_resp_len */,
2059 timeout
, expected_content_type
, it
);
2061 OPENSSL_free(server
);
2067 ASN1_VALUE
*app_http_post_asn1(const char *host
, const char *port
,
2068 const char *path
, const char *proxy
,
2069 const char *no_proxy
, SSL_CTX
*ssl_ctx
,
2070 const STACK_OF(CONF_VALUE
) *headers
,
2071 const char *content_type
,
2072 ASN1_VALUE
*req
, const ASN1_ITEM
*req_it
,
2073 long timeout
, const ASN1_ITEM
*rsp_it
)
2075 APP_HTTP_TLS_INFO info
;
2079 info
.use_proxy
= proxy
!= NULL
;
2080 info
.timeout
= timeout
;
2081 info
.ssl_ctx
= ssl_ctx
;
2082 return OSSL_HTTP_post_asn1(host
, port
, path
, ssl_ctx
!= NULL
,
2084 NULL
, NULL
, app_http_tls_cb
, &info
,
2085 headers
, content_type
, req
, req_it
,
2087 0 /* max_resp_len */, timeout
, NULL
, rsp_it
);
2093 * Platform-specific sections
2098 # define fileno(a) (int)_fileno(a)
2101 # include <windows.h>
2104 static int WIN32_rename(const char *from
, const char *to
)
2106 TCHAR
*tfrom
= NULL
, *tto
;
2110 if (sizeof(TCHAR
) == 1) {
2111 tfrom
= (TCHAR
*)from
;
2113 } else { /* UNICODE path */
2115 size_t i
, flen
= strlen(from
) + 1, tlen
= strlen(to
) + 1;
2116 tfrom
= malloc(sizeof(*tfrom
) * (flen
+ tlen
));
2120 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2121 if (!MultiByteToWideChar(CP_ACP
, 0, from
, flen
, (WCHAR
*)tfrom
, flen
))
2123 for (i
= 0; i
< flen
; i
++)
2124 tfrom
[i
] = (TCHAR
)from
[i
];
2125 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2126 if (!MultiByteToWideChar(CP_ACP
, 0, to
, tlen
, (WCHAR
*)tto
, tlen
))
2128 for (i
= 0; i
< tlen
; i
++)
2129 tto
[i
] = (TCHAR
)to
[i
];
2132 if (MoveFile(tfrom
, tto
))
2134 err
= GetLastError();
2135 if (err
== ERROR_ALREADY_EXISTS
|| err
== ERROR_FILE_EXISTS
) {
2136 if (DeleteFile(tto
) && MoveFile(tfrom
, tto
))
2138 err
= GetLastError();
2140 if (err
== ERROR_FILE_NOT_FOUND
|| err
== ERROR_PATH_NOT_FOUND
)
2142 else if (err
== ERROR_ACCESS_DENIED
)
2145 errno
= EINVAL
; /* we could map more codes... */
2149 if (tfrom
!= NULL
&& tfrom
!= (TCHAR
*)from
)
2155 /* app_tminterval section */
2157 double app_tminterval(int stop
, int usertime
)
2161 static ULARGE_INTEGER tmstart
;
2162 static int warning
= 1;
2163 # ifdef _WIN32_WINNT
2164 static HANDLE proc
= NULL
;
2168 proc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
,
2169 GetCurrentProcessId());
2171 proc
= (HANDLE
) - 1;
2174 if (usertime
&& proc
!= (HANDLE
) - 1) {
2176 GetProcessTimes(proc
, &junk
, &junk
, &junk
, &now
);
2182 if (usertime
&& warning
) {
2183 BIO_printf(bio_err
, "To get meaningful results, run "
2184 "this program on idle system.\n");
2187 GetSystemTime(&systime
);
2188 SystemTimeToFileTime(&systime
, &now
);
2191 if (stop
== TM_START
) {
2192 tmstart
.u
.LowPart
= now
.dwLowDateTime
;
2193 tmstart
.u
.HighPart
= now
.dwHighDateTime
;
2195 ULARGE_INTEGER tmstop
;
2197 tmstop
.u
.LowPart
= now
.dwLowDateTime
;
2198 tmstop
.u
.HighPart
= now
.dwHighDateTime
;
2200 ret
= (__int64
)(tmstop
.QuadPart
- tmstart
.QuadPart
) * 1e-7;
2205 #elif defined(OPENSSL_SYS_VXWORKS)
2208 double app_tminterval(int stop
, int usertime
)
2211 # ifdef CLOCK_REALTIME
2212 static struct timespec tmstart
;
2213 struct timespec now
;
2215 static unsigned long tmstart
;
2218 static int warning
= 1;
2220 if (usertime
&& warning
) {
2221 BIO_printf(bio_err
, "To get meaningful results, run "
2222 "this program on idle system.\n");
2225 # ifdef CLOCK_REALTIME
2226 clock_gettime(CLOCK_REALTIME
, &now
);
2227 if (stop
== TM_START
)
2230 ret
= ((now
.tv_sec
+ now
.tv_nsec
* 1e-9)
2231 - (tmstart
.tv_sec
+ tmstart
.tv_nsec
* 1e-9));
2234 if (stop
== TM_START
)
2237 ret
= (now
- tmstart
) / (double)sysClkRateGet();
2242 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2243 # include <sys/times.h>
2245 double app_tminterval(int stop
, int usertime
)
2249 clock_t now
= times(&rus
);
2250 static clock_t tmstart
;
2253 now
= rus
.tms_utime
;
2255 if (stop
== TM_START
) {
2258 long int tck
= sysconf(_SC_CLK_TCK
);
2259 ret
= (now
- tmstart
) / (double)tck
;
2266 # include <sys/time.h>
2267 # include <sys/resource.h>
2269 double app_tminterval(int stop
, int usertime
)
2274 static struct timeval tmstart
;
2277 getrusage(RUSAGE_SELF
, &rus
), now
= rus
.ru_utime
;
2279 gettimeofday(&now
, NULL
);
2281 if (stop
== TM_START
)
2284 ret
= ((now
.tv_sec
+ now
.tv_usec
* 1e-6)
2285 - (tmstart
.tv_sec
+ tmstart
.tv_usec
* 1e-6));
2291 int app_access(const char* name
, int flag
)
2294 return _access(name
, flag
);
2296 return access(name
, flag
);
2300 int app_isdir(const char *name
)
2302 return opt_isdir(name
);
2305 /* raw_read|write section */
2307 # include "vms_term_sock.h"
2308 static int stdin_sock
= -1;
2310 static void close_stdin_sock(void)
2312 TerminalSocket (TERM_SOCK_DELETE
, &stdin_sock
);
2315 int fileno_stdin(void)
2317 if (stdin_sock
== -1) {
2318 TerminalSocket(TERM_SOCK_CREATE
, &stdin_sock
);
2319 atexit(close_stdin_sock
);
2325 int fileno_stdin(void)
2327 return fileno(stdin
);
2331 int fileno_stdout(void)
2333 return fileno(stdout
);
2336 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2337 int raw_read_stdin(void *buf
, int siz
)
2340 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2345 #elif defined(__VMS)
2346 # include <sys/socket.h>
2348 int raw_read_stdin(void *buf
, int siz
)
2350 return recv(fileno_stdin(), buf
, siz
, 0);
2353 # if defined(__TANDEM)
2354 # if defined(OPENSSL_TANDEM_FLOSS)
2355 # include <floss.h(floss_read)>
2358 int raw_read_stdin(void *buf
, int siz
)
2360 return read(fileno_stdin(), buf
, siz
);
2364 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2365 int raw_write_stdout(const void *buf
, int siz
)
2368 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2373 #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
2374 # if defined(__TANDEM)
2375 # if defined(OPENSSL_TANDEM_FLOSS)
2376 # include <floss.h(floss_write)>
2379 int raw_write_stdout(const void *buf
,int siz
)
2381 return write(fileno(stdout
),(void*)buf
,siz
);
2384 # if defined(__TANDEM)
2385 # if defined(OPENSSL_TANDEM_FLOSS)
2386 # include <floss.h(floss_write)>
2389 int raw_write_stdout(const void *buf
, int siz
)
2391 return write(fileno_stdout(), buf
, siz
);
2396 * Centralized handling of input and output files with format specification
2397 * The format is meant to show what the input and output is supposed to be,
2398 * and is therefore a show of intent more than anything else. However, it
2399 * does impact behavior on some platforms, such as differentiating between
2400 * text and binary input/output on non-Unix platforms
2402 BIO
*dup_bio_in(int format
)
2404 return BIO_new_fp(stdin
,
2405 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2408 BIO
*dup_bio_out(int format
)
2410 BIO
*b
= BIO_new_fp(stdout
,
2411 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2412 void *prefix
= NULL
;
2414 #ifdef OPENSSL_SYS_VMS
2415 if (FMT_istext(format
))
2416 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2419 if (FMT_istext(format
)
2420 && (prefix
= getenv("HARNESS_OSSL_PREFIX")) != NULL
) {
2421 b
= BIO_push(BIO_new(BIO_f_prefix()), b
);
2422 BIO_set_prefix(b
, prefix
);
2428 BIO
*dup_bio_err(int format
)
2430 BIO
*b
= BIO_new_fp(stderr
,
2431 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2432 #ifdef OPENSSL_SYS_VMS
2433 if (FMT_istext(format
))
2434 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2439 void unbuffer(FILE *fp
)
2442 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2443 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2444 * However, we trust that the C RTL will never give us a FILE pointer
2445 * above the first 4 GB of memory, so we simply turn off the warning
2448 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2449 # pragma environment save
2450 # pragma message disable maylosedata2
2453 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2454 # pragma environment restore
2458 static const char *modestr(char mode
, int format
)
2460 OPENSSL_assert(mode
== 'a' || mode
== 'r' || mode
== 'w');
2464 return FMT_istext(format
) ? "a" : "ab";
2466 return FMT_istext(format
) ? "r" : "rb";
2468 return FMT_istext(format
) ? "w" : "wb";
2470 /* The assert above should make sure we never reach this point */
2474 static const char *modeverb(char mode
)
2484 return "(doing something)";
2488 * Open a file for writing, owner-read-only.
2490 BIO
*bio_open_owner(const char *filename
, int format
, int private)
2494 int fd
= -1, bflags
, mode
, textmode
;
2496 if (!private || filename
== NULL
|| strcmp(filename
, "-") == 0)
2497 return bio_open_default(filename
, 'w', format
);
2506 textmode
= FMT_istext(format
);
2510 #elif defined(_O_BINARY)
2515 #ifdef OPENSSL_SYS_VMS
2516 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2517 * it still needs to know that we're going binary, or fdopen()
2518 * will fail with "invalid argument"... so we tell VMS what the
2522 fd
= open(filename
, mode
, 0600, "ctx=bin");
2525 fd
= open(filename
, mode
, 0600);
2528 fp
= fdopen(fd
, modestr('w', format
));
2533 bflags
|= BIO_FP_TEXT
;
2534 b
= BIO_new_fp(fp
, bflags
);
2539 BIO_printf(bio_err
, "%s: Can't open \"%s\" for writing, %s\n",
2540 opt_getprog(), filename
, strerror(errno
));
2541 ERR_print_errors(bio_err
);
2542 /* If we have fp, then fdopen took over fd, so don't close both. */
2550 static BIO
*bio_open_default_(const char *filename
, char mode
, int format
,
2555 if (filename
== NULL
|| strcmp(filename
, "-") == 0) {
2556 ret
= mode
== 'r' ? dup_bio_in(format
) : dup_bio_out(format
);
2564 "Can't open %s, %s\n",
2565 mode
== 'r' ? "stdin" : "stdout", strerror(errno
));
2567 ret
= BIO_new_file(filename
, modestr(mode
, format
));
2575 "Can't open %s for %s, %s\n",
2576 filename
, modeverb(mode
), strerror(errno
));
2578 ERR_print_errors(bio_err
);
2582 BIO
*bio_open_default(const char *filename
, char mode
, int format
)
2584 return bio_open_default_(filename
, mode
, format
, 0);
2587 BIO
*bio_open_default_quiet(const char *filename
, char mode
, int format
)
2589 return bio_open_default_(filename
, mode
, format
, 1);
2592 void wait_for_async(SSL
*s
)
2594 /* On Windows select only works for sockets, so we simply don't wait */
2595 #ifndef OPENSSL_SYS_WINDOWS
2602 if (!SSL_get_all_async_fds(s
, NULL
, &numfds
))
2606 fds
= app_malloc(sizeof(OSSL_ASYNC_FD
) * numfds
, "allocate async fds");
2607 if (!SSL_get_all_async_fds(s
, fds
, &numfds
)) {
2613 for (i
= 0; i
< numfds
; i
++) {
2614 if (width
<= (int)fds
[i
])
2615 width
= (int)fds
[i
] + 1;
2616 openssl_fdset((int)fds
[i
], &asyncfds
);
2618 select(width
, (void *)&asyncfds
, NULL
, NULL
, NULL
);
2623 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2624 #if defined(OPENSSL_SYS_MSDOS)
2625 int has_stdin_waiting(void)
2627 # if defined(OPENSSL_SYS_WINDOWS)
2628 HANDLE inhand
= GetStdHandle(STD_INPUT_HANDLE
);
2630 INPUT_RECORD inputrec
;
2634 if (inhand
== INVALID_HANDLE_VALUE
) {
2638 peeked
= PeekConsoleInput(inhand
, &inputrec
, insize
, &events
);
2640 /* Probably redirected input? _kbhit() does not work in this case */
2651 /* Corrupt a signature by modifying final byte */
2652 void corrupt_signature(const ASN1_STRING
*signature
)
2654 unsigned char *s
= signature
->data
;
2655 s
[signature
->length
- 1] ^= 0x1;
2658 int set_cert_times(X509
*x
, const char *startdate
, const char *enddate
,
2661 if (startdate
== NULL
|| strcmp(startdate
, "today") == 0) {
2662 if (X509_gmtime_adj(X509_getm_notBefore(x
), 0) == NULL
)
2665 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x
), startdate
))
2668 if (enddate
== NULL
) {
2669 if (X509_time_adj_ex(X509_getm_notAfter(x
), days
, 0, NULL
)
2672 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x
), enddate
)) {
2678 int set_crl_lastupdate(X509_CRL
*crl
, const char *lastupdate
)
2681 ASN1_TIME
*tm
= ASN1_TIME_new();
2686 if (lastupdate
== NULL
) {
2687 if (X509_gmtime_adj(tm
, 0) == NULL
)
2690 if (!ASN1_TIME_set_string_X509(tm
, lastupdate
))
2694 if (!X509_CRL_set1_lastUpdate(crl
, tm
))
2703 int set_crl_nextupdate(X509_CRL
*crl
, const char *nextupdate
,
2704 long days
, long hours
, long secs
)
2707 ASN1_TIME
*tm
= ASN1_TIME_new();
2712 if (nextupdate
== NULL
) {
2713 if (X509_time_adj_ex(tm
, days
, hours
* 60 * 60 + secs
, NULL
) == NULL
)
2716 if (!ASN1_TIME_set_string_X509(tm
, nextupdate
))
2720 if (!X509_CRL_set1_nextUpdate(crl
, tm
))
2729 void make_uppercase(char *string
)
2733 for (i
= 0; string
[i
] != '\0'; i
++)
2734 string
[i
] = toupper((unsigned char)string
[i
]);
2737 int opt_printf_stderr(const char *fmt
, ...)
2743 ret
= BIO_vprintf(bio_err
, fmt
, ap
);
2748 OSSL_PARAM
*app_params_new_from_opts(STACK_OF(OPENSSL_STRING
) *opts
,
2749 const OSSL_PARAM
*paramdefs
)
2751 OSSL_PARAM
*params
= NULL
;
2752 size_t sz
= (size_t)sk_OPENSSL_STRING_num(opts
);
2754 char *opt
= "", *stmp
, *vtmp
= NULL
;
2760 params
= OPENSSL_zalloc(sizeof(OSSL_PARAM
) * (sz
+ 1));
2764 for (params_n
= 0; params_n
< sz
; params_n
++) {
2765 opt
= sk_OPENSSL_STRING_value(opts
, (int)params_n
);
2766 if ((stmp
= OPENSSL_strdup(opt
)) == NULL
2767 || (vtmp
= strchr(stmp
, ':')) == NULL
)
2769 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2771 /* Skip over the separator so that vmtp points to the value */
2773 if (!OSSL_PARAM_allocate_from_text(¶ms
[params_n
], paramdefs
,
2774 stmp
, vtmp
, strlen(vtmp
), &found
))
2778 params
[params_n
] = OSSL_PARAM_construct_end();
2782 BIO_printf(bio_err
, "Parameter %s '%s'\n", found
? "error" : "unknown",
2784 ERR_print_errors(bio_err
);
2785 app_params_free(params
);
2789 void app_params_free(OSSL_PARAM
*params
)
2793 if (params
!= NULL
) {
2794 for (i
= 0; params
[i
].key
!= NULL
; ++i
)
2795 OPENSSL_free(params
[i
].data
);
2796 OPENSSL_free(params
);