quote password when generating mysql command string (#2685)

* quote password when generating mysql command string
* added a test for mysql_session, added shellwords escaping to mysql_session resource
* changed the name of the escape method
* clarified test conditions

Signed-off-by: Tom Hodder <tom@limepepper.co.uk>
This commit is contained in:
Tom Hodder 2018-03-09 13:41:21 +00:00 committed by Jared Quick
parent 50772a67ef
commit eeeeda18d8
2 changed files with 47 additions and 15 deletions

View file

@ -1,6 +1,8 @@
# encoding: utf-8
# copyright: 2015, Vulcano Security GmbH
require 'shellwords'
module Inspec::Resources
class MysqlSession < Inspec.resource(1)
name 'mysql_session'
@ -25,21 +27,8 @@ module Inspec::Resources
end
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
command = "mysql -u#{@user} -p#{@pass}"
if !@socket.nil?
command += " -S #{@socket}"
else
command += " -h #{@host}"
end
command += " --port #{@port}" unless @port.nil?
command += " #{db} -s -e \"#{escaped_query}\""
cmd = inspec.command(command)
mysql_cmd = create_mysql_cmd(q, db)
cmd = inspec.command(mysql_cmd)
out = cmd.stdout + "\n" + cmd.stderr
if out =~ /Can't connect to .* MySQL server/ || out.downcase =~ /^error/
# skip this test if the server can't run the query
@ -56,6 +45,31 @@ module Inspec::Resources
private
def escape_string(query)
Shellwords.escape(query)
end
def create_mysql_cmd(q, db = '')
# TODO: simple escape, must be handled by a library
# that does this securely
escaped_query = q.gsub(/\\/, '\\\\').gsub(/"/, '\\"').gsub(/\$/, '\\$')
# construct the query
command = 'mysql'
command += " -u#{escape_string(@user)}" unless @user.nil?
command += " -p#{escape_string(@pass)}" unless @pass.nil?
if !@socket.nil?
command += " -S #{@socket}"
else
command += " -h #{@host}"
end
command += " --port #{@port}" unless @port.nil?
command += " #{db}" unless db.empty?
command += %{ -s -e "#{escaped_query}"}
command
end
def init_fallback
# support debian mysql administration login
debian = inspec.command('test -f /etc/mysql/debian.cnf && cat /etc/mysql/debian.cnf').stdout

View file

@ -0,0 +1,18 @@
# encoding: utf-8
# author: Christoph Hartmann
# author: Dominik Richter
require 'helper'
describe 'Inspec::Resources::MysqlSession' do
it 'verify mysql_session escaped login details with single quotes correctly' do
resource = load_resource('mysql_session',
'root',
%q{'%"'"&^*&()'*%})
_(resource.send(:create_mysql_cmd, 'SELECT 1 FROM DUAL;').must_equal(%q{mysql -uroot -p\'\%\"\'\"\&\^\*\&\(\)\'\*\% -h localhost -s -e "SELECT 1 FROM DUAL;"}))
end
it 'verify mysql_session omits optional username and password' do
resource = load_resource('mysql_session')
_(resource.send(:create_mysql_cmd, 'SELECT 1 FROM DUAL;').must_equal('mysql -h localhost -s -e "SELECT 1 FROM DUAL;"'))
end
end