How to Prevent Cross-Site Scripting (XSS) Attacks

eSecurity Planet content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Cross-site scripting (XSS) vulnerabilities are all too common on web sites and web applications, giving hackers plenty of opportunity to launch XSS attacks and steal user data by introducing destructive scripts into online pages.

Here we’ll look at how XSS attacks work; important coding, prevention and security steps; and a range of application security products that can help make the job of XSS prevention easier.

Jump ahead to:

How Does Cross-Site Scripting (XSS) Work?

Cross-site scripting attacks happen when hackers take advantage of insecure web application validation and encoding practices to inject malicious scripts into a victim’s browser, potentially leading to account takeover, redirection to a malicious website, or other harmful activity. If the website is vulnerable to XSS attacks, the user’s input will execute as code.

Here’s how an attacker creates and then injects malicious code into a vulnerable website:

  1. Malicious code creation: After finding a vulnerable website via vulnerability scanning, subdomain enumeration, and other techniques, the attacker creates malicious code, typically in JavaScript, to take advantage of flaws on the target website.
  2. Code injection: After preparing the malicious code, the attacker injects it into the vulnerable website by modifying an executable script with malicious code.
  3. Attack Initiation: When a person visits a website that has been hacked, the malicious code is automatically run in that user’s browser.
  4. Cookie theft: As the malicious code runs, it can steal tokens, cookies, and other sensitive data from the user.
  5. Illegal access: Armed with the stolen data, the attacker gets access to the user’s session or account without authorization.

How to Prevent Cross-Site Scripting Attacks

Fortunately, good coding practices can mitigate the risk of XSS attacks. Here are some coding techniques and preventive steps to defend your web applications from XSS attacks. You can strengthen the security of your website and provide a safe user experience by putting appropriate input validation and output encoding techniques into practice.

Variable Validation

Variable validation is a technique for determining whether an input satisfies your desired criteria. By doing this, you may lower the possibility of harmful information wreaking havoc in your application by ensuring that only secure and correctly structured data passes through.

Use filters or regular expressions, for example, to ensure that an email address looks like one that is expected from a user. Don’t do any delicate operations and notify the user if it doesn’t follow the anticipated format.

PHP example:

//This code assumes we are receiving an email address input
$userEmail = $_POST['email'];

// Validate the email using a filter to ensure it's in a proper email format
if (filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
    // Email is valid, proceed with further processing
    // ...
} else {
    // Invalid email format, handle the error appropriately
    // ...
}

Output Encoding

Another way to protect against XSS attacks is output encoding. When you display dynamic content on your website (like user comments or messages), you need to encode it properly before rendering it in HTML. Encoding means converting special characters to harmless equivalents so the browser doesn’t interpret them as code.

Encoding ensures that script tags in a user’s submissions show as ordinary text rather than being executed as scripts. OWASP offers a “cheat sheet” to help developers encode securely; we’ve borrowed a few coding examples below.

Output Encoding for HTML Contexts

Inserting a variable between two basic HTML tags such as:

<div> $varUnsafe </div>

could allow data rendered as “$varUnsafe” to be modified to add an attack to a webpage. OWASP recommends HTML entity encoding for a variable as you add it to a web template, using “safe sinks” like textContent for variable placement.

Output Encoding for HTML Attribute Context

This adds variables to HTML attribute values for a variety of functions, like modifying hyperlinks, concealing items, adding alt-text, or altering styling.

Example:

<div attr="$varUnsafe">
<div attr="*x" onblur="alert(1)*"> // Example Attack

Quotes (” and ‘) are difficult to change where a variable operates and this helps prevent XSS attacks. When using JavaScript, .setAttribute and [attribute] will automatically HTML Attribute Encode and will be secure with safe HTML attributes.

Output encoding for JavaScript Context

JavaScript Contexts place variables into inline JavaScript embedded in an HTML document. variables into HTML pages, and should be placed within a quoted data value for security.

Example for “quoted data values”:

<script>alert('$varUnsafe')</script>
<script>x='$varUnsafe'</script>
<div onmouseover="'$varUnsafe'"</div>

Characters should be encoded using the \xHH format. OWASP offers a Java encoder to help developers. For JSON, the Content-Type header should be application/json and not text/html.

Other Output Encoding Dangers

Variables placed into inline CSS must be placed in a CSS property value. This way, users may easily alter the look of their web pages without jeopardizing security.

URLs should be encoded, followed by HTML attribute encoding, and when using JavaScript to construct a URL Query Value, use window.encodeURIComponent(x).

