Skip to content

Instantly share code, notes, and snippets.

@matiaskorhonen
Last active April 19, 2021 21:53
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save matiaskorhonen/81b87ede6af1704c67b8 to your computer and use it in GitHub Desktop.
Save matiaskorhonen/81b87ede6af1704c67b8 to your computer and use it in GitHub Desktop.
Check an SSL/TLS certificate in Ruby (with SNI support)
# Modified from:
# http://findingscience.com/ruby/ssl/2013/01/13/reading-an-ssl-cert-in-ruby.html
require "socket"
require "openssl"
host = "www.piranhas.co"
tcp_client = TCPSocket.new("www.piranhas.co", 443)
ssl_client = OpenSSL::SSL::SSLSocket.new(tcp_client)
ssl_client.hostname = host
ssl_client.connect
cert = OpenSSL::X509::Certificate.new(ssl_client.peer_cert)
ssl_client.sysclose
tcp_client.close
certprops = OpenSSL::X509::Name.new(cert.issuer).to_a
issuer = certprops.select { |name, data, type| name == "O" }.first[1]
results = {
valid_on: cert.not_before,
valid_until: cert.not_after,
issuer: issuer,
valid: (ssl_client.verify_result == 0)
}
@nimf
Copy link

nimf commented Nov 6, 2017

Thank you!

BTW, ssl_client.verify_result is nil if called after ssl_client.sysclose

@GuyPaddock
Copy link

FYI the host variable is not being used.

@ZASMan
Copy link

ZASMan commented Jul 23, 2018

Getting this error:

check_certificate.rb:10:in `initialize': getaddrinfo: Name or service not known (SocketError)

@shaneshort
Copy link

Getting this error:

check_certificate.rb:10:in `initialize': getaddrinfo: Name or service not known (SocketError)

This is a DNS resolution failure. The host you're attempting to connect to doesn't exist, or your DNS resolver is malfunctioning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment