Home > OS >  Does concatenated string that is later used in prepared statement cause sql injection?
Does concatenated string that is later used in prepared statement cause sql injection?

Time:09-13

I am assessing a piece of code to check the possibility of sql injection. I noticed that before making a prepared statement, a string is constrcuted just for the where condition (named strwhere) and then this is passed to a function that created the prepared statement. Noting that in the strwhere it is built using string concatenation, does this raise an sql injection? or just the fact that is passed to a prepared statement eliminates this risk?

Code:

String strWhere = whereString   " AND "   "("   Table1.ID   "="   ID   ")";
Rows = myTable.readRow(jdbcSource, stWhere);

in the readRow function, it builds the final query using prepared statement.

CodePudding user response:

Yes, the code you show has a risk of SQL injection, depending on how Table1.ID and ID are assigned values.

No, using a prepared statement does not eliminate the risk of SQL injection.

CodePudding user response:

Using a prepared statement is useful for ensuring that parameters do not cause a SQL injection. It does not prevent issues from untrusted data going into the statement. If Table.ID or ID are coming from untrusted sources, you will still have a SQL injection problem.

You can resolve this by validating or quoting the untrusted values. Options are:

  • Quote the table and ID names and validate that the table / ID do not have quotes
  • Validate the table and ID names using a parameterized query in the database - since these are variables in this case, this will be safe. Not this won't protect you if the attacker has the ability to create arbitrary IDs or Table names
  • Quote the table and ID names and encode any quotes - this is a bit tricky to get right
  • Related