I posted a question yesterday, which I intend to get back to today however I wrote some JavaScript as a first line of prevention against XSS. However when testing this on my live server I catch some invalid input as the javascript catches the php section. My form uses post and php isn’t in my form items (i haven’t typed it in). Could this be picking up the form action or something? I’m baffeled, Any ideas
Here is my code, it is triggered on the submit button.
function validateForBadNess(){
var theShit = new Array("*","^", "$", "(",")","{", "}","[", "]","\\", "|", "'","/","?",",","=",">","gt","lt", "<","script","`","´","php");
var tagName = new Array();
tagName[0] = "input";
tagName[1] = "select";
tagName[2] = "textbox";
tagName[3] = "textarea";
for (ms=0;ms<tagName.length;ms++){
// loop through the elements of the form
var formItems = document.getElementsByTagName(tagName[ms]);
for (var xs=0;xs<formItems.length;xs++){
var thisString = formItems[xs].value;
// loop through bad array
for (zs in theShit){
//alert(thisString + " " + thisString.indexOf(theShit[zs]))
if(thisString.indexOf(theShit[zs]) >= 0){
alert("Sorry but the following character: " + theShit[zs] + " is not permitted. Please omit it from your input.\nIf this is part of your password please contact us to heave your password reset.")
return false;
}
}
// loop for formitems
}
// tagName toop
}
// original condition
}
What you do is totally unnecessary and useless in terms of protection against attacks. Any JavaScript based “protection” will be circumvented within seconds, and legitimate users will not be happy to be unable to use the
$sign for example. Always assume that any incoming data can have been tampered with.You need to be careful when outputting data on the server side. Use
htmlspecialchars()on any incoming textual data. If you have incoming HTML you need “cleaned”, use HTML purifier as suggested by Sarfraz.Related SO reading: