Home > OS >  OpenSSL::SSL::SSLError: Ruby client's server ca certificate does not work while it worked with
OpenSSL::SSL::SSLError: Ruby client's server ca certificate does not work while it worked with

Time:02-22

I got certificate from customer to connect with their VPN, but it does not work with ruby code while it worked with curl command. Curl command is as follows:

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

In ruby, I am trying to do the following to connect the client APIs provided to us for transactions.

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

We also tried to pass our server's certificate as follows, but that doesn't work either

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"))

Getting the following error while

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

CodePudding user response:

I think the issue with their self-signed certificate. It fails verification. However, you can manually disable it with

http.verify_mode = OpenSSL::SSL::VERIFY_NONE

verify_mode[RW]

Sets the flags for server the certification verification at beginning of SSL/TLS session.

OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER are acceptable.

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

I tried to replicate it locally and it worked with this fix.

CodePudding user response:

CURL is usually not that picky comparing to "Rails tools". I remember the same issue recently, and the problem was about extra new lines.

Try this

http.cert = OpenSSL::X509::Certificate.new(raw.gsub("\n\n", "\n"))

(Same for a key)

  • Related