惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tailwind CSS Blog
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Y
Y Combinator Blog
Hugging Face - Blog
Hugging Face - Blog
博客园 - 聂微东
L
LangChain Blog
博客园_首页
Recent Announcements
Recent Announcements
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
博客园 - 叶小钗
博客园 - 【当耐特】
The Cloudflare Blog
J
Java Code Geeks
G
Google Developers Blog
云风的 BLOG
云风的 BLOG
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
aimingoo的专栏
aimingoo的专栏
A
About on SuperTechFans

博客园 - ghx88

工具记录 [ 转]discuz 的加密与解密函数authcode解析 Balsamiq Mockups完全手册[转] [转]Yahoo!网站性能最佳体验的34条黄金守则——内容 人生的时间管理法则 JavaScript 读取地址栏参数 无题 唐僧的家书 如何成为一个专家 [原创]JQuery实现表格的列列交换 - ghx88 - 博客园 asp.net2 统一搜索引擎关键字编码[转] 中国的数学教育方式 别浪费了你的大内存[转] QQ空间免费养5级花和拥有人参果 把网速提高4倍的方法和动画教程 关于charset在blueidea的帖子[转] 林蛋大 多吃葡萄可以排毒[转] 使类支持排序
使用安全json parser防止json注入
ghx88 · 2009-05-19 · via 博客园 - ghx88


有些程序员如果没有很好的在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了。