Class: SSH::Key::Verifier

Inherits:
Object
  • Object
show all
Includes:
Helper
Defined in:
lib/ssh/key/verifier.rb

Constant Summary collapse

AUTHORIZED_KEYS_REGEX =

We only support protocol 2 public keys. protocol2 is: options keytype b64key comment

/^((?:[A-Za-z0-9-]+(?:="[^"]+")?,?)+ *)?(ssh-(?:dss|rsa)) *([^ ]*) *(.*)/

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helper

#add_key_file, #add_key_from_host, #add_public_key_data

Constructor Details

#initialize(account = nil) ⇒ Verifier

A new SSH Key Verifier.

  • account - optional string username. Should be a valid user on the system.

If account is nil or omitted, then it defaults to the user running this process (current user)



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/ssh/key/verifier.rb', line 30

def initialize(=nil)
  if  == nil
     = Etc.getlogin
  end

  @account = 
  @agent = Net::SSH::Authentication::Agent.new
  @use_agent = true
  @use_authorized_keys = true
  @sshd_config_file = "/etc/ssh/sshd_config"
  @authorized_keys_file = nil
  @logger = Logger.new(STDERR)
  @logger.level = $DEBUG ? Logger::DEBUG : Logger::WARN
  @keys = []
end

Instance Attribute Details

#accountObject

Returns the value of attribute account.



12
13
14
# File 'lib/ssh/key/verifier.rb', line 12

def 
  @account
end

#authorized_keys_fileObject

Returns the value of attribute authorized_keys_file.



14
15
16
# File 'lib/ssh/key/verifier.rb', line 14

def authorized_keys_file
  @authorized_keys_file
end

#loggerObject

Returns the value of attribute logger.



15
16
17
# File 'lib/ssh/key/verifier.rb', line 15

def logger
  @logger
end

#sshd_config_fileObject

Returns the value of attribute sshd_config_file.



13
14
15
# File 'lib/ssh/key/verifier.rb', line 13

def sshd_config_file
  @sshd_config_file
end

#use_agentObject

Returns the value of attribute use_agent.



16
17
18
# File 'lib/ssh/key/verifier.rb', line 16

def use_agent
  @use_agent
end

#use_authorized_keysObject

Returns the value of attribute use_authorized_keys.



17
18
19
# File 'lib/ssh/key/verifier.rb', line 17

def use_authorized_keys
  @use_authorized_keys
end

Instance Method Details

#add_private_key_file(path, passphrase = nil) ⇒ Object

Add a private key to this Verifier from a file (like “.ssh/id_rsa”)

  • path - the string path to the key

  • passphrase - the passphrase for this key, omit if no passphrase.



234
235
236
# File 'lib/ssh/key/verifier.rb', line 234

def add_private_key_file(path, passphrase=nil)
  @keys << Net::SSH::KeyFactory.load_private_key(path, passphrase)
end

#add_public_key_file(path) ⇒ Object

Add a public key to this Verifier from a file (like “.ssh/id_rsa.pub”)

This is for individual key files. If you want to specify an alternate location for your authorized_keys file, set:

Verifier#authorized_keys_file = "/path/to/authorized_keys"
  • path - the string path to the public key



245
246
247
# File 'lib/ssh/key/verifier.rb', line 245

def add_public_key_file(path)
  @keys << Net::SSH::KeyFactory.load_public_key(path)
end

#authorized_keysObject

find_authorized_keys_file



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/ssh/key/verifier.rb', line 182

def authorized_keys
  if @authorized_keys_file
    authorized_keys_file = @authorized_keys_file
  else
    authorized_keys_file = find_authorized_keys_file
  end

  if authorized_keys_file == nil
    @logger.info("No authorized keys file found.")
    return []
  end

  if !File.exists?(authorized_keys_file)
    @logger.info("User '#{@account}' has no authorized keys file '#{authorized_keys_file}'")
    return []
  end

  keys = []
  @logger.info("AuthorizedKeysFile ==> #{authorized_keys_file}")
  File.new(authorized_keys_file).each do |line|
    next if line =~ /^\s*$/    # Skip blanks
    next if line =~ /^\s*\#/  # Skip comments
    @logger.info line

    comment = nil

    # TODO(sissel): support more known_hosts formats
    if line =~ /^\|1\|/ # hashed known_hosts format
      comment, line = line.split(" ",2)
    end

    identity = Net::SSH::KeyFactory.load_data_public_key(line)

    # Add the '.comment' attribute to our key
    identity.extend(Net::SSH::Authentication::Agent::Comment)

    match = AUTHORIZED_KEYS_REGEX.match(line)
    if match
      comment = match[-1] 
    else
      puts "No comment or could not parse #{line}"
    end
    identity.comment = comment if comment

    keys << identity
  end
  return keys
end

#ensure_connectedObject

def initialize



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/ssh/key/verifier.rb', line 46

def ensure_connected
  begin
    @agent.connect! if !@agent.socket
  rescue Net::SSH::Authentication::AgentNotAvailable => e
    @use_agent = false
    @logger.info "SSH Agent not available"
  rescue => e
    @use_agent = false
    @logger.warn "Unexpected error ocurred. Disabling agent usage."
  end
end

#find_authorized_keys_fileObject

def verifying_identities



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/ssh/key/verifier.rb', line 132

def find_authorized_keys_file
  # Look up the @account's home directory.
  begin
     = Etc.getpwnam(@account)
  rescue ArgumentError => e
    @logger.warn("User '#{@account}' does not exist.")
  end

  # TODO(sissel): It's not clear how we should handle empty homedirs, if
  # that happens?

  # Default authorized_keys location
  authorized_keys_file = ".ssh/authorized_keys"

  # Try to find the AuthorizedKeysFile definition in the config.
  if File.exists?(@sshd_config_file)
    begin
      authorized_keys_file = File.new(@sshd_config_file).grep(/^\s*AuthorizedKeysFile/)[-1].split(" ")[-1]
    rescue 
      @logger.info("No AuthorizedKeysFile setting found in #{@sshd_config_file}, assuming '#{authorized_keys_file}'")
    end
  else
    @logger.warn("No sshd_config file found '#{@sshd_config_file}'. Won't check for authorized keys files. Assuming '#{authorized_keys_file}'")
  end

  # Support things sshd_config does.
  authorized_keys_file.gsub!(/%%/, "%")
  authorized_keys_file.gsub!(/%u/, @account)
  if authorized_keys_file =~ /%h/
    if  == nil
      @logger.warn("No homedirectory for #{@account}, skipping authorized_keys")
      return nil
    end

    authorized_keys_file.gsub!(/%h/, .dir)
  end

  # If relative path, use the homedir.
  if authorized_keys_file[0,1] != "/"
    if  == nil
      @logger.warn("No homedirectory for #{@account} and authorized_keys path is relative, skipping authorized_keys")
      return nil
    end

    authorized_keys_file = "#{.dir}/#{authorized_keys_file}"
  end

  return authorized_keys_file
end

#verify(signatures, original) ⇒ Object

Verify an original with the signatures.

  • signatures - a hash of { identity => signature } values or, it can be an array of signature strings or, it can simply be a signature string.

  • original - the original string value to verify



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/ssh/key/verifier.rb', line 78

def verify(signatures, original)
  @logger.info "Getting identities"
  identities = verifying_identities
  @logger.info "Have #{identities.length} identities"
  results = {}

  if signatures.is_a? Hash
    @logger.debug("verify 'signatures' is a Hash")
    inputs = signatures.values
  elsif signatures.is_a? Array
    @logger.debug("verify 'signatures' is an Array")
    inputs = signatures
  elsif signatures.is_a? String
    @logger.debug("verify 'signatures' is an String")
    inputs = [signatures]
  end

  if inputs[0].is_a? SSH::Key::Signature
    @logger.debug("verify 'signatures' is an array of Signatures")
    inputs = inputs.collect { |i| i.signature }
  end

  inputs.each do |signature|
    identities.each do |identity|
      key = [signature, identity]
      results[key] = identity.ssh_do_verify(signature, original)
      @logger.info "Trying key #{identity.to_s.split("\n")[1]}... #{results[key]}"
    end
  end
  return results
end

#verify?(signature, original) ⇒ Boolean

Can we validate ‘original’ against the signature(s)?

  • signature - a single SSH::Key::Signature or hash of { identity => signature } values.

  • original - the original string to verify against

See also: SSH::Key::Signer#sign

Returns:

  • (Boolean)


65
66
67
68
69
70
71
# File 'lib/ssh/key/verifier.rb', line 65

def verify?(signature, original)
  results = verify(signature, original)
  results.each do |identity, verified|
    return true if verified
  end
  return false
end

#verifying_identitiesObject

def verify



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/ssh/key/verifier.rb', line 110

def verifying_identities
  identities = []
  ensure_connected 
  if @use_agent
    begin
      @agent.identities.each { |id| identities << id }
    rescue ArgumentError => e
      @logger.warn("Error from agent query: #{e}")
      @use_agent = false
    end
  end

  if @use_authorized_keys
    # Verifying should include your authorized_keys file, too, if we can 
    # find it.
    authorized_keys.each { |id| identities << id }
  end

  @keys.each { |id| identities << id }
  return identities
end