How do I protect this function from SQL injection?

前端 未结 11 1190
独厮守ぢ
独厮守ぢ 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:10

    In this concrete example you need protection from SQL injection only if table name comes from external source.

    Why would you ever allow this to happen? If you are allowing some external entity (end user, other system, what?) to name a table to be dropped, why won't you just give them admin rights.

    If you are creating and removing tables to provide some functionality for end user, don't let them provide names for database objects directly. Apart from SQL injection, you'll have problems with name clashes etc. Instead generate real table names yourself (e.g DYNTABLE_00001, DYNTABLE_00002, ...) and keep a table that connects them to the names provided by user.


    Some notes on generating dynamic SQL for DDL operations:

    • In most RDBMS-s you'll have to use dynamic SQL and insert table names as text. Be extra careful.

    • Use quoted identifiers ([] in MS SQL Server, "" in all ANSI compliant RDBMS). This will make avoiding errors caused by invalid names easier.

    • Do it in stored procedures and check if all referenced objects are valid.

    • Do not do anything irreversible. E.g. don't drop tables automatically. You can flag them to be dropped and e-mail your DBA. She'll drop them after the backup.

    • Avoid it if you can. If you can't, do what you can to minimize rights to other (non-dynamic) tables that normal users will have.

提交回复
热议问题