OWASP also notes a number of “dangerous contexts” that are insecure even with output encoding, including:

  • <script>Directly in a script</script>
  • <!– Inside an HTML comment –>
  • <style>Directly in CSS</style>
  • <div ToDefineAnAttribute=test />
  • <ToDefineATag href=”/test” />
  • Callback functions
  • URLs handled in code
  • JavaScript event handlers (onclick(), onerror(), onmouseover()).
  • Unsafe JS functions like eval(), setInterval(), setTimeout()

HTML Sanitization 

HTML sanitization is the process of removing any scripts or components that might be hazardous from user-generated HTML. Before user input is shown on your website, HTML sanitization acts as a safety net, removing or neutralizing any possible risks.

HTML sanitization, for instance, will filter away any dangerous components or attributes from a blog post that contains HTML code, ensuring that only safe material is displayed to users. By doing this, you maintain the safety of your website and safeguard users from potentially dangerous activities.

The use of reputable and well-maintained libraries for HTML sanitization in online applications is critical, and OWASP suggests DOMPurify as a useful tool in the fight against XSS attacks.

Other XSS Controls

Validation, encoding and sanitization are primary XSS prevention techniques, but others can help limit damage from inadvertent mistakes. These include cookie attributes, which change how JavaScript and browsers can interact with cookies, and a content security policy allowlist that prevents content from being loaded.

Also read:

3 Types of Cross-Site Scripting Attacks

There are three XSS attack types, each with their own attack techniques and targets. We’ll go into each in greater detail below.

  • Stored XSS includes injecting dangerous scripts that remain on the server permanently
  • Document Object Model (DOM)-based XSS manipulates the DOM to conduct malicious operations directly on the user’s browser
  • Reflected XSS reflects harmful scripts from the victim’s input

Stored XSS

Stored XSS involves the long-term storage of malicious scripts or code on a web server, database, or application. These scripts are then presented to unwary individuals who enter a given website or read a particular piece of information. Sanitize and evaluate all user-generated material before storing it and before presenting it on websites to avoid this.

Stored XSS chart from Research Gate by Hossain Shahriar.
Image from Research Gate by Hossain Shahriar

Reflected XSS

Reflected XSS is a type of attack where malicious scripts or code are injected into the URL or request parameters, and the server reflects this input back to the user in the response. When a user clicks on a manipulated link, the user unknowingly runs the injected script. Validate and sanitize all user input, especially information from URL parameters or form fields, to avoid this.

Reflected XSS chart from Research Gate by Hossain Shahriar.
Image from Research Gate by Hossain Shahriar

DOM-Based XSS

In a DOM-Based XSS attack, malicious scripts manipulate the DOM to damage operations. DOM-Based XSS doesn’t require server interaction, in contrast to other XSS attacks. Before dynamically altering the DOM, it is essential to verify and sanitize user input in order to avoid this.

DOM-based XSS chart from Research Gate by Hossain Shahriar.
Image from Research Gate by Hossain Shahriar

3 Real-Life Examples of Cross-Site Scripting Attacks

British Airways, Fortnite, and eBay are three of the most notable real-life victims of XSS attacks where malicious hackers exploited vulnerabilities in their websites to inject harmful scripts and compromise user data. These high-profile breaches underscore the critical importance of implementing robust security measures to safeguard against such cyber threats and protect user information in the ever-evolving digital landscape.

British Airways

In 2018, British Airways was a target by Magecart, a hacker group known for their credit card skimming tactics. They exploited an XSS flaw in Feedify’s JavaScript library, modifying the script and sending private client information to a fake server. The fake server had an SSL certificate, deceiving consumers into believing transactions were safe. The hackers stole 380,000 booking transactions before anyone discovered the malware flaw.

Fortnite

In 2019, Fortnite, a popular online game with over 200 million users, had an XSS flaw that went unreported. Attackers may have combined the XSS issue with an unsafe single sign-on (SSO) vulnerability to steal virtual money, listen to player conversations, and wreak havoc. Fortnite was informed of the attack by Check Point, but it’s unclear if attackers exploited the vulnerability at the time.

eBay

In 2015 and 2016, a serious XSS flaw on eBay made it possible for attackers to insert malicious code into pages, giving them complete access to seller accounts. The consequences included discounted products, payment details, and manipulation of high-value listings. Although eBay fixed the flaw, follow-on attacks persisted until 2017, making for a lengthy battle against the threats.

What Tools Help Prevent XSS Attacks?

Vulnerability scanning tools, penetration testing tools and web application firewalls can help prevent XSS attacks and keep your website from being compromised. Here are a number of tools you may want to consider, including some specially designed for XSS.

Vulnerability Scanning tools

