应该使用jQuery的parseJSON / getJSON方法吗? [英] Should jQuery's parseJSON/getJSON methods be used?

查看:81
本文介绍了应该使用jQuery的parseJSON / getJSON方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到jQuery parseJSON基本上做了一个简单的正则表达式check:

I noticed that the jQuery parseJSON basically does a simple regex "check":

parseJSON: function( data ) {
    if ( typeof data !== "string" || !data ) {
        return null;
    }

    // Make sure leading/trailing whitespace is removed (IE can't handle it)
    data = jQuery.trim( data );

    // Make sure the incoming data is actual JSON
    // Logic borrowed from http://json.org/json2.js
    if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
        .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {

        // Try to use the native JSON parser first
        return window.JSON && window.JSON.parse ?
            window.JSON.parse( data ) :
            (new Function("return " + data))();

    } else {
        jQuery.error( "Invalid JSON: " + data );
    }
},

如果它通过了检查,如果它是现代浏览器使用本机JSON解析器。否则,我假设对于像IE6这样的浏览器,会自动调用一个新函数并返回该对象。

If it passes that "check" and if it's a modern browser a native JSON parser is used. Otherwise, I assume for a browser like IE6 a new function is automatically invoked and returns the object.

问题#1 :因为这只是一个简单的正则表达式测试,是不是容易出现某种模糊的边缘案例漏洞?对于那些不支持原生JSON解析的浏览器,我们真的不应该使用完整的解析器吗?

Question #1: Since this is just a simple regex test, isn't this prone to some sort of obscure edge-case exploit? Shouldn't we really be using a full blown parser, for the browsers that don't support native JSON parsing at least?

问题#2 :更安全是多少(新函数(返回+数据))()而不是 eval((+ text +))

Question #2: How much "safer" is (new Function(" return " + data ))() as opposed to eval("(" + text + ")")?

推荐答案

正如评论中所提到的,jQuery的JSON解析器借用从json2.js开始测试以查看JSON字符串是否有效的逻辑。这使得它像最常见的非本机实现一样安全,无论如何都是相当严格的:

As mentioned in the comments there jQuery's JSON parser "borrows" the logic that tests to see if the JSON string is valid, right from json2.js. This makes it "as safe" as the most common non-native implementation, which is rather strict anyway:

// 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, ''))) {

我不明白为什么jQuery在检查本机实现之前运行正则表达式/替换,无论如何都会检查正确的JSON语法。似乎只有在没有本机实现的情况下才能加快速度。

What I don't understand is why jQuery runs the regular expression/replaces before checking for a native implementation which would check for correct JSON grammar anyway. It seems like it would speed things up to only do this if a native implementation isn't available.

问题2是在另一个问题上由bobince回答得非常好:

Question 2 is answered very well by bobince in another question:


这不是真的一个很大的区别,但感觉是eval比新功能更糟糕。不是在安全性方面 - 面对不受信任的输入,它们同样无用,但希望你的webapp不会返回不受信任的JSON字符串 - 但是在语言级别的怪异方面,因此对优化的抵制。

It's not really a big difference, but the feeling is that eval is ‘worse’ than new Function. Not in terms of security — they're both equally useless in the face of untrusted input, but then hopefully your webapp is not returning untrusted JSON strings — but in terms of language-level weirdness, and hence resistance to optimisation.

查看 Nick Craver的回答也有来自John Resig的直接引用。

Check out Nick Craver's answer there too for a direct quote from John Resig.

这篇关于应该使用jQuery的parseJSON / getJSON方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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