On this page

C

tls.TLSSocket

History
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.

new tls.TLSSocket(socket, options?): tls.TLSSocket
Attributes
On the server side, any Duplex stream. On the client side, any instance of net.Socket (for generic Duplex stream support on the client side, tls.connect() must be used).
options:Object
enableTrace:
isServer?:
The SSL/TLS protocol is asymmetrical, TLSSockets must know if they are to behave as a server or a client. If true the TLS socket will be instantiated as a server. Default: false.
server:net.Server
A net.Server instance.
requestCert:
Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (isServer is true) may set requestCert to true to request a client certificate.
rejectUnauthorized:
ALPNProtocols:
SNICallback:
ALPNCallback:
session:Buffer
A Buffer instance containing a TLS session.
requestOCSP:boolean
If true, 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 communication
secureContext:
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().

Construct a new tls.TLSSocket object from an existing TCP socket.

E

keylog

History
Attributes
line:Buffer
Line of ASCII text, in NSS SSLKEYLOGFILE 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));
E

OCSPResponse

History

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:

Attributes
response:Buffer
The server's OCSP response

Typically, the response is a digitally signed object from the server's CA that contains information about server's certificate revocation status.

E

secure

History

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.

E

secureConnect

History

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.

E

session

History
Attributes
session:Buffer

The '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
Returns:Object

Returns 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' }.

P

tlsSocket.alpnProtocol

History

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.

P

tlsSocket.authorizationError

History

Returns the reason why the peer's certificate was not been verified. This property is set only when tlsSocket.authorized === false.

P

tlsSocket.authorized

History
Type:boolean

This 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.

M

tlsSocket.disableRenegotiation

History
tlsSocket.disableRenegotiation(): void

Disables TLS renegotiation for this TLSSocket instance. Once called, attempts to renegotiate will trigger an 'error' event on the TLSSocket.

M

tlsSocket.enableTrace

History
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.

P

tlsSocket.encrypted

History

Always returns true. This may be used to distinguish TLS sockets from regular net.Socket instances.

M

tlsSocket.exportKeyingMaterial

History
tlsSocket.exportKeyingMaterial(length, label, context?): Buffer
Attributes
length:number
number of bytes to retrieve from keying material
label:string
an application specific label, typically this will be a value from the IANA Exporter Label Registry.
context:Buffer
Optionally provide a context.
Returns:Buffer
requested bytes of the keying material

Keying 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.

M

tlsSocket.getCertificate

History
tlsSocket.getCertificate(): Object
Returns:Object

Returns 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
Returns:Object
name:string
OpenSSL name for the cipher suite.
standardName:string
IETF name for the cipher suite.
version:string
The minimum TLS protocol version supported by this cipher suite. For the actual negotiated protocol, see tls.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.

M

tlsSocket.getEphemeralKeyInfo

History
tlsSocket.getEphemeralKeyInfo(): Object
Returns:Object

Returns 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 }.

M

tlsSocket.getFinished

History
tlsSocket.getFinished(): Buffer | undefined
Returns:Buffer | undefined
The latest Finished message that has been sent to the socket as part of an SSL/TLS handshake, or undefined if no Finished message has been sent yet.

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.

M

tlsSocket.getPeerCertificate

History
tlsSocket.getPeerCertificate(detailed?): Object
Attributes
detailed:boolean
Include the full certificate chain if true, otherwise include just the peer's certificate.
Returns:Object
A certificate 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.

Attributes
true if a Certificate Authority (CA), false otherwise.
raw:Buffer
The DER encoded X.509 certificate data.
subject:Object
The certificate subject, described in terms of Country (C), 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'}.
issuer:Object
The certificate issuer, described in the same terms as the subject.
valid_from:string
The date-time the certificate is valid from.
valid_to:string
The date-time the certificate is valid to.
serialNumber:string
The certificate serial number, as a hex string. Example: 'B9B0D332A1AA5635'.
fingerprint:string
The SHA-1 digest of the DER encoded certificate. It is returned as a : separated hexadecimal string. Example: '2A:7A:C2:DD:...'.
fingerprint256:string
The SHA-256 digest of the DER encoded certificate. It is returned as a : separated hexadecimal string. Example: '2A:7A:C2:DD:...'.
fingerprint512:string
The SHA-512 digest of the DER encoded certificate. It is returned as a : separated hexadecimal string. Example: '2A:7A:C2:DD:...'.
ext_key_usage:Array
(Optional) The extended key usage, a set of OIDs.
subjectaltname:string
(Optional) A string containing concatenated names for the subject, an alternative to the subject names.
infoAccess:Array
(Optional) An array describing the AuthorityInfoAccess, used with OCSP.
issuerCertificate:Object
(Optional) The issuer certificate object. For self-signed certificates, this may be a circular reference.

