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/lib/_tls_wrap.js at main · synapse/node Expand file tree/ Copy path_tls_wrap.jsMore file actions 1827 lines (1530 loc) · 52.4 KB / Copy path_tls_wrap.jsFile metadata and controls1827 lines (1530 loc) · 52.4 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. 'use strict'; const { ArrayPrototypeForEach, ArrayPrototypeJoin, ArrayPrototypePush, FunctionPrototype, ObjectAssign, ObjectDefineProperty, ObjectSetPrototypeOf, ReflectApply, RegExp, RegExpPrototypeExec, RegExpPrototypeSymbolReplace, StringPrototypeReplaceAll, StringPrototypeSlice, Symbol, SymbolFor, } = primordials; const { assertCrypto, deprecate, kEmptyObject, } = require('internal/util'); assertCrypto(); const { setImmediate } = require('timers'); const assert = require('internal/assert'); const crypto = require('crypto'); const EE = require('events'); const net = require('net'); const tls = require('tls'); const common = require('_tls_common'); const { kReinitializeHandle } = require('internal/net'); const JSStreamSocket = require('internal/js_stream_socket'); const { Buffer } = require('buffer'); let debug = require('internal/util/debuglog').debuglog('tls', (fn) => { debug = fn; }); const { TCP, constants: TCPConstants } = internalBinding('tcp_wrap'); const tls_wrap = internalBinding('tls_wrap'); const { Pipe, constants: PipeConstants } = internalBinding('pipe_wrap'); const { owner_symbol } = require('internal/async_hooks').symbols; const { isArrayBufferView } = require('internal/util/types'); const { SecureContext: NativeSecureContext } = internalBinding('crypto'); const { ConnResetException, codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_MULTIPLE_CALLBACK, ERR_SOCKET_CLOSED, ERR_TLS_ALPN_CALLBACK_INVALID_RESULT, ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS, ERR_TLS_DH_PARAM_SIZE, ERR_TLS_HANDSHAKE_TIMEOUT, ERR_TLS_INVALID_CONTEXT, ERR_TLS_INVALID_STATE, ERR_TLS_RENEGOTIATION_DISABLED, ERR_TLS_REQUIRED_SERVER_NAME, ERR_TLS_SESSION_ATTACK, ERR_TLS_SNI_FROM_SERVER, }, } = require('internal/errors'); const { onpskexchange: kOnPskExchange } = internalBinding('symbols'); const { getOptionValue, getAllowUnauthorized, } = require('internal/options'); const { validateBoolean, validateBuffer, validateFunction, validateInt32, validateNumber, validateObject, validateString, validateUint32, } = require('internal/validators'); const { InternalX509Certificate, } = require('internal/crypto/x509'); const traceTls = getOptionValue('--trace-tls'); const tlsKeylog = getOptionValue('--tls-keylog'); const { appendFile } = require('fs'); const kConnectOptions = Symbol('connect-options'); const kDisableRenegotiation = Symbol('disable-renegotiation'); const kErrorEmitted = Symbol('error-emitted'); const kHandshakeTimeout = Symbol('handshake-timeout'); const kRes = Symbol('res'); const kSNICallback = Symbol('snicallback'); const kALPNCallback = Symbol('alpncallback'); const kEnableTrace = Symbol('enableTrace'); const kPskCallback = Symbol('pskcallback'); const kPskIdentityHint = Symbol('pskidentityhint'); const kPendingSession = Symbol('pendingSession'); const kIsVerified = Symbol('verified'); const noop = FunctionPrototype; let ipServernameWarned = false; let tlsTracingWarned = false; // Server side times how long a handshake is taking to protect against slow // handshakes being used for DoS. function onhandshakestart(now) { debug('server onhandshakestart'); const { lastHandshakeTime } = this; assert(now >= lastHandshakeTime, `now (${now}) < lastHandshakeTime (${lastHandshakeTime})`); this.lastHandshakeTime = now; // If this is the first handshake we can skip the rest of the checks. if (lastHandshakeTime === 0) return; if ((now - lastHandshakeTime) >= tls.CLIENT_RENEG_WINDOW * 1000) this.handshakes = 1; else this.handshakes++; const owner = this[owner_symbol]; assert(owner._tlsOptions.isServer); if (this.handshakes > tls.CLIENT_RENEG_LIMIT) { owner._emitTLSError(new ERR_TLS_SESSION_ATTACK()); return; } if (owner[kDisableRenegotiation]) owner._emitTLSError(new ERR_TLS_RENEGOTIATION_DISABLED()); } function onhandshakedone() { debug('server onhandshakedone'); const owner = this[owner_symbol]; assert(owner._tlsOptions.isServer); // `newSession` callback wasn't called yet if (owner._newSessionPending) { owner._securePending = true; return; } owner._finishInit(); } function loadSession(hello) { debug('server onclienthello', 'sessionid.len', hello.sessionId.length, 'ticket?', hello.tlsTicket, ); const owner = this[owner_symbol]; let once = false; function onSession(err, session) { debug('server resumeSession callback(err %j, sess? %s)', err, !!session); if (once) return owner.destroy(new ERR_MULTIPLE_CALLBACK()); once = true; if (err) return owner.destroy(err); if (owner._handle === null) return owner.destroy(new ERR_SOCKET_CLOSED()); owner._handle.loadSession(session); // Session is loaded. End the parser to allow handshaking to continue. owner._handle.endParser(); } if (hello.sessionId.length <= 0 || hello.tlsTicket || (owner.server && !owner.server.emit('resumeSession', hello.sessionId, onSession))) { // Sessions without identifiers can't be resumed. // Sessions with tickets can be resumed directly from the ticket, no server // session storage is necessary. // Without a call to a resumeSession listener, a session will never be // loaded, so end the parser to allow handshaking to continue. owner._handle.endParser(); } } function loadSNI(info) { const owner = this[owner_symbol]; const servername = info.servername; if (!servername || !owner._SNICallback) return requestOCSP(owner, info); let once = false; owner._SNICallback(servername, (err, context) => { if (once) return owner.destroy(new ERR_MULTIPLE_CALLBACK()); once = true; if (err) return owner.destroy(err); if (owner._handle === null) return owner.destroy(new ERR_SOCKET_CLOSED()); // TODO(indutny): eventually disallow raw `SecureContext` if (context) owner._handle.sni_context = context.context || context; requestOCSP(owner, info); }); } function callALPNCallback(protocolsBuffer) { const handle = this; const socket = handle[owner_symbol]; const servername = handle.getServername(); // Collect all the protocols from the given buffer: const protocols = []; let offset = 0; while (offset < protocolsBuffer.length) { const protocolLen = protocolsBuffer[offset]; offset += 1; const protocol = protocolsBuffer.slice(offset, offset + protocolLen); offset += protocolLen; protocols.push(protocol.toString('ascii')); } const selectedProtocol = socket[kALPNCallback]({ servername, protocols, }); // Undefined -> all proposed protocols rejected if (selectedProtocol === undefined) return undefined; const protocolIndex = protocols.indexOf(selectedProtocol); if (protocolIndex === -1) { throw new ERR_TLS_ALPN_CALLBACK_INVALID_RESULT(selectedProtocol, protocols); } let protocolOffset = 0; for (let i = 0; i < protocolIndex; i++) { protocolOffset += 1 + protocols[i].length; } return protocolOffset; } function requestOCSP(socket, info) { if (!info.OCSPRequest || !socket.server) return requestOCSPDone(socket); let ctx = socket._handle.sni_context; if (!ctx) { ctx = socket.server._sharedCreds; // TLS socket is using a `net.Server` instead of a tls.TLSServer. // Some TLS properties like `server._sharedCreds` will not be present if (!ctx) return requestOCSPDone(socket); } // TODO(indutny): eventually disallow raw `SecureContext` if (ctx.context) ctx = ctx.context; if (socket.server.listenerCount('OCSPRequest') === 0) { return requestOCSPDone(socket); } let once = false; const onOCSP = (err, response) => { debug('server OCSPRequest done', 'handle?', !!socket._handle, 'once?', once, 'response?', !!response, 'err?', err); if (once) return socket.destroy(new ERR_MULTIPLE_CALLBACK()); once = true; if (err) return socket.destroy(err); if (socket._handle === null) return socket.destroy(new ERR_SOCKET_CLOSED()); if (response) socket._handle.setOCSPResponse(response); requestOCSPDone(socket); }; debug('server oncertcb emit OCSPRequest'); socket.server.emit('OCSPRequest', ctx.getCertificate(), ctx.getIssuer(), onOCSP); } function requestOCSPDone(socket) { debug('server certcb done'); try { socket._handle.certCbDone(); } catch (e) { debug('server certcb done errored', e); socket.destroy(e); } } function onnewsessionclient(sessionId, session) { debug('client emit session'); const owner = this[owner_symbol]; if (owner[kIsVerified]) { owner.emit('session', session); } else { owner[kPendingSession] = session; } } function onnewsession(sessionId, session) { debug('onnewsession'); const owner = this[owner_symbol]; // TODO(@sam-github) no server to emit the event on, but handshake won't // continue unless newSessionDone() is called, should it be, or is that // situation unreachable, or only occurring during shutdown? if (!owner.server) return; let once = false; const done = () => { debug('onnewsession done'); if (once) return; once = true; if (owner._handle === null) return owner.destroy(new ERR_SOCKET_CLOSED()); this.newSessionDone(); owner._newSessionPending = false; if (owner._securePending) owner._finishInit(); owner._securePending = false; }; owner._newSessionPending = true; if (!owner.server.emit('newSession', sessionId, session, done)) done(); } function onPskServerCallback(identity, maxPskLen) { const owner = this[owner_symbol]; const ret = owner[kPskCallback](owner, identity); if (ret == null) return undefined; let psk; if (isArrayBufferView(ret)) { psk = ret; } else { if (typeof ret !== 'object') { throw new ERR_INVALID_ARG_TYPE( 'ret', ['Object', 'Buffer', 'TypedArray', 'DataView'], ret, ); } psk = ret.psk; validateBuffer(psk, 'psk'); } if (psk.length > maxPskLen) { throw new ERR_INVALID_ARG_VALUE( 'psk', psk, `Pre-shared key exceeds ${maxPskLen} bytes`, ); } return psk; } function onPskClientCallback(hint, maxPskLen, maxIdentityLen) { const owner = this[owner_symbol]; const ret = owner[kPskCallback](hint); if (ret == null) return undefined; validateObject(ret, 'ret'); validateBuffer(ret.psk, 'psk'); if (ret.psk.length > maxPskLen) { throw new ERR_INVALID_ARG_VALUE( 'psk', ret.psk, `Pre-shared key exceeds ${maxPskLen} bytes`, ); } validateString(ret.identity, 'identity'); if (Buffer.byteLength(ret.identity) > maxIdentityLen) { throw new ERR_INVALID_ARG_VALUE( 'identity', ret.identity, `PSK identity exceeds ${maxIdentityLen} bytes`, ); } return { psk: ret.psk, identity: ret.identity }; } function onkeylog(line) { debug('onkeylog'); this[owner_symbol].emit('keylog', line); } function onocspresponse(resp) { debug('client onocspresponse'); this[owner_symbol].emit('OCSPResponse', resp); } function onerror(err) { const owner = this[owner_symbol]; debug('%s onerror %s had? %j', (typeof owner._tlsOptions === 'object' && owner._tlsOptions !== null) ? owner._tlsOptions.isServer ? 'server' : 'client' : 'unknown', err, owner._hadError); if (owner._hadError) return; owner._hadError = true; // Destroy socket if error happened before handshake's finish if (!owner._secureEstablished) { // When handshake fails control is not yet released, // so self._tlsError will return null instead of actual error // Set closing the socket after emitting an event since the socket needs to // be accessible when the `tlsClientError` event is emitted. owner._closeAfterHandlingError = true; owner.destroy(err); } else if (owner._tlsOptions?.isServer && owner._rejectUnauthorized && RegExpPrototypeExec(/peer did not return a certificate/, err.message) !== null) { // Ignore server's authorization errors owner.destroy(); } else { // Emit error owner._emitTLSError(err); } } // Used by both client and server TLSSockets to start data flowing from _handle, // read(0) causes a StreamBase::ReadStart, via Socket._read. function initRead(tlsSocket, socket) { debug('%s initRead', tlsSocket._tlsOptions.isServer ? 'server' : 'client', 'handle?', !!tlsSocket._handle, 'buffered?', !!socket && socket.readableLength, ); // If we were destroyed already don't bother reading if (!tlsSocket._handle) return; // Socket already has some buffered data - emulate receiving it if (socket && socket.readableLength) { let buf; while ((buf = socket.read()) !== null) tlsSocket._handle.receive(buf); } tlsSocket.read(0); } /** * Provides a wrap of socket stream to do encrypted communication. */ function TLSSocket(socket, opts) { const tlsOptions = { ...opts }; let enableTrace = tlsOptions.enableTrace; if (enableTrace == null) { enableTrace = traceTls; if (enableTrace && !tlsTracingWarned) { tlsTracingWarned = true; process.emitWarning('Enabling --trace-tls can expose sensitive data in ' + 'the resulting log.'); } } else { validateBoolean(enableTrace, 'options.enableTrace'); } if (tlsOptions.ALPNProtocols) tls.convertALPNProtocols(tlsOptions.ALPNProtocols, tlsOptions); this._tlsOptions = tlsOptions; this._secureEstablished = false; this._securePending = false; this._newSessionPending = false; this._controlReleased = false; this.secureConnecting = true; this._SNICallback = null; this[kALPNCallback] = null; this.servername = null; this.alpnProtocol = null; this.authorized = false; this.authorizationError = null; this[kRes] = null; this[kIsVerified] = false; this[kPendingSession] = null; let wrap; let handle; let wrapHasActiveWriteFromPrevOwner; if (socket) { if (socket instanceof net.Socket && socket._handle) { // 1. connected socket wrap = socket; } else { // 2. socket has no handle so it is js not c++ // 3. unconnected sockets are wrapped // TLS expects to interact from C++ with a net.Socket that has a C++ stream // handle, but a JS stream doesn't have one. Wrap it up to make it look like // a socket. wrap = new JSStreamSocket(socket); } handle = wrap._handle; wrapHasActiveWriteFromPrevOwner = wrap.writableLength > 0; } else { // 4. no socket, one will be created with net.Socket().connect wrap = null; wrapHasActiveWriteFromPrevOwner = false; } // Just a documented property to make secure sockets // distinguishable from regular ones. this.encrypted = true; ReflectApply(net.Socket, this, [{ handle: this._wrapHandle(wrap, handle, wrapHasActiveWriteFromPrevOwner), allowHalfOpen: socket ? socket.allowHalfOpen : tlsOptions.allowHalfOpen, pauseOnCreate: tlsOptions.pauseOnConnect, manualStart: true, highWaterMark: tlsOptions.highWaterMark, onread: !socket ? tlsOptions.onread : null, signal: tlsOptions.signal, }]); // Proxy for API compatibility this.ssl = this._handle; // C++ TLSWrap object this.on('error', this._tlsError); this._init(socket, wrap); if (enableTrace && this._handle) this._handle.enableTrace(); if (wrapHasActiveWriteFromPrevOwner) { // `wrap` is a streams.Writable in JS. This empty write will be queued // and hence finish after all existing writes, which is the timing // we want to start to send any tls data to `wrap`. wrap.write('', (err) => { if (err) { debug('error got before writing any tls data to the underlying stream'); this.destroy(err); return; } this._handle.writesIssuedByPrevListenerDone(); }); } // Read on next tick so the caller has a chance to setup listeners process.nextTick(initRead, this, socket); } ObjectSetPrototypeOf(TLSSocket.prototype, net.Socket.prototype); ObjectSetPrototypeOf(TLSSocket, net.Socket); exports.TLSSocket = TLSSocket; const proxiedMethods = [ 'ref', 'unref', 'open', 'bind', 'listen', 'connect', 'bind6', 'connect6', 'getsockname', 'getpeername', 'setNoDelay', 'setKeepAlive', 'setSimultaneousAccepts', 'setBlocking', // PipeWrap 'setPendingInstances', ]; // Proxy HandleWrap, PipeWrap and TCPWrap methods function makeMethodProxy(name) { return function methodProxy(...args) { if (this._parent[name]) return ReflectApply(this._parent[name], this._parent, args); }; } for (const proxiedMethod of proxiedMethods) { tls_wrap.TLSWrap.prototype[proxiedMethod] = makeMethodProxy(proxiedMethod); } tls_wrap.TLSWrap.prototype.close = function close(cb) { let ssl; if (this[owner_symbol]) { ssl = this[owner_symbol].ssl; this[owner_symbol].ssl = null; } // Invoke `destroySSL` on close to clean up possibly pending write requests // that may self-reference TLSWrap, leading to leak const done = () => { if (ssl) { ssl.destroySSL(); if (ssl._secureContext.singleUse) { ssl._secureContext.context.close(); ssl._secureContext.context = null; } } if (cb) cb(); }; if (this._parentWrap) { if (this._parentWrap._handle === null) { // The socket handle was already closed. done(); return; } if (this._parentWrap._handle === this._parent) { this._parentWrap.once('close', done); this._parentWrap.destroy(); return; } } return this._parent.close(done); }; TLSSocket.prototype.disableRenegotiation = function disableRenegotiation() { this[kDisableRenegotiation] = true; }; /** * * @param {null|net.Socket} wrap * @param {null|object} handle * @param {boolean} wrapHasActiveWriteFromPrevOwner * @returns {object} */ TLSSocket.prototype._wrapHandle = function(wrap, handle, wrapHasActiveWriteFromPrevOwner) { const options = this._tlsOptions; if (!handle) { handle = options.pipe ? new Pipe(PipeConstants.SOCKET) : new TCP(TCPConstants.SOCKET); handle[owner_symbol] = this; } // Wrap socket's handle const context = options.secureContext || options.credentials || tls.createSecureContext(options); assert(handle.isStreamBase, 'handle must be a StreamBase'); if (!(context.context instanceof NativeSecureContext)) { throw new ERR_TLS_INVALID_CONTEXT('context'); } const res = tls_wrap.wrap(handle, context.context, !!options.isServer, wrapHasActiveWriteFromPrevOwner); res._parent = handle; // C++ "wrap" object: TCPWrap, JSStream, ... res._parentWrap = wrap; // JS object: net.Socket, JSStreamSocket, ... res._secureContext = context; res.reading = handle.reading; this[kRes] = res; defineHandleReading(this, handle); // Guard against adding multiple listeners, as this method may be called // repeatedly on the same socket by reinitializeHandle if (this.listenerCount('close', onSocketCloseDestroySSL) === 0) { this.on('close', onSocketCloseDestroySSL); } if (wrap) { wrap.on('close', () => this.destroy()); } return res; }; TLSSocket.prototype[kReinitializeHandle] = function reinitializeHandle(handle) { const originalServername = this.ssl ? this._handle.getServername() : null; const originalSession = this.ssl ? this._handle.getSession() : null; this.handle = this._wrapHandle(null, handle, false); this.ssl = this._handle; net.Socket.prototype[kReinitializeHandle].call(this, this.handle); this._init(); if (this._tlsOptions.enableTrace) { this._handle.enableTrace(); } if (originalSession) { this.setSession(originalSession); } if (originalServername) { this.setServername(originalServername); } }; // This eliminates a cyclic reference to TLSWrap // Ref: https://github.com/nodejs/node/commit/f7620fb96d339f704932f9bb9a0dceb9952df2d4 function defineHandleReading(socket, handle) { ObjectDefineProperty(handle, 'reading', { __proto__: null, get: () => { return socket[kRes].reading; }, set: (value) => { socket[kRes].reading = value; }, }); } function onSocketCloseDestroySSL() { // Make sure we are not doing it on OpenSSL's stack setImmediate(destroySSL, this); this[kRes] = null; } function destroySSL(self) { self._destroySSL(); } TLSSocket.prototype._destroySSL = function _destroySSL() { if (!this.ssl) return; this.ssl.destroySSL(); if (this.ssl._secureContext.singleUse) { this.ssl._secureContext.context.close(); this.ssl._secureContext.context = null; } this.ssl = null; this[kPendingSession] = null; this[kIsVerified] = false; }; function keylogNewListener(event) { if (event !== 'keylog') return; // Guard against enableKeylogCallback after destroy if (!this._handle) return; this._handle.enableKeylogCallback(); // Remove this listener since it's no longer needed. this.removeListener('newListener', keylogNewListener); } function newListener(event) { if (event !== 'session') return; // Guard against enableSessionCallbacks after destroy if (!this._handle) return; this._handle.enableSessionCallbacks(); // Remove this listener since it's no longer needed. this.removeListener('newListener', newListener); } // Constructor guts, arbitrarily factored out. let warnOnTlsKeylog = true; let warnOnTlsKeylogError = true; TLSSocket.prototype._init = function(socket, wrap) { const options = this._tlsOptions; const ssl = this._handle; this.server = options.server; debug('%s _init', options.isServer ? 'server' : 'client', 'handle?', !!ssl, ); // Clients (!isServer) always request a cert, servers request a client cert // only on explicit configuration. const requestCert = !!options.requestCert || !options.isServer; const rejectUnauthorized = !!options.rejectUnauthorized; this._requestCert = requestCert; this._rejectUnauthorized = rejectUnauthorized; if (requestCert || rejectUnauthorized) ssl.setVerifyMode(requestCert, rejectUnauthorized); // Only call .onkeylog if there is a keylog listener. ssl.onkeylog = onkeylog; if (this.listenerCount('newListener', keylogNewListener) === 0) { this.on('newListener', keylogNewListener); } if (options.isServer) { ssl.onhandshakestart = onhandshakestart; ssl.onhandshakedone = onhandshakedone; ssl.onclienthello = loadSession; ssl.oncertcb = loadSNI; ssl.onnewsession = onnewsession; ssl.lastHandshakeTime = 0; ssl.handshakes = 0; if (options.ALPNCallback) { validateFunction(options.ALPNCallback, 'options.ALPNCallback'); this[kALPNCallback] = options.ALPNCallback; ssl.ALPNCallback = callALPNCallback; ssl.enableALPNCb(); } if (this.server) { if (this.server.listenerCount('resumeSession') > 0 || this.server.listenerCount('newSession') > 0) { // Also starts the client hello parser as a side effect. ssl.enableSessionCallbacks(); } if (this.server.listenerCount('OCSPRequest') > 0) ssl.enableCertCb(); } } else { ssl.onhandshakestart = noop; ssl.onhandshakedone = () => { debug('client onhandshakedone'); this._finishInit(); }; ssl.onocspresponse = onocspresponse; if (options.session) ssl.setSession(options.session); ssl.onnewsession = onnewsessionclient; // Only call .onnewsession if there is a session listener. if (this.listenerCount('newListener', newListener) === 0) { this.on('newListener', newListener); } } if (tlsKeylog) { if (warnOnTlsKeylog) { warnOnTlsKeylog = false; process.emitWarning('Using --tls-keylog makes TLS connections insecure ' + 'by writing secret key material to file ' + tlsKeylog); } this.on('keylog', (line) => { appendFile(tlsKeylog, line, { mode: 0o600 }, (err) => { if (err && warnOnTlsKeylogError) { warnOnTlsKeylogError = false; process.emitWarning('Failed to write TLS keylog (this warning ' + 'will not be repeated): ' + err); } }); }); } ssl.onerror = onerror; // If custom SNICallback was given, or if // there're SNI contexts to perform match against - // set `.onsniselect` callback. if (options.isServer && options.SNICallback && (options.SNICallback !== SNICallback || (options.server && options.server._contexts.length))) { validateFunction(options.SNICallback, 'options.SNICallback'); this._SNICallback = options.SNICallback; ssl.enableCertCb(); } if (options.ALPNProtocols) ssl.setALPNProtocols(options.ALPNProtocols); if (options.pskCallback && ssl.enablePskCallback) { validateFunction(options.pskCallback, 'pskCallback'); ssl[kOnPskExchange] = options.isServer ? onPskServerCallback : onPskClientCallback; this[kPskCallback] = options.pskCallback; ssl.enablePskCallback(); if (options.pskIdentityHint) { validateString(options.pskIdentityHint, 'options.pskIdentityHint'); ssl.setPskIdentityHint(options.pskIdentityHint); } } // We can only come here via [kWrapConnectedHandle]() call that happens // if the connection is established with `autoSelectFamily` set to `true`. const connectOptions = this[kConnectOptions]; if (!options.isServer && connectOptions) { if (connectOptions.servername) { this.setServername(connectOptions.servername); } } if (options.handshakeTimeout > 0) this.setTimeout(options.handshakeTimeout, this._handleTimeout); if (socket instanceof net.Socket) { this._parent = socket; // To prevent assertion in afterConnect() and properly kick off readStart this.connecting = socket.connecting || !socket._handle; socket.once('connect', () => { this.connecting = false; this.emit('connect'); }); } // Assume `tls.connect()` if (wrap) { wrap.on('error', (err) => this._emitTLSError(err)); } else { assert(!socket); this.connecting = true; } }; TLSSocket.prototype.renegotiate = function(options, callback) { validateObject(options, 'options'); if (callback !== undefined) { validateFunction(callback, 'callback'); } debug('%s renegotiate()', this._tlsOptions.isServer ? 'server' : 'client', 'destroyed?', this.destroyed, ); if (this.destroyed) return; let requestCert = !!this._requestCert; let rejectUnauthorized = !!this._rejectUnauthorized; if (options.requestCert !== undefined) requestCert = !!options.requestCert; if (options.rejectUnauthorized !== undefined) rejectUnauthorized = !!options.rejectUnauthorized; if (requestCert !== this._requestCert || rejectUnauthorized !== this._rejectUnauthorized) { this._handle.setVerifyMode(requestCert, rejectUnauthorized); this._requestCert = requestCert; this._rejectUnauthorized = rejectUnauthorized; } // Ensure that we'll cycle through internal openssl's state this.write(''); try { |
| 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. |