13 January 2010

Prevent XSS attacks

XSS (Cross Site Scripting) is a surprisingly easy weakness to exploit on unprepared websites. To describe it at its highest level an XSS attack involves injecting code into a webpage and having a user execute it on the grounds that they trust the website you have hijacked.

There are a great many vectors for an XSS attack to come through, but for the most part applying a few simple safety precautions will greatly improve your site security.

XSS attacks can be split into one of three categories:

  1. Stored XSS attacks - are those where the attacker stores malicious code in your database, forum, comment section or elsewhere on your site. The victim receives the code when they request that particular content from your website.

  2. Reflected XSS attacks - are those where the malicious code is reflected off the server and sent to the victim as part of search results, emails, error messages, etc. This can be set up by tricking the victim into clicking a specially crafted link (or filling in a malicious form) that generates the appropriate response from the insecure server.

  3. DOM XSS attacks - are those where the payload is delivered on the client side by manipulating the script once it has been sent by the server.
It is essential for web developers to sanitize their data so that it does not open doors to these simple attacks.
Cardinal rule: Don't insert data you can't trust
Don't put received data into scripts, tags, HTML comments, attribute names, or tag names. Especially don't run Javascript that you receive.

If your language has automatic functions to sanitize strings (e.g.: PHP has filter_var) then use it.  Be cautious of using functions that are designed to work with html entities, some XSS attacks can work around this.

This applies to HTML elements, Javascript, CSS, attributes, names, and everywhere else that you use received data.

Useful XSS prevention resources

Acunetix provides a free version of their vulnerability scanner that does a good job of detecting XSS attacks.

The Open Web Application Security Project (OWASP) has an extensive wiki on website security.

These guys provide us with users who click on links they shouldn't. Without them we wouldn't have a job.

Trevor Sewell is a UK developer who has kindly provided a PHP XSS class that sanitizes POST data.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.