2017-08-31 13:51:39 +00:00
|
|
|
# encoding: utf-8
|
|
|
|
|
|
|
|
require 'utils/parser'
|
2018-03-22 12:25:45 +00:00
|
|
|
require 'utils/file_reader'
|
2017-08-31 13:51:39 +00:00
|
|
|
|
|
|
|
class EtcHosts < Inspec.resource(1)
|
|
|
|
name 'etc_hosts'
|
2018-03-08 21:01:50 +00:00
|
|
|
supports platform: 'linux'
|
|
|
|
supports platform: 'bsd'
|
|
|
|
supports platform: 'windows'
|
2017-08-31 13:51:39 +00:00
|
|
|
desc 'Use the etc_hosts InSpec audit resource to find an
|
|
|
|
ip_address and its associated hosts'
|
|
|
|
example "
|
|
|
|
describe etc_hosts.where { ip_address == '127.0.0.1' } do
|
|
|
|
its('ip_address') { should cmp '127.0.0.1' }
|
|
|
|
its('primary_name') { should cmp 'localhost' }
|
|
|
|
its('all_host_names') { should eq [['localhost', 'localhost.localdomain', 'localhost4', 'localhost4.localdomain4']] }
|
|
|
|
end
|
|
|
|
"
|
|
|
|
|
|
|
|
attr_reader :params
|
|
|
|
|
|
|
|
include CommentParser
|
2018-03-22 12:25:45 +00:00
|
|
|
include FileReader
|
2017-08-31 13:51:39 +00:00
|
|
|
|
2018-03-22 16:58:22 +00:00
|
|
|
DEFAULT_UNIX_PATH = '/etc/hosts'.freeze
|
|
|
|
DEFAULT_WINDOWS_PATH = 'C:\windows\system32\drivers\etc\hosts'.freeze
|
|
|
|
|
2017-08-31 13:51:39 +00:00
|
|
|
def initialize(hosts_path = nil)
|
2018-03-22 16:58:22 +00:00
|
|
|
content = read_file_content(hosts_path || default_hosts_file_path)
|
2017-08-31 13:51:39 +00:00
|
|
|
|
2018-03-22 16:58:22 +00:00
|
|
|
@params = parse_conf(content.lines)
|
|
|
|
end
|
2017-08-31 13:51:39 +00:00
|
|
|
|
2018-03-22 16:58:22 +00:00
|
|
|
FilterTable.create
|
|
|
|
.add_accessor(:where)
|
|
|
|
.add_accessor(:entries)
|
|
|
|
.add(:ip_address, field: 'ip_address')
|
|
|
|
.add(:primary_name, field: 'primary_name')
|
|
|
|
.add(:all_host_names, field: 'all_host_names')
|
|
|
|
.connect(self, :params)
|
2017-08-31 13:51:39 +00:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def default_hosts_file_path
|
2018-03-22 16:58:22 +00:00
|
|
|
inspec.os.windows? ? DEFAULT_WINDOWS_PATH : DEFAULT_UNIX_PATH
|
2017-08-31 13:51:39 +00:00
|
|
|
end
|
|
|
|
|
2018-03-22 16:58:22 +00:00
|
|
|
def parse_conf(lines)
|
|
|
|
lines.reject(&:empty?).reject(&comment?).map(&parse_data).map(&format_data)
|
2017-08-31 13:51:39 +00:00
|
|
|
end
|
|
|
|
|
2018-03-22 16:58:22 +00:00
|
|
|
def comment?
|
|
|
|
parse_options = { comment_char: '#', standalone_comments: false }
|
|
|
|
|
|
|
|
->(data) { parse_comment_line(data, parse_options).first.empty? }
|
2017-08-31 13:51:39 +00:00
|
|
|
end
|
|
|
|
|
2018-03-22 16:58:22 +00:00
|
|
|
def parse_data
|
|
|
|
->(data) { [data.split[0], data.split[1], data.split[1..-1]] }
|
2017-08-31 13:51:39 +00:00
|
|
|
end
|
|
|
|
|
2018-03-22 16:58:22 +00:00
|
|
|
def format_data
|
|
|
|
->(data) { %w{ip_address primary_name all_host_names}.zip(data).to_h }
|
2017-08-31 13:51:39 +00:00
|
|
|
end
|
|
|
|
end
|