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