Unsanitized external input in SQL query
- Rule ID: python_django_sql_injection
- Languages: python
- 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 include raw external input in SQL queries. This practice can lead to SQL injection vulnerabilities.
sorting_order = request.GET["untrusted"]
query = f"SELECT id, name FROM products ORDER BY name LIMIT 20 {sorting_order};"; # unsafe - Do validate all external input to ensure it meets the expected format before including it in SQL queries.
sorting_order = "DESC" if request.GET["sortingOrder"] == "DESC" else "ASC"
- Do use parameters for database queries to separate SQL logic from external input, significantly reducing the risk of SQL injection.
Product.objects.raw("SELECT * FROM products WHERE id LIKE ?", [f"%{product_id}%"])
- Do escape all external input using appropriate database-specific escaping functions before including it in SQL queries.
from mysql.connector.conversion import MySQLConverter
converter = MySQLConverter(connection)
ok = converter.escape(request.GET["value"])
References
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=python_django_sql_injection
To run only this rule during a scan, use the following flag
bearer scan /path/to/your-project/ --only-rule=python_django_sql_injection