不安全的动态方法访问¶
ID: js/unsafe-dynamic-method-access
Kind: path-problem
Security severity: 9.3
Severity: error
Precision: high
Tags:
- security
- external/cwe/cwe-094
Query suites:
- javascript-code-scanning.qls
- javascript-security-extended.qls
- javascript-security-and-quality.qls
在某些对象上调用用户控制的方法会导致调用不安全的函数,例如 eval
或 Function
构造函数。特别是,全局对象包含 eval
函数,任何函数对象在其 constructor
属性中都包含 Function
构造函数。
建议¶
避免在全局对象或任何函数对象上调用用户控制的方法。将允许的方法名称列入白名单,或更改存储方法的对象类型。
示例¶
在以下示例中,来自文档父框架的消息可以调用 play
或 pause
方法。但是,它也可以调用 eval
。恶意网站可以将页面嵌入 iframe 中,并通过发送名称为 eval
的消息来执行任意代码。
// API methods
function play(data) {
// ...
}
function pause(data) {
// ...
}
window.addEventListener("message", (ev) => {
let message = JSON.parse(ev.data);
// Let the parent frame call the 'play' or 'pause' function
window[message.name](message.payload);
});
不要将 API 方法存储在全局范围内,而应将其放在 API 对象或 Map 中。同样,最好防止调用继承的方法,例如 toString
和 valueOf
。
// API methods
let api = {
play: function(data) {
// ...
},
pause: function(data) {
// ...
}
};
window.addEventListener("message", (ev) => {
let message = JSON.parse(ev.data);
// Let the parent frame call the 'play' or 'pause' function
if (!api.hasOwnProperty(message.name)) {
return;
}
api[message.name](message.payload);
});
参考¶
OWASP:代码注入.
MDN:全局函数.
MDN:Function 构造函数.
通用弱点枚举:CWE-94.