How to protect against XSS (Cross-Site Scripting)

An OWASP (Open Web Application Security Project) report states that XSS is a vulnerability in about two-thirds of all web applications.

XSS is when an attacker submits a malicious script, usually JavaScript code, into an input on a website. Once inserted, the browser automatically runs the script. The script is designed to either capture server or user login information, or store itself in the website application's database.

Website applications that accept user input into form input fields such as text boxes or textareas are vulnerable to XSS. If the malicious script can store itself in the website application's database, it can execute when a user visits the website, capturing the visitors login information and personal account numbers.

There are three main kinds of XSS attacks: stored, reflected, and DOM based. Stored attacks target online forums and social websites, where user generated content is saved on the server, usually in a database.

Reflected XSS attacks occur in websites that send a response back to the user, for example, the results of a search query, or a Welcome message after the user has logged in. The attacker tricks the user into clicking on a link that executes a malicious script.

A webpage consists of a Document Object Model (DOM) that defines HTML components like the titles, headings, forms, tables, links, etc. that create the structure of the webpage. The browser builds and updates the DOM as it receives the webpage and runs scripts.

A DOM based attack runs a malicious script that modifies the DOM to cause it to provide login information and personal account numbers to the attacker.

Website applications that accept user input into form input fields such as are vulnerable to XSS attacks. The way to protect against XSS attacks is consider all input supplied by the user to be untrustworthy. A web application should never accept input from a user without first validating it.

It should be checked to ensure it is the data type, character or numberic, that is expected, and that it has the proper format, such as five, or five+4 numeric digits for a zip code, or a properly formatted email address or date. Unsafe characters like less-than, greater-than, ampersands, parenthesis, and others, should be replaced with escaped characters, or removed entirely.