Preventing SQL Injection with the Entity Framework and Data Services

Yesterday, at the Developer Dinner, I answered a bunch of questions around SQL Injection in the various usage scenarios of the ADO.NET Entity Framework & ADO.NET Data Services.  For the most part, my responses were correct.  However, the last question asked was specific to Entity SQL queries.  I misspoke.  This post is to clear things up.

Because Entity SQL is string based, it is susceptible to SQL Injection.  From Security Considerations (Entity Framework):

"Entity SQL injection attacks:

SQL injection attacks can be performed in Entity SQL by supplying malicious input to values that are used in a query predicate and in parameter names. To avoid the risk of SQL injection, you should never combine user input with Entity SQL command text.

Entity SQL queries accept parameters everywhere that literals are accepted. You should use parameterized queries instead of injecting literals from an external agent directly into the query."

Therefore, if you decide to execute queries using Entity SQL, then will want to review How to: Execute a Parameterized Query (Entity Framework).  I will be sure to update my Entity SQL demos to use parameterized queries.

The good news is that if you are using LINQ to Entities, then you are covered:

"LINQ to Entities injection attacks:

Although query composition is possible in LINQ to Entities, it is performed through the object model API. Unlike Entity SQL queries, LINQ to Entities queries are not composed by using string manipulation or concatenation, and they are not susceptible to traditional SQL injection attacks. "

If I remember correctly, the originating question starting the series of SQL Injection questions was about introducing SQL Injection into an ADO.NET Data Services query.  ADO.NET Data Services queries go through a translation layer from the http request to the actual query execution.  Although this translation is not exactly the same, it is conceptually similar to what happens when you create LINQ to Entities queries in code.  Because of this translation layer you get the same protection from SQL Injection.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s