1

I'm having a dynamically built SQL as below. My question is, is it vulnerable to SQL Injection? If yes, how should I fix it?

  --search title only    
 if @SearchType =2    
 BEGIN     
  SET @strSQL = @strSQL + 'AND  (IDownload.FileTitle LIKE ''%'+@Search+'%''  ) '    
END     
3
  • 3
    Yes, and it's fixable by using proper parameterisation for your dynamic SQL (e.g. using sp_executesql with @search as a parameter). Commented Jun 23, 2017 at 3:43
  • @ZLK what if my server side code (c#) is already using proper parameterisation & prepared statement, is my SQL Server code still vulnerable? Commented Jun 23, 2017 at 6:39
  • Yes, it's still vulnerable, because of the way the current statement is written. Commented Jun 25, 2017 at 10:32

1 Answer 1

1

Yes, check:

CREATE TABLE Test (Id int)
GO

CREATE TABLE IDownload (FileTitle nvarchar(100))

DECLARE @strSQL nvarchar(max)
DECLARE @Search nvarchar(max) = 'a'') DROP TABLE Test --'

SET @strSQL = 'SELECT 1 FROM IDownload WHERE 1 = 1 '

SET @strSQL = @strSQL + 'AND  (IDownload.FileTitle LIKE ''%'+@Search+'%''  ) '    

PRINT @strSQL
EXEC sp_executesql @strSQL

DROP TABLE IDownload

I can drop table Test passing special string in @Search. Rewrite your code using sp_executesql procedure and parameters.

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

1 Comment

But how should I rephrase the like statement to something which is SQL Injection proof? I've been looking over the internet and all the example seems to be similar as the one you have posted. I'm already using sp_executesql and paramdefinition in my code.

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.