TLS (SSL)

Stability: 2 - Stable

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

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

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

openssl genrsa -out ryans-key.pem 2048

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

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

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

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

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

For Perfect Forward Secrecy, it is required to generate Diffie-Hellman parameters:

openssl dhparam -outform PEM -out dhparam.pem 2048

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

openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \
      -certfile ca-cert.pem -out agent5.pfx
  • in: certificate
  • inkey: private key
  • certfile: all CA certs concatenated in one file like cat ca1-cert.pem ca2-cert.pem > ca-cert.pem

ALPN, NPN and SNI

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

  • ALPN/NPN - Allows the use of one TLS server for multiple protocols (HTTP, SPDY, HTTP/2)
  • SNI - Allows the use of one TLS server for multiple hostnames with different SSL certificates.

Client-initiated renegotiation attack mitigation

The TLS protocol lets the client renegotiate certain aspects of the TLS session. Unfortunately, session renegotiation requires a disproportionate amount of server-side resources, which makes it a potential vector for denial-of-service attacks.

To mitigate this, renegotiation is limited to three times every 10 minutes. An error is emitted on the tls.TLSSocket instance when the threshold is exceeded. These limits are configurable:

  • tls.CLIENT_RENEG_LIMIT: renegotiation limit, default is 3.

  • tls.CLIENT_RENEG_WINDOW: renegotiation window in seconds, default is 10 minutes.

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

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

Modifying the Default TLS Cipher suite

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

ECDHE-RSA-AES128-GCM-SHA256:
ECDHE-ECDSA-AES128-GCM-SHA256:
ECDHE-RSA-AES256-GCM-SHA384:
ECDHE-ECDSA-AES256-GCM-SHA384:
DHE-RSA-AES128-GCM-SHA256:
ECDHE-RSA-AES128-SHA256:
DHE-RSA-AES128-SHA256:
ECDHE-RSA-AES256-SHA384:
DHE-RSA-AES256-SHA384:
ECDHE-RSA-AES256-SHA256:
DHE-RSA-AES256-SHA256:
HIGH:
!aNULL:
!eNULL:
!EXPORT:
!DES:
!RC4:
!MD5:
!PSK:
!SRP:
!CAMELLIA

This default can be overriden entirely using the --tls-cipher-list command line switch. For instance, the following makes ECDHE-RSA-AES128-GCM-SHA256:!RC4 the default TLS cipher suite:

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

Note that the default cipher suite included within Node.js has been carefully selected to reflect current security best practices and risk mitigation. Changing the default cipher suite can have a significant impact on the security of an application. The --tls-cipher-list switch should by used only if absolutely necessary.

Perfect Forward Secrecy

The term "Forward Secrecy" or "Perfect Forward Secrecy" describes a feature of key-agreement (i.e., key-exchange) methods. Practically it means that even if the private key of a server is compromised, communication can only be decrypted by eavesdroppers if they manage to obtain the key-pair specifically generated for each session.

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

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

  • DHE - An ephemeral version of the Diffie Hellman key-agreement protocol.
  • ECDHE - An ephemeral version of the Elliptic Curve Diffie Hellman key-agreement protocol.

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

tls.connect(options[, callback])

tls.connect(port[, host][, options][, callback])

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

  • host: Host the client should connect to.

  • port: Port the client should connect to.

  • socket: Establish secure connection on a given socket rather than creating a new socket. If this option is specified, host and port are ignored.

  • path: Creates unix socket connection to path. If this option is specified, host and port are ignored.

  • pfx: A string or Buffer containing the private key, certificate, and CA certs of the client in PFX or PKCS12 format.

  • key: A string, Buffer, array of strings, or array of Buffers containing the private key of the client in PEM format.

  • passphrase: A string containing the passphrase for the private key or pfx.

  • cert: A string, Buffer, array of strings, or array of Buffers containing the certificate key of the client in PEM format.

  • ca: A string, Buffer, array of strings, or array of Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections.

  • ciphers: A string describing the ciphers to use or exclude, separated by :. Uses the same default cipher suite as tls.createServer().

  • rejectUnauthorized: 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. Default: true.

  • NPNProtocols: An array of strings or Buffers containing supported NPN protocols. Buffers should have the following format: 0x05hello0x05world, where the first byte is the next protocol name's length. (Passing an array is usually be much simpler: ['hello', 'world'].)

  • ALPNProtocols: An array of strings or Buffers containing the supported ALPN protocols. Buffers should have following format: 0x05hello0x05world, where the first byte is the next protocol name's length. (Passing an array is usually be much simpler: ['hello', 'world'].)

  • servername: Server name for the SNI (Server Name Indication) TLS extension.

  • checkServerIdentity(servername, cert): Provide an override for checking the server's hostname against the certificate. Should return an error if verification fails. Returns undefined if passing.

  • secureProtocol: The SSL method to use, e.g., SSLv3_method to force SSL version 3. The possible values depend on the version of OpenSSL installed in the environment and are defined in the constant SSL_METHODS.

  • secureContext: An optional TLS context object from tls.createSecureContext( ... ). It can be used for caching client certificates, keys, and CA certificates.

  • session: A Buffer instance, containing TLS session.

  • minDHSize: 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 this, the TLS connection is destroyed and an error is thrown. Default: 1024.

The callback parameter will be added as a listener for the 'secureConnect' event.

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

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

const tls = require('tls');
const fs = require('fs');

const options = {
  // These are necessary only if using the client certificate authentication
  key: fs.readFileSync('client-key.pem'),
  cert: fs.readFileSync('client-cert.pem'),

  // This is necessary only if the server uses the self-signed certificate
  ca: [ fs.readFileSync('server-cert.pem') ]
};

var socket = tls.connect(8000, options, () => {
  console.log('client connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  process.stdin.pipe(socket);
  process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', (data) => {
  console.log(data);
});
socket.on('end', () => {
  server.close();
});

Or

const tls = require('tls');
const fs = require('fs');

const options = {
  pfx: fs.readFileSync('client.pfx')
};

var socket = tls.connect(8000, options, () => {
  console.log('client connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  process.stdin.pipe(socket);
  process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', (data) => {
  console.log(data);
});
socket.on('end', () => {
  server.close();
});

tls.createSecureContext(options)

Creates a credentials object; the options object may contain the following fields:

  • pfx : A string or Buffer holding the PFX or PKCS12 encoded private key, certificate, and CA certificates.
  • key: A string or Buffer containing the private key of the server in PEM format. To support multiple keys using different algorithms, an array can be provided. It can either be a plain array of keys or an array of objects in the format {pem: key, passphrase: passphrase}. (Required)
  • passphrase : A string containing the passphrase for the private key or pfx.
  • cert : A string containing the PEM encoded certificate
  • ca: A string, Buffer, array of strings, or array of Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections.
  • crl : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List).
  • ciphers: A string describing the ciphers to use or exclude. Consult https://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details on the format.
  • honorCipherOrder : When choosing a cipher, use the server's preferences instead of the client preferences. For further details see tls module documentation.

If no 'CA' details are given, then Node.js will use the default publicly trusted list of CAs as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.

tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])

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

  • credentials: A secure context object from tls.createSecureContext( ... ).

  • isServer: A boolean indicating whether this TLS connection should be opened as a server or a client.

  • requestCert: A boolean indicating whether a server should request a certificate from a connecting client. Only applies to server connections.

  • rejectUnauthorized: A boolean indicating whether a server should automatically reject clients with invalid certificates. Only applies to servers with requestCert enabled.

  • options: An object with common SSL options. See tls.TLSSocket.

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

NOTE: cleartext has the same API as tls.TLSSocket

tls.createServer(options[, secureConnectionListener])

