{ "source": "doc/api/tls.markdown", "modules": [ { "textRaw": "TLS (SSL)", "name": "tls_(ssl)", "stability": 2, "stabilityText": "Stable", "desc": "

Use require('tls') to access this module.\n\n

\n

The tls module uses OpenSSL to provide Transport Layer Security and/or\nSecure Socket Layer: encrypted stream communication.\n\n

\n

TLS/SSL is a public/private key infrastructure. Each client and each\nserver must have a private key. A private key is created like this:\n\n

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

All servers and some clients need to have a certificate. Certificates are public\nkeys signed by a Certificate Authority or self-signed. The first step to\ngetting a certificate is to create a "Certificate Signing Request" (CSR)\nfile. This is done with:\n\n

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

To create a self-signed certificate with the CSR, do this:\n\n

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

Alternatively you can send the CSR to a Certificate Authority for signing.\n\n

\n

For Perfect Forward Secrecy, it is required to generate Diffie-Hellman\nparameters:\n\n

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

To create a .pfx or .p12, do this:\n\n

\n
openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \\\n      -certfile ca-cert.pem -out agent5.pfx
\n\n", "miscs": [ { "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

\n\n" }, { "textRaw": "Client-initiated renegotiation attack mitigation", "name": "Client-initiated renegotiation attack mitigation", "type": "misc", "desc": "

The TLS protocol lets the client renegotiate certain aspects of the TLS session.\nUnfortunately, session renegotiation requires a disproportionate amount of\nserver-side resources, which makes it a potential vector for denial-of-service\nattacks.\n\n

\n

To mitigate this, renegotiation is limited to three times every 10 minutes. An\nerror is emitted on the [tls.TLSSocket][] instance when the threshold is\nexceeded. These limits are configurable:\n\n

\n\n

Do not change the defaults without a full understanding of the implications.\n\n

\n

To test the server, connect to it with openssl s_client -connect address:port\nand tap R<CR> (i.e., the letter R followed by a carriage return) a few\ntimes.\n\n

\n" }, { "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. Practically it means that even if\nthe private key of a server is compromised, communication can only be\ndecrypted by eavesdroppers if they manage to obtain the key-pair specifically\ngenerated for each session.\n\n

\n

This is achieved by randomly generating a key pair for key-agreement on every\nhandshake (in contrast to using the same key for all sessions). Methods\nimplementing this technique, thus offering Perfect Forward Secrecy, are\ncalled "ephemeral".\n\n

\n

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

\n\n

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

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

\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

This default can be overriden 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\n

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

Note that 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 should by used only if\nabsolutely necessary.\n\n

\n", "type": "module", "displayName": "Modifying the Default TLS Cipher suite" } ], "classes": [ { "textRaw": "Class: CryptoStream", "type": "class", "name": "CryptoStream", "stability": 0, "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", "desc": "

This is an encrypted stream.\n\n

\n", "properties": [ { "textRaw": "cryptoStream.bytesWritten", "name": "bytesWritten", "desc": "

A proxy to the underlying socket's bytesWritten accessor, this will return\nthe total bytes written to the socket, including the TLS overhead.\n\n

\n" } ] }, { "textRaw": "Class: SecurePair", "type": "class", "name": "SecurePair", "desc": "

Returned by tls.createSecurePair.\n\n

\n", "events": [ { "textRaw": "Event: 'secure'", "type": "event", "name": "secure", "desc": "

This event is emitted from the SecurePair once the pair has successfully\nestablished a secure connection.\n\n

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

\n", "params": [] } ] }, { "textRaw": "Class: tls.Server", "type": "class", "name": "tls.Server", "desc": "

This class is a subclass of net.Server and has the same methods on it.\nInstead of accepting only raw TCP connections, this accepts encrypted\nconnections using TLS or SSL.\n\n

\n", "events": [ { "textRaw": "Event: 'clientError'", "type": "event", "name": "clientError", "desc": "

function (exception, tlsSocket) { }\n\n

\n

When a client connection emits an 'error' event before a secure connection is\nestablished it will be forwarded here.\n\n

\n

tlsSocket is the [tls.TLSSocket][] that the error originated from.\n\n

\n", "params": [] }, { "textRaw": "Event: 'newSession'", "type": "event", "name": "newSession", "desc": "

function (sessionId, sessionData, callback) { }\n\n

\n

Emitted on creation of a TLS session. May be used to store sessions in external\nstorage. callback must be invoked eventually, otherwise no data will be\nsent or received from the secure connection.\n\n

\n

NOTE: adding this event listener will only have an effect on connections\nestablished after the addition of the event listener.\n\n

\n", "params": [] }, { "textRaw": "Event: 'OCSPRequest'", "type": "event", "name": "OCSPRequest", "desc": "

function (certificate, issuer, callback) { }\n\n

\n

Emitted when the client sends a certificate status request. The server's\ncurrent certificate can be parsed to obtain the OCSP URL and certificate ID;\nafter obtaining an OCSP response callback(null, resp) is then invoked, where\nresp is a Buffer instance. Both certificate and issuer are Buffer\nDER-representations of the primary and issuer's certificates. They can be used\nto obtain the OCSP certificate ID and OCSP endpoint URL.\n\n

\n

Alternatively, callback(null, null) may be called, meaning that there was no\nOCSP response.\n\n

\n

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

\n

Typical flow:\n\n

\n
    \n
  1. Client connects to the server and sends an 'OCSPRequest' to it (via status\ninfo extension in ClientHello).
  2. \n
  3. Server receives the request and invokes the 'OCSPRequest' event listener\nif present.
  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: issuer could be null if the certificate is self-signed or if the\nissuer is not in the root certificates list. (An issuer may be provided via the\nca option.)\n\n

\n

NOTE: adding this event listener will only have an effect on connections\nestablished after the addition of the event listener.\n\n

\n

NOTE: An npm module like [asn1.js] may be used to parse the certificates.\n\n

\n", "params": [] }, { "textRaw": "Event: 'resumeSession'", "type": "event", "name": "resumeSession", "desc": "

function (sessionId, callback) { }\n\n

\n

Emitted when the client wants to resume the previous TLS session. The event\nlistener may perform a lookup in external storage using the given sessionId\nand invoke callback(null, sessionData) once finished. If the session can't be\nresumed (i.e., doesn't exist in storage) one may call callback(null, null).\nCalling callback(err) will terminate incoming connection and destroy the\nsocket.\n\n

\n

NOTE: adding this event listener will only have an effect on connections\nestablished after the addition of the event listener.\n\n

\n

Here's an example for using TLS session resumption:\n\n

\n
var 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", "params": [] }, { "textRaw": "Event: 'secureConnection'", "type": "event", "name": "secureConnection", "desc": "

function (tlsSocket) {}\n\n

\n

This event is emitted after the handshaking process for a new connection has\nsuccessfully completed. The argument is an instance of [tls.TLSSocket][] and\nhas all the common stream methods and events.\n\n

\n

socket.authorized is a boolean value which indicates if the\nclient has been verified by one of the supplied certificate authorities for the\nserver. If socket.authorized is false, then socket.authorizationError is\nset to describe how authorization failed. Implied but worth mentioning:\ndepending on the settings of the TLS server, unauthorized connections may\nbe accepted.\n\n

\n

socket.npnProtocol is a string containing the selected NPN protocol\nand socket.alpnProtocol is a string containing the selected ALPN\nprotocol. When both NPN and ALPN extensions are received, ALPN takes\nprecedence over NPN and the next protocol is selected by ALPN. When\nALPN has no selected protocol, this returns false.\n\n

\n

socket.servername is a string containing the server name requested with\nSNI.\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "server.addContext(hostname, context)", "type": "method", "name": "addContext", "desc": "

Add secure context that will be used if the client request's SNI hostname\nmatches the supplied hostname (wildcards can be used). context can contain\nkey, cert, ca or any other properties from\n[tls.createSecureContext()][] options argument.\n\n

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "context" } ] } ] }, { "textRaw": "server.address()", "type": "method", "name": "address", "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\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

Stops the server from accepting new connections. This function is\nasynchronous, the server is finally closed when the server emits a 'close'\nevent. Optionally, you can pass a callback to listen for the 'close' event.\n\n

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.getTicketKeys()", "type": "method", "name": "getTicketKeys", "desc": "

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

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.listen(port[, hostname][, callback])", "type": "method", "name": "listen", "desc": "

Begin accepting connections on the specified port and hostname. If the\nhostname is omitted, the server will accept connections on any IPv6 address\n(::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise. A\nport value of zero will assign a random port.\n\n

\n

This function is asynchronous. The last parameter callback will be called\nwhen the server has been bound.\n\n

\n

See net.Server for more information.\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "hostname", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.setTicketKeys(keys)", "type": "method", "name": "setTicketKeys", "desc": "

Updates the keys for encryption/decryption of the [TLS Session Tickets][].\n\n

\n

NOTE: the buffer should be 48 bytes long. See ticketKeys option in\ntls.createServer for\nmore information on how it is used.\n\n

\n

NOTE: the change is effective only for future server connections. Existing\nor currently pending server connections will use the previous keys.\n\n

\n", "signatures": [ { "params": [ { "name": "keys" } ] } ] } ], "properties": [ { "textRaw": "server.connections", "name": "connections", "desc": "

The number of concurrent connections on the server.\n\n

\n" }, { "textRaw": "server.maxConnections", "name": "maxConnections", "desc": "

Set this property to reject connections when the server's connection count\nexceeds the specified threshold.\n\n\n

\n" } ] }, { "textRaw": "Class: tls.TLSSocket", "type": "class", "name": "tls.TLSSocket", "desc": "

This is a wrapped version of [net.Socket][] that does transparent encryption\nof written data and all required TLS negotiation.\n\n

\n

This instance implements the duplex [Stream][] interface. It has all the\ncommon stream methods and events.\n\n

\n

Methods that return TLS connection metadata (e.g.\n[tls.TLSSocket.getPeerCertificate()][] will only return data while the\nconnection is open.\n\n

\n", "methods": [ { "textRaw": "new tls.TLSSocket(socket[, options])", "type": "method", "name": "TLSSocket", "desc": "

Construct a new TLSSocket object from an existing TCP socket.\n\n

\n

socket is an instance of [net.Socket][]\n\n

\n

options is an optional object that might contain following properties:\n\n

\n\n", "signatures": [ { "params": [ { "name": "socket" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "tlsSocket.address()", "type": "method", "name": "address", "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\n

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

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

\n

Example:\n{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }\n\n

\n

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

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getEphemeralKeyInfo()", "type": "method", "name": "getEphemeralKeyInfo", "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, it returns null\nif called on a server socket. The supported types are 'DH' and 'ECDH'. The\nname property is only available in 'ECDH'.\n\n

\n

Example:\n\n

\n
{ type: 'ECDH', name: 'prime256v1', size: 256 }
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getPeerCertificate([ detailed ])", "type": "method", "name": "getPeerCertificate", "desc": "

Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the fields of the certificate. If the\ndetailed argument is true the full chain with the issuer property will be\nreturned, if false only the top certificate without the issuer property.\n\n

\n

Example:\n\n

\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  issuerInfo:\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   { ... another certificate ... },\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

If the peer does not provide a certificate, it returns null or an empty\nobject.\n\n

\n", "signatures": [ { "params": [ { "name": "detailed", "optional": true } ] } ] }, { "textRaw": "tlsSocket.getProtocol()", "type": "method", "name": "getProtocol", "desc": "

Returns a string containing the negotiated SSL/TLS protocol version of the\ncurrent connection. 'unknown' will be returned for connected sockets that have\nnot completed the handshaking process. null will be returned for server\nsockets or disconnected client sockets.\n\n

\n

Examples:\n

\n
'SSLv3'\n'TLSv1'\n'TLSv1.1'\n'TLSv1.2'\n'unknown'
\n

See https://www.openssl.org/docs/manmaster/ssl/SSL_get_version.html for more\ninformation.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getSession()", "type": "method", "name": "getSession", "desc": "

Returns the ASN.1 encoded TLS session or undefined if none was negotiated.\nCould be used to speed up handshake establishment when reconnecting to the\nserver.\n\n

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

NOTE: Works only with client TLS sockets. Useful only for debugging, for\nsession reuse provide session option to [tls.connect()][].\n\n

\n

Returns the TLS session ticket or undefined if none was negotiated.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.renegotiate(options, callback)", "type": "method", "name": "renegotiate", "desc": "

Initiate TLS renegotiation process. The options object may contain the\nfollowing fields: rejectUnauthorized, requestCert. (See [tls.createServer\n()][] for details.) callback(err) will be executed with null as err,\nonce the renegotiation is successfully completed.\n\n

\n

NOTE: Can be used to request peer's certificate after the secure connection\nhas been established.\n\n

\n

ANOTHER NOTE: When running as the server, socket will be destroyed\nwith an error after handshakeTimeout timeout.\n\n

\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback" } ] } ] }, { "textRaw": "tlsSocket.setMaxSendFragment(size)", "type": "method", "name": "setMaxSendFragment", "desc": "

Set maximum TLS fragment size (default and maximum value is: 16384, minimum\nis: 512). Returns true on success, false otherwise.\n\n

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

\n", "signatures": [ { "params": [ { "name": "size" } ] } ] } ], "events": [ { "textRaw": "Event: 'OCSPResponse'", "type": "event", "name": "OCSPResponse", "desc": "

function (response) { }\n\n

\n

This event will be emitted if the requestOCSP option was set. response is a\nBuffer containing the server's OCSP response.\n\n

\n

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

\n", "params": [] }, { "textRaw": "Event: 'secureConnect'", "type": "event", "name": "secureConnect", "desc": "

This event is emitted after the handshaking process for a new connection has\nsuccessfully completed. The listener will be called regardless of whether or not\nthe server's certificate has been authorized. It is the user's responsibility to\ntest tlsSocket.authorized to see if the server certificate was signed by one\nof the specified CAs. If tlsSocket.authorized === false then the error can be\nfound in tlsSocket.authorizationError. Also, if either ALPN or NPN was used\ntlsSocket.alpnProtocol or tlsSocket.npnProtocol can be checked for the\nnegotiated protocol.\n\n

\n", "params": [] } ], "properties": [ { "textRaw": "tlsSocket.authorized", "name": "authorized", "desc": "

A boolean that is true if the peer certificate was signed by one of the\nspecified CAs, otherwise false.\n\n

\n" }, { "textRaw": "tlsSocket.authorizationError", "name": "authorizationError", "desc": "

The reason why the peer's certificate has not been verified. This property\nbecomes available only when tlsSocket.authorized === false.\n\n

\n" }, { "textRaw": "tlsSocket.encrypted", "name": "encrypted", "desc": "

Static boolean value, always true. May be used to distinguish TLS sockets\nfrom regular ones.\n\n

\n" }, { "textRaw": "tlsSocket.localAddress", "name": "localAddress", "desc": "

The string representation of the local IP address.\n\n

\n" }, { "textRaw": "tlsSocket.localPort", "name": "localPort", "desc": "

The numeric representation of the local port.\n\n

\n" }, { "textRaw": "tlsSocket.remoteAddress", "name": "remoteAddress", "desc": "

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

\n" }, { "textRaw": "tlsSocket.remoteFamily", "name": "remoteFamily", "desc": "

The string representation of the remote IP family. 'IPv4' or 'IPv6'.\n\n

\n" }, { "textRaw": "tlsSocket.remotePort", "name": "remotePort", "desc": "

The numeric representation of the remote port. For example, 443.\n\n

\n" } ] } ], "methods": [ { "textRaw": "tls.connect(options[, callback])", "type": "method", "name": "connect", "desc": "

Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

\n\n

The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

\n

tls.connect() returns a [tls.TLSSocket][] object.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar 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

Or\n\n

\n
const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar 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", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "tls.connect(port[, host][, options][, callback])", "type": "method", "name": "connect", "desc": "

Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

\n\n

The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

\n

tls.connect() returns a [tls.TLSSocket][] object.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar 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

Or\n\n

\n
const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar 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", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "tls.createSecureContext(options)", "type": "method", "name": "createSecureContext", "desc": "

Creates a credentials object; the options object may contain the following\nfields:\n\n

\n\n

If no 'CA' details are given, then Node.js will use the default\npublicly trusted list of CAs as given in\n

\n

http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.\n\n

\n", "signatures": [ { "params": [ { "name": "options" } ] } ] }, { "textRaw": "tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])", "type": "method", "name": "createSecurePair", "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\n

\n\n

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

\n

NOTE: cleartext has the same API as [tls.TLSSocket][]\n\n

\n", "signatures": [ { "params": [ { "name": "context", "optional": true }, { "name": "isServer", "optional": true }, { "name": "requestCert", "optional": true }, { "name": "rejectUnauthorized", "optional": true }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "tls.createServer(options[, secureConnectionListener])", "type": "method", "name": "createServer", "desc": "

Creates a new [tls.Server][]. The connectionListener argument is\nautomatically set as a listener for the ['secureConnection'][] event. The\noptions object may contain the following fields:\n\n

\n\n

Here is a simple example echo server:\n\n

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

Or\n\n

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

You can test this server by connecting to it with openssl s_client:\n\n

\n
openssl s_client -connect 127.0.0.1:8000
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "secureConnectionListener", "optional": true } ] } ] }, { "textRaw": "tls.getCiphers()", "type": "method", "name": "getCiphers", "desc": "

Returns an array with the names of the supported SSL ciphers.\n\n

\n

Example:\n\n

\n
var ciphers = tls.getCiphers();\nconsole.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]
\n", "signatures": [ { "params": [] } ] } ], "type": "module", "displayName": "TLS (SSL)" } ] }