2016-07-17 18:18:25 +00:00
|
|
|
# encoding: utf-8
|
|
|
|
# author: Christoph Hartmann
|
|
|
|
# author: Dominik Richter
|
|
|
|
|
|
|
|
module Inspec::Resources
|
|
|
|
class MssqlSession < Inspec.resource(1)
|
|
|
|
name 'mssql_session'
|
|
|
|
desc 'Use the mssql_session InSpec audit resource to test SQL commands run against a MS Sql Server database.'
|
|
|
|
example "
|
2017-05-02 14:35:54 +00:00
|
|
|
# Using SQL authentication
|
|
|
|
sql = mssql_session(user: 'myuser', pass: 'mypassword')
|
2016-07-17 18:18:25 +00:00
|
|
|
describe sql.query('select * from sys.databases where name like \'*test*\') do
|
2017-05-02 14:35:54 +00:00
|
|
|
its('stdout') { should_not match(/test/) }
|
|
|
|
end
|
|
|
|
|
|
|
|
# Passing no credentials to mssql_session forces it to use Windows authentication
|
|
|
|
sql_windows_auth = mssql_session
|
|
|
|
describe sql_window_auth.query('select * from sys.databases where name like \'*test*\') do
|
|
|
|
its('stdout') { should_not match(/test/) }
|
2016-07-17 18:18:25 +00:00
|
|
|
end
|
|
|
|
"
|
|
|
|
|
2017-05-02 14:35:54 +00:00
|
|
|
attr_reader :user, :pass, :host
|
|
|
|
|
|
|
|
def initialize(opts = {})
|
|
|
|
@user = opts[:user]
|
|
|
|
@pass = opts[:pass]
|
|
|
|
@host = opts[:host] || 'localhost'
|
|
|
|
@instance = opts[:instance]
|
2016-07-17 18:18:25 +00:00
|
|
|
end
|
|
|
|
|
2016-07-17 18:22:04 +00:00
|
|
|
def query(q)
|
2016-07-17 18:18:25 +00:00
|
|
|
escaped_query = q.gsub(/\\/, '\\\\').gsub(/"/, '\\"').gsub(/\$/, '\\$').gsub(/\@/, '`@')
|
2017-05-02 14:35:54 +00:00
|
|
|
cmd_string = "sqlcmd -Q \"#{escaped_query}\""
|
|
|
|
cmd_string += " -U #{@user} -P #{@pass}" unless @user.nil? or @pass.nil?
|
|
|
|
if @instance.nil?
|
|
|
|
cmd_string += " -S #{@host}"
|
|
|
|
else
|
|
|
|
cmd_string += " -S #{@host}\\#{@instance}"
|
|
|
|
end
|
|
|
|
puts cmd_string
|
|
|
|
cmd = inspec.command(cmd_string)
|
|
|
|
out = cmd.stdout + "\n" + cmd.stderr
|
|
|
|
if out =~ /Sqlcmd: Error/
|
|
|
|
skip_resource("Can't connect to the MS SQL Server.")
|
|
|
|
end
|
2016-07-17 18:18:25 +00:00
|
|
|
cmd
|
|
|
|
end
|
|
|
|
|
|
|
|
def to_s
|
2017-05-02 14:35:54 +00:00
|
|
|
'MSSQL session'
|
2016-07-17 18:18:25 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|