2009-07-17 37 views
4

從安全角度來看,我可以簡單地對傳入的JSON數據執行「eval」作爲嚴重錯誤。如果你有下面的數據,你會遇到一些問題。JSON數據 - 已解析或已評估

{ someData:((function() { 
    alert("i'm in ur code hackin' ur page"); 
})()) } 

我想知道最流行的Javascript庫有哪些功能?它是手動解析還是簡單的評估?

[編輯]

我不問應該EVAL /解析 - 我是問什麼方法所使用的一些流行的JavaScript庫(jQuery的,原型,等...)

回答

7

這裏的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實現)

原型的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「荷蘭國際集團,但看到官方插件的secureEvalJSON功能(線143)。

+0

這是一個正則表達式的問題 – Hugoware 2009-07-17 14:03:12

0

使用evalJSON()代替?
據我所知,這基本上在一些衛生檢查後調用eval()。

1

你應該絕對解析它! JSON只是JavaScript的一個子集。但eval將評估任何JavaScript代碼,而不是像JSON解析器那樣的特定子集。

0

http://code.google.com/p/json-sans-eval/

在 JavaScript中的快速和安全的JSON解析器?

這JSON解析器不嘗試到 驗證JSON,所以可能會返回一個 結果給出一個語法上是無效 輸入,但不使用eval等是 確定性,並不能保證 修改以外的任何物體在其 返回值。

在 JavaScript中有多個JSON解析器?在json.org上。這 實現應該何時使用, 擔心安全問題(當JSON可能 來自不受信任的源),速度 是一個問題,並示數上 畸形的JSON是不是一個問題。

此實現

  • 優點快速,安全
  • 缺點沒有驗證

json_parse.js

  • 優點驗證,安全
  • 缺點慢

json2.js

  • 優點快,一些驗證
  • 缺點可能不安全

json2.js是非常快的,但可能 不安全的,因爲它調用的eval解析 JSON數據,所以攻擊者可能是 能夠提供奇怪的JS,看起來像JSON ,但執行任意 JavaScript。

如果你必須使用json2.js與 不可信的數據,一定要保持你的 的json2.js版本的不斷更新,以便 你得到的補丁,因爲他們是發佈 。