Cross-Site Scripting (XSS) is a vulnerability where an attacker injects malicious scripts into a trusted website, which then execute in the browser of an unsuspecting user. You can identify these flaws by testing how a web application handles user-supplied data that is later displayed on a page.
A common misconception is that XSS only happens in search bars; in reality, it occurs anywhere user input is reflected, including profile names, comment sections, and URL parameters. The correct fact is that any data source not strictly validated and encoded before rendering is a potential entry point.
Test the Input for Basic Reflection
The first step in identifying an XSS vulnerability is determining if the application reflects your input without filtering. Start by entering a unique string of alphanumeric characters, such as Test12345, into every available input field. This includes search boxes, login forms, contact forms, and URL query parameters. If you see Test12345 appear exactly as typed in the page source, the application is reflecting your input.
Once reflection is confirmed, you must check if the application allows HTML tags. Try entering a simple tag like <b>Test</b>. If the word Test appears in bold on the screen, the browser is interpreting the HTML. If you see the literal tags <b> in the browser, the application is likely encoding the characters, which prevents the script from executing. This distinction tells you whether you need to find a way to bypass filters or if the site is already secure against basic injection.
Identifying the Context of Reflection
Where your input lands in the HTML determines which payload will work. You must inspect the page source (Right Click > View Page Source) to see the surrounding code. There are three primary contexts to look for:
- HTML Body: Your input is between tags, like
<div>Your Input Here</div>. Here, standard tags like<script>usually work. - HTML Attribute: Your input is inside an attribute, like
<input value="Your Input Here">. You first need to break out of the attribute using a quote (") and a closing bracket (>). - JavaScript Variable: Your input is inside an existing script, like
var name = 'Your Input Here';. You must break out of the string using a quote and a semicolon to start your own command.
Select Payloads Based on Filter Bypasses
When basic tags are blocked, you must use payloads that avoid the specific keywords the filter is looking for. Many filters look for the string <script>. To bypass this, you can use event handlers attached to other HTML elements. An event handler is an attribute that executes JavaScript when a specific action occurs, such as a mouse movement or a page load.
A reliable alternative is the <img> tag with an onerror attribute. For example, <img src=x> works because the browser tries to load an image from the invalid source 'x', fails, and then triggers the onerror event. This avoids the <script> tag entirely. Similarly, <svg> is effective because SVG files can contain embedded scripts that execute as soon as the element is rendered by the browser.
Handling Case Sensitivity and Encoding
Some filters are poorly written and only check for lowercase letters. If <script> is blocked, try mixing the case: <sCrIpT>alert(1)</sCrIpT>. If the server does not normalize the input to lowercase before checking, this simple change can bypass the security check. Labels and attribute names in HTML are often case-insensitive, allowing the browser to execute the code regardless of the capitalization.
If characters like angle brackets (< and >) are blocked, check if the application accepts URL-encoded or Hex-encoded characters. For instance, %3C is the URL-encoded version of <. If the application decodes the input before rendering it to the page, your encoded payload will be converted back into a functional script. You can test this by entering %3Cimg src=x> into a URL parameter.
Implement Defenses to Stop Script Execution
Preventing XSS requires a defense-in-depth approach where you assume some filters will fail. The most effective defense is Context-Aware Output Encoding. This means converting special characters into their HTML entity equivalents before they are sent to the browser. For example, the character < becomes < and > becomes >. When the browser sees <script>, it displays the text on the screen rather than executing it as a command.
You must choose the encoding method based on where the data is placed. If data goes into a JavaScript string, you need Unicode escapes (e.g., \u003C) rather than HTML entities. If data goes into a URL, you must use percent-encoding. Using the wrong encoding method can leave a gap that an attacker can exploit. For example, HTML encoding data that is placed inside a <script> block will not prevent an attacker from breaking out of a JavaScript string.
Configure Content Security Policy (CSP)
A Content Security Policy (CSP) acts as a second layer of defense by telling the browser which sources of content are trusted. You implement this by adding a Content-Security-Policy HTTP header to your server responses. A strict policy can disable the execution of inline scripts (scripts written directly in the HTML) and prevent the browser from loading scripts from unknown external domains.
To start, you can use a policy like script-src 'self'. This tells the browser to only execute scripts that originate from the same domain as the website. This effectively kills most XSS attacks because even if an attacker manages to inject a <script> tag or an onerror event, the browser will refuse to run it because it is considered 'inline' or from an untrusted source. You can refine this policy over time by adding specific trusted domains to the allow-list.
Validate Input and Sanitize HTML
While encoding handles the output, input validation handles the entry. You should implement a 'whitelist' approach, where you only allow characters that are known to be safe. For example, if a field asks for a phone number, the server should reject any input that contains letters or symbols like < or >. This prevents the malicious payload from ever reaching the database.
In cases where you must allow some HTML (such as in a rich-text editor for a blog), you cannot use simple encoding. Instead, you must use a sanitization library. A sanitizer parses the HTML and strips out dangerous tags (like <script>, <object>, and <embed>) and dangerous attributes (like onclick or onerror). Ensure the library you use is actively maintained, as new bypasses are discovered frequently.
Verifying the Fix
After applying a fix, you must verify it using the same payloads that originally triggered the vulnerability. Check the page source to ensure the characters are being encoded correctly. If you see <script> in the source, the encoding is working. If you have implemented a CSP, open the browser's Developer Tools (F12) and check the Console tab. If the CSP is working, you will see an error message stating that the script was blocked by the Content Security Policy.