Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using parameterized SqlCommand make my program immune to SQL injection?

I'm aware that SQL injection is rather dangerous. Now in my C# code I compose parameterized queries with SqlCommand class:

SqlCommand command = ...; command.CommandText = "SELECT * FROM Jobs WHERE JobId = @JobId;"; command.Parameters.Add("@JobId", SqlDbType.UniqueIdentifier ).Value = actualGuid; command.ExecuteNonQuery(); 

Will this automatically make my code immune to SQL injection? Do I have to do something extra?

like image 803
sharptooth Avatar asked Aug 24 '11 11:08

sharptooth


People also ask

Do parameterized queries prevent SQL injection?

Correct usage of parameterized queries provides very strong, but not impenetrable, protection against SQL injection attacks.

Is parameterized SQL safe?

A driver allows an application to construct and run SQL statements against a database, extracting and manipulating data as needed. Parameterized statements make sure that the parameters (i.e. inputs) passed into SQL statements are treated in a safe manner.

What helps preventing SQL injection?

How to Prevent an SQL Injection. The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.

What is parameterized SQL query?

Parameterized SQL queries allow you to place parameters in an SQL query instead of a constant value. A parameter takes a value only when the query is executed, which allows the query to be reused with different values and for different purposes.


1 Answers

I'd say for your particular, and probably canonical, example for parametrized queries, yes it is sufficient.

However, people sometimes write code like this

cmd.CommandText = string.Format("SELECT * FROM {0} WHERE col = @col;", tableName); cmd.Parameters.Add("@col", ...); 

because there is simply no way to pass the tablename itself as a parameter and the desire to do exists sometimes - misguided or not. It seems it is then often overlooked, that tableName (unless maybe only read from a set of static/constant values that do not derive from any input) indeed allows for SQL injection.

like image 58
Christian.K Avatar answered Sep 25 '22 01:09

Christian.K