Skip to content
CSRF Write-up Advanced

WordPress 5.1 CSRF to Remote Code Execution

WordPress lacked CSRF protection on comment submission, allowing an attacker to create comments as an administrator. A sanitisation flaw then let the attacker inject a stored XSS payload, which, when executed in the administrator's session, enabled editing PHP files and achieving remote code execution.

Simon Scannell Follow

Published on sonarsource.com

Bounty$950 View original

Last month we released an authenticated remote code execution (RCE) vulnerability in WordPress 5.0. This blog post reveals another critical exploit chain for WordPress 5.1 that enables an unauthenticatedattacker to gain remote code execution on any WordPress installation prior to version 5.1.1(CVE-2019-9787).

Simon Scannell (@scannell_simon), on sonarsource.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 8 min read.

Context

WordPress is a blogging and content management platform used by over 33% of all websites on the internet, according to its own download page. Comments are a core feature of blogs and are enabled by default. This write-up covers an exploit chain for WordPress 5.1 that lets an unauthenticated attacker gain remote code execution on any WordPress installation prior to version 5.1.1 (CVE-2019-9787).

The chain starts with a cross-site request forgery (CSRF) flaw in the comment form, abuses a logic flaw in the sanitisation applied to comments posted by administrators, turns the resulting HTML injection into a stored XSS, and finally uses the administrator's session to edit PHP files from the admin dashboard. The previous month Sonar had released an authenticated RCE in WordPress 5.0; this one needs no account at all.

Setup

The vulnerabilities exist in WordPress versions prior to 5.1.1 and are exploitable with default settings. The only precondition is that comments are enabled on the target blog, which is the default. The attacker needs a website of their own to host the CSRF page and the hidden iframe, and the victim must be an administrator of the target blog who visits that website.

Finding it

WordPress performs no CSRF validation when a user posts a new comment. This is deliberate: features such as trackbacks and pingbacks would break if there was any validation. The consequence is that an attacker can create comments in the name of administrative users of a WordPress blog via CSRF attacks.

That alone would be a security issue because administrators of a WordPress blog are allowed to use arbitrary HTML tags in comments, even <script> tags. In theory an attacker could simply abuse the CSRF vulnerability to create a comment containing malicious JavaScript code.

WordPress tries to solve this problem by generating an extra nonce for administrators in the comment form. When the administrator submits a comment and supplies a valid nonce, the comment is created without any sanitisation. If the nonce is invalid, the comment is still created but is sanitised. The following simplified snippet shows how this is handled in the WordPress core, in /wp-includes/comment.php:

Text
/wp-includes/comment.php

The fact that no CSRF protection is implemented for the comment form has been known since 2009. What the researchers found on top of it was a logic flaw in the sanitisation process for administrators.

Exploitation

Step 1: post a comment as the administrator via CSRF

Because the comment form has no CSRF token check, the attacker's page can submit a comment in the administrator's name. The submitted comment carries no valid nonce, so it is sanitised. The comment is still created, but it is sanitised.

Step 2: abuse the sanitisation logic flaw

As the snippet above shows, the comment is always sanitised with wp_filter_kses(), unless the user creating the comment is an administrator with the unfiltered_html capability. If that is the case and no valid nonce is supplied, the comment is sanitised with wp_filter_post_kses() instead (line 3242 of the snippet).

The difference between wp_filter_post_kses() and wp_filter_kses() lies in their strictness. Both functions take in the unsanitized comment and leave only a selected list of HTML tags and attributes in the string. Usually, comments are sanitised with wp_filter_kses(), which only allows very basic HTML tags and attributes, such as the <a> tag in combination with the href attribute.

So the attacker can create comments that contain much more HTML than comments should usually be allowed to contain. However, although wp_filter_post_kses() is much more permissive, it still removes any HTML tags and attributes that could lead to Cross-Site-Scripting vulnerabilities.

Step 3: escalate the additional HTML injection to a stored XSS

The extra HTML injection still leads to a stored XSS vulnerability in the WordPress core. Some attributes that usually can't be set in comments are parsed and manipulated in a faulty way that leads to an arbitrary attribute injection.

After WordPress is done sanitising the comment it modifies <a> tags within the comment string to optimize them for SEO purposes. This is done by parsing the attribute string (e.g. href="#" title="some link" rel="nofollow") of the <a> tags into an associative array (line 3004 of the following snippet), where the key is the name of an attribute and the value the attribute value. The code lives in wp-includes/formatting.php:

Text
wp-includes/formatting.php

WordPress then checks if the rel attribute is set. This attribute can only be set if the comment is filtered via wp_filter_post_kses(). If it is, it processes the rel attribute and then puts the <a> tag back together:

Text
wp-includes/formatting.php

The flaw occurs in lines 3017 and 3018 of the above snippet, where the attribute values are concatenated back together without being escaped.

An attacker can create a comment containing a crafted <a> tag and set, for example, the title attribute of the anchor to title='XSS " onmouseover=alert(1) id="'. This attribute is valid HTML and would pass the sanitisation step. It only works because the crafted title tag uses single quotes.

When the attributes are put back together, the value of the title attribute is wrapped around in double quotes (line 3018). This means an attacker can inject additional HTML attributes by injecting an additional double quote that closes the title attribute. For example:

HTML
<a title='XSS " onmouseover=evilCode() id=" '>

would turn into:

HTML
<a title="XSS " onmouseover=evilCode() id=" ">

after processing. Since the comment has already been sanitised at this point, the injected onmouseover event handler is stored in the database and does not get removed. This allows attackers to inject a stored XSS payload into the target website by chaining this sanitisation flaw with the CSRF vulnerability.

Step 4: execute the XSS through an iframe

The next step is to get the injected JavaScript executed by the administrator. The comment is displayed in the frontend of the targeted WordPress blog. The frontend is not protected by the X-Frame-Options header by WordPress itself, so the comment can be displayed in a hidden <iframe> on the website of the attacker. Since the injected attribute is an onmouseover event handler, the attacker can make the iframe follow the mouse of the victim to instantly trigger the XSS payload.

This executes arbitrary JavaScript code with the session of the administrator who triggered the CSRF vulnerability on the target website. All of the JavaScript execution happens in the background without the victim administrator noticing.

Step 5: from JavaScript to PHP code execution

With arbitrary JavaScript running in the administrator's session, remote code execution is easy. By default, WordPress allows administrators of a blog to directly edit the .php files of themes and plugins from within the admin dashboard. By simply inserting a PHP backdoor, the attacker gains arbitrary PHP code execution on the remote server.

Root cause

Two mistakes combine. First, the comment form has no CSRF protection at all, a design decision kept because trackbacks and pingbacks would break with validation. The nonce in the comment form is not a CSRF defence: it only decides whether the comment is stored unfiltered or filtered, and a missing or invalid nonce still creates the comment.

Second, the sanitisation path chosen for administrators without a valid nonce, wp_filter_post_kses(), is permissive enough to let a rel attribute through, which in turn lets the SEO rewriting code in wp-includes/formatting.php run over the tag. That code parses the attribute string into an associative array and then concatenates the values back together without escaping them (lines 3017 and 3018). Because the sanitisation has already happened, the injected onmouseover handler survives into the database.

The frontend not being protected by X-Frame-Options is what lets the stored payload be triggered from an attacker-controlled page, and the default ability for administrators to edit theme and plugin PHP files turns the XSS into code execution.

Impact

An attacker can take over any WordPress site that has comments enabled by tricking an administrator of the target blog into visiting a website set up by the attacker. As soon as the victim administrator visits the malicious website, the CSRF exploit runs against the target WordPress blog in the background, without the victim noticing. The CSRF exploit abuses multiple logic flaws and sanitisation errors that, combined, lead to remote code execution and a full site takeover.

The vulnerabilities are exploitable with default settings, and since comments are a core feature of blogs and are enabled by default, the vulnerability affected millions of sites. The victim does not have to engage in any other form of interaction other than visiting the website set up by the attacker.

Fix

WordPress fixed the issue in version 5.1.1. By default, WordPress automatically installs security updates, so installations should already run the latest version. If you or your hoster disabled the auto-update functionality for some reason, you can also disable comments until the security patch is installed. Most importantly, make sure to log out of your administrator session before visiting other websites.

