Thetls
module provides an implementation of the Transport Layer Security(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.The module can be accessed using:
const tls = require('tls');
The TLS/SSL is a public/private key infrastructure (PKI). For most commoncases, each client and server must have aprivate key.
Private keys can be generated in multiple ways. The example below illustratesuse of the OpenSSL command-line interface to generate a 2048-bit RSA privatekey:
openssl genrsa -out ryans-key.pem 2048
With TLS/SSL, all servers (and some clients) must have acertificate.Certificates arepublic keys that correspond to a private key, and that aredigitally signed either by a Certificate Authority or by the owner of theprivate key (such certificates are referred to as "self-signed"). The firststep to obtaining a certificate is to create aCertificate Signing Request(CSR) file.
The OpenSSL command-line interface can be used to generate a CSR for a privatekey:
openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem
Once the CSR file is generated, it can either be sent to a CertificateAuthority for signing or used to generate a self-signed certificate.
Creating a self-signed certificate using the OpenSSL command-line interfaceis illustrated in the example below:
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
Once the certificate is generated, it can be used to generate a.pfx
or.p12
file:
openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \ -certfile ca-cert.pem -out ryans.pfx
Where:
in
: is the signed certificateinkey
: is the associated private keycertfile
: is a concatenation of all Certificate Authority (CA) certs intoa 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 ofkey-agreement (i.e., key-exchange) methods. That is, the server and client keysare used to negotiate new temporary keys that are used specifically and only forthe current communication session. Practically, this means that even if theserver's private key is compromised, communication can only be decrypted byeavesdroppers if the attacker manages to obtain the key-pair specificallygenerated for the session.
Perfect Forward Secrecy is achieved by randomly generating a key pair forkey-agreement on every TLS/SSL handshake (in contrast to using the same key forall sessions). Methods implementing this technique are called "ephemeral".
Currently two methods are commonly used to achieve Perfect Forward Secrecy (notethe character "E" appended to the traditional abbreviations):
Ephemeral methods may have some performance drawbacks, because key generationis expensive.
To use Perfect Forward Secrecy usingDHE
with thetls
module, it is requiredto generate Diffie-Hellman parameters and specify them with thedhparam
option totls.createSecureContext()
. The following illustrates the use ofthe OpenSSL command-line interface to generate such parameters:
openssl dhparam -outform PEM -out dhparam.pem 2048
If using Perfect Forward Secrecy usingECDHE
, Diffie-Hellman parameters arenot required and a default ECDHE curve will be used. TheecdhCurve
propertycan be used when creating a TLS Server to specify the list of names of supportedcurves to use, seetls.createServer()
for more info.
ALPN (Application-Layer Protocol Negotiation Extension) andSNI (Server Name Indication) are TLS handshake extensions:
The TLS protocol allows clients to renegotiate certain aspects of the TLSsession. Unfortunately, session renegotiation requires a disproportionate amountof server-side resources, making it a potential vector for denial-of-serviceattacks.
To mitigate the risk, renegotiation is limited to three times every ten minutes.An'error'
event is emitted on thetls.TLSSocket
instance when thisthreshold is exceeded. The limits are configurable:
tls.CLIENT_RENEG_LIMIT
<number> Specifies the number of renegotiationrequests.Default:3
.tls.CLIENT_RENEG_WINDOW
<number> Specifies the time renegotiation windowin seconds.Default:600
(10 minutes).The default renegotiation limits should not be modified without a fullunderstanding of the implications and risks.
Establishing a TLS session can be relatively slow. The process can be spedup by saving and later reusing the session state. There are several mechanismsto do so, discussed here from oldest to newest (and preferred).
Session Identifiers Servers generate a unique ID for new connections andsend it to the client. Clients and servers save the session state. Whenreconnecting, clients send the ID of their saved session state and if the serveralso has the state for that ID, it can agree to use it. Otherwise, the serverwill create a new session. SeeRFC 2246 for more information, page 23 and30.
Resumption using session identifiers is supported by most web browsers whenmaking HTTPS requests.
For Node.js, clients must calltls.TLSSocket.getSession()
after the'secureConnect'
event to get the session data, and provide the data to thesession
option oftls.connect()
to reuse the session. Servers mustimplement handlers for the'newSession'
and'resumeSession'
eventsto save and restore the session data using the session ID as the lookup key toreuse sessions. To reuse sessions across load balancers or cluster workers,servers must use a shared session cache (such as Redis) in their sessionhandlers.
Session Tickets The servers encrypt the entire session state and send itto the client as a "ticket". When reconnecting, the state is sent to the serverin the initial connection. This mechanism avoids the need for server-sidesession cache. If the server doesn't use the ticket, for any reason (failureto decrypt it, it's too old, etc.), it will create a new session and send a newticket. SeeRFC 5077 for more information.
Resumption using session tickets is becoming commonly supported by many webbrowsers when making HTTPS requests.
For Node.js, clients use the same APIs for resumption with session identifiersas for resumption with session tickets. For debugging, iftls.TLSSocket.getTLSTicket()
returns a value, the session data contains aticket, otherwise it contains client-side session state.
Single process servers need no specific implementation to use session tickets.To use session tickets across server restarts or load balancers, servers mustall have the same ticket keys. There are three 16-byte keys internally, but thetls API exposes them as a single 48-byte buffer for convenience.
Its possible to get the ticket keys by callingserver.getTicketKeys()
onone server instance and then distribute them, but it is more reasonable tosecurely generate 48 bytes of secure random data and set them with theticketKeys
option oftls.createServer()
. The keys should be regularlyregenerated and server's keys can be reset withserver.setTicketKeys()
.
Session ticket keys are cryptographic keys, and theymust be storedsecurely. With TLS 1.2 and below, if they are compromised all sessions thatused tickets encrypted with them can be decrypted. They should not be storedon disk, and they should be regenerated regularly.
If clients advertise support for tickets, the server will send them. Theserver can disable tickets by supplyingrequire('constants').SSL_OP_NO_TICKET
insecureOptions
.
Both session identifiers and session tickets timeout, causing the server tocreate new sessions. The timeout can be configured with thesessionTimeout
option oftls.createServer()
.
For all the mechanisms, when resumption fails, servers will create new sessions.Since failing to resume the session does not cause TLS/HTTPS connectionfailures, it is easy to not notice unnecessarily poor TLS performance. TheOpenSSL CLI can be used to verify that servers are resuming sessions. Use the-reconnect
option toopenssl s_client
, for example:
$ openssl s_client -connect localhost:443 -reconnect
Read through the debug output. The first connection should say "New", forexample:
New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
Subsequent connections should say "Reused", for example:
Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
Node.js is built with a default suite of enabled and disabled TLS ciphers.Currently, the default cipher suite is:
ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA
This default can be replaced entirely using the--tls-cipher-list
commandline switch (directly, or via theNODE_OPTIONS
environment variable). Forinstance, the following makesECDHE-RSA-AES128-GCM-SHA256:!RC4
the default TLScipher suite:
node --tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4" server.jsexport NODE_OPTIONS=--tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4"node server.js
The default can also be replaced on a per client or server basis using theciphers
option fromtls.createSecureContext()
, which is also availableintls.createServer()
,tls.connect()
, and when creating newtls.TLSSocket
s.
ConsultOpenSSL cipher list format documentation for details on the format.
The default cipher suite included within Node.js has been carefullyselected to reflect current security best practices and risk mitigation.Changing the default cipher suite can have a significant impact on the securityof an application. The--tls-cipher-list
switch andciphers
option should byused only if absolutely necessary.
The default cipher suite prefers GCM ciphers forChrome's 'moderncryptography' setting and also prefers ECDHE and DHE ciphers for PerfectForward Secrecy, while offeringsome backward compatibility.
128 bit AES is preferred over 192 and 256 bit AES in light ofspecificattacks affecting larger AES key sizes.
Old clients that rely on insecure and deprecated RC4 or DES-based ciphers(like Internet Explorer 6) cannot complete the handshaking process withthe default configuration. If these clientsmust be supported, theTLS recommendations may offer a compatible cipher suite. For more detailson the format, see theOpenSSL cipher list format documentation.
Thetls.Server
class is a subclass ofnet.Server
that accepts encryptedconnections using TLS or SSL.
line
<Buffer> Line of ASCII text, in NSSSSLKEYLOGFILE
format.tlsSocket
<tls.TLSSocket> Thetls.TLSSocket
instance on which it wasgenerated.Thekeylog
event is emitted when key material is generated or received bya connection to this server (typically before handshake has completed, but notnecessarily). This keying material can be stored for debugging, as it allowscaptured TLS traffic to be decrypted. It may be emitted multiple times foreach socket.
A typical use case is to append received lines to a common text file, whichis later used by software (such as Wireshark) to decrypt the traffic:
const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });// ...server.on('keylog', (line, tlsSocket) => { if (tlsSocket.remoteAddress !== '...') return; // Only log keys for a particular IP logFile.write(line);});
The'newSession'
event is emitted upon creation of a new TLS session. This maybe used to store sessions in external storage. The data should be provided tothe'resumeSession'
callback.
The listener callback is passed three arguments when called:
sessionId
<Buffer> The TLS session identifiersessionData
<Buffer> The TLS session datacallback
<Function> A callback function taking no arguments that must beinvoked in order for data to be sent or received over the secure connection.Listening for this event will have an effect only on connections establishedafter the addition of the event listener.
The'OCSPRequest'
event is emitted when the client sends a certificate statusrequest. 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 providethe results of the OCSP request.The server's current certificate can be parsed to obtain the OCSP URLand certificate ID; after obtaining an OCSP response,callback(null, resp)
isthen invoked, whereresp
is aBuffer
instance containing the OCSP response.Bothcertificate
andissuer
areBuffer
DER-representations of theprimary and issuer's certificates. These can be used to obtain the OCSPcertificate ID and OCSP endpoint URL.
Alternatively,callback(null, null)
may be called, indicating that there wasno OCSP response.
Callingcallback(err)
will result in asocket.destroy(err)
call.
The typical flow of an OCSP Request is as follows:
'OCSPRequest'
(via the statusinfo extension in ClientHello).'OCSPRequest'
event, calling thelistener if registered.certificate
orissuer
andperforms anOCSP request to the CA.'OCSPResponse'
from the CA and sends it back to the clientvia thecallback
argumentTheissuer
can benull
if the certificate is either self-signed or theissuer is not in the root certificates list. (An issuer may be providedvia theca
option when establishing the TLS connection.)
Listening for this event will have an effect only on connections establishedafter the addition of the event listener.
An npm module likeasn1.js may be used to parse the certificates.
The'resumeSession'
event is emitted when the client requests to resume aprevious TLS session. The listener callback is passed two arguments whencalled:
sessionId
<Buffer> The TLS session identifiercallback
<Function> A callback function to be called when the prior sessionhas been recovered:callback([err[, sessionData]])
The event listener should perform a lookup in external storage for thesessionData
saved by the'newSession'
event handler using the givensessionId
. If found, callcallback(null, sessionData)
to resume the session.If not found, the session cannot be resumed.callback()
must be calledwithoutsessionData
so that the handshake can continue and a new session canbe created. It is possible to callcallback(err)
to terminate the incomingconnection and destroy the socket.
Listening for this event will have an effect only on connections establishedafter the addition of the event listener.
The following illustrates resuming a TLS session:
const tlsSessionStore = {};server.on('newSession', (id, data, cb) => { tlsSessionStore[id.toString('hex')] = data; cb();});server.on('resumeSession', (id, cb) => { cb(null, tlsSessionStore[id.toString('hex')] || null);});
The'secureConnection'
event is emitted after the handshaking process for anew connection has successfully completed. The listener callback is passed asingle argument when called:
tlsSocket
<tls.TLSSocket> The established TLS socket.ThetlsSocket.authorized
property is aboolean
indicating whether theclient has been verified by one of the supplied Certificate Authorities for theserver. IftlsSocket.authorized
isfalse
, thensocket.authorizationError
is set to describe how authorization failed. Note that depending on the settingsof the TLS server, unauthorized connections may still be accepted.
ThetlsSocket.alpnProtocol
property is a string that contains the selectedALPN protocol. When ALPN has no selected protocol,tlsSocket.alpnProtocol
equalsfalse
.
ThetlsSocket.servername
property is a string containing the server namerequested via SNI.
The'tlsClientError'
event is emitted when an error occurs before a secureconnection is established. The listener callback is passed two arguments whencalled:
exception
<Error> TheError
object describing the errortlsSocket
<tls.TLSSocket> Thetls.TLSSocket
instance from which theerror originated.hostname
<string> A SNI hostname or wildcard (e.g.'*'
)context
<Object> An object containing any of the possible propertiesfrom thetls.createSecureContext()
options
arguments (e.g.key
,cert
,ca
, etc).Theserver.addContext()
method adds a secure context that will be used ifthe client request's SNI name matches the suppliedhostname
(or wildcard).
Returns the bound address, the address family name, and port of theserver as reported by the operating system. Seenet.Server.address()
formore information.
callback
<Function> A listener callback that will be registered to listenfor the server instance's'close'
event.Theserver.close()
method stops the server from accepting new connections.
This function operates asynchronously. The'close'
event will be emittedwhen the server has no more open connections.
server.getConnections()
instead.Returns the current number of concurrent connections on the server.
Returns the session ticket keys.
SeeSession Resumption for more information.
Starts the server listening for encrypted connections.This method is identical toserver.listen()
fromnet.Server
.
keys
<Buffer> A 48-byte buffer containing the session ticket keys.Sets the session ticket keys.
Changes to the ticket keys are effective only for future server connections.Existing or currently pending server connections will use the previous keys.
SeeSession Resumption for more information.
Thetls.TLSSocket
is a subclass ofnet.Socket
that performs transparentencryption of written data and all required TLS negotiation.
Instances oftls.TLSSocket
implement the duplexStream interface.
Methods that return TLS connection metadata (e.g.tls.TLSSocket.getPeerCertificate()
will only return data while theconnection is open.
Version | Changes |
---|---|
v5.0.0 | ALPN options are supported now. |
v0.11.4 | Added in: v0.11.4 |
socket
<net.Socket> |<stream.Duplex>On the server side, anyDuplex
stream. On the client side, anyinstance ofnet.Socket
(for genericDuplex
stream supporton the client side,tls.connect()
must be used).options
<Object>
isServer
: The SSL/TLS protocol is asymmetrical, TLSSockets must know ifthey are to behave as a server or a client. Iftrue
the TLS socket will beinstantiated as a server.Default:false
.server
<net.Server> Anet.Server
instance.requestCert
: Whether to authenticate the remote peer by requesting acertificate. Clients always request a server certificate. Servers(isServer
is true) may setrequestCert
to true to request a clientcertificate.rejectUnauthorized
: Seetls.createServer()
ALPNProtocols
: Seetls.createServer()
SNICallback
: Seetls.createServer()
session
<Buffer> ABuffer
instance containing a TLS session.requestOCSP
<boolean> Iftrue
, specifies that the OCSP status requestextension will be added to the client hello and an'OCSPResponse'
eventwill be emitted on the socket before establishing a secure communicationsecureContext
: TLS context object created withtls.createSecureContext()
. If asecureContext
isnot provided, onewill be created by passing the entireoptions
object totls.createSecureContext()
.tls.createSecureContext()
options that are used if thesecureContext
option is missing. Otherwise, they are ignored.Construct a newtls.TLSSocket
object from an existing TCP socket.
line
<Buffer> Line of ASCII text, in NSSSSLKEYLOGFILE
format.Thekeylog
event is emitted on a clienttls.TLSSocket
when key materialis generated or received by the socket. This keying material can be storedfor debugging, as it allows captured TLS traffic to be decrypted. It maybe emitted multiple times, before or after the handshake completes.
A typical use case is to append received lines to a common text file, whichis later used by software (such as Wireshark) to decrypt the traffic:
const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });// ...tlsSocket.on('keylog', (line) => logFile.write(line));
The'OCSPResponse'
event is emitted if therequestOCSP
option was setwhen thetls.TLSSocket
was created and an OCSP response has been received.The listener callback is passed a single argument when called:
response
<Buffer> The server's OCSP responseTypically, theresponse
is a digitally signed object from the server's CA thatcontains information about server's certificate revocation status.
The'secureConnect'
event is emitted after the handshaking process for a newconnection has successfully completed. The listener callback will be calledregardless of whether or not the server's certificate has been authorized. Itis the client's responsibility to check thetlsSocket.authorized
property todetermine if the server certificate was signed by one of the specified CAs. IftlsSocket.authorized === false
, then the error can be found by examining thetlsSocket.authorizationError
property. If ALPN was used, thetlsSocket.alpnProtocol
property can be checked to determine the negotiatedprotocol.
Returns the boundaddress
, the addressfamily
name, andport
of theunderlying socket as reported by the operating system:{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
.
Returns the reason why the peer's certificate was not been verified. Thisproperty is set only whentlsSocket.authorized === false
.
Returnstrue
if the peer certificate was signed by one of the CAs specifiedwhen creating thetls.TLSSocket
instance, otherwisefalse
.
Disables TLS renegotiation for thisTLSSocket
instance. Once called, attemptsto renegotiate will trigger an'error'
event on theTLSSocket
.
Always returnstrue
. This may be used to distinguish TLS sockets from regularnet.Socket
instances.
Returns an object representing the cipher name. Theversion
key is a legacyfield which always contains the value'TLSv1/SSLv3'
.
For example:{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }
.
SeeSSL_CIPHER_get_name()
inhttps://www.openssl.org/docs/man1.1.0/ssl/SSL_CIPHER_get_name.html for moreinformation.
Returns an object representing the type, name, and size of parameter ofan ephemeral key exchange inPerfect Forward Secrecy on a clientconnection. It returns an empty object when the key exchange is notephemeral. As this is only supported on a client socket;null
is returnedif called on a server socket. The supported types are'DH'
and'ECDH'
. Thename
property is available only when type is'ECDH'
.
For example:{ type: 'ECDH', name: 'prime256v1', size: 256 }
.
Finished
message that has beensent to the socket as part of a SSL/TLS handshake, orundefined
ifnoFinished
message has been sent yet.As theFinished
messages are message digests of the complete handshake(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they canbe used for external authentication procedures when the authenticationprovided by SSL/TLS is not desired or is not enough.
Corresponds to theSSL_get_finished
routine in OpenSSL and may be usedto implement thetls-unique
channel binding fromRFC 5929.
detailed
<boolean> Include the full certificate chain iftrue
, otherwiseinclude just the peer's certificate.Returns an object representing the peer's certificate. The returned object hassome properties corresponding to the fields of the certificate.
If the full certificate chain was requested, each certificate will include anissuerCertificate
property containing an object representing its issuer'scertificate.
{ subject: { C: 'UK', ST: 'Acknack Ltd', L: 'Rhys Jones', O: 'node.js', OU: 'Test TLS Certificate', CN: 'localhost' }, issuer: { C: 'UK', ST: 'Acknack Ltd', L: 'Rhys Jones', O: 'node.js', OU: 'Test TLS Certificate', CN: 'localhost' }, issuerCertificate: { ... another certificate, possibly with an .issuerCertificate ... }, raw: < RAW DER buffer >, pubkey: < RAW DER buffer >, valid_from: 'Nov 11 09:52:22 2009 GMT', valid_to: 'Nov 6 09:52:22 2029 GMT', fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF', fingerprint256: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF:00:11:22:33:44:55:66:77:88:99:AA:BB', serialNumber: 'B9B0D332A1AA5635' }
If the peer does not provide a certificate, an empty object will be returned.
Finished
message that is expectedor has actually been received from the socket as part of a SSL/TLS handshake,orundefined
if there is noFinished
message so far.As theFinished
messages are message digests of the complete handshake(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they canbe used for external authentication procedures when the authenticationprovided by SSL/TLS is not desired or is not enough.
Corresponds to theSSL_get_peer_finished
routine in OpenSSL and may be usedto implement thetls-unique
channel binding fromRFC 5929.
Returns a string containing the negotiated SSL/TLS protocol version of thecurrent connection. The value'unknown'
will be returned for connectedsockets that have not completed the handshaking process. The valuenull
willbe returned for server sockets or disconnected client sockets.
Protocol versions are:
'TLSv1'
'TLSv1.1'
'TLSv1.2'
'SSLv3'
Seehttps://www.openssl.org/docs/man1.1.0/ssl/SSL_get_version.html for moreinformation.
Returns the TLS session data orundefined
if no session wasnegotiated. On the client, the data can be provided to thesession
option oftls.connect()
to resume the connection. On the server, it may be usefulfor debugging.
SeeSession Resumption for more information.
For a client, returns the TLS session ticket if one is available, orundefined
. For a server, always returnsundefined
.
It may be useful for debugging.
SeeSession Resumption for more information.
true
if the session was reused,false
otherwise.SeeSession Resumption for more information.
Returns the string representation of the local IP address.
Returns the numeric representation of the local port.
Returns the string representation of the remote IP address. For example,'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
.
options
<Object>
rejectUnauthorized
<boolean> If notfalse
, the server certificate isverified against the list of supplied CAs. An'error'
event is emitted ifverification fails;err.code
contains the OpenSSL error code.Default:true
.requestCert
callback
<Function> A function that will be called when the renegotiationrequest has been completed.ThetlsSocket.renegotiate()
method initiates a TLS renegotiation process.Upon completion, thecallback
function will be passed a single argumentthat is either anError
(if the request failed) ornull
.
This method can be used to request a peer's certificate after the secureconnection has been established.
When running as the server, the socket will be destroyed with an error afterhandshakeTimeout
timeout.
size
<number> The maximum TLS fragment size. The maximum value is16384
.Default:16384
.ThetlsSocket.setMaxSendFragment()
method sets the maximum TLS fragment size.Returnstrue
if setting the limit succeeded;false
otherwise.
Smaller fragment sizes decrease the buffering latency on the client: largerfragments are buffered by the TLS layer until the entire fragment is receivedand its integrity is verified; large fragments can span multiple roundtripsand their processing can be delayed due to packet loss or reordering. However,smaller fragments add extra TLS framing bytes and CPU overhead, which maydecrease overall server throughput.
hostname
<string> The host name or IP address to verify the certificateagainst.cert
<Object> An object representing the peer's certificate. The returnedobject has some properties corresponding to the fields of the certificate.Verifies the certificatecert
is issued tohostname
.
Returns<Error> object, populating it withreason
,host
, andcert
onfailure. On success, returns<undefined>.
This function can be overwritten by providing alternative function as part oftheoptions.checkServerIdentity
option passed totls.connect()
. Theoverwriting function can calltls.checkServerIdentity()
of course, to augmentthe checks done with additional verification.
This function is only called if the certificate passed all other checks, such asbeing issued by trusted CA (options.ca
).
The cert object contains the parsed certificate and will have a structuresimilar to:
{ subject: { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ], CN: '*.nodejs.org' }, issuer: { C: 'GB', ST: 'Greater Manchester', L: 'Salford', O: 'COMODO CA Limited', CN: 'COMODO RSA Domain Validation Secure Server CA' }, subjectaltname: 'DNS:*.nodejs.org, DNS:nodejs.org', infoAccess: { 'CA Issuers - URI': [ 'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt' ], 'OCSP - URI': [ 'http://ocsp.comodoca.com' ] }, modulus: 'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1', exponent: '0x10001', pubkey: <Buffer ... >, valid_from: 'Aug 14 00:00:00 2017 GMT', valid_to: 'Nov 20 23:59:59 2019 GMT', fingerprint: '01:02:59:D9:C3:D2:0D:08:F7:82:4E:44:A4:B4:53:C5:E2:3A:87:4D', fingerprint256: '69:AE:1A:6A:D4:3D:C6:C1:1B:EA:C6:23:DE:BA:2A:14:62:62:93:5C:7A:EA:06:41:9B:0B:BC:87:CE:48:4E:02', ext_key_usage: [ '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' ], serialNumber: '66593D57F20CBC573E433381B5FEC280', raw: <Buffer ... > }
Version | Changes |
---|---|
v10.16.0 | The |
v8.0.0 | The |
v8.0.0 | The |
v5.3.0, v4.7.0 | The |
v5.0.0 | ALPN options are supported now. |
v0.11.3 | Added in: v0.11.3 |
options
<Object>
host
<string> Host the client should connect to.Default:'localhost'
.port
<number> Port the client should connect to.path
<string> Creates unix socket connection to path. If this option isspecified,host
andport
are ignored.socket
<stream.Duplex> Establish secure connection on a given socketrather than creating a new socket. Typically, this is an instance ofnet.Socket
, but anyDuplex
stream is allowed.If this option is specified,path
,host
andport
are ignored,except for certificate validation. Usually, a socket is already connectedwhen passed totls.connect()
, but it can be connected later. Note thatconnection/disconnection/destruction ofsocket
is the user'sresponsibility, callingtls.connect()
will not causenet.connect()
to becalled.rejectUnauthorized
<boolean> If notfalse
, the server certificate isverified against the list of supplied CAs. An'error'
event is emitted ifverification fails;err.code
contains the OpenSSL error code.Default:true
.ALPNProtocols
:<string[]> |<Buffer[]> |<Uint8Array[]> |<Buffer> |<Uint8Array>An array of strings,Buffer
s orUint8Array
s, or a singleBuffer
orUint8Array
containing the supported ALPN protocols.Buffer
s should havethe format[len][name][len][name]...
e.g.'\x08http/1.1\x08http/1.0'
,where thelen
byte is the length of the next protocol name. Passing anarray is usually much simpler, e.g.['http/1.1', 'http/1.0']
.Protocols earlier in the list have higher preference than those later.servername
:<string> Server name for the SNI (Server Name Indication) TLSextension. It is the name of the host being connected to, and must be a hostname, and not an IP address. It can be used by a multi-homed server tochoose the correct certificate to present to the client, see theSNICallback
option totls.createServer()
.checkServerIdentity(servername, cert)
<Function> A callback functionto be used (instead of the builtintls.checkServerIdentity()
function)when checking the server's hostname (or the providedservername
whenexplicitly set) against the certificate. This should return an<Error> ifverification fails. The method should returnundefined
if theservername
andcert
are verified.session
<Buffer> ABuffer
instance, containing TLS session.minDHSize
<number> Minimum size of the DH parameter in bits to accept aTLS connection. When a server offers a DH parameter with a size lessthanminDHSize
, the TLS connection is destroyed and an error is thrown.Default:1024
.secureContext
: TLS context object created withtls.createSecureContext()
. If asecureContext
isnot provided, onewill be created by passing the entireoptions
object totls.createSecureContext()
.lookup
:<Function> Custom lookup function.Default:dns.lookup()
.timeout
:<number> If set and if a socket is created internally, will callsocket.setTimeout(timeout)
after the socket is created, but before itstarts the connection.tls.createSecureContext()
options that are used if thesecureContext
option is missing, otherwise they are ignored.callback
<Function>Thecallback
function, if specified, will be added as a listener for the'secureConnect'
event.
tls.connect()
returns atls.TLSSocket
object.
The following illustrates a client for the echo server example fromtls.createServer()
:
// Assumes an echo server that is listening on port 8000.const tls = require('tls');const fs = require('fs');const options = { // Necessary only if the server requires client certificate authentication. key: fs.readFileSync('client-key.pem'), cert: fs.readFileSync('client-cert.pem'), // Necessary only if the server uses a self-signed certificate. ca: [ fs.readFileSync('server-cert.pem') ], // Necessary only if the server's cert isn't for "localhost". checkServerIdentity: () => { return null; },};const socket = tls.connect(8000, options, () => { console.log('client connected', socket.authorized ? 'authorized' : 'unauthorized'); process.stdin.pipe(socket); process.stdin.resume();});socket.setEncoding('utf8');socket.on('data', (data) => { console.log(data);});socket.on('end', () => { console.log('server ends connection');});
path
<string> Default value foroptions.path
.options
<Object> Seetls.connect()
.callback
<Function> Seetls.connect()
.Same astls.connect()
except thatpath
can be providedas an argument instead of an option.
A path option, if specified, will take precedence over the path argument.
port
<number> Default value foroptions.port
.host
<string> Default value foroptions.host
.options
<Object> Seetls.connect()
.callback
<Function> Seetls.connect()
.Same astls.connect()
except thatport
andhost
can be providedas arguments instead of options.
A port or host option, if specified, will take precedence over any port or hostargument.
Version | Changes |
---|---|
v10.16.0 | The |
v10.0.0 | The |
v9.3.0 | The |
v9.0.0 | The |
v7.3.0 | If the |
v5.2.0 | The |
v0.11.13 | Added in: v0.11.13 |
options
<Object>
ca
<string> |<string[]> |<Buffer> |<Buffer[]> Optionally override the trusted CAcertificates. Default is to trust the well-known CAs curated by Mozilla.Mozilla's CAs are completely replaced when CAs are explicitly specifiedusing this option. The value can be a string orBuffer
, or anArray
ofstrings and/orBuffer
s. Any string orBuffer
can contain multiple PEMCAs concatenated together. The peer's certificate must be chainable to a CAtrusted by the server for the connection to be authenticated. When usingcertificates that are not chainable to a well-known CA, the certificate's CAmust be explicitly specified as a trusted or the connection will fail toauthenticate.If the peer uses a certificate that doesn't match or chain to one of thedefault CAs, use theca
option to provide a CA certificate that the peer'scertificate can match or chain to.For self-signed certificates, the certificate is its own CA, and must beprovided.For PEM encoded certificates, supported types are "X509 CERTIFICATE", and"CERTIFICATE".cert
<string> |<string[]> |<Buffer> |<Buffer[]> Cert chains in PEM format. One certchain should be provided per private key. Each cert chain should consist ofthe PEM formatted certificate for a provided privatekey
, followed by thePEM formatted intermediate certificates (if any), in order, and notincluding the root CA (the root CA must be pre-known to the peer, seeca
).When providing multiple cert chains, they do not have to be in the sameorder as their private keys inkey
. If the intermediate certificates arenot provided, the peer will not be able to validate the certificate, and thehandshake will fail.ciphers
<string> Cipher suite specification, replacing the default. Formore information, seemodifying the default cipher suite.clientCertEngine
<string> Name of an OpenSSL engine which can provide theclient certificate.crl
<string> |<string[]> |<Buffer> |<Buffer[]> PEM formatted CRLs (CertificateRevocation Lists).dhparam
<string> |<Buffer> Diffie Hellman parameters, required forPerfect Forward Secrecy. Useopenssl dhparam
to create the parameters.The key length must be greater than or equal to 1024 bits, otherwise anerror will be thrown. It is strongly recommended to use 2048 bits or largerfor stronger security. If omitted or invalid, the parameters are silentlydiscarded and DHE ciphers will not be available.ecdhCurve
<string> A string describing a named curve or a colon separatedlist of curve NIDs or names, for exampleP-521:P-384:P-256
, to use forECDH key agreement. Set toauto
to select thecurve automatically. Usecrypto.getCurves()
to obtain a list ofavailable curve names. On recent releases,openssl ecparam -list_curves
will also display the name and description of each available elliptic curve.Default:tls.DEFAULT_ECDH_CURVE
.honorCipherOrder
<boolean> Attempt to use the server's cipher suitepreferences instead of the client's. Whentrue
, causesSSL_OP_CIPHER_SERVER_PREFERENCE
to be set insecureOptions
, seeOpenSSL Options for more information.key
<string> |<string[]> |<Buffer> |<Buffer[]> |<Object[]> Private keys in PEM format.PEM allows the option of private keys being encrypted. Encrypted keys willbe decrypted withoptions.passphrase
. Multiple keys using differentalgorithms can be provided either as an array of unencrypted key strings orbuffers, or an array of objects in the form{pem: <string|buffer>[, passphrase: <string>]}
. The object form can only occur in an array.object.passphrase
is optional. Encrypted keys will be decrypted withobject.passphrase
if provided, oroptions.passphrase
if it is not.maxVersion
<string> Optionally set the maximum TLS version to allow. OneofTLSv1.2'
,'TLSv1.1'
, or'TLSv1'
. Cannot be specified along with thesecureProtocol
option, use one or the other.Default:tls.DEFAULT_MAX_VERSION
.minVersion
<string> Optionally set the minimum TLS version to allow. OneofTLSv1.2'
,'TLSv1.1'
, or'TLSv1'
. Cannot be specified along with thesecureProtocol
option, use one or the other. It is not recommended to useless than TLSv1.2, but it may be required for interoperability.Default:tls.DEFAULT_MIN_VERSION
.passphrase
<string> Shared passphrase used for a single private key and/ora PFX.pfx
<string> |<string[]> |<Buffer> |<Buffer[]> |<Object[]> PFX or PKCS12 encodedprivate key and certificate chain.pfx
is an alternative to providingkey
andcert
individually. PFX is usually encrypted, if it is,passphrase
will be used to decrypt it. Multiple PFX can be provided eitheras an array of unencrypted PFX buffers, or an array of objects in the form{buf: <string|buffer>[, passphrase: <string>]}
. The object form can onlyoccur in an array.object.passphrase
is optional. Encrypted PFX will bedecrypted withobject.passphrase
if provided, oroptions.passphrase
ifit is not.secureOptions
<number> Optionally affect the OpenSSL protocol behavior,which is not usually necessary. This should be used carefully if at all!Value is a numeric bitmask of theSSL_OP_*
options fromOpenSSL Options.secureProtocol
<string> The TLS protocol version to use. The possiblevalues are listed asSSL_METHODS, use the function names as strings. Forexample, use'TLSv1_1_method'
to force TLS version 1.1, or'TLS_method'
to allow any TLS protocol version. It is not recommended to use TLS versionsless than 1.2, but it may be required for interoperability.Default:none, seeminVersion
.sessionIdContext
<string> Opaque identifier used by servers to ensuresession state is not shared between applications. Unused by clients.tls.createServer()
sets the default value of thehonorCipherOrder
optiontotrue
, other APIs that create secure contexts leave it unset.
tls.createServer()
uses a 128 bit truncated SHA1 hash value generatedfromprocess.argv
as the default value of thesessionIdContext
option, otherAPIs that create secure contexts have no default value.
Thetls.createSecureContext()
method creates a credentials object.
A key isrequired for ciphers that make use of certificates. Eitherkey
orpfx
can be used to provide it.
If the 'ca' option is not given, then Node.js will use the defaultpublicly trusted list of CAs as given inhttps://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt.
Version | Changes |
---|---|
v9.3.0 | The |
v8.0.0 | The |
v5.0.0 | ALPN options are supported now. |
v0.3.2 | Added in: v0.3.2 |
options
<Object>
ALPNProtocols
:<string[]> |<Buffer[]> |<Uint8Array[]> |<Buffer> |<Uint8Array>An array of strings,Buffer
s orUint8Array
s, or a singleBuffer
orUint8Array
containing the supported ALPN protocols.Buffer
s should havethe format[len][name][len][name]...
e.g.0x05hello0x05world
, where thefirst byte is the length of the next protocol name. Passing an array isusually much simpler, e.g.['hello', 'world']
.(Protocols should be ordered by their priority.)clientCertEngine
<string> Name of an OpenSSL engine which can provide theclient certificate.handshakeTimeout
<number> Abort the connection if the SSL/TLS handshakedoes not finish in the specified number of milliseconds.A'tlsClientError'
is emitted on thetls.Server
object whenevera handshake times out.Default:120000
(120 seconds).rejectUnauthorized
<boolean> If notfalse
the server will reject anyconnection which is not authorized with the list of supplied CAs. Thisoption only has an effect ifrequestCert
istrue
.Default:true
.requestCert
<boolean> Iftrue
the server will request a certificate fromclients that connect and attempt to verify that certificate.Default:false
.sessionTimeout
<number> The number of seconds after which a TLS sessioncreated by the server will no longer be resumable. SeeSession Resumption for more information.Default:300
.SNICallback(servername, cb)
<Function> A function that will be called ifthe client supports SNI TLS extension. Two arguments will be passed whencalled:servername
andcb
.SNICallback
should invokecb(null, ctx)
,wherectx
is aSecureContext
instance. (tls.createSecureContext(...)
can be used to get a properSecureContext
.) IfSNICallback
wasn'tprovided the default callback with high-level API will be used (see below).ticketKeys
:<Buffer> 48-bytes of cryptographically strong pseudo-randomdata. SeeSession Resumption for more information.tls.createSecureContext()
option can be provided. Forservers, the identity options (pfx
orkey
/cert
) are usually required.secureConnectionListener
<Function>Creates a newtls.Server
. ThesecureConnectionListener
, if provided, isautomatically set as a listener for the'secureConnection'
event.
TheticketKeys
options is automatically shared betweencluster
moduleworkers.
The following illustrates a simple echo server:
const tls = require('tls');const fs = require('fs');const options = { key: fs.readFileSync('server-key.pem'), cert: fs.readFileSync('server-cert.pem'), // This is necessary only if using client certificate authentication. requestCert: true, // This is necessary only if the client uses a self-signed certificate. ca: [ fs.readFileSync('client-cert.pem') ]};const server = tls.createServer(options, (socket) => { console.log('server connected', socket.authorized ? 'authorized' : 'unauthorized'); socket.write('welcome!\n'); socket.setEncoding('utf8'); socket.pipe(socket);});server.listen(8000, () => { console.log('server bound');});
The server can be tested by connecting to it using the example client fromtls.connect()
.
Returns an array with the names of the supported SSL ciphers.
console.log(tls.getCiphers()); // ['AES128-SHA', 'AES256-SHA', ...]
Version | Changes |
---|---|
v10.0.0 | Default value changed to |
v0.11.13 | Added in: v0.11.13 |
The default curve name to use for ECDH key agreement in a tls server. Thedefault value is'auto'
. Seetls.createSecureContext()
for furtherinformation.
maxVersion
option oftls.createSecureContext()
. It can be assigned any of the supported TLSprotocol versions,'TLSv1.2'
,'TLSv1.1'
, or'TLSv1'
.Default:'TLSv1.2'
.minVersion
option oftls.createSecureContext()
. It can be assigned any of the supported TLSprotocol versions,'TLSv1.2'
,'TLSv1.1'
, or'TLSv1'
.Default:'TLSv1'
, unless changed using CLI options. Using--tls-min-v1.0
sets the default to'TLSv1'
. Using--tls-min-v1.1
setsthe default to'TLSv1.1'
. Using--tls-min-v1.2
sets the default to'TLSv1.2'
. If multiple of the options are provided, the lowest minimum isused.tls.TLSSocket
instead.Thetls.CryptoStream
class represents a stream of encrypted data. This classis deprecated and should no longer be used.
ThecryptoStream.bytesWritten
property returns the total number of byteswritten to the underlying socketincluding the bytes required for theimplementation of the TLS protocol.
tls.TLSSocket
instead.Returned bytls.createSecurePair()
.
The'secure'
event is emitted by theSecurePair
object once a secureconnection has been established.
As with checking for the server'secureConnection'
event,pair.cleartext.authorized
should be inspected to confirm whether thecertificate used is properly authorized.
Version | Changes |
---|---|
v5.0.0 | ALPN options are supported now. |
v0.11.3 | Deprecated since: v0.11.3 |
v0.3.2 | Added in: v0.3.2 |
tls.TLSSocket
instead.context
<Object> A secure context object as returned bytls.createSecureContext()
isServer
<boolean>true
to specify that this TLS connection should beopened as a server.requestCert
<boolean>true
to specify whether a server should request acertificate from a connecting client. Only applies whenisServer
istrue
.rejectUnauthorized
<boolean> If notfalse
a server automatically rejectclients with invalid certificates. Only applies whenisServer
istrue
.options
secureContext
: A TLS context object fromtls.createSecureContext()
isServer
: Iftrue
the TLS socket will be instantiated in server-mode.Default:false
.server
<net.Server> Anet.Server
instancerequestCert
: Seetls.createServer()
rejectUnauthorized
: Seetls.createServer()
ALPNProtocols
: Seetls.createServer()
SNICallback
: Seetls.createServer()
session
<Buffer> ABuffer
instance containing a TLS session.requestOCSP
<boolean> Iftrue
, specifies that the OCSP status requestextension will be added to the client hello and an'OCSPResponse'
eventwill be emitted on the socket before establishing a secure communication.Creates a new secure pair object with two streams, one of which reads and writesthe encrypted data and the other of which reads and writes the cleartext data.Generally, the encrypted stream is piped to/from an incoming encrypted datastream and the cleartext one is used as a replacement for the initial encryptedstream.
tls.createSecurePair()
returns atls.SecurePair
object withcleartext
andencrypted
stream properties.
Usingcleartext
has the same API astls.TLSSocket
.
Thetls.createSecurePair()
method is now deprecated in favor oftls.TLSSocket()
. For example, the code:
pair = tls.createSecurePair(/* ... */);pair.encrypted.pipe(socket);socket.pipe(pair.encrypted);
can be replaced by:
secureSocket = tls.TLSSocket(socket, options);
wheresecureSocket
has the same API aspair.cleartext
.