Vulnerability scanning tools identify and assess security weaknesses in web applications, networks, and systems. They scan code and inputs, detect potential vulnerabilities, and report them to developers and IT and security teams for remediation and patching.

  • XSStrike is an open-source XSS scanner that can identify different XSS vulnerabilities. XSStrike can be helpful for spotting possible XSS problems, but how well it works may depend on the particulars of the application being tested.
  • XSS Hunter was created to assist security analysts and programmers in locating and monitoring XSS vulnerabilities. It is capable of finding and confirming XSS issues.
  • XSSER is another free and open-source XSS scanner. Similar to XSStrike, the application and its security measures will help determine success.
  • Acunetix is an effective tool for finding online vulnerabilities, including XSS flaws. It is widely used and well regarded.
  • Burp Suite is another highly regard tool for evaluating the security of online applications. Although it offers a variety of options for testing web applications, how it is set up and used will determine how well it works to find XSS vulnerabilities.
  • Intruder is another vulnerability scanner used to identify XSS vulnerabilities as well as other security flaws in online applications. The setting and scope of its security checks will help determine how effective it is.
  • Dalfox is an open-source XSS scanning tool that is quick and effective. Its usefulness is dependent on the situation in which it is utilized, much like other scanners.

Web Application Firewalls

A web application firewall (WAF) is a security appliance that monitors, filters and blocks malicious traffic before it reaches a web application. It acts as a gatekeeper, detecting and blocking attacks like XSS and SQL injection. WAFs also provide real-time protection by actively analyzing traffic and blocking harmful requests.

While WAFs offer a number of protections for web applications, OWASP notes some limitations for XSS protection, saying they can be “unreliable and new bypass techniques are being discovered regularly. WAFs also don’t address the root cause of an XSS vulnerability. In addition, WAFs also miss a class of XSS vulnerabilities that operate exclusively client-side. WAFs are not recommended for preventing XSS, especially DOM-Based XSS.”

Here are some of the leaders in the WAF market:

  • Akamai App and API Protector: Akamai offers security services, and its WAF product is designed to defend apps against a variety of assaults, including XSS.
  • AppTrana is a cloud-based application security solution with WAF features to defend against XSS and other web application threats.
  • AWS WAF: The web application firewall offered by Amazon Web Services (AWS) may be used to defend applications hosted on AWS against a variety of threats, including XSS.
  • Cloudflare WAF is a popular solution that provides defense against XSS assaults and other web application dangers.
  • Imperva WAF: Imperva offers a variety of security products, and their WAF is intended to defend web applications against various threats such as XSS.
  • Microsoft Azure App Gateway: Azure’s Application Gateway offers WAF capabilities to aid in defending web applications hosted on Azure from typical attacks, such as XSS.
  • F5 Advanced WAF is designed to shield online applications from XSS attacks and other security risks. To find and stop attempts at malicious code injection, it combines signature-based and behavior-based detection approaches.
  • FASTLY is a content delivery network (CDN) that also provides online security services, such as WAF capabilities. Their WAF is intended to recognize and stop a variety of XSS attacks and other web application dangers.
  • Fortinet Fortiweb is a specialized web application firewall that offers a defense against typical web application vulnerabilities like XSS. To identify and stop such assaults, it combines signature-based and behavioral analysis approaches.
  • Radware offers a WAF solution made to safeguard online applications from a variety of dangers, such as XSS assaults. To recognize and prevent malicious code injections, it makes use of a variety of security measures.
  • Wallarm offers a range of application and API security features, including a cloud-based WAF. To find and fix XSS and other web application vulnerabilities, it uses machine learning and behavioral analysis.

Also read:

Bottom Line: Preventing XSS Attacks

Cross-site scripting (XSS) vulnerabilities are all too common, and organizations that depend on their websites and web applications must prioritize cybersecurity and secure coding practices to keep their assets – and brand reputation – safe. XSS attacks can leave seemingly harmless web pages full of destructive scripts, leading to catastrophic consequences and customer harm.

To safeguard your web applications, take proactive measures like routine vulnerability scanning, HTTP-Only cookies, escaping output, and validating user input. XSS attacks happen in a number of ways, and implementing variable validation, output encoding, and HTML sanitization can help enhance security.

Refactor your code to avoid unsafe sinks and rely on trusted libraries like DOMPurify to maintain a safe and user-friendly website. Prioritizing XSS attack prevention and web application security will instill confidence in users, knowing they can count on a secure experience.

Read next: What is Dynamic Application Security Testing (DAST)?

Get the Free Cybersecurity Newsletter

Strengthen your organization’s IT security defenses by keeping up to date on the latest cybersecurity news, solutions, and best practices. Delivered every Monday, Tuesday and Thursday

Kaye Timonera Avatar

Subscribe to Cybersecurity Insider

Strengthen your organization’s IT security defenses by keeping abreast of the latest cybersecurity news, solutions, and best practices.




Top Cybersecurity Companies

Get the Free Newsletter!

Subscribe to Cybersecurity Insider for top news, trends & analysis