Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are SQL operator functions for Entity Framework safe against SQL injection?

These functions give access to specialty functions (SqlClient) in SQL. For example 'like' or 'between'. And they also give a nicer common abstraction layer for them. Not to be confused with stored procedure(s) "functions" which is the topic of this other question.

My question that I can't seem to find a full answer for is. Are they safe to use, or am I opening the system to a SQL injection attack? I always use bound variables when writing regular SqlCommands.

But in moving to Entity Framework. There is less control over the SQL statements. I don't mind it, but I can't help worrying when I concatenate a string coming from a browser and pass it to a function.

Here is an example:

var QueryResult = EFContext.Table.Where(x => 
    SqlFunctions.PatIndex("%" + Potentially_unsafe_search_keyword + "%", 
                          x.Column) > 0);

I did some tests and traced the actual SQL sent to the server. Single quotes are escaped out automatically. So clearly there is some protection there. There is some sanitization taking place. Insert statements do use bind variables. Should I be content with the single quote replacement? Is there something else going on behind the scenes?

like image 853
Arturo Hernandez Avatar asked Apr 08 '13 20:04

Arturo Hernandez


1 Answers

Every Constant, variable, parameter in Linq is passed as command parameter in IDbCommand, which in turn is escaped by underlying driver.

Unless there is a bug, all EF queries and SQL helper functions are safe against SQL injection attacks.

like image 59
Akash Kava Avatar answered Sep 17 '22 15:09

Akash Kava