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