Node.js v18.20.8 文档


传输层安全 (TLS/SSL)#>

【TLS (SSL)】

源代码: lib/tls.js

node:tls 模块提供了基于 OpenSSL 构建的传输层安全(TLS)和安全套接字层(SSL)协议的实现。可以通过以下方式访问该模块:

【The node:tls module provides an implementation of the Transport Layer Security (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. The module can be accessed using:】

const tls = require('node:tls'); 

确定加密支持是否不可用#>

【Determining if crypto support is unavailable】

Node.js 有可能在构建时不包含对 node:crypto 模块的支持。在这种情况下,尝试从 tls 导入或调用 require('node:tls') 将会导致抛出错误。

【It is possible for Node.js to be built without including support for the node:crypto module. In such cases, attempting to import from tls or calling require('node:tls') will result in an error being thrown.】

使用 CommonJS 时,可以使用 try/catch 捕获抛出的错误:

【When using CommonJS, the error thrown can be caught using try/catch:】

let tls;
try {
  tls = require('node:tls');
} catch (err) {
  console.error('tls support is disabled!');
} 

在使用词法 ESM import 关键字时,只有在尝试加载模块之前(例如使用预加载模块)注册了 process.on('uncaughtException') 的处理程序,才能捕获该错误。

【When using the lexical ESM import keyword, the error can only be caught if a handler for process.on('uncaughtException') is registered before any attempt to load the module is made (using, for instance, a preload module).】

在使用 ESM 时,如果代码有可能在未启用加密支持的 Node.js 版本上运行,考虑使用 import() 函数替代词法 import 关键字:

【When using ESM, if there is a chance that the code may be run on a build of Node.js where crypto support is not enabled, consider using the import() function instead of the lexical import keyword:】

let tls;
try {
  tls = await import('node:tls');
} catch (err) {
  console.error('tls support is disabled!');
} 

TLS/SSL 概念#>

【TLS/SSL concepts】

TLS/SSL 是一组依赖公钥基础设施(PKI)的协议,用于实现客户端与服务器之间的安全通信。在大多数常见情况下,每个服务器都必须拥有一个私钥。

【TLS/SSL is a set of protocols that rely on a public key infrastructure (PKI) to enable secure communication between a client and a server. For most common cases, each server must have a private key.】

私钥可以通过多种方式生成。下面的示例说明了如何使用 OpenSSL 命令行接口生成一个 2048 位的 RSA 私钥:

【Private keys can be generated in multiple ways. The example below illustrates use of the OpenSSL command-line interface to generate a 2048-bit RSA private key:】

openssl genrsa -out ryans-key.pem 2048 

使用 TLS/SSL,所有服务器(以及部分客户端)必须拥有一个_证书_。证书是与私钥对应的_公钥_,并且由证书颁发机构或私钥的所有者进行数字签名(这样的证书称为“自签名”)。获取证书的第一步是创建一个_证书签名请求_(CSR)文件。

【With TLS/SSL, all servers (and some clients) must have a certificate. Certificates are public keys that correspond to a private key, and that are digitally signed either by a Certificate Authority or by the owner of the private key (such certificates are referred to as "self-signed"). The first step to obtaining a certificate is to create a Certificate Signing Request (CSR) file.】

可以使用 OpenSSL 命令行接口为私钥生成 CSR:

【The OpenSSL command-line interface can be used to generate a CSR for a private key:】

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

一旦生成了 CSR 文件,它可以发送到证书颁发机构进行签名,也可以用来生成自签名证书。

【Once the CSR file is generated, it can either be sent to a Certificate Authority for signing or used to generate a self-signed certificate.】

下面的示例演示了如何使用 OpenSSL 命令行接口创建自签名证书:

【Creating a self-signed certificate using the OpenSSL command-line interface is illustrated in the example below:】

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

一旦证书生成,就可以用它来生成 .pfx.p12 文件:

【Once the certificate is generated, it can be used to generate a .pfx or .p12 file:】

openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \
      -certfile ca-cert.pem -out ryans.pfx 

在哪里:

【Where:】

  • in:是签署的证书
  • inkey:是关联的私钥
  • certfile:是将所有证书颁发机构(CA)的证书合并到一个文件中,例如 cat ca1-cert.pem ca2-cert.pem > ca-cert.pem

完美前向保密#>

【Perfect forward secrecy】

术语 前向保密 或“完美前向保密”描述了密钥协商(即密钥交换)方法的一种特性。也就是说,服务器和客户端的密钥用于协商新的临时密钥,这些临时密钥仅用于当前的通信会话。实际上,这意味着即使服务器的私钥被泄露,窃听者也只能在攻击者设法获取专门为该会话生成的密钥对时才能解密通信。

【The term forward secrecy or perfect forward secrecy describes a feature of key-agreement (i.e., key-exchange) methods. That is, the server and client keys are used to negotiate new temporary keys that are used specifically and only for the current communication session. Practically, this means that even if the server's private key is compromised, communication can only be decrypted by eavesdroppers if the attacker manages to obtain the key-pair specifically generated for the session.】

完美前向保密性通过在每次 TLS/SSL 握手时随机生成密钥对来实现(与对所有会话使用相同密钥相反)。实现这种技术的方法称为“临时密钥”。

【Perfect forward secrecy is achieved by randomly generating a key pair for key-agreement on every TLS/SSL handshake (in contrast to using the same key for all sessions). Methods implementing this technique are called "ephemeral".】

目前通常使用两种方法来实现完美前向保密(注意在传统缩写后加上的字符“E”):

【Currently two methods are commonly used to achieve perfect forward secrecy (note the character "E" appended to the traditional abbreviations):】

  • ECDHE:椭圆曲线迪菲-赫尔曼密钥协商协议的临时版本。
  • DHE:Diffie-Hellman 密钥协商协议的临时版本。

使用 ECDHE 的完美前向保密性默认启用。在创建 TLS 服务器时,可以使用 ecdhCurve 选项来自定义支持的 ECDH 曲线列表。更多信息请参见 tls.createServer()

【Perfect forward secrecy using ECDHE is enabled by default. The ecdhCurve option can be used when creating a TLS server to customize the list of supported ECDH curves to use. See tls.createServer() for more info.】

DHE 默认情况下是禁用的,但可以通过将 dhparam 选项设置为 'auto' 来与 ECDHE 一起启用。也支持自定义 DHE 参数,但建议使用自动选择的知名参数。

【DHE is disabled by default but can be enabled alongside ECDHE by setting the dhparam option to 'auto'. Custom DHE parameters are also supported but discouraged in favor of automatically selected, well-known parameters.】

在 TLSv1.2 之前,完美前向保密是可选的。从 TLSv1.3 开始,(EC)DHE 总是被使用(仅 PSK 连接除外)。

【Perfect forward secrecy was optional up to TLSv1.2. As of TLSv1.3, (EC)DHE is always used (with the exception of PSK-only connections).】

ALPN 和 SNI#>

【ALPN and SNI】

ALPN(应用层协议协商扩展)和 SNI(服务器名称指示)是 TLS 握手扩展:

【ALPN (Application-Layer Protocol Negotiation Extension) and SNI (Server Name Indication) are TLS handshake extensions:】

  • ALPN:允许一个 TLS 服务器用于多个协议(HTTP、HTTP/2)
  • SNI:允许一个 TLS 服务器使用不同证书来服务多个主机名。

预共享密钥#>

【Pre-shared keys】

TLS-PSK 支持可以作为普通基于证书的认证的替代方案。它使用预共享密钥而不是证书来认证 TLS 连接,从而提供双向认证。TLS-PSK 与公钥基础设施并不互相排斥。客户端和服务器可以同时支持两者,并在正常的密码协商步骤中选择其中一种。

【TLS-PSK support is available as an alternative to normal certificate-based authentication. It uses a pre-shared key instead of certificates to authenticate a TLS connection, providing mutual authentication. TLS-PSK and public key infrastructure are not mutually exclusive. Clients and servers can accommodate both, choosing either of them during the normal cipher negotiation step.】

TLS-PSK 仅在有办法与每台连接的机器安全共享密钥的情况下才是一个好的选择,因此它不能替代大多数 TLS 使用场景下的公钥基础设施(PKI)。 近年来,OpenSSL 中的 TLS-PSK 实现出现了许多安全漏洞,主要是因为它只被少数应用使用。请在切换到 PSK 密码套件之前考虑所有替代解决方案。 生成 PSK 时,使用足够的熵至关重要,如 RFC 4086 所述。从密码或其他低熵来源派生共享密钥是不安全的。

【TLS-PSK is only a good choice where means exist to securely share a key with every connecting machine, so it does not replace the public key infrastructure (PKI) for the majority of TLS uses. The TLS-PSK implementation in OpenSSL has seen many security flaws in recent years, mostly because it is used only by a minority of applications. Please consider all alternative solutions before switching to PSK ciphers. Upon generating PSK it is of critical importance to use sufficient entropy as discussed in RFC 4086. Deriving a shared secret from a password or other low-entropy sources is not secure.】

PSK 加密套件默认情况下是禁用的,因此使用 TLS-PSK 需要通过 ciphers 选项显式指定一个加密套件。可用加密套件的列表可以通过 openssl ciphers -v 'PSK' 获取。所有 TLS 1.3 加密套件都适用于 PSK,并且可以通过 openssl ciphers -v -s -tls1_3 -psk 获取。

【PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with the ciphers option. The list of available ciphers can be retrieved via openssl ciphers -v 'PSK'. All TLS 1.3 ciphers are eligible for PSK and can be retrieved via openssl ciphers -v -s -tls1_3 -psk.】

根据 RFC 4279,必须支持长达 128 字节的 PSK 标识符和长达 64 字节的 PSK。截至 OpenSSL 1.1.0,最大标识符大小为 128 字节,最大 PSK 长度为 256 字节。

【According to the RFC 4279, PSK identities up to 128 bytes in length and PSKs up to 64 bytes in length must be supported. As of OpenSSL 1.1.0 maximum identity size is 128 bytes, and maximum PSK length is 256 bytes.】

由于底层 OpenSSL API 的限制,当前的实现不支持异步 PSK 回调。

【The current implementation doesn't support asynchronous PSK callbacks due to the limitations of the underlying OpenSSL API.】

客户端发起的重新协商攻击缓解#>

【Client-initiated renegotiation attack mitigation】

TLS 协议允许客户端重新协商 TLS 会话的某些方面。不幸的是,会话重新协商会消耗大量的服务器资源,使其成为潜在的拒绝服务攻击的途径。

【The TLS protocol allows clients to renegotiate certain aspects of the TLS session. Unfortunately, session renegotiation requires a disproportionate amount of server-side resources, making it a potential vector for denial-of-service attacks.】

为了降低风险,每十分钟内重新协商的次数限制为三次。当超过此阈值时,tls.TLSSocket 实例会触发 'error' 事件。此限制是可配置的:

【To mitigate the risk, renegotiation is limited to three times every ten minutes. An 'error' event is emitted on the tls.TLSSocket instance when this threshold is exceeded. The limits are configurable:】

  • tls.CLIENT_RENEG_LIMIT <number> 指定重新协商请求的次数。默认值: 3
  • tls.CLIENT_RENEG_WINDOW <number> 指定重新协商窗口的时间(以秒为单位)。默认值: 600(10 分钟)。

在没有充分了解其含义和风险的情况下,不应修改默认的重新协商限制。

【The default renegotiation limits should not be modified without a full understanding of the implications and risks.】

TLSv1.3 不支持重新协商。

【TLSv1.3 does not support renegotiation.】

会话恢复#>

【Session resumption】

建立 TLS 会话可能相对较慢。通过保存并稍后重用会话状态,可以加快该过程。有几种机制可以实现这一点,这里按照从最旧到最新(也是首选)的顺序进行讨论。

【Establishing a TLS session can be relatively slow. The process can be sped up by saving and later reusing the session state. There are several mechanisms to do so, discussed here from oldest to newest (and preferred).】

会话标识符#>

【Session identifiers】

服务器为新的连接生成唯一ID并将其发送给客户端。客户端和服务器都会保存会话状态。当重新连接时,客户端会发送其保存的会话状态ID,如果服务器也有该ID的状态,则可以同意使用它。否则,服务器将创建一个新的会话。更多信息请参见RFC 2246,第23页和第30页。

【Servers generate a unique ID for new connections and send it to the client. Clients and servers save the session state. When reconnecting, clients send the ID of their saved session state and if the server also has the state for that ID, it can agree to use it. Otherwise, the server will create a new session. See RFC 2246 for more information, page 23 and 30.】

大多数网络浏览器在进行 HTTPS 请求时都支持使用会话标识符进行恢复。

【Resumption using session identifiers is supported by most web browsers when making HTTPS requests.】

对于 Node.js,客户端等待 'session' 事件以获取会话数据,并将该数据提供给后续 tls.connect()session 选项以重用会话。服务器必须实现 'newSession''resumeSession' 事件的处理程序,以使用会话 ID 作为查找键来保存和恢复会话数据,从而重用会话。为了在负载均衡器或集群工作节点之间重用会话,服务器在其会话处理程序中必须使用共享会话缓存(例如 Redis)。

【For Node.js, clients wait for the 'session' event to get the session data, and provide the data to the session option of a subsequent tls.connect() to reuse the session. Servers must implement handlers for the 'newSession' and 'resumeSession' events to save and restore the session data using the session ID as the lookup key to reuse sessions. To reuse sessions across load balancers or cluster workers, servers must use a shared session cache (such as Redis) in their session handlers.】

会话门票#>

【Session tickets】

服务器会加密整个会话状态,并将其作为“票据”发送给客户端。在重新连接时,该状态会在初始连接中发送到服务器。这种机制避免了服务器端会话缓存的需求。如果服务器因为任何原因(无法解密、票据过旧等)不使用票据,它将创建一个新的会话并发送一个新的票据。更多信息请参见 RFC 5077

【The servers encrypt the entire session state and send it to the client as a "ticket". When reconnecting, the state is sent to the server in the initial connection. This mechanism avoids the need for a server-side session cache. If the server doesn't use the ticket, for any reason (failure to decrypt it, it's too old, etc.), it will create a new session and send a new ticket. See RFC 5077 for more information.】

