简体   繁体   中英

Can removing non-alphanumeric characters prevent SQL Injection

Imagine a simple query:

Declare @sql varchar(100)
Declare @table varchar(20)
Set @table = 'foo'
select @sql = 'select * from ' + @table 
exec(@sql)

This would work okay until someone changes @table to be something like 'sys.tables;drop table bar'

However I am wondering if @table had all non alpha-numeric characters removed from it, could SQL injection still occur? In this example the malicious @table would = 'systablesdroptablebar'.

Now I know using sp_executesql and parameterized SQL is the best practice. So don't give me any of that junk! I'm curious, how a string that removes all non alphanumeric characters could be compromised to deliver a SQL injection payload.

For clarity's sake this code block would be executed in Microsoft SQL Server 2008 or greater.

I don't have good examples of compromises for your case but I can tell you how I might attempt to defensively program against it...

  1. Consider Whitelisting table access

  2. Maybe you can restrict the access to a specific subset of tables. Ideally, these tables follow a common naming scheme so the table name can be validated against that scheme.

  3. If whitelisting the table names is not an option-- you could at least check whether the supplied table name is present in the database by querying the sys.tables system table.

  4. For SQL Server, you should put the table name in square brackets

SELECT COUNT(*) FROM [" + tableName + "]"

This resource on SQL injection would thoroughly answer your question: OWASP Cheat Sheet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM