Guard against emitting 'end' twice on http responses
[platform/upstream/nodejs.git] / doc / api / tls.markdown
1 # TLS (SSL)
2
3     Stability: 3 - Stable
4
5 Use `require('tls')` to access this module.
6
7 The `tls` module uses OpenSSL to provide Transport Layer Security and/or
8 Secure Socket Layer: encrypted stream communication.
9
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
12
13     openssl genrsa -out ryans-key.pem 1024
14
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:
19
20     openssl req -new -key ryans-key.pem -out ryans-csr.pem
21
22 To create a self-signed certificate with the CSR, do this:
23
24     openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
25
26 Alternatively you can send the CSR to a Certificate Authority for signing.
27
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)
30
31 ## Client-initiated renegotiation attack mitigation
32
33 <!-- type=misc -->
34
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
38 attacks.
39
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:
43
44   - `tls.CLIENT_RENEG_LIMIT`: renegotiation limit, default is 3.
45
46   - `tls.CLIENT_RENEG_WINDOW`: renegotiation window in seconds, default is
47                                10 minutes.
48
49 Don't change the defaults unless you know what you are doing.
50
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
53 times.
54
55
56 ## NPN and SNI
57
58 <!-- type=misc -->
59
60 NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS
61 handshake extensions allowing you:
62
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
65     certificates.
66
67
68 ## tls.createServer(options, [secureConnectionListener])
69
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:
74
75   - `key`: A string or `Buffer` containing the private key of the server in
76     PEM format. (Required)
77
78   - `passphrase`: A string of passphrase for the private key.
79
80   - `cert`: A string or `Buffer` containing the certificate key of the server in
81     PEM format. (Required)
82
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.
86
87   - `crl` : Either a string or list of strings of PEM encoded CRLs (Certificate
88     Revocation List)
89
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`
99
100   - `honorCipherOrder` :
101         When choosing a cipher, use the server's preferences instead of the client
102         preferences.
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
107         BEAST attacks.
108
109   - `requestCert`: If `true` the server will request a certificate from
110     clients that connect and attempt to verify that certificate. Default:
111     `false`.
112
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`.
116
117   - `NPNProtocols`: An array or `Buffer` of possible NPN protocols. (Protocols
118     should be ordered by their priority).
119
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).
126
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.
130
131 Here is a simple example echo server:
132
133     var tls = require('tls');
134     var fs = require('fs');
135
136     var options = {
137       key: fs.readFileSync('server-key.pem'),
138       cert: fs.readFileSync('server-cert.pem'),
139
140       // This is necessary only if using the client certificate authentication.
141       requestCert: true,
142
143       // This is necessary only if the client uses the self-signed certificate.
144       ca: [ fs.readFileSync('client-cert.pem') ]
145     };
146
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);
153     });
154     server.listen(8000, function() {
155       console.log('server bound');
156     });
157
158
159 You can test this server by connecting to it with `openssl s_client`:
160
161
162     openssl s_client -connect 127.0.0.1:8000
163
164
165 ## tls.connect(options, [secureConnectListener])
166 ## tls.connect(port, [host], [options], [secureConnectListener])
167
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:
171
172   - `host`: Host the client should connect to
173
174   - `port`: Port the client should connect to
175
176   - `socket`: Establish secure connection on a given socket rather than
177     creating a new socket. If this option is specified, `host` and `port`
178     are ignored.
179
180   - `key`: A string or `Buffer` containing the private key of the client in
181     PEM format.
182
183   - `passphrase`: A string of passphrase for the private key.
184
185   - `cert`: A string or `Buffer` containing the certificate key of the client in
186     PEM format.
187
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.
191
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`.
195
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']`.)
200
201   - `servername`: Servername for SNI (Server Name Indication) TLS extension.
202
203 The `secureConnectListener` parameter will be added as a listener for the
204 ['secureConnect'](#event_secureConnect_) event.
205
206 `tls.connect()` returns a [CleartextStream](#tls.CleartextStream) object.
207
208 Here is an example of a client of echo server as described previously:
209
210     var tls = require('tls');
211     var fs = require('fs');
212
213     var options = {
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'),
217     
218       // This is necessary only if the server uses the self-signed certificate
219       ca: [ fs.readFileSync('server-cert.pem') ]
220     };
221
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();
227     });
228     cleartextStream.setEncoding('utf8');
229     cleartextStream.on('data', function(data) {
230       console.log(data);
231     });
232     cleartextStream.on('end', function() {
233       server.close();
234     });
235
236
237 ## tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])
238
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.
243
244  - `credentials`: A credentials object from crypto.createCredentials( ... )
245
246  - `isServer`: A boolean indicating whether this tls connection should be
247    opened as a server or a client.
248
249  - `requestCert`: A boolean indicating whether a server should request a
250    certificate from a connecting client. Only applies to server connections.
251
252  - `rejectUnauthorized`: A boolean indicating whether a server should
253    automatically reject clients with invalid certificates. Only applies to
254    servers with `requestCert` enabled.
255
256 `tls.createSecurePair()` returns a SecurePair object with
257 [cleartext](#tls.CleartextStream) and `encrypted` stream properties.
258
259 ## Class: SecurePair
260
261 Returned by tls.createSecurePair.
262
263 ### Event: 'secure'
264
265 The event is emitted from the SecurePair once the pair has successfully
266 established a secure connection.
267
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.
271
272 ## Class: tls.Server
273
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.
277
278 ### Event: 'secureConnection'
279
280 `function (cleartextStream) {}`
281
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
285 and events.
286
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
295 SNI.
296
297
298 ### Event: 'clientError'
299
300 `function (exception) { }`
301
302 When a client connection emits an 'error' event before secure connection is
303 established - it will be forwarded here.
304
305
306 ### server.listen(port, [host], [callback])
307
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`).
311
312 This function is asynchronous. The last parameter `callback` will be called
313 when the server has been bound.
314
315 See `net.Server` for more information.
316
317
318 ### server.close()
319
320 Stops the server from accepting new connections. This function is
321 asynchronous, the server is finally closed when the server emits a `'close'`
322 event.
323
324 ### server.address()
325
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.
329
330 ### server.addContext(hostname, credentials)
331
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`.
335
336 ### server.maxConnections
337
338 Set this property to reject connections when the server's connection count
339 gets high.
340
341 ### server.connections
342
343 The number of concurrent connections on the server.
344
345
346 ## Class: tls.CleartextStream
347
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.
350
351 This instance implements a duplex [Stream](stream.html) interfaces.
352 It has all the common stream methods and events.
353
354 A ClearTextStream is the `clear` member of a SecurePair object.
355
356 ### Event: 'secureConnect'
357
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.
365
366 ### cleartextStream.authorized
367
368 A boolean that is `true` if the peer certificate was signed by one of the
369 specified CAs, otherwise `false`
370
371 ### cleartextStream.authorizationError
372
373 The reason why the peer's certificate has not been verified. This property
374 becomes available only when `cleartextStream.authorized === false`.
375
376 ### cleartextStream.getPeerCertificate()
377
378 Returns an object representing the peer's certificate. The returned object has
379 some properties corresponding to the field of the certificate.
380
381 Example:
382
383     { subject: 
384        { C: 'UK',
385          ST: 'Acknack Ltd',
386          L: 'Rhys Jones',
387          O: 'node.js',
388          OU: 'Test TLS Certificate',
389          CN: 'localhost' },
390       issuer: 
391        { C: 'UK',
392          ST: 'Acknack Ltd',
393          L: 'Rhys Jones',
394          O: 'node.js',
395          OU: 'Test TLS Certificate',
396          CN: 'localhost' },
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' }
400
401 If the peer does not provide a certificate, it returns `null` or an empty
402 object.
403
404 ### cleartextStream.getCipher()
405 Returns an object representing the cipher name and the SSL/TLS
406 protocol version of the current connection.
407
408 Example:
409 { name: 'AES256-SHA', version: 'TLSv1/SSLv3' }
410
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
413 information.
414
415 ### cleartextStream.address()
416
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' }`
421
422 ### cleartextStream.remoteAddress
423
424 The string representation of the remote IP address. For example,
425 `'74.125.127.100'` or `'2001:4860:a005::68'`.
426
427 ### cleartextStream.remotePort
428
429 The numeric representation of the remote port. For example, `443`.