What is Cross-Site Scripting (XSS) and How to Prevent It?

We live in the era of rapid digital transformation with innovative solutions allowing us to perform a wide range of things faster and easier. As technologies continue advancing, hackers and threat actors create sophisticated counter-approaches by exploiting these futuristic technologies.

Although information security professionals are constantly working to develop practical cybersecurity tools, website users are exposed to new vulnerabilities — with cross-site scripting (XSS) being one of the most common cyber threats.

What is Cross-Site Scripting (XSS)?

Cross-site scripting (XSS) is a code injection security attack that allows a threat actor to insert malicious scripts into web browsers belonging to trusted web applications or websites. Unlike SQL injection and other attack vectors that access the database directly, XSS focuses on the end-user to gain complete control over the operations.

By impersonating users, the bad actor can steal the user’s active session cookie and get access to their confidential data. The victim’s browser cannot distinguish legitimate markup from malicious markup and executes it.

XSS ranks eighth in the list of OWASP Top 10 most critical web application vulnerabilities. Open Web Application Security Project rankings are provided by security experts from all over the world to help developers safeguard any weaknesses in the system and reduce the presence of known risks.

What is Cross-Site Scripting (XSS) and How to Prevent It?

What are types of XSS attacks?

Based on where a hacker feeds malicious input, XSS can be divided into three main categories:

Stored Cross-Site Scripting

Stored XSS or Persistent XSS is the most dangerous type of XSS attack, which can compromise many visitors and lead to devastating consequences. Stored XSS arises when the user’s input is not validated before storing content and rendering it on the web page.

Social networks, forums, blogging websites, user profiles, message boards, and comment sections are common areas where XSS can be stored. Threat actors leverage this vulnerability by injecting XSS payloads on the most visited website pages. Upon clicking on the crafted link and opening the viral page, the victim’s web browser executes the payload client-side.

Below is a clear illustration of a stored XSS vulnerability. A user can leave messages to a message board application, which other users can view:

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

The application doesn’t process the data further, making it simple for a fraudster to send a message that targets other users:

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

Reflected Cross-Site Scripting

Reflected XSS is the most commonly employed cross-site scripting attack (also known as non-persistent XSS). While performing this attack, a hacker adds malicious code to the end of the URL. Once the user clicks this link in their web browser, the browser executes the reflected XSS payload.

The threat actor usually uses malicious URLs, phishing emails, and other digital social engineering assaults to trick the victim into clicking on the link. As a rule, the following XSS attacks are made using social networks.

To illustrate reflected XSS vulnerability, take a look at the example below:

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

The web application doesn’t carry out any additional data processing, enabling a hacker to execute the following attack:

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

DOM-Based Cross-Site Scripting

Perpetrators can insert malicious code into a page due to modifying the DOM environment (Document Object Model) when it doesn’t properly filter user input. The attack’s HTML source code and response are identical in DOM-based XSS. The page itself remains the same, but due to the malicious changes made to the DOM environment, the client-side code on the page runs unexpectedly.

DOM-based XSS is entirely a client-side injection vulnerability. Therefore, the parasitic payload never reaches the server. Due to the unique nature of DOM-based XSS,  it is difficult for Web Application Firewalls (WAFs) and other web application security tools to detect the attacks.

The web application in the example below employs 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 threat actor has control over the input field’s value, they can easily create a malicious value that causes their script to act in an unsafe manner:

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

How can threat actor exploit XSS?

As a rule, the malicious content sent to the web browser takes the form of a segment of JavaScript but may also include HTML, Flash, VBScript, ActiveX, or any other code the browser can execute.

JavaScript-based XSS attacks are the most widespread since JavaScript is an underlying component of most browsing experiences.

JavaScript can read cookies in the browser, allowing the perpetrator to perform an XSS attack and impersonate the user for identity theft and other nefarious activities. JavaScript provides several modules and methods to make HTTP requests, which can be used to send data (such as stolen cookies) back to the threat actor. What is more, client-side JavaScript’s vulnerability to hacking can help fraudsters receive access to APIs and easily compromise clients’ geographical location, webcam data, and other private information.

