How to get CA2100 SQL injection warning in calling methods

240 Views Asked by At

I have a helper method to prevent a lot of copy and paste. I want to make sure calling methods of my helper method "MyExecuteSQLQuery" will be checked against rule "CA2100: Review SQL queries for security vulnerabilities". How can I achieve that?

So in other words, i want to get a CA2100 warning for something like that:

MyExecuteSQLQuery("update credentials set password = '" + password +"' where id = " + id);

Helper method:

public static int MyExecuteSQLQuery(string sql, int timeout = 30)
{
    using (MySqlConnection con = new MySqlConnection(DBConnectionstring))
    {
        con.Open();
        using (MySqlCommand cmd = new MySqlCommand(sql, con))
        {
            if (timeout != 30)
            {
                cmd.CommandTimeout = timeout;
            }

            return cmd.ExecuteNonQuery();
        }
    }
}
1

There are 1 best solutions below

1
ste-fu On

I don't think that's a very good idea. I imagine that it's possible to add your method to an analyser, but it is probably easier to refactor your method to take a MySqlCommand instead, maybe something like this:

public static int MyExecuteSQLQuery(MySqlCommand cmd, int timeout = 30)
{
    using (MySqlConnection con = new MySqlConnection(DBConnectionstring))
    {
        con.Open();
        cmd.CommandTimeout = timeout;
        
        return cmd.ExecuteNonQuery();
    }
}

}

And then you would get your error/warning when you construct your MySqlCommand