How to prevent XSS | Web Security Academy (2022)

In this section, we'll describe some general principles for preventing cross-site scripting vulnerabilities and ways of using various common technologies for protecting against XSS attacks.

Cross-site scripting prevention can generally be achieved via two layers of defense:

  • Encode data on output
  • Validate input on arrival

You can use Burp Scanner to scan your web sites for numerous security vulnerabilities including XSS. Burp's cutting-edge scanning logic replicates the actions of a skilled attacker and is able to achieve correspondingly high coverage of XSS vulnerabilities. You can use Burp Scanner to gain assurance that your defenses against XSS attacks are working effectively.

Learn more about Burp Scanner

Encode data on output

Encoding should be applied directly before user-controllable data is written to a page, because the context you're writing into determines what kind of encoding you need to use. For example, values inside a JavaScript string require a different type of escaping to those in an HTML context.

In an HTML context, you should convert non-whitelisted values into HTML entities:

  • < converts to: &lt;
  • > converts to: &gt;

In a JavaScript string context, non-alphanumeric values should be Unicode-escaped:

  • < converts to: \u003c
  • > converts to: \u003e

Sometimes you'll need to apply multiple layers of encoding, in the correct order. For example, to safely embed user input inside an event handler, you need to deal with both the JavaScript context and the HTML context. So you need to first Unicode-escape the input, and then HTML-encode it:

(Video) #AttackOnTuesday | XSS Web Security Academy

<a href="#" onclick="x='This string needs two layers of escaping'">test</a>

Validate input on arrival

Encoding is probably the most important line of XSS defense, but it is not sufficient to prevent XSS vulnerabilities in every context. You should also validate input as strictly as possible at the point when it is first received from a user.

Examples of input validation include:

  • If a user submits a URL that will be returned in responses, validating that it starts with a safe protocol such as HTTP and HTTPS. Otherwise someone might exploit your site with a harmful protocol like javascript or data.
  • If a user supplies a value that it expected to be numeric, validating that the value actually contains an integer.
  • Validating that input contains only an expected set of characters.

Input validation should ideally work by blocking invalid input. An alternative approach, of attempting to clean invalid input to make it valid, is more error prone and should be avoided wherever possible.

Whitelisting vs blacklisting

Input validation should generally employ whitelists rather than blacklists. For example, instead of trying to make a list of all harmful protocols (javascript, data, etc.), simply make a list of safe protocols (HTTP, HTTPS) and disallow anything not on the list. This will ensure your defense doesn't break when new harmful protocols appear and make it less susceptible to attacks that seek to obfuscate invalid values to evade a blacklist.

Allowing "safe" HTML

Allowing users to post HTML markup should be avoided wherever possible, but sometimes it's a business requirement. For example, a blog site might allow comments to be posted containing some limited HTML markup.

The classic approach is to try to filter out potentially harmful tags and JavaScript. You can try to implement this using a whitelist of safe tags and attributes, but thanks to discrepancies in browser parsing engines and quirks like mutation XSS, this approach is extremely difficult to implement securely.

The least bad option is to use a JavaScript library that performs filtering and encoding in the user's browser, such as DOMPurify. Other libraries allow users to provide content in markdown format and convert the markdown into HTML. Unfortunately, all these libraries have XSS vulnerabilities from time to time, so this is not a perfect solution. If you do use one you should monitor closely for security updates.

Note

In addition to JavaScript, other content such as CSS and even regular HTML can be harmful in some situations.

(Video) What is command injection? - Web Security Academy

Attacks using malicious CSS

How to prevent XSS using a template engine

Many modern websites use server-side template engines such as Twig and Freemarker to embed dynamic content in HTML. These typically define their own escaping system. For example, in Twig, you can use the e() filter, with an argument defining the context:

{{ user.firstname | e('html') }}

Some other template engines, such as Jinja and React, escape dynamic content by default which effectively prevents most occurrences of XSS.

We recommend reviewing escaping features closely when you evaluate whether to use a given template engine or framework.

