Skip to content
Browse files

prevent sql injection attacks by escaping quotes in column names

  • Loading branch information...
1 parent e0c03f8 commit fb4747bcf1659a94d76ac221d66ce44148ca7b49 @tenderlove tenderlove committed Aug 16, 2011
View
2 activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -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:
View
2 activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
@@ -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
View
17 activerecord/test/cases/base_test.rb
@@ -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

0 comments on commit fb4747b

Please sign in to comment.
Something went wrong with that request. Please try again.