By leveraging XSS vulnerabilities, a threat actor can carry out malicious activities, such as:

  • Hijack the user’s session. Session hijacking is a method of taking over a user’s authenticated session. Session cookies contain critical data that may allow a threat actor to masquerade as a legitimate user and obtain the session ID if compromised.
  • Perform unauthorized actions. Attackers cannot steal the cookies through JavaScript if the HTTPOnly cookie attribute is set. But, performing the XSS attack, they can still carry out unauthorized activities within the application on the victim’s behalf.
  • Perform phishing attacks. Phishing is a common type of cyber attack where the perpetrator injects a form into the vulnerable page and uses that altered form to steal the user’s credential information, typically in the form of passwords, bank account information, and credit card numbers.
  • Capture users’ keystrokes. This is where a hacker inserts a JavaScript keylogger into the vulnerable page and monitors the victim’s keystrokes on the current web page. The information gathered can disclose usernames, passwords, and potentially compromising data that hackers can use for financial benefit.
  • Steal sensitive information. By performing an XSS attack, a perpetrator collects data from the user’s current session. For instance, cross-site scripting attacks on online banking apps can allow attackers to view the current balance, transactional details, personal information, etc.

XSS vulnerabilities foster the escalation of attacks to a more serious level and, if abused by fraudsters, can cause severe damage. XSS attacks can lead to sensitive data exposure, compromise of the victim’s account, and worse.

By creating a fake form, attackers lure web users into giving their login details, which allows them to receive all information about the user. Once the hackers’ cunning intention to deceive their victims is fulfilled, the obtained data can be used for identity theft or financial fraud.

Real-Life XSS Examples

The cross-site scripting attacks have been able to wreak havoc on well-known companies. The following are the most famous examples:

Fortnite

Fortnite is a gaming phenomenon – one of the most popular online battle games with more than 200 million players worldwide. Due to its huge popularity, the game platform became the main target for malicious actors and could face an XSS attack leading to data leakage in early 2019.

Security researchers from Check Point Software Technologies have discovered the cross-site scripting vulnerability in the game that could have allowed hackers to take over gamers’ accounts, access their sensitive information, steal in-game virtual currency, and eavesdrop on their conversations. The experts have privately reported about the identified XSS vulnerabilities to the game developer Epic Games, and the company has fixed the issues.

British Airways

In 2018, British Airways faced a data breach that affected 380,000 booking transactions. The RiskIQ researchers managed to catch Magecart — one of the largest hacker groups notorious for employing online skimming techniques. The hackers attacked the British Airways website by taking advantage of an XSS vulnerability in a JavaScript library called Feedify.

Having changed the script, the perpetrators sent customer data to their designated server with a domain name similar to British Airways and succeeded in performing credit card skimming. The malicious server had an SSL certificate, so customers fully trusted the server they purchased from.

eBay

eBay is one of the earliest and most popular e-commerce platforms. However, it was compromised through a cross-site scripting vulnerability in late 2014 and early 2015. The website used a URL parameter that redirected eBay members to different pages, but the parameter’s value was not checked before including it in the page. Due to this flaw, the attackers could craft a URL containing a parasitic iFrame and inject it into the legitimate eBay website.

Thus, fraudsters could access eBay seller accounts, steal payment details, sell products at a discount, and manipulate eBay listings of valuable products such as vehicles. Although eBay subsequently fixed the issue, recurrent attacks continued until 2017.

Facebook

In 2011, three separate XSS vulnerabilities were detected on Facebook sites in 10 days. At least two were used to spread viral links and attacks on Facebook users to access or change information on their accounts.

Due to insufficient JavaScript filtering, the first issue came through a page on the mobile API version of Facebook. The interface was prompting people to post an arbitrary message on their walls. Moreover, a second XSS vulnerability was developed using HTML within a viral page to spread malware across the website. Several links rapidly distributed fishing attacks, which caught security researchers’ attention, and Facebook successfully managed to patch the XSS vulnerability.

The last XSS issue that came to light was with a Facebook “channel” page for session management, where a code update mistakenly modified the page’s behavior. However, once security experts noticed it, Facebook immediately fixed the flaw.

Detecting Cross-Site Scripting vulnerabilities

The reasons for the occurrence of XSS vulnerabilities are:

  • Input validation is not performed.
  • Output to the browser is not converted into HTML character entities.

Generally, web scanning tools are used to look for security vulnerabilities in web applications. These automated tools inject malicious scripts into the web application, such as GET or POST variables, URLs, cookies, and other code that could carry out XSS attacks. If the tool succeeds in injecting the script into the webpage, then the site is exposed to XSS. After discovering malware attack vectors, the tool notifies the user of the detected vulnerability.

XSS Prevention & Mitigation