Note

If you directly concatenate user input into template strings, you will be vulnerable to server-side template injection which is often more serious than XSS.

How to prevent XSS in PHP

In PHP there is a built-in function to encode entities called htmlentities. You should call this function to escape your input when inside an HTML context. The function should be called with three arguments:

  • Your input string.
  • ENT_QUOTES, which is a flag that specifies all quotes should be encoded.
  • The character set, which in most cases should be UTF-8.

For example:

<?php echo htmlentities($input, ENT_QUOTES, 'UTF-8');?>

(Video) Learning XXE with PortSwigger's Web Security Academy - Part 1

When in a JavaScript string context, you need to Unicode-escape input as already described. Unfortunately, PHP doesn't provide an API to Unicode-escape a string. Here is some code to do that in PHP:

<?php function jsEscape($str) { $output = ''; $str = str_split($str); for($i=0;$i<count($str);$i++) { $chrNum = ord($str[$i]); $chr = $str[$i]; if($chrNum === 226) { if(isset($str[$i+1]) && ord($str[$i+1]) === 128) { if(isset($str[$i+2]) && ord($str[$i+2]) === 168) { $output .= '\u2028'; $i += 2; continue; } if(isset($str[$i+2]) && ord($str[$i+2]) === 169) { $output .= '\u2029'; $i += 2; continue; } } } switch($chr) { case "'": case '"': case "\n"; case "\r"; case "&"; case "\\"; case "<": case ">": $output .= sprintf("\\u%04x", $chrNum); break; default: $output .= $str[$i]; break; } } return $output;}?>

Here is how to use the jsEscape function in PHP:

<script>x = '<?php echo jsEscape($_GET['x'])?>';</script>

Alternatively, you could use a template engine.

How to prevent XSS client-side in JavaScript

To escape user input in an HTML context in JavaScript, you need your own HTML encoder because JavaScript doesn't provide an API to encode HTML. Here is some example JavaScript code that converts a string to HTML entities:

function htmlEncode(str){ return String(str).replace(/[^\w. ]/gi, function(c){ return '&#'+c.charCodeAt(0)+';'; });}

You would then use this function as follows:

<script>document.body.innerHTML = htmlEncode(untrustedValue)</script>

If your input is inside a JavaScript string, you need an encoder that performs Unicode escaping. Here is a sample Unicode-encoder:

(Video) Cross-Site Scripting(XSS) Attack | Overview and Prevention

function jsEscape(str){ return String(str).replace(/[^\w. ]/gi, function(c){ return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4); });}

You would then use this function as follows:

<script>document.write('<script>x="'+jsEscape(untrustedValue)+'";<\/script>')</script>

How to prevent XSS in jQuery

The most common form of XSS in jQuery is when you pass user input to a jQuery selector. Web developers would often use location.hash and pass it to the selector which would cause XSS as jQuery would render the HTML. jQuery recognized this issue and patched their selector logic to check if input begins with a hash. Now jQuery will only render HTML if the first character is a <. If you pass untrusted data to the jQuery selector, ensure you correctly escape the value using the jsEscape function above.

Mitigating XSS using content security policy (CSP)

Content security policy (CSP) is the last line of defense against cross-site scripting. If your XSS prevention fails, you can use CSP to mitigate XSS by restricting what an attacker can do.

CSP lets you control various things, such as whether external scripts can be loaded and whether inline scripts will be executed. To deploy CSP you need to include an HTTP response header called Content-Security-Policy with a value containing your policy.

An example CSP is as follows:

default-src 'self'; script-src 'self'; object-src 'none'; frame-src 'none'; base-uri 'none';

This policy specifies that resources such as images and scripts can only be loaded from the same origin as the main page. So even if an attacker can successfully inject an XSS payload they can only load resources from the current origin. This greatly reduces the chance that an attacker can exploit the XSS vulnerability.

If you require loading of external resources, ensure you only allow scripts that do not aid an attacker to exploit your site. For example, if you whitelist certain domains then an attacker can load any script from those domains. Where possible, try to host resources on your own domain.

(Video) What is directory traversal? (file path traversal) - Web Security Academy

If that is not possible then you can use hash- or nonce-based policy to allow scripts on different domains. A nonce is a random string that is added as an attribute of a script or resource, which will only be executed if the random string matches the server-generated one. An attacker is unable to guess the randomized string and therefore cannot invoke a script or resource with a valid nonce and so the resource will not be executed.

Read more

Mitigating XSS attacks using CSP

FAQs

How can XSS be prevented? ›

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.

What is XSS and how we can prevent it? ›

Cross-site scripting (XSS) is a type of injection attack in which a threat actor inserts data, such as a malicious script, into content from trusted websites. The malicious code is then included with dynamic content delivered to a victim's browser. XSS is one of the most common cyber attack types.

What is the best defense against cross site scripting attacks? ›

Web application firewall. A web application firewall (WAF) can be a powerful tool for protecting against XSS attacks. WAFs can filter bots and other malicious activity that may indicate an attack. Attacks can then be blocked before any script is executed.

What are the two primary defenses against XSS attacks? ›

4 Answers
  • Specifying a charset. ...
  • HTML escaping. ...
  • Other types of escaping. ...
  • Validating URLs and CSS values. ...
  • Not allowing user-provided HTML. ...
  • Preventing DOM-based XSS.
28 Jun 2010

Does SSL prevent XSS? ›

HTTPS can prevent a man-in-the-middle attack, not XSS. Unfortunately the session cookie is not secure with this alone, one can request a page with HTTP and then the same cookie will be sent unprotected.

Can XSS be prevented without modifying the source code? ›

One of the most common XSS attacks is the theft of cookies (especially session ids). The HttpOnly flag was created to mitigate this threat by ensuring that Cookie values cannot be accessed by client side scripts like JavaScript. This is accomplished by simply appending " ; HttpOnly " to a cookie value.

What is the main cause of XSS vulnerabilities? ›

The root cause of XSS vulnerabilities is when a web application uses untrusted input without performing proper validation first. If a web server embeds user input in a page's HTML code before sending it to the client, then malicious input could enable the execution of attacker-controlled code within the user's browser.

What are the main reasons for XSS? ›

Cross-Site Scripting (XSS) attacks occur when: Data enters a Web application through an untrusted source, most frequently a web request. The data is included in dynamic content that is sent to a web user without being validated for malicious content.

What are advanced anti XSS tools? ›

Tools For Scanning XSS Vulnerability
  • XSStrike is an advanced XSS detection suite. ...
  • XSS Hunter is a useful tool for finding stored XSS vulnerabilities in a website. ...
  • XSSER is an open-source penetration testing tool that detects and exploits cross-site scripting (XSS) injections in a variety of applications.
26 Mar 2022

What is the difference between CSRF and XSS? ›

What is the difference between XSS and CSRF? Cross-site scripting (or XSS) allows an attacker to execute arbitrary JavaScript within the browser of a victim user. Cross-site request forgery (or CSRF) allows an attacker to induce a victim user to perform actions that they do not intend to.

What can you do with XSS? ›

Because XSS can allow untrusted users to execute code in the browser of trusted users and access some types of data, such as session cookies, an XSS vulnerability may allow an attacker to take data from users and dynamically include it in web pages and take control of a site or an application if an administrative or a ...

Which of the following is one of the most effective ways to prevent cross-site scripting XSS flaws in software applications? ›

Which of the following is most effective to prevent Cross Site Scripting flaws in software applications? Use digital certificates to authenticate a server prior to sending data.

What is cross-site scripting example? ›

Examples of reflected cross-site scripting attacks include when an attacker stores malicious script in the data sent from a website's search or contact form. A typical example of reflected cross-site scripting is a search form, where visitors sends their search query to the server, and only they see the result.

How common are XSS attacks? ›

