Posts Tagged ‘ssl’

Ruby 1.9 and the SSL error

  December 30th, 2010

After switching to Ruby 1.9 on Mac OS X 10.6, the following code which makes a https request to encrypted.google.com:

require 'net/https'
https = Net::HTTP.new('encrypted.google.com', 443)
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_PEER
https.request_get('/')

fails with the following error:

/opt/local/lib/ruby1.9/1.9.1/net/http.rb:677:
  in `connect':
  SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (OpenSSL::SSL::SSLError)

The problem comes from the fact that the new Ruby 1.9 installation doesn’t find the certification authority certificates (CA Certs) used to verify the authenticity of secured web servers.

The solution is to install the curl-ca-bundle port which contains the same root certificates used by Firefox:

sudo port install curl-ca-bundle

and tell your https object to use it:

https.ca_file = '/opt/local/share/curl/curl-ca-bundle.crt'

Note that if you want your code to run on Ubuntu, you need to set the ca_path attribute instead, with the default certificates location /etc/ssl/certs.

In the end, that’s what will work on both Mac OS X and Ubuntu:

require 'net/https'
https = Net::HTTP.new('encrypted.google.com', 443)
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_PEER
https.ca_path = '/etc/ssl/certs' if File.exists?('/etc/ssl/certs') # Ubuntu
https.ca_file = '/opt/local/share/curl/curl-ca-bundle.crt' if File.exists?('/opt/local/share/curl/curl-ca-bundle.crt') # Mac OS X
https.request_get('/')