KIRAN KUMAR MATAM
KIRAN KUMAR MATAM

Reputation: 370

How to prevent SQL second order injections in java (Spring Application)

I have been facing the second order SQL injection in this following code

if(subjectId!=null){Query query= sessionFactory
            .getCurrentSession()
            .createSQLQuery(HubQueryConstants.GET_QUERY)
            .setParameter(MyConstants.SUBJECT_ID, subjectId)
            .setFirstResult(offset)
            .setMaxResults(limit)
            .setResultTransformer(
                    Transformers.aliasToBean(MyClass.class));}

My Constant file is :

Constant file is Final class

GET_QUERY="Select * from MyClass where id=:id ";

though it is in static query by default still my security report is giving it as Second order SQL injection

Should we declare constants in interface? to avoid Security issue?

Upvotes: 1

Views: 3877

Answers (1)

A SQL injection occurs, when a placeholder is replaced with a SQL term that alters the original SQL string so that the SQL does something different than intened.

You can find more details at SQL_injection

SQL injection happens when the placeholder of the parameters are replaced. So declaring constants instead of reading the SQL from a properties file does not help. The injection happens later, independently from where the SQL string was obtained.

The easiest way to prevent SQL injection is by using prepared statements.

When a prepared statement is executed, the SQL string and the parameters are handled completely seperate by the SQL server, making SQL injection impossible.

With JPA you can use the annotation javax.persistence.NamedNativeQuery; to declare a SQL query that will be executed as prepared statement.

You find a tutorial using NamedNativeQuers at the end of jpa-native-queries

Upvotes: 1

Related Questions