从安全的 Angular 来看,我认为简单地对传入的 JSON 数据执行“评估”是一个严重的错误。如果你有如下数据,你会遇到一些问题。
{ someData:((function() {
alert("i'm in ur code hackin' ur page");
})()) }
我想知道最流行的 Javascript 库是做什么的?是手动解析还是简单的评估?
[编辑]
我不是在问我是否应该评估/解析 - 我是在问一些流行的 Javascript 库使用了哪些方法(jQuery、Prototype 等...)
最佳答案
这是 official JavaScript parser 的内容做:
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
...
除了内置的 JSON parsing support在现代浏览器中,这是所有(基于库的)安全 JSON 解析器所做的(即,在 eval
之前进行正则表达式测试)。
安全库(除了官方的 json2 实现之外)
原型(prototype)的 isJSON
功能。
Mootools 的 JSON.decode
功能(同样,通过 regex test before eval
)。
不安全的库:
道场的 fromJson
不提供安全的eval
ing。 Here is their entire implementation (minus comments) :
dojo.fromJson = function(json) {
return eval("(" + json + ")");
}
jQuery 不提供安全的 JSON eval
'ing,但请参阅官方插件的 secureEvalJSON
函数(第 143 行)。
关于javascript - JSON 数据 - 已解析或 'Eval' ed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1143417/