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