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