{ "source": "doc/api/tls.markdown", "modules": [ { "textRaw": "TLS (SSL)", "name": "tls_(ssl)", "stability": 3, "stabilityText": "Stable", "desc": "

Use require('tls') to access this module.\n\n

\n

The tls module uses OpenSSL to provide Transport Layer Security and/or\nSecure Socket Layer: encrypted stream communication.\n\n

\n

TLS/SSL is a public/private key infrastructure. Each client and each\nserver must have a private key. A private key is created like this:\n\n

\n
openssl genrsa -out ryans-key.pem 2048
\n

All servers and some clients need to have a certificate. Certificates are public\nkeys signed by a Certificate Authority or self-signed. The first step to\ngetting a certificate is to create a "Certificate Signing Request" (CSR)\nfile. This is done with:\n\n

\n
openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem
\n

To create a self-signed certificate with the CSR, do this:\n\n

\n
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
\n

Alternatively you can send the CSR to a Certificate Authority for signing.\n\n

\n

(TODO: docs on creating a CA, for now interested users should just look at\ntest/fixtures/keys/Makefile in the Node source code)\n\n

\n

To create .pfx or .p12, do this:\n\n

\n
openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \\\n    -certfile ca-cert.pem -out agent5.pfx
\n\n", "modules": [ { "textRaw": "Protocol support", "name": "protocol_support", "desc": "

Node.js is compiled with SSLv2 and SSLv3 protocol support by default, but these\nprotocols are disabled. They are considered insecure and could be easily\ncompromised as was shown by [CVE-2014-3566][]. However, in some situations, it\nmay cause problems with legacy clients/servers (such as Internet Explorer 6).\nIf you wish to enable SSLv2 or SSLv3, run node with the --enable-ssl2 or\n--enable-ssl3 flag respectively. In future versions of Node.js SSLv2 and\nSSLv3 will not be compiled in by default.\n\n

\n

There is a way to force node into using SSLv3 or SSLv2 only mode by explicitly\nspecifying secureProtocol to 'SSLv3_method' or 'SSLv2_method'.\n\n

\n

The default protocol method Node.js uses is SSLv23_method which would be more\naccurately named AutoNegotiate_method. This method will try and negotiate\nfrom the highest level down to whatever the client supports. To provide a\nsecure default, Node.js (since v0.10.33) explicitly disables the use of SSLv3\nand SSLv2 by setting the secureOptions to be\nSSL_OP_NO_SSLv3|SSL_OP_NO_SSLv2 (again, unless you have passed\n--enable-ssl3, or --enable-ssl2, or SSLv3_method as secureProtocol).\n\n

\n

If you have set secureOptions to anything, we will not override your\noptions.\n\n

\n

The ramifications of this behavior change:\n\n

\n\n", "type": "module", "displayName": "Protocol support" } ], "miscs": [ { "textRaw": "Client-initiated renegotiation attack mitigation", "name": "Client-initiated renegotiation attack mitigation", "type": "misc", "desc": "

The TLS protocol lets the client renegotiate certain aspects of the TLS session.\nUnfortunately, session renegotiation requires a disproportional amount of\nserver-side resources, which makes it a potential vector for denial-of-service\nattacks.\n\n

\n

To mitigate this, renegotiations are limited to three times every 10 minutes. An\nerror is emitted on the [CleartextStream][] instance when the threshold is\nexceeded. The limits are configurable:\n\n

\n\n

Don't change the defaults unless you know what you are doing.\n\n

\n

To test your server, connect to it with openssl s_client -connect address:port\nand tap R<CR> (that's the letter R followed by a carriage return) a few\ntimes.\n\n\n

\n" }, { "textRaw": "NPN and SNI", "name": "NPN and SNI", "type": "misc", "desc": "

NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS\nhandshake extensions allowing you:\n\n

\n\n" } ], "methods": [ { "textRaw": "tls.getCiphers()", "type": "method", "name": "getCiphers", "desc": "

Returns an array with the names of the supported SSL ciphers.\n\n

\n

Example:\n\n

\n
var ciphers = tls.getCiphers();\nconsole.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tls.createServer(options, [secureConnectionListener])", "type": "method", "name": "createServer", "desc": "

Creates a new [tls.Server][]. The connectionListener argument is\nautomatically set as a listener for the [secureConnection][] event. The\noptions object has these possibilities:\n\n

\n\n
`AES128-GCM-SHA256` is used when node.js is linked against OpenSSL 1.0.1\nor newer and the client speaks TLS 1.2, RC4 is used as a secure fallback.\n\n**NOTE**: Previous revisions of this section suggested `AES256-SHA` as an\nacceptable cipher. Unfortunately, `AES256-SHA` is a CBC cipher and therefore\nsusceptible to BEAST attacks. Do *not* use it.
\n\n

Here is a simple example echo server:\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  key: fs.readFileSync('server-key.pem'),\n  cert: fs.readFileSync('server-cert.pem'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\n  // This is necessary only if the client uses the self-signed certificate.\n  ca: [ fs.readFileSync('client-cert.pem') ]\n};\n\nvar server = tls.createServer(options, function(cleartextStream) {\n  console.log('server connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  cleartextStream.write("welcome!\\n");\n  cleartextStream.setEncoding('utf8');\n  cleartextStream.pipe(cleartextStream);\n});\nserver.listen(8000, function() {\n  console.log('server bound');\n});
\n

Or\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('server.pfx'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\n};\n\nvar server = tls.createServer(options, function(cleartextStream) {\n  console.log('server connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  cleartextStream.write("welcome!\\n");\n  cleartextStream.setEncoding('utf8');\n  cleartextStream.pipe(cleartextStream);\n});\nserver.listen(8000, function() {\n  console.log('server bound');\n});
\n

You can test this server by connecting to it with openssl s_client:\n\n\n

\n
openssl s_client -connect 127.0.0.1:8000
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "secureConnectionListener", "optional": true } ] } ] }, { "textRaw": "tls.connect(options, [callback])", "type": "method", "name": "connect", "desc": "

Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

\n\n

The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

\n

tls.connect() returns a [CleartextStream][] object.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n

Or\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "tls.connect(port, [host], [options], [callback])", "type": "method", "name": "connect", "desc": "

Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

\n\n

The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

\n

tls.connect() returns a [CleartextStream][] object.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n

Or\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])", "type": "method", "name": "createSecurePair", "desc": "

Creates a new secure pair object with two streams, one of which reads/writes\nencrypted data, and one reads/writes cleartext data.\nGenerally the encrypted one is piped to/from an incoming encrypted data stream,\nand the cleartext one is used as a replacement for the initial encrypted stream.\n\n

\n\n

tls.createSecurePair() returns a SecurePair object with [cleartext][] and\nencrypted stream properties.\n\n

\n", "signatures": [ { "params": [ { "name": "credentials", "optional": true }, { "name": "isServer", "optional": true }, { "name": "requestCert", "optional": true }, { "name": "rejectUnauthorized", "optional": true } ] } ] } ], "properties": [ { "textRaw": "tls.SLAB_BUFFER_SIZE", "name": "SLAB_BUFFER_SIZE", "desc": "

Size of slab buffer used by all tls servers and clients.\nDefault: 10 * 1024 * 1024.\n\n\n

\n

Don't change the defaults unless you know what you are doing.\n\n\n

\n" } ], "classes": [ { "textRaw": "Class: SecurePair", "type": "class", "name": "SecurePair", "desc": "

Returned by tls.createSecurePair.\n\n

\n", "events": [ { "textRaw": "Event: 'secure'", "type": "event", "name": "secure", "desc": "

The event is emitted from the SecurePair once the pair has successfully\nestablished a secure connection.\n\n

\n

Similarly to the checking for the server 'secureConnection' event,\npair.cleartext.authorized should be checked to confirm whether the certificate\nused properly authorized.\n\n

\n", "params": [] } ] }, { "textRaw": "Class: tls.Server", "type": "class", "name": "tls.Server", "desc": "

This class is a subclass of net.Server and has the same methods on it.\nInstead of accepting just raw TCP connections, this accepts encrypted\nconnections using TLS or SSL.\n\n

\n", "events": [ { "textRaw": "Event: 'secureConnection'", "type": "event", "name": "secureConnection", "desc": "

function (cleartextStream) {}\n\n

\n

This event is emitted after a new connection has been successfully\nhandshaked. The argument is an instance of [CleartextStream][]. It has all the\ncommon stream methods and events.\n\n

\n

cleartextStream.authorized is a boolean value which indicates if the\nclient has verified by one of the supplied certificate authorities for the\nserver. If cleartextStream.authorized is false, then\ncleartextStream.authorizationError is set to describe how authorization\nfailed. Implied but worth mentioning: depending on the settings of the TLS\nserver, you unauthorized connections may be accepted.\ncleartextStream.npnProtocol is a string containing selected NPN protocol.\ncleartextStream.servername is a string containing servername requested with\nSNI.\n\n\n

\n", "params": [] }, { "textRaw": "Event: 'clientError'", "type": "event", "name": "clientError", "desc": "

function (exception, securePair) { }\n\n

\n

When a client connection emits an 'error' event before secure connection is\nestablished - it will be forwarded here.\n\n

\n

securePair is the tls.SecurePair that the error originated from.\n\n\n

\n", "params": [] }, { "textRaw": "Event: 'newSession'", "type": "event", "name": "newSession", "desc": "

function (sessionId, sessionData) { }\n\n

\n

Emitted on creation of TLS session. May be used to store sessions in external\nstorage.\n\n\n

\n", "params": [] }, { "textRaw": "Event: 'resumeSession'", "type": "event", "name": "resumeSession", "desc": "

function (sessionId, callback) { }\n\n

\n

Emitted when client wants to resume previous TLS session. Event listener may\nperform lookup in external storage using given sessionId, and invoke\ncallback(null, sessionData) once finished. If session can't be resumed\n(i.e. doesn't exist in storage) one may call callback(null, null). Calling\ncallback(err) will terminate incoming connection and destroy socket.\n\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "server.listen(port, [host], [callback])", "type": "method", "name": "listen", "desc": "

Begin accepting connections on the specified port and host. If the\nhost is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY).\n\n

