Ruby: How to connect to a host with expired SSL certificate

Posted . Visible to the public.

If you need to make an HTTPS connection to a host which uses an expired certificate, do not disable certificate verifications entirely. Doing that enables e.g. man in the middle attacks.
If you accept only a single expired and known certificate, you are much less in trouble.


All the solutions described below use a verify_callback for the request's OpenSSL::X509::Store where you can specify a lambda to adjust its verification response.
Your callback must return either true or false and OpenSSL's verification result is the first callback block argument.

In our examples, we will be connecting to which uses an expired certificate.
The certificate is also a wildcard certificate, so its Common Name property (CN) is set to *

Our verify_callback will allow connecting to an expired host only when its certificate contains CN=*

uri = URI.parse('')
expected_common_name = '*'

verify_callback = lambda do |preverify_ok, store_context|
  if store_context.error == OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED && store_context.current_cert.subject.to_s.include?("CN=#{expected_common_name}")
    # The certiciate for that host is expired, but it's fine for us.

Using that is fairly straightforward in your favorite connection library. We've described a few below.


Ruby's Net::HTTP requires the longest setup of all:

require 'net/https'

http =, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.verify_callback = verify_callback

get =
response = http.request(get)
puts response.body


Using the http Show snapshot gem, you can pass along the verify_callback as an option like so:

require 'http'

response = HTTP.get(uri, ssl: { verify_callback: verify_callback })
puts response.body


The rest-client Show snapshot gem also offers an ssl_verify_callback option, but not for its top-level utility methods, like RestClient.get.
Instead, you can use a like so:

require 'rest-client'

resource =, ssl_verify_callback: verify_callback)
puts resource.get
Arne Hartherz
Last edit
Arne Hartherz
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2024-04-08 08:55)