prevent-sql-injection

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Prevent SQL injection: the value, the identifier, and the context it runs under

防止 SQL 注入:值、标识符及其执行上下文

Parameterising a value is the familiar part. Confirm it in a sentence and spend the answer on what a parameter cannot reach: an identifier, the type of a runtime-chosen sort expression, the permissions a dynamic batch runs under, and an encrypted column. The behavior below is Azure SQL Database's.
对值进行参数化是大家熟悉的部分。用一句话确认即可,本文重点讨论参数无法触及的内容:标识符、运行时选择的排序表达式的类型、动态批处理运行时的权限,以及加密列。以下行为均基于 Azure SQL Database。

1. A parameter is a value, a concatenation is code, and one query shows the difference

1. 参数是值,拼接是代码,一条查询即可看出区别

Do not assert this. Run it. Both statements get the same string.
sql
CREATE TABLE dbo.Users (id int NOT NULL PRIMARY KEY, name nvarchar(50) NOT NULL);
INSERT INTO dbo.Users (id, name) VALUES (1, N'ann'), (2, N'bob');

DECLARE @input nvarchar(100) = N'ann'' OR 1=1--';

-- Typed parameter: the input is one value, and no row holds it. Returns 0.
EXEC sp_executesql N'SELECT COUNT(*) AS matched FROM dbo.Users WHERE name = @n',
                   N'@n nvarchar(100)', @n = @input;

