Sanitize table/column name in Dynamic SQL in .NET? (Prevent SQL injection attacks)

前端 未结 3 1098
误落风尘
误落风尘 2020-11-29 12:34

I am generating some Dynamic SQL and would like to ensure that my code is safe from SQL injection.

For sake of argument here is a minimal example of how it is genera

3条回答
  •  独厮守ぢ
    2020-11-29 12:41

    I'm not sure if you're still looking into this, but the DbCommandBuilder class provides a method QuoteIdentifier for this purpose. The main benefits of this are that it's database-independent and doesn't involve any RegEx mess.

    As of .NET 4.5, you have everything you need to sanitize table and column names just using your DbConnection object:

    DbConnection connection = GetMyConnection(); // Could be SqlConnection
    DbProviderFactory factory = DbProviderFactories.GetFactory(connection);
    
    // Sanitize the table name
    DbCommandBuilder commandBuilder = factory.CreateCommandBuilder();
    
    string tableName = "This Table Name Is Long And Bad";
    string sanitizedTableName = commandBuilder.QuoteIdentifier(tableName);
    
    IDbCommand command = connection.CreateCommand();
    command.CommandText = "SELECT * FROM " + sanitizedTableName;
    
    // Becomes 'SELECT * FROM [This Table Name Is Long And Bad]' in MS-SQL,
    // 'SELECT * FROM "This Table Name Is Long And Bad"' in Oracle, etc.
    

    (Pre-4.5, you'll need some other way to get your DbProviderFactory -- maybe from the data provider name in your application configuration or hard-coded somewhere.)

提交回复
热议问题