5 Use `require('tls')` to access this module.
7 The `tls` module uses OpenSSL to provide Transport Layer Security and/or
8 Secure Socket Layer: encrypted stream communication.
10 TLS/SSL is a public/private key infrastructure. Each client and each
11 server must have a private key. A private key is created like this
13 openssl genrsa -out ryans-key.pem 1024
15 All severs and some clients need to have a certificate. Certificates are public
16 keys signed by a Certificate Authority or self-signed. The first step to
17 getting a certificate is to create a "Certificate Signing Request" (CSR)
18 file. This is done with:
20 openssl req -new -key ryans-key.pem -out ryans-csr.pem
22 To create a self-signed certificate with the CSR, do this:
24 openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
26 Alternatively you can send the CSR to a Certificate Authority for signing.
28 (TODO: docs on creating a CA, for now interested users should just look at
29 `test/fixtures/keys/Makefile` in the Node source code)
31 ## Client-initiated renegotiation attack mitigation
35 The TLS protocol lets the client renegotiate certain aspects of the TLS session.
36 Unfortunately, session renegotiation requires a disproportional amount of
37 server-side resources, which makes it a potential vector for denial-of-service
40 To mitigate this, renegotiations are limited to three times every 10 minutes. An
41 error is emitted on the [CleartextStream](#tls.CleartextStream) instance when
42 the threshold is exceeded. The limits are configurable:
44 - `tls.CLIENT_RENEG_LIMIT`: renegotiation limit, default is 3.
46 - `tls.CLIENT_RENEG_WINDOW`: renegotiation window in seconds, default is
49 Don't change the defaults unless you know what you are doing.
51 To test your server, connect to it with `openssl s_client -connect address:port`
52 and tap `R<CR>` (that's the letter `R` followed by a carriage return) a few
60 NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS
61 handshake extensions allowing you:
63 * NPN - to use one TLS server for multiple protocols (HTTP, SPDY)
64 * SNI - to use one TLS server for multiple hostnames with different SSL
68 ## tls.createServer(options, [secureConnectionListener])
70 Creates a new [tls.Server](#tls.Server).
71 The `connectionListener` argument is automatically set as a listener for the
72 [secureConnection](#event_secureConnection_) event.
73 The `options` object has these possibilities:
75 - `key`: A string or `Buffer` containing the private key of the server in
76 PEM format. (Required)
78 - `passphrase`: A string of passphrase for the private key.
80 - `cert`: A string or `Buffer` containing the certificate key of the server in
81 PEM format. (Required)
83 - `ca`: An array of strings or `Buffer`s of trusted certificates. If this is
84 omitted several well known "root" CAs will be used, like VeriSign.
85 These are used to authorize connections.
87 - `crl` : Either a string or list of strings of PEM encoded CRLs (Certificate
90 - `ciphers`: A string describing the ciphers to use or exclude. Consult
91 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT> for
92 details on the format.
93 To mitigate [BEAST attacks]
94 (http://blog.ivanristic.com/2011/10/mitigating-the-beast-attack-on-tls.html),
95 it is recommended that you use this option in conjunction with the
96 `honorCipherOrder` option described below to prioritize the RC4 algorithm,
97 since it is a non-CBC cipher. A recommended cipher list follows:
98 `ECDHE-RSA-AES256-SHA:AES256-SHA:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM`
100 - `honorCipherOrder` :
101 When choosing a cipher, use the server's preferences instead of the client
103 Note that if SSLv2 is used, the server will send its list of preferences
104 to the client, and the client chooses the cipher.
105 Although, this option is disabled by default, it is *recommended* that you
106 use this option in conjunction with the `ciphers` option to mitigate
109 - `requestCert`: If `true` the server will request a certificate from
110 clients that connect and attempt to verify that certificate. Default:
113 - `rejectUnauthorized`: If `true` the server will reject any connection
114 which is not authorized with the list of supplied CAs. This option only
115 has an effect if `requestCert` is `true`. Default: `false`.
117 - `NPNProtocols`: An array or `Buffer` of possible NPN protocols. (Protocols
118 should be ordered by their priority).
120 - `SNICallback`: A function that will be called if client supports SNI TLS
121 extension. Only one argument will be passed to it: `servername`. And
122 `SNICallback` should return SecureContext instance.
123 (You can use `crypto.createCredentials(...).context` to get proper
124 SecureContext). If `SNICallback` wasn't provided - default callback with
125 high-level API will be used (see below).
127 - `sessionIdContext`: A string containing a opaque identifier for session
128 resumption. If `requestCert` is `true`, the default is MD5 hash value
129 generated from command-line. Otherwise, the default is not provided.
131 Here is a simple example echo server:
133 var tls = require('tls');
134 var fs = require('fs');
137 key: fs.readFileSync('server-key.pem'),
138 cert: fs.readFileSync('server-cert.pem'),
140 // This is necessary only if using the client certificate authentication.
143 // This is necessary only if the client uses the self-signed certificate.
144 ca: [ fs.readFileSync('client-cert.pem') ]
147 var server = tls.createServer(options, function(cleartextStream) {
148 console.log('server connected',
149 cleartextStream.authorized ? 'authorized' : 'unauthorized');
150 cleartextStream.write("welcome!\n");
151 cleartextStream.setEncoding('utf8');
152 cleartextStream.pipe(cleartextStream);
154 server.listen(8000, function() {
155 console.log('server bound');
159 You can test this server by connecting to it with `openssl s_client`:
162 openssl s_client -connect 127.0.0.1:8000
165 ## tls.connect(options, [secureConnectListener])
166 ## tls.connect(port, [host], [options], [secureConnectListener])
168 Creates a new client connection to the given `port` and `host` (old API) or
169 `options.port` and `options.host`. (If `host` is omitted, it defaults to
170 `localhost`.) `options` should be an object which specifies:
172 - `host`: Host the client should connect to
174 - `port`: Port the client should connect to
176 - `socket`: Establish secure connection on a given socket rather than
177 creating a new socket. If this option is specified, `host` and `port`
180 - `key`: A string or `Buffer` containing the private key of the client in
183 - `passphrase`: A string of passphrase for the private key.
185 - `cert`: A string or `Buffer` containing the certificate key of the client in
188 - `ca`: An array of strings or `Buffer`s of trusted certificates. If this is
189 omitted several well known "root" CAs will be used, like VeriSign.
190 These are used to authorize connections.
192 - `rejectUnauthorized`: If `true`, the server certificate is verified against
193 the list of supplied CAs. An `'error'` event is emitted if verification
194 fails. Default: `false`.
196 - `NPNProtocols`: An array of string or `Buffer` containing supported NPN
197 protocols. `Buffer` should have following format: `0x05hello0x05world`,
198 where first byte is next protocol name's length. (Passing array should
199 usually be much simpler: `['hello', 'world']`.)
201 - `servername`: Servername for SNI (Server Name Indication) TLS extension.
203 The `secureConnectListener` parameter will be added as a listener for the
204 ['secureConnect'](#event_secureConnect_) event.
206 `tls.connect()` returns a [CleartextStream](#tls.CleartextStream) object.
208 Here is an example of a client of echo server as described previously:
210 var tls = require('tls');
211 var fs = require('fs');
214 // These are necessary only if using the client certificate authentication
215 key: fs.readFileSync('client-key.pem'),
216 cert: fs.readFileSync('client-cert.pem'),
218 // This is necessary only if the server uses the self-signed certificate
219 ca: [ fs.readFileSync('server-cert.pem') ]
222 var cleartextStream = tls.connect(8000, options, function() {
223 console.log('client connected',
224 cleartextStream.authorized ? 'authorized' : 'unauthorized');
225 process.stdin.pipe(cleartextStream);
226 process.stdin.resume();
228 cleartextStream.setEncoding('utf8');
229 cleartextStream.on('data', function(data) {
232 cleartextStream.on('end', function() {
237 ## tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])
239 Creates a new secure pair object with two streams, one of which reads/writes
240 encrypted data, and one reads/writes cleartext data.
241 Generally the encrypted one is piped to/from an incoming encrypted data stream,
242 and the cleartext one is used as a replacement for the initial encrypted stream.
244 - `credentials`: A credentials object from crypto.createCredentials( ... )
246 - `isServer`: A boolean indicating whether this tls connection should be
247 opened as a server or a client.
249 - `requestCert`: A boolean indicating whether a server should request a
250 certificate from a connecting client. Only applies to server connections.
252 - `rejectUnauthorized`: A boolean indicating whether a server should
253 automatically reject clients with invalid certificates. Only applies to
254 servers with `requestCert` enabled.
256 `tls.createSecurePair()` returns a SecurePair object with
257 [cleartext](#tls.CleartextStream) and `encrypted` stream properties.
261 Returned by tls.createSecurePair.
265 The event is emitted from the SecurePair once the pair has successfully
266 established a secure connection.
268 Similarly to the checking for the server 'secureConnection' event,
269 pair.cleartext.authorized should be checked to confirm whether the certificate
270 used properly authorized.
274 This class is a subclass of `net.Server` and has the same methods on it.
275 Instead of accepting just raw TCP connections, this accepts encrypted
276 connections using TLS or SSL.
278 ### Event: 'secureConnection'
280 `function (cleartextStream) {}`
282 This event is emitted after a new connection has been successfully
283 handshaked. The argument is a instance of
284 [CleartextStream](#tls.CleartextStream). It has all the common stream methods
287 `cleartextStream.authorized` is a boolean value which indicates if the
288 client has verified by one of the supplied certificate authorities for the
289 server. If `cleartextStream.authorized` is false, then
290 `cleartextStream.authorizationError` is set to describe how authorization
291 failed. Implied but worth mentioning: depending on the settings of the TLS
292 server, you unauthorized connections may be accepted.
293 `cleartextStream.npnProtocol` is a string containing selected NPN protocol.
294 `cleartextStream.servername` is a string containing servername requested with
298 ### Event: 'clientError'
300 `function (exception) { }`
302 When a client connection emits an 'error' event before secure connection is
303 established - it will be forwarded here.
306 ### server.listen(port, [host], [callback])
308 Begin accepting connections on the specified `port` and `host`. If the
309 `host` is omitted, the server will accept connections directed to any
310 IPv4 address (`INADDR_ANY`).
312 This function is asynchronous. The last parameter `callback` will be called
313 when the server has been bound.
315 See `net.Server` for more information.
320 Stops the server from accepting new connections. This function is
321 asynchronous, the server is finally closed when the server emits a `'close'`
326 Returns the bound address, the address family name and port of the
327 server as reported by the operating system.
328 See [net.Server.address()](net.html#server.address) for more information.
330 ### server.addContext(hostname, credentials)
332 Add secure context that will be used if client request's SNI hostname is
333 matching passed `hostname` (wildcards can be used). `credentials` can contain
334 `key`, `cert` and `ca`.
336 ### server.maxConnections
338 Set this property to reject connections when the server's connection count
341 ### server.connections
343 The number of concurrent connections on the server.
346 ## Class: tls.CleartextStream
348 This is a stream on top of the *Encrypted* stream that makes it possible to
349 read/write an encrypted data as a cleartext data.
351 This instance implements a duplex [Stream](stream.html) interfaces.
352 It has all the common stream methods and events.
354 A ClearTextStream is the `clear` member of a SecurePair object.
356 ### Event: 'secureConnect'
358 This event is emitted after a new connection has been successfully handshaked.
359 The listener will be called no matter if the server's certificate was
360 authorized or not. It is up to the user to test `cleartextStream.authorized`
361 to see if the server certificate was signed by one of the specified CAs.
362 If `cleartextStream.authorized === false` then the error can be found in
363 `cleartextStream.authorizationError`. Also if NPN was used - you can check
364 `cleartextStream.npnProtocol` for negotiated protocol.
366 ### cleartextStream.authorized
368 A boolean that is `true` if the peer certificate was signed by one of the
369 specified CAs, otherwise `false`
371 ### cleartextStream.authorizationError
373 The reason why the peer's certificate has not been verified. This property
374 becomes available only when `cleartextStream.authorized === false`.
376 ### cleartextStream.getPeerCertificate()
378 Returns an object representing the peer's certificate. The returned object has
379 some properties corresponding to the field of the certificate.
388 OU: 'Test TLS Certificate',
395 OU: 'Test TLS Certificate',
397 valid_from: 'Nov 11 09:52:22 2009 GMT',
398 valid_to: 'Nov 6 09:52:22 2029 GMT',
399 fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' }
401 If the peer does not provide a certificate, it returns `null` or an empty
404 ### cleartextStream.getCipher()
405 Returns an object representing the cipher name and the SSL/TLS
406 protocol version of the current connection.
409 { name: 'AES256-SHA', version: 'TLSv1/SSLv3' }
411 See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in
412 http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more
415 ### cleartextStream.address()
417 Returns the bound address, the address family name and port of the
418 underlying socket as reported by the operating system. Returns an
419 object with three properties, e.g.
420 `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
422 ### cleartextStream.remoteAddress
424 The string representation of the remote IP address. For example,
425 `'74.125.127.100'` or `'2001:4860:a005::68'`.
427 ### cleartextStream.remotePort
429 The numeric representation of the remote port. For example, `443`.