Security

XSS

XSS or cross-site scripting is a web vulnerability that lets an attacker inject code, usually JavaScript, into the pages other users see in order to steal sessions, impersonate them or display fake content.

In this post

XSS, or cross-site scripting, is a website flaw that allows an attacker to inject foreign content into its pages, so that visitors’ browsers run it as if it were a legitimate part of the website. It is written with an X so as not to confuse it with style sheets, which are known as CSS. It is one of the oldest and most recurrent flaws in the history of the web.

The underlying idea behind this flaw is misplaced trust. When you visit a website you know, your browser trusts everything that website sends it. If the attacker manages to get the website to deliver content they wrote to other users, the victims’ browsers will treat it with the same trust. The deception does not happen on the website or on the server, but in the mind of the browser, which cannot tell what the owner wrote from what a third party slipped in.

XSS is a flaw that lets a stranger write on someone else’s pages. Your browser obeys because it believes the content comes from the trusted website.

What is XSS?

Imagine a noticeboard in the entrance hall of a block of flats. Neighbours pin up notes and everyone reads them without hesitation, because they are in their own building. Now imagine that someone pins up a note that, when read, convinces the reader to hand over their key. The noticeboard is the website, the notes are the comments and forms, and the key is each visitor’s session and data. The problem is not the noticeboard, but the fact that nobody checks what gets pinned up.

This is a flaw in the website and not in the user. However careful the visitor is, they cannot know that the page they are viewing has been tampered with. That is why the responsibility for preventing it lies with the people who build and maintain the website. For anyone browsing, the best defences are keeping the browser updated, using a password manager that will not autofill on fake pages and being wary of strange links that lead to well-known websites.

How a hidden script in a comment steals a visitor's session

What an attacker achieves with XSS

A script running on a legitimate page has the same powers as the page itself. Beyond the direct damage, an exploited XSS flaw can lead search engines and browsers to flag the website as dangerous, with the resulting drop in visits and trust. It can steal the session of a logged-in user and impersonate them without needing their password. It can read what the person types into forms, show a fake notice asking for credentials, redirect them to another site or alter the content to deceive them. When the victim is an administrator, the consequences multiply, because the script can create accounts, install extensions or change the configuration. That is why a flaw that looks minor, such as an unchecked comment field, can be the gateway to total control of a website.

Output encoding, the main defence

The essential protection consists of treating everything that comes from outside as text, never as code. Before displaying a piece of data on a page, the application must encode it according to the place where it will appear, so that symbols with a special meaning become harmless characters. A less-than sign, for example, is displayed as a symbol but does not open a tag. Validating input helps, but it is not enough, because what is valid in one context can be dangerous in another. Modern frameworks encode by default, and problems appear when someone disables that protection to allow certain formatting. Any point where rich content has to be accepted should be handled with extreme care.

Types of XSS

Stored XSS

In the stored type, the foreign content stays saved on the website, for example in a comment, a profile or a message. Everyone who visits that page receives it and runs it, without the need for any special link. It is the most dangerous variant, because it affects many users at once and can spread on its own. Social networks and forums have been its usual hunting ground. Once saved, the content remains until someone finds it and removes it. It can lie hidden for months in a forgotten field, waiting for an administrator to open the page that displays it. That is why it is essential to review what gets stored and how it is presented, and to keep an eye on the parts of the website where users can write, even if they seem harmless, such as reviews, nicknames or contact fields.

Reflected XSS

In the reflected type, the foreign content is not saved anywhere on the website. It travels inside a link that the attacker sends to the victim by email or message.

How a manipulated link runs a script in a reflected XSS

When the victim clicks it, the website returns the content it received without checking it and the browser runs it. The link looks legitimate because it carries the name of the trusted website. This type requires deceiving each victim individually, but it is very common in fraudulent email campaigns.

The user’s defence is the same as against phishing. Be wary of unexpected links, even if they carry a well-known domain, and check where messages come from. The website’s defence is never to send back to the browser, unchecked, what it has received. A good web application firewall and modern security headers also stop many of these attempts, although they are no substitute for fixing the root of the problem.

DOM-based XSS

The third type happens entirely inside the browser. The page’s own code takes a piece of data from the link or the environment and writes it out without checking it. The server never sees anything unusual, which is why server-side defences do not detect it. It appears on modern websites, heavily loaded with browser-side code, and it requires reviewing the visible part of the application and not just the server side.

This type shows that web security has two halves. One lives on the server, and the other in the visitor’s browser. Teams that only watch the first leave a huge surface uncovered. Regular reviews, up-to-date libraries and tools that analyse the website from the browser’s point of view help close that gap before anyone uses it.

The blind variant

Blind XSS is a form of stored XSS in which the attacker cannot see where their code runs. They leave it in a contact form, a support field or a header that gets logged, and the code activates days later when an administrator opens that information in an internal panel, with all their permissions.

Mutation of the code

Mutation XSS takes advantage of the fact that the browser rewrites HTML while parsing it. A fragment that looks harmless when a filter checks it turns into executable code after the browser corrects it, and several widely used HTML sanitising libraries have had to fix flaws of this kind, which is why they should always be kept up to date.

XSS and other web attacks

XSS compared with CSRF

The two get confused because both take advantage of the victim’s browser. XSS runs the attacker’s code inside the trusted website, which means it can read the page, steal data and act as the user. Cross-site request forgery, or CSRF, only gets the browser to send a request the user did not want, such as changing their email address, without being able to read the response.

XSS cancels out almost every defence against CSRF, because the malicious code can read the form’s security token and send it with the request. That is why fixing an XSS flaw always takes priority.

Compared with SQL injection

Both of them are injection attacks, but they aim at different targets. SQL injection attacks the database on the server, and XSS attacks users in their browser. Since 2021, the OWASP Top 10 list has grouped them in the same injection category, because they share the same cause, mixing data with instructions.

Cross-site scripting in content management systems and shops

In content management systems and online shops, such as WordPress, Joomla, Drupal, PrestaShop or Magento, the core has been filtering this kind of content properly for years, and the flaws that appear almost always come from extensions and templates, just as in many custom developments they come from in-house code. Contact forms, galleries, settings pages, internal search engines and comment systems have had numerous cases. The pattern repeats itself. A popular extension stores or displays a piece of data without checking it. A researcher discovers it, a fix is published and attackers look for websites that have not updated.

The biggest danger of XSS on a website is the administrator. If the foreign content runs in the control panel, it can do with the administrator account anything the administrator could do, such as creating users, installing extensions or modifying files. That is why it is wise to use an account with minimal permissions for day-to-day work, reserve the administrator account for what is strictly necessary and log out when you are done.

Other simple measures are keeping everything updated, removing unused extensions, reviewing who can write comments or content, enabling a web application firewall that filters known attempts and configuring the server’s security headers. None of this requires advanced knowledge. It takes discipline and consistency, and it noticeably reduces the chance of a flaw of this kind affecting your website.

Layers of protection against XSS and checking your website

Additional layers of protection

Besides output encoding, there are other barriers against XSS. A Content Security Policy limits where scripts can be loaded and executed from, so that even if one is injected, the browser can refuse to run it. Marking session cookies as inaccessible to scripts prevents them from being stolen easily, and the filters of a web application firewall block many known attempts.

None of them replaces fixing the flaw, but they reduce the damage in the meantime. Code reviews, testing with automated tools and keeping extensions and components updated complete the picture. In content management systems, most XSS cases come from third-party extensions and templates, so keeping them up to date is the most effective measure.

Modern frameworks and dangerous functions

Today’s frameworks, such as React, Angular or Vue, escape what they display by default, and that has greatly reduced XSS in new applications. The risk reappears when routes for inserting unfiltered HTML are used, such as innerHTML in JavaScript, dangerouslySetInnerHTML in React or v-html in Vue, or when text is evaluated as code with eval().

Chromium-based browsers also support Trusted Types, which force code to go through a sanitising function before writing HTML into those dangerous routes and turn a slip into a visible error during development.

Detection during development

The most effective way to find an XSS flaw is to review the code for data that is printed without escaping. Static analysis tools partly automate this, and application scanners such as OWASP ZAP test the running website by sending special values to every field and watching whether they come back unencoded. Manual audits cover what the tools cannot see.

How to tell whether your website has an injected script problem

Watch out for strange elements appearing on your pages, such as unexpected pop-ups, redirects, forms you did not add or comments with odd content. Review the places where visitors can write and the fields that are later displayed on screen. Regularly cleaning out suspicious comments and profiles is a good habit, and reviewing the server logs can reveal unusual requests.

Use analysis tools that check your website from the outside, as an attacker would, and services that compare your extensions and libraries against databases of published flaws. Many real findings of this kind arrive through warnings from researchers or automated scanners. If you receive a warning from a researcher, treat it seriously and quickly, because fixing the problem at that moment is usually far cheaper than after it has been exploited.

