gpt4 book ai didi

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

转载 作者:技术小花猫 更新时间:2023-10-29 12:32:45 26 4
gpt4 key购买 nike

事实证明以下看起来像有效的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com