Hug*_*are 4 javascript security json
从安全角度来看,我可以看到只是对传入的JSON数据进行"评估"是一个严重的错误.如果您获得如下数据,则会遇到一些问题.
{ someData:((function() {
alert("i'm in ur code hackin' ur page");
})()) }
Run Code Online (Sandbox Code Playgroud)
我想知道最流行的Javascript库做了什么?它是手动解析还是仅仅是一个评估?
[编辑]
我不是在问我是否应该进行eval/parse - 我问的是一些流行的Javascript库使用了什么方法(jQuery,Prototype等...)
这是官方JavaScript解析器的作用:
// 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 + ')');
...
Run Code Online (Sandbox Code Playgroud)
除了现代浏览器中的内置JSON解析支持之外,这是所有(基于库的)安全JSON解析器所做的事情(即之前的正则表达式测试eval).
安全库(除了官方的json2实现)
原型的isJSON功能.
Mootools的JSON.decode功能(再次,通过之前eval的正则表达式测试).
不安全的库:
道场的fromJson并没有提供安全evalING.这是他们的整个实现(减去评论):
dojo.fromJson = function(json) {
return eval("(" + json + ")");
}
Run Code Online (Sandbox Code Playgroud)
jQuery不提供安全的JSON eval,但请参阅官方插件的secureEvalJSON功能(第143行).