# Use Parameterized JPA Query

# Description

JPA defines the Java Persistence Query Language (JPQL) (opens new window). A JPQL query string may be constructed by concatenating string literals with user defined expressions (e.g., variables, method invocations, user input, etc). Such a query string concatenation in JPQL may cause the same kind of vulnerability to injection attacks as a native SQL query string because the user input may contain fragments that can be interpreted as JPQL code.
This rule looks for queries of type javax.persistence.Query (opens new window) which are created by EntityManager::createQuery (opens new window). The vulnerable concats of the JPQL query strings are parameterized, so that they can only be considered as data and not as code.

Requirements

Activation of this rule requires the following classpath entries to be present:

# Benefits

Prevents SQL injections when using the Java Persistence API (JPA).

# Tags

# Code Changes

# Using Query get single result

Pre

String orderId = "1 OR 1 = 1";
EntityManager entityManager = getEntityManager();
Query jpqlQuery = entityManager.createQuery("Select order from Orders order where order.id = " + orderId);
Object singleResult = jpqlQuery.getSingleResult();

Post

String orderId = "1 OR 1 = 1";
EntityManager entityManager = getEntityManager();
Query jpqlQuery = entityManager.createQuery("Select order from Orders order where order.id =  ?1");
jpqlQuery.setParameter(1, orderId);
Object singleResult = jpqlQuery.getSingleResult();

# Using Query get result list

Pre

String orderId1 = "1000000000";
String orderId2 = "1 OR 1 = 1";
EntityManager entityManager = getEntityManager();
Query jpqlQuery = entityManager.createQuery(
		"Select order from Orders order where order.id = " + orderId1 + " or order.id = " + orderId2);
List resultList = jpqlQuery.getResultList();

Post

String orderId1 = "1000000000";
String orderId2 = "1 OR 1 = 1";
EntityManager entityManager = getEntityManager();
Query jpqlQuery = entityManager
		.createQuery("Select order from Orders order where order.id =  ?1" + " or order.id =  ?2");
jpqlQuery.setParameter(1, orderId1);
jpqlQuery.setParameter(2, orderId2);
List resultList = jpqlQuery.getResultList();

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID UseParameterizedJPAQuery
First seen in jSparrow version 3.18.0
Minimum Java version 1.1
Remediation cost 10 min
Links