logo

Database

Java Like Clause Unescaped Input

Description

Detects potential SQL injection vulnerabilities in JPA queries where unescaped input is used in LIKE clauses. This can allow attackers to manipulate the query logic using wildcard characters (% and _) if input is not properly escaped, potentially leading to information disclosure or data manipulation.

Weakness:

012 - SQL injection - Java Persistence API

Category: Unexpected Injection

Detection Strategy

    Look for Java methods annotated with @Query or @SqlQuery decorators

    Identify LIKE clauses within the query strings of these methods

    Check if query parameters used in LIKE conditions lack proper escaping

    Report vulnerability if unescaped user input can be passed to LIKE clause

Vulnerable code example

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface UserRepository extends JpaRepository<User, Long> {
    // Vulnerable: Using unescaped parameter in LIKE clause allows SQL wildcards injection
    @Query("select u from User u where u.lastname like %:#{[0]}%")
    List<User> findByLastnamePattern(String lastname);...

✅ Secure code example

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;

public interface UserRepository extends JpaRepository<User, Long> {
    // Secure: Using escape() function to sanitize wildcards and escapeCharacter() for escaping
    @Query("select u from User u where u.lastname like %?#{escape([0])}% escape ?#{escapeCharacter()}")...