Published on

What is Cross-Site-Scripting (XSS)? | How XSS Works? | And How to Prevent it

If you're a developer, chances are that you've heard of cross-site scripting. Cross-site scripting, commonly known as XSS, is one of the top 10 most common web security vulneribilities according to OWASP. Cross-site scripting to be a major problem in many web application, and it can result in some serious problems. As developer, it's important to know what XSS is and to be aware of it, but it's even more important to know how to prevent it. Cybersecurity isn't just for security specialists, it's for everyone.

What is Cross-Site Scripting (XSS)?

cross-site-scripting

Cross site scripting (XSS) is an attack in which an attacker injects malicious executable scripts into the code of a trusted application or website. Attackers often initiate an XSS attack by sending a malicious link to a user and enticing the user to click it. If the app or website lacks proper data sanitization, the malicious link executes the attacker's chosen code on the user's system. As a result, the attacker can steal the user's active session cookie.

In Simple Words: If you can control the JavaScript, on which a typical website functions. Then, XSS is a possibility.

How Browser & Website Function?

Before diving in deep, it's important to get some basic knowledge about website and browser.

We know the world runs on some basic rules & principles, to save us from havoc. In a similar manner, the Internet does, & so, the browser and websites do.

Browser & Websites co-exist together on the basis of certain rules. Some rules, mentioned-below, that you should know of, to have a clear understanding of the security impact of flaw:

1. Same-Origin Policy (SOP)

same-origin-policy

The same-origin policy is a web browser security mechanism that aims to prevent websites from attacking each other.

The same-origin policy restricts scripts on one origin from accessing data from another origin. An origin consists of a URI scheme, domain and port number. For example, consider the following URL:

http://normal-website.com/example/example.html

This uses the scheme http, the domain normal-website.com, and the port number 80. The following table shows how the same-origin policy will be applied if content at the above URL tries to access other origins:

 URL accessed Access permitted?
http://normal-website.com/example/ Yes: same scheme, domain, and port
http://normal-website.com/example2/ Yes: same scheme, domain, and port
https://normal-website.com/example/ No: different scheme and port
http://en.normal-website.com/example/ No: different domain
http://www.normal-website.com/example/ No: different domain
http://normal-website.com:8080/example/ No: different port*

In Simple Words: The server defines the rules for a browser, in which *Website1** can interact with a **Website2**.

2. Cross-Origin Resource Sharing (CORS)

CORS is an HTTP-header based mechanism that allows a server to indicate any other origins (domain, scheme, or port) than its own from which a browser should permit loading of resources — Mozilla.

“A relaxation in SOP for easy & allowed interaction with trusted origins.”

In Simple Words: CORS is the HTTP header, that server sends, to state a browser which sites are in its friends list/ allow list.

3. Cross-Site Request Forgery tokens (CSRF)

To prevent cross-origin writes, an unguessable token in the request — known as a Cross-Site Request Forgery (CSRF) token is added. You must prevent cross-origin reads of pages that require CSRF token — Mozilla.

In Simple Words: CSRF tokens are- a one time user, non-predictable(random) and long (at least 16 bytes / 128 bits) token(value/key), generated by the server (not in control of the user) — given to a browser to perform a single task.

An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user’s web browser. The browser may store it and send it back with later requests to the same server. Typically, it’s used to tell if two requests came from the same browser — keeping a user logged-in, for example. It remembers stateful information for the stateless HTTP protocol — Mozilla.

In Simple Words: Cookie is, generally, a replacement of your credentials (Username & Password) that a server sends back and forth to the browser to remind him of a particular session(HTTP-a Stateless protocol, that forgets who you are & what you want from him, after every request) and keep a track of the activities performed.

HttpOnly is an additional flag included in a Set-Cookie HTTP response header. Using the HttpOnly flag when generating a cookie helps mitigate the risk of client-side script accessing the protected cookie. This attribute specifies that a cookie is not accessible through script. By using HTTP-only cookies, a Web site eliminates the possibility that sensitive information contained in the cookie can be sent to a hacker’s computer or Web site with the script. A cookie is set on the client with an HTTP response header.

“Tagging a cookie as httpOnly forbids JavaScript from accessing it, protecting it from being sent to a third party. However, the TRACE method can be used to bypass this protection and access the cookie even in this scenario.”-OWASP

