Vlad Balanescu Vlad Balanescu - 20 days ago 6
SQL Question

Does Rails submit form need protection from SQL injections or XSS attacks?

I am developing a secure Rails app on a secure internal server, though I still want to protect it from any kind of SQL injections or XSS attacks. I know that if I have a search box I can use something like this in my MODEL to protect the app from SQL injections:

def self.search(search)
Project.where("project_title LIKE ?"
"%#{search.strip}%"
end


What about having a submit form with direct actions to a database, say a form on
projects/new
do I need to protect that input from SQL injections as well, and if so, how can I achieve this?

Answer

You have to care about SQL injection whenever you use string concatenation with any kind of user input to construct SQL fragments. If you use parameters, you're fine.

For example this is not vulnerable to SQL injection:

Project.where("project_title LIKE ?", "%#{search.strip}%")

But this is vulnerable, because a request parameter is written directly into the SQL query and the database has no way to know where the intended query ends, so a user could inject additional parts to this query through the search parameter:

Project.where("project_title LIKE %#{search.strip}%")

Similarly, if you post a form, the question is how you use values from the request in resulting queries. If you always use parameters like in the first example above (with ? or named ones with symbols) and any request parameter is always assigned through parameters, your app is not vulnerable. If you ever mix request parameters with SQL queries as string like in the second example, your application will be vulnerable to SQL injection.

So just to clarify: any Rails method call is secure against SQL injection if you are using ActiveRecord. You only have to worry when you write parts of SQL statements yourself as strings and incorporate request parameters into that string. The above example with LIKE is somewhat special, you usually do not need to create SQL strings yourself with an ORM like ActiveRecord.

Comments