使用存储过程通过 "quotename" 防止 SQL 注入

Prevent SQL injection via "quotename" with stored procedure

我正在尝试编写一些代码 "sql-injection-proof"。我被建议使用 QUOTENAME.

这个有效:

select 'abc[]def'

它给出了与

相似的结果
select QUOTENAME('abc[]def')

然而,虽然以下工作:

exec sp_spaceused 'STMALOGqueue'

这不是:

exec sp_spaceused QUOTENAME('STMALOGqueue')

我收到一个恼人的错误:

Incorrect syntax near 'STMALOGqueue'

我试图从注入中证明的实际代码在某些 C# 中进行了硬编码。供参考:

string sp_spaceused = @"
drop table if exists #temp
create table #temp(name nvarchar(100), rows int, reserved nvarchar(100), data nvarchar(100), index_size nvarchar(100), unused nvarchar(100))

insert into #temp
exec sp_spaceused QUOTENAME('{0}')";

我正在使用 String.format 将相关的 table 名称插入到此字符串中,然后执行它。目前它不起作用

QUOTENAME('STMALOGqueue')结果存储到一个变量中并将其用于存储过程参数:

declare @test as varchar(100)

set @test = QUOTENAME('STMALOGqueue')

exec sp_spaceused @test

有效。