在 JSON 中传递 JS 函数有哪些 XSS 危险?
创建一个 JSON 对象非常简单,如下所示:
{ "key": "value", "myFunction": function() { alert('hi'); } } }
其从服务器传递到脚本,我可以在其中调用 myFunction()。果然,该功能正常工作,我收到一条警报:“嗨”。对我来说,这可能是保持脚本大小较小的非常有用的方法。 然而,我认为通过 JSON 传递函数而不仅仅是数据存在 XSS 危险。有人可以解释一下这些是什么吗?如果合适的话,可以采取哪些步骤来消除它们?
It is simple enough to create a JSON object like this:
{ "key": "value", "myFunction": function() { alert('hi'); } }
and pass it from the server to the script where I can call myFunction(). Sure enough, the function works and I get an alert: "hi". For me this could be a very useful way of keeping the script size small.
However, I believe there are XSS dangers in passing functions rather than just data via JSON. Could someone explain what these are and, if appropriate, what steps can be taken to negate them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
function
不是 JSON 的一部分,因为 JSON 不是 JavaScript。大多数库都使用 JSON 解析器(如果可以的话,使用浏览器的解析器)。所以这不会被正确解析。虽然使用
eval
来解析JSON是邪恶的。eval
总的来说是邪恶的。而且您一直使用
加载 JavaScript,因此我在这里没有看到有关 XSS 的问题。
function
isn't part of JSON because JSON isn't JavaScript.Most libraries are using a JSON parser (when they can, the browser's one). So this won't be parsed correctly. Although using
eval
to parse JSON is evil.eval
is evil in general.And you're loading JavaScript all the time using
<script>
, so I don't see the problem here about XSS.这取决于您如何加载和解析 JSON。如果您使用 jQuery 并通过 AJAX 加载数据,那么该数据将传递到浏览器的内置 JSON 解析器,该解析器不支持 greut 所解释的功能。
http://erlend.oftedal.no/blog/misc/json/index.html
但是,如果您通过 JSONP(围绕它包装一个函数)加载它,通过 JSON 将其直接添加到页面末尾的脚本标记中,例如 Socialcast 所做的那样,那么它就很容易受到攻击。
http://erlend.oftedal.no/blog/misc/json/index2.html
如果您在使用最后一个时遇到问题,您应该记住 JSON 值(和键)应始终包含在“”中。因此,如果您从不受信任的数据构建 JSON,则必须记住对其进行 JSON 编码。它有点类似于 Javascript 编码,只是 JSON 有一些额外的怪癖。例如,您可以拥有一个有效的 JSON 文件,该文件不是有效的 javascript,因为它包含 JSON 中允许的字符,但需要用 javascript 进行编码。
That depends on how you are loading and parsing the JSON. If you are using jQuery and loading the data via AJAX, then that data is passed to the browser's built-in JSON-parser which doesn't support function as explained by greut.
http://erlend.oftedal.no/blog/misc/json/index.html
However if you are loading it through either JSONP (wrapping a function around it), by the JSON adding it directly in a script tag at the end of the page like for instance Socialcast does, then it's vulnerable.
http://erlend.oftedal.no/blog/misc/json/index2.html
If you are having problems with this last one, you should remember that JSON values (and keys) should always be wrapped in "". So if you are building JSON from untrusted data, you have to remember to JSON encode it. It's sort of similar to Javascript encoding, except JSON has some additional quirks. For instance you can have a valid JSON file, that is not valid javascript, because it contains characters allowed in JSON, but which need to be encoded in javascript.