SQL Injection : Parameterization Code Review

In c# code it is possible to call SQL commands using the SqlCommand object like below:

string selectString = @”select MyColumn from Mytable where MyOtherColumn = ” + value;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = selectString;
cmd.Connection = conn;
cmd.ExecuteReader();

The code above should be using parameterized statements or stored procedures. A parameterized statement is shown below.

string selectString = @”select MyColumn from Mytable where MyOtherColumn = @value1″; -see SQL Injection: Use Parameterisation

Using a parameterized statements will double quote\escape the input and prevent any issues or catenation of statements.

To code review search in your code for SqlCommand string and then check each one is using ideally a stored procedure or at worst a parameterised SQL statement. If the statement string is appended together from other strings look carefully at the source and consider whitelisting. Never append a string a user has supplied either in a form or stored from previous input in your db, instead use a parameterized statement or a stored procedure.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s