href安全,防止xss攻击 [英] href security, prevent xss attack

查看:54
本文介绍了href安全,防止xss攻击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?PHP
//fetch website data from db..

$website=htmlentities("javascript:alert()");
?>

<a href="<?PHP echo $website;?>">Click me</a>//without http will get attack
<a href="http://<?PHP echo $website;?>">Click me</a>

我有一个网络应用程序为用户提供输入以添加他们的网站.

I have a web application provide an input for user to add their website.

但是我考虑安全问题,我做了测试.如果我添加了 http://,它就不会运行 javascript.我的问题是我还需要为 href 安全做些什么吗?

however i am consider the security problem, I did the testing. if I have add http:// it won't run javascript. My question is are there anything else I need to do for href security?

$url="example.php?name=Peter&age=37";

if(!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)){echo "URL is not valid";}
else{echo "URL is valid";}

我使用了validate_url,但是这个返回无效.它来自 W3 示例,W3 显示输出有效

I have use validate_url, but this one return not valid. Its from W3 example, W3 show output is valid

推荐答案

要通过锚点 href 属性防止 XSS,您需要做三件事:

To prevent XSS through an anchor href attribute you need to do three things:

  1. 将值放在引号内
  2. 对任何具有特殊含义的字符进行编码
  3. 确保将 URL 的协议(如果存在)列入白名单

你已经在做上面的前两个了(尽管 htmlspecialchars 应该优先于 htmlentities 用于此目的),因此您只需要照顾(3).一种方法是在 URL 前强制使用 http://,但这会破坏任何使用不同协议(例如 HTTPS)的 URL.

You are already doing the first two above (although htmlspecialchars should be preferred over htmlentities for this purpose), so you only need to take care of (3). One way to do that is by brute-forcing http:// in front of the URLs, but that would break any URL that uses a different protocol (e.g. HTTPS).

更好的解决方案是使用允许协议的白名单,例如:

A better solution is to use a whitelist of allowed protocols, for example:

$allowed = [null, 'http', 'https']; // null = not specified

$scheme = parse_url($website, PHP_URL_SCHEME);
if ($scheme === false) {
    // seriously malformed URL, what to do?
}
else if (!in_array($scheme, $allowed, true)) {
    // protocol not allowed, don't display the link!
}
else {
    // everything OK
}

这篇关于href安全,防止xss攻击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