使用外部控制的格式字符串¶
ID: js/tainted-format-string
Kind: path-problem
Security severity: 7.3
Severity: warning
Precision: high
Tags:
- security
- external/cwe/cwe-134
Query suites:
- javascript-code-scanning.qls
- javascript-security-extended.qls
- javascript-security-and-quality.qls
像 Node.js 标准库函数 util.format
这样的函数接受一个格式字符串,该字符串用于通过提供内联格式说明符来格式化剩余参数。如果格式字符串包含来自不受信任来源的未经清理的输入,则该字符串可能包含意外的格式说明符,导致输出混乱。
建议¶
在将输入包含在格式字符串中之前清理它,或者在格式字符串中使用 %s
说明符,并将不受信任的数据作为相应的参数传递。
示例¶
以下程序片段记录了关于未授权访问尝试的信息。日志消息包含用户名,用户 IP 地址作为附加参数传递给 console.log
以追加到消息中
const app = require("express")();
app.get("unauthorized", function handler(req, res) {
let user = req.query.user;
let ip = req.connection.remoteAddress;
console.log("Unauthorized access attempt by " + user, ip);
});
但是,如果恶意用户提供 %d
作为他们的用户名,console.log
将尝试将 ip
参数格式化为数字。由于 IP 地址不是有效的数字,因此此转换的结果为 NaN
。生成的日志消息将显示为“Unauthorized access attempt by NaN”,丢失了它试图记录的所有信息。
相反,用户名应使用 %s
说明符包含在内
const app = require("express")();
app.get("unauthorized", function handler(req, res) {
let user = req.query.user;
let ip = req.connection.remoteAddress;
console.log("Unauthorized access attempt by %s", user, ip);
});
参考¶
Node.js 文档:util.format.
常见弱点枚举:CWE-134.