为什么这是 XSS 攻击以及如何防止这种攻击? [英] Why is this a XSS attack and how to prevent this?
问题描述
我有这个 php 代码,我的 CMS 安全自动测试显示这是一次 XSS 攻击.为什么以及如何解决此问题?
I have this php code and my CMS security auto-test says it's a XSS attack. Why and How can I fix this?
$url = "news.php";
if (isset($_GET['id']))
$url .= "?id=".$_GET["id"];
echo "<a href='{$url}'>News</a>";
推荐答案
这是 XSS(跨站点脚本),因为有人可以这样称呼您:
It's XSS (cross site scripting) as someone could call your thing like this:
?id='></a><script type='text/javascript'>alert('xss');</script><a href='
基本上把你的代码变成
<a href='news.php?id='></a><script type='text/javascript'>alert('xss');</script><a href=''>News</a>
现在,每当有人访问此站点时,它都会加载并运行 javascript alert('xss');
,它也可能是重定向器或 cookie 窃取器.
Now whenever someone would visit this site, it'd load and run the javascript alert('xss');
which might as well be a redirector or a cookie stealer.
正如许多其他人所提到的,您可以使用 filter_var
或 intval
(如果它是一个数字)来解决这个问题.如果你想更高级,你也可以使用正则表达式来匹配你的字符串.
As many others have mentioned, you can fix this by using filter_var
or intval
(if it's a number). If you want to be more advanced, you could also use regex to match your string.
假设您接受 a-z A-Z 和 0-9.这会起作用:
Imagine you accept a-z A-Z and 0-9. This would work:
if (preg_match("/^[0-9a-zA-Z]+$", $_GET["id"])) {
//whatever
}
filter_input
甚至有完全按照您的意愿进行手动输入(清理您对链接的输入):
filter_input
even has a manual entry doing exactly what you want (sanitizing your input into a link):
<?php
$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>
这篇关于为什么这是 XSS 攻击以及如何防止这种攻击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!