The broader lesson is that CSRF protections belong on all state-changing endpoints, even those requiring authentication, because a low-severity CSRF can become critical when chained with other flaws in the same application.

Variants to test

  • Comment forms without CSRF tokens on other CMS platforms. Submit a comment from a cross-origin page while authenticated as an administrator. A positive result is a comment created in the administrator's name without any token being sent.
  • Nonce checks that gate sanitisation rather than creation. Look for forms where an invalid nonce downgrades filtering instead of rejecting the request. A positive result is a stored comment containing tags or attributes that the normal path would strip.
  • Attribute re-serialisation in link rewriting or SEO code. Post a comment with an <a> tag whose attribute uses single quotes and contains a double quote, as in the title='XSS " onmouseover=evilCode() id=" ' example. A positive result is the stored markup containing an attribute the sanitizer should have removed.
  • Missing X-Frame-Options on frontend pages that render user content. Load the page in an iframe from another origin. A positive result is the page rendering inside the frame, allowing an event handler to be triggered by mouse movement.
  • Administrator file editing enabled by default. Check whether the theme and plugin editor is reachable in the admin dashboard. A positive result is the ability to write PHP into theme or plugin files, which turns any admin-session XSS into code execution.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 15 min read.

What happened, in plain words

WordPress is a free tool for building websites, especially blogs. You install it on a web server, and it gives you a dashboard where you write posts, approve comments and change how the site looks. According to its own download page, more than 33% of all websites on the internet run on it. That makes any weakness in it interesting to a lot of people, both the ones who want to fix it and the ones who want to abuse it.

A group of researchers at Sonar found a chain of small weaknesses in WordPress 5.1. A chain means that no single weakness is enough on its own, but put together in the right order they add up to something much worse. The end result: an attacker who has no account on the target site at all can make the site run code the attacker wrote. In security language that is called remote code execution, or RCE. The attacker does not need a password and does not need to be logged in. The only thing the attacker needs is for one person, an administrator of the site, to click a single link.

The weakness was fixed in WordPress 5.1.1 and is tracked as CVE-2019-9787. A CVE is a public catalogue number given to a known security flaw so that people can talk about it unambiguously. The month before, the same researchers had published a different WordPress flaw that also ended in code execution, but that one required the attacker to already have an account on the site. This new one requires nothing.

Who is affected, and what the attacker gains

Any WordPress site older than 5.1.1 with comments turned on is affected. Comments are a core feature of blogs and are switched on by default, so in practice that means a very large number of sites. No special plugin, no unusual setting, nothing has to be misconfigured.

The attacker needs two things of their own: a website they control, and a way to get the target site's administrator to visit it. The administrator has to be tricked into visiting the attacker's website. Once the administrator is on the attacker's page while still logged in to their own WordPress site, the attack runs in the background. The victim sees nothing unusual on the attacker's page and does not have to click anything else there.

The prize for the attacker is a full takeover of the site: they end up able to run their own code on the server that hosts it.

The pieces, explained from zero

Before walking through the attack, here are the ideas it relies on. If you already know them, skip ahead.

HTML is the language web pages are written in. It is made of tags such as <a> for a link, and tags can carry attributes, which are extra settings written inside the tag, such as href="..." for the address a link points to. A browser reads the tags and draws the page.

JavaScript is a programming language that runs inside your browser. It can read the page, change it, and send requests to websites on your behalf. When a site lets an attacker's JavaScript run inside a page of that site, that is called cross-site scripting, or XSS. The dangerous part is that the script runs with the permissions of whoever is viewing the page, so it can do anything that person could do.

Stored XSS is the variant where the malicious script is saved on the server, for example inside a comment, and then served to whoever views the page later. It does not need the victim to click a special link; simply viewing the page is enough.

Sanitisation means cleaning input before saving it. A comment box should accept text, but if someone types a <script> tag, the site should strip it out so it cannot run. WordPress does this with functions whose names contain kses.

