Home | History | Annotate | Line # | Download | only in lib
apps.c revision 1.1.1.2
      1 /*
      2  * Copyright 1995-2026 The OpenSSL Project Authors. All Rights Reserved.
      3  *
      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
      8  */
      9 
     10 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
     11 /*
     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.
     14  */
     15 #define _POSIX_C_SOURCE 2
     16 #endif
     17 
     18 #ifndef OPENSSL_NO_ENGINE
     19 /* We need to use some deprecated APIs */
     20 #define OPENSSL_SUPPRESS_DEPRECATED
     21 #include <openssl/engine.h>
     22 #endif
     23 
     24 #include <stdio.h>
     25 #include <stdlib.h>
     26 #include <string.h>
     27 #include <sys/types.h>
     28 #ifndef OPENSSL_NO_POSIX_IO
     29 #include <sys/stat.h>
     30 #include <fcntl.h>
     31 #endif
     32 #include <ctype.h>
     33 #include <errno.h>
     34 #include <openssl/err.h>
     35 #include <openssl/x509.h>
     36 #include <openssl/x509v3.h>
     37 #include <openssl/http.h>
     38 #include <openssl/pem.h>
     39 #include <openssl/store.h>
     40 #include <openssl/pkcs12.h>
     41 #include <openssl/ui.h>
     42 #include <openssl/safestack.h>
     43 #include <openssl/rsa.h>
     44 #include <openssl/rand.h>
     45 #include <openssl/bn.h>
     46 #include <openssl/ssl.h>
     47 #include <openssl/core_names.h>
     48 #include "s_apps.h"
     49 #include "apps.h"
     50 
     51 #include "internal/sockets.h" /* for openssl_fdset() */
     52 #include "internal/numbers.h" /* for LONG_MAX */
     53 #include "internal/e_os.h"
     54 
     55 #ifdef _WIN32
     56 static int WIN32_rename(const char *from, const char *to);
     57 #define rename(from, to) WIN32_rename((from), (to))
     58 #endif
     59 
     60 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
     61 #include <conio.h>
     62 #endif
     63 
     64 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) || defined(__BORLANDC__)
     65 #define _kbhit kbhit
     66 #endif
     67 
     68 static BIO *bio_open_default_(const char *filename, char mode, int format,
     69     int quiet);
     70 
     71 #define PASS_SOURCE_SIZE_MAX 4
     72 
     73 DEFINE_STACK_OF(CONF)
     74 
     75 typedef struct {
     76     const char *name;
     77     unsigned long flag;
     78     unsigned long mask;
     79 } NAME_EX_TBL;
     80 
     81 static int set_table_opts(unsigned long *flags, const char *arg,
     82     const NAME_EX_TBL *in_tbl);
     83 static int set_multi_opts(unsigned long *flags, const char *arg,
     84     const NAME_EX_TBL *in_tbl);
     85 int app_init(long mesgwin);
     86 
     87 #ifndef APP_INIT
     88 int app_init(long mesgwin)
     89 {
     90     return 1;
     91 }
     92 #endif
     93 
     94 int ctx_set_verify_locations(SSL_CTX *ctx,
     95     const char *CAfile, int noCAfile,
     96     const char *CApath, int noCApath,
     97     const char *CAstore, int noCAstore)
     98 {
     99     if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
    100         if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
    101             return 0;
    102         if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
    103             return 0;
    104         if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
    105             return 0;
    106 
    107         return 1;
    108     }
    109 
    110     if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
    111         return 0;
    112     if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
    113         return 0;
    114     if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
    115         return 0;
    116     return 1;
    117 }
    118 
    119 #ifndef OPENSSL_NO_CT
    120 
    121 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
    122 {
    123     if (path == NULL)
    124         return SSL_CTX_set_default_ctlog_list_file(ctx);
    125 
    126     return SSL_CTX_set_ctlog_list_file(ctx, path);
    127 }
    128 
    129 #endif
    130 
    131 static unsigned long nmflag = 0;
    132 static char nmflag_set = 0;
    133 
    134 int set_nameopt(const char *arg)
    135 {
    136     int ret = set_name_ex(&nmflag, arg);
    137 
    138     if (ret)
    139         nmflag_set = 1;
    140 
    141     return ret;
    142 }
    143 
    144 unsigned long get_nameopt(void)
    145 {
    146     return nmflag_set ? nmflag : XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_FN_SN | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_UTF8_CONVERT | ASN1_STRFLGS_DUMP_UNKNOWN | ASN1_STRFLGS_DUMP_DER;
    147 }
    148 
    149 void dump_cert_text(BIO *out, X509 *x)
    150 {
    151     print_name(out, "subject=", X509_get_subject_name(x));
    152     print_name(out, "issuer=", X509_get_issuer_name(x));
    153 }
    154 
    155 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
    156 {
    157     return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
    158 }
    159 
    160 static char *app_get_pass(const char *arg, int keepbio);
    161 
    162 char *get_passwd(const char *pass, const char *desc)
    163 {
    164     char *result = NULL;
    165 
    166     if (desc == NULL)
    167         desc = "<unknown>";
    168     if (!app_passwd(pass, NULL, &result, NULL))
    169         BIO_printf(bio_err, "Error getting password for %s\n", desc);
    170     if (pass != NULL && result == NULL) {
    171         BIO_printf(bio_err,
    172             "Trying plain input string (better precede with 'pass:')\n");
    173         result = OPENSSL_strdup(pass);
    174         if (result == NULL)
    175             BIO_printf(bio_err,
    176                 "Out of memory getting password for %s\n", desc);
    177     }
    178     return result;
    179 }
    180 
    181 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
    182 {
    183     int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
    184 
    185     if (arg1 != NULL) {
    186         *pass1 = app_get_pass(arg1, same);
    187         if (*pass1 == NULL)
    188             return 0;
    189     } else if (pass1 != NULL) {
    190         *pass1 = NULL;
    191     }
    192     if (arg2 != NULL) {
    193         *pass2 = app_get_pass(arg2, same ? 2 : 0);
    194         if (*pass2 == NULL)
    195             return 0;
    196     } else if (pass2 != NULL) {
    197         *pass2 = NULL;
    198     }
    199     return 1;
    200 }
    201 
    202 static char *app_get_pass(const char *arg, int keepbio)
    203 {
    204     static BIO *pwdbio = NULL;
    205     char *tmp, tpass[APP_PASS_LEN];
    206     int i;
    207 
    208     /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
    209     if (CHECK_AND_SKIP_PREFIX(arg, "pass:"))
    210         return OPENSSL_strdup(arg);
    211     if (CHECK_AND_SKIP_PREFIX(arg, "env:")) {
    212         tmp = getenv(arg);
    213         if (tmp == NULL) {
    214             BIO_printf(bio_err, "No environment variable %s\n", arg);
    215             return NULL;
    216         }
    217         return OPENSSL_strdup(tmp);
    218     }
    219     if (!keepbio || pwdbio == NULL) {
    220         if (CHECK_AND_SKIP_PREFIX(arg, "file:")) {
    221             pwdbio = BIO_new_file(arg, "r");
    222             if (pwdbio == NULL) {
    223                 BIO_printf(bio_err, "Can't open file %s\n", arg);
    224                 return NULL;
    225             }
    226 #if !defined(_WIN32)
    227             /*
    228              * Under _WIN32, which covers even Win64 and CE, file
    229              * descriptors referenced by BIO_s_fd are not inherited
    230              * by child process and therefore below is not an option.
    231              * It could have been an option if bss_fd.c was operating
    232              * on real Windows descriptors, such as those obtained
    233              * with CreateFile.
    234              */
    235         } else if (CHECK_AND_SKIP_PREFIX(arg, "fd:")) {
    236             BIO *btmp;
    237 
    238             i = atoi(arg);
    239             if (i >= 0)
    240                 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
    241             if ((i < 0) || pwdbio == NULL) {
    242                 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg);
    243                 return NULL;
    244             }
    245             /*
    246              * Can't do BIO_gets on an fd BIO so add a buffering BIO
    247              */
    248             btmp = BIO_new(BIO_f_buffer());
    249             if (btmp == NULL) {
    250                 BIO_free_all(pwdbio);
    251                 pwdbio = NULL;
    252                 BIO_printf(bio_err, "Out of memory\n");
    253                 return NULL;
    254             }
    255             pwdbio = BIO_push(btmp, pwdbio);
    256 #endif
    257         } else if (strcmp(arg, "stdin") == 0) {
    258             unbuffer(stdin);
    259             pwdbio = dup_bio_in(FORMAT_TEXT);
    260             if (pwdbio == NULL) {
    261                 BIO_printf(bio_err, "Can't open BIO for stdin\n");
    262                 return NULL;
    263             }
    264         } else {
    265             /* argument syntax error; do not reveal too much about arg */
    266             tmp = strchr(arg, ':');
    267             if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
    268                 BIO_printf(bio_err,
    269                     "Invalid password argument, missing ':' within the first %d chars\n",
    270                     PASS_SOURCE_SIZE_MAX + 1);
    271             else
    272                 BIO_printf(bio_err,
    273                     "Invalid password argument, starting with \"%.*s\"\n",
    274                     (int)(tmp - arg + 1), arg);
    275             return NULL;
    276         }
    277     }
    278     i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
    279     if (keepbio != 1) {
    280         BIO_free_all(pwdbio);
    281         pwdbio = NULL;
    282     }
    283     if (i <= 0) {
    284         BIO_printf(bio_err, "Error reading password from BIO\n");
    285         return NULL;
    286     }
    287     tmp = strchr(tpass, '\n');
    288     if (tmp != NULL)
    289         *tmp = 0;
    290     return OPENSSL_strdup(tpass);
    291 }
    292 
    293 char *app_conf_try_string(const CONF *conf, const char *group, const char *name)
    294 {
    295     char *res;
    296 
    297     ERR_set_mark();
    298     res = NCONF_get_string(conf, group, name);
    299     if (res == NULL)
    300         ERR_pop_to_mark();
    301     else
    302         ERR_clear_last_mark();
    303     return res;
    304 }
    305 
    306 int app_conf_try_number(const CONF *conf, const char *group, const char *name,
    307     long *result)
    308 {
    309     int ok;
    310 
    311     ERR_set_mark();
    312     ok = NCONF_get_number(conf, group, name, result);
    313     if (!ok)
    314         ERR_pop_to_mark();
    315     else
    316         ERR_clear_last_mark();
    317     return ok;
    318 }
    319 
    320 CONF *app_load_config_bio(BIO *in, const char *filename)
    321 {
    322     long errorline = -1;
    323     CONF *conf;
    324     int i;
    325 
    326     conf = NCONF_new_ex(app_get0_libctx(), NULL);
    327     i = NCONF_load_bio(conf, in, &errorline);
    328     if (i > 0)
    329         return conf;
    330 
    331     if (errorline <= 0) {
    332         BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
    333     } else {
    334         BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
    335             errorline);
    336     }
    337     if (filename != NULL)
    338         BIO_printf(bio_err, "config file \"%s\"\n", filename);
    339     else
    340         BIO_printf(bio_err, "config input");
    341 
    342     NCONF_free(conf);
    343     return NULL;
    344 }
    345 
    346 CONF *app_load_config_verbose(const char *filename, int verbose)
    347 {
    348     if (verbose) {
    349         if (*filename == '\0')
    350             BIO_printf(bio_err, "No configuration used\n");
    351         else
    352             BIO_printf(bio_err, "Using configuration from %s\n", filename);
    353     }
    354     return app_load_config_internal(filename, 0);
    355 }
    356 
    357 CONF *app_load_config_internal(const char *filename, int quiet)
    358 {
    359     BIO *in;
    360     CONF *conf;
    361 
    362     if (filename == NULL || *filename != '\0') {
    363         if ((in = bio_open_default_(filename, 'r', FORMAT_TEXT, quiet)) == NULL)
    364             return NULL;
    365         conf = app_load_config_bio(in, filename);
    366         BIO_free(in);
    367     } else {
    368         /* Return empty config if filename is empty string. */
    369         conf = NCONF_new_ex(app_get0_libctx(), NULL);
    370     }
    371     return conf;
    372 }
    373 
    374 int app_load_modules(const CONF *config)
    375 {
    376     CONF *to_free = NULL;
    377 
    378     if (config == NULL)
    379         config = to_free = app_load_config_quiet(default_config_file);
    380     if (config == NULL)
    381         return 1;
    382 
    383     if (CONF_modules_load(config, NULL, 0) <= 0) {
    384         BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
    385         ERR_print_errors(bio_err);
    386         NCONF_free(to_free);
    387         return 0;
    388     }
    389     NCONF_free(to_free);
    390     return 1;
    391 }
    392 
    393 int add_oid_section(CONF *conf)
    394 {
    395     char *p;
    396     STACK_OF(CONF_VALUE) *sktmp;
    397     CONF_VALUE *cnf;
    398     int i;
    399 
    400     if ((p = app_conf_try_string(conf, NULL, "oid_section")) == NULL)
    401         return 1;
    402     if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
    403         BIO_printf(bio_err, "problem loading oid section %s\n", p);
    404         return 0;
    405     }
    406     for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
    407         cnf = sk_CONF_VALUE_value(sktmp, i);
    408         if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
    409             BIO_printf(bio_err, "problem creating object %s=%s\n",
    410                 cnf->name, cnf->value);
    411             return 0;
    412         }
    413     }
    414     return 1;
    415 }
    416 
    417 CONF *app_load_config_modules(const char *configfile)
    418 {
    419     CONF *conf = NULL;
    420 
    421     if (configfile != NULL) {
    422         if ((conf = app_load_config_verbose(configfile, 1)) == NULL)
    423             return NULL;
    424         if (configfile != default_config_file && !app_load_modules(conf)) {
    425             NCONF_free(conf);
    426             conf = NULL;
    427         }
    428     }
    429     return conf;
    430 }
    431 
    432 #define IS_HTTP(uri) ((uri) != NULL && HAS_PREFIX(uri, OSSL_HTTP_PREFIX))
    433 #define IS_HTTPS(uri) ((uri) != NULL && HAS_PREFIX(uri, OSSL_HTTPS_PREFIX))
    434 
    435 X509 *load_cert_pass(const char *uri, int format, int maybe_stdin,
    436     const char *pass, const char *desc)
    437 {
    438     X509 *cert = NULL;
    439 
    440     if (desc == NULL)
    441         desc = "certificate";
    442     if (IS_HTTPS(uri)) {
    443         BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
    444     } else if (IS_HTTP(uri)) {
    445         cert = X509_load_http(uri, NULL, NULL, 0 /* timeout */);
    446         if (cert == NULL) {
    447             ERR_print_errors(bio_err);
    448             BIO_printf(bio_err, "Unable to load %s from %s\n", desc, uri);
    449         }
    450     } else {
    451         (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, 0,
    452             NULL, NULL, NULL, &cert, NULL, NULL, NULL);
    453     }
    454     return cert;
    455 }
    456 
    457 X509_CRL *load_crl(const char *uri, int format, int maybe_stdin,
    458     const char *desc)
    459 {
    460     X509_CRL *crl = NULL;
    461 
    462     if (desc == NULL)
    463         desc = "CRL";
    464     if (IS_HTTPS(uri)) {
    465         BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
    466     } else if (IS_HTTP(uri)) {
    467         crl = X509_CRL_load_http(uri, NULL, NULL, 0 /* timeout */);
    468         if (crl == NULL) {
    469             ERR_print_errors(bio_err);
    470             BIO_printf(bio_err, "Unable to load %s from %s\n", desc, uri);
    471         }
    472     } else {
    473         (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc, 0,
    474             NULL, NULL, NULL, NULL, NULL, &crl, NULL);
    475     }
    476     return crl;
    477 }
    478 
    479 /* Could be simplified if OSSL_STORE supported CSRs, see FR #15725 */
    480 X509_REQ *load_csr(const char *file, int format, const char *desc)
    481 {
    482     X509_REQ *req = NULL;
    483     BIO *in;
    484 
    485     if (format == FORMAT_UNDEF)
    486         format = FORMAT_PEM;
    487     in = bio_open_default(file, 'r', format);
    488     if (in == NULL)
    489         goto end;
    490 
    491     if (format == FORMAT_ASN1)
    492         req = d2i_X509_REQ_bio(in, NULL);
    493     else if (format == FORMAT_PEM)
    494         req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
    495     else
    496         print_format_error(format, OPT_FMT_PEMDER);
    497 
    498 end:
    499     if (req == NULL) {
    500         ERR_print_errors(bio_err);
    501         if (desc != NULL)
    502             BIO_printf(bio_err, "Unable to load %s\n", desc);
    503     }
    504     BIO_free(in);
    505     return req;
    506 }
    507 
    508 /* Better extend OSSL_STORE to support CSRs, see FR #15725 */
    509 X509_REQ *load_csr_autofmt(const char *infile, int format,
    510     STACK_OF(OPENSSL_STRING) *vfyopts, const char *desc)
    511 {
    512     X509_REQ *csr;
    513 
    514     if (format != FORMAT_UNDEF) {
    515         csr = load_csr(infile, format, desc);
    516     } else { /* try PEM, then DER */
    517         BIO *bio_bak = bio_err;
    518 
    519         bio_err = NULL; /* do not show errors on more than one try */
    520         csr = load_csr(infile, FORMAT_PEM, NULL /* desc */);
    521         bio_err = bio_bak;
    522         if (csr == NULL) {
    523             ERR_clear_error();
    524             csr = load_csr(infile, FORMAT_ASN1, NULL /* desc */);
    525         }
    526         if (csr == NULL) {
    527             BIO_printf(bio_err, "error: unable to load %s from file '%s'\n",
    528                 desc, infile);
    529         }
    530     }
    531     if (csr != NULL) {
    532         EVP_PKEY *pkey = X509_REQ_get0_pubkey(csr);
    533         int ret = do_X509_REQ_verify(csr, pkey, vfyopts);
    534 
    535         if (pkey == NULL || ret < 0)
    536             BIO_puts(bio_err, "Warning: error while verifying CSR self-signature\n");
    537         else if (ret == 0)
    538             BIO_puts(bio_err, "Warning: CSR self-signature does not match the contents\n");
    539         return csr;
    540     }
    541     return csr;
    542 }
    543 
    544 void cleanse(char *str)
    545 {
    546     if (str != NULL)
    547         OPENSSL_cleanse(str, strlen(str));
    548 }
    549 
    550 void clear_free(char *str)
    551 {
    552     if (str != NULL)
    553         OPENSSL_clear_free(str, strlen(str));
    554 }
    555 
    556 EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
    557     const char *pass, ENGINE *e, const char *desc)
    558 {
    559     EVP_PKEY *pkey = NULL;
    560     char *allocated_uri = NULL;
    561 
    562     if (desc == NULL)
    563         desc = "private key";
    564 
    565     if (format == FORMAT_ENGINE)
    566         uri = allocated_uri = make_engine_uri(e, uri, desc);
    567     (void)load_key_certs_crls(uri, format, may_stdin, pass, desc, 0,
    568         &pkey, NULL, NULL, NULL, NULL, NULL, NULL);
    569 
    570     OPENSSL_free(allocated_uri);
    571     return pkey;
    572 }
    573 
    574 /* first try reading public key, on failure resort to loading private key */
    575 EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
    576     const char *pass, ENGINE *e, const char *desc)
    577 {
    578     EVP_PKEY *pkey = NULL;
    579     char *allocated_uri = NULL;
    580 
    581     if (desc == NULL)
    582         desc = "public key";
    583 
    584     if (format == FORMAT_ENGINE)
    585         uri = allocated_uri = make_engine_uri(e, uri, desc);
    586     (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, 1,
    587         NULL, &pkey, NULL, NULL, NULL, NULL, NULL);
    588     if (pkey == NULL)
    589         (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, 0,
    590             &pkey, NULL, NULL, NULL, NULL, NULL, NULL);
    591     OPENSSL_free(allocated_uri);
    592     return pkey;
    593 }
    594 
    595 EVP_PKEY *load_keyparams_suppress(const char *uri, int format, int maybe_stdin,
    596     const char *keytype, const char *desc,
    597     int suppress_decode_errors)
    598 {
    599     EVP_PKEY *params = NULL;
    600 
    601     if (desc == NULL)
    602         desc = "key parameters";
    603     (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc,
    604         suppress_decode_errors,
    605         NULL, NULL, &params, NULL, NULL, NULL, NULL);
    606     if (params != NULL && keytype != NULL && !EVP_PKEY_is_a(params, keytype)) {
    607         ERR_print_errors(bio_err);
    608         BIO_printf(bio_err,
    609             "Unable to load %s from %s (unexpected parameters type)\n",
    610             desc, uri);
    611         EVP_PKEY_free(params);
    612         params = NULL;
    613     }
    614     return params;
    615 }
    616 
    617 EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin,
    618     const char *keytype, const char *desc)
    619 {
    620     return load_keyparams_suppress(uri, format, maybe_stdin, keytype, desc, 0);
    621 }
    622 
    623 void app_bail_out(char *fmt, ...)
    624 {
    625     va_list args;
    626 
    627     va_start(args, fmt);
    628     BIO_vprintf(bio_err, fmt, args);
    629     va_end(args);
    630     ERR_print_errors(bio_err);
    631     exit(EXIT_FAILURE);
    632 }
    633 
    634 void *app_malloc(size_t sz, const char *what)
    635 {
    636     void *vp = OPENSSL_malloc(sz);
    637 
    638     if (vp == NULL)
    639         app_bail_out("%s: Could not allocate %zu bytes for %s\n",
    640             opt_getprog(), sz, what);
    641     return vp;
    642 }
    643 
    644 char *next_item(char *opt) /* in list separated by comma and/or space */
    645 {
    646     /* advance to separator (comma or whitespace), if any */
    647     while (*opt != ',' && !isspace(_UC(*opt)) && *opt != '\0')
    648         opt++;
    649     if (*opt != '\0') {
    650         /* terminate current item */
    651         *opt++ = '\0';
    652         /* skip over any whitespace after separator */
    653         while (isspace(_UC(*opt)))
    654             opt++;
    655     }
    656     return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */
    657 }
    658 
    659 static void warn_cert_msg(const char *uri, X509 *cert, const char *msg)
    660 {
    661     char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
    662 
    663     BIO_printf(bio_err, "Warning: certificate from '%s' with subject '%s' %s\n",
    664         uri, subj, msg);
    665     OPENSSL_free(subj);
    666 }
    667 
    668 static void warn_cert(const char *uri, X509 *cert, int warn_EE,
    669     X509_VERIFY_PARAM *vpm)
    670 {
    671     uint32_t ex_flags = X509_get_extension_flags(cert);
    672     int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
    673         X509_get0_notAfter(cert));
    674 
    675     if (res != 0)
    676         warn_cert_msg(uri, cert, res > 0 ? "has expired" : "not yet valid");
    677     if (warn_EE && (ex_flags & EXFLAG_V1) == 0 && (ex_flags & EXFLAG_CA) == 0)
    678         warn_cert_msg(uri, cert, "is not a CA cert");
    679 }
    680 
    681 static void warn_certs(const char *uri, STACK_OF(X509) *certs, int warn_EE,
    682     X509_VERIFY_PARAM *vpm)
    683 {
    684     int i;
    685 
    686     for (i = 0; i < sk_X509_num(certs); i++)
    687         warn_cert(uri, sk_X509_value(certs, i), warn_EE, vpm);
    688 }
    689 
    690 int load_cert_certs(const char *uri,
    691     X509 **pcert, STACK_OF(X509) **pcerts,
    692     int exclude_http, const char *pass, const char *desc,
    693     X509_VERIFY_PARAM *vpm)
    694 {
    695     int ret = 0;
    696     char *pass_string;
    697 
    698     if (desc == NULL)
    699         desc = pcerts == NULL ? "certificate" : "certificates";
    700     if (exclude_http && (HAS_CASE_PREFIX(uri, "http://") || HAS_CASE_PREFIX(uri, "https://"))) {
    701         BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc);
    702         return ret;
    703     }
    704     pass_string = get_passwd(pass, desc);
    705     ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass_string, desc, 0,
    706         NULL, NULL, NULL, pcert, pcerts, NULL, NULL);
    707     clear_free(pass_string);
    708 
    709     if (ret) {
    710         if (pcert != NULL)
    711             warn_cert(uri, *pcert, 0, vpm);
    712         if (pcerts != NULL)
    713             warn_certs(uri, *pcerts, 1, vpm);
    714     } else {
    715         if (pcerts != NULL) {
    716             OSSL_STACK_OF_X509_free(*pcerts);
    717             *pcerts = NULL;
    718         }
    719     }
    720     return ret;
    721 }
    722 
    723 STACK_OF(X509) *load_certs_multifile(char *files, const char *pass,
    724     const char *desc, X509_VERIFY_PARAM *vpm)
    725 {
    726     STACK_OF(X509) *certs = NULL;
    727     STACK_OF(X509) *result = sk_X509_new_null();
    728 
    729     if (files == NULL)
    730         goto err;
    731     if (result == NULL)
    732         goto oom;
    733 
    734     while (files != NULL) {
    735         char *next = next_item(files);
    736 
    737         if (!load_cert_certs(files, NULL, &certs, 0, pass, desc, vpm))
    738             goto err;
    739         if (!X509_add_certs(result, certs,
    740                 X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
    741             goto oom;
    742         OSSL_STACK_OF_X509_free(certs);
    743         certs = NULL;
    744         files = next;
    745     }
    746     return result;
    747 
    748 oom:
    749     BIO_printf(bio_err, "out of memory\n");
    750 err:
    751     OSSL_STACK_OF_X509_free(certs);
    752     OSSL_STACK_OF_X509_free(result);
    753     return NULL;
    754 }
    755 
    756 static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */,
    757     const STACK_OF(X509) *certs /* may NULL */)
    758 {
    759     int i;
    760 
    761     if (store == NULL)
    762         store = X509_STORE_new();
    763     if (store == NULL)
    764         return NULL;
    765     for (i = 0; i < sk_X509_num(certs); i++) {
    766         if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) {
    767             X509_STORE_free(store);
    768             return NULL;
    769         }
    770     }
    771     return store;
    772 }
    773 
    774 /*
    775  * Create cert store structure with certificates read from given file(s).
    776  * Returns pointer to created X509_STORE on success, NULL on error.
    777  */
    778 X509_STORE *load_certstore(char *input, const char *pass, const char *desc,
    779     X509_VERIFY_PARAM *vpm)
    780 {
    781     X509_STORE *store = NULL;
    782     STACK_OF(X509) *certs = NULL;
    783 
    784     while (input != NULL) {
    785         char *next = next_item(input);
    786         int ok;
    787 
    788         if (!load_cert_certs(input, NULL, &certs, 1, pass, desc, vpm)) {
    789             X509_STORE_free(store);
    790             return NULL;
    791         }
    792         ok = (store = sk_X509_to_store(store, certs)) != NULL;
    793         OSSL_STACK_OF_X509_free(certs);
    794         certs = NULL;
    795         if (!ok)
    796             return NULL;
    797         input = next;
    798     }
    799     return store;
    800 }
    801 
    802 /*
    803  * Initialize or extend, if *certs != NULL, a certificate stack.
    804  * The caller is responsible for freeing *certs if its value is left not NULL.
    805  */
    806 int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs,
    807     const char *pass, const char *desc)
    808 {
    809     int ret, was_NULL = *certs == NULL;
    810 
    811     if (desc == NULL)
    812         desc = "certificates";
    813     ret = load_key_certs_crls(uri, FORMAT_UNDEF, maybe_stdin, pass, desc, 0,
    814         NULL, NULL, NULL, NULL, certs, NULL, NULL);
    815 
    816     if (!ret && was_NULL) {
    817         OSSL_STACK_OF_X509_free(*certs);
    818         *certs = NULL;
    819     }
    820     return ret;
    821 }
    822 
    823 /*
    824  * Initialize or extend, if *crls != NULL, a certificate stack.
    825  * The caller is responsible for freeing *crls if its value is left not NULL.
    826  */
    827 int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
    828     const char *pass, const char *desc)
    829 {
    830     int ret, was_NULL = *crls == NULL;
    831 
    832     if (desc == NULL)
    833         desc = "CRLs";
    834     ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass, desc, 0,
    835         NULL, NULL, NULL, NULL, NULL, NULL, crls);
    836 
    837     if (!ret && was_NULL) {
    838         sk_X509_CRL_pop_free(*crls, X509_CRL_free);
    839         *crls = NULL;
    840     }
    841     return ret;
    842 }
    843 
    844 static const char *format2string(int format)
    845 {
    846     switch (format) {
    847     case FORMAT_PEM:
    848         return "PEM";
    849     case FORMAT_ASN1:
    850         return "DER";
    851     case FORMAT_PVK:
    852         return "PVK";
    853     case FORMAT_MSBLOB:
    854         return "MSBLOB";
    855     }
    856     return NULL;
    857 }
    858 
    859 /* Set type expectation, but set to 0 if objects of multiple types expected. */
    860 #define SET_EXPECT(val) \
    861     (expect = expect < 0 ? (val) : (expect == (val) ? (val) : 0))
    862 #define SET_EXPECT1(pvar, val) \
    863     if ((pvar) != NULL) {      \
    864         *(pvar) = NULL;        \
    865         SET_EXPECT(val);       \
    866     }
    867 /* Provide (error msg) text for some of the credential types to be loaded. */
    868 #define FAIL_NAME                                                       \
    869     (ppkey != NULL ? "private key" : ppubkey != NULL ? "public key"     \
    870             : pparams != NULL                        ? "key parameters" \
    871             : pcert != NULL                          ? "certificate"    \
    872             : pcerts != NULL                         ? "certificates"   \
    873             : pcrl != NULL                           ? "CRL"            \
    874             : pcrls != NULL                          ? "CRLs"           \
    875                                                      : NULL)
    876 /*
    877  * Load those types of credentials for which the result pointer is not NULL.
    878  * Reads from stdin if 'uri' is NULL and 'maybe_stdin' is nonzero.
    879  * 'format' parameter may be FORMAT_PEM, FORMAT_ASN1, or 0 for no hint.
    880  * desc may contain more detail on the credential(s) to be loaded for error msg
    881  * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
    882  * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
    883  * If pcerts is non-NULL then all available certificates are appended to *pcerts
    884  * except any certificate assigned to *pcert.
    885  * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
    886  * If pcrls is non-NULL then all available CRLs are appended to *pcerts
    887  * except any CRL assigned to *pcrl.
    888  * In any case (also on error) the caller is responsible for freeing all members
    889  * of *pcerts and *pcrls (as far as they are not NULL).
    890  */
    891 int load_key_certs_crls(const char *uri, int format, int maybe_stdin,
    892     const char *pass, const char *desc, int quiet,
    893     EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
    894     EVP_PKEY **pparams,
    895     X509 **pcert, STACK_OF(X509) **pcerts,
    896     X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
    897 {
    898     PW_CB_DATA uidata;
    899     OSSL_STORE_CTX *ctx = NULL;
    900     OSSL_LIB_CTX *libctx = app_get0_libctx();
    901     const char *propq = app_get0_propq();
    902     int ncerts = 0, ncrls = 0, expect = -1;
    903     const char *failed = FAIL_NAME;
    904     const char *input_type;
    905     OSSL_PARAM itp[2];
    906     const OSSL_PARAM *params = NULL;
    907 
    908     /* 'failed' describes type of credential to load for potential error msg */
    909     if (failed == NULL) {
    910         if (!quiet)
    911             BIO_printf(bio_err, "Internal error: nothing was requested to load from %s\n",
    912                 uri != NULL ? uri : "<stdin>");
    913         return 0;
    914     }
    915     /* suppress any extraneous errors left over from failed parse attempts */
    916     ERR_set_mark();
    917 
    918     SET_EXPECT1(ppkey, OSSL_STORE_INFO_PKEY);
    919     SET_EXPECT1(ppubkey, OSSL_STORE_INFO_PUBKEY);
    920     SET_EXPECT1(pparams, OSSL_STORE_INFO_PARAMS);
    921     SET_EXPECT1(pcert, OSSL_STORE_INFO_CERT);
    922     /*
    923      * Up to here, the following holds.
    924      * If just one of the ppkey, ppubkey, pparams, and pcert function parameters
    925      * is nonzero, expect > 0 indicates which type of credential is expected.
    926      * If expect == 0, more than one of them is nonzero (multiple types expected).
    927      */
    928 
    929     if (pcerts != NULL) {
    930         if (*pcerts == NULL && (*pcerts = sk_X509_new_null()) == NULL) {
    931             if (!quiet)
    932                 BIO_printf(bio_err, "Out of memory loading");
    933             goto end;
    934         }
    935         /*
    936          * Adapt the 'expect' variable:
    937          * set to OSSL_STORE_INFO_CERT if no other type is expected so far,
    938          * otherwise set to 0 (indicating that multiple types are expected).
    939          */
    940         SET_EXPECT(OSSL_STORE_INFO_CERT);
    941     }
    942     SET_EXPECT1(pcrl, OSSL_STORE_INFO_CRL);
    943     if (pcrls != NULL) {
    944         if (*pcrls == NULL && (*pcrls = sk_X509_CRL_new_null()) == NULL) {
    945             if (!quiet)
    946                 BIO_printf(bio_err, "Out of memory loading");
    947             goto end;
    948         }
    949         /*
    950          * Adapt the 'expect' variable:
    951          * set to OSSL_STORE_INFO_CRL if no other type is expected so far,
    952          * otherwise set to 0 (indicating that multiple types are expected).
    953          */
    954         SET_EXPECT(OSSL_STORE_INFO_CRL);
    955     }
    956 
    957     uidata.password = pass;
    958     uidata.prompt_info = uri;
    959 
    960     if ((input_type = format2string(format)) != NULL) {
    961         itp[0] = OSSL_PARAM_construct_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE,
    962             (char *)input_type, 0);
    963         itp[1] = OSSL_PARAM_construct_end();
    964         params = itp;
    965     }
    966 
    967     if (uri == NULL) {
    968         BIO *bio;
    969 
    970         if (!maybe_stdin) {
    971             if (!quiet)
    972                 BIO_printf(bio_err, "No filename or uri specified for loading\n");
    973             goto end;
    974         }
    975         uri = "<stdin>";
    976         unbuffer(stdin);
    977         bio = BIO_new_fp(stdin, 0);
    978         if (bio != NULL) {
    979             ctx = OSSL_STORE_attach(bio, "file", libctx, propq,
    980                 get_ui_method(), &uidata, params,
    981                 NULL, NULL);
    982             BIO_free(bio);
    983         }
    984     } else {
    985         ctx = OSSL_STORE_open_ex(uri, libctx, propq, get_ui_method(), &uidata,
    986             params, NULL, NULL);
    987     }
    988     if (ctx == NULL) {
    989         if (!quiet)
    990             BIO_printf(bio_err, "Could not open file or uri for loading");
    991         goto end;
    992     }
    993     /* expect == 0 means here multiple types of credentials are to be loaded */
    994     if (expect > 0 && !OSSL_STORE_expect(ctx, expect)) {
    995         if (!quiet)
    996             BIO_printf(bio_err, "Internal error trying to load");
    997         goto end;
    998     }
    999 
   1000     failed = NULL;
   1001     /* from here, failed != NULL only if actually an error has been detected */
   1002 
   1003     while ((ppkey != NULL || ppubkey != NULL || pparams != NULL
   1004                || pcert != NULL || pcerts != NULL || pcrl != NULL || pcrls != NULL)
   1005         && !OSSL_STORE_eof(ctx)) {
   1006         OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
   1007         int type, ok = 1;
   1008 
   1009         /*
   1010          * This can happen (for example) if we attempt to load a file with
   1011          * multiple different types of things in it - but the thing we just
   1012          * tried to load wasn't one of the ones we wanted, e.g. if we're trying
   1013          * to load a certificate but the file has both the private key and the
   1014          * certificate in it. We just retry until eof.
   1015          */
   1016         if (info == NULL) {
   1017             continue;
   1018         }
   1019 
   1020         type = OSSL_STORE_INFO_get_type(info);
   1021         switch (type) {
   1022         case OSSL_STORE_INFO_PKEY:
   1023             if (ppkey != NULL) {
   1024                 ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL;
   1025                 if (ok)
   1026                     ppkey = NULL;
   1027                 break;
   1028             }
   1029             /*
   1030              * An EVP_PKEY with private parts also holds the public parts,
   1031              * so if the caller asked for a public key, and we got a private
   1032              * key, we can still pass it back.
   1033              */
   1034             /* fall through */
   1035         case OSSL_STORE_INFO_PUBKEY:
   1036             if (ppubkey != NULL) {
   1037                 ok = (*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL;
   1038                 if (ok)
   1039                     ppubkey = NULL;
   1040             }
   1041             break;
   1042         case OSSL_STORE_INFO_PARAMS:
   1043             if (pparams != NULL) {
   1044                 ok = (*pparams = OSSL_STORE_INFO_get1_PARAMS(info)) != NULL;
   1045                 if (ok)
   1046                     pparams = NULL;
   1047             }
   1048             break;
   1049         case OSSL_STORE_INFO_CERT:
   1050             if (pcert != NULL) {
   1051                 ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL;
   1052                 if (ok)
   1053                     pcert = NULL;
   1054             } else if (pcerts != NULL) {
   1055                 ok = X509_add_cert(*pcerts,
   1056                     OSSL_STORE_INFO_get1_CERT(info),
   1057                     X509_ADD_FLAG_DEFAULT);
   1058             }
   1059             ncerts += ok;
   1060             break;
   1061         case OSSL_STORE_INFO_CRL:
   1062             if (pcrl != NULL) {
   1063                 ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL;
   1064                 if (ok)
   1065                     pcrl = NULL;
   1066             } else if (pcrls != NULL) {
   1067                 ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info));
   1068             }
   1069             ncrls += ok;
   1070             break;
   1071         default:
   1072             /* skip any other type; ok stays == 1 */
   1073             break;
   1074         }
   1075         OSSL_STORE_INFO_free(info);
   1076         if (!ok) {
   1077             failed = OSSL_STORE_INFO_type_string(type);
   1078             if (!quiet)
   1079                 BIO_printf(bio_err, "Error reading");
   1080             break;
   1081         }
   1082     }
   1083 
   1084 end:
   1085     OSSL_STORE_close(ctx);
   1086 
   1087     /* see if any of the requested types of credentials was not found */
   1088     if (failed == NULL) {
   1089         if (ncerts > 0)
   1090             pcerts = NULL;
   1091         if (ncrls > 0)
   1092             pcrls = NULL;
   1093         failed = FAIL_NAME;
   1094         if (failed != NULL && !quiet)
   1095             BIO_printf(bio_err, "Could not find");
   1096     }
   1097 
   1098     if (failed != NULL && !quiet) {
   1099         unsigned long err = ERR_peek_last_error();
   1100 
   1101         /* continue the error message with the type of credential affected */
   1102         if (desc != NULL && strstr(desc, failed) != NULL) {
   1103             BIO_printf(bio_err, " %s", desc);
   1104         } else {
   1105             BIO_printf(bio_err, " %s", failed);
   1106             if (desc != NULL)
   1107                 BIO_printf(bio_err, " of %s", desc);
   1108         }
   1109         if (uri != NULL)
   1110             BIO_printf(bio_err, " from %s", uri);
   1111         if (ERR_SYSTEM_ERROR(err)) {
   1112             /* provide more readable diagnostic output */
   1113             BIO_printf(bio_err, ": %s", strerror(ERR_GET_REASON(err)));
   1114             ERR_pop_to_mark();
   1115             ERR_set_mark();
   1116         }
   1117         BIO_printf(bio_err, "\n");
   1118         ERR_print_errors(bio_err);
   1119     }
   1120     if (quiet || failed == NULL)
   1121         /* clear any suppressed or spurious errors */
   1122         ERR_pop_to_mark();
   1123     else
   1124         ERR_clear_last_mark();
   1125     return failed == NULL;
   1126 }
   1127 
   1128 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
   1129 #define X509V3_EXT_DEFAULT 0 /* Return error for unknown exts */
   1130 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16) /* Print error for unknown exts */
   1131 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16) /* ASN1 parse unknown extensions */
   1132 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16) /* BIO_dump unknown extensions */
   1133 
   1134 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
   1135 
   1136 int set_cert_ex(unsigned long *flags, const char *arg)
   1137 {
   1138     static const NAME_EX_TBL cert_tbl[] = {
   1139         { "compatible", X509_FLAG_COMPAT, 0xffffffffl },
   1140         { "ca_default", X509_FLAG_CA, 0xffffffffl },
   1141         { "no_header", X509_FLAG_NO_HEADER, 0 },
   1142         { "no_version", X509_FLAG_NO_VERSION, 0 },
   1143         { "no_serial", X509_FLAG_NO_SERIAL, 0 },
   1144         { "no_signame", X509_FLAG_NO_SIGNAME, 0 },
   1145         { "no_validity", X509_FLAG_NO_VALIDITY, 0 },
   1146         { "no_subject", X509_FLAG_NO_SUBJECT, 0 },
   1147         { "no_issuer", X509_FLAG_NO_ISSUER, 0 },
   1148         { "no_pubkey", X509_FLAG_NO_PUBKEY, 0 },
   1149         { "no_extensions", X509_FLAG_NO_EXTENSIONS, 0 },
   1150         { "no_sigdump", X509_FLAG_NO_SIGDUMP, 0 },
   1151         { "no_aux", X509_FLAG_NO_AUX, 0 },
   1152         { "no_attributes", X509_FLAG_NO_ATTRIBUTES, 0 },
   1153         { "ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK },
   1154         { "ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK },
   1155         { "ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK },
   1156         { "ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK },
   1157         { NULL, 0, 0 }
   1158     };
   1159     return set_multi_opts(flags, arg, cert_tbl);
   1160 }
   1161 
   1162 int set_name_ex(unsigned long *flags, const char *arg)
   1163 {
   1164     static const NAME_EX_TBL ex_tbl[] = {
   1165         { "esc_2253", ASN1_STRFLGS_ESC_2253, 0 },
   1166         { "esc_2254", ASN1_STRFLGS_ESC_2254, 0 },
   1167         { "esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0 },
   1168         { "esc_msb", ASN1_STRFLGS_ESC_MSB, 0 },
   1169         { "use_quote", ASN1_STRFLGS_ESC_QUOTE, 0 },
   1170         { "utf8", ASN1_STRFLGS_UTF8_CONVERT, 0 },
   1171         { "ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0 },
   1172         { "show_type", ASN1_STRFLGS_SHOW_TYPE, 0 },
   1173         { "dump_all", ASN1_STRFLGS_DUMP_ALL, 0 },
   1174         { "dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0 },
   1175         { "dump_der", ASN1_STRFLGS_DUMP_DER, 0 },
   1176         { "compat", XN_FLAG_COMPAT, 0xffffffffL },
   1177         { "sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK },
   1178         { "sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK },
   1179         { "sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK },
   1180         { "sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK },
   1181         { "dn_rev", XN_FLAG_DN_REV, 0 },
   1182         { "nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK },
   1183         { "sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK },
   1184         { "lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK },
   1185         { "align", XN_FLAG_FN_ALIGN, 0 },
   1186         { "oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK },
   1187         { "space_eq", XN_FLAG_SPC_EQ, 0 },
   1188         { "dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0 },
   1189         { "RFC2253", XN_FLAG_RFC2253, 0xffffffffL },
   1190         { "oneline", XN_FLAG_ONELINE, 0xffffffffL },
   1191         { "multiline", XN_FLAG_MULTILINE, 0xffffffffL },
   1192         { "ca_default", XN_FLAG_MULTILINE, 0xffffffffL },
   1193         { NULL, 0, 0 }
   1194     };
   1195     if (set_multi_opts(flags, arg, ex_tbl) == 0)
   1196         return 0;
   1197     if (*flags != XN_FLAG_COMPAT
   1198         && (*flags & XN_FLAG_SEP_MASK) == 0)
   1199         *flags |= XN_FLAG_SEP_CPLUS_SPC;
   1200     return 1;
   1201 }
   1202 
   1203 int set_dateopt(unsigned long *dateopt, const char *arg)
   1204 {
   1205     if (OPENSSL_strcasecmp(arg, "rfc_822") == 0)
   1206         *dateopt = ASN1_DTFLGS_RFC822;
   1207     else if (OPENSSL_strcasecmp(arg, "iso_8601") == 0)
   1208         *dateopt = ASN1_DTFLGS_ISO8601;
   1209     else
   1210         return 0;
   1211     return 1;
   1212 }
   1213 
   1214 int set_ext_copy(int *copy_type, const char *arg)
   1215 {
   1216     if (OPENSSL_strcasecmp(arg, "none") == 0)
   1217         *copy_type = EXT_COPY_NONE;
   1218     else if (OPENSSL_strcasecmp(arg, "copy") == 0)
   1219         *copy_type = EXT_COPY_ADD;
   1220     else if (OPENSSL_strcasecmp(arg, "copyall") == 0)
   1221         *copy_type = EXT_COPY_ALL;
   1222     else
   1223         return 0;
   1224     return 1;
   1225 }
   1226 
   1227 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
   1228 {
   1229     STACK_OF(X509_EXTENSION) *exts;
   1230     int i, ret = 0;
   1231 
   1232     if (x == NULL || req == NULL)
   1233         return 0;
   1234     if (copy_type == EXT_COPY_NONE)
   1235         return 1;
   1236     exts = X509_REQ_get_extensions(req);
   1237 
   1238     for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
   1239         X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
   1240         ASN1_OBJECT *obj = X509_EXTENSION_get_object(ext);
   1241         int idx = X509_get_ext_by_OBJ(x, obj, -1);
   1242 
   1243         /* Does extension exist in target? */
   1244         if (idx != -1) {
   1245             /* If normal copy don't override existing extension */
   1246             if (copy_type == EXT_COPY_ADD)
   1247                 continue;
   1248             /* Delete all extensions of same type */
   1249             do {
   1250                 X509_EXTENSION_free(X509_delete_ext(x, idx));
   1251                 idx = X509_get_ext_by_OBJ(x, obj, -1);
   1252             } while (idx != -1);
   1253         }
   1254         if (!X509_add_ext(x, ext, -1))
   1255             goto end;
   1256     }
   1257     ret = 1;
   1258 
   1259 end:
   1260     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
   1261     return ret;
   1262 }
   1263 
   1264 static int set_multi_opts(unsigned long *flags, const char *arg,
   1265     const NAME_EX_TBL *in_tbl)
   1266 {
   1267     STACK_OF(CONF_VALUE) *vals;
   1268     CONF_VALUE *val;
   1269     int i, ret = 1;
   1270 
   1271     if (!arg)
   1272         return 0;
   1273     vals = X509V3_parse_list(arg);
   1274     for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
   1275         val = sk_CONF_VALUE_value(vals, i);
   1276         if (!set_table_opts(flags, val->name, in_tbl))
   1277             ret = 0;
   1278     }
   1279     sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
   1280     return ret;
   1281 }
   1282 
   1283 static int set_table_opts(unsigned long *flags, const char *arg,
   1284     const NAME_EX_TBL *in_tbl)
   1285 {
   1286     char c;
   1287     const NAME_EX_TBL *ptbl;
   1288 
   1289     c = arg[0];
   1290     if (c == '-') {
   1291         c = 0;
   1292         arg++;
   1293     } else if (c == '+') {
   1294         c = 1;
   1295         arg++;
   1296     } else {
   1297         c = 1;
   1298     }
   1299 
   1300     for (ptbl = in_tbl; ptbl->name; ptbl++) {
   1301         if (OPENSSL_strcasecmp(arg, ptbl->name) == 0) {
   1302             *flags &= ~ptbl->mask;
   1303             if (c)
   1304                 *flags |= ptbl->flag;
   1305             else
   1306                 *flags &= ~ptbl->flag;
   1307             return 1;
   1308         }
   1309     }
   1310     return 0;
   1311 }
   1312 
   1313 void print_name(BIO *out, const char *title, const X509_NAME *nm)
   1314 {
   1315     char *buf;
   1316     char mline = 0;
   1317     int indent = 0;
   1318     unsigned long lflags = get_nameopt();
   1319 
   1320     if (out == NULL)
   1321         return;
   1322     if (title != NULL)
   1323         BIO_puts(out, title);
   1324     if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
   1325         mline = 1;
   1326         indent = 4;
   1327     }
   1328     if (lflags == XN_FLAG_COMPAT) {
   1329         buf = X509_NAME_oneline(nm, 0, 0);
   1330         BIO_puts(out, buf);
   1331         BIO_puts(out, "\n");
   1332         OPENSSL_free(buf);
   1333     } else {
   1334         if (mline)
   1335             BIO_puts(out, "\n");
   1336         X509_NAME_print_ex(out, nm, indent, lflags);
   1337         BIO_puts(out, "\n");
   1338     }
   1339 }
   1340 
   1341 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
   1342     int len, unsigned char *buffer)
   1343 {
   1344     BIO_printf(out, "    static unsigned char %s_%d[] = {", var, len);
   1345     if (BN_is_zero(in)) {
   1346         BIO_printf(out, "\n        0x00");
   1347     } else {
   1348         int i, l;
   1349 
   1350         l = BN_bn2bin(in, buffer);
   1351         for (i = 0; i < l; i++) {
   1352             BIO_printf(out, (i % 10) == 0 ? "\n        " : " ");
   1353             if (i < l - 1)
   1354                 BIO_printf(out, "0x%02X,", buffer[i]);
   1355             else
   1356                 BIO_printf(out, "0x%02X", buffer[i]);
   1357         }
   1358     }
   1359     BIO_printf(out, "\n    };\n");
   1360 }
   1361 
   1362 void print_array(BIO *out, const char *title, int len, const unsigned char *d)
   1363 {
   1364     int i;
   1365 
   1366     BIO_printf(out, "unsigned char %s[%d] = {", title, len);
   1367     for (i = 0; i < len; i++) {
   1368         if ((i % 10) == 0)
   1369             BIO_printf(out, "\n    ");
   1370         if (i < len - 1)
   1371             BIO_printf(out, "0x%02X, ", d[i]);
   1372         else
   1373             BIO_printf(out, "0x%02X", d[i]);
   1374     }
   1375     BIO_printf(out, "\n};\n");
   1376 }
   1377 
   1378 X509_STORE *setup_verify(const char *CAfile, int noCAfile,
   1379     const char *CApath, int noCApath,
   1380     const char *CAstore, int noCAstore)
   1381 {
   1382     X509_STORE *store = X509_STORE_new();
   1383     X509_LOOKUP *lookup;
   1384     OSSL_LIB_CTX *libctx = app_get0_libctx();
   1385     const char *propq = app_get0_propq();
   1386 
   1387     if (store == NULL)
   1388         goto end;
   1389 
   1390     if (CAfile != NULL || !noCAfile) {
   1391         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
   1392         if (lookup == NULL)
   1393             goto end;
   1394         if (CAfile != NULL) {
   1395             if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM,
   1396                     libctx, propq)
   1397                 <= 0) {
   1398                 ERR_clear_error();
   1399                 if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_ASN1,
   1400                         libctx, propq)
   1401                     <= 0) {
   1402                     BIO_printf(bio_err, "Error loading file %s\n", CAfile);
   1403                     goto end;
   1404                 }
   1405             }
   1406         } else {
   1407             X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT,
   1408                 libctx, propq);
   1409         }
   1410     }
   1411 
   1412     if (CApath != NULL || !noCApath) {
   1413         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
   1414         if (lookup == NULL)
   1415             goto end;
   1416         if (CApath != NULL) {
   1417             if (X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM) <= 0) {
   1418                 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
   1419                 goto end;
   1420             }
   1421         } else {
   1422             X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
   1423         }
   1424     }
   1425 
   1426     if (CAstore != NULL || !noCAstore) {
   1427         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
   1428         if (lookup == NULL)
   1429             goto end;
   1430         if (!X509_LOOKUP_add_store_ex(lookup, CAstore, libctx, propq)) {
   1431             if (CAstore != NULL)
   1432                 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
   1433             goto end;
   1434         }
   1435     }
   1436 
   1437     ERR_clear_error();
   1438     return store;
   1439 end:
   1440     ERR_print_errors(bio_err);
   1441     X509_STORE_free(store);
   1442     return NULL;
   1443 }
   1444 
   1445 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
   1446 {
   1447     const char *n;
   1448 
   1449     n = a[DB_serial];
   1450     while (*n == '0')
   1451         n++;
   1452     return OPENSSL_LH_strhash(n);
   1453 }
   1454 
   1455 static int index_serial_cmp(const OPENSSL_CSTRING *a,
   1456     const OPENSSL_CSTRING *b)
   1457 {
   1458     const char *aa, *bb;
   1459 
   1460     for (aa = a[DB_serial]; *aa == '0'; aa++)
   1461         ;
   1462     for (bb = b[DB_serial]; *bb == '0'; bb++)
   1463         ;
   1464     return strcmp(aa, bb);
   1465 }
   1466 
   1467 static int index_name_qual(char **a)
   1468 {
   1469     return (a[0][0] == 'V');
   1470 }
   1471 
   1472 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
   1473 {
   1474     return OPENSSL_LH_strhash(a[DB_name]);
   1475 }
   1476 
   1477 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
   1478 {
   1479     return strcmp(a[DB_name], b[DB_name]);
   1480 }
   1481 
   1482 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
   1483 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
   1484 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
   1485 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
   1486 #undef BSIZE
   1487 #define BSIZE 256
   1488 BIGNUM *load_serial(const char *serialfile, int *exists, int create,
   1489     ASN1_INTEGER **retai)
   1490 {
   1491     BIO *in = NULL;
   1492     BIGNUM *ret = NULL;
   1493     char buf[1024];
   1494     ASN1_INTEGER *ai = NULL;
   1495 
   1496     ai = ASN1_INTEGER_new();
   1497     if (ai == NULL)
   1498         goto err;
   1499 
   1500     in = BIO_new_file(serialfile, "r");
   1501     if (exists != NULL)
   1502         *exists = in != NULL;
   1503     if (in == NULL) {
   1504         if (!create) {
   1505             perror(serialfile);
   1506             goto err;
   1507         }
   1508         ERR_clear_error();
   1509         ret = BN_new();
   1510         if (ret == NULL) {
   1511             BIO_printf(bio_err, "Out of memory\n");
   1512         } else if (!rand_serial(ret, ai)) {
   1513             BIO_printf(bio_err, "Error creating random number to store in %s\n",
   1514                 serialfile);
   1515             BN_free(ret);
   1516             ret = NULL;
   1517         }
   1518     } else {
   1519         if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
   1520             BIO_printf(bio_err, "Unable to load number from %s\n",
   1521                 serialfile);
   1522             goto err;
   1523         }
   1524         ret = ASN1_INTEGER_to_BN(ai, NULL);
   1525         if (ret == NULL) {
   1526             BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
   1527             goto err;
   1528         }
   1529     }
   1530 
   1531     if (ret != NULL && retai != NULL) {
   1532         *retai = ai;
   1533         ai = NULL;
   1534     }
   1535 err:
   1536     if (ret == NULL)
   1537         ERR_print_errors(bio_err);
   1538     BIO_free(in);
   1539     ASN1_INTEGER_free(ai);
   1540     return ret;
   1541 }
   1542 
   1543 int save_serial(const char *serialfile, const char *suffix,
   1544     const BIGNUM *serial, ASN1_INTEGER **retai)
   1545 {
   1546     char buf[1][BSIZE];
   1547     BIO *out = NULL;
   1548     int ret = 0;
   1549     ASN1_INTEGER *ai = NULL;
   1550     int j;
   1551 
   1552     if (suffix == NULL)
   1553         j = strlen(serialfile);
   1554     else
   1555         j = strlen(serialfile) + strlen(suffix) + 1;
   1556     if (j >= BSIZE) {
   1557         BIO_printf(bio_err, "File name too long\n");
   1558         goto err;
   1559     }
   1560 
   1561     if (suffix == NULL) {
   1562         OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
   1563     } else {
   1564 #ifndef OPENSSL_SYS_VMS
   1565         BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
   1566 #else
   1567         BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
   1568 #endif
   1569     }
   1570     out = BIO_new_file(buf[0], "w");
   1571     if (out == NULL) {
   1572         goto err;
   1573     }
   1574 
   1575     if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
   1576         BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
   1577         goto err;
   1578     }
   1579     i2a_ASN1_INTEGER(out, ai);
   1580     BIO_puts(out, "\n");
   1581     ret = 1;
   1582     if (retai) {
   1583         *retai = ai;
   1584         ai = NULL;
   1585     }
   1586 err:
   1587     if (!ret)
   1588         ERR_print_errors(bio_err);
   1589     BIO_free_all(out);
   1590     ASN1_INTEGER_free(ai);
   1591     return ret;
   1592 }
   1593 
   1594 int rotate_serial(const char *serialfile, const char *new_suffix,
   1595     const char *old_suffix)
   1596 {
   1597     char buf[2][BSIZE];
   1598     int i, j;
   1599 
   1600     i = strlen(serialfile) + strlen(old_suffix);
   1601     j = strlen(serialfile) + strlen(new_suffix);
   1602     if (i > j)
   1603         j = i;
   1604     if (j + 1 >= BSIZE) {
   1605         BIO_printf(bio_err, "File name too long\n");
   1606         goto err;
   1607     }
   1608 #ifndef OPENSSL_SYS_VMS
   1609     BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
   1610     BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
   1611 #else
   1612     BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
   1613     BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
   1614 #endif
   1615     if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
   1616 #ifdef ENOTDIR
   1617         && errno != ENOTDIR
   1618 #endif
   1619     ) {
   1620         BIO_printf(bio_err,
   1621             "Unable to rename %s to %s\n", serialfile, buf[1]);
   1622         perror("reason");
   1623         goto err;
   1624     }
   1625     if (rename(buf[0], serialfile) < 0) {
   1626         BIO_printf(bio_err,
   1627             "Unable to rename %s to %s\n", buf[0], serialfile);
   1628         perror("reason");
   1629         rename(buf[1], serialfile);
   1630         goto err;
   1631     }
   1632     return 1;
   1633 err:
   1634     ERR_print_errors(bio_err);
   1635     return 0;
   1636 }
   1637 
   1638 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
   1639 {
   1640     BIGNUM *btmp;
   1641     int ret = 0;
   1642 
   1643     btmp = b == NULL ? BN_new() : b;
   1644     if (btmp == NULL)
   1645         return 0;
   1646 
   1647     if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
   1648         goto error;
   1649     if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
   1650         goto error;
   1651 
   1652     ret = 1;
   1653 
   1654 error:
   1655 
   1656     if (btmp != b)
   1657         BN_free(btmp);
   1658 
   1659     return ret;
   1660 }
   1661 
   1662 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
   1663 {
   1664     CA_DB *retdb = NULL;
   1665     TXT_DB *tmpdb = NULL;
   1666     BIO *in;
   1667     CONF *dbattr_conf = NULL;
   1668     char buf[BSIZE];
   1669 #ifndef OPENSSL_NO_POSIX_IO
   1670     FILE *dbfp;
   1671     struct stat dbst;
   1672 #endif
   1673 
   1674     in = BIO_new_file(dbfile, "r");
   1675     if (in == NULL)
   1676         goto err;
   1677 
   1678 #ifndef OPENSSL_NO_POSIX_IO
   1679     BIO_get_fp(in, &dbfp);
   1680     if (fstat(fileno(dbfp), &dbst) == -1) {
   1681         ERR_raise_data(ERR_LIB_SYS, errno,
   1682             "calling fstat(%s)", dbfile);
   1683         goto err;
   1684     }
   1685 #endif
   1686 
   1687     if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
   1688         goto err;
   1689 
   1690 #ifndef OPENSSL_SYS_VMS
   1691     BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
   1692 #else
   1693     BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
   1694 #endif
   1695     dbattr_conf = app_load_config_quiet(buf);
   1696 
   1697     retdb = app_malloc(sizeof(*retdb), "new DB");
   1698     retdb->db = tmpdb;
   1699     tmpdb = NULL;
   1700     if (db_attr)
   1701         retdb->attributes = *db_attr;
   1702     else
   1703         retdb->attributes.unique_subject = 1;
   1704 
   1705     if (dbattr_conf != NULL) {
   1706         char *p = app_conf_try_string(dbattr_conf, NULL, "unique_subject");
   1707 
   1708         if (p != NULL)
   1709             retdb->attributes.unique_subject = parse_yesno(p, 1);
   1710     }
   1711 
   1712     retdb->dbfname = OPENSSL_strdup(dbfile);
   1713     if (retdb->dbfname == NULL)
   1714         goto err;
   1715 
   1716 #ifndef OPENSSL_NO_POSIX_IO
   1717     retdb->dbst = dbst;
   1718 #endif
   1719 
   1720 err:
   1721     ERR_print_errors(bio_err);
   1722     NCONF_free(dbattr_conf);
   1723     TXT_DB_free(tmpdb);
   1724     BIO_free_all(in);
   1725     return retdb;
   1726 }
   1727 
   1728 /*
   1729  * Returns > 0 on success, <= 0 on error
   1730  */
   1731 int index_index(CA_DB *db)
   1732 {
   1733     if (!TXT_DB_create_index(db->db, DB_serial, NULL,
   1734             LHASH_HASH_FN(index_serial),
   1735             LHASH_COMP_FN(index_serial))) {
   1736         BIO_printf(bio_err,
   1737             "Error creating serial number index:(%ld,%ld,%ld)\n",
   1738             db->db->error, db->db->arg1, db->db->arg2);
   1739         goto err;
   1740     }
   1741 
   1742     if (db->attributes.unique_subject
   1743         && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
   1744             LHASH_HASH_FN(index_name),
   1745             LHASH_COMP_FN(index_name))) {
   1746         BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
   1747             db->db->error, db->db->arg1, db->db->arg2);
   1748         goto err;
   1749     }
   1750     return 1;
   1751 err:
   1752     ERR_print_errors(bio_err);
   1753     return 0;
   1754 }
   1755 
   1756 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
   1757 {
   1758     char buf[3][BSIZE];
   1759     BIO *out;
   1760     int j;
   1761 
   1762     j = strlen(dbfile) + strlen(suffix);
   1763     if (j + 6 >= BSIZE) {
   1764         BIO_printf(bio_err, "File name too long\n");
   1765         goto err;
   1766     }
   1767 #ifndef OPENSSL_SYS_VMS
   1768     BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
   1769     BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
   1770     BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
   1771 #else
   1772     BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
   1773     BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
   1774     BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
   1775 #endif
   1776     out = BIO_new_file(buf[0], "w");
   1777     if (out == NULL) {
   1778         perror(dbfile);
   1779         BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
   1780         goto err;
   1781     }
   1782     j = TXT_DB_write(out, db->db);
   1783     BIO_free(out);
   1784     if (j <= 0)
   1785         goto err;
   1786 
   1787     out = BIO_new_file(buf[1], "w");
   1788     if (out == NULL) {
   1789         perror(buf[2]);
   1790         BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
   1791         goto err;
   1792     }
   1793     BIO_printf(out, "unique_subject = %s\n",
   1794         db->attributes.unique_subject ? "yes" : "no");
   1795     BIO_free(out);
   1796 
   1797     return 1;
   1798 err:
   1799     ERR_print_errors(bio_err);
   1800     return 0;
   1801 }
   1802 
   1803 int rotate_index(const char *dbfile, const char *new_suffix,
   1804     const char *old_suffix)
   1805 {
   1806     char buf[5][BSIZE];
   1807     int i, j;
   1808 
   1809     i = strlen(dbfile) + strlen(old_suffix);
   1810     j = strlen(dbfile) + strlen(new_suffix);
   1811     if (i > j)
   1812         j = i;
   1813     if (j + 6 >= BSIZE) {
   1814         BIO_printf(bio_err, "File name too long\n");
   1815         goto err;
   1816     }
   1817 #ifndef OPENSSL_SYS_VMS
   1818     BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
   1819     BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
   1820     BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
   1821     BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
   1822     BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
   1823 #else
   1824     BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
   1825     BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
   1826     BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
   1827     BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
   1828     BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
   1829 #endif
   1830     if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
   1831 #ifdef ENOTDIR
   1832         && errno != ENOTDIR
   1833 #endif
   1834     ) {
   1835         BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
   1836         perror("reason");
   1837         goto err;
   1838     }
   1839     if (rename(buf[0], dbfile) < 0) {
   1840         BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
   1841         perror("reason");
   1842         rename(buf[1], dbfile);
   1843         goto err;
   1844     }
   1845     if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
   1846 #ifdef ENOTDIR
   1847         && errno != ENOTDIR
   1848 #endif
   1849     ) {
   1850         BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
   1851         perror("reason");
   1852         rename(dbfile, buf[0]);
   1853         rename(buf[1], dbfile);
   1854         goto err;
   1855     }
   1856     if (rename(buf[2], buf[4]) < 0) {
   1857         BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
   1858         perror("reason");
   1859         rename(buf[3], buf[4]);
   1860         rename(dbfile, buf[0]);
   1861         rename(buf[1], dbfile);
   1862         goto err;
   1863     }
   1864     return 1;
   1865 err:
   1866     ERR_print_errors(bio_err);
   1867     return 0;
   1868 }
   1869 
   1870 void free_index(CA_DB *db)
   1871 {
   1872     if (db) {
   1873         TXT_DB_free(db->db);
   1874         OPENSSL_free(db->dbfname);
   1875         OPENSSL_free(db);
   1876     }
   1877 }
   1878 
   1879 int parse_yesno(const char *str, int def)
   1880 {
   1881     if (str) {
   1882         switch (*str) {
   1883         case 'f': /* false */
   1884         case 'F': /* FALSE */
   1885         case 'n': /* no */
   1886         case 'N': /* NO */
   1887         case '0': /* 0 */
   1888             return 0;
   1889         case 't': /* true */
   1890         case 'T': /* TRUE */
   1891         case 'y': /* yes */
   1892         case 'Y': /* YES */
   1893         case '1': /* 1 */
   1894             return 1;
   1895         }
   1896     }
   1897     return def;
   1898 }
   1899 
   1900 /*
   1901  * name is expected to be in the format /type0=value0/type1=value1/type2=...
   1902  * where + can be used instead of / to form multi-valued RDNs if canmulti
   1903  * and characters may be escaped by \
   1904  */
   1905 X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
   1906     const char *desc)
   1907 {
   1908     int nextismulti = 0;
   1909     char *work;
   1910     X509_NAME *n;
   1911 
   1912     if (*cp++ != '/') {
   1913         BIO_printf(bio_err,
   1914             "%s: %s name is expected to be in the format "
   1915             "/type0=value0/type1=value1/type2=... where characters may "
   1916             "be escaped by \\. This name is not in that format: '%s'\n",
   1917             opt_getprog(), desc, --cp);
   1918         return NULL;
   1919     }
   1920 
   1921     n = X509_NAME_new();
   1922     if (n == NULL) {
   1923         BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
   1924         return NULL;
   1925     }
   1926     work = OPENSSL_strdup(cp);
   1927     if (work == NULL) {
   1928         BIO_printf(bio_err, "%s: Error copying %s name input\n",
   1929             opt_getprog(), desc);
   1930         goto err;
   1931     }
   1932 
   1933     while (*cp != '\0') {
   1934         char *bp = work;
   1935         char *typestr = bp;
   1936         unsigned char *valstr;
   1937         int nid;
   1938         int ismulti = nextismulti;
   1939 
   1940         nextismulti = 0;
   1941 
   1942         /* Collect the type */
   1943         while (*cp != '\0' && *cp != '=')
   1944             *bp++ = *cp++;
   1945         *bp++ = '\0';
   1946         if (*cp == '\0') {
   1947             BIO_printf(bio_err,
   1948                 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
   1949                 opt_getprog(), typestr, desc);
   1950             goto err;
   1951         }
   1952         ++cp;
   1953 
   1954         /* Collect the value. */
   1955         valstr = (unsigned char *)bp;
   1956         for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
   1957             /* unescaped '+' symbol string signals further member of multiRDN */
   1958             if (canmulti && *cp == '+') {
   1959                 nextismulti = 1;
   1960                 break;
   1961             }
   1962             if (*cp == '\\' && *++cp == '\0') {
   1963                 BIO_printf(bio_err,
   1964                     "%s: Escape character at end of %s name string\n",
   1965                     opt_getprog(), desc);
   1966                 goto err;
   1967             }
   1968         }
   1969         *bp++ = '\0';
   1970 
   1971         /* If not at EOS (must be + or /), move forward. */
   1972         if (*cp != '\0')
   1973             ++cp;
   1974 
   1975         /* Parse */
   1976         nid = OBJ_txt2nid(typestr);
   1977         if (nid == NID_undef) {
   1978             BIO_printf(bio_err,
   1979                 "%s warning: Skipping unknown %s name attribute \"%s\"\n",
   1980                 opt_getprog(), desc, typestr);
   1981             if (ismulti)
   1982                 BIO_printf(bio_err,
   1983                     "%s hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n",
   1984                     opt_getprog());
   1985             continue;
   1986         }
   1987         if (*valstr == '\0') {
   1988             BIO_printf(bio_err,
   1989                 "%s warning: No value provided for %s name attribute \"%s\", skipped\n",
   1990                 opt_getprog(), desc, typestr);
   1991             continue;
   1992         }
   1993         if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
   1994                 valstr, strlen((char *)valstr),
   1995                 -1, ismulti ? -1 : 0)) {
   1996             ERR_print_errors(bio_err);
   1997             BIO_printf(bio_err,
   1998                 "%s: Error adding %s name attribute \"/%s=%s\"\n",
   1999                 opt_getprog(), desc, typestr, valstr);
   2000             goto err;
   2001         }
   2002     }
   2003 
   2004     OPENSSL_free(work);
   2005     return n;
   2006 
   2007 err:
   2008     X509_NAME_free(n);
   2009     OPENSSL_free(work);
   2010     return NULL;
   2011 }
   2012 
   2013 /*
   2014  * Read whole contents of a BIO into an allocated memory buffer.
   2015  * The return value is one on success, zero on error.
   2016  * If `maxlen` is non-zero, at most `maxlen` bytes are returned, or else, if
   2017  * the input is longer than `maxlen`, an error is returned.
   2018  * If `maxlen` is zero, the limit is effectively `SIZE_MAX`.
   2019  */
   2020 int bio_to_mem(unsigned char **out, size_t *outlen, size_t maxlen, BIO *in)
   2021 {
   2022     unsigned char tbuf[4096];
   2023     BIO *mem;
   2024     BUF_MEM *bufm;
   2025     size_t sz = 0;
   2026     int len;
   2027 
   2028     mem = BIO_new(BIO_s_mem());
   2029     if (mem == NULL)
   2030         return 0;
   2031     for (;;) {
   2032         if ((len = BIO_read(in, tbuf, 4096)) == 0)
   2033             break;
   2034         if (len < 0
   2035             || BIO_write(mem, tbuf, len) != len
   2036             || sz > SIZE_MAX - len
   2037             || ((sz += len) > maxlen && maxlen != 0)) {
   2038             BIO_free(mem);
   2039             return 0;
   2040         }
   2041     }
   2042 
   2043     /* So BIO_free orphans BUF_MEM */
   2044     (void)BIO_set_close(mem, BIO_NOCLOSE);
   2045     BIO_get_mem_ptr(mem, &bufm);
   2046     BIO_free(mem);
   2047     *out = (unsigned char *)bufm->data;
   2048     *outlen = bufm->length;
   2049     /* Tell BUF_MEM to orphan data */
   2050     bufm->data = NULL;
   2051     BUF_MEM_free(bufm);
   2052     return 1;
   2053 }
   2054 
   2055 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
   2056 {
   2057     int rv = 0;
   2058     char *stmp, *vtmp = NULL;
   2059 
   2060     stmp = OPENSSL_strdup(value);
   2061     if (stmp == NULL)
   2062         return -1;
   2063     vtmp = strchr(stmp, ':');
   2064     if (vtmp == NULL)
   2065         goto err;
   2066 
   2067     *vtmp = 0;
   2068     vtmp++;
   2069     rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
   2070 
   2071 err:
   2072     OPENSSL_free(stmp);
   2073     return rv;
   2074 }
   2075 
   2076 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
   2077 {
   2078     X509_POLICY_NODE *node;
   2079     int i;
   2080 
   2081     BIO_printf(bio_err, "%s Policies:", name);
   2082     if (nodes) {
   2083         BIO_puts(bio_err, "\n");
   2084         for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
   2085             node = sk_X509_POLICY_NODE_value(nodes, i);
   2086             X509_POLICY_NODE_print(bio_err, node, 2);
   2087         }
   2088     } else {
   2089         BIO_puts(bio_err, " <empty>\n");
   2090     }
   2091 }
   2092 
   2093 void policies_print(X509_STORE_CTX *ctx)
   2094 {
   2095     X509_POLICY_TREE *tree;
   2096     int explicit_policy;
   2097 
   2098     tree = X509_STORE_CTX_get0_policy_tree(ctx);
   2099     explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
   2100 
   2101     BIO_printf(bio_err, "Require explicit Policy: %s\n",
   2102         explicit_policy ? "True" : "False");
   2103 
   2104     nodes_print("Authority", X509_policy_tree_get0_policies(tree));
   2105     nodes_print("User", X509_policy_tree_get0_user_policies(tree));
   2106 }
   2107 
   2108 /*-
   2109  * next_protos_parse parses a comma separated list of strings into a string
   2110  * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
   2111  *   outlen: (output) set to the length of the resulting buffer on success.
   2112  *   err: (maybe NULL) on failure, an error message line is written to this BIO.
   2113  *   in: a NUL terminated string like "abc,def,ghi"
   2114  *
   2115  *   returns: a malloc'd buffer or NULL on failure.
   2116  */
   2117 unsigned char *next_protos_parse(size_t *outlen, const char *in)
   2118 {
   2119     size_t len;
   2120     unsigned char *out;
   2121     size_t i, start = 0;
   2122     size_t skipped = 0;
   2123 
   2124     len = strlen(in);
   2125     if (len == 0 || len >= 65535)
   2126         return NULL;
   2127 
   2128     out = app_malloc(len + 1, "NPN buffer");
   2129     for (i = 0; i <= len; ++i) {
   2130         if (i == len || in[i] == ',') {
   2131             /*
   2132              * Zero-length ALPN elements are invalid on the wire, we could be
   2133              * strict and reject the entire string, but just ignoring extra
   2134              * commas seems harmless and more friendly.
   2135              *
   2136              * Every comma we skip in this way puts the input buffer another
   2137              * byte ahead of the output buffer, so all stores into the output
   2138              * buffer need to be decremented by the number commas skipped.
   2139              */
   2140             if (i == start) {
   2141                 ++start;
   2142                 ++skipped;
   2143                 continue;
   2144             }
   2145             if (i - start > 255) {
   2146                 OPENSSL_free(out);
   2147                 return NULL;
   2148             }
   2149             out[start - skipped] = (unsigned char)(i - start);
   2150             start = i + 1;
   2151         } else {
   2152             out[i + 1 - skipped] = in[i];
   2153         }
   2154     }
   2155 
   2156     if (len <= skipped) {
   2157         OPENSSL_free(out);
   2158         return NULL;
   2159     }
   2160 
   2161     *outlen = len + 1 - skipped;
   2162     return out;
   2163 }
   2164 
   2165 int check_cert_attributes(BIO *bio, X509 *x, const char *checkhost,
   2166     const char *checkemail, const char *checkip,
   2167     int print)
   2168 {
   2169     int valid_host = 0;
   2170     int valid_mail = 0;
   2171     int valid_ip = 0;
   2172     int ret = 1;
   2173 
   2174     if (x == NULL)
   2175         return 0;
   2176 
   2177     if (checkhost != NULL) {
   2178         valid_host = X509_check_host(x, checkhost, 0, 0, NULL);
   2179         if (print)
   2180             BIO_printf(bio, "Hostname %s does%s match certificate\n",
   2181                 checkhost, valid_host == 1 ? "" : " NOT");
   2182         ret = ret && valid_host > 0;
   2183     }
   2184 
   2185     if (checkemail != NULL) {
   2186         valid_mail = X509_check_email(x, checkemail, 0, 0);
   2187         if (print)
   2188             BIO_printf(bio, "Email %s does%s match certificate\n",
   2189                 checkemail, valid_mail ? "" : " NOT");
   2190         ret = ret && valid_mail > 0;
   2191     }
   2192 
   2193     if (checkip != NULL) {
   2194         valid_ip = X509_check_ip_asc(x, checkip, 0);
   2195         if (print)
   2196             BIO_printf(bio, "IP %s does%s match certificate\n",
   2197                 checkip, valid_ip ? "" : " NOT");
   2198         ret = ret && valid_ip > 0;
   2199     }
   2200 
   2201     return ret;
   2202 }
   2203 
   2204 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
   2205 {
   2206     int i;
   2207 
   2208     if (opts == NULL)
   2209         return 1;
   2210 
   2211     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
   2212         char *opt = sk_OPENSSL_STRING_value(opts, i);
   2213 
   2214         if (pkey_ctrl_string(pkctx, opt) <= 0) {
   2215             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
   2216             ERR_print_errors(bio_err);
   2217             return 0;
   2218         }
   2219     }
   2220 
   2221     return 1;
   2222 }
   2223 
   2224 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
   2225 {
   2226     int i;
   2227 
   2228     if (opts == NULL)
   2229         return 1;
   2230 
   2231     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
   2232         char *opt = sk_OPENSSL_STRING_value(opts, i);
   2233 
   2234         if (x509_ctrl_string(x, opt) <= 0) {
   2235             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
   2236             ERR_print_errors(bio_err);
   2237             return 0;
   2238         }
   2239     }
   2240 
   2241     return 1;
   2242 }
   2243 
   2244 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
   2245 {
   2246     int i;
   2247 
   2248     if (opts == NULL)
   2249         return 1;
   2250 
   2251     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
   2252         char *opt = sk_OPENSSL_STRING_value(opts, i);
   2253 
   2254         if (x509_req_ctrl_string(x, opt) <= 0) {
   2255             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
   2256             ERR_print_errors(bio_err);
   2257             return 0;
   2258         }
   2259     }
   2260 
   2261     return 1;
   2262 }
   2263 
   2264 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
   2265     const char *md, STACK_OF(OPENSSL_STRING) *sigopts)
   2266 {
   2267     EVP_PKEY_CTX *pkctx = NULL;
   2268     char def_md[80];
   2269 
   2270     if (ctx == NULL)
   2271         return 0;
   2272     /*
   2273      * EVP_PKEY_get_default_digest_name() returns 2 if the digest is mandatory
   2274      * for this algorithm.
   2275      */
   2276     if (EVP_PKEY_get_default_digest_name(pkey, def_md, sizeof(def_md)) == 2
   2277         && strcmp(def_md, "UNDEF") == 0) {
   2278         /* The signing algorithm requires there to be no digest */
   2279         md = NULL;
   2280     }
   2281 
   2282     return EVP_DigestSignInit_ex(ctx, &pkctx, md, app_get0_libctx(),
   2283                app_get0_propq(), pkey, NULL)
   2284         && do_pkey_ctx_init(pkctx, sigopts);
   2285 }
   2286 
   2287 static int adapt_keyid_ext(X509 *cert, X509V3_CTX *ext_ctx,
   2288     const char *name, const char *value, int add_default)
   2289 {
   2290     const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
   2291     X509_EXTENSION *new_ext = X509V3_EXT_nconf(NULL, ext_ctx, name, value);
   2292     int idx, rv = 0;
   2293 
   2294     if (new_ext == NULL)
   2295         return rv;
   2296 
   2297     idx = X509v3_get_ext_by_OBJ(exts, X509_EXTENSION_get_object(new_ext), -1);
   2298     if (idx >= 0) {
   2299         X509_EXTENSION *found_ext = X509v3_get_ext(exts, idx);
   2300         ASN1_OCTET_STRING *encoded = X509_EXTENSION_get_data(found_ext);
   2301         int disabled = ASN1_STRING_length(encoded) <= 2; /* indicating "none" */
   2302 
   2303         if (disabled) {
   2304             X509_delete_ext(cert, idx);
   2305             X509_EXTENSION_free(found_ext);
   2306         } /* else keep existing key identifier, which might be outdated */
   2307         rv = 1;
   2308     } else {
   2309         rv = !add_default || X509_add_ext(cert, new_ext, -1);
   2310     }
   2311     X509_EXTENSION_free(new_ext);
   2312     return rv;
   2313 }
   2314 
   2315 int cert_matches_key(const X509 *cert, const EVP_PKEY *pkey)
   2316 {
   2317     int match;
   2318 
   2319     ERR_set_mark();
   2320     match = X509_check_private_key(cert, pkey);
   2321     ERR_pop_to_mark();
   2322     return match;
   2323 }
   2324 
   2325 /* Ensure RFC 5280 compliance, adapt keyIDs as needed, and sign the cert info */
   2326 int do_X509_sign(X509 *cert, int force_v1, EVP_PKEY *pkey, const char *md,
   2327     STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx)
   2328 {
   2329     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
   2330     int self_sign;
   2331     int rv = 0;
   2332 
   2333     if (!force_v1) {
   2334         if (!X509_set_version(cert, X509_VERSION_3))
   2335             goto end;
   2336 
   2337         /*
   2338          * Add default SKID before AKID such that AKID can make use of it
   2339          * in case the certificate is self-signed
   2340          */
   2341         /* Prevent X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER */
   2342         if (!adapt_keyid_ext(cert, ext_ctx, "subjectKeyIdentifier", "hash", 1))
   2343             goto end;
   2344         /* Prevent X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER */
   2345         self_sign = cert_matches_key(cert, pkey);
   2346         if (!adapt_keyid_ext(cert, ext_ctx, "authorityKeyIdentifier",
   2347                 "keyid, issuer", !self_sign))
   2348             goto end;
   2349     }
   2350     /* May add further measures for ensuring RFC 5280 compliance, see #19805 */
   2351 
   2352     if (mctx != NULL && do_sign_init(mctx, pkey, md, sigopts) > 0)
   2353         rv = (X509_sign_ctx(cert, mctx) > 0);
   2354 end:
   2355     EVP_MD_CTX_free(mctx);
   2356     return rv;
   2357 }
   2358 
   2359 /* Sign the certificate request info */
   2360 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md,
   2361     STACK_OF(OPENSSL_STRING) *sigopts)
   2362 {
   2363     int rv = 0;
   2364     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
   2365 
   2366     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
   2367         rv = (X509_REQ_sign_ctx(x, mctx) > 0);
   2368     EVP_MD_CTX_free(mctx);
   2369     return rv;
   2370 }
   2371 
   2372 /* Sign the CRL info */
   2373 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md,
   2374     STACK_OF(OPENSSL_STRING) *sigopts)
   2375 {
   2376     int rv = 0;
   2377     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
   2378 
   2379     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
   2380         rv = (X509_CRL_sign_ctx(x, mctx) > 0);
   2381     EVP_MD_CTX_free(mctx);
   2382     return rv;
   2383 }
   2384 
   2385 /*
   2386  * do_X509_verify returns 1 if the signature is valid,
   2387  * 0 if the signature check fails, or -1 if error occurs.
   2388  */
   2389 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
   2390 {
   2391     int rv = 0;
   2392 
   2393     if (do_x509_init(x, vfyopts) > 0)
   2394         rv = X509_verify(x, pkey);
   2395     else
   2396         rv = -1;
   2397     return rv;
   2398 }
   2399 
   2400 /*
   2401  * do_X509_REQ_verify returns 1 if the signature is valid,
   2402  * 0 if the signature check fails, or -1 if error occurs.
   2403  */
   2404 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
   2405     STACK_OF(OPENSSL_STRING) *vfyopts)
   2406 {
   2407     int rv = 0;
   2408 
   2409     if (do_x509_req_init(x, vfyopts) > 0)
   2410         rv = X509_REQ_verify_ex(x, pkey, app_get0_libctx(), app_get0_propq());
   2411     else
   2412         rv = -1;
   2413     return rv;
   2414 }
   2415 
   2416 /* Get first http URL from a DIST_POINT structure */
   2417 
   2418 static const char *get_dp_url(DIST_POINT *dp)
   2419 {
   2420     GENERAL_NAMES *gens;
   2421     GENERAL_NAME *gen;
   2422     int i, gtype;
   2423     ASN1_STRING *uri;
   2424 
   2425     if (!dp->distpoint || dp->distpoint->type != 0)
   2426         return NULL;
   2427     gens = dp->distpoint->name.fullname;
   2428     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
   2429         gen = sk_GENERAL_NAME_value(gens, i);
   2430         uri = GENERAL_NAME_get0_value(gen, &gtype);
   2431         if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
   2432             const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
   2433 
   2434             if (IS_HTTP(uptr)) /* can/should not use HTTPS here */
   2435                 return uptr;
   2436         }
   2437     }
   2438     return NULL;
   2439 }
   2440 
   2441 /*
   2442  * Look through a CRLDP structure and attempt to find an http URL to
   2443  * downloads a CRL from.
   2444  */
   2445 
   2446 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
   2447 {
   2448     int i;
   2449     const char *urlptr = NULL;
   2450 
   2451     for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
   2452         DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
   2453 
   2454         urlptr = get_dp_url(dp);
   2455         if (urlptr != NULL)
   2456             return load_crl(urlptr, FORMAT_UNDEF, 0, "CRL via CDP");
   2457     }
   2458     return NULL;
   2459 }
   2460 
   2461 /*
   2462  * Example of downloading CRLs from CRLDP:
   2463  * not usable for real world as it always downloads and doesn't cache anything.
   2464  */
   2465 
   2466 static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
   2467     const X509_NAME *nm)
   2468 {
   2469     X509 *x;
   2470     STACK_OF(X509_CRL) *crls = NULL;
   2471     X509_CRL *crl;
   2472     STACK_OF(DIST_POINT) *crldp;
   2473 
   2474     crls = sk_X509_CRL_new_null();
   2475     if (!crls)
   2476         return NULL;
   2477     x = X509_STORE_CTX_get_current_cert(ctx);
   2478     crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
   2479     crl = load_crl_crldp(crldp);
   2480     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
   2481 
   2482     if (crl == NULL || !sk_X509_CRL_push(crls, crl))
   2483         goto error;
   2484 
   2485     /* Try to download delta CRL */
   2486     crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
   2487     crl = load_crl_crldp(crldp);
   2488     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
   2489 
   2490     if (crl != NULL && !sk_X509_CRL_push(crls, crl))
   2491         goto error;
   2492 
   2493     return crls;
   2494 
   2495 error:
   2496     X509_CRL_free(crl);
   2497     sk_X509_CRL_free(crls);
   2498     return NULL;
   2499 }
   2500 
   2501 void store_setup_crl_download(X509_STORE *st)
   2502 {
   2503     X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
   2504 }
   2505 
   2506 #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP)
   2507 static const char *tls_error_hint(void)
   2508 {
   2509     unsigned long err = ERR_peek_error();
   2510 
   2511     if (ERR_GET_LIB(err) != ERR_LIB_SSL)
   2512         err = ERR_peek_last_error();
   2513     if (ERR_GET_LIB(err) != ERR_LIB_SSL)
   2514         return NULL; /* likely no TLS error */
   2515 
   2516     switch (ERR_GET_REASON(err)) {
   2517     case SSL_R_WRONG_VERSION_NUMBER:
   2518         return "The server does not support (a suitable version of) TLS";
   2519     case SSL_R_UNKNOWN_PROTOCOL:
   2520         return "The server does not support HTTPS";
   2521     case SSL_R_CERTIFICATE_VERIFY_FAILED:
   2522         return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
   2523     case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
   2524         return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
   2525     case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
   2526         return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
   2527     default:
   2528         return NULL; /* no hint available for TLS error */
   2529     }
   2530 }
   2531 
   2532 static BIO *http_tls_shutdown(BIO *bio)
   2533 {
   2534     if (bio != NULL) {
   2535         BIO *cbio;
   2536         const char *hint = tls_error_hint();
   2537 
   2538         if (hint != NULL)
   2539             BIO_printf(bio_err, "%s\n", hint);
   2540         (void)ERR_set_mark();
   2541         BIO_ssl_shutdown(bio);
   2542         cbio = BIO_pop(bio); /* connect+HTTP BIO */
   2543         BIO_free(bio); /* SSL BIO */
   2544         (void)ERR_pop_to_mark(); /* hide SSL_R_READ_BIO_NOT_SET etc. */
   2545         bio = cbio;
   2546     }
   2547     return bio;
   2548 }
   2549 
   2550 /* HTTP callback function that supports TLS connection also via HTTPS proxy */
   2551 BIO *app_http_tls_cb(BIO *bio, void *arg, int connect, int detail)
   2552 {
   2553     APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
   2554     SSL_CTX *ssl_ctx = info->ssl_ctx;
   2555 
   2556     if (ssl_ctx == NULL) /* not using TLS */
   2557         return bio;
   2558     if (connect) {
   2559         SSL *ssl;
   2560         BIO *sbio = NULL;
   2561         X509_STORE *ts = SSL_CTX_get_cert_store(ssl_ctx);
   2562         X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts);
   2563         const char *host = vpm == NULL ? NULL : X509_VERIFY_PARAM_get0_host(vpm, 0 /* first hostname */);
   2564 
   2565         /* adapt after fixing callback design flaw, see #17088 */
   2566         if ((info->use_proxy
   2567                 && !OSSL_HTTP_proxy_connect(bio, info->server, info->port,
   2568                     NULL, NULL, /* no proxy credentials */
   2569                     info->timeout, bio_err, opt_getprog()))
   2570             || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
   2571             return NULL;
   2572         }
   2573         if ((ssl = SSL_new(ssl_ctx)) == NULL) {
   2574             BIO_free(sbio);
   2575             return NULL;
   2576         }
   2577 
   2578         if (vpm != NULL)
   2579             SSL_set_tlsext_host_name(ssl, host /* may be NULL */);
   2580 
   2581         SSL_set_connect_state(ssl);
   2582         BIO_set_ssl(sbio, ssl, BIO_CLOSE);
   2583 
   2584         bio = BIO_push(sbio, bio);
   2585     } else { /* disconnect from TLS */
   2586         bio = http_tls_shutdown(bio);
   2587     }
   2588     return bio;
   2589 }
   2590 
   2591 void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info)
   2592 {
   2593     if (info != NULL) {
   2594         SSL_CTX_free(info->ssl_ctx);
   2595         OPENSSL_free(info);
   2596     }
   2597 }
   2598 
   2599 ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
   2600     const char *no_proxy, SSL_CTX *ssl_ctx,
   2601     const STACK_OF(CONF_VALUE) *headers,
   2602     long timeout, const char *expected_content_type,
   2603     const ASN1_ITEM *it)
   2604 {
   2605     APP_HTTP_TLS_INFO info;
   2606     char *server;
   2607     char *port;
   2608     int use_ssl;
   2609     BIO *mem;
   2610     ASN1_VALUE *resp = NULL;
   2611 
   2612     if (url == NULL || it == NULL) {
   2613         ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
   2614         return NULL;
   2615     }
   2616 
   2617     if (!OSSL_HTTP_parse_url(url, &use_ssl, NULL /* userinfo */, &server, &port,
   2618             NULL /* port_num, */, NULL, NULL, NULL))
   2619         return NULL;
   2620     if (use_ssl && ssl_ctx == NULL) {
   2621         ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER,
   2622             "missing SSL_CTX");
   2623         goto end;
   2624     }
   2625     if (!use_ssl && ssl_ctx != NULL) {
   2626         ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT,
   2627             "SSL_CTX given but use_ssl == 0");
   2628         goto end;
   2629     }
   2630 
   2631     info.server = server;
   2632     info.port = port;
   2633     info.use_proxy = /* workaround for callback design flaw, see #17088 */
   2634         OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl) != NULL;
   2635     info.timeout = timeout;
   2636     info.ssl_ctx = ssl_ctx;
   2637     mem = OSSL_HTTP_get(url, proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
   2638         app_http_tls_cb, &info, 0 /* buf_size */, headers,
   2639         expected_content_type, 1 /* expect_asn1 */,
   2640         OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout);
   2641     resp = ASN1_item_d2i_bio(it, mem, NULL);
   2642     BIO_free(mem);
   2643 
   2644 end:
   2645     OPENSSL_free(server);
   2646     OPENSSL_free(port);
   2647     return resp;
   2648 }
   2649 
   2650 ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
   2651     const char *path, const char *proxy,
   2652     const char *no_proxy, SSL_CTX *ssl_ctx,
   2653     const STACK_OF(CONF_VALUE) *headers,
   2654     const char *content_type,
   2655     ASN1_VALUE *req, const ASN1_ITEM *req_it,
   2656     const char *expected_content_type,
   2657     long timeout, const ASN1_ITEM *rsp_it)
   2658 {
   2659     int use_ssl = ssl_ctx != NULL;
   2660     APP_HTTP_TLS_INFO info;
   2661     BIO *rsp, *req_mem = ASN1_item_i2d_mem_bio(req_it, req);
   2662     ASN1_VALUE *res;
   2663 
   2664     if (req_mem == NULL)
   2665         return NULL;
   2666 
   2667     info.server = host;
   2668     info.port = port;
   2669     info.use_proxy = /* workaround for callback design flaw, see #17088 */
   2670         OSSL_HTTP_adapt_proxy(proxy, no_proxy, host, use_ssl) != NULL;
   2671     info.timeout = timeout;
   2672     info.ssl_ctx = ssl_ctx;
   2673     rsp = OSSL_HTTP_transfer(NULL, host, port, path, use_ssl,
   2674         proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
   2675         app_http_tls_cb, &info,
   2676         0 /* buf_size */, headers, content_type, req_mem,
   2677         expected_content_type, 1 /* expect_asn1 */,
   2678         OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout,
   2679         0 /* keep_alive */);
   2680     BIO_free(req_mem);
   2681     res = ASN1_item_d2i_bio(rsp_it, rsp, NULL);
   2682     BIO_free(rsp);
   2683     return res;
   2684 }
   2685 
   2686 #endif
   2687 
   2688 /*
   2689  * Platform-specific sections
   2690  */
   2691 #if defined(_WIN32)
   2692 #ifdef fileno
   2693 #undef fileno
   2694 #define fileno(a) (int)_fileno(a)
   2695 #endif
   2696 
   2697 #include <windows.h>
   2698 #include <tchar.h>
   2699 
   2700 static int WIN32_rename(const char *from, const char *to)
   2701 {
   2702     TCHAR *tfrom = NULL, *tto;
   2703     DWORD err;
   2704     int ret = 0;
   2705 
   2706     if (sizeof(TCHAR) == 1) {
   2707         tfrom = (TCHAR *)from;
   2708         tto = (TCHAR *)to;
   2709     } else { /* UNICODE path */
   2710         size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
   2711 
   2712         tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
   2713         if (tfrom == NULL)
   2714             goto err;
   2715         tto = tfrom + flen;
   2716 #if !defined(_WIN32_WCE) || _WIN32_WCE >= 101
   2717         if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
   2718 #endif
   2719             for (i = 0; i < flen; i++)
   2720                 tfrom[i] = (TCHAR)from[i];
   2721 #if !defined(_WIN32_WCE) || _WIN32_WCE >= 101
   2722         if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
   2723 #endif
   2724             for (i = 0; i < tlen; i++)
   2725                 tto[i] = (TCHAR)to[i];
   2726     }
   2727 
   2728     if (MoveFile(tfrom, tto))
   2729         goto ok;
   2730     err = GetLastError();
   2731     if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
   2732         if (DeleteFile(tto) && MoveFile(tfrom, tto))
   2733             goto ok;
   2734         err = GetLastError();
   2735     }
   2736     if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
   2737         errno = ENOENT;
   2738     else if (err == ERROR_ACCESS_DENIED)
   2739         errno = EACCES;
   2740     else
   2741         errno = EINVAL; /* we could map more codes... */
   2742 err:
   2743     ret = -1;
   2744 ok:
   2745     if (tfrom != NULL && tfrom != (TCHAR *)from)
   2746         free(tfrom);
   2747     return ret;
   2748 }
   2749 #endif
   2750 
   2751 /* app_tminterval section */
   2752 #if defined(_WIN32)
   2753 double app_tminterval(int stop, int usertime)
   2754 {
   2755     FILETIME now;
   2756     double ret = 0;
   2757     static ULARGE_INTEGER tmstart;
   2758     static int warning = 1;
   2759     int use_GetSystemTime = 1;
   2760 #ifdef _WIN32_WINNT
   2761     static HANDLE proc = NULL;
   2762 
   2763     if (proc == NULL) {
   2764         if (check_winnt())
   2765             proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
   2766                 GetCurrentProcessId());
   2767         if (proc == NULL)
   2768             proc = (HANDLE)-1;
   2769     }
   2770 
   2771     if (usertime && proc != (HANDLE)-1) {
   2772         FILETIME junk;
   2773 
   2774         GetProcessTimes(proc, &junk, &junk, &junk, &now);
   2775         use_GetSystemTime = 0;
   2776     }
   2777 #endif
   2778     if (use_GetSystemTime) {
   2779         SYSTEMTIME systime;
   2780 
   2781         if (usertime && warning) {
   2782             BIO_printf(bio_err, "To get meaningful results, run "
   2783                                 "this program on idle system.\n");
   2784             warning = 0;
   2785         }
   2786         GetSystemTime(&systime);
   2787         SystemTimeToFileTime(&systime, &now);
   2788     }
   2789 
   2790     if (stop == TM_START) {
   2791         tmstart.u.LowPart = now.dwLowDateTime;
   2792         tmstart.u.HighPart = now.dwHighDateTime;
   2793     } else {
   2794         ULARGE_INTEGER tmstop;
   2795 
   2796         tmstop.u.LowPart = now.dwLowDateTime;
   2797         tmstop.u.HighPart = now.dwHighDateTime;
   2798 
   2799         ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
   2800     }
   2801 
   2802     return ret;
   2803 }
   2804 #elif defined(OPENSSL_SYS_VXWORKS)
   2805 #include <time.h>
   2806 
   2807 double app_tminterval(int stop, int usertime)
   2808 {
   2809     double ret = 0;
   2810 #ifdef CLOCK_REALTIME
   2811     static struct timespec tmstart;
   2812     struct timespec now;
   2813 #else
   2814     static unsigned long tmstart;
   2815     unsigned long now;
   2816 #endif
   2817     static int warning = 1;
   2818 
   2819     if (usertime && warning) {
   2820         BIO_printf(bio_err, "To get meaningful results, run "
   2821                             "this program on idle system.\n");
   2822         warning = 0;
   2823     }
   2824 #ifdef CLOCK_REALTIME
   2825     clock_gettime(CLOCK_REALTIME, &now);
   2826     if (stop == TM_START)
   2827         tmstart = now;
   2828     else
   2829         ret = ((now.tv_sec + now.tv_nsec * 1e-9)
   2830             - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
   2831 #else
   2832     now = tickGet();
   2833     if (stop == TM_START)
   2834         tmstart = now;
   2835     else
   2836         ret = (now - tmstart) / (double)sysClkRateGet();
   2837 #endif
   2838     return ret;
   2839 }
   2840 
   2841 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
   2842 #include <sys/times.h>
   2843 
   2844 double app_tminterval(int stop, int usertime)
   2845 {
   2846     double ret = 0;
   2847     struct tms rus;
   2848     clock_t now = times(&rus);
   2849     static clock_t tmstart;
   2850 
   2851     if (usertime)
   2852         now = rus.tms_utime;
   2853 
   2854     if (stop == TM_START) {
   2855         tmstart = now;
   2856     } else {
   2857         long int tck = sysconf(_SC_CLK_TCK);
   2858 
   2859         ret = (now - tmstart) / (double)tck;
   2860     }
   2861 
   2862     return ret;
   2863 }
   2864 
   2865 #else
   2866 #include <sys/time.h>
   2867 #include <sys/resource.h>
   2868 
   2869 double app_tminterval(int stop, int usertime)
   2870 {
   2871     double ret = 0;
   2872     struct rusage rus;
   2873     struct timeval now;
   2874     static struct timeval tmstart;
   2875 
   2876     if (usertime)
   2877         getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
   2878     else
   2879         gettimeofday(&now, NULL);
   2880 
   2881     if (stop == TM_START)
   2882         tmstart = now;
   2883     else
   2884         ret = ((now.tv_sec + now.tv_usec * 1e-6)
   2885             - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
   2886 
   2887     return ret;
   2888 }
   2889 #endif
   2890 
   2891 int app_access(const char *name, int flag)
   2892 {
   2893 #ifdef _WIN32
   2894     return _access(name, flag);
   2895 #else
   2896     return access(name, flag);
   2897 #endif
   2898 }
   2899 
   2900 int app_isdir(const char *name)
   2901 {
   2902     return opt_isdir(name);
   2903 }
   2904 
   2905 /* raw_read|write section */
   2906 #if defined(__VMS)
   2907 #include "vms_term_sock.h"
   2908 static int stdin_sock = -1;
   2909 
   2910 static void close_stdin_sock(void)
   2911 {
   2912     TerminalSocket(TERM_SOCK_DELETE, &stdin_sock);
   2913 }
   2914 
   2915 int fileno_stdin(void)
   2916 {
   2917     if (stdin_sock == -1) {
   2918         TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
   2919         atexit(close_stdin_sock);
   2920     }
   2921 
   2922     return stdin_sock;
   2923 }
   2924 #else
   2925 int fileno_stdin(void)
   2926 {
   2927     return fileno(stdin);
   2928 }
   2929 #endif
   2930 
   2931 int fileno_stdout(void)
   2932 {
   2933     return fileno(stdout);
   2934 }
   2935 
   2936 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
   2937 int raw_read_stdin(void *buf, int siz)
   2938 {
   2939     DWORD n;
   2940 
   2941     if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
   2942         return n;
   2943     else
   2944         return -1;
   2945 }
   2946 #elif defined(__VMS)
   2947 #include <sys/socket.h>
   2948 
   2949 int raw_read_stdin(void *buf, int siz)
   2950 {
   2951     return recv(fileno_stdin(), buf, siz, 0);
   2952 }
   2953 #else
   2954 int raw_read_stdin(void *buf, int siz)
   2955 {
   2956     return read(fileno_stdin(), buf, siz);
   2957 }
   2958 #endif
   2959 
   2960 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
   2961 int raw_write_stdout(const void *buf, int siz)
   2962 {
   2963     DWORD n;
   2964 
   2965     if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
   2966         return n;
   2967     else
   2968         return -1;
   2969 }
   2970 #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) \
   2971     && defined(_SPT_MODEL_)
   2972 int raw_write_stdout(const void *buf, int siz)
   2973 {
   2974     return write(fileno(stdout), (void *)buf, siz);
   2975 }
   2976 #else
   2977 int raw_write_stdout(const void *buf, int siz)
   2978 {
   2979     return write(fileno_stdout(), buf, siz);
   2980 }
   2981 #endif
   2982 
   2983 /*
   2984  * Centralized handling of input and output files with format specification
   2985  * The format is meant to show what the input and output is supposed to be,
   2986  * and is therefore a show of intent more than anything else.  However, it
   2987  * does impact behavior on some platforms, such as differentiating between
   2988  * text and binary input/output on non-Unix platforms
   2989  */
   2990 BIO *dup_bio_in(int format)
   2991 {
   2992     return BIO_new_fp(stdin,
   2993         BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
   2994 }
   2995 
   2996 BIO *dup_bio_out(int format)
   2997 {
   2998     BIO *b = BIO_new_fp(stdout,
   2999         BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
   3000     void *prefix = NULL;
   3001 
   3002     if (b == NULL)
   3003         return NULL;
   3004 
   3005 #ifdef OPENSSL_SYS_VMS
   3006     if (FMT_istext(format))
   3007         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
   3008 #endif
   3009 
   3010     if (FMT_istext(format)
   3011         && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
   3012         b = BIO_push(BIO_new(BIO_f_prefix()), b);
   3013         BIO_set_prefix(b, prefix);
   3014     }
   3015 
   3016     return b;
   3017 }
   3018 
   3019 BIO *dup_bio_err(int format)
   3020 {
   3021     BIO *b = BIO_new_fp(stderr,
   3022         BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
   3023 
   3024 #ifdef OPENSSL_SYS_VMS
   3025     if (b != NULL && FMT_istext(format))
   3026         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
   3027 #endif
   3028     return b;
   3029 }
   3030 
   3031 void unbuffer(FILE *fp)
   3032 {
   3033 /*
   3034  * On VMS, setbuf() will only take 32-bit pointers, and a compilation
   3035  * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
   3036  * However, we trust that the C RTL will never give us a FILE pointer
   3037  * above the first 4 GB of memory, so we simply turn off the warning
   3038  * temporarily.
   3039  */
   3040 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
   3041 #pragma environment save
   3042 #pragma message disable maylosedata2
   3043 #endif
   3044     setbuf(fp, NULL);
   3045 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
   3046 #pragma environment restore
   3047 #endif
   3048 }
   3049 
   3050 static const char *modestr(char mode, int format)
   3051 {
   3052     OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
   3053 
   3054     switch (mode) {
   3055     case 'a':
   3056         return FMT_istext(format) ? "a" : "ab";
   3057     case 'r':
   3058         return FMT_istext(format) ? "r" : "rb";
   3059     case 'w':
   3060         return FMT_istext(format) ? "w" : "wb";
   3061     }
   3062     /* The assert above should make sure we never reach this point */
   3063     return NULL;
   3064 }
   3065 
   3066 static const char *modeverb(char mode)
   3067 {
   3068     switch (mode) {
   3069     case 'a':
   3070         return "appending";
   3071     case 'r':
   3072         return "reading";
   3073     case 'w':
   3074         return "writing";
   3075     }
   3076     return "(doing something)";
   3077 }
   3078 
   3079 /*
   3080  * Open a file for writing, owner-read-only.
   3081  */
   3082 BIO *bio_open_owner(const char *filename, int format, int private)
   3083 {
   3084     FILE *fp = NULL;
   3085     BIO *b = NULL;
   3086     int textmode, bflags;
   3087 #ifndef OPENSSL_NO_POSIX_IO
   3088     int fd = -1, mode;
   3089 #endif
   3090 
   3091     if (!private || filename == NULL || strcmp(filename, "-") == 0)
   3092         return bio_open_default(filename, 'w', format);
   3093 
   3094     textmode = FMT_istext(format);
   3095 #ifndef OPENSSL_NO_POSIX_IO
   3096     mode = O_WRONLY;
   3097 #ifdef O_CREAT
   3098     mode |= O_CREAT;
   3099 #endif
   3100 #ifdef O_TRUNC
   3101     mode |= O_TRUNC;
   3102 #endif
   3103     if (!textmode) {
   3104 #ifdef O_BINARY
   3105         mode |= O_BINARY;
   3106 #elif defined(_O_BINARY)
   3107         mode |= _O_BINARY;
   3108 #endif
   3109     }
   3110 
   3111 #ifdef OPENSSL_SYS_VMS
   3112     /*
   3113      * VMS doesn't have O_BINARY, it just doesn't make sense.  But,
   3114      * it still needs to know that we're going binary, or fdopen()
   3115      * will fail with "invalid argument"...  so we tell VMS what the
   3116      * context is.
   3117      */
   3118     if (!textmode)
   3119         fd = open(filename, mode, 0600, "ctx=bin");
   3120     else
   3121 #endif
   3122         fd = open(filename, mode, 0600);
   3123     if (fd < 0)
   3124         goto err;
   3125     fp = fdopen(fd, modestr('w', format));
   3126 #else /* OPENSSL_NO_POSIX_IO */
   3127     /* Have stdio but not Posix IO, do the best we can */
   3128     fp = fopen(filename, modestr('w', format));
   3129 #endif /* OPENSSL_NO_POSIX_IO */
   3130     if (fp == NULL)
   3131         goto err;
   3132     bflags = BIO_CLOSE;
   3133     if (textmode)
   3134         bflags |= BIO_FP_TEXT;
   3135     b = BIO_new_fp(fp, bflags);
   3136     if (b != NULL)
   3137         return b;
   3138 
   3139 err:
   3140     BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
   3141         opt_getprog(), filename, strerror(errno));
   3142     ERR_print_errors(bio_err);
   3143     /* If we have fp, then fdopen took over fd, so don't close both. */
   3144     if (fp != NULL)
   3145         fclose(fp);
   3146 #ifndef OPENSSL_NO_POSIX_IO
   3147     else if (fd >= 0)
   3148         close(fd);
   3149 #endif
   3150     return NULL;
   3151 }
   3152 
   3153 static BIO *bio_open_default_(const char *filename, char mode, int format,
   3154     int quiet)
   3155 {
   3156     BIO *ret;
   3157 
   3158     if (filename == NULL || strcmp(filename, "-") == 0) {
   3159         ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
   3160         if (quiet) {
   3161             ERR_clear_error();
   3162             return ret;
   3163         }
   3164         if (ret != NULL)
   3165             return ret;
   3166         BIO_printf(bio_err,
   3167             "Can't open %s, %s\n",
   3168             mode == 'r' ? "stdin" : "stdout", strerror(errno));
   3169     } else {
   3170         ret = BIO_new_file(filename, modestr(mode, format));
   3171         if (quiet) {
   3172             ERR_clear_error();
   3173             return ret;
   3174         }
   3175         if (ret != NULL)
   3176             return ret;
   3177         BIO_printf(bio_err,
   3178             "Can't open \"%s\" for %s, %s\n",
   3179             filename, modeverb(mode), strerror(errno));
   3180     }
   3181     ERR_print_errors(bio_err);
   3182     return NULL;
   3183 }
   3184 
   3185 BIO *bio_open_default(const char *filename, char mode, int format)
   3186 {
   3187     return bio_open_default_(filename, mode, format, 0);
   3188 }
   3189 
   3190 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
   3191 {
   3192     return bio_open_default_(filename, mode, format, 1);
   3193 }
   3194 
   3195 int mem_bio_to_file(BIO *in, const char *filename, int format, int private)
   3196 {
   3197     int rv = 0, ret = 0;
   3198     BIO *out = NULL;
   3199     BUF_MEM *mem_buffer = NULL;
   3200 
   3201     rv = BIO_get_mem_ptr(in, &mem_buffer);
   3202     if (rv <= 0) {
   3203         BIO_puts(bio_err, "Error reading mem buffer\n");
   3204         goto end;
   3205     }
   3206     out = bio_open_owner(filename, format, private);
   3207     if (out == NULL)
   3208         goto end;
   3209     rv = BIO_write(out, mem_buffer->data, mem_buffer->length);
   3210     if (rv < 0 || (size_t)rv != mem_buffer->length)
   3211         BIO_printf(bio_err, "Error writing to output file: '%s'\n", filename);
   3212     else
   3213         ret = 1;
   3214 end:
   3215     if (!ret)
   3216         ERR_print_errors(bio_err);
   3217     BIO_free_all(out);
   3218     return ret;
   3219 }
   3220 
   3221 void wait_for_async(SSL *s)
   3222 {
   3223     /* On Windows select only works for sockets, so we simply don't wait  */
   3224 #ifndef OPENSSL_SYS_WINDOWS
   3225     int width = 0;
   3226     fd_set asyncfds;
   3227     OSSL_ASYNC_FD *fds;
   3228     size_t numfds;
   3229     size_t i;
   3230 
   3231     if (!SSL_get_all_async_fds(s, NULL, &numfds))
   3232         return;
   3233     if (numfds == 0)
   3234         return;
   3235     fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
   3236     if (!SSL_get_all_async_fds(s, fds, &numfds)) {
   3237         OPENSSL_free(fds);
   3238         return;
   3239     }
   3240 
   3241     FD_ZERO(&asyncfds);
   3242     for (i = 0; i < numfds; i++) {
   3243         if (width <= (int)fds[i])
   3244             width = (int)fds[i] + 1;
   3245         openssl_fdset((int)fds[i], &asyncfds);
   3246     }
   3247     select(width, (void *)&asyncfds, NULL, NULL, NULL);
   3248     OPENSSL_free(fds);
   3249 #endif
   3250 }
   3251 
   3252 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
   3253 #if defined(OPENSSL_SYS_MSDOS)
   3254 int has_stdin_waiting(void)
   3255 {
   3256 #if defined(OPENSSL_SYS_WINDOWS)
   3257     HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
   3258     DWORD events = 0;
   3259     INPUT_RECORD inputrec;
   3260     DWORD insize = 1;
   3261     BOOL peeked;
   3262 
   3263     if (inhand == INVALID_HANDLE_VALUE) {
   3264         return 0;
   3265     }
   3266 
   3267     peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
   3268     if (!peeked) {
   3269         /* Probably redirected input? _kbhit() does not work in this case */
   3270         if (!feof(stdin)) {
   3271             return 1;
   3272         }
   3273         return 0;
   3274     }
   3275 #endif
   3276     return _kbhit();
   3277 }
   3278 #endif
   3279 
   3280 /* Corrupt a signature by modifying final byte */
   3281 void corrupt_signature(const ASN1_STRING *signature)
   3282 {
   3283     unsigned char *s = signature->data;
   3284 
   3285     s[signature->length - 1] ^= 0x1;
   3286 }
   3287 
   3288 int check_cert_time_string(const char *time, const char *desc)
   3289 {
   3290     if (time == NULL || strcmp(time, "today") == 0
   3291         || ASN1_TIME_set_string_X509(NULL, time))
   3292         return 1;
   3293     BIO_printf(bio_err,
   3294         "%s is invalid, it should be \"today\" or have format [CC]YYMMDDHHMMSSZ\n",
   3295         desc);
   3296     return 0;
   3297 }
   3298 
   3299 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
   3300     int days, int strict_compare_times)
   3301 {
   3302     if (!check_cert_time_string(startdate, "start date"))
   3303         return 0;
   3304     if (!check_cert_time_string(enddate, "end date"))
   3305         return 0;
   3306     if (startdate == NULL || strcmp(startdate, "today") == 0) {
   3307         if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL) {
   3308             BIO_printf(bio_err, "Error setting notBefore certificate field\n");
   3309             return 0;
   3310         }
   3311     } else {
   3312         if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate)) {
   3313             BIO_printf(bio_err, "Error setting notBefore certificate field\n");
   3314             return 0;
   3315         }
   3316     }
   3317     if (enddate != NULL && strcmp(enddate, "today") == 0) {
   3318         enddate = NULL;
   3319         days = 0;
   3320     }
   3321     if (enddate == NULL) {
   3322         if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL) == NULL) {
   3323             BIO_printf(bio_err, "Error setting notAfter certificate field\n");
   3324             return 0;
   3325         }
   3326     } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
   3327         BIO_printf(bio_err, "Error setting notAfter certificate field\n");
   3328         return 0;
   3329     }
   3330     if (ASN1_TIME_compare(X509_get0_notAfter(x), X509_get0_notBefore(x)) < 0) {
   3331         BIO_printf(bio_err, "%s: end date before start date\n",
   3332             strict_compare_times ? "Error" : "Warning");
   3333         if (strict_compare_times)
   3334             return 0;
   3335     }
   3336     return 1;
   3337 }
   3338 
   3339 int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate)
   3340 {
   3341     int ret = 0;
   3342     ASN1_TIME *tm = ASN1_TIME_new();
   3343 
   3344     if (tm == NULL)
   3345         goto end;
   3346 
   3347     if (lastupdate == NULL) {
   3348         if (X509_gmtime_adj(tm, 0) == NULL)
   3349             goto end;
   3350     } else {
   3351         if (!ASN1_TIME_set_string_X509(tm, lastupdate))
   3352             goto end;
   3353     }
   3354 
   3355     if (!X509_CRL_set1_lastUpdate(crl, tm))
   3356         goto end;
   3357 
   3358     ret = 1;
   3359 end:
   3360     ASN1_TIME_free(tm);
   3361     return ret;
   3362 }
   3363 
   3364 int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
   3365     long days, long hours, long secs)
   3366 {
   3367     int ret = 0;
   3368     ASN1_TIME *tm = ASN1_TIME_new();
   3369 
   3370     if (tm == NULL)
   3371         goto end;
   3372 
   3373     if (nextupdate == NULL) {
   3374         if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL)
   3375             goto end;
   3376     } else {
   3377         if (!ASN1_TIME_set_string_X509(tm, nextupdate))
   3378             goto end;
   3379     }
   3380 
   3381     if (!X509_CRL_set1_nextUpdate(crl, tm))
   3382         goto end;
   3383 
   3384     ret = 1;
   3385 end:
   3386     ASN1_TIME_free(tm);
   3387     return ret;
   3388 }
   3389 
   3390 void make_uppercase(char *string)
   3391 {
   3392     int i;
   3393 
   3394     for (i = 0; string[i] != '\0'; i++)
   3395         string[i] = toupper((unsigned char)string[i]);
   3396 }
   3397 
   3398 OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
   3399     const OSSL_PARAM *paramdefs)
   3400 {
   3401     OSSL_PARAM *params = NULL;
   3402     size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
   3403     size_t params_n;
   3404     char *opt = "", *stmp, *vtmp = NULL;
   3405     int found = 1;
   3406 
   3407     if (opts == NULL)
   3408         return NULL;
   3409 
   3410     params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
   3411     if (params == NULL)
   3412         return NULL;
   3413 
   3414     for (params_n = 0; params_n < sz; params_n++) {
   3415         opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
   3416         if ((stmp = OPENSSL_strdup(opt)) == NULL
   3417             || (vtmp = strchr(stmp, ':')) == NULL)
   3418             goto err;
   3419         /* Replace ':' with 0 to terminate the string pointed to by stmp */
   3420         *vtmp = 0;
   3421         /* Skip over the separator so that vmtp points to the value */
   3422         vtmp++;
   3423         if (!OSSL_PARAM_allocate_from_text(&params[params_n], paramdefs,
   3424                 stmp, vtmp, strlen(vtmp), &found))
   3425             goto err;
   3426         OPENSSL_free(stmp);
   3427     }
   3428     params[params_n] = OSSL_PARAM_construct_end();
   3429     return params;
   3430 err:
   3431     OPENSSL_free(stmp);
   3432     BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
   3433         opt);
   3434     ERR_print_errors(bio_err);
   3435     app_params_free(params);
   3436     return NULL;
   3437 }
   3438 
   3439 void app_params_free(OSSL_PARAM *params)
   3440 {
   3441     int i;
   3442 
   3443     if (params != NULL) {
   3444         for (i = 0; params[i].key != NULL; ++i)
   3445             OPENSSL_free(params[i].data);
   3446         OPENSSL_free(params);
   3447     }
   3448 }
   3449 
   3450 EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose)
   3451 {
   3452     EVP_PKEY *res = NULL;
   3453 
   3454     if (verbose && alg != NULL) {
   3455         BIO_printf(bio_err, "Generating %s key", alg);
   3456         if (bits > 0)
   3457             BIO_printf(bio_err, " with %d bits\n", bits);
   3458         else
   3459             BIO_printf(bio_err, "\n");
   3460     }
   3461     if (!RAND_status())
   3462         BIO_printf(bio_err, "Warning: generating random key material may take a long time\n"
   3463                             "if the system has a poor entropy source\n");
   3464     if (EVP_PKEY_keygen(ctx, &res) <= 0)
   3465         BIO_printf(bio_err, "%s: Error generating %s key\n", opt_getprog(),
   3466             alg != NULL ? alg : "asymmetric");
   3467     return res;
   3468 }
   3469 
   3470 EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg)
   3471 {
   3472     EVP_PKEY *res = NULL;
   3473 
   3474     if (!RAND_status())
   3475         BIO_printf(bio_err, "Warning: generating random key parameters may take a long time\n"
   3476                             "if the system has a poor entropy source\n");
   3477     if (EVP_PKEY_paramgen(ctx, &res) <= 0)
   3478         BIO_printf(bio_err, "%s: Generating %s key parameters failed\n",
   3479             opt_getprog(), alg != NULL ? alg : "asymmetric");
   3480     return res;
   3481 }
   3482 
   3483 /*
   3484  * Return non-zero if the legacy path is still an option.
   3485  * This decision is based on the global command line operations and the
   3486  * behaviour thus far.
   3487  */
   3488 int opt_legacy_okay(void)
   3489 {
   3490     int provider_options = opt_provider_option_given();
   3491     int libctx = app_get0_libctx() != NULL || app_get0_propq() != NULL;
   3492 
   3493     /*
   3494      * Having a provider option specified or a custom library context or
   3495      * property query, is a sure sign we're not using legacy.
   3496      */
   3497     if (provider_options || libctx)
   3498         return 0;
   3499     return 1;
   3500 }
   3501