Class: Blather::CertStore

Inherits:
Object
  • Object
show all
Defined in:
lib/blather/cert_store.rb

Overview

An X509 certificate store that validates certificate trust chains. This uses the #cert_directory/*.crt files as the list of trusted root CA certificates.

Constant Summary collapse

@@certs =
nil

Instance Method Summary collapse

Constructor Details

#initialize(cert_directory) ⇒ CertStore

Returns a new instance of CertStore.



12
13
14
15
16
# File 'lib/blather/cert_store.rb', line 12

def initialize(cert_directory)
  @cert_directory = cert_directory
  @store = OpenSSL::X509::Store.new
  certs.each {|c| @store.add_cert(c) }
end

Instance Method Details

#certsObject

Return the trusted root CA certificates installed in the @cert_directory. These certificates are used to start the trust chain needed to validate certs we receive from clients and servers.



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/blather/cert_store.rb', line 41

def certs
  unless @@certs
    pattern = /-{5}BEGIN CERTIFICATE-{5}\n.*?-{5}END CERTIFICATE-{5}\n/m
    dir = @cert_directory
    certs = Dir[File.join(dir, '*.crt')].map {|f| File.read(f) }
    certs = certs.map {|c| c.scan(pattern) }.flatten
    certs.map! {|c| OpenSSL::X509::Certificate.new(c) }
    @@certs = certs.reject {|c| c.not_after < Time.now }
  end
  @@certs
end

#domain?(pem, domain) ⇒ Boolean

Return true if the domain name matches one of the names in the certificate. In other words, is the certificate provided to us really for the domain to which we think we’re connected?

Returns:

  • (Boolean)


32
33
34
35
36
# File 'lib/blather/cert_store.rb', line 32

def domain?(pem, domain)
  if cert = OpenSSL::X509::Certificate.new(pem) rescue nil
    OpenSSL::SSL.verify_certificate_identity(cert, domain) rescue false
  end
end

#trusted?(pem) ⇒ Boolean

Return true if the certificate is signed by a CA certificate in the store. If the certificate can be trusted, it’s added to the store so it can be used to trust other certs.

Returns:

  • (Boolean)


21
22
23
24
25
26
27
# File 'lib/blather/cert_store.rb', line 21

def trusted?(pem)
  if cert = OpenSSL::X509::Certificate.new(pem) rescue nil
    @store.verify(cert).tap do |trusted|
      @store.add_cert(cert) if trusted rescue nil
    end
  end
end