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 MysqlSession < Inspec.resource(1)
|
|
|
|
name 'mysql_session'
|
|
|
|
desc 'Use the mysql_session InSpec audit resource to test SQL commands run against a MySQL database.'
|
|
|
|
example "
|
|
|
|
sql = mysql_session('my_user','password')
|
|
|
|
describe sql.query('show databases like \'test\';') do
|
|
|
|
its(:stdout) { should_not match(/test/) }
|
|
|
|
end
|
|
|
|
"
|
|
|
|
|
|
|
|
def initialize(user = nil, pass = nil)
|
|
|
|
@user = user
|
|
|
|
@pass = pass
|
|
|
|
init_fallback if user.nil? or pass.nil?
|
|
|
|
skip_resource("Can't run MySQL SQL checks without authentication") if @user.nil? or @pass.nil?
|
2015-11-27 13:02:38 +00:00
|
|
|
end
|
2015-08-28 19:41:48 +00:00
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
def query(q, db = '')
|
|
|
|
# TODO: simple escape, must be handled by a library
|
|
|
|
# that does this securely
|
|
|
|
escaped_query = q.gsub(/\\/, '\\\\').gsub(/"/, '\\"').gsub(/\$/, '\\$')
|
|
|
|
|
|
|
|
# run the query
|
|
|
|
cmd = inspec.command("mysql -u#{@user} -p#{@pass} #{db} -s -e \"#{escaped_query}\"")
|
|
|
|
out = cmd.stdout + "\n" + cmd.stderr
|
|
|
|
if out =~ /Can't connect to .* MySQL server/ or
|
|
|
|
out.downcase =~ /^error/
|
|
|
|
# skip this test if the server can't run the query
|
|
|
|
skip_resource("Can't connect to MySQL instance for SQL checks.")
|
|
|
|
end
|
|
|
|
|
|
|
|
# return the raw command output
|
|
|
|
cmd
|
2015-04-09 20:01:23 +00:00
|
|
|
end
|
2015-09-26 09:56:49 +00:00
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
def to_s
|
|
|
|
'MySQL Session'
|
|
|
|
end
|
2015-10-12 11:01:58 +00:00
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
private
|
2015-06-22 13:24:35 +00:00
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
def init_fallback
|
|
|
|
# support debian mysql administration login
|
|
|
|
debian = inspec.command('test -f /etc/mysql/debian.cnf && cat /etc/mysql/debian.cnf').stdout
|
|
|
|
return if debian.empty?
|
2015-09-09 16:37:16 +00:00
|
|
|
|
2016-03-08 18:06:55 +00:00
|
|
|
user = debian.match(/^\s*user\s*=\s*([^ ]*)\s*$/)
|
|
|
|
pass = debian.match(/^\s*password\s*=\s*([^ ]*)\s*$/)
|
|
|
|
return if user.nil? or pass.nil?
|
|
|
|
@user = user[1]
|
|
|
|
@pass = pass[1]
|
|
|
|
end
|
2015-06-22 13:24:35 +00:00
|
|
|
end
|
2015-04-09 20:01:23 +00:00
|
|
|
end
|