{ "source": "doc/api/tls.md", "modules": [ { "textRaw": "TLS (SSL)", "name": "tls_(ssl)", "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:

\n
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.

\n

Private 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:

\n
openssl genrsa -out ryans-key.pem 2048\n
\n

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

\n

The OpenSSL command-line interface can be used to generate a CSR for a private\nkey:

\n
openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem\n
\n

Once the CSR file is generated, it can either be sent to a Certificate\nAuthority for signing or used to generate a self-signed certificate.

\n

Creating a self-signed certificate using the OpenSSL command-line interface\nis illustrated in the example below:

\n
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem\n
\n

Once the certificate is generated, it can be used to generate a .pfx or\n.p12 file:

\n
openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \\\n      -certfile ca-cert.pem -out ryans.pfx\n
\n

Where:

\n\n", "miscs": [ { "textRaw": "Perfect Forward Secrecy", "name": "Perfect Forward Secrecy", "type": "misc", "desc": "

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.

\n

Perfect 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".

\n

Currently two methods are commonly used to achieve Perfect Forward Secrecy (note\nthe character "E" appended to the traditional abbreviations):

\n\n

Ephemeral methods may have some performance drawbacks, because key generation\nis expensive.

\n

To 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:

\n
openssl dhparam -outform PEM -out dhparam.pem 2048\n
\n

If 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 name of an alternative\ncurve to use, see tls.createServer() for more info.

\n" }, { "textRaw": "ALPN, NPN and SNI", "name": "ALPN, NPN and SNI", "type": "misc", "desc": "

ALPN (Application-Layer Protocol Negotiation Extension), NPN (Next\nProtocol Negotiation) and, SNI (Server Name Indication) are TLS\nhandshake extensions:

\n\n

Note: 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.

\n

To 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:

\n\n

Note: The default renegotiation limits should not be modified without a full\nunderstanding of the implications and risks.

\n

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

\n" } ], "type": "module", "displayName": "TLS/SSL Concepts" }, { "textRaw": "Modifying the Default TLS Cipher suite", "name": "modifying_the_default_tls_cipher_suite", "desc": "

Node.js is built with a default suite of enabled and disabled TLS ciphers.\nCurrently, the default cipher suite is:

\n
ECDHE-RSA-AES128-GCM-SHA256:\nECDHE-ECDSA-AES128-GCM-SHA256:\nECDHE-RSA-AES256-GCM-SHA384:\nECDHE-ECDSA-AES256-GCM-SHA384:\nDHE-RSA-AES128-GCM-SHA256:\nECDHE-RSA-AES128-SHA256:\nDHE-RSA-AES128-SHA256:\nECDHE-RSA-AES256-SHA384:\nDHE-RSA-AES256-SHA384:\nECDHE-RSA-AES256-SHA256:\nDHE-RSA-AES256-SHA256:\nHIGH:\n!aNULL:\n!eNULL:\n!EXPORT:\n!DES:\n!RC4:\n!MD5:\n!PSK:\n!SRP:\n!CAMELLIA\n
\n

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

\n
node --tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4"\n
\n

The 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.TLSSockets.

\n

Consult OpenSSL cipher list format documentation for details on the format.

\n

Note: 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.

\n

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.

\n

128 bit AES is preferred over 192 and 256 bit AES in light of specific\nattacks affecting larger AES key sizes.

\n

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

\n", "properties": [ { "textRaw": "cryptoStream.bytesWritten", "name": "bytesWritten", "meta": { "added": [ "v0.3.4" ], "deprecated": [ "v0.11.3" ], "changes": [] }, "desc": "

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.

\n" } ] }, { "textRaw": "Class: SecurePair", "type": "class", "name": "SecurePair", "meta": { "added": [ "v0.3.2" ], "deprecated": [ "v0.11.3" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", "desc": "

Returned by tls.createSecurePair().

\n", "events": [ { "textRaw": "Event: 'secure'", "type": "event", "name": "secure", "meta": { "added": [ "v0.3.2" ], "deprecated": [ "v0.11.3" ], "changes": [] }, "desc": "

The 'secure' event is emitted by the SecurePair object once a secure\nconnection has been established.

\n

As with checking for the server secureConnection\nevent, pair.cleartext.authorized should be inspected to confirm whether the\ncertificate used is properly authorized.

\n", "params": [] } ] } ], "methods": [ { "textRaw": "tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])", "type": "method", "name": "createSecurePair", "meta": { "added": [ "v0.3.2" ], "deprecated": [ "v0.11.3" ], "changes": [ { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/2564", "description": "ALPN options are supported now." } ] }, "stability": 0, "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", "signatures": [ { "params": [ { "textRaw": "`context` {Object} A secure context object as returned by `tls.createSecureContext()` ", "name": "context", "type": "Object", "desc": "A secure context object as returned by `tls.createSecureContext()`", "optional": true }, { "textRaw": "`isServer` {boolean} `true` to specify that this TLS connection should be opened as a server. ", "name": "isServer", "type": "boolean", "desc": "`true` to specify that this TLS connection should be opened as a server.", "optional": true }, { "textRaw": "`requestCert` {boolean} `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. ", "name": "requestCert", "type": "boolean", "desc": "`true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`.", "optional": true }, { "textRaw": "`rejectUnauthorized` {boolean} `true` to specify whether a server should automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. ", "name": "rejectUnauthorized", "type": "boolean", "desc": "`true` to specify whether a server should automatically reject clients with invalid certificates. Only applies when `isServer` is `true`.", "optional": true }, { "textRaw": "`options` ", "options": [ { "textRaw": "`secureContext`: An optional TLS context object from [`tls.createSecureContext()`][] ", "name": "secureContext", "desc": "An optional TLS context object from [`tls.createSecureContext()`][]" }, { "textRaw": "`isServer`: If `true` the TLS socket will be instantiated in server-mode. Defaults to `false`. ", "name": "isServer", "desc": "If `true` the TLS socket will be instantiated in server-mode. Defaults to `false`." }, { "textRaw": "`server` {net.Server} An optional [`net.Server`][] instance ", "name": "server", "type": "net.Server", "desc": "An optional [`net.Server`][] instance" }, { "textRaw": "`requestCert`: Optional, see [`tls.createServer()`][] ", "name": "requestCert", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`rejectUnauthorized`: Optional, see [`tls.createServer()`][] ", "name": "rejectUnauthorized", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`NPNProtocols`: Optional, see [`tls.createServer()`][] ", "name": "NPNProtocols", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`ALPNProtocols`: Optional, see [`tls.createServer()`][] ", "name": "ALPNProtocols", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`SNICallback`: Optional, see [`tls.createServer()`][] ", "name": "SNICallback", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`session` {Buffer} An optional `Buffer` instance containing a TLS session. ", "name": "session", "type": "Buffer", "desc": "An optional `Buffer` instance containing a TLS session." }, { "textRaw": "`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 ", "name": "requestOCSP", "type": "boolean", "desc": "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" } ], "name": "options", "optional": true } ] }, { "params": [ { "name": "context", "optional": true }, { "name": "isServer", "optional": true }, { "name": "requestCert", "optional": true }, { "name": "rejectUnauthorized", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

Creates a new secure pair object with two streams, one of which reads and writes\nthe encrypted data and the other of which reads and writes the cleartext data.\nGenerally, the encrypted stream is piped to/from an incoming encrypted data\nstream and the cleartext one is used as a replacement for the initial encrypted\nstream.

\n

tls.createSecurePair() returns a tls.SecurePair object with cleartext and\nencrypted stream properties.

\n

Note: cleartext has the same API as tls.TLSSocket.

\n

Note: The tls.createSecurePair() method is now deprecated in favor of\ntls.TLSSocket(). For example, the code:

\n
pair = tls.createSecurePair( ... );\npair.encrypted.pipe(socket);\nsocket.pipe(pair.encrypted);\n
\n

can be replaced by:

\n
secure_socket = tls.TLSSocket(socket, options);\n
\n

where secure_socket has the same API as pair.cleartext.

\n" } ], "type": "module", "displayName": "Deprecated APIs" } ], "classes": [ { "textRaw": "Class: tls.Server", "type": "class", "name": "tls.Server", "meta": { "added": [ "v0.3.2" ], "changes": [] }, "desc": "

The tls.Server class is a subclass of net.Server that accepts encrypted\nconnections using TLS or SSL.

\n", "events": [ { "textRaw": "Event: 'newSession'", "type": "event", "name": "newSession", "meta": { "added": [ "v0.9.2" ], "changes": [] }, "desc": "

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:

\n\n

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:

\n\n

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.

\n

Alternatively, callback(null, null) may be called, indicating that there was\nno OCSP response.

\n

Calling callback(err) will result in a socket.destroy(err) call.

\n

The typical flow of an OCSP Request is as follows:

\n
    \n
  1. Client connects to the server and sends an 'OCSPRequest' (via the status\ninfo extension in ClientHello).
  2. \n
  3. Server receives the request and emits the 'OCSPRequest' event, calling the\nlistener if registered.
  4. \n
  5. Server extracts the OCSP URL from either the certificate or issuer and\nperforms an OCSP request to the CA.
  6. \n
  7. Server receives OCSPResponse from the CA and sends it back to the client\nvia the callback argument
  8. \n
  9. Client validates the response and either destroys the socket or performs a\nhandshake.
  10. \n
\n

Note: 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.)

\n

Note: Listening for this event will have an effect only on connections\nestablished after the addition of the event listener.

\n

Note: 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:

\n\n

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.

\n

Note: Listening for this event will have an effect only on connections\nestablished after the addition of the event listener.

\n

The following illustrates resuming a TLS session:

\n
const 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:

\n\n

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.

\n

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.

\n

When ALPN has no selected protocol, tlsSocket.alpnProtocol returns false.

\n

The tlsSocket.servername property is a string containing the server name\nrequested via SNI.

\n", "params": [] }, { "textRaw": "Event: 'tlsClientError'", "type": "event", "name": "tlsClientError", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "desc": "

The 'tlsClientError' event is emitted when an error occurs before a secure\nconnection is established. The listener callback is passed two arguments when\ncalled:

\n\n", "params": [] } ], "methods": [ { "textRaw": "server.addContext(hostname, context)", "type": "method", "name": "addContext", "meta": { "added": [ "v0.5.3" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string} A SNI hostname or wildcard (e.g. `'*'`) ", "name": "hostname", "type": "string", "desc": "A SNI hostname or wildcard (e.g. `'*'`)" }, { "textRaw": "`context` {Object} An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc). ", "name": "context", "type": "Object", "desc": "An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc)." } ] }, { "params": [ { "name": "hostname" }, { "name": "context" } ] } ], "desc": "

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

\n" }, { "textRaw": "server.address()", "type": "method", "name": "address", "meta": { "added": [ "v0.6.0" ], "changes": [] }, "desc": "

Returns the bound address, the address family name, and port of the\nserver as reported by the operating system. See net.Server.address() for\nmore information.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "meta": { "added": [ "v0.3.2" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function} An optional listener callback that will be registered to listen for the server instance's `'close'` event. ", "name": "callback", "type": "Function", "desc": "An optional listener callback that will be registered to listen for the server instance's `'close'` event.", "optional": true } ] }, { "params": [ { "name": "callback", "optional": true } ] } ], "desc": "

The server.close() method stops the server from accepting new connections.

\n

This function operates asynchronously. The 'close' event will be emitted\nwhen the server has no more open connections.

\n" }, { "textRaw": "server.getTicketKeys()", "type": "method", "name": "getTicketKeys", "meta": { "added": [ "v3.0.0" ], "changes": [] }, "desc": "

Returns a Buffer instance holding the keys currently used for\nencryption/decryption of the TLS Session Tickets

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.listen(port[, hostname][, callback])", "type": "method", "name": "listen", "meta": { "added": [ "v0.3.2" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`port` {number} The TCP/IP port on which to begin listening for connections. A value of `0` (zero) will assign a random port. ", "name": "port", "type": "number", "desc": "The TCP/IP port on which to begin listening for connections. A value of `0` (zero) will assign a random port." }, { "textRaw": "`hostname` {string} The hostname, IPv4, or IPv6 address on which to begin listening for connections. If `undefined`, the server will accept connections on any IPv6 address (`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. ", "name": "hostname", "type": "string", "desc": "The hostname, IPv4, or IPv6 address on which to begin listening for connections. If `undefined`, the server will accept connections on any IPv6 address (`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise.", "optional": true }, { "textRaw": "`callback` {Function} A callback function to be invoked when the server has begun listening on the `port` and `hostname`. ", "name": "callback", "type": "Function", "desc": "A callback function to be invoked when the server has begun listening on the `port` and `hostname`.", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "hostname", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

The server.listen() methods instructs the server to begin accepting\nconnections on the specified port and hostname.

\n

This function operates asynchronously. If the callback is given, it will be\ncalled when the server has started listening.

\n

See net.Server for more information.

\n" }, { "textRaw": "server.setTicketKeys(keys)", "type": "method", "name": "setTicketKeys", "meta": { "added": [ "v3.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`keys` {Buffer} The keys used for encryption/decryption of the [TLS Session Tickets][]. ", "name": "keys", "type": "Buffer", "desc": "The keys used for encryption/decryption of the [TLS Session Tickets][]." } ] }, { "params": [ { "name": "keys" } ] } ], "desc": "

Updates the keys for encryption/decryption of the TLS Session Tickets.

\n

Note: The key's Buffer should be 48 bytes long. See ticketKeys option in\ntls.createServer for\nmore information on how it is used.

\n

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" ], "changes": [] }, "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.

\n

Instances of tls.TLSSocket implement the duplex Stream interface.

\n

Note: Methods that return TLS connection metadata (e.g.\ntls.TLSSocket.getPeerCertificate() will only return data while the\nconnection is open.

\n", "methods": [ { "textRaw": "new tls.TLSSocket(socket[, options])", "type": "method", "name": "TLSSocket", "meta": { "added": [ "v0.11.4" ], "changes": [ { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/2564", "description": "ALPN options are supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`socket` {net.Socket} An instance of [`net.Socket`][] ", "name": "socket", "type": "net.Socket", "desc": "An instance of [`net.Socket`][]" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`isServer`: The SSL/TLS protocol is asymetrical, 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. Defaults to `false`. ", "name": "isServer", "desc": "The SSL/TLS protocol is asymetrical, 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. Defaults to `false`." }, { "textRaw": "`server` {net.Server} An optional [`net.Server`][] instance. ", "name": "server", "type": "net.Server", "desc": "An optional [`net.Server`][] instance." }, { "textRaw": "`requestCert`: Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (`isServer` is true) may optionally set `requestCert` to true to request a client certificate. ", "name": "requestCert", "desc": "Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (`isServer` is true) may optionally set `requestCert` to true to request a client certificate." }, { "textRaw": "`rejectUnauthorized`: Optional, see [`tls.createServer()`][] ", "name": "rejectUnauthorized", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`NPNProtocols`: Optional, see [`tls.createServer()`][] ", "name": "NPNProtocols", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`ALPNProtocols`: Optional, see [`tls.createServer()`][] ", "name": "ALPNProtocols", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`SNICallback`: Optional, see [`tls.createServer()`][] ", "name": "SNICallback", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`session` {Buffer} An optional `Buffer` instance containing a TLS session. ", "name": "session", "type": "Buffer", "desc": "An optional `Buffer` instance containing a TLS session." }, { "textRaw": "`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 ", "name": "requestOCSP", "type": "boolean", "desc": "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" }, { "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()`. *Note*: In effect, all [`tls.createSecureContext()`][] options can be provided, but they will be _completely ignored_ unless the `secureContext` option is missing. ", "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()`. *Note*: In effect, all [`tls.createSecureContext()`][] options can be provided, but they will be _completely ignored_ unless the `secureContext` option is missing." }, { "textRaw": "...: Optional [`tls.createSecureContext()`][] options can be provided, see the `secureContext` option for more information. ", "name": "...", "desc": "Optional [`tls.createSecureContext()`][] options can be provided, see the `secureContext` option for more information." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "socket" }, { "name": "options", "optional": true } ] } ], "desc": "

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

\n" }, { "textRaw": "tlsSocket.address()", "type": "method", "name": "address", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

Returns the bound address, the address family name, and port of the\nunderlying socket as reported by the operating system. Returns an\nobject with three properties, e.g.,\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getCipher()", "type": "method", "name": "getCipher", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

Returns an object representing the cipher name and the SSL/TLS protocol version\nthat first defined the cipher.

\n

For example: { name: 'AES256-SHA', version: 'TLSv1/SSLv3' }

\n

See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in\nhttps://www.openssl.org/docs/man1.0.2/ssl/SSL_CIPHER_get_name.html for more\ninformation.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getEphemeralKeyInfo()", "type": "method", "name": "getEphemeralKeyInfo", "meta": { "added": [ "v5.0.0" ], "changes": [] }, "desc": "

Returns an object representing the type, name, and size of parameter of\nan ephemeral key exchange in Perfect Forward Secrecy on a client\nconnection. It returns an empty object when the key exchange is not\nephemeral. As this is only supported on a client socket; 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'.

\n

For Example: { type: 'ECDH', name: 'prime256v1', size: 256 }

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getPeerCertificate([ detailed ])", "type": "method", "name": "getPeerCertificate", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`detailed` {boolean} Include the full certificate chain if `true`, otherwise include just the peer's certificate. ", "name": "detailed", "type": "boolean", "desc": "Include the full certificate chain if `true`, otherwise include just the peer's certificate.", "optional": true } ] }, { "params": [ { "name": "detailed", "optional": true } ] } ], "desc": "

Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the fields of the certificate.

\n

If the full certificate chain was requested, each certificate will include a\nissuerCertificate property containing an object representing its issuer's\ncertificate.

\n

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
\n

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

\n

Example responses include:

\n\n

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.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getTLSTicket()", "type": "method", "name": "getTLSTicket", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

Returns the TLS session ticket or undefined if no session was negotiated.

\n

Note: This only works with client TLS sockets. Useful only for debugging, for\nsession reuse provide session option to tls.connect().

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.renegotiate(options, callback)", "type": "method", "name": "renegotiate", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`rejectUnauthorized` {boolean} ", "name": "rejectUnauthorized", "type": "boolean" }, { "textRaw": "`requestCert` ", "name": "requestCert" } ], "name": "options", "type": "Object" }, { "textRaw": "`callback` {Function} A function that will be called when the renegotiation request has been completed. ", "name": "callback", "type": "Function", "desc": "A function that will be called when the renegotiation request has been completed." } ] }, { "params": [ { "name": "options" }, { "name": "callback" } ] } ], "desc": "

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.

