OpenSSL::SSL::SSLError:Ruby 客户端的服务器 ca 证书在使用 curl 时不起作用



我从客户那里获得了连接他们的VPN的证书,但它在使用curl命令时无法使用ruby代码。卷曲命令如下:

curl --cacert cert.cer -d '{"acb": 123 }' -H 'Content-Type: application/json' 'https://demo.com'

在ruby中,我尝试执行以下操作来连接为事务提供的客户端API。

require 'net/http'
require 'json'
require 'uri'
full_url = "https://demo.com"
uri = URI.parse(full_url)
data = { "acb": 123 }
headers = { 'Content-Type' => "application/json" }
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
raw = File.read("path_to_the_certificate")
http.cert = OpenSSL::X509::Certificate.new(raw)
request = Net::HTTP::Post.new(uri.request_uri, headers)
request.body = data.to_json
response = http.request(request)
puts response.code
puts response.body

我们还尝试按如下方式通过服务器的证书,但也不起作用

http.ca_path='/etc/pki/tls/certs'
http.ca_file='/etc/pki/tls/certs/cert.cer'
http.cert = OpenSSL::X509::Certificate.new(File.read("/path/client.crt"))
http.key = OpenSSL::PKey::RSA.new(File.read("/path/client.key"))

时出现以下错误

OpenSSL::SSL::SSLError (SSL_connect returned=1 errno=0 state=error: certificate verify failed (unable to get local issuer certificate))

我认为他们的自签名证书有问题。未通过验证。但是,您可以使用手动禁用它

http.verify_mode = OpenSSL::SSL::VERIFY_NONE

verify_mode[RW]

在SSL/TLS会话开始时设置服务器证书验证的标志。

可以接受OpenSSL::SSL::VERIFY_NONE或OpenSSL::SSL::VERIFY_PEER。

来自https://ruby-doc.org/stdlib-2.7.0/libdoc/net/http/rdoc/Net/HTTP.html

我尝试在本地复制它,它与这个修复程序一起工作。

应该是vpn证书是自签名的,你需要指定自己的cacert,所以你指定cacert文件作为上面curl使用的文件,而不是系统附带的cacert文件

添加此行:

http.ca_file = "cacert filename" 

像这样:

require 'net/http'
require 'json'
require 'uri'
full_url = "https://localhost/test.html"
uri = URI.parse(full_url)
data = { "acb": 123 }
headers = { 'Content-Type' => "application/json" }
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
# You need to specify the cacert file used for curl above (filename: cert.cer)
http.ca_file = "/root/myca/cacert.crt"
request = Net::HTTP::Post.new(uri.request_uri, headers)
request.body = data.to_json
response = http.request(request)
puts response.code
puts response.body

您应该将.pem格式的证书添加到(取决于版本(:

C: \Ruby{版本号}{-x64-if 64位操作系统}\ssl

例如C:\Ruby25-x64\ssl

C: \Ruby{版本号}{-x64-if 64位操作系统}\lib\Ruby{版本编号}\rubygems\ssl_certs{your cn}

例如C:\Ruby25-x64\lib\ruby\2.5.0\rubygems\ssl_certs\client.cn

然后在C:\Ruby{版本号}{-x64-如果是64位操作系统}\ssl\cert中运行C_rehash.r脚本

对于使用PayPal::SDK.configure(…(的应用程序

PayPal::SDK.configure(
mode: ...,
client_id: ...,
client_secret: ...,
# Deliberately set ca_file to nil so the system's Cert Authority is used,
# instead of the bundled paypal.crt file which is out-of-date due to:
# https://www.paypal.com/va/smarthelp/article/discontinue-use-of-verisign-g5-root-certificates-ts2240
ssl_options: { ca_file: nil }
)

对于使用YAML配置文件的应用程序

ssl_options:
ca_file: null

最新更新