The certificate may contain information about the public key, depending on the key type.

For RSA keys, the following properties may be defined:

Attributes
bits:number
The RSA bit size. Example: 1024.
exponent:string
The RSA exponent, as a string in hexadecimal number notation. Example: '0x010001'.
modulus:string
The RSA modulus, as a hexadecimal string. Example: 'B56CE45CB7...'.
pubkey:Buffer
The public key.

For EC keys, the following properties may be defined:

Attributes
pubkey:Buffer
The public key.
bits:number
The key size in bits. Example: 256.
asn1Curve:string
(Optional) The ASN.1 name of the OID of the elliptic curve. Well-known curves are identified by an OID. While it is unusual, it is possible that the curve is identified by its mathematical properties, in which case it will not have an OID. Example: 'prime256v1'.
nistCurve:string
(Optional) The NIST name for the elliptic curve, if it has one (not all well-known curves have been assigned names by NIST). Example: '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 ... > }
M

tlsSocket.getPeerFinished

History
tlsSocket.getPeerFinished(): Buffer | undefined
Returns:Buffer | undefined
The latest Finished message that is expected or has actually been received from the socket as part of an SSL/TLS handshake, or undefined if there is no Finished message so far.

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.

M

tlsSocket.getPeerX509Certificate

History
tlsSocket.getPeerX509Certificate(): X509Certificate

Returns the peer certificate as an X509Certificate object.

If there is no peer certificate, or the socket has been destroyed, undefined will be returned.

M

tlsSocket.getProtocol

History
tlsSocket.getProtocol(): string | null
Returns: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.

M

tlsSocket.getSession

History
tlsSocket.getSession(): void
Type:Buffer

Returns 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).

M

tlsSocket.getSharedSigalgs

History
tlsSocket.getSharedSigalgs(): Array
Returns:Array
List of signature algorithms shared between the server and the client in the order of decreasing preference.

See SSL_get_shared_sigalgs for more information.

M

tlsSocket.getTLSTicket

History
tlsSocket.getTLSTicket(): void
Type:Buffer

For 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.

M

tlsSocket.getX509Certificate

History
tlsSocket.getX509Certificate(): X509Certificate

Returns the local certificate as an X509Certificate object.

If there is no local certificate, or the socket has been destroyed, undefined will be returned.

M

tlsSocket.isSessionReused

History
tlsSocket.isSessionReused(): boolean
Returns:boolean
true if the session was reused, false otherwise.

See Session Resumption for more information.

P

tlsSocket.localAddress

History
Type:string

Returns the string representation of the local IP address.

P

tlsSocket.localPort

History
Type:integer

Returns the numeric representation of the local port.

P

tlsSocket.remoteAddress

History
Type:string

Returns the string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'.

P

tlsSocket.remoteFamily

History
Type:string

Returns the string representation of the remote IP family. 'IPv4' or 'IPv6'.

P

tlsSocket.remotePort

History
Type:integer

Returns the numeric representation of the remote port. For example, 443.

tlsSocket.renegotiate(options, callback): boolean
Attributes
options:Object
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. Default: true.
requestCert:
callback:Function
If renegotiate() 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.
Returns:boolean
true 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.

P

tlsSocket.servername

History

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.

M

tlsSocket.setKeyCert

History
tlsSocket.setKeyCert(context): void
Attributes
An object containing at least key 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.

M

tlsSocket.setMaxSendFragment

History
tlsSocket.setMaxSendFragment(size?): boolean
Attributes
size?:number
The maximum TLS fragment size. The maximum value is 16384. Default: 16384.
Returns: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.