Cross-site scripting (often shortened to XSS) is a common security vulnerability that is more prevalent in web applications. It's estimated that more than 60% of web applications are susceptible to XSS attacks, which eventually account for more than 30% of all web application attacks.

How many types of XSS attacks are there? ›

There 3 main types of cross-site scripting attacks are: Stored XSS. Reflected XSS. DOM-based XSS.

How can Webmasters defend against XSS? ›

Server-side protection against XSS

Strict code guidelines and input checks, for example, can help webmasters to minimize the attack surface for XSS attacks. Whitelisting also enables site operators to define harmless input and, conversely, prevent the transmission of malicious script code to the server.

What are some ways to prevent XSS or at least minimize the chances your site contains XSS vulnerabilities? ›

To protect most from XSS vulnerabilities, follow three practices:
  • Escape user input. Escaping means to convert the key characters in the data that a web page receives to prevent the data from being interpreted in any malicious way. ...
  • Validate user input. ...
  • Sanitize data.

What is HTML escaping for XSS? ›

Escaping from XSS

Escaping is the primary means to avoid cross-site scripting attacks. When escaping, you are effectively telling the web browser that the data you are sending should be treated as data and should not be interpreted in any other way.

What is DOM based XSS? ›

Definition. DOM Based XSS (or as it is called in some texts, “type-0 XSS”) is an XSS attack wherein the attack payload is executed as a result of modifying the DOM “environment” in the victim's browser used by the original client side script, so that the client side code runs in an “unexpected” manner.

What is cross-site scripting XSS? ›

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

Which is most vulnerable to injection attacks? ›

The main types of injection attacks that your application may be vulnerable to are:
  • SQL Injection (SQLi) SQL is a query language to communicate with a database. ...
  • Cross-Site Scripting (XSS) ...
  • Code Injection. ...
  • Command Injection. ...
  • CCS Injection. ...
  • SMTP/IMAP Command Injection. ...
  • Host Header injection. ...
  • LDAP Injection.
25 Jul 2020

Which of the following filtering techniques prevents all cross-site scripting XSS vulnerabilities? ›

Which of the following filtering techniques prevents all cross-site scripting (XSS) vulnerabilities? vulnerabilities? A. Enable magic_quotes_gpc .

What is Cross-site scripting For Dummies? ›

Cross-site scripting (XSS) is a security vulnerability allowing a user to alter the code that an application delivers to a user which is executed in the user's web browser.

Which of the following is true about XSS vulnerabilities? ›

The correct answer is option(3) ie. Explanation: DOM stands for Document Object Model. It defines the structure of the web page and XSS(Cross-site scripting) is a vulnerability by which an attacker or hacker can steal or hijack user session, and perform phishing attacks.

What are reflected XSS attacks? ›

Reflected XSS attacks, also known as non-persistent attacks, occur when a malicious script is reflected off of a web application to the victim's browser. The script is activated through a link, which sends a request to a website with a vulnerability that enables execution of malicious scripts.

How do I check my application vulnerability? ›

These are the best open-source web application penetration testing tools.
  1. Grabber. Grabber is a web application scanner which can detect many security vulnerabilities in web applications. ...
  2. Vega. ...
  3. Zed Attack Proxy. ...
  4. Wapiti. ...
  5. W3af. ...
  6. WebScarab. ...
  7. Skipfish. ...
  8. Ratproxy.

What is an exploit in cyber security? ›

An exploit (in its noun form) is a segment of code or a program that maliciously takes advantage of vulnerabilities or security flaws in software or hardware to infiltrate and initiate a denial-of-service (DoS) attack or install malware, such as spyware, ransomware, Trojan horses, worms, or viruses.

What is the difference between XSS and SQL injection? ›

The main difference between a SQL and XSS injection attack is that SQL injection attacks are used to steal information from databases whereas XSS attacks are used to redirect users to websites where attackers can steal data from them. SQL injection is data-base focused whereas XSS is geared towards attacking end users.

Is CSRF part of XSS? ›