\n

Note: This method can be used to request a peer's certificate after the\nsecure connection has been established.

\n

Note: When running as the server, the socket will be destroyed with an error\nafter handshakeTimeout timeout.

\n" }, { "textRaw": "tlsSocket.setMaxSendFragment(size)", "type": "method", "name": "setMaxSendFragment", "meta": { "added": [ "v0.11.11" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`size` {number} The maximum TLS fragment size. Defaults to `16384`. The maximum value is `16384`. ", "name": "size", "type": "number", "desc": "The maximum TLS fragment size. Defaults to `16384`. The maximum value is `16384`." } ] }, { "params": [ { "name": "size" } ] } ], "desc": "

The tlsSocket.setMaxSendFragment() method sets the maximum TLS fragment size.\nReturns true if setting the limit succeeded; false otherwise.

\n

Smaller fragment sizes decrease the buffering latency on the client: larger\nfragments are buffered by the TLS layer until the entire fragment is received\nand its integrity is verified; large fragments can span multiple roundtrips\nand their processing can be delayed due to packet loss or reordering. However,\nsmaller fragments add extra TLS framing bytes and CPU overhead, which may\ndecrease overall server throughput.

\n" } ], "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:

\n\n

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

\n", "params": [] }, { "textRaw": "Event: 'secureConnect'", "type": "event", "name": "secureConnect", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

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.