A nonce is a one-time code that a page includes in a form. The server checks it to confirm the request really came from a page it served, and not from somewhere else. It is a bit like a cloakroom ticket: the number only means something to the cloakroom that issued it.

CSRF, cross-site request forgery, is a different trick. It does not steal your password. Instead it abuses the fact that your browser automatically attaches your login to every request you make to a site. If you are logged in to your blog and you visit another page, that other page can quietly make your browser send a request to your blog, and your blog will treat it as coming from you. The defence is a secret value that the other page cannot know, which the site checks on every request that changes something. Without that check, any page you visit can act as you.

An iframe is a way to embed one web page inside another, like a small window cut into a page. A site can refuse to be embedded by sending a response header called X-Frame-Options. If it does not, other sites can frame it.

PHP is the programming language WordPress itself is written in, and it runs on the web server. If an attacker can get PHP code of their own onto the server and have it run, they control the server side of the site.

A backdoor is a small piece of code an attacker leaves behind so they can get back in later, usually without needing the original weakness again.

The setup

The conditions are simple. The target runs WordPress older than 5.1.1 with comments enabled, which is the default. The attacker hosts a page of their own. The victim is an administrator of the target blog, logged in, who visits the attacker's page. That is the whole setup.

Finding it

WordPress does not check for CSRF when someone posts a comment. This is not an accident. Some WordPress features, trackbacks and pingbacks, would stop working if every comment submission had to carry a validation value. Trackbacks and pingbacks are ways for one blog to notify another that it has linked to it. So the comment form was left without CSRF protection on purpose.

The consequence is that an attacker's page can create comments in the name of an administrator. On its own that would already matter, because WordPress lets administrators use any HTML in comments, including <script> tags. In theory an attacker could just use the CSRF hole to post a comment full of JavaScript.

WordPress tries to close that door with the nonce in the comment form. When an administrator submits a comment with a valid nonce, the comment is saved with no cleaning at all. When the nonce is missing or wrong, the comment is still saved, but it is cleaned first. The logic lives in the WordPress core file /wp-includes/comment.php:

Text
/wp-includes/comment.php

That file is where the decision is made about which cleaning function to use. The fact that the comment form has no CSRF protection has been publicly known since 2009. What the researchers found was a mistake in the cleaning logic that applies to administrators.

Exploitation

Step 1: post a comment as the administrator via CSRF

Because the comment form never checks for a CSRF token, the attacker's page can make the administrator's browser submit a comment to the target blog. The browser attaches the administrator's login automatically, so the blog believes the administrator wrote it.

The comment arrives without a valid nonce. So the comment arrives without a valid nonce. WordPress still creates it, but this time it goes through the cleaning step. That is exactly what the attacker wants, because the cleaning step is where the next mistake lives.

Step 2: abuse the sanitisation logic flaw

Look again at what the snippet in /wp-includes/comment.php decides. A comment is always cleaned with wp_filter_kses(), unless the person writing it is an administrator who holds a permission called unfiltered_html. If that is the case and no valid nonce was supplied, the comment is cleaned with wp_filter_post_kses() instead, at line 3242 of the snippet.

The two functions differ in how strict they are. Both take the raw comment and keep only a list of allowed HTML tags and attributes, throwing the rest away. Normal comments go through wp_filter_kses(), which allows only very basic markup, such as an <a> tag with an href attribute.

So an administrator's comment, arriving without a nonce, is cleaned by the more generous function. The attacker can therefore get far more HTML into the comment than a comment should ever contain. The generous function is still supposed to remove anything that could lead to XSS. The problem is what happens after it has run.

Step 3: escalate the additional HTML injection to a stored XSS

Once the comment is cleaned, WordPress does something else to it. It rewrites <a> tags inside the comment to make them better for search engines, a practice called SEO optimisation. To do that, it takes the attribute text of the tag, for example href="#" title="some link" rel="nofollow", and parses it into an associative array at line 3004 of the snippet. An associative array is a simple lookup table: here, each attribute name becomes a key and its value becomes the matching entry. The code is in wp-includes/formatting.php:

Text
wp-includes/formatting.php

