Developer Edition Injection Vulnerability Scanning with the Python Psycopg2 Library

I am still having difficulty getting SonarQube to identify potential SQL injection. This a concern because I was hoping it would help us identify things we might not know to look for. Perhaps that is related to Psycopg2 support vs Django? Is there a way to make vulnerability detection more aggressive? For example, by expanding SonarQube’s definition of tainted sources, etc.?

I tried multiple things in an attempt to trigger the unsafe injection rule:

  • full / partial queries passed as a function parameters
  • session.get(“some url”).content
  • requests.get(“some url”).content
  • input("Get input: ")

I was only able to get the Django code from the example to mark a query as tainted:

  • request.GET.get(“id”, “”)

It correctly identified two instances of potential SQL injection in the following code example. However, neither were found without the Django tainted source. For example, setting the “text” variable to “some string” should only remove the finding in self.run_unsafe_query(), not both findings.

Also, renaming self.execute() prevented the finding inside of self.execute(). The issue in self.run_tainted_query() was still reported correctly. I think it may be confusing self.execute() and cursor.execute() in that case? I am unsure what the issue is there.

from django.http import HttpResponse
from django.db import connection
import psycopg2

class SomeClass:
    def __init__(self, params):
        self._cursor = psycopg2.connect(params).cursor()

    def execute(self, sql):
        self._cursor.execute(sql) # Detected as SQL injection (1)

    def run_unsafe_query(self, unsafe_query):
        self.execute(unsafe_query)

    def run_tainted_query(self, request):
        text = request.GET.get("id", "") # Django tainted source
        self._cursor.execute("Unsafe query" + text) # Detected as SQL injection (2)