Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent SQL injection in PYTHON-DJANGO?

Tags:

If a lamer input is inserted into an SQL query directly, the application becomes vulnerable to SQL injection, like in the following example:

dinossauro = request.GET['username']  sql = "SELECT * FROM user_contacts WHERE username = '%s';" % username 

To drop the tables or anything -- making the query:

INSERT INTO table (column) VALUES('`**`value'); DROP TABLE table;--`**`') 

What may one do to prevent this?

like image 412
Jayron Soares Avatar asked Dec 09 '13 10:12

Jayron Soares


People also ask

How does Django prevent SQL injection?

Django's querysets are protected from SQL injection since their queries are constructed using query parameterization. A query's SQL code is defined separately from the query's parameters. Since parameters may be user-provided and therefore unsafe, they are escaped by the underlying database driver.

How can SQL injection be prevented?

How to Prevent an SQL Injection. The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly.

Does ORM protect from SQL injection?

The benefits of using an ORM tool include quick generation of an object layer to communicate to a relational database, standardize code templates for these objects, and that they usually provide a set of safe functions to protect against SQL Injection attacks.


2 Answers

First, you probably should just use Django ORM, it will prevent any possibility of SQL injection.

If for any reason you can't or don't want to then you should use Python Database API. Here is the way you usually do that in Django:

from django.db import connection  cursor = connection.cursor() cursor.execute('insert into table (column) values (%s)', (dinosaur,)) cursor.close() 

You can also use handy python package to reduce the boilerplate:

from handy.db import do_sql  do_sql('insert into table (column) values (%s)', (dinosaur,)) 
like image 171
Suor Avatar answered Sep 17 '22 14:09

Suor


From the Django Docs:

SQL injection protection

SQL injection is a type of attack where a malicious user is able to execute arbitrary SQL code on a database. This can result in records being deleted or data leakage.

By using Django’s querysets, the resulting SQL will be properly escaped by the underlying database driver. However, Django also gives developers power to write raw queries or execute custom sql. These capabilities should be used sparingly and you should always be careful to properly escape any parameters that the user can control. In addition, you should exercise caution when using extra().

like image 37
cstrutton Avatar answered Sep 17 '22 14:09

cstrutton