Executing SQL queries is security-sensitive. It has led in the past to the following vulnerabilities:

SQL injection is still one of the top 10 security vulnerabilities. Applications that execute SQL commands should sanitize any externally-provided values used in those commands. Failure to do so could allow an attacker to include input that changes the query so that unintended commands are executed, or sensitive data is exposed. Instead of trying to sanitize data by hand, SQL binding mechanisms should be used; they can be relied on to automatically perform a full sanitization.

This rule flags the execution of SQL queries via Django methods which are not recommended by Django documentation as their use can result in an SQL injection. The goal is to guide security code reviews.

Recommended Secure Coding Practices

You can also reduce the impact of an attack by using a database account with low privileges.

Questionable Code Example

from django.db import models
from django.db import connection
from django.db import connections
from django.db.models.expressions import RawSQL

value = input()


class MyUser(models.Model):
    name = models.CharField(max_length=200)


def query_my_user(request, params):
    MyUser.objects.raw(request)  # Questionable

    # Parametrized queries
    MyUser.objects.raw(request, params)  # Questionable.

    with connection.cursor() as cursor:
        cursor.execute(request)  # Questionable

    with connections['my_db'].cursor() as cursor:
        cursor.execute(request)  # Questionable

    # https://docs.djangoproject.com/en/2.1/ref/models/expressions/#raw-sql-expressions

    RawSQL("select col from mytable where mycol = %s", ("test",))  # Questionable, See "Note"

    # https://docs.djangoproject.com/en/2.1/ref/models/querysets/#extra

    MyUser.objects.extra(  # Questionable. calling the "extra" method, See "Note"
        select={
            'mycol': 'myothercol > 10'
        },
    )