Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# avoid SQL Injection in a function

I want to create a class that help SELECT , INSERT , UPDATE and DELETE in SQL server databases , but I've found by search that there is "sql injection" and the way to avoid it is to use a function like the following :

private static void Select() {
    string cmdStr = "SELECT FirstName, LastName, Telephone FROM Person WHERE FirstName = @FirstName";
    using (SqlConnection connection = new SqlConnection(ConnectionString))
    using (SqlCommand command = new SqlCommand(cmdStr, connection)) {
        command.Parameters.AddWithValue("@FirstName", "John");
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read()) {
            string output = "First Name: {0} \t Last Name: {1} \t Phone: {2}";
            Console.WriteLine(output, reader["FirstName"], reader["LastName"], reader["Telephone"]);
        }
    }
}

does the following function can have sql injection ?

  private static void SelectWithWhere(String query, String[] parameters)
        {

            {
                string cmdStr = "SELECT FirstName, LastName, Telephone FROM Person WHERE "+parameters[0];
                using (SqlConnection connection = new SqlConnection(ConnectionString))
                using (SqlCommand command = new SqlCommand(cmdStr, connection))
                {
                    command.Parameters.AddWithValue("@FirstName", parameters[0]);
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        string output = "First Name: {0} \t Last Name: {1} \t Phone: {2}";
                        Console.WriteLine(output, reader["FirstName"], reader["LastName"], reader["Telephone"]);
                    }
                }
            }
        }
like image 355
AndroLife Avatar asked Sep 23 '26 20:09

AndroLife


1 Answers

Each time you use an input provided by a user to generate an SQL statement, you open the door to SQL injection. The only way to avoid sql injection is by using parameters.

The first function is safe but the second one may be vulnerable to sql injection if you don't control the provided String[] parameters. If the user is providing the value for this array (directly or indirectly), he could pass an sql statement of it's own an execute basically anything he wants on your database.

like image 111
The_Black_Smurf Avatar answered Sep 26 '26 09:09

The_Black_Smurf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!