防止XSS入侵(嵌入)用户生成的json的最佳方法? [英] Best way to prevent XSS hacking with (embedded)user generated json?

查看:156
本文介绍了防止XSS入侵(嵌入)用户生成的json的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参见: http://jsfiddle.net/agv9ya39/

var json = { name: "</script><script>alert(123);</script>" };

请注意,我要做要在页面中嵌入json(数据与页面紧密相关,无法缓存,并且我不想执行额外的请求)

一种解决方案是在输出前对整个json字符串执行String.Replace("</script>).但这感觉很骇人,而且我可能想念其他容易受到XSS攻击的情况.

当然,我也可以确保它永远不会在数据库中以这种方式结束,但是我宁可对任何情况下的滑脱提供额外的保护.

我正在使用C#和Json.Net.

解决方案

您可以将<!--</script>替换为<\!--<\/script>,以覆盖JSON的所有<script>分支.不过,请考虑将JSON放在data-*属性中,并使用JSON.parse读取它.

 <div id="some-relevant-element"
     data-json="{&quot;name&quot;:&quot;</script><script>alert(123);</script>&quot;}">
   …
</div>

<script>
var someRelevantElement = document.getElementById('some-relevant-element');
var json = JSON.parse(someRelevantElement.getAttribute('data-json'));
</script>
 

See i.e.: http://jsfiddle.net/agv9ya39/

var json = { name: "</script><script>alert(123);</script>" };

Note that I do want to embed the json in the page (data is closely related to the page, can't be cached and I don't want to do an extra request)

One solution would be doing a String.Replace("</script>) on the whole json string before outputting. But it feels hacky, and I'm probably missing other cases vulnerable for XSS.

Of course I can also make sure it nevers ends up like this in the database, but I rather have an extra protection for if something slips in anyway.

I am using C# and Json.Net.

解决方案

You can replace <!-- and </script> with <\!-- and <\/script> to cover all <script> break-outs for JSON. Consider putting the JSON in a data-* attribute instead, though, and reading it with JSON.parse.

<div id="some-relevant-element"
     data-json="{&quot;name&quot;:&quot;</script><script>alert(123);</script>&quot;}">
   …
</div>

<script>
var someRelevantElement = document.getElementById('some-relevant-element');
var json = JSON.parse(someRelevantElement.getAttribute('data-json'));
</script>

这篇关于防止XSS入侵(嵌入)用户生成的json的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