猴子修补use_ssl =方法适用于Net:HTTP但不适用于Ruby 1.9.3中的OpenURI?

时间:2014-02-06 10:14:02

标签: ruby-on-rails ruby ssl net-http open-uri

背景

  • Ruby 1.9.3
  • Rails 3.2.16
  • Windows 7 x64

问题

我正试图修复臭名昭着的

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
通过在我执行的每个HTTP请求中包含我的证书来导致

错误。要做到这一点,我将修补Net::HTTP#use_ssl=

# lib/gem_ext/net_http.rb
require 'open-uri'
require 'net/https'

module Net
  class HTTP
    alias_method :original_use_ssl=, :use_ssl=

    def use_ssl=(flag)
      store = OpenSSL::X509::Store.new
      store.set_default_paths # Auto-include the system CAs.

      Dir[Rails.root + 'config/certificates/*'].each do |cert|
        puts "Adding cert: #{cert}"
        store.add_cert(OpenSSL::X509::Certificate.new(File.read(cert)))
      end

      self.cert_store = store
      self.verify_mode = OpenSSL::SSL::VERIFY_PEER
      self.original_use_ssl = flag
    end
  end
end

现在,请求使用Net::HTTP执行,例如:

> uri = URI.parse('https://internal-app/secure_url.json?foo=bar')
> Net::HTTP.start(uri.host, uri.port, :read_timeout => 10.minutes, :use_ssl => uri.scheme == 'https') do |http|
>  http.request Net::HTTP::Get.new(uri.request_uri)
> end
Adding cert: config/certificates/cert1.cer
Adding cert: config/certificates/cert2.cer
=> #<Net::HTTPOK 200 OK readbody=true>

完美地工作。

但是,当我尝试使用OpenURI时,我认为它只是Net :: HTTP(以及其他IO操作)的包装,例如:

> require 'open-uri'    
> open('https://our-all/secure_url.json?foo=bar', 'r', :read_timeout => 10.minutes)
Adding cert: config/certificates/cert1.cer
Adding cert: config/certificates/cert2.cer
#<Class:0x870e2e0>: SSL_connect returned=1 errno=0 state=SSLv3 read server certi
  from D:/Ruby/Ruby193/lib/ruby/1.9.1/net/http.rb:800:in `connect'
  from D:/Ruby/Ruby193/lib/ruby/1.9.1/net/http.rb:800:in `block in connect

所以我可以看到我的猴子补丁方法被击中(“添加证书......”),但我仍然得到错误。好像其他东西正在压倒它。有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

我设法提出了一个解决方案(现在回来一段时间,所以我希望它仍然适用)。

根据我的代码中的评论,我需要将补丁cert_store=use_ssl=作为Net::HTTPOpenURI.open_http以不同的顺序调用这些方法,所以我们需要确保一致地添加证书。“

所以,这是我的解决方案:

module Net
  class HTTP

    alias_method :original_use_ssl=, :use_ssl=
    def use_ssl=(flag)
      store = OpenSSL::X509::Store.new
      store.set_default_paths # Auto-include the system CAs.
      self.cert_store = store # Now include internal certificates.
      self.verify_mode = OpenSSL::SSL::VERIFY_PEER # Force verification.
      self.original_use_ssl = flag
    end

    alias_method :original_cert_store=, :cert_store=
    def cert_store=(store)
      Dir[Rails.root + 'config/certificates/*'].each do |cert|
        store.add_cert(OpenSSL::X509::Certificate.new(File.read(cert)))
      end

      self.original_cert_store = store
    end
  end
end

希望有所帮助