Search code examples
javahibernatepersistencecriteriahibernate-criteria

Does the Java/Hibernate Criteria Query API Protect Against Injection?


This might be a dumb question, but I have not seen anything in the docs explicitly stating that criteria queries are parameterized or otherwise injection-protected under the hood.

In other words, is a predicate like the following directly vulnerable to injection attacks? If so, how do I fix it? Looking around the docs I don't see any options for parameterization or anything similar.

criteriaBuilder.like(
    root.get("prop"),
    "%"+userInput+"%"
)

Solution

  • Yes, hibernate is using parameterized queries for criteria*

    The easiest way to confirm this, is to activate the sql logging (set org.hibernate.SQL category to DEBUG) and you'll see the queries produced by hibernate (and to get parameter values, activate the log category : org.hibernate.type to TRACE level).

    *in criteria you can write sql section by hand (using Restrictions.sqlRestriction("...")). If you are writing sql that is prone to sql injection there, your criteria query will be subject to it too.