【发布时间】:2014-07-23 16:43:22
【问题描述】:
所以,我注意到 XSS 主要依赖未转义的尖括号来插入 html 标记。我这里有这段代码:
<!doctype html>
<html lang = 'en'>
<head>
<meta charset = 'utf-8' />
<title>XSS Blocker</title>
<style>
textarea { width: 400px; height: 300px; margin-left: auto; margin-right: auto }
#abc { background: white; }
div { background: blue; }
</style>
</head>
<body>
<div id = 'abc'>
</div>
<br>
<textarea id = 'noXSS'> </textarea>
<button type = 'button' id = 'insert'>Insert into page</button>
<button type = 'button' id = 'toggle'>Disable XSS</button>
</body>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(function() {
var noXSS = false;
function cleanInput(input) {
return input = input.replace('<','<').replace('>','>');
}
$('#toggle').mousedown(function() {
noXSS = !noXSS;
if (noXSS) {
$(this).html('Enable XSS');
}
else {
$(this).html('Disable XSS');
}
});
$('#insert').mousedown(function() {
var text = $('#noXSS').val();
if (noXSS) { text = cleanInput(text) }
$('#abc').append(text);
$('#noXSS').val('');
});
});
</script>
</html>
本质上只是在将文本插入网页之前转义了 < 和 > 字符。在一个相关问题 (Escaping < Good Enough to Prevent XSS Attacks) 中,我读到还必须声明字符集(人们无论如何都应该这样做)以防止 UTF-7 XSS,并且还应该转义与号、反斜杠以及单引号和双引号安全字符。
为了更好地理解“额外”字符(&、'、")如何以及为什么可能有害(并且因为学习起来也很有趣),我希望看到劫持我上面的代码使用这些字符的程序。
我知道这不是相当一个问题,更多的是对知识的追求,但我希望没问题。
【问题讨论】:
-
尝试在Programmers StackExchange 上发布此内容。该站点更多地用于解决现有代码和您的工作。
-
转义
'和"是为了防止在 HTML 属性中注入。&用于正确编码。通常,您不应创建自己的 XSS 过滤器,而应使用本机方法来设置元素的文本或属性。此外,您的replace调用只会替换字符串中第一次出现的字符,因此它根本不安全。
标签: javascript regex html escaping xss