And if you suspect it has already happened, act in an orderly way. Change the passwords and close the sessions of all administrators, review the users and recently modified files, clean up suspicious content, update everything and warn your users if necessary. The MySpace worm taught that speed of reaction makes the difference, and that transparency with the community helps rebuild trust faster. To clean up a hacked website it is not enough to delete what you can see, you also have to find the backdoors.

How cross-site scripting emerged

In February 2000, the CERT Coordination Center published an advisory about malicious tags embedded in web requests, and some Microsoft engineers gave the problem the name cross-site scripting, abbreviated XSS so as not to confuse it with CSS style sheets. In 2002 Microsoft introduced HttpOnly cookies, and in 2005 Amit Klein described DOM-based XSS.

For years browsers tried to defend themselves against XSS on their own. Internet Explorer 8 added a filter against reflected XSS in 2009 and Chrome added its XSS Auditor in 2010, but both were withdrawn years later because they produced false positives and could be abused.

The lasting answer was the Content Security Policy, which Firefox implemented in 2011 and the W3C later standardised, together with frameworks that escape by default. XSS has appeared on the OWASP Top 10 list since its earliest editions.

A worm that gained a million friends in twenty hours

In October 2005, a young programmer named Samy Kamkar wanted to increase his number of friends on MySpace, then the largest social network in the world. MySpace allowed users to customise their profiles, but it filtered dangerous code. Samy found a way to slip past those filters by exploiting the leniency of browsers. He placed a piece of text on his profile that, when viewed, automatically copied itself to the visitor’s profile and added him as a friend.

The effect of that worm on the social network was exponential. Everyone who visited an infected profile ended up with the text on their own, and whoever visited theirs received it in turn. According to the reports, in about twenty hours the worm had reached more than a million users, a rate of contagion never seen before on the web. Samy tells the story with humour, and recalls that his number of friends grew faster than he could have imagined.

MySpace had to take the website down temporarily to remove the content and fix the flaw, and two days later it was still dealing with the consequences. The worm did not steal data or cause major damage, but it showed that a flaw of this kind could spread on its own and reach millions of people within hours. Samy was sentenced to three years of probation, community service and restitution, and his internet use was restricted for a time.

The lesson of that worm still holds today. The flaw was not in some unknown system, but in the habit of trusting what users write. And it showed that the danger lies not only in what an attacker steals, but in the ability to infect other users with a single action. Today the large platforms devote entire teams to making sure an episode like that never happens again.

Frequently asked questions

Frequently asked questions about XSS

What is XSS?

It is a website flaw that lets an attacker slip their own content into the pages other users see. The visitor's browser runs it believing it comes from the trusted website. With it, sessions can be stolen, what is displayed can be altered or users can be redirected to fake pages.

What does XSS stand for?

It stands for cross-site scripting. It is abbreviated with an X rather than a C so as not to confuse it with style sheets, known as CSS. The word site refers to the fact that content from one site ends up running in the context of another.

Who suffers the damage in an XSS attack?

Above all the visitors of the affected website, because it is their browser that runs the foreign content. But also the website itself, which loses reputation and trust, and sometimes its administrators, when the foreign content is viewed by an account with extensive permissions.

What types of XSS exist?

There are three main families. Stored XSS, which stays saved on the website and affects everyone who visits it. Reflected XSS, which travels inside a booby-trapped link. And DOM-based XSS, which happens without the server ever seeing it. Each one has its own glossary entry.

How is XSS exploited?

The attacker looks for a field or a parameter whose content is returned to the page without encoding, injects a piece of code and gets another person's browser to run it with the permissions of the legitimate website. With that, they can steal the session, change what is displayed or redirect to a fake page.

Is XSS the same as SQL injection?

No. SQL injection attacks the server's database. XSS attacks the website's visitors, through their browser. Both stem from the same mistake, trusting what a user types without checking it, but their victims and consequences are different.

How do you prevent XSS?

By treating everything a user types as harmless text before displaying it, limiting what content the browser can execute and keeping the system and its extensions up to date. In content management systems and online shops, most real cases come from outdated extensions and templates.

Does XSS affect content management systems and online shops?

Yes. It is one of the most frequent flaws in extensions and templates for WordPress, Joomla, PrestaShop or Magento, and in custom developments, especially in forms, comments and settings pages. An administrator who visits a tampered page can have their session compromised. Keeping everything updated and limiting accounts with high privileges greatly reduces the risk.

I check your website for XSS vulnerabilities

I can audit your website's code, including extensions, modules and custom developments, to find the points vulnerable to this type of attack.

About the author

Javier Afán

WordPress developer specialised in security, WooCommerce, and hacked website recovery.

I work on WordPress from a technical angle focused on security, architecture, and the decisions that really affect a project's continuity.