Tuesday, July 14, 2009

A tip to avoid SQL injection

System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(
"select * from Orders where OrderID= '" + passOrderID + "'";

An user can pass anything to passOrderID , this leads a hacker to easily replace
string with something malicious. As shown in the above bad example do not build
dynamic strings, instead use parameters. Anything passed to a parameter considered
as field data and not as part of SQL statement, This avoids above malicious scenario.

Following code snippet demos a parametrized querying steps,



//define SQLCommand object
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(
"select * from Orders where OrderID= @OrderID", conn);

//define parameters used in SQLCommand object
SqlParameter para = new SqlParameter();
para.ParameterName = "@OrderID";
para.Value = passOrderID;

// add parameter to SQLCommand object
cmd.Parameters.Add(para);

or in one line

cmd.Parameters.Add(new SqlParameter("@OrderID",passOrderID));

This makes the application more secure.

0 comments:

My Achievements

Member of

Blog Archive

Followers

free counters