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