Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added SQL escaping for :limit and :offset [#288 state:closed] (Aaron …

…Bedra, Steven Bristol, Jonathan Wiess)
  • Loading branch information...
commit ef0ea782b1f5cf7b08e74ea3002a16c708f66645 1 parent a6e7908
@dhh dhh authored
View
9 activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -106,11 +106,16 @@ def add_limit!(sql, options)
# SELECT * FROM suppliers LIMIT 10 OFFSET 50
def add_limit_offset!(sql, options)
if limit = options[:limit]
- sql << " LIMIT #{limit}"
+ sql << " LIMIT #{sanitize_limit(limit)}"
if offset = options[:offset]
- sql << " OFFSET #{offset}"
+ sql << " OFFSET #{offset.to_i}"
end
end
+ sql
+ end
+
+ def sanitize_limit(limit)
+ limit.to_s[/,/] ? limit.split(',').map{ |i| i.to_i }.join(',') : limit.to_i
end
# Appends a locking clause to an SQL statement.
View
20 activerecord/test/cases/adapter_test.rb
@@ -104,4 +104,24 @@ def test_reset_table_with_non_integer_pk
end
end
+ def test_add_limit_offset_should_sanitize_sql_injection_for_limit_without_comas
+ sql_inject = "1 select * from schema"
+ assert_equal " LIMIT 1", @connection.add_limit_offset!("", :limit=>sql_inject)
+ if current_adapter?(:MysqlAdapter)
+ assert_equal " LIMIT 7, 1", @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7)
+ else
+ assert_equal " LIMIT 1 OFFSET 7", @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7)
+ end
+ end
+
+ def test_add_limit_offset_should_sanitize_sql_injection_for_limit_with_comas
+ sql_inject = "1, 7 procedure help()"
+ if current_adapter?(:MysqlAdapter)
+ assert_equal " LIMIT 1,7", @connection.add_limit_offset!("", :limit=>sql_inject)
+ assert_equal " LIMIT 7, 1", @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7)
+ else
+ assert_equal " LIMIT 1,7", @connection.add_limit_offset!("", :limit=>sql_inject)
+ assert_equal " LIMIT 1,7 OFFSET 7", @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7)
+ end
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.