122 Hacking Exposed Web 2.0
The preceding example could be rewritten to use SqlParameters as follows:
SqlCommand sqlCommand = sqlConn.CreateCommand();
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = "SELECT * FROM Contact WHERE
FirstName=@FirstName";
SqlParameter nameParam = new SqlParameter("@FirstName", firstName);
nameParam.SqlDbType = SqlDbType.Text;
sqlCommand.Parameters.Add(nameParam);
By looking closely, you can see that the query has changed and now uses an
SqlParameter object to specify the value for the FirstName column in the where
clause. This query can now be executed safely without worrying about data from the
user being used to attack the database.
This same mitigation strategy can be used when calling stored procedures. To avoid
having to specify a long query string such as exec sp_my_stored_procedure @param1,
@param2, change the SqlCommand??™s CommandType property to CommandType
.StoredProcedure. By changing the command type to StoredProcedure, the .Net
Framework will understand that the developer intends to call a stored procedure and
will put together the query appropriately.
Attackers have a couple advantages when attempting to perform SQL injection attacks
against ASP.
Pages:
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240