\n", "params": [] } ], "properties": [ { "textRaw": "tlsSocket.authorizationError", "name": "authorizationError", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

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

\n" }, { "textRaw": "tlsSocket.authorized", "name": "authorized", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

Returns true if the peer certificate was signed by one of the CAs specified\nwhen creating the tls.TLSSocket instance, otherwise false.

\n" }, { "textRaw": "tlsSocket.encrypted", "name": "encrypted", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

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

\n" }, { "textRaw": "tlsSocket.localAddress", "name": "localAddress", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

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

\n" }, { "textRaw": "tlsSocket.remoteFamily", "name": "remoteFamily", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

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

\n" }, { "textRaw": "tlsSocket.remotePort", "name": "remotePort", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

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

\n" } ] } ], "methods": [ { "textRaw": "tls.connect(options[, callback])", "type": "method", "name": "connect", "meta": { "added": [ "v0.11.3" ], "changes": [ { "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` {net.Socket} Establish secure connection on a given socket rather than creating a new socket. If this option is specified, `path`, `host` and `port` are ignored. 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": "net.Socket", "desc": "Establish secure connection on a given socket rather than creating a new socket. If this option is specified, `path`, `host` and `port` are ignored. 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 `true`, 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 `true`, 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[]} An array of strings or `Buffer`s 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[]", "desc": "An array of strings or `Buffer`s 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[]} An array of strings or `Buffer`s 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: `['hello', 'world']`.) ", "name": "ALPNProtocols", "type": "string[]|Buffer[]", "desc": "An array of strings or `Buffer`s 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: `['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 when checking the server's hostname against the certificate. This should throw 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 when checking the server's hostname against the certificate. This should throw 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()`. *Note*: In effect, all [`tls.createSecureContext()`][] options can be provided, but they will be _completely ignored_ unless the `secureContext` option is missing. ", "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()`. *Note*: In effect, all [`tls.createSecureContext()`][] options can be provided, but they will be _completely ignored_ unless the `secureContext` option is missing." }, { "textRaw": "...: Optional [`tls.createSecureContext()`][] options can be provided, see the `secureContext` option for more information. ", "name": "...", "desc": "Optional [`tls.createSecureContext()`][] options can be provided, see the `secureContext` option for more information." } ], "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.

\n

tls.connect() returns a tls.TLSSocket object.

\n

The following implements a simple "echo server" example:

\n
const 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
\n

Or

\n
const 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.

\n

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.

\n

Note: A port or host option, if specified, will take precedence over any port\nor 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|Buffer} 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. ", "name": "pfx", "type": "string|Buffer", "desc": "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." }, { "textRaw": "`key` {string|string[]|Buffer|Buffer[]|Object[]} Optional private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with `options.passphrase`. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form `{pem: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted keys will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not. ", "name": "key", "type": "string|string[]|Buffer|Buffer[]|Object[]", "desc": "Optional private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with `options.passphrase`. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form `{pem: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted keys will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not." }, { "textRaw": "`passphrase` {string} Optional shared passphrase used for a single private key and/or a PFX. ", "name": "passphrase", "type": "string", "desc": "Optional shared passphrase used for a single private key and/or a PFX." }, { "textRaw": "`cert` {string|string[]|Buffer|Buffer[]} Optional cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private `key`, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see `ca`). When providing multiple cert chains, they do not have to be in the same order as their private keys in `key`. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail. ", "name": "cert", "type": "string|string[]|Buffer|Buffer[]", "desc": "Optional cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private `key`, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see `ca`). When providing multiple cert chains, they do not have to be in the same order as their private keys in `key`. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail." }, { "textRaw": "`ca` {string|string[]|Buffer|Buffer[]} Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. The value can be a string or Buffer, or an Array of strings and/or Buffers. Any string or Buffer can contain multiple PEM CAs concatenated together. The peer's certificate must be chainable to a CA trusted by the server for the connection to be authenticated. When using certificates that are not chainable to a well-known CA, the certificate's CA must be explicitly specified as a trusted or the connection will fail to authenticate. If the peer uses a certificate that doesn't match or chain to one of the default CAs, use the `ca` option to provide a CA certificate that the peer's certificate can match or chain to. For self-signed certificates, the certificate is its own CA, and must be provided. ", "name": "ca", "type": "string|string[]|Buffer|Buffer[]", "desc": "Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. The value can be a string or Buffer, or an Array of strings and/or Buffers. Any string or Buffer can contain multiple PEM CAs concatenated together. The peer's certificate must be chainable to a CA trusted by the server for the connection to be authenticated. When using certificates that are not chainable to a well-known CA, the certificate's CA must be explicitly specified as a trusted or the connection will fail to authenticate. If the peer uses a certificate that doesn't match or chain to one of the default CAs, use the `ca` option to provide a CA certificate that the peer's certificate can match or chain to. For self-signed certificates, the certificate is its own CA, and must be provided." }, { "textRaw": "`crl` {string|string[]|Buffer|Buffer[]} Optional PEM formatted CRLs (Certificate Revocation Lists). ", "name": "crl", "type": "string|string[]|Buffer|Buffer[]", "desc": "Optional PEM formatted CRLs (Certificate Revocation Lists)." }, { "textRaw": "`ciphers` {string} Optional cipher suite specification, replacing the default. For more information, see [modifying the default cipher suite][]. ", "name": "ciphers", "type": "string", "desc": "Optional cipher suite specification, replacing the default. For more information, see [modifying the default cipher suite][]." }, { "textRaw": "`honorCipherOrder` {boolean} Attempt to use the server's cipher suite preferences instead of the client's. When `true`, causes `SSL_OP_CIPHER_SERVER_PREFERENCE` to be set in `secureOptions`, see [OpenSSL Options][] for more information. *Note*: [`tls.createServer()`][] sets the default value to `true`, other APIs that create secure contexts leave it unset. ", "name": "honorCipherOrder", "type": "boolean", "desc": "Attempt to use the server's cipher suite preferences instead of the client's. When `true`, causes `SSL_OP_CIPHER_SERVER_PREFERENCE` to be set in `secureOptions`, see [OpenSSL Options][] for more information. *Note*: [`tls.createServer()`][] sets the default value to `true`, other APIs that create secure contexts leave it unset." }, { "textRaw": "`ecdhCurve` {string} A string describing a named curve to use for ECDH key agreement or `false` to disable ECDH. Defaults to [`tls.DEFAULT_ECDH_CURVE`]. Use [`crypto.getCurves()`][] to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve. ", "name": "ecdhCurve", "type": "string", "desc": "A string describing a named curve to use for ECDH key agreement or `false` to disable ECDH. Defaults to [`tls.DEFAULT_ECDH_CURVE`]. Use [`crypto.getCurves()`][] to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve." }, { "textRaw": "`dhparam` {string|Buffer} Diffie Hellman parameters, required for [Perfect Forward Secrecy][]. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits, otherwise an error will be thrown. It is strongly recommended to use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. ", "name": "dhparam", "type": "string|Buffer", "desc": "Diffie Hellman parameters, required for [Perfect Forward Secrecy][]. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits, otherwise an error will be thrown. It is strongly recommended to use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available." }, { "textRaw": "`secureProtocol` {string} Optional SSL method to use, default is `\"SSLv23_method\"`. The possible values are listed as [SSL_METHODS][], use the function names as strings. For example, `\"SSLv3_method\"` to force SSL version 3. ", "name": "secureProtocol", "type": "string", "desc": "Optional SSL method to use, default is `\"SSLv23_method\"`. The possible values are listed as [SSL_METHODS][], use the function names as strings. For example, `\"SSLv3_method\"` to force SSL version 3." }, { "textRaw": "`secureOptions` {number} Optionally affect the OpenSSL protocol behaviour, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the `SSL_OP_*` options from [OpenSSL Options][]. ", "name": "secureOptions", "type": "number", "desc": "Optionally affect the OpenSSL protocol behaviour, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the `SSL_OP_*` options from [OpenSSL Options][]." }, { "textRaw": "`sessionIdContext` {string} Optional opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients. *Note*: [`tls.createServer()`][] uses a 128 bit truncated SHA1 hash value generated from `process.argv`, other APIs that create secure contexts have no default value. ", "name": "sessionIdContext", "type": "string", "desc": "Optional opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients. *Note*: [`tls.createServer()`][] uses a 128 bit truncated SHA1 hash value generated from `process.argv`, other APIs that create secure contexts have no default value." } ], "name": "options", "type": "Object" } ] }, { "params": [ { "name": "options" } ] } ], "desc": "