在使用 HTTPS 请求时,许多网络浏览器越来越普遍地支持使用会话票据进行恢复。

【Resumption using session tickets is becoming commonly supported by many web browsers when making HTTPS requests.】

对于 Node.js,客户端使用与会话票证恢复相同的 API 来进行会话标识符恢复。用于调试时,如果 tls.TLSSocket.getTLSTicket() 返回一个值,会话数据包含票证,否则它包含客户端会话状态。

【For Node.js, clients use the same APIs for resumption with session identifiers as for resumption with session tickets. For debugging, if tls.TLSSocket.getTLSTicket() returns a value, the session data contains a ticket, otherwise it contains client-side session state.】

使用 TLSv1.3 时,请注意服务器可能会发送多个票证,从而导致多个 'session' 事件,更多信息请参见 'session'

【With TLSv1.3, be aware that multiple tickets may be sent by the server, resulting in multiple 'session' events, see 'session' for more information.】

单进程服务器无需特定实现即可使用会话票据。要在服务器重启或负载均衡器之间使用会话票据,所有服务器必须拥有相同的票据密钥。内部有三个16字节的密钥,但 TLS API 为方便起见将它们作为一个48字节的缓冲区暴露出来。

【Single process servers need no specific implementation to use session tickets. To use session tickets across server restarts or load balancers, servers must all have the same ticket keys. There are three 16-byte keys internally, but the tls API exposes them as a single 48-byte buffer for convenience.】

可以通过在一个服务器实例上调用 server.getTicketKeys() 来获取票据密钥,然后分发它们,但更合理的方法是安全地生成 48 字节的随机数据,并使用 tls.createServer()ticketKeys 选项来设置它们。密钥应定期重新生成,并且可以使用 server.setTicketKeys() 重置服务器的密钥。

【It's possible to get the ticket keys by calling server.getTicketKeys() on one server instance and then distribute them, but it is more reasonable to securely generate 48 bytes of secure random data and set them with the ticketKeys option of tls.createServer(). The keys should be regularly regenerated and server's keys can be reset with server.setTicketKeys().】

会话票据密钥是加密密钥,必须安全存储。在 TLS 1.2 及以下版本中,如果这些密钥被泄露,使用这些密钥加密的所有会话都可以被解密。它们不应存储在磁盘上,并且应定期重新生成。

【Session ticket keys are cryptographic keys, and they must be stored securely. With TLS 1.2 and below, if they are compromised all sessions that used tickets encrypted with them can be decrypted. They should not be stored on disk, and they should be regenerated regularly.】

如果客户端声明支持票据,服务器将会发送票据。服务器可以通过在 secureOptions 中提供 require('node:constants').SSL_OP_NO_TICKET 来禁用票据。

【If clients advertise support for tickets, the server will send them. The server can disable tickets by supplying require('node:constants').SSL_OP_NO_TICKET in secureOptions.】

会话标识符和会话票据都会超时,导致服务器创建新的会话。超时时间可以通过 tls.createServer()sessionTimeout 选项进行配置。

【Both session identifiers and session tickets timeout, causing the server to create new sessions. The timeout can be configured with the sessionTimeout option of tls.createServer().】

对于所有机制,当会话恢复失败时,服务器将创建新的会话。由于会话恢复失败不会导致 TLS/HTTPS 连接失败,因此很容易忽略不必要的低效 TLS 性能。可以使用 OpenSSL 命令行工具验证服务器是否正在恢复会话。例如,可以使用 openssl s_client-reconnect 选项:

【For all the mechanisms, when resumption fails, servers will create new sessions. Since failing to resume the session does not cause TLS/HTTPS connection failures, it is easy to not notice unnecessarily poor TLS performance. The OpenSSL CLI can be used to verify that servers are resuming sessions. Use the -reconnect option to openssl s_client, for example:】

$ openssl s_client -connect localhost:443 -reconnect 

阅读调试输出。第一个连接应该显示“新建”,例如:

【Read through the debug output. The first connection should say "New", for example:】

New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256 

后续连接应显示“已重用”,例如:

【Subsequent connections should say "Reused", for example:】

Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256 

修改默认的 TLS 密码套件#>

【Modifying the default TLS cipher suite】

Node.js 内置了一套默认启用和禁用的 TLS 加密套件。在构建 Node.js 时,可以配置此默认加密套件列表,以允许各发行版提供自己的默认列表。

【Node.js is built with a default suite of enabled and disabled TLS ciphers. This default cipher list can be configured when building Node.js to allow distributions to provide their own default list.】

以下命令可用于显示默认密码套件:

【The following command can be used to show the default cipher suite:】

node -p crypto.constants.defaultCoreCipherList | tr ':' '\n'
TLS_AES_256_GCM_SHA384
TLS_CHACHA20_POLY1305_SHA256
TLS_AES_128_GCM_SHA256
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 

可以完全使用 --tls-cipher-list 命令行开关(直接使用,或通过 NODE_OPTIONS 环境变量)来替换此默认值。例如,以下设置将 ECDHE-RSA-AES128-GCM-SHA256:!RC4 作为默认的 TLS 加密套件:

【This default can be replaced entirely using the --tls-cipher-list command-line switch (directly, or via the NODE_OPTIONS environment variable). 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' server.js

export NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'
node server.js 

要验证,请使用以下命令显示设置的加密列表,并注意 defaultCoreCipherListdefaultCipherList 之间的差异:

【To verify, use the following command to show the set cipher list, note the difference between defaultCoreCipherList and defaultCipherList:】

node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' -p crypto.constants.defaultCipherList | tr ':' '\n'
ECDHE-RSA-AES128-GCM-SHA256
!RC4 

defaultCoreCipherList 列表是在编译时设置的,而 defaultCipherList 是在运行时设置的。

【i.e. the defaultCoreCipherList list is set at compilation time and the defaultCipherList is set at runtime.】

要在运行时修改默认的加密套件,请修改 tls.DEFAULT_CIPHERS 变量,这必须在监听任何套接字之前进行,对已打开的套接字不会有影响。例如:

【To modify the default cipher suites from within the runtime, modify the tls.DEFAULT_CIPHERS variable, this must be performed before listening on any sockets, it will not affect sockets already opened. For example:】

// Remove Obsolete CBC Ciphers and RSA Key Exchange based Ciphers as they don't provide Forward Secrecy
tls.DEFAULT_CIPHERS +=
  ':!ECDHE-RSA-AES128-SHA:!ECDHE-RSA-AES128-SHA256:!ECDHE-RSA-AES256-SHA:!ECDHE-RSA-AES256-SHA384' +
  ':!ECDHE-ECDSA-AES128-SHA:!ECDHE-ECDSA-AES128-SHA256:!ECDHE-ECDSA-AES256-SHA:!ECDHE-ECDSA-AES256-SHA384' +
  ':!kRSA'; 

默认设置也可以通过 tls.createSecureContext()ciphers 选项按每个客户端或服务器进行替换,该选项在 tls.createServer()tls.connect() 中以及创建新的 tls.TLSSocket 时也可用。

【The default can also be replaced on a per client or server basis using the ciphers option from tls.createSecureContext(), which is also available in tls.createServer(), tls.connect(), and when creating new tls.TLSSockets.】

密码套件列表可以包含 TLSv1.3 密码套件名称的混合项,这些名称以 'TLS_' 开头,以及 TLSv1.2 及以下版本密码套件的规范。TLSv1.2 密码套件支持遗留的规范格式,详情请参考 OpenSSL 密码列表格式 文档,但这些规范不适用于 TLSv1.3 密码套件。TLSv1.3 套件只能通过在密码列表中包含它们的完整名称来启用。例如,它们无法通过使用遗留的 TLSv1.2 'EECDH''!EECDH' 规范来启用或禁用。

【The ciphers list can contain a mixture of TLSv1.3 cipher suite names, the ones that start with 'TLS_', and specifications for TLSv1.2 and below cipher suites. The TLSv1.2 ciphers support a legacy specification format, consult the OpenSSL cipher list format documentation for details, but those specifications do not apply to TLSv1.3 ciphers. The TLSv1.3 suites can only be enabled by including their full name in the cipher list. They cannot, for example, be enabled or disabled by using the legacy TLSv1.2 'EECDH' or '!EECDH' specification.】