Creates a new tls.Server. The connectionListener argument is automatically set as a listener for the 'secureConnection' event. The options object may contain the following fields:

  • pfx: A string or Buffer containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with the key, cert, and ca options.)

  • key: A string or Buffer containing the private key of the server in PEM format. To support multiple keys using different algorithms an array can be provided. It can either be a plain array of keys or an array of objects in the format {pem: key, passphrase: passphrase}. (Required)

  • passphrase: A string containing the passphrase for the private key or pfx.

  • cert: A string, Buffer, array of strings, or array of Buffers containing the certificate key of the server in PEM format. (Required)

  • ca: A string, Buffer, array of strings, or array of Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections.

  • crl : Either a string or array of strings of PEM encoded CRLs (Certificate Revocation List).

  • ciphers: A string describing the ciphers to use or exclude, separated by :. The default cipher suite is:

    ECDHE-RSA-AES128-GCM-SHA256:
    ECDHE-ECDSA-AES128-GCM-SHA256:
    ECDHE-RSA-AES256-GCM-SHA384:
    ECDHE-ECDSA-AES256-GCM-SHA384:
    DHE-RSA-AES128-GCM-SHA256:
    ECDHE-RSA-AES128-SHA256:
    DHE-RSA-AES128-SHA256:
    ECDHE-RSA-AES256-SHA384:
    DHE-RSA-AES256-SHA384:
    ECDHE-RSA-AES256-SHA256:
    DHE-RSA-AES256-SHA256:
    HIGH:
    !aNULL:
    !eNULL:
    !EXPORT:
    !DES:
    !RC4:
    !MD5:
    !PSK:
    !SRP:
    !CAMELLIA
    

    The default cipher suite prefers GCM ciphers for Chrome's 'modern cryptography' setting and also prefers ECDHE and DHE ciphers for Perfect Forward Secrecy, while offering some backward compatibility.

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

    Old clients that rely on insecure and deprecated RC4 or DES-based ciphers (like Internet Explorer 6) cannot complete the handshaking process with the default configuration. If these clients must be supported, the TLS recommendations may offer a compatible cipher suite. For more details on the format, see the OpenSSL cipher list format documentation.

  • ecdhCurve: A string describing a named curve to use for ECDH key agreement or false to disable ECDH.

    Defaults to prime256v1 (NIST P-256). 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.

  • dhparam: A string or Buffer containing Diffie Hellman parameters, required for Perfect Forward Secrecy. Use openssl dhparam to create it. Its key length should be greater than or equal to 1024 bits, otherwise it throws an error. It is strongly recommended to use 2048 bits or larger for stronger security. If omitted or invalid, it is silently discarded and DHE ciphers won't be available.

  • handshakeTimeout: Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. The default is 120 seconds.

    A 'clientError' is emitted on the tls.Server object whenever a handshake times out.

  • honorCipherOrder : When choosing a cipher, use the server's preferences instead of the client preferences. Default: true.

  • requestCert: If true the server will request a certificate from clients that connect and attempt to verify that certificate. Default: false.

  • rejectUnauthorized: 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. Default: false.

  • NPNProtocols: An array or Buffer of possible NPN protocols. (Protocols should be ordered by their priority.)

  • ALPNProtocols: An array or Buffer of 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.

  • SNICallback(servername, cb): A function that will be called if the client supports SNI TLS extension. Two arguments will be passed to it: 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).

  • sessionTimeout: 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.

  • 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: Automatically shared between cluster module workers.

  • sessionIdContext: A string containing an opaque identifier for session resumption. If requestCert is true, the default is a 128 bit truncated SHA1 hash value generated from the command-line. Otherwise, a default is not provided.

  • secureProtocol: The SSL method to use, e.g., SSLv3_method to force SSL version 3. The possible values depend on the version of OpenSSL installed in the environment and are defined in the constant SSL_METHODS.

Here is a simple example echo server:

const tls = require('tls');
const fs = require('fs');

const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),

  // This is necessary only if using the client certificate authentication.
  requestCert: true,

  // This is necessary only if the client uses the self-signed certificate.
  ca: [ fs.readFileSync('client-cert.pem') ]
};

var server = tls.createServer(options, (socket) => {
  console.log('server connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  socket.write('welcome!\n');
  socket.setEncoding('utf8');
  socket.pipe(socket);
});
server.listen(8000, () => {
  console.log('server bound');
});

Or

const tls = require('tls');
const fs = require('fs');

const options = {
  pfx: fs.readFileSync('server.pfx'),

  // This is necessary only if using the client certificate authentication.
  requestCert: true,

};

var server = tls.createServer(options, (socket) => {
  console.log('server connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  socket.write('welcome!\n');
  socket.setEncoding('utf8');
  socket.pipe(socket);
});
server.listen(8000, () => {
  console.log('server bound');
});

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

openssl s_client -connect 127.0.0.1:8000

tls.getCiphers()

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

Example:

var ciphers = tls.getCiphers();
console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]