Monkey patching use_ssl= method works for Net:HTTP but not for OpenURI in Ruby 1.9.3? -
background:
- ruby 1.9.3
- rails 3.2.16
- windows 7 x64
issue
i'm trying fix infamous
ssl_connect returned=1 errno=0 state=sslv3 read server certificate b: certificate verify failed
error including certificates in each http request perform. monkey patch 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 system cas. dir[rails.root + 'config/certificates/*'].each |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
now, requests performed using net::http
, example:
> 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') |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>
work perfectly.
however, when try use openuri, thought wrapper around net::http (and other io operations), such as:
> 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 d:/ruby/ruby193/lib/ruby/1.9.1/net/http.rb:800:in `connect' d:/ruby/ruby193/lib/ruby/1.9.1/net/http.rb:800:in `block in connect
so can see monkey patched method getting hit ("adding cert.."), still error. seems though else overriding it. ideas?
thanks
i managed come solution (a while now, hope still applicable).
according comments in code, needed monkey patch cert_store=
"as use_ssl=
net::http
, openuri.open_http
call these methods in different orders, need ensure certificates consistently added."
so, here solution:
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 system cas. self.cert_store = store # 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 |cert| store.add_cert(openssl::x509::certificate.new(file.read(cert))) end self.original_cert_store = store end end end
hope helps
Comments
Post a Comment