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 | 94 94 94 94 94 94 94 94 94 94 94 94 94 94 94 280 280 280 280 280 280 278 280 280 280 2 94 266 266 94 12 94 5 5 5 5 5 12 7 94 16 7 9 9 9 9 9 9 6 9 94 16 14 2 2 2 2 2 2 2 94 2 2 2 2 1 2 94 12 12 12 12 94 16 16 16 16 16 16 16 94 1 1 1 1 1 94 1 1 1 1 1 1 1 94 2 94 532 532 532 532 532 532 532 532 532 532 532 532 2 530 1 529 532 532 532 532 532 532 532 532 94 94 94 94 1504 773 773 94 532 532 532 243 243 532 532 532 532 532 532 7 1 532 530 530 532 94 530 530 530 250 250 530 94 532 532 532 532 532 532 532 532 532 285 532 280 280 280 280 280 280 280 280 279 12 279 3 252 252 252 252 22 532 16 2 14 12 2 2 14 532 13 13 13 532 159 532 279 532 1 1 1 532 287 287 287 4 4 532 289 243 243 94 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 94 3 94 6 94 2 94 4 4 2 94 16 16 3 13 94 511 1 510 510 510 94 507 1 1 506 506 506 266 506 506 506 265 506 94 249 4 4 4 245 245 2 245 94 159 94 22 22 94 34 34 94 24 24 94 4 4 94 9 9 94 133 133 133 133 133 117 117 117 117 116 116 116 116 116 6 116 279 279 265 30 30 23 23 6 7 265 258 279 279 279 279 8 8 8 8 279 14 13 13 116 112 94 94 94 70 94 94 94 117 11 106 117 9 108 117 117 117 117 117 117 117 117 117 2 117 117 117 117 117 7 110 117 117 117 117 94 3 3 3 94 5 5 12 3 3 5 94 254 254 254 254 35 219 6 254 94 254 254 254 254 254 254 254 254 254 252 252 252 94 252 243 243 1 242 243 236 252 252 22 252 159 252 9 252 240 240 21 21 240 232 232 232 5 5 227 8 8 235 94 2 2 2 2 2 252 252 | (function () { 'use strict'; const assert = require('assert'); const crypto = require('crypto'); const net = require('net'); const tls = require('tls'); const util = require('util'); const listenerCount = require('events').listenerCount; const common = require('_tls_common'); const StreamWrap = require('_stream_wrap').StreamWrap; const Duplex = require('stream').Duplex; const debug = util.debuglog('tls'); const Timer = process.binding('timer_wrap').Timer; const tls_wrap = process.binding('tls_wrap'); const TCP = process.binding('tcp_wrap').TCP; const Pipe = process.binding('pipe_wrap').Pipe; function onhandshakestart() { debug('onhandshakestart'); var self = this; var ssl = self._handle; var now = Timer.now(); assert(now >= ssl.lastHandshakeTime); if ((now - ssl.lastHandshakeTime) >= tls.CLIENT_RENEG_WINDOW * 1000) { ssl.handshakes = 0; } var first = (ssl.lastHandshakeTime === 0); ssl.lastHandshakeTime = now; if (first) return; Iif (++ssl.handshakes > tls.CLIENT_RENEG_LIMIT) { // Defer the error event to the next tick. We're being called from OpenSSL's // state machine and OpenSSL is not re-entrant. We cannot allow the user's // callback to destroy the connection right now, it would crash and burn. setImmediate(function() { var err = new Error('TLS session renegotiation attack detected.'); self._emitTLSError(err); }); } } function onhandshakedone() { // for future use debug('onhandshakedone'); this._finishInit(); } function loadSession(self, hello, cb) { var once = false; function onSession(err, session) { Iif (once) return cb(new Error('TLS session callback was called 2 times')); once = true; Iif (err) return cb(err); // NOTE: That we have disabled OpenSSL's internal session storage in // `node_crypto.cc` and hence its safe to rely on getting servername only // from clienthello or this place. var ret = self._handle.loadSession(session); cb(null, ret); } if (hello.sessionId.length <= 0 || hello.tlsTicket || self.server && !self.server.emit('resumeSession', hello.sessionId, onSession)) { cb(null); } } function loadSNI(self, servername, cb) { if (!servername || !self._SNICallback) return cb(null); var once = false; self._SNICallback(servername, function(err, context) { Iif (once) return cb(new Error('TLS SNI callback was called 2 times')); once = true; Iif (err) return cb(err); // TODO(indutny): eventually disallow raw `SecureContext` if (context) self._handle.sni_context = context.context || context; cb(null, self._handle.sni_context); }); } function requestOCSP(self, hello, ctx, cb) { if (!hello.OCSPRequest || !self.server) return cb(null); Eif (!ctx) ctx = self.server._sharedCreds; Eif (ctx.context) ctx = ctx.context; Iif (listenerCount(self.server, 'OCSPRequest') === 0) { return cb(null); } else { self.server.emit('OCSPRequest', ctx.getCertificate(), ctx.getIssuer(), onOCSP); } var once = false; function onOCSP(err, response) { Iif (once) return cb(new Error('TLS OCSP callback was called 2 times')); once = true; Iif (err) return cb(err); if (response) self._handle.setOCSPResponse(response); cb(null); } } function onclienthello(hello) { var self = this; loadSession(self, hello, function(err, session) { Iif (err) return self.destroy(err); self._handle.endParser(); }); } function oncertcb(info) { var self = this; var servername = info.servername; loadSNI(self, servername, function(err, ctx) { Iif (err) return self.destroy(err); requestOCSP(self, info, ctx, function(err) { Iif (err) return self.destroy(err); self._handle.certCbDone(); }); }); } function onnewsession(key, session) { Iif (!this.server) return; var self = this; var once = false; this._newSessionPending = true; Iif (!this.server.emit('newSession', key, session, done)) done(); function done() { Iif (once) return; once = true; self._handle.newSessionDone(); self._newSessionPending = false; Eif (self._securePending) self._finishInit(); self._securePending = false; } } function onocspresponse(resp) { this.emit('OCSPResponse', resp); } /** * Provides a wrap of socket stream to do encrypted communication. */ function TLSSocket(socket, options) { this._tlsOptions = options; this._secureEstablished = false; this._securePending = false; this._newSessionPending = false; this._controlReleased = false; this._SNICallback = null; this.servername = null; this.npnProtocol = null; this.authorized = false; this.authorizationError = null; // Wrap plain JS Stream into StreamWrap var wrap; if (!(socket instanceof net.Socket) && socket instanceof Duplex) wrap = new StreamWrap(socket); else if ((socket instanceof net.Socket) && !socket._handle) wrap = new StreamWrap(socket); else wrap = socket; // Just a documented property to make secure sockets // distinguishable from regular ones. this.encrypted = true; net.Socket.call(this, { handle: this._wrapHandle(wrap && wrap._handle), allowHalfOpen: socket && socket.allowHalfOpen, readable: false, writable: false }); // Proxy for API compatibility this.ssl = this._handle; this.on('error', this._emitTLSError); this._init(socket, wrap); // Make sure to setup all required properties like: `_connecting` before // starting the flow of the data this.readable = true; this.writable = true; this.read(0); } util.inherits(TLSSocket, net.Socket); exports.TLSSocket = TLSSocket; var proxiedMethods = [ 'close', 'ref', 'unref', 'open', 'bind', 'listen', 'connect', 'bind6', 'connect6', 'getsockname', 'getpeername', 'setNoDelay', 'setKeepAlive', 'setSimultaneousAccepts', 'setBlocking', // PipeWrap 'setPendingInstances' ]; // Proxy HandleWrap, PipeWrap and TCPWrap methods proxiedMethods.forEach(function(name) { tls_wrap.TLSWrap.prototype[name] = function methodProxy() { Eif (this._parent[name]) return this._parent[name].apply(this._parent, arguments); }; }); TLSSocket.prototype._wrapHandle = function(handle) { var res; var options = this._tlsOptions; if (!handle) { handle = options.pipe ? new Pipe() : new TCP(); handle.owner = this; } // Wrap socket's handle var context = options.secureContext || options.credentials || tls.createSecureContext(); res = tls_wrap.wrap(handle, context.context, options.isServer); res._parent = handle; res._secureContext = context; res.reading = handle.reading; Object.defineProperty(handle, 'reading', { get: function readingGetter() { return res.reading; }, set: function readingSetter(value) { res.reading = value; } }); this.on('close', function() { this._destroySSL(); res = null; }); return res; }; TLSSocket.prototype._destroySSL = function _destroySSL() { Iif (!this.ssl) return; this.ssl.destroySSL(); if (this.ssl._secureContext.singleUse) { this.ssl._secureContext.context.close(); this.ssl._secureContext.context = null; } this.ssl = null; }; TLSSocket.prototype._init = function(socket, wrap) { var self = this; var options = this._tlsOptions; var ssl = this._handle; // lib/net.js expect this value to be non-zero if write hasn't been flushed // immediately // TODO(indutny): rewise this solution, it might be 1 before handshake and // represent real writeQueueSize during regular writes. ssl.writeQueueSize = 1; this.server = options.server || null; // For clients, we will always have either a given ca list or be using // default one var requestCert = !!options.requestCert || !options.isServer, rejectUnauthorized = !!options.rejectUnauthorized; this._requestCert = requestCert; this._rejectUnauthorized = rejectUnauthorized; if (requestCert || rejectUnauthorized) ssl.setVerifyMode(requestCert, rejectUnauthorized); if (options.isServer) { ssl.onhandshakestart = onhandshakestart.bind(this); ssl.onhandshakedone = onhandshakedone.bind(this); ssl.onclienthello = onclienthello.bind(this); ssl.oncertcb = oncertcb.bind(this); ssl.onnewsession = onnewsession.bind(this); ssl.lastHandshakeTime = 0; ssl.handshakes = 0; if (this.server) { if (listenerCount(this.server, 'resumeSession') > 0 || listenerCount(this.server, 'newSession') > 0) { ssl.enableSessionCallbacks(); } if (listenerCount(this.server, 'OCSPRequest') > 0) ssl.enableCertCb(); } } else { ssl.onhandshakestart = function() {}; ssl.onhandshakedone = this._finishInit.bind(this); ssl.onocspresponse = onocspresponse.bind(this); if (options.session) ssl.setSession(options.session); } ssl.onerror = function(err) { if (self._writableState.errorEmitted) return; // Destroy socket if error happened before handshake's finish if (!self._secureEstablished) { self.destroy(self._tlsError(err)); } else Iif (options.isServer && rejectUnauthorized && /peer did not return a certificate/.test(err.message)) { // Ignore server's authorization errors self.destroy(); } else { // Throw error self._emitTLSError(err); } self._writableState.errorEmitted = true; }; // If custom SNICallback was given, or if // there're SNI contexts to perform match against - // set `.onsniselect` callback. if (process.features.tls_sni && options.isServer && options.server && (options.SNICallback !== SNICallback || options.server._contexts.length)) { assert(typeof options.SNICallback === 'function'); this._SNICallback = options.SNICallback; ssl.enableCertCb(); } if (process.features.tls_npn && options.NPNProtocols) ssl.setNPNProtocols(options.NPNProtocols); if (options.handshakeTimeout > 0) this.setTimeout(options.handshakeTimeout, this._handleTimeout); // Socket already has some buffered data - emulate receiving it if (socket && socket._readableState && socket._readableState.length) { var buf; while ((buf = socket.read()) !== null) ssl.receive(buf); } 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', function() { self._connecting = false; self.emit('connect'); }); } // Assume `tls.connect()` if (wrap) { wrap.on('error', function(err) { self._emitTLSError(err); }); } else { assert(!socket); this._connecting = true; } }; TLSSocket.prototype.renegotiate = function(options, callback) { var requestCert = this._requestCert, rejectUnauthorized = this._rejectUnauthorized; Iif (this.destroyed) return; Eif (typeof options.requestCert !== 'undefined') requestCert = !!options.requestCert; Eif (typeof options.rejectUnauthorized !== 'undefined') rejectUnauthorized = !!options.rejectUnauthorized; Eif (requestCert !== this._requestCert || rejectUnauthorized !== this._rejectUnauthorized) { this._handle.setVerifyMode(requestCert, rejectUnauthorized); this._requestCert = requestCert; this._rejectUnauthorized = rejectUnauthorized; } Iif (!this._handle.renegotiate()) { if (callback) { process.nextTick(callback, new Error('Failed to renegotiate')); } return false; } // Ensure that we'll cycle through internal openssl's state this.write(''); Eif (callback) { this.once('secure', function() { callback(null); }); } return true; }; TLSSocket.prototype.setMaxSendFragment = function setMaxSendFragment(size) { return this._handle.setMaxSendFragment(size) == 1; }; TLSSocket.prototype.getTLSTicket = function getTLSTicket() { return this._handle.getTLSTicket(); }; TLSSocket.prototype._handleTimeout = function() { this._emitTLSError(new Error('TLS handshake timeout')); }; TLSSocket.prototype._emitTLSError = function(err) { var e = this._tlsError(err); if (e) this.emit('error', e); }; TLSSocket.prototype._tlsError = function(err) { this.emit('_tlsError', err); if (this._controlReleased) return err; return null; }; TLSSocket.prototype._releaseControl = function() { if (this._controlReleased) return false; this._controlReleased = true; this.removeListener('error', this._emitTLSError); return true; }; TLSSocket.prototype._finishInit = function() { // `newSession` callback wasn't called yet if (this._newSessionPending) { this._securePending = true; return; } Eif (process.features.tls_npn) { this.npnProtocol = this._handle.getNegotiatedProtocol(); } if (process.features.tls_sni && this._tlsOptions.isServer) { this.servername = this._handle.getServername(); } debug('secure established'); this._secureEstablished = true; if (this._tlsOptions.handshakeTimeout > 0) this.setTimeout(0, this._handleTimeout); this.emit('secure'); }; TLSSocket.prototype._start = function() { if (this._connecting) { this.once('connect', function() { this._start(); }); return; } debug('start'); if (this._tlsOptions.requestOCSP) this._handle.requestOCSP(); this._handle.start(); }; TLSSocket.prototype.setServername = function(name) { this._handle.setServername(name); }; TLSSocket.prototype.setSession = function(session) { Iif (typeof session === 'string') session = new Buffer(session, 'binary'); this._handle.setSession(session); }; TLSSocket.prototype.getPeerCertificate = function(detailed) { Eif (this._handle) { return common.translatePeerCertificate( this._handle.getPeerCertificate(detailed)); } return null; }; TLSSocket.prototype.getSession = function() { Eif (this._handle) { return this._handle.getSession(); } return null; }; TLSSocket.prototype.isSessionReused = function() { Eif (this._handle) { return this._handle.isSessionReused(); } return null; }; TLSSocket.prototype.getCipher = function(err) { Eif (this._handle) { return this._handle.getCurrentCipher(); } else { return null; } }; // TODO: support anonymous (nocert) and PSK // AUTHENTICATION MODES // // There are several levels of authentication that TLS/SSL supports. // Read more about this in "man SSL_set_verify". // // 1. The server sends a certificate to the client but does not request a // cert from the client. This is common for most HTTPS servers. The browser // can verify the identity of the server, but the server does not know who // the client is. Authenticating the client is usually done over HTTP using // login boxes and cookies and stuff. // // 2. The server sends a cert to the client and requests that the client // also send it a cert. The client knows who the server is and the server is // requesting the client also identify themselves. There are several // outcomes: // // A) verifyError returns null meaning the client's certificate is signed // by one of the server's CAs. The server know's the client idenity now // and the client is authorized. // // B) For some reason the client's certificate is not acceptable - // verifyError returns a string indicating the problem. The server can // either (i) reject the client or (ii) allow the client to connect as an // unauthorized connection. // // The mode is controlled by two boolean variables. // // requestCert // If true the server requests a certificate from client connections. For // the common HTTPS case, users will want this to be false, which is what // it defaults to. // // rejectUnauthorized // If true clients whose certificates are invalid for any reason will not // be allowed to make connections. If false, they will simply be marked as // unauthorized but secure communication will continue. By default this is // true. // // // // Options: // - requestCert. Send verify request. Default to false. // - rejectUnauthorized. Boolean, default to true. // - key. string. // - cert: string. // - ca: string or array of strings. // - sessionTimeout: integer. // // emit 'secureConnection' // function (tlsSocket) { } // // "UNABLE_TO_GET_ISSUER_CERT", "UNABLE_TO_GET_CRL", // "UNABLE_TO_DECRYPT_CERT_SIGNATURE", "UNABLE_TO_DECRYPT_CRL_SIGNATURE", // "UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY", "CERT_SIGNATURE_FAILURE", // "CRL_SIGNATURE_FAILURE", "CERT_NOT_YET_VALID" "CERT_HAS_EXPIRED", // "CRL_NOT_YET_VALID", "CRL_HAS_EXPIRED" "ERROR_IN_CERT_NOT_BEFORE_FIELD", // "ERROR_IN_CERT_NOT_AFTER_FIELD", "ERROR_IN_CRL_LAST_UPDATE_FIELD", // "ERROR_IN_CRL_NEXT_UPDATE_FIELD", "OUT_OF_MEM", // "DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN", // "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", // "CERT_CHAIN_TOO_LONG", "CERT_REVOKED" "INVALID_CA", // "PATH_LENGTH_EXCEEDED", "INVALID_PURPOSE" "CERT_UNTRUSTED", // "CERT_REJECTED" // function Server(/* [options], listener */) { var options, listener; Eif (arguments[0] !== null && typeof arguments[0] === 'object') { options = arguments[0]; listener = arguments[1]; } else if (typeof arguments[0] === 'function') { options = {}; listener = arguments[0]; } if (!(this instanceof Server)) return new Server(options, listener); this._contexts = []; var self = this; // Handle option defaults: this.setOptions(options); var sharedCreds = tls.createSecureContext({ pfx: self.pfx, key: self.key, passphrase: self.passphrase, cert: self.cert, ca: self.ca, ciphers: self.ciphers, ecdhCurve: self.ecdhCurve, dhparam: self.dhparam, secureProtocol: self.secureProtocol, secureOptions: self.secureOptions, honorCipherOrder: self.honorCipherOrder, crl: self.crl, sessionIdContext: self.sessionIdContext }); this._sharedCreds = sharedCreds; var timeout = options.handshakeTimeout || (120 * 1000); Iif (typeof timeout !== 'number') { throw new TypeError('handshakeTimeout must be a number'); } Iif (self.sessionTimeout) { sharedCreds.context.setSessionTimeout(self.sessionTimeout); } if (self.ticketKeys) { sharedCreds.context.setTicketKeys(self.ticketKeys); } // constructor call net.Server.call(this, function(raw_socket) { var socket = new TLSSocket(raw_socket, { secureContext: sharedCreds, isServer: true, server: self, requestCert: self.requestCert, rejectUnauthorized: self.rejectUnauthorized, handshakeTimeout: timeout, NPNProtocols: self.NPNProtocols, SNICallback: options.SNICallback || SNICallback }); socket.on('secure', function() { if (socket._requestCert) { var verifyError = socket._handle.verifyError(); if (verifyError) { socket.authorizationError = verifyError.code; if (socket._rejectUnauthorized) socket.destroy(); } else { socket.authorized = true; } } if (!socket.destroyed && socket._releaseControl()) self.emit('secureConnection', socket); }); var errorEmitted = false; socket.on('close', function(err) { // Closed because of error - no need to emit it twice Iif (err) return; // Emit ECONNRESET if (!socket._controlReleased && !errorEmitted) { errorEmitted = true; var connReset = new Error('socket hang up'); connReset.code = 'ECONNRESET'; self.emit('clientError', connReset, socket); } }); socket.on('_tlsError', function(err) { if (!socket._controlReleased && !errorEmitted) { errorEmitted = true; self.emit('clientError', err, socket); } }); }); if (listener) { this.on('secureConnection', listener); } } util.inherits(Server, net.Server); exports.Server = Server; exports.createServer = function(options, listener) { return new Server(options, listener); }; Server.prototype._getServerData = function() { return { ticketKeys: this._sharedCreds.context.getTicketKeys().toString('hex') }; }; Server.prototype._setServerData = function(data) { this._sharedCreds.context.setTicketKeys(new Buffer(data.ticketKeys, 'hex')); }; Server.prototype.setOptions = function(options) { if (typeof options.requestCert === 'boolean') { this.requestCert = options.requestCert; } else { this.requestCert = false; } if (typeof options.rejectUnauthorized === 'boolean') { this.rejectUnauthorized = options.rejectUnauthorized; } else { this.rejectUnauthorized = false; } if (options.pfx) this.pfx = options.pfx; if (options.key) this.key = options.key; if (options.passphrase) this.passphrase = options.passphrase; if (options.cert) this.cert = options.cert; if (options.ca) this.ca = options.ca; if (options.secureProtocol) this.secureProtocol = options.secureProtocol; if (options.crl) this.crl = options.crl; if (options.ciphers) this.ciphers = options.ciphers; if (options.ecdhCurve !== undefined) this.ecdhCurve = options.ecdhCurve; if (options.dhparam) this.dhparam = options.dhparam; Iif (options.sessionTimeout) this.sessionTimeout = options.sessionTimeout; if (options.ticketKeys) this.ticketKeys = options.ticketKeys; var secureOptions = options.secureOptions || 0; if (options.honorCipherOrder !== undefined) this.honorCipherOrder = !!options.honorCipherOrder; else this.honorCipherOrder = true; if (secureOptions) this.secureOptions = secureOptions; if (options.NPNProtocols) tls.convertNPNProtocols(options.NPNProtocols, this); Iif (options.sessionIdContext) { this.sessionIdContext = options.sessionIdContext; } else { this.sessionIdContext = crypto.createHash('md5') .update(process.argv.join(' ')) .digest('hex'); } }; // SNI Contexts High-Level API Server.prototype.addContext = function(servername, context) { Iif (!servername) { throw new Error('Servername is required parameter for Server.addContext'); } var re = new RegExp('^' + servername.replace(/([\.^$+?\-\\[\]{}])/g, '\\$1') .replace(/\*/g, '[^\.]*') + '$'); this._contexts.push([re, tls.createSecureContext(context).context]); }; function SNICallback(servername, callback) { var ctx; this.server._contexts.some(function(elem) { if (servername.match(elem[0]) !== null) { ctx = elem[1]; return true; } }); callback(null, ctx); } // Target API: // // var s = tls.connect({port: 8000, host: "google.com"}, function() { // if (!s.authorized) { // s.destroy(); // return; // } // // // s.socket; // // s.end("hello world\n"); // }); // // function normalizeConnectArgs(listArgs) { var args = net._normalizeConnectArgs(listArgs); var options = args[0]; var cb = args[1]; if (listArgs[1] !== null && typeof listArgs[1] === 'object') { options = util._extend(options, listArgs[1]); } else if (listArgs[2] !== null && typeof listArgs[2] === 'object') { options = util._extend(options, listArgs[2]); } return (cb) ? [options, cb] : [options]; } exports.connect = function(/* [port, host], options, cb */) { var args = normalizeConnectArgs(arguments); var options = args[0]; var cb = args[1]; var defaults = { rejectUnauthorized: '0' !== process.env.NODE_TLS_REJECT_UNAUTHORIZED, ciphers: tls.DEFAULT_CIPHERS, checkServerIdentity: tls.checkServerIdentity }; options = util._extend(defaults, options || {}); Eif (!options.keepAlive) options.singleUse = true; assert(typeof options.checkServerIdentity === 'function'); var hostname = options.servername || options.host || (options.socket && options.socket._host) || 'localhost', NPN = {}, context = tls.createSecureContext(options); tls.convertNPNProtocols(options.NPNProtocols, NPN); var socket = new TLSSocket(options.socket, { pipe: options.path && !options.port, secureContext: context, isServer: false, requestCert: true, rejectUnauthorized: options.rejectUnauthorized, session: options.session, NPNProtocols: NPN.NPNProtocols, requestOCSP: options.requestOCSP }); if (cb) socket.once('secureConnect', cb); if (!options.socket) { var connect_opt; if (options.path && !options.port) { connect_opt = { path: options.path }; } else { connect_opt = { port: options.port, host: options.host, localAddress: options.localAddress }; } socket.connect(connect_opt, function() { socket._start(); }); } socket._releaseControl(); if (options.session) socket.setSession(options.session); if (options.servername) socket.setServername(options.servername); if (options.socket) socket._start(); socket.on('secure', function() { var verifyError = socket._handle.verifyError(); // Verify that server's identity matches it's certificate's names if (!verifyError) { var cert = socket.getPeerCertificate(); verifyError = options.checkServerIdentity(hostname, cert); } if (verifyError) { socket.authorized = false; socket.authorizationError = verifyError.code || verifyError.message; if (options.rejectUnauthorized) { socket.destroy(verifyError); return; } else { socket.emit('secureConnect'); } } else { socket.authorized = true; socket.emit('secureConnect'); } // Uncork incoming data socket.removeListener('end', onHangUp); }); function onHangUp() { // NOTE: This logic is shared with _http_client.js Eif (!socket._hadError) { socket._hadError = true; var error = new Error('socket hang up'); error.code = 'ECONNRESET'; socket.destroy(error); } } socket.once('end', onHangUp); return socket; }; }()); |