Friday, April 4, 2008

J2EE / ASP.NET SQL Injection Protection

J2EE

Let's take a vulnerable code example from Hacme Books.

String query = "select * from products where " + “lower(title) like '%" + keyword.toLowerCase() + "%‘”;

As seen
keyword is passed to the interpreter without validation or encoding.

For SQL Injection protection, the secure version with Prepared Statement as shown below can be used.

PreparedStatement query = con.prepareStatement( “select * from products where lower(title) like ?");
query.setString(1, keyword);
updateSales.executeUpdate():

ASP.Net

A vulnerable code example from Hacme Bank looks like this.

string sqlQuery = "select user_id from fsb_users where login_id = '" + loginID+ "' and password = '" + password + "'";

Here the loginID and password are passed to the MS SQL server without validation or encoding .

Using a secure replacement with SQLParameters as below this attack can be mitigated.

string sqlQuery = "select user_id from fsb_users where login_id = @loginID and password = @password";

//Assuming you have defined a command called 'cmd'
cmd.Parameters.Add(New SQLParameter("@loginID", loginID))
cmd.Parameters.Add(New SQLParameter("@password", password))

No comments:

Post a Comment