Skip to content

Instantly share code, notes, and snippets.

@zealot128
Last active June 21, 2018 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zealot128/934901e134b0e98945476140340feb3c to your computer and use it in GitHub Desktop.
Save zealot128/934901e134b0e98945476140340feb3c to your computer and use it in GitHub Desktop.
Ruby: check for domain name certificate expirations (supports starttls smtp and tls/https)

Check

check for domain tls certificate expirations.

Pass any number of domain:port pairs to the program, it will try to fetch all and present a little table with the soonest to expire on top.

On port 25 it will use Starttls for validation, otherwise SNI TLS.

ruby check.rb my.domain.de www.domain.de mail.domain.de:25 pop.domain.de:995
require 'socket'
require 'openssl'
require 'net/smtp'
class Check
def initialize(domain, port)
@domain = domain
@port = port || 443
end
def expiration
if @port.to_i == 25
smtp_starttls
else
tls
end
end
def context
@context ||= begin
context = OpenSSL::SSL::SSLContext.new
context.verify_mode = OpenSSL::SSL::VERIFY_PEER
context.ca_path = '/etc/ssl/certs'
context
end
end
def tls
tcp_client = TCPSocket.new @domain, @port.to_i
ssl_client = OpenSSL::SSL::SSLSocket.new tcp_client, context
ssl_client.hostname = @domain
ssl_client.connect
cert = ssl_client.peer_cert
cert.not_after
rescue OpenSSL::SSL::SSLError => e
e.inspect
ensure
tcp_client.close if tcp_client
end
def smtp_starttls
smtp = Net::SMTP.new(@domain)
# smtp.set_debug_output $stdout
smtp.enable_starttls(context)
smtp.start
smtp.instance_variable_get("@socket").io.peer_cert.not_after
ensure
smtp.finish
end
end
result = []
if ARGV.length == 0
puts "USAGE: ruby check.rb www.domain.de mail.server.de:25 mail.server.de:995"
exit 1
end
ARGV.each do |domain|
d, p = domain.split(':')
result << [domain, Check.new(d, p).expiration]
end
result.sort_by { |a, b| b.to_s }.each do |domain, expiration|
puts sprintf("%30s - %s", domain, expiration)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment