Reputation: 1
In Java, if a user input is directly appended to an SQL query without using methods like setString() or setInt(), but the query is executed using a PreparedStatement, is it still considered SQL injection?
Can we consider this as SQL injection?
Upvotes: 0
Views: 82
Reputation: 562230
Yes. Concatenating or interpolating untrusted input into an SQL string before it is parsed is SQL injection.
It helps to understand why prepared statements are often mentioned as a defense against SQL injection.
The problem with SQL injection is that you combine some content with your SQL query string, and then submit the string to be parsed an executed. If the content changes the SQL syntax of your query, then this causes the query to do something you didn't intend.
Using prepared statements allows you to separate the step of parsing SQL from the execution of the query. Once the query has been parsed in the prepare step, then it's not possible for content added with setString()
or setInt()
to change the syntax of the query. The query has already been parsed by the database engine, and parameters can only be treated as if they are scalar values, not other SQL syntax.
In other words, setString()
is not the same as string concatenation. It adds the string content into the query after the query has been parsed. So it's safe to add content that contains characters that would have resulted in different query logic.
If you concatenate SQL strings with untrusted content before preparing the statement, this does not help. Prepared statements do not confer any kind of "blessing" to make unsafe queries into safe queries.
They only give you the opportunity to combine parameters after the query has been prepared.
Upvotes: 1
Reputation: 628
It will be a SQL injection because automatic interpretation of the value as sql code.
If you use prepared statement as ps.setString(value), it will interpret the value as data, not as code and will do automatic escaping of problematic characters, which will prevent it from sql injection.
Upvotes: 0
Reputation: 11062
Yes, indeed it is still vulnerable to SQL injection.
A PreparedStatement
by itself does not prevent SQL injection. What prevents it is a parameterized query. In order to use a parameterized query with JDBC, you need a PreparedStatement
. But just using a PreparedStatement
does not automatically mean you're using a parameterized query. A PreparedStatement
does not prevent you from adding user input to your query string. To prevent SQL injection, you need to pass all your user input as parameters.
Upvotes: 0