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


i generating dynamic sql , ensure code safe sql injection.

for sake of argument here minimal example of how generated:

var sql = string.format("insert {0} ({1}) values (@value)",     tablename, columnname); 

in above, tablename, columnname, , whatever bound @value come untrusted source. since placeholders being used @value safe sql injection attacks, , can ignored. (the command executed via sqlcommand.)

however, tablename , columnname cannot bound placeholders , therefor vulnerable injection attacks. since "truly dynamic" scenario, there no whitelist of tablename or columnname available.

the question thus:

is there standard, built-in way check and/or sanitize tablename , columnname? (sqlconnection, or helper class, etc.) if not, way perform task without using 3rd party library?

notes:

  • all sql identifiers, including schema, should accepted: e.g. [schema].[my table].column "safe" table1.
  • can either sanitize identifiers or detect invalid identifier. (it not need ensure table/column valid in context; resulting sql can invalid, must "safe".)

update:

just found this, , thought interesting: there sqlfunctions.quotename function in .net4 (ef4?). okay, doesn't really me here...

since using sqlconnection, assumption sql server database.

given assumption, validate table , field names using regular expression follows sql server identifier rules defined in msdn. while complete , utter novice @ regular expressions, did find 1 should come close:

[\p{l}{\p{nd}}$#_][\p{l}{\p{nd}}@$#_]* 

however, regular expression not address sql server keywords , not ensure table and/or column exists (although indicated wasn't of issue).

if application, first ensure end user not trying perform injection rejecting request contained semi-colons (;).

next, validate table existence removing valid name delimiters (", ', [, ]), splitting table name period see if schema specified, , executing query against information_schema.tables determine existence of table.

for example:

select 1    information_schema.tables   table_name = 'tablename'  ,    table_schema = 'tableschema' 

if create query using parameters, should further protect injection.

finally, validate existence of each column name performing similar set of steps, using information_schema.columns determine validity of column(s) once table has been determined valid.

i fetch list of valid columns table sql server, verify each request column in list within code. way tell columns in error , provide feedback user.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -