Class: RVC::KnownHosts

Inherits:
Object
  • Object
show all
Defined in:
lib/rvc/known_hosts.rb

Instance Method Summary collapse

Constructor Details

#initializeKnownHosts

Returns a new instance of KnownHosts.



8
9
10
# File 'lib/rvc/known_hosts.rb', line 8

def initialize
  @ignore_permissions = RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
end

Instance Method Details

#add(protocol, hostname, public_key) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/rvc/known_hosts.rb', line 42

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

#filenameObject



12
13
14
# File 'lib/rvc/known_hosts.rb', line 12

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

#hash_host(protocol, hostname) ⇒ Object



16
17
18
# File 'lib/rvc/known_hosts.rb', line 16

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

#hash_public_key(public_key) ⇒ Object



20
21
22
# File 'lib/rvc/known_hosts.rb', line 20

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

#verify(protocol, hostname, public_key) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rvc/known_hosts.rb', line 24

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 #{filename}, expected 0600" unless @ignore_permissions or 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