尽管 TLSv1.3 和 TLSv1.2 密码套件的相对顺序不同,TLSv1.3 协议的安全性明显高于 TLSv1.2,并且如果握监视明支持 TLSv1.3 且启用了任何 TLSv1.3 密码套件,它将始终被优先选择而不是 TLSv1.2。

【Despite the relative order of TLSv1.3 and TLSv1.2 cipher suites, the TLSv1.3 protocol is significantly more secure than TLSv1.2, and will always be chosen over TLSv1.2 if the handshake indicates it is supported, and if any TLSv1.3 cipher suites are enabled.】

Node.js 中包含的默认密码套件经过精心选择,以反映当前的安全最佳实践和风险缓解措施。更改默认密码套件可能会对应用的安全性产生重大影响。--tls-cipher-list 选项和 ciphers 选项应仅在绝对必要时使用。

【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 and ciphers option should by used only if absolutely necessary.】

默认的加密套件对于 Chrome 的“现代加密”设置 首选 GCM 加密,同时为了实现完美前向保密性,也首选 ECDHE 和 DHE 加密,同时提供一定的向后兼容性。

【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.】

依赖不安全且已废弃的基于 RC4 或 DES 的加密算法的旧客户端(如 Internet Explorer 6)无法使用默认配置完成握手过程。如果必须支持这些客户端,TLS 建议 可能提供兼容的加密套件。有关格式的更多详细信息,请参阅 OpenSSL 密码列表格式 文档。

【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.】

只有五个 TLSv1.3 密码套件:

【There are only five TLSv1.3 cipher suites:】

  • 'TLS_AES_256_GCM_SHA384'
  • 'TLS_CHACHA20_POLY1305_SHA256'
  • 'TLS_AES_128_GCM_SHA256'
  • 'TLS_AES_128_CCM_SHA256'
  • 'TLS_AES_128_CCM_8_SHA256'

前三个默认启用。基于 CCM 的两个套件受到 TLSv1.3 支持,因为它们在受限系统上可能性能更好,但由于安全性较低,因此默认不启用。

【The first three are enabled by default. The two CCM-based suites are supported by TLSv1.3 because they may be more performant on constrained systems, but they are not enabled by default since they offer less security.】

X509 证书错误代码#>

【X509 certificate error codes】

由于 OpenSSL 报告的证书错误,多个功能可能会失败。在这种情况下,该函数会通过其回调提供一个 <Error>,该对象具有 code 属性,该属性可以取以下值之一:

【Multiple functions can fail due to certificate errors that are reported by OpenSSL. In such a case, the function provides an <Error> via its callback that has the property code which can take one of the following values:】

  • 'UNABLE_TO_GET_ISSUER_CERT':无法获取颁发者证书。
  • 'UNABLE_TO_GET_CRL':无法获取证书撤销列表(CRL)。
  • 'UNABLE_TO_DECRYPT_CERT_SIGNATURE':无法解密证书的签名。
  • 'UNABLE_TO_DECRYPT_CRL_SIGNATURE':无法解密 CRL 的签名。
  • 'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY':无法解码发行者公钥。
  • 'CERT_SIGNATURE_FAILURE':证书签名失败。
  • 'CRL_SIGNATURE_FAILURE':CRL 签名失败。
  • 'CERT_NOT_YET_VALID':证书尚未生效。
  • 'CERT_HAS_EXPIRED':证书已过期。
  • 'CRL_NOT_YET_VALID':CRL 尚未生效。
  • 'CRL_HAS_EXPIRED':CRL 已过期。
  • 'ERROR_IN_CERT_NOT_BEFORE_FIELD':证书的 notBefore 字段格式错误。
  • 'ERROR_IN_CERT_NOT_AFTER_FIELD':证书的 notAfter 字段格式错误。
  • 'ERROR_IN_CRL_LAST_UPDATE_FIELD':CRL 的 lastUpdate 字段格式错误。
  • 'ERROR_IN_CRL_NEXT_UPDATE_FIELD':CRL 的 nextUpdate 字段格式错误。
  • 'OUT_OF_MEM':内存不足。
  • 'DEPTH_ZERO_SELF_SIGNED_CERT':自签名证书。
  • 'SELF_SIGNED_CERT_IN_CHAIN':证书链中存在自签名证书。
  • 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY':无法获取本地颁发者证书。
  • 'UNABLE_TO_VERIFY_LEAF_SIGNATURE':无法验证第一个证书。
  • 'CERT_CHAIN_TOO_LONG':证书链过长。
  • 'CERT_REVOKED':证书已被吊销。
  • 'INVALID_CA':无效的 CA 证书。
  • 'PATH_LENGTH_EXCEEDED':路径长度超出限制。
  • 'INVALID_PURPOSE':证书用途不受支持。
  • 'CERT_UNTRUSTED':证书不受信任。
  • 'CERT_REJECTED':证书被拒绝。
  • 'HOSTNAME_MISMATCH':主机名不匹配。

类:tls.CryptoStream#>

【Class: tls.CryptoStream

稳定性: 0 - 弃用:请改用 tls.TLSSocket

tls.CryptoStream 类表示加密数据流。此类已被弃用,不应再使用。

【The tls.CryptoStream class represents a stream of encrypted data. This class is deprecated and should no longer be used.】

cryptoStream.bytesWritten#>

cryptoStream.bytesWritten 属性返回写入底层套接字的字节总数,_包括_实现 TLS 协议所需的字节。

【The cryptoStream.bytesWritten property returns the total number of bytes written to the underlying socket including the bytes required for the implementation of the TLS protocol.】

类:tls.SecurePair#>

【Class: tls.SecurePair

稳定性: 0 - 弃用:请改用 tls.TLSSocket

tls.createSecurePair() 返回。

【Returned by tls.createSecurePair().】

事件:'secure'#>

【Event: 'secure'

SecurePair 对象在建立安全连接后会触发 'secure' 事件。

【The 'secure' event is emitted by the SecurePair object once a secure connection has been established.】

与检查服务器 'secureConnection' 事件一样,应检查 pair.cleartext.authorized 以确认所使用的证书是否经过适当授权。

【As with checking for the server 'secureConnection' event, pair.cleartext.authorized should be inspected to confirm whether the certificate used is properly authorized.】

类:tls.Server#>

【Class: tls.Server

接受使用 TLS 或 SSL 的加密连接。

【Accepts encrypted connections using TLS or SSL.】

事件:'connection'#>

【Event: 'connection'

当建立新的 TCP 流时会触发此事件,在 TLS 握手开始之前。socket 通常是 net.Socket 类型的对象,但不会接收到事件,这一点不同于从 net.Server 'connection' 事件创建的 socket。通常用户不会想要访问此事件。

【This event is emitted when a new TCP stream is established, before the TLS handshake begins. socket is typically an object of type net.Socket but will not receive events unlike the socket created from the net.Server 'connection' event. Usually users will not want to access this event.】

此事件也可以由用户显式触发,以向 TLS 服务器注入连接。在这种情况下,任何 Duplex 流都可以被传递。

【This event can also be explicitly emitted by users to inject connections into the TLS server. In that case, any Duplex stream can be passed.】

事件:'keylog'#>

【Event: 'keylog'

  • line <Buffer> ASCII 文本行,采用 NSS SSLKEYLOGFILE 格式。
  • tlsSocket <tls.TLSSocket> 它被生成的 tls.TLSSocket 实例。

keylog 事件在通过与此服务器的连接生成或接收密钥材料时触发(通常在握手完成之前,但不一定)。这些密钥材料可以存储用于调试,因为它允许解密捕获的 TLS 流量。对于每个套接字,它可能会被触发多次。

【The keylog event is emitted when key material is generated or received by a connection to this server (typically before handshake has completed, but not necessarily). This keying material can be stored for debugging, as it allows captured TLS traffic to be decrypted. It may be emitted multiple times for each socket.】

一个典型的使用案例是将接收到的行追加到一个通用的文本文件中,该文件随后被软件(例如 Wireshark)用来解密流量:

【A typical use case is to append received lines to a common text file, which is later used by software (such as Wireshark) to decrypt the traffic:】

const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });
// ...
server.on('keylog', (line, tlsSocket) => {
  if (tlsSocket.remoteAddress !== '...')
    return; // Only log keys for a particular IP
  logFile.write(line);
}); 

事件:'newSession'#>

【Event: 'newSession'

'newSession' 事件在创建新的 TLS 会话时触发。这可以用于将会话存储在外部存储中。数据应提供给 'resumeSession' 回调。

【The 'newSession' event is emitted upon creation of a new TLS session. This may be used to store sessions in external storage. The data should be provided to the 'resumeSession' callback.】

监听器回调在调用时传入三个参数:

【The listener callback is passed three arguments when called:】

  • sessionId <Buffer> TLS 会话标识符
  • sessionData <Buffer> TLS 会话数据
  • callback <Function> 一个不接受任何参数的回调函数,必须调用它才能通过安全连接发送或接收数据。

监听此事件只会对在添加事件监听器之后建立的连接产生影响。

【Listening for this event will have an effect only on connections established after the addition of the event listener.】

事件:'OCSPRequest'#>

【Event: 'OCSPRequest'

当客户端发送证书状态请求时,会触发 'OCSPRequest' 事件。调用监听器回调时会传入三个参数:

【The 'OCSPRequest' event is emitted when the client sends a certificate status request. The listener callback is passed three arguments when called:】

  • certificate <Buffer> 服务器证书
  • issuer <Buffer> 发行者的证书
  • callback <Function> 必须调用的回调函数,用于提供 OCSP 请求的结果。

服务器当前的证书可以解析以获取 OCSP URL 和证书 ID;在获取 OCSP 响应后,会调用 callback(null, resp),其中 resp 是包含 OCSP 响应的 Buffer 实例。certificateissuer 都是主证书和颁发者证书的 Buffer DER 表示形式。这些可以用来获取 OCSP 证书 ID 和 OCSP 端点 URL。

【The server's current certificate can be parsed to obtain the OCSP URL and certificate ID; after obtaining an OCSP response, callback(null, resp) is then invoked, where resp is a Buffer instance containing the OCSP response. Both certificate and issuer are Buffer DER-representations of the primary and issuer's certificates. These can be used to obtain the OCSP certificate ID and OCSP endpoint URL.】

或者,可以调用 callback(null, null),表示没有 OCSP 响应。

【Alternatively, callback(null, null) may be called, indicating that there was no OCSP response.】

调用 callback(err) 将导致执行 socket.destroy(err)

【Calling callback(err) will result in a socket.destroy(err) call.】

OCSP 请求的典型流程如下:

【The typical flow of an OCSP request is as follows:】

  1. 客户端连接到服务器并发送一个 'OCSPRequest'(通过 ClientHello 中的状态信息扩展)。
  2. 服务器接收请求并触发 'OCSPRequest' 事件,如果已注册监听器则调用它。
  3. 服务器从 certificateissuer 中提取 OCSP URL,并向 CA 执行 OCSP请求
  4. 服务器从 CA 接收 'OCSPResponse' 并通过 callback 参数将其发送回客户端
  5. 客户端验证响应,然后要么销毁套接字,要么执行握手。

