Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it safe using dynamic SQL with parameters? If not, what security issues might it be exposed to?

For example, this is the code that I am using:

String commandString = "UPDATE Members SET UserName = @newName , AdminLevel = @userLevel WHERE UserID = @userid";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnectionstring"].ConnectionString))
{
    SqlCommand cmd = new SqlCommand(commandString, conn);
    cmd.Parameters.Add("@newName", newName);
    cmd.Parameters.Add("@userLevel", userLevel);
    cmd.Parameters.Add("@userid", userid);
    conn.Open();
    cmd.ExecuteReader();
    Reader.Close();
}
like image 460
RoundOutTooSoon Avatar asked Jan 12 '11 18:01

RoundOutTooSoon


2 Answers

That code looks fine. Parameterisation is the way to go, as opposed to concatenating user-supplied values in an adhoc SQL statement which can open you up to sql injection attacks. This can also help with execution plan reuse.

The only thing I'd add, is I prefer to explicitly define the datatype and sizes of the parameters. For example, if you don't then, as an example, all string values will get passed in to the database as NVARCHAR instead of VARCHAR. Hence I like to be explicit.

like image 200
AdaTheDev Avatar answered Sep 19 '22 22:09

AdaTheDev


It's safe against SQL injection because it's parameterized. Other security concerns, such as ensuring that @userid is not spoofed, are separate security concerns that should be dealt with in other layers of your application.

like image 25
Shan Plourde Avatar answered Sep 18 '22 22:09

Shan Plourde