{ "source": "doc/api/tls.md", "modules": [ { "textRaw": "TLS (SSL)", "name": "tls_(ssl)", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "
The tls
module provides an implementation of the Transport Layer Security\n(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.\nThe module can be accessed using:
const tls = require('tls');\n
\n",
"modules": [
{
"textRaw": "TLS/SSL Concepts",
"name": "tls/ssl_concepts",
"desc": "The TLS/SSL is a public/private key infrastructure (PKI). For most common\ncases, each client and server must have a private key.
\nPrivate keys can be generated in multiple ways. The example below illustrates\nuse of the OpenSSL command-line interface to generate a 2048-bit RSA private\nkey:
\nopenssl genrsa -out ryans-key.pem 2048\n
\nWith TLS/SSL, all servers (and some clients) must have a certificate.\nCertificates are public keys that correspond to a private key, and that are\ndigitally signed either by a Certificate Authority or by the owner of the\nprivate key (such certificates are referred to as "self-signed"). The first\nstep to obtaining a certificate is to create a Certificate Signing Request\n(CSR) file.
\nThe OpenSSL command-line interface can be used to generate a CSR for a private\nkey:
\nopenssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem\n
\nOnce the CSR file is generated, it can either be sent to a Certificate\nAuthority for signing or used to generate a self-signed certificate.
\nCreating a self-signed certificate using the OpenSSL command-line interface\nis illustrated in the example below:
\nopenssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem\n
\nOnce the certificate is generated, it can be used to generate a .pfx
or\n.p12
file:
openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \\\n -certfile ca-cert.pem -out ryans.pfx\n
\nWhere:
\nin
: is the signed certificateinkey
: is the associated private keycertfile
: is a concatenation of all Certificate Authority (CA) certs into\n a single file, e.g. cat ca1-cert.pem ca2-cert.pem > ca-cert.pem
The term "Forward Secrecy" or "Perfect Forward Secrecy" describes a feature of\nkey-agreement (i.e., key-exchange) methods. That is, the server and client keys\nare used to negotiate new temporary keys that are used specifically and only for\nthe current communication session. Practically, this means that even if the\nserver's private key is compromised, communication can only be decrypted by\neavesdroppers if the attacker manages to obtain the key-pair specifically\ngenerated for the session.
\nPerfect Forward Secrecy is achieved by randomly generating a key pair for\nkey-agreement on every TLS/SSL handshake (in contrast to using the same key for\nall sessions). Methods implementing this technique are called "ephemeral".
\nCurrently two methods are commonly used to achieve Perfect Forward Secrecy (note\nthe character "E" appended to the traditional abbreviations):
\nEphemeral methods may have some performance drawbacks, because key generation\nis expensive.
\nTo use Perfect Forward Secrecy using DHE
with the tls
module, it is required\nto generate Diffie-Hellman parameters and specify them with the dhparam
\noption to tls.createSecureContext()
. The following illustrates the use of\nthe OpenSSL command-line interface to generate such parameters:
openssl dhparam -outform PEM -out dhparam.pem 2048\n
\nIf using Perfect Forward Secrecy using ECDHE
, Diffie-Hellman parameters are\nnot required and a default ECDHE curve will be used. The ecdhCurve
property\ncan be used when creating a TLS Server to specify the list of names of supported\ncurves to use, see tls.createServer()
for more info.
ALPN (Application-Layer Protocol Negotiation Extension), NPN (Next\nProtocol Negotiation) and, SNI (Server Name Indication) are TLS\nhandshake extensions:
\nNote: Use of ALPN is recommended over NPN. The NPN extension has never been\nformally defined or documented and generally not recommended for use.
\n" }, { "textRaw": "Client-initiated renegotiation attack mitigation", "name": "Client-initiated renegotiation attack mitigation", "type": "misc", "desc": "The TLS protocol allows clients to renegotiate certain aspects of the TLS\nsession. Unfortunately, session renegotiation requires a disproportionate amount\nof server-side resources, making it a potential vector for denial-of-service\nattacks.
\nTo mitigate the risk, renegotiation is limited to three times every ten minutes.\nAn 'error'
event is emitted on the tls.TLSSocket
instance when this\nthreshold is exceeded. The limits are configurable:
tls.CLIENT_RENEG_LIMIT
{number} Specifies the number of renegotiation\nrequests. Defaults to 3
.tls.CLIENT_RENEG_WINDOW
{number} Specifies the time renegotiation window\nin seconds. Defaults to 600
(10 minutes).Note: The default renegotiation limits should not be modified without a full\nunderstanding of the implications and risks.
\nTo test the renegotiation limits on a server, connect to it using the OpenSSL\ncommand-line client (openssl s_client -connect address:port
) then input\nR<CR>
(i.e., the letter R
followed by a carriage return) multiple times.
Node.js is built with a default suite of enabled and disabled TLS ciphers.\nCurrently, the default cipher suite is:
\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\n
\nThis default can be replaced 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:
node --tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4"\n
\nThe default can also be replaced on a per client or server basis using the\nciphers
option from tls.createSecureContext()
, which is also available\nin tls.createServer()
, tls.connect()
, and when creating new\ntls.TLSSocket
s.
Consult OpenSSL cipher list format documentation for details on the format.
\nNote: 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 and ciphers
option should by\nused only if absolutely necessary.
The 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\nTLS recommendations may offer a compatible cipher suite. For more details\non the format, see the OpenSSL cipher list format documentation.
\n", "type": "module", "displayName": "Modifying the Default TLS Cipher suite" }, { "textRaw": "Deprecated APIs", "name": "deprecated_apis", "classes": [ { "textRaw": "Class: CryptoStream", "type": "class", "name": "CryptoStream", "meta": { "added": [ "v0.3.4" ], "deprecated": [ "v0.11.3" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", "desc": "The tls.CryptoStream
class represents a stream of encrypted data. This class\nhas been deprecated and should no longer be used.
The cryptoStream.bytesWritten
property returns the total number of bytes\nwritten to the underlying socket including the bytes required for the\nimplementation of the TLS protocol.
Returned by tls.createSecurePair()
.
The 'secure'
event is emitted by the SecurePair
object once a secure\nconnection has been established.
As with checking for the server secureConnection
\nevent, pair.cleartext.authorized
should be inspected to confirm whether the\ncertificate used is properly authorized.
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.
\ntls.createSecurePair()
returns a tls.SecurePair
object with cleartext
and\nencrypted
stream properties.
Note: cleartext
has the same API as tls.TLSSocket
.
Note: The tls.createSecurePair()
method is now deprecated in favor of\ntls.TLSSocket()
. For example, the code:
pair = tls.createSecurePair(/* ... */);\npair.encrypted.pipe(socket);\nsocket.pipe(pair.encrypted);\n
\ncan be replaced by:
\nsecure_socket = tls.TLSSocket(socket, options);\n
\nwhere secure_socket
has the same API as pair.cleartext
.
The tls.Server
class is a subclass of net.Server
that accepts encrypted\nconnections using TLS or SSL.
The 'newSession'
event is emitted upon creation of a new TLS session. This may\nbe used to store sessions in external storage. The listener callback is passed\nthree arguments when called:
sessionId
- The TLS session identifiersessionData
- The TLS session datacallback
{Function} A callback function taking no arguments that must be\ninvoked in order for data to be sent or received over the secure connection.Note: Listening for this event will have an effect only on connections\nestablished after the addition of the event listener.
\n", "params": [] }, { "textRaw": "Event: 'OCSPRequest'", "type": "event", "name": "OCSPRequest", "meta": { "added": [ "v0.11.13" ], "changes": [] }, "desc": "The 'OCSPRequest'
event is emitted when the client sends a certificate status\nrequest. The listener callback is passed three arguments when called:
certificate
{Buffer} The server certificateissuer
{Buffer} The issuer's certificatecallback
{Function} A callback function that must be invoked to provide\nthe results of the OCSP request.The server's current certificate can be parsed to obtain the OCSP URL\nand certificate ID; after obtaining an OCSP response, callback(null, resp)
is\nthen invoked, where resp
is a Buffer
instance containing the OCSP response.\nBoth certificate
and issuer
are Buffer
DER-representations of the\nprimary and issuer's certificates. These can be used to obtain the OCSP\ncertificate ID and OCSP endpoint URL.
Alternatively, callback(null, null)
may be called, indicating that there was\nno OCSP response.
Calling callback(err)
will result in a socket.destroy(err)
call.
The typical flow of an OCSP Request is as follows:
\n'OCSPRequest'
(via the status\ninfo extension in ClientHello).'OCSPRequest'
event, calling the\nlistener if registered.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: The issuer
can be null
if the certificate is either self-signed or\nthe issuer is not in the root certificates list. (An issuer may be provided\nvia the ca
option when establishing the TLS connection.)
Note: Listening for this event will have an effect only on connections\nestablished after the addition of the event listener.
\nNote: An npm module like asn1.js may be used to parse the certificates.
\n", "params": [] }, { "textRaw": "Event: 'resumeSession'", "type": "event", "name": "resumeSession", "meta": { "added": [ "v0.9.2" ], "changes": [] }, "desc": "The 'resumeSession'
event is emitted when the client requests to resume a\nprevious TLS session. The listener callback is passed two arguments when\ncalled:
sessionId
- The TLS/SSL session identifiercallback
{Function} A callback function to be called when the prior session\nhas been recovered.When called, the event listener may perform a lookup in external storage using\nthe given sessionId
and invoke callback(null, sessionData)
once finished. If\nthe session cannot be resumed (i.e., doesn't exist in storage) the callback may\nbe invoked as callback(null, null)
. Calling callback(err)
will terminate the\nincoming connection and destroy the socket.
Note: Listening for this event will have an effect only on connections\nestablished after the addition of the event listener.
\nThe following illustrates resuming a TLS session:
\nconst 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
\n",
"params": []
},
{
"textRaw": "Event: 'secureConnection'",
"type": "event",
"name": "secureConnection",
"meta": {
"added": [
"v0.3.2"
],
"changes": []
},
"desc": "The 'secureConnection'
event is emitted after the handshaking process for a\nnew connection has successfully completed. The listener callback is passed a\nsingle argument when called:
tlsSocket
{tls.TLSSocket} The established TLS socket.The tlsSocket.authorized
property is a boolean
indicating whether the\nclient has been verified by one of the supplied Certificate Authorities for the\nserver. If tlsSocket.authorized
is false
, then socket.authorizationError
\nis set to describe how authorization failed. Note that depending on the settings\nof the TLS server, unauthorized connections may still be accepted.
The tlsSocket.npnProtocol
and tlsSocket.alpnProtocol
properties are strings\nthat contain the selected NPN and ALPN protocols, respectively. When both NPN\nand ALPN extensions are received, ALPN takes precedence over NPN and the next\nprotocol is selected by ALPN.
When ALPN has no selected protocol, tlsSocket.alpnProtocol
returns false
.
The tlsSocket.servername
property is a string containing the server name\nrequested via SNI.
The 'tlsClientError'
event is emitted when an error occurs before a secure\nconnection is established. The listener callback is passed two arguments when\ncalled:
exception
{Error} The Error
object describing the errortlsSocket
{tls.TLSSocket} The tls.TLSSocket
instance from which the\nerror originated.The server.addContext()
method adds a secure context that will be used if\nthe client request's SNI hostname matches the supplied hostname
(or wildcard).
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.
The server.close()
method stops the server from accepting new connections.
This function operates asynchronously. The 'close'
event will be emitted\nwhen the server has no more open connections.
Returns a Buffer
instance holding the keys currently used for\nencryption/decryption of the TLS Session Tickets
Starts the server listening for encrypted connections.\nThis method is identical to server.listen()
from net.Server
.
Updates the keys for encryption/decryption of the TLS Session Tickets.
\nNote: The key's Buffer
should be 48 bytes long. See ticketKeys
option in\ntls.createServer for\nmore information on how it is used.
Note: Changes to the ticket keys are effective only for future server\nconnections. Existing or currently pending server connections will use the\nprevious keys.
\n" } ], "properties": [ { "textRaw": "server.connections", "name": "connections", "meta": { "added": [ "v0.3.2" ], "deprecated": [ "v0.9.7" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`server.getConnections()`][] instead.", "desc": "Returns the current number of concurrent connections on the server.
\n" } ] }, { "textRaw": "Class: tls.TLSSocket", "type": "class", "name": "tls.TLSSocket", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "The tls.TLSSocket
is a subclass of net.Socket
that performs transparent\nencryption of written data and all required TLS negotiation.
Instances of tls.TLSSocket
implement the duplex Stream interface.
Note: Methods that return TLS connection metadata (e.g.\ntls.TLSSocket.getPeerCertificate()
will only return data while the\nconnection is open.
Construct a new tls.TLSSocket
object from an existing TCP socket.
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' }
Disables TLS renegotiation for this TLSSocket
instance. Once called, attempts\nto renegotiate will trigger an 'error'
event on the TLSSocket
.
Returns an object representing the cipher name. The version
key is a legacy\nfield which always contains the value 'TLSv1/SSLv3'
.
For example: { name: 'AES256-SHA', version: 'TLSv1/SSLv3' }
See SSL_CIPHER_get_name()
in\nhttps://www.openssl.org/docs/man1.0.2/ssl/SSL_CIPHER_get_name.html for more\ninformation.
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; null
is returned\nif called on a server socket. The supported types are 'DH'
and 'ECDH'
. The\nname
property is available only when type is 'ECDH'.
For Example: { type: 'ECDH', name: 'prime256v1', size: 256 }
Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the fields of the certificate.
\nIf the full certificate chain was requested, each certificate will include a\nissuerCertificate
property containing an object representing its issuer's\ncertificate.
For example:
\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 issuerCertificate:\n { ... another certificate, possibly with a .issuerCertificate ... },\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' }\n
\nIf the peer does not provide a certificate, an empty object will be returned.
\n" }, { "textRaw": "tlsSocket.getProtocol()", "type": "method", "name": "getProtocol", "meta": { "added": [ "v5.7.0" ], "changes": [] }, "desc": "Returns a string containing the negotiated SSL/TLS protocol version of the\ncurrent connection. The value 'unknown'
will be returned for connected\nsockets that have not completed the handshaking process. The value null
will\nbe returned for server sockets or disconnected client sockets.
Example responses include:
\nSSLv3
TLSv1
TLSv1.1
TLSv1.2
unknown
See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more\ninformation.
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getSession()", "type": "method", "name": "getSession", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "Returns the ASN.1 encoded TLS session or undefined
if no session was\nnegotiated. Can be used to speed up handshake establishment when reconnecting\nto the server.
Returns the TLS session ticket or undefined
if no session was negotiated.
Note: This only works with client TLS sockets. Useful only for debugging,\nfor session reuse provide session
option to tls.connect()
.
The tlsSocket.renegotiate()
method initiates a TLS renegotiation process.\nUpon completion, the callback
function will be passed a single argument\nthat is either an Error
(if the request failed) or null
.
Note: This method can be used to request a peer's certificate after the\nsecure connection has been established.
\nNote: When running as the server, the socket will be destroyed with an error\nafter handshakeTimeout
timeout.
The tlsSocket.setMaxSendFragment()
method sets the maximum TLS fragment size.\nReturns true
if setting the limit succeeded; false
otherwise.
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" } ], "events": [ { "textRaw": "Event: 'OCSPResponse'", "type": "event", "name": "OCSPResponse", "meta": { "added": [ "v0.11.13" ], "changes": [] }, "desc": "The 'OCSPResponse'
event is emitted if the requestOCSP
option was set\nwhen the tls.TLSSocket
was created and an OCSP response has been received.\nThe listener callback is passed a single argument when called:
response
{Buffer} The server's OCSP responseTypically, the response
is a digitally signed object from the server's CA that\ncontains information about server's certificate revocation status.
The 'secureConnect'
event is emitted after the handshaking process for a new\nconnection has successfully completed. The listener callback will be called\nregardless of whether or not the server's certificate has been authorized. It\nis the client's responsibility to check the tlsSocket.authorized
property to\ndetermine if the server certificate was signed by one of the specified CAs. If\ntlsSocket.authorized === false
, then the error can be found by examining the\ntlsSocket.authorizationError
property. If either ALPN or NPN was used,\nthe tlsSocket.alpnProtocol
or tlsSocket.npnProtocol
properties can be\nchecked to determine the negotiated protocol.
Returns the reason why the peer's certificate was not been verified. This\nproperty is set only when tlsSocket.authorized === false
.
Returns true
if the peer certificate was signed by one of the CAs specified\nwhen creating the tls.TLSSocket
instance, otherwise false
.
Always returns true
. This may be used to distinguish TLS sockets from regular\nnet.Socket
instances.
Returns the string representation of the local IP address.
\n" }, { "textRaw": "tlsSocket.localPort", "name": "localPort", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "Returns the numeric representation of the local port.
\n" }, { "textRaw": "tlsSocket.remoteAddress", "name": "remoteAddress", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "Returns the string representation of the remote IP address. For example,\n'74.125.127.100'
or '2001:4860:a005::68'
.
Returns the string representation of the remote IP family. 'IPv4'
or 'IPv6'
.
Returns the numeric representation of the remote port. For example, 443
.
Verifies the certificate cert
is issued to host host
.
Returns {Error} object, populating it with the reason, host, and cert on\nfailure. On success, returns {undefined}.
\nNote: This function can be overwritten by providing alternative function\nas part of the options.checkServerIdentity
option passed to tls.connect()
.\nThe overwriting function can call tls.checkServerIdentity()
of course, to augment\nthe checks done with additional verification.
Note: This function is only called if the certificate passed all other checks, such as\nbeing issued by trusted CA (options.ca
).
The cert object contains the parsed certificate and will have a structure similar to:
\n{ subject:\n { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ],\n CN: '*.nodejs.org' },\n issuer:\n { C: 'GB',\n ST: 'Greater Manchester',\n L: 'Salford',\n O: 'COMODO CA Limited',\n CN: 'COMODO RSA Domain Validation Secure Server CA' },\n subjectaltname: 'DNS:*.nodejs.org, DNS:nodejs.org',\n infoAccess:\n { 'CA Issuers - URI':\n [ 'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt' ],\n 'OCSP - URI': [ 'http://ocsp.comodoca.com' ] },\n modulus: 'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1',\n exponent: '0x10001',\n valid_from: 'Aug 14 00:00:00 2017 GMT',\n valid_to: 'Nov 20 23:59:59 2019 GMT',\n fingerprint: '01:02:59:D9:C3:D2:0D:08:F7:82:4E:44:A4:B4:53:C5:E2:3A:87:4D',\n ext_key_usage: [ '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' ],\n serialNumber: '66593D57F20CBC573E433381B5FEC280',\n raw: <Buffer ....> }\n
\n"
},
{
"textRaw": "tls.connect(options[, callback])",
"type": "method",
"name": "connect",
"meta": {
"added": [
"v0.11.3"
],
"changes": [
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/12839",
"description": "The `lookup` option is supported now."
},
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/11984",
"description": "The `ALPNProtocols` and `NPNProtocols` options can be `Uint8Array`s now."
},
{
"version": "v5.3.0, v4.7.0",
"pr-url": "https://github.com/nodejs/node/pull/4246",
"description": "The `secureContext` option is supported now."
},
{
"version": "v5.0.0",
"pr-url": "https://github.com/nodejs/node/pull/2564",
"description": "ALPN options are supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object} ",
"options": [
{
"textRaw": "`host` {string} Host the client should connect to, defaults to 'localhost'. ",
"name": "host",
"type": "string",
"desc": "Host the client should connect to, defaults to 'localhost'."
},
{
"textRaw": "`port` {number} Port the client should connect to. ",
"name": "port",
"type": "number",
"desc": "Port the client should connect to."
},
{
"textRaw": "`path` {string} Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. ",
"name": "path",
"type": "string",
"desc": "Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored."
},
{
"textRaw": "`socket` {stream.Duplex} Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance of [`net.Socket`][], but any `Duplex` stream is allowed. If this option is specified, `path`, `host` and `port` are ignored, except for certificate validation. Usually, a socket is already connected when passed to `tls.connect()`, but it can be connected later. Note that connection/disconnection/destruction of `socket` is the user's responsibility, calling `tls.connect()` will not cause `net.connect()` to be called. ",
"name": "socket",
"type": "stream.Duplex",
"desc": "Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance of [`net.Socket`][], but any `Duplex` stream is allowed. If this option is specified, `path`, `host` and `port` are ignored, except for certificate validation. Usually, a socket is already connected when passed to `tls.connect()`, but it can be connected later. Note that connection/disconnection/destruction of `socket` is the user's responsibility, calling `tls.connect()` will not cause `net.connect()` to be called."
},
{
"textRaw": "`rejectUnauthorized` {boolean} If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. Defaults to `true`. ",
"name": "rejectUnauthorized",
"type": "boolean",
"desc": "If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. Defaults to `true`."
},
{
"textRaw": "`NPNProtocols` {string[]|Buffer[]|Uint8Array[]|Buffer|Uint8Array} An array of strings, `Buffer`s or `Uint8Array`s, or a single `Buffer` or `Uint8Array` containing supported NPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. ",
"name": "NPNProtocols",
"type": "string[]|Buffer[]|Uint8Array[]|Buffer|Uint8Array",
"desc": "An array of strings, `Buffer`s or `Uint8Array`s, or a single `Buffer` or `Uint8Array` containing supported NPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`."
},
{
"textRaw": "`ALPNProtocols`: {string[]|Buffer[]|Uint8Array[]|Buffer|Uint8Array} An array of strings, `Buffer`s or `Uint8Array`s, or a single `Buffer` or `Uint8Array` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. ",
"name": "ALPNProtocols",
"type": "string[]|Buffer[]|Uint8Array[]|Buffer|Uint8Array",
"desc": "An array of strings, `Buffer`s or `Uint8Array`s, or a single `Buffer` or `Uint8Array` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`."
},
{
"textRaw": "`servername`: {string} Server name for the SNI (Server Name Indication) TLS extension. ",
"name": "servername",
"type": "string",
"desc": "Server name for the SNI (Server Name Indication) TLS extension."
},
{
"textRaw": "`checkServerIdentity(servername, cert)` {Function} A callback function to be used (instead of the builtin `tls.checkServerIdentity()` function) when checking the server's hostname (or the provided `servername` when explicitly set) against the certificate. This should return an {Error} if verification fails. The method should return `undefined` if the `servername` and `cert` are verified. ",
"name": "checkServerIdentity(servername,",
"desc": "cert)` {Function} A callback function to be used (instead of the builtin `tls.checkServerIdentity()` function) when checking the server's hostname (or the provided `servername` when explicitly set) against the certificate. This should return an {Error} if verification fails. The method should return `undefined` if the `servername` and `cert` are verified."
},
{
"textRaw": "`session` {Buffer} A `Buffer` instance, containing TLS session. ",
"name": "session",
"type": "Buffer",
"desc": "A `Buffer` instance, containing TLS session."
},
{
"textRaw": "`minDHSize` {number} Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. Defaults to `1024`. ",
"name": "minDHSize",
"type": "number",
"desc": "Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. Defaults to `1024`."
},
{
"textRaw": "`secureContext`: Optional TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`. ",
"name": "secureContext",
"desc": "Optional TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`."
},
{
"textRaw": "`lookup`: {Function} Custom lookup function. Defaults to [`dns.lookup()`][]. ",
"name": "lookup",
"type": "Function",
"desc": "Custom lookup function. Defaults to [`dns.lookup()`][]."
},
{
"textRaw": "...: Optional [`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing, otherwise they are ignored. ",
"name": "...",
"desc": "Optional [`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing, otherwise they are ignored."
}
],
"name": "options",
"type": "Object"
},
{
"textRaw": "`callback` {Function} ",
"name": "callback",
"type": "Function",
"optional": true
}
]
},
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "The callback
function, if specified, will be added as a listener for the\n'secureConnect'
event.
tls.connect()
returns a tls.TLSSocket
object.
The following implements a simple "echo server" example:
\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n // Necessary only if using the client certificate authentication\n key: fs.readFileSync('client-key.pem'),\n cert: fs.readFileSync('client-cert.pem'),\n\n // Necessary only if the server uses the self-signed certificate\n ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nconst 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
\nOr
\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n pfx: fs.readFileSync('client.pfx')\n};\n\nconst 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
\n"
},
{
"textRaw": "tls.connect(path[, options][, callback])",
"type": "method",
"name": "connect",
"meta": {
"added": [
"v0.11.3"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string} Default value for `options.path`. ",
"name": "path",
"type": "string",
"desc": "Default value for `options.path`."
},
{
"textRaw": "`options` {Object} See [`tls.connect()`][]. ",
"name": "options",
"type": "Object",
"desc": "See [`tls.connect()`][].",
"optional": true
},
{
"textRaw": "`callback` {Function} See [`tls.connect()`][]. ",
"name": "callback",
"type": "Function",
"desc": "See [`tls.connect()`][].",
"optional": true
}
]
},
{
"params": [
{
"name": "path"
},
{
"name": "options",
"optional": true
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "Same as tls.connect()
except that path
can be provided\nas an argument instead of an option.
Note: A path option, if specified, will take precedence over the path\nargument.
\n" }, { "textRaw": "tls.connect(port[, host][, options][, callback])", "type": "method", "name": "connect", "meta": { "added": [ "v0.11.3" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`port` {number} Default value for `options.port`. ", "name": "port", "type": "number", "desc": "Default value for `options.port`." }, { "textRaw": "`host` {string} Optional default value for `options.host`. ", "name": "host", "type": "string", "desc": "Optional default value for `options.host`.", "optional": true }, { "textRaw": "`options` {Object} See [`tls.connect()`][]. ", "name": "options", "type": "Object", "desc": "See [`tls.connect()`][].", "optional": true }, { "textRaw": "`callback` {Function} See [`tls.connect()`][]. ", "name": "callback", "type": "Function", "desc": "See [`tls.connect()`][].", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "Same as tls.connect()
except that port
and host
can be provided\nas arguments instead of options.
Note: A port or host option, if specified, will take precedence over any\nport or host argument.
\n" }, { "textRaw": "tls.createSecureContext(options)", "type": "method", "name": "createSecureContext", "meta": { "added": [ "v0.11.13" ], "changes": [ { "version": "v7.3.0", "pr-url": "https://github.com/nodejs/node/pull/10294", "description": "If the `key` option is an array, individual entries do not need a `passphrase` property anymore. Array entries can also just be `string`s or `Buffer`s now." }, { "version": "v5.2.0", "pr-url": "https://github.com/nodejs/node/pull/4099", "description": "The `ca` option can now be a single string containing multiple CA certificates." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`pfx` {string|string[]|Buffer|Buffer[]|Object[]} Optional PFX or PKCS12 encoded private key and certificate chain. `pfx` is an alternative to providing `key` and `cert` individually. PFX is usually encrypted, if it is, `passphrase` will be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form `{buf:Note:
\ntls.createServer()
sets the default value of the\nhonorCipherOrder
option to true
, other APIs that create secure contexts\nleave it unset.
tls.createServer()
uses a 128 bit truncated SHA1 hash value\ngenerated from process.argv
as the default value of the sessionIdContext
\noption, other APIs that create secure contexts have no default value.
The tls.createSecureContext()
method creates a credentials object.
A key is required for ciphers that make use of certificates. Either key
or\npfx
can be used to provide it.
If the 'ca' option is not given, then Node.js will use the default\npublicly trusted list of CAs as given in\nhttps://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt.
\n" }, { "textRaw": "tls.createServer([options][, secureConnectionListener])", "type": "method", "name": "createServer", "meta": { "added": [ "v0.3.2" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11984", "description": "The `ALPNProtocols` and `NPNProtocols` options can be `Uint8Array`s now." }, { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/2564", "description": "ALPN options are supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`handshakeTimeout` {number} Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. Defaults to `120` seconds. A `'tlsClientError'` is emitted on the `tls.Server` object whenever a handshake times out. ", "name": "handshakeTimeout", "type": "number", "desc": "Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. Defaults to `120` seconds. A `'tlsClientError'` is emitted on the `tls.Server` object whenever a handshake times out." }, { "textRaw": "`requestCert` {boolean} If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to `false`. ", "name": "requestCert", "type": "boolean", "desc": "If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to `false`." }, { "textRaw": "`rejectUnauthorized` {boolean} If not `false` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. Defaults to `true`. ", "name": "rejectUnauthorized", "type": "boolean", "desc": "If not `false` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. Defaults to `true`." }, { "textRaw": "`NPNProtocols` {string[]|Buffer[]|Uint8Array[]|Buffer|Uint8Array} An array of strings, `Buffer`s or `Uint8Array`s, or a single `Buffer` or `Uint8Array` containing supported NPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. (Protocols should be ordered by their priority.) ", "name": "NPNProtocols", "type": "string[]|Buffer[]|Uint8Array[]|Buffer|Uint8Array", "desc": "An array of strings, `Buffer`s or `Uint8Array`s, or a single `Buffer` or `Uint8Array` containing supported NPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. (Protocols should be ordered by their priority.)" }, { "textRaw": "`ALPNProtocols`: {string[]|Buffer[]|Uint8Array[]|Buffer|Uint8Array} An array of strings, `Buffer`s or `Uint8Array`s, or a single `Buffer` or `Uint8Array` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. (Protocols should be ordered by their priority.) When the server receives both NPN and ALPN extensions from the client, ALPN takes precedence over NPN and the server does not send an NPN extension to the client. ", "name": "ALPNProtocols", "type": "string[]|Buffer[]|Uint8Array[]|Buffer|Uint8Array", "desc": "An array of strings, `Buffer`s or `Uint8Array`s, or a single `Buffer` or `Uint8Array` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. (Protocols should be ordered by their priority.) When the server receives both NPN and ALPN extensions from the client, ALPN takes precedence over NPN and the server does not send an NPN extension to the client." }, { "textRaw": "`SNICallback(servername, cb)` {Function} A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a SecureContext instance. (`tls.createSecureContext(...)` can be used to get a proper SecureContext.) If `SNICallback` wasn't provided the default callback with high-level API will be used (see below). ", "name": "SNICallback(servername,", "desc": "cb)` {Function} A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a SecureContext instance. (`tls.createSecureContext(...)` can be used to get a proper SecureContext.) If `SNICallback` wasn't provided the default callback with high-level API will be used (see below)." }, { "textRaw": "`sessionTimeout` {number} An integer specifying the number of seconds after which the TLS session identifiers and TLS session tickets created by the server will time out. See [SSL_CTX_set_timeout] for more details. ", "name": "sessionTimeout", "type": "number", "desc": "An integer specifying the number of seconds after which the TLS session identifiers and TLS session tickets created by the server will time out. See [SSL_CTX_set_timeout] for more details." }, { "textRaw": "`ticketKeys`: A 48-byte `Buffer` instance consisting of a 16-byte prefix, a 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS session tickets on multiple instances of the TLS server. ", "name": "ticketKeys", "desc": "A 48-byte `Buffer` instance consisting of a 16-byte prefix, a 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS session tickets on multiple instances of the TLS server." }, { "textRaw": "...: Any [`tls.createSecureContext()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required. ", "name": "...", "desc": "Any [`tls.createSecureContext()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required." } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`secureConnectionListener` {Function} ", "name": "secureConnectionListener", "type": "Function", "optional": true } ] }, { "params": [ { "name": "options", "optional": true }, { "name": "secureConnectionListener", "optional": true } ] } ], "desc": "Creates a new tls.Server. The secureConnectionListener
, if provided, is\nautomatically set as a listener for the 'secureConnection'
event.
Note: The ticketKeys
options is automatically shared between cluster
\nmodule workers.
The following illustrates a simple echo server:
\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\nconst 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});\n
\nOr
\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\nconst 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});\n
\nThis server can be tested by connecting to it using openssl s_client
:
openssl s_client -connect 127.0.0.1:8000\n
\n"
},
{
"textRaw": "tls.getCiphers()",
"type": "method",
"name": "getCiphers",
"meta": {
"added": [
"v0.10.2"
],
"changes": []
},
"desc": "Returns an array with the names of the supported SSL ciphers.
\nFor example:
\nconsole.log(tls.getCiphers()); // ['AES128-SHA', 'AES256-SHA', ...]\n
\n",
"signatures": [
{
"params": []
}
]
}
],
"properties": [
{
"textRaw": "tls.DEFAULT_ECDH_CURVE",
"name": "DEFAULT_ECDH_CURVE",
"meta": {
"added": [
"v0.11.13"
],
"changes": []
},
"desc": "The default curve name to use for ECDH key agreement in a tls server. The\ndefault value is 'prime256v1'
(NIST P-256). Consult RFC 4492 and\nFIPS.186-4 for more details.