Monday, December 29, 2008

Preventing JavaScript injection attacks

Whenever one is developing web pages that accept input from the user, one needs to be extra careful in order to prevent the extremely dangerous XSS (Cross Site Scripting) attacks. Typically, these attacks are carried out by users who input malicious scripts in the input fields provided on the web page. The scripts get executed when the page tries to display back the values that were input by the user. For example, if the user is presented with a field for entering his name, he may enter something like

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 :

  1. 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.
  2. 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.

No comments:

Post a Comment