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/http.h>
32 #include <openssl/pem.h>
33 #include <openssl/store.h>
34 #include <openssl/pkcs12.h>
35 #include <openssl/ui.h>
36 #include <openssl/safestack.h>
37 #ifndef OPENSSL_NO_RSA
38 # include <openssl/rsa.h>
40 #include <openssl/bn.h>
41 #include <openssl/ssl.h>
45 static int WIN32_rename(const char *from
, const char *to
);
46 # define rename(from,to) WIN32_rename((from),(to))
49 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
53 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32)
57 #define PASS_SOURCE_SIZE_MAX 4
67 static OSSL_LIB_CTX
*app_libctx
= NULL
;
69 static int set_table_opts(unsigned long *flags
, const char *arg
,
70 const NAME_EX_TBL
* in_tbl
);
71 static int set_multi_opts(unsigned long *flags
, const char *arg
,
72 const NAME_EX_TBL
* in_tbl
);
74 int app_init(long mesgwin
);
76 int chopup_args(ARGS
*arg
, char *buf
)
79 char c
= '\0', *p
= NULL
;
84 arg
->argv
= app_malloc(sizeof(*arg
->argv
) * arg
->size
, "argv space");
88 /* Skip whitespace. */
89 while (*p
&& isspace(_UC(*p
)))
94 /* The start of something good :-) */
95 if (arg
->argc
>= arg
->size
) {
98 tmp
= OPENSSL_realloc(arg
->argv
, sizeof(*arg
->argv
) * arg
->size
);
103 quoted
= *p
== '\'' || *p
== '"';
106 arg
->argv
[arg
->argc
++] = p
;
108 /* now look for the end of this */
110 while (*p
&& *p
!= c
)
114 while (*p
&& !isspace(_UC(*p
)))
120 arg
->argv
[arg
->argc
] = NULL
;
125 int app_init(long mesgwin
)
131 int ctx_set_verify_locations(SSL_CTX
*ctx
,
132 const char *CAfile
, int noCAfile
,
133 const char *CApath
, int noCApath
,
134 const char *CAstore
, int noCAstore
)
136 if (CAfile
== NULL
&& CApath
== NULL
&& CAstore
== NULL
) {
137 if (!noCAfile
&& SSL_CTX_set_default_verify_file(ctx
) <= 0)
139 if (!noCApath
&& SSL_CTX_set_default_verify_dir(ctx
) <= 0)
141 if (!noCAstore
&& SSL_CTX_set_default_verify_store(ctx
) <= 0)
147 if (CAfile
!= NULL
&& !SSL_CTX_load_verify_file(ctx
, CAfile
))
149 if (CApath
!= NULL
&& !SSL_CTX_load_verify_dir(ctx
, CApath
))
151 if (CAstore
!= NULL
&& !SSL_CTX_load_verify_store(ctx
, CAstore
))
156 #ifndef OPENSSL_NO_CT
158 int ctx_set_ctlog_list_file(SSL_CTX
*ctx
, const char *path
)
161 return SSL_CTX_set_default_ctlog_list_file(ctx
);
163 return SSL_CTX_set_ctlog_list_file(ctx
, path
);
168 static unsigned long nmflag
= 0;
169 static char nmflag_set
= 0;
171 int set_nameopt(const char *arg
)
173 int ret
= set_name_ex(&nmflag
, arg
);
181 unsigned long get_nameopt(void)
183 return (nmflag_set
) ? nmflag
: XN_FLAG_ONELINE
;
186 int dump_cert_text(BIO
*out
, X509
*x
)
188 print_name(out
, "subject=", X509_get_subject_name(x
), get_nameopt());
190 print_name(out
, "issuer=", X509_get_issuer_name(x
), get_nameopt());
196 int wrap_password_callback(char *buf
, int bufsiz
, int verify
, void *userdata
)
198 return password_callback(buf
, bufsiz
, verify
, (PW_CB_DATA
*)userdata
);
202 static char *app_get_pass(const char *arg
, int keepbio
);
204 char *get_passwd(const char *pass
, const char *desc
)
210 if (!app_passwd(pass
, NULL
, &result
, NULL
))
211 BIO_printf(bio_err
, "Error getting password for %s\n", desc
);
212 if (pass
!= NULL
&& result
== NULL
) {
214 "Trying plain input string (better precede with 'pass:')\n");
215 result
= OPENSSL_strdup(pass
);
217 BIO_printf(bio_err
, "Out of memory getting password for %s\n", desc
);
222 int app_passwd(const char *arg1
, const char *arg2
, char **pass1
, char **pass2
)
224 int same
= arg1
!= NULL
&& arg2
!= NULL
&& strcmp(arg1
, arg2
) == 0;
227 *pass1
= app_get_pass(arg1
, same
);
230 } else if (pass1
!= NULL
) {
234 *pass2
= app_get_pass(arg2
, same
? 2 : 0);
237 } else if (pass2
!= NULL
) {
243 static char *app_get_pass(const char *arg
, int keepbio
)
245 static BIO
*pwdbio
= NULL
;
246 char *tmp
, tpass
[APP_PASS_LEN
];
249 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
250 if (strncmp(arg
, "pass:", 5) == 0)
251 return OPENSSL_strdup(arg
+ 5);
252 if (strncmp(arg
, "env:", 4) == 0) {
253 tmp
= getenv(arg
+ 4);
255 BIO_printf(bio_err
, "No environment variable %s\n", arg
+ 4);
258 return OPENSSL_strdup(tmp
);
260 if (!keepbio
|| pwdbio
== NULL
) {
261 if (strncmp(arg
, "file:", 5) == 0) {
262 pwdbio
= BIO_new_file(arg
+ 5, "r");
263 if (pwdbio
== NULL
) {
264 BIO_printf(bio_err
, "Can't open file %s\n", arg
+ 5);
269 * Under _WIN32, which covers even Win64 and CE, file
270 * descriptors referenced by BIO_s_fd are not inherited
271 * by child process and therefore below is not an option.
272 * It could have been an option if bss_fd.c was operating
273 * on real Windows descriptors, such as those obtained
276 } else if (strncmp(arg
, "fd:", 3) == 0) {
280 pwdbio
= BIO_new_fd(i
, BIO_NOCLOSE
);
281 if ((i
< 0) || !pwdbio
) {
282 BIO_printf(bio_err
, "Can't access file descriptor %s\n", arg
+ 3);
286 * Can't do BIO_gets on an fd BIO so add a buffering BIO
288 btmp
= BIO_new(BIO_f_buffer());
289 pwdbio
= BIO_push(btmp
, pwdbio
);
291 } else if (strcmp(arg
, "stdin") == 0) {
292 pwdbio
= dup_bio_in(FORMAT_TEXT
);
293 if (pwdbio
== NULL
) {
294 BIO_printf(bio_err
, "Can't open BIO for stdin\n");
298 /* argument syntax error; do not reveal too much about arg */
299 tmp
= strchr(arg
, ':');
300 if (tmp
== NULL
|| tmp
- arg
> PASS_SOURCE_SIZE_MAX
)
302 "Invalid password argument, missing ':' within the first %d chars\n",
303 PASS_SOURCE_SIZE_MAX
+ 1);
306 "Invalid password argument, starting with \"%.*s\"\n",
307 (int)(tmp
- arg
+ 1), arg
);
311 i
= BIO_gets(pwdbio
, tpass
, APP_PASS_LEN
);
313 BIO_free_all(pwdbio
);
317 BIO_printf(bio_err
, "Error reading password from BIO\n");
320 tmp
= strchr(tpass
, '\n');
323 return OPENSSL_strdup(tpass
);
326 OSSL_LIB_CTX
*app_get0_libctx(void)
331 /* TODO(3.0): Make this an environment variable if required */
332 const char *app_get0_propq(void)
337 OSSL_LIB_CTX
*app_create_libctx(void)
340 * Load the NULL provider into the default library context and create a
341 * library context which will then be used for any OPT_PROV options.
343 if (app_libctx
== NULL
) {
345 if (!app_provider_load(NULL
, "null")) {
346 BIO_puts(bio_err
, "Failed to create null provider\n");
349 app_libctx
= OSSL_LIB_CTX_new();
351 if (app_libctx
== NULL
)
352 BIO_puts(bio_err
, "Failed to create library context\n");
356 CONF
*app_load_config_bio(BIO
*in
, const char *filename
)
362 conf
= NCONF_new_ex(app_libctx
, NULL
);
363 i
= NCONF_load_bio(conf
, in
, &errorline
);
367 if (errorline
<= 0) {
368 BIO_printf(bio_err
, "%s: Can't load ", opt_getprog());
370 BIO_printf(bio_err
, "%s: Error on line %ld of ", opt_getprog(),
373 if (filename
!= NULL
)
374 BIO_printf(bio_err
, "config file \"%s\"\n", filename
);
376 BIO_printf(bio_err
, "config input");
382 CONF
*app_load_config(const char *filename
)
387 in
= bio_open_default(filename
, 'r', FORMAT_TEXT
);
391 conf
= app_load_config_bio(in
, filename
);
396 CONF
*app_load_config_quiet(const char *filename
)
401 in
= bio_open_default_quiet(filename
, 'r', FORMAT_TEXT
);
405 conf
= app_load_config_bio(in
, filename
);
410 int app_load_modules(const CONF
*config
)
412 CONF
*to_free
= NULL
;
415 config
= to_free
= app_load_config_quiet(default_config_file
);
419 if (CONF_modules_load(config
, NULL
, 0) <= 0) {
420 BIO_printf(bio_err
, "Error configuring OpenSSL modules\n");
421 ERR_print_errors(bio_err
);
429 int add_oid_section(CONF
*conf
)
432 STACK_OF(CONF_VALUE
) *sktmp
;
436 if ((p
= NCONF_get_string(conf
, NULL
, "oid_section")) == NULL
) {
440 if ((sktmp
= NCONF_get_section(conf
, p
)) == NULL
) {
441 BIO_printf(bio_err
, "problem loading oid section %s\n", p
);
444 for (i
= 0; i
< sk_CONF_VALUE_num(sktmp
); i
++) {
445 cnf
= sk_CONF_VALUE_value(sktmp
, i
);
446 if (OBJ_create(cnf
->value
, cnf
->name
, cnf
->name
) == NID_undef
) {
447 BIO_printf(bio_err
, "problem creating object %s=%s\n",
448 cnf
->name
, cnf
->value
);
455 CONF
*app_load_config_modules(const char *configfile
)
459 if (configfile
!= NULL
) {
460 BIO_printf(bio_err
, "Using configuration from %s\n", configfile
);
462 if ((conf
= app_load_config(configfile
)) == NULL
)
464 if (configfile
!= default_config_file
&& !app_load_modules(conf
)) {
472 #define IS_HTTP(uri) \
473 (strncmp(uri, OSSL_HTTP_PREFIX, strlen(OSSL_HTTP_PREFIX)) == 0)
474 #define IS_HTTPS(uri) \
475 (strncmp(uri, OSSL_HTTPS_PREFIX, strlen(OSSL_HTTPS_PREFIX)) == 0)
477 X509
*load_cert_pass(const char *uri
, int maybe_stdin
,
478 const char *pass
, const char *desc
)
483 desc
= "certificate";
485 BIO_printf(bio_err
, "Loading %s over HTTPS is unsupported\n", desc
);
486 else if (IS_HTTP(uri
))
487 cert
= X509_load_http(uri
, NULL
, NULL
, 0 /* timeout */);
489 (void)load_key_certs_crls(uri
, maybe_stdin
, pass
, desc
,
490 NULL
, NULL
, NULL
, &cert
, NULL
, NULL
, NULL
);
492 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
493 ERR_print_errors(bio_err
);
498 X509_CRL
*load_crl(const char *uri
, const char *desc
)
500 X509_CRL
*crl
= NULL
;
505 BIO_printf(bio_err
, "Loading %s over HTTPS is unsupported\n", desc
);
506 else if (IS_HTTP(uri
))
507 crl
= X509_CRL_load_http(uri
, NULL
, NULL
, 0 /* timeout */);
509 (void)load_key_certs_crls(uri
, 0, NULL
, desc
,
510 NULL
, NULL
, NULL
, NULL
, NULL
, &crl
, NULL
);
512 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
513 ERR_print_errors(bio_err
);
518 X509_REQ
*load_csr(const char *file
, int format
, const char *desc
)
520 X509_REQ
*req
= NULL
;
525 in
= bio_open_default(file
, 'r', format
);
529 if (format
== FORMAT_ASN1
)
530 req
= d2i_X509_REQ_bio(in
, NULL
);
531 else if (format
== FORMAT_PEM
)
532 req
= PEM_read_bio_X509_REQ(in
, NULL
, NULL
, NULL
);
534 print_format_error(format
, OPT_FMT_PEMDER
);
538 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
539 ERR_print_errors(bio_err
);
545 void cleanse(char *str
)
548 OPENSSL_cleanse(str
, strlen(str
));
551 void clear_free(char *str
)
554 OPENSSL_clear_free(str
, strlen(str
));
557 EVP_PKEY
*load_key(const char *uri
, int format
, int may_stdin
,
558 const char *pass
, ENGINE
*e
, const char *desc
)
560 EVP_PKEY
*pkey
= NULL
;
563 desc
= "private key";
565 if (format
== FORMAT_ENGINE
) {
567 BIO_printf(bio_err
, "No engine specified for loading %s\n", desc
);
569 pkey
= load_engine_private_key(e
, uri
, pass
, desc
);
571 BIO_printf(bio_err
, "Cannot load %s from engine\n", desc
);
572 ERR_print_errors(bio_err
);
576 (void)load_key_certs_crls(uri
, may_stdin
, pass
, desc
,
577 &pkey
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
);
583 EVP_PKEY
*load_pubkey(const char *uri
, int format
, int maybe_stdin
,
584 const char *pass
, ENGINE
*e
, const char *desc
)
586 EVP_PKEY
*pkey
= NULL
;
591 if (format
== FORMAT_ENGINE
) {
593 BIO_printf(bio_err
, "No engine specified for loading %s\n", desc
);
595 pkey
= load_engine_public_key(e
, uri
, pass
, desc
);
597 BIO_printf(bio_err
, "Cannot load %s from engine\n", desc
);
598 ERR_print_errors(bio_err
);
602 (void)load_key_certs_crls(uri
, maybe_stdin
, pass
, desc
,
603 NULL
, &pkey
, NULL
, NULL
, NULL
, NULL
, NULL
);
609 EVP_PKEY
*load_keyparams(const char *uri
, int maybe_stdin
, const char *keytype
,
612 EVP_PKEY
*params
= NULL
;
615 desc
= "key parameters";
617 (void)load_key_certs_crls(uri
, maybe_stdin
, NULL
, desc
,
618 NULL
, NULL
, ¶ms
, NULL
, NULL
, NULL
, NULL
);
619 if (params
!= NULL
&& keytype
!= NULL
&& !EVP_PKEY_is_a(params
, keytype
)) {
621 "Unable to load %s from %s (unexpected parameters type)\n",
623 ERR_print_errors(bio_err
);
624 EVP_PKEY_free(params
);
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
, 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
, 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
,
704 X509
**pcert
, STACK_OF(X509
) **pcerts
,
705 X509_CRL
**pcrl
, STACK_OF(X509_CRL
) **pcrls
)
708 OSSL_STORE_CTX
*ctx
= NULL
;
709 OSSL_LIB_CTX
*libctx
= app_get0_libctx();
710 const char *propq
= app_get0_propq();
714 ppkey
!= NULL
? "key" : ppubkey
!= NULL
? "public key" :
715 pparams
!= NULL
? "params" : pcert
!= NULL
? "cert" :
716 pcrl
!= NULL
? "CRL" : pcerts
!= NULL
? "certs" :
717 pcrls
!= NULL
? "CRLs" : NULL
;
718 /* TODO make use of the engine reference 'eng' when loading pkeys */
726 if (failed
== NULL
) {
727 BIO_printf(bio_err
, "Internal error: nothing to load into from %s\n",
728 uri
!= NULL
? uri
: "<stdin>");
732 if (pcerts
!= NULL
&& *pcerts
== NULL
733 && (*pcerts
= sk_X509_new_null()) == NULL
) {
734 BIO_printf(bio_err
, "Out of memory loading");
739 if (pcrls
!= NULL
&& *pcrls
== NULL
740 && (*pcrls
= sk_X509_CRL_new_null()) == NULL
) {
741 BIO_printf(bio_err
, "Out of memory loading");
745 uidata
.password
= pass
;
746 uidata
.prompt_info
= uri
;
752 BIO_printf(bio_err
, "No filename or uri specified for loading");
757 bio
= BIO_new_fp(stdin
, 0);
759 ctx
= OSSL_STORE_attach(bio
, "file", libctx
, propq
,
760 get_ui_method(), &uidata
, NULL
, NULL
);
762 ctx
= OSSL_STORE_open_ex(uri
, libctx
, propq
, get_ui_method(), &uidata
,
766 BIO_printf(bio_err
, "Could not open file or uri for loading");
771 while (!OSSL_STORE_eof(ctx
)) {
772 OSSL_STORE_INFO
*info
= OSSL_STORE_load(ctx
);
777 type
= OSSL_STORE_INFO_get_type(info
);
779 case OSSL_STORE_INFO_PKEY
:
780 if (ppkey
!= NULL
&& *ppkey
== NULL
)
781 ok
= (*ppkey
= OSSL_STORE_INFO_get1_PKEY(info
)) != NULL
;
784 * An EVP_PKEY with private parts also holds the public parts,
785 * so if the caller asked for a public key, and we got a private
786 * key, we can still pass it back.
788 if (ok
&& ppubkey
!= NULL
&& *ppubkey
== NULL
)
789 ok
= ((*ppubkey
= OSSL_STORE_INFO_get1_PKEY(info
)) != NULL
);
791 case OSSL_STORE_INFO_PUBKEY
:
792 if (ppubkey
!= NULL
&& *ppubkey
== NULL
)
793 ok
= ((*ppubkey
= OSSL_STORE_INFO_get1_PUBKEY(info
)) != NULL
);
795 case OSSL_STORE_INFO_PARAMS
:
796 if (pparams
!= NULL
&& *pparams
== NULL
)
797 ok
= ((*pparams
= OSSL_STORE_INFO_get1_PARAMS(info
)) != NULL
);
799 case OSSL_STORE_INFO_CERT
:
800 if (pcert
!= NULL
&& *pcert
== NULL
)
801 ok
= (*pcert
= OSSL_STORE_INFO_get1_CERT(info
)) != NULL
;
802 else if (pcerts
!= NULL
)
803 ok
= X509_add_cert(*pcerts
,
804 OSSL_STORE_INFO_get1_CERT(info
),
805 X509_ADD_FLAG_DEFAULT
);
808 case OSSL_STORE_INFO_CRL
:
809 if (pcrl
!= NULL
&& *pcrl
== NULL
)
810 ok
= (*pcrl
= OSSL_STORE_INFO_get1_CRL(info
)) != NULL
;
811 else if (pcrls
!= NULL
)
812 ok
= sk_X509_CRL_push(*pcrls
, OSSL_STORE_INFO_get1_CRL(info
));
816 /* skip any other type */
819 OSSL_STORE_INFO_free(info
);
821 failed
= info
== NULL
? NULL
: OSSL_STORE_INFO_type_string(type
);
822 BIO_printf(bio_err
, "Error reading");
828 OSSL_STORE_close(ctx
);
829 if (failed
== NULL
) {
832 if ((ppkey
!= NULL
&& *ppkey
== NULL
)
833 || (ppubkey
!= NULL
&& *ppubkey
== NULL
)) {
835 } else if (pparams
!= NULL
&& *pparams
== NULL
) {
837 } else if ((pcert
!= NULL
|| pcerts
!= NULL
) && ncerts
== 0) {
841 } else if ((pcrl
!= NULL
|| pcrls
!= NULL
) && ncrls
== 0) {
847 BIO_printf(bio_err
, "Could not read");
849 BIO_printf(bio_err
, " any");
851 if (failed
!= NULL
) {
852 if (desc
!= NULL
&& strstr(desc
, failed
) != NULL
) {
853 BIO_printf(bio_err
, " %s", desc
);
855 BIO_printf(bio_err
, " %s", failed
);
857 BIO_printf(bio_err
, " of %s", desc
);
860 BIO_printf(bio_err
, " from %s", uri
);
861 BIO_printf(bio_err
, "\n");
862 ERR_print_errors(bio_err
);
864 return failed
== NULL
;
868 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
869 /* Return error for unknown extensions */
870 #define X509V3_EXT_DEFAULT 0
871 /* Print error for unknown extensions */
872 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
873 /* ASN1 parse unknown extensions */
874 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
875 /* BIO_dump unknown extensions */
876 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
878 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
879 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
881 int set_cert_ex(unsigned long *flags
, const char *arg
)
883 static const NAME_EX_TBL cert_tbl
[] = {
884 {"compatible", X509_FLAG_COMPAT
, 0xffffffffl
},
885 {"ca_default", X509_FLAG_CA
, 0xffffffffl
},
886 {"no_header", X509_FLAG_NO_HEADER
, 0},
887 {"no_version", X509_FLAG_NO_VERSION
, 0},
888 {"no_serial", X509_FLAG_NO_SERIAL
, 0},
889 {"no_signame", X509_FLAG_NO_SIGNAME
, 0},
890 {"no_validity", X509_FLAG_NO_VALIDITY
, 0},
891 {"no_subject", X509_FLAG_NO_SUBJECT
, 0},
892 {"no_issuer", X509_FLAG_NO_ISSUER
, 0},
893 {"no_pubkey", X509_FLAG_NO_PUBKEY
, 0},
894 {"no_extensions", X509_FLAG_NO_EXTENSIONS
, 0},
895 {"no_sigdump", X509_FLAG_NO_SIGDUMP
, 0},
896 {"no_aux", X509_FLAG_NO_AUX
, 0},
897 {"no_attributes", X509_FLAG_NO_ATTRIBUTES
, 0},
898 {"ext_default", X509V3_EXT_DEFAULT
, X509V3_EXT_UNKNOWN_MASK
},
899 {"ext_error", X509V3_EXT_ERROR_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
900 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
901 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
904 return set_multi_opts(flags
, arg
, cert_tbl
);
907 int set_name_ex(unsigned long *flags
, const char *arg
)
909 static const NAME_EX_TBL ex_tbl
[] = {
910 {"esc_2253", ASN1_STRFLGS_ESC_2253
, 0},
911 {"esc_2254", ASN1_STRFLGS_ESC_2254
, 0},
912 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL
, 0},
913 {"esc_msb", ASN1_STRFLGS_ESC_MSB
, 0},
914 {"use_quote", ASN1_STRFLGS_ESC_QUOTE
, 0},
915 {"utf8", ASN1_STRFLGS_UTF8_CONVERT
, 0},
916 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE
, 0},
917 {"show_type", ASN1_STRFLGS_SHOW_TYPE
, 0},
918 {"dump_all", ASN1_STRFLGS_DUMP_ALL
, 0},
919 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN
, 0},
920 {"dump_der", ASN1_STRFLGS_DUMP_DER
, 0},
921 {"compat", XN_FLAG_COMPAT
, 0xffffffffL
},
922 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS
, XN_FLAG_SEP_MASK
},
923 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC
, XN_FLAG_SEP_MASK
},
924 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC
, XN_FLAG_SEP_MASK
},
925 {"sep_multiline", XN_FLAG_SEP_MULTILINE
, XN_FLAG_SEP_MASK
},
926 {"dn_rev", XN_FLAG_DN_REV
, 0},
927 {"nofname", XN_FLAG_FN_NONE
, XN_FLAG_FN_MASK
},
928 {"sname", XN_FLAG_FN_SN
, XN_FLAG_FN_MASK
},
929 {"lname", XN_FLAG_FN_LN
, XN_FLAG_FN_MASK
},
930 {"align", XN_FLAG_FN_ALIGN
, 0},
931 {"oid", XN_FLAG_FN_OID
, XN_FLAG_FN_MASK
},
932 {"space_eq", XN_FLAG_SPC_EQ
, 0},
933 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS
, 0},
934 {"RFC2253", XN_FLAG_RFC2253
, 0xffffffffL
},
935 {"oneline", XN_FLAG_ONELINE
, 0xffffffffL
},
936 {"multiline", XN_FLAG_MULTILINE
, 0xffffffffL
},
937 {"ca_default", XN_FLAG_MULTILINE
, 0xffffffffL
},
940 if (set_multi_opts(flags
, arg
, ex_tbl
) == 0)
942 if (*flags
!= XN_FLAG_COMPAT
943 && (*flags
& XN_FLAG_SEP_MASK
) == 0)
944 *flags
|= XN_FLAG_SEP_CPLUS_SPC
;
948 int set_ext_copy(int *copy_type
, const char *arg
)
950 if (strcasecmp(arg
, "none") == 0)
951 *copy_type
= EXT_COPY_NONE
;
952 else if (strcasecmp(arg
, "copy") == 0)
953 *copy_type
= EXT_COPY_ADD
;
954 else if (strcasecmp(arg
, "copyall") == 0)
955 *copy_type
= EXT_COPY_ALL
;
961 int copy_extensions(X509
*x
, X509_REQ
*req
, int copy_type
)
963 STACK_OF(X509_EXTENSION
) *exts
= NULL
;
964 X509_EXTENSION
*ext
, *tmpext
;
967 if (!x
|| !req
|| (copy_type
== EXT_COPY_NONE
))
969 exts
= X509_REQ_get_extensions(req
);
971 for (i
= 0; i
< sk_X509_EXTENSION_num(exts
); i
++) {
972 ext
= sk_X509_EXTENSION_value(exts
, i
);
973 obj
= X509_EXTENSION_get_object(ext
);
974 idx
= X509_get_ext_by_OBJ(x
, obj
, -1);
975 /* Does extension exist? */
977 /* If normal copy don't override existing extension */
978 if (copy_type
== EXT_COPY_ADD
)
980 /* Delete all extensions of same type */
982 tmpext
= X509_get_ext(x
, idx
);
983 X509_delete_ext(x
, idx
);
984 X509_EXTENSION_free(tmpext
);
985 idx
= X509_get_ext_by_OBJ(x
, obj
, -1);
988 if (!X509_add_ext(x
, ext
, -1))
996 sk_X509_EXTENSION_pop_free(exts
, X509_EXTENSION_free
);
1001 static int set_multi_opts(unsigned long *flags
, const char *arg
,
1002 const NAME_EX_TBL
* in_tbl
)
1004 STACK_OF(CONF_VALUE
) *vals
;
1009 vals
= X509V3_parse_list(arg
);
1010 for (i
= 0; i
< sk_CONF_VALUE_num(vals
); i
++) {
1011 val
= sk_CONF_VALUE_value(vals
, i
);
1012 if (!set_table_opts(flags
, val
->name
, in_tbl
))
1015 sk_CONF_VALUE_pop_free(vals
, X509V3_conf_free
);
1019 static int set_table_opts(unsigned long *flags
, const char *arg
,
1020 const NAME_EX_TBL
* in_tbl
)
1023 const NAME_EX_TBL
*ptbl
;
1029 } else if (c
== '+') {
1036 for (ptbl
= in_tbl
; ptbl
->name
; ptbl
++) {
1037 if (strcasecmp(arg
, ptbl
->name
) == 0) {
1038 *flags
&= ~ptbl
->mask
;
1040 *flags
|= ptbl
->flag
;
1042 *flags
&= ~ptbl
->flag
;
1049 void print_name(BIO
*out
, const char *title
, const X509_NAME
*nm
,
1050 unsigned long lflags
)
1057 BIO_puts(out
, title
);
1058 if ((lflags
& XN_FLAG_SEP_MASK
) == XN_FLAG_SEP_MULTILINE
) {
1062 if (lflags
== XN_FLAG_COMPAT
) {
1063 buf
= X509_NAME_oneline(nm
, 0, 0);
1065 BIO_puts(out
, "\n");
1069 BIO_puts(out
, "\n");
1070 X509_NAME_print_ex(out
, nm
, indent
, lflags
);
1071 BIO_puts(out
, "\n");
1075 void print_bignum_var(BIO
*out
, const BIGNUM
*in
, const char *var
,
1076 int len
, unsigned char *buffer
)
1078 BIO_printf(out
, " static unsigned char %s_%d[] = {", var
, len
);
1079 if (BN_is_zero(in
)) {
1080 BIO_printf(out
, "\n 0x00");
1084 l
= BN_bn2bin(in
, buffer
);
1085 for (i
= 0; i
< l
; i
++) {
1086 BIO_printf(out
, (i
% 10) == 0 ? "\n " : " ");
1088 BIO_printf(out
, "0x%02X,", buffer
[i
]);
1090 BIO_printf(out
, "0x%02X", buffer
[i
]);
1093 BIO_printf(out
, "\n };\n");
1096 void print_array(BIO
*out
, const char* title
, int len
, const unsigned char* d
)
1100 BIO_printf(out
, "unsigned char %s[%d] = {", title
, len
);
1101 for (i
= 0; i
< len
; i
++) {
1103 BIO_printf(out
, "\n ");
1105 BIO_printf(out
, "0x%02X, ", d
[i
]);
1107 BIO_printf(out
, "0x%02X", d
[i
]);
1109 BIO_printf(out
, "\n};\n");
1112 X509_STORE
*setup_verify(const char *CAfile
, int noCAfile
,
1113 const char *CApath
, int noCApath
,
1114 const char *CAstore
, int noCAstore
)
1116 X509_STORE
*store
= X509_STORE_new();
1117 X509_LOOKUP
*lookup
;
1118 OSSL_LIB_CTX
*libctx
= app_get0_libctx();
1119 const char *propq
= app_get0_propq();
1124 if (CAfile
!= NULL
|| !noCAfile
) {
1125 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_file());
1128 if (CAfile
!= NULL
) {
1129 if (!X509_LOOKUP_load_file_ex(lookup
, CAfile
, X509_FILETYPE_PEM
,
1131 BIO_printf(bio_err
, "Error loading file %s\n", CAfile
);
1135 X509_LOOKUP_load_file_ex(lookup
, NULL
, X509_FILETYPE_DEFAULT
,
1140 if (CApath
!= NULL
|| !noCApath
) {
1141 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_hash_dir());
1144 if (CApath
!= NULL
) {
1145 if (!X509_LOOKUP_add_dir(lookup
, CApath
, X509_FILETYPE_PEM
)) {
1146 BIO_printf(bio_err
, "Error loading directory %s\n", CApath
);
1150 X509_LOOKUP_add_dir(lookup
, NULL
, X509_FILETYPE_DEFAULT
);
1154 if (CAstore
!= NULL
|| !noCAstore
) {
1155 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_store());
1158 if (!X509_LOOKUP_add_store_ex(lookup
, CAstore
, libctx
, propq
)) {
1159 if (CAstore
!= NULL
)
1160 BIO_printf(bio_err
, "Error loading store URI %s\n", CAstore
);
1168 ERR_print_errors(bio_err
);
1169 X509_STORE_free(store
);
1173 static unsigned long index_serial_hash(const OPENSSL_CSTRING
*a
)
1180 return OPENSSL_LH_strhash(n
);
1183 static int index_serial_cmp(const OPENSSL_CSTRING
*a
,
1184 const OPENSSL_CSTRING
*b
)
1186 const char *aa
, *bb
;
1188 for (aa
= a
[DB_serial
]; *aa
== '0'; aa
++) ;
1189 for (bb
= b
[DB_serial
]; *bb
== '0'; bb
++) ;
1190 return strcmp(aa
, bb
);
1193 static int index_name_qual(char **a
)
1195 return (a
[0][0] == 'V');
1198 static unsigned long index_name_hash(const OPENSSL_CSTRING
*a
)
1200 return OPENSSL_LH_strhash(a
[DB_name
]);
1203 int index_name_cmp(const OPENSSL_CSTRING
*a
, const OPENSSL_CSTRING
*b
)
1205 return strcmp(a
[DB_name
], b
[DB_name
]);
1208 static IMPLEMENT_LHASH_HASH_FN(index_serial
, OPENSSL_CSTRING
)
1209 static IMPLEMENT_LHASH_COMP_FN(index_serial
, OPENSSL_CSTRING
)
1210 static IMPLEMENT_LHASH_HASH_FN(index_name
, OPENSSL_CSTRING
)
1211 static IMPLEMENT_LHASH_COMP_FN(index_name
, OPENSSL_CSTRING
)
1214 BIGNUM
*load_serial(const char *serialfile
, int create
, ASN1_INTEGER
**retai
)
1219 ASN1_INTEGER
*ai
= NULL
;
1221 ai
= ASN1_INTEGER_new();
1225 in
= BIO_new_file(serialfile
, "r");
1233 if (ret
== NULL
|| !rand_serial(ret
, ai
))
1234 BIO_printf(bio_err
, "Out of memory\n");
1236 if (!a2i_ASN1_INTEGER(in
, ai
, buf
, 1024)) {
1237 BIO_printf(bio_err
, "Unable to load number from %s\n",
1241 ret
= ASN1_INTEGER_to_BN(ai
, NULL
);
1243 BIO_printf(bio_err
, "Error converting number from bin to BIGNUM\n");
1253 ERR_print_errors(bio_err
);
1255 ASN1_INTEGER_free(ai
);
1259 int save_serial(const char *serialfile
, const char *suffix
, const BIGNUM
*serial
,
1260 ASN1_INTEGER
**retai
)
1265 ASN1_INTEGER
*ai
= NULL
;
1269 j
= strlen(serialfile
);
1271 j
= strlen(serialfile
) + strlen(suffix
) + 1;
1273 BIO_printf(bio_err
, "File name too long\n");
1278 OPENSSL_strlcpy(buf
[0], serialfile
, BSIZE
);
1280 #ifndef OPENSSL_SYS_VMS
1281 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, suffix
);
1283 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, suffix
);
1286 out
= BIO_new_file(buf
[0], "w");
1291 if ((ai
= BN_to_ASN1_INTEGER(serial
, NULL
)) == NULL
) {
1292 BIO_printf(bio_err
, "error converting serial to ASN.1 format\n");
1295 i2a_ASN1_INTEGER(out
, ai
);
1296 BIO_puts(out
, "\n");
1304 ERR_print_errors(bio_err
);
1306 ASN1_INTEGER_free(ai
);
1310 int rotate_serial(const char *serialfile
, const char *new_suffix
,
1311 const char *old_suffix
)
1316 i
= strlen(serialfile
) + strlen(old_suffix
);
1317 j
= strlen(serialfile
) + strlen(new_suffix
);
1320 if (j
+ 1 >= BSIZE
) {
1321 BIO_printf(bio_err
, "File name too long\n");
1324 #ifndef OPENSSL_SYS_VMS
1325 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, new_suffix
);
1326 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", serialfile
, old_suffix
);
1328 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, new_suffix
);
1329 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", serialfile
, old_suffix
);
1331 if (rename(serialfile
, buf
[1]) < 0 && errno
!= ENOENT
1337 "Unable to rename %s to %s\n", serialfile
, buf
[1]);
1341 if (rename(buf
[0], serialfile
) < 0) {
1343 "Unable to rename %s to %s\n", buf
[0], serialfile
);
1345 rename(buf
[1], serialfile
);
1350 ERR_print_errors(bio_err
);
1354 int rand_serial(BIGNUM
*b
, ASN1_INTEGER
*ai
)
1359 btmp
= b
== NULL
? BN_new() : b
;
1363 if (!BN_rand(btmp
, SERIAL_RAND_BITS
, BN_RAND_TOP_ANY
, BN_RAND_BOTTOM_ANY
))
1365 if (ai
&& !BN_to_ASN1_INTEGER(btmp
, ai
))
1378 CA_DB
*load_index(const char *dbfile
, DB_ATTR
*db_attr
)
1380 CA_DB
*retdb
= NULL
;
1381 TXT_DB
*tmpdb
= NULL
;
1383 CONF
*dbattr_conf
= NULL
;
1385 #ifndef OPENSSL_NO_POSIX_IO
1390 in
= BIO_new_file(dbfile
, "r");
1394 #ifndef OPENSSL_NO_POSIX_IO
1395 BIO_get_fp(in
, &dbfp
);
1396 if (fstat(fileno(dbfp
), &dbst
) == -1) {
1397 ERR_raise_data(ERR_LIB_SYS
, errno
,
1398 "calling fstat(%s)", dbfile
);
1403 if ((tmpdb
= TXT_DB_read(in
, DB_NUMBER
)) == NULL
)
1406 #ifndef OPENSSL_SYS_VMS
1407 BIO_snprintf(buf
, sizeof(buf
), "%s.attr", dbfile
);
1409 BIO_snprintf(buf
, sizeof(buf
), "%s-attr", dbfile
);
1411 dbattr_conf
= app_load_config_quiet(buf
);
1413 retdb
= app_malloc(sizeof(*retdb
), "new DB");
1417 retdb
->attributes
= *db_attr
;
1419 retdb
->attributes
.unique_subject
= 1;
1423 char *p
= NCONF_get_string(dbattr_conf
, NULL
, "unique_subject");
1425 retdb
->attributes
.unique_subject
= parse_yesno(p
, 1);
1429 retdb
->dbfname
= OPENSSL_strdup(dbfile
);
1430 #ifndef OPENSSL_NO_POSIX_IO
1435 ERR_print_errors(bio_err
);
1436 NCONF_free(dbattr_conf
);
1443 * Returns > 0 on success, <= 0 on error
1445 int index_index(CA_DB
*db
)
1447 if (!TXT_DB_create_index(db
->db
, DB_serial
, NULL
,
1448 LHASH_HASH_FN(index_serial
),
1449 LHASH_COMP_FN(index_serial
))) {
1451 "Error creating serial number index:(%ld,%ld,%ld)\n",
1452 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1456 if (db
->attributes
.unique_subject
1457 && !TXT_DB_create_index(db
->db
, DB_name
, index_name_qual
,
1458 LHASH_HASH_FN(index_name
),
1459 LHASH_COMP_FN(index_name
))) {
1460 BIO_printf(bio_err
, "Error creating name index:(%ld,%ld,%ld)\n",
1461 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1466 ERR_print_errors(bio_err
);
1470 int save_index(const char *dbfile
, const char *suffix
, CA_DB
*db
)
1476 j
= strlen(dbfile
) + strlen(suffix
);
1477 if (j
+ 6 >= BSIZE
) {
1478 BIO_printf(bio_err
, "File name too long\n");
1481 #ifndef OPENSSL_SYS_VMS
1482 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr", dbfile
);
1483 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.attr.%s", dbfile
, suffix
);
1484 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, suffix
);
1486 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr", dbfile
);
1487 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-attr-%s", dbfile
, suffix
);
1488 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, suffix
);
1490 out
= BIO_new_file(buf
[0], "w");
1493 BIO_printf(bio_err
, "Unable to open '%s'\n", dbfile
);
1496 j
= TXT_DB_write(out
, db
->db
);
1501 out
= BIO_new_file(buf
[1], "w");
1504 BIO_printf(bio_err
, "Unable to open '%s'\n", buf
[2]);
1507 BIO_printf(out
, "unique_subject = %s\n",
1508 db
->attributes
.unique_subject
? "yes" : "no");
1513 ERR_print_errors(bio_err
);
1517 int rotate_index(const char *dbfile
, const char *new_suffix
,
1518 const char *old_suffix
)
1523 i
= strlen(dbfile
) + strlen(old_suffix
);
1524 j
= strlen(dbfile
) + strlen(new_suffix
);
1527 if (j
+ 6 >= BSIZE
) {
1528 BIO_printf(bio_err
, "File name too long\n");
1531 #ifndef OPENSSL_SYS_VMS
1532 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s.attr", dbfile
);
1533 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s.attr.%s", dbfile
, old_suffix
);
1534 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr.%s", dbfile
, new_suffix
);
1535 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", dbfile
, old_suffix
);
1536 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, new_suffix
);
1538 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s-attr", dbfile
);
1539 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s-attr-%s", dbfile
, old_suffix
);
1540 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr-%s", dbfile
, new_suffix
);
1541 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", dbfile
, old_suffix
);
1542 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, new_suffix
);
1544 if (rename(dbfile
, buf
[1]) < 0 && errno
!= ENOENT
1549 BIO_printf(bio_err
, "Unable to rename %s to %s\n", dbfile
, buf
[1]);
1553 if (rename(buf
[0], dbfile
) < 0) {
1554 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[0], dbfile
);
1556 rename(buf
[1], dbfile
);
1559 if (rename(buf
[4], buf
[3]) < 0 && errno
!= ENOENT
1564 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[4], buf
[3]);
1566 rename(dbfile
, buf
[0]);
1567 rename(buf
[1], dbfile
);
1570 if (rename(buf
[2], buf
[4]) < 0) {
1571 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[2], buf
[4]);
1573 rename(buf
[3], buf
[4]);
1574 rename(dbfile
, buf
[0]);
1575 rename(buf
[1], dbfile
);
1580 ERR_print_errors(bio_err
);
1584 void free_index(CA_DB
*db
)
1587 TXT_DB_free(db
->db
);
1588 OPENSSL_free(db
->dbfname
);
1593 int parse_yesno(const char *str
, int def
)
1597 case 'f': /* false */
1598 case 'F': /* FALSE */
1603 case 't': /* true */
1604 case 'T': /* TRUE */
1615 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1616 * where + can be used instead of / to form multi-valued RDNs if canmulti
1617 * and characters may be escaped by \
1619 X509_NAME
*parse_name(const char *cp
, int chtype
, int canmulti
,
1622 int nextismulti
= 0;
1628 "%s: %s name is expected to be in the format "
1629 "/type0=value0/type1=value1/type2=... where characters may "
1630 "be escaped by \\. This name is not in that format: '%s'\n",
1631 opt_getprog(), desc
, --cp
);
1635 n
= X509_NAME_new();
1637 BIO_printf(bio_err
, "%s: Out of memory\n", opt_getprog());
1640 work
= OPENSSL_strdup(cp
);
1642 BIO_printf(bio_err
, "%s: Error copying %s name input\n",
1643 opt_getprog(), desc
);
1647 while (*cp
!= '\0') {
1650 unsigned char *valstr
;
1652 int ismulti
= nextismulti
;
1655 /* Collect the type */
1656 while (*cp
!= '\0' && *cp
!= '=')
1661 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1662 opt_getprog(), typestr
, desc
);
1667 /* Collect the value. */
1668 valstr
= (unsigned char *)bp
;
1669 for (; *cp
!= '\0' && *cp
!= '/'; *bp
++ = *cp
++) {
1670 /* unescaped '+' symbol string signals further member of multiRDN */
1671 if (canmulti
&& *cp
== '+') {
1675 if (*cp
== '\\' && *++cp
== '\0') {
1677 "%s: Escape character at end of %s name string\n",
1678 opt_getprog(), desc
);
1684 /* If not at EOS (must be + or /), move forward. */
1689 nid
= OBJ_txt2nid(typestr
);
1690 if (nid
== NID_undef
) {
1692 "%s: Skipping unknown %s name attribute \"%s\"\n",
1693 opt_getprog(), desc
, typestr
);
1696 "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
1699 if (*valstr
== '\0') {
1701 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1702 opt_getprog(), desc
, typestr
);
1705 if (!X509_NAME_add_entry_by_NID(n
, nid
, chtype
,
1706 valstr
, strlen((char *)valstr
),
1707 -1, ismulti
? -1 : 0)) {
1708 ERR_print_errors(bio_err
);
1710 "%s: Error adding %s name attribute \"/%s=%s\"\n",
1711 opt_getprog(), desc
, typestr
,valstr
);
1726 * Read whole contents of a BIO into an allocated memory buffer and return
1730 int bio_to_mem(unsigned char **out
, int maxlen
, BIO
*in
)
1734 unsigned char tbuf
[1024];
1736 mem
= BIO_new(BIO_s_mem());
1740 if ((maxlen
!= -1) && maxlen
< 1024)
1744 len
= BIO_read(in
, tbuf
, len
);
1751 if (BIO_write(mem
, tbuf
, len
) != len
) {
1760 ret
= BIO_get_mem_data(mem
, (char **)out
);
1761 BIO_set_flags(mem
, BIO_FLAGS_MEM_RDONLY
);
1766 int pkey_ctrl_string(EVP_PKEY_CTX
*ctx
, const char *value
)
1769 char *stmp
, *vtmp
= NULL
;
1770 stmp
= OPENSSL_strdup(value
);
1773 vtmp
= strchr(stmp
, ':');
1778 rv
= EVP_PKEY_CTX_ctrl_str(ctx
, stmp
, vtmp
);
1783 static void nodes_print(const char *name
, STACK_OF(X509_POLICY_NODE
) *nodes
)
1785 X509_POLICY_NODE
*node
;
1788 BIO_printf(bio_err
, "%s Policies:", name
);
1790 BIO_puts(bio_err
, "\n");
1791 for (i
= 0; i
< sk_X509_POLICY_NODE_num(nodes
); i
++) {
1792 node
= sk_X509_POLICY_NODE_value(nodes
, i
);
1793 X509_POLICY_NODE_print(bio_err
, node
, 2);
1796 BIO_puts(bio_err
, " <empty>\n");
1800 void policies_print(X509_STORE_CTX
*ctx
)
1802 X509_POLICY_TREE
*tree
;
1803 int explicit_policy
;
1804 tree
= X509_STORE_CTX_get0_policy_tree(ctx
);
1805 explicit_policy
= X509_STORE_CTX_get_explicit_policy(ctx
);
1807 BIO_printf(bio_err
, "Require explicit Policy: %s\n",
1808 explicit_policy
? "True" : "False");
1810 nodes_print("Authority", X509_policy_tree_get0_policies(tree
));
1811 nodes_print("User", X509_policy_tree_get0_user_policies(tree
));
1815 * next_protos_parse parses a comma separated list of strings into a string
1816 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1817 * outlen: (output) set to the length of the resulting buffer on success.
1818 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1819 * in: a NUL terminated string like "abc,def,ghi"
1821 * returns: a malloc'd buffer or NULL on failure.
1823 unsigned char *next_protos_parse(size_t *outlen
, const char *in
)
1827 size_t i
, start
= 0;
1831 if (len
== 0 || len
>= 65535)
1834 out
= app_malloc(len
+ 1, "NPN buffer");
1835 for (i
= 0; i
<= len
; ++i
) {
1836 if (i
== len
|| in
[i
] == ',') {
1838 * Zero-length ALPN elements are invalid on the wire, we could be
1839 * strict and reject the entire string, but just ignoring extra
1840 * commas seems harmless and more friendly.
1842 * Every comma we skip in this way puts the input buffer another
1843 * byte ahead of the output buffer, so all stores into the output
1844 * buffer need to be decremented by the number commas skipped.
1851 if (i
- start
> 255) {
1855 out
[start
-skipped
] = (unsigned char)(i
- start
);
1858 out
[i
+ 1 - skipped
] = in
[i
];
1862 if (len
<= skipped
) {
1867 *outlen
= len
+ 1 - skipped
;
1871 void print_cert_checks(BIO
*bio
, X509
*x
,
1872 const char *checkhost
,
1873 const char *checkemail
, const char *checkip
)
1878 BIO_printf(bio
, "Hostname %s does%s match certificate\n",
1880 X509_check_host(x
, checkhost
, 0, 0, NULL
) == 1
1885 BIO_printf(bio
, "Email %s does%s match certificate\n",
1886 checkemail
, X509_check_email(x
, checkemail
, 0, 0)
1891 BIO_printf(bio
, "IP %s does%s match certificate\n",
1892 checkip
, X509_check_ip_asc(x
, checkip
, 0) ? "" : " NOT");
1896 /* Get first http URL from a DIST_POINT structure */
1898 static const char *get_dp_url(DIST_POINT
*dp
)
1900 GENERAL_NAMES
*gens
;
1904 if (!dp
->distpoint
|| dp
->distpoint
->type
!= 0)
1906 gens
= dp
->distpoint
->name
.fullname
;
1907 for (i
= 0; i
< sk_GENERAL_NAME_num(gens
); i
++) {
1908 gen
= sk_GENERAL_NAME_value(gens
, i
);
1909 uri
= GENERAL_NAME_get0_value(gen
, >ype
);
1910 if (gtype
== GEN_URI
&& ASN1_STRING_length(uri
) > 6) {
1911 const char *uptr
= (const char *)ASN1_STRING_get0_data(uri
);
1913 if (IS_HTTP(uptr
)) /* can/should not use HTTPS here */
1921 * Look through a CRLDP structure and attempt to find an http URL to
1922 * downloads a CRL from.
1925 static X509_CRL
*load_crl_crldp(STACK_OF(DIST_POINT
) *crldp
)
1928 const char *urlptr
= NULL
;
1929 for (i
= 0; i
< sk_DIST_POINT_num(crldp
); i
++) {
1930 DIST_POINT
*dp
= sk_DIST_POINT_value(crldp
, i
);
1931 urlptr
= get_dp_url(dp
);
1933 return load_crl(urlptr
, "CRL via CDP");
1939 * Example of downloading CRLs from CRLDP:
1940 * not usable for real world as it always downloads and doesn't cache anything.
1943 static STACK_OF(X509_CRL
) *crls_http_cb(const X509_STORE_CTX
*ctx
,
1944 const X509_NAME
*nm
)
1947 STACK_OF(X509_CRL
) *crls
= NULL
;
1949 STACK_OF(DIST_POINT
) *crldp
;
1951 crls
= sk_X509_CRL_new_null();
1954 x
= X509_STORE_CTX_get_current_cert(ctx
);
1955 crldp
= X509_get_ext_d2i(x
, NID_crl_distribution_points
, NULL
, NULL
);
1956 crl
= load_crl_crldp(crldp
);
1957 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
1959 sk_X509_CRL_free(crls
);
1962 sk_X509_CRL_push(crls
, crl
);
1963 /* Try to download delta CRL */
1964 crldp
= X509_get_ext_d2i(x
, NID_freshest_crl
, NULL
, NULL
);
1965 crl
= load_crl_crldp(crldp
);
1966 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
1968 sk_X509_CRL_push(crls
, crl
);
1972 void store_setup_crl_download(X509_STORE
*st
)
1974 X509_STORE_set_lookup_crls_cb(st
, crls_http_cb
);
1977 #ifndef OPENSSL_NO_SOCK
1978 static const char *tls_error_hint(void)
1980 unsigned long err
= ERR_peek_error();
1982 if (ERR_GET_LIB(err
) != ERR_LIB_SSL
)
1983 err
= ERR_peek_last_error();
1984 if (ERR_GET_LIB(err
) != ERR_LIB_SSL
)
1987 switch (ERR_GET_REASON(err
)) {
1988 case SSL_R_WRONG_VERSION_NUMBER
:
1989 return "The server does not support (a suitable version of) TLS";
1990 case SSL_R_UNKNOWN_PROTOCOL
:
1991 return "The server does not support HTTPS";
1992 case SSL_R_CERTIFICATE_VERIFY_FAILED
:
1993 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
1994 case SSL_AD_REASON_OFFSET
+ TLS1_AD_UNKNOWN_CA
:
1995 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
1996 case SSL_AD_REASON_OFFSET
+ SSL3_AD_HANDSHAKE_FAILURE
:
1997 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
1998 default: /* no error or no hint available for error */
2003 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
2004 BIO
*app_http_tls_cb(BIO
*hbio
, void *arg
, int connect
, int detail
)
2006 APP_HTTP_TLS_INFO
*info
= (APP_HTTP_TLS_INFO
*)arg
;
2007 SSL_CTX
*ssl_ctx
= info
->ssl_ctx
;
2011 if (connect
&& detail
) { /* connecting with TLS */
2012 if ((info
->use_proxy
2013 && !OSSL_HTTP_proxy_connect(hbio
, info
->server
, info
->port
,
2014 NULL
, NULL
, /* no proxy credentials */
2015 info
->timeout
, bio_err
, opt_getprog()))
2016 || (sbio
= BIO_new(BIO_f_ssl())) == NULL
) {
2019 if (ssl_ctx
== NULL
|| (ssl
= SSL_new(ssl_ctx
)) == NULL
) {
2024 SSL_set_tlsext_host_name(ssl
, info
->server
);
2026 SSL_set_connect_state(ssl
);
2027 BIO_set_ssl(sbio
, ssl
, BIO_CLOSE
);
2029 hbio
= BIO_push(sbio
, hbio
);
2030 } else if (!connect
&& !detail
) { /* disconnecting after error */
2031 const char *hint
= tls_error_hint();
2033 ERR_add_error_data(2, " : ", hint
);
2035 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2036 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2042 ASN1_VALUE
*app_http_get_asn1(const char *url
, const char *proxy
,
2043 const char *no_proxy
, SSL_CTX
*ssl_ctx
,
2044 const STACK_OF(CONF_VALUE
) *headers
,
2045 long timeout
, const char *expected_content_type
,
2046 const ASN1_ITEM
*it
)
2048 APP_HTTP_TLS_INFO info
;
2052 ASN1_VALUE
*resp
= NULL
;
2054 if (url
== NULL
|| it
== NULL
) {
2055 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
2059 if (!OSSL_HTTP_parse_url(url
, &server
, &port
, NULL
, NULL
, &use_ssl
))
2061 if (use_ssl
&& ssl_ctx
== NULL
) {
2062 ERR_raise_data(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
,
2067 info
.server
= server
;
2069 info
.use_proxy
= proxy
!= NULL
;
2070 info
.timeout
= timeout
;
2071 info
.ssl_ctx
= ssl_ctx
;
2072 resp
= OSSL_HTTP_get_asn1(url
, proxy
, no_proxy
,
2073 NULL
, NULL
, app_http_tls_cb
, &info
,
2074 headers
, 0 /* maxline */, 0 /* max_resp_len */,
2075 timeout
, expected_content_type
, it
);
2077 OPENSSL_free(server
);
2083 ASN1_VALUE
*app_http_post_asn1(const char *host
, const char *port
,
2084 const char *path
, const char *proxy
,
2085 const char *no_proxy
, SSL_CTX
*ssl_ctx
,
2086 const STACK_OF(CONF_VALUE
) *headers
,
2087 const char *content_type
,
2088 ASN1_VALUE
*req
, const ASN1_ITEM
*req_it
,
2089 long timeout
, const ASN1_ITEM
*rsp_it
)
2091 APP_HTTP_TLS_INFO info
;
2095 info
.use_proxy
= proxy
!= NULL
;
2096 info
.timeout
= timeout
;
2097 info
.ssl_ctx
= ssl_ctx
;
2098 return OSSL_HTTP_post_asn1(host
, port
, path
, ssl_ctx
!= NULL
,
2100 NULL
, NULL
, app_http_tls_cb
, &info
,
2101 headers
, content_type
, req
, req_it
,
2103 0 /* max_resp_len */, timeout
, NULL
, rsp_it
);
2109 * Platform-specific sections
2114 # define fileno(a) (int)_fileno(a)
2117 # include <windows.h>
2120 static int WIN32_rename(const char *from
, const char *to
)
2122 TCHAR
*tfrom
= NULL
, *tto
;
2126 if (sizeof(TCHAR
) == 1) {
2127 tfrom
= (TCHAR
*)from
;
2129 } else { /* UNICODE path */
2131 size_t i
, flen
= strlen(from
) + 1, tlen
= strlen(to
) + 1;
2132 tfrom
= malloc(sizeof(*tfrom
) * (flen
+ tlen
));
2136 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2137 if (!MultiByteToWideChar(CP_ACP
, 0, from
, flen
, (WCHAR
*)tfrom
, flen
))
2139 for (i
= 0; i
< flen
; i
++)
2140 tfrom
[i
] = (TCHAR
)from
[i
];
2141 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2142 if (!MultiByteToWideChar(CP_ACP
, 0, to
, tlen
, (WCHAR
*)tto
, tlen
))
2144 for (i
= 0; i
< tlen
; i
++)
2145 tto
[i
] = (TCHAR
)to
[i
];
2148 if (MoveFile(tfrom
, tto
))
2150 err
= GetLastError();
2151 if (err
== ERROR_ALREADY_EXISTS
|| err
== ERROR_FILE_EXISTS
) {
2152 if (DeleteFile(tto
) && MoveFile(tfrom
, tto
))
2154 err
= GetLastError();
2156 if (err
== ERROR_FILE_NOT_FOUND
|| err
== ERROR_PATH_NOT_FOUND
)
2158 else if (err
== ERROR_ACCESS_DENIED
)
2161 errno
= EINVAL
; /* we could map more codes... */
2165 if (tfrom
!= NULL
&& tfrom
!= (TCHAR
*)from
)
2171 /* app_tminterval section */
2173 double app_tminterval(int stop
, int usertime
)
2177 static ULARGE_INTEGER tmstart
;
2178 static int warning
= 1;
2179 # ifdef _WIN32_WINNT
2180 static HANDLE proc
= NULL
;
2184 proc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
,
2185 GetCurrentProcessId());
2187 proc
= (HANDLE
) - 1;
2190 if (usertime
&& proc
!= (HANDLE
) - 1) {
2192 GetProcessTimes(proc
, &junk
, &junk
, &junk
, &now
);
2198 if (usertime
&& warning
) {
2199 BIO_printf(bio_err
, "To get meaningful results, run "
2200 "this program on idle system.\n");
2203 GetSystemTime(&systime
);
2204 SystemTimeToFileTime(&systime
, &now
);
2207 if (stop
== TM_START
) {
2208 tmstart
.u
.LowPart
= now
.dwLowDateTime
;
2209 tmstart
.u
.HighPart
= now
.dwHighDateTime
;
2211 ULARGE_INTEGER tmstop
;
2213 tmstop
.u
.LowPart
= now
.dwLowDateTime
;
2214 tmstop
.u
.HighPart
= now
.dwHighDateTime
;
2216 ret
= (__int64
)(tmstop
.QuadPart
- tmstart
.QuadPart
) * 1e-7;
2221 #elif defined(OPENSSL_SYS_VXWORKS)
2224 double app_tminterval(int stop
, int usertime
)
2227 # ifdef CLOCK_REALTIME
2228 static struct timespec tmstart
;
2229 struct timespec now
;
2231 static unsigned long tmstart
;
2234 static int warning
= 1;
2236 if (usertime
&& warning
) {
2237 BIO_printf(bio_err
, "To get meaningful results, run "
2238 "this program on idle system.\n");
2241 # ifdef CLOCK_REALTIME
2242 clock_gettime(CLOCK_REALTIME
, &now
);
2243 if (stop
== TM_START
)
2246 ret
= ((now
.tv_sec
+ now
.tv_nsec
* 1e-9)
2247 - (tmstart
.tv_sec
+ tmstart
.tv_nsec
* 1e-9));
2250 if (stop
== TM_START
)
2253 ret
= (now
- tmstart
) / (double)sysClkRateGet();
2258 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2259 # include <sys/times.h>
2261 double app_tminterval(int stop
, int usertime
)
2265 clock_t now
= times(&rus
);
2266 static clock_t tmstart
;
2269 now
= rus
.tms_utime
;
2271 if (stop
== TM_START
) {
2274 long int tck
= sysconf(_SC_CLK_TCK
);
2275 ret
= (now
- tmstart
) / (double)tck
;
2282 # include <sys/time.h>
2283 # include <sys/resource.h>
2285 double app_tminterval(int stop
, int usertime
)
2290 static struct timeval tmstart
;
2293 getrusage(RUSAGE_SELF
, &rus
), now
= rus
.ru_utime
;
2295 gettimeofday(&now
, NULL
);
2297 if (stop
== TM_START
)
2300 ret
= ((now
.tv_sec
+ now
.tv_usec
* 1e-6)
2301 - (tmstart
.tv_sec
+ tmstart
.tv_usec
* 1e-6));
2307 int app_access(const char* name
, int flag
)
2310 return _access(name
, flag
);
2312 return access(name
, flag
);
2316 int app_isdir(const char *name
)
2318 return opt_isdir(name
);
2321 /* raw_read|write section */
2323 # include "vms_term_sock.h"
2324 static int stdin_sock
= -1;
2326 static void close_stdin_sock(void)
2328 TerminalSocket (TERM_SOCK_DELETE
, &stdin_sock
);
2331 int fileno_stdin(void)
2333 if (stdin_sock
== -1) {
2334 TerminalSocket(TERM_SOCK_CREATE
, &stdin_sock
);
2335 atexit(close_stdin_sock
);
2341 int fileno_stdin(void)
2343 return fileno(stdin
);
2347 int fileno_stdout(void)
2349 return fileno(stdout
);
2352 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2353 int raw_read_stdin(void *buf
, int siz
)
2356 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2361 #elif defined(__VMS)
2362 # include <sys/socket.h>
2364 int raw_read_stdin(void *buf
, int siz
)
2366 return recv(fileno_stdin(), buf
, siz
, 0);
2369 # if defined(__TANDEM)
2370 # if defined(OPENSSL_TANDEM_FLOSS)
2371 # include <floss.h(floss_read)>
2374 int raw_read_stdin(void *buf
, int siz
)
2376 return read(fileno_stdin(), buf
, siz
);
2380 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2381 int raw_write_stdout(const void *buf
, int siz
)
2384 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2389 #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
2390 # if defined(__TANDEM)
2391 # if defined(OPENSSL_TANDEM_FLOSS)
2392 # include <floss.h(floss_write)>
2395 int raw_write_stdout(const void *buf
,int siz
)
2397 return write(fileno(stdout
),(void*)buf
,siz
);
2400 # if defined(__TANDEM)
2401 # if defined(OPENSSL_TANDEM_FLOSS)
2402 # include <floss.h(floss_write)>
2405 int raw_write_stdout(const void *buf
, int siz
)
2407 return write(fileno_stdout(), buf
, siz
);
2412 * Centralized handling of input and output files with format specification
2413 * The format is meant to show what the input and output is supposed to be,
2414 * and is therefore a show of intent more than anything else. However, it
2415 * does impact behavior on some platforms, such as differentiating between
2416 * text and binary input/output on non-Unix platforms
2418 BIO
*dup_bio_in(int format
)
2420 return BIO_new_fp(stdin
,
2421 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2424 BIO
*dup_bio_out(int format
)
2426 BIO
*b
= BIO_new_fp(stdout
,
2427 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2428 void *prefix
= NULL
;
2430 #ifdef OPENSSL_SYS_VMS
2431 if (FMT_istext(format
))
2432 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2435 if (FMT_istext(format
)
2436 && (prefix
= getenv("HARNESS_OSSL_PREFIX")) != NULL
) {
2437 b
= BIO_push(BIO_new(BIO_f_prefix()), b
);
2438 BIO_set_prefix(b
, prefix
);
2444 BIO
*dup_bio_err(int format
)
2446 BIO
*b
= BIO_new_fp(stderr
,
2447 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2448 #ifdef OPENSSL_SYS_VMS
2449 if (FMT_istext(format
))
2450 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2455 void unbuffer(FILE *fp
)
2458 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2459 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2460 * However, we trust that the C RTL will never give us a FILE pointer
2461 * above the first 4 GB of memory, so we simply turn off the warning
2464 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2465 # pragma environment save
2466 # pragma message disable maylosedata2
2469 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2470 # pragma environment restore
2474 static const char *modestr(char mode
, int format
)
2476 OPENSSL_assert(mode
== 'a' || mode
== 'r' || mode
== 'w');
2480 return FMT_istext(format
) ? "a" : "ab";
2482 return FMT_istext(format
) ? "r" : "rb";
2484 return FMT_istext(format
) ? "w" : "wb";
2486 /* The assert above should make sure we never reach this point */
2490 static const char *modeverb(char mode
)
2500 return "(doing something)";
2504 * Open a file for writing, owner-read-only.
2506 BIO
*bio_open_owner(const char *filename
, int format
, int private)
2510 int fd
= -1, bflags
, mode
, textmode
;
2512 if (!private || filename
== NULL
|| strcmp(filename
, "-") == 0)
2513 return bio_open_default(filename
, 'w', format
);
2522 textmode
= FMT_istext(format
);
2526 #elif defined(_O_BINARY)
2531 #ifdef OPENSSL_SYS_VMS
2532 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2533 * it still needs to know that we're going binary, or fdopen()
2534 * will fail with "invalid argument"... so we tell VMS what the
2538 fd
= open(filename
, mode
, 0600, "ctx=bin");
2541 fd
= open(filename
, mode
, 0600);
2544 fp
= fdopen(fd
, modestr('w', format
));
2549 bflags
|= BIO_FP_TEXT
;
2550 b
= BIO_new_fp(fp
, bflags
);
2555 BIO_printf(bio_err
, "%s: Can't open \"%s\" for writing, %s\n",
2556 opt_getprog(), filename
, strerror(errno
));
2557 ERR_print_errors(bio_err
);
2558 /* If we have fp, then fdopen took over fd, so don't close both. */
2566 static BIO
*bio_open_default_(const char *filename
, char mode
, int format
,
2571 if (filename
== NULL
|| strcmp(filename
, "-") == 0) {
2572 ret
= mode
== 'r' ? dup_bio_in(format
) : dup_bio_out(format
);
2580 "Can't open %s, %s\n",
2581 mode
== 'r' ? "stdin" : "stdout", strerror(errno
));
2583 ret
= BIO_new_file(filename
, modestr(mode
, format
));
2591 "Can't open %s for %s, %s\n",
2592 filename
, modeverb(mode
), strerror(errno
));
2594 ERR_print_errors(bio_err
);
2598 BIO
*bio_open_default(const char *filename
, char mode
, int format
)
2600 return bio_open_default_(filename
, mode
, format
, 0);
2603 BIO
*bio_open_default_quiet(const char *filename
, char mode
, int format
)
2605 return bio_open_default_(filename
, mode
, format
, 1);
2608 void wait_for_async(SSL
*s
)
2610 /* On Windows select only works for sockets, so we simply don't wait */
2611 #ifndef OPENSSL_SYS_WINDOWS
2618 if (!SSL_get_all_async_fds(s
, NULL
, &numfds
))
2622 fds
= app_malloc(sizeof(OSSL_ASYNC_FD
) * numfds
, "allocate async fds");
2623 if (!SSL_get_all_async_fds(s
, fds
, &numfds
)) {
2629 for (i
= 0; i
< numfds
; i
++) {
2630 if (width
<= (int)fds
[i
])
2631 width
= (int)fds
[i
] + 1;
2632 openssl_fdset((int)fds
[i
], &asyncfds
);
2634 select(width
, (void *)&asyncfds
, NULL
, NULL
, NULL
);
2639 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2640 #if defined(OPENSSL_SYS_MSDOS)
2641 int has_stdin_waiting(void)
2643 # if defined(OPENSSL_SYS_WINDOWS)
2644 HANDLE inhand
= GetStdHandle(STD_INPUT_HANDLE
);
2646 INPUT_RECORD inputrec
;
2650 if (inhand
== INVALID_HANDLE_VALUE
) {
2654 peeked
= PeekConsoleInput(inhand
, &inputrec
, insize
, &events
);
2656 /* Probably redirected input? _kbhit() does not work in this case */
2667 /* Corrupt a signature by modifying final byte */
2668 void corrupt_signature(const ASN1_STRING
*signature
)
2670 unsigned char *s
= signature
->data
;
2671 s
[signature
->length
- 1] ^= 0x1;
2674 int set_cert_times(X509
*x
, const char *startdate
, const char *enddate
,
2677 if (startdate
== NULL
|| strcmp(startdate
, "today") == 0) {
2678 if (X509_gmtime_adj(X509_getm_notBefore(x
), 0) == NULL
)
2681 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x
), startdate
))
2684 if (enddate
== NULL
) {
2685 if (X509_time_adj_ex(X509_getm_notAfter(x
), days
, 0, NULL
)
2688 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x
), enddate
)) {
2694 int set_crl_lastupdate(X509_CRL
*crl
, const char *lastupdate
)
2697 ASN1_TIME
*tm
= ASN1_TIME_new();
2702 if (lastupdate
== NULL
) {
2703 if (X509_gmtime_adj(tm
, 0) == NULL
)
2706 if (!ASN1_TIME_set_string_X509(tm
, lastupdate
))
2710 if (!X509_CRL_set1_lastUpdate(crl
, tm
))
2719 int set_crl_nextupdate(X509_CRL
*crl
, const char *nextupdate
,
2720 long days
, long hours
, long secs
)
2723 ASN1_TIME
*tm
= ASN1_TIME_new();
2728 if (nextupdate
== NULL
) {
2729 if (X509_time_adj_ex(tm
, days
, hours
* 60 * 60 + secs
, NULL
) == NULL
)
2732 if (!ASN1_TIME_set_string_X509(tm
, nextupdate
))
2736 if (!X509_CRL_set1_nextUpdate(crl
, tm
))
2745 void make_uppercase(char *string
)
2749 for (i
= 0; string
[i
] != '\0'; i
++)
2750 string
[i
] = toupper((unsigned char)string
[i
]);
2753 int opt_printf_stderr(const char *fmt
, ...)
2759 ret
= BIO_vprintf(bio_err
, fmt
, ap
);
2764 OSSL_PARAM
*app_params_new_from_opts(STACK_OF(OPENSSL_STRING
) *opts
,
2765 const OSSL_PARAM
*paramdefs
)
2767 OSSL_PARAM
*params
= NULL
;
2768 size_t sz
= (size_t)sk_OPENSSL_STRING_num(opts
);
2770 char *opt
= "", *stmp
, *vtmp
= NULL
;
2776 params
= OPENSSL_zalloc(sizeof(OSSL_PARAM
) * (sz
+ 1));
2780 for (params_n
= 0; params_n
< sz
; params_n
++) {
2781 opt
= sk_OPENSSL_STRING_value(opts
, (int)params_n
);
2782 if ((stmp
= OPENSSL_strdup(opt
)) == NULL
2783 || (vtmp
= strchr(stmp
, ':')) == NULL
)
2785 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2787 /* Skip over the separator so that vmtp points to the value */
2789 if (!OSSL_PARAM_allocate_from_text(¶ms
[params_n
], paramdefs
,
2790 stmp
, vtmp
, strlen(vtmp
), &found
))
2794 params
[params_n
] = OSSL_PARAM_construct_end();
2798 BIO_printf(bio_err
, "Parameter %s '%s'\n", found
? "error" : "unknown",
2800 ERR_print_errors(bio_err
);
2801 app_params_free(params
);
2805 void app_params_free(OSSL_PARAM
*params
)
2809 if (params
!= NULL
) {
2810 for (i
= 0; params
[i
].key
!= NULL
; ++i
)
2811 OPENSSL_free(params
[i
].data
);
2812 OPENSSL_free(params
);