`quote_ident()` 和 psycopg2 中的参数化查询有区别吗?
is there a difference between `quote_ident()` and parametized queries in psycopg2?
在 python3 和 postgresql12 中,参数化 SQL 查询 "proper" 方式或仅使用 psycopg2.quote_ident()
转义潜在危险内容之间是否存在安全差异?
例如,考虑这两个选项。
选项 1:
name = get_unsafe_input_from_web_form()
cursor.execute("SELECT * FROM students WHERE name = %s;", (name,))
选项 2:
from psycopg2.extensions import quote_ident
name = get_unsafe_input_from_web_form()
cursor.execute(f"SELECT * FROM students WHERE name = {quote_ident(name, cursor)};"
documentation不是特别明确。选项 2 在防止注入攻击的安全性方面是否完全等效?
quote_ident() 是错误的用法,因为它用于标识符,例如 table,列名。你会想要 quote_literal(),它在 psycopg2.extensions 中不存在。我会坚持第一个选项,但使用 psycopg2.sql 模块:
安全方面,参数化查询和 quote_ident 都可以安全地处理不受信任的输入,不会让您面临 SQL 注入问题。但是您不能像您在示例中尝试的那样使用 quote_ident 作为值。您传递给 cursor.execute() 的字符串最终将是 (for name foobar
) SELECT * FROM students WHERE name = "foobar";
,它将尝试查找 name
列等于的行foobar
列,而不是名称等于字符串 'foobar'
.
的地方
在 python3 和 postgresql12 中,参数化 SQL 查询 "proper" 方式或仅使用 psycopg2.quote_ident()
转义潜在危险内容之间是否存在安全差异?
例如,考虑这两个选项。
选项 1:
name = get_unsafe_input_from_web_form()
cursor.execute("SELECT * FROM students WHERE name = %s;", (name,))
选项 2:
from psycopg2.extensions import quote_ident
name = get_unsafe_input_from_web_form()
cursor.execute(f"SELECT * FROM students WHERE name = {quote_ident(name, cursor)};"
documentation不是特别明确。选项 2 在防止注入攻击的安全性方面是否完全等效?
quote_ident() 是错误的用法,因为它用于标识符,例如 table,列名。你会想要 quote_literal(),它在 psycopg2.extensions 中不存在。我会坚持第一个选项,但使用 psycopg2.sql 模块:
安全方面,参数化查询和 quote_ident 都可以安全地处理不受信任的输入,不会让您面临 SQL 注入问题。但是您不能像您在示例中尝试的那样使用 quote_ident 作为值。您传递给 cursor.execute() 的字符串最终将是 (for name foobar
) SELECT * FROM students WHERE name = "foobar";
,它将尝试查找 name
列等于的行foobar
列,而不是名称等于字符串 'foobar'
.