How to Prevent SQL Injection Attacks
A Quick Introduction to SQL Injection​
SQL injection vulnerabilities are caused by code that passes any form of user input directly to the database.
Here's a quick example.
Let's say you want to create an account on a new website. This site happens to be vulnerable to SQL injection.
You could set your email to something odd, like this:
[email protected]';update users set password='password'--
That query might look something like this:
SELECT * FROM "users" WHERE email = '[email protected]';update users set password='password'--'
Can you guess what this might do?... 🤔
Sanitize Inputs to Prevent SQL Injection​
Input sanitization is the most important tool for preventing SQL injection in your database. And Active Record automatically does this when you use it correctly. But that's the key, you have to use it correctly.
BAAAD​
Do not write pure string conditions in active query record it could not prevent SQL injection, exp:
Post.where("category = 'books'")
or
Post.where("category = #{params[:category]}")
GOOD​
Instead of example above use these queries:​
# Array Conditions
Post.where("category = ?", params[:category])
# Hash Conditions
Post.where(category: params[:category])
Both examples will be sanitized by active records under the hood