// *** Prevent Javascript attacks using Javascript...sweet! *** // Proof of concept for output encoding user input on the client side. // Works in IE6+ // Some user input var malicious_input = ""; // Inserting it safely var body = document.querySelector('body'); body.innerHTML = malicious_input.xssSafe(); // Encoding function String.prototype.xssSafe = function() { var node = document.createTextNode(this); // using the nodeValue property allows us to use it in markup and also in element attributes // otherwise we get a [object Text] instead of what we actually want return node.nodeValue; } // ================================================= // Using from server-side - language agnostic // For cases when data is added using server variables before access to JS // // Simply output the JS function at the start of the body tag // and then reference it before outputting any user input. For eg: // String.prototype.xssSafe = function() { ... } "; // ... // // bunch of random php markup // ... // echo ""; // // the above is too much text, best to write a helper php function // ?> // Note: Markup comes out with script tags intact this way, // doesn't seem to be causing issues with CSS rendering though. // TO DO: // Look into documentFragment to see if it can do the same thing more efficiently // What happens if Javascript is disabled // Look at why providing the value with document.write gives SyntaxError in Chrome and Firefox