GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — node/src/node_crypto.cc at master · lufzle/node Expand file tree/ Copy pathnode_crypto.ccMore file actions 5727 lines (4623 loc) · 179 KB / Copy pathnode_crypto.ccFile metadata and controls5727 lines (4623 loc) · 179 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node.h" #include "node_buffer.h" #include "node_errors.h" #include "node_constants.h" #include "node_crypto.h" #include "node_crypto_bio.h" #include "node_crypto_groups.h" #include "node_crypto_clienthello-inl.h" #include "node_mutex.h" #include "node_internals.h" #include "tls_wrap.h" // TLSWrap #include "async_wrap-inl.h" #include "env-inl.h" #include "string_bytes.h" #include "util-inl.h" #include "v8.h" #include <errno.h> #include <limits.h> // INT_MAX #include <string.h> #include <algorithm> #include <memory> #include <utility> #include <vector> static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_UTF8_CONVERT | XN_FLAG_SEP_MULTILINE | XN_FLAG_FN_SN; namespace node { namespace crypto { using v8::Array; using v8::Boolean; using v8::ConstructorBehavior; using v8::Context; using v8::DontDelete; using v8::EscapableHandleScope; using v8::Exception; using v8::External; using v8::FunctionCallback; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; using v8::Int32; using v8::Integer; using v8::Isolate; using v8::Just; using v8::Local; using v8::Maybe; using v8::MaybeLocal; using v8::NewStringType; using v8::Nothing; using v8::Null; using v8::Object; using v8::PropertyAttribute; using v8::ReadOnly; using v8::SideEffectType; using v8::Signature; using v8::String; using v8::Uint32; using v8::Undefined; using v8::Value; #ifdef OPENSSL_NO_OCB # define IS_OCB_MODE(mode) false #else # define IS_OCB_MODE(mode) ((mode) == EVP_CIPH_OCB_MODE) #endif struct StackOfX509Deleter { void operator()(STACK_OF(X509)* p) const { sk_X509_pop_free(p, X509_free); } }; using StackOfX509 = std::unique_ptr<STACK_OF(X509), StackOfX509Deleter>; struct StackOfXASN1Deleter { void operator()(STACK_OF(ASN1_OBJECT)* p) const { sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free); } }; using StackOfASN1 = std::unique_ptr<STACK_OF(ASN1_OBJECT), StackOfXASN1Deleter>; // OPENSSL_free is a macro, so we need a wrapper function. struct OpenSSLBufferDeleter { void operator()(char* pointer) const { OPENSSL_free(pointer); } }; using OpenSSLBuffer = std::unique_ptr<char[], OpenSSLBufferDeleter>; static const char* const root_certs[] = { #include "node_root_certs.h" // NOLINT(build/include_order) }; static const char system_cert_path[] = NODE_OPENSSL_SYSTEM_CERT_PATH; static X509_STORE* root_cert_store; static bool extra_root_certs_loaded = false; // Just to generate static methods template void SSLWrap<TLSWrap>::AddMethods(Environment* env, Local<FunctionTemplate> t); template void SSLWrap<TLSWrap>::ConfigureSecureContext(SecureContext* sc); template void SSLWrap<TLSWrap>::SetSNIContext(SecureContext* sc); template int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc); template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback( SSL* s, const unsigned char* key, int len, int* copy); template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s, SSL_SESSION* sess); template void SSLWrap<TLSWrap>::OnClientHello( void* arg, const ClientHelloParser::ClientHello& hello); template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg); template void SSLWrap<TLSWrap>::DestroySSL(); template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg); template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg); template int SSLWrap<TLSWrap>::SelectALPNCallback( SSL* s, const unsigned char** out, unsigned char* outlen, const unsigned char* in, unsigned int inlen, void* arg); static int PasswordCallback(char* buf, int size, int rwflag, void* u) { if (u) { size_t buflen = static_cast<size_t>(size); size_t len = strlen(static_cast<const char*>(u)); len = len > buflen ? buflen : len; memcpy(buf, u, len); return len; } return 0; } // Loads OpenSSL engine by engine id and returns it. The loaded engine // gets a reference so remember the corresponding call to ENGINE_free. // In case of error the appropriate js exception is scheduled // and nullptr is returned. #ifndef OPENSSL_NO_ENGINE static ENGINE* LoadEngineById(const char* engine_id, char (*errmsg)[1024]) { MarkPopErrorOnReturn mark_pop_error_on_return; ENGINE* engine = ENGINE_by_id(engine_id); if (engine == nullptr) { // Engine not found, try loading dynamically. engine = ENGINE_by_id("dynamic"); if (engine != nullptr) { if (!ENGINE_ctrl_cmd_string(engine, "SO_PATH", engine_id, 0) || !ENGINE_ctrl_cmd_string(engine, "LOAD", nullptr, 0)) { ENGINE_free(engine); engine = nullptr; } } } if (engine == nullptr) { int err = ERR_get_error(); if (err != 0) { ERR_error_string_n(err, *errmsg, sizeof(*errmsg)); } else { snprintf(*errmsg, sizeof(*errmsg), "Engine \"%s\" was not found", engine_id); } } return engine; } #endif // !OPENSSL_NO_ENGINE // This callback is used to avoid the default passphrase callback in OpenSSL // which will typically prompt for the passphrase. The prompting is designed // for the OpenSSL CLI, but works poorly for Node.js because it involves // synchronous interaction with the controlling terminal, something we never // want, and use this function to avoid it. static int NoPasswordCallback(char* buf, int size, int rwflag, void* u) { return 0; } struct CryptoErrorVector : public std::vector<std::string> { inline void Capture() { clear(); while (auto err = ERR_get_error()) { char buf[256]; ERR_error_string_n(err, buf, sizeof(buf)); push_back(buf); } std::reverse(begin(), end()); } inline Local<Value> ToException( Environment* env, Local<String> exception_string = Local<String>()) const { if (exception_string.IsEmpty()) { CryptoErrorVector copy(*this); if (copy.empty()) copy.push_back("no error"); // But possibly a bug... // Use last element as the error message, everything else goes // into the .opensslErrorStack property on the exception object. auto exception_string = String::NewFromUtf8(env->isolate(), copy.back().data(), NewStringType::kNormal, copy.back().size()) .ToLocalChecked(); copy.pop_back(); return copy.ToException(env, exception_string); } Local<Value> exception_v = Exception::Error(exception_string); CHECK(!exception_v.IsEmpty()); if (!empty()) { Local<Array> array = Array::New(env->isolate(), size()); CHECK(!array.IsEmpty()); for (const std::string& string : *this) { const size_t index = &string - &front(); Local<String> value = String::NewFromUtf8(env->isolate(), string.data(), NewStringType::kNormal, string.size()) .ToLocalChecked(); array->Set(env->context(), index, value).FromJust(); } CHECK(exception_v->IsObject()); Local<Object> exception = exception_v.As<Object>(); exception->Set(env->context(), env->openssl_error_stack(), array).FromJust(); } return exception_v; } }; void ThrowCryptoError(Environment* env, unsigned long err, // NOLINT(runtime/int) const char* message = nullptr) { char message_buffer[128] = {0}; if (err != 0 || message == nullptr) { ERR_error_string_n(err, message_buffer, sizeof(message_buffer)); message = message_buffer; } HandleScope scope(env->isolate()); auto exception_string = String::NewFromUtf8(env->isolate(), message, NewStringType::kNormal) .ToLocalChecked(); CryptoErrorVector errors; errors.Capture(); auto exception = errors.ToException(env, exception_string); env->isolate()->ThrowException(exception); } // Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG. // The entropy pool starts out empty and needs to fill up before the PRNG // can be used securely. Once the pool is filled, it never dries up again; // its contents is stirred and reused when necessary. // // OpenSSL normally fills the pool automatically but not when someone starts // generating random numbers before the pool is full: in that case OpenSSL // keeps lowering the entropy estimate to thwart attackers trying to guess // the initial state of the PRNG. // // When that happens, we will have to wait until enough entropy is available. // That should normally never take longer than a few milliseconds. // // OpenSSL draws from /dev/random and /dev/urandom. While /dev/random may // block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't // block under normal circumstances. // // The only time when /dev/urandom may conceivably block is right after boot, // when the whole system is still low on entropy. That's not something we can // do anything about. inline void CheckEntropy() { for (;;) { int status = RAND_status(); CHECK_GE(status, 0); // Cannot fail. if (status != 0) break; // Give up, RAND_poll() not supported. if (RAND_poll() == 0) break; } } bool EntropySource(unsigned char* buffer, size_t length) { // Ensure that OpenSSL's PRNG is properly seeded. CheckEntropy(); // RAND_bytes() can return 0 to indicate that the entropy data is not truly // random. That's okay, it's still better than V8's stock source of entropy, // which is /dev/urandom on UNIX platforms and the current time on Windows. return RAND_bytes(buffer, length) != -1; } void SecureContext::Initialize(Environment* env, Local<Object> target) { Local<FunctionTemplate> t = env->NewFunctionTemplate(New); t->InstanceTemplate()->SetInternalFieldCount(1); Local<String> secureContextString = FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext"); t->SetClassName(secureContextString); env->SetProtoMethod(t, "init", Init); env->SetProtoMethod(t, "setKey", SetKey); env->SetProtoMethod(t, "setCert", SetCert); env->SetProtoMethod(t, "addCACert", AddCACert); env->SetProtoMethod(t, "addCRL", AddCRL); env->SetProtoMethod(t, "addRootCerts", AddRootCerts); env->SetProtoMethod(t, "setCiphers", SetCiphers); env->SetProtoMethod(t, "setECDHCurve", SetECDHCurve); env->SetProtoMethod(t, "setDHParam", SetDHParam); env->SetProtoMethod(t, "setOptions", SetOptions); env->SetProtoMethod(t, "setSessionIdContext", SetSessionIdContext); env->SetProtoMethod(t, "setSessionTimeout", SetSessionTimeout); env->SetProtoMethod(t, "close", Close); env->SetProtoMethod(t, "loadPKCS12", LoadPKCS12); #ifndef OPENSSL_NO_ENGINE env->SetProtoMethod(t, "setClientCertEngine", SetClientCertEngine); #endif // !OPENSSL_NO_ENGINE env->SetProtoMethodNoSideEffect(t, "getTicketKeys", GetTicketKeys); env->SetProtoMethod(t, "setTicketKeys", SetTicketKeys); env->SetProtoMethod(t, "setFreeListLength", SetFreeListLength); env->SetProtoMethod(t, "enableTicketKeyCallback", EnableTicketKeyCallback); env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate<true>); env->SetProtoMethodNoSideEffect(t, "getIssuer", GetCertificate<false>); #define SET_INTEGER_CONSTANTS(name, value) \ t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), name), \ Integer::NewFromUnsigned(env->isolate(), value)); SET_INTEGER_CONSTANTS("kTicketKeyReturnIndex", kTicketKeyReturnIndex); SET_INTEGER_CONSTANTS("kTicketKeyHMACIndex", kTicketKeyHMACIndex); SET_INTEGER_CONSTANTS("kTicketKeyAESIndex", kTicketKeyAESIndex); SET_INTEGER_CONSTANTS("kTicketKeyNameIndex", kTicketKeyNameIndex); SET_INTEGER_CONSTANTS("kTicketKeyIVIndex", kTicketKeyIVIndex); #undef SET_INTEGER_CONSTANTS Local<FunctionTemplate> ctx_getter_templ = FunctionTemplate::New(env->isolate(), CtxGetter, env->as_external(), Signature::New(env->isolate(), t)); t->PrototypeTemplate()->SetAccessorProperty( FIXED_ONE_BYTE_STRING(env->isolate(), "_external"), ctx_getter_templ, Local<FunctionTemplate>(), static_cast<PropertyAttribute>(ReadOnly | DontDelete)); target->Set(secureContextString, t->GetFunction(env->context()).ToLocalChecked()); env->set_secure_context_constructor_template(t); } void SecureContext::New(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); new SecureContext(env, args.This()); } void SecureContext::Init(const FunctionCallbackInfo<Value>& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); Environment* env = sc->env(); int min_version = 0; int max_version = 0; const SSL_METHOD* method = TLS_method(); if (args.Length() == 1 && args[0]->IsString()) { const node::Utf8Value sslmethod(env->isolate(), args[0]); // Note that SSLv2 and SSLv3 are disallowed but SSLv23_method and friends // are still accepted. They are OpenSSL's way of saying that all known // protocols are supported unless explicitly disabled (which we do below // for SSLv2 and SSLv3.) if (strcmp(*sslmethod, "SSLv2_method") == 0) { return env->ThrowError("SSLv2 methods disabled"); } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) { return env->ThrowError("SSLv2 methods disabled"); } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) { return env->ThrowError("SSLv2 methods disabled"); } else if (strcmp(*sslmethod, "SSLv3_method") == 0) { return env->ThrowError("SSLv3 methods disabled"); } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) { return env->ThrowError("SSLv3 methods disabled"); } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) { return env->ThrowError("SSLv3 methods disabled"); } else if (strcmp(*sslmethod, "SSLv23_method") == 0) { // noop } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) { method = TLS_server_method(); } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) { method = TLS_client_method(); } else if (strcmp(*sslmethod, "TLSv1_method") == 0) { min_version = TLS1_VERSION; max_version = TLS1_VERSION; } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) { min_version = TLS1_VERSION; max_version = TLS1_VERSION; method = TLS_server_method(); } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) { min_version = TLS1_VERSION; max_version = TLS1_VERSION; method = TLS_client_method(); } else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) { min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; } else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) { min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; method = TLS_server_method(); } else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) { min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; method = TLS_client_method(); } else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) { min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; } else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) { min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; method = TLS_server_method(); } else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) { min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; method = TLS_client_method(); } else { return env->ThrowError("Unknown method"); } } sc->ctx_.reset(SSL_CTX_new(method)); SSL_CTX_set_app_data(sc->ctx_.get(), sc); // Disable SSLv2 in the case when method == TLS_method() and the // cipher list contains SSLv2 ciphers (not the default, should be rare.) // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may. // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.) SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv2); SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv3); // Enable automatic cert chaining. This is enabled by default in OpenSSL, but // disabled by default in BoringSSL. Enable it explicitly to make the // behavior match when Node is built with BoringSSL. SSL_CTX_clear_mode(sc->ctx_.get(), SSL_MODE_NO_AUTO_CHAIN); // SSL session cache configuration SSL_CTX_set_session_cache_mode(sc->ctx_.get(), SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_NO_AUTO_CLEAR); SSL_CTX_set_min_proto_version(sc->ctx_.get(), min_version); SSL_CTX_set_max_proto_version(sc->ctx_.get(), max_version); // OpenSSL 1.1.0 changed the ticket key size, but the OpenSSL 1.0.x size was // exposed in the public API. To retain compatibility, install a callback // which restores the old algorithm. if (RAND_bytes(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) <= 0 || RAND_bytes(sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_)) <= 0 || RAND_bytes(sc->ticket_key_aes_, sizeof(sc->ticket_key_aes_)) <= 0) { return env->ThrowError("Error generating ticket keys"); } SSL_CTX_set_tlsext_ticket_key_cb(sc->ctx_.get(), TicketCompatibilityCallback); } // Takes a string or buffer and loads it into a BIO. // Caller responsible for BIO_free_all-ing the returned object. static BIOPointer LoadBIO(Environment* env, Local<Value> v) { HandleScope scope(env->isolate()); if (v->IsString()) { const node::Utf8Value s(env->isolate(), v); return NodeBIO::NewFixed(*s, s.length()); } if (Buffer::HasInstance(v)) { return NodeBIO::NewFixed(Buffer::Data(v), Buffer::Length(v)); } return nullptr; } void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); unsigned int len = args.Length(); if (len < 1) { return THROW_ERR_MISSING_ARGS(env, "Private key argument is mandatory"); } if (len > 2) { return env->ThrowError("Only private key and pass phrase are expected"); } if (len == 2) { if (args[1]->IsUndefined() || args[1]->IsNull()) len = 1; else THROW_AND_RETURN_IF_NOT_STRING(env, args[1], "Pass phrase"); } BIOPointer bio(LoadBIO(env, args[0])); if (!bio) return; node::Utf8Value passphrase(env->isolate(), args[1]); EVPKeyPointer key( PEM_read_bio_PrivateKey(bio.get(), nullptr, PasswordCallback, len == 1 ? nullptr : *passphrase)); if (!key) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) if (!err) { return env->ThrowError("PEM_read_bio_PrivateKey"); } return ThrowCryptoError(env, err); } int rv = SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get()); if (!rv) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) if (!err) return env->ThrowError("SSL_CTX_use_PrivateKey"); return ThrowCryptoError(env, err); } } int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) { X509_STORE* store = SSL_CTX_get_cert_store(ctx); DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx( X509_STORE_CTX_new()); return store_ctx.get() != nullptr && X509_STORE_CTX_init(store_ctx.get(), store, nullptr, nullptr) == 1 && X509_STORE_CTX_get1_issuer(issuer, store_ctx.get(), cert) == 1; } int SSL_CTX_use_certificate_chain(SSL_CTX* ctx, X509Pointer&& x, STACK_OF(X509)* extra_certs, X509Pointer* cert, X509Pointer* issuer_) { CHECK(!*issuer_); CHECK(!*cert); X509* issuer = nullptr; int ret = SSL_CTX_use_certificate(ctx, x.get()); if (ret) { // If we could set up our certificate, now proceed to // the CA certificates. SSL_CTX_clear_extra_chain_certs(ctx); for (int i = 0; i < sk_X509_num(extra_certs); i++) { X509* ca = sk_X509_value(extra_certs, i); // NOTE: Increments reference count on `ca` if (!SSL_CTX_add1_chain_cert(ctx, ca)) { ret = 0; issuer = nullptr; break; } // Note that we must not free r if it was successfully // added to the chain (while we must free the main // certificate, since its reference count is increased // by SSL_CTX_use_certificate). // Find issuer if (issuer != nullptr || X509_check_issued(ca, x.get()) != X509_V_OK) continue; issuer = ca; } } // Try getting issuer from a cert store if (ret) { if (issuer == nullptr) { ret = SSL_CTX_get_issuer(ctx, x.get(), &issuer); ret = ret < 0 ? 0 : 1; // NOTE: get_cert_store doesn't increment reference count, // no need to free `store` } else { // Increment issuer reference count issuer = X509_dup(issuer); if (issuer == nullptr) { ret = 0; } } } issuer_->reset(issuer); if (ret && x != nullptr) { cert->reset(X509_dup(x.get())); if (!*cert) ret = 0; } return ret; } // Read a file that contains our certificate in "PEM" format, // possibly followed by a sequence of CA certificates that should be // sent to the peer in the Certificate message. // // Taken from OpenSSL - edited for style. int SSL_CTX_use_certificate_chain(SSL_CTX* ctx, BIOPointer&& in, X509Pointer* cert, X509Pointer* issuer) { // Just to ensure that `ERR_peek_last_error` below will return only errors // that we are interested in ERR_clear_error(); X509Pointer x( PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr)); if (!x) return 0; unsigned long err = 0; // NOLINT(runtime/int) StackOfX509 extra_certs(sk_X509_new_null()); if (!extra_certs) return 0; while (X509Pointer extra {PEM_read_bio_X509(in.get(), nullptr, NoPasswordCallback, nullptr)}) { if (sk_X509_push(extra_certs.get(), extra.get())) { extra.release(); continue; } return 0; } // When the while loop ends, it's usually just EOF. err = ERR_peek_last_error(); if (ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE) { ERR_clear_error(); } else { // some real error return 0; } return SSL_CTX_use_certificate_chain(ctx, std::move(x), extra_certs.get(), cert, issuer); } void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); if (args.Length() != 1) { return THROW_ERR_MISSING_ARGS(env, "Certificate argument is mandatory"); } BIOPointer bio(LoadBIO(env, args[0])); if (!bio) return; sc->cert_.reset(); sc->issuer_.reset(); int rv = SSL_CTX_use_certificate_chain(sc->ctx_.get(), std::move(bio), &sc->cert_, &sc->issuer_); if (!rv) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) if (!err) { return env->ThrowError("SSL_CTX_use_certificate_chain"); } return ThrowCryptoError(env, err); } } static X509_STORE* NewRootCertStore() { static std::vector<X509*> root_certs_vector; static Mutex root_certs_vector_mutex; Mutex::ScopedLock lock(root_certs_vector_mutex); if (root_certs_vector.empty()) { for (size_t i = 0; i < arraysize(root_certs); i++) { X509* x509 = PEM_read_bio_X509(NodeBIO::NewFixed(root_certs[i], strlen(root_certs[i])).get(), nullptr, // no re-use of X509 structure NoPasswordCallback, nullptr); // no callback data // Parse errors from the built-in roots are fatal. CHECK_NOT_NULL(x509); root_certs_vector.push_back(x509); } } X509_STORE* store = X509_STORE_new(); if (*system_cert_path != '\0') { X509_STORE_load_locations(store, system_cert_path, nullptr); } if (per_process_opts->ssl_openssl_cert_store) { X509_STORE_set_default_paths(store); } else { for (X509* cert : root_certs_vector) { X509_up_ref(cert); X509_STORE_add_cert(store, cert); } } return store; } void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); ClearErrorOnReturn clear_error_on_return; if (args.Length() != 1) { return THROW_ERR_MISSING_ARGS(env, "CA certificate argument is mandatory"); } BIOPointer bio(LoadBIO(env, args[0])); if (!bio) return; X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get()); while (X509* x509 = PEM_read_bio_X509( bio.get(), nullptr, NoPasswordCallback, nullptr)) { if (cert_store == root_cert_store) { cert_store = NewRootCertStore(); SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store); } X509_STORE_add_cert(cert_store, x509); SSL_CTX_add_client_CA(sc->ctx_.get(), x509); X509_free(x509); } } void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); if (args.Length() != 1) { return THROW_ERR_MISSING_ARGS(env, "CRL argument is mandatory"); } ClearErrorOnReturn clear_error_on_return; BIOPointer bio(LoadBIO(env, args[0])); if (!bio) return; DeleteFnPtr<X509_CRL, X509_CRL_free> crl( PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr)); if (!crl) return env->ThrowError("Failed to parse CRL"); X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get()); if (cert_store == root_cert_store) { cert_store = NewRootCertStore(); SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store); } X509_STORE_add_crl(cert_store, crl.get()); X509_STORE_set_flags(cert_store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL); } static unsigned long AddCertsFromFile( // NOLINT(runtime/int) X509_STORE* store, const char* file) { ERR_clear_error(); MarkPopErrorOnReturn mark_pop_error_on_return; BIOPointer bio(BIO_new_file(file, "r")); if (!bio) return ERR_get_error(); while (X509* x509 = PEM_read_bio_X509(bio.get(), nullptr, NoPasswordCallback, nullptr)) { X509_STORE_add_cert(store, x509); X509_free(x509); } unsigned long err = ERR_peek_error(); // NOLINT(runtime/int) // Ignore error if its EOF/no start line found. if (ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE) { return 0; } return err; } void UseExtraCaCerts(const std::string& file) { ClearErrorOnReturn clear_error_on_return; if (root_cert_store == nullptr) { root_cert_store = NewRootCertStore(); if (!file.empty()) { unsigned long err = AddCertsFromFile( // NOLINT(runtime/int) root_cert_store, file.c_str()); if (err) { fprintf(stderr, "Warning: Ignoring extra certs from `%s`, load failed: %s\n", file.c_str(), ERR_error_string(err, nullptr)); } else { extra_root_certs_loaded = true; } } } } static void IsExtraRootCertsFileLoaded( const FunctionCallbackInfo<Value>& args) { return args.GetReturnValue().Set(extra_root_certs_loaded); } void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); ClearErrorOnReturn clear_error_on_return; if (root_cert_store == nullptr) { root_cert_store = NewRootCertStore(); } // Increment reference count so global store is not deleted along with CTX. X509_STORE_up_ref(root_cert_store); SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store); } void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); Environment* env = sc->env(); ClearErrorOnReturn clear_error_on_return; if (args.Length() != 1) { return THROW_ERR_MISSING_ARGS(env, "Ciphers argument is mandatory"); } THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Ciphers"); const node::Utf8Value ciphers(args.GetIsolate(), args[0]); if (!SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) { unsigned long err = ERR_get_error(); // NOLINT(runtime/int) if (!err) { return env->ThrowError("Failed to set ciphers"); } return ThrowCryptoError(env, err); } } void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); Environment* env = sc->env(); if (args.Length() != 1) return THROW_ERR_MISSING_ARGS(env, "ECDH curve name argument is mandatory"); THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "ECDH curve name"); node::Utf8Value curve(env->isolate(), args[0]); if (strcmp(*curve, "auto") == 0) return; if (!SSL_CTX_set1_curves_list(sc->ctx_.get(), *curve)) return env->ThrowError("Failed to set ECDH curve"); } void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.This()); Environment* env = sc->env(); ClearErrorOnReturn clear_error_on_return; // Auto DH is not supported in openssl 1.0.1, so dhparam needs // to be specified explicitly if (args.Length() != 1) return THROW_ERR_MISSING_ARGS(env, "DH argument is mandatory"); DHPointer dh; { BIOPointer bio(LoadBIO(env, args[0])); if (!bio) return; dh.reset(PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr)); } // Invalid dhparam is silently discarded and DHE is no longer used. if (!dh) return; const BIGNUM* p; DH_get0_pqg(dh.get(), &p, nullptr, nullptr); const int size = BN_num_bits(p); if (size < 1024) { return THROW_ERR_INVALID_ARG_VALUE( env, "DH parameter is less than 1024 bits"); } else if (size < 2048) { args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING( env->isolate(), "DH parameter is less than 2048 bits")); } SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_SINGLE_DH_USE); int r = SSL_CTX_set_tmp_dh(sc->ctx_.get(), dh.get()); if (!r) return env->ThrowTypeError("Error setting temp DH parameter"); } void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) { SecureContext* sc; ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder()); int64_t val; if (args.Length() != 1 || !args[0]->IntegerValue(args.GetIsolate()->GetCurrentContext()).To(&val)) { return THROW_ERR_INVALID_ARG_TYPE( sc->env(), "Options must be an integer value"); |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |