Sha256: a13b7c7053d3950e709225e9b31299f14213b4d6eae2276894c7f8245e8333b7

Contents?: true

Size: 1.89 KB

Versions: 3

Compression:

Stored size: 1.89 KB

Contents

# frozen_string_literal: true

require "openssl/signature_algorithm"
require "tpm/constants"
require "tpm/s_attest"

module TPM
  class CertifyValidator
    attr_reader :info, :signature, :nonce, :object, :signature_algorithm, :hash_algorithm

    TPM_SIGNATURE_ALG_TO_OPENSSL = {
      ALG_RSASSA => OpenSSL::SignatureAlgorithm::RSAPKCS1,
      ALG_RSAPSS => OpenSSL::SignatureAlgorithm::RSAPSS,
      ALG_ECDSA => OpenSSL::SignatureAlgorithm::ECDSA
    }.freeze

    TPM_HASH_ALG_TO_OPENSSL = {
      ALG_SHA1 => "SHA1",
      ALG_SHA256 => "SHA256"
    }.freeze

    def initialize(info, signature, nonce, object, signature_algorithm: ALG_RSASSA, hash_algorithm: ALG_SHA256)
      @info = info
      @signature = signature
      @nonce = nonce
      @object = object
      @signature_algorithm = signature_algorithm
      @hash_algorithm = hash_algorithm
    end

    def valid?(signing_key)
      valid_info? && valid_signature?(signing_key)
    end

    private

    def valid_info?
      attest.attested_type == TPM::ST_ATTEST_CERTIFY &&
        attest.extra_data.buffer == nonce &&
        attest.magic == TPM::GENERATED_VALUE &&
        attest.attested.name.valid_for?(object)
    end

    def valid_signature?(verify_key)
      openssl_signature_algorithm = openssl_signature_algorithm_class.new(openssl_hash_function[3..-1])
      openssl_signature_algorithm.verify_key = verify_key

      begin
        openssl_signature_algorithm.verify(signature, info)
      rescue OpenSSL::SignatureAlgorithm::Error
        false
      end
    end

    def attest
      @attest ||= TPM::SAttest.deserialize(info)
    end

    def openssl_hash_function
      TPM_HASH_ALG_TO_OPENSSL[hash_algorithm] || raise("Unsupported hash algorithm #{hash_algorithm}")
    end

    def openssl_signature_algorithm_class
      TPM_SIGNATURE_ALG_TO_OPENSSL[signature_algorithm] || raise("Unsupported signature algorithm #{algorithm}")
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
tpm-key_attestation-0.9.0 lib/tpm/certify_validator.rb
tpm-key_attestation-0.8.0 lib/tpm/certify_validator.rb
tpm-key_attestation-0.7.0 lib/tpm/certify_validator.rb