issuer 可以为 null,如果证书是自签名的或发行者不在根证书列表中。(在建立 TLS 连接时,可以通过 ca 选项提供发行者。)

【The issuer can be null if the certificate is either self-signed or the issuer is not in the root certificates list. (An issuer may be provided via the ca option when establishing the TLS connection.)】

监听此事件只会对在添加事件监听器之后建立的连接产生影响。

【Listening for this event will have an effect only on connections established after the addition of the event listener.】

可以使用像 asn1.js 这样的 npm 模块来解析证书。

【An npm module like asn1.js may be used to parse the certificates.】

事件:'resumeSession'#>

【Event: 'resumeSession'

当客户端请求恢复之前的 TLS 会话时,会触发 'resumeSession' 事件。调用监听器回调时会传入两个参数:

【The 'resumeSession' event is emitted when the client requests to resume a previous TLS session. The listener callback is passed two arguments when called:】

  • sessionId <Buffer> TLS 会话标识符
  • callback <Function> 当先前的会话已恢复时要调用的回调函数:callback([err[, sessionData]])

事件监听器应使用给定的 sessionId 在外部存储中查找由 'newSession' 事件处理程序保存的 sessionData。如果找到,请调用 callback(null, sessionData) 以恢复会话。如果未找到,则无法恢复会话。必须调用 callback() 而不带 sessionData,以便握手可以继续并创建新会话。也可以调用 callback(err) 来终止传入连接并销毁套接字。

【The event listener should perform a lookup in external storage for the sessionData saved by the 'newSession' event handler using the given sessionId. If found, call callback(null, sessionData) to resume the session. If not found, the session cannot be resumed. callback() must be called without sessionData so that the handshake can continue and a new session can be created. It is possible to call callback(err) to terminate the incoming connection and destroy the socket.】

监听此事件只会对在添加事件监听器之后建立的连接产生影响。

【Listening for this event will have an effect only on connections established after the addition of the event listener.】

以下说明恢复 TLS 会话:

【The following illustrates resuming a TLS session:】

const tlsSessionStore = {};
server.on('newSession', (id, data, cb) => {
  tlsSessionStore[id.toString('hex')] = data;
  cb();
});
server.on('resumeSession', (id, cb) => {
  cb(null, tlsSessionStore[id.toString('hex')] || null);
}); 

事件:'secureConnection'#>

【Event: 'secureConnection'

'secureConnection' 事件在新连接的握手过程成功完成后触发。调用监听器回调时,会传入一个参数:

【The 'secureConnection' event is emitted after the handshaking process for a new connection has successfully completed. The listener callback is passed a single argument when called:】

tlsSocket.authorized 属性是一个 boolean,用于指示客户端是否已通过服务器提供的某个证书颁发机构进行验证。如果 tlsSocket.authorizedfalse,则 socket.authorizationError 会被设置以描述授权失败的原因。根据 TLS 服务器的设置,未授权的连接仍可能被接受。

【The tlsSocket.authorized property is a boolean indicating whether the client has been verified by one of the supplied Certificate Authorities for the server. If tlsSocket.authorized is false, then socket.authorizationError is set to describe how authorization failed. Depending on the settings of the TLS server, unauthorized connections may still be accepted.】

tlsSocket.alpnProtocol 属性是一个字符串,包含所选的 ALPN 协议。当 ALPN 没有选择协议时,tlsSocket.alpnProtocol 的值为 false

【The tlsSocket.alpnProtocol property is a string that contains the selected ALPN protocol. When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false.】

tlsSocket.servername 属性是一个字符串,包含通过 SNI 请求的服务器名称。

【The tlsSocket.servername property is a string containing the server name requested via SNI.】

事件:'tlsClientError'#>

【Event: 'tlsClientError'

当在建立安全连接之前发生错误时,会触发 'tlsClientError' 事件。调用监听器回调时会传入两个参数:

【The 'tlsClientError' event is emitted when an error occurs before a secure connection is established. The listener callback is passed two arguments when called:】

  • exception <Error> 描述该错误的 Error 对象
  • tlsSocket <tls.TLSSocket> 产生错误的 tls.TLSSocket 实例。

server.addContext(hostname, context)#>

server.addContext() 方法会添加一个安全上下文,如果客户端请求的 SNI 名称与提供的 hostname(或通配符)匹配,将使用该上下文。

【The server.addContext() method adds a secure context that will be used if the client request's SNI name matches the supplied hostname (or wildcard).】

当存在多个匹配的上下文时,会使用最近添加的那个。

【When there are multiple matching contexts, the most recently added one is used.】

server.address()#>

返回操作系统报告的服务器绑定地址、地址族名称和端口。有关更多信息,请参见 net.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.close([callback])#>

  • callback <Function> 一个监听器回调函数,将被注册以监听服务器实例的 'close' 事件。
  • 返回值:<tls.Server>

server.close() 方法会停止服务器接受新的连接。

【The server.close() method stops the server from accepting new connections.】

该函数异步操作。当服务器没有更多打开的连接时,将触发 'close' 事件。

【This function operates asynchronously. The 'close' event will be emitted when the server has no more open connections.】

server.getTicketKeys()#>

  • 返回:<Buffer> 一个包含会话票据密钥的48字节缓冲区。

返回会话票证密钥。

【Returns the session ticket keys.】

有关更多信息,请参见会话恢复

【See Session Resumption for more information.】

server.listen()#>

启动服务器以监听加密连接。此方法与 net.Serverserver.listen() 相同。

【Starts the server listening for encrypted connections. This method is identical to server.listen() from net.Server.】

server.setSecureContext(options)#>

server.setSecureContext() 方法用于替换现有服务器的安全上下文。服务器的现有连接不会被中断。

【The server.setSecureContext() method replaces the secure context of an existing server. Existing connections to the server are not interrupted.】

server.setTicketKeys(keys)#>

设置会话票证密钥。

【Sets the session ticket keys.】

对票据密钥的更改仅对未来的服务器连接有效。现有或当前待处理的服务器连接将使用之前的密钥。

【Changes to the ticket keys are effective only for future server connections. Existing or currently pending server connections will use the previous keys.】

有关更多信息,请参见会话恢复

【See Session Resumption for more information.】

类:tls.TLSSocket#>

【Class: tls.TLSSocket

对写入的数据进行透明加密,并处理所有必要的 TLS 协商。

【Performs transparent encryption of written data and all required TLS negotiation.】

tls.TLSSocket 的实例实现了双工 接口。

【Instances of tls.TLSSocket implement the duplex Stream interface.】

返回 TLS 连接元数据的方法(例如 tls.TLSSocket.getPeerCertificate())仅在连接打开时返回数据。

【Methods that return TLS connection metadata (e.g. tls.TLSSocket.getPeerCertificate()) will only return data while the connection is open.】

new tls.TLSSocket(socket[, options])#>

  • socket <net.Socket> | <stream.Duplex> 在服务器端,任何 Duplex 流。在客户端,任何 net.Socket 的实例(如果要在客户端支持通用 Duplex 流,必须使用 tls.connect())。
  • options <Object>
    • enableTrace:参见 tls.createServer()
    • isServer:SSL/TLS 协议是非对称的,TLSSockets 必须知道它们是要作为服务器还是客户端。如果为 true,TLS 套接字将作为服务器实例化。默认值: false
    • server <net.Server> 一个 net.Server 实例。
    • requestCert:是否通过请求证书来验证远程节点的身份。客户端总是请求服务器证书。服务器(isServer 为 true)可以将 requestCert 设置为 true 来请求客户端证书。
    • rejectUnauthorized: 参见 tls.createServer()
    • ALPNProtocols:见 tls.createServer()
    • SNICallback:参见 tls.createServer()
    • session <Buffer> 一个包含 TLS 会话的 Buffer 实例。
    • requestOCSP <boolean> 如果为 true,指定将在客户端问候(client hello)中添加 OCSP 状态请求扩展,并在建立安全通信之前在套接字上触发 'OCSPResponse' 事件
    • secureContext:使用 tls.createSecureContext() 创建的 TLS 上下文对象。如果未提供 secureContext,将通过将整个 options 对象传递给 tls.createSecureContext() 来创建一个。
    • ...:如果缺少 secureContext 选项,将使用 tls.createSecureContext() 选项。否则,这些选项将被忽略。

从现有的 TCP 套接字构建一个新的 tls.TLSSocket 对象。

【Construct a new tls.TLSSocket object from an existing TCP socket.】

事件:'keylog'#>

【Event: 'keylog'

  • line <Buffer> ASCII 文本行,采用 NSS SSLKEYLOGFILE 格式。

keylog 事件会在 tls.TLSSocket 上触发,当套接字生成或接收到密钥材料时。该密钥材料可以被存储用于调试,因为它允许解密捕获的 TLS 流量。它可能会在握手完成前或完成后多次触发。

【The keylog event is emitted on a tls.TLSSocket when key material is generated or received by the socket. This keying material can be stored for debugging, as it allows captured TLS traffic to be decrypted. It may be emitted multiple times, before or after the handshake completes.】

一个典型的使用案例是将接收到的行追加到一个通用的文本文件中,该文件随后被软件(例如 Wireshark)用来解密流量:

【A typical use case is to append received lines to a common text file, which is later used by software (such as Wireshark) to decrypt the traffic:】

const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });
// ...
tlsSocket.on('keylog', (line) => logFile.write(line)); 

事件:'OCSPResponse'#>

【Event: 'OCSPResponse'

如果在创建 tls.TLSSocket 时设置了 requestOCSP 选项,并且已收到 OCSP 响应,将会触发 'OCSPResponse' 事件。调用监听器回调时会传入一个参数:

【The 'OCSPResponse' event is emitted if the requestOCSP option was set when the tls.TLSSocket was created and an OCSP response has been received. The listener callback is passed a single argument when called:】

  • response <Buffer> 服务器的 OCSP 响应

通常,response 是来自服务器 CA 的数字签名对象,包含有关服务器证书吊销状态的信息。

【Typically, the response is a digitally signed object from the server's CA that contains information about server's certificate revocation status.】

事件:'secureConnect'#>

【Event: 'secureConnect'

在新连接的握手过程成功完成后,会触发 'secureConnect' 事件。无论服务器证书是否已被授权,监听器回调都会被调用。客户端有责任检查 tlsSocket.authorized 属性,以确定服务器证书是否由指定的 CA 签发。如果 tlsSocket.authorized === false,则可以通过检查 tlsSocket.authorizationError 属性来找到错误。如果使用了 ALPN,则可以检查 tlsSocket.alpnProtocol 属性以确定协商的协议。

【The 'secureConnect' event is emitted after the handshaking process for a new connection has successfully completed. The listener callback will be called regardless of whether or not the server's certificate has been authorized. It is the client's responsibility to check the tlsSocket.authorized property to determine if the server certificate was signed by one of the specified CAs. If tlsSocket.authorized === false, then the error can be found by examining the tlsSocket.authorizationError property. If ALPN was used, the tlsSocket.alpnProtocol property can be checked to determine the negotiated protocol.】

