Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Fix SQL injection via nested hashes in conditions

  • Loading branch information...
commit a6eb61b7e4138c999099a7e6ed7b3d2f0a227004 1 parent fe11782
Justin Collins authored rtomayko committed
View
10 activerecord/lib/active_record/base.rb
@@ -2333,17 +2333,17 @@ def expand_hash_conditions_for_aggregates(attrs)
# And for value objects on a composed_of relationship:
# { :address => Address.new("123 abc st.", "chicago") }
# # => "address_street='123 abc st.' and address_city='chicago'"
- def sanitize_sql_hash_for_conditions(attrs, default_table_name = quoted_table_name)
+ def sanitize_sql_hash_for_conditions(attrs, default_table_name = quoted_table_name, top_level = true)
attrs = expand_hash_conditions_for_aggregates(attrs)
conditions = attrs.map do |attr, value|
table_name = default_table_name
- unless value.is_a?(Hash)
+ if not value.is_a?(Hash)
attr = attr.to_s
# Extract table name from qualified attribute names.
- if attr.include?('.')
+ if attr.include?('.') and top_level
attr_table_name, attr = attr.split('.', 2)
attr_table_name = connection.quote_table_name(attr_table_name)
else
@@ -2351,8 +2351,10 @@ def sanitize_sql_hash_for_conditions(attrs, default_table_name = quoted_table_na
end
attribute_condition("#{attr_table_name}.#{connection.quote_column_name(attr)}", value)
+ elsif top_level
+ sanitize_sql_hash_for_conditions(value, connection.quote_table_name(attr.to_s), false)
else
- sanitize_sql_hash_for_conditions(value, connection.quote_table_name(attr.to_s))
+ raise ActiveRecord::StatementInvalid
end
end.join(' AND ')
View
16 activerecord/test/cases/finder_test.rb
@@ -363,6 +363,22 @@ def test_hash_condition_find_malformed
}
end
+ def test_hash_condition_find_with_improper_nested_hashes
+ assert_raise(ActiveRecord::StatementInvalid) {
+ Company.find(:first, :conditions => { :name => { :companies => { :id => 1 }}})
+ }
+ end
+
+ def test_hash_condition_find_with_dot_in_nested_column_name
+ assert_raise(ActiveRecord::StatementInvalid) {
+ Company.find(:first, :conditions => { :name => { "companies.id" => 1 }})
+ }
+ end
+
+ def test_hash_condition_find_with_dot_in_column_name_okay
+ assert Company.find(:first, :conditions => { "companies.id" => 1 })
+ end
+
def test_hash_condition_find_with_escaped_characters
Company.create("name" => "Ain't noth'n like' \#stuff")
assert Company.find(:first, :conditions => { :name => "Ain't noth'n like' \#stuff" })

0 comments on commit a6eb61b

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