14

I am working with Hibernate to protect my website from SQL Injection.

I heard that Hibernate Criteria API is more powerful than HQL. Does Hibernate Criteria Api completely protect from SQL Injection?

Xavi López
  • 27,550
  • 11
  • 97
  • 161
ѕтƒ
  • 3,547
  • 10
  • 47
  • 78

1 Answers1

19

Yes, it does.

Criteria API as well as query parameters in HQL or JPQL both escape the parameters and would not execute malicious SQL.

The vulnerability is only exposed if you simply concatenate the parameters into your query. Then any malicious SQL becomes part of your query.

EDIT The OWASP features a SQL injection prevention cheatsheet. Using criteria queries is equivalent to defense option 1: using prepared statements.

kostja
  • 60,521
  • 48
  • 179
  • 224
  • what is the conclusion. does the criteria API completely protects my websites from SQL Injection.? – ѕтƒ Feb 25 '13 at 12:04
  • 1
    @яєηנιтн.я Sorry for sounding inconclusive. Yes, it does. – kostja Feb 25 '13 at 12:08
  • 3
    @яєηנιтн.я what actually protects you from SQL injection is the `Statements`that are used with Criteria, HQL or even pure JDBC, if you use it correctly. The conclusion is: Don't concatenate String to create your query. Use the API. – Caesar Ralf Feb 25 '13 at 12:27
  • kostja, Ralf Hoppen: Thanks for the valuable comments – ѕтƒ Feb 26 '13 at 04:31
  • it seems that HQL is prone to HQL injection that is as unsafe as SQL injection. https://www.dineshonjava.com/hibernate/understanding-parameter-binding-and-sql/ – White_King Sep 06 '21 at 19:42
  • As long as the HQL query uses bound params, it is not vulnerable. The linked article does not make it clear, but the weakness is in concatenation. There have been some exploits, enabling specific SQL injection attacks, e.g. https://snyk.io/vuln/SNYK-JAVA-ORGHIBERNATE-1041788, but in general, you are safe. – kostja Sep 07 '21 at 14:29