Python Rawsql With Unvalidated Input
Description
Detects potential SQL injection vulnerabilities in Django applications where raw SQL queries are used with unvalidated input. This targets dangerous uses of Django's RawSQL, extra(), and raw() methods which can allow attackers to inject malicious SQL statements if user input is not properly sanitized.
Detection Strategy
• Identifies function calls to Django's raw SQL methods: RawSQL, extra(), or raw()
• Analyzes parameters passed to these SQL methods to check if they contain unvalidated user input
• Checks if user-controlled data flows into the SQL query without proper sanitization or parameterization
• Reports a vulnerability when unvalidated input is directly concatenated or formatted into raw SQL queries
Vulnerable code example
from django.db.models import RawSQL
from myapp.models import MyModel
def vulnerable_query(request):
user_input = request.GET.get("user_input")
# Vulnerable: Direct string interpolation in SQL allows injection
return MyModel.objects.filter(...✅ Secure code example
from django.db.models import RawSQL
from myapp.models import MyModel
def secure_query(request):
user_input = request.GET.get("user_input")
# Safe: Uses parameterized query with placeholder and params list
return MyModel.objects.filter(...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.