1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
57 /* ====================================================================
58 * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
86 * 6. Redistributions of any form whatsoever must retain the following
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com).
111 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
113 * On VMS, you need to define this to get the declaration of fileno(). The
114 * value 2 is to make sure no function defined in POSIX-2 is left undefined.
116 # define _POSIX_C_SOURCE 2
121 #if !defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_SYS_WINCE) && !defined(NETWARE_CLIB)
122 # include <strings.h>
124 #include <sys/types.h>
128 #include <openssl/err.h>
129 #include <openssl/x509.h>
130 #include <openssl/x509v3.h>
131 #include <openssl/pem.h>
132 #include <openssl/pkcs12.h>
133 #include <openssl/ui.h>
134 #include <openssl/safestack.h>
135 #ifndef OPENSSL_NO_ENGINE
136 # include <openssl/engine.h>
138 #ifndef OPENSSL_NO_RSA
139 # include <openssl/rsa.h>
141 #include <openssl/bn.h>
142 #ifndef OPENSSL_NO_JPAKE
143 # include <openssl/jpake.h>
145 #include <openssl/ssl.h>
150 static int WIN32_rename(const char *from, const char *to);
151 # define rename(from,to) WIN32_rename((from),(to))
160 static UI_METHOD *ui_method = NULL;
162 static int set_table_opts(unsigned long *flags, const char *arg,
163 const NAME_EX_TBL * in_tbl);
164 static int set_multi_opts(unsigned long *flags, const char *arg,
165 const NAME_EX_TBL * in_tbl);
167 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
168 /* Looks like this stuff is worth moving into separate function */
169 static EVP_PKEY *load_netscape_key(BIO *key, const char *file,
170 const char *key_descrip, int format);
173 int app_init(long mesgwin);
175 int chopup_args(ARGS *arg, char *buf)
181 if (arg->size == 0) {
183 arg->argv = app_malloc(sizeof(char *) * arg->size, "argv space");
184 if (arg->argv == NULL)
189 /* Skip whitespace. */
190 while (*p && isspace(*p))
195 /* The start of something good :-) */
196 if (arg->argc >= arg->size) {
198 arg->argv = OPENSSL_realloc(arg->argv, sizeof(char *) * arg->size);
199 if (arg->argv == NULL)
202 quoted = *p == '\'' || *p == '"';
205 arg->argv[arg->argc++] = p;
207 /* now look for the end of this */
209 while (*p && *p != c)
213 while (*p && !isspace(*p))
219 arg->argv[arg->argc] = NULL;
224 int app_init(long mesgwin)
230 int ctx_set_verify_locations(SSL_CTX *ctx,
231 const char *CAfile, const char *CApath)
233 if (CAfile == NULL && CApath == NULL)
234 return SSL_CTX_set_default_verify_paths(ctx);
235 return SSL_CTX_load_verify_locations(ctx, CAfile, CApath);
238 int dump_cert_text(BIO *out, X509 *x)
242 p = X509_NAME_oneline(X509_get_subject_name(x), NULL, 0);
243 BIO_puts(out, "subject=");
247 p = X509_NAME_oneline(X509_get_issuer_name(x), NULL, 0);
248 BIO_puts(out, "\nissuer=");
256 static int ui_open(UI *ui)
258 return UI_method_get_opener(UI_OpenSSL())(ui);
261 static int ui_read(UI *ui, UI_STRING *uis)
263 if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
264 && UI_get0_user_data(ui)) {
265 switch (UI_get_string_type(uis)) {
269 const char *password =
270 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
271 if (password && password[0] != '\0') {
272 UI_set_result(ui, uis, password);
280 return UI_method_get_reader(UI_OpenSSL())(ui, uis);
283 static int ui_write(UI *ui, UI_STRING *uis)
285 if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
286 && UI_get0_user_data(ui)) {
287 switch (UI_get_string_type(uis)) {
291 const char *password =
292 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
293 if (password && password[0] != '\0')
300 return UI_method_get_writer(UI_OpenSSL())(ui, uis);
303 static int ui_close(UI *ui)
305 return UI_method_get_closer(UI_OpenSSL())(ui);
308 int setup_ui_method(void)
310 ui_method = UI_create_method("OpenSSL application user interface");
311 UI_method_set_opener(ui_method, ui_open);
312 UI_method_set_reader(ui_method, ui_read);
313 UI_method_set_writer(ui_method, ui_write);
314 UI_method_set_closer(ui_method, ui_close);
318 void destroy_ui_method(void)
321 UI_destroy_method(ui_method);
326 int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp)
330 const char *prompt_info = NULL;
331 const char *password = NULL;
332 PW_CB_DATA *cb_data = (PW_CB_DATA *)cb_tmp;
335 if (cb_data->password)
336 password = cb_data->password;
337 if (cb_data->prompt_info)
338 prompt_info = cb_data->prompt_info;
342 res = strlen(password);
345 memcpy(buf, password, res);
349 ui = UI_new_method(ui_method);
356 prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
358 BIO_printf(bio_err, "Out of memory\n");
363 ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
364 UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
367 ok = UI_add_input_string(ui, prompt, ui_flags, buf,
368 PW_MIN_LENGTH, bufsiz - 1);
369 if (ok >= 0 && verify) {
370 buff = app_malloc(bufsiz, "password buffer");
371 ok = UI_add_verify_string(ui, prompt, ui_flags, buff,
372 PW_MIN_LENGTH, bufsiz - 1, buf);
378 while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
380 OPENSSL_clear_free(buff, (unsigned int)bufsiz);
385 BIO_printf(bio_err, "User interface error\n");
386 ERR_print_errors(bio_err);
387 OPENSSL_cleanse(buf, (unsigned int)bufsiz);
391 BIO_printf(bio_err, "aborted!\n");
392 OPENSSL_cleanse(buf, (unsigned int)bufsiz);
396 OPENSSL_free(prompt);
401 static char *app_get_pass(char *arg, int keepbio);
403 int app_passwd(char *arg1, char *arg2, char **pass1, char **pass2)
406 if (!arg2 || !arg1 || strcmp(arg1, arg2))
411 *pass1 = app_get_pass(arg1, same);
417 *pass2 = app_get_pass(arg2, same ? 2 : 0);
425 static char *app_get_pass(char *arg, int keepbio)
427 char *tmp, tpass[APP_PASS_LEN];
428 static BIO *pwdbio = NULL;
430 if (!strncmp(arg, "pass:", 5))
431 return BUF_strdup(arg + 5);
432 if (!strncmp(arg, "env:", 4)) {
433 tmp = getenv(arg + 4);
435 BIO_printf(bio_err, "Can't read environment variable %s\n", arg + 4);
438 return BUF_strdup(tmp);
440 if (!keepbio || !pwdbio) {
441 if (!strncmp(arg, "file:", 5)) {
442 pwdbio = BIO_new_file(arg + 5, "r");
444 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
449 * Under _WIN32, which covers even Win64 and CE, file
450 * descriptors referenced by BIO_s_fd are not inherited
451 * by child process and therefore below is not an option.
452 * It could have been an option if bss_fd.c was operating
453 * on real Windows descriptors, such as those obtained
456 } else if (!strncmp(arg, "fd:", 3)) {
460 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
461 if ((i < 0) || !pwdbio) {
462 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
466 * Can't do BIO_gets on an fd BIO so add a buffering BIO
468 btmp = BIO_new(BIO_f_buffer());
469 pwdbio = BIO_push(btmp, pwdbio);
471 } else if (!strcmp(arg, "stdin")) {
472 pwdbio = dup_bio_in();
474 BIO_printf(bio_err, "Can't open BIO for stdin\n");
478 BIO_printf(bio_err, "Invalid password argument \"%s\"\n", arg);
482 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
484 BIO_free_all(pwdbio);
488 BIO_printf(bio_err, "Error reading password from BIO\n");
491 tmp = strchr(tpass, '\n');
494 return BUF_strdup(tpass);
497 int add_oid_section(CONF *conf)
500 STACK_OF(CONF_VALUE) *sktmp;
503 if (!(p = NCONF_get_string(conf, NULL, "oid_section"))) {
507 if (!(sktmp = NCONF_get_section(conf, p))) {
508 BIO_printf(bio_err, "problem loading oid section %s\n", p);
511 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
512 cnf = sk_CONF_VALUE_value(sktmp, i);
513 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
514 BIO_printf(bio_err, "problem creating object %s=%s\n",
515 cnf->name, cnf->value);
522 static int load_pkcs12(BIO *in, const char *desc,
523 pem_password_cb *pem_cb, void *cb_data,
524 EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
527 char tpass[PEM_BUFSIZE];
530 p12 = d2i_PKCS12_bio(in, NULL);
532 BIO_printf(bio_err, "Error loading PKCS12 file for %s\n", desc);
535 /* See if an empty password will do */
536 if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0))
540 pem_cb = (pem_password_cb *)password_callback;
541 len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
543 BIO_printf(bio_err, "Passphrase callback error for %s\n", desc);
546 if (len < PEM_BUFSIZE)
548 if (!PKCS12_verify_mac(p12, tpass, len)) {
550 "Mac verify error (wrong password?) in PKCS12 file for %s\n",
556 ret = PKCS12_parse(p12, pass, pkey, cert, ca);
562 int load_cert_crl_http(const char *url, X509 **pcert, X509_CRL **pcrl)
564 char *host = NULL, *port = NULL, *path = NULL;
566 OCSP_REQ_CTX *rctx = NULL;
568 if (!OCSP_parse_url(url, &host, &port, &path, &use_ssl))
571 BIO_puts(bio_err, "https not supported\n");
574 bio = BIO_new_connect(host);
575 if (!bio || !BIO_set_conn_port(bio, port))
577 rctx = OCSP_REQ_CTX_new(bio, 1024);
580 if (!OCSP_REQ_CTX_http(rctx, "GET", path))
582 if (!OCSP_REQ_CTX_add1_header(rctx, "Host", host))
586 rv = X509_http_nbio(rctx, pcert);
590 rv = X509_CRL_http_nbio(rctx, pcrl);
600 OCSP_REQ_CTX_free(rctx);
602 BIO_printf(bio_err, "Error loading %s from %s\n",
603 pcert ? "certificate" : "CRL", url);
604 ERR_print_errors(bio_err);
609 X509 *load_cert(const char *file, int format,
610 const char *pass, ENGINE *e, const char *cert_descrip)
615 if (format == FORMAT_HTTP) {
616 load_cert_crl_http(file, &x, NULL);
624 cert = bio_open_default(file, RB(format));
628 if (format == FORMAT_ASN1)
629 x = d2i_X509_bio(cert, NULL);
630 else if (format == FORMAT_NETSCAPE) {
632 nx = ASN1_item_d2i_bio(ASN1_ITEM_rptr(NETSCAPE_X509), cert, NULL);
636 if ((strncmp(NETSCAPE_CERT_HDR, (char *)nx->header->data,
637 nx->header->length) != 0)) {
638 NETSCAPE_X509_free(nx);
639 BIO_printf(bio_err, "Error reading header on certificate\n");
644 NETSCAPE_X509_free(nx);
645 } else if (format == FORMAT_PEM)
646 x = PEM_read_bio_X509_AUX(cert, NULL,
647 (pem_password_cb *)password_callback, NULL);
648 else if (format == FORMAT_PKCS12) {
649 if (!load_pkcs12(cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
652 BIO_printf(bio_err, "bad input format specified for %s\n", cert_descrip);
657 BIO_printf(bio_err, "unable to load certificate\n");
658 ERR_print_errors(bio_err);
664 X509_CRL *load_crl(const char *infile, int format)
669 if (format == FORMAT_HTTP) {
670 load_cert_crl_http(infile, NULL, &x);
674 in = bio_open_default(infile, RB(format));
677 if (format == FORMAT_ASN1)
678 x = d2i_X509_CRL_bio(in, NULL);
679 else if (format == FORMAT_PEM)
680 x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
682 BIO_printf(bio_err, "bad input format specified for input crl\n");
686 BIO_printf(bio_err, "unable to load CRL\n");
687 ERR_print_errors(bio_err);
696 EVP_PKEY *load_key(const char *file, int format, int maybe_stdin,
697 const char *pass, ENGINE *e, const char *key_descrip)
700 EVP_PKEY *pkey = NULL;
703 cb_data.password = pass;
704 cb_data.prompt_info = file;
706 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
707 BIO_printf(bio_err, "no keyfile specified\n");
710 #ifndef OPENSSL_NO_ENGINE
711 if (format == FORMAT_ENGINE) {
713 BIO_printf(bio_err, "no engine specified\n");
715 pkey = ENGINE_load_private_key(e, file, ui_method, &cb_data);
717 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
718 ERR_print_errors(bio_err);
724 if (file == NULL && maybe_stdin) {
728 key = bio_open_default(file, RB(format));
731 if (format == FORMAT_ASN1) {
732 pkey = d2i_PrivateKey_bio(key, NULL);
733 } else if (format == FORMAT_PEM) {
734 pkey = PEM_read_bio_PrivateKey(key, NULL,
735 (pem_password_cb *)password_callback,
738 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
739 else if (format == FORMAT_NETSCAPE)
740 pkey = load_netscape_key(key, file, key_descrip, format);
742 else if (format == FORMAT_PKCS12) {
743 if (!load_pkcs12(key, key_descrip,
744 (pem_password_cb *)password_callback, &cb_data,
748 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
749 else if (format == FORMAT_MSBLOB)
750 pkey = b2i_PrivateKey_bio(key);
751 else if (format == FORMAT_PVK)
752 pkey = b2i_PVK_bio(key, (pem_password_cb *)password_callback,
756 BIO_printf(bio_err, "bad input format specified for key file\n");
762 BIO_printf(bio_err, "unable to load %s\n", key_descrip);
763 ERR_print_errors(bio_err);
768 static const char *key_file_format(int format)
770 if (format == FORMAT_PEM || format == FORMAT_PEMRSA)
775 EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin,
776 const char *pass, ENGINE *e, const char *key_descrip)
779 EVP_PKEY *pkey = NULL;
782 cb_data.password = pass;
783 cb_data.prompt_info = file;
785 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
786 BIO_printf(bio_err, "no keyfile specified\n");
789 #ifndef OPENSSL_NO_ENGINE
790 if (format == FORMAT_ENGINE) {
792 BIO_printf(bio_err, "no engine specified\n");
794 pkey = ENGINE_load_public_key(e, file, ui_method, &cb_data);
798 if (file == NULL && maybe_stdin) {
802 key = bio_open_default(file, key_file_format(format));
805 if (format == FORMAT_ASN1) {
806 pkey = d2i_PUBKEY_bio(key, NULL);
808 #ifndef OPENSSL_NO_RSA
809 else if (format == FORMAT_ASN1RSA) {
811 rsa = d2i_RSAPublicKey_bio(key, NULL);
813 pkey = EVP_PKEY_new();
815 EVP_PKEY_set1_RSA(pkey, rsa);
819 } else if (format == FORMAT_PEMRSA) {
821 rsa = PEM_read_bio_RSAPublicKey(key, NULL,
822 (pem_password_cb *)password_callback,
825 pkey = EVP_PKEY_new();
827 EVP_PKEY_set1_RSA(pkey, rsa);
833 else if (format == FORMAT_PEM) {
834 pkey = PEM_read_bio_PUBKEY(key, NULL,
835 (pem_password_cb *)password_callback,
838 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
839 else if (format == FORMAT_NETSCAPE)
840 pkey = load_netscape_key(key, file, key_descrip, format);
842 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
843 else if (format == FORMAT_MSBLOB)
844 pkey = b2i_PublicKey_bio(key);
849 BIO_printf(bio_err, "unable to load %s\n", key_descrip);
853 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
854 static EVP_PKEY *load_netscape_key(BIO *key, const char *file,
855 const char *key_descrip, int format)
860 const unsigned char *p;
864 pkey = EVP_PKEY_new();
866 if (buf == NULL || pkey == NULL)
869 if (!BUF_MEM_grow_clean(buf, size + 1024 * 10))
871 i = BIO_read(key, &(buf->data[size]), 1024 * 10);
876 BIO_printf(bio_err, "Error reading %s %s", key_descrip, file);
880 p = (unsigned char *)buf->data;
881 rsa = d2i_RSA_NET(NULL, &p, (long)size, NULL, 0);
885 EVP_PKEY_set1_RSA(pkey, rsa);
892 #endif /* ndef OPENSSL_NO_RC4 */
894 static int load_certs_crls(const char *file, int format,
895 const char *pass, ENGINE *e, const char *desc,
896 STACK_OF(X509) **pcerts,
897 STACK_OF(X509_CRL) **pcrls)
901 STACK_OF(X509_INFO) *xis = NULL;
906 cb_data.password = pass;
907 cb_data.prompt_info = file;
909 if (format != FORMAT_PEM) {
910 BIO_printf(bio_err, "bad input format specified for %s\n", desc);
914 bio = bio_open_default(file, "r");
918 xis = PEM_X509_INFO_read_bio(bio, NULL,
919 (pem_password_cb *)password_callback,
925 *pcerts = sk_X509_new_null();
931 *pcrls = sk_X509_CRL_new_null();
936 for (i = 0; i < sk_X509_INFO_num(xis); i++) {
937 xi = sk_X509_INFO_value(xis, i);
938 if (xi->x509 && pcerts) {
939 if (!sk_X509_push(*pcerts, xi->x509))
943 if (xi->crl && pcrls) {
944 if (!sk_X509_CRL_push(*pcrls, xi->crl))
950 if (pcerts && sk_X509_num(*pcerts) > 0)
953 if (pcrls && sk_X509_CRL_num(*pcrls) > 0)
958 sk_X509_INFO_pop_free(xis, X509_INFO_free);
962 sk_X509_pop_free(*pcerts, X509_free);
966 sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
969 BIO_printf(bio_err, "unable to load %s\n",
970 pcerts ? "certificates" : "CRLs");
971 ERR_print_errors(bio_err);
976 void* app_malloc(int sz, const char *what)
978 void *vp = OPENSSL_malloc(sz);
981 BIO_printf(bio_err, "%s: Could not allocate %d bytes for %s\n",
982 opt_getprog(), sz, what);
983 ERR_print_errors(bio_err);
991 STACK_OF(X509) *load_certs(const char *file, int format,
992 const char *pass, ENGINE *e, const char *desc)
994 STACK_OF(X509) *certs;
995 if (!load_certs_crls(file, format, pass, e, desc, &certs, NULL))
1000 STACK_OF(X509_CRL) *load_crls(const char *file, int format,
1001 const char *pass, ENGINE *e, const char *desc)
1003 STACK_OF(X509_CRL) *crls;
1004 if (!load_certs_crls(file, format, pass, e, desc, NULL, &crls))
1009 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
1010 /* Return error for unknown extensions */
1011 #define X509V3_EXT_DEFAULT 0
1012 /* Print error for unknown extensions */
1013 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
1014 /* ASN1 parse unknown extensions */
1015 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
1016 /* BIO_dump unknown extensions */
1017 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
1019 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1020 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1022 int set_cert_ex(unsigned long *flags, const char *arg)
1024 static const NAME_EX_TBL cert_tbl[] = {
1025 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
1026 {"ca_default", X509_FLAG_CA, 0xffffffffl},
1027 {"no_header", X509_FLAG_NO_HEADER, 0},
1028 {"no_version", X509_FLAG_NO_VERSION, 0},
1029 {"no_serial", X509_FLAG_NO_SERIAL, 0},
1030 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
1031 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
1032 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
1033 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1034 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1035 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1036 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1037 {"no_aux", X509_FLAG_NO_AUX, 0},
1038 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1039 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1040 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1041 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1042 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1045 return set_multi_opts(flags, arg, cert_tbl);
1048 int set_name_ex(unsigned long *flags, const char *arg)
1050 static const NAME_EX_TBL ex_tbl[] = {
1051 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1052 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1053 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1054 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1055 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1056 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1057 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1058 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1059 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1060 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1061 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1062 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1063 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1064 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1065 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1066 {"dn_rev", XN_FLAG_DN_REV, 0},
1067 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1068 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1069 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1070 {"align", XN_FLAG_FN_ALIGN, 0},
1071 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1072 {"space_eq", XN_FLAG_SPC_EQ, 0},
1073 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1074 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1075 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1076 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1077 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1080 return set_multi_opts(flags, arg, ex_tbl);
1083 int set_ext_copy(int *copy_type, const char *arg)
1085 if (!strcasecmp(arg, "none"))
1086 *copy_type = EXT_COPY_NONE;
1087 else if (!strcasecmp(arg, "copy"))
1088 *copy_type = EXT_COPY_ADD;
1089 else if (!strcasecmp(arg, "copyall"))
1090 *copy_type = EXT_COPY_ALL;
1096 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1098 STACK_OF(X509_EXTENSION) *exts = NULL;
1099 X509_EXTENSION *ext, *tmpext;
1101 int i, idx, ret = 0;
1102 if (!x || !req || (copy_type == EXT_COPY_NONE))
1104 exts = X509_REQ_get_extensions(req);
1106 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1107 ext = sk_X509_EXTENSION_value(exts, i);
1108 obj = X509_EXTENSION_get_object(ext);
1109 idx = X509_get_ext_by_OBJ(x, obj, -1);
1110 /* Does extension exist? */
1112 /* If normal copy don't override existing extension */
1113 if (copy_type == EXT_COPY_ADD)
1115 /* Delete all extensions of same type */
1117 tmpext = X509_get_ext(x, idx);
1118 X509_delete_ext(x, idx);
1119 X509_EXTENSION_free(tmpext);
1120 idx = X509_get_ext_by_OBJ(x, obj, -1);
1121 } while (idx != -1);
1123 if (!X509_add_ext(x, ext, -1))
1131 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1136 static int set_multi_opts(unsigned long *flags, const char *arg,
1137 const NAME_EX_TBL * in_tbl)
1139 STACK_OF(CONF_VALUE) *vals;
1144 vals = X509V3_parse_list(arg);
1145 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1146 val = sk_CONF_VALUE_value(vals, i);
1147 if (!set_table_opts(flags, val->name, in_tbl))
1150 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1154 static int set_table_opts(unsigned long *flags, const char *arg,
1155 const NAME_EX_TBL * in_tbl)
1158 const NAME_EX_TBL *ptbl;
1164 } else if (c == '+') {
1170 for (ptbl = in_tbl; ptbl->name; ptbl++) {
1171 if (!strcasecmp(arg, ptbl->name)) {
1172 *flags &= ~ptbl->mask;
1174 *flags |= ptbl->flag;
1176 *flags &= ~ptbl->flag;
1183 void print_name(BIO *out, const char *title, X509_NAME *nm,
1184 unsigned long lflags)
1191 BIO_puts(out, title);
1192 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1196 if (lflags == XN_FLAG_COMPAT) {
1197 buf = X509_NAME_oneline(nm, 0, 0);
1199 BIO_puts(out, "\n");
1203 BIO_puts(out, "\n");
1204 X509_NAME_print_ex(out, nm, indent, lflags);
1205 BIO_puts(out, "\n");
1209 void print_bignum_var(BIO *out, BIGNUM *in, const char *var,
1210 int len, unsigned char *buffer)
1212 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1214 BIO_printf(out, "\n\t0x00");
1218 l = BN_bn2bin(in, buffer);
1219 for (i = 0; i < l; i++) {
1221 BIO_printf(out, "\n\t");
1223 BIO_printf(out, "0x%02X, ", buffer[i]);
1225 BIO_printf(out, "0x%02X", buffer[i]);
1228 BIO_printf(out, "\n };\n");
1230 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1234 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1235 for (i = 0; i < len; i++) {
1237 BIO_printf(out, "\n ");
1239 BIO_printf(out, "0x%02X, ", d[i]);
1241 BIO_printf(out, "0x%02X", d[i]);
1243 BIO_printf(out, "\n};\n");
1246 X509_STORE *setup_verify(char *CAfile, char *CApath)
1248 X509_STORE *store = X509_STORE_new();
1249 X509_LOOKUP *lookup;
1253 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1257 if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1258 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1262 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1264 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1268 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1269 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1273 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1278 X509_STORE_free(store);
1282 #ifndef OPENSSL_NO_ENGINE
1283 /* Try to load an engine in a shareable library */
1284 static ENGINE *try_load_engine(const char *engine, int debug)
1286 ENGINE *e = ENGINE_by_id("dynamic");
1288 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1289 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1297 ENGINE *setup_engine(const char *engine, int debug)
1302 if (strcmp(engine, "auto") == 0) {
1303 BIO_printf(bio_err, "enabling auto ENGINE support\n");
1304 ENGINE_register_all_complete();
1307 if ((e = ENGINE_by_id(engine)) == NULL
1308 && (e = try_load_engine(engine, debug)) == NULL) {
1309 BIO_printf(bio_err, "invalid engine \"%s\"\n", engine);
1310 ERR_print_errors(bio_err);
1314 ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1316 ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
1317 if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1318 BIO_printf(bio_err, "can't use that engine\n");
1319 ERR_print_errors(bio_err);
1324 BIO_printf(bio_err, "engine \"%s\" set.\n", ENGINE_get_id(e));
1326 /* Free our "structural" reference. */
1333 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1340 return (lh_strhash(n));
1343 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1344 const OPENSSL_CSTRING *b)
1346 const char *aa, *bb;
1348 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1349 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1350 return (strcmp(aa, bb));
1353 static int index_name_qual(char **a)
1355 return (a[0][0] == 'V');
1358 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1360 return (lh_strhash(a[DB_name]));
1363 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1365 return (strcmp(a[DB_name], b[DB_name]));
1368 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1369 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1370 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1371 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1374 BIGNUM *load_serial(char *serialfile, int create, ASN1_INTEGER **retai)
1379 ASN1_INTEGER *ai = NULL;
1381 ai = ASN1_INTEGER_new();
1385 in = BIO_new_file(serialfile, "r");
1393 if (ret == NULL || !rand_serial(ret, ai))
1394 BIO_printf(bio_err, "Out of memory\n");
1396 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1397 BIO_printf(bio_err, "unable to load number from %s\n",
1401 ret = ASN1_INTEGER_to_BN(ai, NULL);
1404 "error converting number from bin to BIGNUM\n");
1415 ASN1_INTEGER_free(ai);
1419 int save_serial(char *serialfile, char *suffix, BIGNUM *serial,
1420 ASN1_INTEGER **retai)
1425 ASN1_INTEGER *ai = NULL;
1429 j = strlen(serialfile);
1431 j = strlen(serialfile) + strlen(suffix) + 1;
1433 BIO_printf(bio_err, "file name too long\n");
1438 BUF_strlcpy(buf[0], serialfile, BSIZE);
1440 #ifndef OPENSSL_SYS_VMS
1441 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, suffix);
1443 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, suffix);
1447 BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1449 out = BIO_new_file(buf[0], "w");
1451 ERR_print_errors(bio_err);
1455 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1456 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1459 i2a_ASN1_INTEGER(out, ai);
1460 BIO_puts(out, "\n");
1468 ASN1_INTEGER_free(ai);
1472 int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
1477 i = strlen(serialfile) + strlen(old_suffix);
1478 j = strlen(serialfile) + strlen(new_suffix);
1481 if (j + 1 >= BSIZE) {
1482 BIO_printf(bio_err, "file name too long\n");
1485 #ifndef OPENSSL_SYS_VMS
1486 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, new_suffix);
1488 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, new_suffix);
1490 #ifndef OPENSSL_SYS_VMS
1491 j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", serialfile, old_suffix);
1493 j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", serialfile, old_suffix);
1496 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1497 serialfile, buf[1]);
1499 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1505 "unable to rename %s to %s\n", serialfile, buf[1]);
1510 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1511 buf[0], serialfile);
1513 if (rename(buf[0], serialfile) < 0) {
1515 "unable to rename %s to %s\n", buf[0], serialfile);
1517 rename(buf[1], serialfile);
1525 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1538 if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
1540 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1553 CA_DB *load_index(char *dbfile, DB_ATTR *db_attr)
1555 CA_DB *retdb = NULL;
1556 TXT_DB *tmpdb = NULL;
1558 CONF *dbattr_conf = NULL;
1560 long errorline = -1;
1562 in = BIO_new_file(dbfile, "r");
1564 ERR_print_errors(bio_err);
1567 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1570 #ifndef OPENSSL_SYS_VMS
1571 BIO_snprintf(buf[0], sizeof buf[0], "%s.attr", dbfile);
1573 BIO_snprintf(buf[0], sizeof buf[0], "%s-attr", dbfile);
1575 dbattr_conf = NCONF_new(NULL);
1576 if (NCONF_load(dbattr_conf, buf[0], &errorline) <= 0) {
1577 if (errorline > 0) {
1579 "error on line %ld of db attribute file '%s'\n",
1583 NCONF_free(dbattr_conf);
1588 retdb = app_malloc(sizeof *retdb, "new DB");
1592 retdb->attributes = *db_attr;
1594 retdb->attributes.unique_subject = 1;
1598 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1602 "DEBUG[load_index]: unique_subject = \"%s\"\n", p);
1604 retdb->attributes.unique_subject = parse_yesno(p, 1);
1609 NCONF_free(dbattr_conf);
1615 int index_index(CA_DB *db)
1617 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1618 LHASH_HASH_FN(index_serial),
1619 LHASH_COMP_FN(index_serial))) {
1621 "error creating serial number index:(%ld,%ld,%ld)\n",
1622 db->db->error, db->db->arg1, db->db->arg2);
1626 if (db->attributes.unique_subject
1627 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1628 LHASH_HASH_FN(index_name),
1629 LHASH_COMP_FN(index_name))) {
1630 BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
1631 db->db->error, db->db->arg1, db->db->arg2);
1637 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1643 j = strlen(dbfile) + strlen(suffix);
1644 if (j + 6 >= BSIZE) {
1645 BIO_printf(bio_err, "file name too long\n");
1648 #ifndef OPENSSL_SYS_VMS
1649 j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr", dbfile);
1651 j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr", dbfile);
1653 #ifndef OPENSSL_SYS_VMS
1654 j = BIO_snprintf(buf[1], sizeof buf[1], "%s.attr.%s", dbfile, suffix);
1656 j = BIO_snprintf(buf[1], sizeof buf[1], "%s-attr-%s", dbfile, suffix);
1658 #ifndef OPENSSL_SYS_VMS
1659 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, suffix);
1661 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, suffix);
1664 BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1666 out = BIO_new_file(buf[0], "w");
1669 BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1672 j = TXT_DB_write(out, db->db);
1677 out = BIO_new_file(buf[1], "w");
1679 BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[1]);
1683 BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
1686 BIO_printf(out, "unique_subject = %s\n",
1687 db->attributes.unique_subject ? "yes" : "no");
1695 int rotate_index(const char *dbfile, const char *new_suffix,
1696 const char *old_suffix)
1701 i = strlen(dbfile) + strlen(old_suffix);
1702 j = strlen(dbfile) + strlen(new_suffix);
1705 if (j + 6 >= BSIZE) {
1706 BIO_printf(bio_err, "file name too long\n");
1709 #ifndef OPENSSL_SYS_VMS
1710 j = BIO_snprintf(buf[4], sizeof buf[4], "%s.attr", dbfile);
1712 j = BIO_snprintf(buf[4], sizeof buf[4], "%s-attr", dbfile);
1714 #ifndef OPENSSL_SYS_VMS
1715 j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr.%s", dbfile, new_suffix);
1717 j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr-%s", dbfile, new_suffix);
1719 #ifndef OPENSSL_SYS_VMS
1720 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, new_suffix);
1722 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, new_suffix);
1724 #ifndef OPENSSL_SYS_VMS
1725 j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", dbfile, old_suffix);
1727 j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", dbfile, old_suffix);
1729 #ifndef OPENSSL_SYS_VMS
1730 j = BIO_snprintf(buf[3], sizeof buf[3], "%s.attr.%s", dbfile, old_suffix);
1732 j = BIO_snprintf(buf[3], sizeof buf[3], "%s-attr-%s", dbfile, old_suffix);
1735 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", dbfile, buf[1]);
1737 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1742 BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
1747 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[0], dbfile);
1749 if (rename(buf[0], dbfile) < 0) {
1750 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
1752 rename(buf[1], dbfile);
1756 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[4], buf[3]);
1758 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1763 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
1765 rename(dbfile, buf[0]);
1766 rename(buf[1], dbfile);
1770 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[2], buf[4]);
1772 if (rename(buf[2], buf[4]) < 0) {
1773 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
1775 rename(buf[3], buf[4]);
1776 rename(dbfile, buf[0]);
1777 rename(buf[1], dbfile);
1785 void free_index(CA_DB *db)
1788 TXT_DB_free(db->db);
1793 int parse_yesno(const char *str, int def)
1797 case 'f': /* false */
1798 case 'F': /* FALSE */
1803 case 't': /* true */
1804 case 'T': /* TRUE */
1815 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1816 * where characters may be escaped by \
1818 X509_NAME *parse_name(const char *cp, long chtype, int canmulti)
1820 int nextismulti = 0;
1827 n = X509_NAME_new();
1830 work = OPENSSL_strdup(cp);
1837 unsigned char *valstr;
1839 int ismulti = nextismulti;
1842 /* Collect the type */
1843 while (*cp && *cp != '=')
1847 "%s: Hit end of string before finding the equals.\n",
1854 /* Collect the value. */
1855 valstr = (unsigned char *)bp;
1856 for (; *cp && *cp != '/'; *bp++ = *cp++) {
1857 if (canmulti && *cp == '+') {
1861 if (*cp == '\\' && *++cp == '\0') {
1863 "%s: escape character at end of string\n",
1870 /* If not at EOS (must be + or /), move forward. */
1875 nid = OBJ_txt2nid(typestr);
1876 if (nid == NID_undef) {
1877 BIO_printf(bio_err, "%s: Skipping unknown attribute \"%s\"\n",
1878 opt_getprog(), typestr);
1881 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1882 valstr, strlen((char *)valstr),
1883 -1, ismulti ? -1 : 0))
1897 * Read whole contents of a BIO into an allocated memory buffer and return
1901 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1905 unsigned char tbuf[1024];
1906 mem = BIO_new(BIO_s_mem());
1910 if ((maxlen != -1) && maxlen < 1024)
1914 len = BIO_read(in, tbuf, len);
1917 if (BIO_write(mem, tbuf, len) != len) {
1926 ret = BIO_get_mem_data(mem, (char **)out);
1927 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1932 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, char *value)
1935 char *stmp, *vtmp = NULL;
1936 stmp = BUF_strdup(value);
1939 vtmp = strchr(stmp, ':');
1944 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1949 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1951 X509_POLICY_NODE *node;
1954 BIO_printf(bio_err, "%s Policies:", name);
1956 BIO_puts(bio_err, "\n");
1957 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1958 node = sk_X509_POLICY_NODE_value(nodes, i);
1959 X509_POLICY_NODE_print(bio_err, node, 2);
1962 BIO_puts(bio_err, " <empty>\n");
1965 void policies_print(X509_STORE_CTX *ctx)
1967 X509_POLICY_TREE *tree;
1968 int explicit_policy;
1969 tree = X509_STORE_CTX_get0_policy_tree(ctx);
1970 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1972 BIO_printf(bio_err, "Require explicit Policy: %s\n",
1973 explicit_policy ? "True" : "False");
1975 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1976 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1979 #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
1981 static JPAKE_CTX *jpake_init(const char *us, const char *them,
1987 BIGNUM *bnsecret = BN_new();
1990 /* Use a safe prime for p (that we found earlier) */
1992 "F9E5B365665EA7A05A9C534502780FEE6F1AB5BD4F49947FD036DBD7E905269AF46EF28B0FC07487EE4F5D20FB3C0AF8E700F3A2FA3414970CBED44FEDFF80CE78D800F184BB82435D137AADA2C6C16523247930A63B85661D1FC817A51ACD96168E95898A1F83A79FFB529368AA7833ABD1B0C3AEDDB14D2E1A2F71D99F763F");
1998 BN_bin2bn((const unsigned char *)secret, strlen(secret), bnsecret);
2000 ctx = JPAKE_CTX_new(us, them, p, g, q, bnsecret);
2009 static void jpake_send_part(BIO *conn, const JPAKE_STEP_PART *p)
2011 BN_print(conn, p->gx);
2012 BIO_puts(conn, "\n");
2013 BN_print(conn, p->zkpx.gr);
2014 BIO_puts(conn, "\n");
2015 BN_print(conn, p->zkpx.b);
2016 BIO_puts(conn, "\n");
2019 static void jpake_send_step1(BIO *bconn, JPAKE_CTX *ctx)
2023 JPAKE_STEP1_init(&s1);
2024 JPAKE_STEP1_generate(&s1, ctx);
2025 jpake_send_part(bconn, &s1.p1);
2026 jpake_send_part(bconn, &s1.p2);
2027 (void)BIO_flush(bconn);
2028 JPAKE_STEP1_release(&s1);
2031 static void jpake_send_step2(BIO *bconn, JPAKE_CTX *ctx)
2035 JPAKE_STEP2_init(&s2);
2036 JPAKE_STEP2_generate(&s2, ctx);
2037 jpake_send_part(bconn, &s2);
2038 (void)BIO_flush(bconn);
2039 JPAKE_STEP2_release(&s2);
2042 static void jpake_send_step3a(BIO *bconn, JPAKE_CTX *ctx)
2046 JPAKE_STEP3A_init(&s3a);
2047 JPAKE_STEP3A_generate(&s3a, ctx);
2048 BIO_write(bconn, s3a.hhk, sizeof s3a.hhk);
2049 (void)BIO_flush(bconn);
2050 JPAKE_STEP3A_release(&s3a);
2053 static void jpake_send_step3b(BIO *bconn, JPAKE_CTX *ctx)
2057 JPAKE_STEP3B_init(&s3b);
2058 JPAKE_STEP3B_generate(&s3b, ctx);
2059 BIO_write(bconn, s3b.hk, sizeof s3b.hk);
2060 (void)BIO_flush(bconn);
2061 JPAKE_STEP3B_release(&s3b);
2064 static void readbn(BIGNUM **bn, BIO *bconn)
2069 l = BIO_gets(bconn, buf, sizeof buf);
2071 assert(buf[l - 1] == '\n');
2076 static void jpake_receive_part(JPAKE_STEP_PART *p, BIO *bconn)
2078 readbn(&p->gx, bconn);
2079 readbn(&p->zkpx.gr, bconn);
2080 readbn(&p->zkpx.b, bconn);
2083 static void jpake_receive_step1(JPAKE_CTX *ctx, BIO *bconn)
2087 JPAKE_STEP1_init(&s1);
2088 jpake_receive_part(&s1.p1, bconn);
2089 jpake_receive_part(&s1.p2, bconn);
2090 if (!JPAKE_STEP1_process(ctx, &s1)) {
2091 ERR_print_errors(bio_err);
2094 JPAKE_STEP1_release(&s1);
2097 static void jpake_receive_step2(JPAKE_CTX *ctx, BIO *bconn)
2101 JPAKE_STEP2_init(&s2);
2102 jpake_receive_part(&s2, bconn);
2103 if (!JPAKE_STEP2_process(ctx, &s2)) {
2104 ERR_print_errors(bio_err);
2107 JPAKE_STEP2_release(&s2);
2110 static void jpake_receive_step3a(JPAKE_CTX *ctx, BIO *bconn)
2115 JPAKE_STEP3A_init(&s3a);
2116 l = BIO_read(bconn, s3a.hhk, sizeof s3a.hhk);
2117 assert(l == sizeof s3a.hhk);
2118 if (!JPAKE_STEP3A_process(ctx, &s3a)) {
2119 ERR_print_errors(bio_err);
2122 JPAKE_STEP3A_release(&s3a);
2125 static void jpake_receive_step3b(JPAKE_CTX *ctx, BIO *bconn)
2130 JPAKE_STEP3B_init(&s3b);
2131 l = BIO_read(bconn, s3b.hk, sizeof s3b.hk);
2132 assert(l == sizeof s3b.hk);
2133 if (!JPAKE_STEP3B_process(ctx, &s3b)) {
2134 ERR_print_errors(bio_err);
2137 JPAKE_STEP3B_release(&s3b);
2140 void jpake_client_auth(BIO *out, BIO *conn, const char *secret)
2145 BIO_puts(out, "Authenticating with JPAKE\n");
2147 ctx = jpake_init("client", "server", secret);
2149 bconn = BIO_new(BIO_f_buffer());
2150 BIO_push(bconn, conn);
2152 jpake_send_step1(bconn, ctx);
2153 jpake_receive_step1(ctx, bconn);
2154 jpake_send_step2(bconn, ctx);
2155 jpake_receive_step2(ctx, bconn);
2156 jpake_send_step3a(bconn, ctx);
2157 jpake_receive_step3b(ctx, bconn);
2159 BIO_puts(out, "JPAKE authentication succeeded, setting PSK\n");
2161 OPENSSL_free(psk_key);
2162 psk_key = BN_bn2hex(JPAKE_get_shared_key(ctx));
2167 JPAKE_CTX_free(ctx);
2170 void jpake_server_auth(BIO *out, BIO *conn, const char *secret)
2175 BIO_puts(out, "Authenticating with JPAKE\n");
2177 ctx = jpake_init("server", "client", secret);
2179 bconn = BIO_new(BIO_f_buffer());
2180 BIO_push(bconn, conn);
2182 jpake_receive_step1(ctx, bconn);
2183 jpake_send_step1(bconn, ctx);
2184 jpake_receive_step2(ctx, bconn);
2185 jpake_send_step2(bconn, ctx);
2186 jpake_receive_step3a(ctx, bconn);
2187 jpake_send_step3b(bconn, ctx);
2189 BIO_puts(out, "JPAKE authentication succeeded, setting PSK\n");
2191 OPENSSL_free(psk_key);
2192 psk_key = BN_bn2hex(JPAKE_get_shared_key(ctx));
2197 JPAKE_CTX_free(ctx);
2202 #ifndef OPENSSL_NO_TLSEXT
2204 * next_protos_parse parses a comma separated list of strings into a string
2205 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
2206 * outlen: (output) set to the length of the resulting buffer on success.
2207 * err: (maybe NULL) on failure, an error message line is written to this BIO.
2208 * in: a NUL termianted string like "abc,def,ghi"
2210 * returns: a malloced buffer or NULL on failure.
2212 unsigned char *next_protos_parse(unsigned short *outlen, const char *in)
2216 size_t i, start = 0;
2222 out = app_malloc(strlen(in) + 1, "NPN buffer");
2223 for (i = 0; i <= len; ++i) {
2224 if (i == len || in[i] == ',') {
2225 if (i - start > 255) {
2229 out[start] = i - start;
2238 #endif /* ndef OPENSSL_NO_TLSEXT */
2240 void print_cert_checks(BIO *bio, X509 *x,
2241 const char *checkhost,
2242 const char *checkemail, const char *checkip)
2247 BIO_printf(bio, "Hostname %s does%s match certificate\n",
2249 X509_check_host(x, checkhost, 0, 0, NULL) == 1
2254 BIO_printf(bio, "Email %s does%s match certificate\n",
2255 checkemail, X509_check_email(x, checkemail, 0, 0)
2260 BIO_printf(bio, "IP %s does%s match certificate\n",
2261 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
2265 /* Get first http URL from a DIST_POINT structure */
2267 static const char *get_dp_url(DIST_POINT *dp)
2269 GENERAL_NAMES *gens;
2273 if (!dp->distpoint || dp->distpoint->type != 0)
2275 gens = dp->distpoint->name.fullname;
2276 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2277 gen = sk_GENERAL_NAME_value(gens, i);
2278 uri = GENERAL_NAME_get0_value(gen, >ype);
2279 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
2280 char *uptr = (char *)ASN1_STRING_data(uri);
2281 if (!strncmp(uptr, "http://", 7))
2289 * Look through a CRLDP structure and attempt to find an http URL to
2290 * downloads a CRL from.
2293 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
2296 const char *urlptr = NULL;
2297 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2298 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
2299 urlptr = get_dp_url(dp);
2301 return load_crl(urlptr, FORMAT_HTTP);
2307 * Example of downloading CRLs from CRLDP: not usable for real world as it
2308 * always downloads, doesn't support non-blocking I/O and doesn't cache
2312 static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
2315 STACK_OF(X509_CRL) *crls = NULL;
2317 STACK_OF(DIST_POINT) *crldp;
2319 crls = sk_X509_CRL_new_null();
2322 x = X509_STORE_CTX_get_current_cert(ctx);
2323 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2324 crl = load_crl_crldp(crldp);
2325 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2328 sk_X509_CRL_push(crls, crl);
2329 /* Try to download delta CRL */
2330 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2331 crl = load_crl_crldp(crldp);
2332 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2334 sk_X509_CRL_push(crls, crl);
2338 void store_setup_crl_download(X509_STORE *st)
2340 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2344 * Platform-specific sections
2349 # define fileno(a) (int)_fileno(a)
2352 # include <windows.h>
2355 static int WIN32_rename(const char *from, const char *to)
2357 TCHAR *tfrom = NULL, *tto;
2361 if (sizeof(TCHAR) == 1) {
2362 tfrom = (TCHAR *)from;
2364 } else { /* UNICODE path */
2366 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2367 tfrom = (TCHAR *)malloc(sizeof(TCHAR) * (flen + tlen));
2371 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2372 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2374 for (i = 0; i < flen; i++)
2375 tfrom[i] = (TCHAR)from[i];
2376 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2377 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2379 for (i = 0; i < tlen; i++)
2380 tto[i] = (TCHAR)to[i];
2383 if (MoveFile(tfrom, tto))
2385 err = GetLastError();
2386 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2387 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2389 err = GetLastError();
2391 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2393 else if (err == ERROR_ACCESS_DENIED)
2396 errno = EINVAL; /* we could map more codes... */
2400 if (tfrom != NULL && tfrom != (TCHAR *)from)
2406 /* app_tminterval section */
2408 double app_tminterval(int stop, int usertime)
2412 static ULARGE_INTEGER tmstart;
2413 static int warning = 1;
2414 # ifdef _WIN32_WINNT
2415 static HANDLE proc = NULL;
2419 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2420 GetCurrentProcessId());
2422 proc = (HANDLE) - 1;
2425 if (usertime && proc != (HANDLE) - 1) {
2427 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2433 if (usertime && warning) {
2434 BIO_printf(bio_err, "To get meaningful results, run "
2435 "this program on idle system.\n");
2438 GetSystemTime(&systime);
2439 SystemTimeToFileTime(&systime, &now);
2442 if (stop == TM_START) {
2443 tmstart.u.LowPart = now.dwLowDateTime;
2444 tmstart.u.HighPart = now.dwHighDateTime;
2446 ULARGE_INTEGER tmstop;
2448 tmstop.u.LowPart = now.dwLowDateTime;
2449 tmstop.u.HighPart = now.dwHighDateTime;
2451 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2456 #elif defined(OPENSSL_SYS_NETWARE)
2459 double app_tminterval(int stop, int usertime)
2461 static clock_t tmstart;
2462 static int warning = 1;
2465 if (usertime && warning) {
2466 BIO_printf(bio_err, "To get meaningful results, run "
2467 "this program on idle system.\n");
2471 if (stop == TM_START)
2474 ret = (clock() - tmstart) / (double)CLOCKS_PER_SEC;
2480 #elif defined(OPENSSL_SYSTEM_VXWORKS)
2483 double app_tminterval(int stop, int usertime)
2486 # ifdef CLOCK_REALTIME
2487 static struct timespec tmstart;
2488 struct timespec now;
2490 static unsigned long tmstart;
2493 static int warning = 1;
2495 if (usertime && warning) {
2496 BIO_printf(bio_err, "To get meaningful results, run "
2497 "this program on idle system.\n");
2500 # ifdef CLOCK_REALTIME
2501 clock_gettime(CLOCK_REALTIME, &now);
2502 if (stop == TM_START)
2505 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2506 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2509 if (stop == TM_START)
2512 ret = (now - tmstart) / (double)sysClkRateGet();
2517 #elif defined(OPENSSL_SYSTEM_VMS)
2521 double app_tminterval(int stop, int usertime)
2523 static clock_t tmstart;
2531 now = rus.tms_utime;
2534 now = clock(); /* sum of user and kernel times */
2537 gettimeofday(&tv, NULL);
2538 now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
2539 (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
2543 if (stop == TM_START)
2546 ret = (now - tmstart) / (double)(CLK_TCK);
2551 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2552 # include <sys/times.h>
2554 double app_tminterval(int stop, int usertime)
2558 clock_t now = times(&rus);
2559 static clock_t tmstart;
2562 now = rus.tms_utime;
2564 if (stop == TM_START)
2567 long int tck = sysconf(_SC_CLK_TCK);
2568 ret = (now - tmstart) / (double)tck;
2575 # include <sys/time.h>
2576 # include <sys/resource.h>
2578 double app_tminterval(int stop, int usertime)
2583 static struct timeval tmstart;
2586 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2588 gettimeofday(&now, NULL);
2590 if (stop == TM_START)
2593 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2594 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2600 int app_access(const char* name, int flag)
2603 return _access(name, flag);
2605 return access(name, flag);
2648 /* app_isdir section */
2650 int app_isdir(const char *name)
2653 WIN32_FIND_DATA FileData;
2654 # if defined(UNICODE) || defined(_UNICODE)
2655 size_t i, len_0 = strlen(name) + 1;
2657 if (len_0 > sizeof(FileData.cFileName) / sizeof(FileData.cFileName[0]))
2660 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2661 if (!MultiByteToWideChar
2662 (CP_ACP, 0, name, len_0, FileData.cFileName, len_0))
2664 for (i = 0; i < len_0; i++)
2665 FileData.cFileName[i] = (WCHAR)name[i];
2667 hList = FindFirstFile(FileData.cFileName, &FileData);
2669 hList = FindFirstFile(name, &FileData);
2671 if (hList == INVALID_HANDLE_VALUE)
2674 return ((FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
2677 # include <sys/stat.h>
2679 # if defined(_S_IFMT) && defined(_S_IFDIR)
2680 # define S_ISDIR(a) (((a) & _S_IFMT) == _S_IFDIR)
2682 # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
2686 int app_isdir(const char *name)
2688 # if defined(S_ISDIR)
2691 if (stat(name, &st) == 0)
2692 return S_ISDIR(st.st_mode);
2701 /* raw_read|write section */
2702 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2703 int raw_read_stdin(void *buf, int siz)
2706 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2712 int raw_read_stdin(void *buf, int siz)
2714 return read(fileno(stdin), buf, siz);
2718 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2719 int raw_write_stdout(const void *buf, int siz)
2722 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2728 int raw_write_stdout(const void *buf, int siz)
2730 return write(fileno(stdout), buf, siz);