Is Injection Possible through Dynamic LINQ?

Well, I do not agree that the injection is not possible in Dynamic Linq.

What described in the answer by Ɖiamond ǤeezeƦ is correct but appies to standard Linq as constructed within the given language – C# or VB.Net or by calling extension methods like .Where with lambda functions.

Then, true, it is not possible to inject anything as the .NET Linq to Sql translator is, of course, decently written.
Thus, the “SQL injection” is not possible, that’s true.

However, what is possible with Dynamic Linq is “Linq injection” attack. In the explanation for safety of linq quoted by OP, it is stated:

LINQ to Entities queries are not composed by using string manipulation or concatenation, and they are not susceptible to traditional SQL injection attacks.

And basically this is a gist. If queries are composed by string manipulation then it is prone to injection attacks. And Dynamic Linq is actually composed from strings, therefore it is potentially prone to attack by injection.

Obviously, the attacker will have to be aware of the fact that you are using DynamicLinq and could attack only preparing the data so it results in valid malicious Dynamic Linq query.

I want to highlight this fact – the final SQL is composed safely, but whether original dynamic Linq is safe depends on you.

The must to make your dynamic linq query safe is to use placeholders for all user input. Never concatenate your string!

Imagine the following query:

dataset.Where("allowed == 1 and code == \"" + user_entered_data + "\"");

If input is not sanitized and not escaped, the attacker could potentially input:

200" or allowed == 0 and code == "200

which will result in:

allowed == 1 and code == "200" or allowed == 0 and code == "200"

In order to avoid this, you should use placeholders:

dataset.Where("allowed == 1 and code == @0", user_entered_data);

DynamicLinq will make the placeholder (in this case: user-entered data) a lambda argument (instead of concatenating it into query) and depend on Linq-To-Entities (or whatever backend is) to safely convert to SQL.

Leave a Comment