3

I'm using squeel gem in my project, and I have code something like this :

def self.search(query)
    return self.scoped if query.blank?

    self.joins(:supplier).where{lower(supplier.supplier_name).like_any(["%#{query}%"])}
  end

My questions is this code vulnerable to SQL injection? And how do I fix it? I tried to do sanitize(query) but it just adds extra set of quotes and the SQL statement doesn't get generated appropriately

messanjah
  • 8,977
  • 4
  • 27
  • 40
Gandalf StormCrow
  • 25,788
  • 70
  • 174
  • 263
  • Is this from Sequel? Looks like it could be from Squeel gem instead: https://github.com/activerecord-hackery/squeel - please clarify because the vulnerability or not to SQL injection is going to depend which library. I suspect it is *not* vulnerable though, most of these libraries carefully escape params used for queries. – Neil Slater Apr 17 '15 at 14:59
  • @NeilSlater you're right, let me edit the question, feel free to answer thanks – Gandalf StormCrow Apr 17 '15 at 15:06
  • 1
    Well I could of answered if it was Sequel . . . but I don't have ActiveRecord db set up, and don't know for sure, although I suspect your code is not vulnerable. Hopefully someone who knows better will be able to answer with more confidence. – Neil Slater Apr 17 '15 at 15:38

1 Answers1

1

UPDATED:

Squeel will automatically escape strings, so your query is fine and won't open you up to injection. See question about sql injection - Squeel - Github

OLD (INCORRECT) ANSWER: This is the active record version

Someone correct me if i'm wrong, but since you are passing in #{query} as a STRING and not an argument, then you are opening yourself up to injection. See the docs for passing in arguments

Using arguments will escape the 'query' STRING

Your query using arguments:

self.joins(:supplier).where{lower(supplier.supplier_name).like_any(["%"+?+"%"], query)}
dannypaz
  • 1,294
  • 1
  • 12
  • 16