Cross-site Scripting (XSS) can seriously threaten individual users and companies whose websites may be infected. In some cases, it’s challenging to deter the attack. For this reason, you must thoroughly sanitize all untrusted data to keep yourself safe from XSS. To reduce risk to your web application, never allow your browser to process data received as input without validating it.

Specific prevention methods vary depending on the subtype of XSS vulnerability, and user input usage context. However, certain general measures should be taken to safeguard your users against XSS attacks and keep your web application safe:

Validation

This is where you ensure the inputs are safe for processing within the code and malformed data does not damage a website, database, and users. By rejecting requests from external parties or sources, input validation prevents users from entering special characters into data entry fields on the websites. Input validation deters injection attacks, data leaks, and compromised systems.

Encoding

Encoding is an essential line of XSS defense. Here, at the point where user-controllable data is output in HTTP responses, you encode the output so that the browser interprets it only as data, not as executable code. Various encoding methods may be necessary depending on the output context since browsers analyze JavaScript, JS, URL, HTML, and CSS  differently.

Setting HttpOnly flags

The following precautionary method helps mitigate XSS attacks. If this additional flag is included in the HTTP response header, the cookie containing the user’s confidential information cannot be accessed through the client script. Employ the HttpOnly attribute to deter JavaScript from reading the sensitive content of the cookie, making it difficult for a hacker to hijack the session and take over the account.

Content Security Policy

Content Security Policy (CSP) is an additional layer of security designed to reduce the severity of any XSS vulnerabilities that may occur. This browser security tool helps repel and mitigate XSS and other client-side attacks.

Regular scanning

You should run a robust web vulnerability scanner on your web servers to prevent malicious content from being executed by unaware users or visitors. Pentesters and security experts regularly use XSS scanning tools for web application analysis.

Penetration testing

Penetration testing is a cybersecurity technique that uses the hacker perspective to find weaknesses in systems and mitigate cybersecurity risks, enabling organizations to close the identified loopholes before malicious hackers get to them.

Vulnerability scanning is not a substitute for penetration testing. Pentesters imitate the approaches of real-world threat actors, concentrating on security vulnerabilities that cannot be identified automatically.

The QAwerk team consists of professional pentesters who have a good command of advanced tools to conduct thorough security audits and vulnerability assessment.

How to effectively fix XSS errors?

You can take several measures to fix your website if cross-site scripting occurs:

  • Find vulnerable code. In the initial phase of cross-site scripting recovery, identify the location of the vulnerability.
  • Delete malicious content and backdoors. Once you know where the malware is located, you can remove any malicious content or incorrect data from your database and restore it to a clean state with a robust website malware removal tool. Additionally, you must scan the rest of your website and file systems for backdoors to correct existing errors and maintain your website’s reputation.
  • Patch the vulnerability. Perpetrators frequently take advantage of weaknesses in databases, apps, and third-party components. If they pose a real risk, they need to be patched. Once you have identified the vulnerable software, distribute and apply updates to the vulnerable code to remove vulnerabilities that have been flagged.
  • Change your credentials. In the event of XSS, it is crucial to immediately reset your passwords and application secrets with a strong password policy once the vulnerability is patched. Make sure there are no backdoors or rogue admin users in the database by clearing up your data to prevent reinfection.
  • Set up a WAF. A key component of your security strategy is setting up a powerful web application firewall (WAF) to specifically address XSS by blocking malicious server requests to your website that aim to exfiltrate sensitive data. With a suitable WAF, you can protect against potential threats before patches are made available.

In Conclusion

Cross-site scripting attack exploits web security holes by allowing a threat actor to bypass client-side security mechanisms and inject malicious JavaScript code into otherwise benign websites. Based on the functionality and data processed by the vulnerable application, XSS vulnerabilities can pose a significant threat to companies. By masquerading as a reputable source with an enticing request, hackers can impersonate users’ accounts, observe their behavior, load external content, and take over the entire web sessions of the victim users.

Therefore, it’s crucial to understand where your system has flaws and take preventive measures before an XSS attack seriously harms the website and its visitors. Unless the variables in a web application go through a validation process, they are a potential vulnerability. The most effective protection approaches to deter XSS attacks are: data sanitization, cookie protection, removing HTML tags from strings, vulnerability scanning, and regular penetration testing by professionals.

Increase your web app security now: The ultimate XSS cheat sheet

Increase your web app security now: The ultimate XSS cheat sheet
Please enter your business email isn′t a business email