Low Cost XSS Protection.
Publicated on :
1178627545
Usually it's only possible to invoke a XSS attack when certain chars are allowed to inject along some parameters in the URI. Just like SQL injection if you have a few chars you can insert like the single quotes or the less and greater signs it is possible to quickly launch a XSS attack. Not everyone has the skills or time to protect himself against XSS or SQL injection so I wrote this post to give a quick sollution against it. It won't protect you from all attacks, but you can make it pretty hard for them to lauch one. And so we can use this in certain areas where security is needed but isn't a big issue anyway like in basic forms or search scripts.
The scripts are in Javascript for an easy example to test. I do not recommend it to write it in Javascript though. If you can write it in a server side language; please use that one.
Here I added a few PHP functions that are commonly used:
htmlentities($_REQUEST['text'], ENT_QUOTES, 'UTF-8');
And:
$var = htmlspecialchars($var, ENT_COMPAT, 'UTF-8');
$var = iconv("UTF-8", "UTF-8", $var)
$var = iconv("ISO-8859-1","UTF-8",$var);
The quickest way I know of is to pair given strings into single quotes. I've seen this practice a couple of times and it really works nicely. For example this vector: "><script>alert('xss');</script><" will never work if this vector is paired with single quotes like so: ' "><script>alert('xss');</script><" '
Another lowcost strip function to remove the less and greater sings and replace them with a space. This way one can't execute markup, it's a quick sollution and works pretty good.
function Strip(input) {
var text = input;
text = text.replace(/</gi," ");
text = text.replace(/>/gi," ");
document.getElementById('output').innerHTML = text;
}
A full strip function which does allow basic HTML but no Javascript could be: