Recipe Name:
Injection - SQL Injection in JPA: EntityManager#createQuery
Description:
Avoid SQLi by using parameterized queries, instead of string concatenation with untrusted input
Level:
error
Language:
  • java
Tags:
  • security
  • JPA
  • injection
  • SQL
  • OWASP Top 10
Documentation

Use parameterized queries to prevent SQL injection.

Dynamically creating queries by means of concatenating (untrusted) user input puts the application at risk of SQL injection. An attacker could insert malicious input to obtain or modify data.

Before
entityManager.createQuery("Select b from Books b where b.author like " + author).getResultList();
After
entityManager.createQuery("Select b from Books b where b.author like :author")
    .setParameter("author", author).getResultList();
Resources
Recipe
id: scw:db:jpa:createquery
version: 10
metadata:
  name: 'Injection - SQL Injection in JPA: EntityManager#createQuery'
  shortDescription: Avoid SQLi by using parameterized queries, instead of string concatenation with untrusted input
  level: error
  language: java
  enabled: true
  descriptionFile: descriptions/Injection-SQLInjectioninJPAEntityManagercreateQuery.html
  tags: security;JPA;injection;SQL;OWASP Top 10
search:
  methodcall:
    args:
      1:
        type: java.lang.String
        value:
          containsUntrustedInput: true
          trustedSources:
          - methodcall:
              name: format
              declaration:
                type: java.lang.String
    name:
      matches: createQuery
    declaration:
      type: javax.persistence.EntityManager
availableFixes:
- name: Use parameterized queries
  actions:
  - parameterize:
      placeholderFormat: :{{{name}}}
      extractUntrustedInput:
        methodsOnObject:
          methods:
          - methodName: setParameter
            args:
              "1": '"{{{ name }}}"'
              "2": '{{{ . }}}'
          target:
            returnValue:
              useMethodChaining: true