How to prevent XSS attacks

Prevent the execution of malicious scripts and theft of user information by blocking HTML inputs, sanitizing data, securing cookies, and deploying web application firewalls (WAFs).

Learning Objectives

After reading this article you will be able to:

  • Define "XSS"
  • Understand how XSS works
  • Learn ways to prevent XSS attacks

Copy article link

What is XSS?

Cross-site scripting (XSS) is a tactic in which an attacker injects malicious code via one or more web scripts into a legitimate website or web application. When a user loads the website or runs the web application, these scripts execute within the user’s browser.

The scripts could perform a variety of malicious actions, such as stealing users’ HTTP cookies, session tokens, or other sensitive information. An attacker could use this information to impersonate users and gain unauthorized access to accounts on different platforms, like social media platforms or banking websites. Additionally, the scripts could deface websites, redirect users to malicious sites, or extract confidential data from web applications.

To learn more, see What is cross-site scripting?

What are the types of XSS attacks?

The two most prominent types of XSS attacks are reflected (non-persistent) and stored (persistent) XSS.

Reflected XSS (non-persistent)

Reflected XSS attacks can occur when legitimate websites fail to validate or sanitize user input. These attacks often start with social engineering, in which attackers send phishing emails or leave messages in online forum posts with a link that entices users to click on it. Typically, the link includes the URL of a legitimate website appended with malicious code.

When a user clicks on the link, their browser sends a request to the legitimate website, which reflects the injected code back to the user’s browser. Since the website does not properly sanitize the input, the malicious script executes in the user’s browser.

The code could copy the user’s cookies and send them to the attackers. If the attackers acquire a session cookie, they could take control of the session, which might enable them to make fraudulent purchases, steal banking information, or post spam on social media platforms, among other malicious actions.

This type of XSS is called a “reflected” attack because the malicious script is reflected off the web server and executed in the user’s browser. It is also referred to as “non-persistent” because the script operates only in the user’s browser when the page is loaded, not on a continual basis.

Stored XSS (persistent)

Stored XSS attacks are more severe than reflected XSS attacks. With stored XSS, a malicious script is permanently stored on the target server.

Attackers usually carry out this form of XSS by embedding a malicious script within a form field, such as a comment box, user profile, or any input field that accepts and stores user content. Once the post, comment, or form is submitted, the script is injected into the web application and saved in the web application’s database. When other users load the affected page, the stored script is executed in their browsers. As with reflected XSS attacks, the script could steal cookies or other user information, which could then be sent back to the attacker.

This type of XSS is also referred to as “persistent” because the execution occurs every time the page is accessed. That is also what makes stored XSS attacks particularly dangerous: they can affect a large number of users without any interaction beyond simply viewing a web page.

How can users prevent XSS attacks?

Individual users can take several steps to reduce the risk of XSS attacks:

Identify suspicious emails and messages

Because many XSS attacks begin with phishing schemes or other social engineering tactics, users should learn how to identify suspicious emails and messages. By notifying appropriate IT or security teams, users can help halt XSS attacks and address other security issues.

Scrutinize links

If users see a link within an online forum, or in a social post from someone they do not know or trust, they should think twice before clicking on it. Even if the link seems legitimate, users should proceed with caution. Many links that trigger XSS attacks appear legitimate because they contain legitimate URLs within them. But users should examine the full link — including everything after the .com, .org, .gov, or other suffix. Unexpected text after the page address might be malicious code.

How can developers prevent XSS attacks?

Developers can play a vital role in preventing XSS attacks by implementing a few key best practices:

Validate inputs

Developers can implement rules that prevent users from posting data on a page or into a form unless it meets certain criteria. For example, if a form asks for a social security number or a phone number, developers can create a rule that this input should contain only numbers, dashes, or parentheses. For more robust attack prevention, developers can set validation rules that explicitly reject tags or characters commonly used in XSS attacks, such as < script > tags.

Developers can also prevent users from using HTML in comments, posts, and form inputs. HTML content can be a means of posting malicious scripts or concealing links to URLs that include malicious code.

