Created
November 1, 2012 12:45
-
-
Save jksdua/3993433 to your computer and use it in GitHub Desktop.
XSS prevention using JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// *** 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 = "<script>alert(document.cookie)</script>"; | |
// 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: | |
// <?php | |
// echo "<script> String.prototype.xssSafe = function() { ... } </script>"; | |
// ... | |
// // bunch of random php markup | |
// ... | |
// echo "<script>document.write($malicious.xssSafe());</script>"; | |
// // 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 </script> with document.write gives SyntaxError in Chrome and Firefox |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment