Search code examples
c#linqlinq-to-sqlsql-injection

C# Linq to SQL is contains safe for sql injections


Generally I know that Linq to SQL is safe for SQL Injections because it is using SqlParameter (as explained here and also here).

But how does it look like for contains:

StreetRepository.Streets.Where(w => w.Streetname.Contains("Road"))

If I log the queries in SQL Server directly, I can see that following query is used:

SELECT [Extent1].[Id] AS [Id], [Extent1].[Streetname] AS [Streetname] 
FROM [dbo].[Streets] AS [Extent1]  
WHERE [Extent1].[Streetname] LIKE N'%Road%'

As we can see it is not using parameters for this query. If I'm using following command:

StreetRepository.Streets.Where(w => w.Streetname.Contains("Road' OR 1=1"))

I get:

SELECT [Extent1].[Id] AS [Id], [Extent1].[Streetname] AS [Streetname] 
FROM [dbo].[Streets] AS [Extent1]  
WHERE [Extent1].[Streetname] LIKE N'%Road'' OR 1=1%'

In this case it is escaped by a double ''.

But is this safe enough for all attacks? Can I use contains without worries? If not what can I use instead of contains?


Solution

  • Parameters is not only way to protect from SQL Injection. LINQ to SQL knows how to properly escape strings. So do not worry, everything will be ok.

    Anyway if you prefer parameters, just put string value into local variable:

    var streetName = "Road";
    StreetRepository.Streets.Where(w => w.Streetname.Contains(streetName));