If organizations want to allow users to post rich content, such as formatted text or images, they could incorporate Markdown (a lightweight markup language) or enable rich text formatting within a “What-You-See-Is-What-You-Get” (WYSIWYG) editor. Both of those methods are more secure ways of supporting rich content.

Sanitize data

Developers can help prevent harm from XSS attacks by implementing a process for examining data after it has been posted to the web server but before it is displayed to another user. Even if the developers allow the use of HTML, for example, they can sanitize all HTML input and filter out any malicious code before it executes in a browser.

Output encoding and “escaping” follow a similar approach. The idea is to transform malicious scripts or other code found within user input into ordinary text before anything is written to a page. Output encoding converts code into a different format; escaping adds special characters to the code (like backslashes or quotes). In either case, a browser will not interpret the resulting text as code and execute it. While sanitizing filters out code, output encoding and escaping preserve the code while rendering it harmless.

Review and test code

Developers should integrate security throughout web application development. For example, they should conduct code reviews, focusing especially on areas where user input is accepted and displayed. They should also conduct threat modeling and testing to identify vulnerabilities before applications go live.

How can security teams prevent and respond to XSS attacks?

Security teams can implement several best practices to help prevent and rapidly respond to XSS attacks:

Ensure appropriate web server and app security configurations

Security teams can take several steps to help ensure web servers are configured correctly to block malicious scripts and prevent attackers from stealing user cookies:

Implement a content security policy: Developers and security teams should work together to define strong content security policies (CSPs) for websites and web applications, and implement them on web servers. A CSP is an added layer of security that can detect and mitigate certain types of attacks. To prevent XSS attacks, it restricts what scripts can be executed. Web servers can be configured to return CSP HTTP response headers that prohibit browsers from loading harmful scripts.

Secure cookies: Security teams can set special rules for how web servers handle cookies to reduce the likelihood of cookie theft. For example, they can tie cookies to particular IP addresses. Because most users have a dynamic IP address, the connections between an IP address and cookies do not last long. As a result, attackers are not able to steal and use those cookies.

Additionally, security teams can block JavaScript from accessing cookies altogether. One means of doing so is to add the HttpOnly flag to cookies when generating them. The flag indicates that the cookies might contain sensitive user information, such as session tokens or authentication credentials. A browser that supports the HttpOnly flag will not reveal that information.

Implement a web application firewall

A web application firewall (WAF) can offer a key line of defense against XSS attacks. Operating as a reverse-proxy server positioned in front of web applications, a WAF protects those applications by monitoring and filtering HTTP traffic between the applications and the Internet. Organizations can set WAF rules to inspect URLs for malicious scripts and block them from being reflected to users. WAF solutions with machine learning offer even stronger protection by detecting attempts to bypass rules and identifying variations on known attacks.

Focus on phishing detection and response

Since many XSS attacks begin with phishing, security teams should strengthen defenses against phishing attacks. In addition to educating users on how to identify suspicious emails and messages, security teams can implement security capabilities for blocking email spam, use a browser isolation service to prevent execution of malware, install a secure web gateway (SWG) to prevent users from downloading malicious files, and deploy email security tools to detect and block phishing attempts in real time.

Run security tests on applications

Security teams should test for vulnerabilities in production environments. Teams can run manual penetration tests or use automated XSS scanners.

Build an incident response plan

Despite extensive prevention efforts, organizations might still be subject to XSS attacks. Having an incident response plan in place is essential for recovering quickly. That plan should include strategies for monitoring web application activities and taking action when suspicious events occur. Teams should then analyze root causes and identify attack methods. When the attack is over, they should apply lessons learned to augment security capabilities, update policies, and patch vulnerabilities in web applications.

How does Cloudflare help prevent XSS attacks?

Cloudflare has several products and capabilities that can help organizations and users prevent XSS attacks:

  • The Cloudflare WAF can protect web applications from XSS attacks, DDoS attacks, SQL injection, and other common threats
  • Cloudflare Email Security helps block phishing emails that can be used to trigger XSS attacks
  • Cloudflare Browser Isolation prevents the execution of malicious scripts on user computers
  • Cloudflare CSPs can help detect and mitigate XSS attacks, as well as content/code injection, malicious resource embedding, and the use of malicious iframes (clickjacking)

Learn more about the Cloudflare WAF.