2 * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
12 * On VMS, you need to define this to get the declaration of fileno(). The
13 * value 2 is to make sure no function defined in POSIX-2 is left undefined.
15 # define _POSIX_C_SOURCE 2
21 #include <sys/types.h>
22 #ifndef OPENSSL_NO_POSIX_IO
23 # include <sys/stat.h>
28 #include <openssl/err.h>
29 #include <openssl/x509.h>
30 #include <openssl/x509v3.h>
31 #include <openssl/pem.h>
32 #include <openssl/pkcs12.h>
33 #include <openssl/ui.h>
34 #include <openssl/safestack.h>
35 #ifndef OPENSSL_NO_ENGINE
36 # include <openssl/engine.h>
38 #ifndef OPENSSL_NO_RSA
39 # include <openssl/rsa.h>
41 #include <openssl/bn.h>
42 #include <openssl/ssl.h>
47 static int WIN32_rename(const char *from, const char *to);
48 # define rename(from,to) WIN32_rename((from),(to))
57 static UI_METHOD *ui_method = NULL;
58 static const UI_METHOD *ui_fallback_method = NULL;
60 static int set_table_opts(unsigned long *flags, const char *arg,
61 const NAME_EX_TBL * in_tbl);
62 static int set_multi_opts(unsigned long *flags, const char *arg,
63 const NAME_EX_TBL * in_tbl);
65 int app_init(long mesgwin);
67 int chopup_args(ARGS *arg, char *buf)
70 char c = '\0', *p = NULL;
75 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
79 /* Skip whitespace. */
80 while (*p && isspace(_UC(*p)))
85 /* The start of something good :-) */
86 if (arg->argc >= arg->size) {
89 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
94 quoted = *p == '\'' || *p == '"';
97 arg->argv[arg->argc++] = p;
99 /* now look for the end of this */
101 while (*p && *p != c)
105 while (*p && !isspace(_UC(*p)))
111 arg->argv[arg->argc] = NULL;
116 int app_init(long mesgwin)
122 int ctx_set_verify_locations(SSL_CTX *ctx, const char *CAfile,
123 const char *CApath, int noCAfile, int noCApath)
125 if (CAfile == NULL && CApath == NULL) {
126 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
128 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
133 return SSL_CTX_load_verify_locations(ctx, CAfile, CApath);
136 #ifndef OPENSSL_NO_CT
138 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
141 return SSL_CTX_set_default_ctlog_list_file(ctx);
143 return SSL_CTX_set_ctlog_list_file(ctx, path);
148 static unsigned long nmflag = 0;
149 static char nmflag_set = 0;
151 int set_nameopt(const char *arg)
153 int ret = set_name_ex(&nmflag, arg);
161 unsigned long get_nameopt(void)
163 return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
166 int dump_cert_text(BIO *out, X509 *x)
168 print_name(out, "subject=", X509_get_subject_name(x), get_nameopt());
170 print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
176 static int ui_open(UI *ui)
178 int (*opener)(UI *ui) = UI_method_get_opener(ui_fallback_method);
185 static int ui_read(UI *ui, UI_STRING *uis)
187 int (*reader)(UI *ui, UI_STRING *uis) = NULL;
189 if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
190 && UI_get0_user_data(ui)) {
191 switch (UI_get_string_type(uis)) {
195 const char *password =
196 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
197 if (password && password[0] != '\0') {
198 UI_set_result(ui, uis, password);
211 reader = UI_method_get_reader(ui_fallback_method);
213 return reader(ui, uis);
217 static int ui_write(UI *ui, UI_STRING *uis)
219 int (*writer)(UI *ui, UI_STRING *uis) = NULL;
221 if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
222 && UI_get0_user_data(ui)) {
223 switch (UI_get_string_type(uis)) {
227 const char *password =
228 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
229 if (password && password[0] != '\0')
241 writer = UI_method_get_writer(ui_fallback_method);
243 return writer(ui, uis);
247 static int ui_close(UI *ui)
249 int (*closer)(UI *ui) = UI_method_get_closer(ui_fallback_method);
256 int setup_ui_method(void)
258 ui_fallback_method = UI_null();
259 #ifndef OPENSSL_NO_UI_CONSOLE
260 ui_fallback_method = UI_OpenSSL();
262 ui_method = UI_create_method("OpenSSL application user interface");
263 UI_method_set_opener(ui_method, ui_open);
264 UI_method_set_reader(ui_method, ui_read);
265 UI_method_set_writer(ui_method, ui_write);
266 UI_method_set_closer(ui_method, ui_close);
270 void destroy_ui_method(void)
273 UI_destroy_method(ui_method);
278 const UI_METHOD *get_ui_method(void)
283 int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_data)
290 const char *prompt_info = NULL;
293 if ((ui = UI_new_method(ui_method)) == NULL)
296 if (cb_data != NULL && cb_data->prompt_info != NULL)
297 prompt_info = cb_data->prompt_info;
298 prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
299 if (prompt == NULL) {
300 BIO_printf(bio_err, "Out of memory\n");
305 ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
306 UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
308 /* We know that there is no previous user data to return to us */
309 (void)UI_add_user_data(ui, cb_data);
311 ok = UI_add_input_string(ui, prompt, ui_flags, buf,
312 PW_MIN_LENGTH, bufsiz - 1);
314 if (ok >= 0 && verify) {
315 buff = app_malloc(bufsiz, "password buffer");
316 ok = UI_add_verify_string(ui, prompt, ui_flags, buff,
317 PW_MIN_LENGTH, bufsiz - 1, buf);
322 } while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
324 OPENSSL_clear_free(buff, (unsigned int)bufsiz);
329 BIO_printf(bio_err, "User interface error\n");
330 ERR_print_errors(bio_err);
331 OPENSSL_cleanse(buf, (unsigned int)bufsiz);
335 BIO_printf(bio_err, "aborted!\n");
336 OPENSSL_cleanse(buf, (unsigned int)bufsiz);
340 OPENSSL_free(prompt);
344 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
346 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
349 static char *app_get_pass(const char *arg, int keepbio);
351 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
353 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
356 *pass1 = app_get_pass(arg1, same);
359 } else if (pass1 != NULL) {
363 *pass2 = app_get_pass(arg2, same ? 2 : 0);
366 } else if (pass2 != NULL) {
372 static char *app_get_pass(const char *arg, int keepbio)
374 static BIO *pwdbio = NULL;
375 char *tmp, tpass[APP_PASS_LEN];
378 if (strncmp(arg, "pass:", 5) == 0)
379 return OPENSSL_strdup(arg + 5);
380 if (strncmp(arg, "env:", 4) == 0) {
381 tmp = getenv(arg + 4);
383 BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
386 return OPENSSL_strdup(tmp);
388 if (!keepbio || pwdbio == NULL) {
389 if (strncmp(arg, "file:", 5) == 0) {
390 pwdbio = BIO_new_file(arg + 5, "r");
391 if (pwdbio == NULL) {
392 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
397 * Under _WIN32, which covers even Win64 and CE, file
398 * descriptors referenced by BIO_s_fd are not inherited
399 * by child process and therefore below is not an option.
400 * It could have been an option if bss_fd.c was operating
401 * on real Windows descriptors, such as those obtained
404 } else if (strncmp(arg, "fd:", 3) == 0) {
408 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
409 if ((i < 0) || !pwdbio) {
410 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
414 * Can't do BIO_gets on an fd BIO so add a buffering BIO
416 btmp = BIO_new(BIO_f_buffer());
417 pwdbio = BIO_push(btmp, pwdbio);
419 } else if (strcmp(arg, "stdin") == 0) {
420 pwdbio = dup_bio_in(FORMAT_TEXT);
422 BIO_printf(bio_err, "Can't open BIO for stdin\n");
426 BIO_printf(bio_err, "Invalid password argument \"%s\"\n", arg);
430 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
432 BIO_free_all(pwdbio);
436 BIO_printf(bio_err, "Error reading password from BIO\n");
439 tmp = strchr(tpass, '\n');
442 return OPENSSL_strdup(tpass);
445 CONF *app_load_config_bio(BIO *in, const char *filename)
451 conf = NCONF_new(NULL);
452 i = NCONF_load_bio(conf, in, &errorline);
456 if (errorline <= 0) {
457 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
459 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
462 if (filename != NULL)
463 BIO_printf(bio_err, "config file \"%s\"\n", filename);
465 BIO_printf(bio_err, "config input");
471 CONF *app_load_config(const char *filename)
476 in = bio_open_default(filename, 'r', FORMAT_TEXT);
480 conf = app_load_config_bio(in, filename);
485 CONF *app_load_config_quiet(const char *filename)
490 in = bio_open_default_quiet(filename, 'r', FORMAT_TEXT);
494 conf = app_load_config_bio(in, filename);
499 int app_load_modules(const CONF *config)
501 CONF *to_free = NULL;
504 config = to_free = app_load_config_quiet(default_config_file);
508 if (CONF_modules_load(config, NULL, 0) <= 0) {
509 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
510 ERR_print_errors(bio_err);
518 int add_oid_section(CONF *conf)
521 STACK_OF(CONF_VALUE) *sktmp;
525 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
529 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
530 BIO_printf(bio_err, "problem loading oid section %s\n", p);
533 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
534 cnf = sk_CONF_VALUE_value(sktmp, i);
535 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
536 BIO_printf(bio_err, "problem creating object %s=%s\n",
537 cnf->name, cnf->value);
544 static int load_pkcs12(BIO *in, const char *desc,
545 pem_password_cb *pem_cb, PW_CB_DATA *cb_data,
546 EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
549 char tpass[PEM_BUFSIZE];
552 p12 = d2i_PKCS12_bio(in, NULL);
554 BIO_printf(bio_err, "Error loading PKCS12 file for %s\n", desc);
557 /* See if an empty password will do */
558 if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0)) {
562 pem_cb = (pem_password_cb *)password_callback;
563 len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
565 BIO_printf(bio_err, "Passphrase callback error for %s\n", desc);
568 if (len < PEM_BUFSIZE)
570 if (!PKCS12_verify_mac(p12, tpass, len)) {
572 "Mac verify error (wrong password?) in PKCS12 file for %s\n",
578 ret = PKCS12_parse(p12, pass, pkey, cert, ca);
584 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
585 static int load_cert_crl_http(const char *url, X509 **pcert, X509_CRL **pcrl)
587 char *host = NULL, *port = NULL, *path = NULL;
589 OCSP_REQ_CTX *rctx = NULL;
591 if (!OCSP_parse_url(url, &host, &port, &path, &use_ssl))
594 BIO_puts(bio_err, "https not supported\n");
597 bio = BIO_new_connect(host);
598 if (!bio || !BIO_set_conn_port(bio, port))
600 rctx = OCSP_REQ_CTX_new(bio, 1024);
603 if (!OCSP_REQ_CTX_http(rctx, "GET", path))
605 if (!OCSP_REQ_CTX_add1_header(rctx, "Host", host))
609 rv = X509_http_nbio(rctx, pcert);
613 rv = X509_CRL_http_nbio(rctx, pcrl);
622 OCSP_REQ_CTX_free(rctx);
624 BIO_printf(bio_err, "Error loading %s from %s\n",
625 pcert ? "certificate" : "CRL", url);
626 ERR_print_errors(bio_err);
632 X509 *load_cert(const char *file, int format, const char *cert_descrip)
637 if (format == FORMAT_HTTP) {
638 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
639 load_cert_crl_http(file, &x, NULL);
646 cert = dup_bio_in(format);
648 cert = bio_open_default(file, 'r', format);
653 if (format == FORMAT_ASN1) {
654 x = d2i_X509_bio(cert, NULL);
655 } else if (format == FORMAT_PEM) {
656 x = PEM_read_bio_X509_AUX(cert, NULL,
657 (pem_password_cb *)password_callback, NULL);
658 } else if (format == FORMAT_PKCS12) {
659 if (!load_pkcs12(cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
662 BIO_printf(bio_err, "bad input format specified for %s\n", cert_descrip);
667 BIO_printf(bio_err, "unable to load certificate\n");
668 ERR_print_errors(bio_err);
674 X509_CRL *load_crl(const char *infile, int format)
679 if (format == FORMAT_HTTP) {
680 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
681 load_cert_crl_http(infile, NULL, &x);
686 in = bio_open_default(infile, 'r', format);
689 if (format == FORMAT_ASN1) {
690 x = d2i_X509_CRL_bio(in, NULL);
691 } else if (format == FORMAT_PEM) {
692 x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
694 BIO_printf(bio_err, "bad input format specified for input crl\n");
698 BIO_printf(bio_err, "unable to load CRL\n");
699 ERR_print_errors(bio_err);
708 EVP_PKEY *load_key(const char *file, int format, int maybe_stdin,
709 const char *pass, ENGINE *e, const char *key_descrip)
712 EVP_PKEY *pkey = NULL;
715 cb_data.password = pass;
716 cb_data.prompt_info = file;
718 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
719 BIO_printf(bio_err, "no keyfile specified\n");
722 if (format == FORMAT_ENGINE) {
724 BIO_printf(bio_err, "no engine specified\n");
726 #ifndef OPENSSL_NO_ENGINE
727 if (ENGINE_init(e)) {
728 pkey = ENGINE_load_private_key(e, file, ui_method, &cb_data);
732 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
733 ERR_print_errors(bio_err);
736 BIO_printf(bio_err, "engines not supported\n");
741 if (file == NULL && maybe_stdin) {
743 key = dup_bio_in(format);
745 key = bio_open_default(file, 'r', format);
749 if (format == FORMAT_ASN1) {
750 pkey = d2i_PrivateKey_bio(key, NULL);
751 } else if (format == FORMAT_PEM) {
752 pkey = PEM_read_bio_PrivateKey(key, NULL, wrap_password_callback, &cb_data);
753 } else if (format == FORMAT_PKCS12) {
754 if (!load_pkcs12(key, key_descrip, wrap_password_callback, &cb_data,
757 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
758 } else if (format == FORMAT_MSBLOB) {
759 pkey = b2i_PrivateKey_bio(key);
760 } else if (format == FORMAT_PVK) {
761 pkey = b2i_PVK_bio(key, wrap_password_callback, &cb_data);
764 BIO_printf(bio_err, "bad input format specified for key file\n");
770 BIO_printf(bio_err, "unable to load %s\n", key_descrip);
771 ERR_print_errors(bio_err);
776 EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin,
777 const char *pass, ENGINE *e, const char *key_descrip)
780 EVP_PKEY *pkey = NULL;
783 cb_data.password = pass;
784 cb_data.prompt_info = file;
786 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
787 BIO_printf(bio_err, "no keyfile specified\n");
790 if (format == FORMAT_ENGINE) {
792 BIO_printf(bio_err, "no engine specified\n");
794 #ifndef OPENSSL_NO_ENGINE
795 pkey = ENGINE_load_public_key(e, file, ui_method, &cb_data);
797 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
798 ERR_print_errors(bio_err);
801 BIO_printf(bio_err, "engines not supported\n");
806 if (file == NULL && maybe_stdin) {
808 key = dup_bio_in(format);
810 key = bio_open_default(file, 'r', format);
814 if (format == FORMAT_ASN1) {
815 pkey = d2i_PUBKEY_bio(key, NULL);
816 } else if (format == FORMAT_ASN1RSA) {
817 #ifndef OPENSSL_NO_RSA
819 rsa = d2i_RSAPublicKey_bio(key, NULL);
821 pkey = EVP_PKEY_new();
823 EVP_PKEY_set1_RSA(pkey, rsa);
827 BIO_printf(bio_err, "RSA keys not supported\n");
830 } else if (format == FORMAT_PEMRSA) {
831 #ifndef OPENSSL_NO_RSA
833 rsa = PEM_read_bio_RSAPublicKey(key, NULL,
834 (pem_password_cb *)password_callback,
837 pkey = EVP_PKEY_new();
839 EVP_PKEY_set1_RSA(pkey, rsa);
843 BIO_printf(bio_err, "RSA keys not supported\n");
846 } else if (format == FORMAT_PEM) {
847 pkey = PEM_read_bio_PUBKEY(key, NULL,
848 (pem_password_cb *)password_callback,
850 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
851 } else if (format == FORMAT_MSBLOB) {
852 pkey = b2i_PublicKey_bio(key);
858 BIO_printf(bio_err, "unable to load %s\n", key_descrip);
862 static int load_certs_crls(const char *file, int format,
863 const char *pass, const char *desc,
864 STACK_OF(X509) **pcerts,
865 STACK_OF(X509_CRL) **pcrls)
869 STACK_OF(X509_INFO) *xis = NULL;
874 cb_data.password = pass;
875 cb_data.prompt_info = file;
877 if (format != FORMAT_PEM) {
878 BIO_printf(bio_err, "bad input format specified for %s\n", desc);
882 bio = bio_open_default(file, 'r', FORMAT_PEM);
886 xis = PEM_X509_INFO_read_bio(bio, NULL,
887 (pem_password_cb *)password_callback,
892 if (pcerts != NULL && *pcerts == NULL) {
893 *pcerts = sk_X509_new_null();
898 if (pcrls != NULL && *pcrls == NULL) {
899 *pcrls = sk_X509_CRL_new_null();
904 for (i = 0; i < sk_X509_INFO_num(xis); i++) {
905 xi = sk_X509_INFO_value(xis, i);
906 if (xi->x509 != NULL && pcerts != NULL) {
907 if (!sk_X509_push(*pcerts, xi->x509))
911 if (xi->crl != NULL && pcrls != NULL) {
912 if (!sk_X509_CRL_push(*pcrls, xi->crl))
918 if (pcerts != NULL && sk_X509_num(*pcerts) > 0)
921 if (pcrls != NULL && sk_X509_CRL_num(*pcrls) > 0)
926 sk_X509_INFO_pop_free(xis, X509_INFO_free);
929 if (pcerts != NULL) {
930 sk_X509_pop_free(*pcerts, X509_free);
934 sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
937 BIO_printf(bio_err, "unable to load %s\n",
938 pcerts ? "certificates" : "CRLs");
939 ERR_print_errors(bio_err);
944 void* app_malloc(int sz, const char *what)
946 void *vp = OPENSSL_malloc(sz);
949 BIO_printf(bio_err, "%s: Could not allocate %d bytes for %s\n",
950 opt_getprog(), sz, what);
951 ERR_print_errors(bio_err);
958 * Initialize or extend, if *certs != NULL, a certificate stack.
960 int load_certs(const char *file, STACK_OF(X509) **certs, int format,
961 const char *pass, const char *desc)
963 return load_certs_crls(file, format, pass, desc, certs, NULL);
967 * Initialize or extend, if *crls != NULL, a certificate stack.
969 int load_crls(const char *file, STACK_OF(X509_CRL) **crls, int format,
970 const char *pass, const char *desc)
972 return load_certs_crls(file, format, pass, desc, NULL, crls);
975 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
976 /* Return error for unknown extensions */
977 #define X509V3_EXT_DEFAULT 0
978 /* Print error for unknown extensions */
979 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
980 /* ASN1 parse unknown extensions */
981 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
982 /* BIO_dump unknown extensions */
983 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
985 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
986 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
988 int set_cert_ex(unsigned long *flags, const char *arg)
990 static const NAME_EX_TBL cert_tbl[] = {
991 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
992 {"ca_default", X509_FLAG_CA, 0xffffffffl},
993 {"no_header", X509_FLAG_NO_HEADER, 0},
994 {"no_version", X509_FLAG_NO_VERSION, 0},
995 {"no_serial", X509_FLAG_NO_SERIAL, 0},
996 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
997 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
998 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
999 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1000 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1001 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1002 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1003 {"no_aux", X509_FLAG_NO_AUX, 0},
1004 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1005 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1006 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1007 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1008 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1011 return set_multi_opts(flags, arg, cert_tbl);
1014 int set_name_ex(unsigned long *flags, const char *arg)
1016 static const NAME_EX_TBL ex_tbl[] = {
1017 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1018 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
1019 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1020 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1021 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1022 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1023 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1024 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1025 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1026 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1027 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1028 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1029 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1030 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1031 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1032 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1033 {"dn_rev", XN_FLAG_DN_REV, 0},
1034 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1035 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1036 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1037 {"align", XN_FLAG_FN_ALIGN, 0},
1038 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1039 {"space_eq", XN_FLAG_SPC_EQ, 0},
1040 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1041 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1042 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1043 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1044 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1047 if (set_multi_opts(flags, arg, ex_tbl) == 0)
1049 if (*flags != XN_FLAG_COMPAT
1050 && (*flags & XN_FLAG_SEP_MASK) == 0)
1051 *flags |= XN_FLAG_SEP_CPLUS_SPC;
1055 int set_ext_copy(int *copy_type, const char *arg)
1057 if (strcasecmp(arg, "none") == 0)
1058 *copy_type = EXT_COPY_NONE;
1059 else if (strcasecmp(arg, "copy") == 0)
1060 *copy_type = EXT_COPY_ADD;
1061 else if (strcasecmp(arg, "copyall") == 0)
1062 *copy_type = EXT_COPY_ALL;
1068 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1070 STACK_OF(X509_EXTENSION) *exts = NULL;
1071 X509_EXTENSION *ext, *tmpext;
1073 int i, idx, ret = 0;
1074 if (!x || !req || (copy_type == EXT_COPY_NONE))
1076 exts = X509_REQ_get_extensions(req);
1078 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1079 ext = sk_X509_EXTENSION_value(exts, i);
1080 obj = X509_EXTENSION_get_object(ext);
1081 idx = X509_get_ext_by_OBJ(x, obj, -1);
1082 /* Does extension exist? */
1084 /* If normal copy don't override existing extension */
1085 if (copy_type == EXT_COPY_ADD)
1087 /* Delete all extensions of same type */
1089 tmpext = X509_get_ext(x, idx);
1090 X509_delete_ext(x, idx);
1091 X509_EXTENSION_free(tmpext);
1092 idx = X509_get_ext_by_OBJ(x, obj, -1);
1093 } while (idx != -1);
1095 if (!X509_add_ext(x, ext, -1))
1103 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1108 static int set_multi_opts(unsigned long *flags, const char *arg,
1109 const NAME_EX_TBL * in_tbl)
1111 STACK_OF(CONF_VALUE) *vals;
1116 vals = X509V3_parse_list(arg);
1117 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1118 val = sk_CONF_VALUE_value(vals, i);
1119 if (!set_table_opts(flags, val->name, in_tbl))
1122 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1126 static int set_table_opts(unsigned long *flags, const char *arg,
1127 const NAME_EX_TBL * in_tbl)
1130 const NAME_EX_TBL *ptbl;
1136 } else if (c == '+') {
1143 for (ptbl = in_tbl; ptbl->name; ptbl++) {
1144 if (strcasecmp(arg, ptbl->name) == 0) {
1145 *flags &= ~ptbl->mask;
1147 *flags |= ptbl->flag;
1149 *flags &= ~ptbl->flag;
1156 void print_name(BIO *out, const char *title, X509_NAME *nm,
1157 unsigned long lflags)
1164 BIO_puts(out, title);
1165 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1169 if (lflags == XN_FLAG_COMPAT) {
1170 buf = X509_NAME_oneline(nm, 0, 0);
1172 BIO_puts(out, "\n");
1176 BIO_puts(out, "\n");
1177 X509_NAME_print_ex(out, nm, indent, lflags);
1178 BIO_puts(out, "\n");
1182 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1183 int len, unsigned char *buffer)
1185 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1186 if (BN_is_zero(in)) {
1187 BIO_printf(out, "\n 0x00");
1191 l = BN_bn2bin(in, buffer);
1192 for (i = 0; i < l; i++) {
1193 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1195 BIO_printf(out, "0x%02X,", buffer[i]);
1197 BIO_printf(out, "0x%02X", buffer[i]);
1200 BIO_printf(out, "\n };\n");
1203 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1207 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1208 for (i = 0; i < len; i++) {
1210 BIO_printf(out, "\n ");
1212 BIO_printf(out, "0x%02X, ", d[i]);
1214 BIO_printf(out, "0x%02X", d[i]);
1216 BIO_printf(out, "\n};\n");
1219 X509_STORE *setup_verify(const char *CAfile, const char *CApath, int noCAfile, int noCApath)
1221 X509_STORE *store = X509_STORE_new();
1222 X509_LOOKUP *lookup;
1227 if (CAfile != NULL || !noCAfile) {
1228 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1232 if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1233 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1237 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1241 if (CApath != NULL || !noCApath) {
1242 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1246 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1247 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1251 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1258 X509_STORE_free(store);
1262 #ifndef OPENSSL_NO_ENGINE
1263 /* Try to load an engine in a shareable library */
1264 static ENGINE *try_load_engine(const char *engine)
1266 ENGINE *e = ENGINE_by_id("dynamic");
1268 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1269 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1278 ENGINE *setup_engine(const char *engine, int debug)
1282 #ifndef OPENSSL_NO_ENGINE
1283 if (engine != NULL) {
1284 if (strcmp(engine, "auto") == 0) {
1285 BIO_printf(bio_err, "enabling auto ENGINE support\n");
1286 ENGINE_register_all_complete();
1289 if ((e = ENGINE_by_id(engine)) == NULL
1290 && (e = try_load_engine(engine)) == NULL) {
1291 BIO_printf(bio_err, "invalid engine \"%s\"\n", engine);
1292 ERR_print_errors(bio_err);
1296 ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1298 ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
1299 if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1300 BIO_printf(bio_err, "can't use that engine\n");
1301 ERR_print_errors(bio_err);
1306 BIO_printf(bio_err, "engine \"%s\" set.\n", ENGINE_get_id(e));
1312 void release_engine(ENGINE *e)
1314 #ifndef OPENSSL_NO_ENGINE
1316 /* Free our "structural" reference. */
1321 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1328 return OPENSSL_LH_strhash(n);
1331 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1332 const OPENSSL_CSTRING *b)
1334 const char *aa, *bb;
1336 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1337 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1338 return strcmp(aa, bb);
1341 static int index_name_qual(char **a)
1343 return (a[0][0] == 'V');
1346 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1348 return OPENSSL_LH_strhash(a[DB_name]);
1351 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1353 return strcmp(a[DB_name], b[DB_name]);
1356 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1357 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1358 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1359 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1362 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1367 ASN1_INTEGER *ai = NULL;
1369 ai = ASN1_INTEGER_new();
1373 in = BIO_new_file(serialfile, "r");
1381 if (ret == NULL || !rand_serial(ret, ai))
1382 BIO_printf(bio_err, "Out of memory\n");
1384 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1385 BIO_printf(bio_err, "unable to load number from %s\n",
1389 ret = ASN1_INTEGER_to_BN(ai, NULL);
1392 "error converting number from bin to BIGNUM\n");
1403 ASN1_INTEGER_free(ai);
1407 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1408 ASN1_INTEGER **retai)
1413 ASN1_INTEGER *ai = NULL;
1417 j = strlen(serialfile);
1419 j = strlen(serialfile) + strlen(suffix) + 1;
1421 BIO_printf(bio_err, "file name too long\n");
1426 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1428 #ifndef OPENSSL_SYS_VMS
1429 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1431 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1434 out = BIO_new_file(buf[0], "w");
1436 ERR_print_errors(bio_err);
1440 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1441 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1444 i2a_ASN1_INTEGER(out, ai);
1445 BIO_puts(out, "\n");
1453 ASN1_INTEGER_free(ai);
1457 int rotate_serial(const char *serialfile, const char *new_suffix,
1458 const char *old_suffix)
1463 i = strlen(serialfile) + strlen(old_suffix);
1464 j = strlen(serialfile) + strlen(new_suffix);
1467 if (j + 1 >= BSIZE) {
1468 BIO_printf(bio_err, "file name too long\n");
1471 #ifndef OPENSSL_SYS_VMS
1472 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1473 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1475 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1476 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1478 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1484 "unable to rename %s to %s\n", serialfile, buf[1]);
1488 if (rename(buf[0], serialfile) < 0) {
1490 "unable to rename %s to %s\n", buf[0], serialfile);
1492 rename(buf[1], serialfile);
1500 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1505 btmp = b == NULL ? BN_new() : b;
1509 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1511 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1524 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1526 CA_DB *retdb = NULL;
1527 TXT_DB *tmpdb = NULL;
1529 CONF *dbattr_conf = NULL;
1531 #ifndef OPENSSL_NO_POSIX_IO
1536 in = BIO_new_file(dbfile, "r");
1538 ERR_print_errors(bio_err);
1542 #ifndef OPENSSL_NO_POSIX_IO
1543 BIO_get_fp(in, &dbfp);
1544 if (fstat(fileno(dbfp), &dbst) == -1) {
1545 SYSerr(SYS_F_FSTAT, errno);
1546 ERR_add_error_data(3, "fstat('", dbfile, "')");
1547 ERR_print_errors(bio_err);
1552 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1555 #ifndef OPENSSL_SYS_VMS
1556 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1558 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1560 dbattr_conf = app_load_config_quiet(buf);
1562 retdb = app_malloc(sizeof(*retdb), "new DB");
1566 retdb->attributes = *db_attr;
1568 retdb->attributes.unique_subject = 1;
1572 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1574 retdb->attributes.unique_subject = parse_yesno(p, 1);
1578 retdb->dbfname = OPENSSL_strdup(dbfile);
1579 #ifndef OPENSSL_NO_POSIX_IO
1584 NCONF_free(dbattr_conf);
1591 * Returns > 0 on success, <= 0 on error
1593 int index_index(CA_DB *db)
1595 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1596 LHASH_HASH_FN(index_serial),
1597 LHASH_COMP_FN(index_serial))) {
1599 "error creating serial number index:(%ld,%ld,%ld)\n",
1600 db->db->error, db->db->arg1, db->db->arg2);
1604 if (db->attributes.unique_subject
1605 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1606 LHASH_HASH_FN(index_name),
1607 LHASH_COMP_FN(index_name))) {
1608 BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
1609 db->db->error, db->db->arg1, db->db->arg2);
1615 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1621 j = strlen(dbfile) + strlen(suffix);
1622 if (j + 6 >= BSIZE) {
1623 BIO_printf(bio_err, "file name too long\n");
1626 #ifndef OPENSSL_SYS_VMS
1627 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1628 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1629 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1631 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1632 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1633 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1635 out = BIO_new_file(buf[0], "w");
1638 BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1641 j = TXT_DB_write(out, db->db);
1646 out = BIO_new_file(buf[1], "w");
1649 BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
1652 BIO_printf(out, "unique_subject = %s\n",
1653 db->attributes.unique_subject ? "yes" : "no");
1661 int rotate_index(const char *dbfile, const char *new_suffix,
1662 const char *old_suffix)
1667 i = strlen(dbfile) + strlen(old_suffix);
1668 j = strlen(dbfile) + strlen(new_suffix);
1671 if (j + 6 >= BSIZE) {
1672 BIO_printf(bio_err, "file name too long\n");
1675 #ifndef OPENSSL_SYS_VMS
1676 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1677 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1678 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1679 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1680 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1682 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1683 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1684 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1685 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1686 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1688 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1693 BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
1697 if (rename(buf[0], dbfile) < 0) {
1698 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
1700 rename(buf[1], dbfile);
1703 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1708 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
1710 rename(dbfile, buf[0]);
1711 rename(buf[1], dbfile);
1714 if (rename(buf[2], buf[4]) < 0) {
1715 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
1717 rename(buf[3], buf[4]);
1718 rename(dbfile, buf[0]);
1719 rename(buf[1], dbfile);
1727 void free_index(CA_DB *db)
1730 TXT_DB_free(db->db);
1731 OPENSSL_free(db->dbfname);
1736 int parse_yesno(const char *str, int def)
1740 case 'f': /* false */
1741 case 'F': /* FALSE */
1746 case 't': /* true */
1747 case 'T': /* TRUE */
1758 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1759 * where characters may be escaped by \
1761 X509_NAME *parse_name(const char *cp, long chtype, int canmulti)
1763 int nextismulti = 0;
1769 "name is expected to be in the format "
1770 "/type0=value0/type1=value1/type2=... where characters may "
1771 "be escaped by \\. This name is not in that format: '%s'\n",
1776 n = X509_NAME_new();
1779 work = OPENSSL_strdup(cp);
1786 unsigned char *valstr;
1788 int ismulti = nextismulti;
1791 /* Collect the type */
1792 while (*cp && *cp != '=')
1796 "%s: Hit end of string before finding the equals.\n",
1803 /* Collect the value. */
1804 valstr = (unsigned char *)bp;
1805 for (; *cp && *cp != '/'; *bp++ = *cp++) {
1806 if (canmulti && *cp == '+') {
1810 if (*cp == '\\' && *++cp == '\0') {
1812 "%s: escape character at end of string\n",
1819 /* If not at EOS (must be + or /), move forward. */
1824 nid = OBJ_txt2nid(typestr);
1825 if (nid == NID_undef) {
1826 BIO_printf(bio_err, "%s: Skipping unknown attribute \"%s\"\n",
1827 opt_getprog(), typestr);
1830 if (*valstr == '\0') {
1832 "%s: No value provided for Subject Attribute %s, skipped\n",
1833 opt_getprog(), typestr);
1836 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1837 valstr, strlen((char *)valstr),
1838 -1, ismulti ? -1 : 0))
1852 * Read whole contents of a BIO into an allocated memory buffer and return
1856 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1860 unsigned char tbuf[1024];
1862 mem = BIO_new(BIO_s_mem());
1866 if ((maxlen != -1) && maxlen < 1024)
1870 len = BIO_read(in, tbuf, len);
1877 if (BIO_write(mem, tbuf, len) != len) {
1886 ret = BIO_get_mem_data(mem, (char **)out);
1887 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1892 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1895 char *stmp, *vtmp = NULL;
1896 stmp = OPENSSL_strdup(value);
1899 vtmp = strchr(stmp, ':');
1904 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1909 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1911 X509_POLICY_NODE *node;
1914 BIO_printf(bio_err, "%s Policies:", name);
1916 BIO_puts(bio_err, "\n");
1917 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1918 node = sk_X509_POLICY_NODE_value(nodes, i);
1919 X509_POLICY_NODE_print(bio_err, node, 2);
1922 BIO_puts(bio_err, " <empty>\n");
1926 void policies_print(X509_STORE_CTX *ctx)
1928 X509_POLICY_TREE *tree;
1929 int explicit_policy;
1930 tree = X509_STORE_CTX_get0_policy_tree(ctx);
1931 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1933 BIO_printf(bio_err, "Require explicit Policy: %s\n",
1934 explicit_policy ? "True" : "False");
1936 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1937 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1941 * next_protos_parse parses a comma separated list of strings into a string
1942 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1943 * outlen: (output) set to the length of the resulting buffer on success.
1944 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1945 * in: a NUL terminated string like "abc,def,ghi"
1947 * returns: a malloc'd buffer or NULL on failure.
1949 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1953 size_t i, start = 0;
1959 out = app_malloc(strlen(in) + 1, "NPN buffer");
1960 for (i = 0; i <= len; ++i) {
1961 if (i == len || in[i] == ',') {
1962 if (i - start > 255) {
1966 out[start] = (unsigned char)(i - start);
1977 void print_cert_checks(BIO *bio, X509 *x,
1978 const char *checkhost,
1979 const char *checkemail, const char *checkip)
1984 BIO_printf(bio, "Hostname %s does%s match certificate\n",
1986 X509_check_host(x, checkhost, 0, 0, NULL) == 1
1991 BIO_printf(bio, "Email %s does%s match certificate\n",
1992 checkemail, X509_check_email(x, checkemail, 0, 0)
1997 BIO_printf(bio, "IP %s does%s match certificate\n",
1998 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
2002 /* Get first http URL from a DIST_POINT structure */
2004 static const char *get_dp_url(DIST_POINT *dp)
2006 GENERAL_NAMES *gens;
2010 if (!dp->distpoint || dp->distpoint->type != 0)
2012 gens = dp->distpoint->name.fullname;
2013 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2014 gen = sk_GENERAL_NAME_value(gens, i);
2015 uri = GENERAL_NAME_get0_value(gen, >ype);
2016 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
2017 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
2018 if (strncmp(uptr, "http://", 7) == 0)
2026 * Look through a CRLDP structure and attempt to find an http URL to
2027 * downloads a CRL from.
2030 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
2033 const char *urlptr = NULL;
2034 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2035 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
2036 urlptr = get_dp_url(dp);
2038 return load_crl(urlptr, FORMAT_HTTP);
2044 * Example of downloading CRLs from CRLDP: not usable for real world as it
2045 * always downloads, doesn't support non-blocking I/O and doesn't cache
2049 static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
2052 STACK_OF(X509_CRL) *crls = NULL;
2054 STACK_OF(DIST_POINT) *crldp;
2056 crls = sk_X509_CRL_new_null();
2059 x = X509_STORE_CTX_get_current_cert(ctx);
2060 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2061 crl = load_crl_crldp(crldp);
2062 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2064 sk_X509_CRL_free(crls);
2067 sk_X509_CRL_push(crls, crl);
2068 /* Try to download delta CRL */
2069 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2070 crl = load_crl_crldp(crldp);
2071 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2073 sk_X509_CRL_push(crls, crl);
2077 void store_setup_crl_download(X509_STORE *st)
2079 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2083 * Platform-specific sections
2088 # define fileno(a) (int)_fileno(a)
2091 # include <windows.h>
2094 static int WIN32_rename(const char *from, const char *to)
2096 TCHAR *tfrom = NULL, *tto;
2100 if (sizeof(TCHAR) == 1) {
2101 tfrom = (TCHAR *)from;
2103 } else { /* UNICODE path */
2105 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2106 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2110 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2111 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2113 for (i = 0; i < flen; i++)
2114 tfrom[i] = (TCHAR)from[i];
2115 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2116 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2118 for (i = 0; i < tlen; i++)
2119 tto[i] = (TCHAR)to[i];
2122 if (MoveFile(tfrom, tto))
2124 err = GetLastError();
2125 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2126 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2128 err = GetLastError();
2130 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2132 else if (err == ERROR_ACCESS_DENIED)
2135 errno = EINVAL; /* we could map more codes... */
2139 if (tfrom != NULL && tfrom != (TCHAR *)from)
2145 /* app_tminterval section */
2147 double app_tminterval(int stop, int usertime)
2151 static ULARGE_INTEGER tmstart;
2152 static int warning = 1;
2153 # ifdef _WIN32_WINNT
2154 static HANDLE proc = NULL;
2158 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2159 GetCurrentProcessId());
2161 proc = (HANDLE) - 1;
2164 if (usertime && proc != (HANDLE) - 1) {
2166 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2172 if (usertime && warning) {
2173 BIO_printf(bio_err, "To get meaningful results, run "
2174 "this program on idle system.\n");
2177 GetSystemTime(&systime);
2178 SystemTimeToFileTime(&systime, &now);
2181 if (stop == TM_START) {
2182 tmstart.u.LowPart = now.dwLowDateTime;
2183 tmstart.u.HighPart = now.dwHighDateTime;
2185 ULARGE_INTEGER tmstop;
2187 tmstop.u.LowPart = now.dwLowDateTime;
2188 tmstop.u.HighPart = now.dwHighDateTime;
2190 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2195 #elif defined(OPENSSL_SYSTEM_VXWORKS)
2198 double app_tminterval(int stop, int usertime)
2201 # ifdef CLOCK_REALTIME
2202 static struct timespec tmstart;
2203 struct timespec now;
2205 static unsigned long tmstart;
2208 static int warning = 1;
2210 if (usertime && warning) {
2211 BIO_printf(bio_err, "To get meaningful results, run "
2212 "this program on idle system.\n");
2215 # ifdef CLOCK_REALTIME
2216 clock_gettime(CLOCK_REALTIME, &now);
2217 if (stop == TM_START)
2220 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2221 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2224 if (stop == TM_START)
2227 ret = (now - tmstart) / (double)sysClkRateGet();
2232 #elif defined(OPENSSL_SYSTEM_VMS)
2236 double app_tminterval(int stop, int usertime)
2238 static clock_t tmstart;
2246 now = rus.tms_utime;
2249 now = clock(); /* sum of user and kernel times */
2252 gettimeofday(&tv, NULL);
2253 now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
2254 (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
2258 if (stop == TM_START)
2261 ret = (now - tmstart) / (double)(CLK_TCK);
2266 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2267 # include <sys/times.h>
2269 double app_tminterval(int stop, int usertime)
2273 clock_t now = times(&rus);
2274 static clock_t tmstart;
2277 now = rus.tms_utime;
2279 if (stop == TM_START) {
2282 long int tck = sysconf(_SC_CLK_TCK);
2283 ret = (now - tmstart) / (double)tck;
2290 # include <sys/time.h>
2291 # include <sys/resource.h>
2293 double app_tminterval(int stop, int usertime)
2298 static struct timeval tmstart;
2301 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2303 gettimeofday(&now, NULL);
2305 if (stop == TM_START)
2308 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2309 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2315 int app_access(const char* name, int flag)
2318 return _access(name, flag);
2320 return access(name, flag);
2324 /* app_isdir section */
2326 int app_isdir(const char *name)
2329 # if defined(UNICODE) || defined(_UNICODE)
2330 size_t i, len_0 = strlen(name) + 1;
2331 WCHAR tempname[MAX_PATH];
2333 if (len_0 > MAX_PATH)
2336 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2337 if (!MultiByteToWideChar(CP_ACP, 0, name, len_0, tempname, MAX_PATH))
2339 for (i = 0; i < len_0; i++)
2340 tempname[i] = (WCHAR)name[i];
2342 attr = GetFileAttributes(tempname);
2344 attr = GetFileAttributes(name);
2346 if (attr == INVALID_FILE_ATTRIBUTES)
2348 return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
2351 # include <sys/stat.h>
2353 # if defined(_S_IFMT) && defined(_S_IFDIR)
2354 # define S_ISDIR(a) (((a) & _S_IFMT) == _S_IFDIR)
2356 # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
2360 int app_isdir(const char *name)
2362 # if defined(S_ISDIR)
2365 if (stat(name, &st) == 0)
2366 return S_ISDIR(st.st_mode);
2375 /* raw_read|write section */
2377 # include "vms_term_sock.h"
2378 static int stdin_sock = -1;
2380 static void close_stdin_sock(void)
2382 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2385 int fileno_stdin(void)
2387 if (stdin_sock == -1) {
2388 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2389 atexit(close_stdin_sock);
2395 int fileno_stdin(void)
2397 return fileno(stdin);
2401 int fileno_stdout(void)
2403 return fileno(stdout);
2406 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2407 int raw_read_stdin(void *buf, int siz)
2410 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2415 #elif defined(__VMS)
2416 # include <sys/socket.h>
2418 int raw_read_stdin(void *buf, int siz)
2420 return recv(fileno_stdin(), buf, siz, 0);
2423 int raw_read_stdin(void *buf, int siz)
2425 return read(fileno_stdin(), buf, siz);
2429 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2430 int raw_write_stdout(const void *buf, int siz)
2433 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2439 int raw_write_stdout(const void *buf, int siz)
2441 return write(fileno_stdout(), buf, siz);
2446 * Centralized handling if input and output files with format specification
2447 * The format is meant to show what the input and output is supposed to be,
2448 * and is therefore a show of intent more than anything else. However, it
2449 * does impact behavior on some platform, such as differentiating between
2450 * text and binary input/output on non-Unix platforms
2452 static int istext(int format)
2454 return (format & B_FORMAT_TEXT) == B_FORMAT_TEXT;
2457 BIO *dup_bio_in(int format)
2459 return BIO_new_fp(stdin,
2460 BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
2463 static BIO_METHOD *prefix_method = NULL;
2465 BIO *dup_bio_out(int format)
2467 BIO *b = BIO_new_fp(stdout,
2468 BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
2469 void *prefix = NULL;
2471 #ifdef OPENSSL_SYS_VMS
2473 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2476 if (istext(format) && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2477 if (prefix_method == NULL)
2478 prefix_method = apps_bf_prefix();
2479 b = BIO_push(BIO_new(prefix_method), b);
2480 BIO_ctrl(b, PREFIX_CTRL_SET_PREFIX, 0, prefix);
2486 BIO *dup_bio_err(int format)
2488 BIO *b = BIO_new_fp(stderr,
2489 BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
2490 #ifdef OPENSSL_SYS_VMS
2492 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2497 void destroy_prefix_method(void)
2499 BIO_meth_free(prefix_method);
2500 prefix_method = NULL;
2503 void unbuffer(FILE *fp)
2506 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2507 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2508 * However, we trust that the C RTL will never give us a FILE pointer
2509 * above the first 4 GB of memory, so we simply turn off the warning
2512 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2513 # pragma environment save
2514 # pragma message disable maylosedata2
2517 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2518 # pragma environment restore
2522 static const char *modestr(char mode, int format)
2524 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2528 return istext(format) ? "a" : "ab";
2530 return istext(format) ? "r" : "rb";
2532 return istext(format) ? "w" : "wb";
2534 /* The assert above should make sure we never reach this point */
2538 static const char *modeverb(char mode)
2548 return "(doing something)";
2552 * Open a file for writing, owner-read-only.
2554 BIO *bio_open_owner(const char *filename, int format, int private)
2558 int fd = -1, bflags, mode, textmode;
2560 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2561 return bio_open_default(filename, 'w', format);
2570 textmode = istext(format);
2574 #elif defined(_O_BINARY)
2579 #ifdef OPENSSL_SYS_VMS
2580 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2581 * it still needs to know that we're going binary, or fdopen()
2582 * will fail with "invalid argument"... so we tell VMS what the
2586 fd = open(filename, mode, 0600, "ctx=bin");
2589 fd = open(filename, mode, 0600);
2592 fp = fdopen(fd, modestr('w', format));
2597 bflags |= BIO_FP_TEXT;
2598 b = BIO_new_fp(fp, bflags);
2603 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2604 opt_getprog(), filename, strerror(errno));
2605 ERR_print_errors(bio_err);
2606 /* If we have fp, then fdopen took over fd, so don't close both. */
2614 static BIO *bio_open_default_(const char *filename, char mode, int format,
2619 if (filename == NULL || strcmp(filename, "-") == 0) {
2620 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2628 "Can't open %s, %s\n",
2629 mode == 'r' ? "stdin" : "stdout", strerror(errno));
2631 ret = BIO_new_file(filename, modestr(mode, format));
2639 "Can't open %s for %s, %s\n",
2640 filename, modeverb(mode), strerror(errno));
2642 ERR_print_errors(bio_err);
2646 BIO *bio_open_default(const char *filename, char mode, int format)
2648 return bio_open_default_(filename, mode, format, 0);
2651 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2653 return bio_open_default_(filename, mode, format, 1);
2656 void wait_for_async(SSL *s)
2658 /* On Windows select only works for sockets, so we simply don't wait */
2659 #ifndef OPENSSL_SYS_WINDOWS
2666 if (!SSL_get_all_async_fds(s, NULL, &numfds))
2670 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2671 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2677 for (i = 0; i < numfds; i++) {
2678 if (width <= (int)fds[i])
2679 width = (int)fds[i] + 1;
2680 openssl_fdset((int)fds[i], &asyncfds);
2682 select(width, (void *)&asyncfds, NULL, NULL, NULL);
2687 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2688 #if defined(OPENSSL_SYS_MSDOS)
2689 int has_stdin_waiting(void)
2691 # if defined(OPENSSL_SYS_WINDOWS)
2692 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2694 INPUT_RECORD inputrec;
2698 if (inhand == INVALID_HANDLE_VALUE) {
2702 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2704 /* Probably redirected input? _kbhit() does not work in this case */
2715 /* Corrupt a signature by modifying final byte */
2716 void corrupt_signature(const ASN1_STRING *signature)
2718 unsigned char *s = signature->data;
2719 s[signature->length - 1] ^= 0x1;
2722 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2725 if (startdate == NULL || strcmp(startdate, "today") == 0) {
2726 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2729 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2732 if (enddate == NULL) {
2733 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2736 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2742 void make_uppercase(char *string)
2746 for (i = 0; string[i] != '\0'; i++)
2747 string[i] = toupper((unsigned char)string[i]);