mercredi, septembre 12, 2007

Ruby net/https and invalid server certificate

Again in English since there is so few documentation. Here's the code to connect to a https server using ssl and certificate (using net/https standard lib):
def get_url(url, &block)
 puts "Getting url: #{url}"

 uri = URI.parse(url)
 http = Net::HTTP.new(uri.host, uri.port)
 http.use_ssl = true
 http.verify_mode = OpenSSL::SSL::VERIFY_PEER
 http.ca_file = 'ca.server.domain.com.crt'
 pem_file = 'certificate-privateKey.pem'
 http.cert = OpenSSL::X509::Certificate.new(File.open(pem_file).read)
 http.key = OpenSSL::PKey::RSA.new(File.open(pem_file).read)

 http.start {
   http.request_get(uri.path) {|res|
     @page.response = res
     yield
   }
 }
end
end
For the pem format see my other article: Https, Ssl and Ruby
If the server ca is "strange" (I don't know in which way I'm not an ssl expert), you will get those kind of error messages:
.../http.rb:586:in `connect': certificate verify failed (OpenSSL::SSL::SSLError)
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.ca_file = 'ca.server.domain.com.crt'
can be replace with
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
Technorati tags:

Aucun commentaire: