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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With