In my WebDD09 talk on Saturday I mentioned SQL injection and LINQ. I’ve had a query about what exactly is the problem with LINQ as I was constrained by time and only mentioned it in passing.
Microsoft asserts that LINQ stops SQL injection attacks:
LINQ to SQL avoids such injection by using SqlParameter in queries. User input is turned into parameter values. This approach prevents malicious commands from being used from customer input.
This is generally true, however LINQ has a problem method – ExecuteQuery. This methodexecutes queries directly on the server which can lead to injection. Now ExecuteQuery does support parameters:
IEnumerable<Customer> results = db.ExecuteQuery<Customer>(
"SELECT contactname FROM customers WHERE city = {0}",
"London");
However if you don't know about SQL parameters already it's going to be all to tempting to build a command string up with concatenation and then bang, there’s SQL Injection. I’ve seen ExecuteQuery recommended for optimisation and performance with scant or no warnings given about parameterisation.
In summary LINQ avoids SQL Injection - if you use it properly – but the same thing can be said about the ADO.NET classes… and we know people still slip up using those.
Technorati Tags:
LINQ,
SQL Injection