博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用安全json parser防止json注入
阅读量:2434 次
发布时间:2019-05-10

本文共 1288 字,大约阅读时间需要 4 分钟。

 今天在网上瞎逛又看到了一个不错的东西。
有些程序员如果没有很好的在
javascript中解析
json数据,往往会直接
eval把json转成js对象,这时候如果json的数据中包含了被注入的恶意数据,则可能导致代码注入的问题。
正确的做法是
分割出json里包含的特殊字符,然后再解析为对象
http://json.org/json2.js 中是通过正则来完成的。
// 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 + ')');
目前不少写的好的框架和js解析函数都取用了这种做法。
所以,以后千万别直接eval了。

转载地址:http://vnhmb.baihongyu.com/

你可能感兴趣的文章
CSS Padding in Outlook 2007 and 2010
查看>>
有关内存的思考题
查看>>
What is the difference between gross sales and revenue?
查看>>
Dreamweaver默认打开后缀名为ftl的文件时
查看>>
LNMP一键安装
查看>>
几个分析函数的比较
查看>>
主流算法:
查看>>
RMI
查看>>
J.U.C之Future
查看>>
缓存思想分析
查看>>
一致性hash
查看>>
J.U.C之ConcurrentHashMap分析
查看>>
J.U.C之CopyOnWriteArrayList
查看>>
J.U.C之Atomic&CAS
查看>>
类的生命周期
查看>>
Joda-Time学习
查看>>
Guava扩展工具包
查看>>
Jedis分片策略-一致性Hash
查看>>
BeanFactory和FactoryBean
查看>>
用户态和内核态的概念区别
查看>>