13

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?

3
  • 1
    Test it. Profile your db to find out exactly what SQL was generated. Commented Apr 8, 2013 at 21:07
  • @marvc1 I did, that is how I found that single qoutes are escaped into double quotes. But I am no SQL injection expert, is that really enougth? Commented Apr 8, 2013 at 21:10
  • 1
    try the line x'; DROP TABLE tableName; -- and see if that table is dropped. Replace table name first. Commented Apr 8, 2013 at 21:13

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.