Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent SQL injection with Hibernate

I'm going through Hibernate and I know that you can prevent SQL injection with HQL:

String query1 = "from Obj where id = "+ id;
String query2 = "from Obj where id = :id";

query1 is unsafe while query2 is safe.

How can I achieve safe queries with Criteria? Is this already implemented or do I have to do something else?

Criteria c = session.createCriteria(Obj.class);
c.add(Restrictions.eq("id", 5));
like image 775
5er Avatar asked Jul 22 '26 17:07

5er


1 Answers

I'm going through Hibernate and I know that you can prevent SQL injection with HQL:

It is a very common misconception that ORM solutions, like hibernate, are SQL Injection proof. Hibernate allows the use of "native SQL" and defines a proprietary query language, named, HQL (Hibernate Query Language); the former is prone to SQL Injection and the later is prone to HQL (or ORM) injection. Source: http://software-security.sans.org/developer-how-to/fix-sql-injection-in-java-hibernate

How can I achieve safe queries with Criteria? 

As far as your latter question is concerned, Criteria API (similar to PreparedStatement) escapes the parameters and won't cause malicious SQL to be executed.

The bottom line is don't concatenate your application's parameters directly into your query (and make use of Criteria, PreparedStatement), your app is safe.

like image 174
Raman Sahasi Avatar answered Jul 25 '26 08:07

Raman Sahasi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!