Class: Net::SSH::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/net/ssh/config.rb

Overview

The Net::SSH::Config class is used to parse OpenSSH configuration files, and translates that syntax into the configuration syntax that Net::SSH understands. This lets Net::SSH scripts read their configuration (to some extent) from OpenSSH configuration files (~/.ssh/config, /etc/ssh_config, and so forth).

Only a subset of OpenSSH configuration options are understood:

  • ChallengeResponseAuthentication => maps to the :auth_methods option challenge-response (then coleasced into keyboard-interactive)

  • KbdInteractiveAuthentication => maps to the :auth_methods keyboard-interactive

  • CertificateFile => maps to the :keycerts option

  • Ciphers => maps to the :encryption option

  • Compression => :compression

  • CompressionLevel => :compression_level

  • ConnectTimeout => maps to the :timeout option

  • ForwardAgent => :forward_agent

  • GlobalKnownHostsFile => :global_known_hosts_file

  • HostBasedAuthentication => maps to the :auth_methods option

  • HostKeyAlgorithms => maps to :host_key option

  • HostKeyAlias => :host_key_alias

  • HostName => :host_name

  • IdentityFile => maps to the :keys option

  • IdentityAgent => :identity_agent

  • IdentitiesOnly => :keys_only

  • CheckHostIP => :check_host_ip

  • Macs => maps to the :hmac option

  • PasswordAuthentication => maps to the :auth_methods option password

  • Port => :port

  • PreferredAuthentications => maps to the :auth_methods option

  • ProxyCommand => maps to the :proxy option

  • ProxyJump => maps to the :proxy option

  • PubKeyAuthentication => maps to the :auth_methods option

  • RekeyLimit => :rekey_limit

  • StrictHostKeyChecking => :verify_host_key

  • User => :user

  • UserKnownHostsFile => :user_known_hosts_file

  • NumberOfPasswordPrompts => :number_of_password_prompts

  • FingerprintHash => :fingerprint_hash

Note that you will never need to use this class directly–you can control whether the OpenSSH configuration files are read by passing the :config option to Net::SSH.start. (They are, by default.)

Constant Summary collapse

@@default_files =
%w[~/.ssh/config /etc/ssh_config /etc/ssh/ssh_config]
@@default_auth_methods =

The following defaults follow the openssh client ssh_config defaults. lwn.net/Articles/544640/ “hostbased” is off and “none” is not supported but we allow it since it’s used by some clients to query the server for allowed auth methods

%w[none publickey password keyboard-interactive]

Class Method Summary collapse

Class Method Details

.default_auth_methodsObject



60
61
62
# File 'lib/net/ssh/config.rb', line 60

def default_auth_methods
  @@default_auth_methods.clone
end

.default_filesObject

Returns an array of locations of OpenSSH configuration files to parse by default.



56
57
58
# File 'lib/net/ssh/config.rb', line 56

def default_files
  @@default_files.clone
end

.expandable_default_filesObject

Filters default_files down to the files that are expandable.



186
187
188
189
190
191
192
193
# File 'lib/net/ssh/config.rb', line 186

def expandable_default_files
  default_files.keep_if do |path|
    File.expand_path(path)
    true
  rescue ArgumentError
    false
  end
end

.for(host, files = expandable_default_files) ⇒ Object

Loads the configuration data for the given host from all of the given files (defaulting to the list of files returned by #default_files), translates the resulting hash into the options recognized by Net::SSH, and returns them.



68
69
70
71
72
# File 'lib/net/ssh/config.rb', line 68

def for(host, files = expandable_default_files)
  translate(files.inject({}) { |settings, file|
    load(file, host, settings)
  })
end

.load(path, host, settings = {}, base_dir = nil) ⇒ Object

Load the OpenSSH configuration settings in the given file for the given host. If settings is given, the options are merged into that hash, with existing values taking precedence over newly parsed ones. Returns a hash containing the OpenSSH options. (See #translate for how to convert the OpenSSH options into Net::SSH options.)



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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
# File 'lib/net/ssh/config.rb', line 80

def load(path, host, settings = {}, base_dir = nil)
  file = File.expand_path(path)
  base_dir ||= File.dirname(file)
  return settings unless File.readable?(file)

  globals = {}
  block_matched = false
  block_seen = false
  IO.foreach(file) do |line|
    next if line =~ /^\s*(?:#.*)?$/

    if line =~ /^\s*(\S+)\s*=(.*)$/
      key, value = $1, $2
    else
      key, value = line.strip.split(/\s+/, 2)
    end

    # silently ignore malformed entries
    next if value.nil?

    key.downcase!
    value = unquote(value)

    value = case value.strip
            when /^\d+$/ then value.to_i
            when /^no$/i then false
            when /^yes$/i then true
            else value
            end

    if key == 'host'
      # Support "Host host1 host2 hostN".
      # See http://github.com/net-ssh/net-ssh/issues#issue/6
      negative_hosts, positive_hosts = value.to_s.split(/\s+/).partition { |h| h.start_with?('!') }

      # Check for negative patterns first. If the host matches, that overrules any other positive match.
      # The host substring code is used to strip out the starting "!" so the regexp will be correct.
      negative_matched = negative_hosts.any? { |h| host =~ pattern2regex(h[1..-1]) }

      if negative_matched
        block_matched = false
      else
        block_matched = positive_hosts.any? { |h| host =~ pattern2regex(h) }
      end

      block_seen = true
      settings[key] = host
    elsif key == 'match'
      block_matched = eval_match_conditions(value, host, settings)
      block_seen = true
    elsif !block_seen
      case key
      when 'identityfile', 'certificatefile'
        (globals[key] ||= []) << value
      when 'include'
        included_file_paths(base_dir, value).each do |file_path|
          globals = load(file_path, host, globals, base_dir)
        end
      else
        globals[key] = value unless settings.key?(key)
      end
    elsif block_matched
      case key
      when 'identityfile', 'certificatefile'
        (settings[key] ||= []) << value
      when 'include'
        included_file_paths(base_dir, value).each do |file_path|
          settings = load(file_path, host, settings, base_dir)
        end
      else
        settings[key] = value unless settings.key?(key)
      end
    end

    # ProxyCommand and ProxyJump override each other so they need to be tracked togeather
    %w[proxyjump proxycommand].each do |proxy_key|
      if (proxy_value = settings.delete(proxy_key))
        settings['proxy'] ||= [proxy_key, proxy_value]
      end
    end
  end

  globals.merge(settings) do |key, oldval, newval|
    case key
    when 'identityfile', 'certificatefile'
      oldval + newval
    else
      newval
    end
  end
end

.translate(settings) ⇒ Object

Given a hash of OpenSSH configuration options, converts them into a hash of Net::SSH options. Unrecognized options are ignored. The settings hash must have Strings for keys, all downcased, and the returned hash will have Symbols for keys.



176
177
178
179
180
181
182
183
# File 'lib/net/ssh/config.rb', line 176

def translate(settings)
  auth_methods = default_auth_methods.clone
  (auth_methods << 'challenge-response').uniq!
  ret = settings.each_with_object({ auth_methods: auth_methods }) do |(key, value), hash|
    translate_config_key(hash, key.to_sym, value, settings)
  end
  merge_challenge_response_with_keyboard_interactive(ret)
end