Prevention against SQL Injection in Hibernate
Asked Answered
P

1

10

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

Periapt answered 5/1, 2011 at 16:29 Comment(0)
L
4

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.

Lothario answered 5/1, 2011 at 16:35 Comment(4)
I looked into the link you proposed.. people are suggesting solutions for html escaping.. Is there any other type of escaping required ??Periapt
-1. Escaping input data is not a good approach to XSS prevention. The better way is to escaped the untrusted data when you are going to insert them inso dangerous context (such as HTML page), taking in account the rules of that context. See also OWASP XSS Prevention Cheat Sheet. Also the question was about SQL injection, not about XSS.Antoinetteanton
@Antoinetteanton If you read my answer and comment inside the code you will see I mention that the data must be escaped upon insert into the table Mother.Lothario
@axtavt: Axtvt is not so wrong: Escping is needed when the meta data representation is changed. -- What I mean: when going from Java to SQL (Send a Sql Statemment) you have to take care about the SQL escaping, but not the HTML stuff. When writing an HTML Page you have to take care about the HTML escaping, but not the SQL stuff. -- The rule is simple: every time your data went from one context/style to an other you have to pay attnetion to escapeingGadget

© 2022 - 2024 — McMap. All rights reserved.