{ "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 2048
\nAll 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
\nopenssl req -new -sha256 -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
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
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
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
If you have set secureOptions
to anything, we will not override your\noptions.\n\n
The ramifications of this behavior change:\n\n
\nSSLv3
\nonly will now not be able to appropriately negotiate a connection and will be\nrefused. In this case your server will emit a clientError
event. The error\nmessage will include 'wrong version number'
.error
event. The error message will include 'wrong version number'
.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 [tls.TLSSocket][] 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\n10 minutes.
Don'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
\nThe term "[Forward Secrecy]" or "Perfect Forward Secrecy" describes a feature of\nkey-agreement (i.e. key-exchange) methods. Practically it means that even if the\nprivate key of a (your) server is compromised, communication can only be\ndecrypted by eavesdroppers if they manage to obtain the key-pair specifically\ngenerated for each session.\n\n
\nThis is achieved by randomly generating a key pair for key-agreement on every\nhandshake (in contrary to the same key for all sessions). Methods implementing\nthis technique, thus offering Perfect Forward Secrecy, are called "ephemeral".\n\n
\nCurrently two methods are commonly used to achieve Perfect Forward Secrecy (note\nthe character "E" appended to the traditional abbreviations):\n\n
\nEphemeral methods may have some performance drawbacks, because key generation\nis expensive.\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
\nExample:\n\n
\nvar 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
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. (Could be an array of keys). (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. (Could be an array of certs). (Required)
ca
: An array of strings or Buffer
s of trusted certificates in PEM\nformat. If this is omitted several well known "root" CAs will be used,\nlike VeriSign. These 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:DHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL
.\nConsult the [OpenSSL cipher list format documentation] for details\non the format.
ECDHE-RSA-AES128-SHA256
, DHE-RSA-AES128-SHA256
and\nAES128-GCM-SHA256
are TLS v1.2 ciphers and used when Node.js is\nlinked against OpenSSL 1.0.1 or newer, such as the bundled version\nof OpenSSL. Note that it is still possible for a TLS v1.2 client\nto negotiate a weaker cipher unless honorCipherOrder
is enabled.
RC4
is used as a fallback for clients that speak on older version of\nthe TLS protocol. RC4
has in recent years come under suspicion and\nshould be considered compromised for anything that is truly sensitive.\nIt is speculated that state-level actors possess the ability to break it.
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.
ecdhCurve
: A string describing a named curve to use for ECDH key agreement\nor false to disable ECDH.
Defaults to prime256v1
. Consult [RFC 4492] for more details.
dhparam
: DH parameter file to use for DHE key agreement. Use\nopenssl dhparam
command to create it. If the file is invalid to\nload, it is silently discarded.
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.
Although, this option is disabled by default, it is recommended that you\nuse this option in conjunction with the ciphers
option to mitigate\nBEAST attacks.
Note: If SSLv2 is used, the server will send its list of preferences to the\nclient, and the client chooses the cipher. Support for SSLv2 is disabled\nunless node.js was configured with ./configure --with-sslv2
.
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
.
checkServerIdentity(servername, cert)
: Provide an override for checking\nserver's hostname against the certificate. Should return an error if verification\nfails. Return undefined
if passing.
NPNProtocols
: An array or Buffer
of possible NPN protocols. (Protocols\nshould be ordered by their priority).
SNICallback(servername, cb)
: A function that will be called if client\nsupports SNI TLS extension. Two argument will be passed to it: servername
,\nand cb
. SNICallback
should invoke cb(null, ctx)
, where ctx
is a\nSecureContext instance.\n(You can use tls.createSecureContext(...)
to get proper\nSecureContext). If SNICallback
wasn't provided - default callback with\nhigh-level API will be used (see below).
sessionTimeout
: An integer specifying the seconds after which TLS\nsession identifiers and TLS session tickets created by the server are\ntimed out. See [SSL_CTX_set_timeout] for more details.
ticketKeys
: A 48-byte Buffer
instance consisting of 16-byte prefix,\n16-byte hmac key, 16-byte AES key. You could use it to accept tls session\ntickets on multiple instances of tls server.
NOTE: Automatically shared between cluster
module workers.
sessionIdContext
: A string containing an 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.
secureProtocol
: The SSL method to use, e.g. SSLv3_method
to force\nSSL version 3. The possible values depend on your installation of\nOpenSSL and are defined in the constant [SSL_METHODS][].
secureOptions
: Set server options. For example, to disable the SSLv3\nprotocol set the SSL_OP_NO_SSLv3
flag. See [SSL_CTX_set_options]\nfor all available options.
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(socket) {\n console.log('server connected',\n socket.authorized ? 'authorized' : 'unauthorized');\n socket.write("welcome!\\n");\n socket.setEncoding('utf8');\n socket.pipe(socket);\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(socket) {\n console.log('server connected',\n socket.authorized ? 'authorized' : 'unauthorized');\n socket.write("welcome!\\n");\n socket.setEncoding('utf8');\n socket.pipe(socket);\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.
path
: Creates unix socket connection to path. If this option is\nspecified, host
and port
are ignored.
ciphers
: A string describing the ciphers to use or exclude.
Defaults to\nECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:AES128-GCM-SHA256:HIGH:!RC4:!MD5:!aNULL
.\nConsult the [OpenSSL cipher list format documentation] for details\non the format.
The full list of available ciphers can be obtained via [tls.getCiphers][].
\nECDHE-RSA-AES128-SHA256
, DHE-RSA-AES128-SHA256
and\nAES128-GCM-SHA256
are TLS v1.2 ciphers and used when Node.js is\nlinked against OpenSSL 1.0.1 or newer, such as the bundled version\nof OpenSSL.
pfx
: A string or Buffer
containing the private key, certificate and\nCA certs of the client in PFX or PKCS12 format.
key
: A string or Buffer
containing the private key of the client in\nPEM format. (Could be an array of keys).
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. (Could be an array of certs).
ca
: An array of strings or Buffer
s of trusted certificates in PEM\nformat. If this is omitted several well known "root" CAs will be used,\nlike VeriSign. These 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; err.code
contains the OpenSSL error code. Default: true
.
NPNProtocols
: An array of strings or Buffer
s containing supported NPN\nprotocols. Buffer
s 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.
secureProtocol
: The SSL method to use, e.g. SSLv3_method
to force\nSSL version 3. The possible values depend on your installation of\nOpenSSL and are defined in the constant [SSL_METHODS][].
session
: A Buffer
instance, containing TLS session.
The callback
parameter will be added as a listener for the\n['secureConnect'][] event.\n\n
tls.connect()
returns a [tls.TLSSocket][] 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 socket = tls.connect(8000, options, function() {\n console.log('client connected',\n socket.authorized ? 'authorized' : 'unauthorized');\n process.stdin.pipe(socket);\n process.stdin.resume();\n});\nsocket.setEncoding('utf8');\nsocket.on('data', function(data) {\n console.log(data);\n});\nsocket.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 socket = tls.connect(8000, options, function() {\n console.log('client connected',\n socket.authorized ? 'authorized' : 'unauthorized');\n process.stdin.pipe(socket);\n process.stdin.resume();\n});\nsocket.setEncoding('utf8');\nsocket.on('data', function(data) {\n console.log(data);\n});\nsocket.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.
path
: Creates unix socket connection to path. If this option is\nspecified, host
and port
are ignored.
ciphers
: A string describing the ciphers to use or exclude.
Defaults to\nECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:AES128-GCM-SHA256:HIGH:!RC4:!MD5:!aNULL
.\nConsult the [OpenSSL cipher list format documentation] for details\non the format.
The full list of available ciphers can be obtained via [tls.getCiphers][].
\nECDHE-RSA-AES128-SHA256
, DHE-RSA-AES128-SHA256
and\nAES128-GCM-SHA256
are TLS v1.2 ciphers and used when Node.js is\nlinked against OpenSSL 1.0.1 or newer, such as the bundled version\nof OpenSSL.
pfx
: A string or Buffer
containing the private key, certificate and\nCA certs of the client in PFX or PKCS12 format.
key
: A string or Buffer
containing the private key of the client in\nPEM format. (Could be an array of keys).
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. (Could be an array of certs).
ca
: An array of strings or Buffer
s of trusted certificates in PEM\nformat. If this is omitted several well known "root" CAs will be used,\nlike VeriSign. These 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; err.code
contains the OpenSSL error code. Default: true
.
NPNProtocols
: An array of strings or Buffer
s containing supported NPN\nprotocols. Buffer
s 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.
secureProtocol
: The SSL method to use, e.g. SSLv3_method
to force\nSSL version 3. The possible values depend on your installation of\nOpenSSL and are defined in the constant [SSL_METHODS][].
session
: A Buffer
instance, containing TLS session.
The callback
parameter will be added as a listener for the\n['secureConnect'][] event.\n\n
tls.connect()
returns a [tls.TLSSocket][] 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 socket = tls.connect(8000, options, function() {\n console.log('client connected',\n socket.authorized ? 'authorized' : 'unauthorized');\n process.stdin.pipe(socket);\n process.stdin.resume();\n});\nsocket.setEncoding('utf8');\nsocket.on('data', function(data) {\n console.log(data);\n});\nsocket.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 socket = tls.connect(8000, options, function() {\n console.log('client connected',\n socket.authorized ? 'authorized' : 'unauthorized');\n process.stdin.pipe(socket);\n process.stdin.resume();\n});\nsocket.setEncoding('utf8');\nsocket.on('data', function(data) {\n console.log(data);\n});\nsocket.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": "new tls.TLSSocket(socket, options)",
"type": "method",
"name": "TLSSocket",
"desc": "Construct a new TLSSocket object from existing TCP socket.\n\n
\nsocket
is an instance of [net.Socket][]\n\n
options
is an object that might contain following properties:\n\n
secureContext
: An optional TLS context object from\n tls.createSecureContext( ... )
isServer
: If true - TLS socket will be instantiated in server-mode
server
: An optional [net.Server][] instance
requestCert
: Optional, see [tls.createSecurePair][]
rejectUnauthorized
: Optional, see [tls.createSecurePair][]
NPNProtocols
: Optional, see [tls.createServer][]
SNICallback
: Optional, see [tls.createServer][]
session
: Optional, a Buffer
instance, containing TLS session
requestOCSP
: Optional, if true
- OCSP status request extension would\nbe added to client hello, and OCSPResponse
event will be emitted on socket\nbefore establishing secure communication
Creates a credentials object, with the optional details being a\ndictionary with keys:\n\n
\npfx
: A string or buffer holding the PFX or PKCS12 encoded private\nkey, certificate and CA certificateskey
: A string holding the PEM encoded private keypassphrase
: A string of passphrase for the private key or pfxcert
: A string holding the PEM encoded certificateca
: Either a string or list of strings of PEM encoded CA\ncertificates to trust.crl
: Either a string or list of strings of PEM encoded CRLs\n(Certificate Revocation List)ciphers
: A string describing the ciphers to use or exclude.\nConsult\nhttp://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT\nfor details on the format.honorCipherOrder
: When choosing a cipher, use the server's preferences\ninstead of the client preferences. For further details see tls
module\ndocumentation.If no 'ca' details are given, then node.js will use the default\npublicly trusted list of CAs as given in\n
\nhttp://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.\n\n\n
\n", "signatures": [ { "params": [ { "name": "details" } ] } ] }, { "textRaw": "tls.createSecurePair([context][, 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 secure context object from tls.createSecureContext( ... )
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
NOTE: cleartext
has the same APIs as [tls.TLSSocket][]\n\n
Wrapper for instance of [net.Socket][], replaces internal socket read/write\nroutines to perform transparent encryption/decryption of incoming/outgoing data.\n\n
\n" }, { "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
\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 (tlsSocket) {}
\n\n
This event is emitted after a new connection has been successfully\nhandshaked. The argument is an instance of [tls.TLSSocket][]. It has all the\ncommon stream methods and events.\n\n
\nsocket.authorized
is a boolean value which indicates if the\nclient has verified by one of the supplied certificate authorities for the\nserver. If socket.authorized
is false, then\nsocket.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.\nsocket.npnProtocol
is a string containing selected NPN protocol.\nsocket.servername
is a string containing servername requested with\nSNI.\n\n\n
function (exception, tlsSocket) { }
\n\n
When a client connection emits an 'error' event before secure connection is\nestablished - it will be forwarded here.\n\n
\ntlsSocket
is the [tls.TLSSocket][] that the error originated from.\n\n\n
function (sessionId, sessionData, callback) { }
\n\n
Emitted on creation of TLS session. May be used to store sessions in external\nstorage. callback
must be invoked eventually, otherwise no data will be\nsent or received from secure connection.\n\n
NOTE: adding this event listener will have an effect only on connections\nestablished after addition of event listener.\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
NOTE: adding this event listener will have an effect only on connections\nestablished after addition of event listener.\n\n\n
\n", "params": [] }, { "textRaw": "Event: 'OCSPRequest'", "type": "event", "name": "OCSPRequest", "desc": "function (certificate, issuer, callback) { }
\n\n
Emitted when the client sends a certificate status request. You could parse\nserver's current certificate to obtain OCSP url and certificate id, and after\nobtaining OCSP response invoke callback(null, resp)
, where resp
is a\nBuffer
instance. Both certificate
and issuer
are a Buffer
\nDER-representations of the primary and issuer's certificates. They could be used\nto obtain OCSP certificate id and OCSP endpoint url.\n\n
Alternatively, callback(null, null)
could be called, meaning that there is no\nOCSP response.\n\n
Calling callback(err)
will result in a socket.destroy(err)
call.\n\n
Typical flow:\n\n
\nOCSPRequest
to it (via status info\nextension in ClientHello.)OCSPRequest
event listener if presentcertificate
or issuer
and performs an\n[OCSP request] to the CAOCSPResponse
from CA and sends it back to client via\ncallback
argumentNOTE: issuer
could be null, if the certificate is self-signed or if the issuer\nis not in the root certificates list. (You could provide an issuer via ca
\noption.)\n\n
NOTE: adding this event listener will have an effect only on connections\nestablished after addition of event listener.\n\n
\nNOTE: you may want to use some npm module like [asn1.js] to parse the\ncertificates.\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
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, context)", "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). context
can contain\nkey
, cert
, ca
and/or any other properties from tls.createSecureContext
\noptions
argument.\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: CryptoStream", "type": "class", "name": "CryptoStream", "stability": 0, "stabilityText": "Deprecated. Use tls.TLSSocket instead.", "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.TLSSocket", "type": "class", "name": "tls.TLSSocket", "desc": "This is a wrapped version of [net.Socket][] that does transparent encryption\nof written data and all required TLS negotiation.\n\n
\nThis instance implements a duplex [Stream][] interfaces. It has all the\ncommon stream methods and events.\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 tlsSocket.authorized
\nto see if the server certificate was signed by one of the specified CAs.\nIf tlsSocket.authorized === false
then the error can be found in\ntlsSocket.authorizationError
. Also if NPN was used - you can check\ntlsSocket.npnProtocol
for negotiated protocol.\n\n
function (response) { }
\n\n
This event will be emitted if requestOCSP
option was set. response
is a\nbuffer object, containing server's OCSP response.\n\n
Traditionally, the response
is a signed object from the server's CA that\ncontains information about server's certificate revocation status.\n\n
Static boolean value, always true
. May be used to distinguish TLS sockets\nfrom regular ones.\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 tlsSocket.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 string representation of the remote IP family. 'IPv4'
or 'IPv6'
.\n\n
The numeric representation of the remote port. For example, 443
.\n\n
The string representation of the local IP address.\n\n
\n" }, { "textRaw": "tlsSocket.localPort", "name": "localPort", "desc": "The numeric representation of the local port.\n\n
\n" } ], "methods": [ { "textRaw": "tlsSocket.getPeerCertificate([ detailed ])", "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. If detailed
\nargument is true
- the full chain with issuer
property will be returned,\nif false
- only the top certificate without issuer
property.\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 issuerInfo:\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 { ... another certificate ... },\n raw: < RAW DER buffer >,\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 serialNumber: 'B9B0D332A1AA5635' }
\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": "tlsSocket.renegotiate(options, callback)", "type": "method", "name": "renegotiate", "desc": "Initiate TLS renegotiation process. The options
may contain the following\nfields: rejectUnauthorized
, requestCert
(See [tls.createServer][]\nfor details). callback(err)
will be executed with null
as err
,\nonce the renegotiation is successfully completed.\n\n
NOTE: Can be used to request peer's certificate after the secure connection\nhas been established.\n\n
\nANOTHER NOTE: When running as the server, socket will be destroyed\nwith an error after handshakeTimeout
timeout.\n\n
Set maximum TLS fragment size (default and maximum value is: 16384
, minimum\nis: 512
). Returns true
on success, false
otherwise.\n\n
Smaller fragment size decreases buffering latency on the client: large\nfragments are buffered by the TLS layer until the entire fragment is received\nand its integrity is verified; large fragments can span multiple roundtrips,\nand their processing can be delayed due to packet loss or reordering. However,\nsmaller fragments add extra TLS framing bytes and CPU overhead, which may\ndecrease overall server throughput.\n\n
\n", "signatures": [ { "params": [ { "name": "size" } ] } ] }, { "textRaw": "tlsSocket.getSession()", "type": "method", "name": "getSession", "desc": "Return ASN.1 encoded TLS session or undefined
if none was negotiated. Could\nbe used to speed up handshake establishment when reconnecting to the server.\n\n
NOTE: Works only with client TLS sockets. Useful only for debugging, for\nsession reuse provide session
option to tls.connect
.\n\n
Return TLS session ticket or undefined
if none was negotiated.\n\n
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