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

问题描述 投票:0回答:3

我正在使用客户端证书从节点应用程序建立 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 选项或其他地方找到任何方法来配置它。是否可以配置它,或者我是否必须建立连接,然后查询协议版本,例如:

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

如果协议不令人满意,则中止连接?

node.js https tls1.2
3个回答
32
投票

首先我找到了有关发出 HTTPS 请求的文档。它提到您可以将其他选项传递给

tls.connect()
,其中包括称为
secureProtocol
的选项。深入研究
tls.connect()
,我发现
secureContext
选项提到了
tls.createSecureContext()
。最后提到
secureProtocol
,可以使用来自 OpenSSL 页面 的字符串指定。我选择了一个看起来合理的字符串 (
TLSv1_2_method
) 并将
secureProtocol
选项直接传递到
https.request

这将使用给定的

SSL Version: TLS 1.2
打印
secureProtocol
,并使用
SSL Version: TLS 1.1
打印
secureProtocol: "TLSv1_1_method"
。如果无法使用给定的 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()

9
投票

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

Node 文档现在建议使用

minVersion
maxVersion
代替
secureProtocol
,因为最后一个选项已成为选择 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"
}
...

参考文献:节点文档:tls_tls_createsecurecontext_options


0
投票

您可以使用

tls
库:

const tls = require('tls');

tls.DEFAULT_MAX_VERSION = 'TLSv1.2';
© www.soinside.com 2019 - 2024. All rights reserved.