Stay ahead of Web 2.0 worms
XSS marks the spot
As you can see from my examples you can - if you're careful - think through all the inputs to your application and prevent code from getting mixed into your data. But for real protection, you'll need to get organized and put a strategy in place.
You'll need to define some organization-wide security standards that cover XSS. You'll also need to make sure all developers know how to recognize XSS problems and implement protections. Don't reinvent your controls in every application. You'll want to adopt standard controls for canonicalization, validation, and encoding across your organization. The Enterprise Security API from the organization I work with, the Open Web Application Security Project (OWASP), is one attempt to define a set of interfaces and a reference implementation.
You'll also need a good testing program, with both automated scanning and manual reviews. Automated tools can find simple XSS problems, but only manual code review and penetration testing will be able to diagnose the complex problems. Only manual review can verify that the standard controls work as intended and that developers are using them properly.
XSS isn't going to go away anytime soon - in fact the problem's going to become worse thanks to AJAX, web services and Web 2.0. The key to containing the problem, though, is to act tactically and strategically whilst building web applications.®