在Hibernate中防止SQL注入 [英] Prevention against SQL Injection in Hibernate

查看:1037
本文介绍了在Hibernate中防止SQL注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用hibernate与我的数据库进行交互,现在我想让我的数据库层对SQL注入安全,所以我做了一些研究,并且发现我的查询应该被参数化,所以这意味着如果我只是结构化我的HQL查询为:

  List mothers = session.createQuery(
母亲作为母亲,其中cat.name =?)
.setString(0,name)
.list();

然后它的参数化和受保护免受SQL注入的影响,或者还有其他我需要做的事情.. 。



另外还有一点 - 永远逃离您的数据 怎么能实现?

解决方案

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



更新



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



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

  String name =< script> ;警报( '你好');< /脚本>中; 
//将此名称插入到Mother中,然后当您从数据库中加载它时,它将显示

列出母亲= session.createQuery(
select cat from cat作为猫加入cat.mother作为母亲,其中cat.name =?)
.setString(0,name)
.list();

添加到您的查询中,然后下一次从数据库加载它并将其呈现在Web浏览器中它会运行该脚本。

你需要确保你的框架转义所有非法字符,即:将< 更改为& lt; ,然后将其插入数据库中。

如果你的框架没有这样做,你必须手动完成。
在那里有大量的图书馆正确地逃避了你的代码。例如,请查看 此问题 ,那里的答案。

I have used hibernate to interact with my database, now I wanted to make my database layer secure against SQL Injection, so I did some research and I found out that my queries should be parameterized , so does it mean if I just structure my HQL queries as:

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

Then it's parameterized and protected from SQL Injection, or is there something else which I need to do...

One other thing was mentioned - "Always escape your Data" How can that be achieved ??

解决方案

I don't know about setString() but if it is the same as setParameter() then yes, it is enough to do that to prevent sql injection.

Update

By escaping data, means that you have to make sure you are not storing dangerous values in the database.

A quick example is for instance if you pass in the argument

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();

to your query, then next time you load this from the database, and render it in your web browser, it will run the script.
You need to make sure your framework escapes all illegal characters, ie: changing < to &lt; before you insert it in the database.
If your framework does not do this, you have to do it manually. There are tons of libraries out there that correctly escapes code for you. Take a look at this question for instance and the answers there.

这篇关于在Hibernate中防止SQL注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