inspec/lib/resources/postgres_hba_conf.rb
eramoto c7e87ca3e3 Unify method in which file content is read across all resources (#2359)
* Create file-check functionality into utility file

There are the similar issues as PR #2302. Almost resources return false
positives when a file does not exist or is not read.

* Replace to file-check functionality
* Fix dh_params and x509_certificate resources

If a file is empty, OpenSSL::PKey::DH and OpenSSL::X509::Certificate have
raised an exception and have skipped the inspection. Thus x509_certificate
and dh_params resources are not allowed to read a empty file.

* to_s of shadow expects filters is not nil
* Remove workaround of sshd_config

Removes the workaround of sshd_config since Travis CI fails due to a bug
of dev-sec/ssh-baseline and the PR #100 will fix it.

* Use init block variable in methods

Signed-off-by: ERAMOTO Masaya <eramoto.masaya@jp.fujitsu.com>
2018-03-22 08:25:45 -04:00

90 lines
2.4 KiB
Ruby

# encoding: utf-8
require 'resources/postgres'
require 'utils/file_reader'
module Inspec::Resources
class PostgresHbaConf < Inspec.resource(1)
name 'postgres_hba_conf'
supports platform: 'unix'
desc 'Use the `postgres_hba_conf` InSpec audit resource to test the client
authentication data defined in the pg_hba.conf file.'
example "
describe postgres_hba_conf.where { type == 'local' } do
its('auth_method') { should eq ['peer'] }
end
"
include FileReader
attr_reader :conf_file, :params
# @todo add checks to ensure that we have data in our file
def initialize(hba_conf_path = nil)
@conf_file = hba_conf_path || File.expand_path('pg_hba.conf', inspec.postgres.conf_dir)
@content = ''
@params = {}
read_content
end
filter = FilterTable.create
filter.add_accessor(:where)
.add_accessor(:entries)
.add(:type, field: 'type')
.add(:database, field: 'database')
.add(:user, field: 'user')
.add(:address, field: 'address')
.add(:auth_method, field: 'auth_method')
.add(:auth_params, field: 'auth_params')
filter.connect(self, :params)
def to_s
"Postgres Hba Config #{@conf_file}"
end
private
def clean_conf_file(conf_file = @conf_file)
data = read_file_content(conf_file).to_s.lines
content = []
data.each do |line|
line.chomp!
content << line unless line.match(/^\s*#/) || line.empty?
end
content
end
def read_content(config_file = @conf_file)
# @todo use SimpleConfig here if we can
# ^\s*(\S+)\s+(\S+)\s+(\S+)\s(?:(\d*.\d*.\d*.\d*\/\d*)|(::\/\d+))\s+(\S+)\s*(.*)?\s*$
@content = clean_conf_file(config_file)
@params = parse_conf(@content)
@params.each do |line|
if line['type'] == 'local'
line['auth_method'] = line['address']
line['address'] = ''
end
end
end
def parse_conf(content)
content.map do |line|
parse_line(line)
end.compact
end
def parse_line(line)
x = line.split(/\s+/)
{
'type' => x[0],
'database' => x[1],
'user' => x[2],
'address' => x[3],
'auth_method' => x[4],
'auth_params' => ('' if x.length == 4) || x[5..-1].join(' '),
}
end
end
end