什么函数在SQL Server的dynamic-sql中引用标识符?


11

用于动态sql生成的SQL Server安全引用标识符的方法是什么。

如何确保给定动态生成的语句的动态生成的列名称,该列本身不是SQL注入攻击。

假设我有一条SQL语句,

SELECT [$col] FROM table;

基本上与

'SELECT [' + $col + '] FROM table;'

什么阻止了注射攻击

$col = "name] FROM sys.objects; \r\n DROP TABLE my.accounts; \r\n\ --";

导致

SELECT [name] FROM sys.objects;
DROP TABLE my.accounts;
-- ] FROM table;

Answers:


14

您要寻找的功能是QUOTENAME

通过实际使用方括号技术,您可以安全地封装字符串以帮助防止热SQL注入攻击。

请注意,虽然可以避免对象名称中的无效字符导致代码错误,但仅在某些内容周围加上方括号并不能安全地将其引出。

好代码

DECLARE @sql NVARCHAR(MAX) = N''
SELECT @sql = 'SELECT ' + QUOTENAME(d.name) + ' FROM your_mom'
FROM sys.databases AS d

错误的代码

DECLARE @sql NVARCHAR(MAX) = N''
SELECT @sql = 'SELECT [' + d.name + '] FROM your_mom'
FROM sys.databases AS d

举一个具体的例子...

以下内容适用于初始输入

DECLARE @ObjectName SYSNAME = 'sysobjects';

DECLARE @dynSql NVARCHAR(MAX) = 'SELECT COUNT(*) FROM [' + @ObjectName + ']';

EXEC (@dynSql);

但是通过恶意输入,它很容易受到SQL注入的攻击

DECLARE @ObjectName SYSNAME = 'sysobjects];SELECT ''This is some arbitrary code executed. It might have dropped a table or granted permissions''--'

DECLARE @dynSql NVARCHAR(MAX) = 'SELECT  COUNT(*)  FROM [' + @ObjectName + ']';

EXEC (@dynSql);

使用QUOTENAME正确会逃避嵌入,]并防止发生尝试的SQL注入。

DECLARE @ObjectName SYSNAME = 'sysobjects];SELECT ''This is some arbitrary code executed. It might have dropped a table or granted permissions''--'

DECLARE @dynSql NVARCHAR(MAX) = 'SELECT  COUNT(*)  FROM ' + QUOTENAME(@ObjectName);

EXEC (@dynSql);

无效的对象名称'sysobjects]; SELECT'这是一些执行的任意代码。它可能已删除表或授予了权限“-”。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.