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

后端 未结 5 2201
我寻月下人不归
我寻月下人不归 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条回答
  •  死守一世寂寞
    2020-12-17 11:01

    Short answer is you need to sanitize your inputs.

    If the strings you are planning to interpolate come from an untrusted source (e.g. web browser) then you need to first map them to trusted values. You could do this via a hash:

    # Mappings from known values to SQL
    order_mappings = {
      'first_name_asc'  => 'first_name ASC',
      'first_name_desc' => 'first_name DESC',
      'last_name_asc'   => 'last_name ASC',
      'last_name_desc'  => 'last_name DESC',
    }
    
    # Ordering options passed in as an array from some source:
    order_options = ['last_name_asc', 'first_name_asc']
    
    # Map them to the correct SQL:
    order = order_options.map{|o| order_mappings[o] }.compact.join(', ')
    Client.order(order)
    

提交回复
热议问题