使用安全json parser防止json注入

有些程序員若是沒有很好的在javascript中解析json數據,每每會直接eval把json轉成js對象,這時候若是json的數據中包含了被注入的惡意數據,則可能致使代碼注入的問題。javascript


正確的作法是分割出json裏包含的特殊字符,而後再解析爲對象java


http://json.org/json2.js 中是經過正則來完成的。程序員


// We split the second stage into 4 regexp operations in order to work aroundjson

// 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 allui

// open brackets that follow a colon or comma or that begin the text. Finally,spa

// we look to see that the remaining characters are only whitespace or ']' orregexp

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

目前很多寫的好的框架和js解析函數都取用了這種作法。


因此,之後千萬別直接eval了。

相關文章
相關標籤/搜索