\n

This function is asynchronous. The last parameter callback will be called\nwhen the server has been bound.\n\n

\n

See net.Server for more information.\n\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.close()", "type": "method", "name": "close", "desc": "

Stops the server from accepting new connections. This function is\nasynchronous, the server is finally closed when the server emits a 'close'\nevent.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.address()", "type": "method", "name": "address", "desc": "

Returns the bound address, the address family name and port of the\nserver as reported by the operating system. See [net.Server.address()][] for\nmore information.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.addContext(hostname, credentials)", "type": "method", "name": "addContext", "desc": "

Add secure context that will be used if client request's SNI hostname is\nmatching passed hostname (wildcards can be used). credentials can contain\nkey, cert and ca.\n\n

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "credentials" } ] } ] } ], "properties": [ { "textRaw": "server.maxConnections", "name": "maxConnections", "desc": "

Set this property to reject connections when the server's connection count\ngets high.\n\n

\n" }, { "textRaw": "server.connections", "name": "connections", "desc": "

The number of concurrent connections on the server.\n\n\n

\n" } ] }, { "textRaw": "Class: CryptoStream", "type": "class", "name": "CryptoStream", "desc": "

This is an encrypted stream.\n\n

\n", "properties": [ { "textRaw": "cryptoStream.bytesWritten", "name": "bytesWritten", "desc": "

A proxy to the underlying socket's bytesWritten accessor, this will return\nthe total bytes written to the socket, including the TLS overhead.\n\n

\n" } ] }, { "textRaw": "Class: tls.CleartextStream", "type": "class", "name": "tls.CleartextStream", "desc": "

This is a stream on top of the Encrypted stream that makes it possible to\nread/write an encrypted data as a cleartext data.\n\n

\n

This instance implements a duplex [Stream][] interfaces. It has all the\ncommon stream methods and events.\n\n

\n

A ClearTextStream is the clear member of a SecurePair object.\n\n

\n", "events": [ { "textRaw": "Event: 'secureConnect'", "type": "event", "name": "secureConnect", "desc": "

This event is emitted after a new connection has been successfully handshaked. \nThe listener will be called no matter if the server's certificate was\nauthorized or not. It is up to the user to test cleartextStream.authorized\nto see if the server certificate was signed by one of the specified CAs.\nIf cleartextStream.authorized === false then the error can be found in\ncleartextStream.authorizationError. Also if NPN was used - you can check\ncleartextStream.npnProtocol for negotiated protocol.\n\n

\n", "params": [] } ], "properties": [ { "textRaw": "cleartextStream.authorized", "name": "authorized", "desc": "

A boolean that is true if the peer certificate was signed by one of the\nspecified CAs, otherwise false\n\n

\n" }, { "textRaw": "cleartextStream.authorizationError", "name": "authorizationError", "desc": "

The reason why the peer's certificate has not been verified. This property\nbecomes available only when cleartextStream.authorized === false.\n\n

\n" }, { "textRaw": "cleartextStream.remoteAddress", "name": "remoteAddress", "desc": "

The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

\n" }, { "textRaw": "cleartextStream.remotePort", "name": "remotePort", "desc": "

The numeric representation of the remote port. For example, 443.\n\n

\n" } ], "methods": [ { "textRaw": "cleartextStream.getPeerCertificate()", "type": "method", "name": "getPeerCertificate", "desc": "

Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the field of the certificate.\n\n

\n

Example:\n\n

\n
{ subject: \n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  issuer: \n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  valid_from: 'Nov 11 09:52:22 2009 GMT',\n  valid_to: 'Nov  6 09:52:22 2029 GMT',\n  fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' }
\n

If the peer does not provide a certificate, it returns null or an empty\nobject.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "cleartextStream.getCipher()", "type": "method", "name": "getCipher", "desc": "

Returns an object representing the cipher name and the SSL/TLS\nprotocol version of the current connection.\n\n

\n

Example:\n{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }\n\n

\n

See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in\nhttp://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more\ninformation.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "cleartextStream.address()", "type": "method", "name": "address", "desc": "

Returns the bound address, the address family name and port of the\nunderlying socket as reported by the operating system. Returns an\nobject with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

\n", "signatures": [ { "params": [] } ] } ] } ], "type": "module", "displayName": "TLS (SSL)" } ] }