logo

Database

Python Drivers Sql Injection

Description

Detects potential SQL injection vulnerabilities in Python applications by identifying unsafe database query execution. Specifically looks for cases where untrusted/dynamic input flows into SQL queries when using common Python database drivers (sqlite3, psycopg2, pymysql, mysql.connector) without proper parameterization or sanitization.

Weakness:

297 - SQL injection - Code

Category: Unexpected Injection

Detection Strategy

    Check if any supported database drivers (sqlite3, psycopg2, pymysql, mysql.connector) are imported in the code

    Look for calls to the 'execute' method on database connection/cursor objects

    Examine the first argument passed to execute() to determine if it contains potentially unsafe dynamic content

    Report a vulnerability if the SQL query string contains user-controlled or unsanitized input variables

Vulnerable code example

import sqlite3
from django.http import HttpRequest, HttpResponse

def vulnerable_query(request: HttpRequest) -> HttpResponse:
    user_id = request.GET.get("id")  # Source: untrusted user input
    conn = sqlite3.connect("example.db")
    cursor = conn.cursor()
    query = f"SELECT * FROM users WHERE id = {user_id}"  # VULNERABLE: f-string allows SQL injection...

✅ Secure code example

import sqlite3
from django.http import HttpRequest, HttpResponse

def secure_query(request: HttpRequest) -> HttpResponse:
    user_id = request.GET.get("id")  # Source: untrusted user input
    conn = sqlite3.connect("example.db")
    cursor = conn.cursor()
    query = "SELECT * FROM users WHERE id = ?"  # SECURE: Using parameterized query with placeholder...