The tls.createSecureContext() method creates a credentials object.

\n

A key is required for ciphers that make use of certificates. Either key or\npfx can be used to provide it.

\n

If the 'ca' option is not given, then Node.js will use the default\npublicly trusted list of CAs as given in\nhttp://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.

\n" }, { "textRaw": "tls.createServer([options][, secureConnectionListener])", "type": "method", "name": "createServer", "meta": { "added": [ "v0.3.2" ], "changes": [ { "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 `'clientError'` 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 `'clientError'` 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 `true` 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 `false`. ", "name": "rejectUnauthorized", "type": "boolean", "desc": "If `true` 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 `false`." }, { "textRaw": "`NPNProtocols` {string[]|Buffer} An array of strings or a `Buffer` naming possible NPN protocols. (Protocols should be ordered by their priority.) ", "name": "NPNProtocols", "type": "string[]|Buffer", "desc": "An array of strings or a `Buffer` naming possible NPN protocols. (Protocols should be ordered by their priority.)" }, { "textRaw": "`ALPNProtocols` {string[]|Buffer} An array of strings or a `Buffer` naming possible ALPN protocols. (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", "desc": "An array of strings or a `Buffer` naming possible ALPN protocols. (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. *Note* that this is automatically shared between `cluster` module workers. ", "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. *Note* that this is automatically shared between `cluster` module workers." }, { "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.

\n

The following illustrates a simple echo server:

\n
const 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
\n

Or

\n
const 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
\n

This server can be tested by connecting to it using openssl s_client:

\n
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.

\n

For example:

\n
console.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.

\n" } ], "type": "module", "displayName": "TLS (SSL)" } ] }