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