Does LINQ to SQL eliminate the possibility of SQL Injection by ThinqLinq

Does LINQ to SQL eliminate the possibility of SQL Injection

By default, LINQ to SQL uses parameterized queries rather than concatenated strings when executing your LINQ queries. As a result, if a user tries to perform SQL Injection by improperly escaping parts of the SQL, the escape is considered part of the parameter rather than part of the query and thus avoids the injection.

However, as we discussed in chapter 8 of LINQ in Action, LINQ to SQL greatly reduces the possibility of SQL Injection, but doesn't completely eliminate it. For example, if you are using Stored Procedures and call spExecuteSQL passing in a concatenated string inside of the SQL Stored Proc, you are still subject to SQL Injection. Of course, this applies regardless of the data access technology and shows that even stored procs can't eliminate the possibility of SQL Injection.

In addition, the LINQ to SQL DataContext does offer the ability to pass a SQL Pass-through query as a string which can be injectable. For example, the following returns all rows in the Authors table:

string searchName = "Good' OR ''='";
TypedDataContext context = this;

string sql = @"Select ID, LastName, FirstName, WebSite, TimeStamp " +
"From dbo.Author " +
"Where LastName = '" + searchName + "'";

IEnumerable<Author> authors = context.ExecuteQuery<Author>(sql);

LINQ to SQL does allow for a Injection safe version if you use string parameter place holders and pass the parameters into the overloaded version of ExecuteQuery accepting a paramarray of objects:

string sql = @"Select ID, LastName, FirstName, WebSite, TimeStamp    " +
"From dbo.Author " +
"Where LastName = {0}";

IEnumerable<Author> authors = context.ExecuteQuery<Author>(sql, searchName);

Thankfully, if you're standard LINQ methods, you're safe from SQL Injection with LINQ to SQL. The Entity Framework on the other hand actually does have some other potential injectionable areas if you're thinking of going down that route.

Posted on - Comment
Categories: LINQ) - C#) -
comments powered by Disqus