WordPress then checks whether the rel attribute is present. That attribute can only survive if the comment went through the generous wp_filter_post_kses() path. If it is there, WordPress processes it and then rebuilds the <a> tag from the pieces:

Text
wp-includes/formatting.php

The mistake is at lines 3017 and 3018 of that snippet, where the attribute values are glued back together without being escaped. Escaping means converting characters that have a special meaning in HTML, such as a double quote, into a safe form so they cannot end an attribute early. Here that step is missing.

An attacker can write a comment containing a crafted <a> tag and set, for example, the title attribute to title='XSS " onmouseover=alert(1) id="'. This is valid HTML and passes the cleaning step. It only works because the crafted title uses single quotes around its value.

When WordPress rebuilds the tag, it wraps the value of title in double quotes, at line 3018. So a double quote inside the value now closes the attribute early, and whatever follows is read by the browser as a new attribute. That is how the attacker smuggles in extra attributes. For example:

HTML
<a title='XSS " onmouseover=evilCode() id=" '>

would turn into:

HTML
<a title="XSS " onmouseover=evilCode() id=" ">

after processing. Read the second version as a browser would. The title attribute ends at the second double quote. What comes next, onmouseover=evilCode(), is a separate attribute. onmouseover is an event handler: the browser runs the JavaScript inside it whenever the mouse pointer moves over the element. The id attribute is then closed off with the leftover quote.

Because the cleaning already happened before this rebuilding step, the injected onmouseover handler is written to the database and never removed. The attacker has now planted a stored XSS payload on the target site, by chaining the cleaning mistake to the CSRF hole.

Step 4: execute the XSS through an iframe

The payload is sitting in the database, but it has not run yet. It runs when a browser displays the comment. Comments appear on the public front end of the blog, the part visitors see. WordPress itself does not send the X-Frame-Options header on those pages, so nothing stops another site from loading them inside an iframe.

So the attacker's page loads the target blog's comment page in a hidden iframe. The attacker can make that iframe follow the victim's mouse pointer, so the pointer passes over the planted link and the handler fires. The onmouseover handler fires, and the attacker's JavaScript now runs inside the target blog's page, with the administrator's session.

This is the moment the CSRF and the XSS join up. The JavaScript runs as the logged-in administrator, so it can do anything the administrator could do in the dashboard. All of it happens in the background, and the victim notices nothing.

Step 5: from JavaScript to PHP code execution

With JavaScript running in the administrator's session, the last step is easy. By default, WordPress lets administrators edit the .php files of themes and plugins directly from the admin dashboard. That is a convenience feature for people customising their site. The attacker's JavaScript simply uses it to write a PHP backdoor into one of those files. From then on the attacker can run any PHP code they like on the server.

Root cause

Two mistakes combine.

  1. The comment form has no CSRF protection at all. This was a deliberate design choice, kept because trackbacks and pingbacks would break with validation. The nonce in the form is not a CSRF defence: it only decides whether the comment is stored unfiltered or filtered, and a missing or invalid nonce still creates the comment.
  2. The cleaning path chosen for administrators without a valid nonce, wp_filter_post_kses(), is permissive enough to let a rel attribute through. That in turn lets the SEO rewriting code in wp-includes/formatting.php run over the tag. That code parses the attribute text into an associative array and then glues the values back together without escaping them, at lines 3017 and 3018. Since cleaning has already happened, the injected onmouseover handler survives into the database.

Two more defaults turn the stored XSS into a full takeover. The front end is not protected by X-Frame-Options, so the payload can be triggered from an attacker-controlled page. And administrators can edit theme and plugin PHP files, so the XSS can be turned into code execution.

Impact

An attacker can take over any WordPress site with comments enabled by getting an administrator of that blog to visit a website the attacker set up. The moment the administrator arrives, the CSRF exploit runs against the target blog in the background, without the victim noticing. It abuses several logic flaws and cleaning errors which, combined, lead to remote code execution and a full site takeover.

The flaws work with default settings. Comments are a core feature of blogs and are on by default, so millions of sites were affected. The victim does not have to do anything beyond visiting the attacker's website.

Fix

