Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for handling SQL injections when calling a stored procedure

I have inherited code that I am fixing security holes up. What's the best practice for handling SQL injections when a stored procedure is called?

The code is something like:

StringBuilder sql = new StringBuilder("");

sql.Append(string.Format("Sp_MyStoredProc '{0}', {1}, {2}", sessionid, myVar, "0"));


using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
{
    cn.Open();
    using (SqlCommand command = new SqlCommand(sql.ToString(), cn))
    {
        command.CommandType = CommandType.Text;
        command.CommandTimeout = 10000;
        returnCode = (string)command.ExecuteScalar();
    }
}

I just do the same thing with a regular SQL query and add the parameters using AddParameter correct?

like image 456
cdub Avatar asked Dec 20 '22 09:12

cdub


1 Answers

Q. What's the Best practice for Handling SQL injections?

A. Use parameterised queries

example:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    // Create the command and set its properties.
    SqlCommand command = new SqlCommand();
    command.Connection = connection;
    command.CommandText = "SalesByCategory";
    command.CommandType = CommandType.StoredProcedure;

    // Add the input parameter and set its properties.
    SqlParameter parameter = new SqlParameter();
    parameter.ParameterName = "@CategoryName";
    parameter.SqlDbType = SqlDbType.NVarChar;
    parameter.Direction = ParameterDirection.Input;
    parameter.Value = categoryName;

    // Add the parameter to the Parameters collection.
    command.Parameters.Add(parameter);

    // Open the connection and execute the reader.
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    .
    .
    .
}
like image 129
Mitch Wheat Avatar answered Dec 28 '22 11:12

Mitch Wheat