Ruby and SSL Certificate Validation

Ariejan de vroomPosted by Ariejan de Vroom on 12-4-2009

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

Bij Kabisa staat privacy hoog in het vaandel. Wij vinden het belangrijk dat er zorgvuldig wordt omgegaan met de data die onze bezoekers achterlaten. Zo zult u op onze website geen tracking-cookies vinden van third-parties zoals Facebook, Hotjar of Hubspot. Er worden alleen cookies geplaatst van Google en Vimeo. Deze worden gebruikt voor analyses, om zo de gebruikerservaring van onze websitebezoekers te kunnen verbeteren. Tevens zorgen deze cookies ervoor dat er relevante advertenties worden getoond. Lees meer over het gebruik van cookies in ons privacy statement.