Node.js v0.10.18 手册 & 文档
目录
- TLS (SSL)
- Client-initiated renegotiation attack mitigation
- NPN 和 SNI
- tls.getCiphers()
- tls.createServer(options, [secureConnectionListener])
- tls.connect(options, [callback])
- tls.connect(port, [host], [options], [callback])
- tls.connect(options, [callback])
- tls.connect(port, [host], [options], [callback])
- 类: tls.TLSSocket
- new tls.TLSSocket(socket, options)
- tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])
- 类: SecurePair
- 类: tls.Server
- 类: CryptoStream
- 类: tls.TLSSocket
TLS (SSL)#
稳定度: 3 - 稳定
Use require('tls')
to access this module.
使用 require('tls')
来访问此模块。
The tls
module uses OpenSSL to provide Transport Layer Security and/or
Secure Socket Layer: encrypted stream communication.
tls
模块使用 OpenSSL 来提供传输层安全协议(Transport Layer Security)和/或安全套接层(Secure Socket Layer):加密过的流通讯。
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
TLS/SSL 是一种公钥/私钥架构。每个客户端和服务器都必有一个私钥。一个私钥使用类似的方式创建:
openssl genrsa -out ryans-key.pem 1024
All severs 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:
所有服务器和某些客户端需要具备证书。证书是证书办法机构签发或自签发的公钥。获取证书的第一步是创建一个“证书签发申请”(CSR)文件。使用这条命令完成:
openssl req -new -key ryans-key.pem -out ryans-csr.pem
To create a self-signed certificate with the CSR, do this:
像这样使用 CSR 创建一个自签名证书:
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.
又或者你可以将 CSR 发送给一个数字证书认证机构请求签名。
(TODO: docs on creating a CA, for now interested users should just look at
test/fixtures/keys/Makefile
in the Node source code)
To create .pfx or .p12, do this:
像这样创建 .pfx 或 .p12:
openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \
-certfile ca-cert.pem -out agent5.pfx
in
: certificateinkey
: private keycertfile
: all CA certs concatenated in one file likecat ca1-cert.pem ca2-cert.pem > ca-cert.pem
in
: certificateinkey
: private keycertfile
: all CA certs concatenated in one file likecat ca1-cert.pem ca2-cert.pem > ca-cert.pem
Client-initiated renegotiation attack mitigation#
The TLS protocol lets the client renegotiate certain aspects of the TLS session. Unfortunately, session renegotiation requires a disproportional amount of server-side resources, which makes it a potential vector for denial-of-service attacks.
TLS协议会令客户端可以重新协商TLS会话的某些方面。但是,会话的重新协商是需要相应量的服务器端资源的,所以导致其变成一个阻断服务攻击(denial-of-service)的潜在媒介。
To mitigate this, renegotiations are limited to three times every 10 minutes. An error is emitted on the tls.TLSSocket instance when the threshold is exceeded. The limits are configurable:
为了减低这种情况的发生,重新协商被限制在每10分钟三次。如果超过这个数目,那么在tls.TLSSocket实例上就会分发一个错误。这个限制是可设置的:
tls.CLIENT_RENEG_LIMIT
: renegotiation limit, default is 3.tls.CLIENT_RENEG_LIMIT
: 重新协商的次数限制,默认为3。tls.CLIENT_RENEG_WINDOW
: renegotiation window in seconds, default is 10 minutes.tls.CLIENT_RENEG_WINDOW
: 重新协商窗口的秒数,默认为600(10分钟)。
Don't change the defaults unless you know what you are doing.
除非你完全理解整个机制和清楚自己要干什么,否则不要改变这个默认值。
To test your server, connect to it with openssl s_client -connect address:port
and tap R<CR>
(that's the letter R
followed by a carriage return) a few
times.
要测试你的服务器的话,用命令 openssl s_client -connect 地址:端口
连接上服务器,然后敲击R<CR>
(字母键R
加回车键)几次。
NPN 和 SNI#
NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS handshake extensions allowing you:
- NPN - to use one TLS server for multiple protocols (HTTP, SPDY)
- SNI - to use one TLS server for multiple hostnames with different SSL certificates.
tls.getCiphers()#
Returns an array with the names of the supported SSL ciphers.
返回一个数组,其中包含了所支持的SSL加密器的名字。
Example:
示例:
var ciphers = tls.getCiphers();
console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]
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 has these possibilities:
新建一个新的 tls.Server. The connectionListener
参数会自动设置为 secureConnection 事件的监听器. 这个 options
对象有这些可能性:
pfx
: A string orBuffer
containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with thekey
,cert
andca
options.)pfx
: 一个String 或Buffer
包含了私钥, 证书和CA certs, 一般是 PFX 或者 PKCS12 格式. (Mutually exclusive with thekey
,cert
andca
options.)key
: A string orBuffer
containing the private key of the server in PEM format. (Required)key
: 一个字符串或Buffer
对象,其中包含了PEF格式的服务器的私钥。 (必需)passphrase
: A string of passphrase for the private key or pfx.passphrase
: 私钥或pfx密码的字符串。cert
: A string orBuffer
containing the certificate key of the server in PEM format. (Required)ca
: An array of strings orBuffer
s of trusted certificates. If this is omitted several well known "root" CAs will be used, like VeriSign. 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.NOTE: Previous revisions of this section suggested
AES256-SHA
as an acceptable cipher. Unfortunately,AES256-SHA
is a CBC cipher and therefore susceptible to BEAST attacks. Do not use it.handshakeTimeout
: Abort the connection if the SSL/TLS handshake does not finish in this many milliseconds. The default is 120 seconds.A
'clientError'
is emitted on thetls.Server
object whenever a handshake times out.honorCipherOrder
: When choosing a cipher, use the server's preferences instead of the client preferences.Although, this option is disabled by default, it is recommended that you use this option in conjunction with the
ciphers
option to mitigate BEAST attacks.requestCert
: Iftrue
the server will request a certificate from clients that connect and attempt to verify that certificate. Default:false
.rejectUnauthorized
: Iftrue
the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect ifrequestCert
istrue
. Default:false
.NPNProtocols
: An array orBuffer
of possible NPN protocols. (Protocols should be ordered by their priority).SNICallback(servername, cb)
: A function that will be called if client supports SNI TLS extension. Two argument will be passed to it:servername
, andcb
.SNICallback
should invokecb(null, ctx)
, wherectx
is a SecureContext instance. (You can usecrypto.createCredentials(...).context
to get proper SecureContext). IfSNICallback
wasn't provided - default callback with high-level API will be used (see below).sessionTimeout
: An integer specifying the seconds after which TLS session identifiers and TLS session tickets created by the server are timed out. See SSL_CTX_set_timeout for more details.sessionIdContext
: A string containing a opaque identifier for session resumption. IfrequestCert
istrue
, the default is MD5 hash value generated from command-line. Otherwise, the default is not provided.secureProtocol
: The SSL method to use, e.g.SSLv3_method
to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS.
Here is a simple example echo server:
这是一个简单的应答服务器例子:
var server = tls.createServer(options, function(socket) {
console.log('服务器已连接',
socket.authorized ? '已授权' : '未授权');
socket.write("欢迎!\n");
socket.setEncoding('utf8');
socket.pipe(socket);
});
server.listen(8000, function() {
console.log('server bound');
});
Or
或者
};
var server = tls.createServer(options, function(socket) {
console.log('server connected',
socket.authorized ? 'authorized' : 'unauthorized');
socket.write("welcome!\n");
socket.setEncoding('utf8');
socket.pipe(socket);
});
server.listen(8000, function() {
console.log('server bound');
});
You can test this server by connecting to it with openssl s_client
:
var server = tls.createServer(options, function(socket) {
console.log('服务器已连接',
socket.authorized ? '已授权' : '未授权');
socket.write("欢迎!\n");
socket.setEncoding('utf8');
socket.pipe(socket);
});
server.listen(8000, function() {
console.log('服务器已绑定');
});
您可以使用 openssl s_client
连接这个服务器来测试:
openssl s_client -connect 127.0.0.1:8000
tls.connect(options, [callback])#
tls.connect(port, [host], [options], [callback])#
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 toport
: Port the client should connect tosocket
: Establish secure connection on a given socket rather than creating a new socket. If this option is specified,host
andport
are ignored.pfx
: A string orBuffer
containing the private key, certificate and CA certs of the server in PFX or PKCS12 format.key
: A string orBuffer
containing the private key of the client in PEM format.passphrase
: A string of passphrase for the private key or pfx.passphrase
: 私钥或pfx密码的字符串。cert
: A string orBuffer
containing the certificate key of the client in PEM format.ca
: An array of strings orBuffer
s of trusted certificates. If this is omitted several well known "root" CAs will be used, like VeriSign. These are used to authorize connections.rejectUnauthorized
: Iftrue
, the server certificate is verified against the list of supplied CAs. An'error'
event is emitted if verification fails. Default:true
.NPNProtocols
: An array of string orBuffer
containing supported NPN protocols.Buffer
should have following format:0x05hello0x05world
, where first byte is next protocol name's length. (Passing array should usually be much simpler:['hello', 'world']
.)servername
: Servername for SNI (Server Name Indication) TLS extension.secureProtocol
: The SSL method to use, e.g.SSLv3_method
to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS.
The callback
parameter will be added as a listener for the
'secureConnect' event.
callback
参数会被作为监听器添加到'secureConnect'事件。
tls.connect()
returns a tls.TLSSocket object.
tls.connect()
返回一个tls.TLSSocket对象。
Here is an example of a client of echo server as described previously:
下面是一个上述应答服务器的客户端的例子:
var socket = tls.connect(8000, options, function() {
console.log('client connected',
socket.authorized ? 'authorized' : 'unauthorized');
process.stdin.pipe(socket);
process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', function(data) {
console.log(data);
});
socket.on('end', function() {
server.close();
});
Or
或者
var socket = tls.connect(8000, options, function() {
console.log('client connected',
socket.authorized ? 'authorized' : 'unauthorized');
process.stdin.pipe(socket);
process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', function(data) {
console.log(data);
});
socket.on('end', function() {
server.close();
});
类: tls.TLSSocket#
Wrapper for instance of net.Socket, replaces internal socket read/write routines to perform transparent encryption/decryption of incoming/outgoing data.
new tls.TLSSocket(socket, options)#
Construct a new TLSSocket object from existing TCP socket.
socket
is an instance of net.Socket
socket
是一个net.Socket示例。
options
is an object that might contain following properties:
options
是一个可能包含以下属性的对象:
credentials
: An optional credentials object fromcrypto.createCredentials( ... )
isServer
: If true - TLS socket will be instantiated in server-modeserver
: An optional net.Server instanceserver
: 一个可选的net.Server实例requestCert
: Optional, see tls.createSecurePairrequestCert
: 可选的,见tls.createSecurePairrejectUnauthorized
: Optional, see tls.createSecurePairrejectUnauthorized
: 可选的,见tls.createSecurePairNPNProtocols
: Optional, see tls.createServerNPNProtocols
: 可选的,见tls.createServerSNICallback
: Optional, see tls.createServerSNICallback
: 可选的,见tls.createServer
tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])#
稳定性: 0 - 已废弃。使用 tls.TLSSocket 替代。
Creates a new secure pair object with two streams, one of which reads/writes encrypted data, and one reads/writes cleartext data. Generally the encrypted one 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 credentials object from crypto.createCredentials( ... )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 withrequestCert
enabled.
tls.createSecurePair()
returns a SecurePair object with cleartext
and
encrypted
stream properties.
NOTE: cleartext
has the same APIs as tls.TLSSocket
类: SecurePair#
Returned by tls.createSecurePair.
由tls.createSecurePair返回。
事件: 'secure'#
The event is emitted from the SecurePair once the pair has successfully established a secure connection.
Similarly to the checking for the server 'secureConnection' event, pair.cleartext.authorized should be checked to confirm whether the certificate used properly authorized.
类: tls.Server#
This class is a subclass of net.Server
and has the same methods on it.
Instead of accepting just raw TCP connections, this accepts encrypted
connections using TLS or SSL.
事件: 'secureConnection'#
function (tlsSocket) {}
function (tlsSocket) {}
This event is emitted after a new connection has been successfully handshaked. The argument is a instance of tls.TLSSocket. It has all the common stream methods and events.
socket.authorized
is a boolean value which indicates if the
client has verified by one of the supplied certificate authorities for the
server. If socket.authorized
is false, then
socket.authorizationError
is set to describe how authorization
failed. Implied but worth mentioning: depending on the settings of the TLS
server, you unauthorized connections may be accepted.
socket.npnProtocol
is a string containing selected NPN protocol.
socket.servername
is a string containing servername requested with
SNI.
Event: 'clientError'#
function (exception, tlsSocket) { }
function (exception, tlsSocket) { }
When a client connection emits an 'error' event before secure connection is established - it will be forwarded here.
tlsSocket
is the tls.TLSSocket that the error originated from.
事件: 'newSession'#
function (sessionId, sessionData) { }
function (sessionId, sessionData) { }
Emitted on creation of TLS session. May be used to store sessions in external storage.
NOTE: adding this event listener will have an effect only on connections established after addition of event listener.
事件: 'resumeSession'#
function (sessionId, callback) { }
function (sessionId, callback) { }
Emitted when client wants to resume previous TLS session. Event listener may
perform lookup in external storage using given sessionId
, and invoke
callback(null, sessionData)
once finished. If session can't be resumed
(i.e. doesn't exist in storage) one may call callback(null, null)
. Calling
callback(err)
will terminate incoming connection and destroy socket.
NOTE: adding this event listener will have an effect only on connections established after addition of event listener.
server.listen(port, [host], [callback])#
Begin accepting connections on the specified port
and host
. If the
host
is omitted, the server will accept connections directed to any
IPv4 address (INADDR_ANY
).
This function is asynchronous. The last parameter callback
will be called
when the server has been bound.
See net.Server
for more information.
更多信息见net.Server
。
server.close()#
Stops the server from accepting new connections. This function is
asynchronous, the server is finally closed when the server emits a 'close'
event.
server.address()#
Returns the bound address, the address family name and port of the server as reported by the operating system. See net.Server.address() for more information.
server.addContext(hostname, credentials)#
Add secure context that will be used if client request's SNI hostname is
matching passed hostname
(wildcards can be used). credentials
can contain
key
, cert
and ca
.
server.maxConnections#
Set this property to reject connections when the server's connection count gets high.
server.connections#
The number of concurrent connections on the server.
服务器的并发连接数.
类: CryptoStream#
稳定性: 0 - 已废弃。使用 tls.TLSSocket 替代。
This is an encrypted stream.
这是一个被加密的流。
cryptoStream.bytesWritten#
A proxy to the underlying socket's bytesWritten accessor, this will return the total bytes written to the socket, including the TLS overhead.
类: tls.TLSSocket#
This is a wrapped version of net.Socket that does transparent encryption of written data and all required TLS negotiation.
This instance implements a duplex Stream interfaces. It has all the common stream methods and events.
事件: 'secureConnect'#
This event is emitted after a new connection has been successfully handshaked.
The listener will be called no matter if the server's certificate was
authorized or not. It is up to the user to test tlsSocket.authorized
to see if the server certificate was signed by one of the specified CAs.
If tlsSocket.authorized === false
then the error can be found in
tlsSocket.authorizationError
. Also if NPN was used - you can check
tlsSocket.npnProtocol
for negotiated protocol.
tlsSocket.authorized#
A boolean that is true
if the peer certificate was signed by one of the
specified CAs, otherwise false
tlsSocket.authorizationError#
The reason why the peer's certificate has not been verified. This property
becomes available only when tlsSocket.authorized === false
.
tlsSocket.getPeerCertificate()#
Returns an object representing the peer's certificate. The returned object has some properties corresponding to the field of the certificate.
Example:
示例:
{ subject:
{ C: 'UK',
ST: 'Acknack Ltd',
L: 'Rhys Jones',
O: 'node.js',
OU: 'Test TLS Certificate',
CN: 'localhost' },
issuer:
{ C: 'UK',
ST: 'Acknack Ltd',
L: 'Rhys Jones',
O: 'node.js',
OU: 'Test TLS Certificate',
CN: 'localhost' },
valid_from: 'Nov 11 09:52:22 2009 GMT',
valid_to: 'Nov 6 09:52:22 2029 GMT',
fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' }
If the peer does not provide a certificate, it returns null
or an empty
object.
tlsSocket.getCipher()#
Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection.
Example: { name: 'AES256-SHA', version: 'TLSv1/SSLv3' }
Example: { name: 'AES256-SHA', version: 'TLSv1/SSLv3' }
See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more information.
tlsSocket.renegotiate(options, callback)#
Initiate TLS renegotiation process. The options
may contain the following
fields: rejectUnauthorized
, requestCert
(See tls.createServer
for details). callback(err)
will be executed with null
as err
,
once the renegotiation is successfully completed.
NOTE: Can be used to request peer's certificate after the secure connection has been established.
ANOTHER NOTE: When running as the server, socket will be destroyed
with an error after handshakeTimeout
timeout.
tlsSocket.address()#
Returns the bound address, the address family name and port of the
underlying socket as reported by the operating system. Returns an
object with three properties, e.g.
{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
tlsSocket.remoteAddress#
The string representation of the remote IP address. For example,
'74.125.127.100'
or '2001:4860:a005::68'
.
远程IP地址的字符串表示。例如,'74.125.127.100'
或 '2001:4860:a005::68'
。
tlsSocket.remotePort#
The numeric representation of the remote port. For example, 443
.
远程端口的数值表示。例如, 443
。
tlsSocket.localAddress#
The string representation of the local IP address.
本地IP地址的字符串表达。
tlsSocket.localPort#
The numeric representation of the local port.
本地端口的数值表示。