Sha256: eac8966d55ccb3016a6a7224eca0771b81f0e4797107424c3b24f3fa5e11940b

Contents?: true

Size: 1.84 KB

Versions: 9

Compression:

Stored size: 1.84 KB

Contents

# encoding: utf-8
# copyright: 2015, Vulcano Security GmbH
# author: Dominik Richter
# author: Christoph Hartmann
# author: Aaron Lippold

require 'shellwords'

module Inspec::Resources
  class Lines
    attr_reader :output

    def initialize(raw, desc)
      @output = raw
      @desc = desc
    end

    def lines
      output.split("\n")
    end

    def to_s
      @desc
    end
  end

  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', 'host')
      query('sql_query', ['database_name'])` contains the query and (optional) database to execute

      # default values:
      # username: 'postgres'
      # host: 'localhost'
      # db: databse == db_user running the sql query

      describe sql.query('SELECT * FROM pg_shadow WHERE passwd IS NULL;') do
        its('output') { should eq '' }
      end
    "

    def initialize(user, pass, host = nil)
      @user = user || 'postgres'
      @pass = pass
      @host = host || 'localhost'
    end

    def query(query, db = [])
      psql_cmd = create_psql_cmd(query, db)
      cmd = inspec.command(psql_cmd)
      out = cmd.stdout + "\n" + cmd.stderr
      if cmd.exit_status != 0 || out =~ /could not connect to .*/ || out.downcase =~ /^error:.*/
        skip_resource "Can't read run query #{query.inspect} on postgres_session: #{out}"
      else
        Lines.new(cmd.stdout.strip, "PostgreSQL query: #{query}")
      end
    end

    private

    def escaped_query(query)
      Shellwords.escape(query)
    end

    def create_psql_cmd(query, db = [])
      dbs = db.map { |x| "-d #{x}" }.join(' ')
      "PGPASSWORD='#{@pass}' psql -U #{@user} #{dbs} -h #{@host} -A -t -c #{escaped_query(query)}"
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
inspec-1.37.6 lib/resources/postgres_session.rb
inspec-1.36.1 lib/resources/postgres_session.rb
inspec-1.35.1 lib/resources/postgres_session.rb
inspec-1.34.1 lib/resources/postgres_session.rb
inspec-1.33.12 lib/resources/postgres_session.rb
inspec-1.33.1 lib/resources/postgres_session.rb
inspec-1.32.1 lib/resources/postgres_session.rb
inspec-1.31.1 lib/resources/postgres_session.rb
inspec-1.31.0 lib/resources/postgres_session.rb