Is ActiveRecord's “order” method vulnerable to SQL injection?

后端 未结 5 2205
我寻月下人不归
我寻月下人不归 2020-12-17 10:32

I know it\'s not safe to use interpolated strings when calling .where.

e.g. this:

Client.where(\"orders_count = #{params[:orders]}\")

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 11:19

    @Mike explanation is correct. @dmcnally workaround would work. I'm following in a slightly different path mentioned in [Railscast][1] http://railscasts.com/episodes/228-sortable-table-columns

    In a nutshell, if you can construct a private method in the controller, in order to sanitize the user input:

    1. Order by name of one your table columns:

          private 
      
          def sort_column
             Client.column_names.include?(params[:sort]) ? params[:sort] : "first_name"
          end
      
    2. Order by other criteria, then use the whitelist construct such as below:

      def sort_direction
          %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
      end
      

    And your controller method should then look like this:

        Client.all.order(sort_column + " " + sort_direction)
    

    Just anther way to Rome. Hope this help.

提交回复
热议问题