2 * Copyright 1995-2021 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 #include <openssl/rsa.h>
38 #include <openssl/bn.h>
39 #include <openssl/ssl.h>
40 #include <openssl/store.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 static BIO
*bio_open_default_(const char *filename
, char mode
, int format
,
60 #define PASS_SOURCE_SIZE_MAX 4
70 static OSSL_LIB_CTX
*app_libctx
= NULL
;
72 static int set_table_opts(unsigned long *flags
, const char *arg
,
73 const NAME_EX_TBL
* in_tbl
);
74 static int set_multi_opts(unsigned long *flags
, const char *arg
,
75 const NAME_EX_TBL
* in_tbl
);
77 int app_init(long mesgwin
);
79 int chopup_args(ARGS
*arg
, char *buf
)
82 char c
= '\0', *p
= NULL
;
87 arg
->argv
= app_malloc(sizeof(*arg
->argv
) * arg
->size
, "argv space");
91 /* Skip whitespace. */
92 while (*p
&& isspace(_UC(*p
)))
97 /* The start of something good :-) */
98 if (arg
->argc
>= arg
->size
) {
101 tmp
= OPENSSL_realloc(arg
->argv
, sizeof(*arg
->argv
) * arg
->size
);
106 quoted
= *p
== '\'' || *p
== '"';
109 arg
->argv
[arg
->argc
++] = p
;
111 /* now look for the end of this */
113 while (*p
&& *p
!= c
)
117 while (*p
&& !isspace(_UC(*p
)))
123 arg
->argv
[arg
->argc
] = NULL
;
128 int app_init(long mesgwin
)
134 int ctx_set_verify_locations(SSL_CTX
*ctx
,
135 const char *CAfile
, int noCAfile
,
136 const char *CApath
, int noCApath
,
137 const char *CAstore
, int noCAstore
)
139 if (CAfile
== NULL
&& CApath
== NULL
&& CAstore
== NULL
) {
140 if (!noCAfile
&& SSL_CTX_set_default_verify_file(ctx
) <= 0)
142 if (!noCApath
&& SSL_CTX_set_default_verify_dir(ctx
) <= 0)
144 if (!noCAstore
&& SSL_CTX_set_default_verify_store(ctx
) <= 0)
150 if (CAfile
!= NULL
&& !SSL_CTX_load_verify_file(ctx
, CAfile
))
152 if (CApath
!= NULL
&& !SSL_CTX_load_verify_dir(ctx
, CApath
))
154 if (CAstore
!= NULL
&& !SSL_CTX_load_verify_store(ctx
, CAstore
))
159 #ifndef OPENSSL_NO_CT
161 int ctx_set_ctlog_list_file(SSL_CTX
*ctx
, const char *path
)
164 return SSL_CTX_set_default_ctlog_list_file(ctx
);
166 return SSL_CTX_set_ctlog_list_file(ctx
, path
);
171 static unsigned long nmflag
= 0;
172 static char nmflag_set
= 0;
174 int set_nameopt(const char *arg
)
176 int ret
= set_name_ex(&nmflag
, arg
);
184 unsigned long get_nameopt(void)
186 return (nmflag_set
) ? nmflag
: XN_FLAG_ONELINE
;
189 int dump_cert_text(BIO
*out
, X509
*x
)
191 print_name(out
, "subject=", X509_get_subject_name(x
), get_nameopt());
193 print_name(out
, "issuer=", X509_get_issuer_name(x
), get_nameopt());
199 int wrap_password_callback(char *buf
, int bufsiz
, int verify
, void *userdata
)
201 return password_callback(buf
, bufsiz
, verify
, (PW_CB_DATA
*)userdata
);
205 static char *app_get_pass(const char *arg
, int keepbio
);
207 char *get_passwd(const char *pass
, const char *desc
)
213 if (!app_passwd(pass
, NULL
, &result
, NULL
))
214 BIO_printf(bio_err
, "Error getting password for %s\n", desc
);
215 if (pass
!= NULL
&& result
== NULL
) {
217 "Trying plain input string (better precede with 'pass:')\n");
218 result
= OPENSSL_strdup(pass
);
220 BIO_printf(bio_err
, "Out of memory getting password for %s\n", desc
);
225 int app_passwd(const char *arg1
, const char *arg2
, char **pass1
, char **pass2
)
227 int same
= arg1
!= NULL
&& arg2
!= NULL
&& strcmp(arg1
, arg2
) == 0;
230 *pass1
= app_get_pass(arg1
, same
);
233 } else if (pass1
!= NULL
) {
237 *pass2
= app_get_pass(arg2
, same
? 2 : 0);
240 } else if (pass2
!= NULL
) {
246 static char *app_get_pass(const char *arg
, int keepbio
)
248 static BIO
*pwdbio
= NULL
;
249 char *tmp
, tpass
[APP_PASS_LEN
];
252 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
253 if (strncmp(arg
, "pass:", 5) == 0)
254 return OPENSSL_strdup(arg
+ 5);
255 if (strncmp(arg
, "env:", 4) == 0) {
256 tmp
= getenv(arg
+ 4);
258 BIO_printf(bio_err
, "No environment variable %s\n", arg
+ 4);
261 return OPENSSL_strdup(tmp
);
263 if (!keepbio
|| pwdbio
== NULL
) {
264 if (strncmp(arg
, "file:", 5) == 0) {
265 pwdbio
= BIO_new_file(arg
+ 5, "r");
266 if (pwdbio
== NULL
) {
267 BIO_printf(bio_err
, "Can't open file %s\n", arg
+ 5);
272 * Under _WIN32, which covers even Win64 and CE, file
273 * descriptors referenced by BIO_s_fd are not inherited
274 * by child process and therefore below is not an option.
275 * It could have been an option if bss_fd.c was operating
276 * on real Windows descriptors, such as those obtained
279 } else if (strncmp(arg
, "fd:", 3) == 0) {
283 pwdbio
= BIO_new_fd(i
, BIO_NOCLOSE
);
284 if ((i
< 0) || !pwdbio
) {
285 BIO_printf(bio_err
, "Can't access file descriptor %s\n", arg
+ 3);
289 * Can't do BIO_gets on an fd BIO so add a buffering BIO
291 btmp
= BIO_new(BIO_f_buffer());
292 pwdbio
= BIO_push(btmp
, pwdbio
);
294 } else if (strcmp(arg
, "stdin") == 0) {
295 pwdbio
= dup_bio_in(FORMAT_TEXT
);
296 if (pwdbio
== NULL
) {
297 BIO_printf(bio_err
, "Can't open BIO for stdin\n");
301 /* argument syntax error; do not reveal too much about arg */
302 tmp
= strchr(arg
, ':');
303 if (tmp
== NULL
|| tmp
- arg
> PASS_SOURCE_SIZE_MAX
)
305 "Invalid password argument, missing ':' within the first %d chars\n",
306 PASS_SOURCE_SIZE_MAX
+ 1);
309 "Invalid password argument, starting with \"%.*s\"\n",
310 (int)(tmp
- arg
+ 1), arg
);
314 i
= BIO_gets(pwdbio
, tpass
, APP_PASS_LEN
);
316 BIO_free_all(pwdbio
);
320 BIO_printf(bio_err
, "Error reading password from BIO\n");
323 tmp
= strchr(tpass
, '\n');
326 return OPENSSL_strdup(tpass
);
329 OSSL_LIB_CTX
*app_get0_libctx(void)
334 /* TODO(3.0): Make this an environment variable if required */
335 const char *app_get0_propq(void)
340 OSSL_LIB_CTX
*app_create_libctx(void)
343 * Load the NULL provider into the default library context and create a
344 * library context which will then be used for any OPT_PROV options.
346 if (app_libctx
== NULL
) {
348 if (!app_provider_load(NULL
, "null")) {
349 BIO_puts(bio_err
, "Failed to create null provider\n");
352 app_libctx
= OSSL_LIB_CTX_new();
354 if (app_libctx
== NULL
)
355 BIO_puts(bio_err
, "Failed to create library context\n");
359 CONF
*app_load_config_bio(BIO
*in
, const char *filename
)
365 conf
= NCONF_new_ex(app_libctx
, NULL
);
366 i
= NCONF_load_bio(conf
, in
, &errorline
);
370 if (errorline
<= 0) {
371 BIO_printf(bio_err
, "%s: Can't load ", opt_getprog());
373 BIO_printf(bio_err
, "%s: Error on line %ld of ", opt_getprog(),
376 if (filename
!= NULL
)
377 BIO_printf(bio_err
, "config file \"%s\"\n", filename
);
379 BIO_printf(bio_err
, "config input");
385 CONF
*app_load_config_verbose(const char *filename
, int verbose
)
388 if (*filename
== '\0')
389 BIO_printf(bio_err
, "No configuration used\n");
391 BIO_printf(bio_err
, "Using configuration from %s\n", filename
);
393 return app_load_config_internal(filename
, 0);
396 CONF
*app_load_config_internal(const char *filename
, int quiet
)
398 BIO
*in
= NULL
; /* leads to empty config in case filename == "" */
401 if (*filename
!= '\0'
402 && (in
= bio_open_default_(filename
, 'r', FORMAT_TEXT
, quiet
)) == NULL
)
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 if ((conf
= app_load_config_verbose(configfile
, 1)) == NULL
)
461 if (configfile
!= default_config_file
&& !app_load_modules(conf
)) {
469 #define IS_HTTP(uri) ((uri) != NULL \
470 && strncmp(uri, OSSL_HTTP_PREFIX, strlen(OSSL_HTTP_PREFIX)) == 0)
471 #define IS_HTTPS(uri) ((uri) != NULL \
472 && strncmp(uri, OSSL_HTTPS_PREFIX, strlen(OSSL_HTTPS_PREFIX)) == 0)
474 X509
*load_cert_pass(const char *uri
, int maybe_stdin
,
475 const char *pass
, const char *desc
)
480 desc
= "certificate";
482 BIO_printf(bio_err
, "Loading %s over HTTPS is unsupported\n", desc
);
483 else if (IS_HTTP(uri
))
484 cert
= X509_load_http(uri
, NULL
, NULL
, 0 /* timeout */);
486 (void)load_key_certs_crls(uri
, maybe_stdin
, pass
, desc
,
487 NULL
, NULL
, NULL
, &cert
, NULL
, NULL
, NULL
);
489 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
490 ERR_print_errors(bio_err
);
495 X509_CRL
*load_crl(const char *uri
, const char *desc
)
497 X509_CRL
*crl
= NULL
;
502 BIO_printf(bio_err
, "Loading %s over HTTPS is unsupported\n", desc
);
503 else if (IS_HTTP(uri
))
504 crl
= X509_CRL_load_http(uri
, NULL
, NULL
, 0 /* timeout */);
506 (void)load_key_certs_crls(uri
, 0, NULL
, desc
,
507 NULL
, NULL
, NULL
, NULL
, NULL
, &crl
, NULL
);
509 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
510 ERR_print_errors(bio_err
);
515 X509_REQ
*load_csr(const char *file
, int format
, const char *desc
)
517 X509_REQ
*req
= NULL
;
522 in
= bio_open_default(file
, 'r', format
);
526 if (format
== FORMAT_ASN1
)
527 req
= d2i_X509_REQ_bio(in
, NULL
);
528 else if (format
== FORMAT_PEM
)
529 req
= PEM_read_bio_X509_REQ(in
, NULL
, NULL
, NULL
);
531 print_format_error(format
, OPT_FMT_PEMDER
);
535 BIO_printf(bio_err
, "Unable to load %s\n", desc
);
536 ERR_print_errors(bio_err
);
542 void cleanse(char *str
)
545 OPENSSL_cleanse(str
, strlen(str
));
548 void clear_free(char *str
)
551 OPENSSL_clear_free(str
, strlen(str
));
554 EVP_PKEY
*load_key(const char *uri
, int format
, int may_stdin
,
555 const char *pass
, ENGINE
*e
, const char *desc
)
557 EVP_PKEY
*pkey
= NULL
;
558 char *allocated_uri
= NULL
;
561 desc
= "private key";
563 if (format
== FORMAT_ENGINE
) {
564 uri
= allocated_uri
= make_engine_uri(e
, uri
, desc
);
566 (void)load_key_certs_crls(uri
, may_stdin
, pass
, desc
,
567 &pkey
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
);
569 OPENSSL_free(allocated_uri
);
573 EVP_PKEY
*load_pubkey(const char *uri
, int format
, int maybe_stdin
,
574 const char *pass
, ENGINE
*e
, const char *desc
)
576 EVP_PKEY
*pkey
= NULL
;
577 char *allocated_uri
= NULL
;
582 if (format
== FORMAT_ENGINE
) {
583 uri
= allocated_uri
= make_engine_uri(e
, uri
, desc
);
585 (void)load_key_certs_crls(uri
, maybe_stdin
, pass
, desc
,
586 NULL
, &pkey
, NULL
, NULL
, NULL
, NULL
, NULL
);
588 OPENSSL_free(allocated_uri
);
592 EVP_PKEY
*load_keyparams(const char *uri
, int maybe_stdin
, const char *keytype
,
595 EVP_PKEY
*params
= NULL
;
598 desc
= "key parameters";
600 (void)load_key_certs_crls(uri
, maybe_stdin
, NULL
, desc
,
601 NULL
, NULL
, ¶ms
, NULL
, NULL
, NULL
, NULL
);
602 if (params
!= NULL
&& keytype
!= NULL
&& !EVP_PKEY_is_a(params
, keytype
)) {
604 "Unable to load %s from %s (unexpected parameters type)\n",
606 ERR_print_errors(bio_err
);
607 EVP_PKEY_free(params
);
613 void app_bail_out(char *fmt
, ...)
618 BIO_vprintf(bio_err
, fmt
, args
);
620 ERR_print_errors(bio_err
);
624 void* app_malloc(int sz
, const char *what
)
626 void *vp
= OPENSSL_malloc(sz
);
629 app_bail_out("%s: Could not allocate %d bytes for %s\n",
630 opt_getprog(), sz
, what
);
635 * Initialize or extend, if *certs != NULL, a certificate stack.
636 * The caller is responsible for freeing *certs if its value is left not NULL.
638 int load_certs(const char *uri
, STACK_OF(X509
) **certs
,
639 const char *pass
, const char *desc
)
641 int was_NULL
= *certs
== NULL
;
642 int ret
= load_key_certs_crls(uri
, 0, pass
, desc
, NULL
, NULL
, NULL
,
643 NULL
, certs
, NULL
, NULL
);
645 if (!ret
&& was_NULL
) {
646 sk_X509_pop_free(*certs
, X509_free
);
653 * Initialize or extend, if *crls != NULL, a certificate stack.
654 * The caller is responsible for freeing *crls if its value is left not NULL.
656 int load_crls(const char *uri
, STACK_OF(X509_CRL
) **crls
,
657 const char *pass
, const char *desc
)
659 int was_NULL
= *crls
== NULL
;
660 int ret
= load_key_certs_crls(uri
, 0, pass
, desc
, NULL
, NULL
, NULL
,
661 NULL
, NULL
, NULL
, crls
);
663 if (!ret
&& was_NULL
) {
664 sk_X509_CRL_pop_free(*crls
, X509_CRL_free
);
671 * Load those types of credentials for which the result pointer is not NULL.
672 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
673 * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
674 * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
675 * If pcerts is non-NULL then all available certificates are appended to *pcerts
676 * except any certificate assigned to *pcert.
677 * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
678 * If pcrls is non-NULL then all available CRLs are appended to *pcerts
679 * except any CRL assigned to *pcrl.
680 * In any case (also on error) the caller is responsible for freeing all members
681 * of *pcerts and *pcrls (as far as they are not NULL).
683 int load_key_certs_crls(const char *uri
, int maybe_stdin
,
684 const char *pass
, const char *desc
,
685 EVP_PKEY
**ppkey
, EVP_PKEY
**ppubkey
,
687 X509
**pcert
, STACK_OF(X509
) **pcerts
,
688 X509_CRL
**pcrl
, STACK_OF(X509_CRL
) **pcrls
)
691 OSSL_STORE_CTX
*ctx
= NULL
;
692 OSSL_LIB_CTX
*libctx
= app_get0_libctx();
693 const char *propq
= app_get0_propq();
697 ppkey
!= NULL
? "key" : ppubkey
!= NULL
? "public key" :
698 pparams
!= NULL
? "params" : pcert
!= NULL
? "cert" :
699 pcrl
!= NULL
? "CRL" : pcerts
!= NULL
? "certs" :
700 pcrls
!= NULL
? "CRLs" : NULL
;
701 int cnt_expectations
= 0;
703 /* TODO make use of the engine reference 'eng' when loading pkeys */
708 expect
= OSSL_STORE_INFO_PKEY
;
710 if (ppubkey
!= NULL
) {
713 expect
= OSSL_STORE_INFO_PUBKEY
;
718 expect
= OSSL_STORE_INFO_CERT
;
720 if (failed
== NULL
) {
721 BIO_printf(bio_err
, "Internal error: nothing to load into from %s\n",
722 uri
!= NULL
? uri
: "<stdin>");
726 if (pcerts
!= NULL
&& *pcerts
== NULL
727 && (*pcerts
= sk_X509_new_null()) == NULL
) {
728 BIO_printf(bio_err
, "Out of memory loading");
732 expect
= OSSL_STORE_INFO_CERT
;
737 expect
= OSSL_STORE_INFO_CRL
;
739 if (pcrls
!= NULL
&& *pcrls
== NULL
740 && (*pcrls
= sk_X509_CRL_new_null()) == NULL
) {
741 BIO_printf(bio_err
, "Out of memory loading");
745 expect
= OSSL_STORE_INFO_CRL
;
748 uidata
.password
= pass
;
749 uidata
.prompt_info
= uri
;
755 BIO_printf(bio_err
, "No filename or uri specified for loading");
760 bio
= BIO_new_fp(stdin
, 0);
762 ctx
= OSSL_STORE_attach(bio
, "file", libctx
, propq
,
763 get_ui_method(), &uidata
, NULL
, NULL
);
765 ctx
= OSSL_STORE_open_ex(uri
, libctx
, propq
, get_ui_method(), &uidata
,
769 BIO_printf(bio_err
, "Could not open file or uri for loading");
773 if (cnt_expectations
!= 1)
775 if (!OSSL_STORE_expect(ctx
, expect
))
779 while (!OSSL_STORE_eof(ctx
)) {
780 OSSL_STORE_INFO
*info
= OSSL_STORE_load(ctx
);
785 type
= OSSL_STORE_INFO_get_type(info
);
787 case OSSL_STORE_INFO_PKEY
:
788 if (ppkey
!= NULL
&& *ppkey
== NULL
)
789 ok
= (*ppkey
= OSSL_STORE_INFO_get1_PKEY(info
)) != NULL
;
792 * An EVP_PKEY with private parts also holds the public parts,
793 * so if the caller asked for a public key, and we got a private
794 * key, we can still pass it back.
796 if (ok
&& ppubkey
!= NULL
&& *ppubkey
== NULL
)
797 ok
= ((*ppubkey
= OSSL_STORE_INFO_get1_PKEY(info
)) != NULL
);
799 case OSSL_STORE_INFO_PUBKEY
:
800 if (ppubkey
!= NULL
&& *ppubkey
== NULL
)
801 ok
= ((*ppubkey
= OSSL_STORE_INFO_get1_PUBKEY(info
)) != NULL
);
803 case OSSL_STORE_INFO_PARAMS
:
804 if (pparams
!= NULL
&& *pparams
== NULL
)
805 ok
= ((*pparams
= OSSL_STORE_INFO_get1_PARAMS(info
)) != NULL
);
807 case OSSL_STORE_INFO_CERT
:
808 if (pcert
!= NULL
&& *pcert
== NULL
)
809 ok
= (*pcert
= OSSL_STORE_INFO_get1_CERT(info
)) != NULL
;
810 else if (pcerts
!= NULL
)
811 ok
= X509_add_cert(*pcerts
,
812 OSSL_STORE_INFO_get1_CERT(info
),
813 X509_ADD_FLAG_DEFAULT
);
816 case OSSL_STORE_INFO_CRL
:
817 if (pcrl
!= NULL
&& *pcrl
== NULL
)
818 ok
= (*pcrl
= OSSL_STORE_INFO_get1_CRL(info
)) != NULL
;
819 else if (pcrls
!= NULL
)
820 ok
= sk_X509_CRL_push(*pcrls
, OSSL_STORE_INFO_get1_CRL(info
));
824 /* skip any other type */
827 OSSL_STORE_INFO_free(info
);
829 failed
= info
== NULL
? NULL
: OSSL_STORE_INFO_type_string(type
);
830 BIO_printf(bio_err
, "Error reading");
836 OSSL_STORE_close(ctx
);
837 if (failed
== NULL
) {
840 if ((ppkey
!= NULL
&& *ppkey
== NULL
)
841 || (ppubkey
!= NULL
&& *ppubkey
== NULL
)) {
843 } else if (pparams
!= NULL
&& *pparams
== NULL
) {
845 } else if ((pcert
!= NULL
|| pcerts
!= NULL
) && ncerts
== 0) {
849 } else if ((pcrl
!= NULL
|| pcrls
!= NULL
) && ncrls
== 0) {
855 BIO_printf(bio_err
, "Could not read");
857 BIO_printf(bio_err
, " any");
859 if (failed
!= NULL
) {
860 if (desc
!= NULL
&& strstr(desc
, failed
) != NULL
) {
861 BIO_printf(bio_err
, " %s", desc
);
863 BIO_printf(bio_err
, " %s", failed
);
865 BIO_printf(bio_err
, " of %s", desc
);
868 BIO_printf(bio_err
, " from %s", uri
);
869 BIO_printf(bio_err
, "\n");
870 ERR_print_errors(bio_err
);
872 return failed
== NULL
;
876 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
877 /* Return error for unknown extensions */
878 #define X509V3_EXT_DEFAULT 0
879 /* Print error for unknown extensions */
880 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
881 /* ASN1 parse unknown extensions */
882 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
883 /* BIO_dump unknown extensions */
884 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
886 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
887 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
889 int set_cert_ex(unsigned long *flags
, const char *arg
)
891 static const NAME_EX_TBL cert_tbl
[] = {
892 {"compatible", X509_FLAG_COMPAT
, 0xffffffffl
},
893 {"ca_default", X509_FLAG_CA
, 0xffffffffl
},
894 {"no_header", X509_FLAG_NO_HEADER
, 0},
895 {"no_version", X509_FLAG_NO_VERSION
, 0},
896 {"no_serial", X509_FLAG_NO_SERIAL
, 0},
897 {"no_signame", X509_FLAG_NO_SIGNAME
, 0},
898 {"no_validity", X509_FLAG_NO_VALIDITY
, 0},
899 {"no_subject", X509_FLAG_NO_SUBJECT
, 0},
900 {"no_issuer", X509_FLAG_NO_ISSUER
, 0},
901 {"no_pubkey", X509_FLAG_NO_PUBKEY
, 0},
902 {"no_extensions", X509_FLAG_NO_EXTENSIONS
, 0},
903 {"no_sigdump", X509_FLAG_NO_SIGDUMP
, 0},
904 {"no_aux", X509_FLAG_NO_AUX
, 0},
905 {"no_attributes", X509_FLAG_NO_ATTRIBUTES
, 0},
906 {"ext_default", X509V3_EXT_DEFAULT
, X509V3_EXT_UNKNOWN_MASK
},
907 {"ext_error", X509V3_EXT_ERROR_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
908 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
909 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN
, X509V3_EXT_UNKNOWN_MASK
},
912 return set_multi_opts(flags
, arg
, cert_tbl
);
915 int set_name_ex(unsigned long *flags
, const char *arg
)
917 static const NAME_EX_TBL ex_tbl
[] = {
918 {"esc_2253", ASN1_STRFLGS_ESC_2253
, 0},
919 {"esc_2254", ASN1_STRFLGS_ESC_2254
, 0},
920 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL
, 0},
921 {"esc_msb", ASN1_STRFLGS_ESC_MSB
, 0},
922 {"use_quote", ASN1_STRFLGS_ESC_QUOTE
, 0},
923 {"utf8", ASN1_STRFLGS_UTF8_CONVERT
, 0},
924 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE
, 0},
925 {"show_type", ASN1_STRFLGS_SHOW_TYPE
, 0},
926 {"dump_all", ASN1_STRFLGS_DUMP_ALL
, 0},
927 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN
, 0},
928 {"dump_der", ASN1_STRFLGS_DUMP_DER
, 0},
929 {"compat", XN_FLAG_COMPAT
, 0xffffffffL
},
930 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS
, XN_FLAG_SEP_MASK
},
931 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC
, XN_FLAG_SEP_MASK
},
932 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC
, XN_FLAG_SEP_MASK
},
933 {"sep_multiline", XN_FLAG_SEP_MULTILINE
, XN_FLAG_SEP_MASK
},
934 {"dn_rev", XN_FLAG_DN_REV
, 0},
935 {"nofname", XN_FLAG_FN_NONE
, XN_FLAG_FN_MASK
},
936 {"sname", XN_FLAG_FN_SN
, XN_FLAG_FN_MASK
},
937 {"lname", XN_FLAG_FN_LN
, XN_FLAG_FN_MASK
},
938 {"align", XN_FLAG_FN_ALIGN
, 0},
939 {"oid", XN_FLAG_FN_OID
, XN_FLAG_FN_MASK
},
940 {"space_eq", XN_FLAG_SPC_EQ
, 0},
941 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS
, 0},
942 {"RFC2253", XN_FLAG_RFC2253
, 0xffffffffL
},
943 {"oneline", XN_FLAG_ONELINE
, 0xffffffffL
},
944 {"multiline", XN_FLAG_MULTILINE
, 0xffffffffL
},
945 {"ca_default", XN_FLAG_MULTILINE
, 0xffffffffL
},
948 if (set_multi_opts(flags
, arg
, ex_tbl
) == 0)
950 if (*flags
!= XN_FLAG_COMPAT
951 && (*flags
& XN_FLAG_SEP_MASK
) == 0)
952 *flags
|= XN_FLAG_SEP_CPLUS_SPC
;
956 int set_ext_copy(int *copy_type
, const char *arg
)
958 if (strcasecmp(arg
, "none") == 0)
959 *copy_type
= EXT_COPY_NONE
;
960 else if (strcasecmp(arg
, "copy") == 0)
961 *copy_type
= EXT_COPY_ADD
;
962 else if (strcasecmp(arg
, "copyall") == 0)
963 *copy_type
= EXT_COPY_ALL
;
969 int copy_extensions(X509
*x
, X509_REQ
*req
, int copy_type
)
971 STACK_OF(X509_EXTENSION
) *exts
;
974 if (x
== NULL
|| req
== NULL
)
976 if (copy_type
== EXT_COPY_NONE
)
978 exts
= X509_REQ_get_extensions(req
);
980 for (i
= 0; i
< sk_X509_EXTENSION_num(exts
); i
++) {
981 X509_EXTENSION
*ext
= sk_X509_EXTENSION_value(exts
, i
);
982 ASN1_OBJECT
*obj
= X509_EXTENSION_get_object(ext
);
983 int idx
= X509_get_ext_by_OBJ(x
, obj
, -1);
985 /* Does extension exist in target? */
987 /* If normal copy don't override existing extension */
988 if (copy_type
== EXT_COPY_ADD
)
990 /* Delete all extensions of same type */
992 X509_EXTENSION_free(X509_delete_ext(x
, idx
));
993 idx
= X509_get_ext_by_OBJ(x
, obj
, -1);
996 if (!X509_add_ext(x
, ext
, -1))
1002 sk_X509_EXTENSION_pop_free(exts
, X509_EXTENSION_free
);
1006 static int set_multi_opts(unsigned long *flags
, const char *arg
,
1007 const NAME_EX_TBL
* in_tbl
)
1009 STACK_OF(CONF_VALUE
) *vals
;
1014 vals
= X509V3_parse_list(arg
);
1015 for (i
= 0; i
< sk_CONF_VALUE_num(vals
); i
++) {
1016 val
= sk_CONF_VALUE_value(vals
, i
);
1017 if (!set_table_opts(flags
, val
->name
, in_tbl
))
1020 sk_CONF_VALUE_pop_free(vals
, X509V3_conf_free
);
1024 static int set_table_opts(unsigned long *flags
, const char *arg
,
1025 const NAME_EX_TBL
* in_tbl
)
1028 const NAME_EX_TBL
*ptbl
;
1034 } else if (c
== '+') {
1041 for (ptbl
= in_tbl
; ptbl
->name
; ptbl
++) {
1042 if (strcasecmp(arg
, ptbl
->name
) == 0) {
1043 *flags
&= ~ptbl
->mask
;
1045 *flags
|= ptbl
->flag
;
1047 *flags
&= ~ptbl
->flag
;
1054 void print_name(BIO
*out
, const char *title
, const X509_NAME
*nm
,
1055 unsigned long lflags
)
1062 BIO_puts(out
, title
);
1063 if ((lflags
& XN_FLAG_SEP_MASK
) == XN_FLAG_SEP_MULTILINE
) {
1067 if (lflags
== XN_FLAG_COMPAT
) {
1068 buf
= X509_NAME_oneline(nm
, 0, 0);
1070 BIO_puts(out
, "\n");
1074 BIO_puts(out
, "\n");
1075 X509_NAME_print_ex(out
, nm
, indent
, lflags
);
1076 BIO_puts(out
, "\n");
1080 void print_bignum_var(BIO
*out
, const BIGNUM
*in
, const char *var
,
1081 int len
, unsigned char *buffer
)
1083 BIO_printf(out
, " static unsigned char %s_%d[] = {", var
, len
);
1084 if (BN_is_zero(in
)) {
1085 BIO_printf(out
, "\n 0x00");
1089 l
= BN_bn2bin(in
, buffer
);
1090 for (i
= 0; i
< l
; i
++) {
1091 BIO_printf(out
, (i
% 10) == 0 ? "\n " : " ");
1093 BIO_printf(out
, "0x%02X,", buffer
[i
]);
1095 BIO_printf(out
, "0x%02X", buffer
[i
]);
1098 BIO_printf(out
, "\n };\n");
1101 void print_array(BIO
*out
, const char* title
, int len
, const unsigned char* d
)
1105 BIO_printf(out
, "unsigned char %s[%d] = {", title
, len
);
1106 for (i
= 0; i
< len
; i
++) {
1108 BIO_printf(out
, "\n ");
1110 BIO_printf(out
, "0x%02X, ", d
[i
]);
1112 BIO_printf(out
, "0x%02X", d
[i
]);
1114 BIO_printf(out
, "\n};\n");
1117 X509_STORE
*setup_verify(const char *CAfile
, int noCAfile
,
1118 const char *CApath
, int noCApath
,
1119 const char *CAstore
, int noCAstore
)
1121 X509_STORE
*store
= X509_STORE_new();
1122 X509_LOOKUP
*lookup
;
1123 OSSL_LIB_CTX
*libctx
= app_get0_libctx();
1124 const char *propq
= app_get0_propq();
1129 if (CAfile
!= NULL
|| !noCAfile
) {
1130 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_file());
1133 if (CAfile
!= NULL
) {
1134 if (!X509_LOOKUP_load_file_ex(lookup
, CAfile
, X509_FILETYPE_PEM
,
1136 BIO_printf(bio_err
, "Error loading file %s\n", CAfile
);
1140 X509_LOOKUP_load_file_ex(lookup
, NULL
, X509_FILETYPE_DEFAULT
,
1145 if (CApath
!= NULL
|| !noCApath
) {
1146 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_hash_dir());
1149 if (CApath
!= NULL
) {
1150 if (!X509_LOOKUP_add_dir(lookup
, CApath
, X509_FILETYPE_PEM
)) {
1151 BIO_printf(bio_err
, "Error loading directory %s\n", CApath
);
1155 X509_LOOKUP_add_dir(lookup
, NULL
, X509_FILETYPE_DEFAULT
);
1159 if (CAstore
!= NULL
|| !noCAstore
) {
1160 lookup
= X509_STORE_add_lookup(store
, X509_LOOKUP_store());
1163 if (!X509_LOOKUP_add_store_ex(lookup
, CAstore
, libctx
, propq
)) {
1164 if (CAstore
!= NULL
)
1165 BIO_printf(bio_err
, "Error loading store URI %s\n", CAstore
);
1173 ERR_print_errors(bio_err
);
1174 X509_STORE_free(store
);
1178 static unsigned long index_serial_hash(const OPENSSL_CSTRING
*a
)
1185 return OPENSSL_LH_strhash(n
);
1188 static int index_serial_cmp(const OPENSSL_CSTRING
*a
,
1189 const OPENSSL_CSTRING
*b
)
1191 const char *aa
, *bb
;
1193 for (aa
= a
[DB_serial
]; *aa
== '0'; aa
++) ;
1194 for (bb
= b
[DB_serial
]; *bb
== '0'; bb
++) ;
1195 return strcmp(aa
, bb
);
1198 static int index_name_qual(char **a
)
1200 return (a
[0][0] == 'V');
1203 static unsigned long index_name_hash(const OPENSSL_CSTRING
*a
)
1205 return OPENSSL_LH_strhash(a
[DB_name
]);
1208 int index_name_cmp(const OPENSSL_CSTRING
*a
, const OPENSSL_CSTRING
*b
)
1210 return strcmp(a
[DB_name
], b
[DB_name
]);
1213 static IMPLEMENT_LHASH_HASH_FN(index_serial
, OPENSSL_CSTRING
)
1214 static IMPLEMENT_LHASH_COMP_FN(index_serial
, OPENSSL_CSTRING
)
1215 static IMPLEMENT_LHASH_HASH_FN(index_name
, OPENSSL_CSTRING
)
1216 static IMPLEMENT_LHASH_COMP_FN(index_name
, OPENSSL_CSTRING
)
1219 BIGNUM
*load_serial(const char *serialfile
, int create
, ASN1_INTEGER
**retai
)
1224 ASN1_INTEGER
*ai
= NULL
;
1226 ai
= ASN1_INTEGER_new();
1230 in
= BIO_new_file(serialfile
, "r");
1238 if (ret
== NULL
|| !rand_serial(ret
, ai
))
1239 BIO_printf(bio_err
, "Out of memory\n");
1241 if (!a2i_ASN1_INTEGER(in
, ai
, buf
, 1024)) {
1242 BIO_printf(bio_err
, "Unable to load number from %s\n",
1246 ret
= ASN1_INTEGER_to_BN(ai
, NULL
);
1248 BIO_printf(bio_err
, "Error converting number from bin to BIGNUM\n");
1258 ERR_print_errors(bio_err
);
1260 ASN1_INTEGER_free(ai
);
1264 int save_serial(const char *serialfile
, const char *suffix
, const BIGNUM
*serial
,
1265 ASN1_INTEGER
**retai
)
1270 ASN1_INTEGER
*ai
= NULL
;
1274 j
= strlen(serialfile
);
1276 j
= strlen(serialfile
) + strlen(suffix
) + 1;
1278 BIO_printf(bio_err
, "File name too long\n");
1283 OPENSSL_strlcpy(buf
[0], serialfile
, BSIZE
);
1285 #ifndef OPENSSL_SYS_VMS
1286 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, suffix
);
1288 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, suffix
);
1291 out
= BIO_new_file(buf
[0], "w");
1296 if ((ai
= BN_to_ASN1_INTEGER(serial
, NULL
)) == NULL
) {
1297 BIO_printf(bio_err
, "error converting serial to ASN.1 format\n");
1300 i2a_ASN1_INTEGER(out
, ai
);
1301 BIO_puts(out
, "\n");
1309 ERR_print_errors(bio_err
);
1311 ASN1_INTEGER_free(ai
);
1315 int rotate_serial(const char *serialfile
, const char *new_suffix
,
1316 const char *old_suffix
)
1321 i
= strlen(serialfile
) + strlen(old_suffix
);
1322 j
= strlen(serialfile
) + strlen(new_suffix
);
1325 if (j
+ 1 >= BSIZE
) {
1326 BIO_printf(bio_err
, "File name too long\n");
1329 #ifndef OPENSSL_SYS_VMS
1330 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", serialfile
, new_suffix
);
1331 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", serialfile
, old_suffix
);
1333 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", serialfile
, new_suffix
);
1334 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", serialfile
, old_suffix
);
1336 if (rename(serialfile
, buf
[1]) < 0 && errno
!= ENOENT
1342 "Unable to rename %s to %s\n", serialfile
, buf
[1]);
1346 if (rename(buf
[0], serialfile
) < 0) {
1348 "Unable to rename %s to %s\n", buf
[0], serialfile
);
1350 rename(buf
[1], serialfile
);
1355 ERR_print_errors(bio_err
);
1359 int rand_serial(BIGNUM
*b
, ASN1_INTEGER
*ai
)
1364 btmp
= b
== NULL
? BN_new() : b
;
1368 if (!BN_rand(btmp
, SERIAL_RAND_BITS
, BN_RAND_TOP_ANY
, BN_RAND_BOTTOM_ANY
))
1370 if (ai
&& !BN_to_ASN1_INTEGER(btmp
, ai
))
1383 CA_DB
*load_index(const char *dbfile
, DB_ATTR
*db_attr
)
1385 CA_DB
*retdb
= NULL
;
1386 TXT_DB
*tmpdb
= NULL
;
1388 CONF
*dbattr_conf
= NULL
;
1390 #ifndef OPENSSL_NO_POSIX_IO
1395 in
= BIO_new_file(dbfile
, "r");
1399 #ifndef OPENSSL_NO_POSIX_IO
1400 BIO_get_fp(in
, &dbfp
);
1401 if (fstat(fileno(dbfp
), &dbst
) == -1) {
1402 ERR_raise_data(ERR_LIB_SYS
, errno
,
1403 "calling fstat(%s)", dbfile
);
1408 if ((tmpdb
= TXT_DB_read(in
, DB_NUMBER
)) == NULL
)
1411 #ifndef OPENSSL_SYS_VMS
1412 BIO_snprintf(buf
, sizeof(buf
), "%s.attr", dbfile
);
1414 BIO_snprintf(buf
, sizeof(buf
), "%s-attr", dbfile
);
1416 dbattr_conf
= app_load_config_quiet(buf
);
1418 retdb
= app_malloc(sizeof(*retdb
), "new DB");
1422 retdb
->attributes
= *db_attr
;
1424 retdb
->attributes
.unique_subject
= 1;
1428 char *p
= NCONF_get_string(dbattr_conf
, NULL
, "unique_subject");
1430 retdb
->attributes
.unique_subject
= parse_yesno(p
, 1);
1434 retdb
->dbfname
= OPENSSL_strdup(dbfile
);
1435 #ifndef OPENSSL_NO_POSIX_IO
1440 ERR_print_errors(bio_err
);
1441 NCONF_free(dbattr_conf
);
1448 * Returns > 0 on success, <= 0 on error
1450 int index_index(CA_DB
*db
)
1452 if (!TXT_DB_create_index(db
->db
, DB_serial
, NULL
,
1453 LHASH_HASH_FN(index_serial
),
1454 LHASH_COMP_FN(index_serial
))) {
1456 "Error creating serial number index:(%ld,%ld,%ld)\n",
1457 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1461 if (db
->attributes
.unique_subject
1462 && !TXT_DB_create_index(db
->db
, DB_name
, index_name_qual
,
1463 LHASH_HASH_FN(index_name
),
1464 LHASH_COMP_FN(index_name
))) {
1465 BIO_printf(bio_err
, "Error creating name index:(%ld,%ld,%ld)\n",
1466 db
->db
->error
, db
->db
->arg1
, db
->db
->arg2
);
1471 ERR_print_errors(bio_err
);
1475 int save_index(const char *dbfile
, const char *suffix
, CA_DB
*db
)
1481 j
= strlen(dbfile
) + strlen(suffix
);
1482 if (j
+ 6 >= BSIZE
) {
1483 BIO_printf(bio_err
, "File name too long\n");
1486 #ifndef OPENSSL_SYS_VMS
1487 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr", dbfile
);
1488 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.attr.%s", dbfile
, suffix
);
1489 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, suffix
);
1491 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr", dbfile
);
1492 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-attr-%s", dbfile
, suffix
);
1493 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, suffix
);
1495 out
= BIO_new_file(buf
[0], "w");
1498 BIO_printf(bio_err
, "Unable to open '%s'\n", dbfile
);
1501 j
= TXT_DB_write(out
, db
->db
);
1506 out
= BIO_new_file(buf
[1], "w");
1509 BIO_printf(bio_err
, "Unable to open '%s'\n", buf
[2]);
1512 BIO_printf(out
, "unique_subject = %s\n",
1513 db
->attributes
.unique_subject
? "yes" : "no");
1518 ERR_print_errors(bio_err
);
1522 int rotate_index(const char *dbfile
, const char *new_suffix
,
1523 const char *old_suffix
)
1528 i
= strlen(dbfile
) + strlen(old_suffix
);
1529 j
= strlen(dbfile
) + strlen(new_suffix
);
1532 if (j
+ 6 >= BSIZE
) {
1533 BIO_printf(bio_err
, "File name too long\n");
1536 #ifndef OPENSSL_SYS_VMS
1537 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s.attr", dbfile
);
1538 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s.attr.%s", dbfile
, old_suffix
);
1539 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s.attr.%s", dbfile
, new_suffix
);
1540 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s.%s", dbfile
, old_suffix
);
1541 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s.%s", dbfile
, new_suffix
);
1543 j
= BIO_snprintf(buf
[4], sizeof(buf
[4]), "%s-attr", dbfile
);
1544 j
= BIO_snprintf(buf
[3], sizeof(buf
[3]), "%s-attr-%s", dbfile
, old_suffix
);
1545 j
= BIO_snprintf(buf
[2], sizeof(buf
[2]), "%s-attr-%s", dbfile
, new_suffix
);
1546 j
= BIO_snprintf(buf
[1], sizeof(buf
[1]), "%s-%s", dbfile
, old_suffix
);
1547 j
= BIO_snprintf(buf
[0], sizeof(buf
[0]), "%s-%s", dbfile
, new_suffix
);
1549 if (rename(dbfile
, buf
[1]) < 0 && errno
!= ENOENT
1554 BIO_printf(bio_err
, "Unable to rename %s to %s\n", dbfile
, buf
[1]);
1558 if (rename(buf
[0], dbfile
) < 0) {
1559 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[0], dbfile
);
1561 rename(buf
[1], dbfile
);
1564 if (rename(buf
[4], buf
[3]) < 0 && errno
!= ENOENT
1569 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[4], buf
[3]);
1571 rename(dbfile
, buf
[0]);
1572 rename(buf
[1], dbfile
);
1575 if (rename(buf
[2], buf
[4]) < 0) {
1576 BIO_printf(bio_err
, "Unable to rename %s to %s\n", buf
[2], buf
[4]);
1578 rename(buf
[3], buf
[4]);
1579 rename(dbfile
, buf
[0]);
1580 rename(buf
[1], dbfile
);
1585 ERR_print_errors(bio_err
);
1589 void free_index(CA_DB
*db
)
1592 TXT_DB_free(db
->db
);
1593 OPENSSL_free(db
->dbfname
);
1598 int parse_yesno(const char *str
, int def
)
1602 case 'f': /* false */
1603 case 'F': /* FALSE */
1608 case 't': /* true */
1609 case 'T': /* TRUE */
1620 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1621 * where + can be used instead of / to form multi-valued RDNs if canmulti
1622 * and characters may be escaped by \
1624 X509_NAME
*parse_name(const char *cp
, int chtype
, int canmulti
,
1627 int nextismulti
= 0;
1633 "%s: %s name is expected to be in the format "
1634 "/type0=value0/type1=value1/type2=... where characters may "
1635 "be escaped by \\. This name is not in that format: '%s'\n",
1636 opt_getprog(), desc
, --cp
);
1640 n
= X509_NAME_new();
1642 BIO_printf(bio_err
, "%s: Out of memory\n", opt_getprog());
1645 work
= OPENSSL_strdup(cp
);
1647 BIO_printf(bio_err
, "%s: Error copying %s name input\n",
1648 opt_getprog(), desc
);
1652 while (*cp
!= '\0') {
1655 unsigned char *valstr
;
1657 int ismulti
= nextismulti
;
1660 /* Collect the type */
1661 while (*cp
!= '\0' && *cp
!= '=')
1666 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1667 opt_getprog(), typestr
, desc
);
1672 /* Collect the value. */
1673 valstr
= (unsigned char *)bp
;
1674 for (; *cp
!= '\0' && *cp
!= '/'; *bp
++ = *cp
++) {
1675 /* unescaped '+' symbol string signals further member of multiRDN */
1676 if (canmulti
&& *cp
== '+') {
1680 if (*cp
== '\\' && *++cp
== '\0') {
1682 "%s: Escape character at end of %s name string\n",
1683 opt_getprog(), desc
);
1689 /* If not at EOS (must be + or /), move forward. */
1694 nid
= OBJ_txt2nid(typestr
);
1695 if (nid
== NID_undef
) {
1697 "%s: Skipping unknown %s name attribute \"%s\"\n",
1698 opt_getprog(), desc
, typestr
);
1701 "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
1704 if (*valstr
== '\0') {
1706 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1707 opt_getprog(), desc
, typestr
);
1710 if (!X509_NAME_add_entry_by_NID(n
, nid
, chtype
,
1711 valstr
, strlen((char *)valstr
),
1712 -1, ismulti
? -1 : 0)) {
1713 ERR_print_errors(bio_err
);
1715 "%s: Error adding %s name attribute \"/%s=%s\"\n",
1716 opt_getprog(), desc
, typestr
,valstr
);
1731 * Read whole contents of a BIO into an allocated memory buffer and return
1735 int bio_to_mem(unsigned char **out
, int maxlen
, BIO
*in
)
1739 unsigned char tbuf
[1024];
1741 mem
= BIO_new(BIO_s_mem());
1745 if ((maxlen
!= -1) && maxlen
< 1024)
1749 len
= BIO_read(in
, tbuf
, len
);
1756 if (BIO_write(mem
, tbuf
, len
) != len
) {
1765 ret
= BIO_get_mem_data(mem
, (char **)out
);
1766 BIO_set_flags(mem
, BIO_FLAGS_MEM_RDONLY
);
1771 int pkey_ctrl_string(EVP_PKEY_CTX
*ctx
, const char *value
)
1774 char *stmp
, *vtmp
= NULL
;
1775 stmp
= OPENSSL_strdup(value
);
1778 vtmp
= strchr(stmp
, ':');
1783 rv
= EVP_PKEY_CTX_ctrl_str(ctx
, stmp
, vtmp
);
1788 static void nodes_print(const char *name
, STACK_OF(X509_POLICY_NODE
) *nodes
)
1790 X509_POLICY_NODE
*node
;
1793 BIO_printf(bio_err
, "%s Policies:", name
);
1795 BIO_puts(bio_err
, "\n");
1796 for (i
= 0; i
< sk_X509_POLICY_NODE_num(nodes
); i
++) {
1797 node
= sk_X509_POLICY_NODE_value(nodes
, i
);
1798 X509_POLICY_NODE_print(bio_err
, node
, 2);
1801 BIO_puts(bio_err
, " <empty>\n");
1805 void policies_print(X509_STORE_CTX
*ctx
)
1807 X509_POLICY_TREE
*tree
;
1808 int explicit_policy
;
1809 tree
= X509_STORE_CTX_get0_policy_tree(ctx
);
1810 explicit_policy
= X509_STORE_CTX_get_explicit_policy(ctx
);
1812 BIO_printf(bio_err
, "Require explicit Policy: %s\n",
1813 explicit_policy
? "True" : "False");
1815 nodes_print("Authority", X509_policy_tree_get0_policies(tree
));
1816 nodes_print("User", X509_policy_tree_get0_user_policies(tree
));
1820 * next_protos_parse parses a comma separated list of strings into a string
1821 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1822 * outlen: (output) set to the length of the resulting buffer on success.
1823 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1824 * in: a NUL terminated string like "abc,def,ghi"
1826 * returns: a malloc'd buffer or NULL on failure.
1828 unsigned char *next_protos_parse(size_t *outlen
, const char *in
)
1832 size_t i
, start
= 0;
1836 if (len
== 0 || len
>= 65535)
1839 out
= app_malloc(len
+ 1, "NPN buffer");
1840 for (i
= 0; i
<= len
; ++i
) {
1841 if (i
== len
|| in
[i
] == ',') {
1843 * Zero-length ALPN elements are invalid on the wire, we could be
1844 * strict and reject the entire string, but just ignoring extra
1845 * commas seems harmless and more friendly.
1847 * Every comma we skip in this way puts the input buffer another
1848 * byte ahead of the output buffer, so all stores into the output
1849 * buffer need to be decremented by the number commas skipped.
1856 if (i
- start
> 255) {
1860 out
[start
-skipped
] = (unsigned char)(i
- start
);
1863 out
[i
+ 1 - skipped
] = in
[i
];
1867 if (len
<= skipped
) {
1872 *outlen
= len
+ 1 - skipped
;
1876 void print_cert_checks(BIO
*bio
, X509
*x
,
1877 const char *checkhost
,
1878 const char *checkemail
, const char *checkip
)
1883 BIO_printf(bio
, "Hostname %s does%s match certificate\n",
1885 X509_check_host(x
, checkhost
, 0, 0, NULL
) == 1
1890 BIO_printf(bio
, "Email %s does%s match certificate\n",
1891 checkemail
, X509_check_email(x
, checkemail
, 0, 0)
1896 BIO_printf(bio
, "IP %s does%s match certificate\n",
1897 checkip
, X509_check_ip_asc(x
, checkip
, 0) ? "" : " NOT");
1901 static int do_pkey_ctx_init(EVP_PKEY_CTX
*pkctx
, STACK_OF(OPENSSL_STRING
) *opts
)
1908 for (i
= 0; i
< sk_OPENSSL_STRING_num(opts
); i
++) {
1909 char *opt
= sk_OPENSSL_STRING_value(opts
, i
);
1910 if (pkey_ctrl_string(pkctx
, opt
) <= 0) {
1911 BIO_printf(bio_err
, "parameter error \"%s\"\n", opt
);
1912 ERR_print_errors(bio_err
);
1920 static int do_x509_init(X509
*x
, STACK_OF(OPENSSL_STRING
) *opts
)
1927 for (i
= 0; i
< sk_OPENSSL_STRING_num(opts
); i
++) {
1928 char *opt
= sk_OPENSSL_STRING_value(opts
, i
);
1929 if (x509_ctrl_string(x
, opt
) <= 0) {
1930 BIO_printf(bio_err
, "parameter error \"%s\"\n", opt
);
1931 ERR_print_errors(bio_err
);
1939 static int do_x509_req_init(X509_REQ
*x
, STACK_OF(OPENSSL_STRING
) *opts
)
1946 for (i
= 0; i
< sk_OPENSSL_STRING_num(opts
); i
++) {
1947 char *opt
= sk_OPENSSL_STRING_value(opts
, i
);
1948 if (x509_req_ctrl_string(x
, opt
) <= 0) {
1949 BIO_printf(bio_err
, "parameter error \"%s\"\n", opt
);
1950 ERR_print_errors(bio_err
);
1958 static int do_sign_init(EVP_MD_CTX
*ctx
, EVP_PKEY
*pkey
,
1959 const EVP_MD
*md
, STACK_OF(OPENSSL_STRING
) *sigopts
)
1961 EVP_PKEY_CTX
*pkctx
= NULL
;
1967 * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1968 * for this algorithm.
1970 if (EVP_PKEY_get_default_digest_nid(pkey
, &def_nid
) == 2
1971 && def_nid
== NID_undef
) {
1972 /* The signing algorithm requires there to be no digest */
1975 return EVP_DigestSignInit(ctx
, &pkctx
, md
, NULL
, pkey
)
1976 && do_pkey_ctx_init(pkctx
, sigopts
);
1979 static int adapt_keyid_ext(X509
*cert
, X509V3_CTX
*ext_ctx
,
1980 const char *name
, const char *value
, int add_default
)
1982 const STACK_OF(X509_EXTENSION
) *exts
= X509_get0_extensions(cert
);
1983 X509_EXTENSION
*new_ext
= X509V3_EXT_nconf(NULL
, ext_ctx
, name
, value
);
1986 if (new_ext
== NULL
)
1989 idx
= X509v3_get_ext_by_OBJ(exts
, X509_EXTENSION_get_object(new_ext
), -1);
1991 X509_EXTENSION
*found_ext
= X509v3_get_ext(exts
, idx
);
1992 ASN1_OCTET_STRING
*data
= X509_EXTENSION_get_data(found_ext
);
1993 int disabled
= ASN1_STRING_length(data
) <= 2; /* config said "none" */
1996 X509_delete_ext(cert
, idx
);
1997 X509_EXTENSION_free(found_ext
);
1998 } /* else keep existing key identifier, which might be outdated */
2001 rv
= !add_default
|| X509_add_ext(cert
, new_ext
, -1);
2003 X509_EXTENSION_free(new_ext
);
2007 /* Ensure RFC 5280 compliance, adapt keyIDs as needed, and sign the cert info */
2008 int do_X509_sign(X509
*cert
, EVP_PKEY
*pkey
, const EVP_MD
*md
,
2009 STACK_OF(OPENSSL_STRING
) *sigopts
, X509V3_CTX
*ext_ctx
)
2011 const STACK_OF(X509_EXTENSION
) *exts
= X509_get0_extensions(cert
);
2012 EVP_MD_CTX
*mctx
= EVP_MD_CTX_new();
2016 if (sk_X509_EXTENSION_num(exts
/* may be NULL */) > 0) {
2017 /* Prevent X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 */
2018 if (!X509_set_version(cert
, 2)) /* Make sure cert is X509 v3 */
2022 * Add default SKID before such that default AKID can make use of it
2023 * in case the certificate is self-signed
2025 /* Prevent X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER */
2026 if (!adapt_keyid_ext(cert
, ext_ctx
, "subjectKeyIdentifier", "hash", 1))
2028 /* Prevent X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER */
2030 self_sign
= X509_check_private_key(cert
, pkey
);
2032 if (!adapt_keyid_ext(cert
, ext_ctx
, "authorityKeyIdentifier",
2033 "keyid, issuer", !self_sign
))
2036 /* TODO any further measures for ensuring default RFC 5280 compliance */
2039 if (mctx
!= NULL
&& do_sign_init(mctx
, pkey
, md
, sigopts
) > 0)
2040 rv
= (X509_sign_ctx(cert
, mctx
) > 0);
2042 EVP_MD_CTX_free(mctx
);
2046 /* Sign the certificate request info */
2047 int do_X509_REQ_sign(X509_REQ
*x
, EVP_PKEY
*pkey
, const EVP_MD
*md
,
2048 STACK_OF(OPENSSL_STRING
) *sigopts
)
2051 EVP_MD_CTX
*mctx
= EVP_MD_CTX_new();
2053 if (do_sign_init(mctx
, pkey
, md
, sigopts
) > 0)
2054 rv
= (X509_REQ_sign_ctx(x
, mctx
) > 0);
2055 EVP_MD_CTX_free(mctx
);
2059 /* Sign the CRL info */
2060 int do_X509_CRL_sign(X509_CRL
*x
, EVP_PKEY
*pkey
, const EVP_MD
*md
,
2061 STACK_OF(OPENSSL_STRING
) *sigopts
)
2064 EVP_MD_CTX
*mctx
= EVP_MD_CTX_new();
2066 if (do_sign_init(mctx
, pkey
, md
, sigopts
) > 0)
2067 rv
= (X509_CRL_sign_ctx(x
, mctx
) > 0);
2068 EVP_MD_CTX_free(mctx
);
2072 int do_X509_verify(X509
*x
, EVP_PKEY
*pkey
, STACK_OF(OPENSSL_STRING
) *vfyopts
)
2076 if (do_x509_init(x
, vfyopts
) > 0)
2077 rv
= (X509_verify(x
, pkey
) > 0);
2081 int do_X509_REQ_verify(X509_REQ
*x
, EVP_PKEY
*pkey
,
2082 STACK_OF(OPENSSL_STRING
) *vfyopts
)
2086 if (do_x509_req_init(x
, vfyopts
) > 0)
2087 rv
= (X509_REQ_verify(x
, pkey
) > 0);
2091 /* Get first http URL from a DIST_POINT structure */
2093 static const char *get_dp_url(DIST_POINT
*dp
)
2095 GENERAL_NAMES
*gens
;
2099 if (!dp
->distpoint
|| dp
->distpoint
->type
!= 0)
2101 gens
= dp
->distpoint
->name
.fullname
;
2102 for (i
= 0; i
< sk_GENERAL_NAME_num(gens
); i
++) {
2103 gen
= sk_GENERAL_NAME_value(gens
, i
);
2104 uri
= GENERAL_NAME_get0_value(gen
, >ype
);
2105 if (gtype
== GEN_URI
&& ASN1_STRING_length(uri
) > 6) {
2106 const char *uptr
= (const char *)ASN1_STRING_get0_data(uri
);
2108 if (IS_HTTP(uptr
)) /* can/should not use HTTPS here */
2116 * Look through a CRLDP structure and attempt to find an http URL to
2117 * downloads a CRL from.
2120 static X509_CRL
*load_crl_crldp(STACK_OF(DIST_POINT
) *crldp
)
2123 const char *urlptr
= NULL
;
2124 for (i
= 0; i
< sk_DIST_POINT_num(crldp
); i
++) {
2125 DIST_POINT
*dp
= sk_DIST_POINT_value(crldp
, i
);
2126 urlptr
= get_dp_url(dp
);
2128 return load_crl(urlptr
, "CRL via CDP");
2134 * Example of downloading CRLs from CRLDP:
2135 * not usable for real world as it always downloads and doesn't cache anything.
2138 static STACK_OF(X509_CRL
) *crls_http_cb(const X509_STORE_CTX
*ctx
,
2139 const X509_NAME
*nm
)
2142 STACK_OF(X509_CRL
) *crls
= NULL
;
2144 STACK_OF(DIST_POINT
) *crldp
;
2146 crls
= sk_X509_CRL_new_null();
2149 x
= X509_STORE_CTX_get_current_cert(ctx
);
2150 crldp
= X509_get_ext_d2i(x
, NID_crl_distribution_points
, NULL
, NULL
);
2151 crl
= load_crl_crldp(crldp
);
2152 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
2154 sk_X509_CRL_free(crls
);
2157 sk_X509_CRL_push(crls
, crl
);
2158 /* Try to download delta CRL */
2159 crldp
= X509_get_ext_d2i(x
, NID_freshest_crl
, NULL
, NULL
);
2160 crl
= load_crl_crldp(crldp
);
2161 sk_DIST_POINT_pop_free(crldp
, DIST_POINT_free
);
2163 sk_X509_CRL_push(crls
, crl
);
2167 void store_setup_crl_download(X509_STORE
*st
)
2169 X509_STORE_set_lookup_crls_cb(st
, crls_http_cb
);
2172 #ifndef OPENSSL_NO_SOCK
2173 static const char *tls_error_hint(void)
2175 unsigned long err
= ERR_peek_error();
2177 if (ERR_GET_LIB(err
) != ERR_LIB_SSL
)
2178 err
= ERR_peek_last_error();
2179 if (ERR_GET_LIB(err
) != ERR_LIB_SSL
)
2182 switch (ERR_GET_REASON(err
)) {
2183 case SSL_R_WRONG_VERSION_NUMBER
:
2184 return "The server does not support (a suitable version of) TLS";
2185 case SSL_R_UNKNOWN_PROTOCOL
:
2186 return "The server does not support HTTPS";
2187 case SSL_R_CERTIFICATE_VERIFY_FAILED
:
2188 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2189 case SSL_AD_REASON_OFFSET
+ TLS1_AD_UNKNOWN_CA
:
2190 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2191 case SSL_AD_REASON_OFFSET
+ SSL3_AD_HANDSHAKE_FAILURE
:
2192 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2193 default: /* no error or no hint available for error */
2198 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
2199 BIO
*app_http_tls_cb(BIO
*hbio
, void *arg
, int connect
, int detail
)
2201 APP_HTTP_TLS_INFO
*info
= (APP_HTTP_TLS_INFO
*)arg
;
2202 SSL_CTX
*ssl_ctx
= info
->ssl_ctx
;
2206 if (connect
&& detail
) { /* connecting with TLS */
2207 if ((info
->use_proxy
2208 && !OSSL_HTTP_proxy_connect(hbio
, info
->server
, info
->port
,
2209 NULL
, NULL
, /* no proxy credentials */
2210 info
->timeout
, bio_err
, opt_getprog()))
2211 || (sbio
= BIO_new(BIO_f_ssl())) == NULL
) {
2214 if (ssl_ctx
== NULL
|| (ssl
= SSL_new(ssl_ctx
)) == NULL
) {
2219 SSL_set_tlsext_host_name(ssl
, info
->server
);
2221 SSL_set_connect_state(ssl
);
2222 BIO_set_ssl(sbio
, ssl
, BIO_CLOSE
);
2224 hbio
= BIO_push(sbio
, hbio
);
2225 } else if (!connect
&& !detail
) { /* disconnecting after error */
2226 const char *hint
= tls_error_hint();
2228 ERR_add_error_data(2, " : ", hint
);
2230 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2231 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2237 ASN1_VALUE
*app_http_get_asn1(const char *url
, const char *proxy
,
2238 const char *no_proxy
, SSL_CTX
*ssl_ctx
,
2239 const STACK_OF(CONF_VALUE
) *headers
,
2240 long timeout
, const char *expected_content_type
,
2241 const ASN1_ITEM
*it
)
2243 APP_HTTP_TLS_INFO info
;
2247 ASN1_VALUE
*resp
= NULL
;
2249 if (url
== NULL
|| it
== NULL
) {
2250 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
2254 if (!OSSL_HTTP_parse_url(url
, &server
, &port
, NULL
, NULL
, &use_ssl
))
2256 if (use_ssl
&& ssl_ctx
== NULL
) {
2257 ERR_raise_data(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
,
2262 info
.server
= server
;
2264 info
.use_proxy
= proxy
!= NULL
;
2265 info
.timeout
= timeout
;
2266 info
.ssl_ctx
= ssl_ctx
;
2267 resp
= OSSL_HTTP_get_asn1(url
, proxy
, no_proxy
,
2268 NULL
, NULL
, app_http_tls_cb
, &info
,
2269 headers
, 0 /* maxline */, 0 /* max_resp_len */,
2270 timeout
, expected_content_type
, it
);
2272 OPENSSL_free(server
);
2278 ASN1_VALUE
*app_http_post_asn1(const char *host
, const char *port
,
2279 const char *path
, const char *proxy
,
2280 const char *no_proxy
, SSL_CTX
*ssl_ctx
,
2281 const STACK_OF(CONF_VALUE
) *headers
,
2282 const char *content_type
,
2283 ASN1_VALUE
*req
, const ASN1_ITEM
*req_it
,
2284 long timeout
, const ASN1_ITEM
*rsp_it
)
2286 APP_HTTP_TLS_INFO info
;
2290 info
.use_proxy
= proxy
!= NULL
;
2291 info
.timeout
= timeout
;
2292 info
.ssl_ctx
= ssl_ctx
;
2293 return OSSL_HTTP_post_asn1(host
, port
, path
, ssl_ctx
!= NULL
,
2295 NULL
, NULL
, app_http_tls_cb
, &info
,
2296 headers
, content_type
, req
, req_it
,
2298 0 /* max_resp_len */, timeout
, NULL
, rsp_it
);
2304 * Platform-specific sections
2309 # define fileno(a) (int)_fileno(a)
2312 # include <windows.h>
2315 static int WIN32_rename(const char *from
, const char *to
)
2317 TCHAR
*tfrom
= NULL
, *tto
;
2321 if (sizeof(TCHAR
) == 1) {
2322 tfrom
= (TCHAR
*)from
;
2324 } else { /* UNICODE path */
2326 size_t i
, flen
= strlen(from
) + 1, tlen
= strlen(to
) + 1;
2327 tfrom
= malloc(sizeof(*tfrom
) * (flen
+ tlen
));
2331 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2332 if (!MultiByteToWideChar(CP_ACP
, 0, from
, flen
, (WCHAR
*)tfrom
, flen
))
2334 for (i
= 0; i
< flen
; i
++)
2335 tfrom
[i
] = (TCHAR
)from
[i
];
2336 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2337 if (!MultiByteToWideChar(CP_ACP
, 0, to
, tlen
, (WCHAR
*)tto
, tlen
))
2339 for (i
= 0; i
< tlen
; i
++)
2340 tto
[i
] = (TCHAR
)to
[i
];
2343 if (MoveFile(tfrom
, tto
))
2345 err
= GetLastError();
2346 if (err
== ERROR_ALREADY_EXISTS
|| err
== ERROR_FILE_EXISTS
) {
2347 if (DeleteFile(tto
) && MoveFile(tfrom
, tto
))
2349 err
= GetLastError();
2351 if (err
== ERROR_FILE_NOT_FOUND
|| err
== ERROR_PATH_NOT_FOUND
)
2353 else if (err
== ERROR_ACCESS_DENIED
)
2356 errno
= EINVAL
; /* we could map more codes... */
2360 if (tfrom
!= NULL
&& tfrom
!= (TCHAR
*)from
)
2366 /* app_tminterval section */
2368 double app_tminterval(int stop
, int usertime
)
2372 static ULARGE_INTEGER tmstart
;
2373 static int warning
= 1;
2374 # ifdef _WIN32_WINNT
2375 static HANDLE proc
= NULL
;
2379 proc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
,
2380 GetCurrentProcessId());
2382 proc
= (HANDLE
) - 1;
2385 if (usertime
&& proc
!= (HANDLE
) - 1) {
2387 GetProcessTimes(proc
, &junk
, &junk
, &junk
, &now
);
2393 if (usertime
&& warning
) {
2394 BIO_printf(bio_err
, "To get meaningful results, run "
2395 "this program on idle system.\n");
2398 GetSystemTime(&systime
);
2399 SystemTimeToFileTime(&systime
, &now
);
2402 if (stop
== TM_START
) {
2403 tmstart
.u
.LowPart
= now
.dwLowDateTime
;
2404 tmstart
.u
.HighPart
= now
.dwHighDateTime
;
2406 ULARGE_INTEGER tmstop
;
2408 tmstop
.u
.LowPart
= now
.dwLowDateTime
;
2409 tmstop
.u
.HighPart
= now
.dwHighDateTime
;
2411 ret
= (__int64
)(tmstop
.QuadPart
- tmstart
.QuadPart
) * 1e-7;
2416 #elif defined(OPENSSL_SYS_VXWORKS)
2419 double app_tminterval(int stop
, int usertime
)
2422 # ifdef CLOCK_REALTIME
2423 static struct timespec tmstart
;
2424 struct timespec now
;
2426 static unsigned long tmstart
;
2429 static int warning
= 1;
2431 if (usertime
&& warning
) {
2432 BIO_printf(bio_err
, "To get meaningful results, run "
2433 "this program on idle system.\n");
2436 # ifdef CLOCK_REALTIME
2437 clock_gettime(CLOCK_REALTIME
, &now
);
2438 if (stop
== TM_START
)
2441 ret
= ((now
.tv_sec
+ now
.tv_nsec
* 1e-9)
2442 - (tmstart
.tv_sec
+ tmstart
.tv_nsec
* 1e-9));
2445 if (stop
== TM_START
)
2448 ret
= (now
- tmstart
) / (double)sysClkRateGet();
2453 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2454 # include <sys/times.h>
2456 double app_tminterval(int stop
, int usertime
)
2460 clock_t now
= times(&rus
);
2461 static clock_t tmstart
;
2464 now
= rus
.tms_utime
;
2466 if (stop
== TM_START
) {
2469 long int tck
= sysconf(_SC_CLK_TCK
);
2470 ret
= (now
- tmstart
) / (double)tck
;
2477 # include <sys/time.h>
2478 # include <sys/resource.h>
2480 double app_tminterval(int stop
, int usertime
)
2485 static struct timeval tmstart
;
2488 getrusage(RUSAGE_SELF
, &rus
), now
= rus
.ru_utime
;
2490 gettimeofday(&now
, NULL
);
2492 if (stop
== TM_START
)
2495 ret
= ((now
.tv_sec
+ now
.tv_usec
* 1e-6)
2496 - (tmstart
.tv_sec
+ tmstart
.tv_usec
* 1e-6));
2502 int app_access(const char* name
, int flag
)
2505 return _access(name
, flag
);
2507 return access(name
, flag
);
2511 int app_isdir(const char *name
)
2513 return opt_isdir(name
);
2516 /* raw_read|write section */
2518 # include "vms_term_sock.h"
2519 static int stdin_sock
= -1;
2521 static void close_stdin_sock(void)
2523 TerminalSocket (TERM_SOCK_DELETE
, &stdin_sock
);
2526 int fileno_stdin(void)
2528 if (stdin_sock
== -1) {
2529 TerminalSocket(TERM_SOCK_CREATE
, &stdin_sock
);
2530 atexit(close_stdin_sock
);
2536 int fileno_stdin(void)
2538 return fileno(stdin
);
2542 int fileno_stdout(void)
2544 return fileno(stdout
);
2547 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2548 int raw_read_stdin(void *buf
, int siz
)
2551 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2556 #elif defined(__VMS)
2557 # include <sys/socket.h>
2559 int raw_read_stdin(void *buf
, int siz
)
2561 return recv(fileno_stdin(), buf
, siz
, 0);
2564 # if defined(__TANDEM)
2565 # if defined(OPENSSL_TANDEM_FLOSS)
2566 # include <floss.h(floss_read)>
2569 int raw_read_stdin(void *buf
, int siz
)
2571 return read(fileno_stdin(), buf
, siz
);
2575 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2576 int raw_write_stdout(const void *buf
, int siz
)
2579 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE
), buf
, siz
, &n
, NULL
))
2584 #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
2585 # if defined(__TANDEM)
2586 # if defined(OPENSSL_TANDEM_FLOSS)
2587 # include <floss.h(floss_write)>
2590 int raw_write_stdout(const void *buf
,int siz
)
2592 return write(fileno(stdout
),(void*)buf
,siz
);
2595 # if defined(__TANDEM)
2596 # if defined(OPENSSL_TANDEM_FLOSS)
2597 # include <floss.h(floss_write)>
2600 int raw_write_stdout(const void *buf
, int siz
)
2602 return write(fileno_stdout(), buf
, siz
);
2607 * Centralized handling of input and output files with format specification
2608 * The format is meant to show what the input and output is supposed to be,
2609 * and is therefore a show of intent more than anything else. However, it
2610 * does impact behavior on some platforms, such as differentiating between
2611 * text and binary input/output on non-Unix platforms
2613 BIO
*dup_bio_in(int format
)
2615 return BIO_new_fp(stdin
,
2616 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2619 BIO
*dup_bio_out(int format
)
2621 BIO
*b
= BIO_new_fp(stdout
,
2622 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2623 void *prefix
= NULL
;
2625 #ifdef OPENSSL_SYS_VMS
2626 if (FMT_istext(format
))
2627 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2630 if (FMT_istext(format
)
2631 && (prefix
= getenv("HARNESS_OSSL_PREFIX")) != NULL
) {
2632 b
= BIO_push(BIO_new(BIO_f_prefix()), b
);
2633 BIO_set_prefix(b
, prefix
);
2639 BIO
*dup_bio_err(int format
)
2641 BIO
*b
= BIO_new_fp(stderr
,
2642 BIO_NOCLOSE
| (FMT_istext(format
) ? BIO_FP_TEXT
: 0));
2643 #ifdef OPENSSL_SYS_VMS
2644 if (FMT_istext(format
))
2645 b
= BIO_push(BIO_new(BIO_f_linebuffer()), b
);
2650 void unbuffer(FILE *fp
)
2653 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2654 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2655 * However, we trust that the C RTL will never give us a FILE pointer
2656 * above the first 4 GB of memory, so we simply turn off the warning
2659 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2660 # pragma environment save
2661 # pragma message disable maylosedata2
2664 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2665 # pragma environment restore
2669 static const char *modestr(char mode
, int format
)
2671 OPENSSL_assert(mode
== 'a' || mode
== 'r' || mode
== 'w');
2675 return FMT_istext(format
) ? "a" : "ab";
2677 return FMT_istext(format
) ? "r" : "rb";
2679 return FMT_istext(format
) ? "w" : "wb";
2681 /* The assert above should make sure we never reach this point */
2685 static const char *modeverb(char mode
)
2695 return "(doing something)";
2699 * Open a file for writing, owner-read-only.
2701 BIO
*bio_open_owner(const char *filename
, int format
, int private)
2705 int fd
= -1, bflags
, mode
, textmode
;
2707 if (!private || filename
== NULL
|| strcmp(filename
, "-") == 0)
2708 return bio_open_default(filename
, 'w', format
);
2717 textmode
= FMT_istext(format
);
2721 #elif defined(_O_BINARY)
2726 #ifdef OPENSSL_SYS_VMS
2727 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2728 * it still needs to know that we're going binary, or fdopen()
2729 * will fail with "invalid argument"... so we tell VMS what the
2733 fd
= open(filename
, mode
, 0600, "ctx=bin");
2736 fd
= open(filename
, mode
, 0600);
2739 fp
= fdopen(fd
, modestr('w', format
));
2744 bflags
|= BIO_FP_TEXT
;
2745 b
= BIO_new_fp(fp
, bflags
);
2750 BIO_printf(bio_err
, "%s: Can't open \"%s\" for writing, %s\n",
2751 opt_getprog(), filename
, strerror(errno
));
2752 ERR_print_errors(bio_err
);
2753 /* If we have fp, then fdopen took over fd, so don't close both. */
2761 static BIO
*bio_open_default_(const char *filename
, char mode
, int format
,
2766 if (filename
== NULL
|| strcmp(filename
, "-") == 0) {
2767 ret
= mode
== 'r' ? dup_bio_in(format
) : dup_bio_out(format
);
2775 "Can't open %s, %s\n",
2776 mode
== 'r' ? "stdin" : "stdout", strerror(errno
));
2778 ret
= BIO_new_file(filename
, modestr(mode
, format
));
2786 "Can't open \"%s\" for %s, %s\n",
2787 filename
, modeverb(mode
), strerror(errno
));
2789 ERR_print_errors(bio_err
);
2793 BIO
*bio_open_default(const char *filename
, char mode
, int format
)
2795 return bio_open_default_(filename
, mode
, format
, 0);
2798 BIO
*bio_open_default_quiet(const char *filename
, char mode
, int format
)
2800 return bio_open_default_(filename
, mode
, format
, 1);
2803 void wait_for_async(SSL
*s
)
2805 /* On Windows select only works for sockets, so we simply don't wait */
2806 #ifndef OPENSSL_SYS_WINDOWS
2813 if (!SSL_get_all_async_fds(s
, NULL
, &numfds
))
2817 fds
= app_malloc(sizeof(OSSL_ASYNC_FD
) * numfds
, "allocate async fds");
2818 if (!SSL_get_all_async_fds(s
, fds
, &numfds
)) {
2824 for (i
= 0; i
< numfds
; i
++) {
2825 if (width
<= (int)fds
[i
])
2826 width
= (int)fds
[i
] + 1;
2827 openssl_fdset((int)fds
[i
], &asyncfds
);
2829 select(width
, (void *)&asyncfds
, NULL
, NULL
, NULL
);
2834 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2835 #if defined(OPENSSL_SYS_MSDOS)
2836 int has_stdin_waiting(void)
2838 # if defined(OPENSSL_SYS_WINDOWS)
2839 HANDLE inhand
= GetStdHandle(STD_INPUT_HANDLE
);
2841 INPUT_RECORD inputrec
;
2845 if (inhand
== INVALID_HANDLE_VALUE
) {
2849 peeked
= PeekConsoleInput(inhand
, &inputrec
, insize
, &events
);
2851 /* Probably redirected input? _kbhit() does not work in this case */
2862 /* Corrupt a signature by modifying final byte */
2863 void corrupt_signature(const ASN1_STRING
*signature
)
2865 unsigned char *s
= signature
->data
;
2866 s
[signature
->length
- 1] ^= 0x1;
2869 int set_cert_times(X509
*x
, const char *startdate
, const char *enddate
,
2872 if (startdate
== NULL
|| strcmp(startdate
, "today") == 0) {
2873 if (X509_gmtime_adj(X509_getm_notBefore(x
), 0) == NULL
)
2876 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x
), startdate
))
2879 if (enddate
== NULL
) {
2880 if (X509_time_adj_ex(X509_getm_notAfter(x
), days
, 0, NULL
)
2883 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x
), enddate
)) {
2889 int set_crl_lastupdate(X509_CRL
*crl
, const char *lastupdate
)
2892 ASN1_TIME
*tm
= ASN1_TIME_new();
2897 if (lastupdate
== NULL
) {
2898 if (X509_gmtime_adj(tm
, 0) == NULL
)
2901 if (!ASN1_TIME_set_string_X509(tm
, lastupdate
))
2905 if (!X509_CRL_set1_lastUpdate(crl
, tm
))
2914 int set_crl_nextupdate(X509_CRL
*crl
, const char *nextupdate
,
2915 long days
, long hours
, long secs
)
2918 ASN1_TIME
*tm
= ASN1_TIME_new();
2923 if (nextupdate
== NULL
) {
2924 if (X509_time_adj_ex(tm
, days
, hours
* 60 * 60 + secs
, NULL
) == NULL
)
2927 if (!ASN1_TIME_set_string_X509(tm
, nextupdate
))
2931 if (!X509_CRL_set1_nextUpdate(crl
, tm
))
2940 void make_uppercase(char *string
)
2944 for (i
= 0; string
[i
] != '\0'; i
++)
2945 string
[i
] = toupper((unsigned char)string
[i
]);
2948 int opt_printf_stderr(const char *fmt
, ...)
2954 ret
= BIO_vprintf(bio_err
, fmt
, ap
);
2959 OSSL_PARAM
*app_params_new_from_opts(STACK_OF(OPENSSL_STRING
) *opts
,
2960 const OSSL_PARAM
*paramdefs
)
2962 OSSL_PARAM
*params
= NULL
;
2963 size_t sz
= (size_t)sk_OPENSSL_STRING_num(opts
);
2965 char *opt
= "", *stmp
, *vtmp
= NULL
;
2971 params
= OPENSSL_zalloc(sizeof(OSSL_PARAM
) * (sz
+ 1));
2975 for (params_n
= 0; params_n
< sz
; params_n
++) {
2976 opt
= sk_OPENSSL_STRING_value(opts
, (int)params_n
);
2977 if ((stmp
= OPENSSL_strdup(opt
)) == NULL
2978 || (vtmp
= strchr(stmp
, ':')) == NULL
)
2980 /* Replace ':' with 0 to terminate the string pointed to by stmp */
2982 /* Skip over the separator so that vmtp points to the value */
2984 if (!OSSL_PARAM_allocate_from_text(¶ms
[params_n
], paramdefs
,
2985 stmp
, vtmp
, strlen(vtmp
), &found
))
2989 params
[params_n
] = OSSL_PARAM_construct_end();
2993 BIO_printf(bio_err
, "Parameter %s '%s'\n", found
? "error" : "unknown",
2995 ERR_print_errors(bio_err
);
2996 app_params_free(params
);
3000 void app_params_free(OSSL_PARAM
*params
)
3004 if (params
!= NULL
) {
3005 for (i
= 0; params
[i
].key
!= NULL
; ++i
)
3006 OPENSSL_free(params
[i
].data
);
3007 OPENSSL_free(params
);