class tls.TLSSocket extends net.Socket
Performs transparent encryption of written data and all required TLS negotiation.
Instances of tls.TLSSocket implement the duplex Stream interface.
Methods that return TLS connection metadata (e.g.
tls.TLSSocket.getPeerCertificate()) will only return data while the
connection is open.
tls.TLSSocket Constructor
History
enableTrace option is now supported.new tls.TLSSocket(socket, options?): tls.TLSSocket
net.Socket | stream.DuplexDuplex stream. On the client side, any
instance of net.Socket (for generic Duplex stream support
on the client side, tls.connect() must be used).Objecttrue the TLS socket will be
instantiated as a server. Default: false.net.Servernet.Server instance.isServer is true) may set requestCert to true to request a client
certificate.BufferBuffer instance containing a TLS session.booleantrue, specifies that the OCSP status request
extension will be added to the client hello and an 'OCSPResponse' event
will be emitted on the socket before establishing a secure communicationtls.createSecureContext(). If a secureContext is not provided, one
will be created by passing the entire options object to
tls.createSecureContext().Construct a new tls.TLSSocket object from an existing TCP socket.
BufferSSLKEYLOGFILE format.The keylog event is emitted on a tls.TLSSocket when key material
is generated or received by the socket. This keying material can be stored
for debugging, as it allows captured TLS traffic to be decrypted. It may
be emitted multiple times, before or after the handshake completes.
A typical use case is to append received lines to a common text file, which is 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 the requestOCSP option was set
when the tls.TLSSocket was created and an OCSP response has been received.
The listener callback is passed a single argument when called:
BufferTypically, the response is a digitally signed object from the server's CA that
contains information about server's certificate revocation status.
The 'secure' event is emitted after the TLS handshake has successfully
completed and a secure connection has been established.
This event is emitted on both client and server tls.TLSSocket instances,
including sockets created using the new tls.TLSSocket() constructor.
The 'secureConnect' event is emitted after the handshaking process for a new
connection has successfully completed. The listener callback will be called
regardless of whether or not the server's certificate has been authorized. It
is the client's responsibility to check the tlsSocket.authorized property to
determine if the server certificate was signed by one of the specified CAs. If
tlsSocket.authorized === false, then the error can be found by examining the
tlsSocket.authorizationError property. If ALPN was used, the
tlsSocket.alpnProtocol property can be checked to determine the negotiated
protocol.
The 'secureConnect' event is not emitted when a tls.TLSSocket is created
using the new tls.TLSSocket() constructor.
BufferThe 'session' event is emitted on a client tls.TLSSocket when a new session
or TLS ticket is available. This may or may not be before the handshake is
complete, depending on the TLS protocol version that was negotiated. The event
is not emitted on the server, or if a new session was not created, for example,
when the connection was resumed. For some TLS protocol versions the event may be
emitted multiple times, in which case all the sessions can be used for
resumption.
On the client, the session can be provided to the session option of
tls.connect() to resume the connection.
See Session Resumption for more information.
For TLSv1.2 and below, tls.TLSSocket.getSession() can be called once
the handshake is complete. For TLSv1.3, only ticket-based resumption is allowed
by the protocol, multiple tickets are sent, and the tickets aren't sent until
after the handshake completes. So it is necessary to wait for the
'session' event to get a resumable session. Applications
should use the 'session' event instead of getSession() to ensure
they will work for all TLS versions. Applications that only expect to
get or use one session should listen for this event only once:
tlsSocket.once('session', (session) => { // The session can be used immediately or later. tls.connect({ session: session, // Other connect options... }); });
tlsSocket.address(): Object
ObjectReturns the bound address, the address family name, and port of the
underlying socket as reported by the operating system:
{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.
The negotiated ALPN protocol. This is null before the handshake completes.
Once the handshake completes, it settles as either the negotiated protocol
name, or false if the peers did not negotiate an ALPN protocol.
Returns the reason why the peer's certificate was not been verified. This
property is set only when tlsSocket.authorized === false.
booleanThis property is true if the peer certificate was signed by one of the CAs
specified when creating the tls.TLSSocket instance, otherwise false.
The peer certificate is only verified during a full TLS handshake. When a
connection is established by resuming a previous session (see
Session Resumption), verification is not repeated. If the client
presented a certificate in the original handshake, authorized and
authorizationError carry the result stored with the session, including
any verification error. On TLS 1.3, a client that sent no certificate at
all can resume a session and report authorized as true, while
tls.TLSSocket.getPeerCertificate() returns an empty object. Servers
that authorize clients manually with rejectUnauthorized: false should
therefore also check tls.TLSSocket.isSessionReused() and that a peer
certificate is present.
tlsSocket.disableRenegotiation(): void
Disables TLS renegotiation for this TLSSocket instance. Once called, attempts
to renegotiate will trigger an 'error' event on the TLSSocket.
tlsSocket.enableTrace(): void
When enabled, TLS packet trace information is written to stderr. This can be
used to debug TLS connection problems.
The format of the output is identical to the output of
openssl s_client -trace or openssl s_server -trace. While it is produced by
OpenSSL's SSL_trace() function, the format is undocumented, can change
without notice, and should not be relied on.
Always returns true. This may be used to distinguish TLS sockets from regular
net.Socket instances.
tlsSocket.exportKeyingMaterial(length, label, context?): Buffer
numberstringBufferBufferKeying material is used for validations to prevent different kind of attacks in network protocols, for example in the specifications of IEEE 802.1X.
Example
const keyingMaterial = tlsSocket.exportKeyingMaterial( 128, 'client finished'); /* Example return value of keyingMaterial: <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9 12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91 74 ef 2c ... 78 more bytes> */
See the OpenSSL SSL_export_keying_material documentation for more
information.
tlsSocket.getCertificate(): Object
ObjectReturns an object representing the local certificate. The returned object has some properties corresponding to the fields of the certificate.
See tls.TLSSocket.getPeerCertificate() for an example of the certificate
structure.
If there is no local certificate, an empty object will be returned. If the
socket has been destroyed, null will be returned.
tlsSocket.getCipher(): Object
Objectstringstringstringtls.TLSSocket.getProtocol().Returns an object containing information on the negotiated cipher suite.
For example, a TLSv1.2 protocol with AES256-SHA cipher:
{ "name": "AES256-SHA", "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", "version": "SSLv3" }
See SSL_CIPHER_get_name for more information.
tlsSocket.getEphemeralKeyInfo(): Object
ObjectReturns an object describing ephemeral key agreement in perfect forward
secrecy on a client connection. It returns an empty object when the key
agreement is not ephemeral. As this is only supported on a client socket;
null is returned if called on a server socket. The supported types are 'DH',
'ECDH', and 'TLSGroup'. For 'DH' and 'ECDH', the object describes peer
temporary key parameters. For 'TLSGroup', the object identifies the negotiated
TLS Supported Group used for key agreement when a peer temporary key object is
not available.
The name property is available only when type is 'ECDH' or 'TLSGroup'. The
size property is not available when type is 'TLSGroup'. For 'TLSGroup',
name is the negotiated TLS Supported Group name. Standardized TLS group names
and code points are listed in the IANA TLS Supported Groups registry.
For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.
tlsSocket.getFinished(): Buffer | undefined
As the Finished 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 can
be used for external authentication procedures when the authentication
provided by SSL/TLS is not desired or is not enough.
Corresponds to the SSL_get_finished routine in OpenSSL and may be used
to implement the tls-unique channel binding from RFC 5929.
tlsSocket.getPeerCertificate(detailed?): Object
Returns an object representing the peer's certificate. If the peer does not
provide a certificate, an empty object will be returned. If the socket has been
destroyed, null will be returned.
If the full certificate chain was requested, each certificate will include an
issuerCertificate property containing an object representing its issuer's
certificate.
A certificate object has properties corresponding to the fields of the certificate.
booleantrue if a Certificate Authority (CA), false otherwise.BufferObjectC), StateOrProvince (ST), Locality (L), Organization (O),
OrganizationalUnit (OU), and CommonName (CN). The CommonName is typically
a DNS name with TLS certificates. Example:
{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}.Objectsubject.stringstringstring'B9B0D332A1AA5635'.string: separated hexadecimal string. Example: '2A:7A:C2:DD:...'.string: separated hexadecimal string. Example:
'2A:7A:C2:DD:...'.string: separated hexadecimal string. Example:
'2A:7A:C2:DD:...'.Arraystringsubject names.ArrayObjectThe certificate may contain information about the public key, depending on the key type.
For RSA keys, the following properties may be defined:
For EC keys, the following properties may be defined:
Buffernumber256.string'prime256v1'.string'P-256'.Example certificate:
{ 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', fingerprint512: '19:2B:3E:C3:B3:5B:32:E8:AE:BB:78:97:27:E4:BA:6C:39:C9:92:79:4F:31:46:39:E2:70:E5:5F:89:42:17:C9:E8:64:CA:FF:BB:72:56:73:6E:28:8A:92:7E:A3:2A:15:8B:C2:E0:45:CA:C3:BC:EA:40:52:EC:CA:A2:68:CB:32', 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 ... > }
tlsSocket.getPeerFinished(): Buffer | undefined
As the Finished 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 can
be used for external authentication procedures when the authentication
provided by SSL/TLS is not desired or is not enough.
Corresponds to the SSL_get_peer_finished routine in OpenSSL and may be used
to implement the tls-unique channel binding from RFC 5929.
tlsSocket.getPeerX509Certificate(): X509Certificate
X509CertificateReturns the peer certificate as an X509Certificate object.
If there is no peer certificate, or the socket has been destroyed,
undefined will be returned.
tlsSocket.getProtocol(): string | null
Returns a string containing the negotiated SSL/TLS protocol version of the
current connection. The value 'unknown' will be returned for connected
sockets that have not completed the handshaking process. The value null will
be returned for server sockets or disconnected client sockets.
Protocol versions are:
'SSLv3''TLSv1''TLSv1.1''TLSv1.2''TLSv1.3'
See the OpenSSL SSL_get_version documentation for more information.
tlsSocket.getSession(): void
BufferReturns the TLS session data or undefined if no session was
negotiated. On the client, the data can be provided to the session option of
tls.connect() to resume the connection. On the server, it may be useful
for debugging.
See Session Resumption for more information.
Note: getSession() works only for TLSv1.2 and below. For TLSv1.3, applications
must use the 'session' event (it also works for TLSv1.2 and below).
tlsSocket.getSharedSigalgs(): Array
ArraySee SSL_get_shared_sigalgs for more information.
tlsSocket.getTLSTicket(): void
BufferFor a client, returns the TLS session ticket if one is available, or
undefined. For a server, always returns undefined.
It may be useful for debugging.
See Session Resumption for more information.
tlsSocket.getX509Certificate(): X509Certificate
X509CertificateReturns the local certificate as an X509Certificate object.
If there is no local certificate, or the socket has been destroyed,
undefined will be returned.
tlsSocket.isSessionReused(): boolean
booleantrue if the session was reused, false otherwise.See Session Resumption for more information.
stringReturns the string representation of the local IP address.
integerReturns the numeric representation of the local port.
stringReturns the string representation of the remote IP address. For example,
'74.125.127.100' or '2001:4860:a005::68'.
stringReturns the string representation of the remote IP family. 'IPv4' or 'IPv6'.
integerReturns the numeric representation of the remote port. For example, 443.
tlsSocket.renegotiate(options, callback): boolean
Objectbooleanfalse, 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. Default:
true.Functionrenegotiate() returned true, callback is
attached once to the 'secure' event. If renegotiate() returned false,
callback will be called in the next tick with an error, unless the
tlsSocket has been destroyed, in which case callback will not be called
at all.booleantrue if renegotiation was initiated, false otherwise.The tlsSocket.renegotiate() method initiates a TLS renegotiation process.
Upon completion, the callback function will be passed a single argument
that is either an Error (if the request failed) or null.
This method can be used to request a peer's certificate after the secure connection has been established.
When running as the server, the socket will be destroyed with an error after
handshakeTimeout timeout.
For TLSv1.3, renegotiation cannot be initiated, it is not supported by the protocol.
The SNI (Server Name Indication) host name associated with the socket. This is
null before the handshake completes. Once the handshake completes it settles
as either the host name string, or false if SNI was not used.
tlsSocket.setKeyCert(context): void
Object | tls.SecureContextkey and
cert properties from the tls.createSecureContext() options, or a
TLS context object created with tls.createSecureContext() itself.The tlsSocket.setKeyCert() method sets the private key and certificate to use
for the socket. This is mainly useful if you wish to select a server certificate
from a TLS server's ALPNCallback.
tlsSocket.setMaxSendFragment(size?): boolean
The tlsSocket.setMaxSendFragment() method sets the maximum TLS fragment size.
Returns true if setting the limit succeeded; false otherwise.
Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput.