17

Do the parameters of a string passed to the @Query annotation, for Spring, get treated as pure data as they would if, for example, you were using the PreparedStatement class or any method meant to prevent SQL injection?

final String MY_QUERY = "SELECT * FROM some_table WHERE some_column = ?1";

@Query(value=MY_QUERY, nativeQuery = true)
List<SomeEntity> findResults(String potentiallyMaliciousUserInput);

Bottom Line: Is the code above susceptible to SQL injection?

6
  • Must MY_QUERY not be static?
    – tkr
    Commented Dec 4, 2017 at 6:44
  • @tkr Yes I believe so. I've run into issues trying to dynamically build the query components to feed into Query. I believe only the parameters are what you have access to change. Commented Dec 4, 2017 at 6:46
  • I actually think that this is by design. This encourages you to not build up the SQL using string concatenation, but by using proper prepared statement parameters. (But I am not quite sure.)
    – tkr
    Commented Dec 4, 2017 at 6:58
  • @tkr Thats my guess too. It might also have to do with the way in which the queries are transformed at run time to sql statements. I believe this transformation takes place when the Spring beans are initializing which is also before your own code is actually executed. Or put another way, your query must be ready by bean initialization time, minus the prepared parameters. Commented Dec 4, 2017 at 7:01
  • I checked it. MY_QUERY must not be static but final.
    – tkr
    Commented Dec 5, 2017 at 12:04

3 Answers 3

3

It looks like Spring Data's @Query is just a wrapper around JPA

See this SO answer: Are SQL injection attacks possible in JPA?

2
  • 20
    Is the example in the question safe or unsafe?
    – tkr
    Commented Dec 4, 2017 at 6:43
  • I would also like to know if the above example is safe or unsafe.
    – Ant T.
    Commented Sep 8, 2023 at 10:07
0

In the query you use bind variable instead of string concatenation (which would be vulnerable to SQL Injection), so I think your example is save in the respect of vulnerability from SQL Injection.

0

It depends on the spring data implementation. Your example is safe in spring-data-couchbase, as spring-data-couchbase will keep the positional parameter in the sql string, and set a parameter to the value of the provided parameter. An implementation which re-wrote the sql string replacing the positional parameter with the provided argument would not be safe.

However, the SPEL expression of #{[<n>]} in the @Query string will be replaced by the (n+1)th parameter provided, thus it would not be safe in any implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.