Tim
Tim

Reputation: 141

Spring JPA @Query and @Param string escaping (sql injection)

Good Afternoon

I believe the usage of org.springframework.data.jpa.repository.Query in combination with org.springframework.data.repository.query.Param prevents a SQL injection above these parameters.
For example:

@Query("DELETE User c WHERE c.issuer = :issuer AND c.subject = :subject")
    void deleteByIssSub(@Param("issuer") String issuer, @Param("subject") String subject);

should be secure. Please correct me, if I am wrong.

Now I'm looking for documentation, which describes, that the usages of @Param in combination with @Query prevent SQL injection (throw string escaping). But I don't find this documentation.

Am I wrong?

T

Upvotes: 1

Views: 4969

Answers (1)

zawarudo
zawarudo

Reputation: 2496

Does this help? How to prevent SQL Injection with JPA and Hibernate?

By default

when you are using arguments ( =: )

and

when you are setting parameters ( .setParameter("issuer", issuer) )

in your code reduces changes of SQL injection to 0, because you are building a query through your code, you are not allowing a user to send any query to the database in altered form, the only thing that he can send are arguments, and only expected arguments.

https://mkyong.com/hibernate/hibernate-parameter-binding-examples/

As long you avoid building dynamic queries with String concatenation you will be safe, but if you really need to use dynamic queries, you need to use Criteria API instead.

EDIT: No one can guarantee that for you because and I quote From the OWASP page: "Hibernate does not grant immunity to SQL Injection, one can misuse the API as they please." So no one will say that it is 100% bulletproof because people can code and use API as it was not supposed to be used or designed. https://owasp.org/www-community/Hibernate#Security_Implications

Who is OWASP? The OWASP® Foundation works to improve the security of software through its community-led open-source software projects, hundreds of chapters worldwide, tens of thousands of members, and by hosting local and global conferences.

No matter how much a car might be safe, the manufacturer will never say "our car is uncrashable", they will just state that it is really safe. The same goes for security. Nothing is 100% safe with the human factor involved.

Upvotes: 1

Related Questions