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