Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

hql - Prevention against SQL Injection in Hibernate

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 ??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...