prevent-sql-injection
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePrevent 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 copyZero against two, from one string. Learn's rule for is the discipline in one line: values
can only be constants or variables, never expressions built with operators.
@params不要凭空断言这一点。运行一下。两个语句接收到的都是同一个字符串。
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 对 的规则可以概括为一句话:值只能是常量或变量,绝不能是由运算符构建的表达式。
@params2. 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@tQUOTENAMEcharacter_string- Up to 128 characters, returns the name in brackets. An embedded
QUOTENAMEis doubled correctly, so escaping is not the defect.] - Over 128 characters, returns
QUOTENAME. It does not truncate the name and it raises no error. An unacceptable quote character also returnsNULL.NULL - A concatenated into a batch makes the whole batch
NULL, and executing aNULLbatch does nothing and reports nothing. The long name is not rejected; the statement silently does not run.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, 0EXEC (@sql)NULLNULLbash
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-m-1errNULLNeither helper checks that the object exists. brackets a string and
splits a qualified name; Learn says each part is sysname, a part over 256 bytes comes back
, 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:
QUOTENAMEPARSENAMENULLsql
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 , which only brackets names read back
from the catalog. The lookup matches no row, because no catalog name is longer than 128 characters,
so stays and the raises error 50001. The long name is rejected with an error
by the lookup, instead of turning into a silent batch at . Where the legal
identifiers are known in advance, an allowlist is simpler.
QUOTENAME@safeNULLTHROWNULLQUOTENAMEEXEC sp_executesql N'SELECT * FROM @t', N'@t sysname', @t = @name@tcharacter_string- 不超过 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对同一个 使用 时,行为完全相同:这是 批处理的问题,而不是某一种调用约定的问题。任何严重级别都不会报告它:
NULLEXEC (@sql)NULLbash
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-m-1errNULL两个辅助函数都不会检查对象是否存在。 QUOTENAME 为字符串添加方括号,PARSENAME 拆分限定名称;Learn 指出每个组成部分都是 sysname,超过 256 字节的部分会返回 ,而且它不会指出是否存在同名对象。只有目录查询才能确定对象是否存在,因此应将调用方传入的字符串与目录进行匹配,并基于返回结果构建 SQL:
NULLsql
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 个字符,查询不会匹配到任何行,因此 会保持为 ,而 将引发错误 50001。过长名称会由目录查询报错拒绝,而不是在 QUOTENAME 处变成一个悄无声息的 批处理。如果合法标识符预先已知,使用 allowlist 会更简单。
@safeNULLTHROWNULL3. One CASE over mixed types in a dynamic ORDER BY fails for some sort keys and not others
3. 在动态 ORDER BY 中使用一个 CASE 覆盖混合类型时,某些排序键会失败,而其他排序键不会
A single forces every branch to one common type chosen by type precedence, not by the branch
the sort key selects. On :
CASEdbo.T (i int, d date, s nvarchar(50))| Branches | sort key selects | Result |
|---|---|---|
| anything, including neither | |
| | runs clean |
| | |
| | |
intdateBEGIN TRYCASENULLOFFSETFETCHsql
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))| 分支 | 排序键选择 | 结果 |
|---|---|---|
| 任意项,包括两者均未选择 | |
| | 正常运行 |
| | |
| | |
intdateBEGIN TRYCASECASENULLOFFSETFETCHsql
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. 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
returning 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 before
putting on a module touching a table under a security policy: the proxy context is what
a tenant predicate reads. Neither remedy substitutes for parameterising.
EXECUTE ASrunning_asdborls-multi-tenantEXECUTE ASLearn 指出:过程代码中的动态 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 ASrunning_asdboEXECUTE ASrls-multi-tenant5. 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 . Only a value bound as a
parameter over a connection with is encrypted before it leaves
the driver, so parameterising is the only thing that returns a row.
Msg 206, Level 16, State 2, Operand type clashColumn Encryption Setting=EnabledLearn 将其列为 Always Encrypted 的限制之一:将加密列与字面量比较,或向加密列插入字面量,都会因 而失败。只有在启用了 的连接上以参数绑定的值,才会在离开驱动程序之前完成加密,因此参数化是唯一能够返回结果行的方式。
Msg 206, Level 16, State 2, Operand type clashColumn Encryption Setting=EnabledCheck 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 once per sort key a caller may send, not only the one
tested: any raising , or means a mixed-type is still there.
ORDER BYMsg 206241245CASEsql
-- 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 BYMsg 206241245CASEDo not
请勿
- Do not present as sufficient for a caller-supplied identifier without checking its result for
QUOTENAME, and do not say it truncates a long name or raises an error for one. It returnsNULL, and nothing reports it.NULL - Do not say either helper checks that an object exists. Neither reads the catalog.
- Do not build a caller-chosen from one
ORDER BYspanning columns of different types, even when the columns tried in testing share a type.CASE - Do not add 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.
WITH EXECUTE AS OWNER - 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 , linked servers or
xp_cmdshellagainst arbitrary providers. None exist on Azure SQL Database to escalate to.OPENROWSET
- 不要将 QUOTENAME 描述为:在没有检查其结果是否为 的情况下,它足以保护调用方提供的标识符;也不要声称它会截断过长名称或为过长名称引发错误。它返回
NULL,而且不会报告任何信息。NULL - 不要声称任一辅助函数会检查对象是否存在。它们都不会读取目录。
- 不要用一个跨越不同类型列的 来构建调用方选择的
CASE,即使测试过的列类型相同也不行。ORDER BY - 不要为了消除权限错误而直接添加 ,却不说明该模块现在可以访问什么,也不说明调用方身份在模块内部已不可见。
WITH EXECUTE AS OWNER - 不要告诉开发者,只需对 agent 生成的语句中唯一一个值进行参数化,就能保证整个语句安全。模型编写了整个语句,因此真正的控制边界是其连接运行时所具有的权限边界。
- 不要警告在 Azure SQL Database 上使用 、linked servers 或
xp_cmdshell访问任意提供程序所带来的风险。它们在 Azure SQL Database 中并不存在,无法借此提升权限。OPENROWSET
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.