Consider this statement:
PreparedStatement stmt = connection.prepareStatement("SELECT * FROM t WHERE id=?");
stmt.setInt(1, id);
The above is considered safe from SQL Injection attacks. Is the one below also safe, knowing that id
is of type int
?
PreparedStatement stmt = connection.prepareStatement("SELECT * FROM t WHERE id=" id);
If not, what can go wrong?
CodePudding user response:
I can think of two things that might go wrong even if id
is an int and can never be anything else:
- Someone in the future might change the
id
type to aString
. - Someone might copy-paste your code to another part of the codebase, and then modify the SQL so that it's concatenated with a
String
, making that part vulnerable.
CodePudding user response:
If your langage doesn't support strong typing or if input validation is weak, some malicious string (for example: "1 OR 1=1") can makes its way down to your request.
CodePudding user response:
First Java is strongly typed language so, pragmatically speaking there is no way an sql injection make it to this part of code.
but security is more than that. code quality is also a security level that is not to be taken lightly, if you pass this code snippet in a sonar qube server this will be revoqued.
Why ?
First if you r not respecting the string concatenation, this is not a performance freindly way of coding.
In large scale applications everything matters. where technical debt is also a vulnerablity