Andrew Ricci Andrew Ricci - 11 months ago 74
Java Question

JAVA - Possible SQL Injection

So I have this snippet of code:

String username = props.getProperty("jdbc.username");
try {
String username = parts[1];

// Check procedure
System.out.println("Checking user");

// Check database user table for username
conn = getSQLConnection();
Statement stat = conn.createStatement();
ResultSet user = stat.executeQuery( "SELECT * FROM USER WHERE log_id='" + username + "';" );
// Check given password against user entry
System.out.println("User Exists: " + username);

System.out.println("User Does Not Exist: " + username);
sendMessage("false user");

For educational purposes, is the SQL statement protected from an SQL injection even though I know where the input is coming from?

fge fge
Answer Source
ResultSet user = stat.executeQuery( "SELECT * FROM USER WHERE log_id='" + username + "';" );

This is subject to SQL injection.

Imagine what happens if username has this value:

John'; delete from user where 'a' = 'a

And yes, a s*load of Java JDBC SQL tutorials get this wrong. Basically, always use PreparedStatements.

Not only because this makes it safe ot use even if username has malicious values as the above, but also, and more importantly, because the same query can be reused by the RDBMS engine for all further invocations.

In short, there is no reason at all not to use them. And tutorials demonstrating SQL using string concatenation should die a painful, SQL injection death.