# Use Parameterized JPA Query

# Properties

Property Value
Rule ID UseParameterizedJPAQuery
First seen in jSparrow version 3.18.0
Minimum Java version 1.1
Remediation cost 10 min
Links How To Fix SQL Injection: JPA

# Description

JPA defines the Java Persistence Query Language (JPQL). 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 which are created by EntityManager::createQuery. 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).

# 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();

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