WordPress fixed the issue in version 5.1.1. By default WordPress installs security updates automatically, so installations should already be on the latest version. If you or your hosting provider turned auto-updates off for some reason, you can also disable comments until the patch is installed. Most importantly, log out of your administrator session before visiting other websites.

The wider lesson is that CSRF protection belongs on every endpoint that changes something, even ones that require a login. A CSRF flaw that looks minor on its own can become critical when chained with other flaws in the same application.

Variants to test

If you look after a web application, these are the same ideas applied elsewhere.

  • Comment forms without CSRF tokens on other CMS platforms. Submit a comment from a page on another origin while logged in as an administrator. A positive result is a comment created in the administrator's name without any token being sent.
  • Nonce checks that gate sanitisation rather than creation. Look for forms where an invalid nonce downgrades the filtering instead of rejecting the request. A positive result is a stored comment containing tags or attributes that the normal path would strip.
  • Attribute re-serialisation in link rewriting or SEO code. Post a comment with an <a> tag whose attribute uses single quotes and contains a double quote, as in the title='XSS " onmouseover=evilCode() id=" ' example. A positive result is stored markup containing an attribute the cleaner should have removed.
  • Missing X-Frame-Options on frontend pages that render user content. Load the page in an iframe from another origin. A positive result is the page rendering inside the frame, which lets an event handler be triggered by mouse movement.
  • Administrator file editing enabled by default. Check whether the theme and plugin editor is reachable in the admin dashboard. A positive result is the ability to write PHP into theme or plugin files, which turns any admin-session XSS into code execution.

Glossary

  • Administrator: the highest-level user role on a WordPress site, able to change settings, install plugins and edit files.
  • Associative array: a lookup table where each named key maps to a value, used here to hold attribute names and their values.
  • Attribute: an extra setting written inside an HTML tag, such as href or title.
  • Backdoor: code an attacker leaves on a system so they can return later without needing the original weakness.
  • Comment: a message left by a visitor under a blog post; a core WordPress feature, enabled by default.
  • Cross-site request forgery (CSRF): tricking a logged-in user's browser into sending a request to a site the user is logged in to, so the site treats it as the user's own action.
  • Cross-site scripting (XSS): getting an attacker's JavaScript to run inside a page of another site, with that site's permissions.
  • CVE: a public catalogue number assigned to a known security flaw so it can be referenced unambiguously.
  • Escaping: converting characters with special meaning in HTML, such as quotes, into a safe form so they cannot break out of their context.
  • Event handler: an attribute such as onmouseover whose value is JavaScript the browser runs when that event happens.
  • Front end: the public part of a site that visitors see, as opposed to the admin dashboard.
  • HTML: the markup language web pages are written in, made of tags and attributes.
  • Iframe: an HTML element that embeds one web page inside another.
  • JavaScript: the programming language that runs in the browser and can act on the page and send requests.
  • Nonce: a one-time code placed in a form and checked by the server to confirm the request came from a page it served.
  • PHP: the programming language WordPress and many web servers run, executed on the server side.
  • Remote code execution (RCE): getting a server to run code the attacker wrote, usually the most severe outcome of a web flaw.
  • Sanitisation: cleaning user input before storing or displaying it, removing anything dangerous.
  • SEO: search engine optimisation, changes made to markup to help search engines understand and rank a page.
  • Session: the state of being logged in, which the browser carries automatically with each request to the site.
  • Stored XSS: XSS where the malicious script is saved on the server and served to whoever views the page later.
  • Trackback / pingback: automated notifications one blog sends to another when it links to it; they cannot carry a browser session's secret, which is why the comment form was left without CSRF checks.
  • unfiltered_html: a WordPress permission that lets a user post HTML without cleaning.
  • wp_filter_kses() / wp_filter_post_kses(): WordPress cleaning functions; the first is strict and used for normal comments, the second is more permissive and used for administrators without a valid nonce.
  • X-Frame-Options: a response header a site can send to refuse being embedded in an iframe on another site.

More by Simon Scannell

View all

2 more disclosed reports, best first.

More from WordPress

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Cross-site request forgery (CSRF)

The lesson behind this report.

Another site makes a signed-in user's browser perform an action they did not intend.