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