Entity Framework + sql injection Entity Framework + sql injection sql sql

Entity Framework + sql injection


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 callmethods on the result that expose secure data or increase the size ofthe 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 areiterated over, a consumer of a query that exposes an IQueryable<T>type could catch exceptions that are thrown. Exceptions could containinformation 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)