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

前端 未结 3 1099
误落风尘
误落风尘 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:57

    Since you are using an SqlConnection, the assumption is that this is an SQL Server database.

    Given that assumption, you could validate the table and field names using a regular expression that follows the SQL Server identifier rules as defined in MSDN. While I am a complete and utter novice at regular expressions, I did find this one that should come close:

    [\p{L}{\p{Nd}}$#_][\p{L}{\p{Nd}}@$#_]*
    

    However, a regular expression will not address SQL Server keywords and it does not ensure that the table and/or column actually exists (although you indicated that wasn't much of an issue).

    If this were my application, I would first ensure the end user was not trying to perform injection by rejecting any request that contained semi-colons (;).

    Next, I would validate the table existence by removing the valid name delimiters (", ', [, ]), splitting the table name by a period to see if a schema was specified, and executing a query against INFORMATION_SCHEMA.TABLES to determine the existence of the table.

    For example:

    SELECT 1 
    FROM   INFORMATION_SCHEMA.TABLES 
    WHERE  TABLE_NAME = 'tablename' 
    AND    TABLE_SCHEMA = 'tableschema'
    

    If you create this query using parameters, then you should further protect yourself from injection.

    Finally, I would validate the existence of each column name by performing a similar set of steps, only using INFORMATION_SCHEMA.COLUMNS to determine the validity of the column(s) once the table has been determined to be valid.

    I would probably fetch the list of valid columns for this table from SQL Server, then verify that each request column was in the list within my code. That way you could tell exactly which columns were in error and provide that feedback to the user.

提交回复
热议问题