Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a SQL CLR stored procedure prevent injection?

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?

like image 569
Nest Avatar asked Dec 18 '25 04:12

Nest


1 Answers

The only correct way to prevent sql injection should be using parameterized queries. What you are doing is not safe, since you are concatenating strings.

Look into this here for reference How do parameterized queries help against SQL injection?

For clearification, why your code is vulnerable:
In terms of SQLParameter even something like '); DROP TABLE YourTable;-- will be a valid input (since it is a string). This will then be used by you to create the inner query and there's your SQL-Injection.

like image 54
TGlatzer Avatar answered Dec 19 '25 22:12

TGlatzer