简体   繁体   English

如何在PYTHON-DJANGO中阻止SQL注入?

[英]How can I prevent SQL injection in PYTHON-DJANGO?

If a lamer input is inserted into an SQL query directly, the application becomes vulnerable to SQL injection, like in the following example: 如果将lamer输入直接插入到SQL查询中,则应用程序容易受到SQL注入的攻击,如下例所示:

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? 有什么办法可以防止这种情况发生?

First, you probably should just use Django ORM , it will prevent any possibility of SQL injection. 首先,您可能应该只使用Django ORM ,它将阻止任何SQL注入的可能性。

If for any reason you can't or don't want to then you should use Python Database API . 如果由于任何原因你不能或不想那么你应该使用Python Database API Here is the way you usually do that in Django: 这是你在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: 您还可以使用方便的 python包来减少样板:

from handy.db import do_sql

do_sql('insert into table (column) values (%s)', (dinosaur,))

From the Django Docs : 来自Django Docs

SQL injection protection SQL注入保护

SQL injection is a type of attack where a malicious user is able to execute arbitrary SQL code on a database. SQL注入是一种攻击类型,恶意用户可以在数据库上执行任意SQL代码。 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. 通过使用Django的查询集,生成的SQL将被底层数据库驱动程序正确转义。 However, Django also gives developers power to write raw queries or execute custom sql. 但是,Django还为开发人员提供了编写原始查询或执行自定义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(). 此外,使用extra()时应谨慎。

If you are using .extra() the syntax is: 如果您使用.extra()则语法为:

YourModel.objects.extra(where=['title LIKE %s'], params=['%123%321%'])

Repeating here from this answer as this is hard to find, and the docs that say "you should always be careful to properly escape any parameters" do not go on to say how to properly escape them! 这个答案重复,因为这很难找到,并且说"you should always be careful to properly escape any parameters"文档不会继续说明如何正确地逃避它们!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM