{ "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
The tls
module uses OpenSSL to provide Transport Layer Security and/or\nSecure Socket Layer: encrypted stream communication.\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
\nopenssl genrsa -out ryans-key.pem 1024
\nAll severs 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
\nopenssl req -new -key ryans-key.pem -out ryans-csr.pem
\nTo create a self-signed certificate with the CSR, do this:\n\n
\nopenssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
\nAlternatively 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
To create .pfx or .p12, do this:\n\n
\nopenssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \\\n -certfile ca-cert.pem -out agent5.pfx
\nin
: certificateinkey
: private keycertfile
: all CA certs concatenated in one file like\ncat ca1-cert.pem ca2-cert.pem > ca-cert.pem
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
\nTo 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
\ntls.CLIENT_RENEG_LIMIT
: renegotiation limit, default is 3.
tls.CLIENT_RENEG_WINDOW
: renegotiation window in seconds, default is
10 minutes.
\nDon't change the defaults unless you know what you are doing.\n\n
\nTo 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
NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS\nhandshake extensions allowing you:\n\n
\nCreates 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
pfx
: A string or Buffer
containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format. (Mutually exclusive with\nthe key
, cert
and ca
options.)
key
: A string or Buffer
containing the private key of the server in\nPEM format. (Required)
passphrase
: A string of passphrase for the private key or pfx.
cert
: A string or Buffer
containing the certificate key of the server in\nPEM format. (Required)
ca
: An array of strings or Buffer
s of trusted certificates. If this is\nomitted several well known "root" CAs will be used, like VeriSign.\nThese are used to authorize connections.
crl
: Either a string or list of strings of PEM encoded CRLs (Certificate\nRevocation List)
ciphers
: A string describing the ciphers to use or exclude.
To mitigate [BEAST attacks] it is recommended that you use this option in\nconjunction with the honorCipherOrder
option described below to\nprioritize the non-CBC cipher.
Defaults to\nECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH
.\nConsult the [OpenSSL cipher list format documentation] for details on the\nformat.
ECDHE-RSA-AES128-SHA256
and AES128-GCM-SHA256
are used when node.js is\nlinked against OpenSSL 1.0.1 or newer and the client speaks TLS 1.2, RC4 is\nused as a secure fallback.
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.
handshakeTimeout
: Abort the connection if the SSL/TLS handshake does not\nfinish in this many milliseconds. The default is 120 seconds.
A 'clientError'
is emitted on the tls.Server
object whenever a handshake\ntimes out.
honorCipherOrder
: When choosing a cipher, use the server's preferences\ninstead of the client preferences.
Note that if SSLv2 is used, the server will send its list of preferences\nto the client, and the client chooses the cipher.
\nAlthough, this option is disabled by default, it is recommended that you\nuse this option in conjunction with the ciphers
option to mitigate\nBEAST attacks.
requestCert
: If true
the server will request a certificate from\nclients that connect and attempt to verify that certificate. Default:\nfalse
.
rejectUnauthorized
: If true
the server will reject any connection\nwhich is not authorized with the list of supplied CAs. This option only\nhas an effect if requestCert
is true
. Default: false
.
NPNProtocols
: An array or Buffer
of possible NPN protocols. (Protocols\nshould be ordered by their priority).
SNICallback
: A function that will be called if client supports SNI TLS\nextension. Only one argument will be passed to it: servername
. And\nSNICallback
should return SecureContext instance.\n(You can use crypto.createCredentials(...).context
to get proper\nSecureContext). If SNICallback
wasn't provided - default callback with\nhigh-level API will be used (see below).
sessionIdContext
: A string containing a opaque identifier for session\nresumption. If requestCert
is true
, the default is MD5 hash value\ngenerated from command-line. Otherwise, the default is not provided.
Here is a simple example echo server:\n\n
\nvar 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});
\nOr\n\n
\nvar 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});
\nYou can test this server by connecting to it with openssl s_client
:\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
host
: Host the client should connect to
port
: Port the client should connect to
socket
: Establish secure connection on a given socket rather than\ncreating a new socket. If this option is specified, host
and port
\nare ignored.
pfx
: A string or Buffer
containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format.
key
: A string or Buffer
containing the private key of the client in\nPEM format.
passphrase
: A string of passphrase for the private key or pfx.
cert
: A string or Buffer
containing the certificate key of the client in\nPEM format.
ca
: An array of strings or Buffer
s of trusted certificates. If this is\nomitted several well known "root" CAs will be used, like VeriSign.\nThese are used to authorize connections.
rejectUnauthorized
: If true
, the server certificate is verified against\nthe list of supplied CAs. An 'error'
event is emitted if verification\nfails. Default: true
.
NPNProtocols
: An array of string or Buffer
containing supported NPN\nprotocols. Buffer
should have following format: 0x05hello0x05world
,\nwhere first byte is next protocol name's length. (Passing array should\nusually be much simpler: ['hello', 'world']
.)
servername
: Servername for SNI (Server Name Indication) TLS extension.
The callback
parameter will be added as a listener for the\n['secureConnect'][] event.\n\n
tls.connect()
returns a [CleartextStream][] object.\n\n
Here is an example of a client of echo server as described previously:\n\n
\nvar 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});
\nOr\n\n
\nvar 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
host
: Host the client should connect to
port
: Port the client should connect to
socket
: Establish secure connection on a given socket rather than\ncreating a new socket. If this option is specified, host
and port
\nare ignored.
pfx
: A string or Buffer
containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format.
key
: A string or Buffer
containing the private key of the client in\nPEM format.
passphrase
: A string of passphrase for the private key or pfx.
cert
: A string or Buffer
containing the certificate key of the client in\nPEM format.
ca
: An array of strings or Buffer
s of trusted certificates. If this is\nomitted several well known "root" CAs will be used, like VeriSign.\nThese are used to authorize connections.
rejectUnauthorized
: If true
, the server certificate is verified against\nthe list of supplied CAs. An 'error'
event is emitted if verification\nfails. Default: true
.
NPNProtocols
: An array of string or Buffer
containing supported NPN\nprotocols. Buffer
should have following format: 0x05hello0x05world
,\nwhere first byte is next protocol name's length. (Passing array should\nusually be much simpler: ['hello', 'world']
.)
servername
: Servername for SNI (Server Name Indication) TLS extension.
The callback
parameter will be added as a listener for the\n['secureConnect'][] event.\n\n
tls.connect()
returns a [CleartextStream][] object.\n\n
Here is an example of a client of echo server as described previously:\n\n
\nvar 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});
\nOr\n\n
\nvar 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
\ncredentials
: A credentials object from crypto.createCredentials( ... )
isServer
: A boolean indicating whether this tls connection should be\nopened as a server or a client.
requestCert
: A boolean indicating whether a server should request a\ncertificate from a connecting client. Only applies to server connections.
rejectUnauthorized
: A boolean indicating whether a server should\nautomatically reject clients with invalid certificates. Only applies to\nservers with requestCert
enabled.
tls.createSecurePair()
returns a SecurePair object with [cleartext][] and\nencrypted
stream properties.\n\n
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
\nSimilarly 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
function (cleartextStream) {}
\n\n
This event is emitted after a new connection has been successfully\nhandshaked. The argument is a instance of [CleartextStream][]. It has all the\ncommon stream methods and events.\n\n
\ncleartextStream.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
function (exception, securePair) { }
\n\n
When a client connection emits an 'error' event before secure connection is\nestablished - it will be forwarded here.\n\n
\nsecurePair
is the tls.SecurePair
that the error originated from.\n\n\n
function (sessionId, sessionData) { }
\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
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
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
This function is asynchronous. The last parameter callback
will be called\nwhen the server has been bound.\n\n
See net.Server
for more information.\n\n\n
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
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
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: 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
\nThis instance implements a duplex [Stream][] interfaces. It has all the\ncommon stream methods and events.\n\n
\nA ClearTextStream is the clear
member of a SecurePair object.\n\n
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
A boolean that is true
if the peer certificate was signed by one of the\nspecified CAs, otherwise false
\n\n
The reason why the peer's certificate has not been verified. This property\nbecomes available only when cleartextStream.authorized === false
.\n\n
The string representation of the remote IP address. For example,\n'74.125.127.100'
or '2001:4860:a005::68'
.\n\n
The numeric representation of the remote port. For example, 443
.\n\n
Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the field of the certificate.\n\n
\nExample:\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' }
\nIf the peer does not provide a certificate, it returns null
or an empty\nobject.\n\n
Returns an object representing the cipher name and the SSL/TLS\nprotocol version of the current connection.\n\n
\nExample:\n{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }\n\n
\nSee 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