How do I protect this function from SQL injection?

前端 未结 11 1188
独厮守ぢ
独厮守ぢ 2020-12-16 18:47
public static bool TruncateTable(string dbAlias, string tableName)
{
    string sqlStatement = string.Format(\"TRUNCATE TABLE {0}\", tableName);
    return ExecuteNo         


        
11条回答
  •  一生所求
    2020-12-16 19:01

    The most common recommendation to fight SQL injection is to use an SQL query parameter (several people on this thread have suggested it).

    This is the wrong answer in this case. You can't use an SQL query parameter for a table name in a DDL statement.

    SQL query parameters can be used only in place of a literal value in an SQL expression. This is standard in every implementation of SQL.

    My recommendation for protecting against SQL injection when you have a table name is to validate the input string against a list of known table names.

    You can get a list of valid table names from the INFORMATION_SCHEMA:

    SELECT table_name 
    FROM INFORMATION_SCHEMA.Tables 
    WHERE table_type = 'BASE TABLE'
      AND table_name = @tableName
    

    Now you can pass your input variable to this query as an SQL parameter. If the query returns no rows, you know that the input is not valid to use as a table. If the query returns a row, it matched, so you have more assurance you can use it safely.

    You could also validate the table name against a list of specific tables you define as okay for your app to truncate, as @John Buchanan suggests.

    Even after validating that tableName exists as a table name in your RDBMS, I would also suggest delimiting the table name, just in case you use table names with spaces or special characters. In Microsoft SQL Server, the default identifier delimiters are square brackets:

    string sqlStatement = string.Format("TRUNCATE TABLE [{0}]", tableName);
    

    Now you're only at risk for SQL injection if tableName matches a real table, and you actually use square brackets in the names of your tables!

提交回复
热议问题