javascript - 为了保护它免受 XSS 攻击,对内联 javascript 对象进行编码的正确方法是什么?

标签 javascript html json xss

事实证明以下看起来像有效的 javascript,但不是:

<html> 
<body>
<script>
 json = {test: "</script><script>alert('hello');</script>"};
</script>
</body>
</html>

相同的文本,当通过 ajax api 返回 JSON 时按预期工作。但是,当在线呈现时会导致基本的 XSS 问题。

给定一个任意正确的 JSON 字符串,我需要在服务器端做什么才能使其安全地进行内联渲染?

编辑 理想情况下,我希望修复程序也适用于以下字符串:

json = {test: "<\/script><script>alert('hello');<\/script>"};

意思是,我不知道我的底层库是如何编码 / 的char,它可能已经选择对其进行编码,也可能没有。 (所以它可能是一个正则表达式修复更健壮)

最佳答案

参见 OWASP's XSS prevention guide (参见规则 #3)-

Except for alphanumeric characters, escape all characters less than 256 with the \xHH format to prevent switching out of the data value into the script context or into another attribute. Do not use any escaping shortcuts like \" because the quote character may be matched by the HTML attribute parser which runs first.

假设这就是您的对象的样子 -


var log = {
trace: function(m1, m2, m3){},
debug: function(m1, m2, m3){},
currentLogValue : "trace {].a23-%\/^&",
someOtherObject : {someKey:"somevalue", someOtherKey:"someothervalue"}
};

这应该是这样结束的——


var log = {
trace : "function\x28m1,\x20m2,\x20m3\x29\x7B\x7D",
debug : "function\x28m1,\x20m2,\x20m3\x29\x7B\x7D",
currentLogValue : "trace\x20\x7B\x5D.a23\x2D\x25\x5C\x2F\x5E\x26",
someOtherObject : {someKey : "somevalue", someOtherKey:"someothervalue"}
};

规则很简单 -

  1. 不可信数据只允许出现在一对引号内
  2. 引号内的任何内容都会按如下方式转义 - “除了字母数字字符,使用\xHH 格式转义其他所有字符”

这确保不受信任的数据始终被解释为字符串,而不是函数/对象/任何其他内容。

关于javascript - 为了保护它免受 XSS 攻击,对内联 javascript 对象进行编码的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3489859/

相关文章:

javascript - 使用 React 获取文本而不是下拉(选择)输入的值

javascript - Nouislider 设置范围可变

javascript - 如何验证货币输入

html - 视网膜显示和 css + 图像

html - Bootstrap 右列与左列重叠

json - Airflow |设置变量

javascript - Angular UI-router - 尽管 $stateParams 获取对象,但不填充参数

php - 如何在同一页面上同时为不同的 div 使用不同的样式表?

javascript - 如何检测生成元素的点击?

javascript - 将数据从 json 转换为给定格式