Unsanitized external input in SQL query
- Rule ID: ruby_rails_sql_injection
- Languages: ruby
- Source: sql_injection.yml
Description
Using unsanitized data, such as user input or request data, or externally influenced data passed to a function, in SQL query exposes your application to SQL injection attacks. This vulnerability arises when externally controlled data is directly included in SQL statements without proper sanitation, allowing attackers to manipulate queries and access or modify data.
Remediations
- Do not use raw SQL queries that incorporate unsanitized external input directly. This approach is vulnerable to SQL injection.
User.where("user.email = #{params[:email]}") # unsafe
- Do utilize the ActiveRecord API for constructing SQL queries to automatically handle input sanitization.
User.where(email: params[:email])
- Do employ bind variables in SQL queries to separate the query structure from the data, effectively preventing SQL injection.
User.where("user.email = ?", [params[:email]])
- Do manually sanitize input values when constructing SQL queries to ensure that any potentially harmful characters are neutralized.
User.where(sanitize_sql(["user.email = ?", params[:email]]))
References
- OWASP SQL injection explained
- OWASP SQL injection prevention cheat sheet
- Securing Rails applications - SQL injection
Associated CWE
OWASP Top 10
Configuration
To skip this rule during a scan, use the following flag
bearer scan /path/to/your-project/ --skip-rule=ruby_rails_sql_injection
To run only this rule during a scan, use the following flag
bearer scan /path/to/your-project/ --only-rule=ruby_rails_sql_injection