logo

Database

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.

Weakness:

297 - SQL injection - Code

Category: Unexpected Injection

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(...