问题
<?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:
- Place the value inside quotes
- Encode any characters with special meaning
- 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