-- Same input concatenated: the input is now part of the statement. Returns 2.
DECLARE @sql nvarchar(max) =
        N'SELECT COUNT(*) AS matched FROM dbo.Users WHERE name = N''' + @input + N'''';
EXEC (@sql);  -- vulnerable on purpose: do not copy
Zero against two, from one string. Learn's rule for
@params
is the discipline in one line: values can only be constants or variables, never expressions built with operators.
不要凭空断言这一点。运行一下。两个语句接收到的都是同一个字符串。
sql
CREATE TABLE dbo.Users (id int NOT NULL PRIMARY KEY, name nvarchar(50) NOT NULL);
INSERT INTO dbo.Users (id, name) VALUES (1, N'ann'), (2, N'bob');

DECLARE @input nvarchar(100) = N'ann'' OR 1=1--';

-- Typed parameter: the input is one value, and no row holds it. Returns 0.
EXEC sp_executesql N'SELECT COUNT(*) AS matched FROM dbo.Users WHERE name = @n',
                   N'@n nvarchar(100)', @n = @input;

-- Same input concatenated: the input is now part of the statement. Returns 2.
DECLARE @sql nvarchar(max) =
        N'SELECT COUNT(*) AS matched FROM dbo.Users WHERE name = N''' + @input + N'''';
EXEC (@sql);  -- vulnerable on purpose: do not copy
同一个字符串,结果却是 0 对 2。Learn 对
@params
的规则可以概括为一句话:值只能是常量或变量,绝不能是由运算符构建的表达式。

2. No parameter binds an identifier, and QUOTENAME returns NULL past 128 characters

2. 没有参数能够绑定标识符,而且 QUOTENAME 在超过 128 个字符时返回 NULL

EXEC sp_executesql N'SELECT * FROM @t', N'@t sysname', @t = @name
cannot work:
@t
is a value, not a table. A dynamic identifier has to enter the SQL text, so
QUOTENAME
's documented edges are load bearing. Its input,
character_string
, is sysname:
  • Up to 128 characters,
    QUOTENAME
    returns the name in brackets. An embedded
    ]
    is doubled correctly, so escaping is not the defect.
  • Over 128 characters,
    QUOTENAME
    returns
    NULL
    . It does not truncate the name and it raises no error. An unacceptable quote character also returns
    NULL
    .
  • A
    NULL
    concatenated into a batch makes the whole batch
    NULL
    , and executing a
    NULL
    batch does nothing and reports nothing. The long name is not rejected; the statement silently does not run.
sql
DECLARE @n129 nvarchar(200) = REPLICATE(N'a', 129);
SELECT LEN(QUOTENAME(REPLICATE(N'a', 128)))       AS len_at_128,      -- 130
       IIF(QUOTENAME(@n129) IS NULL, 1, 0)        AS null_at_129,     -- 1
       IIF(QUOTENAME(N'tbl', N'#') IS NULL, 1, 0) AS null_bad_quote;  -- 1

DECLARE @sql nvarchar(max) = N'SELECT * FROM ' + QUOTENAME(@n129);
EXEC sp_executesql @sql;
SELECT IIF(@sql IS NULL, 1, 0) AS batch_was_null, @@ERROR AS err;     -- 1, 0
EXEC (@sql)
on the same
NULL
behaves identically: this is the
NULL
batch, not one calling convention. Nothing reports it at any severity:
bash
sqlcmd -S <server-name>.database.windows.net,1433 -d <database> -U <user> -C -b -m-1 \
  -Q "DECLARE @s nvarchar(max)=N'SELECT 1 FROM '+QUOTENAME(REPLICATE(N'x',129)); EXEC sp_executesql @s; SELECT @@ERROR AS err;"
-b
exits non-zero at severity 11 and above and
-m-1
lowers the print level, but there is no message at any level:
err
is 0 and so is the exit code. The
NULL
has to be the check.
Neither helper checks that the object exists.
QUOTENAME
brackets a string and
PARSENAME
splits a qualified name; Learn says each part is sysname, a part over 256 bytes comes back
NULL
, and it does not indicate whether an object of that name exists. Only a catalog lookup decides existence, so resolve the caller's string against the catalog and build from what it returned:
sql
DECLARE @requested nvarchar(400) = N'dbo.Users', @safe nvarchar(300);
SELECT @safe = QUOTENAME(s.name) + N'.' + QUOTENAME(o.name)
FROM sys.objects AS o JOIN sys.schemas AS s ON s.schema_id = o.schema_id
WHERE s.name = PARSENAME(@requested, 2) AND o.name = PARSENAME(@requested, 1) AND o.type = 'U';
IF @safe IS NULL THROW 50001, 'No row in the catalog matched that name.', 1;

DECLARE @sql nvarchar(max) = N'SELECT COUNT(*) AS n FROM ' + @safe;
EXEC sp_executesql @sql;
In this pattern an over-long name never reaches
QUOTENAME
, which only brackets names read back from the catalog. The lookup matches no row, because no catalog name is longer than 128 characters, so
@safe
stays
NULL
and the
THROW
raises error 50001. The long name is rejected with an error by the lookup, instead of turning into a silent
NULL
batch at
QUOTENAME
. Where the legal identifiers are known in advance, an allowlist is simpler.
EXEC sp_executesql N'SELECT * FROM @t', N'@t sysname', @t = @name
无法奏效:
@t
是值,而不是表。动态标识符必须进入 SQL 文本,因此 QUOTENAME 有文档记载的边界条件至关重要。它的输入
character_string
是 sysname:
  • 不超过 128 个字符时,QUOTENAME 返回带方括号括起来的名称。嵌入的
    ]
    会被正确地重复一次,因此问题并不在转义上。
  • 超过 128 个字符时,QUOTENAME 返回
    NULL
    。它不会截断名称,也不会引发错误。不可接受的引号字符同样会返回
    NULL
    。
  • 拼接到批处理中的
    NULL
    会使整个批处理变为
    NULL
    ,而执行
    NULL
    批处理既不会执行任何操作,也不会报告任何信息。这个长名称并未被拒绝;语句只是悄无声息地没有运行。
sql
DECLARE @n129 nvarchar(200) = REPLICATE(N'a', 129);
SELECT LEN(QUOTENAME(REPLICATE(N'a', 128)))       AS len_at_128,      -- 130
       IIF(QUOTENAME(@n129) IS NULL, 1, 0)        AS null_at_129,     -- 1
       IIF(QUOTENAME(N'tbl', N'#') IS NULL, 1, 0) AS null_bad_quote;  -- 1

DECLARE @sql nvarchar(max) = N'SELECT * FROM ' + QUOTENAME(@n129);
EXEC sp_executesql @sql;
SELECT IIF(@sql IS NULL, 1, 0) AS batch_was_null, @@ERROR AS err;     -- 1, 0
对同一个
NULL
使用
EXEC (@sql)
时,行为完全相同:这是
NULL
批处理的问题,而不是某一种调用约定的问题。任何严重级别都不会报告它:
bash
sqlcmd -S <server-name>.database.windows.net,1433 -d <database> -U <user> -C -b -m-1 \
  -Q "DECLARE @s nvarchar(max)=N'SELECT 1 FROM '+QUOTENAME(REPLICATE(N'x',129)); EXEC sp_executesql @s; SELECT @@ERROR AS err;"
-b
会在严重级别 11 及以上时以非零状态退出,
-m-1
会降低打印级别,但这里任何级别都没有消息:
err
为 0,退出代码也是 0。因此必须显式检查
NULL
。
两个辅助函数都不会检查对象是否存在。 QUOTENAME 为字符串添加方括号,PARSENAME 拆分限定名称;Learn 指出每个组成部分都是 sysname,超过 256 字节的部分会返回
NULL
,而且它不会指出是否存在同名对象。只有目录查询才能确定对象是否存在,因此应将调用方传入的字符串与目录进行匹配,并基于返回结果构建 SQL:
sql
DECLARE @requested nvarchar(400) = N'dbo.Users', @safe nvarchar(300);
SELECT @safe = QUOTENAME(s.name) + N'.' + QUOTENAME(o.name)
FROM sys.objects AS o JOIN sys.schemas AS s ON s.schema_id = o.schema_id
WHERE s.name = PARSENAME(@requested, 2) AND o.name = PARSENAME(@requested, 1) AND o.type = 'U';
IF @safe IS NULL THROW 50001, 'No row in the catalog matched that name.', 1;

DECLARE @sql nvarchar(max) = N'SELECT COUNT(*) AS n FROM ' + @safe;
EXEC sp_executesql @sql;
在这种模式中,过长的名称永远不会到达 QUOTENAME,后者只会为从目录读取回来的名称添加方括号。由于目录中没有任何名称超过 128 个字符,查询不会匹配到任何行,因此
@safe
会保持为
NULL
,而
THROW
将引发错误 50001。过长名称会由目录查询报错拒绝,而不是在 QUOTENAME 处变成一个悄无声息的
NULL
批处理。如果合法标识符预先已知,使用 allowlist 会更简单。

3. One CASE over mixed types in a dynamic ORDER BY fails for some sort keys and not others

3. 在动态 ORDER BY 中使用一个 CASE 覆盖混合类型时,某些排序键会失败,而其他排序键不会

A single
CASE
forces every branch to one common type chosen by type precedence, not by the branch the sort key selects. On
dbo.T (i int, d date, s nvarchar(50))
:
Branchessort key selectsResult
THEN i
/
THEN d
anything, including neither
Msg 206
, operand type clash, int against date
THEN s
/
THEN d
d
, the higher-precedence side
runs clean
THEN s
/
THEN d
s
, the lower-precedence side
Msg 241
, conversion failed from character string
THEN i
/
THEN s
s
, the lower-precedence side
Msg 245
, conversion failed converting nvarchar to int
int
and
date
have no implicit conversion, so that pairing is refused at compile time and a surrounding
BEGIN TRY
does not catch it. The string pairings are the sharper trap: the identical statement passes for one sort key and fails for another, so it survives a test against whichever column the author tried. One
CASE
per candidate column, each carrying a single type, has no common type to coerce toward; non-matching columns evaluate to
NULL
and tie, so this composes with
OFFSET
/
FETCH
and a direction toggle:
sql
DECLARE @col sysname = N'created', @dir char(1) = N'A';
SELECT id, name, created FROM dbo.Grid
ORDER BY CASE WHEN @col = N'id'      AND @dir = N'A' THEN id      END ASC,
         CASE WHEN @col = N'id'      AND @dir = N'D' THEN id      END DESC,
         CASE WHEN @col = N'created' AND @dir = N'A' THEN created END ASC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;
单个 CASE 会依据类型优先级,将所有分支强制转换为一种公共类型,而不是根据排序键选择的分支决定类型。对于
dbo.T (i int, d date, s nvarchar(50))
:
分支排序键选择结果
THEN i
/
THEN d
任意项,包括两者均未选择
Msg 206
,操作数类型冲突:int 与 date
THEN s
/
THEN d
d
,优先级较高的一侧
正常运行
THEN s
/
THEN d
s
,优先级较低的一侧
Msg 241
,从字符字符串转换失败
THEN i
/
THEN s
s
,优先级较低的一侧
Msg 245
,将 nvarchar 转换为 int 时失败
int
与
date
之间没有隐式转换,因此这种组合会在编译期被拒绝,外围的
BEGIN TRY
也无法捕获。字符串组合的陷阱更隐蔽:完全相同的语句对于一个排序键可以通过,对另一个排序键却会失败,所以即便只针对作者尝试过的列进行测试,它也能躲过测试。为每个候选列分别使用一个
CASE
,并让每个
CASE
只包含单一类型,就不存在需要强制转换的公共类型;未匹配的列会求值为
NULL
并被视为并列,因此这种方式可与
OFFSET
/
FETCH
以及方向切换组合使用:
sql
DECLARE @col sysname = N'created', @dir char(1) = N'A';
SELECT id, name, created FROM dbo.Grid
ORDER BY CASE WHEN @col = N'id'      AND @dir = N'A' THEN id      END ASC,
         CASE WHEN @col = N'id'      AND @dir = N'D' THEN id      END DESC,
         CASE WHEN @col = N'created' AND @dir = N'A' THEN created END ASC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;

4. Dynamic SQL breaks the ownership chain, so EXECUTE AS is part of the answer

4. 动态 SQL 会中断所有权链,因此 EXECUTE AS 是解决方案的一部分

Learn: dynamic SQL in procedural code breaks the ownership chain, so the engine checks the caller's permissions against every object the statement touches. A procedure a caller could run yesterday stops working the day its query becomes dynamic, and parameterising does not bring it back.
sql
CREATE TABLE dbo.Ledger (id int NOT NULL PRIMARY KEY);
INSERT INTO dbo.Ledger (id) VALUES (1);
CREATE USER app_reader WITHOUT LOGIN;
GO
CREATE PROCEDURE dbo.CountLedgerDynamic AS
  EXEC sp_executesql N'SELECT COUNT(*) AS n FROM dbo.Ledger';
GO
CREATE PROCEDURE dbo.CountLedgerAsOwner WITH EXECUTE AS OWNER AS
  EXEC sp_executesql N'SELECT COUNT(*) AS n, CURRENT_USER AS running_as FROM dbo.Ledger';
GO
GRANT EXECUTE ON dbo.CountLedgerDynamic TO app_reader;
GRANT EXECUTE ON dbo.CountLedgerAsOwner TO app_reader;
GO
EXECUTE AS USER = 'app_reader';
EXEC dbo.CountLedgerDynamic;   -- Msg 229, SELECT permission denied on 'Ledger'
EXEC dbo.CountLedgerAsOwner;   -- 1, dbo
REVERT;
Learn names two remedies.
EXECUTE AS
replaces the caller's permissions for the whole module, nested modules inherit the proxy context, and the identity functions report the proxy, which is what
running_as
returning
dbo
shows, so anything keyed to the caller must arrive as a parameter. Certificate signing merges the certificate user's permissions with the caller's and leaves the execution context alone, at the cost of re-signing on every change. Open
rls-multi-tenant
before putting
EXECUTE AS
on a module touching a table under a security policy: the proxy context is what a tenant predicate reads. Neither remedy substitutes for parameterising.
Learn 指出:过程代码中的动态 SQL 会中断所有权链,因此引擎会针对语句访问的每个对象检查调用方的权限。调用方昨天还能运行的存储过程,可能在查询改为动态 SQL 的当天就无法工作,而参数化并不能恢复原来的权限链。
sql
CREATE TABLE dbo.Ledger (id int NOT NULL PRIMARY KEY);
INSERT INTO dbo.Ledger (id) VALUES (1);
CREATE USER app_reader WITHOUT LOGIN;
GO
CREATE PROCEDURE dbo.CountLedgerDynamic AS
  EXEC sp_executesql N'SELECT COUNT(*) AS n FROM dbo.Ledger';
GO
CREATE PROCEDURE dbo.CountLedgerAsOwner WITH EXECUTE AS OWNER AS
  EXEC sp_executesql N'SELECT COUNT(*) AS n, CURRENT_USER AS running_as FROM dbo.Ledger';
GO
GRANT EXECUTE ON dbo.CountLedgerDynamic TO app_reader;
GRANT EXECUTE ON dbo.CountLedgerAsOwner TO app_reader;
GO
EXECUTE AS USER = 'app_reader';
EXEC dbo.CountLedgerDynamic;   -- Msg 229, SELECT permission denied on 'Ledger'
EXEC dbo.CountLedgerAsOwner;   -- 1, dbo
REVERT;
Learn 给出了两种补救方式。
EXECUTE AS
会在整个模块内替换调用方的权限,嵌套模块会继承代理上下文,身份函数也会报告代理身份;
running_as
返回
dbo
正是这一点的体现,因此任何以调用方身份为依据的内容都必须通过参数传入。证书签名会将证书用户的权限与调用方权限合并,同时保持执行上下文不变,代价是每次变更后都必须重新签名。在对访问安全策略所涵盖表的模块使用
EXECUTE AS
前,请先打开
rls-multi-tenant
:租户谓词读取的是代理上下文。这两种补救方式都不能取代参数化。

5. On an Always Encrypted column a literal does not run at all

5. 在 Always Encrypted 列上,字面量根本无法运行

Learn lists it under Always Encrypted's limitations: comparing an encrypted column to a literal, or inserting one, fails with
Msg 206, Level 16, State 2, Operand type clash
. Only a value bound as a parameter over a connection with
Column Encryption Setting=Enabled
is encrypted before it leaves the driver, so parameterising is the only thing that returns a row.
Learn 将其列为 Always Encrypted 的限制之一:将加密列与字面量比较,或向加密列插入字面量,都会因
Msg 206, Level 16, State 2, Operand type clash
而失败。只有在启用了
Column Encryption Setting=Enabled
的连接上以参数绑定的值,才会在离开驱动程序之前完成加密,因此参数化是唯一能够返回结果行的方式。

Check it worked

检查是否生效

sql
-- Every module that builds SQL, and the context it runs under. A NULL principal id means the
-- caller's permissions apply to whatever the dynamic statement touches.
SELECT o.name, m.execute_as_principal_id
FROM sys.sql_modules AS m JOIN sys.objects AS o ON o.object_id = m.object_id
WHERE m.definition LIKE N'%sp_executesql%' OR m.definition LIKE N'%EXECUTE (%';
sql
-- No dynamic batch executes while NULL. Expect the rejection, not zero rows.
DECLARE @batch nvarchar(max) = N'SELECT * FROM ' + QUOTENAME(REPLICATE(N'x', 129));
IF @batch IS NULL SELECT 'rejected before execution' AS result ELSE EXEC sp_executesql @batch;
Then re-run section 1's pair against the real table: parameterised matches zero rows, concatenated every row. Run the generated
ORDER BY
once per sort key a caller may send, not only the one tested: any raising
Msg 206
,
241
or
245
means a mixed-type
CASE
is still there.
sql
-- Every module that builds SQL, and the context it runs under. A NULL principal id means the
-- caller's permissions apply to whatever the dynamic statement touches.
SELECT o.name, m.execute_as_principal_id
FROM sys.sql_modules AS m JOIN sys.objects AS o ON o.object_id = m.object_id
WHERE m.definition LIKE N'%sp_executesql%' OR m.definition LIKE N'%EXECUTE (%';
sql
-- No dynamic batch executes while NULL. Expect the rejection, not zero rows.
DECLARE @batch nvarchar(max) = N'SELECT * FROM ' + QUOTENAME(REPLICATE(N'x', 129));
IF @batch IS NULL SELECT 'rejected before execution' AS result ELSE EXEC sp_executesql @batch;
然后针对真实表重新运行第 1 节中的两个语句:参数化语句匹配零行,拼接语句匹配所有行。对于调用方可能传入的每个排序键,都要运行一次生成的
ORDER BY
,而不能只测试其中一个:任何出现
Msg 206
、
241
或
245
的情况都意味着混合类型
CASE
仍然存在。

Do not

请勿

  • Do not present
    QUOTENAME
    as sufficient for a caller-supplied identifier without checking its result for
    NULL
    , and do not say it truncates a long name or raises an error for one. It returns
    NULL
    , and nothing reports it.
  • Do not say either helper checks that an object exists. Neither reads the catalog.
  • Do not build a caller-chosen
    ORDER BY
    from one
    CASE
    spanning columns of different types, even when the columns tried in testing share a type.
  • Do not add
    WITH EXECUTE AS OWNER
    to clear a permission error without saying what the module can now reach and that the caller's identity is no longer visible inside it.
  • Do not tell a developer an agent-composed statement is made safe by parameterising the one value inside it. The model authored the whole statement, so the control is the permission boundary its connection runs under.
  • Do not warn about
    xp_cmdshell
    , linked servers or
    OPENROWSET
    against arbitrary providers. None exist on Azure SQL Database to escalate to.
  • 不要将 QUOTENAME 描述为:在没有检查其结果是否为
    NULL
    的情况下,它足以保护调用方提供的标识符;也不要声称它会截断过长名称或为过长名称引发错误。它返回
    NULL
    ,而且不会报告任何信息。
  • 不要声称任一辅助函数会检查对象是否存在。它们都不会读取目录。
  • 不要用一个跨越不同类型列的
    CASE
    来构建调用方选择的
    ORDER BY
    ,即使测试过的列类型相同也不行。
  • 不要为了消除权限错误而直接添加
    WITH EXECUTE AS OWNER
    ,却不说明该模块现在可以访问什么,也不说明调用方身份在模块内部已不可见。
  • 不要告诉开发者,只需对 agent 生成的语句中唯一一个值进行参数化,就能保证整个语句安全。模型编写了整个语句,因此真正的控制边界是其连接运行时所具有的权限边界。
  • 不要警告在 Azure SQL Database 上使用
    xp_cmdshell
    、linked servers 或
    OPENROWSET
    访问任意提供程序所带来的风险。它们在 Azure SQL Database 中并不存在,无法借此提升权限。

References

参考资料

  • Open the runnable checks when a claim above disagrees with what you see, or to look up the message a column-type pairing produces.
  • Microsoft Learn, if a number above looks stale: QUOTENAME, PARSENAME, secure dynamic SQL.
  • 当上述说法与你观察到的结果不一致时,或需要查看某个列类型组合产生的消息时,请打开可运行的检查。
  • 如果上述数字看起来已经过时,请查阅 Microsoft Learn: QUOTENAME、 PARSENAME、 安全动态 SQL。