Sha256: f7ea080d1b6243a197fc87c608455a6c34dad4a9d930b81a2c93e266caaf1276

Contents?: true

Size: 1.21 KB

Versions: 3

Compression:

Stored size: 1.21 KB

Contents

require 'digest/sha2'
require 'fileutils'

module RVC

class KnownHosts
  def filename
    File.join(ENV['HOME'], ".rvc", "known_hosts");
  end

  def hash_host protocol, hostname
    Digest::SHA2.hexdigest([protocol, hostname] * "\0")
  end

  def hash_public_key public_key
    Digest::SHA2.hexdigest(public_key)
  end

  def verify protocol, hostname, public_key
    expected_hashed_host = hash_host protocol, hostname
    expected_hashed_public_key = hash_public_key public_key
    if File.exists? filename
      fail "bad permissions on known_hosts, expected 0600" unless File.stat(filename).mode & 0666 == 0600
      File.readlines(filename).each_with_index do |l,i|
        hashed_host, hashed_public_key = l.split
        next unless hashed_host == expected_hashed_host
        if hashed_public_key == expected_hashed_public_key
          return :ok
        else
          return :mismatch, i
        end
      end
    end
    return :not_found, expected_hashed_public_key
  end

  def add protocol, hostname, public_key
    FileUtils.mkdir_p File.dirname(filename)
    File.open(filename, 'a') do |io|
      io.chmod 0600
      io.write "#{hash_host protocol, hostname} #{hash_public_key public_key}\n"
    end
  end
end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rvc-1.3.2 lib/rvc/known_hosts.rb
rvc-1.3.1 lib/rvc/known_hosts.rb
rvc-1.3.0 lib/rvc/known_hosts.rb