httprb / http

HTTP (The Gem! a.k.a. http.rb) - a fast Ruby HTTP client with a chainable API, streaming support, and timeouts
MIT License
3k stars 321 forks source link

access ssl certificate details? #747

Open jots opened 1 year ago

jots commented 1 year ago

Is it possible to access the certificate details from the response? Interested in Common name, issued by and validity period.

tarcieri commented 1 year ago

I don't believe so. Which type were you thinking of having an accessor for it?

jots commented 1 year ago

some way to access peer_cert? like this

require 'openssl'
require 'net/http'
require 'uri'

url = ARGV[0] # get the URL from the command line arguments

uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true # use SSL for the request

begin
  http.start
rescue OpenSSL::SSL::SSLError => e
  puts "Error: SSL connection could not be established. #{e.message}"
  exit
end

cert = http.peer_cert
if cert.nil?
  puts "Error: No SSL certificate could be retrieved."
  exit
end

cert = OpenSSL::X509::Certificate.new(cert)

puts "Issuer: #{cert.issuer}"
puts "Common Names: #{cert.subject.to_a.select { |name, _, _| name == 'CN' }.map { |_, value, _| value }.join(', ')}"
puts "Valid From: #{cert.not_before}"
puts "Valid Until: #{cert.not_after}"

example:

$ ruby getcert.rb https://google.com
Issuer: /C=US/O=Google Trust Services LLC/CN=GTS CA 1C3
Common Names: *.google.com
Valid From: 2023-03-20 08:22:16 UTC
Valid Until: 2023-06-12 08:22:15 UTC
jots commented 1 year ago

I think this should suffice: response = HTTP.get('https://www.example.com') pp response.connection.instance_variable_get("@socket").instance_variable_get("@socket").peer_cert

tarcieri commented 1 year ago

Seems like you could use an accessor like HTTP::Connection#peer_cert