问题没有从这个出现:
Why does the browser modify the ID of an HTML element that contains &#x?此代码是否容易受到XSS攻击?
考虑到以下网页:
<html>
<head>
<script type="text/javascript">
// --------------------------------------------------------
// could calling this method produce an XSS attack?
// --------------------------------------------------------
function decodeEntity(text){
text = text.replace(/<(.*?)>/g,''); // strip out all HTML tags, to prevent possible XSS
var div = document.createElement('div');
div.innerHTML = text;
return div.textContent?div.textContent:div.innerText;
}
function echoValue(){
var e = document.getElementById(decodeEntity("/path/$whatever"));
if(e) {
alert(e.innerHTML);
}
else {
alert("not found\n");
}
}
</script>
</head>
<body>
<p id="/path/$whatever">The Value</p>
<button onclick="echoValue()">Tell me</button>
</body>
</html>
的<p>
元素的id
包含为了防止XSS攻击了逃脱字符。 HTML部分和JS部分由服务器生成,服务器在两个部分插入相同的转义值(可能来自不安全的源)。
服务器逸出在&#x
格式以下字符范围:
- 为0x00 – 0x2D
- 0x3A – 0x40的
- 0x5B – 0x5E
- 0x60的
- 0x7B – 0xFF的
- 0x0100 – 0xFFFF的
换句话说:是不逃过字符只有:
- 器0x2E – 0x39(
.
,/
,)
- 的0x41 – 0x5A(
A
–Z
) - 0x5F(
_
) - 0x61 – 0x7A(
a
–z
)
现在,我得通过JavaScript访问该<p>
。引用问题中的函数echoValue()
始终失败,因为浏览器在HTML部分中将$
转换为$
,但在JS部分中将其保留为$
。
因此,Gareth想出了an answer这是简单和有效的。
我担心的是,当使用参考答案中提供的decodeEntity()
函数时,通过转义动态字符串消除的XSS攻击的可能性将再次出现。
可能有人指出是否可能有安全问题(哪个?)否(为什么不呢?)?
只是让服务器不在脚本内部转义它。 – Bergi