当使用 new tls.TLSSocket() 构造函数创建 <tls.TLSSocket> 时,不会触发 'secureConnect' 事件。

【The 'secureConnect' event is not emitted when a <tls.TLSSocket> is created using the new tls.TLSSocket() constructor.】

事件:'session'#>

【Event: 'session'

当客户端的 tls.TLSSocket 有新的会话或 TLS 票证可用时,会触发 'session' 事件。根据协商的 TLS 协议版本,这可能在握手完成之前或之后发生。该事件不会在服务器上触发,也不会在未创建新会话时触发,例如,在连接恢复时。对于某些 TLS 协议版本,该事件可能会触发多次,这种情况下所有会话都可以用于恢复。

【The 'session' event is emitted on a client tls.TLSSocket when a new session or TLS ticket is available. This may or may not be before the handshake is complete, depending on the TLS protocol version that was negotiated. The event is not emitted on the server, or if a new session was not created, for example, when the connection was resumed. For some TLS protocol versions the event may be emitted multiple times, in which case all the sessions can be used for resumption.】

在客户端,session 可以提供给 tls.connect()session 选项以恢复连接。

【On the client, the session can be provided to the session option of tls.connect() to resume the connection.】

有关更多信息,请参见会话恢复

【See Session Resumption for more information.】

对于 TLSv1.2 及以下版本,tls.TLSSocket.getSession() 可以在握手完成后调用一次。对于 TLSv1.3,协议只允许基于票据的会话恢复,会发送多个票据,并且票据要等到握手完成后才发送。因此,有必要等待 'session' 事件来获得可恢复的会话。应用应使用 'session' 事件而不是 getSession(),以确保它们适用于所有 TLS 版本。只期望获取或使用一个会话的应用,应只监听此事件一次:

【For TLSv1.2 and below, tls.TLSSocket.getSession() can be called once the handshake is complete. For TLSv1.3, only ticket-based resumption is allowed by the protocol, multiple tickets are sent, and the tickets aren't sent until after the handshake completes. So it is necessary to wait for the 'session' event to get a resumable session. Applications should use the 'session' event instead of getSession() to ensure they will work for all TLS versions. Applications that only expect to get or use one session should listen for this event only once:】

tlsSocket.once('session', (session) => {
  // The session can be used immediately or later.
  tls.connect({
    session: session,
    // Other connect options...
  });
}); 

tlsSocket.address()#>

返回操作系统报告的底层套接字的绑定 address、地址 family 名称和 port{ port: 12346, family: 'IPv4', address: '127.0.0.1' }

【Returns the bound address, the address family name, and port of the underlying socket as reported by the operating system: { port: 12346, family: 'IPv4', address: '127.0.0.1' }.】

tlsSocket.authorizationError#>

返回对端证书未被验证的原因。只有当 tlsSocket.authorized === false 时,此属性才会被设置。

【Returns the reason why the peer's certificate was not been verified. This property is set only when tlsSocket.authorized === false.】

tlsSocket.authorized#>

如果对等证书是由创建 tls.TLSSocket 实例时指定的某个 CA 签署的,则此属性为 true,否则为 false

【This property is true if the peer certificate was signed by one of the CAs specified when creating the tls.TLSSocket instance, otherwise false.】

tlsSocket.disableRenegotiation()#>

禁用此 TLSSocket 实例的 TLS 重新协商。一旦调用,尝试重新协商将在 TLSSocket 上触发 'error' 事件。

【Disables TLS renegotiation for this TLSSocket instance. Once called, attempts to renegotiate will trigger an 'error' event on the TLSSocket.】

tlsSocket.enableTrace()#>

启用后,TLS 数据包跟踪信息将写入 stderr。这可用于调试 TLS 连接问题。

【When enabled, TLS packet trace information is written to stderr. This can be used to debug TLS connection problems.】

输出的格式与 openssl s_client -traceopenssl s_server -trace 的输出格式相同。虽然它是由 OpenSSL 的 SSL_trace() 函数生成的,但该格式没有文档说明,可能会在没有通知的情况下更改,因此不应依赖它。

【The format of the output is identical to the output of openssl s_client -trace or openssl s_server -trace. While it is produced by OpenSSL's SSL_trace() function, the format is undocumented, can change without notice, and should not be relied on.】

tlsSocket.encrypted#>

总是返回 true。这可用于区分 TLS 套接字与普通的 net.Socket 实例。

【Always returns true. This may be used to distinguish TLS sockets from regular net.Socket instances.】

tlsSocket.exportKeyingMaterial(length, label[, context])#>

密钥材料用于验证,以防止网络协议中的各种攻击,例如在 IEEE 802.1X 的规范中。

【Keying material is used for validations to prevent different kind of attacks in network protocols, for example in the specifications of IEEE 802.1X.】

示例

【Example】

const keyingMaterial = tlsSocket.exportKeyingMaterial(
  128,
  'client finished');

/*
 Example return value of keyingMaterial:
 <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
    12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
    74 ef 2c ... 78 more bytes>
*/ 

有关更多信息,请参阅 OpenSSL SSL_export_keying_material 文档。

【See the OpenSSL SSL_export_keying_material documentation for more information.】

tlsSocket.getCertificate()#>

返回一个表示本地证书的对象。返回的对象具有一些对应证书字段的属性。

【Returns an object representing the local certificate. The returned object has some properties corresponding to the fields of the certificate.】

有关证书结构的示例,请参见 tls.TLSSocket.getPeerCertificate()

【See tls.TLSSocket.getPeerCertificate() for an example of the certificate structure.】

如果没有本地证书,将返回一个空对象。如果套接字已被销毁,将返回 null

【If there is no local certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.】

tlsSocket.getCipher()#>

返回包含协商密码套件信息的对象。

【Returns an object containing information on the negotiated cipher suite.】

例如,带有 AES256-SHA 密码的 TLSv1.2 协议:

【For example, a TLSv1.2 protocol with AES256-SHA cipher:】

{
    "name": "AES256-SHA",
    "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA",
    "version": "SSLv3"
} 

参见 [SSL_CIPHER_get_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) 更多信息请见。

【See SSL_CIPHER_get_name for more information.】

tlsSocket.getEphemeralKeyInfo()#>

返回一个对象,表示客户端连接中 完美前向保密 临时密钥交换参数的类型、名称和大小。当密钥交换不是临时密钥交换时,它返回一个空对象。由于此功能仅支持客户端套接字,如果在服务器套接字上调用,则返回 null。支持的类型为 'DH''ECDH'。仅当类型为 'ECDH' 时,name 属性才可用。

【Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in perfect forward secrecy on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; null is returned if called on a server socket. The supported types are 'DH' and 'ECDH'. The name property is available only when type is 'ECDH'.】

例如:{ type: 'ECDH', name: 'prime256v1', size: 256 }

【For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.】

tlsSocket.getFinished()#>

  • 返回值: <Buffer> | <undefined> 最近一次作为 SSL/TLS 握手的一部分发送到套接字的 Finished 消息,如果尚未发送任何 Finished 消息,则为 undefined

Finished 消息是完整握手的消息摘要(TLS 1.0 共 192 位,SSL 3.0 更长),当不需要或 SSL/TLS 提供的认证不够时,它们可以用于外部认证过程。

【As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.】

对应于 OpenSSL 中的 SSL_get_finished 例程,可用于实现 RFC 5929tls-unique 通道绑定。

【Corresponds to the SSL_get_finished routine in OpenSSL and may be used to implement the tls-unique channel binding from RFC 5929.】

tlsSocket.getPeerCertificate([detailed])#>

  • detailed <boolean> 如果为 true,则包含完整的证书链,否则仅包含对端证书。
  • 返回:<Object> 一个证书对象。

返回一个表示对等方证书的对象。如果对等方未提供证书,将返回一个空对象。如果套接字已被销毁,则返回 null

【Returns an object representing the peer's certificate. If the peer does not provide a certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.】

如果请求了完整的证书链,每个证书都会包含一个 issuerCertificate 属性,其中包含表示其颁发者证书的对象。

【If the full certificate chain was requested, each certificate will include an issuerCertificate property containing an object representing its issuer's certificate.】

证书对象#>

【Certificate object】

证书对象具有与证书字段对应的属性。

【A certificate object has properties corresponding to the fields of the certificate.】

  • ca <boolean> 如果是证书颁发机构 (CA) 则为 true,否则为 false
  • raw <Buffer> DER 编码的 X.509 证书数据。
  • subject <Object> 证书主题,以国家(C)、州或省(ST)、城市(L)、组织(O)、组织单位(OU)和通用名称(CN)描述。通用名称通常是 TLS 证书中的 DNS 名称。示例:{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}
  • issuer <Object> 证书颁发者,用与 subject 相同的术语描述。
  • valid_from <string> 证书有效的起始日期时间。
  • valid_to <string> 证书有效到的日期和时间。
  • serialNumber <string> 证书序列号,以十六进制字符串表示。示例:'B9B0D332A1AA5635'
  • fingerprint <string> DER 编码证书的 SHA-1 摘要。返回值为用 : 分隔的十六进制字符串。示例:'2A:7A:C2:DD:...'。
  • fingerprint256 <string> DER 编码证书的 SHA-256 摘要。它以用冒号分隔的十六进制字符串返回。示例:'2A:7A:C2:DD:...'
  • fingerprint512 <string> DER 编码证书的 SHA-512 摘要。它以 : 分隔的十六进制字符串返回。例如:'2A:7A:C2:DD:...'
  • ext_key_usage <Array>(可选)扩展密钥用途,一组 OID。
  • subjectaltname <string>(可选)一个包含连接的主体名称的字符串,是 subject 名称的替代方案。
  • infoAccess <Array>(可选)一个描述 AuthorityInfoAccess 的数组,用于 OCSP。
  • issuerCertificate <Object>(可选)签发者证书对象。对于自签名证书,这可能是一个循环引用。

证书可能包含关于公钥的信息,这取决于密钥类型。

【The certificate may contain information about the public key, depending on the key type.】

对于 RSA 密钥,可以定义以下属性:

【For RSA keys, the following properties may be defined:】

  • bits <number> RSA 的位数。例如:1024
  • exponent <string> RSA 指数,使用十六进制字符串表示。例如:'0x010001'
  • modulus <string> RSA 模数,以十六进制字符串表示。例如:'B56CE45CB7...'
  • pubkey <Buffer> 公钥。

对于 EC 密钥,可以定义以下属性:

【For EC keys, the following properties may be defined:】

  • pubkey <Buffer> 公钥。
  • bits <number> 密钥的位数。例如:256
  • asn1Curve <string>(可选)椭圆曲线 OID 的 ASN.1 名称。知名曲线通过 OID 进行标识。虽然不常见,但也可能通过其数学特性来标识曲线,在这种情况下它将没有 OID。例如:'prime256v1'
  • nistCurve <string>(可选)椭圆曲线的 NIST 名称(如果有的话),并非所有知名曲线都被 NIST 分配了名称)。示例:'P-256'

示例证书:

【Example certificate:】

{ subject:
   { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ],
     CN: '*.nodejs.org' },
  issuer:
   { C: 'GB',
     ST: 'Greater Manchester',
     L: 'Salford',
     O: 'COMODO CA Limited',
     CN: 'COMODO RSA Domain Validation Secure Server CA' },
  subjectaltname: 'DNS:*.nodejs.org, DNS:nodejs.org',
  infoAccess:
   { 'CA Issuers - URI':
      [ 'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt' ],
     'OCSP - URI': [ 'http://ocsp.comodoca.com' ] },
  modulus: 'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1',
  exponent: '0x10001',
  pubkey: <Buffer ... >,
  valid_from: 'Aug 14 00:00:00 2017 GMT',
  valid_to: 'Nov 20 23:59:59 2019 GMT',
  fingerprint: '01:02:59:D9:C3:D2:0D:08:F7:82:4E:44:A4:B4:53:C5:E2:3A:87:4D',
  fingerprint256: '69:AE:1A:6A:D4:3D:C6:C1:1B:EA:C6:23:DE:BA:2A:14:62:62:93:5C:7A:EA:06:41:9B:0B:BC:87:CE:48:4E:02',
  fingerprint512: '19:2B:3E:C3:B3:5B:32:E8:AE:BB:78:97:27:E4:BA:6C:39:C9:92:79:4F:31:46:39:E2:70:E5:5F:89:42:17:C9:E8:64:CA:FF:BB:72:56:73:6E:28:8A:92:7E:A3:2A:15:8B:C2:E0:45:CA:C3:BC:EA:40:52:EC:CA:A2:68:CB:32',
  ext_key_usage: [ '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' ],
  serialNumber: '66593D57F20CBC573E433381B5FEC280',
  raw: <Buffer ... > } 

tlsSocket.getPeerFinished()#>

  • 返回:<Buffer> | <undefined> 作为 SSL/TLS 握手的一部分,从套接字中预计或实际接收到的最新 Finished 消息,或如果目前没有 Finished 消息,则为 undefined

Finished 消息是完整握手的消息摘要(TLS 1.0 共 192 位,SSL 3.0 更长),当不需要或 SSL/TLS 提供的认证不够时,它们可以用于外部认证过程。

【As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.】

对应于 OpenSSL 中的 SSL_get_peer_finished 例程,可用于实现来自 RFC 5929tls-unique 通道绑定。

【Corresponds to the SSL_get_peer_finished routine in OpenSSL and may be used to implement the tls-unique channel binding from RFC 5929.】

tlsSocket.getPeerX509Certificate()#>

将对等证书作为 <X509Certificate> 对象返回。

【Returns the peer certificate as an <X509Certificate> object.】

如果没有对等证书,或者套接字已被销毁,将返回 undefined

【If there is no peer certificate, or the socket has been destroyed, undefined will be returned.】

tlsSocket.getProtocol()#>

返回一个字符串,包含当前连接协商的 SSL/TLS 协议版本。对于尚未完成握手过程的已连接套接字,将返回值 'unknown'。对于服务器套接字或已断开连接的客户端套接字,将返回值 null

【Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value 'unknown' will be returned for connected sockets that have not completed the handshaking process. The value null will be returned for server sockets or disconnected client sockets.】

协议版本为:

【Protocol versions are:】

  • 'SSLv3'
  • 'TLSv1'
  • 'TLSv1.1'
  • 'TLSv1.2'
  • 'TLSv1.3'

有关更多信息,请参阅 OpenSSL SSL_get_version 文档。

【See the OpenSSL SSL_get_version documentation for more information.】

tlsSocket.getSession()#>

返回 TLS 会话数据,如果没有协商会话则返回 undefined。在客户端,这些数据可以提供给 tls.connect()session 选项以恢复连接。在服务器端,这可能对调试有用。

【Returns the TLS session data or undefined if no session was negotiated. On the client, the data can be provided to the session option of tls.connect() to resume the connection. On the server, it may be useful for debugging.】

有关更多信息,请参见会话恢复

【See Session Resumption for more information.】

注意:getSession() 仅适用于 TLSv1.2 及更低版本。对于 TLSv1.3,应用必须使用 'session' 事件(它也适用于 TLSv1.2 及更低版本)。

【Note: getSession() works only for TLSv1.2 and below. For TLSv1.3, applications must use the 'session' event (it also works for TLSv1.2 and below).】

tlsSocket.getSharedSigalgs()#>

  • 返回值:<Array> 按优先顺序从高到低列出的服务器和客户端共享的签名算法列表。

参见 [SSL_get_shared_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) 更多信息请见。

【See SSL_get_shared_sigalgs for more information.】

tlsSocket.getTLSTicket()#>

对于客户端,如果有可用的 TLS 会话票证,则返回该票证,否则返回 undefined。对于服务器,则始终返回 undefined

【For a client, returns the TLS session ticket if one is available, or undefined. For a server, always returns undefined.】

它可能对调试有用。

【It may be useful for debugging.】

有关更多信息,请参见会话恢复

【See Session Resumption for more information.】

tlsSocket.getX509Certificate()#>

将本地证书作为 <X509Certificate> 对象返回。

【Returns the local certificate as an <X509Certificate> object.】

如果没有本地证书,或者套接字已被销毁,将返回 undefined

【If there is no local certificate, or the socket has been destroyed, undefined will be returned.】

tlsSocket.isSessionReused()#>

  • 返回:<boolean> 如果会话被重用,则为 true,否则为 false

有关更多信息,请参见会话恢复

【See Session Resumption for more information.】

tlsSocket.localAddress#>

返回本地 IP 地址的字符串表示形式。

【Returns the string representation of the local IP address.】

tlsSocket.localPort#>

返回本地端口的数字表示。

【Returns the numeric representation of the local port.】

tlsSocket.remoteAddress#>

返回远程 IP 地址的字符串表示。例如,'74.125.127.100''2001:4860:a005::68'

【Returns the string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'.】

tlsSocket.remoteFamily#>

返回远程 IP 类型的字符串表示。'IPv4''IPv6'

【Returns the string representation of the remote IP family. 'IPv4' or 'IPv6'.】

tlsSocket.remotePort#>

返回远程端口的数字表示。例如,443

【Returns the numeric representation of the remote port. For example, 443.】

tlsSocket.renegotiate(options, callback)#>

  • options <Object>
    • rejectUnauthorized <boolean> 如果不是 false,服务器证书将会根据提供的 CA 列表进行验证。如果验证失败,会触发 'error' 事件;err.code 包含 OpenSSL 错误代码。默认值: true
    • requestCert
  • callback <Function> 如果 renegotiate() 返回 true,回调会被附加一次到 'secure' 事件上。如果 renegotiate() 返回 falsecallback 将在下一个周期被调用并带有一个错误,除非 tlsSocket 已被销毁,在这种情况下 callback 将根本不会被调用。
  • 返回:<boolean> 如果重新协商已启动,则为 true,否则为 false

tlsSocket.renegotiate() 方法会启动一个 TLS 重新协商过程。完成后,callback 函数将接收一个参数,该参数要么是 Error(如果请求失败),要么是 null

【The tlsSocket.renegotiate() method initiates a TLS renegotiation process. Upon completion, the callback function will be passed a single argument that is either an Error (if the request failed) or null.】

此方法可在建立安全连接后用于请求对端的证书。

【This method can be used to request a peer's certificate after the secure connection has been established.】

作为服务器运行时,套接字将在 handshakeTimeout 超时后因错误而被销毁。

【When running as the server, the socket will be destroyed with an error after handshakeTimeout timeout.】

对于 TLSv1.3,无法发起重新协商,协议不支持此功能。

【For TLSv1.3, renegotiation cannot be initiated, it is not supported by the protocol.】

tlsSocket.setMaxSendFragment(size)#>

  • size <number> 最大 TLS 分片大小。最大值为 16384默认值: 16384
  • 返回:<boolean>

tlsSocket.setMaxSendFragment() 方法设置最大的 TLS 数据片段大小。如果设置限制成功,返回 true;否则返回 false

【The tlsSocket.setMaxSendFragment() method sets the maximum TLS fragment size. Returns true if setting the limit succeeded; false otherwise.】

较小的片段大小可以减少客户端的缓冲延迟:TLS 层会缓冲较大的片段,直到整个片段接收完成并且其完整性得到验证;较大的片段可能跨多个往返,并且由于数据包丢失或重排,其处理可能被延迟。然而,较小的片段会增加额外的 TLS 帧字节和 CPU 开销,这可能会降低服务器的整体吞吐量。

【Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput.】

tls.checkServerIdentity(hostname, cert)#>

验证证书 cert 是否颁发给 hostname

【Verifies the certificate cert is issued to hostname.】

返回 <Error> 对象,在失败时用 reasonhostcert 填充它。成功时,返回 <undefined>

【Returns <Error> object, populating it with reason, host, and cert on failure. On success, returns <undefined>.】

此函数旨在与可以传递给 tls.connect()checkServerIdentity 选项结合使用,因此它作用于 证书对象。对于其他用途,请考虑使用 x509.checkHost()

【This function is intended to be used in combination with the checkServerIdentity option that can be passed to tls.connect() and as such operates on a certificate object. For other purposes, consider using x509.checkHost() instead.】

可以通过提供一个替代函数作为传递给 tls.connect()options.checkServerIdentity 选项来重写此函数。当然,重写的函数可以调用 tls.checkServerIdentity(),以在现有检查的基础上增加额外的验证。

【This function can be overwritten by providing an alternative function as the options.checkServerIdentity option that is passed to tls.connect(). The overwriting function can call tls.checkServerIdentity() of course, to augment the checks done with additional verification.】

只有在证书通过了所有其他检查后才会调用此函数,例如由受信任的 CA (options.ca) 颁发。

【This function is only called if the certificate passed all other checks, such as being issued by trusted CA (options.ca).】

早期版本的 Node.js 如果存在匹配的 uniformResourceIdentifier 主题备用名称,会错误地接受给定 hostname 的证书(参见 CVE-2021-44531)。希望接受 uniformResourceIdentifier 主题备用名称的应用可以使用自定义的 options.checkServerIdentity 函数来实现所需的行为。

【Earlier versions of Node.js incorrectly accepted certificates for a given hostname if a matching uniformResourceIdentifier subject alternative name was present (see CVE-2021-44531). Applications that wish to accept uniformResourceIdentifier subject alternative names can use a custom options.checkServerIdentity function that implements the desired behavior.】

