The third security threat in the Open Web Application Security Project (OWASP) 2013 top 10 security vulnerabilities list is cross-site scripting, usually referred to as XSS. This threat exists whenever a website displays content that is generated by a third party. As a developer, when users trust you by accessing your website they are giving you a significant amount of power over what your code can make their browsers do.
Many popular sites today allow users to interact with other users; users can do so through comments on videos, posts, and articles; status updates on social sites; or product reviews on marketplace sites. When you as a developer deliver content to one user that was created by someone else, it is your responsibility to make sure it is safe.
Defining the Problem
A simple example of how XSS works is through the comments section on a blog. When users access the site, their browser receives the text to be displayed on the comments section. This is text that was created by other users. Ideally, this content consists of simple text, but a malicious user could submit text containing HTML code. This could act as a reference to an image file on another site or a script, which, if executed by your browser, could post a comment on your behalf or send some of your session information to another site.
OWASP outlines using components with known vulnerabilities as follows:
Detection & Prevention
Once you are aware of this type of attack, detection and prevention are fairly straightforward. You are vulnerable if your site displays any kind of content that is not generated directly by you. This is almost always the case.
Prevention is a matter of being careful about how you process the content that is generated by other parties. There are several approaches to this and they vary in complexity and efficiency. One of the simplest options is to only allow a certain set of characters to be entered by the user, if they can only enter basic English letters, punctuation marks, and numbers it will be harder for them to enter malicious code.
More sophisticated solutions involve the use of sanitizing libraries to process all the third party content that will be displayed on your site. Their effect is to rewrite the content so it is safe to display. In the example we mentioned before it would transform the content so the user’s browser can safely display the comment as text containing the HTML and not interpret the HTML as code it needs to execute.
Most popular websites use and display content that is created by their users. This can create some issues since malicious users can submit content that other users’ browser could execute as content provided by you and have undesired security effects. It is easy but very important to sanitize any user submitted data before delivering it to other users through your website.