Hibernate Query Language (HQL) Injection
Description
Hibernate Query Language (HQL) Injection is a code injection vulnerability that occurs when untrusted user input is directly concatenated into HQL queries without proper validation or parameterization. HQL is the object-oriented query language used by Hibernate ORM, a popular Java framework for database operations. When attackers can manipulate HQL queries, they can alter the query logic to bypass security controls, access unauthorized data, or modify database contents. This vulnerability is analogous to SQL injection but targets the Hibernate abstraction layer.
Remediation
Prevent HQL injection by using parameterized queries (also called prepared statements or named parameters) for all database operations that include user input. Never concatenate user input directly into HQL query strings.<br/><br/><strong>Vulnerable Code Example:</strong><pre>// UNSAFE - Direct concatenation of user input String username = request.getParameter("username"); String hql = "FROM User WHERE username = '" + username + "'"; Query query = session.createQuery(hql);</pre><br/><strong>Secure Code Example:</strong><pre>// SAFE - Using named parameters String username = request.getParameter("username"); String hql = "FROM User WHERE username = :username"; Query query = session.createQuery(hql); query.setParameter("username", username);</pre><br/><strong>Additional Recommendations:</strong><br/>• Implement input validation to reject unexpected characters or patterns<br/>• Apply the principle of least privilege to database accounts used by the application<br/>• Use Hibernate's Criteria API or JPA Criteria queries as type-safe alternatives to string-based HQL<br/>• Enable database activity monitoring to detect potential injection attempts<br/>• Conduct regular code reviews and security testing to identify injection vulnerabilities