PageRenderTime 48ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/doc/api/tls.markdown

https://gitlab.com/GeekSir/node
Markdown | 945 lines | 659 code | 286 blank | 0 comment | 0 complexity | 388e94a20469fe423a88af190d7cee34 MD5 | raw file
Possible License(s): 0BSD, Apache-2.0, MPL-2.0-no-copyleft-exception, JSON, WTFPL, CC-BY-SA-3.0, Unlicense, ISC, BSD-3-Clause, MIT, AGPL-3.0
  1. # TLS (SSL)
  2. Stability: 3 - Stable
  3. Use `require('tls')` to access this module.
  4. The `tls` module uses OpenSSL to provide Transport Layer Security and/or
  5. Secure Socket Layer: encrypted stream communication.
  6. TLS/SSL is a public/private key infrastructure. Each client and each
  7. server must have a private key. A private key is created like this:
  8. openssl genrsa -out ryans-key.pem 2048
  9. All servers and some clients need to have a certificate. Certificates are public
  10. keys signed by a Certificate Authority or self-signed. The first step to
  11. getting a certificate is to create a "Certificate Signing Request" (CSR)
  12. file. This is done with:
  13. openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem
  14. To create a self-signed certificate with the CSR, do this:
  15. openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
  16. Alternatively you can send the CSR to a Certificate Authority for signing.
  17. For Perfect Forward Secrecy, it is required to generate Diffie-Hellman
  18. parameters:
  19. openssl dhparam -outform PEM -out dhparam.pem 2048
  20. To create .pfx or .p12, do this:
  21. openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \
  22. -certfile ca-cert.pem -out agent5.pfx
  23. - `in`: certificate
  24. - `inkey`: private key
  25. - `certfile`: all CA certs concatenated in one file like
  26. `cat ca1-cert.pem ca2-cert.pem > ca-cert.pem`
  27. ## Protocol support
  28. Node.js is compiled with SSLv2 and SSLv3 protocol support by default, but these
  29. protocols are **disabled**. They are considered insecure and could be easily
  30. compromised as was shown by [CVE-2014-3566][]. However, in some situations, it
  31. may cause problems with legacy clients/servers (such as Internet Explorer 6).
  32. If you wish to enable SSLv2 or SSLv3, run node with the `--enable-ssl2` or
  33. `--enable-ssl3` flag respectively. In future versions of Node.js SSLv2 and
  34. SSLv3 will not be compiled in by default.
  35. There is a way to force node into using SSLv3 or SSLv2 only mode by explicitly
  36. specifying `secureProtocol` to `'SSLv3_method'` or `'SSLv2_method'`.
  37. The default protocol method Node.js uses is `SSLv23_method` which would be more
  38. accurately named `AutoNegotiate_method`. This method will try and negotiate
  39. from the highest level down to whatever the client supports. To provide a
  40. secure default, Node.js (since v0.10.33) explicitly disables the use of SSLv3
  41. and SSLv2 by setting the `secureOptions` to be
  42. `SSL_OP_NO_SSLv3|SSL_OP_NO_SSLv2` (again, unless you have passed
  43. `--enable-ssl3`, or `--enable-ssl2`, or `SSLv3_method` as `secureProtocol`).
  44. If you have set `secureOptions` to anything, we will not override your
  45. options.
  46. The ramifications of this behavior change:
  47. * If your application is behaving as a secure server, clients who are `SSLv3`
  48. only will now not be able to appropriately negotiate a connection and will be
  49. refused. In this case your server will emit a `clientError` event. The error
  50. message will include `'wrong version number'`.
  51. * If your application is behaving as a secure client and communicating with a
  52. server that doesn't support methods more secure than SSLv3 then your connection
  53. won't be able to negotiate and will fail. In this case your client will emit a
  54. an `error` event. The error message will include `'wrong version number'`.
  55. ## Client-initiated renegotiation attack mitigation
  56. <!-- type=misc -->
  57. The TLS protocol lets the client renegotiate certain aspects of the TLS session.
  58. Unfortunately, session renegotiation requires a disproportional amount of
  59. server-side resources, which makes it a potential vector for denial-of-service
  60. attacks.
  61. To mitigate this, renegotiations are limited to three times every 10 minutes. An
  62. error is emitted on the [tls.TLSSocket][] instance when the threshold is
  63. exceeded. The limits are configurable:
  64. - `tls.CLIENT_RENEG_LIMIT`: renegotiation limit, default is 3.
  65. - `tls.CLIENT_RENEG_WINDOW`: renegotiation window in seconds, default is
  66. 10 minutes.
  67. Don't change the defaults unless you know what you are doing.
  68. To test your server, connect to it with `openssl s_client -connect address:port`
  69. and tap `R<CR>` (that's the letter `R` followed by a carriage return) a few
  70. times.
  71. ## NPN and SNI
  72. <!-- type=misc -->
  73. NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS
  74. handshake extensions allowing you:
  75. * NPN - to use one TLS server for multiple protocols (HTTP, SPDY)
  76. * SNI - to use one TLS server for multiple hostnames with different SSL
  77. certificates.
  78. ## Perfect Forward Secrecy
  79. <!-- type=misc -->
  80. The term "[Forward Secrecy]" or "Perfect Forward Secrecy" describes a feature of
  81. key-agreement (i.e. key-exchange) methods. Practically it means that even if the
  82. private key of a (your) server is compromised, communication can only be
  83. decrypted by eavesdroppers if they manage to obtain the key-pair specifically
  84. generated for each session.
  85. This is achieved by randomly generating a key pair for key-agreement on every
  86. handshake (in contrary to the same key for all sessions). Methods implementing
  87. this technique, thus offering Perfect Forward Secrecy, are called "ephemeral".
  88. Currently two methods are commonly used to achieve Perfect Forward Secrecy (note
  89. the character "E" appended to the traditional abbreviations):
  90. * [DHE] - An ephemeral version of the Diffie Hellman key-agreement protocol.
  91. * [ECDHE] - An ephemeral version of the Elliptic Curve Diffie Hellman
  92. key-agreement protocol.
  93. Ephemeral methods may have some performance drawbacks, because key generation
  94. is expensive.
  95. ## Modifying the Default Cipher Suite
  96. Node.js is built with a default suite of enabled and disabled ciphers.
  97. Currently, the default cipher suite is:
  98. ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:
  99. DHE-RSA-AES256-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:
  100. HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA
  101. This default can be overridden entirely using the `--cipher-list` command line
  102. switch or `NODE_CIPHER_LIST` environment variable. For instance:
  103. node --cipher-list=ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384
  104. Setting the environment variable would have the same effect:
  105. NODE_CIPHER_LIST=ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384
  106. CAUTION: The default cipher suite has been carefully selected to reflect current
  107. security best practices and risk mitigation. Changing the default cipher suite
  108. can have a significant impact on the security of an application. The
  109. `--cipher-list` and `NODE_CIPHER_LIST` options should only be used if
  110. absolutely necessary.
  111. ### Using Legacy Default Cipher Suite ###
  112. It is possible for the built-in default cipher suite to change from one release
  113. of Node.js to another. For instance, v0.10.38 uses a different default than
  114. v0.12.2. Such changes can cause issues with applications written to assume
  115. certain specific defaults. To help buffer applications against such changes,
  116. the `--enable-legacy-cipher-list` command line switch or `NODE_LEGACY_CIPHER_LIST`
  117. environment variable can be set to specify a specific preset default:
  118. # Use the v0.10.38 defaults
  119. node --enable-legacy-cipher-list=v0.10.38
  120. // or
  121. NODE_LEGACY_CIPHER_LIST=v0.10.38
  122. # Use the v0.12.2 defaults
  123. node --enable-legacy-cipher-list=v0.12.2
  124. // or
  125. NODE_LEGACY_CIPHER_LIST=v0.12.2
  126. Currently, the values supported for the `enable-legacy-cipher-list` switch and
  127. `NODE_LEGACY_CIPHER_LIST` environment variable include:
  128. v0.10.38 - To enable the default cipher suite used in v0.10.38
  129. ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH
  130. v0.10.39 - To enable the default cipher suite used in v0.10.39
  131. ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:HIGH:!RC4:!MD5:!aNULL:!EDH
  132. v0.12.2 - To enable the default cipher suite used in v0.12.2
  133. ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:
  134. HIGH:!MD5:!aNULL
  135. v.0.12.3 - To enable the default cipher suite used in v0.12.3
  136. ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:AES128-GCM-SHA256:HIGH:
  137. !RC4:!MD5:!aNULL
  138. These legacy cipher suites are also made available for use via the
  139. `getLegacyCiphers()` method:
  140. var tls = require('tls');
  141. console.log(tls.getLegacyCiphers('v0.10.38'));
  142. CAUTION: Changes to the default cipher suite are typically made in order to
  143. strengthen the default security for applications running within Node.js.
  144. Reverting back to the defaults used by older releases can weaken the security
  145. of your applications. The legacy cipher suites should only be used if absolutely
  146. necessary.
  147. ## tls.getCiphers()
  148. Returns an array with the names of the supported SSL ciphers.
  149. Example:
  150. var ciphers = tls.getCiphers();
  151. console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]
  152. ## tls.getLegacyCiphers(version)
  153. Returns the legacy default cipher suite for the specified Node.js release.
  154. Example:
  155. var cipher_suite = tls.getLegacyCiphers('v0.10.38');
  156. ## tls.createServer(options[, secureConnectionListener])
  157. Creates a new [tls.Server][]. The `connectionListener` argument is
  158. automatically set as a listener for the [secureConnection][] event. The
  159. `options` object has these possibilities:
  160. - `pfx`: A string or `Buffer` containing the private key, certificate and
  161. CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with
  162. the `key`, `cert` and `ca` options.)
  163. - `key`: A string or `Buffer` containing the private key of the server in
  164. PEM format. (Could be an array of keys). (Required)
  165. - `passphrase`: A string of passphrase for the private key or pfx.
  166. - `cert`: A string or `Buffer` containing the certificate key of the server in
  167. PEM format. (Could be an array of certs). (Required)
  168. - `ca`: An array of strings or `Buffer`s of trusted certificates in PEM
  169. format. If this is omitted several well known "root" CAs will be used,
  170. like VeriSign. These are used to authorize connections.
  171. - `crl` : Either a string or list of strings of PEM encoded CRLs (Certificate
  172. Revocation List)
  173. - `ciphers`: A string describing the ciphers to use or exclude, separated by
  174. `:`. The default cipher suite is:
  175. ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:
  176. DHE-RSA-AES256-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:
  177. HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA
  178. The default cipher suite prefers ECDHE and DHE ciphers for Perfect Forward
  179. secrecy, while offering *some* backward compatibility. Old clients which
  180. rely on insecure and deprecated RC4 or DES-based ciphers (like Internet
  181. Explorer 6) aren't able to complete the handshake with the default
  182. configuration. If you absolutely must support these clients, the
  183. [TLS recommendations] may offer a compatible cipher suite. For more details
  184. on the format, see the [OpenSSL cipher list format documentation].
  185. - `ecdhCurve`: A string describing a named curve to use for ECDH key agreement
  186. or false to disable ECDH.
  187. Defaults to `prime256v1`. Consult [RFC 4492] for more details.
  188. - `dhparam`: DH parameter file to use for DHE key agreement. Use
  189. `openssl dhparam` command to create it. If the file is invalid to
  190. load, it is silently discarded.
  191. - `handshakeTimeout`: Abort the connection if the SSL/TLS handshake does not
  192. finish in this many milliseconds. The default is 120 seconds.
  193. A `'clientError'` is emitted on the `tls.Server` object whenever a handshake
  194. times out.
  195. - `honorCipherOrder` : When choosing a cipher, use the server's preferences
  196. instead of the client preferences. Default: `true`.
  197. Although, this option is disabled by default, it is *recommended* that you
  198. use this option in conjunction with the `ciphers` option to mitigate
  199. BEAST attacks.
  200. Note: If SSLv2 is used, the server will send its list of preferences to the
  201. client, and the client chooses the cipher. Support for SSLv2 is disabled
  202. unless node.js was configured with `./configure --with-sslv2`.
  203. - `requestCert`: If `true` the server will request a certificate from
  204. clients that connect and attempt to verify that certificate. Default:
  205. `false`.
  206. - `rejectUnauthorized`: If `true` the server will reject any connection
  207. which is not authorized with the list of supplied CAs. This option only
  208. has an effect if `requestCert` is `true`. Default: `false`.
  209. - `checkServerIdentity(servername, cert)`: Provide an override for checking
  210. server's hostname against the certificate. Should return an error if verification
  211. fails. Return `undefined` if passing.
  212. - `NPNProtocols`: An array or `Buffer` of possible NPN protocols. (Protocols
  213. should be ordered by their priority).
  214. - `SNICallback(servername, cb)`: A function that will be called if client
  215. supports SNI TLS extension. Two argument will be passed to it: `servername`,
  216. and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a
  217. SecureContext instance.
  218. (You can use `tls.createSecureContext(...)` to get proper
  219. SecureContext). If `SNICallback` wasn't provided - default callback with
  220. high-level API will be used (see below).
  221. - `sessionTimeout`: An integer specifying the seconds after which TLS
  222. session identifiers and TLS session tickets created by the server are
  223. timed out. See [SSL_CTX_set_timeout] for more details.
  224. - `ticketKeys`: A 48-byte `Buffer` instance consisting of 16-byte prefix,
  225. 16-byte hmac key, 16-byte AES key. You could use it to accept tls session
  226. tickets on multiple instances of tls server.
  227. NOTE: Automatically shared between `cluster` module workers.
  228. - `sessionIdContext`: A string containing an opaque identifier for session
  229. resumption. If `requestCert` is `true`, the default is MD5 hash value
  230. generated from command-line. Otherwise, the default is not provided.
  231. - `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force
  232. SSL version 3. The possible values depend on your installation of
  233. OpenSSL and are defined in the constant [SSL_METHODS][].
  234. - `secureOptions`: Set server options. For example, to disable the SSLv3
  235. protocol set the `SSL_OP_NO_SSLv3` flag. See [SSL_CTX_set_options]
  236. for all available options.
  237. Here is a simple example echo server:
  238. var tls = require('tls');
  239. var fs = require('fs');
  240. var options = {
  241. key: fs.readFileSync('server-key.pem'),
  242. cert: fs.readFileSync('server-cert.pem'),
  243. // This is necessary only if using the client certificate authentication.
  244. requestCert: true,
  245. // This is necessary only if the client uses the self-signed certificate.
  246. ca: [ fs.readFileSync('client-cert.pem') ]
  247. };
  248. var server = tls.createServer(options, function(socket) {
  249. console.log('server connected',
  250. socket.authorized ? 'authorized' : 'unauthorized');
  251. socket.write("welcome!\n");
  252. socket.setEncoding('utf8');
  253. socket.pipe(socket);
  254. });
  255. server.listen(8000, function() {
  256. console.log('server bound');
  257. });
  258. Or
  259. var tls = require('tls');
  260. var fs = require('fs');
  261. var options = {
  262. pfx: fs.readFileSync('server.pfx'),
  263. // This is necessary only if using the client certificate authentication.
  264. requestCert: true,
  265. };
  266. var server = tls.createServer(options, function(socket) {
  267. console.log('server connected',
  268. socket.authorized ? 'authorized' : 'unauthorized');
  269. socket.write("welcome!\n");
  270. socket.setEncoding('utf8');
  271. socket.pipe(socket);
  272. });
  273. server.listen(8000, function() {
  274. console.log('server bound');
  275. });
  276. You can test this server by connecting to it with `openssl s_client`:
  277. openssl s_client -connect 127.0.0.1:8000
  278. ## tls.connect(options[, callback])
  279. ## tls.connect(port[, host][, options][, callback])
  280. Creates a new client connection to the given `port` and `host` (old API) or
  281. `options.port` and `options.host`. (If `host` is omitted, it defaults to
  282. `localhost`.) `options` should be an object which specifies:
  283. - `host`: Host the client should connect to
  284. - `port`: Port the client should connect to
  285. - `socket`: Establish secure connection on a given socket rather than
  286. creating a new socket. If this option is specified, `host` and `port`
  287. are ignored.
  288. - `path`: Creates unix socket connection to path. If this option is
  289. specified, `host` and `port` are ignored.
  290. - `ciphers`: A string describing the ciphers to use or exclude.
  291. Defaults to
  292. `ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:AES128-GCM-SHA256:HIGH:!RC4:!MD5:!aNULL`.
  293. Consult the [OpenSSL cipher list format documentation] for details
  294. on the format.
  295. The full list of available ciphers can be obtained via [tls.getCiphers][].
  296. `ECDHE-RSA-AES128-SHA256`, `DHE-RSA-AES128-SHA256` and
  297. `AES128-GCM-SHA256` are TLS v1.2 ciphers and used when Node.js is
  298. linked against OpenSSL 1.0.1 or newer, such as the bundled version
  299. of OpenSSL.
  300. - `pfx`: A string or `Buffer` containing the private key, certificate and
  301. CA certs of the client in PFX or PKCS12 format.
  302. - `key`: A string or `Buffer` containing the private key of the client in
  303. PEM format. (Could be an array of keys).
  304. - `passphrase`: A string of passphrase for the private key or pfx.
  305. - `cert`: A string or `Buffer` containing the certificate key of the client in
  306. PEM format. (Could be an array of certs).
  307. - `ca`: An array of strings or `Buffer`s of trusted certificates in PEM
  308. format. If this is omitted several well known "root" CAs will be used,
  309. like VeriSign. These are used to authorize connections.
  310. - `rejectUnauthorized`: If `true`, the server certificate is verified against
  311. the list of supplied CAs. An `'error'` event is emitted if verification
  312. fails; `err.code` contains the OpenSSL error code. Default: `true`.
  313. - `NPNProtocols`: An array of strings or `Buffer`s containing supported NPN
  314. protocols. `Buffer`s should have following format: `0x05hello0x05world`,
  315. where first byte is next protocol name's length. (Passing array should
  316. usually be much simpler: `['hello', 'world']`.)
  317. - `servername`: Servername for SNI (Server Name Indication) TLS extension.
  318. - `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force
  319. SSL version 3. The possible values depend on your installation of
  320. OpenSSL and are defined in the constant [SSL_METHODS][].
  321. - `session`: A `Buffer` instance, containing TLS session.
  322. The `callback` parameter will be added as a listener for the
  323. ['secureConnect'][] event.
  324. `tls.connect()` returns a [tls.TLSSocket][] object.
  325. Here is an example of a client of echo server as described previously:
  326. var tls = require('tls');
  327. var fs = require('fs');
  328. var options = {
  329. // These are necessary only if using the client certificate authentication
  330. key: fs.readFileSync('client-key.pem'),
  331. cert: fs.readFileSync('client-cert.pem'),
  332. // This is necessary only if the server uses the self-signed certificate
  333. ca: [ fs.readFileSync('server-cert.pem') ]
  334. };
  335. var socket = tls.connect(8000, options, function() {
  336. console.log('client connected',
  337. socket.authorized ? 'authorized' : 'unauthorized');
  338. process.stdin.pipe(socket);
  339. process.stdin.resume();
  340. });
  341. socket.setEncoding('utf8');
  342. socket.on('data', function(data) {
  343. console.log(data);
  344. });
  345. socket.on('end', function() {
  346. server.close();
  347. });
  348. Or
  349. var tls = require('tls');
  350. var fs = require('fs');
  351. var options = {
  352. pfx: fs.readFileSync('client.pfx')
  353. };
  354. var socket = tls.connect(8000, options, function() {
  355. console.log('client connected',
  356. socket.authorized ? 'authorized' : 'unauthorized');
  357. process.stdin.pipe(socket);
  358. process.stdin.resume();
  359. });
  360. socket.setEncoding('utf8');
  361. socket.on('data', function(data) {
  362. console.log(data);
  363. });
  364. socket.on('end', function() {
  365. server.close();
  366. });
  367. ## Class: tls.TLSSocket
  368. Wrapper for instance of [net.Socket][], replaces internal socket read/write
  369. routines to perform transparent encryption/decryption of incoming/outgoing data.
  370. ## new tls.TLSSocket(socket, options)
  371. Construct a new TLSSocket object from existing TCP socket.
  372. `socket` is an instance of [net.Socket][]
  373. `options` is an object that might contain following properties:
  374. - `secureContext`: An optional TLS context object from
  375. `tls.createSecureContext( ... )`
  376. - `isServer`: If true - TLS socket will be instantiated in server-mode
  377. - `server`: An optional [net.Server][] instance
  378. - `requestCert`: Optional, see [tls.createSecurePair][]
  379. - `rejectUnauthorized`: Optional, see [tls.createSecurePair][]
  380. - `NPNProtocols`: Optional, see [tls.createServer][]
  381. - `SNICallback`: Optional, see [tls.createServer][]
  382. - `session`: Optional, a `Buffer` instance, containing TLS session
  383. - `requestOCSP`: Optional, if `true` - OCSP status request extension would
  384. be added to client hello, and `OCSPResponse` event will be emitted on socket
  385. before establishing secure communication
  386. ## tls.createSecureContext(details)
  387. Creates a credentials object, with the optional details being a
  388. dictionary with keys:
  389. * `pfx` : A string or buffer holding the PFX or PKCS12 encoded private
  390. key, certificate and CA certificates
  391. * `key` : A string holding the PEM encoded private key
  392. * `passphrase` : A string of passphrase for the private key or pfx
  393. * `cert` : A string holding the PEM encoded certificate
  394. * `ca` : Either a string or list of strings of PEM encoded CA
  395. certificates to trust.
  396. * `crl` : Either a string or list of strings of PEM encoded CRLs
  397. (Certificate Revocation List)
  398. * `ciphers`: A string describing the ciphers to use or exclude.
  399. Consult
  400. <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>
  401. for details on the format.
  402. * `honorCipherOrder` : When choosing a cipher, use the server's preferences
  403. instead of the client preferences. For further details see `tls` module
  404. documentation.
  405. If no 'ca' details are given, then node.js will use the default
  406. publicly trusted list of CAs as given in
  407. <http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt>.
  408. ## tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized])
  409. Creates a new secure pair object with two streams, one of which reads/writes
  410. encrypted data, and one reads/writes cleartext data.
  411. Generally the encrypted one is piped to/from an incoming encrypted data stream,
  412. and the cleartext one is used as a replacement for the initial encrypted stream.
  413. - `context`: A secure context object from tls.createSecureContext( ... )
  414. - `isServer`: A boolean indicating whether this tls connection should be
  415. opened as a server or a client.
  416. - `requestCert`: A boolean indicating whether a server should request a
  417. certificate from a connecting client. Only applies to server connections.
  418. - `rejectUnauthorized`: A boolean indicating whether a server should
  419. automatically reject clients with invalid certificates. Only applies to
  420. servers with `requestCert` enabled.
  421. `tls.createSecurePair()` returns a SecurePair object with `cleartext` and
  422. `encrypted` stream properties.
  423. NOTE: `cleartext` has the same APIs as [tls.TLSSocket][]
  424. ## Class: SecurePair
  425. Returned by tls.createSecurePair.
  426. ### Event: 'secure'
  427. The event is emitted from the SecurePair once the pair has successfully
  428. established a secure connection.
  429. Similarly to the checking for the server 'secureConnection' event,
  430. pair.cleartext.authorized should be checked to confirm whether the certificate
  431. used properly authorized.
  432. ## Class: tls.Server
  433. This class is a subclass of `net.Server` and has the same methods on it.
  434. Instead of accepting just raw TCP connections, this accepts encrypted
  435. connections using TLS or SSL.
  436. ### Event: 'secureConnection'
  437. `function (tlsSocket) {}`
  438. This event is emitted after a new connection has been successfully
  439. handshaked. The argument is an instance of [tls.TLSSocket][]. It has all the
  440. common stream methods and events.
  441. `socket.authorized` is a boolean value which indicates if the
  442. client has verified by one of the supplied certificate authorities for the
  443. server. If `socket.authorized` is false, then
  444. `socket.authorizationError` is set to describe how authorization
  445. failed. Implied but worth mentioning: depending on the settings of the TLS
  446. server, you unauthorized connections may be accepted.
  447. `socket.npnProtocol` is a string containing selected NPN protocol.
  448. `socket.servername` is a string containing servername requested with
  449. SNI.
  450. ### Event: 'clientError'
  451. `function (exception, tlsSocket) { }`
  452. When a client connection emits an 'error' event before secure connection is
  453. established - it will be forwarded here.
  454. `tlsSocket` is the [tls.TLSSocket][] that the error originated from.
  455. ### Event: 'newSession'
  456. `function (sessionId, sessionData, callback) { }`
  457. Emitted on creation of TLS session. May be used to store sessions in external
  458. storage. `callback` must be invoked eventually, otherwise no data will be
  459. sent or received from secure connection.
  460. NOTE: adding this event listener will have an effect only on connections
  461. established after addition of event listener.
  462. ### Event: 'resumeSession'
  463. `function (sessionId, callback) { }`
  464. Emitted when client wants to resume previous TLS session. Event listener may
  465. perform lookup in external storage using given `sessionId`, and invoke
  466. `callback(null, sessionData)` once finished. If session can't be resumed
  467. (i.e. doesn't exist in storage) one may call `callback(null, null)`. Calling
  468. `callback(err)` will terminate incoming connection and destroy socket.
  469. NOTE: adding this event listener will have an effect only on connections
  470. established after addition of event listener.
  471. ### Event: 'OCSPRequest'
  472. `function (certificate, issuer, callback) { }`
  473. Emitted when the client sends a certificate status request. You could parse
  474. server's current certificate to obtain OCSP url and certificate id, and after
  475. obtaining OCSP response invoke `callback(null, resp)`, where `resp` is a
  476. `Buffer` instance. Both `certificate` and `issuer` are a `Buffer`
  477. DER-representations of the primary and issuer's certificates. They could be used
  478. to obtain OCSP certificate id and OCSP endpoint url.
  479. Alternatively, `callback(null, null)` could be called, meaning that there is no
  480. OCSP response.
  481. Calling `callback(err)` will result in a `socket.destroy(err)` call.
  482. Typical flow:
  483. 1. Client connects to server and sends `OCSPRequest` to it (via status info
  484. extension in ClientHello.)
  485. 2. Server receives request and invokes `OCSPRequest` event listener if present
  486. 3. Server grabs OCSP url from either `certificate` or `issuer` and performs an
  487. [OCSP request] to the CA
  488. 4. Server receives `OCSPResponse` from CA and sends it back to client via
  489. `callback` argument
  490. 5. Client validates the response and either destroys socket or performs a
  491. handshake.
  492. NOTE: `issuer` could be null, if the certificate is self-signed or if the issuer
  493. is not in the root certificates list. (You could provide an issuer via `ca`
  494. option.)
  495. NOTE: adding this event listener will have an effect only on connections
  496. established after addition of event listener.
  497. NOTE: you may want to use some npm module like [asn1.js] to parse the
  498. certificates.
  499. ### server.listen(port[, host][, callback])
  500. Begin accepting connections on the specified `port` and `host`. If the
  501. `host` is omitted, the server will accept connections directed to any
  502. IPv4 address (`INADDR_ANY`).
  503. This function is asynchronous. The last parameter `callback` will be called
  504. when the server has been bound.
  505. See `net.Server` for more information.
  506. ### server.close()
  507. Stops the server from accepting new connections. This function is
  508. asynchronous, the server is finally closed when the server emits a `'close'`
  509. event.
  510. ### server.address()
  511. Returns the bound address, the address family name and port of the
  512. server as reported by the operating system. See [net.Server.address()][] for
  513. more information.
  514. ### server.addContext(hostname, context)
  515. Add secure context that will be used if client request's SNI hostname is
  516. matching passed `hostname` (wildcards can be used). `context` can contain
  517. `key`, `cert`, `ca` and/or any other properties from `tls.createSecureContext`
  518. `options` argument.
  519. ### server.maxConnections
  520. Set this property to reject connections when the server's connection count
  521. gets high.
  522. ### server.connections
  523. The number of concurrent connections on the server.
  524. ## Class: CryptoStream
  525. Stability: 0 - Deprecated. Use tls.TLSSocket instead.
  526. This is an encrypted stream.
  527. ### cryptoStream.bytesWritten
  528. A proxy to the underlying socket's bytesWritten accessor, this will return
  529. the total bytes written to the socket, *including the TLS overhead*.
  530. ## Class: tls.TLSSocket
  531. This is a wrapped version of [net.Socket][] that does transparent encryption
  532. of written data and all required TLS negotiation.
  533. This instance implements a duplex [Stream][] interfaces. It has all the
  534. common stream methods and events.
  535. ### Event: 'secureConnect'
  536. This event is emitted after a new connection has been successfully handshaked.
  537. The listener will be called no matter if the server's certificate was
  538. authorized or not. It is up to the user to test `tlsSocket.authorized`
  539. to see if the server certificate was signed by one of the specified CAs.
  540. If `tlsSocket.authorized === false` then the error can be found in
  541. `tlsSocket.authorizationError`. Also if NPN was used - you can check
  542. `tlsSocket.npnProtocol` for negotiated protocol.
  543. ### Event: 'OCSPResponse'
  544. `function (response) { }`
  545. This event will be emitted if `requestOCSP` option was set. `response` is a
  546. buffer object, containing server's OCSP response.
  547. Traditionally, the `response` is a signed object from the server's CA that
  548. contains information about server's certificate revocation status.
  549. ### tlsSocket.encrypted
  550. Static boolean value, always `true`. May be used to distinguish TLS sockets
  551. from regular ones.
  552. ### tlsSocket.authorized
  553. A boolean that is `true` if the peer certificate was signed by one of the
  554. specified CAs, otherwise `false`
  555. ### tlsSocket.authorizationError
  556. The reason why the peer's certificate has not been verified. This property
  557. becomes available only when `tlsSocket.authorized === false`.
  558. ### tlsSocket.getPeerCertificate([ detailed ])
  559. Returns an object representing the peer's certificate. The returned object has
  560. some properties corresponding to the field of the certificate. If `detailed`
  561. argument is `true` - the full chain with `issuer` property will be returned,
  562. if `false` - only the top certificate without `issuer` property.
  563. Example:
  564. { subject:
  565. { C: 'UK',
  566. ST: 'Acknack Ltd',
  567. L: 'Rhys Jones',
  568. O: 'node.js',
  569. OU: 'Test TLS Certificate',
  570. CN: 'localhost' },
  571. issuerInfo:
  572. { C: 'UK',
  573. ST: 'Acknack Ltd',
  574. L: 'Rhys Jones',
  575. O: 'node.js',
  576. OU: 'Test TLS Certificate',
  577. CN: 'localhost' },
  578. issuer:
  579. { ... another certificate ... },
  580. raw: < RAW DER buffer >,
  581. valid_from: 'Nov 11 09:52:22 2009 GMT',
  582. valid_to: 'Nov 6 09:52:22 2029 GMT',
  583. fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF',
  584. serialNumber: 'B9B0D332A1AA5635' }
  585. If the peer does not provide a certificate, it returns `null` or an empty
  586. object.
  587. ### tlsSocket.getCipher()
  588. Returns an object representing the cipher name and the SSL/TLS
  589. protocol version of the current connection.
  590. Example:
  591. { name: 'AES256-SHA', version: 'TLSv1/SSLv3' }
  592. See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in
  593. http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more
  594. information.
  595. ### tlsSocket.renegotiate(options, callback)
  596. Initiate TLS renegotiation process. The `options` may contain the following
  597. fields: `rejectUnauthorized`, `requestCert` (See [tls.createServer][]
  598. for details). `callback(err)` will be executed with `null` as `err`,
  599. once the renegotiation is successfully completed.
  600. NOTE: Can be used to request peer's certificate after the secure connection
  601. has been established.
  602. ANOTHER NOTE: When running as the server, socket will be destroyed
  603. with an error after `handshakeTimeout` timeout.
  604. ### tlsSocket.setMaxSendFragment(size)
  605. Set maximum TLS fragment size (default and maximum value is: `16384`, minimum
  606. is: `512`). Returns `true` on success, `false` otherwise.
  607. Smaller fragment size decreases buffering latency on the client: large
  608. fragments are buffered by the TLS layer until the entire fragment is received
  609. and its integrity is verified; large fragments can span multiple roundtrips,
  610. and their processing can be delayed due to packet loss or reordering. However,
  611. smaller fragments add extra TLS framing bytes and CPU overhead, which may
  612. decrease overall server throughput.
  613. ### tlsSocket.getSession()
  614. Return ASN.1 encoded TLS session or `undefined` if none was negotiated. Could
  615. be used to speed up handshake establishment when reconnecting to the server.
  616. ### tlsSocket.getTLSTicket()
  617. NOTE: Works only with client TLS sockets. Useful only for debugging, for
  618. session reuse provide `session` option to `tls.connect`.
  619. Return TLS session ticket or `undefined` if none was negotiated.
  620. ### tlsSocket.address()
  621. Returns the bound address, the address family name and port of the
  622. underlying socket as reported by the operating system. Returns an
  623. object with three properties, e.g.
  624. `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
  625. ### tlsSocket.remoteAddress
  626. The string representation of the remote IP address. For example,
  627. `'74.125.127.100'` or `'2001:4860:a005::68'`.
  628. ### tlsSocket.remoteFamily
  629. The string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
  630. ### tlsSocket.remotePort
  631. The numeric representation of the remote port. For example, `443`.
  632. ### tlsSocket.localAddress
  633. The string representation of the local IP address.
  634. ### tlsSocket.localPort
  635. The numeric representation of the local port.
  636. [OpenSSL cipher list format documentation]: http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT
  637. [BEAST attacks]: http://blog.ivanristic.com/2011/10/mitigating-the-beast-attack-on-tls.html
  638. [tls.getCiphers]: #tls_tls_getciphers
  639. [tls.createServer]: #tls_tls_createserver_options_secureconnectionlistener
  640. [tls.createSecurePair]: #tls_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized
  641. [tls.TLSSocket]: #tls_class_tls_tlssocket
  642. [net.Server]: net.html#net_class_net_server
  643. [net.Socket]: net.html#net_class_net_socket
  644. [net.Server.address()]: net.html#net_server_address
  645. ['secureConnect']: #tls_event_secureconnect
  646. [secureConnection]: #tls_event_secureconnection
  647. [Stream]: stream.html#stream_stream
  648. [SSL_METHODS]: http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS
  649. [tls.Server]: #tls_class_tls_server
  650. [SSL_CTX_set_timeout]: http://www.openssl.org/docs/ssl/SSL_CTX_set_timeout.html
  651. [RFC 4492]: http://www.rfc-editor.org/rfc/rfc4492.txt
  652. [Forward secrecy]: http://en.wikipedia.org/wiki/Perfect_forward_secrecy
  653. [DHE]: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
  654. [ECDHE]: https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman
  655. [asn1.js]: http://npmjs.org/package/asn1.js
  656. [OCSP request]: http://en.wikipedia.org/wiki/OCSP_stapling
  657. [TLS recommendations]: https://wiki.mozilla.org/Security/Server_Side_TLS
  658. [SSL_CTX_set_options]: https://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
  659. [CVE-2014-3566]: https://access.redhat.com/articles/1232123