ES2015模板字符串安全问题 [英] ES2015 template strings security issue

查看:231
本文介绍了ES2015模板字符串安全问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是 MDN 的报价:


模板字符串不得由不受信任的用户构造,因为他们可以访问变量和函数。

Template strings MUST NOT be constructed by untrusted users, because they have access to variables and functions.

另一个例子:

`${console.warn("this is",this)}`; // "this is" Window

let a = 10;
console.warn(`${a+=20}`); // "30"
console.warn(a); // 30

这里的示例不显示任何可以看到的漏洞。

The example here doesn't show any vulnerabilities I can see.

任何人都可以提供一个利用此漏洞的示例?

Can anyone give an example of an exploit that takes advantage of this?

推荐答案

没有意义。模板字符串无法访问任何东西,也不会执行。模板字符串是语言的语法元素。

This makes no sense. A template string doesn't have access to anything, it is not executed either. A template string is a syntactical element of the language.

动态构建模板字符串是没有问题的 - 这就像构建一个表达式(以任何格式,它是一个代码字符串或AST)。 MDN提示的问题是评估这样的表达式(例如使用 eval ,将其序列化为为用户提供的脚本等) - 它可能包含任意代码,与字符串文字相反!但是你当然不会这样做,你会吗?

Dynamically constructing a template string is no problem therefore - it's like building an expression (in whatever format, be it a code string or an AST). The problem MDN hints at is with evaluating such an expression (e.g. using eval, serialising it into a script that is served to the user, etc.) - it may contain arbitrary code, in contrast to a string literal! But of course you wouldn't do that anyway, would you?

这个警告就像说使用 + 操作符不能由不受信任的用户构造,因为他们可以访问变量和函数。并给出示例+ console.warn(this is这个)+为它。那么对于任何语言的表达来说,这是真的,所以这并不是特别有趣。

This warning is like saying "Concatenations using the + operator must not be constructed by untrusted users, because they have access to variables and functions." and giving the example "" + console.warn("this is",this) + "" for it. Well, this is true for any expression of the language, so it's not particularly interesting.

当然,使用模板字符串(嘿,它们是多行的,而不是字符串)可能会导致问题:

While we are talking about crappy coding, there is of course a scenario where using template strings (hey, they're multiline and whatnot) instead of string literals can lead to problems:

function escapeString(str) {
    return JSON.stringify(str).slice(1, -1)
           .replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
}

// This is (kinda) fine!
var statement = 'var x = "Hello,\\n'+escapeString(userInput)+'";';
eval(statement); // some kind of evaluation

// But this is not:
var statement = 'var x = `Hello,\n'+escapeString(userInput)+'`;';
//                       ^                                   ^

现在想象 userInput 包含一个 $ {...} - 我们没有逃脱...

Now imagine userInput contains a ${…} - which we did not escape…

这篇关于ES2015模板字符串安全问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