href security, prevent xss attack

倖福魔咒の 提交于 2019-12-23 02:01:53

问题


<?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.

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";}

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


回答1:


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

  1. Place the value inside quotes
  2. Encode any characters with special meaning
  3. Make sure to whitelist the protocol of the URL, if one exists

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
}


来源:https://stackoverflow.com/questions/19047119/href-security-prevent-xss-attack

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!