Exception: If an application allows HTTP-method: TRACE. Cross-Site Tracing (XST) is still a possibility, where again Cookie could be stolen, despite the Flag: Set-Cookie HTTPOnly.”

In Simple Words: HTTPOnly attribute specifies that a cookie is not accessible through script, but only by an HTTP header

Note: The use of the above individual technique is not enough, but when used together, can mitigate the risk of cross-site scripting. Used alone, they cannot completely the danger of cross-site scripting.

There are several other rules that are used by a browser for safe-secure communication. But, here we are limiting the scope of the rules for an XSS.

Now, that we know what an XSS is and how a browser & website function, on the basis of certain rules. Let's move further to types of XSS and important XSSs' in Bug Hunting.

What are the types of XSS attacks?

There are three types of XSS attacks. These are:

  • Reflected XSS, where the malicious script comes from the current HTTP request.

  • Stored XSS, where the malicious script comes from the website's database.

  • DOM-based XSS, where the vulnerability exists in client-side code rather than server-side code.

Reflected cross-site scripting

Reflected XSS? You can clearly guess by the name itself. “Reflected”, that means something needs to be reflected. Exactly, XSS Vulnerability arises when the injected script is reflected off the web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server as part of the request.

Here is a simple example of a reflected XSS vulnerability:

https://insecure-website.com/status?message=All+is+well.

<p>Status: All is well.</p>

The application doesn't perform any other processing of the data, so an attacker can easily construct an attack like this:

https://insecure-website.com/status?message=<script>/*+Bad+stuff+here...+*/</script>

<p>Status: <script>/* Bad stuff here... */</script></p>

If the user visits the URL constructed by the attacker, then the attacker's script executes in the user's browser, in the context of that user's session with the application. At that point, the script can carry out any action, and retrieve any data, to which the user has access.

Stored cross-site scripting

Stored XSS (also known as persistent or second-order XSS) arises when an application receives data from an untrusted source and includes that data within its later HTTP responses in an unsafe way.

The data in question might be submitted to the application via HTTP requests; for example, comments on a blog post, user nicknames in a chat room, or contact details on a customer order. In other cases, the data might arrive from other untrusted sources; for example, a webmail application displaying messages received over SMTP, a marketing application displaying social media posts, or a network monitoring application displaying packet data from network traffic.

Here is a simple example of a stored XSS vulnerability. A message board application lets users submit messages, which are displayed to other users:

<p>Hello, this is my message!</p>

The application doesn't perform any other processing of the data, so an attacker can easily send a message that attacks other users:

<p><script>/* Bad stuff here... */</script></p>

DOM-based cross-site scripting

DOM-based XSS (also known as DOM XSS) arises when an application contains some client-side JavaScript that processes data from an untrusted source in an unsafe way, usually by writing the data back to the DOM.

In the following example, an application uses some JavaScript to read the value from an input field and write that value to an element within the HTML:

var search = document.getElementById('search').value
var results = document.getElementById('results')
results.innerHTML = 'You searched for: ' + search

If the attacker can control the value of the input field, they can easily construct a malicious value that causes their own script to execute:

You searched for: <img src=1 onerror='/* Bad stuff here... */'>

In a typical case, the input field would be populated from part of the HTTP request, such as a URL query string parameter, allowing the attacker to deliver an attack using a malicious URL, in the same manner as reflected XSS.

How to prevent XSS attacks

Preventing cross-site scripting is trivial in some cases but can be much harder depending on the complexity of the application and the ways it handles user-controllable data.

In general, effectively preventing XSS vulnerabilities is likely to involve a combination of the following measures:

  • Filter input on arrival. At the point where user input is received, filter as strictly as possible based on what is expected or valid input.

  • Encode data on output At the point where user-controllable data is output in HTTP responses, encode the output to prevent it from being interpreted as active content Depending on the output context, this might require applying combinations of HTML, URL, JavaScript, and CSS encoding.

  • Use appropriate response headers To prevent XSS in HTTP responses that aren't intended to contain any HTML or JavaScript, you can use the Content-Type and X-Content-Type-Options headers to ensure that browsers interpret the responses in the way you intend.

  • Content Security Policy As a last line defense, you can use Content Security Policy(CSP) to reduce the severity of any XSS vulnerability that still occur.