tls.connect(options[, callback])#>

  • options <Object>
    • enableTrace:参见 tls.createServer()

    • host <string> 客户端应连接的主机。默认值: 'localhost'

    • port <number> 客户端应连接的端口。

    • path <string> 创建到指定路径的 Unix 套接字连接。如果指定了此选项,hostport 将被忽略。

    • socket <stream.Duplex> 在给定的套接字上建立安全连接,而不是创建新的套接字。通常,这是 net.Socket 的一个实例,但允许使用任何 Duplex 流。 如果指定了此选项,pathhostport 将被忽略,但证书验证除外。通常,将套接字传递给 tls.connect() 时,它已经连接,但也可以稍后连接。socket 的连接/断开/销毁由用户负责;调用 tls.connect() 不会调用 net.connect()

    • allowHalfOpen <boolean> 如果设置为 false,当可读端结束时,套接字会自动结束可写端。如果设置了 socket 选项,则此选项不起作用。有关详细信息,请参阅 net.SocketallowHalfOpen 选项。默认值: false

    • rejectUnauthorized <boolean> 如果不是 false,服务器证书将会根据提供的 CA 列表进行验证。如果验证失败,会触发 'error' 事件;err.code 包含 OpenSSL 错误代码。默认值: true

    • pskCallback <Function>

      • 提示:<string> 可选消息,由服务器发送以帮助客户端在协商期间决定使用哪种身份。如果使用 TLS 1.3,则始终为 null
      • 返回: <Object>,形式为 { psk: <Buffer|TypedArray|DataView>, identity: <string> },或 null 以停止协商过程。psk 必须与所选加密算法的摘要兼容。identity 必须使用 UTF-8 编码。

      When negotiating TLS-PSK (pre-shared keys), this function is called with optional identity hint provided by the server or null in case of TLS 1.3 where hint was removed. It will be necessary to provide a custom tls.checkServerIdentity() for the connection as the default one will try to check host name/IP of the server against the certificate but that's not applicable for PSK because there won't be a certificate present. More information can be found in the RFC 4279.

    • ALPNProtocols: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> An array of strings, Buffers, TypedArrays, or DataViews, or a single Buffer, TypedArray, or DataView containing the supported ALPN protocols. Buffers should have the format [len][name][len][name]... e.g. '\x08http/1.1\x08http/1.0', where the len byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. ['http/1.1', 'http/1.0']. Protocols earlier in the list have higher preference than those later.

    • servername: <string> Server name for the SNI (Server Name Indication) TLS extension. It is the name of the host being connected to, and must be a host name, and not an IP address. It can be used by a multi-homed server to choose the correct certificate to present to the client, see the SNICallback option to tls.createServer().

    • checkServerIdentity(servername, cert) <Function> A callback function to be used (instead of the builtin tls.checkServerIdentity() function) when checking the server's host name (or the provided servername when explicitly set) against the certificate. This should return an <Error> if verification fails. The method should return undefined if the servername and cert are verified.

    • session <Buffer> A Buffer instance, containing TLS session.

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

    • highWaterMark: <number> Consistent with the readable stream highWaterMark parameter. Default: 16 * 1024.

    • secureContext: TLS context object created with tls.createSecureContext(). If a secureContext is not provided, one will be created by passing the entire options object to tls.createSecureContext().

    • onread <Object> If the socket option is missing, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket, otherwise the option is ignored. See the onread option of net.Socket for details.

    • ...: tls.createSecureContext() options that are used if the secureContext option is missing, otherwise they are ignored.

    • ...: Any socket.connect() option not already listed.

  • callback <Function>
  • Returns: <tls.TLSSocket>

如果指定,callback 函数将被添加为 'secureConnect' 事件的监听器。

【The callback function, if specified, will be added as a listener for the 'secureConnect' event.】

tls.connect() 返回一个 tls.TLSSocket 对象。

https API 不同,tls.connect() 默认不启用 SNI(服务器名称指示)扩展,这可能导致某些服务器返回错误的证书或完全拒绝连接。要启用 SNI,除了设置 host 外,还需设置 servername 选项。

【Unlike the https API, tls.connect() does not enable the SNI (Server Name Indication) extension by default, which may cause some servers to return an incorrect certificate or reject the connection altogether. To enable SNI, set the servername option in addition to host.】

以下展示了来自 tls.createServer() 的回声服务器示例客户端:

【The following illustrates a client for the echo server example from tls.createServer():】

// Assumes an echo server that is listening on port 8000.
const tls = require('node:tls');
const fs = require('node:fs');

const options = {
  // Necessary only if the server requires client certificate authentication.
  key: fs.readFileSync('client-key.pem'),
  cert: fs.readFileSync('client-cert.pem'),

  // Necessary only if the server uses a self-signed certificate.
  ca: [ fs.readFileSync('server-cert.pem') ],

  // Necessary only if the server's cert isn't for "localhost".
  checkServerIdentity: () => { return null; },
};

const 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', () => {
  console.log('server ends connection');
}); 

tls.connect(path[, options][, callback])#>

tls.connect() 相同,不同之处在于 path 可以作为参数提供,而不是作为选项。

【Same as tls.connect() except that path can be provided as an argument instead of an option.】

路径选项,如果指定,将优先于路径参数。

【A path option, if specified, will take precedence over the path argument.】

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

tls.connect() 相同,不同的是 porthost 可以作为参数提供,而不是作为选项。

【Same as tls.connect() except that port and host can be provided as arguments instead of options.】

如果指定了端口或主机选项,它将优先于任何端口或主机参数。

【A port or host option, if specified, will take precedence over any port or host argument.】

tls.createSecureContext([options])#>

  • options <Object>
    • ca <string> | <string[]> | <Buffer> | <Buffer[]> Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. The value can be a string or Buffer, or an Array of strings and/or Buffers. Any string or Buffer can contain multiple PEM CAs concatenated together. The peer's certificate must be chainable to a CA trusted by the server for the connection to be authenticated. When using certificates that are not chainable to a well-known CA, the certificate's CA must be explicitly specified as a trusted or the connection will fail to authenticate. If the peer uses a certificate that doesn't match or chain to one of the default CAs, use the ca option to provide a CA certificate that the peer's certificate can match or chain to. For self-signed certificates, the certificate is its own CA, and must be provided. For PEM encoded certificates, supported types are "TRUSTED CERTIFICATE", "X509 CERTIFICATE", and "CERTIFICATE". See also tls.rootCertificates.
    • cert <string> | <string[]> | <Buffer> | <Buffer[]> PEM 格式的证书链。每个私钥应提供一个证书链。每条证书链应包含提供的私钥 key 对应的 PEM 格式证书,然后按顺序附上 PEM 格式的中间证书(如果有),但不包括根 CA(根 CA 必须预先为对端所知,参见 ca)。在提供多条证书链时,其顺序不必与 key 中的私钥顺序一致。如果未提供中间证书,对端将无法验证证书,握手将失败。
    • sigalgs <string> 冒号分隔的支持签名算法列表。该列表可以包含摘要算法(如 SHA256MD5 等)、公钥算法(如 RSA-PSSECDSA 等)、两者的组合(如 'RSA+SHA384')或 TLS v1.3 的方案名称(如 rsa_pss_pss_sha512)。有关更多信息,请参阅 OpenSSL 手册页
    • ciphers <string> 密码套件规范,用于替换默认设置。更多信息请参见 修改默认的 TLS 密码套件。允许的密码套件可以通过 tls.getCiphers() 获取。密码名称必须大写,以便 OpenSSL 接受它们。
    • clientCertEngine <string> 可以提供客户端证书的 OpenSSL 引擎的名称。
    • crl <string> | <string[]> | <Buffer> | <Buffer[]> PEM 格式的 CRL(证书吊销列表)。
    • dhparam <string> | <Buffer> 'auto' 或自定义 Diffie-Hellman 参数,非 ECDHE 完美前向保密 所必需。如果省略或无效,参数将被静默丢弃,DHE 密码套件将不可用。基于 ECDHE完美前向保密 仍然可用。
    • ecdhCurve <string> 一个描述命名曲线的字符串,或一个以冒号分隔的曲线 NID 或名称列表,例如 P-521:P-384:P-256,用于 ECDH 密钥协商。设置为 auto 可自动选择曲线。使用 crypto.getCurves() 获取可用曲线名称列表。在近期版本中,openssl ecparam -list_curves 也会显示每条可用椭圆曲线的名称和描述。默认值: tls.DEFAULT_ECDH_CURVE
    • honorCipherOrder <boolean> 尝试使用服务器的加密套件偏好设置,而不是客户端的。当设置为 true 时,会在 secureOptions 中设置 SSL_OP_CIPHER_SERVER_PREFERENCE,有关详细信息,请参见 OpenSSL 选项
    • key <string> | <string[]> | <Buffer> | <Buffer[]> | <Object[]> PEM 格式的私钥。PEM 允许私钥加密。加密的密钥将使用 options.passphrase 解密。可以提供使用不同算法的多个密钥,方式可以是未加密密钥字符串或缓冲区的数组,或者是形如 {pem: <string|buffer>[, passphrase: <string>]} 的对象数组。对象形式仅可以出现在数组中。object.passphrase 可选。如果提供了加密密钥,将使用 object.passphrase 解密;如果未提供,则使用 options.passphrase
    • privateKeyEngine <string> 用于获取私钥的 OpenSSL 引擎名称。应与 privateKeyIdentifier 一起使用。
    • privateKeyIdentifier <string> 由 OpenSSL 引擎管理的私钥标识符。应与 privateKeyEngine 一起使用。不应与 key 一起设置,因为这两个选项以不同方式定义私钥。
    • maxVersion <string> 可选地设置允许的最大 TLS 版本。可以是 'TLSv1.3''TLSv1.2''TLSv1.1''TLSv1'。不能与 secureProtocol 选项同时指定;两者只能选其一。默认值: tls.DEFAULT_MAX_VERSION
    • minVersion <string> 可选地设置允许的最低 TLS 版本。可选值为 'TLSv1.3''TLSv1.2''TLSv1.1''TLSv1'。不能与 secureProtocol 选项同时指定;两者只能选其一。尽量不要设置低于 TLSv1.2,但为实现互操作性可能需要这样设置。默认值: tls.DEFAULT_MIN_VERSION
    • passphrase <string> 用于单个私钥和/或 PFX 的共享口令。
    • pfx <string> | <string[]> | <Buffer> | <Buffer[]> | <Object[]> PFX 或 PKCS12 编码的私钥和证书链。pfx 是提供 keycert 的替代方式。PFX 通常是加密的,如果是加密的,会使用 passphrase 对其进行解密。可以提供多个 PFX,方式是以未加密的 PFX 缓冲区数组,或以对象数组的形式 {buf: <string|buffer>[, passphrase: <string>]}。对象形式只能出现在数组中。object.passphrase 是可选的。加密的 PFX 将使用提供的 object.passphraseoptions.passphrase(如果未提供 object.passphrase)进行解密。
    • secureOptions <number> 可选择性地影响 OpenSSL 协议行为,通常并不必要。如果使用,应谨慎!值是来自 OpenSSL 选项SSL_OP_* 选项的数字位掩码。
    • secureProtocol <string> 选择要使用的 TLS 协议版本的旧机制,它不支持对最小版本和最大版本的独立控制,也不支持将协议限制为 TLSv1.3。请改用 minVersionmaxVersion。可能的值列在 SSL_方法 中,使用函数名称的字符串。例如,使用 'TLSv1_1_method' 强制使用 TLS 版本 1.1,或使用 'TLS_method' 允许使用最高到 TLSv1.3 的任何 TLS 协议版本。不推荐使用低于 1.2 的 TLS 版本,但可能为了互操作性而需要使用。默认值: 无,见 minVersion
    • sessionIdContext <string> 服务器使用的不透明标识符,用于确保会话状态不会在应用之间共享。客户端不使用此标识符。
    • ticketKeys<Buffer> 48 字节的加密强伪随机数据。更多信息请参见 会话恢复
    • sessionTimeout <number> 服务器创建的 TLS 会话在多少秒后将无法恢复。更多信息请参见 会话恢复默认值: 300

