Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django,if using raw SQL, what steps should I take to avoid SQL injection attacks?

I have read that ORM's should minimise the possibilities of SQL injection attacks. However in Django, sometimes the ORM is somewhat limited, and I need to use raw SQL. What steps should I take to avoid SQL injection attacks?

Currently I would know to check for semicolons in the query string, but not much else. If I use parametrised queries, will this solve the problem? Are there any libraries to pass the string to, that will check it for me?

like image 728
wobbily_col Avatar asked Jul 15 '14 08:07

wobbily_col


2 Answers

The documentation states the following:

If you need to perform parameterized queries, you can use the params argument to raw():

>>> lname = 'Doe'
>>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])

params is a list or dictionary of parameters. You’ll use %s placeholders in the query string for a list, or %(key)s placeholders for a dictionary (where key is replaced by a dictionary key, of course), regardless of your database engine. Such placeholders will be replaced with parameters from the params argument.

This is also the standard way to pass parameters using Python's DB-API, which will sanitize your queries correctly.

Whatever you do, don't do string interpolation.

like image 153
Burhan Khalid Avatar answered Nov 15 '22 07:11

Burhan Khalid


You have to bind your parameters! A complete guide with examples and solutions you can find here:

http://www.djangobook.com/en/2.0/chapter20.html

like image 29
Lara Avatar answered Nov 15 '22 07:11

Lara