Is the following PHP code XSS proof?
<?php
$site = $_GET["url"];
echo "<a href='".str_replace(array("\"", "'", "javascript:", "vbscript:"), array("%22", "%27", "", ""), $site)."'>Site</a>";
?>
Information Security Stack Exchange is a question and answer site for information security professionals. It only takes a minute to sign up.
Sign up to join this communityIs the following PHP code XSS proof?
<?php
$site = $_GET["url"];
echo "<a href='".str_replace(array("\"", "'", "javascript:", "vbscript:"), array("%22", "%27", "", ""), $site)."'>Site</a>";
?>
No, it is not.
Try insert javascript:alert(9)
as the URL, or like @wireghoul pointed, JAVASCRIPT:alert(9)
. Even with javascript :alert(9)
in older browsers (IE < 8, I guess).
Better solution:
<?php
header('Content-Type: text/html; charset=utf-8');
header('X-Content-Type-Options: nosniff');
$site = $_GET["url"];
$site_lowercase = strtolower($site);
if(strpos($site_lowercase, "http://")===0 || strpos($site_lowercase, "https://")===0){
$possible_xss = false;
}
else if(strpos($site_lowercase, "ftp://")===0 || strpos($site_lowercase, "ftps://")===0){
$possible_xss = false;
}
else if(strpos($site, "/")===0){
$possible_xss = false;
}
else{
$possible_xss = true;
}
$site = str_replace(array("\"", "'"), array("%22", "%27"), $site);
echo "<a href='".(($possible_xss)?"//".$site:$site)."'>Site</a>";
?>
$site="JAVASCRIPT:alert(1)";
. I would recommend using a whitelist to ensure no malicious data is included in the output.
Nov 27, 2014 at 6:46
I'm generally a fan of not re inventing the wheel because people way smarter than us already did. I did a quick search for you and found the current library you can use: https://code.google.com/p/php-antixss/
Re: your code, it looks a little too simple to prevent fully. I would use a standardized solution that is used by others and continuously contributed to as new exploits develop.
Hope it helps.
people who put time and effort into this matter already
instead.
There's a ton of ink written on the subject of why you shouldn't try doing your own homebrew filters for these things! Please have a look at OWASP's XSS mitigation guidelines.
Use the proper libraries for these things - OWASP ESAPI for PHP is a great tool to start with. I'd look at HTML Purifier as well.