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:
- 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.
- 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.
- 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.
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.
Useful XSS prevention resourcesAcunetix 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.