What are the differences between a JPQL-Injection and SQL-Injection

845 views Asked by At

I have read about JPQL injection and SQL injection. In many sites it has been said that ORM injection is almost as same as SQL injection in a testers point of view. So what basically i want to know is the major differences between JPQL and SQL injections.

1

There are 1 answers

0
Bill Karwin On BEST ANSWER

Both JPQL injection and SQL injection are examples of the broader category of Code Injection.

Any language that is parsed at runtime is susceptible to Code Injection.

JPQL or Java Persistence Query Language is similar to SQL in syntax, and in the fact that it is written as strings and parsed at runtime.

Building queries by passing JPQL query strings directly to the createQuery method, as shown above, is referred to in JPA as dynamic query construction because the query string can be built dynamically at runtime.

When the description says "built dynamically at runtime" they mean your code formats the JPQL query as a Java string, then submits the string to be parsed and executed. Therefore your code has an opportunity to combine fixed strings with variable content.

Here's an example of using parameters safely to combine a variable with a JPQL statement. This comes from https://www.objectdb.com/java/jpa/query/parameter

SAFE:

TypedQuery<Country> query = em.createQuery(
    "SELECT c FROM Country c WHERE c.name = :name", Country.class);
return query.setParameter("name", name).getSingleResult();

Here's the same query written in an unsafe way, combining the variable directly into the string.

UNSAFE:

TypedQuery<Country> query = em.createQuery(
    "SELECT c FROM Country c WHERE c.name = '" + name + "'", Country.class);

Don't use string concatenation to form JPQL queries if you can avoid it. That's how unsafe content sneaks into your JPQL.