Are Django Q objects (complex queries) secure?

617 views Asked by At

I can't seem to find any resources explaining the security of Django's built in complex queries (Q objects, or F objects). Is it possible to inject a SQL attack in these queries? I did a small test:

from models import *
from django.db.models import Q
q = MyModel.objects.filter(Q(mycolumn__contains='%; DROP DATABASE mydatabase;'))
print q
>>> []
print q.query
>>> SELECT `mydatabase_mytable`.`mycolumn` FROM `mydatabase_mytable` WHERE 
    `mydatabase_mytable`.`mycolumn` LIKE BINARY %\%; DROP DATABASE mydatabase;% 

This doesn't seem to have dropped my database though. What's going on here?

1

There are 1 answers

1
Jon S. On BEST ANSWER

As you can see from your SQL, Django is escaping the LIKE clause. Here is a reference to what is happening in that case.

In general, Django does protect you from SQL injection attacks. Here is their security page. Note that you can get in trouble by executing custom SQL or by using "extra" carelessly, but otherwise, you are protected.