Ruby and SSL Certificate Validation

Ariejan de vroom

Ariejan de Vroom – 12 April 2009
202 words in about 1 minute

If your ruby app is doing SSL, you have probably seen one of the following errors:

1
doc = Hpricot(open("https://www.cert.org/blogs/vuls/rss.xml")) # => /usr/lib/ruby/1.8/net/http.rb:590:in `connect': certificate verify failed (OpenSSL::SSL::SSLError)

or

1
warning: peer certificate won't be verified in this SSL session

The solution is to make sure ruby has access to the right set of root certificates.

The easiest way to get hold of those root certificates is by downloading this file cacert.pem (details) (updated weekly by the developers of CURL, based on the Mozilla browser). Download this file and store it somewhere in your app.

If you’re really keen on security, don’t trust the guys from CURL and download the different root certificates from their providers manually. However, in most cases, the file from CURL will suffice.

Then, in your ruby code, setup the connection like this and you’ll have a validated SSL connection:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#! /usr/bin/env ruby
require 'net/https'
require 'uri'

uri = URI.parse(ARGV[0] || 'https://localhost/')
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == "https"  # enable SSL/TLS
  http.use_ssl = true
  # Only needed for ruby 1.8.6
  # http.enable_post_connection_check = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  http.ca_file = File.join(File.dirname(__FILE__), "cacert.pem")
end

http.start do
  http.request_get(uri.path) do |res|
    print res.body
  end
end
Ariejan de vroom

Ariejan de Vroom

Software Engineer • CodeRetreat Facilitator • Ruby, Go and C Programmer • Electronics Apprentice

At Kabisa, privacy is of the greatest importance. We think it is important that the data our visitors leave behind is handled with care. For example, you will not find tracking cookies from third parties such as Facebook, Hotjar or Hubspot on our website. Only cookies from Google and Vimeo are used in order to improve the user experience of our visitors. These cookies also ensure that relevant advertisements are displayed. Read more about the use of cookies in our privacy statement.