hibernatesql-injectionhibernate-criteriahibernate-restrictions

Is using Hibernate's Restrictions.eq() method safe against SQL injection?


Is using Hibernate's Restrictions.eq() method, as used in the example below, safe against SQL injection? Or similar methods like Restrictions.in(), Restrictions.ge(), ...

String vulnerable = //parameter from user interface 
Criteria ct = this.getCriteria();
ct.add(Restrictions.eq("propertyName", vulnerable));

I have found that probably is, as explained in this answer

but reviewing OWASP documentation, there is an example that shows a comment which confuses me (// This should REALLY be validated too). Is needed to validate the input, or is secure as is?

The example in the OWASP documentation

// Criteria API
// This should REALLY be validated too
String userSuppliedParameter = request.getParameter("Product-Description");
// Perform input validation to detect attacks
Inventory inv = (Inventory) session.createCriteria(Inventory.class).add
(Restrictions.eq("productDescription", userSuppliedParameter)).uniqueResult();

Solution

  • Yes, Hibernate's Criteria API would protect you against SQL Injection, as it parameterises the query - you can see this in action by enabling sql logging.

    What you do need to be careful about is concatenating user inputs etc. I think the documentation may perhaps be referring to validate the user input at both client and server side.