tls.createServer()honorCipherOrder 选项的默认值设置为 true,其他创建安全上下文的 API 则保持未设置状态。

tls.createServer() 使用从 process.argv 生成的 128 位截断 SHA1 哈希值作为 sessionIdContext 选项的默认值,其他创建安全上下文的 API 没有默认值。

tls.createSecureContext() 方法创建一个 SecureContext 对象。它可以作为多个 tls API 的参数使用,例如 server.addContext(),但没有公开的方法。tls.Server 构造函数和 tls.createServer() 方法不支持 secureContext 选项。

【The tls.createSecureContext() method creates a SecureContext object. It is usable as an argument to several tls APIs, such as server.addContext(), but has no public methods. The tls.Server constructor and the tls.createServer() method do not support the secureContext option.】

对于使用证书的密码来说,_需要_一个密钥。可以使用 keypfx 来提供它。

【A key is required for ciphers that use certificates. Either key or pfx can be used to provide it.】

如果未提供 ca 选项,那么 Node.js 将默认使用 Mozilla 的公开信任 CA 列表

【If the ca option is not given, then Node.js will default to using Mozilla's publicly trusted list of CAs.】

不推荐使用自定义 DHE 参数,建议使用新的 dhparam: 'auto' 选项。设置为 'auto' 时,将会自动选择足够强度的知名 DHE 参数。否则,如果有必要,可以使用 openssl dhparam 来创建自定义参数。密钥长度必须大于或等于 1024 位,否则会抛出错误。虽然 1024 位是允许的,但为了更强的安全性,建议使用 2048 位或更长的密钥。

【Custom DHE parameters are discouraged in favor of the new dhparam: 'auto' option. When set to 'auto', well-known DHE parameters of sufficient strength will be selected automatically. Otherwise, if necessary, openssl dhparam can be used to create custom parameters. The key length must be greater than or equal to 1024 bits or else an error will be thrown. Although 1024 bits is permissible, use 2048 bits or larger for stronger security.】

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

稳定性: 0 - 弃用:请改用 tls.TLSSocket

  • context <Object>tls.createSecureContext() 返回的安全上下文对象
  • isServer <boolean> true 用于指定此 TLS 连接应以服务器模式打开。
  • requestCert <boolean> true 用于指定服务器是否应从连接的客户端请求证书。仅在 isServertrue 时适用。
  • rejectUnauthorized <boolean> 如果不是 false,服务器会自动拒绝具有无效证书的客户端。仅当 isServertrue 时适用。
  • 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.】

tls.createSecurePair() 返回一个带有 cleartextencrypted 流属性的 tls.SecurePair 对象。

使用 cleartext 的 API 与 tls.TLSSocket 相同。

【Using cleartext has the same API as tls.TLSSocket.】

tls.createSecurePair() 方法现在已被弃用,建议使用 tls.TLSSocket()。例如,代码:

【The tls.createSecurePair() method is now deprecated in favor of tls.TLSSocket(). For example, the code:】

pair = tls.createSecurePair(/* ... */);
pair.encrypted.pipe(socket);
socket.pipe(pair.encrypted); 

可以替换为:

【can be replaced by:】

secureSocket = tls.TLSSocket(socket, options); 

其中 secureSocketpair.cleartext 拥有相同的 API。

【where secureSocket has the same API as pair.cleartext.】

tls.createServer([options][, secureConnectionListener])#>

  • options <Object>
    • ALPNProtocols<string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> 一个包含字符串、BufferTypedArrayDataView 的数组,或者是单个包含支持的 ALPN 协议的 BufferTypedArrayDataViewBuffer 的格式应为 [长度][name][长度][name]...,例如 0x05hello0x05world,其中第一个字节表示下一个协议名称的长度。传递数组通常更简单,例如 ['hello', 'world']。(协议应按优先级排序。)

    • ALPNCallback<Function> 如果设置,当客户端使用 ALPN 扩展打开连接时将调用此回调。回调将接收一个参数:一个包含 servernameprotocols 字段的对象,分别包含来自 SNI 扩展的服务器名称(如果有)和一个 ALPN 协议名称字符串数组。回调必须返回 protocols 列表中的某个字符串,该字符串将作为所选 ALPN 协议返回给客户端,或者返回 undefined,以致命警报拒绝连接。如果返回的字符串不匹配客户端的 ALPN 协议之一,将抛出错误。此选项不能与 ALPNProtocols 选项同时使用,同时设置两个选项将抛出错误。

    • clientCertEngine <string> 可以提供客户端证书的 OpenSSL 引擎的名称。

    • enableTrace <boolean> 如果为 truetls.TLSSocket.enableTrace() 将在新连接上被调用。可以在安全连接建立后启用跟踪,但必须使用此选项才能跟踪安全连接的建立过程。默认值: false

    • handshakeTimeout <number> 如果 SSL/TLS 握手在指定的毫秒数内未完成,则中止连接。每当握手超时时,tls.Server 对象上会触发 'tlsClientError'默认值: 120000(120 秒)。

    • rejectUnauthorized <boolean> 如果不是 false,服务器将拒绝任何未通过所提供的 CA 列表授权的连接。此选项仅在 requestCerttrue 时有效。默认值: true

    • requestCert <boolean> 如果为 true,服务器将向连接的客户端请求证书,并尝试验证该证书。默认值: false

    • sessionTimeout <number> 服务器创建的 TLS 会话在多少秒后将无法恢复。更多信息请参见 会话恢复默认值: 300

    • SNICallback(servername, callback) <Function> 如果客户端支持 SNI TLS 扩展,将调用该函数。调用时会传入两个参数:servernamecallbackcallback 是一个错误优先的回调,接受两个可选参数:errorctx。如果提供,ctx 是一个 SecureContext 实例。tls.createSecureContext() 可以用来获取合适的 SecureContext。如果 callback 被调用时 ctx 参数为假值,则使用服务器的默认安全上下文。如果未提供 SNICallback,则将使用具有高级 API 的默认回调(见下文)。

    • ticketKeys<Buffer> 48 字节的加密强伪随机数据。更多信息请参见 会话恢复

    • pskCallback <Function>

      When negotiating TLS-PSK (pre-shared keys), this function is called with the identity provided by the client. If the return value is null the negotiation process will stop and an "unknown_psk_identity" alert message will be sent to the other party. If the server wishes to hide the fact that the PSK identity was not known, the callback must provide some random data as psk to make the connection fail with "decrypt_error" before negotiation is finished. PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with the ciphers option. More information can be found in the RFC 4279.

    • pskIdentityHint <string> optional hint to send to a client to help with selecting the identity during TLS-PSK negotiation. Will be ignored in TLS 1.3. Upon failing to set pskIdentityHint 'tlsClientError' will be emitted with 'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED' code.

    • ...: Any tls.createSecureContext() option can be provided. For servers, the identity options (pfx, key/cert, or pskCallback) are usually required.

    • ...: Any net.createServer() option can be provided.

  • secureConnectionListener <Function>
  • Returns: <tls.Server>

创建一个新的 tls.Server。如果提供了 secureConnectionListener,它会自动被设置为 'secureConnection' 事件的监听器。

【Creates a new tls.Server. The secureConnectionListener, if provided, is automatically set as a listener for the 'secureConnection' event.】

ticketKeys 选项会自动在 node:cluster 模块的工作线程之间共享。

【The ticketKeys options is automatically shared between node:cluster module workers.】

以下说明了一个简单的回显服务器:

【The following illustrates a simple echo server:】

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

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

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

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

const 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');
}); 

可以通过使用来自 tls.connect() 的示例客户端连接服务器来对其进行测试。

【The server can be tested by connecting to it using the example client from tls.connect().】

tls.getCiphers()#>

返回一个包含受支持的 TLS 加密套件名称的数组。这些名称由于历史原因为小写,但在用于 tls.createSecureContext()ciphers 选项时必须大写。

【Returns an array with the names of the supported TLS ciphers. The names are lower-case for historical reasons, but must be uppercased to be used in the ciphers option of tls.createSecureContext().】

并非所有支持的密码算法默认都已启用。请参阅 修改默认的 TLS 密码套件

【Not all supported ciphers are enabled by default. See Modifying the default TLS cipher suite.】

以 'tls_' 开头的加密套件名称用于 TLSv1.3,其他所有名称用于 TLSv1.2 及以下版本。

【Cipher names that start with 'tls_' are for TLSv1.3, all the others are for TLSv1.2 and below.】

console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] 

tls.rootCertificates#>

一个不可变的字符串数组,表示来自当前 Node.js 版本提供的打包 Mozilla CA 存储的根证书(PEM 格式)。

【An immutable array of strings representing the root certificates (in PEM format) from the bundled Mozilla CA store as supplied by the current Node.js version.】

由 Node.js 提供的打包 CA 证书库是 Mozilla CA 证书库在发布时的快照。在所有支持的平台上都是相同的。

【The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store that is fixed at release time. It is identical on all supported platforms.】

tls.DEFAULT_ECDH_CURVE#>

在 TLS 服务器中用于 ECDH 密钥协商的默认曲线名称。默认值为 'auto'。有关更多信息,请参见 tls.createSecureContext()

【The default curve name to use for ECDH key agreement in a tls server. The default value is 'auto'. See tls.createSecureContext() for further information.】

tls.DEFAULT_MAX_VERSION#>

  • <string> tls.createSecureContext()maxVersion 选项的默认值。它可以被设置为任何受支持的 TLS 协议版本:'TLSv1.3''TLSv1.2''TLSv1.1''TLSv1'默认值: 'TLSv1.3',除非通过 CLI 选项进行更改。使用 --tls-max-v1.2 将默认值设置为 'TLSv1.2'。使用 --tls-max-v1.3 将默认值设置为 'TLSv1.3'。如果提供了多个选项,将使用最高的最大值。

tls.DEFAULT_MIN_VERSION#>

  • <string> tls.createSecureContext()minVersion 选项的默认值。它可以被赋值为任何支持的 TLS 协议版本,'TLSv1.3''TLSv1.2''TLSv1.1''TLSv1'默认值: 'TLSv1.2',除非使用 CLI 选项进行更改。使用 --tls-min-v1.0 会将默认值设置为 'TLSv1'。使用 --tls-min-v1.1 会将默认值设置为 'TLSv1.1'。使用 --tls-min-v1.3 会将默认值设置为 'TLSv1.3'。如果提供了多个选项,则使用最低的最小版本。

tls.DEFAULT_CIPHERS#>

  • <string> tls.createSecureContext()ciphers 选项的默认值。它可以被分配为任何受支持的 OpenSSL 密码套件。默认情况下为 crypto.constants.defaultCoreCipherList 的内容,除非通过 CLI 选项使用 --tls-default-ciphers 修改。
Node.js 中文网 - 粤ICP备13048890号