Javascript JSON数据-解析或';评估';预计起飞时间
从安全角度来看,我可以认为对传入的JSON数据进行“评估”是一个严重错误。如果你有下面这样的数据,你会有一些问题Javascript JSON数据-解析或';评估';预计起飞时间,javascript,security,json,Javascript,Security,Json,从安全角度来看,我可以认为对传入的JSON数据进行“评估”是一个严重错误。如果你有下面这样的数据,你会有一些问题 { someData:((function() { alert("i'm in ur code hackin' ur page"); })()) } 我想知道最流行的Javascript库做什么?它是手动解析还是简单的评估 [编辑] 我不是问我是否应该评估/解析——我是问一些流行的Javascript库(jQuery、Prototype等)使用了什么方法。取而代之的是什
{ someData:((function() {
alert("i'm in ur code hackin' ur page");
})()) }
我想知道最流行的Javascript库做什么?它是手动解析还是简单的评估
[编辑]
我不是问我是否应该评估/解析——我是问一些流行的Javascript库(jQuery、Prototype等)使用了什么方法。取而代之的是什么?据我所知,这基本上是在一些卫生检查之后调用eval()。您应该绝对解析它!JSON只是JavaScript的一个子集。但是
eval
将评估任何JavaScript代码,而不是像JSON解析器那样评估特定子集
除了现代浏览器中内置的JSON解析器之外,所有(基于库的)安全JSON解析器都是这样做的(即,在eval
之前进行正则表达式测试)
安全库(除了正式的json2实现)
原型的功能
Mootools的功能(同样,通过a)
不安全库:
dojo不提供安全的eval
ing.:
jQuery不提供安全的JSONeval
'ing,但可以查看官方插件的功能(第143行)。来自:
一个快速安全的JSON解析器
JavaScript
此JSON解析器不会尝试
验证JSON,因此可能会返回
给定的结果在语法上无效
输入,但不使用eval
确定性,并保证不会
修改对象以外的任何对象
返回值
中有许多JSON解析器
JavaScript?在json.org上。这
无论何时,都应该使用实现
安全性是一个问题(当JSON可能
来自不受信任的来源),速度
是一个问题,而且还在继续
格式错误的JSON不值得关注
此实现
- 快速、安全
- 不验证的缺点
- 安全,安全
- 慢犯人
- 专业快速,一些验证
- 潜在的不安全因素
这是一个很好的常规表达式。实际上,一些JSON解析器有一个跳过正则表达式的安全模式。这种模式更快,但也不太安全。@Henrik:如果不太安全,为什么称它为“安全模式”?;)因为它假设输入已经是安全的。(当它来自您控制的服务器时,这听起来很合理。)
// 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 + ')');
...
dojo.fromJson = function(json) {
return eval("(" + json + ")");
}