ABC;<script>alert("This site is hacked")</script>
Now, whenever the site displays this user's name, the script also gets executed and the viewer of the page will get an alert box proclaiming "This site is hacked". Although this is a contrived example, there is the potential to do much more harmful things using the same technique. Skilled users can write scripts that can read data from cookies, for example, and send to another site (hence the name cross site scripting).
In order to prevent such things from happening, all one has to do is "Server.HTMLEncode" all the values that the user provides, assuming you are using ASP.NET. There are 2 places where you can do the encoding :
- You can do the encoding while storing the data in the database so that anytime those values are to be displayed to the user, they won't cause any problems.
- You can also do the encoding just before showing the values to the user. This technique can be used when you are just displaying the values without ever storing them in the database or in case you need to display the values before storing them in the database
What Server.HTMLEncode does is it converts all the special characters such as "<" and ">" to their ASCII equivalents so that the browser runtime engine interprets them as normal characters instead of interpreting and executing them. You can find the complete list of actions taken by this method here.
Remember to encode any and all values you accept from users to avoid having serious XSS attacks launched on your website.