2015-04-09 20:01:23 +00:00
|
|
|
# encoding: utf-8
|
2015-07-15 13:15:18 +00:00
|
|
|
# copyright: 2015, Vulcano Security GmbH
|
2015-10-06 16:55:44 +00:00
|
|
|
# author: Dominik Richter
|
|
|
|
# author: Christoph Hartmann
|
2015-04-09 20:01:23 +00:00
|
|
|
# license: All rights reserved
|
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
module Inspec::Resources
|
|
|
|
class Lines
|
|
|
|
attr_reader :output
|
2015-12-08 11:32:23 +00:00
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
def initialize(raw, desc)
|
|
|
|
@output = raw
|
|
|
|
@desc = desc
|
|
|
|
end
|
2015-04-09 20:01:23 +00:00
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
def lines
|
|
|
|
output.split("\n")
|
|
|
|
end
|
2015-04-09 20:01:23 +00:00
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
def to_s
|
|
|
|
@desc
|
|
|
|
end
|
2015-04-09 20:01:23 +00:00
|
|
|
end
|
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
class PostgresSession < Inspec.resource(1)
|
|
|
|
name 'postgres_session'
|
|
|
|
desc 'Use the postgres_session InSpec audit resource to test SQL commands run against a PostgreSQL database.'
|
|
|
|
example "
|
|
|
|
sql = postgres_session('username', 'password')
|
2015-11-27 13:02:38 +00:00
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
describe sql.query('SELECT * FROM pg_shadow WHERE passwd IS NULL;') do
|
|
|
|
its('output') { should eq('') }
|
|
|
|
end
|
|
|
|
"
|
2015-10-26 15:47:45 +00:00
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
def initialize(user, pass)
|
|
|
|
@user = user || 'postgres'
|
|
|
|
@pass = pass
|
|
|
|
end
|
2015-04-09 20:01:23 +00:00
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
def query(query, db = [])
|
|
|
|
dbs = db.map { |x| "-d #{x}" }.join(' ')
|
|
|
|
# TODO: simple escape, must be handled by a library
|
|
|
|
# that does this securely
|
|
|
|
escaped_query = query.gsub(/\\/, '\\\\').gsub(/"/, '\\"').gsub(/\$/, '\\$')
|
|
|
|
# run the query
|
|
|
|
cmd = inspec.command("PGPASSWORD='#{@pass}' psql -U #{@user} #{dbs} -h localhost -c \"#{escaped_query}\"")
|
|
|
|
out = cmd.stdout + "\n" + cmd.stderr
|
|
|
|
if cmd.exit_status != 0 or
|
|
|
|
out =~ /could not connect to .*/ or
|
|
|
|
out.downcase =~ /^error/
|
|
|
|
# skip this test if the server can't run the query
|
|
|
|
skip_resource "Can't read run query #{query.inspect} on postgres_session: #{out}"
|
|
|
|
else
|
|
|
|
# remove the whole header (i.e. up to the first ^-----+------+------$)
|
|
|
|
# remove the tail
|
|
|
|
lines = cmd.stdout
|
|
|
|
.sub(/(.*\n)+([-]+[+])*[-]+\n/, '')
|
|
|
|
.sub(/\n[^\n]*\n\n$/, '')
|
|
|
|
Lines.new(lines.strip, "PostgreSQL query: #{query}")
|
|
|
|
end
|
2015-04-09 20:01:23 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|