问题
I need the following code to be rewritten by avoiding SQL Injection in Rails 3.
some_table_name.joins("inner join #{table_name} on linked_config_items.linked_type = '#{class_name}' and linked_config_items.linked_id = #{table_name}.id").
where("#{table_name}.saved is true and #{table_name}.deleted_at is null")
Here, table_name is dynamic and it will vary.
回答1:
SQL identifiers like table names and column names cannot be replaced with bound parameters, which is the more common method to ensure protection against SQL injection vulnerabilities.
The best solution for making your table_name
safe is to whitelist it.
That is, before interpolating it into your query, use code to verify that it's matches a table name that exists in your database. Many apps keep a cache of table names, or map their metadata into code somehow.
Also you should delimit dynamic identifiers in back-ticks, so in case the table is legitimate but happens to be a reserved word, it'll still work.
some_table_name.joins("inner join `#{table_name}` as t1 ...
It's also handy to use table aliases like I show above (as t1
), so you don't have to repeat the Ruby variable multiple times in your query.
回答2:
Finally, I had to rewrite my above query like this
some_table_name.joins(self.class.superclass.send(:sanitize_sql_array,"inner join #{table_name} as t1 on linked_config_items.linked_type = '#{class_name}' and linked_config_items.linked_id = t1.id")).
where("t1.saved is true and t1.deleted_at is null")
Here, 'self.class.superclass' is 'ActiveRecord::Base'
来源:https://stackoverflow.com/questions/50154062/need-to-avoid-sql-injection-in-rails3