我曾经使用过hibernate与我的数据库进行交互,现在我想使我的数据库层免受SQL注入(inject)的侵害,所以我做了一些研究,发现我的查询应该参数化,这是否意味着如果我仅构造HQL查询作为:

List mothers = session.createQuery(
"select mother from Cat as cat join cat.mother as mother where cat.name = ?")
.setString(0, name)
.list();

然后将其参数化并保护其不受SQL注入(inject)的影响,或者还有其他需要执行的操作...

提到了另一件事-“始终转义数据”如何实现?

最佳答案

我不知道setString(),但是如果它与setParameter()相同,那么是的,这样做足以防止sql注入(inject)。

更新

通过转义数据,意味着您必须确保没有在数据库中存储危险值。

一个简单的例子是,例如,如果您传入参数

String name = "<script>alert('Hello');</script>";
//insert this name into Mother, and then when you load it from the database, it will be displayed

List mothers = session.createQuery(
"select mother from Cat as cat join cat.mother as mother where cat.name = ?")
.setString(0, name)
.list();

到查询中,然后下次从数据库中加载它并在Web浏览器中呈现它时,它将运行该脚本。
您需要确保您的框架转义了所有非法字符,即:将<更改为&lt;,然后再将其插入数据库。
如果您的框架没有执行此操作,则必须手动执行。
有大量的库可以为您正确地转义代码。例如,看看this question及其答案。

关于hibernate - 防止Hibernate中的SQL注入(inject),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4606505/

10-11 19:03