XSS is a computer security vulnerability found in web applications that enables cybercriminal to inject client-side scripts into web pages viewed by the users.
...
Difference between XSS and CSRF :
S.No.XSSCSRF
1.XSS stands for Cross-Site Scripting.CSRF stands for Cross-Site Request Forgery.
7 more rows
15 Dec 2021

Can the Secret Token countermeasure be used to defeat XSS attacks? ›

Can the secret token countermeasure be used to defeat XSS attacks? No, since the injected javascript can do anything that the victim's page can normally do, it can easily access the secret token and send a request to the server.

What can you steal with XSS? ›

Stealing cookies is a traditional way to exploit XSS. Most web applications use cookies for session handling. You can exploit cross-site scripting vulnerabilities to send the victim's cookies to your own domain, then manually inject the cookies into the browser and impersonate the victim.

Can XSS capture keystrokes? ›

XSS Attack 4: Capture the keystrokes by injecting a keylogger. In this attack scenario, we will inject a JavaScript keylogger into the vulnerable web page and we will capture all the keystrokes of the user within the current page.

How does XSS payload work? ›

DOM XSS Payload:

Victims web browser makes a request to the attackers web server with the victims cookie data within the URL. The attacker can now extract the victims cookie from the web logs and hijack the users session using the session identifier from the cookie.

What is XSS How will you mitigate it? ›

Mitigations for XSS typically involve sanitizing data input (to make sure input does not contain any code), escaping all output (to make sure data is not presented as code), and re-structuring applications so code is loaded from well-defined endpoints.

Which of the following safety mechanisms should be used to prevent cross site scripting? ›

Content security policy (CSP) is the last line of defense against cross-site scripting. If your XSS prevention fails, you can use CSP to mitigate XSS by restricting what an attacker can do. CSP lets you control various things, such as whether external scripts can be loaded and whether inline scripts will be executed.

When and user can fall victim of cross site scripting? ›

In a Cross-site Scripting attack (XSS), the attacker uses your vulnerable web page to deliver malicious JavaScript to your user. The user's browser executes this malicious JavaScript on the user's computer. Note that about one in three websites is vulnerable to Cross-site scripting.

Does encryption protect from an XSS? ›

Websites that use SSL (https) are in no way more protected than websites that are not encrypted. The web applications work the same way as before, except the attack is taking place in an encrypted connection. XSS attacks are generally invisible to the victim.

Is self XSS a vulnerability? ›

Definition : Self Cross site scripting(XSS) is a vulnerability in web applications which gives the ability of executing JS as the same user and not to other users.

What are different types of XSS and its nature? ›

Types of XSS: Stored XSS, Reflected XSS and DOM-based XSS. Cross-site Scripting attacks (XSS) can be used by attackers to undermine application security in many ways. It is most often used to steal session cookies, which allows the attacker to impersonate the victim.

What are the two types of cross site attacks? ›

Types of XSS attacks

XSS attacks can be generally categorized into two main types: non-persistent (reflected) and persistent (stored).

Which of the following is the best way to protect against injection attacks? ›

The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.

What is the difference between stored or persistent XSS and reflected XSS? ›

Stored XSS, also known as persistent XSS, is the more damaging of the two. It occurs when a malicious script is injected directly into a vulnerable web application. Reflected XSS involves the reflecting of a malicious script off of a web application, onto a user's browser.

What is the preferred method of preventing broken access control? ›

Enable Permission-Based Access Control:

This is an access control method, where the authorization layer checks if the user has permission to access particular data or to perform a particular action, typically by checking if the user's roles have this permission or not.

What can you do with XSS? ›

Because XSS can allow untrusted users to execute code in the browser of trusted users and access some types of data, such as session cookies, an XSS vulnerability may allow an attacker to take data from users and dynamically include it in web pages and take control of a site or an application if an administrative or a ...

Which of the following is the best way to protect against injection attacks? ›

The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.

How can Webmasters defend against XSS? ›

Server-side protection against XSS

Strict code guidelines and input checks, for example, can help webmasters to minimize the attack surface for XSS attacks. Whitelisting also enables site operators to define harmless input and, conversely, prevent the transmission of malicious script code to the server.

What are the solution for broken authentication? ›

Implement Multi-Factor Authentication (MFA)

OWASP's number one tip for fixing broken authentication is to “implement multi-factor authentication to prevent automated, credential stuffing, brute force, and stolen credential reuse attacks.”

What is the most common form of bypassing access control system? ›

Bypassing access control checks by modifying the URL (parameter tampering or force browsing), internal application state, or the HTML page, or by using an attack tool modifying API requests. Permitting viewing or editing someone else's account, by providing its unique identifier (insecure direct object references)

Which Owasp top 10 weakness can be prevented using role based access control? ›

Role-Based Access control helps prevent this OWASP Top 10 weakness.
  • Failure to restrict URL Access.
  • Unvalidated Redirect or Forward.
  • Security Misconfiguration.
  • Insufficient Transport Layer Protection.
22 Mar 2022

What is the main cause of XSS vulnerabilities? ›

The root cause of XSS vulnerabilities is when a web application uses untrusted input without performing proper validation first. If a web server embeds user input in a page's HTML code before sending it to the client, then malicious input could enable the execution of attacker-controlled code within the user's browser.

What are the main reasons for XSS? ›

Cross-Site Scripting (XSS) attacks occur when: Data enters a Web application through an untrusted source, most frequently a web request. The data is included in dynamic content that is sent to a web user without being validated for malicious content.

What can you steal with XSS? ›

Stealing cookies is a traditional way to exploit XSS. Most web applications use cookies for session handling. You can exploit cross-site scripting vulnerabilities to send the victim's cookies to your own domain, then manually inject the cookies into the browser and impersonate the victim.

Which is most vulnerable to injection attacks? ›

The main types of injection attacks that your application may be vulnerable to are:
  • SQL Injection (SQLi) SQL is a query language to communicate with a database. ...
  • Cross-Site Scripting (XSS) ...
  • Code Injection. ...
  • Command Injection. ...
  • CCS Injection. ...
  • SMTP/IMAP Command Injection. ...
  • Host Header injection. ...
  • LDAP Injection.
25 Jul 2020

What is SQL injection in cyber security? ›

An SQL injection, sometimes abbreviated to SQLi, is a type of cyber attack in which a hacker uses a piece of SQL (structured query language) code to manipulate a database and gain access to potentially valuable information.

What is the difference between CSRF and XSS? ›

What is the difference between XSS and CSRF? Cross-site scripting (or XSS) allows an attacker to execute arbitrary JavaScript within the browser of a victim user. Cross-site request forgery (or CSRF) allows an attacker to induce a victim user to perform actions that they do not intend to.

What is cross-site scripting example? ›

Examples of reflected cross-site scripting attacks include when an attacker stores malicious script in the data sent from a website's search or contact form. A typical example of reflected cross-site scripting is a search form, where visitors sends their search query to the server, and only they see the result.

Which of the following is one of the most effective ways to prevent cross-site scripting XSS flaws in software applications? ›

Which of the following is most effective to prevent Cross Site Scripting flaws in software applications? Use digital certificates to authenticate a server prior to sending data.

Videos

1. Common Web Security Vulnerabilities and Their Fixes
(Salesforce Developers)
2. What is SQL injection? - Web Security Academy
(PortSwigger)
3. Broken bf protection, IP block (Video solution, Audio)
(Michael Sommer)
4. Let's Hack! - DOM XSS Labs - PortSwigger Web Security Academy
(HypeMonster)
5. How to protect against Malware? - Daniel's Security Academy
(Daniel's Security Academy)
6. A one million milestone for the Web Security Academy
(PortSwigger)

Top Articles

You might also like

Latest Posts

Article information

Author: Trent Wehner

Last Updated: 10/25/2022

Views: 5744

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.