OWASP Cross Site Scripting

Cross-site scripting (XSS) attacks are a type of injection attack. They occur when an attacker uses a vulnerability in a trusted web site to send malicious code to an unsuspecting user, generally in the form of a JavaScript or HTML browser-side script or markup. 

The user’s browser has no way to know that the script should not be trusted, and executes it. The malicious script can then transmit private data — like cookies or other session information — to the attacker, redirect the victim to web content controlled by the attacker, or perform other malicious operations on the user’s machine, all under the guise of the vulnerable site. These scripts can even rewrite the content of the HTML page.

Cross-site scripting is a moving target, and preventing it requires defense-in-depth. Due to the complexity and interactive nature of modern web applications, XSS attacks are as rampant as ever, even in the most battle-tested web applications. Make sure to never trust your inputs and let the OWASP Cross-Site Scripting Prevention Cheat Sheet be your guide.

In this lesson, we’ll look at ways to protect your applications from XSS attacks.Complete

XSS PROTECTION CHECKLIST

This component is an accordion comprised of collapsible content panels containing display text. Select the item titles to toggle the visibility of these content panels.

The following is a good list of strategies for preventing XSS attacks when you are writing your web applications:

Escaping or Output Encoding

Escaping all untrusted data before displaying its value back to the application is a critical protection against XSS attacks. Escaping essentially tells the browser that the data you are sending should be treated as data and not be interpreted in any other way. Escaping differs based on the location in the web document; because of this, there are a number of pitfalls that can occur when trying to escape all Javascript, CSS, and XML yourself. It’s best to use an escaping library such as the OWASP Java Encoder library to aid in this work. When possible, use a web application framework that provides automatic contextual escaping (such as AngularJS strict contextual escapingGo Templates, and built-in Rails HTML-escaping).

HTML Sanitization

If an application intentionally accepts and renders HTML markup from untrusted inputs, preventing XSS can be a major challenge. A library is needed that can parse and sanitize the HTML input. Some well-established projects include HtmlSanitizer for .Net, OWASP Java HTML Sanitizer, the SanitizeHelper for the Ruby on Rails framework, htmlpurifier for PHP, and bleach for Python and JS projects.

Client-Side HTML Sanitization

Even the best server-side HTML sanitizers have a history of security issues. HTML sanitization is a challenging problem for framework developers. The most secure applications sanitize HTML on both the server and on the client. For client-side HTML sanitization, consider DOMPurify, a project built by a team with deep expertise in this specific area.

Use Safe JavaScript

When passing data between various Javascript functions, it’s important to use safe Javascript functions and variable assignments that will not cause XSS if evil Javascript is included in user content. Avoid using calls like .innerHTML and document.write(). Instead, use safe Javascript functions like createTextNote() and assignments like .textContent, .value and .className, which are all resistant to XSS when passing data between different Javascript functions.

Handle JSON Properly on the Client

JavaScript Object Notation (JSON) is quickly becoming the de facto method for formatting data and dynamically generating content in modern web applications. JSON containing untrusted data is not safe from XSS attacks by default. A few important rules must be implemented when utilizing JSON:

  • Ensure the Content-Type HTTP header is set to application/json and not text/html so browsers and other clients properly recognize data as JSON.
  • Avoid using eval() to convert JavaScript objects. Instead use JSON.parse(data) or data.toJSON()
  • If you are embedding JSON in HTML (as opposed to parsing it via XHR responses), be sure to embed JSON safely. Avoid using stringification to JSON, which will lead to XSS. Instead, serialize JSON when embedding JSON in HTML using libraries such as the Yahoo! JSON Serialization library.

Content Security Policy

Implement a properly configured Content-Security-Policy (CSP) HTTP response header in your application. This is a modern browser feature that mitigates XSS and other data-injection attacks by whitelisting “safe” script hosts, restricting or forcing nonce use for inline scripts, and more. (This can be rather complex, especially when retrofitting older applications).

HTTP Only Cookies

Using the HTTPOnly attribute in cookies will prevent cookie theft via XSS. However, it is not a defense against XSS itself.

X-XSS-Protection

Using the X-XSS-Protection response header still stops some forms of reflective XSS.

General Input Validation

Validate all input. Whitelist validation can be used as one layer of defense but should not be your only XSS prevention mechanism. Do not attempt to blacklist characters; it is a losing battle.

ALL THE FRIENDS ON MY SPACE (Video)

Rewind back to 2005. Computer security was the wild west. A little website named MySpace (maybe you’ve heard of it)? was gaining popularity with the masses. And a computer tinkerer named Samy Kamkar decided to unleash a post to the social networking site that would end up spreading to over one million users in 20 hours.

The worm itself was pretty harmless. It carried the string “but most of all, samy is my hero” along with a Javascript attack payload that replicated the post and planted it on the user’s profile page, contributing to the distribution of the Javascript.

With a little bit of Javascript skill, Samy was able to set the record for the fastest spreading virus of all time. The folks at MySpace were not naive; they did indeed have several controls in place to prevent XSS. The problem was that they wanted to allow users to format certain data on their pages, so they allowed some HTML markup in user input.

MYSPACE: ADD FRIENDS… DON’T HACK THEM

So what did Samy do? Samy found a clever way to bypass their blacklist controls to inject his payload into multiple parts of a page, and then bootstrap the attack with a script that combined these into the full payload. For example, MySpace blacklisted the word “javascript,” but Samy managed to get past it by adding a newline in the middle of it (java/nscript). Internet Explorer was forgiving and ignored it, so it still executed.

MySpace had CSRF protection in place, too, but with his XSS Samy could steal the token and create a valid request, thus enabling him to spread the attack payload to other users visiting his profile.

Samy pled guilty to felony hacking charges, and was prohibited from using a computer for three years. Now a white hat hacker, Samy demonstrates attacks and solutions across various technologies and industries in a way that is supportive of the community.

KNOWLEDGE CHECK

This component is a multiple choice question. Once you have selected an option select the submit button below

True or False:

XSS attacks can be prevented by blacklisting known bad characters.

  • True
  • False