Entity Framework + sql injection

c# entity-framework sql sql-injection

Question

I'm building up an IQueryable where I am applying relevant filters, and I come across this line of code here.

items = items.OrderBy(string.Format("{0} {1}", sortBy, sortDirection));

Is this snippet vulnerable to SQL injection? Or are these (string) parameters parameterized behind the scenes? I assumed that all Linq queries were escaped and parameterized for me, but the fact that I am able to pass in a string directly like this is throwing me off.

1
9
9/7/2016 4:57:40 AM

Accepted Answer

First Point :

You have to avoid returning IQueryable<T> types from methods that are exposed to potentially untrusted callers for the following reasons:

  • A consumer of a query that exposes an IQueryable<T> type could call methods on the result that expose secure data or increase the size of the result set. For example, consider the following method signature:

    public IQueryable<Customer> GetCustomer(int customerId)

A consumer of this query could call .Include("Orders") on the returned IQueryable<Customer> to retrieve data that the query did not intend to expose. This can be avoided by changing the return type of the method to IEnumerable<T> and calling a method (such as .ToList()) that materializes the results.

  • Because IQueryable<T> queries are executed when the results are iterated over, a consumer of a query that exposes an IQueryable<T> type could catch exceptions that are thrown. Exceptions could contain information not intended for the consumer.

Second Point :

How to prevent SQL injection attacks ?

  • 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. You should also consider using query builder methods to safely construct Entity SQL.

  • 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.

Reference : Security Considerations (Entity Framework)

20
9/7/2016 5:46:22 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow