{ "source": "doc/api/tls.markdown", "modules": [ { "textRaw": "TLS (SSL)", "name": "tls_(ssl)", "stability": 2, "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
\nFor Perfect Forward Secrecy, it is required to generate Diffie-Hellman\nparameters:\n\n
\nopenssl dhparam -outform PEM -out dhparam.pem 2048
\nTo create a .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
ALPN (Application-Layer Protocol Negotiation Extension), NPN (Next\nProtocol Negotiation) and, SNI (Server Name Indication) are TLS\nhandshake extensions:\n\n
\nThe TLS protocol lets the client renegotiate certain aspects of the TLS session.\nUnfortunately, session renegotiation requires a disproportionate amount of\nserver-side resources, which makes it a potential vector for denial-of-service\nattacks.\n\n
\nTo mitigate this, renegotiation is limited to three times every 10 minutes. An\nerror is emitted on the [tls.TLSSocket
][] instance when the threshold is\nexceeded. These limits are configurable:\n\n
tls.CLIENT_RENEG_LIMIT
: renegotiation limit, default is 3.
tls.CLIENT_RENEG_WINDOW
: renegotiation window in seconds, default is\n10 minutes.
Do not change the defaults without a full understanding of the implications.\n\n
\nTo test the server, connect to it with openssl s_client -connect address:port
\nand tap R<CR>
(i.e., the letter R
followed by a carriage return) a few\ntimes.\n\n
The term "[Forward Secrecy]" or "Perfect Forward Secrecy" describes a feature of\nkey-agreement (i.e., key-exchange) methods. Practically it means that even if\nthe private key of a 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 contrast to using the same key for all sessions). Methods\nimplementing this technique, thus offering Perfect Forward Secrecy, are\ncalled "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" } ], "modules": [ { "textRaw": "Modifying the Default TLS Cipher suite", "name": "modifying_the_default_tls_cipher_suite", "desc": "Node.js is built with a default suite of enabled and disabled TLS ciphers.\nCurrently, the default cipher suite is:\n\n
\nECDHE-RSA-AES128-GCM-SHA256:\nECDHE-ECDSA-AES128-GCM-SHA256:\nECDHE-RSA-AES256-GCM-SHA384:\nECDHE-ECDSA-AES256-GCM-SHA384:\nDHE-RSA-AES128-GCM-SHA256:\nECDHE-RSA-AES128-SHA256:\nDHE-RSA-AES128-SHA256:\nECDHE-RSA-AES256-SHA384:\nDHE-RSA-AES256-SHA384:\nECDHE-RSA-AES256-SHA256:\nDHE-RSA-AES256-SHA256:\nHIGH:\n!aNULL:\n!eNULL:\n!EXPORT:\n!DES:\n!RC4:\n!MD5:\n!PSK:\n!SRP:\n!CAMELLIA
\nThis default can be overriden entirely using the --tls-cipher-list
command\nline switch. For instance, the following makes\nECDHE-RSA-AES128-GCM-SHA256:!RC4
the default TLS cipher suite:\n\n
node --tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4"
\nNote that the default cipher suite included within Node.js has been carefully\nselected to reflect current security best practices and risk mitigation.\nChanging the default cipher suite can have a significant impact on the security\nof an application. The --tls-cipher-list
switch should by used only if\nabsolutely necessary.\n\n
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: SecurePair", "type": "class", "name": "SecurePair", "desc": "Returned by tls.createSecurePair.\n\n
\n", "events": [ { "textRaw": "Event: 'secure'", "type": "event", "name": "secure", "desc": "This event is emitted from the SecurePair once the pair has successfully\nestablished a secure connection.\n\n
\nAs with checking for the server secureConnection
\nevent, pair.cleartext.authorized
should be inspected to confirm whether the\ncertificate used is properly authorized.\n\n
This class is a subclass of net.Server
and has the same methods on it.\nInstead of accepting only raw TCP connections, this accepts encrypted\nconnections using TLS or SSL.\n\n
function (exception, tlsSocket) { }
\n\n
When a client connection emits an 'error'
event before a secure connection is\nestablished it will be forwarded here.\n\n
tlsSocket
is the [tls.TLSSocket
][] that the error originated from.\n\n
function (sessionId, sessionData, callback) { }
\n\n
Emitted on creation of a 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 the secure connection.\n\n
NOTE: adding this event listener will only have an effect on connections\nestablished after the addition of the event listener.\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. The server's\ncurrent certificate can be parsed to obtain the OCSP URL and certificate ID;\nafter obtaining an OCSP response callback(null, resp)
is then invoked, where\nresp
is a Buffer
instance. Both certificate
and issuer
are Buffer
\nDER-representations of the primary and issuer's certificates. They can be used\nto obtain the OCSP certificate ID and OCSP endpoint URL.\n\n
Alternatively, callback(null, null)
may be called, meaning that there was no\nOCSP response.\n\n
Calling callback(err)
will result in a socket.destroy(err)
call.\n\n
Typical flow:\n\n
\n'OCSPRequest'
to it (via status\ninfo extension in ClientHello).'OCSPRequest'
event listener\nif present.certificate
or issuer
and\nperforms an [OCSP request] to the CA.OCSPResponse
from the CA and sends it back to the client\nvia the callback
argumentNOTE: issuer
could be null
if the certificate is self-signed or if the\nissuer is not in the root certificates list. (An issuer may be provided via the\nca
option.)\n\n
NOTE: adding this event listener will only have an effect on connections\nestablished after the addition of the event listener.\n\n
\nNOTE: An npm module like [asn1.js] may be used to parse the certificates.\n\n
\n", "params": [] }, { "textRaw": "Event: 'resumeSession'", "type": "event", "name": "resumeSession", "desc": "function (sessionId, callback) { }
\n\n
Emitted when the client wants to resume the previous TLS session. The event\nlistener may perform a lookup in external storage using the given sessionId
\nand invoke callback(null, sessionData)
once finished. If the session can't be\nresumed (i.e., doesn't exist in storage) one may call callback(null, null)
.\nCalling callback(err)
will terminate incoming connection and destroy the\nsocket.\n\n
NOTE: adding this event listener will only have an effect on connections\nestablished after the addition of the event listener.\n\n
\nHere's an example for using TLS session resumption:\n\n
\nvar tlsSessionStore = {};\nserver.on('newSession', (id, data, cb) => {\n tlsSessionStore[id.toString('hex')] = data;\n cb();\n});\nserver.on('resumeSession', (id, cb) => {\n cb(null, tlsSessionStore[id.toString('hex')] || null);\n});
\n",
"params": []
},
{
"textRaw": "Event: 'secureConnection'",
"type": "event",
"name": "secureConnection",
"desc": "function (tlsSocket) {}
\n\n
This event is emitted after the handshaking process for a new connection has\nsuccessfully completed. The argument is an instance of [tls.TLSSocket
][] and\nhas all the common stream methods and events.\n\n
socket.authorized
is a boolean value which indicates if the\nclient has been verified by one of the supplied certificate authorities for the\nserver. If socket.authorized
is false, then socket.authorizationError
is\nset to describe how authorization failed. Implied but worth mentioning:\ndepending on the settings of the TLS server, unauthorized connections may\nbe accepted.\n\n
socket.npnProtocol
is a string containing the selected NPN protocol\nand socket.alpnProtocol
is a string containing the selected ALPN\nprotocol. When both NPN and ALPN extensions are received, ALPN takes\nprecedence over NPN and the next protocol is selected by ALPN. When\nALPN has no selected protocol, this returns false.\n\n
socket.servername
is a string containing the server name requested with\nSNI.\n\n
Add secure context that will be used if the client request's SNI hostname\nmatches the supplied hostname
(wildcards can be used). context
can contain\nkey
, cert
, ca
or any other properties from\n[tls.createSecureContext()
][] options
argument.\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
Stops the server from accepting new connections. This function is\nasynchronous, the server is finally closed when the server emits a 'close'
\nevent. Optionally, you can pass a callback to listen for the 'close'
event.\n\n
Returns a Buffer
instance holding the keys currently used for\nencryption/decryption of the [TLS Session Tickets][]\n\n
Begin accepting connections on the specified port
and hostname
. If the\nhostname
is omitted, the server will accept connections on any IPv6 address\n(::
) when IPv6 is available, or any IPv4 address (0.0.0.0
) otherwise. A\nport value of zero will assign a random port.\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
Updates the keys for encryption/decryption of the [TLS Session Tickets][].\n\n
\nNOTE: the buffer should be 48 bytes long. See ticketKeys
option in\ntls.createServer for\nmore information on how it is used.\n\n
NOTE: the change is effective only for future server connections. Existing\nor currently pending server connections will use the previous keys.\n\n
\n", "signatures": [ { "params": [ { "name": "keys" } ] } ] } ], "properties": [ { "textRaw": "server.connections", "name": "connections", "desc": "The number of concurrent connections on the server.\n\n
\n" }, { "textRaw": "server.maxConnections", "name": "maxConnections", "desc": "Set this property to reject connections when the server's connection count\nexceeds the specified threshold.\n\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
This instance implements the duplex [Stream][] interface. It has all the\ncommon stream methods and events.\n\n
\nMethods that return TLS connection metadata (e.g.\n[tls.TLSSocket.getPeerCertificate()
][] will only return data while the\nconnection is open.\n\n
Construct a new TLSSocket object from an existing TCP socket.\n\n
\nsocket
is an instance of [net.Socket
][]\n\n
options
is an optional object that might contain following properties:\n\n
secureContext
: An optional TLS context object from\n [tls.createSecureContext()
][]
isServer
: If true
the TLS socket will be instantiated in server-mode.\nDefault: false
server
: An optional [net.Server
][] instance
requestCert
: Optional, see [tls.createSecurePair()
][]
rejectUnauthorized
: Optional, see [tls.createSecurePair()
][]
NPNProtocols
: Optional, see [tls.createServer()
][]
ALPNProtocols
: Optional, see [tls.createServer()
][]
SNICallback
: Optional, see [tls.createServer()
][]
session
: Optional, a Buffer
instance, containing a TLS session
requestOCSP
: Optional, if true
the OCSP status request extension will\nbe added to the client hello and an 'OCSPResponse'
event will be emitted\non the socket before establishing a secure communication
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
Returns an object representing the cipher name and the SSL/TLS protocol version\nthat first defined the cipher.\n\n
\nExample:\n{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }
\n\n
See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in\nhttps://www.openssl.org/docs/manmaster/ssl/SSL_CIPHER_get_name.html for more\ninformation.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getEphemeralKeyInfo()", "type": "method", "name": "getEphemeralKeyInfo", "desc": "Returns an object representing the type, name, and size of parameter of\nan ephemeral key exchange in [Perfect Forward Secrecy][] on a client\nconnection. It returns an empty object when the key exchange is not\nephemeral. As this is only supported on a client socket, it returns null
\nif called on a server socket. The supported types are 'DH' and 'ECDH'. The\nname
property is only available in 'ECDH'.\n\n
Example:\n\n
\n{ type: 'ECDH', name: 'prime256v1', size: 256 }
\n",
"signatures": [
{
"params": []
}
]
},
{
"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 fields of the certificate. If the\ndetailed
argument is true
the full chain with the issuer
property will be\nreturned, if false
only the top certificate without the 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 a string containing the negotiated SSL/TLS protocol version of the\ncurrent connection. 'unknown'
will be returned for connected sockets that have\nnot completed the handshaking process. null
will be returned for server\nsockets or disconnected client sockets.\n\n
Examples:\n
\n'SSLv3'\n'TLSv1'\n'TLSv1.1'\n'TLSv1.2'\n'unknown'
\nSee https://www.openssl.org/docs/manmaster/ssl/SSL_get_version.html for more\ninformation.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getSession()", "type": "method", "name": "getSession", "desc": "Returns the ASN.1 encoded TLS session or undefined
if none was negotiated.\nCould be used to speed up handshake establishment when reconnecting to the\nserver.\n\n
NOTE: Works only with client TLS sockets. Useful only for debugging, for\nsession reuse provide session
option to [tls.connect()
][].\n\n
Returns the TLS session ticket or undefined
if none was negotiated.\n\n
Initiate TLS renegotiation process. The options
object may contain the\nfollowing fields: rejectUnauthorized
, requestCert
. (See [tls.createServer\n()
][] for 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 sizes decrease the buffering latency on the client: larger\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
\n", "signatures": [ { "params": [ { "name": "size" } ] } ] } ], "events": [ { "textRaw": "Event: 'OCSPResponse'", "type": "event", "name": "OCSPResponse", "desc": "function (response) { }
\n\n
This event will be emitted if the requestOCSP
option was set. response
is a\nBuffer
containing the 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
This event is emitted after the handshaking process for a new connection has\nsuccessfully completed. The listener will be called regardless of whether or not\nthe server's certificate has been authorized. It is the user's responsibility to\ntest tlsSocket.authorized
to see if the server certificate was signed by one\nof the specified CAs. If tlsSocket.authorized === false
then the error can be\nfound in tlsSocket.authorizationError
. Also, if either ALPN or NPN was used\ntlsSocket.alpnProtocol
or tlsSocket.npnProtocol
can be checked for the\nnegotiated 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 tlsSocket.authorized === false
.\n\n
Static boolean value, always true
. May be used to distinguish TLS sockets\nfrom regular ones.\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" }, { "textRaw": "tlsSocket.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
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
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.
pfx
: A string or Buffer
containing the private key, certificate, and\nCA certs of the client in PFX or PKCS12 format.
key
: A string, Buffer
, array of strings, or array of Buffer
s\ncontaining the private key of the client in PEM format.
passphrase
: A string containing the passphrase for the private key or pfx.
cert
: A string, Buffer
, array of strings, or array of Buffer
s\ncontaining the certificate key of the client in PEM format.
ca
: A string, Buffer
, array of strings, or array of Buffer
s of trusted\ncertificates in PEM format. If this is omitted several well known "root"\nCAs (like VeriSign) will be used. These are used to authorize connections.
ciphers
: A string describing the ciphers to use or exclude, separated by\n:
. Uses the same default cipher suite as [tls.createServer()
][].
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 the following format:\n0x05hello0x05world
, where the first byte is the next protocol name's\nlength. (Passing an array is usually be much simpler: ['hello', 'world']
.)
ALPNProtocols
: An array of strings or Buffer
s containing the\nsupported ALPN protocols. Buffer
s should have following format:\n0x05hello0x05world
, where the first byte is the next protocol\nname's length. (Passing an array is usually be much simpler:\n['hello', 'world']
.)
servername
: Server name for the SNI (Server Name Indication) TLS\nextension.
checkServerIdentity(servername, cert)
: Provide an override for checking\nthe server's hostname against the certificate. Should return an error if\nverification fails. Returns undefined
if passing.
secureProtocol
: The SSL method to use, e.g., SSLv3_method
to force\nSSL version 3. The possible values depend on the version of OpenSSL\ninstalled in the environment and are defined in the constant\n[SSL_METHODS][].
secureContext
: An optional TLS context object from\ntls.createSecureContext( ... )
. It can be used for caching client\ncertificates, keys, and CA certificates.
session
: A Buffer
instance, containing TLS session.
minDHSize
: Minimum size of the DH parameter in bits to accept a TLS\nconnection. When a server offers a DH parameter with a size less\nthan this, the TLS connection is destroyed and an error is thrown. Default:\n1024.
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
\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst 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, () => {\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', (data) => {\n console.log(data);\n});\nsocket.on('end', () => {\n server.close();\n});
\nOr\n\n
\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n pfx: fs.readFileSync('client.pfx')\n};\n\nvar socket = tls.connect(8000, options, () => {\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', (data) => {\n console.log(data);\n});\nsocket.on('end', () => {\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.
pfx
: A string or Buffer
containing the private key, certificate, and\nCA certs of the client in PFX or PKCS12 format.
key
: A string, Buffer
, array of strings, or array of Buffer
s\ncontaining the private key of the client in PEM format.
passphrase
: A string containing the passphrase for the private key or pfx.
cert
: A string, Buffer
, array of strings, or array of Buffer
s\ncontaining the certificate key of the client in PEM format.
ca
: A string, Buffer
, array of strings, or array of Buffer
s of trusted\ncertificates in PEM format. If this is omitted several well known "root"\nCAs (like VeriSign) will be used. These are used to authorize connections.
ciphers
: A string describing the ciphers to use or exclude, separated by\n:
. Uses the same default cipher suite as [tls.createServer()
][].
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 the following format:\n0x05hello0x05world
, where the first byte is the next protocol name's\nlength. (Passing an array is usually be much simpler: ['hello', 'world']
.)
ALPNProtocols
: An array of strings or Buffer
s containing the\nsupported ALPN protocols. Buffer
s should have following format:\n0x05hello0x05world
, where the first byte is the next protocol\nname's length. (Passing an array is usually be much simpler:\n['hello', 'world']
.)
servername
: Server name for the SNI (Server Name Indication) TLS\nextension.
checkServerIdentity(servername, cert)
: Provide an override for checking\nthe server's hostname against the certificate. Should return an error if\nverification fails. Returns undefined
if passing.
secureProtocol
: The SSL method to use, e.g., SSLv3_method
to force\nSSL version 3. The possible values depend on the version of OpenSSL\ninstalled in the environment and are defined in the constant\n[SSL_METHODS][].
secureContext
: An optional TLS context object from\ntls.createSecureContext( ... )
. It can be used for caching client\ncertificates, keys, and CA certificates.
session
: A Buffer
instance, containing TLS session.
minDHSize
: Minimum size of the DH parameter in bits to accept a TLS\nconnection. When a server offers a DH parameter with a size less\nthan this, the TLS connection is destroyed and an error is thrown. Default:\n1024.
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
\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst 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, () => {\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', (data) => {\n console.log(data);\n});\nsocket.on('end', () => {\n server.close();\n});
\nOr\n\n
\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n pfx: fs.readFileSync('client.pfx')\n};\n\nvar socket = tls.connect(8000, options, () => {\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', (data) => {\n console.log(data);\n});\nsocket.on('end', () => {\n server.close();\n});
\n",
"signatures": [
{
"params": [
{
"name": "port"
},
{
"name": "host",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "callback",
"optional": true
}
]
}
]
},
{
"textRaw": "tls.createSecureContext(options)",
"type": "method",
"name": "createSecureContext",
"desc": "Creates a credentials object; the options
object may contain the following\nfields:\n\n
pfx
: A string or Buffer
holding the PFX or PKCS12 encoded private\nkey, certificate, and CA certificates.key
: A string or Buffer
containing the private key of the server in\nPEM format. To support multiple keys using different algorithms, an array\ncan be provided. It can either be a plain array of keys or an array of\nobjects in the format {pem: key, passphrase: passphrase}
. (Required)passphrase
: A string containing the passphrase for the private key or pfx.cert
: A string containing the PEM encoded certificateca
: A string, Buffer
, array of strings, or array of Buffer
s of trusted\ncertificates in PEM format. If this is omitted several well known "root"\nCAs (like VeriSign) will be used. These are used to authorize connections.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\nhttps://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", "signatures": [ { "params": [ { "name": "options" } ] } ] }, { "textRaw": "tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])", "type": "method", "name": "createSecurePair", "desc": "Creates a new secure pair object with two streams, one of which reads and writes\nthe encrypted data and the other of which reads and writes the cleartext data.\nGenerally, the encrypted stream is piped to/from an incoming encrypted data\nstream and the cleartext one is used as a replacement for the initial encrypted\nstream.\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.
options
: An object with common SSL options. See [tls.TLSSocket
][].
tls.createSecurePair()
returns a SecurePair object with cleartext
and\nencrypted
stream properties.\n\n
NOTE: cleartext
has the same API as [tls.TLSSocket
][]\n\n
Creates a new [tls.Server][]. The connectionListener
argument is\nautomatically set as a listener for the ['secureConnection'
][] event. The\noptions
object may contain the following fields:\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. To support multiple keys using different algorithms an array\ncan be provided. It can either be a plain array of keys or an array of\nobjects in the format {pem: key, passphrase: passphrase}
. (Required)
passphrase
: A string containing the passphrase for the private key or pfx.
cert
: A string, Buffer
, array of strings, or array of Buffer
s\ncontaining the certificate key of the server in PEM format. (Required)
ca
: A string, Buffer
, array of strings, or array of Buffer
s of trusted\ncertificates in PEM format. If this is omitted several well known "root"\nCAs (like VeriSign) will be used. These are used to authorize connections.
crl
: Either a string or array of strings of PEM encoded CRLs (Certificate\nRevocation List).
ciphers
: A string describing the ciphers to use or exclude, separated by\n:
. The default cipher suite is:
ECDHE-RSA-AES128-GCM-SHA256:\nECDHE-ECDSA-AES128-GCM-SHA256:\nECDHE-RSA-AES256-GCM-SHA384:\nECDHE-ECDSA-AES256-GCM-SHA384:\nDHE-RSA-AES128-GCM-SHA256:\nECDHE-RSA-AES128-SHA256:\nDHE-RSA-AES128-SHA256:\nECDHE-RSA-AES256-SHA384:\nDHE-RSA-AES256-SHA384:\nECDHE-RSA-AES256-SHA256:\nDHE-RSA-AES256-SHA256:\nHIGH:\n!aNULL:\n!eNULL:\n!EXPORT:\n!DES:\n!RC4:\n!MD5:\n!PSK:\n!SRP:\n!CAMELLIA
\nThe default cipher suite prefers GCM ciphers for [Chrome's 'modern\ncryptography' setting] and also prefers ECDHE and DHE ciphers for Perfect\nForward Secrecy, while offering some backward compatibility.
\n128 bit AES is preferred over 192 and 256 bit AES in light of [specific\nattacks affecting larger AES key sizes].
\nOld clients that rely on insecure and deprecated RC4 or DES-based ciphers\n(like Internet Explorer 6) cannot complete the handshaking process with\nthe default configuration. If these clients must be supported, the\n[TLS recommendations] may offer a compatible cipher suite. For more details\non the format, see the [OpenSSL cipher list format documentation].
\necdhCurve
: A string describing a named curve to use for ECDH key agreement\nor false to disable ECDH.
Defaults to prime256v1
(NIST P-256). Use [crypto.getCurves()
][] to\nobtain a list of available curve names. On recent releases,\nopenssl ecparam -list_curves
will also display the name and description of\neach available elliptic curve.
dhparam
: A string or Buffer
containing Diffie Hellman parameters,\nrequired for Perfect Forward Secrecy. Use openssl dhparam
to create it.\nIts key length should be greater than or equal to 1024 bits, otherwise\nit throws an error. It is strongly recommended to use 2048 bits or\nlarger for stronger security. If omitted or invalid, it is silently\ndiscarded and DHE ciphers won't be available.
handshakeTimeout
: Abort the connection if the SSL/TLS handshake does not\nfinish in the specified number of 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. Default: true
.
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.)
ALPNProtocols
: An array or Buffer
of possible ALPN\nprotocols. (Protocols should be ordered by their priority.) When\nthe server receives both NPN and ALPN extensions from the client,\nALPN takes precedence over NPN and the server does not send an NPN\nextension to the client.
SNICallback(servername, cb)
: A function that will be called if the client\nsupports SNI TLS extension. Two arguments will be passed to it:\nservername
and cb
. SNICallback
should invoke cb(null, ctx)
, where\nctx
is a SecureContext instance. (tls.createSecureContext(...)
can be\nused to get a proper SecureContext.) If SNICallback
wasn't provided the\ndefault callback with high-level API will be used (see below).
sessionTimeout
: An integer specifying the number of seconds after which\nthe TLS session identifiers and TLS session tickets created by the server\nwill time out. See [SSL_CTX_set_timeout] for more details.
ticketKeys
: A 48-byte Buffer
instance consisting of a 16-byte prefix,\na 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS\nsession tickets on multiple instances of the 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 a MD5 hash value\ngenerated from the command-line. (In FIPS mode a truncated SHA1 hash is\nused instead.) Otherwise, a default is not provided.
secureProtocol
: The SSL method to use, e.g., SSLv3_method
to force\nSSL version 3. The possible values depend on the version of OpenSSL\ninstalled in the environment and are defined in the constant [SSL_METHODS][].
Here is a simple example echo server:\n\n
\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst 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, (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, () => {\n console.log('server bound');\n});
\nOr\n\n
\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst 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, (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, () => {\n console.log('server bound');\n});
\nYou can test this server by connecting to it with openssl s_client
:\n\n
openssl s_client -connect 127.0.0.1:8000
\n",
"signatures": [
{
"params": [
{
"name": "options"
},
{
"name": "secureConnectionListener",
"optional": true
}
]
}
]
},
{
"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": []
}
]
}
],
"type": "module",
"displayName": "TLS (SSL)"
}
]
}