Skip to content

Commit

Permalink
prevent sql injection attacks by escaping quotes in column names
Browse files Browse the repository at this point in the history
  • Loading branch information
tenderlove committed Aug 16, 2011
1 parent e0c03f8 commit fb4747b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ def quote(value, column = nil)
end

def quote_column_name(name) #:nodoc:
@quoted_column_names[name] ||= "`#{name}`"
@quoted_column_names[name] ||= "`#{name.to_s.gsub('`', '``')}`"
end

def quote_table_name(name) #:nodoc:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def quote_string(s) #:nodoc:
end

def quote_column_name(name) #:nodoc:
%Q("#{name}")
%Q("#{name.to_s.gsub('"', '""')}")
end

# Quote date/time values for use in SQL input. Includes microseconds
Expand Down
17 changes: 17 additions & 0 deletions activerecord/test/cases/base_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,23 @@ class Boolean < ActiveRecord::Base; end
class BasicsTest < ActiveRecord::TestCase
fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts

def test_column_names_are_escaped
conn = ActiveRecord::Base.connection
classname = conn.class.name[/[^:]*$/]
badchar = {
'SQLite3Adapter' => '"',
'MysqlAdapter' => '`',
'Mysql2Adapter' => '`',
'PostgreSQLAdapter' => '"',
'OracleAdapter' => '"',
}.fetch(classname) {
raise "need a bad char for #{classname}"
}

quoted = conn.quote_column_name "foo#{badchar}bar"
assert_equal("#{badchar}foo#{badchar * 2}bar#{badchar}", quoted)
end

unless current_adapter?(:PostgreSQLAdapter,:OracleAdapter,:SQLServerAdapter)
def test_limit_with_comma
assert_nothing_raised do
Expand Down

0 comments on commit fb4747b

Please sign in to comment.