Sha256: 085ef2d3a43aacb35a80fea4d3ad3e4ae04d75d487d5eb850fe3cfc740ca5d58

Contents?: true

Size: 1.52 KB

Versions: 1

Compression:

Stored size: 1.52 KB

Contents

module AlexaSkillsRuby
  class CertificateValidator

    def initialize(extra_cas = [])
      @store = OpenSSL::X509::Store.new.tap { |store| store.set_default_paths }
      extra_cas.each do |ca|
        case ca
          when String
            @store.add_file(ca)
          when OpenSSL::X509::Certificate
            @store.add_cert(ca)
          else
            raise AlexaSkillsRuby::ConfigurationError, 'root_certificates config option must contain only filenames as strings or OpenSSL::X509::Certificate objects'
        end
      end
    end

    def get_signing_certificate(pem_data)
      chain = chain_certs(get_certs(pem_data))
      chain[0...-1].each do |c|
        if @store.verify(c)
          @store.add_cert(c)
        end
      end

      if @store.verify(chain.last)
        chain.last
      else
        nil
      end
    end

    private

    def get_certs(pem_data)
      pem_data.scan(/-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----\n?/m).map do |pem|
        OpenSSL::X509::Certificate.new(pem)
      end
    end

    def chain_certs(certs)
      certs = certs.dup
      failed = false
      chain = [certs.pop]

      while certs.length > 0 && !failed
        failed = true

        certs.each do |c|
          if c.subject == chain.first.issuer
            failed = false
            chain.unshift(c)
            certs.delete(c)
          elsif c.issuer == chain.last.subject
            failed = false
            chain << c
            certs.delete(c)
          end
        end
      end

      chain

    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
alexa_skills_ruby-1.1.0 lib/alexa_skills_ruby/certificate_validator.rb