Created
February 3, 2020 02:17
-
-
Save Aupajo/cda47182a301da34332fb23b28bdec42 to your computer and use it in GitHub Desktop.
SSL verification in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage: ruby verify-ssl.rb domain1.com domain2.com domain3.com | |
require 'socket' | |
require 'openssl' | |
SSL_PORT = 443 | |
def verify(domain, cert_store) | |
puts "---" | |
puts "Domain: #{domain}" | |
tcp_socket = TCPSocket.new(domain, SSL_PORT) | |
ssl_client = OpenSSL::SSL::SSLSocket.new(tcp_socket) | |
# Pass the hostname, for SNI support | |
ssl_client.hostname = domain | |
# Close the underlying socket when closin the client connection | |
ssl_client.sync_close = true | |
print "Connection: " | |
ssl_client.connect | |
ssl_client.sysclose | |
puts "OK" | |
cert, *chain = ssl_client.peer_cert_chain | |
puts "Cert:" | |
common_name = cert.subject.to_a.find { |entry| entry.first == 'CN' }[1] | |
puts "- Version: #{cert.version + 1}" # NB: version 3 = int 2 | |
puts "- Name: #{common_name}" | |
puts "- Issued by: #{cert.issuer}" | |
puts "- Expires: #{cert.not_after}" | |
cert.extensions.each do |extension| | |
next unless extension.oid == 'subjectAltName' | |
puts "- Alternative names: #{extension.value}" | |
end | |
puts "Chain: " | |
chain.each.with_index do |cert, i| | |
puts "#{i + 1}. #{cert.issuer}" | |
end | |
print "Valid: " | |
puts cert_store.verify(cert, chain) | |
# Close the connection | |
end | |
puts "Using: #{OpenSSL::OPENSSL_VERSION}" | |
puts "Default certs:" | |
puts "- #{OpenSSL::X509::DEFAULT_CERT_FILE}" | |
puts "- #{OpenSSL::X509::DEFAULT_CERT_DIR}" | |
# Use the system's CA certs | |
cert_store = OpenSSL::X509::Store.new | |
cert_store.set_default_paths | |
domains = ARGV | |
domains.each { |domain| verify(domain, cert_store) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment