Dynamic query as a parameter in stored procedure and SQL Injection

时间:2017-06-15 09:49:04

标签: asp.net sql-server stored-procedures sql-injection

I have the following stored procedure (modified for this post):

ALTER PROCEDURE [dbo].[SEL_ARTICLE](
@FILTER VARCHAR(8000) = ''
) AS
BEGIN

DECLARE @SQLQuery varchar(8000);

SET @SQLQuery = 'SELECT DISTINCT ArticleNo, desc, ...
FROM Article INNER JOIN
...
{0}
ORDER BY ArticleNo, ...';

SET @SQLQuery = REPLACE(@SQLQuery, '{0}', @FILTER);

EXEC(@SQLQuery);
END

I call this proc in my prog like this:

Public Function get_Article(ByVal strFilter As String) As DataTable
    Dim tblData As New DataTable
    Dim par As SqlParameter = New SqlParameter("@FILTER", SqlDbType.VarChar)        
    par.Value = strFilter
    Load_Data("SEL_ARTICLE", tblData, par) 'SqlCommand used
    Return tblData
End Function

The value of the parameter strFilter is dynamic (Fields, values) depending on what we search. Here is an example:

" AND ((Article = [input from User]) OR (Description LIKE '%[input from User]%'))"

The user must be able to enter the character ' (word in French) it is why I replace it server-side like this:

strFilter &= String.Format(" AND ((Article = {0}) OR (description LIKE '%{1}%'))", strArticleNo, strArticleName.Replace("'", "''"))

I prevent the user to enter the following characters: <,>,{,},;

Now my question: Is this code safe against SQL injection attacks ?

Thank you!

0 个答案:

没有答案