3

I have written a CLR stored procedure in C# like this

[Microsoft.SqlServer.Server.SqlProcedure]
public static void IsUserNameExists(string strUserName, out SqlBoolean returnValue)
{      
    using (SqlConnection connection = new SqlConnection("context connection=true"))
    {
        connection.Open();
        SqlCommand command = new SqlCommand("Select count(UserName) from [User] where UserName='" + strUserName + "'", connection);

        int nHowMany = int.Parse(command.ExecuteScalar().ToString());

        if (nHowMany > 0)
            returnValue = true;
        else
            returnValue = false;
    }
}

Is it vulnerable to SQL injection? I am using SqlParameter. Any best practises?

4

3 回答 3

3

防止 sql 注入的唯一正确方法应该是使用参数化查询。您正在做的事情并不安全,因为您正在连接字符串。

在此处查看以供参考参数化查询如何帮助防止 SQL 注入?

为了清楚起见,为什么您的代码易受攻击:
SQLParameter甚至类似的内容而言,这'); DROP TABLE YourTable;--将是一个有效的输入(因为它是一个字符串)。然后您将使用它来创建内部查询,这就是您的 SQL 注入。

于 2013-04-22T05:22:02.283 回答
1

它是否容易受到 SQL 注入的影响?

这是:

SomeType.IsUserNameExists("'; insert into [User](UserName) values ('Malefactor_Username'); select '1", out returnValue);

有什么最佳做法吗?

始终使用参数化查询。

于 2013-04-22T05:31:50.253 回答
0

默认情况下,CLR 存储过程不会阻止这种情况。您需要自己执行此操作,因为 CLR 不会自动执行此操作(我想这是您想知道的实际问题)

只需像这样更新您的代码,您应该一切都好。

 [Microsoft.SqlServer.Server.SqlProcedure]
    public static void IsUserNameExists(string strUserName, out SqlBoolean returnValue)
    {
        using (SqlConnection connection = new SqlConnection("context connection=true"))
        {
            connection.Open();
            SqlCommand command = new SqlCommand("Select count(UserName) from [User] where UserName=@UserName", connection);
            command.Parameters.Add(new SqlParameter("@UserName", strUserName));

            int nHowMany = int.Parse(command.ExecuteScalar().ToString());

            if (nHowMany > 0)
                returnValue = true;
            else
                returnValue = false;
        }
    }
于 2013-04-22T10:40:48.287 回答