配置 https 代理以仅允许 TLS1.2 用于传出请求

Configure https agent to allow only TLS1.2 for outgoing requests

我正在使用客户端证书从节点应用建立 HTTPS 连接:

var options = { 
    hostname: 'https://my-server.com', 
    port: 443, 
    path: '/', 
    method: 'GET', 
    key: fs.readFileSync('client1-key.pem'), 
    cert: fs.readFileSync('client1-crt.pem'), 
    ca: fs.readFileSync('ca-crt.pem') }; 

var req = https.request(options, res => { 
    [...]
}); 

一切正常,但我想添加代码以确保只允许 TLS 1.2 连接。我找不到任何方法在 https.agent options, or elsewhere. Is it possible to configure this, or do I have to make a connection and then query the protocol 版本中配置它,例如:

res.socket.getProtocol() === 'TLSv1.2'

如果协议不满意就中止连接?

首先我找到了关于制作 HTTPS requests. It mentions that you can pass additional options to tls.connect() which includes something called secureProtocol. Digging into tls.connect(), I found the secureContext option which mentions tls.createSecureContext(). And there it finally mentions secureProtocol which can be specified with a string from an OpenSSL page 的文档。我选择了一个看起来合理的字符串 (TLSv1_2_method) 并将 secureProtocol 选项直接传递给 https.request.

这将使用给定的 secureProtocol 打印 SSL Version: TLS 1.2 并使用 secureProtocol: "TLSv1_1_method" 打印 SSL Version: TLS 1.1。如果无法使用给定的 TLS 版本建立连接,最后的错误处理程序将被调用。

var https = require('https')

var options = {
    hostname: 'www.howsmyssl.com',
    port: 443,
    path: '/a/check',
    method: 'GET',
    secureProtocol: "TLSv1_2_method"
}

https.request(options, res => {
  let body = ''
  res.on('data', d => body += d)
  res.on('end', () => {
    data = JSON.parse(body)
    console.log('SSL Version: ' + data.tls_version)
  })
}).on('error', err => {
  // This gets called if a connection cannot be established.
  console.warn(err)
}).end()

只是关于这个解决方案的更新,几年过去了,有些事情发生了变化。

Node 文档现在建议使用 minVersionmaxVersion 而不是 secureProtocol,因为最后一个选项已成为 select TLS 协议版本的遗留机制,因此您使用 minVersion: "TLSv1.2":

可以获得相同的结果
var https = require('https')

var options = {
    hostname: 'www.howsmyssl.com',
    port: 443,
    path: '/a/check',
    method: 'GET',
    minVersion: "TLSv1.2",
    maxVersion: "TLSv1.2"
}
...

参考文献:Node docs: tls_tls_createsecurecontext_options